From 10c99e81ef477905cc16aecfbe8db6986bedb1bf Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 15:36:26 +0900 Subject: [PATCH 01/27] =?UTF-8?q?docs:=20comlog=20=EC=84=A4=EA=B3=84?= =?UTF-8?q?=EC=99=80=20=EA=B5=AC=ED=98=84=20=EA=B3=84=ED=9A=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/superpowers/plans/2026-12-01-comlog.md | 394 ++++++++++++++++++ .../specs/2026-12-01-comlog-design.md | 222 ++++++++++ 2 files changed, 616 insertions(+) create mode 100644 docs/superpowers/plans/2026-12-01-comlog.md create mode 100644 docs/superpowers/specs/2026-12-01-comlog-design.md diff --git a/docs/superpowers/plans/2026-12-01-comlog.md b/docs/superpowers/plans/2026-12-01-comlog.md new file mode 100644 index 0000000..db244a9 --- /dev/null +++ b/docs/superpowers/plans/2026-12-01-comlog.md @@ -0,0 +1,394 @@ +# comlog 구현 계획 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 연결한 저장소의 작업을 회차 단위로 기록·공개하는 comlog 를 만든다 (커밋 트리거 연동, 스튜디오 회차 사이드바, `/comlog` 공개 페이지). + +**Architecture:** 회차는 종류가 `comlog` 인 기존 `draft` / `post` 행이다 (설계 §4 방식 A). 프로젝트 정보는 새 `comlog_project` 테이블. 트리거는 커밋 제목 단어(`post`, `log`)로 만들 초안 종류를 정하고, 회차 트리거가 막히면 밀린 커밋(`backlog`)으로 남긴다. Lambda 는 글 종류 `worklog` 하나만 추가한다. + +**Tech Stack:** Next.js 16 (app router, server actions), Drizzle + Postgres(Supabase), Lingui(ko/en), Tailwind v4, lucide 아이콘, Vitest, comdraft-lambda (TypeScript, Anthropic). + +**Spec:** `docs/superpowers/specs/2026-12-01-comlog-design.md` + +## Global Constraints + +- 작업 브랜치: 두 저장소 모두 main checkout 에서 `feat/comlog` 브랜치 (worktree 쓰지 않음). 커밋은 로컬만, push·PR 은 사용자 요청 때. +- 커밋 끝줄: `Co-Authored-By: Claude Opus 5.5 `. 커밋 제목에 `[comdraft]` 를 넣지 않음. +- pnpm: `PATH=/Users/junmyeongjo/.nvm/versions/node/v24.12.0/bin:$PATH` 로 실행. +- Tailwind v4, 아이콘은 lucide (`lucide-react` 또는 기존 `/images/studio/*.svg` 방식 중 주변 코드와 같은 것), 새 문구는 Lingui ko + en (`pnpm i18n:extract` 후 en 번역 채우기). +- DB: 로컬은 `pnpm db:generate` → `pnpm db:migrate:local` 직접 실행. 운영 마이그레이션은 사용자가 직접 (요청만 함). +- lint/prettier 는 바뀐 파일만. comdraft-lambda 에는 prettier 를 돌리지 않음. +- 실제 AI 호출(로컬 Lambda)은 최종 확인에서 2~3회 이내. +- 비밀값·사용자 키를 출력하거나 커밋하지 않음. untracked `app/[lang]/dev/`, `components/dev/` 는 건드리지 않음. +- 회차 옵션 고정값: 글 종류 `worklog`, 길이 `short`. 기술 스택 최대 20개. 처음 기술 스택은 저장소 언어 바이트 수 상위 3개. +- 공개 범위 순서: `private` < `unlisted` < `public`. 실효 = 더 좁은 쪽. +- `private` 공개 범위는 종류 `comlog` 게시글에만 허용. + +## Review Focus + +1. 회차가 `/posts` 목록·`/posts/[id]` 상세·게시글 사이트맵·관리자 게시글 목록·통계에 섞이는 것 → Task 9 의 조건 함수 테스트 + Task 16 브라우저 확인. +2. 비공개 회차/프로젝트가 작성자가 아닌 사람에게 상세, OG 이미지 라우트, 이전/다음 링크, 프로젝트 회차 목록, JSON-LD 로 드러나는 것 → Task 3 `canViewComlog` 테스트, Task 11 에서 모든 공개 경로가 같은 함수를 씀. +3. comlog 를 끄거나 프로젝트가 숨겨진 뒤에도 OG 이미지·사이트맵·직접 주소로 열리는 것 → Task 3 테스트(`enabled=false`, `banned`), Task 11 사이트맵 재생성. +4. `[comdraft] post log` 가 한쪽만 만들어지거나, 웹훅 재전송으로 같은 종류가 두 번 만들어지는 것 → Task 7 run 테스트. +5. 밀린 커밋이 다음 트리거 묶음에 섞이거나, 시작 뒤 실패한 회차 작업의 커밋이 기록 없이 사라지는 것 → Task 7, Task 8 테스트. + +--- + +### Task 1: Lambda 글 종류 `worklog` (comdraft-lambda) + +**Files:** +- Modify: `comdraft-lambda/src/prompts/types.ts` (POST_TYPES) +- Modify: `comdraft-lambda/src/prompts/ko.ts`, `src/prompts/en.ts` (postType 문구) +- Test: `comdraft-lambda/src/prompts/prompts.test.ts`, `src/prompts/editable.test.ts` + +**Interfaces:** +- Produces: `POST_TYPES = ['experience', 'lecture', 'experiment', 'worklog']`, 관리자 편집 키 `postType.worklog` (기존 `EDITABLE_PROMPT_KEYS` 가 POST_TYPES 로 만들어지므로 자동 포함). + +- [ ] **Step 1: 실패하는 테스트** — `prompts.test.ts` 에 `it('worklog 글 종류 문구가 옵션 표에 들어간다')`: ko/en 묶음 모두 `pack.postType.worklog` 가 비어 있지 않고, 옵션 `postType: 'worklog'` 로 만든 작성 프롬프트에 그 문구가 포함됨. `editable.test.ts` 에 `EDITABLE_PROMPT_KEYS` 가 `'postType.worklog'` 를 포함. +- [ ] **Step 2: 실패 확인** — `pnpm vitest run src/prompts` → FAIL. +- [ ] **Step 3: 구현** — POST_TYPES 에 `worklog` 추가. ko 문구: `'이번 작업을 하게 된 계기 → 무엇을 바꾸고 더했는지 → "그래서 이번 작업에서 ~를 했다" 로 마무리. 작업 기록이므로 짧고 담백하게 쓰고, 마무리를 위한 "결론"·"정리" 같은 절 제목은 따로 두지 않는다. 이전 작업과 이어지는 이야기로 쓰지 않는다'`. en 은 같은 뜻. +- [ ] **Step 4: 통과 확인** — `pnpm vitest run` 전체 + `pnpm tsc --noEmit` → PASS. +- [ ] **Step 5: 커밋** — `feat: 작업 기록(worklog) 글 종류 추가`. + +### Task 2: 옵션·트리거 단어 (comdraft 순수 함수) + +**Files:** +- Modify: `lib/studio/options.ts`, `lib/auto-draft/trigger.ts`, `components/studio/prompt-options.tsx` +- Test: `lib/studio/options.test.ts`, `lib/auto-draft/trigger.test.ts` + +**Interfaces:** +- Produces (`lib/studio/options.ts`): + - `POST_TYPES = ['experience','lecture','experiment','worklog']` (저장·검증용), `SELECTABLE_POST_TYPES = ['experience','lecture','experiment']` (화면·트리거용), `POST_TYPE_LABELS.worklog = msg\`작업 기록\`` + - `DRAFT_KINDS = ['post','comlog'] as const; type DraftKind` + - `applyDraftKindOptions(kind: DraftKind, options: PromptOptions): PromptOptions | null` — comlog 면 `postType:'worklog', length:'short'` 로 덮어씀, post 인데 `postType === 'worklog'` 면 null. +- Produces (`lib/auto-draft/trigger.ts`): + - `TriggerOptions` 에 `targets: { post: boolean; log: boolean }` 추가 (`post`, `log` 단어, 대소문자 무시). + - `resolveTriggerKinds(comlogEnabled: boolean, targets: TriggerOptions['targets']): DraftKind[]` — 설계 §6 표. 반환 순서는 `['post','comlog']` 고정. + - `parseTrigger` 는 글 종류 단어를 `SELECTABLE_POST_TYPES` 에서만 고름 (`worklog` 무시). + +- [ ] **Step 1: 실패하는 테스트** + - `applyDraftKindOptions('comlog', {...DEFAULT_PROMPT_OPTIONS, postType:'lecture', length:'long'})` → postType `worklog`, length `short`, 나머지 그대로. + - `applyDraftKindOptions('post', {...DEFAULT_PROMPT_OPTIONS, postType:'worklog'})` → `null`. + - `parsePromptOptions({...postType:'worklog'})` → null 아님. + - `parseTrigger('[comdraft] post log friendly')` → `targets {post:true, log:true}`, tone friendly. `parseTrigger('[comdraft] worklog')` → postType undefined. + - `resolveTriggerKinds`: (true, 없음)→`['comlog']`, (true, log)→`['comlog']`, (true, post)→`['post']`, (true, post+log)→`['post','comlog']`, (false, 무엇이든)→`['post']`. +- [ ] **Step 2: 실패 확인** — `pnpm vitest run lib/studio/options.test.ts lib/auto-draft/trigger.test.ts` → FAIL. +- [ ] **Step 3: 구현** — 위 시그니처. `prompt-options.tsx` 의 글 종류 선택은 `SELECTABLE_POST_TYPES` 를 씀. +- [ ] **Step 4: 통과 확인** — 같은 명령 + `pnpm vitest run` → PASS. +- [ ] **Step 5: 커밋** — `feat(comlog): 회차 고정 옵션과 트리거 단어 post·log`. + +### Task 3: comlog 규칙 (공개 범위·기술 스택·링크, 순수 함수) + +**Files:** +- Create: `lib/comlog/rules.ts`, `lib/comlog/rules.test.ts` + +**Interfaces:** +- Produces: + - `type ComlogVisibility = 'public' | 'unlisted' | 'private'` + - `effectiveVisibility(project: ComlogVisibility, entry: ComlogVisibility): ComlogVisibility` + - `interface ComlogAccess { enabled: boolean; bannedAt: Date | null; ownerId: string; projectVisibility: ComlogVisibility }` + - `canViewProject(access: ComlogAccess, viewerId: string | null): boolean` — 꺼짐·밴이면 항상 false (작성자 포함, 공개 화면 기준), private 은 작성자만. + - `canViewEntry(access: ComlogAccess, entry: { visibility: ComlogVisibility; bannedAt: Date | null }, viewerId: string | null): boolean` + - `isListedEntry(access, entry): boolean` — 실효 `public` 이고 꺼짐·밴 아님 (목록·사이트맵용). + - `isIndexable(access, entry?): boolean` — 실효 public 일 때만. + - `mergeTechStack(stack: string[], removed: string[], added: string[]): string[]` — `normalizeTags` 규칙, removed·중복 제외, 기존 순서 유지 뒤에 추가, 최대 `COMLOG_MAX_TECH = 20`. + - `removeTech(stack, removed, tag): { stack: string[]; removed: string[] }` + - `topLanguages(languages: Record, count = 3): string[]` — 바이트 내림차순, 정규화. + - `showGithubLink(project: { showGithubLink: boolean }, repo: { isPrivate: boolean }): boolean` + - `parseDemoUrl(value: unknown): string | null` — http/https 만, 2048자 이하. + +- [ ] **Step 1: 실패하는 테스트** — `effectiveVisibility` 9가지 조합 표, `canViewEntry`: private 회차는 작성자 true·남 false·비로그인 false, `enabled:false` 면 작성자도 false, 프로젝트 `banned` 면 false, 회차 `bannedAt` 이면 false. `isListedEntry`: 프로젝트 unlisted + 회차 public → false. `mergeTechStack(['next.js'], ['zod'], ['ZOD','drizzle','next.js'])` → `['next.js','drizzle']`, 21개 입력 → 20개. `showGithubLink({showGithubLink:true},{isPrivate:true})` → false. `parseDemoUrl('javascript:alert(1)')` → null. +- [ ] **Step 2: 실패 확인** — `pnpm vitest run lib/comlog` → FAIL. +- [ ] **Step 3: 구현**. +- [ ] **Step 4: 통과 확인** — 같은 명령 → PASS. +- [ ] **Step 5: 커밋** — `feat(comlog): 공개 범위와 기술 스택 규칙`. + +### Task 4: DB 스키마와 로컬 마이그레이션 + +**Files:** +- Create: `lib/db/schema/comlog.ts`; Modify: `lib/db/schema/index.ts`, `draft.ts`, `post.ts`, `auto-draft.ts` +- Create: `drizzle/0031_*.sql` (생성), `drizzle/meta/*` + +**Interfaces:** +- Produces: + - `comlogProject` 테이블 (설계 §5.1 칸 전부 + `author_display`/`author_nickname`/`show_author_profile`(게시글과 같은 타입·기본값), `banned_at`, `ban_reason`, `cover_image_id` → `image.id` on delete set null). PK `id`, 유일 `(user_id, repository_id)`, FK `(user_id, repository_id)` → `user_repository` on delete cascade (`repositoryAutoDraft` 와 같은 방식). `status` check `in ('in_progress','completed')`, `visibility` check 3값. + - `draft.kind text not null default 'post'` (check 2값), `draft.paired_draft_id text` (FK draft.id on delete set null). + - `post.kind text not null default 'post'`, `POST_VISIBILITIES = ['public','unlisted','private']`, check: `visibility <> 'private' or kind = 'comlog'`. + - `draft_prompt.draft_kind text not null default 'post'`, `draft_prompt.boundary_claimed boolean not null default false`, `draft_prompt.backlog_recorded_at timestamptz`. + - `comlog_project.author_set_at timestamptz` (첫 회차 게시 때 작성자 표시를 채웠는지). + - 유일 인덱스 `(user_id, trigger_sha)` → `(user_id, trigger_sha, draft_kind)` where trigger_sha is not null. `isTriggerDuplicateConflict` 가 새 인덱스 이름을 보도록 수정. + - `EXCLUDED_COMMIT_REASONS = ['user','force_push','backlog']` + check 제약 갱신. + - 타입: `type ComlogProjectRow = typeof comlogProject.$inferSelect`. + +- [ ] **Step 1: 스키마 수정** (위 내용). +- [ ] **Step 2: 마이그레이션 생성** — `pnpm db:generate`. 생성된 SQL 을 읽어 기존 행 기본값(`post`)·check·인덱스 교체가 맞는지 확인. 기존 `trigger_sha` 행은 모두 `draft_kind='post'` 가 되어 충돌 없음. +- [ ] **Step 3: 로컬 적용** — `pnpm db:migrate:local` → 오류 없음. `pnpm tsc --noEmit` → PASS (타입 오류가 나는 곳은 `PostVisibility` 를 쓰는 화면: 일반 게시 창은 `REGULAR_POST_VISIBILITIES = ['public','unlisted']` 를 새로 두고 그것을 쓰게 바꿈). +- [ ] **Step 4: 기존 테스트** — `pnpm vitest run` → PASS (`parsePostVisibility` 테스트에 `private` 은 kind 없이 거절되는지는 Task 10 에서). +- [ ] **Step 5: 커밋** — `feat(comlog): comlog 프로젝트 테이블과 초안 종류 컬럼`. + +### Task 5: comlog 저장소 계층과 GitHub 정보 + +**Files:** +- Create: `lib/comlog/store.ts`, `lib/comlog/github.ts`, `lib/comlog/github.test.ts` +- Modify: `lib/github/user-api.ts` 또는 `lib/github/app.ts` (설치 토큰으로 저장소 조회가 이미 있는 쪽에 함수 추가) + +**Interfaces:** +- Produces (`lib/comlog/github.ts`): + - `interface RepoSnapshot { name: string; description: string | null; homepage: string | null; isPrivate: boolean; languages: Record }` + - `fetchRepoSnapshot(repo: AutoDraftRepo): Promise` — `GET /repos/{owner}/{repo}` + `/languages` (설치 토큰, `lib/auto-draft/github.ts` 의 방식). + - `buildInitialProject(snapshot: RepoSnapshot): Pick` (순수, `createPostSlug`, `parseDemoUrl`, `topLanguages`). +- Produces (`lib/comlog/store.ts`, server-only): + - `getComlogProject(userId, repositoryId): Promise` + - `enableComlog(userId, repositoryId): Promise` — 행이 없으면 `fetchRepoSnapshot` 으로 만들고, 있으면 `enabled=true`. 둘 다 `github_repository.is_private` 갱신. + - `disableComlog(userId, repositoryId): Promise` + - `updateComlogProject(userId, repositoryId, patch: ComlogProjectPatch): Promise<'ok'|'not_found'|'invalid'>` — 이름(1~60자), 소개(최대 2000자), 상태, 기술 스택(정규화·최대 20, 지운 것은 removed 로), GitHub 링크 표시, 데모 링크, 공개 범위, 작성자 표시(`parseAuthorDisplay`), 대표 이미지 id(본인 이미지만). + - `refreshRepositoryPrivacy(repositoryId: string, isPrivate: boolean): Promise` + - `mergeProjectTech(userId, repositoryId, tags: string[]): Promise` (Task 3 `mergeTechStack`) + - `setProjectAuthorIfUnset(userId, repositoryId, author: AuthorDisplaySettings): Promise` — `author_set_at` 이 null 일 때만 채우고 시각 기록. + - `refreshProjectRepoPrivacy(userId, repositoryId): Promise` — `fetchRepoSnapshot` 으로 `is_private` 만 갱신 (실패하면 조용히 넘어가고 기존 값 유지). 회차 게시(Task 10), 소개 저장(Task 12), 스튜디오 comlog 화면 열기(Task 13)에서 호출. + +- [ ] **Step 1: 실패하는 테스트** — `buildInitialProject`: 설명 null → intro `''`, homepage `ftp://x` → demoUrl null, languages `{TypeScript:900, CSS:50, Shell:10, HTML:5}` → `['typescript','css','shell']`, 이름 → slug. +- [ ] **Step 2: 실패 확인** — `pnpm vitest run lib/comlog/github.test.ts` → FAIL. +- [ ] **Step 3: 구현**. +- [ ] **Step 4: 통과 확인** — `pnpm vitest run lib/comlog` + `pnpm tsc --noEmit` → PASS. +- [ ] **Step 5: 커밋** — `feat(comlog): 프로젝트 저장 계층과 GitHub 저장소 정보`. + +### Task 6: 작업 생성에 초안 종류 연결 + +**Files:** +- Modify: `lib/generation/draft-job.ts` (`DraftJobRequest`, `createDraftJob`), `lib/actions/generation.ts` (`requestDraftGeneration`), `lib/generation/jobs.ts` (`isTriggerDuplicateConflict`, 작업 조회에 `draftKind`) +- Test: `lib/generation/jobs.test.ts`, 새 `lib/generation/draft-kind.test.ts` + +**Interfaces:** +- Consumes: `applyDraftKindOptions`, `DraftKind` (Task 2). +- Produces: + - `DraftJobRequest` 에 `draftKind: DraftKind` 와 `boundaryClaimed: boolean` 추가. 새 초안이면 `draft.kind = draftKind`, 작업 행 `draft_kind = draftKind`, `boundary_claimed`. + - `resolveRequestKind(existingDraftKind: DraftKind | null, requestedKind: DraftKind): DraftKind` (순수, 기존 초안이면 기존 종류가 이김) — `lib/generation/draft-kind.ts`. + - `requestDraftGeneration` 이 클라이언트 인자 `draftKind` 를 받고 (`comlog` 는 그 저장소 comlog 가 켜져 있을 때만, 아니면 `invalid`), 옵션은 `applyDraftKindOptions` 결과를 씀 (null 이면 `invalid`). + - comlog 초안 작업이면 사용됨 겹침 검사(`overlap`)는 Task 8 의 `consumedScope('comlog')` 를 씀. + +- [ ] **Step 1: 실패하는 테스트** — `resolveRequestKind('post','comlog')` → `post`, `(null,'comlog')` → `comlog`. `isTriggerDuplicateConflict` 가 새 인덱스 이름 오류 객체를 true 로 판정. +- [ ] **Step 2: 실패 확인**. +- [ ] **Step 3: 구현**. 기존 호출부(스튜디오, run.ts)는 `draftKind:'post', boundaryClaimed:false` 로 우선 컴파일되게. +- [ ] **Step 4: 통과 확인** — `pnpm vitest run` + `pnpm tsc --noEmit`. +- [ ] **Step 5: 커밋** — `feat(comlog): 초안 작업에 종류를 싣고 회차 옵션 고정`. + +### Task 7: 트리거 실행 — 종류별 작업, 둘 다, 밀린 커밋 + +**Files:** +- Modify: `lib/auto-draft/run.ts`, `lib/auto-draft/store.ts` (`PushTarget.comlogEnabled`, `findPushTargets` 조인, `listExcludedShas` 가 backlog 포함, `recordBacklog`), `app/api/github/webhook/route.ts` +- Test: `lib/auto-draft/run.test.ts` + +**Interfaces:** +- Consumes: `resolveTriggerKinds` (Task 2), `DraftJobRequest.draftKind/boundaryClaimed` (Task 6), `findConsumedShas(…, scope)` (Task 8 — 이 Task 에서 scope 인자를 먼저 추가하고 Task 8 이 표시·스튜디오 쪽을 채움). +- Produces: + - `RunOutcome` → `{ status:'started'; jobIds: string[] } | { status:'skipped'; errorCode } | { status:'duplicate' }` + - `RunDeps.recordBacklog(userId, repositoryId, shas: string[]): Promise` (제외 목록에 `backlog`, 이미 있으면 무시) + - `RunDeps.gate` 호출 뒤 `requiredSlots = kinds.length` 를 `createDraftJobs` 에 넘김. + - `RunDeps.createDraftJobs(userId, repositoryId, requests: DraftJobRequest[], locale): Promise` — 한 트랜잭션, 시간당·동시 진행 자리를 `requests.length` 만큼 확인, 하나라도 duplicate 면 전체 duplicate, overlap 이면 전체 overlap. 기존 `createDraftJob` 은 이것의 1개짜리 래퍼로 유지. + - `consumedScopeFor(kinds: DraftKind[]): ConsumedScope` (`'post_trigger' | 'comlog' | 'both'`) + - `BACKLOG_ERROR_CODES = ['quota_exceeded','quota_unavailable','rate_limited','too_many_active','service_paused'] as const` (할당량·속도·AI 작성 중지). `no_preset`, `anchor_missing`, `no_commits`, `model_locked`, `github_reauth`, `user_banned`, `internal` 은 밀림으로 처리하지 않음. +- 동작 (설계 §6.1, §8): + 1. `kinds = resolveTriggerKinds(target.comlogEnabled, trigger.targets)`. + 2. 실패 행은 종류마다 남김 (`draft_kind` 포함, 유일 인덱스가 종류별이라 재전송은 duplicate). + 3. kinds 에 `comlog` 가 있고 막힌 사유가 `BACKLOG_ERROR_CODES` 면: 경계부터 푸시 끝까지 묶음을 **20개 제한 없이** 계산(`selectBatch` 에 limit 인자 추가, 기본 20)해 `recordBacklog` 후 `moveBoundary(boundary → headSha)`. gate 가 묶음 계산보다 앞이므로 이 경로에서는 gate 실패 뒤 계산을 이어서 함. + 4. 두 작업 모두 같은 `commitShas`, `triggerSha`, `boundaryClaimed = (claimTo !== null)`. 일반 글은 트리거 옵션, 회차는 `applyDraftKindOptions('comlog', 저장소 옵션)`. + 5. 실행기 시작: 각각 시도. 둘 다 실패했을 때만 경계 되돌림. 실패한 쪽은 `failJob(…,'runner_unavailable')`. +- 웹훅: push 페이로드 `repository.private` 로 `refreshRepositoryPrivacy` 호출 (추적 브랜치·푸시한 사람과 무관하게, 저장소 행이 있을 때만). + +- [ ] **Step 1: 실패하는 테스트** (`run.test.ts`, 기존 fake deps 확장) + - `comlog 켬 + [comdraft] → 회차 작업 하나, draftKind comlog, postType worklog, length short` + - `comlog 켬 + post log → 같은 commitShas 로 작업 두 개, requests 길이 2 로 한 번 호출` + - `comlog 끔 + post log → 일반 글 하나` + - `createDraftJobs 가 too_many_active → 둘 다 없음, 종류별 실패 행 2개` + - `회차 트리거가 quota_exceeded 로 막히면 범위 커밋 전부 backlog + 경계가 headSha 로` + - `post 만인 트리거가 quota_exceeded → backlog 없음, 경계 그대로` + - `no_preset 으로 막힌 회차 트리거 → backlog 없음` + - `25개 범위에서 막힘 → backlog 25개 (20개 제한 없음)` + - `post log 중 회차 실행기 시작 실패 → 경계 유지, 회차 작업 runner_unavailable` + - `둘 다 시작 실패 → 경계 원위치` + - `재전송(같은 trigger_sha, 종류별 duplicate) → duplicate` + - `listExcludedShas 에 backlog 가 있으면 묶음에서 빠짐 (다음 트리거)` +- [ ] **Step 2: 실패 확인** — `pnpm vitest run lib/auto-draft` → FAIL. +- [ ] **Step 3: 구현**. +- [ ] **Step 4: 통과 확인** — `pnpm vitest run` + `pnpm tsc --noEmit` → PASS. +- [ ] **Step 5: 커밋** — `feat(comlog): 트리거가 회차·일반 글을 만들고 막히면 밀린 커밋으로 남김`. + +### Task 8: 사용됨 범위, 시작 뒤 실패한 회차의 밀린 커밋, 커밋 표시 + +**Files:** +- Modify: `lib/auto-draft/store.ts` (`findConsumedShas(userId, repositoryId, shas, scope)`), `lib/auto-draft/markers.ts`, `lib/generation/jobs.ts` (`applyPendingDraftJobs` 끝에서 호출), `lib/actions/auto-draft.ts` (`loadAutoDraftState` 에 backlog·applied) +- Create: `lib/comlog/backlog.ts`, `lib/comlog/backlog.test.ts` +- Test: `lib/auto-draft/markers.test.ts` + +**Interfaces:** +- Produces: + - `type ConsumedScope = 'post_trigger' | 'comlog' | 'both'` — `post_trigger`: 지금 규칙(source commit_trigger, draft_kind post). `comlog`: draft_kind comlog 이고 상태 queued·running·awaiting_input·completed (출처 무관). `both`: 합집합. + - `CommitMarker` 에 `{ kind: 'backlog' }` 와 `{ kind: 'applied' }` 추가. `MarkerState` 에 `backlogShas: Set`, `appliedShas: Set` (보고 있는 초안의 최근 완료 작업 commit_shas). + - `countOpenBacklog(backlog: string[], comlogUsed: Set): number` (순수). + - `syncFailedComlogBacklog(userId, repositoryId): Promise` — `draft_kind='comlog' and source='commit_trigger' and status='failed' and boundary_claimed and backlog_recorded_at is null` 작업의 `commit_shas` 를 backlog 로 넣고 `backlog_recorded_at = now()`. `applyPendingDraftJobs` 끝과 웹훅 처리 시작 시 호출 (Lambda 가 직접 failed 로 바꾼 작업도 다음 조회 때 반영). + - `loadAutoDraftState` 결과에 `backlog: string[]`, `openBacklogCount: number`. + +- [ ] **Step 1: 실패하는 테스트** — `countOpenBacklog(['a','b','c'], new Set(['b']))` → 2. markers: backlog 커밋에 `backlog` 표시, applied 커밋에 `applied` 표시, backlog 이면서 회차에 사용된 커밋은 `backlog` 표시 없음. `syncFailedComlogBacklog` 는 DB 함수라 선택 조건을 `buildFailedBacklogFilter()` 같은 순수 조건 객체로 빼서, `boundary_claimed=false` 작업과 `post` 작업이 제외됨을 테스트. +- [ ] **Step 2: 실패 확인**. +- [ ] **Step 3: 구현**. +- [ ] **Step 4: 통과 확인** — `pnpm vitest run` + tsc. +- [ ] **Step 5: 커밋** — `feat(comlog): 회차 사용됨 규칙과 시작 뒤 실패한 회차의 밀린 커밋`. + +### Task 9: 게시글 쪽 섞임 방지 + +**Files:** +- Create: `lib/posts/kind.ts`, `lib/posts/kind.test.ts` +- Modify: `lib/posts/queries.ts` (`getPublishedPost`, `getPostListPage`, `listPublicPostPaths`), `lib/posts/views.ts`, `lib/admin/post-queries.ts`, `lib/admin/stats-queries.ts`, `lib/admin/user-queries.ts`, `lib/studio/queries.ts` (`listStudioDrafts` 는 종류도 반환), `lib/posts/moderation.ts` + +**Interfaces:** +- Produces: + - `regularPostCondition(): SQL` = `post.kind = 'post'` 한 곳 정의. 게시글 목록·사이트맵·`/posts` 상세·관리자 게시글 목록·통계 집계에 사용 (관리자 쪽은 `kind` 필터 인자 `'post' | 'comlog' | 'all'`, 기본 `post`; 관리자 게시글 상세는 둘 다 열 수 있게). + - `parseModerationRequest` 의 대상 해석이 `/comlog/[프로젝트]/[회차]` 주소도 받음 (마지막 조각이 `parsePostPath` 형식이면 그대로 동작하므로 테스트로 고정). + - `StudioDraftSummary.kind: DraftKind`, `pairedDraftId: string | null`. + +- [ ] **Step 1: 실패하는 테스트** — `parseModerationRequest({target:'https://comdraft.dev/ko/comlog/abc-my-app/xyz-login', action:'ban', reason:'x'})` → `postId` 가 `xyz` 의 id 부분. `regularPostCondition` 이 만드는 SQL 문자열에 `kind` 와 `'post'` 가 들어감 (drizzle `PgDialect().sqlToQuery`). +- [ ] **Step 2: 실패 확인**. +- [ ] **Step 3: 구현** — `grep -rn "from(post)" lib app` 로 나온 모든 조회를 검토해 공개 게시글 경로면 조건 추가 (목록은 이 Task 의 Files 에 적은 곳; 새로 발견되면 같은 방식으로). +- [ ] **Step 4: 통과 확인** — `pnpm vitest run` + tsc. +- [ ] **Step 5: 커밋** — `fix(posts): 게시글 목록·사이트맵·상세·관리자 집계에서 comlog 회차 제외`. + +### Task 10: 회차 게시·게시 취소 + +**Files:** +- Modify: `lib/actions/posts.ts` (`publishDraft`, `unpublishDraft`), `lib/posts/post-values.ts` (`parsePostVisibility(value, kind)`), `components/studio/publish-dialog.tsx`, `components/studio/publish-state.ts` +- Test: `lib/posts/post-values.test.ts`, `components/studio/publish-state.test.ts` + +**Interfaces:** +- Consumes: `mergeProjectTech`, `setProjectAuthorIfUnset`, `getComlogProject` (Task 5), `effectiveVisibility` (Task 3). +- Produces: + - `parsePostVisibility(value: unknown, kind: DraftKind): PostVisibility | null` — `private` 은 comlog 만. + - `publishDraft` 는 초안 종류를 `post.kind` 로 복사. comlog 면: 프로젝트가 없거나 꺼져 있으면 `{status:'comlog_disabled'}`; 게시 후 `mergeProjectTech(태그)`, `setProjectAuthorIfUnset(작성자 설정)`, `revalidateLocalizedPath('/comlog')` 와 프로젝트·회차 경로, `revalidateSitemap()`. + - 게시 창: 종류 comlog 면 공개 범위 3개(공개/일부 공개/비공개) + 프로젝트가 더 좁으면 안내 문구 (설계 §9). + +- [ ] **Step 1: 실패하는 테스트** — `parsePostVisibility('private','post')` → null, `('private','comlog')` → `private`, `('unlisted','post')` → `unlisted`. publish-state: comlog 초안의 공개 범위 선택지가 3개. +- [ ] **Step 2: 실패 확인**. +- [ ] **Step 3: 구현**. +- [ ] **Step 4: 통과 확인** — `pnpm vitest run` + tsc. +- [ ] **Step 5: 커밋** — `feat(comlog): 회차 게시와 비공개 공개 범위`. + +### Task 11: 공개 페이지 `/comlog` + +**Files:** +- Create: `lib/comlog/queries.ts`, `lib/comlog/paths.ts`, `lib/comlog/paths.test.ts` +- Create: `app/[lang]/comlog/page.tsx`, `app/[lang]/comlog/[projectPath]/page.tsx`, `app/[lang]/comlog/[projectPath]/[entryPath]/page.tsx`, 각 `opengraph-image.tsx` +- Create: `components/comlog/project-card.tsx`, `project-intro.tsx`, `entry-list.tsx`, `entry-nav.tsx` +- Modify: `components/main/posts-nav-link.tsx` 옆에 `comlog-nav-link.tsx`, `components/main/mobile-menu.tsx`, 헤더에서 쓰는 곳, `app/sitemap.ts`(또는 `lib/seo/sitemap.ts` 호출부), `lib/seo/json-ld.ts` + +**Interfaces:** +- Consumes: `canViewProject`, `canViewEntry`, `isListedEntry`, `isIndexable`, `showGithubLink` (Task 3), `resolvePostAuthor` (`lib/posts/author-display.ts`), 게시글 본문 렌더링 `components/posts/post-content.tsx`, 조회 기록 `recordViewIfDue`, 게시글 OG 생성기 `lib/seo/og-image.tsx`. +- Produces: + - `getComlogProjectPath(p: {id: string; slug: string}): string` / `parseComlogProjectPath(segment)` (게시글 `post-path` 와 같은 id-slug 형식), 회차는 기존 `getPostPath` 재사용 → `/comlog/${projectPath}/${postPath}`. + - `listComlogProjects(page: number): Promise` — 켜짐·밴 아님·프로젝트 public·`isListedEntry` 회차 1개 이상, 최근 회차 게시순, 카드 필드(설계 §10), 작성자는 프로젝트 작성자 설정. + - `getComlogProjectPage(projectId: string, viewerId: string | null): Promise` — 회차는 `canViewEntry` 통과분만 최신순, 썸네일 = 본문 첫 이미지 src (없으면 null), 게시 시각 포함, 작성자에게 비공개 표시 플래그. + - `getComlogEntryPage(projectId, postId, viewerId): Promise` — 이전/다음은 viewer 가 볼 수 있는 회차 사이에서, 짝 블로그 글은 게시되어 있고 공개/일부 공개이며 밴이 아닐 때만 링크. + - `listComlogSitemapEntries(): Promise<…>` — `isListedEntry` 회차 + public 프로젝트 페이지. + - 페이지: 볼 수 없으면 `notFound()`. `unlisted`·`private` 는 `robots: { index: false }`. OG 이미지 라우트도 같은 판정(비공개·꺼짐이면 404). 프로젝트 대표 이미지가 없으면 OG 생성기로 이름 이미지. + - 메뉴 "comlog" (ko/en 동일), 목록 제목 아래 설명 ko "프로젝트 제작기" / en "Build logs from real commits". + - GitHub 링크는 `showGithubLink` 가 true 일 때만, 표시 이름은 프로젝트 `name` (저장소 full name 노출 금지). + +- [ ] **Step 1: 실패하는 테스트** — `paths.test.ts`: 경로 왕복, 잘못된 조각 null. 조회 함수의 필터 판단은 Task 3 함수 호출로만 하도록 하고, 페이지별로 `canView*` 를 거치는지 확인하는 대신 `lib/comlog/queries.ts` 의 행→화면 변환 함수(`toEntryListItems(rows, access, viewerId)`)를 순수로 빼서 비공개 회차가 남에게 빠지고 작성자에게 표시 플래그로 남는지, 이전/다음이 숨김 회차를 건너뛰는지 테스트. +- [ ] **Step 2: 실패 확인**. +- [ ] **Step 3: 구현** — Next 16 문서(`node_modules/next/dist/docs/`)에서 동적 라우트 params(Promise), `generateMetadata`, `opengraph-image` 규칙 확인 후 기존 `/posts` 라우트와 같은 패턴으로. +- [ ] **Step 4: 통과 확인** — `pnpm vitest run` + tsc + 바뀐 파일 eslint. +- [ ] **Step 5: 커밋** — `feat(comlog): /comlog 목록·프로젝트·회차 공개 페이지`. + +### Task 12: 저장소 설정의 comlog 토글과 안내 + +**Files:** +- Create: `lib/actions/comlog.ts` +- Modify: `components/studio/repository-settings-panel.tsx`, `components/studio/auto-draft-settings-section.tsx` + +**Interfaces:** +- Consumes: `enableComlog`, `disableComlog`, `getComlogProject` (Task 5). +- Produces (server actions, 모두 `requireSession` + 본인 연결 저장소 확인): + - `toggleComlog(repositoryId: string, enabled: boolean): Promise<{status:'ok'; enabled:boolean} | {status:'not_found'|'github_unavailable'}>` — 끄면 `revalidateLocalizedPath('/comlog')`·프로젝트 경로·`revalidateSitemap()`. + - `saveComlogProject(repositoryId: string, patch: ComlogProjectPatch)` → `updateComlogProject` 결과 + 같은 재검증. + - `getComlogPanelState(repositoryId)` → `{ enabled, project | null, presetLength }`. +- 화면: 저장소 설정 패널에 "comlog 사용" 토글, 켤 때 프리셋이 비었거나 100자 미만이면 권장 문구 (설계 §7). 트리거 안내에 `[comdraft]`, `[comdraft] post`, `[comdraft] post log`(쿼터 두 번) 줄 추가. + +- [ ] **Step 1: 실패하는 테스트** — 권장 문구 표시 판정 `shouldRecommendPreset(prompt: string): boolean` (`lib/comlog/rules.ts` 에 추가): `''`→true, 99자→true, 100자→false. +- [ ] **Step 2: 실패 확인**. +- [ ] **Step 3: 구현**. +- [ ] **Step 4: 통과 확인**. +- [ ] **Step 5: 커밋** — `feat(comlog): 저장소 설정의 comlog 토글`. + +### Task 13: 스튜디오 회차 사이드바·프로젝트 소개 편집 + +**Files:** +- Create: `components/studio/comlog-sidebar.tsx`, `components/studio/comlog-project-editor.tsx`, `app/[lang]/dashboard/repositories/[repositoryId]/comlog/page.tsx` +- Modify: `components/studio/studio-shell.tsx`, `studio-context.tsx` (`StudioPanel` 에 `'comlog'`), `draft-sidebar.tsx`, `draft-list-item.tsx`, `commit-sidebar.tsx`, `prompt-composer.tsx`, `lib/studio/queries.ts` (`getStudioRepository` 에 `comlog: { enabled; openBacklogCount; entryCount; status } | null`), `lib/studio/sidebar-width.ts` (접기 상태) +- Test: `lib/studio/comlog-view.test.ts` (새 순수 함수) + +**Interfaces:** +- Consumes: Task 8 markers(`applied`, `backlog`), Task 6 `requestDraftGeneration(… draftKind)`, Task 12 `saveComlogProject`. +- Produces: + - `splitStudioDrafts(drafts: StudioDraftSummary[]): { entries: StudioDraftSummary[]; regular: StudioDraftSummary[] }` (회차는 최신순) — `lib/studio/comlog-view.ts`. + - `isComlogView(pathname: string, activeDraft: {kind: DraftKind} | null): boolean` — `/comlog` 소개 경로이거나 회차 초안을 보고 있을 때 회차 칸 표시. + - 배치: 초안 목록 → 회차 칸 → 커밋 목록 → 편집기 (설계 §9). 회차 칸: 밀린 커밋 안내(N>0), 프로젝트 소개, 회차 목록, 새 회차. 접기 가능, 모바일은 서랍(`openPanel === 'comlog'`). + - 회차를 열면 커밋 목록이 그 초안의 최근 완료 작업 `commit_shas` 를 선택 상태로 시작하고 `applied` 표시. 체크가 달라지면 프롬프트 입력의 보내기 문구를 "고른 커밋으로 다시 작성" 으로. + - "새 회차": `draftKind:'comlog'` 로 빈 초안 생성 (기존 새 초안 흐름 + 종류). + - 프로젝트 소개 편집: 이름, 상태, 소개, 기술 스택(추가·삭제), 대표 이미지(기존 이미지 업로드 흐름, Task 14), GitHub 링크 표시(비공개 저장소면 끄고 비활성 이유 안내), 데모 링크, 공개 범위, 작성자 표시(기존 `publish-author-fields.tsx` 재사용), 프리셋 권장 안내, 꺼짐·숨김 상태 안내. + - 일반 초안 항목에 짝 회차가 있으면 작은 링크 표시. + +- [ ] **Step 1: 실패하는 테스트** — `splitStudioDrafts` 가 종류로 나누고 회차를 최신순 정렬, `isComlogView` 경로/초안 조합 4가지. +- [ ] **Step 2: 실패 확인**. +- [ ] **Step 3: 구현** — 사이드바는 기존 `getSidebarClass`, `THIN_SCROLL_CLASS` 스타일을 따름. +- [ ] **Step 4: 통과 확인** — `pnpm vitest run` + tsc + 바뀐 파일 eslint. 로컬 dev 서버에서 회차 칸 열기/접기, 회차 선택 시 커밋 표시 확인 (스크린샷). +- [ ] **Step 5: 커밋** — `feat(comlog): 스튜디오 회차 사이드바와 프로젝트 소개 편집`. + +### Task 14: 대표 이미지 업로드와 정리 예외 + +**Files:** +- Modify: `lib/actions/images.ts`, `lib/images/cleanup.ts`, `lib/images/rules.ts` +- Test: `lib/images/rules.test.ts` + +**Interfaces:** +- Produces: + - `uploadComlogCover(repositoryId: string, formData: FormData): Promise<{status:'ok'; imageId: string; url: string} | …>` — 기존 업로드 변환·한도 재사용, `image.draft_id = null`, `comlog_project.cover_image_id` 갱신 (이전 커버는 정리 대상으로). + - 정리 규칙: `comlog_project.cover_image_id` 가 가리키는 이미지는 어떤 정리 경로에서도 지우지 않음. 순수 판정 `isProtectedImage(imageId, protectedIds: Set): boolean` 을 정리 함수들이 거침. + +- [ ] **Step 1: 실패하는 테스트** — 정리 후보 목록에서 보호 id 가 빠짐. +- [ ] **Step 2: 실패 확인**. +- [ ] **Step 3: 구현** — `draft_id` 가 null 인 이미지를 지우는 경로가 있는지 먼저 확인하고 그 경로에도 적용. +- [ ] **Step 4: 통과 확인**. +- [ ] **Step 5: 커밋** — `feat(comlog): 프로젝트 대표 이미지`. + +### Task 15: 관리자 콘솔 — 프로젝트 숨기기 + +**Files:** +- Create: `lib/admin/comlog-queries.ts`, 관리자 콘솔 페이지 `app/[lang]/admin/[adminKey]/(console)/comlog/page.tsx` +- Modify: 관리자 메뉴, `lib/admin/audit.ts` (액션 종류 추가) +- Test: `lib/admin/comlog-queries.test.ts` (순수 부분) + +**Interfaces:** +- Produces: `setComlogProjectBan(projectId: string, action: 'ban'|'unban', reason: string | null, adminId: string): Promise<'banned'|'unbanned'|'not_found'>` — `requireAdmin` 뒤, 감사 기록, `revalidateSitemap()` 과 comlog 경로 재검증. 사유 규칙은 `parseModerationRequest` 와 같은 길이 제한(500자). 목록: 프로젝트 이름·소유자·회차 수·상태·숨김 여부. + +- [ ] **Step 1: 실패하는 테스트** — 사유 검증(ban 은 1~500자 필수, unban 은 무시) 순수 함수 `parseComlogBanInput`. +- [ ] **Step 2: 실패 확인**. +- [ ] **Step 3: 구현** — 기존 게시글 밴 관리자 화면과 같은 구조. +- [ ] **Step 4: 통과 확인**. +- [ ] **Step 5: 커밋** — `feat(admin): comlog 프로젝트 숨기기`. + +### Task 16: 번역·전체 검증·실제 AI 확인 + +**Files:** +- Modify: `locales/*` (Lingui), 필요 시 앞 Task 파일 수정 + +- [ ] **Step 1: 번역** — `pnpm i18n:extract` → en 빈 항목 채움 → `pnpm i18n:compile`. +- [ ] **Step 2: 전체 검사** — `pnpm vitest run`, `pnpm tsc --noEmit`, 바뀐 파일 `pnpm eslint `, `pnpm prettier --check `, `pnpm build` → 모두 PASS. comdraft-lambda: `pnpm vitest run`, `pnpm tsc --noEmit`, `pnpm build`(smoke 포함). +- [ ] **Step 3: 로컬 실제 확인** (dev 서버, 로컬 관리자 테스트 계정 또는 본인 계정, 실제 Lambda 는 로컬 env 그대로) + - 저장소 설정에서 comlog 켜기 → 소개가 저장소 설명·언어로 채워짐 + - 스튜디오 "새 회차" 에서 커밋 2~3개 골라 실제 AI 작성 1회 → 글 종류 worklog·짧게, 결론 문장으로 끝나는지 확인 + - 회차 게시(공개) → `/comlog`, 프로젝트 페이지, 회차 상세 확인. `/posts` 목록·`/posts/[회차 id]` 에 없음, `/sitemap.xml` 에 회차 주소 있음 + - 같은 회차를 비공개로 바꿔 로그아웃 창에서 404 확인, 프로젝트 일부 공개 → 목록에서 빠지고 noindex + - comlog 끄기 → 모든 comlog 주소 404, 다시 켜면 복구 + - (선택, 1회) 커밋 고르기를 바꿔 "다시 작성" + - 실제 AI 호출은 이 단계에서 최대 2~3회. +- [ ] **Step 4: 커밋** — `chore(comlog): 번역 추가`. +- [ ] **Step 5: 운영 준비 메모** — 운영 마이그레이션 SQL 파일 이름, Lambda 배포 순서(Lambda `worklog` 먼저 배포 → comdraft), 검수 루틴 프롬프트에 `/comlog` 추가 요청, 트리거 안내 변경을 사용자에게 전달할 내용으로 정리. diff --git a/docs/superpowers/specs/2026-12-01-comlog-design.md b/docs/superpowers/specs/2026-12-01-comlog-design.md new file mode 100644 index 0000000..5f93e15 --- /dev/null +++ b/docs/superpowers/specs/2026-12-01-comlog-design.md @@ -0,0 +1,222 @@ +# comlog (저장소 작업 기록) 설계 + +- 작성일: 2026-12-01 +- 상태: 승인 (2026-12-01) +- 대상: comdraft (DB 스키마, 저장소 설정, 커밋 트리거, 스튜디오, 공개 페이지), comdraft-lambda (글 종류 `worklog` 추가) +- 관련 문서: `2026-11-24-commit-trigger-auto-draft-design.md` (커밋 트리거 자동 초안). 이 문서의 용어(경계, 기준점, 묶음, 제외, 사용됨, 트리거 커밋)를 그대로 쓴다. + +## 1. 목적 + +커밋 트리거는 지금 블로그 글 초안만 만든다. 하지만 저장소에 쌓이는 작업은 간단한 수정, 일부 기능 추가, 라이브러리 도입처럼 블로그 글 한 편으로는 작거나 애매한 것이 많다. + +comlog 는 연결한 저장소 하나의 작업을 꾸준히 기록하는 공간이다. 완성된 프로젝트를 공유하면서 만든 과정까지 함께 보여 주는 것이 목적이다. 각 회차는 이어지는 이야기가 아니라 따로 읽히는 **작업 기록**이며, 블로그 글처럼 쓰되 짧고 "그래서 이번 작업에서 ~를 했다" 는 결론으로 끝난다 (`## 결론` 같은 절 제목은 두지 않는다). + +## 2. 목표 / 비목표 / 실패 조건 + +- 목표 + - 저장소 설정에 "comlog 사용" 토글. 켜면 그 저장소의 커밋 트리거가 기본으로 comlog 회차 초안을 만든다 + - 커밋 제목 `[comdraft] post` 로 블로그 글, `[comdraft] post log` 로 둘 다 + - 회차는 지금 초안과 똑같이 스튜디오에서 다듬고 게시한다 (커밋 선택, 다시 작성, 프롬프트 내역 그대로) + - 스튜디오에 comlog 회차 사이드바 추가 (초안 목록 → 회차 목록 → 커밋 목록 → 편집기) + - 공개 페이지: comlog 메뉴(프로젝트 카드 목록) → 프로젝트 페이지(소개 + 회차 목록) → 회차 상세 + - 프로젝트 소개는 comlog 를 켤 때 GitHub 저장소 정보로 채우고 이후 직접 수정 + - 기술 스택은 회차를 게시할 때마다 회차 태그로 자동 추가, 직접 수정 가능, 지운 기술은 다시 넣지 않음 + - 공개 범위: 프로젝트와 회차 각각 공개 / 일부 공개 / 비공개, 더 좁은 쪽을 따름 + - 할당량 등으로 트리거가 막히면 그 사이 커밋을 "밀림" 으로 남기고, 사용자가 골라서 회차를 만든다 +- 비목표 + - 이전 회차 내용을 AI 에 넘기는 것 (프리셋에 프로젝트 설명을 넣도록 권장만) + - AI 가 프로젝트 소개를 써 주는 것 + - 밀린 커밋으로 회차를 한꺼번에 자동 생성하는 것 + - 회차 번호 (날짜로 표시) + - 알림, 댓글, 구독 + - 저장소 하나에 comlog 여러 개 (사용자·저장소당 하나) +- 실패 조건 (동작해도 실패로 본다) + - comlog 회차가 '게시글' 목록, 게시글 사이트맵, 게시글 검색에 섞여 나옴 + - 비공개 회차·비공개 프로젝트를 작성자가 아닌 사람이 볼 수 있음 (주소를 알아도) + - comlog 를 끈 뒤에도 프로젝트 페이지나 회차가 열리거나 목록·사이트맵에 남음 + - 비공개 저장소의 GitHub 주소가 공개 화면에 나옴 + - 사용자가 지운 기술이 다음 회차 게시 때 다시 기술 스택에 들어감 + - `[comdraft] post log` 가 쿼터를 두 번 쓴다는 사실이 안내 없이 일어남, 또는 시작 전 검사에서 하나만 통과해 하나만 만들어짐 (시작 뒤 Lambda 에서 하나가 실패하는 것은 막을 수 없음, §6.1) + - 막힌 트리거의 밀린 커밋이 할당량이 돌아온 뒤 첫 트리거의 묶음에 섞여 들어감 + - comlog 를 켜지 않은 저장소의 커밋 트리거 동작이 바뀜 + +## 3. 용어 + +| 용어 | 뜻 | +| --- | --- | +| comlog 프로젝트 | 사용자·저장소당 하나. 소개, 상태, 기술 스택, 공개 범위를 가진다 | +| 회차 | comlog 프로젝트에 속한 초안·게시글. 데이터로는 종류가 `comlog` 인 `draft` / `post` | +| 일반 글 | 지금의 블로그 초안·게시글. 종류 `post` | +| 밀린 커밋 | comlog 회차를 만들 트리거가 시작 전에 막혀서 기록되지 못한 커밋. 자동 묶음에는 다시 들어가지 않고 사용자가 골라 회차로 만든다 | +| 실효 공개 범위 | 프로젝트 공개 범위와 회차 공개 범위 중 더 좁은 쪽 (비공개 < 일부 공개 < 공개) | + +## 4. 방식 (결정) + +검토한 방식: + +- **A. 기존 `draft` / `post` 에 종류 칸 추가 (선택)**: 회차도 게시글이라 작성자 표시, 조회수, 매일 검수, OG 이미지, 검색 노출을 그대로 물려받는다. 대가는 게시글 쪽 조회에 "종류 = post" 조건을 빠짐없이 넣어야 한다는 것. +- B. 초안은 공유, 게시된 회차만 새 테이블: 섞일 위험은 없지만 조회수·검수·작성자 표시·OG·사이트맵을 한 벌 더 만들고 계속 두 곳을 고쳐야 한다. +- C. 초안부터 전부 별도: 스튜디오 동작(커밋 선택, 다시 작성, 프롬프트 내역)을 다시 만들어야 해서 "기존 스튜디오 그대로" 와 맞지 않는다. + +사용자가 A 를 골랐다. 섞임 위험은 게시글 조회 조건을 한 곳(예: `lib/posts/` 의 공통 조건 함수)에 모으고, 게시글 목록·사이트맵·상세·검색·관리자 목록 각각에 회차가 나오지 않는다는 테스트로 막는다. + +## 5. 데이터 모델 (마이그레이션 필요, 운영 적용은 사용자가 직접) + +### 5.1 새 테이블 `comlog_project` + +사용자·저장소당 한 행 (`(user_id, repository_id)` 유일). + +| 칸 | 뜻 | +| --- | --- | +| `id` | 기본 키 | +| `user_id` | 사용자 (계정 삭제 시 함께 삭제) | +| `repository_id` | 저장소 (저장소 연결 해제 시 함께 삭제, §11) | +| `enabled` | comlog 사용 여부. 끄면 숨김 (행과 회차는 지우지 않음) | +| `name` | 프로젝트 이름 (처음엔 저장소 이름) | +| `slug` | 주소용 (이름에서 만듦, 게시글 `createPostSlug` 규칙) | +| `intro` | 소개 본문 (처음엔 저장소 설명, 비어 있을 수 있음) | +| `status` | `in_progress` / `completed` (처음엔 `in_progress`) | +| `tech_stack` | 기술 스택 (게시글 태그 정규화 규칙, 최대 20개) | +| `removed_tech` | 사용자가 지운 기술 (자동 추가에서 제외) | +| `cover_image` | 대표 이미지 (없으면 이름으로 만든 자동 이미지) | +| `show_github_link` | GitHub 링크 표시 (공개 저장소만 켤 수 있음, 처음엔 켜짐) | +| `demo_url` | 데모 링크 (처음엔 저장소 Website, http/https 만) | +| `visibility` | `public` / `unlisted` / `private` (처음엔 `public`) | +| `author_display`, `author_nickname`, `show_author_profile` | 프로젝트 페이지·카드의 작성자 표시 (게시글과 같은 규칙, `lib/posts/author-display.ts`). 처음 값은 첫 회차를 게시할 때 고른 설정으로 채우고, 이후 소개 편집 화면에서 직접 바꿈. 첫 회차 게시 전에는 기본값 | +| `banned_at`, `ban_reason` | 관리자가 프로젝트를 통째로 숨긴 시각과 사유 (§12) | +| `created_at`, `updated_at` | | + +`name`, `intro`, `demo_url`, `tech_stack` 의 처음 값은 **comlog 를 처음 켤 때** GitHub 에서 다시 읽어 채운다 (저장소 연결 시점의 값은 오래됐을 수 있음). 이후에는 GitHub 쪽이 바뀌어도 덮어쓰지 않는다. 껐다 다시 켜면 기존 행을 그대로 쓴다. 처음 기술 스택은 저장소 언어 중 바이트 수 상위 3개. + +### 5.2 기존 테이블 변경 + +- `draft.kind`: `post` / `comlog` (기본 `post`). 회차 초안은 `comlog`. +- `post.kind`: 같은 값. 게시할 때 초안의 종류를 복사. +- `post.visibility`: `private` 추가. **`comlog` 종류에만 허용** (일반 게시글 게시 창에는 나오지 않음, 서버 액션에서도 거절). +- 짝 연결: `[comdraft] post log` 로 함께 만든 두 초안을 서로 가리키는 칸 (예: `draft.paired_draft_id`). 상세 페이지 링크에만 쓴다. +- `draft_prompt.trigger_sha` 유일 인덱스: `(user_id, trigger_sha)` → 초안 종류를 포함하도록 바꾼다 (한 트리거로 블로그·회차 작업 두 개를 허용, 같은 종류 중복은 계속 막음). 초안 없이 남는 실패 행도 종류를 가져야 하므로 `draft_prompt` 에도 종류 칸이 필요하다 (Claude 판단: `draft_prompt.draft_kind`). +- 밀린 커밋: 기존 제외 목록(`repository_excluded_commit`)의 사유에 `backlog` 를 더해 저장한다 (§8). + +## 6. 트리거 규칙 (comlog 를 켠 저장소) + +| 커밋 제목 | 만드는 초안 | +| --- | --- | +| `[comdraft]` | 회차 | +| `[comdraft] log` | 회차 (위와 같음) | +| `[comdraft] post` | 일반 글 | +| `[comdraft] post log` | 둘 다 (같은 커밋 묶음) | + +- `post`, `log` 는 순서와 상관없이 단어로 인식한다. 다른 옵션 단어와 섞어 쓸 수 있다 (`[comdraft] post log friendly long`). +- 톤·글 종류·길이 단어는 **일반 글에만** 적용한다. 회차는 고정 옵션(§7)을 쓴다. +- comlog 를 켜지 않은 저장소: `log` 단어는 무시하고 지금과 똑같이 일반 글만 만든다. `post` 도 의미 없이 무시. +- comlog 사용과 자동 초안 토글은 따로다. 자동 초안이 꺼져 있으면 트리거는 동작하지 않지만, 스튜디오에서 직접 회차를 만들 수 있다. + +### 6.1 둘 다 만들 때 + +- 묶음 계산과 경계 선점은 한 번 한다. 두 작업은 같은 `commitShas` 와 같은 `trigger_sha` 를 쓴다 (종류만 다름). +- 시작 전 검사는 **두 작업을 합쳐서** 한다. 앱은 작업 예상량을 모르므로 (예상량은 Lambda 가 시작한 뒤 계산, `comdraft-lambda/src/quota.ts`) 주간 쿼터는 지금처럼 남은 양이 있는지만 보고, 시간당 요청 수와 동시 진행 수는 두 자리가 남아야 한다. 하나라도 모자라면 둘 다 만들지 않는다 (같은 커밋을 다시 쓸 수 없어 나머지를 만들 길이 애매해지기 때문). +- 두 작업 생성은 한 트랜잭션. 실행기 시작이 하나라도 실패하면 지금 규칙대로 그 작업을 실패 처리한다. 경계는 **둘 다** 시작하지 못했을 때만 되돌린다 (하나라도 시작했으면 그 작업이 커밋을 쓰고 있음). +- 시작 뒤 Lambda 에서 한쪽이 실패할 수 있다 (예상량이 남은 쿼터보다 큼 등). 회차 쪽이 실패하면 §8 의 밀린 커밋으로 남긴다. 일반 글 쪽이 실패하면 지금 동작과 같다. +- 트리거 문서(사용 안내)에 "둘 다는 쿼터를 두 번 쓴다" 를 적는다. + +## 7. AI 작성 (회차) + +- 회차 작업은 옵션을 고정한다: 글 종류 `worklog`, 길이 `short`. 톤·모델·필수 블록은 저장소 설정 기본값. +- comdraft-lambda 에 글 종류 `worklog` 를 추가한다 (ko/en 문구, 타입, 관리자 프롬프트 편집 키가 있으면 포함). 흐름: 이번 작업의 계기 → 무엇을 했는지 → "그래서 이번 작업에서 ~를 했다" 로 마무리. `## 결론` 같은 마무리 절 제목은 쓰지 않는다. 비슷한 내용을 이전 회차와 이어 쓰지 않는다 (이전 회차를 모른다). +- `worklog` 는 일반 글에서 고를 수 없다 (스튜디오 옵션 목록과 트리거 단어 해석에서 제외). +- 이전 회차 맥락은 넘기지 않는다. 대신 comlog 를 켤 때와 회차 작성 화면에서 프리셋이 비어 있거나 짧으면 "프리셋에 프로젝트 개요와 목적을 적어 두면 회차 품질이 좋아져요" 를 보여 준다 (막지는 않음). +- 기술 태그: 지금처럼 Lambda 가 `draft_prompt.tags` 에 기술 태그를 남기고 초안 태그로 반영된다. 회차를 게시할 때 그 태그를 프로젝트 `tech_stack` 에 더한다 (`removed_tech` 에 있는 것과 이미 있는 것은 빼고, 최대 20개). Lambda 계약 변경 없음. + +## 8. 밀린 커밋 (comlog 를 켠 저장소) + +지금은 트리거가 시작 전에 막히면(주간 쿼터, 시간당 요청 수, 동시 진행 수 등) 실패 행만 남기고 경계를 그대로 둔다. 그래서 할당량이 돌아온 뒤 첫 트리거가 밀린 커밋을 최대 20개까지 한 회차로 몰아 쓴다. comlog 에서는 이렇게 바꾼다. + +1. **회차를 만들 트리거**(`[comdraft]`, `log`, `post log`)가 시작 전에 막히면: 실패 행은 지금처럼 남긴다. 그리고 경계부터 푸시 끝까지의 대상 커밋(머지·제외·사용됨·빈 트리거를 뺀 것, 20개 제한 없이)을 제외 목록에 사유 `backlog` 로 넣고, 경계를 푸시 끝으로 옮긴다. + - 지금은 gate 검사가 묶음 계산보다 먼저다. 회차 트리거가 gate 에서 막히면 묶음 계산을 이어서 해야 한다. + - `[comdraft] post` (일반 글만) 가 막힌 경우는 지금 동작 그대로 (경계를 옮기지 않음). + - `no_preset`, `anchor_missing`, `no_commits` 같은 "할 게 없거나 설정 문제" 는 밀림으로 처리하지 않는다 (Claude 판단: 할당량·속도 제한 계열만. 대상: 주간 쿼터, 시간당 요청 수, 동시 진행 수, AI 작성 중지). +2. 밀린 커밋은 자동 묶음에 다시 들어가지 않는다 (경계 뒤에 있고, 제외 목록에도 있음). 할당량이 돌아온 뒤 첫 트리거는 새로 한 작업만 쓴다. +3. 스튜디오 회차 사이드바 맨 위에 "할당량 때문에 기록하지 못한 커밋 N개" 를 보여 준다. N 은 `backlog` 커밋 중 아직 회차 작업(실패 제외)에 쓰이지 않은 것. 커밋 목록에는 밀림 표시(아이콘 + 툴팁)를 둔다. +4. 사용자가 밀린 커밋을 골라 "새 회차" 로 작성하면 그 커밋은 사용됨으로 표시되고 N 에서 빠진다. 고르지 않은 커밋은 그대로 남는다. 기존 "제외" 메뉴로 치울 수 있다 (사유를 `user` 로 바꾸면 N 에서 빠짐). +5. 일괄 생성은 하지 않는다. +6. 시작 **뒤에** 실패한 회차 트리거 작업 (Lambda `quota_exceeded`, `runner_unavailable`, 작성 중 실패, 시간 초과 등) 도 경계가 이미 지나갔다면 그 작업의 커밋을 `backlog` 로 남긴다. 실패 처리하는 곳(작업 상태를 failed 로 바꾸는 앱 쪽 경로와, Lambda 가 failed 로 남긴 작업을 앱이 반영하는 경로)에서 기록한다. 경계가 지나가지 않은 경우(20개에서 잘림)는 지금처럼 사용됨에서 풀려 다음 묶음 대상이 되므로 기록하지 않는다. + +### 8.1 사용됨 규칙 (comlog 를 켠 저장소) + +- 회차 작업(종류 `comlog`) 은 출처와 상관없이 (트리거든 스튜디오 직접이든) 진행 중·완료면 그 커밋을 "회차에 사용됨" 으로 본다. 스튜디오에서 손으로 회차를 쓴 커밋은 다음 회차 트리거 묶음에서 빠진다 (같은 작업이 회차 두 개가 되지 않게). +- 일반 글 작업의 사용됨은 지금 규칙 그대로 (`source = 'commit_trigger'` 만). +- 묶음 계산 시 건너뛰는 사용됨 집합: 회차만 만드는 트리거는 "회차에 사용됨", 일반 글만 만드는 트리거는 지금 규칙, `post log` 는 두 집합의 합. +- 커밋 목록 표시: 회차를 보고 있을 때는 "회차에 사용됨", 일반 초안을 보고 있을 때는 지금 표시. + +## 9. 스튜디오 + +배치 (왼쪽부터): 초안 목록 → **회차 목록 (새 칸)** → 커밋 목록 → 편집기. 편집기는 계속 가장 오른쪽. + +- 초안 목록 맨 위에 comlog 항목 (comlog 를 켠 저장소만). 이름 "comlog", 회차 수, 프로젝트 상태. 일반 초안은 그 아래 지금처럼. +- comlog 를 누르면 회차 칸이 나타난다. 일반 초안을 고르면 회차 칸이 빠지고 지금의 세 칸으로 돌아간다. 회차 칸은 접을 수 있다. 모바일은 다른 사이드바처럼 서랍으로 연다. +- 회차 칸: 맨 위 밀린 커밋 안내(§8), "프로젝트 소개", 회차 목록(최신순, 제목 + 날짜 + 상태/공개 범위), 맨 끝 "새 회차". +- "프로젝트 소개" 를 고르면 편집기 자리에 소개 편집 화면: 이름, 상태, 소개 본문, 기술 스택(추가·삭제), 대표 이미지(기존 이미지 업로드 사용), GitHub 링크 표시, 데모 링크, 공개 범위. 프리셋 권장 안내도 여기. +- 회차를 고르면 지금 초안 화면과 똑같다 (편집기, 프롬프트 입력, 되묻기, 빈칸 채우기, 게시). 위에 "커밋 N개 · 날짜 범위" 요약. +- 커밋 목록: 고른 회차의 최근 완료 작업 `commit_shas` 를 "적용됨" 으로 표시하고 체크해 둔다. 체크를 바꾸면 그 커밋으로 다시 작성할 수 있다 (지금 프롬프트 보내기와 같은 경로). 일반 초안에서도 같은 "적용됨" 표시를 할지는 구현 때 판단 (Claude 판단: 같은 컴포넌트라 같이 해도 됨). +- "새 회차": 종류 `comlog` 인 빈 초안을 만든다. 지금 "새 초안" 과 같다. +- `post log` 로 함께 만든 일반 초안에는 짝 회차 표시. +- 회차 게시 창: 지금 게시 창 + 공개 범위에 "비공개" 추가, 실효 공개 범위 안내 (프로젝트가 일부 공개면 "프로젝트가 일부 공개라 목록·검색에는 나오지 않아요"). + +## 10. 공개 페이지 + +주소 (게시글 `post-path` 처럼 id + slug): + +- `/comlog`: 프로젝트 카드 목록. 실효로 공개된 회차가 하나 이상 있고, 프로젝트가 `public` 이며 켜져 있는 것만. 최근 회차 게시순. 카드: 대표 이미지, 이름, 소개 앞부분, 상태, 회차 수, 최근 업데이트. +- `/comlog/[프로젝트]`: 상단 소개 (이름, 상태, 소개 본문, 기술 스택, 링크) + 회차 목록 (최신순, 제목, 날짜, 발췌, 썸네일 = 본문 첫 이미지, 없으면 없음). `unlisted` 프로젝트도 주소로 열림 (noindex). `private` 프로젝트는 작성자만. +- `/comlog/[프로젝트]/[회차]`: 게시글 상세와 같은 본문 렌더링 + 이전/다음 회차 + 프로젝트로 돌아가기. 짝 블로그 글이 게시되어 있고 실효로 볼 수 있으면 "자세한 과정은 이 글에서" 링크. +- 실효 공개 범위 + - 공개: 목록·사이트맵·검색 노출 + - 일부 공개: 주소로만, noindex, 목록·사이트맵 제외 + - 비공개: 작성자만 (다른 사람에게는 404). 작성자에게는 프로젝트 페이지 목록에 "비공개" 표시와 함께 보임 +- 이전/다음은 보는 사람이 볼 수 있는 회차 사이에서만 이동한다. +- 작성자 표시(이름/아이디/별명, 프로필), 조회수, OG 이미지, JSON-LD, 매일 검수(밴)는 게시글과 같게 적용한다. 밴된 회차는 게시글처럼 숨긴다. +- 프로젝트 카드·프로젝트 페이지·프로젝트 JSON-LD 의 작성자는 프로젝트의 작성자 표시 설정(§5.1)을 따른다. 회차 상세는 그 회차의 설정을 따른다. +- 밴된 프로젝트(`banned_at` 있음)는 끈 것과 같이 프로젝트 페이지와 모든 회차가 404, 목록·사이트맵에서 빠진다. 작성자의 스튜디오에는 숨겨졌다는 안내를 보여 준다. +- 헤더 메뉴에 "comlog" 추가 (ko/en 모두 "comlog"). 페이지 제목 아래 한 줄 설명 (ko "프로젝트 제작기", en "Build logs from real commits"). +- GitHub 링크: 저장소가 비공개면 절대 표시하지 않는다 (`show_github_link` 와 무관). 공개 화면에는 `name` 만 쓰고 저장소 full name 은 쓰지 않는다. +- 비공개 여부 최신화: 지금 `github_repository.is_private` 는 연결할 때만 기록된다. 다음 때마다 GitHub 값으로 갱신한다: comlog 를 켤 때, 웹훅 push 페이로드의 `repository.private` (추적 브랜치가 아니어도), 스튜디오를 열 때, 회차·소개를 게시·저장할 때. 링크는 마지막으로 확인한 값이 공개일 때만 보인다 (Claude 판단: GitHub App 의 repository 이벤트 구독은 외부 설정이 필요해 이번 범위에서 뺌. 푸시가 없는 저장소가 비공개로 바뀌는 경우는 다음 갱신 때까지 링크가 남을 수 있으나, 링크를 눌러도 404 라 저장소 내용은 드러나지 않음). + +## 11. 켜기 / 끄기 / 연결 해제 + +- 켜기: 처음이면 `comlog_project` 행을 만들고 GitHub 에서 값을 채운다 (§5.1). 다시 켜면 기존 행을 `enabled = true` 로. +- 끄기: `enabled = false`. 프로젝트 페이지와 모든 회차가 공개 화면에서 404, 목록·사이트맵에서 빠진다 (사이트맵 재생성). 데이터는 지우지 않으며 다시 켜면 그대로 돌아온다. 스튜디오의 회차 초안은 작성자에게 계속 보이되 게시·트리거로 새 회차를 만들 수는 없다 (Claude 판단: 꺼져 있으면 comlog 항목을 "꺼짐" 으로 보여 주고 회차 열람만 허용). +- 저장소 연결 해제: 지금처럼 초안·게시글이 지워지고, `comlog_project` 도 지운다. + +## 12. 운영·기타 + +- 게시글 조회 공통 조건: '게시글' 목록, 게시글 사이트맵, 게시글 상세(`/posts/...`), 관리자 게시글 목록·통계는 종류 `post` 만 (관리자에서 회차를 따로 볼지는 구현 때 판단, 최소한 섞여 보이지 않게). 회차를 `/posts/[id]` 주소로 열면 404 (또는 comlog 주소로 이동, Claude 판단: 404). +- 매일 검수 루틴: 루틴은 DB 없이 공개 사이트(게시글 목록)를 읽어 새 글을 찾고 `POST /api/moderation/posts` 로 밴한다. 회차는 게시글 목록에 없으므로 루틴이 `/comlog` 와 프로젝트 페이지도 읽어야 한다 (프로젝트 페이지에 소개가 있어 회차와 함께 검수됨). 밴 API 는 회차 주소(`/comlog/[프로젝트]/[회차]`, 마지막 조각이 게시글 id-slug 형식)도 받도록 한다. 루틴 프롬프트 수정은 운영 배포 뒤 사용자 확인을 받아 한다 (원격 루틴 설정). +- `/comlog` 목록에 "최근 회차" 정렬 기준(최근 회차 게시순)을 두어 루틴이 지난 24시간 회차가 있는 프로젝트를 찾기 쉽게 한다. 프로젝트 페이지의 회차 목록에는 게시 시각을 표시한다. +- 관리자 콘솔: 프로젝트를 통째로 숨기기/되돌리기 (`banned_at`, `ban_reason`, 감사 기록은 기존 게시글 밴과 같은 방식). 검수 API 로 프로젝트 자체를 밴하는 기능은 이번 범위에 넣지 않는다 (루틴이 문제를 찾으면 회차를 밴하고, 프로젝트 소개가 문제면 관리자가 콘솔에서 숨김). +- 대시보드 저장소 카드: comlog 를 켠 저장소에 표시 (선택). +- i18n: 새 문구는 모두 ko + en (Lingui). +- 아이콘: lucide. +- 마이그레이션: 로컬은 `pnpm db:migrate:local`, 운영은 사용자가 직접 적용. 운영 적용 전 의존 배포 보류. + +## 13. 테스트 + +- 트리거 해석: comlog 켬/끔 × `[comdraft]` / `log` / `post` / `post log` / 옵션 섞기 +- 둘 다: 쿼터·시간당·동시 진행 합산 판정, 하나라도 모자라면 둘 다 안 만듦, 같은 트리거 재전송 중복 방지 (종류별) +- 밀린 커밋: 회차 트리거가 gate 에서 막히면 `backlog` 기록 + 경계 이동, `post` 만 막히면 지금 동작, 이후 트리거 묶음에 밀린 커밋 없음, 회차로 쓰면 N 감소 +- 공개 범위: 실효 범위 계산 표, 비공개 회차·프로젝트 404, 일부 공개 noindex·목록 제외, 이전/다음이 볼 수 없는 회차를 건너뜀 +- 섞임 방지: 게시글 목록·사이트맵·상세·관리자 목록에 회차 없음 +- 끄기: 모든 공개 경로 404, 사이트맵 제외, 다시 켜면 복구 +- 기술 스택: 게시 시 병합, `removed_tech` 제외, 최대 20개 +- 작성자 표시: 첫 회차 게시 때 프로젝트 설정이 채워지고 이후 회차 게시는 바꾸지 않음, 프로젝트 페이지가 프로젝트 설정을 따름 +- 프로젝트 밴: 모든 공개 경로 404, 되돌리면 복구, 검수 API 응답에 프로젝트 이름·소개 포함 +- GitHub 링크: 비공개 저장소는 항상 숨김 +- Lambda: `worklog` 문구가 프롬프트 표에 들어가고 일반 글 옵션에는 노출되지 않음 + +- 이미지 정리: 지금 이미지 정리는 초안·게시글 본문이 가리키는 이미지만 남긴다. `comlog_project.cover_image` 도 남기도록 규칙을 넓힌다. + +## 14. 빌더에게 맡기는 것 + +- 컴포넌트 분리 방식, 회차 칸 접기 상태 저장 방식 (지금 사이드바 너비 저장과 같은 방식 권장) +- 관리자 콘솔에서 회차를 어떻게 보여 줄지 (섞이지 않게만) +- 프로젝트 카드 자동 이미지 디자인 (게시글 OG 이미지 생성기 재사용) +- 밀린 커밋 아이콘 모양 (기존 커밋 표시 아이콘 체계에 맞춤) From 7b27c83e6879fe7716ab8a193c29f0901cda5ce2 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 15:39:30 +0900 Subject: [PATCH 02/27] =?UTF-8?q?feat(comlog):=20=ED=9A=8C=EC=B0=A8=20?= =?UTF-8?q?=EA=B3=A0=EC=A0=95=20=EC=98=B5=EC=85=98=EA=B3=BC=20=ED=8A=B8?= =?UTF-8?q?=EB=A6=AC=EA=B1=B0=20=EB=8B=A8=EC=96=B4=20post=C2=B7log?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../studio/auto-draft-settings-section.tsx | 4 +- components/studio/prompt-options.tsx | 4 +- lib/auto-draft/run.test.ts | 10 ++- lib/auto-draft/trigger.test.ts | 64 +++++++++++++++++-- lib/auto-draft/trigger.ts | 26 ++++++-- lib/auto-draft/webhook.test.ts | 25 ++++++-- lib/studio/options.test.ts | 38 +++++++++++ lib/studio/options.ts | 35 +++++++++- 8 files changed, 185 insertions(+), 21 deletions(-) diff --git a/components/studio/auto-draft-settings-section.tsx b/components/studio/auto-draft-settings-section.tsx index 38ee403..b47295d 100644 --- a/components/studio/auto-draft-settings-section.tsx +++ b/components/studio/auto-draft-settings-section.tsx @@ -17,7 +17,7 @@ import { import { MAX_GENERATION_PROMPT_LENGTH } from '@/lib/generation/limits'; import { LENGTHS, - POST_TYPES, + SELECTABLE_POST_TYPES, TONES, type PromptOptions as PromptOptionsValue, } from '@/lib/studio/options'; @@ -36,7 +36,7 @@ type Notice = { kind: 'saved' } | { kind: 'error'; message: string } | null; // 사용법 표의 옵션 값 (커밋 제목에 적는 영어 단어라 번역하지 않음) const OPTION_VALUE_ROWS = [ { key: 'tone', values: TONES }, - { key: 'postType', values: POST_TYPES }, + { key: 'postType', values: SELECTABLE_POST_TYPES }, { key: 'length', values: LENGTHS }, ] as const; diff --git a/components/studio/prompt-options.tsx b/components/studio/prompt-options.tsx index f553db2..0efc75b 100644 --- a/components/studio/prompt-options.tsx +++ b/components/studio/prompt-options.tsx @@ -23,7 +23,7 @@ import { LENGTH_LABELS, LENGTHS, POST_TYPE_LABELS, - POST_TYPES, + SELECTABLE_POST_TYPES, REQUIRED_BLOCK_LABELS, REQUIRED_BLOCKS, TONE_LABELS, @@ -445,7 +445,7 @@ const PromptOptions = ({ onChange({ ...value, postType })} diff --git a/lib/auto-draft/run.test.ts b/lib/auto-draft/run.test.ts index 1d5b1be..f5bdb7f 100644 --- a/lib/auto-draft/run.test.ts +++ b/lib/auto-draft/run.test.ts @@ -46,9 +46,15 @@ const commit = (n: number, message = `커밋 ${n}`): BranchCommit => ({ // 트리거 하나인 푸시 (끝 SHA 기본값은 트리거 자신) const push = ( sha: string, - options: TriggerOptions = {}, + options: Partial = {}, headSha: string = sha, -): TriggerPush => ({ headSha, trigger: { sha, options } }); +): TriggerPush => ({ + headSha, + trigger: { + sha, + options: { targets: { post: false, log: false }, ...options }, + }, +}); // 부모를 직접 지정하는 커밋 const node = ( diff --git a/lib/auto-draft/trigger.test.ts b/lib/auto-draft/trigger.test.ts index c65bf67..44900bd 100644 --- a/lib/auto-draft/trigger.test.ts +++ b/lib/auto-draft/trigger.test.ts @@ -1,19 +1,26 @@ import { describe, expect, it, vi } from 'vitest'; import { DEFAULT_PROMPT_OPTIONS } from '@/lib/studio/options'; -import { mergeTriggerOptions, parseTrigger } from '@/lib/auto-draft/trigger'; +import { + mergeTriggerOptions, + parseTrigger, + resolveTriggerKinds, +} from '@/lib/auto-draft/trigger'; // options.ts 가 Lingui 매크로를 쓰므로 테스트에서는 대체한다 vi.mock('@lingui/core/macro', () => ({ msg: (id: unknown) => id })); +const NO_TARGETS = { post: false, log: false }; + describe('parseTrigger', () => { it('태그만 있으면 빈 옵션', () => { - expect(parseTrigger('[comdraft]')).toEqual({}); + expect(parseTrigger('[comdraft]')).toEqual({ targets: NO_TARGETS }); }); it('옵션 단어를 읽는다', () => { expect(parseTrigger('[comdraft] friendly short')).toEqual({ tone: 'friendly', length: 'short', + targets: NO_TARGETS, }); }); @@ -21,28 +28,39 @@ describe('parseTrigger', () => { expect(parseTrigger('[comdraft] LECTURE\tlong')).toEqual({ postType: 'lecture', length: 'long', + targets: NO_TARGETS, }); }); it('같은 종류는 앞의 값을 쓴다', () => { - expect(parseTrigger('[comdraft] short long')).toEqual({ length: 'short' }); + expect(parseTrigger('[comdraft] short long')).toEqual({ + length: 'short', + targets: NO_TARGETS, + }); }); it('모르는 단어는 무시한다', () => { - expect(parseTrigger('[comdraft] hello short')).toEqual({ length: 'short' }); + expect(parseTrigger('[comdraft] hello short')).toEqual({ + length: 'short', + targets: NO_TARGETS, + }); }); it('첫 줄만 본다', () => { expect(parseTrigger('[comdraft] plain\n\nbody short')).toEqual({ tone: 'plain', + targets: NO_TARGETS, }); expect(parseTrigger('[comdraft] plain\r\nbody short')).toEqual({ tone: 'plain', + targets: NO_TARGETS, }); }); it('태그 뒤가 줄 끝일 때 줄바꿈도 허용한다', () => { - expect(parseTrigger('[comdraft]\nbody short')).toEqual({}); + expect(parseTrigger('[comdraft]\nbody short')).toEqual({ + targets: NO_TARGETS, + }); }); it.each(['[Comdraft]', '[comdraft]x', 'fix [comdraft]', ' [comdraft]', ''])( @@ -53,6 +71,42 @@ describe('parseTrigger', () => { ); }); +describe('parseTrigger 의 글 종류 단어', () => { + it('post·log 를 대소문자 무시하고 읽는다', () => { + expect(parseTrigger('[comdraft] post LOG friendly')).toEqual({ + tone: 'friendly', + targets: { post: true, log: true }, + }); + }); + + it('worklog 는 글 종류로 고르지 않는다', () => { + expect(parseTrigger('[comdraft] worklog')?.postType).toBeUndefined(); + }); +}); + +describe('resolveTriggerKinds', () => { + const none = { post: false, log: false }; + const post = { post: true, log: false }; + const log = { post: false, log: true }; + const both = { post: true, log: true }; + + it('comlog 켜짐: 단어 없음·log 는 comlog', () => { + expect(resolveTriggerKinds(true, none)).toEqual(['comlog']); + expect(resolveTriggerKinds(true, log)).toEqual(['comlog']); + }); + + it('comlog 켜짐: post 는 post, 둘 다면 post 먼저', () => { + expect(resolveTriggerKinds(true, post)).toEqual(['post']); + expect(resolveTriggerKinds(true, both)).toEqual(['post', 'comlog']); + }); + + it('comlog 꺼짐: 항상 post 하나', () => { + for (const targets of [none, post, log, both]) { + expect(resolveTriggerKinds(false, targets)).toEqual(['post']); + } + }); +}); + describe('mergeTriggerOptions', () => { it('트리거에 지정된 값만 바꾼다', () => { const merged = mergeTriggerOptions(DEFAULT_PROMPT_OPTIONS, { diff --git a/lib/auto-draft/trigger.ts b/lib/auto-draft/trigger.ts index 96bc9d8..0ba6e73 100644 --- a/lib/auto-draft/trigger.ts +++ b/lib/auto-draft/trigger.ts @@ -1,7 +1,8 @@ import { LENGTHS, - POST_TYPES, + SELECTABLE_POST_TYPES, TONES, + type DraftKind, type Length, type PostType, type PromptOptions, @@ -16,6 +17,8 @@ export interface TriggerOptions { tone?: Tone; postType?: PostType; length?: Length; + // 만들 초안 종류 단어 (post·log). 둘 다 없으면 둘 다 false + targets: { post: boolean; log: boolean }; } // 단어가 목록에 있으면 해당 값, 없으면 undefined @@ -35,13 +38,16 @@ export function parseTrigger(message: string): TriggerOptions | null { // 태그 바로 뒤는 줄 끝이거나 공백/탭이어야 함 if (rest !== '' && !/^[ \t]/.test(rest)) return null; - const options: TriggerOptions = {}; + const options: TriggerOptions = { targets: { post: false, log: false } }; for (const token of rest.split(/\s+/)) { const word = token.toLowerCase(); if (!word) continue; + if (word === 'post') options.targets.post = true; + else if (word === 'log') options.targets.log = true; + const tone = pickValue(TONES, word); - const postType = pickValue(POST_TYPES, word); + const postType = pickValue(SELECTABLE_POST_TYPES, word); const length = pickValue(LENGTHS, word); // 같은 종류는 먼저 나온 값 유지 if (tone && options.tone === undefined) options.tone = tone; @@ -55,7 +61,7 @@ export function parseTrigger(message: string): TriggerOptions | null { // 기본 옵션 위에 트리거에서 지정된 값만 덮어쓴 새 객체 (필수 블록·모델은 그대로) export function mergeTriggerOptions( base: PromptOptions, - trigger: TriggerOptions, + trigger: Omit, ): PromptOptions { return { ...base, @@ -64,3 +70,15 @@ export function mergeTriggerOptions( length: trigger.length ?? base.length, }; } + +// 트리거 단어와 저장소의 comlog 사용 여부로 만들 초안 종류를 정함 (순서 고정: post, comlog) +// - comlog 꺼짐: 단어와 무관하게 일반 글 하나 +// - comlog 켜짐: 단어 없음·log 만 → 회차, post 만 → 글, 둘 다 → 둘 다 +export function resolveTriggerKinds( + comlogEnabled: boolean, + targets: TriggerOptions['targets'], +): DraftKind[] { + if (!comlogEnabled) return ['post']; + if (!targets.post) return ['comlog']; + return targets.log ? ['post', 'comlog'] : ['post']; +} diff --git a/lib/auto-draft/webhook.test.ts b/lib/auto-draft/webhook.test.ts index 4e1e57a..1b352b7 100644 --- a/lib/auto-draft/webhook.test.ts +++ b/lib/auto-draft/webhook.test.ts @@ -122,7 +122,10 @@ describe('planPushEvent', () => { expect(planPushEvent(event(), target)).toEqual({ kind: 'trigger', headSha: HEAD, - trigger: { sha: 'a1', options: { length: 'short' } }, + trigger: { + sha: 'a1', + options: { length: 'short', targets: { post: false, log: false } }, + }, }); }); @@ -189,7 +192,10 @@ describe('planPushEvent', () => { expect(planPushEvent(e, target)).toEqual({ kind: 'trigger', headSha: HEAD, - trigger: { sha: 'a3', options: { length: 'long' } }, + trigger: { + sha: 'a3', + options: { length: 'long', targets: { post: false, log: false } }, + }, }); }); @@ -211,7 +217,10 @@ describe('planPushEvent', () => { ).toEqual({ kind: 'trigger', headSha: merged, - trigger: { sha: 'f2', options: { tone: 'friendly' } }, + trigger: { + sha: 'f2', + options: { tone: 'friendly', targets: { post: false, log: false } }, + }, }); // 제목을 [comdraft] 로 고친 머지 커밋이 가장 최신 expect( @@ -228,7 +237,10 @@ describe('planPushEvent', () => { ).toEqual({ kind: 'trigger', headSha: merged, - trigger: { sha: 'm', options: { length: 'long' } }, + trigger: { + sha: 'm', + options: { length: 'long', targets: { post: false, log: false } }, + }, }); // squash 머지 커밋 (web-flow, 제목은 PR 제목) expect( @@ -241,7 +253,10 @@ describe('planPushEvent', () => { ).toEqual({ kind: 'trigger', headSha: HEAD, - trigger: { sha: 's', options: { postType: 'lecture' } }, + trigger: { + sha: 's', + options: { postType: 'lecture', targets: { post: false, log: false } }, + }, }); }); }); diff --git a/lib/studio/options.test.ts b/lib/studio/options.test.ts index ba4ad4b..4e9ffa9 100644 --- a/lib/studio/options.test.ts +++ b/lib/studio/options.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it, vi } from 'vitest'; vi.mock('@lingui/core/macro', () => ({ msg: (id: unknown) => id })); import { + applyDraftKindOptions, DEFAULT_PROMPT_OPTIONS, parsePromptOptions, } from '@/lib/studio/options'; @@ -34,3 +35,40 @@ describe('parsePromptOptions 의 model', () => { expect(DEFAULT_PROMPT_OPTIONS.model).toBe('haiku'); }); }); + +describe('작업 기록(worklog) 글 종류', () => { + it('저장된 worklog 옵션도 읽는다', () => { + expect(parsePromptOptions({ ...base, postType: 'worklog' })).not.toBeNull(); + }); +}); + +describe('applyDraftKindOptions', () => { + it('comlog 는 글 종류 worklog·길이 short 로 고정한다', () => { + expect( + applyDraftKindOptions('comlog', { + ...DEFAULT_PROMPT_OPTIONS, + postType: 'lecture', + length: 'long', + }), + ).toEqual({ + ...DEFAULT_PROMPT_OPTIONS, + postType: 'worklog', + length: 'short', + }); + }); + + it('post 는 옵션을 그대로 돌려준다', () => { + expect(applyDraftKindOptions('post', DEFAULT_PROMPT_OPTIONS)).toEqual( + DEFAULT_PROMPT_OPTIONS, + ); + }); + + it('post 인데 worklog 면 null', () => { + expect( + applyDraftKindOptions('post', { + ...DEFAULT_PROMPT_OPTIONS, + postType: 'worklog', + }), + ).toBeNull(); + }); +}); diff --git a/lib/studio/options.ts b/lib/studio/options.ts index 4966a18..84d3d8a 100644 --- a/lib/studio/options.ts +++ b/lib/studio/options.ts @@ -14,9 +14,26 @@ import { export const TONES = ['plain', 'friendly', 'professional'] as const; export type Tone = (typeof TONES)[number]; -export const POST_TYPES = ['experience', 'lecture', 'experiment'] as const; +// 저장·검증용 (worklog 는 comlog 회차 전용이라 옛 기록을 읽을 수 있도록 포함) +export const POST_TYPES = [ + 'experience', + 'lecture', + 'experiment', + 'worklog', +] as const; export type PostType = (typeof POST_TYPES)[number]; +// 화면 선택·커밋 트리거용 (worklog 는 사용자가 직접 고르지 않음) +export const SELECTABLE_POST_TYPES = [ + 'experience', + 'lecture', + 'experiment', +] as const; + +// 초안 종류: 일반 블로그 글 / comlog 회차 +export const DRAFT_KINDS = ['post', 'comlog'] as const; +export type DraftKind = (typeof DRAFT_KINDS)[number]; + export const LENGTHS = ['short', 'medium', 'long'] as const; export type Length = (typeof LENGTHS)[number]; @@ -56,6 +73,7 @@ export const POST_TYPE_LABELS: Record = { experience: msg`경험`, lecture: msg`강의`, experiment: msg`실험`, + worklog: msg`작업 기록`, }; export const LENGTH_LABELS: Record = { @@ -124,3 +142,18 @@ export const parsePromptOptions = (value: unknown): PromptOptions | null => { model: resolvedModel, }; }; + +/** + * 초안 종류에 맞게 옵션을 확정 + * - comlog 회차는 글 종류 worklog·길이 short 로 고정 (사용자 옵션 무시) + * - 일반 글에 worklog 가 들어오면 맞지 않는 조합이라 null + */ +export const applyDraftKindOptions = ( + kind: DraftKind, + options: PromptOptions, +): PromptOptions | null => { + if (kind === 'comlog') { + return { ...options, postType: 'worklog', length: 'short' }; + } + return options.postType === 'worklog' ? null : options; +}; From 6e990717a6c94d4b53fa304878f40b3e63b302df Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 15:41:12 +0900 Subject: [PATCH 03/27] =?UTF-8?q?feat(comlog):=20=EA=B3=B5=EA=B0=9C=20?= =?UTF-8?q?=EB=B2=94=EC=9C=84=EC=99=80=20=EA=B8=B0=EC=88=A0=20=EC=8A=A4?= =?UTF-8?q?=ED=83=9D=20=EA=B7=9C=EC=B9=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/comlog/rules.test.ts | 195 +++++++++++++++++++++++++++++++++++++++ lib/comlog/rules.ts | 168 +++++++++++++++++++++++++++++++++ 2 files changed, 363 insertions(+) create mode 100644 lib/comlog/rules.test.ts create mode 100644 lib/comlog/rules.ts diff --git a/lib/comlog/rules.test.ts b/lib/comlog/rules.test.ts new file mode 100644 index 0000000..5af81c9 --- /dev/null +++ b/lib/comlog/rules.test.ts @@ -0,0 +1,195 @@ +import { describe, expect, it } from 'vitest'; +import { + COMLOG_MAX_TECH, + canViewEntry, + canViewProject, + effectiveVisibility, + isIndexable, + isListedEntry, + mergeTechStack, + parseDemoUrl, + removeTech, + showGithubLink, + topLanguages, + type ComlogAccess, + type ComlogVisibility, +} from '@/lib/comlog/rules'; + +const access = (over: Partial = {}): ComlogAccess => ({ + enabled: true, + bannedAt: null, + ownerId: 'owner', + projectVisibility: 'public', + ...over, +}); +const entry = ( + visibility: ComlogVisibility = 'public', + bannedAt: Date | null = null, +) => ({ visibility, bannedAt }); + +describe('effectiveVisibility', () => { + const table: Array<[ComlogVisibility, ComlogVisibility, ComlogVisibility]> = [ + ['public', 'public', 'public'], + ['public', 'unlisted', 'unlisted'], + ['public', 'private', 'private'], + ['unlisted', 'public', 'unlisted'], + ['unlisted', 'unlisted', 'unlisted'], + ['unlisted', 'private', 'private'], + ['private', 'public', 'private'], + ['private', 'unlisted', 'private'], + ['private', 'private', 'private'], + ]; + + it.each(table)('%s + %s -> %s', (p, e, expected) => { + expect(effectiveVisibility(p, e)).toBe(expected); + }); +}); + +describe('canViewProject', () => { + it('public 은 누구나', () => { + expect(canViewProject(access(), null)).toBe(true); + }); + + it('private 은 작성자만', () => { + const a = access({ projectVisibility: 'private' }); + expect(canViewProject(a, 'owner')).toBe(true); + expect(canViewProject(a, 'other')).toBe(false); + expect(canViewProject(a, null)).toBe(false); + }); + + it('꺼짐·밴이면 작성자도 false', () => { + expect(canViewProject(access({ enabled: false }), 'owner')).toBe(false); + expect(canViewProject(access({ bannedAt: new Date() }), 'owner')).toBe( + false, + ); + }); +}); + +describe('canViewEntry', () => { + it('private 회차는 작성자만', () => { + const e = entry('private'); + expect(canViewEntry(access(), e, 'owner')).toBe(true); + expect(canViewEntry(access(), e, 'other')).toBe(false); + expect(canViewEntry(access(), e, null)).toBe(false); + }); + + it('unlisted 는 누구나 (링크)', () => { + expect(canViewEntry(access(), entry('unlisted'), null)).toBe(true); + }); + + it('꺼짐이면 작성자도 false', () => { + expect(canViewEntry(access({ enabled: false }), entry(), 'owner')).toBe( + false, + ); + }); + + it('프로젝트 밴이면 false', () => { + expect( + canViewEntry(access({ bannedAt: new Date() }), entry(), 'owner'), + ).toBe(false); + }); + + it('회차 밴이면 false', () => { + expect(canViewEntry(access(), entry('public', new Date()), 'owner')).toBe( + false, + ); + }); + + it('프로젝트 private 이면 남은 못 봄', () => { + const a = access({ projectVisibility: 'private' }); + expect(canViewEntry(a, entry(), 'other')).toBe(false); + expect(canViewEntry(a, entry(), 'owner')).toBe(true); + }); +}); + +describe('isListedEntry / isIndexable', () => { + it('프로젝트 unlisted + 회차 public → 목록 아님', () => { + const a = access({ projectVisibility: 'unlisted' }); + expect(isListedEntry(a, entry())).toBe(false); + expect(isIndexable(a, entry())).toBe(false); + }); + + it('실효 public 이면 true', () => { + expect(isListedEntry(access(), entry())).toBe(true); + expect(isIndexable(access(), entry())).toBe(true); + }); + + it('꺼짐·밴·회차 밴이면 false', () => { + expect(isListedEntry(access({ enabled: false }), entry())).toBe(false); + expect(isListedEntry(access({ bannedAt: new Date() }), entry())).toBe( + false, + ); + expect(isListedEntry(access(), entry('public', new Date()))).toBe(false); + }); + + it('회차 없이 프로젝트만 판단', () => { + expect(isIndexable(access())).toBe(true); + expect(isIndexable(access({ projectVisibility: 'unlisted' }))).toBe(false); + expect(isIndexable(access({ enabled: false }))).toBe(false); + expect(isIndexable(access({ bannedAt: new Date() }))).toBe(false); + }); +}); + +describe('mergeTechStack', () => { + it('removed·중복 제외, 기존 순서 뒤에 추가', () => { + expect( + mergeTechStack(['next.js'], ['zod'], ['ZOD', 'drizzle', 'next.js']), + ).toEqual(['next.js', 'drizzle']); + }); + + it('최대 20개', () => { + const added = Array.from({ length: 21 }, (_, i) => `t${i}`); + expect(mergeTechStack([], [], added)).toHaveLength(COMLOG_MAX_TECH); + }); +}); + +describe('removeTech', () => { + it('스택에서 빼고 removed 에 정규화해 추가', () => { + expect(removeTech(['next.js', 'zod'], ['x'], ' ZOD ')).toEqual({ + stack: ['next.js'], + removed: ['x', 'zod'], + }); + }); + + it('removed 중복 없음', () => { + expect(removeTech(['a'], ['a'], 'a').removed).toEqual(['a']); + }); +}); + +describe('topLanguages', () => { + it('바이트 내림차순, 정규화, 개수 제한', () => { + expect( + topLanguages({ TypeScript: 100, CSS: 10, 'Vim Script': 50, Go: 5 }), + ).toEqual(['typescript', 'vim-script', 'css']); + expect(topLanguages({ A: 1, B: 2 }, 1)).toEqual(['b']); + }); +}); + +describe('showGithubLink', () => { + it('비공개 저장소면 항상 false', () => { + expect(showGithubLink({ showGithubLink: true }, { isPrivate: true })).toBe( + false, + ); + expect(showGithubLink({ showGithubLink: true }, { isPrivate: false })).toBe( + true, + ); + expect( + showGithubLink({ showGithubLink: false }, { isPrivate: false }), + ).toBe(false); + }); +}); + +describe('parseDemoUrl', () => { + it('http/https 만', () => { + expect(parseDemoUrl('javascript:alert(1)')).toBeNull(); + expect(parseDemoUrl('ftp://a.com')).toBeNull(); + expect(parseDemoUrl(' https://a.com/x ')).toBe('https://a.com/x'); + expect(parseDemoUrl('http://a.com')).toBe('http://a.com'); + }); + + it('잘못된 값·길이 초과', () => { + expect(parseDemoUrl(123)).toBeNull(); + expect(parseDemoUrl('not a url')).toBeNull(); + expect(parseDemoUrl(`https://a.com/${'a'.repeat(2048)}`)).toBeNull(); + }); +}); diff --git a/lib/comlog/rules.ts b/lib/comlog/rules.ts new file mode 100644 index 0000000..8efcab4 --- /dev/null +++ b/lib/comlog/rules.ts @@ -0,0 +1,168 @@ +import { normalizeTag } from '@/lib/posts/tags'; + +export type ComlogVisibility = 'public' | 'unlisted' | 'private'; + +// 프로젝트 기술 스택 최대 개수 (게시글 태그 10개와 별개) +export const COMLOG_MAX_TECH = 20; +export const COMLOG_MAX_DEMO_URL_LENGTH = 2048; + +export interface ComlogAccess { + enabled: boolean; + bannedAt: Date | null; + ownerId: string; + projectVisibility: ComlogVisibility; +} + +interface EntryAccess { + visibility: ComlogVisibility; + bannedAt: Date | null; +} + +// 더 좁은 쪽을 따름: 프로젝트가 비공개면 회차가 public 이어도 비공개 +const RANK: Record = { + public: 0, + unlisted: 1, + private: 2, +}; + +export const effectiveVisibility = ( + project: ComlogVisibility, + entry: ComlogVisibility, +): ComlogVisibility => (RANK[project] >= RANK[entry] ? project : entry); + +// 공개 화면 기준: 꺼짐·밴이면 작성자에게도 보이지 않음 +const isLive = (access: ComlogAccess): boolean => + access.enabled && access.bannedAt === null; + +const canSee = ( + visibility: ComlogVisibility, + ownerId: string, + viewerId: string | null, +): boolean => visibility !== 'private' || viewerId === ownerId; + +export const canViewProject = ( + access: ComlogAccess, + viewerId: string | null, +): boolean => + isLive(access) && canSee(access.projectVisibility, access.ownerId, viewerId); + +export const canViewEntry = ( + access: ComlogAccess, + entry: EntryAccess, + viewerId: string | null, +): boolean => + isLive(access) && + entry.bannedAt === null && + canSee( + effectiveVisibility(access.projectVisibility, entry.visibility), + access.ownerId, + viewerId, + ); + +// 목록·사이트맵 노출: 실효 public 일 때만 +export const isListedEntry = ( + access: ComlogAccess, + entry: EntryAccess, +): boolean => + isLive(access) && + entry.bannedAt === null && + effectiveVisibility(access.projectVisibility, entry.visibility) === 'public'; + +// 검색 색인 대상: 회차가 없으면 프로젝트 단독으로 판단 +export const isIndexable = ( + access: ComlogAccess, + entry?: EntryAccess, +): boolean => { + if (!entry) { + return isLive(access) && access.projectVisibility === 'public'; + } + + return isListedEntry(access, entry); +}; + +// 기술 스택 병합: 사용자가 뺀 것은 다시 넣지 않고, 기존 순서 뒤에 새 것을 붙임 +export const mergeTechStack = ( + stack: string[], + removed: string[], + added: string[], +): string[] => { + const excluded = new Set(removed.map(normalizeTag)); + const result = new Set(); + + for (const value of [...stack, ...added]) { + if (result.size >= COMLOG_MAX_TECH) { + break; + } + + const tag = normalizeTag(value); + + if (tag && !excluded.has(tag)) { + result.add(tag); + } + } + + return [...result]; +}; + +export const removeTech = ( + stack: string[], + removed: string[], + tag: string, +): { stack: string[]; removed: string[] } => { + const target = normalizeTag(tag); + + return { + stack: stack.filter((item) => normalizeTag(item) !== target), + removed: + !target || removed.includes(target) ? removed : [...removed, target], + }; +}; + +// 언어별 바이트 수 → 많은 순 상위 count 개 (태그 규칙으로 정규화) +export const topLanguages = ( + languages: Record, + count = 3, +): string[] => { + const result: string[] = []; + + for (const [name] of Object.entries(languages).sort((a, b) => b[1] - a[1])) { + const tag = normalizeTag(name); + + if (tag && !result.includes(tag)) { + result.push(tag); + } + + if (result.length >= count) { + break; + } + } + + return result; +}; + +// 비공개 저장소는 설정과 무관하게 GitHub 링크를 노출하지 않음 +export const showGithubLink = ( + project: { showGithubLink: boolean }, + repo: { isPrivate: boolean }, +): boolean => project.showGithubLink && !repo.isPrivate; + +// 데모 URL: http/https 만 허용 (javascript: 등 차단) +export const parseDemoUrl = (value: unknown): string | null => { + if (typeof value !== 'string') { + return null; + } + + const trimmed = value.trim(); + + if (!trimmed || trimmed.length > COMLOG_MAX_DEMO_URL_LENGTH) { + return null; + } + + try { + const { protocol } = new URL(trimmed); + + return protocol === 'http:' || protocol === 'https:' ? trimmed : null; + } catch { + return null; + } +}; From 3a7eff692bfcaffa0ee725b066434a8de6abe856 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 15:43:40 +0900 Subject: [PATCH 04/27] =?UTF-8?q?feat(comlog):=20comlog=20=ED=94=84?= =?UTF-8?q?=EB=A1=9C=EC=A0=9D=ED=8A=B8=20=ED=85=8C=EC=9D=B4=EB=B8=94?= =?UTF-8?q?=EA=B3=BC=20=EC=B4=88=EC=95=88=20=EC=A2=85=EB=A5=98=20=EC=BB=AC?= =?UTF-8?q?=EB=9F=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- components/studio/draft-status.ts | 1 + components/studio/publish-dialog.tsx | 5 +- drizzle/0031_perpetual_marauders.sql | 50 + drizzle/meta/0031_snapshot.json | 3085 ++++++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + lib/auto-draft/markers.ts | 4 +- lib/db/schema/auto-draft.ts | 10 +- lib/db/schema/comlog.ts | 117 + lib/db/schema/draft.ts | 29 +- lib/db/schema/index.ts | 1 + lib/db/schema/post.ts | 19 +- lib/generation/jobs.test.ts | 4 +- lib/generation/jobs.ts | 2 +- lib/posts/post-values.ts | 14 +- 14 files changed, 3331 insertions(+), 17 deletions(-) create mode 100644 drizzle/0031_perpetual_marauders.sql create mode 100644 drizzle/meta/0031_snapshot.json create mode 100644 lib/db/schema/comlog.ts diff --git a/components/studio/draft-status.ts b/components/studio/draft-status.ts index bb85d79..c58d179 100644 --- a/components/studio/draft-status.ts +++ b/components/studio/draft-status.ts @@ -5,6 +5,7 @@ import type { DraftStatus, PostVisibility } from '@/lib/db/schema'; export const VISIBILITY_LABELS: Record = { public: msg`게시 · 공개`, unlisted: msg`게시 · 일부 공개`, + private: msg`게시 · 비공개`, }; /** diff --git a/components/studio/publish-dialog.tsx b/components/studio/publish-dialog.tsx index 316fc01..a76f4f3 100644 --- a/components/studio/publish-dialog.tsx +++ b/components/studio/publish-dialog.tsx @@ -10,7 +10,7 @@ import { BRAND_BUTTON_CLASS, OUTLINE_BUTTON_CLASS, } from '@/components/studio/studio-styles'; -import type { PostVisibility } from '@/lib/db/schema'; +import type { PostVisibility, RegularPostVisibility } from '@/lib/db/schema'; import { getNicknameProblem, normalizeAuthorNickname, @@ -38,8 +38,9 @@ const FAILURE_MESSAGES: Record = { error: msg`게시하지 못했습니다. 다시 시도해주세요.`, }; +// 일반 게시 창은 비공개(private)를 보이지 않음 (comlog 회차 전용) const VISIBILITY_OPTIONS: Array<{ - value: PostVisibility; + value: RegularPostVisibility; label: MessageDescriptor; description: MessageDescriptor; }> = [ diff --git a/drizzle/0031_perpetual_marauders.sql b/drizzle/0031_perpetual_marauders.sql new file mode 100644 index 0000000..ca33518 --- /dev/null +++ b/drizzle/0031_perpetual_marauders.sql @@ -0,0 +1,50 @@ +CREATE TABLE "comdraft"."comlog_project" ( + "id" text PRIMARY KEY NOT NULL, + "user_id" text NOT NULL, + "repository_id" text NOT NULL, + "enabled" boolean DEFAULT true NOT NULL, + "name" text NOT NULL, + "slug" text NOT NULL, + "intro" text DEFAULT '' NOT NULL, + "status" text DEFAULT 'in_progress' NOT NULL, + "tech_stack" text[] DEFAULT '{}' NOT NULL, + "removed_tech" text[] DEFAULT '{}' NOT NULL, + "cover_image_id" text, + "show_github_link" boolean DEFAULT true NOT NULL, + "demo_url" text, + "visibility" text DEFAULT 'public' NOT NULL, + "author_display" text DEFAULT 'name' NOT NULL, + "author_nickname" text, + "show_author_profile" boolean DEFAULT true NOT NULL, + "author_set_at" timestamp (3) with time zone, + "banned_at" timestamp (3) with time zone, + "ban_reason" text, + "created_at" timestamp (3) with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp (3) with time zone DEFAULT now() NOT NULL, + CONSTRAINT "comlog_project_user_repository_unique" UNIQUE("user_id","repository_id"), + CONSTRAINT "comlog_project_status_check" CHECK ("comdraft"."comlog_project"."status" in ('in_progress', 'completed')), + CONSTRAINT "comlog_project_visibility_check" CHECK ("comdraft"."comlog_project"."visibility" in ('public', 'unlisted', 'private')), + CONSTRAINT "comlog_project_author_display_check" CHECK ("comdraft"."comlog_project"."author_display" in ('name', 'login', 'nickname')), + CONSTRAINT "comlog_project_author_nickname_check" CHECK (("comdraft"."comlog_project"."author_display" = 'nickname') = ("comdraft"."comlog_project"."author_nickname" is not null)) +); +--> statement-breakpoint +ALTER TABLE "comdraft"."post" DROP CONSTRAINT "post_visibility_check";--> statement-breakpoint +ALTER TABLE "comdraft"."repository_excluded_commit" DROP CONSTRAINT "repository_excluded_commit_reason_check";--> statement-breakpoint +DROP INDEX "comdraft"."draft_prompt_user_trigger_unique";--> statement-breakpoint +ALTER TABLE "comdraft"."draft" ADD COLUMN "kind" text DEFAULT 'post' NOT NULL;--> statement-breakpoint +ALTER TABLE "comdraft"."draft" ADD COLUMN "paired_draft_id" text;--> statement-breakpoint +ALTER TABLE "comdraft"."draft_prompt" ADD COLUMN "draft_kind" text DEFAULT 'post' NOT NULL;--> statement-breakpoint +ALTER TABLE "comdraft"."draft_prompt" ADD COLUMN "boundary_claimed" boolean DEFAULT false NOT NULL;--> statement-breakpoint +ALTER TABLE "comdraft"."draft_prompt" ADD COLUMN "backlog_recorded_at" timestamp (3) with time zone;--> statement-breakpoint +ALTER TABLE "comdraft"."post" ADD COLUMN "kind" text DEFAULT 'post' NOT NULL;--> statement-breakpoint +ALTER TABLE "comdraft"."comlog_project" ADD CONSTRAINT "comlog_project_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "comdraft"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "comdraft"."comlog_project" ADD CONSTRAINT "comlog_project_cover_image_id_image_id_fk" FOREIGN KEY ("cover_image_id") REFERENCES "comdraft"."image"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "comdraft"."comlog_project" ADD CONSTRAINT "comlog_project_user_repository_fk" FOREIGN KEY ("user_id","repository_id") REFERENCES "comdraft"."user_repository"("user_id","repository_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "comdraft"."draft" ADD CONSTRAINT "draft_paired_draft_id_draft_id_fk" FOREIGN KEY ("paired_draft_id") REFERENCES "comdraft"."draft"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "draft_prompt_user_trigger_kind_unique" ON "comdraft"."draft_prompt" USING btree ("user_id","trigger_sha","draft_kind") WHERE "comdraft"."draft_prompt"."trigger_sha" is not null;--> statement-breakpoint +ALTER TABLE "comdraft"."draft" ADD CONSTRAINT "draft_kind_check" CHECK ("comdraft"."draft"."kind" in ('post', 'comlog'));--> statement-breakpoint +ALTER TABLE "comdraft"."draft_prompt" ADD CONSTRAINT "draft_prompt_draft_kind_check" CHECK ("comdraft"."draft_prompt"."draft_kind" in ('post', 'comlog'));--> statement-breakpoint +ALTER TABLE "comdraft"."post" ADD CONSTRAINT "post_private_kind_check" CHECK ("comdraft"."post"."visibility" <> 'private' or "comdraft"."post"."kind" = 'comlog');--> statement-breakpoint +ALTER TABLE "comdraft"."post" ADD CONSTRAINT "post_kind_check" CHECK ("comdraft"."post"."kind" in ('post', 'comlog'));--> statement-breakpoint +ALTER TABLE "comdraft"."post" ADD CONSTRAINT "post_visibility_check" CHECK ("comdraft"."post"."visibility" in ('public', 'unlisted', 'private'));--> statement-breakpoint +ALTER TABLE "comdraft"."repository_excluded_commit" ADD CONSTRAINT "repository_excluded_commit_reason_check" CHECK ("comdraft"."repository_excluded_commit"."reason" in ('user', 'force_push', 'backlog')); \ No newline at end of file diff --git a/drizzle/meta/0031_snapshot.json b/drizzle/meta/0031_snapshot.json new file mode 100644 index 0000000..ad694d7 --- /dev/null +++ b/drizzle/meta/0031_snapshot.json @@ -0,0 +1,3085 @@ +{ + "id": "3e764c8e-e626-4e14-ae0a-b484c0ed51a3", + "prevId": "e2d3201a-9915-42d0-a3e3-31f40d384f3b", + "version": "7", + "dialect": "postgresql", + "tables": { + "comdraft.account": { + "name": "account", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "account_user_id_idx": { + "name": "account_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.rate_limit": { + "name": "rate_limit", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "count": { + "name": "count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "last_request": { + "name": "last_request", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "rate_limit_key_unique": { + "name": "rate_limit_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.session": { + "name": "session", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "session_user_id_idx": { + "name": "session_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.user": { + "name": "user", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "github_login": { + "name": "github_login", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'basic'" + }, + "onboarded_at": { + "name": "onboarded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "banned_at": { + "name": "banned_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "quota_reset_at": { + "name": "quota_reset_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_role_quota_plan_fk": { + "name": "user_role_quota_plan_fk", + "tableFrom": "user", + "tableTo": "quota_plan", + "schemaTo": "comdraft", + "columnsFrom": [ + "role" + ], + "columnsTo": [ + "role" + ], + "onDelete": "restrict", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.user_withdrawal": { + "name": "user_withdrawal", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "withdrawn_at": { + "name": "withdrawn_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "user_withdrawal_withdrawn_at_idx": { + "name": "user_withdrawal_withdrawn_at_idx", + "columns": [ + { + "expression": "withdrawn_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.verification": { + "name": "verification", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.github_installation": { + "name": "github_installation", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "account_login": { + "name": "account_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_type": { + "name": "account_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_avatar_url": { + "name": "account_avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "repository_selection": { + "name": "repository_selection", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "installed_by_user_id": { + "name": "installed_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "github_installation_installed_by_user_id_user_id_fk": { + "name": "github_installation_installed_by_user_id_user_id_fk", + "tableFrom": "github_installation", + "tableTo": "user", + "schemaTo": "comdraft", + "columnsFrom": [ + "installed_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "github_installation_installation_id_unique": { + "name": "github_installation_installation_id_unique", + "nullsNotDistinct": false, + "columns": [ + "installation_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.github_repository": { + "name": "github_repository", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_repo_id": { + "name": "github_repo_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "owner_login": { + "name": "owner_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "full_name": { + "name": "full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_private": { + "name": "is_private", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "html_url": { + "name": "html_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "license": { + "name": "license", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "github_repository_installation_id_idx": { + "name": "github_repository_installation_id_idx", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "github_repository_installation_id_github_installation_id_fk": { + "name": "github_repository_installation_id_github_installation_id_fk", + "tableFrom": "github_repository", + "tableTo": "github_installation", + "schemaTo": "comdraft", + "columnsFrom": [ + "installation_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "github_repository_github_repo_id_unique": { + "name": "github_repository_github_repo_id_unique", + "nullsNotDistinct": false, + "columns": [ + "github_repo_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.user_repository": { + "name": "user_repository", + "schema": "comdraft", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "user_repository_repository_id_idx": { + "name": "user_repository_repository_id_idx", + "columns": [ + { + "expression": "repository_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_repository_user_updated_idx": { + "name": "user_repository_user_updated_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "repository_id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_repository_user_id_user_id_fk": { + "name": "user_repository_user_id_user_id_fk", + "tableFrom": "user_repository", + "tableTo": "user", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_repository_repository_id_github_repository_id_fk": { + "name": "user_repository_repository_id_github_repository_id_fk", + "tableFrom": "user_repository", + "tableTo": "github_repository", + "schemaTo": "comdraft", + "columnsFrom": [ + "repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "user_repository_user_id_repository_id_pk": { + "name": "user_repository_user_id_repository_id_pk", + "columns": [ + "user_id", + "repository_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.draft": { + "name": "draft", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'post'" + }, + "paired_draft_id": { + "name": "paired_draft_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tags": { + "name": "tags", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "draft_user_repository_updated_idx": { + "name": "draft_user_repository_updated_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repository_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "draft_user_id_user_id_fk": { + "name": "draft_user_id_user_id_fk", + "tableFrom": "draft", + "tableTo": "user", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "draft_paired_draft_id_draft_id_fk": { + "name": "draft_paired_draft_id_draft_id_fk", + "tableFrom": "draft", + "tableTo": "draft", + "schemaTo": "comdraft", + "columnsFrom": [ + "paired_draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "draft_user_repository_fk": { + "name": "draft_user_repository_fk", + "tableFrom": "draft", + "tableTo": "user_repository", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id", + "repository_id" + ], + "columnsTo": [ + "user_id", + "repository_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "draft_kind_check": { + "name": "draft_kind_check", + "value": "\"comdraft\".\"draft\".\"kind\" in ('post', 'comlog')" + } + }, + "isRLSEnabled": false + }, + "comdraft.draft_prompt": { + "name": "draft_prompt", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'studio'" + }, + "trigger_sha": { + "name": "trigger_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "draft_kind": { + "name": "draft_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'post'" + }, + "boundary_claimed": { + "name": "boundary_claimed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "backlog_recorded_at": { + "name": "backlog_recorded_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tone": { + "name": "tone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "post_type": { + "name": "post_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "length": { + "name": "length", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "required_blocks": { + "name": "required_blocks", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "commit_shas": { + "name": "commit_shas", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "code_inputs": { + "name": "code_inputs", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "locale": { + "name": "locale", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'ko'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "step": { + "name": "step", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "channel": { + "name": "channel", + "type": "uuid", + "primaryKey": false, + "notNull": true, + "default": "gen_random_uuid()" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tags": { + "name": "tags", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "estimated_tokens": { + "name": "estimated_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "used_tokens": { + "name": "used_tokens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'haiku'" + }, + "estimated_cost": { + "name": "estimated_cost", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "used_cost": { + "name": "used_cost", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reference_urls": { + "name": "reference_urls", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "blank_id": { + "name": "blank_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blank_question": { + "name": "blank_question", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blank_answer": { + "name": "blank_answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blank_context": { + "name": "blank_context", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "analysis": { + "name": "analysis", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "clarification": { + "name": "clarification", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "applied_at": { + "name": "applied_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "draft_prompt_draft_created_idx": { + "name": "draft_prompt_draft_created_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "draft_prompt_user_created_idx": { + "name": "draft_prompt_user_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "draft_prompt_draft_active_unique": { + "name": "draft_prompt_draft_active_unique", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"comdraft\".\"draft_prompt\".\"status\" in ('queued', 'running', 'awaiting_input')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "draft_prompt_user_trigger_kind_unique": { + "name": "draft_prompt_user_trigger_kind_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger_sha", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "draft_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"comdraft\".\"draft_prompt\".\"trigger_sha\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "draft_prompt_user_repository_trigger_idx": { + "name": "draft_prompt_user_repository_trigger_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repository_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"comdraft\".\"draft_prompt\".\"source\" = 'commit_trigger'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "draft_prompt_user_id_user_id_fk": { + "name": "draft_prompt_user_id_user_id_fk", + "tableFrom": "draft_prompt", + "tableTo": "user", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "draft_prompt_draft_id_draft_id_fk": { + "name": "draft_prompt_draft_id_draft_id_fk", + "tableFrom": "draft_prompt", + "tableTo": "draft", + "schemaTo": "comdraft", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "draft_prompt_channel_unique": { + "name": "draft_prompt_channel_unique", + "nullsNotDistinct": false, + "columns": [ + "channel" + ] + } + }, + "policies": {}, + "checkConstraints": { + "draft_prompt_status_check": { + "name": "draft_prompt_status_check", + "value": "\"comdraft\".\"draft_prompt\".\"status\" in ('queued', 'running', 'awaiting_input', 'completed', 'failed')" + }, + "draft_prompt_step_check": { + "name": "draft_prompt_step_check", + "value": "\"comdraft\".\"draft_prompt\".\"step\" between 0 and 3" + }, + "draft_prompt_kind_check": { + "name": "draft_prompt_kind_check", + "value": "\"comdraft\".\"draft_prompt\".\"kind\" in ('draft', 'fill')" + }, + "draft_prompt_draft_kind_check": { + "name": "draft_prompt_draft_kind_check", + "value": "\"comdraft\".\"draft_prompt\".\"draft_kind\" in ('post', 'comlog')" + }, + "draft_prompt_locale_check": { + "name": "draft_prompt_locale_check", + "value": "\"comdraft\".\"draft_prompt\".\"locale\" in ('ko', 'en')" + }, + "draft_prompt_source_check": { + "name": "draft_prompt_source_check", + "value": "\"comdraft\".\"draft_prompt\".\"source\" in ('studio', 'commit_trigger')" + }, + "draft_prompt_model_check": { + "name": "draft_prompt_model_check", + "value": "\"comdraft\".\"draft_prompt\".\"model\" in ('haiku', 'sonnet', 'opus')" + } + }, + "isRLSEnabled": false + }, + "comdraft.draft_reference_link": { + "name": "draft_reference_link", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "draft_reference_link_draft_id_draft_id_fk": { + "name": "draft_reference_link_draft_id_draft_id_fk", + "tableFrom": "draft_reference_link", + "tableTo": "draft", + "schemaTo": "comdraft", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "draft_reference_link_draft_url_unique": { + "name": "draft_reference_link_draft_url_unique", + "nullsNotDistinct": false, + "columns": [ + "draft_id", + "url" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.post": { + "name": "post", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "excerpt": { + "name": "excerpt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'post'" + }, + "locale": { + "name": "locale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tags": { + "name": "tags", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "published_at": { + "name": "published_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "banned_at": { + "name": "banned_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "author_display": { + "name": "author_display", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'name'" + }, + "author_nickname": { + "name": "author_nickname", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "show_author_profile": { + "name": "show_author_profile", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + } + }, + "indexes": { + "post_public_published_idx": { + "name": "post_public_published_idx", + "columns": [ + { + "expression": "published_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"comdraft\".\"post\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "post_tags_idx": { + "name": "post_tags_idx", + "columns": [ + { + "expression": "tags", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": { + "post_draft_id_draft_id_fk": { + "name": "post_draft_id_draft_id_fk", + "tableFrom": "post", + "tableTo": "draft", + "schemaTo": "comdraft", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "post_user_id_user_id_fk": { + "name": "post_user_id_user_id_fk", + "tableFrom": "post", + "tableTo": "user", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "post_draft_id_unique": { + "name": "post_draft_id_unique", + "nullsNotDistinct": false, + "columns": [ + "draft_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "post_visibility_check": { + "name": "post_visibility_check", + "value": "\"comdraft\".\"post\".\"visibility\" in ('public', 'unlisted', 'private')" + }, + "post_private_kind_check": { + "name": "post_private_kind_check", + "value": "\"comdraft\".\"post\".\"visibility\" <> 'private' or \"comdraft\".\"post\".\"kind\" = 'comlog'" + }, + "post_kind_check": { + "name": "post_kind_check", + "value": "\"comdraft\".\"post\".\"kind\" in ('post', 'comlog')" + }, + "post_locale_check": { + "name": "post_locale_check", + "value": "\"comdraft\".\"post\".\"locale\" in ('ko', 'en')" + }, + "post_author_display_check": { + "name": "post_author_display_check", + "value": "\"comdraft\".\"post\".\"author_display\" in ('name', 'login', 'nickname')" + }, + "post_author_nickname_check": { + "name": "post_author_nickname_check", + "value": "(\"comdraft\".\"post\".\"author_display\" = 'nickname') = (\"comdraft\".\"post\".\"author_nickname\" is not null)" + } + }, + "isRLSEnabled": false + }, + "comdraft.post_view": { + "name": "post_view", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "post_id": { + "name": "post_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "viewer_key": { + "name": "viewer_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "viewed_at": { + "name": "viewed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "post_view_post_viewer_idx": { + "name": "post_view_post_viewer_idx", + "columns": [ + { + "expression": "post_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "viewer_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "viewed_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "post_view_post_viewed_idx": { + "name": "post_view_post_viewed_idx", + "columns": [ + { + "expression": "post_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "viewed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "post_view_post_id_post_id_fk": { + "name": "post_view_post_id_post_id_fk", + "tableFrom": "post_view", + "tableTo": "post", + "schemaTo": "comdraft", + "columnsFrom": [ + "post_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.quota_plan": { + "name": "quota_plan", + "schema": "comdraft", + "columns": { + "role": { + "name": "role", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "weekly_token_limit": { + "name": "weekly_token_limit", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "weekly_cost_limit": { + "name": "weekly_cost_limit", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "overrun_ratio": { + "name": "overrun_ratio", + "type": "numeric(4, 2)", + "primaryKey": false, + "notNull": true + }, + "reset_timezone": { + "name": "reset_timezone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reset_weekday": { + "name": "reset_weekday", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "reset_hour": { + "name": "reset_hour", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "quota_plan_limit_check": { + "name": "quota_plan_limit_check", + "value": "\"comdraft\".\"quota_plan\".\"weekly_token_limit\" > 0" + }, + "quota_plan_cost_limit_check": { + "name": "quota_plan_cost_limit_check", + "value": "\"comdraft\".\"quota_plan\".\"weekly_cost_limit\" > 0" + }, + "quota_plan_ratio_check": { + "name": "quota_plan_ratio_check", + "value": "\"comdraft\".\"quota_plan\".\"overrun_ratio\" >= 1" + }, + "quota_plan_weekday_check": { + "name": "quota_plan_weekday_check", + "value": "\"comdraft\".\"quota_plan\".\"reset_weekday\" between 0 and 6" + }, + "quota_plan_hour_check": { + "name": "quota_plan_hour_check", + "value": "\"comdraft\".\"quota_plan\".\"reset_hour\" between 0 and 23" + } + }, + "isRLSEnabled": false + }, + "comdraft.image": { + "name": "image", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "bytes": { + "name": "bytes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "image_draft_idx": { + "name": "image_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "image_user_created_idx": { + "name": "image_user_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "image_user_id_user_id_fk": { + "name": "image_user_id_user_id_fk", + "tableFrom": "image", + "tableTo": "user", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "image_draft_id_draft_id_fk": { + "name": "image_draft_id_draft_id_fk", + "tableFrom": "image", + "tableTo": "draft", + "schemaTo": "comdraft", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "image_path_unique": { + "name": "image_path_unique", + "nullsNotDistinct": false, + "columns": [ + "path" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.admin_account": { + "name": "admin_account", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "login_id": { + "name": "login_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "temp_password_hash": { + "name": "temp_password_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'guest'" + }, + "failed_attempts": { + "name": "failed_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "locked_until": { + "name": "locked_until", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "password_changed_at": { + "name": "password_changed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "admin_account_login_id_unique": { + "name": "admin_account_login_id_unique", + "nullsNotDistinct": false, + "columns": [ + "login_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "admin_account_role_check": { + "name": "admin_account_role_check", + "value": "\"comdraft\".\"admin_account\".\"role\" in ('guest', 'viewer', 'editor', 'admin')" + } + }, + "isRLSEnabled": false + }, + "comdraft.admin_action_log": { + "name": "admin_action_log", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "admin_id": { + "name": "admin_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "detail": { + "name": "detail", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "admin_action_log_created_at_idx": { + "name": "admin_action_log_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "admin_action_log_target_idx": { + "name": "admin_action_log_target_idx", + "columns": [ + { + "expression": "target_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "admin_action_log_admin_id_admin_account_id_fk": { + "name": "admin_action_log_admin_id_admin_account_id_fk", + "tableFrom": "admin_action_log", + "tableTo": "admin_account", + "schemaTo": "comdraft", + "columnsFrom": [ + "admin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.admin_session": { + "name": "admin_session", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "admin_id": { + "name": "admin_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "admin_session_admin_id_admin_account_id_fk": { + "name": "admin_session_admin_id_admin_account_id_fk", + "tableFrom": "admin_session", + "tableTo": "admin_account", + "schemaTo": "comdraft", + "columnsFrom": [ + "admin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "admin_session_token_hash_unique": { + "name": "admin_session_token_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "token_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.ai_prompt": { + "name": "ai_prompt", + "schema": "comdraft", + "columns": { + "locale": { + "name": "locale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "ai_prompt_updated_by_admin_account_id_fk": { + "name": "ai_prompt_updated_by_admin_account_id_fk", + "tableFrom": "ai_prompt", + "tableTo": "admin_account", + "schemaTo": "comdraft", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ai_prompt_locale_key_pk": { + "name": "ai_prompt_locale_key_pk", + "columns": [ + "locale", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.ai_prompt_default": { + "name": "ai_prompt_default", + "schema": "comdraft", + "columns": { + "locale": { + "name": "locale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "required_markers": { + "name": "required_markers", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "ai_prompt_default_locale_key_pk": { + "name": "ai_prompt_default_locale_key_pk", + "columns": [ + "locale", + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.ai_prompt_revision": { + "name": "ai_prompt_revision", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "locale": { + "name": "locale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "admin_id": { + "name": "admin_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "ai_prompt_revision_key_idx": { + "name": "ai_prompt_revision_key_idx", + "columns": [ + { + "expression": "locale", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ai_prompt_revision_admin_id_admin_account_id_fk": { + "name": "ai_prompt_revision_admin_id_admin_account_id_fk", + "tableFrom": "ai_prompt_revision", + "tableTo": "admin_account", + "schemaTo": "comdraft", + "columnsFrom": [ + "admin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.service_setting": { + "name": "service_setting", + "schema": "comdraft", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "service_setting_updated_by_admin_account_id_fk": { + "name": "service_setting_updated_by_admin_account_id_fk", + "tableFrom": "service_setting", + "tableTo": "admin_account", + "schemaTo": "comdraft", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.repository_auto_draft": { + "name": "repository_auto_draft", + "schema": "comdraft", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "tone": { + "name": "tone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'plain'" + }, + "post_type": { + "name": "post_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'experience'" + }, + "length": { + "name": "length", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'short'" + }, + "required_blocks": { + "name": "required_blocks", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{\"h2\",\"list\",\"code\"}'" + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'haiku'" + }, + "boundary_sha": { + "name": "boundary_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "repository_auto_draft_user_repository_fk": { + "name": "repository_auto_draft_user_repository_fk", + "tableFrom": "repository_auto_draft", + "tableTo": "user_repository", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id", + "repository_id" + ], + "columnsTo": [ + "user_id", + "repository_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "repository_auto_draft_user_id_repository_id_pk": { + "name": "repository_auto_draft_user_id_repository_id_pk", + "columns": [ + "user_id", + "repository_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "comdraft.repository_excluded_commit": { + "name": "repository_excluded_commit", + "schema": "comdraft", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "repository_excluded_commit_user_repository_fk": { + "name": "repository_excluded_commit_user_repository_fk", + "tableFrom": "repository_excluded_commit", + "tableTo": "user_repository", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id", + "repository_id" + ], + "columnsTo": [ + "user_id", + "repository_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "repository_excluded_commit_user_id_repository_id_sha_pk": { + "name": "repository_excluded_commit_user_id_repository_id_sha_pk", + "columns": [ + "user_id", + "repository_id", + "sha" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "repository_excluded_commit_reason_check": { + "name": "repository_excluded_commit_reason_check", + "value": "\"comdraft\".\"repository_excluded_commit\".\"reason\" in ('user', 'force_push', 'backlog')" + } + }, + "isRLSEnabled": false + }, + "comdraft.comlog_project": { + "name": "comlog_project", + "schema": "comdraft", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "intro": { + "name": "intro", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'in_progress'" + }, + "tech_stack": { + "name": "tech_stack", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "removed_tech": { + "name": "removed_tech", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "cover_image_id": { + "name": "cover_image_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "show_github_link": { + "name": "show_github_link", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "demo_url": { + "name": "demo_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "author_display": { + "name": "author_display", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'name'" + }, + "author_nickname": { + "name": "author_nickname", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "show_author_profile": { + "name": "show_author_profile", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "author_set_at": { + "name": "author_set_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "banned_at": { + "name": "banned_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "comlog_project_user_id_user_id_fk": { + "name": "comlog_project_user_id_user_id_fk", + "tableFrom": "comlog_project", + "tableTo": "user", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "comlog_project_cover_image_id_image_id_fk": { + "name": "comlog_project_cover_image_id_image_id_fk", + "tableFrom": "comlog_project", + "tableTo": "image", + "schemaTo": "comdraft", + "columnsFrom": [ + "cover_image_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "comlog_project_user_repository_fk": { + "name": "comlog_project_user_repository_fk", + "tableFrom": "comlog_project", + "tableTo": "user_repository", + "schemaTo": "comdraft", + "columnsFrom": [ + "user_id", + "repository_id" + ], + "columnsTo": [ + "user_id", + "repository_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "comlog_project_user_repository_unique": { + "name": "comlog_project_user_repository_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id", + "repository_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "comlog_project_status_check": { + "name": "comlog_project_status_check", + "value": "\"comdraft\".\"comlog_project\".\"status\" in ('in_progress', 'completed')" + }, + "comlog_project_visibility_check": { + "name": "comlog_project_visibility_check", + "value": "\"comdraft\".\"comlog_project\".\"visibility\" in ('public', 'unlisted', 'private')" + }, + "comlog_project_author_display_check": { + "name": "comlog_project_author_display_check", + "value": "\"comdraft\".\"comlog_project\".\"author_display\" in ('name', 'login', 'nickname')" + }, + "comlog_project_author_nickname_check": { + "name": "comlog_project_author_nickname_check", + "value": "(\"comdraft\".\"comlog_project\".\"author_display\" = 'nickname') = (\"comdraft\".\"comlog_project\".\"author_nickname\" is not null)" + } + }, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 491001b..9e7756a 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -218,6 +218,13 @@ "when": 1796013074174, "tag": "0030_nasty_lethal_legion", "breakpoints": true + }, + { + "idx": 31, + "version": "7", + "when": 1796107354409, + "tag": "0031_perpetual_marauders", + "breakpoints": true } ] } \ No newline at end of file diff --git a/lib/auto-draft/markers.ts b/lib/auto-draft/markers.ts index cd7d6b2..a084fd9 100644 --- a/lib/auto-draft/markers.ts +++ b/lib/auto-draft/markers.ts @@ -1,10 +1,12 @@ +import type { ExcludedCommitReason } from '@/lib/db/schema/auto-draft'; import { isMergeCommit, type SkipReason } from '@/lib/auto-draft/batch'; /** * 스튜디오 커밋 줄에 붙이는 자동 초안 표시 계산 (순수 함수) */ -export type ExcludedReason = 'user' | 'force_push'; +// 밀린 커밋(backlog) 표시는 이후 작업에서 다룸, 지금은 스키마 값과 같게만 맞춤 +export type ExcludedReason = ExcludedCommitReason; export type CommitMarker = | { kind: 'anchor' } diff --git a/lib/db/schema/auto-draft.ts b/lib/db/schema/auto-draft.ts index 0fb1b7c..01ec19f 100644 --- a/lib/db/schema/auto-draft.ts +++ b/lib/db/schema/auto-draft.ts @@ -21,8 +21,12 @@ import { userRepository } from '@/lib/db/schema/github'; * - repository_excluded_commit: 자동 초안 대상에서 제외한 커밋 SHA (SHA 만 저장, 메시지는 저장하지 않음) */ -// 제외 사유 (user: 사용자가 직접 제외, force_push: 강제 푸시로 사라진 커밋) -export const EXCLUDED_COMMIT_REASONS = ['user', 'force_push'] as const; +// 제외 사유 (user: 사용자가 직접 제외, force_push: 강제 푸시로 사라진 커밋, backlog: comlog 회차를 못 만들어 밀린 커밋) +export const EXCLUDED_COMMIT_REASONS = [ + 'user', + 'force_push', + 'backlog', +] as const; export type ExcludedCommitReason = (typeof EXCLUDED_COMMIT_REASONS)[number]; export const repositoryAutoDraft = comdraftSchema.table( @@ -82,7 +86,7 @@ export const repositoryExcludedCommit = comdraftSchema.table( }).onDelete('cascade'), check( 'repository_excluded_commit_reason_check', - sql`${table.reason} in ('user', 'force_push')`, + sql`${table.reason} in ('user', 'force_push', 'backlog')`, ), ], ); diff --git a/lib/db/schema/comlog.ts b/lib/db/schema/comlog.ts new file mode 100644 index 0000000..899156f --- /dev/null +++ b/lib/db/schema/comlog.ts @@ -0,0 +1,117 @@ +import { sql } from 'drizzle-orm'; +import { + boolean, + check, + foreignKey, + text, + timestamp, + unique, +} from 'drizzle-orm/pg-core'; +import { comdraftSchema } from '@/lib/db/pg-schema'; +import { user } from '@/lib/db/schema/auth'; +import { userRepository } from '@/lib/db/schema/github'; +import { image } from '@/lib/db/schema/image'; +import type { ComlogVisibility } from '@/lib/comlog/rules'; +import type { AuthorDisplayMode } from '@/lib/posts/author-display'; + +/** + * comlog 프로젝트 테이블 + * + * - comlog_project: 사용자 + 저장소별 프로젝트 한 행 (프로젝트 페이지와 회차 묶음의 기준) + * → 저장소 연동을 해제하면 함께 삭제됨, 끄면 enabled 만 내리고 행과 회차는 남김 + * → 프로젝트 소개·기술 스택·공개 범위·작성자 표시는 소개 편집 화면에서 바꿈 + */ + +// 프로젝트 진행 상태 (in_progress: 진행 중, completed: 완료) +export const COMLOG_PROJECT_STATUSES = ['in_progress', 'completed'] as const; +export type ComlogProjectStatus = (typeof COMLOG_PROJECT_STATUSES)[number]; + +export const comlogProject = comdraftSchema.table( + 'comlog_project', + { + id: text('id').primaryKey(), + userId: text('user_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + repositoryId: text('repository_id').notNull(), + // comlog 사용 여부 (끄면 공개 화면에서 숨김) + enabled: boolean('enabled').default(true).notNull(), + // 프로젝트 이름 (처음엔 저장소 이름) + name: text('name').notNull(), + // 주소용 slug (이름에서 만듦) + slug: text('slug').notNull(), + // 소개 본문 (처음엔 저장소 설명, 비어 있을 수 있음) + intro: text('intro').default('').notNull(), + status: text('status') + .$type() + .default('in_progress') + .notNull(), + // 기술 스택 (게시글 태그 정규화 규칙, 최대 20개) + techStack: text('tech_stack').array().default([]).notNull(), + // 사용자가 지운 기술 (자동 추가에서 제외) + removedTech: text('removed_tech').array().default([]).notNull(), + // 대표 이미지 (null 이면 이름으로 만든 자동 이미지, 이미지가 지워지면 null) + coverImageId: text('cover_image_id').references(() => image.id, { + onDelete: 'set null', + }), + // GitHub 링크 표시 (공개 저장소만 켤 수 있음) + showGithubLink: boolean('show_github_link').default(true).notNull(), + // 데모 링크 (http/https 만) + demoUrl: text('demo_url'), + visibility: text('visibility') + .$type() + .default('public') + .notNull(), + // 프로젝트 페이지·카드의 작성자 표시 (게시글과 같은 타입·기본값) + authorDisplay: text('author_display') + .$type() + .default('name') + .notNull(), + authorNickname: text('author_nickname'), + showAuthorProfile: boolean('show_author_profile').default(true).notNull(), + // 첫 회차를 게시할 때 작성자 표시를 채운 시각 (null 이면 아직 채우지 않음) + authorSetAt: timestamp('author_set_at', { + withTimezone: true, + precision: 3, + }), + // 관리자가 프로젝트를 통째로 숨긴 시각과 사유 (null 이면 정상) + bannedAt: timestamp('banned_at', { withTimezone: true, precision: 3 }), + banReason: text('ban_reason'), + createdAt: timestamp('created_at', { withTimezone: true, precision: 3 }) + .defaultNow() + .notNull(), + updatedAt: timestamp('updated_at', { withTimezone: true, precision: 3 }) + .defaultNow() + .$onUpdate(() => new Date()) + .notNull(), + }, + (table) => [ + unique('comlog_project_user_repository_unique').on( + table.userId, + table.repositoryId, + ), + foreignKey({ + name: 'comlog_project_user_repository_fk', + columns: [table.userId, table.repositoryId], + foreignColumns: [userRepository.userId, userRepository.repositoryId], + }).onDelete('cascade'), + check( + 'comlog_project_status_check', + sql`${table.status} in ('in_progress', 'completed')`, + ), + check( + 'comlog_project_visibility_check', + sql`${table.visibility} in ('public', 'unlisted', 'private')`, + ), + check( + 'comlog_project_author_display_check', + sql`${table.authorDisplay} in ('name', 'login', 'nickname')`, + ), + check( + 'comlog_project_author_nickname_check', + sql`(${table.authorDisplay} = 'nickname') = (${table.authorNickname} is not null)`, + ), + ], +); + +export type ComlogProjectRow = typeof comlogProject.$inferSelect; diff --git a/lib/db/schema/draft.ts b/lib/db/schema/draft.ts index 183f597..ce32349 100644 --- a/lib/db/schema/draft.ts +++ b/lib/db/schema/draft.ts @@ -1,6 +1,8 @@ import { relations, sql } from 'drizzle-orm'; import { + type AnyPgColumn, bigint, + boolean, check, foreignKey, index, @@ -21,6 +23,7 @@ import type { } from '@/lib/generation/contract'; import { comdraftSchema } from '@/lib/db/pg-schema'; import type { Locale } from '@/lib/i18n/config'; +import type { DraftKind } from '@/lib/studio/options'; import { user } from '@/lib/db/schema/auth'; import { githubRepository, userRepository } from '@/lib/db/schema/github'; @@ -76,6 +79,13 @@ export const draft = comdraftSchema.table( // Tiptap 문서(JSON). 아직 작성 요청을 보내지 않은 초안은 null content: jsonb('content'), status: text('status').$type().default('draft').notNull(), + // 초안 종류 (post: 일반 글, comlog: 프로젝트 회차) + kind: text('kind').$type().default('post').notNull(), + // 'post log' 로 함께 만든 짝 초안 (상세 페이지 링크용, 짝이 지워지면 null) + pairedDraftId: text('paired_draft_id').references( + (): AnyPgColumn => draft.id, + { onDelete: 'set null' }, + ), // 기술 태그 (lib/posts/tags.ts 규칙으로 정규화, AI 결과 반영이나 편집기 입력으로 바뀜, 게시할 때 게시글로 복사) tags: text('tags').array().default([]).notNull(), createdAt: timestamp('created_at', { withTimezone: true, precision: 3 }) @@ -98,6 +108,7 @@ export const draft = comdraftSchema.table( table.repositoryId, table.updatedAt.desc(), ), + check('draft_kind_check', sql`${table.kind} in ('post', 'comlog')`), ], ); @@ -124,6 +135,15 @@ export const draftPrompt = comdraftSchema.table( .notNull(), // 커밋 트리거 요청을 일으킨 커밋 SHA (같은 커밋의 중복 요청 방지, studio 요청은 null) triggerSha: text('trigger_sha'), + // 만들려는 초안 종류 (초안 없이 남는 실패 행도 종류를 가져야 같은 트리거의 종류별 중복을 막을 수 있음) + draftKind: text('draft_kind').$type().default('post').notNull(), + // 이 작업이 자동 묶음의 경계를 선점했는지 (되돌릴 때 쓰는 표시) + boundaryClaimed: boolean('boundary_claimed').default(false).notNull(), + // 실패한 회차 작업의 커밋을 밀린 커밋으로 남긴 시각 (한 번만 기록) + backlogRecordedAt: timestamp('backlog_recorded_at', { + withTimezone: true, + precision: 3, + }), prompt: text('prompt').notNull(), // 기본 옵션 값 (lib/studio/options.ts 의 키) tone: text('tone').notNull(), @@ -207,10 +227,15 @@ export const draftPrompt = comdraftSchema.table( sql`${table.step} between 0 and ${sql.raw(String(DRAFT_PROMPT_LAST_STEP))}`, ), check('draft_prompt_kind_check', sql`${table.kind} in ('draft', 'fill')`), + check( + 'draft_prompt_draft_kind_check', + sql`${table.draftKind} in ('post', 'comlog')`, + ), check('draft_prompt_locale_check', sql`${table.locale} in ('ko', 'en')`), // 같은 사용자의 같은 트리거 커밋은 한 번만 요청 (웹훅 재전송 중복 방지) - uniqueIndex('draft_prompt_user_trigger_unique') - .on(table.userId, table.triggerSha) + // 한 트리거로 블로그·회차 작업 두 개는 허용하고 같은 종류 중복만 막음 + uniqueIndex('draft_prompt_user_trigger_kind_unique') + .on(table.userId, table.triggerSha, table.draftKind) .where(sql`${table.triggerSha} is not null`), // 자동 초안에 이미 쓴 커밋 조회 (사용자·저장소의 자동 초안 행만) index('draft_prompt_user_repository_trigger_idx') diff --git a/lib/db/schema/index.ts b/lib/db/schema/index.ts index 553b262..a1a07da 100644 --- a/lib/db/schema/index.ts +++ b/lib/db/schema/index.ts @@ -6,3 +6,4 @@ export * from '@/lib/db/schema/quota'; export * from '@/lib/db/schema/image'; export * from '@/lib/db/schema/admin'; export * from '@/lib/db/schema/auto-draft'; +export * from '@/lib/db/schema/comlog'; diff --git a/lib/db/schema/post.ts b/lib/db/schema/post.ts index 6f02070..2a19982 100644 --- a/lib/db/schema/post.ts +++ b/lib/db/schema/post.ts @@ -9,6 +9,7 @@ import { } from 'drizzle-orm/pg-core'; import { comdraftSchema } from '@/lib/db/pg-schema'; import type { Locale } from '@/lib/i18n/config'; +import type { DraftKind } from '@/lib/studio/options'; import type { AuthorDisplayMode } from '@/lib/posts/author-display'; import { user } from '@/lib/db/schema/auth'; import { draft } from '@/lib/db/schema/draft'; @@ -22,10 +23,14 @@ import { draft } from '@/lib/db/schema/draft'; * → 문제 있는 글은 검수가 임시 조치(banned_at)해 공개 화면에서 내용을 숨김 */ -// 게시글 공개 범위 ('공개' | '일부 공개') -export const POST_VISIBILITIES = ['public', 'unlisted'] as const; +// 게시글 공개 범위 ('공개' | '일부 공개' | '비공개', 비공개는 comlog 종류에만 허용) +export const POST_VISIBILITIES = ['public', 'unlisted', 'private'] as const; export type PostVisibility = (typeof POST_VISIBILITIES)[number]; +// 일반 게시글 게시 창과 서버 검증이 받는 공개 범위 (private 제외) +export const REGULAR_POST_VISIBILITIES = ['public', 'unlisted'] as const; +export type RegularPostVisibility = (typeof REGULAR_POST_VISIBILITIES)[number]; + export const post = comdraftSchema.table( 'post', { @@ -46,6 +51,8 @@ export const post = comdraftSchema.table( // 정리를 거친 본문 스냅샷 (Tiptap 문서) content: jsonb('content').notNull(), visibility: text('visibility').$type().notNull(), + // 글 종류 (게시할 때 초안의 종류를 복사) + kind: text('kind').$type().default('post').notNull(), // 게시할 때의 화면 언어 (대표 주소 언어, lib/i18n/config.ts 의 LOCALES) locale: text('locale').$type().notNull(), // 기술 태그 (게시할 때 초안 태그를 복사, 나중 목록 필터와 SEO 용으로 지금은 수집만) @@ -82,8 +89,14 @@ export const post = comdraftSchema.table( index('post_tags_idx').using('gin', table.tags), check( 'post_visibility_check', - sql`${table.visibility} in ('public', 'unlisted')`, + sql`${table.visibility} in ('public', 'unlisted', 'private')`, + ), + // 비공개는 comlog 회차에만 허용 + check( + 'post_private_kind_check', + sql`${table.visibility} <> 'private' or ${table.kind} = 'comlog'`, ), + check('post_kind_check', sql`${table.kind} in ('post', 'comlog')`), check('post_locale_check', sql`${table.locale} in ('ko', 'en')`), check( 'post_author_display_check', diff --git a/lib/generation/jobs.test.ts b/lib/generation/jobs.test.ts index 5f5b705..80d09fd 100644 --- a/lib/generation/jobs.test.ts +++ b/lib/generation/jobs.test.ts @@ -178,12 +178,12 @@ describe('isTriggerDuplicateConflict', () => { it('트리거 SHA 유일 인덱스 충돌만 true (cause 도 확인)', () => { expect( jobs.isTriggerDuplicateConflict( - violation('draft_prompt_user_trigger_unique'), + violation('draft_prompt_user_trigger_kind_unique'), ), ).toBe(true); expect( jobs.isTriggerDuplicateConflict({ - cause: violation('draft_prompt_user_trigger_unique'), + cause: violation('draft_prompt_user_trigger_kind_unique'), }), ).toBe(true); expect( diff --git a/lib/generation/jobs.ts b/lib/generation/jobs.ts index 0b797dd..d61138d 100644 --- a/lib/generation/jobs.ts +++ b/lib/generation/jobs.ts @@ -726,7 +726,7 @@ export const isActiveJobConflict = (error: unknown) => // 같은 커밋(SHA)으로 이미 자동 초안을 만든 경우 (사용자별 트리거 SHA 유일 인덱스) export const isTriggerDuplicateConflict = (error: unknown) => - isUniqueViolation(error, 'draft_prompt_user_trigger_unique'); + isUniqueViolation(error, 'draft_prompt_user_trigger_kind_unique'); /* ---------- 작성기(Runner)가 쓰는 상태 전이 ---------- */ diff --git a/lib/posts/post-values.ts b/lib/posts/post-values.ts index c26e84d..ae6f735 100644 --- a/lib/posts/post-values.ts +++ b/lib/posts/post-values.ts @@ -1,5 +1,9 @@ import type { JSONContent } from '@tiptap/core'; -import { POST_VISIBILITIES, type PostVisibility } from '@/lib/db/schema/post'; +import { + REGULAR_POST_VISIBILITIES, + type PostVisibility, + type RegularPostVisibility, +} from '@/lib/db/schema/post'; import type { Locale } from '@/lib/i18n/config'; import { extractPostExcerpt, @@ -13,8 +17,12 @@ import { createPostSlug } from '@/lib/posts/post-path'; */ // 클라이언트가 보낸 공개 범위를 확인 (허용 값이 아니면 null) -export const parsePostVisibility = (value: unknown): PostVisibility | null => { - return POST_VISIBILITIES.find((visibility) => visibility === value) ?? null; +export const parsePostVisibility = ( + value: unknown, +): RegularPostVisibility | null => { + return ( + REGULAR_POST_VISIBILITIES.find((visibility) => visibility === value) ?? null + ); }; /** From 88c085c83994fce3e529c7c439a51f1506209e77 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 15:45:41 +0900 Subject: [PATCH 05/27] =?UTF-8?q?feat(comlog):=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=EC=A0=9D=ED=8A=B8=20=EC=A0=80=EC=9E=A5=20=EA=B3=84=EC=B8=B5?= =?UTF-8?q?=EA=B3=BC=20GitHub=20=EC=A0=80=EC=9E=A5=EC=86=8C=20=EC=A0=95?= =?UTF-8?q?=EB=B3=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/comlog/github.ts | 31 ++++ lib/comlog/initial-project.test.ts | 52 +++++++ lib/comlog/initial-project.ts | 30 ++++ lib/comlog/patch.test.ts | 87 +++++++++++ lib/comlog/patch.ts | 190 ++++++++++++++++++++++ lib/comlog/store.ts | 242 +++++++++++++++++++++++++++++ 6 files changed, 632 insertions(+) create mode 100644 lib/comlog/github.ts create mode 100644 lib/comlog/initial-project.test.ts create mode 100644 lib/comlog/initial-project.ts create mode 100644 lib/comlog/patch.test.ts create mode 100644 lib/comlog/patch.ts create mode 100644 lib/comlog/store.ts diff --git a/lib/comlog/github.ts b/lib/comlog/github.ts new file mode 100644 index 0000000..d5e08b1 --- /dev/null +++ b/lib/comlog/github.ts @@ -0,0 +1,31 @@ +import 'server-only'; +import type { AutoDraftRepo } from '@/lib/auto-draft/github'; +import type { RepoSnapshot } from '@/lib/comlog/initial-project'; +import { getInstallationOctokit } from '@/lib/github/app'; + +/** + * comlog 용 GitHub 저장소 조회 (설치 토큰 사용) + * - 프로젝트 초기값과 공개 여부 갱신에만 쓰고 코드 내용은 읽지 않음 + */ + +export { buildInitialProject } from '@/lib/comlog/initial-project'; +export type { RepoSnapshot } from '@/lib/comlog/initial-project'; + +export async function fetchRepoSnapshot( + repo: AutoDraftRepo, +): Promise { + const octokit = await getInstallationOctokit(repo.installationId); + const params = { owner: repo.owner, repo: repo.name }; + const [info, languages] = await Promise.all([ + octokit.request('GET /repos/{owner}/{repo}', params), + octokit.request('GET /repos/{owner}/{repo}/languages', params), + ]); + + return { + name: info.data.name, + description: info.data.description, + homepage: info.data.homepage ?? null, + isPrivate: info.data.private, + languages: languages.data, + }; +} diff --git a/lib/comlog/initial-project.test.ts b/lib/comlog/initial-project.test.ts new file mode 100644 index 0000000..33bff35 --- /dev/null +++ b/lib/comlog/initial-project.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { + buildInitialProject, + type RepoSnapshot, +} from '@/lib/comlog/initial-project'; + +const snapshot = (overrides: Partial = {}): RepoSnapshot => ({ + name: 'My-Repo', + description: null, + homepage: null, + isPrivate: false, + languages: {}, + ...overrides, +}); + +describe('buildInitialProject', () => { + it('설명이 없으면 소개는 빈 문자열', () => { + expect(buildInitialProject(snapshot()).intro).toBe(''); + }); + + it('설명이 있으면 소개로 씀', () => { + expect( + buildInitialProject(snapshot({ description: '작은 도구' })).intro, + ).toBe('작은 도구'); + }); + + it('http/https 가 아닌 홈페이지는 데모 링크로 쓰지 않음', () => { + expect( + buildInitialProject(snapshot({ homepage: 'ftp://x' })).demoUrl, + ).toBeNull(); + expect( + buildInitialProject(snapshot({ homepage: 'https://x.dev' })).demoUrl, + ).toBe('https://x.dev'); + }); + + it('언어는 많은 순 상위 3개를 기술 스택으로', () => { + expect( + buildInitialProject( + snapshot({ + languages: { TypeScript: 900, CSS: 50, Shell: 10, HTML: 5 }, + }), + ).techStack, + ).toEqual(['typescript', 'css', 'shell']); + }); + + it('이름과 slug 를 만듦', () => { + const project = buildInitialProject(snapshot()); + + expect(project.name).toBe('My-Repo'); + expect(project.slug).toBe('my-repo'); + }); +}); diff --git a/lib/comlog/initial-project.ts b/lib/comlog/initial-project.ts new file mode 100644 index 0000000..66669bb --- /dev/null +++ b/lib/comlog/initial-project.ts @@ -0,0 +1,30 @@ +import { parseDemoUrl, topLanguages } from '@/lib/comlog/rules'; +import type { ComlogProjectRow } from '@/lib/db/schema/comlog'; +import { createPostSlug } from '@/lib/posts/post-path'; + +/** + * 저장소 정보로 프로젝트 초기값을 만드는 순수 함수 + * - GitHub 조회(server-only)와 분리해 테스트에서 바로 불러올 수 있게 함 + */ + +export interface RepoSnapshot { + name: string; + description: string | null; + homepage: string | null; + isPrivate: boolean; + // 언어 이름 → 바이트 수 + languages: Record; +} + +export const buildInitialProject = ( + snapshot: RepoSnapshot, +): Pick< + ComlogProjectRow, + 'name' | 'slug' | 'intro' | 'demoUrl' | 'techStack' +> => ({ + name: snapshot.name, + slug: createPostSlug(snapshot.name), + intro: snapshot.description ?? '', + demoUrl: parseDemoUrl(snapshot.homepage), + techStack: topLanguages(snapshot.languages), +}); diff --git a/lib/comlog/patch.test.ts b/lib/comlog/patch.test.ts new file mode 100644 index 0000000..5023f21 --- /dev/null +++ b/lib/comlog/patch.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest'; +import { buildProjectUpdate } from '@/lib/comlog/patch'; + +const current = { + name: 'Old', + techStack: ['typescript', 'css'], + removedTech: ['shell'], +}; + +describe('buildProjectUpdate', () => { + it('이름은 앞뒤 공백을 지우고 slug 도 다시 만듦', () => { + expect(buildProjectUpdate(current, { name: ' New Name ' })).toEqual({ + name: 'New Name', + slug: 'new-name', + }); + }); + + it('이름이 비었거나 60자를 넘으면 거부', () => { + expect(buildProjectUpdate(current, { name: ' ' })).toBeNull(); + expect(buildProjectUpdate(current, { name: 'a'.repeat(61) })).toBeNull(); + expect( + buildProjectUpdate(current, { name: 'a'.repeat(60) }), + ).not.toBeNull(); + }); + + it('소개는 2000자까지', () => { + expect(buildProjectUpdate(current, { intro: 'a'.repeat(2001) })).toBeNull(); + expect(buildProjectUpdate(current, { intro: '' })).toEqual({ intro: '' }); + }); + + it('지운 기술은 removed 로, 다시 넣은 기술은 removed 에서 뺌', () => { + expect( + buildProjectUpdate(current, { techStack: ['TypeScript', 'Shell'] }), + ).toEqual({ + techStack: ['typescript', 'shell'], + removedTech: ['css'], + }); + }); + + it('기술이 20개를 넘거나 문자열이 아니면 거부', () => { + const many = Array.from({ length: 21 }, (_, i) => `t${i}`); + + expect(buildProjectUpdate(current, { techStack: many })).toBeNull(); + expect( + buildProjectUpdate(current, { techStack: [1] as unknown as string[] }), + ).toBeNull(); + }); + + it('데모 링크는 http/https 만, 빈 값이면 지움', () => { + expect(buildProjectUpdate(current, { demoUrl: 'javascript:1' })).toBeNull(); + expect(buildProjectUpdate(current, { demoUrl: ' ' })).toEqual({ + demoUrl: null, + }); + expect(buildProjectUpdate(current, { demoUrl: 'https://a.dev' })).toEqual({ + demoUrl: 'https://a.dev', + }); + }); + + it('상태·공개 범위는 허용 값만', () => { + expect( + buildProjectUpdate(current, { status: 'x' as 'completed' }), + ).toBeNull(); + expect( + buildProjectUpdate(current, { visibility: 'secret' as 'public' }), + ).toBeNull(); + expect(buildProjectUpdate(current, { visibility: 'unlisted' })).toEqual({ + visibility: 'unlisted', + }); + }); + + it('작성자 표시는 parseAuthorDisplay 로 확인', () => { + expect( + buildProjectUpdate(current, { + authorDisplay: { mode: 'nickname', nickname: '', showProfile: true }, + }), + ).toBeNull(); + expect( + buildProjectUpdate(current, { + authorDisplay: { mode: 'login', nickname: 'x', showProfile: false }, + }), + ).toEqual({ + authorDisplay: 'login', + authorNickname: null, + showAuthorProfile: false, + }); + }); +}); diff --git a/lib/comlog/patch.ts b/lib/comlog/patch.ts new file mode 100644 index 0000000..c702393 --- /dev/null +++ b/lib/comlog/patch.ts @@ -0,0 +1,190 @@ +import { COMLOG_MAX_TECH, parseDemoUrl, removeTech } from '@/lib/comlog/rules'; +import type { ComlogVisibility } from '@/lib/comlog/rules'; +import { + COMLOG_PROJECT_STATUSES, + type ComlogProjectRow, + type ComlogProjectStatus, +} from '@/lib/db/schema/comlog'; +import { parseAuthorDisplay } from '@/lib/posts/author-display'; +import { createPostSlug } from '@/lib/posts/post-path'; +import { normalizeTag } from '@/lib/posts/tags'; + +/** + * 프로젝트 수정 입력 검증 (순수 함수) + * - 서버 액션 인자는 신뢰하지 않으므로 모든 값을 여기서 확인함 + * - 대표 이미지 소유 확인처럼 DB 가 필요한 검증은 store 에서 따로 함 + */ + +export const COMLOG_NAME_MAX_LENGTH = 60; +export const COMLOG_INTRO_MAX_LENGTH = 2000; + +const VISIBILITIES: readonly ComlogVisibility[] = [ + 'public', + 'unlisted', + 'private', +]; + +export interface ComlogProjectPatch { + name?: string; + intro?: string; + status?: ComlogProjectStatus; + techStack?: string[]; + githubLinkVisible?: boolean; + // 빈 문자열이면 지움 + demoUrl?: string | null; + visibility?: ComlogVisibility; + authorDisplay?: unknown; + coverImageId?: string | null; +} + +export type ComlogProjectUpdate = Partial< + Pick< + ComlogProjectRow, + | 'name' + | 'slug' + | 'intro' + | 'status' + | 'techStack' + | 'removedTech' + | 'showGithubLink' + | 'demoUrl' + | 'visibility' + | 'authorDisplay' + | 'authorNickname' + | 'showAuthorProfile' + | 'coverImageId' + > +>; + +type CurrentProject = Pick< + ComlogProjectRow, + 'name' | 'techStack' | 'removedTech' +>; + +const normalizeStack = (values: unknown): string[] | null => { + if (!Array.isArray(values)) return null; + + const stack = new Set(); + + for (const value of values) { + if (typeof value !== 'string') return null; + + const tag = normalizeTag(value); + + if (tag) stack.add(tag); + } + + return stack.size <= COMLOG_MAX_TECH ? [...stack] : null; +}; + +// 지운 기술은 removed 에 쌓고, 사용자가 다시 넣은 기술은 removed 에서 뺌 +const applyTechStack = ( + current: CurrentProject, + next: string[], +): Pick => { + const kept = new Set(next); + let removedTech = current.removedTech; + + for (const tag of current.techStack) { + if (!kept.has(normalizeTag(tag))) { + removedTech = removeTech([], removedTech, tag).removed; + } + } + + return { + techStack: next, + removedTech: removedTech.filter((tag) => !kept.has(tag)), + }; +}; + +const isOneOf = ( + values: readonly T[], + value: unknown, +): value is T => values.some((item) => item === value); + +/** 올바르지 않은 값이 하나라도 있으면 null (부분 저장 없음) */ +export function buildProjectUpdate( + current: CurrentProject, + patch: ComlogProjectPatch, +): ComlogProjectUpdate | null { + const update: ComlogProjectUpdate = {}; + + if (patch.name !== undefined) { + const name = typeof patch.name === 'string' ? patch.name.trim() : ''; + const length = [...name].length; + + if (length < 1 || length > COMLOG_NAME_MAX_LENGTH) return null; + + if (name !== current.name) { + update.name = name; + update.slug = createPostSlug(name); + } + } + + if (patch.intro !== undefined) { + if ( + typeof patch.intro !== 'string' || + [...patch.intro].length > COMLOG_INTRO_MAX_LENGTH + ) { + return null; + } + + update.intro = patch.intro; + } + + if (patch.status !== undefined) { + if (!isOneOf(COMLOG_PROJECT_STATUSES, patch.status)) return null; + + update.status = patch.status; + } + + if (patch.techStack !== undefined) { + const next = normalizeStack(patch.techStack); + + if (!next) return null; + + Object.assign(update, applyTechStack(current, next)); + } + + if (patch.githubLinkVisible !== undefined) { + if (typeof patch.githubLinkVisible !== 'boolean') return null; + + update.showGithubLink = patch.githubLinkVisible; + } + + if (patch.demoUrl !== undefined) { + const raw = patch.demoUrl; + const cleared = raw === null || (typeof raw === 'string' && !raw.trim()); + const demoUrl = cleared ? null : parseDemoUrl(raw); + + if (!cleared && !demoUrl) return null; + + update.demoUrl = demoUrl; + } + + if (patch.visibility !== undefined) { + if (!isOneOf(VISIBILITIES, patch.visibility)) return null; + + update.visibility = patch.visibility; + } + + if (patch.authorDisplay !== undefined) { + const author = parseAuthorDisplay(patch.authorDisplay); + + if (!author) return null; + + update.authorDisplay = author.mode; + update.authorNickname = author.nickname; + update.showAuthorProfile = author.showProfile; + } + + if (patch.coverImageId !== undefined) { + if (patch.coverImageId !== null && typeof patch.coverImageId !== 'string') { + return null; + } + + update.coverImageId = patch.coverImageId; + } + + return update; +} diff --git a/lib/comlog/store.ts b/lib/comlog/store.ts new file mode 100644 index 0000000..ccd5805 --- /dev/null +++ b/lib/comlog/store.ts @@ -0,0 +1,242 @@ +import 'server-only'; +import { and, eq, isNull } from 'drizzle-orm'; +import { getAutoDraftRepo } from '@/lib/auto-draft/store'; +import { fetchRepoSnapshot } from '@/lib/comlog/github'; +import { buildInitialProject } from '@/lib/comlog/initial-project'; +import { + buildProjectUpdate, + type ComlogProjectPatch, +} from '@/lib/comlog/patch'; +import { mergeTechStack } from '@/lib/comlog/rules'; +import { db } from '@/lib/db'; +import { + comlogProject, + githubRepository, + image, + type ComlogProjectRow, +} from '@/lib/db/schema'; +import { reportError } from '@/lib/observability/report-error'; +import type { AuthorDisplaySettings } from '@/lib/posts/author-display'; + +/** + * comlog 프로젝트 저장소 계층 + * - 사용자 + 저장소별 한 행, 모든 함수는 userId 로 소유를 확인함 + */ + +export type { ComlogProjectPatch } from '@/lib/comlog/patch'; + +const projectWhere = (userId: string, repositoryId: string) => + and( + eq(comlogProject.userId, userId), + eq(comlogProject.repositoryId, repositoryId), + ); + +export async function getComlogProject( + userId: string, + repositoryId: string, +): Promise { + const [row] = await db + .select() + .from(comlogProject) + .where(projectWhere(userId, repositoryId)) + .limit(1); + + return row ?? null; +} + +export async function refreshRepositoryPrivacy( + repositoryId: string, + isPrivate: boolean, +): Promise { + await db + .update(githubRepository) + .set({ isPrivate }) + .where(eq(githubRepository.id, repositoryId)); +} + +// 저장소를 등록하지 않았으면 오류 (호출부가 이미 소유를 확인했어야 함) +const requireRepo = async (userId: string, repositoryId: string) => { + const repo = await getAutoDraftRepo(userId, repositoryId); + + if (!repo) { + throw new Error('comlog: repository not registered'); + } + + return repo; +}; + +/** + * comlog 켜기 + * - 행이 없으면 저장소 정보로 만들고, 있으면 enabled 만 올림 (회차는 그대로) + * - 두 경우 모두 저장소 공개 여부를 최신으로 맞춤 + */ +export async function enableComlog( + userId: string, + repositoryId: string, +): Promise { + const repo = await requireRepo(userId, repositoryId); + const snapshot = await fetchRepoSnapshot(repo); + + await refreshRepositoryPrivacy(repositoryId, snapshot.isPrivate); + + const existing = await getComlogProject(userId, repositoryId); + + if (existing) { + if (existing.enabled) return existing; + + const [row] = await db + .update(comlogProject) + .set({ enabled: true }) + .where(projectWhere(userId, repositoryId)) + .returning(); + + return row ?? existing; + } + + // 비공개 저장소는 GitHub 링크를 처음부터 끔 + const [created] = await db + .insert(comlogProject) + .values({ + id: crypto.randomUUID(), + userId, + repositoryId, + showGithubLink: !snapshot.isPrivate, + ...buildInitialProject(snapshot), + }) + .onConflictDoNothing() + .returning(); + + // 동시에 켜서 다른 요청이 먼저 만든 경우 + const row = created ?? (await getComlogProject(userId, repositoryId)); + + if (!row) throw new Error('comlog: project not created'); + + return row; +} + +export async function disableComlog( + userId: string, + repositoryId: string, +): Promise { + await db + .update(comlogProject) + .set({ enabled: false }) + .where(projectWhere(userId, repositoryId)); +} + +// 대표 이미지는 본인 이미지만 (null 은 자동 이미지로 되돌림) +const ownsImage = async (userId: string, imageId: string) => { + const [row] = await db + .select({ id: image.id }) + .from(image) + .where(and(eq(image.id, imageId), eq(image.userId, userId))) + .limit(1); + + return Boolean(row); +}; + +const isPrivateRepo = async (repositoryId: string) => { + const [row] = await db + .select({ isPrivate: githubRepository.isPrivate }) + .from(githubRepository) + .where(eq(githubRepository.id, repositoryId)) + .limit(1); + + return row?.isPrivate ?? true; +}; + +export async function updateComlogProject( + userId: string, + repositoryId: string, + patch: ComlogProjectPatch, +): Promise<'ok' | 'not_found' | 'invalid'> { + const current = await getComlogProject(userId, repositoryId); + + if (!current) return 'not_found'; + + const update = buildProjectUpdate(current, patch); + + if (!update) return 'invalid'; + + if (update.coverImageId && !(await ownsImage(userId, update.coverImageId))) { + return 'invalid'; + } + + // 비공개 저장소는 GitHub 링크를 켤 수 없음 + if (update.showGithubLink && (await isPrivateRepo(repositoryId))) { + return 'invalid'; + } + + if (Object.keys(update).length > 0) { + await db + .update(comlogProject) + .set(update) + .where(projectWhere(userId, repositoryId)); + } + + return 'ok'; +} + +// 회차에서 나온 기술을 스택에 합침 (사용자가 지운 것은 제외) +export async function mergeProjectTech( + userId: string, + repositoryId: string, + tags: string[], +): Promise { + const current = await getComlogProject(userId, repositoryId); + + if (!current) return; + + const techStack = mergeTechStack( + current.techStack, + current.removedTech, + tags, + ); + + if (techStack.join('\n') === current.techStack.join('\n')) return; + + await db + .update(comlogProject) + .set({ techStack }) + .where(projectWhere(userId, repositoryId)); +} + +// 첫 회차를 게시할 때만 작성자 표시를 채움 (author_set_at 이 null 일 때) +export async function setProjectAuthorIfUnset( + userId: string, + repositoryId: string, + author: AuthorDisplaySettings, +): Promise { + await db + .update(comlogProject) + .set({ + authorDisplay: author.mode, + authorNickname: author.nickname, + showAuthorProfile: author.showProfile, + authorSetAt: new Date(), + }) + .where( + and( + projectWhere(userId, repositoryId), + isNull(comlogProject.authorSetAt), + ), + ); +} + +// 공개 여부만 GitHub 와 맞춤 (조회에 실패하면 기존 값 유지) +export async function refreshProjectRepoPrivacy( + userId: string, + repositoryId: string, +): Promise { + try { + const repo = await getAutoDraftRepo(userId, repositoryId); + + if (!repo) return; + + const { isPrivate } = await fetchRepoSnapshot(repo); + + await refreshRepositoryPrivacy(repositoryId, isPrivate); + } catch (error) { + reportError(error, 'comlog.refresh-repo-privacy', { repositoryId }); + } +} From 718b04bd3f3746aa7cf6aa7499ec4b346c25ae81 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 15:47:38 +0900 Subject: [PATCH 06/27] =?UTF-8?q?feat(comlog):=20=EC=B4=88=EC=95=88=20?= =?UTF-8?q?=EC=9E=91=EC=97=85=EC=97=90=20=EC=A2=85=EB=A5=98=EB=A5=BC=20?= =?UTF-8?q?=EC=8B=A3=EA=B3=A0=20=ED=9A=8C=EC=B0=A8=20=EC=98=B5=EC=85=98=20?= =?UTF-8?q?=EA=B3=A0=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- components/studio/prompt-composer.tsx | 2 ++ lib/actions/generation.ts | 50 +++++++++++++++++++++++++-- lib/auto-draft/run.ts | 2 ++ lib/generation/draft-job.ts | 15 ++++++-- lib/generation/draft-kind.test.ts | 14 ++++++++ lib/generation/draft-kind.ts | 11 ++++++ lib/generation/jobs.ts | 6 ++++ lib/studio/queries.ts | 22 ++++++++++++ 8 files changed, 118 insertions(+), 4 deletions(-) create mode 100644 lib/generation/draft-kind.test.ts create mode 100644 lib/generation/draft-kind.ts diff --git a/components/studio/prompt-composer.tsx b/components/studio/prompt-composer.tsx index d2127da..ac4a635 100644 --- a/components/studio/prompt-composer.tsx +++ b/components/studio/prompt-composer.tsx @@ -324,6 +324,8 @@ const PromptComposer = ({ draftId, prompt, options, + // comlog 화면 연결은 이후 작업에서 (지금은 일반 글만) + draftKind: 'post', commitShas: selectedCommits.map(({ sha }) => sha), codeInputs: sentCodeInputs, referenceLinks: pendingReferenceUrls, diff --git a/lib/actions/generation.ts b/lib/actions/generation.ts index 60ce937..1fb46c1 100644 --- a/lib/actions/generation.ts +++ b/lib/actions/generation.ts @@ -5,6 +5,7 @@ import { eq } from 'drizzle-orm'; import { refresh } from 'next/cache'; import { headers } from 'next/headers'; import { requireSession } from '@/lib/auth/session'; +import { getComlogProject } from '@/lib/comlog/store'; import { db } from '@/lib/db'; import { draft, draftPrompt } from '@/lib/db/schema'; import { @@ -28,6 +29,7 @@ import { type ParsedRequest, type SlotRejection, } from '@/lib/generation/draft-job'; +import { resolveRequestKind } from '@/lib/generation/draft-kind'; import { getGenerationRunner } from '@/lib/generation/get-runner'; import { applyCompletedJob, @@ -61,11 +63,18 @@ import { import { ensureBlankIds, findBlank } from '@/lib/studio/draft-blank'; import { isDraftDocument } from '@/lib/studio/draft-content'; import { + applyDraftKindOptions, DEFAULT_PROMPT_OPTIONS, + DRAFT_KINDS, parsePromptOptions, + type DraftKind, type PromptOptions, } from '@/lib/studio/options'; -import { getStudioRepository, isOwnedDraft } from '@/lib/studio/queries'; +import { + getDraftKind, + getStudioRepository, + isOwnedDraft, +} from '@/lib/studio/queries'; import { parseReferenceUrls } from '@/lib/studio/reference-link'; import { reportError } from '@/lib/observability/report-error'; @@ -75,6 +84,8 @@ export interface RequestDraftGenerationInput { draftId: string | null; prompt: string; options: unknown; + // 초안 종류 (이미 있는 초안은 저장된 종류가 이김) + draftKind: DraftKind; // 선택한 커밋 SHA (최신순, 직접 입력 코드가 있으면 비어도 됨) commitShas: string[]; // 직접 입력 코드 (저장하지 않고 작성기에만 넘김) @@ -179,6 +190,34 @@ export async function requestDraftGeneration( return { status: 'not_found' }; } + const requestedKind = DRAFT_KINDS.find((kind) => kind === input.draftKind); + + if (!requestedKind) { + return { status: 'invalid' }; + } + + const draftKind = resolveRequestKind( + request.draftId + ? await getDraftKind(user.id, repository.id, request.draftId) + : null, + requestedKind, + ); + + // comlog 회차는 그 저장소의 comlog 가 켜져 있을 때만 만들 수 있음 + if ( + draftKind === 'comlog' && + !(await getComlogProject(user.id, repository.id))?.enabled + ) { + return { status: 'invalid' }; + } + + // 종류에 맞게 옵션 확정 (comlog 는 worklog·short 고정, 일반 글에 worklog 는 거부) + const options = applyDraftKindOptions(draftKind, request.options); + + if (!options) { + return { status: 'invalid' }; + } + const gate = await checkGenerationGate(user, await headers()); if (gate.status !== 'ok') { @@ -194,7 +233,14 @@ export async function requestDraftGeneration( const created = await createDraftJob( user.id, repository.id, - { ...request, source: 'studio', triggerSha: null }, + { + ...request, + options, + source: 'studio', + triggerSha: null, + draftKind, + boundaryClaimed: false, + }, await getRequestLocale(), ); diff --git a/lib/auto-draft/run.ts b/lib/auto-draft/run.ts index 2ab1962..edb6c7f 100644 --- a/lib/auto-draft/run.ts +++ b/lib/auto-draft/run.ts @@ -329,6 +329,8 @@ async function tryStartBatch( draftId: null, source: 'commit_trigger', triggerSha: push.trigger.sha, + draftKind: 'post', + boundaryClaimed: false, }, locale, ); diff --git a/lib/generation/draft-job.ts b/lib/generation/draft-job.ts index b4b6147..691a2de 100644 --- a/lib/generation/draft-job.ts +++ b/lib/generation/draft-job.ts @@ -28,7 +28,7 @@ import { getGithubUserToken, GithubUserTokenError, } from '@/lib/github/user-api'; -import type { PromptOptions } from '@/lib/studio/options'; +import type { DraftKind, PromptOptions } from '@/lib/studio/options'; /** * 초안 작업 생성과 사용자 단위 검사 (스튜디오 요청과 커밋 웹훅 공용) @@ -57,6 +57,10 @@ export interface ParsedRequest { export interface DraftJobRequest extends ParsedRequest { source: DraftPromptSource; triggerSha: string | null; + // 초안 종류 (새 초안이면 draft.kind 로 저장, 작업 행에도 남김) + draftKind: DraftKind; + // 이 작업이 자동 초안 경계를 먼저 가져갔는지 (실패 때 되돌릴 대상 표시) + boundaryClaimed: boolean; } // 초안 작업 만들기 결과 @@ -124,7 +128,12 @@ export const createDraftJob = async ( ); referenceUrls = links.map((link) => link.url); } else { - await tx.insert(draft).values({ id: draftId, userId, repositoryId }); + await tx.insert(draft).values({ + id: draftId, + userId, + repositoryId, + kind: request.draftKind, + }); if (request.referenceUrls.length > 0) { await tx.insert(draftReferenceLink).values( @@ -155,6 +164,8 @@ export const createDraftJob = async ( repositoryId, source: request.source, triggerSha: request.triggerSha, + draftKind: request.draftKind, + boundaryClaimed: request.boundaryClaimed, }); return reserved; diff --git a/lib/generation/draft-kind.test.ts b/lib/generation/draft-kind.test.ts new file mode 100644 index 0000000..6752785 --- /dev/null +++ b/lib/generation/draft-kind.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest'; +import { resolveRequestKind } from '@/lib/generation/draft-kind'; + +describe('resolveRequestKind', () => { + it('기존 초안이면 기존 종류가 이김', () => { + expect(resolveRequestKind('post', 'comlog')).toBe('post'); + expect(resolveRequestKind('comlog', 'post')).toBe('comlog'); + }); + + it('새 초안이면 요청한 종류', () => { + expect(resolveRequestKind(null, 'comlog')).toBe('comlog'); + expect(resolveRequestKind(null, 'post')).toBe('post'); + }); +}); diff --git a/lib/generation/draft-kind.ts b/lib/generation/draft-kind.ts new file mode 100644 index 0000000..effbaad --- /dev/null +++ b/lib/generation/draft-kind.ts @@ -0,0 +1,11 @@ +import type { DraftKind } from '@/lib/studio/options'; + +/** + * 요청에 적용할 초안 종류 + * - 이미 있는 초안은 만들 때 정해진 종류가 이김 (클라이언트가 다른 종류를 보내도 바꿀 수 없음) + * - 새 초안(기존 종류 null)은 요청한 종류 + */ +export const resolveRequestKind = ( + existingDraftKind: DraftKind | null, + requestedKind: DraftKind, +): DraftKind => existingDraftKind ?? requestedKind; diff --git a/lib/generation/jobs.ts b/lib/generation/jobs.ts index d61138d..7a3d973 100644 --- a/lib/generation/jobs.ts +++ b/lib/generation/jobs.ts @@ -48,6 +48,7 @@ import { ensureBlankIds, replaceBlank } from '@/lib/studio/draft-blank'; import { extractDraftTitle, isDraftDocument } from '@/lib/studio/draft-content'; import { getSupabaseUrl } from '@/lib/supabase/server'; import { reportError } from '@/lib/observability/report-error'; +import type { DraftKind } from '@/lib/studio/options'; /** * AI 작성 작업(draft_prompt) 저장소 @@ -66,6 +67,8 @@ export interface GenerationJobView { id: string; // 작업 종류 (fill 은 편집기 전체가 아니라 blankId 의 빈칸만 막음) kind: GenerationJobKind; + // 초안 종류 (일반 글 / comlog 회차) + draftKind: DraftKind; // 빈칸 채우기 대상 빈칸 id (초안 작성 작업은 null) blankId: string | null; channel: string; @@ -96,6 +99,7 @@ const LOCKING_ACTIVE_STATUSES: GenerationStatus[] = [ const jobViewColumns = { id: draftPrompt.id, kind: draftPrompt.kind, + draftKind: draftPrompt.draftKind, blankId: draftPrompt.blankId, channel: draftPrompt.channel, status: draftPrompt.status, @@ -110,6 +114,7 @@ const jobViewColumns = { interface JobViewRow { id: string; kind: GenerationJobKind; + draftKind: DraftKind; blankId: string | null; channel: string; status: GenerationStatus; @@ -135,6 +140,7 @@ const toViewClarification = (row: JobViewRow) => { const toJobView = (row: JobViewRow): GenerationJobView => ({ id: row.id, kind: row.kind, + draftKind: row.draftKind, blankId: row.kind === 'fill' ? row.blankId : null, channel: row.channel, status: row.status, diff --git a/lib/studio/queries.ts b/lib/studio/queries.ts index 1dea93c..ee13acf 100644 --- a/lib/studio/queries.ts +++ b/lib/studio/queries.ts @@ -25,6 +25,7 @@ import { parsePromptOptions, type PromptOptions, } from '@/lib/studio/options'; +import type { DraftKind } from '@/lib/studio/options'; import type { ReferenceLink } from '@/lib/studio/reference-link'; import { isJobResumable } from '@/lib/generation/job-state'; import { @@ -220,6 +221,27 @@ export const isOwnedDraft = async ( return Boolean(row); }; +// 초안의 종류 (소유한 초안이 아니면 null) +export const getDraftKind = async ( + userId: string, + repositoryId: string, + draftId: string, +): Promise => { + const [row] = await db + .select({ kind: draft.kind }) + .from(draft) + .where( + and( + eq(draft.id, draftId), + eq(draft.userId, userId), + eq(draft.repositoryId, repositoryId), + ), + ) + .limit(1); + + return row?.kind ?? null; +}; + // 초안의 참고 링크 (추가한 순서대로) export const listDraftReferenceLinks = async ( draftId: string, From 2302e8416998530205afa80b21665e997e7f7137 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 15:56:30 +0900 Subject: [PATCH 07/27] =?UTF-8?q?feat(comlog):=20=ED=8A=B8=EB=A6=AC?= =?UTF-8?q?=EA=B1=B0=EA=B0=80=20=ED=9A=8C=EC=B0=A8=C2=B7=EC=9D=BC=EB=B0=98?= =?UTF-8?q?=20=EA=B8=80=EC=9D=84=20=EB=A7=8C=EB=93=A4=EA=B3=A0=20=EB=A7=89?= =?UTF-8?q?=ED=9E=88=EB=A9=B4=20=EB=B0=80=EB=A6=B0=20=EC=BB=A4=EB=B0=8B?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EB=82=A8=EA=B9=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 트리거 단어와 저장소 comlog 사용 여부로 종류를 정해 post / comlog / 둘 다 작업을 한 트랜잭션에서 생성 (createDraftJobs, 자리 수만큼 확인) - 사용됨 범위(post_trigger / comlog / both)를 findConsumedShas 에 추가, 초안 작성 작업만 셈 - 회차 트리거가 할당량·속도 제한 등으로 막히면 범위 커밋 전부를 backlog 로 남기고 경계를 푸시 끝으로 - 실패 행은 종류마다, 실행기는 각각 시작하고 둘 다 실패했을 때만 경계를 되돌림 - push 웹훅에서 저장소 공개 여부를 갱신 Co-Authored-By: Claude Opus 5.5 --- app/api/github/webhook/route.ts | 29 +- lib/auto-draft/batch-server.test.ts | 32 +- lib/auto-draft/batch-server.ts | 34 +- lib/auto-draft/batch.test.ts | 7 + lib/auto-draft/batch.ts | 12 +- lib/auto-draft/run.test.ts | 601 +++++++++++++++++++++++----- lib/auto-draft/run.ts | 303 ++++++++++---- lib/auto-draft/store.test.ts | 42 ++ lib/auto-draft/store.ts | 74 +++- lib/auto-draft/trigger.test.ts | 9 + lib/auto-draft/trigger.ts | 16 + lib/auto-draft/webhook.test.ts | 18 +- lib/auto-draft/webhook.ts | 4 + lib/generation/draft-job.ts | 247 ++++++++---- lib/generation/jobs.test.ts | 8 + lib/generation/jobs.ts | 4 +- lib/generation/slot.test.ts | 20 + lib/generation/slot.ts | 13 +- 18 files changed, 1202 insertions(+), 271 deletions(-) create mode 100644 lib/auto-draft/store.test.ts diff --git a/app/api/github/webhook/route.ts b/app/api/github/webhook/route.ts index 2560f55..db1ba53 100644 --- a/app/api/github/webhook/route.ts +++ b/app/api/github/webhook/route.ts @@ -1,11 +1,16 @@ import { after, type NextRequest } from 'next/server'; import { recordUnexpectedFailure, runAutoDraft } from '@/lib/auto-draft/run'; -import { excludeCommits, findPushTargets } from '@/lib/auto-draft/store'; +import { + excludeCommits, + findPushTargets, + findRepositoryIdByGithubRepoId, +} from '@/lib/auto-draft/store'; import { parsePushEvent, planPushEvent, verifyWebhookSignature, } from '@/lib/auto-draft/webhook'; +import { refreshRepositoryPrivacy } from '@/lib/comlog/store'; import { getGithubWebhookSecret } from '@/lib/github/env'; import { flushReports, reportError } from '@/lib/observability/report-error'; @@ -15,6 +20,26 @@ const BRANCH_REF_PREFIX = 'refs/heads/'; const toErrorMessage = (error: unknown) => error instanceof Error ? error.message : String(error); +/** + * 푸시 페이로드의 공개 여부로 등록된 저장소 행을 갱신 (comlog GitHub 링크 표시에 씀) + * - 추적 브랜치·푸시한 사람과 무관하게, 등록된 저장소일 때만 + * - 실패해도 자동 초안 처리는 이어감 + */ +const syncRepositoryPrivacy = async ( + githubRepoId: number, + isPrivate: boolean | null, +) => { + if (isPrivate === null) return; + + try { + const repositoryId = await findRepositoryIdByGithubRepoId(githubRepoId); + + if (repositoryId) await refreshRepositoryPrivacy(repositoryId, isPrivate); + } catch (error) { + reportError(error, 'github-webhook.repository-privacy', { githubRepoId }); + } +}; + // 자동 초안 실행은 응답 뒤에 이어지므로 넉넉한 시간을 줌 export const maxDuration = 300; @@ -55,6 +80,8 @@ export async function POST(request: NextRequest) { return Response.json({ error: 'invalid_request' }, { status: 400 }); } + await syncRepositoryPrivacy(event.repositoryId, event.repositoryPrivate); + // 태그 등 브랜치가 아닌 ref 는 대상이 아님 if (!event.ref.startsWith(BRANCH_REF_PREFIX)) { return Response.json({ status: 'ignored' }); diff --git a/lib/auto-draft/batch-server.test.ts b/lib/auto-draft/batch-server.test.ts index 0ae1b6f..97a87fd 100644 --- a/lib/auto-draft/batch-server.test.ts +++ b/lib/auto-draft/batch-server.test.ts @@ -90,11 +90,13 @@ describe('computeAutoDraftBatch', () => { { ...input, endSha: 'c3', excluded: new Map([['c2', 'user']]) }, io, ); - expect(io.findConsumedShas).toHaveBeenCalledWith('u1', 'r1', [ - 'c1', - 'c2', - 'c3', - ]); + // 범위를 주지 않으면 일반 글 트리거 규칙 + expect(io.findConsumedShas).toHaveBeenCalledWith( + 'u1', + 'r1', + ['c1', 'c2', 'c3'], + 'post_trigger', + ); expect(io.findEmptyCommits).not.toHaveBeenCalled(); expect(result).toEqual({ status: 'ok', @@ -107,6 +109,26 @@ describe('computeAutoDraftBatch', () => { }); }); + it('사용됨 범위와 개수 제한을 넘기면 그대로 씀', async () => { + const commits = Array.from({ length: 25 }, (_, i) => + node(`c${i + 1}`, [i === 0 ? 'b' : `c${i}`]), + ); + const io = makeIo(commits); + const result = await computeAutoDraftBatch( + repo, + { ...input, consumedScope: 'comlog', limit: Infinity }, + io, + ); + expect(io.findConsumedShas).toHaveBeenCalledWith( + 'u1', + 'r1', + commits.map((c) => c.sha), + 'comlog', + ); + expect(result).toMatchObject({ status: 'ok', exhausted: true }); + expect(result.status === 'ok' && result.batchShas).toHaveLength(25); + }); + it('compare 결과에 커밋이 없으면(identical·behind) 조회 없이 빈 묶음', async () => { const io = makeIo([]); expect(await computeAutoDraftBatch(repo, input, io)).toEqual({ diff --git a/lib/auto-draft/batch-server.ts b/lib/auto-draft/batch-server.ts index 0f5c73d..8f006d3 100644 --- a/lib/auto-draft/batch-server.ts +++ b/lib/auto-draft/batch-server.ts @@ -10,6 +10,7 @@ import { type AutoDraftRepo, } from '@/lib/auto-draft/github'; import { findConsumedShas } from '@/lib/auto-draft/store'; +import type { ConsumedScope } from '@/lib/auto-draft/trigger'; // GitHub·DB 조회 (테스트에서 바꿔 끼움) export interface BatchIo { @@ -21,8 +22,8 @@ export interface BatchIo { const defaultIo: BatchIo = { compare: (repo, base, head) => compareBranch(repo, base, head), findEmptyCommits: (repo, shas) => findEmptyCommits(repo, shas), - findConsumedShas: (userId, repositoryId, shas) => - findConsumedShas(userId, repositoryId, shas), + findConsumedShas: (userId, repositoryId, shas, scope) => + findConsumedShas(userId, repositoryId, shas, scope), }; export interface AutoDraftBatchInput { @@ -33,6 +34,10 @@ export interface AutoDraftBatchInput { // 범위 끝: 스튜디오는 브랜치 끝, 실행기는 푸시 끝(after) endSha: string; excluded: ReadonlyMap; + // 건너뛸 사용됨 범위 (기본: 일반 글 트리거 규칙) + consumedScope?: ConsumedScope; + // 묶음 최대 개수 (기본 20, 밀린 커밋 기록은 Infinity) + limit?: number; } /** @@ -44,7 +49,15 @@ export interface AutoDraftBatchInput { */ export async function computeAutoDraftBatch( repo: AutoDraftRepo, - { userId, repositoryId, boundarySha, endSha, excluded }: AutoDraftBatchInput, + { + userId, + repositoryId, + boundarySha, + endSha, + excluded, + consumedScope = 'post_trigger', + limit, + }: AutoDraftBatchInput, io: BatchIo = defaultIo, ): Promise { const compared = await io.compare(repo, boundarySha, endSha); @@ -67,15 +80,20 @@ export async function computeAutoDraftBatch( userId, repositoryId, commits.map((commit) => commit.sha), + consumedScope, ), ]); return { status: 'ok', - ...selectBatch(commits, { - excludedShas: new Set(excluded.keys()), - consumedShas, - emptyShas, - }), + ...selectBatch( + commits, + { + excludedShas: new Set(excluded.keys()), + consumedShas, + emptyShas, + }, + limit, + ), }; } diff --git a/lib/auto-draft/batch.test.ts b/lib/auto-draft/batch.test.ts index 37e2855..921a557 100644 --- a/lib/auto-draft/batch.test.ts +++ b/lib/auto-draft/batch.test.ts @@ -52,6 +52,13 @@ describe('selectBatch', () => { expect(exhausted).toBe(false); }); + it('limit 을 주면 그 수까지 담음 (밀린 커밋 기록은 제한 없이)', () => { + const commits = Array.from({ length: 25 }, (_, i) => commit(i + 1)); + const { batchShas, exhausted } = selectBatch(commits, none, Infinity); + expect(batchShas).toHaveLength(25); + expect(exhausted).toBe(true); + }); + it('스무 번째 대상이 마지막 커밋이면 끝까지 본 것', () => { const commits = Array.from({ length: 20 }, (_, i) => commit(i + 1)); const { batchShas, exhausted } = selectBatch(commits, none); diff --git a/lib/auto-draft/batch.ts b/lib/auto-draft/batch.ts index 57a4864..0cecd28 100644 --- a/lib/auto-draft/batch.ts +++ b/lib/auto-draft/batch.ts @@ -29,10 +29,10 @@ export interface SkipSets { } export interface BatchSelection { - // 오래된 순, 최대 20개 + // 오래된 순, 최대 limit 개 (기본 20) batchShas: string[]; skipped: Map; - // 20개 제한에 걸리지 않고 범위 끝까지 다 봤는지 + // 개수 제한에 걸리지 않고 범위 끝까지 다 봤는지 exhausted: boolean; } @@ -67,12 +67,14 @@ export function getSkipReason( } /** - * compare 범위(경계 다음 ~ 범위 끝)의 커밋에서 묶음(최대 20개)과 건너뛴 커밋을 계산 + * compare 범위(경계 다음 ~ 범위 끝)의 커밋에서 묶음(최대 limit 개, 기본 20)과 건너뛴 커밋을 계산 * - PR 로 들어온 커밋, GitHub 가 만든 squash·rebase 커밋, 웹 편집 커밋도 일반 커밋처럼 대상 + * - 밀린 커밋 기록은 범위 전부가 필요해 limit 을 Infinity 로 넘김 */ export function selectBatch( commits: BranchCommit[], sets: SkipSets, + limit: number = MAX_GENERATION_COMMITS, ): BatchSelection { const batchShas: string[] = []; const skipped = new Map(); @@ -83,9 +85,9 @@ export function selectBatch( skipped.set(commit.sha, reason); continue; } - // 20개가 찬 뒤 대상이 하나라도 더 있으면 그 커밋부터 다음 묶음 몫 + // limit 개가 찬 뒤 대상이 하나라도 더 있으면 그 커밋부터 다음 묶음 몫 // → 뒤에 건너뛸 커밋(머지 커밋 등)만 남았으면 끝까지 본 것 - if (batchShas.length >= MAX_GENERATION_COMMITS) { + if (batchShas.length >= limit) { return { batchShas, skipped, exhausted: false }; } batchShas.push(commit.sha); diff --git a/lib/auto-draft/run.test.ts b/lib/auto-draft/run.test.ts index f5bdb7f..b725f42 100644 --- a/lib/auto-draft/run.test.ts +++ b/lib/auto-draft/run.test.ts @@ -18,15 +18,20 @@ import { import type { PushTarget } from '@/lib/auto-draft/store'; import type { TriggerOptions } from '@/lib/auto-draft/trigger'; import type { TriggerPush } from '@/lib/auto-draft/webhook'; +import type { DraftJobRequest } from '@/lib/generation/draft-job'; import { DEFAULT_PROMPT_OPTIONS } from '@/lib/studio/options'; // 경계 = 첫 커밋 c1 의 첫 부모 const OLD = 'c0'; -const target = (over: Partial = {}): PushTarget => ({ +const target = ( + over: Partial = {}, + comlogEnabled = false, +): PushTarget => ({ userId: 'u1', repositoryId: 'r1', githubAccountId: '1', + comlogEnabled, user: { id: 'u1', role: 'basic', bannedAt: null }, repo: { installationId: 1, owner: 'o', name: 'n', branch: 'main' }, setting: { @@ -73,15 +78,21 @@ const makeDeps = (over: Partial = {}) => { findConsumedShas: vi.fn(async () => new Set()), listExcludedShas: vi.fn(async () => new Map()), gate: vi.fn(async () => ({ status: 'ok' as const, githubToken: 'tok' })), - createDraftJob: vi.fn(async () => ({ - status: 'created' as const, - draftId: 'd1', - jobId: 'j1', - })), + // 요청마다 초안·작업 하나 (d1/j1, d2/j2 …) + createDraftJobs: vi.fn( + async (_u: string, _r: string, requests: DraftJobRequest[]) => ({ + status: 'created' as const, + jobs: requests.map((_, i) => ({ + draftId: `d${i + 1}`, + jobId: `j${i + 1}`, + })), + }), + ), startRunner: vi.fn(async () => {}), failJob: vi.fn(async () => null), recordFailure: vi.fn(async () => 'recorded' as const), moveBoundary: vi.fn(async () => true), + recordBacklog: vi.fn(async () => {}), getBoundary: vi.fn(async (): Promise => OLD), getLocale: vi.fn(async () => 'en' as const), ...over, @@ -162,7 +173,7 @@ describe('runAutoDraft', () => { expect.objectContaining({ errorCode: 'no_commits', triggerSha: 'c3' }), ); expect(deps.moveBoundary).not.toHaveBeenCalled(); - expect(deps.createDraftJob).not.toHaveBeenCalled(); + expect(deps.createDraftJobs).not.toHaveBeenCalled(); }); it('묶음이 비면 no_commits, 경계는 건드리지 않음', async () => { @@ -197,23 +208,25 @@ describe('runAutoDraft', () => { push('c3', { tone: 'friendly' }, 'c5'), deps, ); - expect(out).toEqual({ status: 'started', jobId: 'j1' }); + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); expect(deps.compare).toHaveBeenCalledWith(expect.anything(), OLD, 'c5'); expect(deps.moveBoundary).toHaveBeenCalledTimes(1); expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c5'); - expect(deps.createDraftJob).toHaveBeenCalledWith( + expect(deps.createDraftJobs).toHaveBeenCalledWith( 'u1', 'r1', - expect.objectContaining({ - prompt: '프리셋', - commitShas: ['c5', 'c4', 'c3', 'c2', 'c1'], - codeInputs: [], - referenceUrls: [], - draftId: null, - source: 'commit_trigger', - triggerSha: 'c3', - options: expect.objectContaining({ tone: 'friendly' }), - }), + [ + expect.objectContaining({ + prompt: '프리셋', + commitShas: ['c5', 'c4', 'c3', 'c2', 'c1'], + codeInputs: [], + referenceUrls: [], + draftId: null, + source: 'commit_trigger', + triggerSha: 'c3', + options: expect.objectContaining({ tone: 'friendly' }), + }), + ], 'en', ); expect(deps.startRunner).toHaveBeenCalledWith({ @@ -232,10 +245,10 @@ describe('runAutoDraft', () => { 'c3', ]); expect(out).toMatchObject({ status: 'started' }); - expect(deps.createDraftJob).toHaveBeenCalledWith( + expect(deps.createDraftJobs).toHaveBeenCalledWith( 'u1', 'r1', - expect.objectContaining({ commitShas: ['c2', 'c1'] }), + [expect.objectContaining({ commitShas: ['c2', 'c1'] })], 'en', ); expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c3'); @@ -259,16 +272,18 @@ describe('runAutoDraft', () => { push('f2', { length: 'long' }, 'm'), deps, ); - expect(out).toEqual({ status: 'started', jobId: 'j1' }); + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); expect(deps.compare).toHaveBeenCalledWith(expect.anything(), OLD, 'm'); - expect(deps.createDraftJob).toHaveBeenCalledWith( + expect(deps.createDraftJobs).toHaveBeenCalledWith( 'u1', 'r1', - expect.objectContaining({ - commitShas: ['f2', 'c1', 'f1'], - triggerSha: 'f2', - options: expect.objectContaining({ length: 'long' }), - }), + [ + expect.objectContaining({ + commitShas: ['f2', 'c1', 'f1'], + triggerSha: 'f2', + options: expect.objectContaining({ length: 'long' }), + }), + ], 'en', ); expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'm'); @@ -286,15 +301,17 @@ describe('runAutoDraft', () => { push('c2', { postType: 'lecture' }), deps, ); - expect(out).toEqual({ status: 'started', jobId: 'j1' }); - expect(deps.createDraftJob).toHaveBeenCalledWith( + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); + expect(deps.createDraftJobs).toHaveBeenCalledWith( 'u1', 'r1', - expect.objectContaining({ - commitShas: ['c2', 'c1'], - triggerSha: 'c2', - options: expect.objectContaining({ postType: 'lecture' }), - }), + [ + expect.objectContaining({ + commitShas: ['c2', 'c1'], + triggerSha: 'c2', + options: expect.objectContaining({ postType: 'lecture' }), + }), + ], 'en', ); expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c2'); @@ -305,15 +322,16 @@ describe('runAutoDraft', () => { findConsumedShas: vi.fn(async () => new Set(['c1'])), }); await runAutoDraft(target(), push('c3'), deps); - expect(deps.findConsumedShas).toHaveBeenCalledWith('u1', 'r1', [ - 'c1', - 'c2', - 'c3', - ]); - expect(deps.createDraftJob).toHaveBeenCalledWith( + expect(deps.findConsumedShas).toHaveBeenCalledWith( + 'u1', + 'r1', + ['c1', 'c2', 'c3'], + 'post_trigger', + ); + expect(deps.createDraftJobs).toHaveBeenCalledWith( 'u1', 'r1', - expect.objectContaining({ commitShas: ['c3', 'c2'] }), + [expect.objectContaining({ commitShas: ['c3', 'c2'] })], 'en', ); }); @@ -329,15 +347,17 @@ describe('runAutoDraft', () => { it('20개에서 잘리면 경계를 옮기지 않고 작업을 만듦', async () => { const deps = makeDeps({ compare: capped() }); const out = await runAutoDraft(target(), push('c25'), deps); - expect(out).toEqual({ status: 'started', jobId: 'j1' }); + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); expect(deps.moveBoundary).not.toHaveBeenCalled(); - expect(deps.createDraftJob).toHaveBeenCalledWith( + expect(deps.createDraftJobs).toHaveBeenCalledWith( 'u1', 'r1', - expect.objectContaining({ - commitShas: Array.from({ length: 20 }, (_, i) => `c${20 - i}`), - triggerSha: 'c25', - }), + [ + expect.objectContaining({ + commitShas: Array.from({ length: 20 }, (_, i) => `c${20 - i}`), + triggerSha: 'c25', + }), + ], 'en', ); }); @@ -345,7 +365,7 @@ describe('runAutoDraft', () => { it('20개에서 잘린 뒤 작업을 못 만들면 실패 기록만, 경계는 건드리지 않음', async () => { const deps = makeDeps({ compare: capped(), - createDraftJob: vi.fn(async () => ({ status: 'rate_limited' as const })), + createDraftJobs: vi.fn(async () => ({ status: 'rate_limited' as const })), }); const out = await runAutoDraft(target(), push('c25'), deps); expect(out).toEqual({ status: 'skipped', errorCode: 'rate_limited' }); @@ -365,10 +385,10 @@ describe('runAutoDraft', () => { expect(deps.moveBoundary).not.toHaveBeenCalled(); }); - it('20개에서 잘린 뒤 createDraftJob 이 던지면 원래 오류, 경계는 건드리지 않음', async () => { + it('20개에서 잘린 뒤 createDraftJobs 가 던지면 원래 오류, 경계는 건드리지 않음', async () => { const deps = makeDeps({ compare: capped(), - createDraftJob: vi.fn(async () => { + createDraftJobs: vi.fn(async () => { throw new Error('orig'); }), }); @@ -384,7 +404,7 @@ describe('runAutoDraft', () => { expect(out).toEqual({ status: 'skipped', errorCode: 'no_commits' }); expect(deps.compare).toHaveBeenCalledTimes(3); expect(deps.getBoundary).toHaveBeenCalledTimes(2); - expect(deps.createDraftJob).not.toHaveBeenCalled(); + expect(deps.createDraftJobs).not.toHaveBeenCalled(); }); it('다른 트리거가 먼저 경계를 옮겼으면 새 경계로 다시 계산해 남은 커밋으로 실행', async () => { @@ -402,13 +422,13 @@ describe('runAutoDraft', () => { getBoundary: vi.fn(async () => 'c2'), }); const out = await runAutoDraft(target(), push('c3'), deps); - expect(out).toEqual({ status: 'started', jobId: 'j1' }); + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); expect(compare).toHaveBeenLastCalledWith(expect.anything(), 'c2', 'c3'); expect(deps.moveBoundary).toHaveBeenLastCalledWith('u1', 'r1', 'c2', 'c3'); - expect(deps.createDraftJob).toHaveBeenCalledWith( + expect(deps.createDraftJobs).toHaveBeenCalledWith( 'u1', 'r1', - expect.objectContaining({ commitShas: ['c3'] }), + [expect.objectContaining({ commitShas: ['c3'] })], 'en', ); }); @@ -420,7 +440,7 @@ describe('runAutoDraft', () => { }); const out = await runAutoDraft(target(), push('c3'), deps); expect(out).toEqual({ status: 'skipped', errorCode: 'anchor_missing' }); - expect(deps.createDraftJob).not.toHaveBeenCalled(); + expect(deps.createDraftJobs).not.toHaveBeenCalled(); }); it('20개에서 잘린 묶음이 다른 트리거와 겹치면(overlap) 사용된 커밋을 빼고 다음 묶음으로 실행', async () => { @@ -433,19 +453,24 @@ describe('runAutoDraft', () => { const deps = makeDeps({ compare: vi.fn(async () => ({ status: 'ok' as const, commits })), findConsumedShas, - createDraftJob: vi - .fn() + createDraftJobs: vi + .fn() .mockResolvedValueOnce({ status: 'overlap' }) - .mockResolvedValue({ status: 'created', draftId: 'd1', jobId: 'j1' }), + .mockResolvedValue({ + status: 'created', + jobs: [{ draftId: 'd1', jobId: 'j1' }], + }), }); const out = await runAutoDraft(target(), push('c25'), deps); - expect(out).toEqual({ status: 'started', jobId: 'j1' }); - expect(deps.createDraftJob).toHaveBeenLastCalledWith( + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); + expect(deps.createDraftJobs).toHaveBeenLastCalledWith( 'u1', 'r1', - expect.objectContaining({ - commitShas: ['c25', 'c24', 'c23', 'c22', 'c21'], - }), + [ + expect.objectContaining({ + commitShas: ['c25', 'c24', 'c23', 'c22', 'c21'], + }), + ], 'en', ); // 두 번째 묶음은 끝까지 봐서 경계를 푸시 끝으로 선점 @@ -454,20 +479,20 @@ describe('runAutoDraft', () => { it('끝까지 본 묶음이 overlap 이면 선점한 경계를 되돌린 뒤 다시 계산', async () => { const deps = makeDeps({ - createDraftJob: vi - .fn() + createDraftJobs: vi + .fn() .mockResolvedValue({ status: 'overlap' }), }); const out = await runAutoDraft(target(), push('c3'), deps); expect(out).toEqual({ status: 'skipped', errorCode: 'no_commits' }); - expect(deps.createDraftJob).toHaveBeenCalledTimes(3); + expect(deps.createDraftJobs).toHaveBeenCalledTimes(3); expect(deps.moveBoundary).toHaveBeenLastCalledWith('u1', 'r1', 'c3', OLD); expect(deps.startRunner).not.toHaveBeenCalled(); }); it('slot rate_limited 면 실패 기록 + 경계 되돌림', async () => { const deps = makeDeps({ - createDraftJob: vi.fn(async () => ({ status: 'rate_limited' as const })), + createDraftJobs: vi.fn(async () => ({ status: 'rate_limited' as const })), }); const out = await runAutoDraft(target(), push('c3', {}, 'c3'), deps); expect(out).toEqual({ status: 'skipped', errorCode: 'rate_limited' }); @@ -479,15 +504,15 @@ describe('runAutoDraft', () => { it('busy 는 too_many_active', async () => { const deps = makeDeps({ - createDraftJob: vi.fn(async () => ({ status: 'busy' as const })), + createDraftJobs: vi.fn(async () => ({ status: 'busy' as const })), }); const out = await runAutoDraft(target(), push('c3'), deps); expect(out).toEqual({ status: 'skipped', errorCode: 'too_many_active' }); }); - it('createDraftJob duplicate 면 duplicate, 러너 안 부르고 경계 되돌림', async () => { + it('createDraftJobs duplicate 면 duplicate, 러너 안 부르고 경계 되돌림', async () => { const deps = makeDeps({ - createDraftJob: vi.fn(async () => ({ status: 'duplicate' as const })), + createDraftJobs: vi.fn(async () => ({ status: 'duplicate' as const })), }); const out = await runAutoDraft(target(), push('c3'), deps); expect(out).toEqual({ status: 'duplicate' }); @@ -524,14 +549,14 @@ describe('runAutoDraft', () => { expect(deps.moveBoundary).toHaveBeenLastCalledWith('u1', 'r1', 'c3', OLD); }); - it('createDraftJob 이 던지면 경계를 되돌리고 원래 오류를 던짐', async () => { + it('createDraftJobs 가 던지면 경계를 되돌리고 원래 오류를 던짐', async () => { const moveBoundary = vi .fn() .mockResolvedValueOnce(true) .mockRejectedValueOnce(new Error('revert')); const deps = makeDeps({ moveBoundary, - createDraftJob: vi.fn(async () => { + createDraftJobs: vi.fn(async () => { throw new Error('orig'); }), }); @@ -541,10 +566,11 @@ describe('runAutoDraft', () => { expect(moveBoundary).toHaveBeenLastCalledWith('u1', 'r1', 'c3', OLD); }); - // 웹훅 재전송 시뮬레이션: 작업 행·실패 행이 같은 (user, trigger_sha) 유일 인덱스를 나눠 씀 + // 웹훅 재전송 시뮬레이션: 작업 행·실패 행이 같은 (user, trigger_sha, draft_kind) 유일 인덱스를 나눠 씀 const redeliveryDeps = (commits: BranchCommit[]) => { let boundary = OLD; - const triggerShas = new Set(); + // `${trigger_sha}:${draft_kind}` + const triggerKeys = new Set(); const consumed = new Set(); const deps = makeDeps({ compare: vi.fn(async (_repo: unknown, base: string, head: string) => { @@ -567,24 +593,31 @@ describe('runAutoDraft', () => { return true; }, ), - createDraftJob: vi.fn( - async ( - _u: string, - _r: string, - request: { triggerSha: string | null; commitShas: string[] }, - ) => { - if (triggerShas.has(request.triggerSha as string)) { + createDraftJobs: vi.fn( + async (_u: string, _r: string, requests: DraftJobRequest[]) => { + const keys = requests.map((r) => `${r.triggerSha}:${r.draftKind}`); + // 한 트랜잭션: 하나라도 겹치면 아무것도 만들지 않음 + if (keys.some((key) => triggerKeys.has(key))) { return { status: 'duplicate' as const }; } - triggerShas.add(request.triggerSha as string); - for (const sha of request.commitShas) consumed.add(sha); - return { status: 'created' as const, draftId: 'd1', jobId: 'j1' }; + for (const key of keys) triggerKeys.add(key); + for (const sha of requests[0].commitShas) consumed.add(sha); + return { + status: 'created' as const, + jobs: requests.map((_, i) => ({ + draftId: `d${i + 1}`, + jobId: `j${i + 1}`, + })), + }; }, ), - recordFailure: vi.fn(async (record: { triggerSha: string }) => - triggerShas.has(record.triggerSha) - ? ('duplicate' as const) - : ('recorded' as const), + recordFailure: vi.fn( + async (record: { triggerSha: string; draftKind: string }) => { + const key = `${record.triggerSha}:${record.draftKind}`; + if (triggerKeys.has(key)) return 'duplicate' as const; + triggerKeys.add(key); + return 'recorded' as const; + }, ), }); return { deps, getBoundary: () => boundary }; @@ -596,7 +629,7 @@ describe('runAutoDraft', () => { expect(await runAutoDraft(target(), push('c3'), deps)).toEqual({ status: 'started', - jobId: 'j1', + jobIds: ['j1'], }); expect(getBoundary()).toBe('c3'); @@ -607,7 +640,7 @@ describe('runAutoDraft', () => { deps, ), ).toEqual({ status: 'duplicate' }); - expect(deps.createDraftJob).toHaveBeenCalledTimes(1); + expect(deps.createDraftJobs).toHaveBeenCalledTimes(1); expect(deps.recordFailure).toHaveBeenCalledWith( expect.objectContaining({ errorCode: 'no_commits', triggerSha: 'c3' }), ); @@ -630,18 +663,375 @@ describe('runAutoDraft', () => { status: 'duplicate', }); // 두 번째 계산은 c21~c25 만 묶음으로 봄 - expect(deps.createDraftJob).toHaveBeenLastCalledWith( + expect(deps.createDraftJobs).toHaveBeenLastCalledWith( 'u1', 'r1', - expect.objectContaining({ - commitShas: ['c25', 'c24', 'c23', 'c22', 'c21'], - }), + [ + expect.objectContaining({ + commitShas: ['c25', 'c24', 'c23', 'c22', 'c21'], + }), + ], 'en', ); // 남은 커밋을 끝까지 봐서 선점했다가 duplicate 로 되돌림 → 경계는 그대로 expect(getBoundary()).toBe(OLD); }); + it('재전송(comlog post log): 종류별 실패 행이 두 작업의 trigger_sha 와 충돌 → duplicate', async () => { + const commits = [commit(0), commit(1), commit(2), commit(3, '[comdraft]')]; + const { deps, getBoundary } = redeliveryDeps(commits); + const both = push('c3', { targets: { post: true, log: true } }); + + expect(await runAutoDraft(target({}, true), both, deps)).toEqual({ + status: 'started', + jobIds: ['j1', 'j2'], + }); + + expect( + await runAutoDraft( + target({ boundarySha: getBoundary() }, true), + both, + deps, + ), + ).toEqual({ status: 'duplicate' }); + expect(deps.createDraftJobs).toHaveBeenCalledTimes(1); + expect(deps.recordFailure).toHaveBeenCalledWith( + expect.objectContaining({ triggerSha: 'c3', draftKind: 'post' }), + ); + expect(deps.recordFailure).toHaveBeenCalledWith( + expect.objectContaining({ triggerSha: 'c3', draftKind: 'comlog' }), + ); + expect(deps.recordBacklog).not.toHaveBeenCalled(); + }); + + describe('comlog', () => { + const both = { targets: { post: true, log: true } }; + + it('comlog 켬 + [comdraft] → 회차 작업 하나, draftKind comlog, postType worklog, length short', async () => { + const deps = makeDeps(); + const out = await runAutoDraft( + target({}, true), + // 트리거의 톤·길이 단어는 회차에 쓰지 않음 + push('c3', { tone: 'friendly', length: 'long' }), + deps, + ); + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); + expect(deps.findConsumedShas).toHaveBeenCalledWith( + 'u1', + 'r1', + ['c1', 'c2', 'c3'], + 'comlog', + ); + expect(deps.createDraftJobs).toHaveBeenCalledWith( + 'u1', + 'r1', + [ + expect.objectContaining({ + draftKind: 'comlog', + commitShas: ['c3', 'c2', 'c1'], + triggerSha: 'c3', + source: 'commit_trigger', + boundaryClaimed: true, + options: { + ...DEFAULT_PROMPT_OPTIONS, + model: 'haiku', + postType: 'worklog', + length: 'short', + }, + }), + ], + 'en', + ); + expect(deps.startRunner).toHaveBeenCalledWith({ + jobId: 'j1', + githubToken: 'tok', + }); + }); + + it('comlog 켬 + post log → 같은 commitShas 로 작업 두 개, requests 길이 2 로 한 번 호출', async () => { + const deps = makeDeps(); + const out = await runAutoDraft( + target({}, true), + push('c3', { ...both, tone: 'friendly' }), + deps, + ); + expect(out).toEqual({ status: 'started', jobIds: ['j1', 'j2'] }); + expect(deps.findConsumedShas).toHaveBeenCalledWith( + 'u1', + 'r1', + ['c1', 'c2', 'c3'], + 'both', + ); + expect(deps.createDraftJobs).toHaveBeenCalledTimes(1); + const requests = vi.mocked(deps.createDraftJobs).mock.calls[0][2]; + expect(requests).toHaveLength(2); + expect(requests[0]).toMatchObject({ + draftKind: 'post', + commitShas: ['c3', 'c2', 'c1'], + triggerSha: 'c3', + boundaryClaimed: true, + options: { tone: 'friendly' }, + }); + expect(requests[1]).toMatchObject({ + draftKind: 'comlog', + commitShas: ['c3', 'c2', 'c1'], + triggerSha: 'c3', + boundaryClaimed: true, + options: { + tone: DEFAULT_PROMPT_OPTIONS.tone, + postType: 'worklog', + length: 'short', + }, + }); + expect(deps.startRunner).toHaveBeenCalledTimes(2); + expect(deps.moveBoundary).toHaveBeenCalledTimes(1); + }); + + it('comlog 끔 + post log → 일반 글 하나', async () => { + const deps = makeDeps(); + const out = await runAutoDraft(target(), push('c3', both), deps); + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); + expect(deps.createDraftJobs).toHaveBeenCalledWith( + 'u1', + 'r1', + [expect.objectContaining({ draftKind: 'post' })], + 'en', + ); + }); + + it('20개에서 잘린 회차 작업은 경계를 선점하지 않았으므로 boundaryClaimed false', async () => { + const commits = Array.from({ length: 25 }, (_, i) => commit(i + 1)); + const deps = makeDeps({ + compare: vi.fn(async () => ({ status: 'ok' as const, commits })), + }); + await runAutoDraft(target({}, true), push('c25'), deps); + expect(deps.createDraftJobs).toHaveBeenCalledWith( + 'u1', + 'r1', + [expect.objectContaining({ boundaryClaimed: false })], + 'en', + ); + }); + + it('createDraftJobs 가 too_many_active → 둘 다 없음, 종류별 실패 행 2개', async () => { + const deps = makeDeps({ + createDraftJobs: vi.fn(async () => ({ + status: 'too_many_active' as const, + })), + }); + const out = await runAutoDraft(target({}, true), push('c3', both), deps); + expect(out).toEqual({ status: 'skipped', errorCode: 'too_many_active' }); + expect(deps.startRunner).not.toHaveBeenCalled(); + expect(deps.recordFailure).toHaveBeenCalledTimes(2); + expect(deps.recordFailure).toHaveBeenCalledWith( + expect.objectContaining({ + draftKind: 'post', + errorCode: 'too_many_active', + }), + ); + expect(deps.recordFailure).toHaveBeenCalledWith( + expect.objectContaining({ + draftKind: 'comlog', + errorCode: 'too_many_active', + options: expect.objectContaining({ postType: 'worklog' }), + }), + ); + // 회차가 막혔으므로 밀린 커밋으로 남기고 경계는 푸시 끝 + expect(deps.recordBacklog).toHaveBeenCalledWith('u1', 'r1', [ + 'c1', + 'c2', + 'c3', + ]); + expect(deps.moveBoundary).toHaveBeenLastCalledWith('u1', 'r1', OLD, 'c3'); + }); + + const quotaGate = () => + vi.fn(async () => ({ + status: 'quota_exhausted' as const, + resetsAt: 'x', + })); + + it('회차 트리거가 quota_exceeded 로 막히면 범위 커밋 전부 backlog + 경계가 headSha 로', async () => { + const deps = makeDeps({ + gate: quotaGate(), + compare: vi.fn(async () => ({ + status: 'ok' as const, + commits: [ + commit(1), + commit(2), + commit(3, '[comdraft]'), + commit(4), + commit(5), + ], + })), + }); + const out = await runAutoDraft( + target({}, true), + push('c3', {}, 'c5'), + deps, + ); + expect(out).toEqual({ status: 'skipped', errorCode: 'quota_exceeded' }); + expect(deps.recordFailure).toHaveBeenCalledWith( + expect.objectContaining({ + draftKind: 'comlog', + errorCode: 'quota_exceeded', + }), + ); + expect(deps.compare).toHaveBeenCalledWith(expect.anything(), OLD, 'c5'); + expect(deps.recordBacklog).toHaveBeenCalledWith('u1', 'r1', [ + 'c1', + 'c2', + 'c3', + 'c4', + 'c5', + ]); + expect(deps.moveBoundary).toHaveBeenCalledTimes(1); + expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c5'); + expect(deps.createDraftJobs).not.toHaveBeenCalled(); + }); + + it('post log 가 quota_exceeded 로 막혀도 회차 쪽 커밋을 backlog 로 남김', async () => { + const deps = makeDeps({ gate: quotaGate() }); + await runAutoDraft(target({}, true), push('c3', both), deps); + expect(deps.recordFailure).toHaveBeenCalledTimes(2); + expect(deps.recordBacklog).toHaveBeenCalledWith('u1', 'r1', [ + 'c1', + 'c2', + 'c3', + ]); + expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c3'); + }); + + it('post 만인 트리거가 quota_exceeded → backlog 없음, 경계 그대로', async () => { + const deps = makeDeps({ gate: quotaGate() }); + const out = await runAutoDraft( + target({}, true), + push('c3', { targets: { post: true, log: false } }), + deps, + ); + expect(out).toEqual({ status: 'skipped', errorCode: 'quota_exceeded' }); + expect(deps.recordFailure).toHaveBeenCalledTimes(1); + expect(deps.recordFailure).toHaveBeenCalledWith( + expect.objectContaining({ draftKind: 'post' }), + ); + expect(deps.recordBacklog).not.toHaveBeenCalled(); + expect(deps.moveBoundary).not.toHaveBeenCalled(); + expect(deps.compare).not.toHaveBeenCalled(); + }); + + it('no_preset 으로 막힌 회차 트리거 → backlog 없음', async () => { + const deps = makeDeps(); + const out = await runAutoDraft( + target({ prompt: '' }, true), + push('c3'), + deps, + ); + expect(out).toEqual({ status: 'skipped', errorCode: 'no_preset' }); + expect(deps.recordBacklog).not.toHaveBeenCalled(); + expect(deps.moveBoundary).not.toHaveBeenCalled(); + }); + + it('github_reauth 로 막힌 회차 트리거 → backlog 없음', async () => { + const deps = makeDeps({ + gate: vi.fn(async () => ({ status: 'github_reauth' as const })), + }); + await runAutoDraft(target({}, true), push('c3'), deps); + expect(deps.recordBacklog).not.toHaveBeenCalled(); + expect(deps.moveBoundary).not.toHaveBeenCalled(); + }); + + it('25개 범위에서 막힘 → backlog 25개 (20개 제한 없음)', async () => { + const commits = Array.from({ length: 25 }, (_, i) => + commit(i + 1, i === 24 ? '[comdraft]' : undefined), + ); + const deps = makeDeps({ + gate: quotaGate(), + compare: vi.fn(async () => ({ status: 'ok' as const, commits })), + }); + await runAutoDraft(target({}, true), push('c25'), deps); + expect(deps.recordBacklog).toHaveBeenCalledWith( + 'u1', + 'r1', + commits.map((c) => c.sha), + ); + expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c25'); + }); + + it('막힌 뒤 범위 계산이 anchor_missing 이면 실패 행만 남김', async () => { + const deps = makeDeps({ + gate: quotaGate(), + compare: vi.fn(async () => ({ status: 'anchor_missing' as const })), + }); + const out = await runAutoDraft(target({}, true), push('c3'), deps); + expect(out).toEqual({ status: 'skipped', errorCode: 'quota_exceeded' }); + expect(deps.recordBacklog).not.toHaveBeenCalled(); + expect(deps.moveBoundary).not.toHaveBeenCalled(); + }); + + it('재전송으로 실패 행이 duplicate 면 backlog 를 남기지 않음', async () => { + const deps = makeDeps({ + gate: quotaGate(), + recordFailure: vi.fn(async () => 'duplicate' as const), + }); + const out = await runAutoDraft(target({}, true), push('c3'), deps); + expect(out).toEqual({ status: 'duplicate' }); + expect(deps.recordBacklog).not.toHaveBeenCalled(); + }); + + it('post log 중 회차 실행기 시작 실패 → 경계 유지, 회차 작업 runner_unavailable', async () => { + const deps = makeDeps({ + startRunner: vi.fn(async ({ jobId }: { jobId: string }) => { + if (jobId === 'j2') throw new Error('down'); + }), + }); + const out = await runAutoDraft(target({}, true), push('c3', both), deps); + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); + expect(deps.failJob).toHaveBeenCalledTimes(1); + expect(deps.failJob).toHaveBeenCalledWith('j2', 'runner_unavailable'); + // 선점만 하고 되돌리지 않음 + expect(deps.moveBoundary).toHaveBeenCalledTimes(1); + expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c3'); + expect(deps.recordFailure).not.toHaveBeenCalled(); + }); + + it('둘 다 시작 실패 → 경계 원위치', async () => { + const deps = makeDeps({ + startRunner: vi.fn(async () => { + throw new Error('down'); + }), + }); + const out = await runAutoDraft(target({}, true), push('c3', both), deps); + expect(out).toEqual({ + status: 'skipped', + errorCode: 'runner_unavailable', + }); + expect(deps.failJob).toHaveBeenCalledWith('j1', 'runner_unavailable'); + expect(deps.failJob).toHaveBeenCalledWith('j2', 'runner_unavailable'); + expect(deps.moveBoundary).toHaveBeenLastCalledWith('u1', 'r1', 'c3', OLD); + expect(deps.recordBacklog).not.toHaveBeenCalled(); + }); + + it('listExcludedShas 에 backlog 가 있으면 묶음에서 빠짐 (다음 트리거)', async () => { + const deps = makeDeps({ + listExcludedShas: vi.fn( + async () => + new Map([ + ['c1', 'backlog'], + ['c2', 'backlog'], + ]), + ), + }); + const out = await runAutoDraft(target({}, true), push('c3'), deps); + expect(out).toEqual({ status: 'started', jobIds: ['j1'] }); + expect(deps.createDraftJobs).toHaveBeenCalledWith( + 'u1', + 'r1', + [expect.objectContaining({ commitShas: ['c3'] })], + 'en', + ); + }); + }); + it('실패 기록이 duplicate 이면 duplicate', async () => { const deps = makeDeps({ recordFailure: vi.fn(async () => 'duplicate' as const), @@ -667,9 +1057,30 @@ describe('recordUnexpectedFailure', () => { prompt: '프리셋', options: expect.objectContaining({ length: 'long', model: 'haiku' }), locale: 'en', + draftKind: 'post', }); }); + it('comlog post log 면 종류마다 internal 실패 행', async () => { + const deps = makeDeps(); + await recordUnexpectedFailure( + target({}, true), + push('c3', { targets: { post: true, log: true } }), + deps, + ); + expect(deps.recordFailure).toHaveBeenCalledTimes(2); + expect(deps.recordFailure).toHaveBeenCalledWith( + expect.objectContaining({ errorCode: 'internal', draftKind: 'post' }), + ); + expect(deps.recordFailure).toHaveBeenCalledWith( + expect.objectContaining({ + errorCode: 'internal', + draftKind: 'comlog', + options: expect.objectContaining({ postType: 'worklog' }), + }), + ); + }); + it('이미 같은 트리거 행이 있으면(duplicate) 조용히 끝냄', async () => { const deps = makeDeps({ recordFailure: vi.fn(async () => 'duplicate' as const), diff --git a/lib/auto-draft/run.ts b/lib/auto-draft/run.ts index edb6c7f..8bf0843 100644 --- a/lib/auto-draft/run.ts +++ b/lib/auto-draft/run.ts @@ -7,17 +7,23 @@ import { getAutoDraftSetting, listExcludedShas, moveBoundary, + recordBacklog, type PushTarget, } from '@/lib/auto-draft/store'; -import { mergeTriggerOptions } from '@/lib/auto-draft/trigger'; +import { + consumedScopeFor, + mergeTriggerOptions, + resolveTriggerKinds, + type ConsumedScope, +} from '@/lib/auto-draft/trigger'; import type { TriggerPush } from '@/lib/auto-draft/webhook'; import { db } from '@/lib/db'; import { draftPrompt } from '@/lib/db/schema'; import type { GenerationErrorCode } from '@/lib/generation/contract'; import { checkGenerationGate, - createDraftJob, - type CreateDraftJobResult, + createDraftJobs, + type CreateDraftJobsResult, type DraftJobRequest, type GenerationGateResult, } from '@/lib/generation/draft-job'; @@ -25,7 +31,11 @@ import { getGenerationRunner } from '@/lib/generation/get-runner'; import { failJob, isTriggerDuplicateConflict } from '@/lib/generation/jobs'; import { isModelAllowed } from '@/lib/generation/models'; import { DEFAULT_LOCALE, isLocale, type Locale } from '@/lib/i18n/config'; -import type { PromptOptions } from '@/lib/studio/options'; +import { + applyDraftKindOptions, + type DraftKind, + type PromptOptions, +} from '@/lib/studio/options'; import { reportError } from '@/lib/observability/report-error'; /** @@ -37,10 +47,31 @@ import { reportError } from '@/lib/observability/report-error'; * - 20개에서 잘렸으면 경계를 옮기지 않음 (쓴 커밋은 consumed 로 다음 계산에서 빠짐) * - 다른 트리거가 먼저 경계를 옮겼거나 같은 커밋을 썼으면 지금 경계로 다시 계산 (최대 3번) * - 시작 전에 막힌 경우는 초안 없이 실패 행(draft_prompt)만 남김 (커밋 메시지는 저장하지 않음) + * + * comlog (설계 §6, §8) + * - 만들 초안 종류는 저장소의 comlog 사용 여부와 트리거 단어로 정함 (post / comlog / 둘 다) + * - 둘 다면 묶음 계산·경계 선점은 한 번, 같은 커밋과 트리거 SHA 로 작업 두 개를 한 트랜잭션에서 만듦 + * → 실행기는 각각 시작, 둘 다 시작하지 못했을 때만 경계를 되돌림 + * - 실패 행은 종류마다 남김 (종류별 유일 인덱스라 재전송은 duplicate) + * - 회차를 만들 트리거가 할당량·속도 제한 등으로 시작 전에 막히면 범위 커밋 전부(20개 제한 없음)를 + * 밀린 커밋(backlog)으로 남기고 경계를 푸시 끝으로 옮김 → 다음 트리거는 새 커밋만 씀 */ +// 회차 트리거가 막혔을 때 밀린 커밋으로 남기는 실패 사유 (할당량·속도 제한·AI 작성 중지) +// → 설정 문제나 할 일이 없는 경우(no_preset, anchor_missing, no_commits, model_locked 등)는 해당 없음 +export const BACKLOG_ERROR_CODES = [ + 'quota_exceeded', + 'quota_unavailable', + 'rate_limited', + 'too_many_active', + 'service_paused', +] as const satisfies readonly GenerationErrorCode[]; + +const isBacklogErrorCode = (code: GenerationErrorCode): boolean => + (BACKLOG_ERROR_CODES as readonly GenerationErrorCode[]).includes(code); + export type RunOutcome = - | { status: 'started'; jobId: string } + | { status: 'started'; jobIds: string[] } | { status: 'skipped'; errorCode: GenerationErrorCode } | { status: 'duplicate' }; @@ -53,6 +84,7 @@ export interface FailureRecord { prompt: string; options: PromptOptions; locale: Locale; + draftKind: DraftKind; } export interface RunDeps { @@ -64,12 +96,12 @@ export interface RunDeps { user: PushTarget['user'], headers: Headers | null, ) => Promise; - createDraftJob: ( + createDraftJobs: ( userId: string, repositoryId: string, - request: DraftJobRequest, + requests: DraftJobRequest[], locale: Locale, - ) => Promise; + ) => Promise; startRunner: (request: { jobId: string; githubToken: string; @@ -77,6 +109,8 @@ export interface RunDeps { failJob: (jobId: string, errorCode: GenerationErrorCode) => Promise; recordFailure: (record: FailureRecord) => Promise<'recorded' | 'duplicate'>; moveBoundary: typeof moveBoundary; + // 범위 커밋을 밀린 커밋(제외 사유 backlog)으로 남김 + recordBacklog: typeof recordBacklog; // 지금 경계 (설정 행이 없으면 null) getBoundary: (userId: string, repositoryId: string) => Promise; getLocale: (userId: string) => Promise; @@ -115,6 +149,7 @@ const insertFailure = async ( model: record.options.model, commitShas: [], locale: record.locale, + draftKind: record.draftKind, status: 'failed', errorCode: record.errorCode, finishedAt: new Date(), @@ -131,18 +166,20 @@ const insertFailure = async ( export const defaultRunDeps: RunDeps = { compare: (repo, base, head) => compareBranch(repo, base, head), findEmptyCommits: (repo, shas) => findEmptyCommits(repo, shas), - findConsumedShas: (userId, repositoryId, shas) => - findConsumedShas(userId, repositoryId, shas), + findConsumedShas: (userId, repositoryId, shas, scope) => + findConsumedShas(userId, repositoryId, shas, scope), listExcludedShas: (userId, repositoryId) => listExcludedShas(userId, repositoryId), gate: (user, headers) => checkGenerationGate(user, headers), - createDraftJob: (userId, repositoryId, request, locale) => - createDraftJob(userId, repositoryId, request, locale), + createDraftJobs: (userId, repositoryId, requests, locale) => + createDraftJobs(userId, repositoryId, requests, locale), startRunner: (request) => getGenerationRunner().start(request), failJob: (jobId, errorCode) => failJob(jobId, errorCode), recordFailure: insertFailure, moveBoundary: (userId, repositoryId, from, to) => moveBoundary(userId, repositoryId, from, to), + recordBacklog: (userId, repositoryId, shas) => + recordBacklog(userId, repositoryId, shas), getBoundary: async (userId, repositoryId) => (await getAutoDraftSetting(userId, repositoryId))?.boundarySha ?? null, getLocale: getLatestLocale, @@ -162,26 +199,78 @@ const slotErrorCode = ( return status === 'busy' ? 'too_many_active' : status; }; +// 트리거로 만들 작업 하나의 종류와 옵션 +interface PlannedKind { + kind: DraftKind; + options: PromptOptions; +} + +/** + * 종류별 옵션 + * - 일반 글: 저장소 기본 옵션 위에 트리거 단어(톤·글 종류·길이) + * - 회차: 저장소 기본 옵션에 고정 옵션(worklog·short), 트리거 단어는 쓰지 않음 + */ +const planKinds = (target: PushTarget, push: TriggerPush): PlannedKind[] => { + const base = target.setting.options; + + return resolveTriggerKinds( + target.comlogEnabled, + push.trigger.options.targets, + ).map((kind) => ({ + kind, + options: + kind === 'comlog' + ? // comlog 는 항상 옵션을 돌려줌 (null 은 일반 글의 worklog 뿐) + (applyDraftKindOptions('comlog', base) ?? base) + : mergeTriggerOptions(base, push.trigger.options), + })); +}; + +// 종류마다 실패 행을 남김 (하나라도 이미 있으면 재전송이라 duplicate) +const recordFailures = async ( + target: PushTarget, + push: TriggerPush, + plans: PlannedKind[], + errorCode: GenerationErrorCode, + locale: Locale, + deps: Pick, +): Promise<'recorded' | 'duplicate'> => { + let duplicate = false; + + for (const plan of plans) { + const recorded = await deps.recordFailure({ + userId: target.userId, + repositoryId: target.repositoryId, + triggerSha: push.trigger.sha, + errorCode, + prompt: target.setting.prompt, + options: plan.options, + locale, + draftKind: plan.kind, + }); + if (recorded === 'duplicate') duplicate = true; + } + + return duplicate ? 'duplicate' : 'recorded'; +}; + /** - * 실행 중 예상 밖 오류가 났을 때 internal 실패 행을 남김 (웹훅 after() 에서 호출) - * - 같은 트리거 SHA 의 행(작업 행이나 실패 행)이 이미 있으면 그대로 둠 + * 실행 중 예상 밖 오류가 났을 때 종류마다 internal 실패 행을 남김 (웹훅 after() 에서 호출) + * - 같은 트리거 SHA·종류의 행(작업 행이나 실패 행)이 이미 있으면 그대로 둠 */ export async function recordUnexpectedFailure( target: PushTarget, push: TriggerPush, deps: Pick = defaultRunDeps, ): Promise { - const { userId, repositoryId, setting } = target; - - await deps.recordFailure({ - userId, - repositoryId, - triggerSha: push.trigger.sha, - errorCode: 'internal', - prompt: setting.prompt, - options: mergeTriggerOptions(setting.options, push.trigger.options), - locale: await deps.getLocale(userId), - }); + await recordFailures( + target, + push, + planKinds(target, push), + 'internal', + await deps.getLocale(target.userId), + deps, + ); } export async function runAutoDraft( @@ -190,26 +279,39 @@ export async function runAutoDraft( deps: RunDeps = defaultRunDeps, ): Promise { const { userId, repositoryId, setting } = target; - const { trigger } = push; - const triggerSha = trigger.sha; - const options = mergeTriggerOptions(setting.options, trigger.options); + const plans = planKinds(target, push); + const kinds = plans.map((plan) => plan.kind); + const scope = consumedScopeFor(kinds); const locale = await deps.getLocale(userId); - // 시작 전 실패: 행을 남기고 결과로 변환 - const skip = async (errorCode: GenerationErrorCode): Promise => { - const recorded = await deps.recordFailure({ - userId, - repositoryId, - triggerSha, + /** + * 시작 전 실패: 종류마다 행을 남기고 결과로 변환 + * - backlogFrom: 막힌 시점의 경계 (회차가 할당량 등으로 막혔으면 여기서부터 밀린 커밋으로 남김) + */ + const skip = async ( + errorCode: GenerationErrorCode, + backlogFrom: string | null = null, + ): Promise => { + const recorded = await recordFailures( + target, + push, + plans, errorCode, - prompt: setting.prompt, - options, locale, - }); + deps, + ); + // 재전송이면 첫 실행이 이미 처리함 + if (recorded === 'duplicate') return { status: 'duplicate' }; + + if ( + backlogFrom !== null && + kinds.includes('comlog') && + isBacklogErrorCode(errorCode) + ) { + await recordRangeBacklog(target, push, deps, backlogFrom, scope); + } - return recorded === 'duplicate' - ? { status: 'duplicate' } - : { status: 'skipped', errorCode }; + return { status: 'skipped', errorCode }; }; if (setting.prompt.trim() === '') return skip('no_preset'); @@ -217,7 +319,9 @@ export async function runAutoDraft( if (setting.boundarySha === null) return skip('anchor_missing'); const gate = await deps.gate(target.user, null); - if (gate.status !== 'ok') return skip(gateErrorCode(gate.status)); + if (gate.status !== 'ok') { + return skip(gateErrorCode(gate.status), setting.boundarySha); + } // 모델은 커밋 옵션으로 바꿀 수 없음 if (!isModelAllowed(target.user.role, setting.options.model)) { @@ -231,12 +335,14 @@ export async function runAutoDraft( const result = await tryStartBatch(target, push, deps, { boundary, excluded, - options, + plans, + scope, locale, githubToken: gate.githubToken, }); - if (result.status === 'skip') return skip(result.errorCode); + // 작업을 못 만들었으면 선점한 경계는 이미 되돌렸으므로 지금 경계부터 밀린 커밋으로 봄 + if (result.status === 'skip') return skip(result.errorCode, boundary); if (result.status !== 'conflict') return result; // 다른 트리거가 먼저 경계를 옮기거나 커밋을 썼음 → 지금 경계로 다시 계산 @@ -248,13 +354,48 @@ export async function runAutoDraft( } } +/** + * 막힌 회차 트리거의 범위 커밋(경계 다음 ~ 푸시 끝, 20개 제한 없음)을 밀린 커밋으로 남기고 경계를 푸시 끝으로 + * - 범위를 계산하지 못하면(anchor_missing) 실패 행만 남긴 채 그대로 둠 + * - 경계는 막힌 시점 값일 때만 옮김 (그 사이 다른 트리거가 옮겼으면 그쪽을 따름) + */ +async function recordRangeBacklog( + target: PushTarget, + push: TriggerPush, + deps: RunDeps, + boundary: string, + scope: ConsumedScope, +): Promise { + const { userId, repositoryId } = target; + const plan = await computeAutoDraftBatch( + target.repo, + { + userId, + repositoryId, + boundarySha: boundary, + endSha: push.headSha, + excluded: await deps.listExcludedShas(userId, repositoryId), + consumedScope: scope, + limit: Infinity, + }, + deps, + ); + if (plan.status !== 'ok') return; + + if (plan.batchShas.length > 0) { + await deps.recordBacklog(userId, repositoryId, plan.batchShas); + } + await deps.moveBoundary(userId, repositoryId, boundary, push.headSha); +} + // 다른 트리거와 겹쳤을 때 묶음을 다시 계산하는 최대 횟수 const MAX_BATCH_ATTEMPTS = 3; interface BatchAttempt { boundary: string; excluded: ReadonlyMap; - options: PromptOptions; + plans: PlannedKind[]; + scope: ConsumedScope; locale: Locale; githubToken: string; } @@ -274,7 +415,7 @@ async function tryStartBatch( target: PushTarget, push: TriggerPush, deps: RunDeps, - { boundary, excluded, options, locale, githubToken }: BatchAttempt, + { boundary, excluded, plans, scope, locale, githubToken }: BatchAttempt, ): Promise { const { userId, repositoryId, setting } = target; const plan = await computeAutoDraftBatch( @@ -285,6 +426,7 @@ async function tryStartBatch( boundarySha: boundary, endSha: push.headSha, excluded, + consumedScope: scope, }, deps, ); @@ -314,24 +456,27 @@ async function tryStartBatch( } }; - let created: CreateDraftJobResult; + // 종류마다 같은 커밋(최신순)·트리거 SHA 로 요청 + const commitShas = [...batchShas].reverse(); + const requests: DraftJobRequest[] = plans.map(({ kind, options }) => ({ + prompt: setting.prompt, + options, + commitShas, + codeInputs: [], + referenceUrls: [], + draftId: null, + source: 'commit_trigger', + triggerSha: push.trigger.sha, + draftKind: kind, + boundaryClaimed: claimTo !== null, + })); + + let created: CreateDraftJobsResult; try { - created = await deps.createDraftJob( + created = await deps.createDraftJobs( userId, repositoryId, - { - prompt: setting.prompt, - options, - // 최신순 - commitShas: [...batchShas].reverse(), - codeInputs: [], - referenceUrls: [], - draftId: null, - source: 'commit_trigger', - triggerSha: push.trigger.sha, - draftKind: 'post', - boundaryClaimed: false, - }, + requests, locale, ); } catch (error) { @@ -351,20 +496,34 @@ async function tryStartBatch( return { status: 'skip', errorCode: slotErrorCode(created.status) }; } - try { - await deps.startRunner({ jobId: created.jobId, githubToken }); - } catch (error) { - reportError(error, 'auto-draft.start-runner', { - jobId: created.jobId, - repositoryId, - }); - // 작업 행이 이미 있으므로 실패 행을 따로 남기지 않음 - // 경계를 먼저 되돌려 failJob 이 실패해도 항상 복구 - await revert(); - await deps.failJob(created.jobId, 'runner_unavailable'); + const jobIds = created.jobs.map((job) => job.jobId); + const failedJobIds: string[] = []; + + for (const jobId of jobIds) { + try { + await deps.startRunner({ jobId, githubToken }); + } catch (error) { + reportError(error, 'auto-draft.start-runner', { jobId, repositoryId }); + failedJobIds.push(jobId); + } + } + // 하나도 시작하지 못했을 때만 경계를 되돌림 (하나라도 시작했으면 그 작업이 커밋을 쓰고 있음) + // 경계를 먼저 되돌려 failJob 이 실패해도 항상 복구 + const noneStarted = failedJobIds.length === jobIds.length; + if (noneStarted) await revert(); + + // 작업 행이 이미 있으므로 실패 행을 따로 남기지 않음 + for (const jobId of failedJobIds) { + await deps.failJob(jobId, 'runner_unavailable'); + } + + if (noneStarted) { return { status: 'skipped', errorCode: 'runner_unavailable' }; } - return { status: 'started', jobId: created.jobId }; + return { + status: 'started', + jobIds: jobIds.filter((jobId) => !failedJobIds.includes(jobId)), + }; } diff --git a/lib/auto-draft/store.test.ts b/lib/auto-draft/store.test.ts new file mode 100644 index 0000000..adfe527 --- /dev/null +++ b/lib/auto-draft/store.test.ts @@ -0,0 +1,42 @@ +import { PgDialect } from 'drizzle-orm/pg-core'; +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('@lingui/core/macro', () => ({ msg: (id: unknown) => id })); +vi.mock('server-only', () => ({})); +vi.mock('@/lib/db', () => ({ db: {} })); +vi.mock('@/lib/auto-draft/github', () => ({})); + +import { consumedScopeCondition } from '@/lib/auto-draft/store'; + +// 조건을 값이 채워진 SQL 문자열로 +const render = (scope: Parameters[0]) => { + const { sql, params } = new PgDialect().sqlToQuery( + consumedScopeCondition(scope), + ); + return sql.replace( + /\$(\d+)/g, + (_, index) => `'${params[Number(index) - 1]}'`, + ); +}; + +describe('consumedScopeCondition', () => { + it('post_trigger: 자동 초안 출처의 일반 글 작업만', () => { + const sql = render('post_trigger'); + expect(sql).toContain(`"source" = 'commit_trigger'`); + expect(sql).toContain(`"draft_kind" = 'post'`); + expect(sql).not.toContain(`'comlog'`); + }); + + it('comlog: 출처와 상관없이 회차 작업', () => { + const sql = render('comlog'); + expect(sql).toContain(`"draft_kind" = 'comlog'`); + expect(sql).not.toContain('"source"'); + }); + + it('both: 두 조건의 합', () => { + const sql = render('both'); + expect(sql).toContain(' or '); + expect(sql).toContain(`"draft_kind" = 'post'`); + expect(sql).toContain(`"draft_kind" = 'comlog'`); + }); +}); diff --git a/lib/auto-draft/store.ts b/lib/auto-draft/store.ts index cd6c744..73a4d8f 100644 --- a/lib/auto-draft/store.ts +++ b/lib/auto-draft/store.ts @@ -1,11 +1,22 @@ import 'server-only'; -import { and, arrayOverlaps, eq, inArray, isNull, sql } from 'drizzle-orm'; +import { + and, + arrayOverlaps, + eq, + inArray, + isNull, + or, + sql, + type SQL, +} from 'drizzle-orm'; import type { ExcludedCommitReason } from '@/lib/db/schema/auto-draft'; import type { DraftPromptStatus } from '@/lib/db/schema/draft'; import { getBranchHead, type AutoDraftRepo } from '@/lib/auto-draft/github'; +import type { ConsumedScope } from '@/lib/auto-draft/trigger'; import { db } from '@/lib/db'; import { account, + comlogProject, draftPrompt, githubInstallation, githubRepository, @@ -47,6 +58,8 @@ export interface PushTarget { githubAccountId: string; user: { id: string; role: string; bannedAt: Date | null }; repo: AutoDraftRepo; + // 이 저장소에 comlog 를 켰는지 (트리거가 만들 초안 종류를 정함) + comlogEnabled: boolean; setting: { prompt: string; options: PromptOptions; @@ -275,14 +288,34 @@ const CONSUMING_STATUSES: DraftPromptStatus[] = [ ]; /** - * 주어진 SHA 중 이 사용자·저장소의 이전 자동 초안(commit_trigger) 작업에 이미 쓴 것 - * - 진행 중·되묻기·완료 작업만 (실패한 작업은 커밋을 놓아줌), 스키마 변경 없이 commit_shas 로 판정 + * 사용됨 범위별 작업 행 조건 (상태·초안 작성 작업 조건은 findConsumedShas 가 함께 씀) + * - post_trigger: 일반 글 자동 초안(commit_trigger) 작업 (지금 규칙) + * - comlog: 회차 작업 (트리거·스튜디오 직접 모두) + * - both: 둘의 합 + */ +export function consumedScopeCondition(scope: ConsumedScope): SQL { + const postTrigger = and( + eq(draftPrompt.source, 'commit_trigger'), + eq(draftPrompt.draftKind, 'post'), + ) as SQL; + const comlog = eq(draftPrompt.draftKind, 'comlog'); + + if (scope === 'post_trigger') return postTrigger; + if (scope === 'comlog') return comlog; + return or(postTrigger, comlog) as SQL; +} + +/** + * 주어진 SHA 중 이 사용자·저장소의 이전 작업에 이미 쓴 것 (범위는 consumedScopeCondition) + * - 진행 중·되묻기·완료 작업만 (실패한 작업은 커밋을 놓아줌), commit_shas 로 판정 + * - 초안 작성 작업(kind = 'draft')만 셈 (빈칸 채우기 작업은 draft_kind 가 기본값 post 라 섞이면 안 됨) * - 범위 SHA 와 겹치는 행만 읽어 쌓인 이력 전체를 보지 않음 */ export async function findConsumedShas( userId: string, repositoryId: string, shas: string[], + scope: ConsumedScope, // 작업 생성 트랜잭션 안에서 다시 확인할 때는 그 트랜잭션 executor: typeof db | JobTransaction = db, ): Promise> { @@ -295,7 +328,8 @@ export async function findConsumedShas( and( eq(draftPrompt.userId, userId), eq(draftPrompt.repositoryId, repositoryId), - eq(draftPrompt.source, 'commit_trigger'), + eq(draftPrompt.kind, 'draft'), + consumedScopeCondition(scope), inArray(draftPrompt.status, CONSUMING_STATUSES), arrayOverlaps(draftPrompt.commitShas, shas), ), @@ -322,6 +356,15 @@ export async function excludeCommits( .onConflictDoNothing(); } +// 회차를 만들지 못해 밀린 커밋으로 남김 (이미 제외 목록에 있으면 그 사유를 그대로 둠) +export async function recordBacklog( + userId: string, + repositoryId: string, + shas: string[], +): Promise { + await excludeCommits(userId, repositoryId, shas, 'backlog'); +} + // 제외한 커밋을 다시 대상으로 되돌림 export async function restoreCommit( userId: string, @@ -339,6 +382,19 @@ export async function restoreCommit( ); } +// GitHub 저장소 id 로 등록된 저장소 행 id (등록되지 않았으면 null) +export async function findRepositoryIdByGithubRepoId( + githubRepoId: number, +): Promise { + const [row] = await db + .select({ id: githubRepository.id }) + .from(githubRepository) + .where(eq(githubRepository.githubRepoId, githubRepoId)) + .limit(1); + + return row?.id ?? null; +} + // push 된 저장소·브랜치를 추적하면서 자동 초안이 켜진 연결 export async function findPushTargets( githubRepoId: number, @@ -362,6 +418,7 @@ export async function findPushTargets( requiredBlocks: repositoryAutoDraft.requiredBlocks, model: repositoryAutoDraft.model, boundarySha: repositoryAutoDraft.boundarySha, + comlogEnabled: comlogProject.enabled, }) .from(userRepository) .innerJoin( @@ -380,6 +437,14 @@ export async function findPushTargets( ), ) .innerJoin(user, eq(user.id, userRepository.userId)) + // comlog 프로젝트 행이 없으면 꺼진 것 + .leftJoin( + comlogProject, + and( + eq(comlogProject.userId, userRepository.userId), + eq(comlogProject.repositoryId, userRepository.repositoryId), + ), + ) .innerJoin( account, and(eq(account.userId, user.id), eq(account.providerId, 'github')), @@ -403,6 +468,7 @@ export async function findPushTargets( name: row.name, branch: row.branch, }, + comlogEnabled: row.comlogEnabled === true, setting: { prompt: row.prompt, options: toOptions(row), diff --git a/lib/auto-draft/trigger.test.ts b/lib/auto-draft/trigger.test.ts index 44900bd..d45763a 100644 --- a/lib/auto-draft/trigger.test.ts +++ b/lib/auto-draft/trigger.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest'; import { DEFAULT_PROMPT_OPTIONS } from '@/lib/studio/options'; import { + consumedScopeFor, mergeTriggerOptions, parseTrigger, resolveTriggerKinds, @@ -107,6 +108,14 @@ describe('resolveTriggerKinds', () => { }); }); +describe('consumedScopeFor', () => { + it('만들 종류에 맞는 사용됨 범위', () => { + expect(consumedScopeFor(['post'])).toBe('post_trigger'); + expect(consumedScopeFor(['comlog'])).toBe('comlog'); + expect(consumedScopeFor(['post', 'comlog'])).toBe('both'); + }); +}); + describe('mergeTriggerOptions', () => { it('트리거에 지정된 값만 바꾼다', () => { const merged = mergeTriggerOptions(DEFAULT_PROMPT_OPTIONS, { diff --git a/lib/auto-draft/trigger.ts b/lib/auto-draft/trigger.ts index 0ba6e73..c12ed22 100644 --- a/lib/auto-draft/trigger.ts +++ b/lib/auto-draft/trigger.ts @@ -82,3 +82,19 @@ export function resolveTriggerKinds( if (!targets.post) return ['comlog']; return targets.log ? ['post', 'comlog'] : ['post']; } + +/** + * 묶음에서 건너뛸 "사용됨" 커밋을 셀 범위 (설계 §8.1) + * - post_trigger: 일반 글 자동 초안 작업에 쓴 커밋 (지금 규칙) + * - comlog: 회차 작업에 쓴 커밋 (트리거든 스튜디오 직접이든) + * - both: 둘의 합 (post log 는 같은 묶음으로 두 작업을 만듦) + */ +export type ConsumedScope = 'post_trigger' | 'comlog' | 'both'; + +// 트리거가 만들 초안 종류 → 사용됨 범위 +export function consumedScopeFor(kinds: readonly DraftKind[]): ConsumedScope { + const post = kinds.includes('post'); + const comlog = kinds.includes('comlog'); + if (post && comlog) return 'both'; + return comlog ? 'comlog' : 'post_trigger'; +} diff --git a/lib/auto-draft/webhook.test.ts b/lib/auto-draft/webhook.test.ts index 1b352b7..66fe641 100644 --- a/lib/auto-draft/webhook.test.ts +++ b/lib/auto-draft/webhook.test.ts @@ -58,7 +58,7 @@ const payload = { after: HEAD, forced: false, sender: { id: 42 }, - repository: { id: 7 }, + repository: { id: 7, private: true }, commits: [{ id: 'a1', message: 'feat: x' }], }; @@ -70,10 +70,25 @@ describe('parsePushEvent', () => { forced: false, senderId: 42, repositoryId: 7, + repositoryPrivate: true, commits: [{ id: 'a1', message: 'feat: x' }], }); }); + it('repository.private 가 없거나 boolean 이 아니면 null (푸시 처리는 계속)', () => { + expect( + parsePushEvent({ ...payload, repository: { id: 7 } })?.repositoryPrivate, + ).toBeNull(); + expect( + parsePushEvent({ ...payload, repository: { id: 7, private: 'yes' } }) + ?.repositoryPrivate, + ).toBeNull(); + expect( + parsePushEvent({ ...payload, repository: { id: 7, private: false } }) + ?.repositoryPrivate, + ).toBe(false); + }); + it('commits 가 빈 배열이어도 파싱', () => { expect(parsePushEvent({ ...payload, commits: [] })?.commits).toEqual([]); }); @@ -112,6 +127,7 @@ function event(overrides: Partial = {}): PushEvent { forced: false, senderId: 42, repositoryId: 7, + repositoryPrivate: false, commits: [{ id: 'a1', message: '[comdraft] short' }], ...overrides, }; diff --git a/lib/auto-draft/webhook.ts b/lib/auto-draft/webhook.ts index da4863e..2a97ee6 100644 --- a/lib/auto-draft/webhook.ts +++ b/lib/auto-draft/webhook.ts @@ -11,6 +11,8 @@ export interface PushEvent { forced: boolean; senderId: number; repositoryId: number; + // 저장소 공개 여부 (페이로드에 없거나 형식이 다르면 null → 갱신하지 않음) + repositoryPrivate: boolean | null; commits: Array<{ id: string; message: string }>; } @@ -85,6 +87,8 @@ export function parsePushEvent(payload: unknown): PushEvent | null { forced, senderId: sender.id, repositoryId: repository.id, + repositoryPrivate: + typeof repository.private === 'boolean' ? repository.private : null, commits: parsed, }; } diff --git a/lib/generation/draft-job.ts b/lib/generation/draft-job.ts index 691a2de..1b0c908 100644 --- a/lib/generation/draft-job.ts +++ b/lib/generation/draft-job.ts @@ -2,6 +2,7 @@ import 'server-only'; import { asc, eq } from 'drizzle-orm'; import { getAiGenerationSetting } from '@/lib/admin/service-setting'; import { findConsumedShas } from '@/lib/auto-draft/store'; +import { consumedScopeFor } from '@/lib/auto-draft/trigger'; import { db } from '@/lib/db'; import { draft, @@ -16,6 +17,7 @@ import { isActiveJobConflict, isTriggerDuplicateConflict, reserveGenerationSlot, + type JobTransaction, } from '@/lib/generation/jobs'; import { getUserQuota } from '@/lib/generation/quota-queries'; import { @@ -65,7 +67,7 @@ export interface DraftJobRequest extends ParsedRequest { // 초안 작업 만들기 결과 // - duplicate: 같은 트리거 SHA 로 이미 만듦 -// - overlap: 자동 초안 커밋 중 일부를 다른 자동 초안이 먼저 씀 (묶음을 다시 계산해야 함) +// - overlap: 자동 초안 커밋 중 일부를 다른 작업이 먼저 씀 (묶음을 다시 계산해야 함) export type CreateDraftJobResult = | CreateJobResult<{ draftId: string; @@ -74,99 +76,175 @@ export type CreateDraftJobResult = | { status: 'duplicate' } | { status: 'overlap' }; +// 여러 작업을 한꺼번에 만든 결과 (jobs 는 요청 순서 그대로) +export type CreateDraftJobsResult = + | CreateJobResult<{ + jobs: Array<{ draftId: string; jobId: string }>; + }> + | { status: 'duplicate' } + | { status: 'overlap' }; + +// 요청 하나에 붙인 새 id (기존 초안이면 그 id) +interface PlannedJob { + request: DraftJobRequest; + draftId: string; + jobId: string; +} + +/** + * 자동 초안 요청의 커밋이 이미 다른 작업에 쓰였는지 (사용자 잠금을 잡은 트랜잭션 안에서) + * - 범위는 만들 초안 종류로 정함 (post log 면 두 범위의 합) + * - 스튜디오 요청은 확인하지 않음 (지금 동작 유지) + */ +const hasTriggerOverlap = async ( + tx: JobTransaction, + userId: string, + repositoryId: string, + requests: DraftJobRequest[], +): Promise => { + const triggered = requests.filter( + (request) => request.source === 'commit_trigger', + ); + + if (triggered.length === 0) return false; + + const shas = [...new Set(triggered.flatMap((request) => request.commitShas))]; + const scope = consumedScopeFor(triggered.map((request) => request.draftKind)); + const consumed = await findConsumedShas( + userId, + repositoryId, + shas, + scope, + tx, + ); + + return consumed.size > 0; +}; + +// 작업 하나 INSERT (새 초안이면 초안과 참고 링크도 함께) +const insertDraftJob = async ( + tx: JobTransaction, + userId: string, + repositoryId: string, + { request, draftId, jobId }: PlannedJob, + locale: Locale, +): Promise => { + // 요청 시점의 참고 링크 (작성기는 이 목록만 읽음) + let referenceUrls = request.referenceUrls; + + if (request.draftId) { + // 최근 수정순 목록의 맨 위로 올림 + await tx + .update(draft) + .set({ updatedAt: new Date() }) + .where(eq(draft.id, draftId)); + + const links = await tx + .select({ url: draftReferenceLink.url }) + .from(draftReferenceLink) + .where(eq(draftReferenceLink.draftId, draftId)) + .orderBy(asc(draftReferenceLink.createdAt), asc(draftReferenceLink.id)); + referenceUrls = links.map((link) => link.url); + } else { + await tx.insert(draft).values({ + id: draftId, + userId, + repositoryId, + kind: request.draftKind, + }); + + if (request.referenceUrls.length > 0) { + await tx.insert(draftReferenceLink).values( + request.referenceUrls.map((url) => ({ + id: crypto.randomUUID(), + draftId, + url, + })), + ); + } + } + + await tx.insert(draftPrompt).values({ + id: jobId, + userId, + draftId, + prompt: request.prompt, + tone: request.options.tone, + postType: request.options.postType, + length: request.options.length, + requiredBlocks: request.options.requiredBlocks, + model: request.options.model, + commitShas: request.commitShas, + // 이름·줄 수만 저장 (코드 원문은 작성기 요청 본문으로만 보냄) + codeInputs: toCodeInputMeta(request.codeInputs), + referenceUrls, + locale, + repositoryId, + source: request.source, + triggerSha: request.triggerSha, + draftKind: request.draftKind, + boundaryClaimed: request.boundaryClaimed, + }); +}; + +// 한 트리거로 함께 만든 새 초안 두 개를 서로 짝으로 연결 (post log, 상세 페이지 링크용) +const pairNewDrafts = async ( + tx: JobTransaction, + planned: PlannedJob[], +): Promise => { + const created = planned.filter(({ request }) => request.draftId === null); + + if (created.length !== 2) return; + + const [first, second] = created; + await tx + .update(draft) + .set({ pairedDraftId: second.draftId }) + .where(eq(draft.id, first.draftId)); + await tx + .update(draft) + .set({ pairedDraftId: first.draftId }) + .where(eq(draft.id, second.draftId)); +}; + /** - * 작업(queued)을 만들고 초안 id 와 작업 id 반환 (새 초안이면 초안과 참고 링크도 함께 생성) - * - 같은 트랜잭션에서 사용자 잠금을 잡고 시간당 요청 수·동시 진행 수를 센 뒤 INSERT + * 작업(queued) 여러 개를 한 트랜잭션에서 만들고 초안 id 와 작업 id 반환 (요청 순서) + * - 사용자 잠금을 잡고 시간당 요청 수·동시 진행 수가 요청 수만큼 남았는지 센 뒤 INSERT * (한도에 걸리면 아무것도 만들지 않고 rate_limited·too_many_active) * - 같은 초안에 진행 중인 작업이 있으면 유일 인덱스에 걸려 'busy' - * - 같은 트리거 SHA 로 이미 만든 작업이 있으면 유일 인덱스에 걸려 'duplicate' - * - 자동 초안은 사용자 잠금을 잡은 뒤 커밋이 이미 다른 자동 초안에 쓰였는지 다시 확인해 'overlap' + * - 같은 트리거 SHA·종류로 이미 만든 작업이 있으면 유일 인덱스에 걸려 'duplicate' (하나라도 걸리면 전부 취소) + * - 자동 초안은 사용자 잠금을 잡은 뒤 커밋이 이미 다른 작업에 쓰였는지 다시 확인해 'overlap' * (거의 동시에 온 두 트리거가 같은 커밋 묶음으로 초안을 두 번 만들지 않게) */ -export const createDraftJob = async ( +export const createDraftJobs = async ( userId: string, repositoryId: string, - request: DraftJobRequest, + requests: DraftJobRequest[], locale: Locale, -): Promise => { - const draftId = request.draftId ?? crypto.randomUUID(); - const jobId = crypto.randomUUID(); +): Promise => { + const planned: PlannedJob[] = requests.map((request) => ({ + request, + draftId: request.draftId ?? crypto.randomUUID(), + jobId: crypto.randomUUID(), + })); try { const slot = await db.transaction(async (tx) => { - const reserved = await reserveGenerationSlot(tx, userId); + const reserved = await reserveGenerationSlot(tx, userId, requests.length); if (reserved !== 'ok') { return reserved; } - if ( - request.source === 'commit_trigger' && - (await findConsumedShas(userId, repositoryId, request.commitShas, tx)) - .size > 0 - ) { + if (await hasTriggerOverlap(tx, userId, repositoryId, requests)) { return 'overlap'; } - // 요청 시점의 참고 링크 (작성기는 이 목록만 읽음) - let referenceUrls = request.referenceUrls; - - if (request.draftId) { - // 최근 수정순 목록의 맨 위로 올림 - await tx - .update(draft) - .set({ updatedAt: new Date() }) - .where(eq(draft.id, draftId)); - - const links = await tx - .select({ url: draftReferenceLink.url }) - .from(draftReferenceLink) - .where(eq(draftReferenceLink.draftId, draftId)) - .orderBy( - asc(draftReferenceLink.createdAt), - asc(draftReferenceLink.id), - ); - referenceUrls = links.map((link) => link.url); - } else { - await tx.insert(draft).values({ - id: draftId, - userId, - repositoryId, - kind: request.draftKind, - }); - - if (request.referenceUrls.length > 0) { - await tx.insert(draftReferenceLink).values( - request.referenceUrls.map((url) => ({ - id: crypto.randomUUID(), - draftId, - url, - })), - ); - } + for (const job of planned) { + await insertDraftJob(tx, userId, repositoryId, job, locale); } - await tx.insert(draftPrompt).values({ - id: jobId, - userId, - draftId, - prompt: request.prompt, - tone: request.options.tone, - postType: request.options.postType, - length: request.options.length, - requiredBlocks: request.options.requiredBlocks, - model: request.options.model, - commitShas: request.commitShas, - // 이름·줄 수만 저장 (코드 원문은 작성기 요청 본문으로만 보냄) - codeInputs: toCodeInputMeta(request.codeInputs), - referenceUrls, - locale, - repositoryId, - source: request.source, - triggerSha: request.triggerSha, - draftKind: request.draftKind, - boundaryClaimed: request.boundaryClaimed, - }); + await pairNewDrafts(tx, planned); return reserved; }); @@ -186,7 +264,28 @@ export const createDraftJob = async ( throw error; } - return { status: 'created', draftId, jobId }; + return { + status: 'created', + jobs: planned.map(({ draftId, jobId }) => ({ draftId, jobId })), + }; +}; + +// 작업 하나 만들기 (createDraftJobs 의 1개짜리, 스튜디오 요청용) +export const createDraftJob = async ( + userId: string, + repositoryId: string, + request: DraftJobRequest, + locale: Locale, +): Promise => { + const result = await createDraftJobs(userId, repositoryId, [request], locale); + + if (result.status !== 'created') { + return result; + } + + const [job] = result.jobs; + + return { status: 'created', ...job }; }; // 작업을 만들기 전 사용자 단위 검사 결과 (통과하면 실행기에 넘길 GitHub 토큰) diff --git a/lib/generation/jobs.test.ts b/lib/generation/jobs.test.ts index 80d09fd..d6c7cbe 100644 --- a/lib/generation/jobs.test.ts +++ b/lib/generation/jobs.test.ts @@ -126,6 +126,14 @@ describe('reserveGenerationSlot', () => { ); }); + it('자리를 여러 개 요청하면 그 수만큼 남아야 함', async () => { + const { tx } = setupTx([1, 0]); + + await expect( + jobs.reserveGenerationSlot(tx as never, 'u1', 2), + ).resolves.toBe('too_many_active'); + }); + it('시간당 요청 수가 한도면 rate_limited', async () => { const { tx } = setupTx([0, 20]); diff --git a/lib/generation/jobs.ts b/lib/generation/jobs.ts index 7a3d973..4703156 100644 --- a/lib/generation/jobs.ts +++ b/lib/generation/jobs.ts @@ -695,6 +695,8 @@ const lockAndCountActiveJobs = async ( export const reserveGenerationSlot = async ( tx: JobTransaction, userId: string, + // 한꺼번에 만들 작업 수 (자리가 이만큼 남아야 ok) + required = 1, now = new Date(), ): Promise => { const activeJobs = await lockAndCountActiveJobs(tx, userId); @@ -711,7 +713,7 @@ export const reserveGenerationSlot = async ( ), ); - return decideGenerationSlot({ recentJobs, activeJobs }); + return decideGenerationSlot({ recentJobs, activeJobs, required }); }; // 유일 인덱스(constraint) 위반 오류인지 (오류 자신 또는 cause 가 23505) diff --git a/lib/generation/slot.test.ts b/lib/generation/slot.test.ts index 95783e4..bc08958 100644 --- a/lib/generation/slot.test.ts +++ b/lib/generation/slot.test.ts @@ -41,6 +41,26 @@ describe('decideGenerationSlot', () => { ); }); + it('한 번에 여러 작업을 만들면 그 수만큼 자리가 남아야 함', () => { + expect( + decideGenerationSlot({ recentJobs: 0, activeJobs: 0, required: 2 }), + ).toBe('ok'); + expect( + decideGenerationSlot({ + recentJobs: 0, + activeJobs: MAX_ACTIVE_GENERATIONS - 1, + required: 2, + }), + ).toBe('too_many_active'); + expect( + decideGenerationSlot({ + recentJobs: GENERATION_HOURLY_LIMIT - 1, + activeJobs: 0, + required: 2, + }), + ).toBe('rate_limited'); + }); + it('둘 다 넘으면 시간당 제한을 먼저 알림', () => { expect( decideGenerationSlot({ diff --git a/lib/generation/slot.ts b/lib/generation/slot.ts index f323feb..0f5dbd8 100644 --- a/lib/generation/slot.ts +++ b/lib/generation/slot.ts @@ -11,21 +11,24 @@ export interface GenerationSlotCounts { recentJobs: number; // 진행 중(queued·running) 작업 수 activeJobs: number; + // 이번에 한꺼번에 만들 작업 수 (커밋 트리거 post log 는 2, 기본 1) + required?: number; } -// 진행 중 작업이 한도 아래라 하나 더 시작할 수 있는지 (새 작업·되묻기 재개 공통) -export const hasActiveCapacity = (activeJobs: number) => - activeJobs < MAX_ACTIVE_GENERATIONS; +// 진행 중 작업이 한도 아래라 required 개를 더 시작할 수 있는지 (새 작업·되묻기 재개 공통) +export const hasActiveCapacity = (activeJobs: number, required = 1) => + activeJobs + required <= MAX_ACTIVE_GENERATIONS; export const decideGenerationSlot = ({ recentJobs, activeJobs, + required = 1, }: GenerationSlotCounts): GenerationSlotStatus => { - if (recentJobs >= GENERATION_HOURLY_LIMIT) { + if (recentJobs + required > GENERATION_HOURLY_LIMIT) { return 'rate_limited'; } - if (!hasActiveCapacity(activeJobs)) { + if (!hasActiveCapacity(activeJobs, required)) { return 'too_many_active'; } From 527ff3995ba3427d3b2197c73dfa80ecb928943c Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 16:02:16 +0900 Subject: [PATCH 08/27] =?UTF-8?q?fix(posts):=20=EA=B2=8C=EC=8B=9C=EA=B8=80?= =?UTF-8?q?=20=EB=AA=A9=EB=A1=9D=C2=B7=EC=82=AC=EC=9D=B4=ED=8A=B8=EB=A7=B5?= =?UTF-8?q?=C2=B7=EC=83=81=EC=84=B8=C2=B7=EA=B4=80=EB=A6=AC=EC=9E=90=20?= =?UTF-8?q?=EC=A7=91=EA=B3=84=EC=97=90=EC=84=9C=20comlog=20=ED=9A=8C?= =?UTF-8?q?=EC=B0=A8=20=EC=A0=9C=EC=99=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/admin/post-queries.ts | 5 +++++ lib/admin/stats-queries.ts | 6 +++++- lib/admin/user-queries.ts | 6 +++++- lib/posts/kind.test.ts | 29 +++++++++++++++++++++++++++++ lib/posts/kind.ts | 16 ++++++++++++++++ lib/posts/moderation.test.ts | 12 ++++++++++++ lib/posts/queries.ts | 12 ++++++++++-- lib/posts/views.ts | 7 +++++-- lib/studio/queries.ts | 7 +++++++ 9 files changed, 94 insertions(+), 6 deletions(-) create mode 100644 lib/posts/kind.test.ts create mode 100644 lib/posts/kind.ts diff --git a/lib/admin/post-queries.ts b/lib/admin/post-queries.ts index a94f51d..fa2d2ac 100644 --- a/lib/admin/post-queries.ts +++ b/lib/admin/post-queries.ts @@ -15,6 +15,7 @@ import { adminAccount, adminActionLog } from '@/lib/db/schema/admin'; import { user } from '@/lib/db/schema/auth'; import { post, postView, POST_VISIBILITIES } from '@/lib/db/schema/post'; import type { PostVisibility } from '@/lib/db/schema/post'; +import { adminKindCondition, type AdminPostKindFilter } from '@/lib/posts/kind'; import { LOCALES } from '@/lib/i18n/config'; import type { Locale } from '@/lib/i18n/config'; @@ -26,6 +27,8 @@ const DETAIL_ACTION_LIMIT = 20; export interface PostListFilters { q: string; + // 게시글 종류 (생략하면 일반 게시글만, 회차가 게시글 목록에 섞이지 않게) + kind?: AdminPostKindFilter; visibility: PostVisibility | null; locale: Locale | null; page: number; @@ -59,6 +62,7 @@ export interface PostListRow { */ export const listPosts = async ({ q, + kind = 'post', visibility, locale, page, @@ -69,6 +73,7 @@ export const listPosts = async ({ const term = q.trim(); const pattern = `%${escapeLike(term)}%`; const where = and( + adminKindCondition(kind), term ? or( ilike(post.title, pattern), diff --git a/lib/admin/stats-queries.ts b/lib/admin/stats-queries.ts index e6f2929..520a2b5 100644 --- a/lib/admin/stats-queries.ts +++ b/lib/admin/stats-queries.ts @@ -15,6 +15,7 @@ import { adminAccount, adminActionLog } from '@/lib/db/schema/admin'; import { user } from '@/lib/db/schema/auth'; import { draftPrompt } from '@/lib/db/schema/draft'; import { post } from '@/lib/db/schema/post'; +import { regularPostCondition } from '@/lib/posts/kind'; import { quotaPlan } from '@/lib/db/schema/quota'; import type { GenerationModel } from '@/lib/generation/contract'; import { toQuotaPlan } from '@/lib/generation/quota'; @@ -120,10 +121,13 @@ export const getDashboardStats = async (now: Date): Promise => { banned: count(post.bannedAt), newThisWeek: countSince(post.publishedAt, start), }) - .from(post), + .from(post) + // 게시글 통계는 일반 게시글만 (comlog 회차 제외) + .where(regularPostCondition()), db .select({ visibility: post.visibility, count: count() }) .from(post) + .where(regularPostCondition()) .groupBy(post.visibility) .orderBy(post.visibility), db diff --git a/lib/admin/user-queries.ts b/lib/admin/user-queries.ts index 9fed512..978b248 100644 --- a/lib/admin/user-queries.ts +++ b/lib/admin/user-queries.ts @@ -8,6 +8,7 @@ import { adminAccount, adminActionLog } from '@/lib/db/schema/admin'; import { session, user } from '@/lib/db/schema/auth'; import { draftPrompt } from '@/lib/db/schema/draft'; import { post } from '@/lib/db/schema/post'; +import { regularPostCondition } from '@/lib/posts/kind'; import { quotaPlan } from '@/lib/db/schema/quota'; import { getUserQuota } from '@/lib/generation/quota-queries'; import type { QuotaSummary } from '@/lib/generation/quota'; @@ -146,7 +147,10 @@ export const getUserDetail = async ( .select({ role: quotaPlan.role }) .from(quotaPlan) .orderBy(quotaPlan.role), - db.select({ total: count() }).from(post).where(eq(post.userId, userId)), + db + .select({ total: count() }) + .from(post) + .where(and(eq(post.userId, userId), regularPostCondition())), db .select({ total: count() }) .from(session) diff --git a/lib/posts/kind.test.ts b/lib/posts/kind.test.ts new file mode 100644 index 0000000..10f97df --- /dev/null +++ b/lib/posts/kind.test.ts @@ -0,0 +1,29 @@ +import { PgDialect } from 'drizzle-orm/pg-core'; +import { describe, expect, it } from 'vitest'; +import { adminKindCondition, regularPostCondition } from '@/lib/posts/kind'; + +const dialect = new PgDialect(); + +describe('regularPostCondition', () => { + it("post.kind = 'post' 조건을 만든다", () => { + const { sql, params } = dialect.sqlToQuery(regularPostCondition()); + + expect(sql).toContain('"kind"'); + expect(params).toEqual(['post']); + }); +}); + +describe('adminKindCondition', () => { + it('all 이면 거르지 않는다', () => { + expect(adminKindCondition('all')).toBeUndefined(); + }); + + it('post / comlog 는 그 종류만 거른다', () => { + expect(dialect.sqlToQuery(adminKindCondition('comlog')!).params).toEqual([ + 'comlog', + ]); + expect(dialect.sqlToQuery(adminKindCondition('post')!).params).toEqual([ + 'post', + ]); + }); +}); diff --git a/lib/posts/kind.ts b/lib/posts/kind.ts new file mode 100644 index 0000000..af808c3 --- /dev/null +++ b/lib/posts/kind.ts @@ -0,0 +1,16 @@ +import { eq, type SQL } from 'drizzle-orm'; +import { post } from '@/lib/db/schema'; + +/** + * 일반 게시글 조건 (post.kind = 'post') + * - comlog 회차도 post 테이블에 있어서, 게시글 목록·사이트맵·상세·집계는 모두 이 조건으로 거른다 + * - 한 곳에서만 정의해 새 조회가 생겨도 같은 조건을 쓰게 함 + */ +export const regularPostCondition = (): SQL => eq(post.kind, 'post'); + +/** 관리자 조회의 종류 필터 (all 이면 거르지 않음) */ +export type AdminPostKindFilter = 'post' | 'comlog' | 'all'; + +export const adminKindCondition = ( + kind: AdminPostKindFilter, +): SQL | undefined => (kind === 'all' ? undefined : eq(post.kind, kind)); diff --git a/lib/posts/moderation.test.ts b/lib/posts/moderation.test.ts index db80bda..c204782 100644 --- a/lib/posts/moderation.test.ts +++ b/lib/posts/moderation.test.ts @@ -69,3 +69,15 @@ describe('parseModerationRequest', () => { } }); }); + +describe('parseModerationRequest comlog 회차 주소', () => { + it('/comlog/[프로젝트]/[회차] 주소의 마지막 조각에서 게시글 id 를 찾는다', () => { + expect( + parseModerationRequest({ + target: 'https://comdraft.dev/ko/comlog/abc-my-app/login-aB3dE5gH7j', + action: 'ban', + reason: 'x', + }), + ).toEqual({ postId: 'aB3dE5gH7j', action: 'ban', reason: 'x' }); + }); +}); diff --git a/lib/posts/queries.ts b/lib/posts/queries.ts index 32bc77a..8fa83bd 100644 --- a/lib/posts/queries.ts +++ b/lib/posts/queries.ts @@ -4,6 +4,7 @@ import { and, count, desc, eq, isNull, sql } from 'drizzle-orm'; import type { JSONContent } from '@tiptap/core'; import { db } from '@/lib/db'; import { draft, post, user, type PostVisibility } from '@/lib/db/schema'; +import { regularPostCondition } from '@/lib/posts/kind'; import { resolvePostAuthor, type PostAuthor } from '@/lib/posts/author-display'; import type { Locale } from '@/lib/i18n/config'; import { @@ -57,7 +58,7 @@ export const getPublishedPost = cache( }) .from(post) .innerJoin(user, eq(post.userId, user.id)) - .where(eq(post.id, id)) + .where(and(eq(post.id, id), regularPostCondition())) .limit(1); if (!row) return null; @@ -120,6 +121,7 @@ export const getPostListPage = async ( filters: PostListFilters, ): Promise => { const where = and( + regularPostCondition(), eq(post.visibility, 'public'), // 임시 조치된 글은 목록에서 뺌 isNull(post.bannedAt), @@ -165,7 +167,13 @@ export const listPublicPostPaths = async (): Promise< }) .from(post) // 임시 조치된 글은 사이트맵에서 뺌 - .where(and(eq(post.visibility, 'public'), isNull(post.bannedAt))) + .where( + and( + regularPostCondition(), + eq(post.visibility, 'public'), + isNull(post.bannedAt), + ), + ) .orderBy(desc(post.publishedAt), desc(post.id)) ); }; diff --git a/lib/posts/views.ts b/lib/posts/views.ts index 38f4a89..432e9ff 100644 --- a/lib/posts/views.ts +++ b/lib/posts/views.ts @@ -2,6 +2,7 @@ import 'server-only'; import { and, eq, gt, isNull, sql } from 'drizzle-orm'; import { db } from '@/lib/db'; import { post, postView } from '@/lib/db/schema'; +import { regularPostCondition } from '@/lib/posts/kind'; import { POST_VIEW_WINDOW_DAYS } from '@/lib/posts/post-view'; /** 조회 수를 셀 때 필요한 게시글 정보 (게시된 글이 없으면 null) */ @@ -11,8 +12,10 @@ export const getPostAuthorId = async ( const [row] = await db .select({ userId: post.userId }) .from(post) - // 임시 조치된 글은 조회를 세지 않음 - .where(and(eq(post.id, postId), isNull(post.bannedAt))) + // 임시 조치된 글과 comlog 회차는 조회를 세지 않음 + .where( + and(eq(post.id, postId), isNull(post.bannedAt), regularPostCondition()), + ) .limit(1); return row?.userId ?? null; diff --git a/lib/studio/queries.ts b/lib/studio/queries.ts index ee13acf..3f4a81b 100644 --- a/lib/studio/queries.ts +++ b/lib/studio/queries.ts @@ -55,6 +55,9 @@ export interface StudioDraftSummary { id: string; title: string; status: DraftStatus; + // 초안 종류 (일반 글 / comlog 회차)와 짝 초안(함께 만든 다른 종류) + kind: DraftKind; + pairedDraftId: string | null; // 게시한 초안의 공개 범위 (post 조인 결과, 게시 전에는 null) visibility: PostVisibility | null; // 답변 대기(awaiting_input)인 초안 작성 작업이 있는지 (목록 표시용) @@ -186,6 +189,8 @@ export const listStudioDrafts = async ( id: draft.id, title: draft.title, status: draft.status, + kind: draft.kind, + pairedDraftId: draft.pairedDraftId, visibility: post.visibility, isAwaitingInput: sql`exists ( select 1 from ${draftPrompt} @@ -278,6 +283,8 @@ export const getStudioDraft = async ( id: draft.id, title: draft.title, status: draft.status, + kind: draft.kind, + pairedDraftId: draft.pairedDraftId, visibility: post.visibility, postId: post.id, postSlug: post.slug, From 99fc5869c433c0f1d4f7a6078f083920231dd442 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 16:02:58 +0900 Subject: [PATCH 09/27] =?UTF-8?q?fix(comlog):=20=EB=B0=80=EB=A6=B0=20?= =?UTF-8?q?=EC=BB=A4=EB=B0=8B=20=EA=B8=B0=EB=A1=9D=20=EC=88=9C=EC=84=9C?= =?UTF-8?q?=EC=99=80=20=EA=B2=BD=EA=B3=84=20=EB=90=98=EB=8F=8C=EB=A6=BC=20?= =?UTF-8?q?=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 밀린 커밋 기록·경계 이동을 실패 행보다 먼저 해 중간에 실패해도 재전송이 다시 기록 - 선점 뒤 회차가 할당량·속도 제한으로 막히면 경계를 되돌리지 않고 선점한 묶음을 밀린 커밋으로 - 실행기를 하나도 시작하지 못해 경계를 되돌리면 작업의 경계 선점 표시를 지움 Co-Authored-By: Claude Opus 5.5 --- lib/auto-draft/run.test.ts | 132 ++++++++++++++++++++++++++++++++++--- lib/auto-draft/run.ts | 94 ++++++++++++++++++++------ lib/auto-draft/store.ts | 10 +++ 3 files changed, 207 insertions(+), 29 deletions(-) diff --git a/lib/auto-draft/run.test.ts b/lib/auto-draft/run.test.ts index b725f42..d3a53d4 100644 --- a/lib/auto-draft/run.test.ts +++ b/lib/auto-draft/run.test.ts @@ -93,6 +93,7 @@ const makeDeps = (over: Partial = {}) => { recordFailure: vi.fn(async () => 'recorded' as const), moveBoundary: vi.fn(async () => true), recordBacklog: vi.fn(async () => {}), + clearBoundaryClaim: vi.fn(async () => {}), getBoundary: vi.fn(async (): Promise => OLD), getLocale: vi.fn(async () => 'en' as const), ...over, @@ -836,13 +837,70 @@ describe('runAutoDraft', () => { options: expect.objectContaining({ postType: 'worklog' }), }), ); - // 회차가 막혔으므로 밀린 커밋으로 남기고 경계는 푸시 끝 + // 회차가 막혔으므로 선점한 묶음을 그대로 밀린 커밋으로 남기고 경계는 되돌리지 않음 expect(deps.recordBacklog).toHaveBeenCalledWith('u1', 'r1', [ 'c1', 'c2', 'c3', ]); - expect(deps.moveBoundary).toHaveBeenLastCalledWith('u1', 'r1', OLD, 'c3'); + expect(deps.moveBoundary).toHaveBeenCalledTimes(1); + expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c3'); + // 범위를 다시 계산하지 않음 + expect(deps.compare).toHaveBeenCalledTimes(1); + }); + + it('선점 뒤 rate_limited 로 막힌 회차: 경계를 되돌리지 않고(옛 경계로 돌아가는 틈 없음) 밀린 커밋을 실패 행보다 먼저', async () => { + const deps = makeDeps({ + createDraftJobs: vi.fn(async () => ({ + status: 'rate_limited' as const, + })), + }); + const out = await runAutoDraft(target({}, true), push('c3'), deps); + expect(out).toEqual({ status: 'skipped', errorCode: 'rate_limited' }); + expect(deps.moveBoundary).not.toHaveBeenCalledWith('u1', 'r1', 'c3', OLD); + expect(deps.moveBoundary).toHaveBeenCalledTimes(1); + expect(deps.recordBacklog).toHaveBeenCalledWith('u1', 'r1', [ + 'c1', + 'c2', + 'c3', + ]); + expect( + vi.mocked(deps.recordBacklog).mock.invocationCallOrder[0], + ).toBeLessThan(vi.mocked(deps.recordFailure).mock.invocationCallOrder[0]); + }); + + it('선점 뒤 막혔는데 밀린 커밋 기록이 실패하면 경계를 되돌리고 오류를 던짐 (실패 행 없음)', async () => { + const deps = makeDeps({ + createDraftJobs: vi.fn(async () => ({ + status: 'too_many_active' as const, + })), + recordBacklog: vi.fn(async () => { + throw new Error('db'); + }), + }); + await expect( + runAutoDraft(target({}, true), push('c3'), deps), + ).rejects.toThrow('db'); + expect(deps.moveBoundary).toHaveBeenLastCalledWith('u1', 'r1', 'c3', OLD); + expect(deps.recordFailure).not.toHaveBeenCalled(); + }); + + it('20개에서 잘려 선점하지 않은 묶음이 막히면 범위 전부를 다시 계산해 밀린 커밋으로, 경계는 푸시 끝', async () => { + const commits = Array.from({ length: 25 }, (_, i) => commit(i + 1)); + const deps = makeDeps({ + compare: vi.fn(async () => ({ status: 'ok' as const, commits })), + createDraftJobs: vi.fn(async () => ({ + status: 'too_many_active' as const, + })), + }); + await runAutoDraft(target({}, true), push('c25'), deps); + expect(deps.recordBacklog).toHaveBeenCalledWith( + 'u1', + 'r1', + commits.map((c) => c.sha), + ); + expect(deps.moveBoundary).toHaveBeenCalledTimes(1); + expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c25'); }); const quotaGate = () => @@ -968,14 +1026,44 @@ describe('runAutoDraft', () => { expect(deps.moveBoundary).not.toHaveBeenCalled(); }); - it('재전송으로 실패 행이 duplicate 면 backlog 를 남기지 않음', async () => { - const deps = makeDeps({ - gate: quotaGate(), - recordFailure: vi.fn(async () => 'duplicate' as const), - }); + it('밀린 커밋은 실패 행보다 먼저 기록', async () => { + const deps = makeDeps({ gate: quotaGate() }); + await runAutoDraft(target({}, true), push('c3'), deps); + const backlogAt = vi.mocked(deps.recordBacklog).mock + .invocationCallOrder[0]; + const boundaryAt = vi.mocked(deps.moveBoundary).mock + .invocationCallOrder[0]; + const failureAt = vi.mocked(deps.recordFailure).mock + .invocationCallOrder[0]; + expect(backlogAt).toBeLessThan(failureAt); + expect(boundaryAt).toBeLessThan(failureAt); + }); + + it('범위 계산(compare)이 던지면 실패 행이 없어 재전송이 밀린 커밋을 다시 기록', async () => { + const commits = [commit(1), commit(2), commit(3, '[comdraft]')]; + const compare = vi + .fn() + .mockRejectedValueOnce(new Error('github')) + .mockResolvedValue({ status: 'ok', commits }); + const deps = makeDeps({ gate: quotaGate(), compare }); + + await expect( + runAutoDraft(target({}, true), push('c3'), deps), + ).rejects.toThrow('github'); + expect(deps.recordFailure).not.toHaveBeenCalled(); + expect(deps.recordBacklog).not.toHaveBeenCalled(); + expect(deps.moveBoundary).not.toHaveBeenCalled(); + + // 웹훅이 internal 행을 남긴 뒤 재전송 → 실패 행은 duplicate 여도 밀린 커밋은 기록 + vi.mocked(deps.recordFailure).mockResolvedValue('duplicate'); const out = await runAutoDraft(target({}, true), push('c3'), deps); expect(out).toEqual({ status: 'duplicate' }); - expect(deps.recordBacklog).not.toHaveBeenCalled(); + expect(deps.recordBacklog).toHaveBeenCalledWith('u1', 'r1', [ + 'c1', + 'c2', + 'c3', + ]); + expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c3'); }); it('post log 중 회차 실행기 시작 실패 → 경계 유지, 회차 작업 runner_unavailable', async () => { @@ -1009,6 +1097,34 @@ describe('runAutoDraft', () => { expect(deps.failJob).toHaveBeenCalledWith('j2', 'runner_unavailable'); expect(deps.moveBoundary).toHaveBeenLastCalledWith('u1', 'r1', 'c3', OLD); expect(deps.recordBacklog).not.toHaveBeenCalled(); + // 경계를 지나가지 않았으므로 선점 표시를 지운 뒤 실패 처리 + expect(deps.clearBoundaryClaim).toHaveBeenCalledWith(['j1', 'j2']); + expect( + vi.mocked(deps.clearBoundaryClaim).mock.invocationCallOrder[0], + ).toBeLessThan(vi.mocked(deps.failJob).mock.invocationCallOrder[0]); + }); + + it('하나라도 시작했거나 선점하지 않았으면 선점 표시를 그대로 둠', async () => { + const partial = makeDeps({ + startRunner: vi.fn(async ({ jobId }: { jobId: string }) => { + if (jobId === 'j2') throw new Error('down'); + }), + }); + await runAutoDraft(target({}, true), push('c3', both), partial); + expect(partial.clearBoundaryClaim).not.toHaveBeenCalled(); + + const capped = makeDeps({ + compare: vi.fn(async () => ({ + status: 'ok' as const, + commits: Array.from({ length: 25 }, (_, i) => commit(i + 1)), + })), + startRunner: vi.fn(async () => { + throw new Error('down'); + }), + }); + await runAutoDraft(target({}, true), push('c25'), capped); + expect(capped.clearBoundaryClaim).not.toHaveBeenCalled(); + expect(capped.moveBoundary).not.toHaveBeenCalled(); }); it('listExcludedShas 에 backlog 가 있으면 묶음에서 빠짐 (다음 트리거)', async () => { diff --git a/lib/auto-draft/run.ts b/lib/auto-draft/run.ts index 8bf0843..c6cb15f 100644 --- a/lib/auto-draft/run.ts +++ b/lib/auto-draft/run.ts @@ -3,6 +3,7 @@ import { desc, eq } from 'drizzle-orm'; import { computeAutoDraftBatch } from '@/lib/auto-draft/batch-server'; import { compareBranch, findEmptyCommits } from '@/lib/auto-draft/github'; import { + clearBoundaryClaim, findConsumedShas, getAutoDraftSetting, listExcludedShas, @@ -111,6 +112,8 @@ export interface RunDeps { moveBoundary: typeof moveBoundary; // 범위 커밋을 밀린 커밋(제외 사유 backlog)으로 남김 recordBacklog: typeof recordBacklog; + // 경계를 되돌린 작업의 "경계 선점" 표시를 지움 (실패한 회차를 밀린 커밋으로 오인하지 않게) + clearBoundaryClaim: typeof clearBoundaryClaim; // 지금 경계 (설정 행이 없으면 null) getBoundary: (userId: string, repositoryId: string) => Promise; getLocale: (userId: string) => Promise; @@ -180,6 +183,7 @@ export const defaultRunDeps: RunDeps = { moveBoundary(userId, repositoryId, from, to), recordBacklog: (userId, repositoryId, shas) => recordBacklog(userId, repositoryId, shas), + clearBoundaryClaim: (jobIds) => clearBoundaryClaim(jobIds), getBoundary: async (userId, repositoryId) => (await getAutoDraftSetting(userId, repositoryId))?.boundarySha ?? null, getLocale: getLatestLocale, @@ -284,14 +288,24 @@ export async function runAutoDraft( const scope = consumedScopeFor(kinds); const locale = await deps.getLocale(userId); + // 이 사유로 막혔을 때 밀린 커밋으로 남기는지 (회차를 만들 트리거 + 할당량·속도 제한 계열) + const willBacklog = (errorCode: GenerationErrorCode) => + kinds.includes('comlog') && isBacklogErrorCode(errorCode); + /** - * 시작 전 실패: 종류마다 행을 남기고 결과로 변환 + * 시작 전 실패: (밀린 커밋 기록 →) 종류마다 행을 남기고 결과로 변환 * - backlogFrom: 막힌 시점의 경계 (회차가 할당량 등으로 막혔으면 여기서부터 밀린 커밋으로 남김) + * - 밀린 커밋을 실패 행보다 먼저 기록: 중간에 던지면 실패 행이 없어 재전송이 다시 기록할 수 있음 + * (제외 목록 INSERT 와 경계 CAS 는 여러 번 해도 결과가 같음) */ const skip = async ( errorCode: GenerationErrorCode, backlogFrom: string | null = null, ): Promise => { + if (backlogFrom !== null && willBacklog(errorCode)) { + await recordRangeBacklog(target, push, deps, backlogFrom, scope); + } + const recorded = await recordFailures( target, push, @@ -300,18 +314,10 @@ export async function runAutoDraft( locale, deps, ); - // 재전송이면 첫 실행이 이미 처리함 - if (recorded === 'duplicate') return { status: 'duplicate' }; - - if ( - backlogFrom !== null && - kinds.includes('comlog') && - isBacklogErrorCode(errorCode) - ) { - await recordRangeBacklog(target, push, deps, backlogFrom, scope); - } - return { status: 'skipped', errorCode }; + return recorded === 'duplicate' + ? { status: 'duplicate' } + : { status: 'skipped', errorCode }; }; if (setting.prompt.trim() === '') return skip('no_preset'); @@ -337,12 +343,15 @@ export async function runAutoDraft( excluded, plans, scope, + willBacklog, locale, githubToken: gate.githubToken, }); - // 작업을 못 만들었으면 선점한 경계는 이미 되돌렸으므로 지금 경계부터 밀린 커밋으로 봄 - if (result.status === 'skip') return skip(result.errorCode, boundary); + // 작업을 못 만들었으면 (선점한 범위를 이미 밀린 커밋으로 남긴 경우가 아니면) 지금 경계부터 밀린 커밋으로 봄 + if (result.status === 'skip') { + return skip(result.errorCode, result.backlogRecorded ? null : boundary); + } if (result.status !== 'conflict') return result; // 다른 트리거가 먼저 경계를 옮기거나 커밋을 썼음 → 지금 경계로 다시 계산 @@ -396,6 +405,7 @@ interface BatchAttempt { excluded: ReadonlyMap; plans: PlannedKind[]; scope: ConsumedScope; + willBacklog: (errorCode: GenerationErrorCode) => boolean; locale: Locale; githubToken: string; } @@ -403,7 +413,12 @@ interface BatchAttempt { type AttemptResult = | Exclude | { status: 'skipped'; errorCode: 'runner_unavailable' } - | { status: 'skip'; errorCode: GenerationErrorCode } + // backlogRecorded: 선점한 범위를 이미 밀린 커밋으로 남김 (경계는 푸시 끝 그대로) + | { + status: 'skip'; + errorCode: GenerationErrorCode; + backlogRecorded?: boolean; + } | { status: 'conflict' }; /** @@ -415,7 +430,15 @@ async function tryStartBatch( target: PushTarget, push: TriggerPush, deps: RunDeps, - { boundary, excluded, plans, scope, locale, githubToken }: BatchAttempt, + { + boundary, + excluded, + plans, + scope, + willBacklog, + locale, + githubToken, + }: BatchAttempt, ): Promise { const { userId, repositoryId, setting } = target; const plan = await computeAutoDraftBatch( @@ -487,13 +510,38 @@ async function tryStartBatch( throw error; } - if (created.status !== 'created') { + if (created.status === 'duplicate' || created.status === 'overlap') { await revert(); - if (created.status === 'duplicate') return { status: 'duplicate' }; - if (created.status === 'overlap') return { status: 'conflict' }; + return created.status === 'duplicate' + ? { status: 'duplicate' } + : { status: 'conflict' }; + } + + if (created.status !== 'created') { + const errorCode = slotErrorCode(created.status); + + // 회차가 막혔고 끝까지 선점했으면 경계를 되돌리지 않고 이 묶음을 그대로 밀린 커밋으로 남김 + // (되돌렸다 다시 옮기면 그 사이 다른 트리거가 옛 경계로 같은 커밋을 가져갈 수 있음) + if (claimTo !== null && willBacklog(errorCode)) { + try { + await deps.recordBacklog(userId, repositoryId, batchShas); + } catch (error) { + // 기록하지 못했으면 경계를 되돌려 재전송이 처음부터 다시 처리하게 함 + await revert().catch((revertError: unknown) => + reportError(revertError, 'auto-draft.revert-boundary', { + repositoryId, + }), + ); + throw error; + } + + return { status: 'skip', errorCode, backlogRecorded: true }; + } - return { status: 'skip', errorCode: slotErrorCode(created.status) }; + await revert(); + + return { status: 'skip', errorCode }; } const jobIds = created.jobs.map((job) => job.jobId); @@ -511,7 +559,11 @@ async function tryStartBatch( // 하나도 시작하지 못했을 때만 경계를 되돌림 (하나라도 시작했으면 그 작업이 커밋을 쓰고 있음) // 경계를 먼저 되돌려 failJob 이 실패해도 항상 복구 const noneStarted = failedJobIds.length === jobIds.length; - if (noneStarted) await revert(); + if (noneStarted && claimTo !== null) { + await revert(); + // 경계를 지나가지 않았으므로 실패한 회차의 커밋을 밀린 커밋으로 남기지 않게 표시를 지움 + await deps.clearBoundaryClaim(jobIds); + } // 작업 행이 이미 있으므로 실패 행을 따로 남기지 않음 for (const jobId of failedJobIds) { diff --git a/lib/auto-draft/store.ts b/lib/auto-draft/store.ts index 73a4d8f..14087ce 100644 --- a/lib/auto-draft/store.ts +++ b/lib/auto-draft/store.ts @@ -365,6 +365,16 @@ export async function recordBacklog( await excludeCommits(userId, repositoryId, shas, 'backlog'); } +// 경계를 되돌린 작업의 "경계 선점" 표시를 지움 (실행기를 하나도 시작하지 못해 되돌린 경우) +export async function clearBoundaryClaim(jobIds: string[]): Promise { + if (jobIds.length === 0) return; + + await db + .update(draftPrompt) + .set({ boundaryClaimed: false }) + .where(inArray(draftPrompt.id, jobIds)); +} + // 제외한 커밋을 다시 대상으로 되돌림 export async function restoreCommit( userId: string, From f44e558be7cd013b1d52fe9c4b4cd4a759959ab1 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 16:03:50 +0900 Subject: [PATCH 10/27] =?UTF-8?q?fix(report):=20=EC=9D=BC=EC=9D=BC=20?= =?UTF-8?q?=EB=A6=AC=ED=8F=AC=ED=8A=B8=20=EA=B2=8C=EC=8B=9C=EA=B8=80=20?= =?UTF-8?q?=EC=88=98=EC=97=90=EC=84=9C=20comlog=20=ED=9A=8C=EC=B0=A8=20?= =?UTF-8?q?=EC=A0=9C=EC=99=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/admin/post-queries.ts | 2 +- lib/admin/stats-queries.ts | 2 +- lib/admin/user-queries.ts | 2 +- lib/report/service-stats.ts | 7 ++++++- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/lib/admin/post-queries.ts b/lib/admin/post-queries.ts index fa2d2ac..0cf5ef7 100644 --- a/lib/admin/post-queries.ts +++ b/lib/admin/post-queries.ts @@ -15,9 +15,9 @@ import { adminAccount, adminActionLog } from '@/lib/db/schema/admin'; import { user } from '@/lib/db/schema/auth'; import { post, postView, POST_VISIBILITIES } from '@/lib/db/schema/post'; import type { PostVisibility } from '@/lib/db/schema/post'; -import { adminKindCondition, type AdminPostKindFilter } from '@/lib/posts/kind'; import { LOCALES } from '@/lib/i18n/config'; import type { Locale } from '@/lib/i18n/config'; +import { adminKindCondition, type AdminPostKindFilter } from '@/lib/posts/kind'; /** * 어드민 게시글 조회 (읽기 전용) diff --git a/lib/admin/stats-queries.ts b/lib/admin/stats-queries.ts index 520a2b5..aaf9bf2 100644 --- a/lib/admin/stats-queries.ts +++ b/lib/admin/stats-queries.ts @@ -15,10 +15,10 @@ import { adminAccount, adminActionLog } from '@/lib/db/schema/admin'; import { user } from '@/lib/db/schema/auth'; import { draftPrompt } from '@/lib/db/schema/draft'; import { post } from '@/lib/db/schema/post'; -import { regularPostCondition } from '@/lib/posts/kind'; import { quotaPlan } from '@/lib/db/schema/quota'; import type { GenerationModel } from '@/lib/generation/contract'; import { toQuotaPlan } from '@/lib/generation/quota'; +import { regularPostCondition } from '@/lib/posts/kind'; /** * 어드민 대시보드 조회 (읽기 전용) diff --git a/lib/admin/user-queries.ts b/lib/admin/user-queries.ts index 978b248..c9bbd12 100644 --- a/lib/admin/user-queries.ts +++ b/lib/admin/user-queries.ts @@ -8,10 +8,10 @@ import { adminAccount, adminActionLog } from '@/lib/db/schema/admin'; import { session, user } from '@/lib/db/schema/auth'; import { draftPrompt } from '@/lib/db/schema/draft'; import { post } from '@/lib/db/schema/post'; -import { regularPostCondition } from '@/lib/posts/kind'; import { quotaPlan } from '@/lib/db/schema/quota'; import { getUserQuota } from '@/lib/generation/quota-queries'; import type { QuotaSummary } from '@/lib/generation/quota'; +import { regularPostCondition } from '@/lib/posts/kind'; /** * 어드민 사용자 조회 (읽기 전용) diff --git a/lib/report/service-stats.ts b/lib/report/service-stats.ts index 61c8f6b..7e2b859 100644 --- a/lib/report/service-stats.ts +++ b/lib/report/service-stats.ts @@ -2,6 +2,7 @@ import 'server-only'; import { and, eq, gte, lt } from 'drizzle-orm'; import { db } from '@/lib/db'; import { draftPrompt, post, user } from '@/lib/db/schema'; +import { regularPostCondition } from '@/lib/posts/kind'; import type { ServiceStats } from '@/lib/report/format'; /** @@ -33,7 +34,11 @@ export const fetchServiceStats = async ({ db.$count(draftPrompt, and(createdIn, eq(draftPrompt.status, 'failed'))), db.$count( post, - and(gte(post.publishedAt, start), lt(post.publishedAt, end)), + and( + regularPostCondition(), + gte(post.publishedAt, start), + lt(post.publishedAt, end), + ), ), ]); From 1fea068d03753caa730a3f7ae2227ab350ea4456 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 16:06:22 +0900 Subject: [PATCH 11/27] =?UTF-8?q?feat(comlog):=20=ED=9A=8C=EC=B0=A8=20?= =?UTF-8?q?=EC=82=AC=EC=9A=A9=EB=90=A8=20=EA=B7=9C=EC=B9=99=EA=B3=BC=20?= =?UTF-8?q?=EC=8B=9C=EC=9E=91=20=EB=92=A4=20=EC=8B=A4=ED=8C=A8=ED=95=9C=20?= =?UTF-8?q?=ED=9A=8C=EC=B0=A8=EC=9D=98=20=EB=B0=80=EB=A6=B0=20=EC=BB=A4?= =?UTF-8?q?=EB=B0=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/api/github/webhook/route.ts | 10 +++ components/studio/commit-markers.tsx | 7 ++ components/studio/commit-sidebar.tsx | 3 + lib/actions/auto-draft.ts | 71 +++++++++++++++++-- lib/auto-draft/markers.test.ts | 39 +++++++++++ lib/auto-draft/markers.ts | 45 ++++++++++-- lib/auto-draft/store.ts | 23 ++++++ lib/comlog/backlog.test.ts | 77 ++++++++++++++++++++ lib/comlog/backlog.ts | 101 +++++++++++++++++++++++++++ lib/generation/jobs.test.ts | 4 ++ lib/generation/jobs.ts | 4 ++ 11 files changed, 374 insertions(+), 10 deletions(-) create mode 100644 lib/comlog/backlog.test.ts create mode 100644 lib/comlog/backlog.ts diff --git a/app/api/github/webhook/route.ts b/app/api/github/webhook/route.ts index db1ba53..451ba9e 100644 --- a/app/api/github/webhook/route.ts +++ b/app/api/github/webhook/route.ts @@ -10,6 +10,7 @@ import { planPushEvent, verifyWebhookSignature, } from '@/lib/auto-draft/webhook'; +import { syncFailedComlogBacklog } from '@/lib/comlog/backlog'; import { refreshRepositoryPrivacy } from '@/lib/comlog/store'; import { getGithubWebhookSecret } from '@/lib/github/env'; import { flushReports, reportError } from '@/lib/observability/report-error'; @@ -92,6 +93,15 @@ export async function POST(request: NextRequest) { let scheduled = 0; for (const target of targets) { + // 이전에 실패한 회차 작업의 커밋을 먼저 밀린 커밋으로 반영 (실패해도 이번 푸시 처리는 이어감) + try { + await syncFailedComlogBacklog(target.userId, target.repositoryId); + } catch (error) { + reportError(error, 'github-webhook.sync-backlog', { + repositoryId: target.repositoryId, + }); + } + const plan = planPushEvent(event, { branch, githubAccountId: target.githubAccountId, diff --git a/components/studio/commit-markers.tsx b/components/studio/commit-markers.tsx index abf53fa..a882b1b 100644 --- a/components/studio/commit-markers.tsx +++ b/components/studio/commit-markers.tsx @@ -12,6 +12,9 @@ const MARKER_ICONS: Record = { excluded: '/images/studio/circle-slash.svg', consumed: '/images/studio/circle-check.svg', not_collected: '/images/studio/git-merge.svg', + // 밀림·반영됨 전용 아이콘과 문구는 스튜디오 UI 작업에서 정함 (지금은 기존 아이콘을 재사용) + backlog: '/images/studio/circle-slash.svg', + applied: '/images/studio/circle-check.svg', }; interface CommitMarkersProps { @@ -43,6 +46,10 @@ const CommitMarkers = ({ markers }: CommitMarkersProps) => { return t`이미 자동 초안에 사용한 커밋입니다`; case 'not_collected': return t`머지 커밋은 내용이 없어 자동 대상에 들어가지 않습니다`; + case 'backlog': + return t`할당량 때문에 기록하지 못한 커밋입니다`; + case 'applied': + return t`이 초안에 반영한 커밋입니다`; } }; diff --git a/components/studio/commit-sidebar.tsx b/components/studio/commit-sidebar.tsx index 86937c9..ac5853e 100644 --- a/components/studio/commit-sidebar.tsx +++ b/components/studio/commit-sidebar.tsx @@ -270,6 +270,9 @@ const CommitSidebar = ({ isOpen }: CommitSidebarProps) => { excluded: new Map( autoDraftState.excluded.map(({ sha, reason }) => [sha, reason]), ), + backlogShas: new Set(autoDraftState.backlog), + comlogUsedShas: new Set(autoDraftState.backlogUsed), + appliedShas: new Set(autoDraftState.appliedShas), }; }, [autoDraftState]); const { run: runAutoDraftAction, isPending: isAutoDraftPending } = autoDraft; diff --git a/lib/actions/auto-draft.ts b/lib/actions/auto-draft.ts index 6fe791e..bbb0431 100644 --- a/lib/actions/auto-draft.ts +++ b/lib/actions/auto-draft.ts @@ -2,11 +2,14 @@ import { requireSession } from '@/lib/auth/session'; import type { SkipReason } from '@/lib/auto-draft/batch'; +import { countOpenBacklog } from '@/lib/comlog/backlog'; import { computeAutoDraftBatch } from '@/lib/auto-draft/batch-server'; import { getBranchHead, getCommitParents } from '@/lib/auto-draft/github'; import { excludeCommits, + findConsumedShas, getAutoDraftRepo, + getAppliedShas, getAutoDraftSetting, listExcludedShas, restoreCommit, @@ -142,7 +145,7 @@ export interface AutoDraftSkipped { export type AutoDraftStateResult = | { status: 'off' | 'not_found' | 'error' } - | { + | ({ status: 'ok'; // 묶음의 첫 커밋 (대상이 없으면 null) anchorSha: string | null; @@ -150,11 +153,49 @@ export type AutoDraftStateResult = // 범위 안에서 건너뛴 커밋 (수집 안 됨·이미 사용됨 표시용) skipped: AutoDraftSkipped[]; excluded: AutoDraftExcluded[]; - } - | { status: 'anchor_missing'; excluded: AutoDraftExcluded[] }; + } & AutoDraftBacklogState) + | ({ + status: 'anchor_missing'; + excluded: AutoDraftExcluded[]; + } & AutoDraftBacklogState); + +// 밀린 커밋과 보고 있는 초안에 반영한 커밋 (커밋 줄 표시·회차 사이드바 상단 표시용) +export interface AutoDraftBacklogState { + // 밀린 커밋 전체 (회차에 쓴 것 포함) + backlog: string[]; + // 밀린 커밋 중 회차 작업(실패 제외)에 쓴 것 + backlogUsed: string[]; + // 아직 회차에 쓰이지 않은 밀린 커밋 수 + openBacklogCount: number; + // 보고 있는 초안의 최근 완료 작업이 쓴 커밋 + appliedShas: string[]; +} +// 제외 목록에서 밀린 커밋(backlog)은 따로 뺌 (표시가 다르고 제외 취소 대상이 아님) const toExcludedList = (excluded: Map) => - Array.from(excluded, ([sha, reason]) => ({ sha, reason })); + Array.from(excluded, ([sha, reason]) => ({ sha, reason })).filter( + ({ reason }) => reason !== 'backlog', + ); + +const toBacklogState = async ( + userId: string, + repositoryId: string, + excluded: Map, + draftId: string | undefined, +): Promise => { + const backlog = Array.from(excluded) + .filter(([, reason]) => reason === 'backlog') + .map(([sha]) => sha); + const used = await findConsumedShas(userId, repositoryId, backlog, 'comlog'); + const appliedShas = draftId ? await getAppliedShas(userId, draftId) : []; + + return { + backlog, + backlogUsed: Array.from(used), + openBacklogCount: countOpenBacklog(backlog, used), + appliedShas, + }; +}; /** * 스튜디오 커밋 목록 표시용: 경계 다음 커밋부터 브랜치 끝까지 자동 대상 묶음을 계산 (실행기와 같은 계산) @@ -163,6 +204,8 @@ const toExcludedList = (excluded: Map) => */ export async function loadAutoDraftState( repositoryId: string, + // 보고 있는 초안 (있으면 그 초안의 최근 완료 작업 커밋에 applied 표시) + draftId?: string, ): Promise { const { user } = await requireSession(); const repo = await getAutoDraftRepo(user.id, repositoryId); @@ -180,8 +223,19 @@ export async function loadAutoDraftState( try { const excluded = await listExcludedShas(user.id, repositoryId); + const backlogState = await toBacklogState( + user.id, + repositoryId, + excluded, + draftId, + ); + if (setting.boundarySha === null) { - return { status: 'anchor_missing', excluded: toExcludedList(excluded) }; + return { + status: 'anchor_missing', + excluded: toExcludedList(excluded), + ...backlogState, + }; } const head = await getBranchHead(repo); @@ -196,7 +250,11 @@ export async function loadAutoDraftState( : ({ status: 'anchor_missing' } as const); if (plan.status !== 'ok') { - return { status: 'anchor_missing', excluded: toExcludedList(excluded) }; + return { + status: 'anchor_missing', + excluded: toExcludedList(excluded), + ...backlogState, + }; } return { @@ -205,6 +263,7 @@ export async function loadAutoDraftState( batchShas: plan.batchShas, skipped: Array.from(plan.skipped, ([sha, reason]) => ({ sha, reason })), excluded: toExcludedList(excluded), + ...backlogState, }; } catch (error) { reportError(error, 'auto-draft.load-state', { repositoryId }); diff --git a/lib/auto-draft/markers.test.ts b/lib/auto-draft/markers.test.ts index deeaff9..14f9caf 100644 --- a/lib/auto-draft/markers.test.ts +++ b/lib/auto-draft/markers.test.ts @@ -15,6 +15,9 @@ const state = { batchShas: ['a', 'b'], skipped: new Map(), excluded: new Map(), + backlogShas: new Set(), + comlogUsedShas: new Set(), + appliedShas: new Set(), }; describe('getCommitMarkers', () => { @@ -156,3 +159,39 @@ describe('getCommitMenu', () => { ).toEqual({ exclude: null }); }); }); + +describe('backlog·applied 표시', () => { + const extra = { + ...state, + backlogShas: new Set(['k']), + appliedShas: new Set(['p1']), + comlogUsedShas: new Set(), + }; + + it('밀린 커밋에 backlog 표시', () => { + expect(getCommitMarkers({ ...base, sha: 'k' }, extra)).toEqual([ + { kind: 'backlog' }, + ]); + }); + + it('밀렸어도 회차에 쓴 커밋은 backlog 표시가 없다', () => { + expect( + getCommitMarkers( + { ...base, sha: 'k' }, + { ...extra, comlogUsedShas: new Set(['k']) }, + ), + ).toEqual([]); + }); + + it('보고 있는 초안에 반영한 커밋에 applied 표시', () => { + expect(getCommitMarkers({ ...base, sha: 'p1' }, extra)).toEqual([ + { kind: 'applied' }, + ]); + }); + + it('머지 커밋에는 applied 를 붙이지 않는다', () => { + expect( + getCommitMarkers({ sha: 'p1', parentShas: ['x', 'y'] }, extra), + ).toEqual([{ kind: 'not_collected' }]); + }); +}); diff --git a/lib/auto-draft/markers.ts b/lib/auto-draft/markers.ts index a084fd9..5058573 100644 --- a/lib/auto-draft/markers.ts +++ b/lib/auto-draft/markers.ts @@ -5,7 +5,7 @@ import { isMergeCommit, type SkipReason } from '@/lib/auto-draft/batch'; * 스튜디오 커밋 줄에 붙이는 자동 초안 표시 계산 (순수 함수) */ -// 밀린 커밋(backlog) 표시는 이후 작업에서 다룸, 지금은 스키마 값과 같게만 맞춤 +// 스키마 값과 같음 (backlog 는 제외 목록에 함께 저장되지만 표시는 별도 backlogShas 로 다룸) export type ExcludedReason = ExcludedCommitReason; export type CommitMarker = @@ -16,7 +16,11 @@ export type CommitMarker = // 이전 자동 초안에 이미 쓴 커밋 | { kind: 'consumed' } // 머지 커밋 (내용이 없어 자동 대상이 아님) - | { kind: 'not_collected' }; + | { kind: 'not_collected' } + // 회차를 만들지 못해 밀린 커밋 (아직 회차에 쓰이지 않음) + | { kind: 'backlog' } + // 보고 있는 초안의 최근 완료 작업에 쓴 커밋 + | { kind: 'applied' }; export interface MarkerCommit { sha: string; @@ -29,6 +33,12 @@ export interface MarkerState { // 서버가 계산한 범위(경계 다음 ~ 브랜치 끝) 안에서 건너뛴 커밋과 사유 skipped: ReadonlyMap; excluded: ReadonlyMap; + // 밀린 커밋 (회차에 쓴 것도 들어 있을 수 있음, 표시는 comlogUsedShas 를 뺀 것만) + backlogShas: ReadonlySet; + // 회차 작업(실패 제외)에 쓴 커밋 + comlogUsedShas: ReadonlySet; + // 보고 있는 초안의 최근 완료 작업 commit_shas + appliedShas: ReadonlySet; } /** @@ -47,16 +57,43 @@ const isConsumed = ( { skipped }: Pick, ) => skipped.get(commit.sha) === 'consumed'; -// 표시 우선순위(수집 안 됨 → 제외 → 이미 사용됨)는 서버의 getSkipReason 과 같음 +// 밀린 커밋이면서 아직 회차에 쓰이지 않았는지 +const isOpenBacklog = ( + commit: MarkerCommit, + { + backlogShas, + comlogUsedShas, + }: Pick, +) => backlogShas.has(commit.sha) && !comlogUsedShas.has(commit.sha); + +/** + * 커밋 줄 표시: 자동 대상 표시에 "이 초안에 반영됨" 을 더함 (머지 커밋 제외) + */ export const getCommitMarkers = ( commit: MarkerCommit, state: MarkerState, +): CommitMarker[] => { + const markers = getBaseMarkers(commit, state); + + if (isCollectable(commit, state) && state.appliedShas.has(commit.sha)) { + markers.push({ kind: 'applied' }); + } + + return markers; +}; + +// 표시 우선순위(수집 안 됨 → 제외 → 밀림 → 이미 사용됨)는 서버의 getSkipReason 과 같음 +const getBaseMarkers = ( + commit: MarkerCommit, + state: MarkerState, ): CommitMarker[] => { if (!isCollectable(commit, state)) return [{ kind: 'not_collected' }]; const reason = state.excluded.get(commit.sha); - if (reason) return [{ kind: 'excluded', reason }]; + if (reason && reason !== 'backlog') return [{ kind: 'excluded', reason }]; + + if (isOpenBacklog(commit, state)) return [{ kind: 'backlog' }]; if (isConsumed(commit, state)) return [{ kind: 'consumed' }]; diff --git a/lib/auto-draft/store.ts b/lib/auto-draft/store.ts index 14087ce..40152eb 100644 --- a/lib/auto-draft/store.ts +++ b/lib/auto-draft/store.ts @@ -3,6 +3,7 @@ import { and, arrayOverlaps, eq, + desc, inArray, isNull, or, @@ -341,6 +342,28 @@ export async function findConsumedShas( ); } +// 초안의 최근 완료된 초안 작성 작업이 쓴 커밋 (커밋 줄의 "이 초안에 반영됨" 표시용, 없으면 빈 배열) +export async function getAppliedShas( + userId: string, + draftId: string, +): Promise { + const [row] = await db + .select({ commitShas: draftPrompt.commitShas }) + .from(draftPrompt) + .where( + and( + eq(draftPrompt.userId, userId), + eq(draftPrompt.draftId, draftId), + eq(draftPrompt.kind, 'draft'), + eq(draftPrompt.status, 'completed'), + ), + ) + .orderBy(desc(draftPrompt.createdAt)) + .limit(1); + + return row?.commitShas ?? []; +} + // 커밋을 자동 초안 대상에서 제외 (이미 제외된 SHA 는 무시) export async function excludeCommits( userId: string, diff --git a/lib/comlog/backlog.test.ts b/lib/comlog/backlog.test.ts new file mode 100644 index 0000000..52bf503 --- /dev/null +++ b/lib/comlog/backlog.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('server-only', () => ({})); +vi.mock('@/lib/db', () => ({ db: {} })); +vi.mock('@/lib/auto-draft/store', () => ({ recordBacklog: vi.fn() })); + +import { + buildFailedBacklogFilter, + countOpenBacklog, + matchesFailedBacklogFilter, + type BacklogCandidateJob, +} from '@/lib/comlog/backlog'; + +const failedClaimed: BacklogCandidateJob = { + draftKind: 'comlog', + source: 'commit_trigger', + status: 'failed', + boundaryClaimed: true, + backlogRecordedAt: null, +}; + +describe('countOpenBacklog', () => { + it('회차에 쓰인 커밋은 세지 않는다', () => { + expect(countOpenBacklog(['a', 'b', 'c'], new Set(['b']))).toBe(2); + }); + + it('밀린 커밋이 없으면 0', () => { + expect(countOpenBacklog([], new Set(['b']))).toBe(0); + }); +}); + +describe('matchesFailedBacklogFilter', () => { + const filter = buildFailedBacklogFilter(); + + it('경계가 지나간 실패한 회차 트리거 작업은 대상', () => { + expect(matchesFailedBacklogFilter(failedClaimed, filter)).toBe(true); + }); + + it('boundary_claimed 가 아닌 작업은 제외', () => { + expect( + matchesFailedBacklogFilter( + { ...failedClaimed, boundaryClaimed: false }, + filter, + ), + ).toBe(false); + }); + + it('일반 글(post) 작업은 제외', () => { + expect( + matchesFailedBacklogFilter( + { ...failedClaimed, draftKind: 'post' }, + filter, + ), + ).toBe(false); + }); + + it('이미 기록한 작업, 실패가 아닌 작업, 직접 요청 작업은 제외', () => { + expect( + matchesFailedBacklogFilter( + { ...failedClaimed, backlogRecordedAt: new Date() }, + filter, + ), + ).toBe(false); + expect( + matchesFailedBacklogFilter( + { ...failedClaimed, status: 'running' }, + filter, + ), + ).toBe(false); + expect( + matchesFailedBacklogFilter( + { ...failedClaimed, source: 'studio' }, + filter, + ), + ).toBe(false); + }); +}); diff --git a/lib/comlog/backlog.ts b/lib/comlog/backlog.ts new file mode 100644 index 0000000..59081c9 --- /dev/null +++ b/lib/comlog/backlog.ts @@ -0,0 +1,101 @@ +import 'server-only'; +import { and, eq, inArray, isNull } from 'drizzle-orm'; +import { recordBacklog } from '@/lib/auto-draft/store'; +import { db } from '@/lib/db'; +import { draftPrompt } from '@/lib/db/schema'; +import type { + DraftPromptSource, + DraftPromptStatus, +} from '@/lib/db/schema/draft'; +import type { DraftKind } from '@/lib/studio/options'; + +/** + * 시작 뒤에 실패한 회차 작업의 커밋을 밀린 커밋(backlog)으로 남김 + */ + +// 밀린 커밋 중 아직 회차 작업에 쓰이지 않은 것의 수 (스튜디오 회차 사이드바 상단 표시) +export const countOpenBacklog = ( + backlog: readonly string[], + comlogUsed: ReadonlySet, +): number => backlog.filter((sha) => !comlogUsed.has(sha)).length; + +export interface FailedBacklogFilter { + draftKind: DraftKind; + source: DraftPromptSource; + status: DraftPromptStatus; + // 경계가 실제로 이 작업의 커밋을 지나간 경우만 (20개에서 잘려 풀려난 작업은 다음 묶음 대상이라 제외) + boundaryClaimed: boolean; + // 이미 기록한 작업은 다시 읽지 않음 + backlogRecorded: boolean; +} + +// 밀린 커밋으로 옮길 작업의 선택 조건 (DB 조건과 같은 값을 순수 객체로 둠) +export const buildFailedBacklogFilter = (): FailedBacklogFilter => ({ + draftKind: 'comlog', + source: 'commit_trigger', + status: 'failed', + boundaryClaimed: true, + backlogRecorded: false, +}); + +export interface BacklogCandidateJob { + draftKind: DraftKind; + source: DraftPromptSource; + status: DraftPromptStatus; + boundaryClaimed: boolean; + backlogRecordedAt: Date | null; +} + +export const matchesFailedBacklogFilter = ( + job: BacklogCandidateJob, + filter: FailedBacklogFilter = buildFailedBacklogFilter(), +): boolean => + job.draftKind === filter.draftKind && + job.source === filter.source && + job.status === filter.status && + job.boundaryClaimed === filter.boundaryClaimed && + (job.backlogRecordedAt === null) === !filter.backlogRecorded; + +/** + * 실패한 회차 트리거 작업의 커밋을 backlog 로 넣고 기록 시각을 남김 + * - 앱이 실패로 바꾼 작업과 Lambda 가 직접 failed 로 남긴 작업 모두, 다음 조회 때 반영 + * - backlog 삽입은 중복을 무시하므로 중간에 끊겨도 다시 불러 안전 + */ +export const syncFailedComlogBacklog = async ( + userId: string, + repositoryId: string, +): Promise => { + const filter = buildFailedBacklogFilter(); + const rows = await db + .select({ id: draftPrompt.id, commitShas: draftPrompt.commitShas }) + .from(draftPrompt) + .where( + and( + eq(draftPrompt.userId, userId), + eq(draftPrompt.repositoryId, repositoryId), + eq(draftPrompt.kind, 'draft'), + eq(draftPrompt.draftKind, filter.draftKind), + eq(draftPrompt.source, filter.source), + eq(draftPrompt.status, filter.status), + eq(draftPrompt.boundaryClaimed, filter.boundaryClaimed), + isNull(draftPrompt.backlogRecordedAt), + ), + ); + + if (rows.length === 0) return; + + await recordBacklog( + userId, + repositoryId, + Array.from(new Set(rows.flatMap((row) => row.commitShas))), + ); + await db + .update(draftPrompt) + .set({ backlogRecordedAt: new Date() }) + .where( + inArray( + draftPrompt.id, + rows.map((row) => row.id), + ), + ); +}; diff --git a/lib/generation/jobs.test.ts b/lib/generation/jobs.test.ts index d6c7cbe..f8ef0e8 100644 --- a/lib/generation/jobs.test.ts +++ b/lib/generation/jobs.test.ts @@ -17,6 +17,10 @@ builder.where = (condition: SQL) => { }; builder.limit = async () => []; vi.mock('@/lib/db', () => ({ db: builder })); +// 실패한 회차의 밀린 커밋 반영은 backlog.test.ts 에서 다룸 +vi.mock('@/lib/comlog/backlog', () => ({ + syncFailedComlogBacklog: vi.fn(), +})); const jobs = await import('@/lib/generation/jobs'); const toSql = (condition: SQL) => new PgDialect().sqlToQuery(condition).sql; diff --git a/lib/generation/jobs.ts b/lib/generation/jobs.ts index 4703156..0ccf24c 100644 --- a/lib/generation/jobs.ts +++ b/lib/generation/jobs.ts @@ -15,6 +15,7 @@ import { } from 'drizzle-orm'; import type { JSONContent } from '@tiptap/core'; import type { PgColumn } from 'drizzle-orm/pg-core'; +import { syncFailedComlogBacklog } from '@/lib/comlog/backlog'; import { db, type Database } from '@/lib/db'; import { draft, draftPrompt } from '@/lib/db/schema'; import { fillResultToParagraphs } from '@/lib/generation/blank-fill'; @@ -554,6 +555,9 @@ export const applyPendingDraftJobs = async ( for (const { id } of pending) { await applyCompletedJob(id); } + + // Lambda 가 직접 failed 로 남긴 회차 작업의 커밋도 다음 조회 때 밀린 커밋으로 반영 + await syncFailedComlogBacklog(userId, repositoryId); }; // 초안을 바꿀 수 없는 상태인지 (정리 후 진행 중인 초안 작성 작업이 남아 있으면 잠금, 빈칸 채우기는 잠그지 않음) From cfca9ddd7be23faa043e3af27e03a9209b5e2376 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 16:08:29 +0900 Subject: [PATCH 12/27] =?UTF-8?q?feat(comlog):=20=ED=9A=8C=EC=B0=A8=20?= =?UTF-8?q?=EA=B2=8C=EC=8B=9C=EC=99=80=20=EB=B9=84=EA=B3=B5=EA=B0=9C=20?= =?UTF-8?q?=EA=B3=B5=EA=B0=9C=20=EB=B2=94=EC=9C=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- components/studio/publish-actions.tsx | 13 +++- components/studio/publish-dialog.tsx | 71 ++++++++++++++------ components/studio/publish-state.test.ts | 34 ++++++++++ components/studio/publish-state.ts | 31 +++++++++ lib/actions/posts.ts | 89 ++++++++++++++++++++++--- lib/posts/post-values.test.ts | 16 +++-- lib/posts/post-values.ts | 14 ++-- lib/studio/queries.ts | 9 +++ 8 files changed, 233 insertions(+), 44 deletions(-) diff --git a/components/studio/publish-actions.tsx b/components/studio/publish-actions.tsx index 3bdd8ff..41930b7 100644 --- a/components/studio/publish-actions.tsx +++ b/components/studio/publish-actions.tsx @@ -103,7 +103,9 @@ const PublishActions = ({ ); const { primary, canView, canUnpublish } = getPublishActions(publishState); const isDisabled = !draft || isLocked; - const hasMenu = canView || canUnpublish; + // 회차는 comlog 주소가 생기기 전까지 글 보기 링크가 없음 (게시 취소만) + const canViewPost = canView && draft?.kind === 'post'; + const hasMenu = canViewPost || canUnpublish; const closeDialog = () => { if (!isPending) { @@ -161,7 +163,10 @@ const PublishActions = ({ }); setOpenDialog(null); // 게시가 끝났음을 결과로 보여 주도록 게시된 글로 이동 (본문은 게시가 저장함) - router.push(getPostPath({ id: result.id, slug: result.slug })); + // - 회차는 /posts 주소로 열면 404 라 이동하지 않음 (comlog 주소는 공개 페이지 작업에서 연결) + if (draft.kind === 'post') { + router.push(getPostPath({ id: result.id, slug: result.slug })); + } return; } @@ -247,7 +252,7 @@ const PublishActions = ({ id={menuId} className="animate-dropdown absolute top-[calc(100%+8px)] right-0 z-20 w-33 rounded border border-line bg-white" > - {canView && publishState.post && ( + {canViewPost && publishState.post && ( = { locked: msg`AI 작성 중에는 게시할 수 없습니다`, invalid: msg`게시할 수 없는 본문입니다. 내용을 확인해주세요.`, not_found: msg`초안을 찾을 수 없습니다. 새로고침 후 다시 시도해주세요.`, + comlog_disabled: msg`comlog 가 꺼져 있어 회차를 게시할 수 없습니다`, images: msg`올리지 못한 이미지가 있습니다`, error: msg`게시하지 못했습니다. 다시 시도해주세요.`, }; -// 일반 게시 창은 비공개(private)를 보이지 않음 (comlog 회차 전용) -const VISIBILITY_OPTIONS: Array<{ - value: RegularPostVisibility; - label: MessageDescriptor; - description: MessageDescriptor; -}> = [ - { - value: 'public', +// 보여 줄 선택지는 초안 종류가 정함 (비공개는 comlog 회차 전용) +const VISIBILITY_OPTIONS: Record< + PostVisibility, + { label: MessageDescriptor; description: MessageDescriptor } +> = { + public: { label: msg`공개`, description: msg`누구나 목록과 검색에서 글을 찾을 수 있습니다`, }, - { - value: 'unlisted', + unlisted: { label: msg`일부 공개`, description: msg`주소를 아는 사람만 글을 볼 수 있습니다`, }, -]; + private: { + label: msg`비공개`, + description: msg`나만 볼 수 있습니다`, + }, +}; + +// 프로젝트가 회차보다 좁을 때 보이는 안내 (설계 §9) +const NOTICE_MESSAGES = { + project_unlisted: msg`프로젝트가 일부 공개라 목록·검색에는 나오지 않아요`, + project_private: msg`프로젝트가 비공개라 나만 볼 수 있어요`, +} satisfies Record<'project_unlisted' | 'project_private', MessageDescriptor>; interface PublishDialogProps { + // 초안 종류 (공개 범위 선택지가 달라짐) + kind: DraftKind; + // comlog 회차일 때 프로젝트의 공개 범위 (일반 글은 null) + projectVisibility: ComlogVisibility | null; // 다시 게시인지 (제목과 안내 문구가 달라짐) isRepublish: boolean; // 처음 선택돼 있을 공개 범위 (다시 게시면 현재 값) @@ -83,6 +103,8 @@ interface PublishDialogProps { * - 열 때마다 새로 마운트되어 선택이 초기화됨 */ const PublishDialog = ({ + kind, + projectVisibility, isRepublish, initialVisibility, author, @@ -99,6 +121,8 @@ const PublishDialog = ({ const [authorDraft, setAuthorDraft] = useState(() => toAuthorDisplayDraft(author.initial), ); + const choices = getVisibilityChoices(kind); + const notice = getVisibilityNotice(projectVisibility, visibility); const hasBlanks = blankCount > 0; const hasNicknameProblem = getNicknameProblem(authorDraft) !== null; const cannotSubmit = hasBlanks || hasNoTitle || hasNicknameProblem; @@ -132,35 +156,38 @@ const PublishDialog = ({ 공개 범위 - {VISIBILITY_OPTIONS.map((option) => ( + {choices.map((value) => ( // 라벨 문구가 번역 함수 호출 결과라 린트가 접근 가능한 이름을 찾지 못함 // eslint-disable-next-line jsx-a11y/label-has-associated-control ))} + {notice && ( +

+ {i18n._(NOTICE_MESSAGES[notice])} +

+ )} { ).toEqual({ status: 'temporary', post }); }); }); + +describe('getVisibilityChoices', () => { + it('일반 글은 공개와 일부 공개', () => { + expect(getVisibilityChoices('post')).toEqual(['public', 'unlisted']); + }); + + it('comlog 회차는 비공개까지 3개', () => { + expect(getVisibilityChoices('comlog')).toEqual([ + 'public', + 'unlisted', + 'private', + ]); + }); +}); + +describe('getVisibilityNotice', () => { + it('프로젝트가 일부 공개고 회차가 공개면 목록 제외 안내', () => { + expect(getVisibilityNotice('unlisted', 'public')).toBe('project_unlisted'); + }); + + it('프로젝트가 비공개면 나만 볼 수 있다는 안내', () => { + expect(getVisibilityNotice('private', 'public')).toBe('project_private'); + expect(getVisibilityNotice('private', 'unlisted')).toBe('project_private'); + }); + + it('회차가 더 좁거나 같으면 안내 없음', () => { + expect(getVisibilityNotice('public', 'private')).toBeNull(); + expect(getVisibilityNotice('unlisted', 'unlisted')).toBeNull(); + expect(getVisibilityNotice('unlisted', 'private')).toBeNull(); + expect(getVisibilityNotice(null, 'public')).toBeNull(); + }); +}); diff --git a/components/studio/publish-state.ts b/components/studio/publish-state.ts index c982619..1079af6 100644 --- a/components/studio/publish-state.ts +++ b/components/studio/publish-state.ts @@ -1,4 +1,6 @@ +import { effectiveVisibility, type ComlogVisibility } from '@/lib/comlog/rules'; import type { DraftStatus, PostVisibility } from '@/lib/db/schema'; +import type { DraftKind } from '@/lib/studio/options'; // 초안의 게시 상태 (게시글이 있으면 post 가 있음) export interface DraftPublishState { @@ -34,3 +36,32 @@ export const resolvePublishState = ( return { ...state, status: statusOverride ?? state.status }; }; + +/** 게시 창에서 고를 수 있는 공개 범위: 비공개는 comlog 회차만 */ +export const getVisibilityChoices = (kind: DraftKind): PostVisibility[] => + kind === 'comlog' + ? ['public', 'unlisted', 'private'] + : ['public', 'unlisted']; + +export type VisibilityNotice = 'project_unlisted' | 'project_private'; + +/** + * 프로젝트가 고른 공개 범위보다 좁아 실제로는 더 좁게 보일 때의 안내 종류 + * - 실효 공개 범위(더 좁은 쪽)가 고른 값과 다를 때만 안내 + */ +export const getVisibilityNotice = ( + projectVisibility: ComlogVisibility | null, + entryVisibility: PostVisibility, +): VisibilityNotice | null => { + if (!projectVisibility) { + return null; + } + + const effective = effectiveVisibility(projectVisibility, entryVisibility); + + if (effective === entryVisibility) { + return null; + } + + return effective === 'private' ? 'project_private' : 'project_unlisted'; +}; diff --git a/lib/actions/posts.ts b/lib/actions/posts.ts index 0c903ea..c4f5300 100644 --- a/lib/actions/posts.ts +++ b/lib/actions/posts.ts @@ -1,9 +1,15 @@ 'use server'; import type { JSONContent } from '@tiptap/core'; -import { refresh } from 'next/cache'; +import { refresh, revalidatePath } from 'next/cache'; import { and, eq, not, sql } from 'drizzle-orm'; import { requireSession } from '@/lib/auth/session'; +import { + getComlogProject, + mergeProjectTech, + refreshProjectRepoPrivacy, + setProjectAuthorIfUnset, +} from '@/lib/comlog/store'; import { db } from '@/lib/db'; import { draft, post, type PostVisibility } from '@/lib/db/schema'; import { @@ -11,7 +17,12 @@ import { lockingJobExists, syncDraftJobs, } from '@/lib/generation/jobs'; -import { isLocale, type Locale } from '@/lib/i18n/config'; +import { + isLocale, + LOCALES, + localizePath, + type Locale, +} from '@/lib/i18n/config'; import { markImagesUsed, readDraftContentForUpdate, @@ -26,9 +37,11 @@ import { checkPublishable } from '@/lib/posts/post-content'; import { createPostId } from '@/lib/posts/post-id'; import { buildPostValues, parsePostVisibility } from '@/lib/posts/post-values'; import { normalizeTags } from '@/lib/posts/tags'; +import type { DraftKind } from '@/lib/studio/options'; import { parseDraftDocument } from '@/lib/studio/draft-content'; -import { isOwnedDraft } from '@/lib/studio/queries'; +import { getDraftKind, isOwnedDraft } from '@/lib/studio/queries'; import { revalidateSitemap } from '@/lib/seo/revalidate-sitemap'; +import { reportError } from '@/lib/observability/report-error'; import { getSupabaseUrl } from '@/lib/supabase/server'; export type PublishDraftResult = @@ -47,8 +60,18 @@ export type PublishDraftResult = | { status: 'invalid' } // AI 작성 중이라 편집 잠금 | { status: 'locked' } + // comlog 회차인데 프로젝트가 없거나 꺼져 있음 (게시할 수 없음) + | { status: 'comlog_disabled' } | { status: 'not_found' }; +// comlog 공개 화면 캐시 비우기: /comlog 아래(목록·프로젝트·회차)를 모든 로케일에서 한 번에 +// - 프로젝트·회차 경로를 하나씩 짚는 대신 layout 범위로 비움 (회차 하나가 목록·이전/다음에 모두 걸림) +const revalidateComlogPages = () => { + for (const locale of LOCALES) { + revalidatePath(localizePath(locale, '/comlog'), 'layout'); + } +}; + /** * 초안 게시 (다시 게시도 같은 액션) * - 화면 내용 그대로 게시되도록 초안 본문도 함께 저장 (잠금 조건은 자동 저장과 같음) @@ -60,6 +83,9 @@ export type PublishDraftResult = * - 바뀌기 전 초안 본문, 새 초안·게시글 본문에 든 이미지는 같은 트랜잭션에서 마지막 사용 시각을 갱신 * - 게시 후 응답 뒤에 쓰지 않는 이미지를 정리 (게시글 본문의 이미지도 쓰는 것으로 셈) * - 초안 태그를 정규화해 게시글로 복사 + * - 초안 종류(post / comlog)를 게시글로 복사. 회차는 비공개 공개 범위도 허용하고, + * 프로젝트가 없거나 꺼져 있으면 게시하지 않음 + * - 회차를 게시하면 프로젝트 기술 스택에 태그를 합치고, 첫 회차면 작성자 표시를 프로젝트에 채움 */ export async function publishDraft( repositoryId: string, @@ -71,15 +97,26 @@ export async function publishDraft( ): Promise { const { user } = await requireSession(); const parsed = parseDraftDocument(contentJson); - const checkedVisibility = parsePostVisibility(visibility); const checkedAuthor = parseAuthorDisplay(authorDisplay); + // 소유 확인과 종류 조회를 함께 함 (초안 종류가 공개 범위 검사에 필요) + const kind = await getDraftKind(user.id, repositoryId, draftId); + + if (!kind) { + return { status: 'not_found' }; + } + + const checkedVisibility = parsePostVisibility(visibility, kind); + if (!parsed || !checkedVisibility || !checkedAuthor || !isLocale(locale)) { return { status: 'invalid' }; } - if (!(await isOwnedDraft(user.id, repositoryId, draftId))) { - return { status: 'not_found' }; + const project = + kind === 'comlog' ? await getComlogProject(user.id, repositoryId) : null; + + if (kind === 'comlog' && (!project || !project.enabled)) { + return { status: 'comlog_disabled' }; } // 시간 초과된 작업 정리, 완료한 결과 반영 (반영되면 잠금이 풀림) @@ -146,6 +183,7 @@ export async function publishDraft( id: createPostId(), draftId, userId: user.id, + kind, ...values, ...author, tags, @@ -182,6 +220,10 @@ export async function publishDraft( }, ); + if (result.status === 'published' && kind === 'comlog') { + await afterComlogPublish(user.id, repositoryId, draftId, checkedAuthor); + } + if (result.status === 'published') { scheduleDraftImageCleanup(draftId); // 사이트맵에 새 글 또는 바뀐 수정 시각·공개 범위를 바로 반영 @@ -194,8 +236,33 @@ export async function publishDraft( return result; } +// 회차 게시 뒤 프로젝트 쪽 후처리: 실패해도 게시는 이미 끝났으므로 오류만 기록 +async function afterComlogPublish( + userId: string, + repositoryId: string, + draftId: string, + author: AuthorDisplaySettings, +): Promise { + try { + const [row] = await db + .select({ tags: post.tags }) + .from(post) + .where(eq(post.draftId, draftId)) + .limit(1); + + await mergeProjectTech(userId, repositoryId, row?.tags ?? []); + await setProjectAuthorIfUnset(userId, repositoryId, author); + } catch (error) { + reportError(error, 'comlog.publish-project-update', { repositoryId }); + } + + // 저장소 공개 여부를 GitHub 와 다시 맞춤 (스스로 실패를 삼킴) + await refreshProjectRepoPrivacy(userId, repositoryId); + revalidateComlogPages(); +} + export type UnpublishDraftResult = - | { status: 'unpublished' } + | { status: 'unpublished'; kind: DraftKind } // AI 작성 중이라 상태를 바꿀 수 없음 | { status: 'locked' } | { status: 'not_found' }; @@ -226,7 +293,7 @@ export async function unpublishDraft( const deleted = await tx .delete(post) .where(and(eq(post.draftId, draftId), eq(post.userId, user.id))) - .returning({ id: post.id }); + .returning({ id: post.id, kind: post.kind }); if (deleted.length === 0) { return { status: 'not_found' }; @@ -237,13 +304,17 @@ export async function unpublishDraft( .set({ status: 'draft' }) .where(eq(draft.id, draftId)); - return { status: 'unpublished' }; + return { status: 'unpublished', kind: deleted[0].kind }; }, ); if (result.status === 'unpublished') { scheduleDraftImageCleanup(draftId); revalidateSitemap(); + // 회차였다면 공개 화면(목록·프로젝트·이전/다음)에서 바로 빠지도록 + if (result.kind === 'comlog') { + revalidateComlogPages(); + } } return result; diff --git a/lib/posts/post-values.test.ts b/lib/posts/post-values.test.ts index 23ccd3d..b3871bd 100644 --- a/lib/posts/post-values.test.ts +++ b/lib/posts/post-values.test.ts @@ -19,11 +19,17 @@ const link = (value: string, href: string): JSONContent => ({ }); describe('parsePostVisibility', () => { - it('공개 범위는 public, unlisted 만', () => { - expect(parsePostVisibility('public')).toBe('public'); - expect(parsePostVisibility('unlisted')).toBe('unlisted'); - expect(parsePostVisibility('private')).toBeNull(); - expect(parsePostVisibility(undefined)).toBeNull(); + it('일반 글의 공개 범위는 public, unlisted 만', () => { + expect(parsePostVisibility('public', 'post')).toBe('public'); + expect(parsePostVisibility('unlisted', 'post')).toBe('unlisted'); + expect(parsePostVisibility('private', 'post')).toBeNull(); + expect(parsePostVisibility(undefined, 'post')).toBeNull(); + }); + + it('comlog 회차는 private 도 허용', () => { + expect(parsePostVisibility('private', 'comlog')).toBe('private'); + expect(parsePostVisibility('public', 'comlog')).toBe('public'); + expect(parsePostVisibility('secret', 'comlog')).toBeNull(); }); }); diff --git a/lib/posts/post-values.ts b/lib/posts/post-values.ts index ae6f735..f1d44c5 100644 --- a/lib/posts/post-values.ts +++ b/lib/posts/post-values.ts @@ -1,8 +1,8 @@ import type { JSONContent } from '@tiptap/core'; import { + POST_VISIBILITIES, REGULAR_POST_VISIBILITIES, type PostVisibility, - type RegularPostVisibility, } from '@/lib/db/schema/post'; import type { Locale } from '@/lib/i18n/config'; import { @@ -11,18 +11,22 @@ import { type SanitizePostContentOptions, } from '@/lib/posts/post-content'; import { createPostSlug } from '@/lib/posts/post-path'; +import type { DraftKind } from '@/lib/studio/options'; /** * 게시글 저장 값 조립 (서버 액션에서 쓰는 순수 함수, 테스트 가능) */ // 클라이언트가 보낸 공개 범위를 확인 (허용 값이 아니면 null) +// - private 은 comlog 회차만 (DB 검사 제약과 같은 규칙) export const parsePostVisibility = ( value: unknown, -): RegularPostVisibility | null => { - return ( - REGULAR_POST_VISIBILITIES.find((visibility) => visibility === value) ?? null - ); + kind: DraftKind, +): PostVisibility | null => { + const allowed: readonly PostVisibility[] = + kind === 'comlog' ? POST_VISIBILITIES : REGULAR_POST_VISIBILITIES; + + return allowed.find((visibility) => visibility === value) ?? null; }; /** diff --git a/lib/studio/queries.ts b/lib/studio/queries.ts index 3f4a81b..a8bbdb8 100644 --- a/lib/studio/queries.ts +++ b/lib/studio/queries.ts @@ -2,6 +2,8 @@ import 'server-only'; import { cache } from 'react'; import { and, asc, desc, eq, sql } from 'drizzle-orm'; import type { JSONContent } from '@tiptap/core'; +import { getComlogProject } from '@/lib/comlog/store'; +import type { ComlogVisibility } from '@/lib/comlog/rules'; import { db } from '@/lib/db'; import { draft, @@ -85,6 +87,8 @@ export interface StudioDraft extends Omit< tags: string[]; // 게시 창의 작성자 표시: 미리보기용 GitHub 정보와 처음 선택돼 있을 설정 publishAuthor: PublishAuthor; + // comlog 회차일 때 프로젝트의 공개 범위 (게시 창의 실효 공개 범위 안내용, 일반 글은 null) + projectVisibility: ComlogVisibility | null; } export interface PublishAuthor { @@ -330,6 +334,7 @@ export const getStudioDraft = async ( latestJob, latestDraftJob, publishAuthor, + project, ] = await Promise.all([ // id 가 없는 빈칸(기능 추가 전 본문)에 id 를 붙여 저장 (빈칸 채우기는 저장된 id 로 찾음) isDraftDocument(row.content) ? persistBlankIds(row.id, row.content) : null, @@ -338,6 +343,9 @@ export const getStudioDraft = async ( getLatestDraftJob(row.id), getLatestDraftJob(row.id, 'draft'), getPublishAuthor(userId, currentAuthor), + row.kind === 'comlog' + ? getComlogProject(userId, repositoryId) + : Promise.resolve(null), ]); return { @@ -359,5 +367,6 @@ export const getStudioDraft = async ( ? latestDraftJob.id : null, publishAuthor, + projectVisibility: project?.visibility ?? null, }; }; From 14fcf0219d18d49f75775335d1475257262e8b27 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 16:08:35 +0900 Subject: [PATCH 13/27] =?UTF-8?q?fix(comlog):=20=EB=B0=80=EB=A6=B0=20?= =?UTF-8?q?=EC=BB=A4=EB=B0=8B=EC=9D=84=20=EC=A0=9C=EC=99=B8=20=EB=A9=94?= =?UTF-8?q?=EB=89=B4=EB=A1=9C=20=EC=B9=98=EC=9A=B8=20=EC=88=98=20=EC=9E=88?= =?UTF-8?q?=EA=B2=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/auto-draft/exclusion.test.ts | 18 ++++++++++++++++++ lib/auto-draft/exclusion.ts | 11 +++++++++++ lib/auto-draft/markers.test.ts | 27 +++++++++++++++++++++++++++ lib/auto-draft/store.ts | 16 ++++++++++++++-- lib/generation/jobs.test.ts | 23 +++++++++++++++++++++++ lib/generation/jobs.ts | 7 ++++++- 6 files changed, 99 insertions(+), 3 deletions(-) create mode 100644 lib/auto-draft/exclusion.test.ts create mode 100644 lib/auto-draft/exclusion.ts diff --git a/lib/auto-draft/exclusion.test.ts b/lib/auto-draft/exclusion.test.ts new file mode 100644 index 0000000..644d1de --- /dev/null +++ b/lib/auto-draft/exclusion.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { shouldOverwriteExcludedReason } from '@/lib/auto-draft/exclusion'; + +describe('shouldOverwriteExcludedReason', () => { + it('밀린 커밋을 사용자가 제외하면 user 로 바꿈', () => { + expect(shouldOverwriteExcludedReason('backlog', 'user')).toBe(true); + }); + + it('force_push 와 기존 user 사유는 덮어쓰지 않음', () => { + expect(shouldOverwriteExcludedReason('force_push', 'user')).toBe(false); + expect(shouldOverwriteExcludedReason('user', 'user')).toBe(false); + }); + + it('밀림 기록이 다른 사유를 덮어쓰지 않음', () => { + expect(shouldOverwriteExcludedReason('user', 'backlog')).toBe(false); + expect(shouldOverwriteExcludedReason('backlog', 'backlog')).toBe(false); + }); +}); diff --git a/lib/auto-draft/exclusion.ts b/lib/auto-draft/exclusion.ts new file mode 100644 index 0000000..d60bc59 --- /dev/null +++ b/lib/auto-draft/exclusion.ts @@ -0,0 +1,11 @@ +import type { ExcludedCommitReason } from '@/lib/db/schema/auto-draft'; + +/** + * 이미 제외 목록에 있는 커밋의 사유를 새 사유로 바꿀지 + * - 밀린 커밋(backlog)만 사용자가 직접 제외하면 'user' 로 바뀜 (경계가 이미 지나가 있어 제외 취소 시 행 삭제로 충분) + * - force_push 등 나머지는 그대로 둠 + */ +export const shouldOverwriteExcludedReason = ( + existing: ExcludedCommitReason, + incoming: ExcludedCommitReason, +): boolean => existing === 'backlog' && incoming === 'user'; diff --git a/lib/auto-draft/markers.test.ts b/lib/auto-draft/markers.test.ts index 14f9caf..4291cc2 100644 --- a/lib/auto-draft/markers.test.ts +++ b/lib/auto-draft/markers.test.ts @@ -195,3 +195,30 @@ describe('backlog·applied 표시', () => { ).toEqual([{ kind: 'not_collected' }]); }); }); + +describe('밀린 커밋을 제외한 뒤', () => { + const backlogState = { + ...state, + backlogShas: new Set(['k']), + }; + + it('밀린 커밋의 메뉴는 제외', () => { + expect(getCommitMenu({ ...base, sha: 'k' }, backlogState)).toEqual({ + exclude: 'exclude', + }); + }); + + it('사유가 user 로 바뀌면 제외 표시와 제외 취소 메뉴, backlog 표시는 없다', () => { + // 서버가 backlog 행을 user 로 바꾸면 backlogShas 에서 빠지고 excluded 에 user 로 들어옴 + const moved = { + ...state, + excluded: new Map([['k', 'user']]), + }; + const commit = { ...base, sha: 'k' }; + + expect(getCommitMarkers(commit, moved)).toEqual([ + { kind: 'excluded', reason: 'user' }, + ]); + expect(getCommitMenu(commit, moved)).toEqual({ exclude: 'restore' }); + }); +}); diff --git a/lib/auto-draft/store.ts b/lib/auto-draft/store.ts index 40152eb..6aec9b9 100644 --- a/lib/auto-draft/store.ts +++ b/lib/auto-draft/store.ts @@ -364,7 +364,7 @@ export async function getAppliedShas( return row?.commitShas ?? []; } -// 커밋을 자동 초안 대상에서 제외 (이미 제외된 SHA 는 무시) +// 커밋을 자동 초안 대상에서 제외 (이미 제외된 SHA 는 무시, 단 밀린 커밋을 사용자가 제외하면 user 로 바뀜: shouldOverwriteExcludedReason) export async function excludeCommits( userId: string, repositoryId: string, @@ -376,7 +376,19 @@ export async function excludeCommits( await db .insert(repositoryExcludedCommit) .values(shas.map((sha) => ({ userId, repositoryId, sha, reason }))) - .onConflictDoNothing(); + .onConflictDoUpdate({ + target: [ + repositoryExcludedCommit.userId, + repositoryExcludedCommit.repositoryId, + repositoryExcludedCommit.sha, + ], + set: { reason }, + // 위 규칙: 기존 사유가 backlog 이고 새 사유가 user 일 때만 덮어씀 + setWhere: + reason === 'user' + ? eq(repositoryExcludedCommit.reason, 'backlog') + : sql`false`, + }); } // 회차를 만들지 못해 밀린 커밋으로 남김 (이미 제외 목록에 있으면 그 사유를 그대로 둠) diff --git a/lib/generation/jobs.test.ts b/lib/generation/jobs.test.ts index f8ef0e8..477d160 100644 --- a/lib/generation/jobs.test.ts +++ b/lib/generation/jobs.test.ts @@ -21,8 +21,11 @@ vi.mock('@/lib/db', () => ({ db: builder })); vi.mock('@/lib/comlog/backlog', () => ({ syncFailedComlogBacklog: vi.fn(), })); +vi.mock('@/lib/observability/report-error', () => ({ reportError: vi.fn() })); const jobs = await import('@/lib/generation/jobs'); +const { syncFailedComlogBacklog } = await import('@/lib/comlog/backlog'); +const { reportError } = await import('@/lib/observability/report-error'); const toSql = (condition: SQL) => new PgDialect().sqlToQuery(condition).sql; describe('visibleToUser', () => { @@ -206,3 +209,23 @@ describe('isTriggerDuplicateConflict', () => { expect(jobs.isTriggerDuplicateConflict(null)).toBe(false); }); }); + +describe('applyPendingDraftJobs', () => { + it('밀린 커밋 반영이 실패해도 던지지 않고 보고만 한다', async () => { + const error = new Error('sync failed'); + vi.mocked(syncFailedComlogBacklog).mockRejectedValueOnce(error); + // 반영할 완료 작업이 없도록 orderBy 가 빈 목록을 돌려줌 + builder.orderBy = async () => []; + + await expect( + jobs.applyPendingDraftJobs('u1', 'r1'), + ).resolves.toBeUndefined(); + expect(reportError).toHaveBeenCalledWith( + error, + 'generation.sync-comlog-backlog', + { repositoryId: 'r1' }, + ); + + builder.orderBy = () => builder; + }); +}); diff --git a/lib/generation/jobs.ts b/lib/generation/jobs.ts index 0ccf24c..adda94c 100644 --- a/lib/generation/jobs.ts +++ b/lib/generation/jobs.ts @@ -557,7 +557,12 @@ export const applyPendingDraftJobs = async ( } // Lambda 가 직접 failed 로 남긴 회차 작업의 커밋도 다음 조회 때 밀린 커밋으로 반영 - await syncFailedComlogBacklog(userId, repositoryId); + // 부가 반영이라 실패해도 스튜디오 화면 로드를 막지 않음 + try { + await syncFailedComlogBacklog(userId, repositoryId); + } catch (error) { + reportError(error, 'generation.sync-comlog-backlog', { repositoryId }); + } }; // 초안을 바꿀 수 없는 상태인지 (정리 후 진행 중인 초안 작성 작업이 남아 있으면 잠금, 빈칸 채우기는 잠그지 않음) From f8cefcfe60e6431d0b9b72aa883a510968314a33 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 16:10:36 +0900 Subject: [PATCH 14/27] =?UTF-8?q?fix(comlog):=20=EC=A0=9C=EC=99=B8=20?= =?UTF-8?q?=EB=8D=AE=EC=96=B4=EC=93=B0=EA=B8=B0=20=EA=B7=9C=EC=B9=99?= =?UTF-8?q?=EC=9D=84=20=ED=95=9C=20=EA=B3=B3=EC=9C=BC=EB=A1=9C=20=EB=AA=A8?= =?UTF-8?q?=EC=9C=BC=EA=B3=A0=20=EC=A4=91=EB=B3=B5=20SHA=20=EC=A0=95?= =?UTF-8?q?=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- lib/auto-draft/exclusion.test.ts | 29 ++++++++++++++-------- lib/auto-draft/exclusion.ts | 18 ++++++++++---- lib/auto-draft/store.ts | 41 +++++++++++++++++++------------- lib/generation/jobs.test.ts | 26 ++++++++++---------- 4 files changed, 70 insertions(+), 44 deletions(-) diff --git a/lib/auto-draft/exclusion.test.ts b/lib/auto-draft/exclusion.test.ts index 644d1de..237948a 100644 --- a/lib/auto-draft/exclusion.test.ts +++ b/lib/auto-draft/exclusion.test.ts @@ -1,18 +1,27 @@ +import { PgDialect } from 'drizzle-orm/pg-core'; import { describe, expect, it } from 'vitest'; -import { shouldOverwriteExcludedReason } from '@/lib/auto-draft/exclusion'; +import { overwriteWhere, uniqueShas } from '@/lib/auto-draft/exclusion'; -describe('shouldOverwriteExcludedReason', () => { - it('밀린 커밋을 사용자가 제외하면 user 로 바꿈', () => { - expect(shouldOverwriteExcludedReason('backlog', 'user')).toBe(true); +describe('overwriteWhere', () => { + it('사용자 제외는 기존 backlog 행만 덮어쓰는 조건', () => { + const { sql, params } = new PgDialect().sqlToQuery(overwriteWhere('user')!); + + expect(sql).toContain('"reason" = $1'); + expect(params).toEqual(['backlog']); + }); + + it('그 밖의 사유는 덮어쓰지 않음 (force_push 보존, 밀림 기록은 기존 사유 유지)', () => { + expect(overwriteWhere('force_push')).toBeNull(); + expect(overwriteWhere('backlog')).toBeNull(); }); +}); - it('force_push 와 기존 user 사유는 덮어쓰지 않음', () => { - expect(shouldOverwriteExcludedReason('force_push', 'user')).toBe(false); - expect(shouldOverwriteExcludedReason('user', 'user')).toBe(false); +describe('uniqueShas', () => { + it('겹치는 SHA 를 순서대로 하나만 남김', () => { + expect(uniqueShas(['a', 'b', 'a', 'c', 'b'])).toEqual(['a', 'b', 'c']); }); - it('밀림 기록이 다른 사유를 덮어쓰지 않음', () => { - expect(shouldOverwriteExcludedReason('user', 'backlog')).toBe(false); - expect(shouldOverwriteExcludedReason('backlog', 'backlog')).toBe(false); + it('빈 목록은 그대로', () => { + expect(uniqueShas([])).toEqual([]); }); }); diff --git a/lib/auto-draft/exclusion.ts b/lib/auto-draft/exclusion.ts index d60bc59..74e7523 100644 --- a/lib/auto-draft/exclusion.ts +++ b/lib/auto-draft/exclusion.ts @@ -1,11 +1,19 @@ +import { eq, type SQL } from 'drizzle-orm'; import type { ExcludedCommitReason } from '@/lib/db/schema/auto-draft'; +import { repositoryExcludedCommit } from '@/lib/db/schema/auto-draft'; /** - * 이미 제외 목록에 있는 커밋의 사유를 새 사유로 바꿀지 + * 제외 목록 기록 규칙 (순수) + */ + +// 같은 SHA 를 한 문장에 두 번 넣으면 ON CONFLICT DO UPDATE 가 거부되므로 중복을 없앰 (순서 유지) +export const uniqueShas = (shas: readonly string[]): string[] => + Array.from(new Set(shas)); + +/** + * 이미 제외 목록에 있는 커밋의 사유를 덮어쓸 조건 (null 이면 덮어쓰지 않음) * - 밀린 커밋(backlog)만 사용자가 직접 제외하면 'user' 로 바뀜 (경계가 이미 지나가 있어 제외 취소 시 행 삭제로 충분) * - force_push 등 나머지는 그대로 둠 */ -export const shouldOverwriteExcludedReason = ( - existing: ExcludedCommitReason, - incoming: ExcludedCommitReason, -): boolean => existing === 'backlog' && incoming === 'user'; +export const overwriteWhere = (reason: ExcludedCommitReason): SQL | null => + reason === 'user' ? eq(repositoryExcludedCommit.reason, 'backlog') : null; diff --git a/lib/auto-draft/store.ts b/lib/auto-draft/store.ts index 6aec9b9..fc8d52f 100644 --- a/lib/auto-draft/store.ts +++ b/lib/auto-draft/store.ts @@ -12,6 +12,7 @@ import { } from 'drizzle-orm'; import type { ExcludedCommitReason } from '@/lib/db/schema/auto-draft'; import type { DraftPromptStatus } from '@/lib/db/schema/draft'; +import { overwriteWhere, uniqueShas } from '@/lib/auto-draft/exclusion'; import { getBranchHead, type AutoDraftRepo } from '@/lib/auto-draft/github'; import type { ConsumedScope } from '@/lib/auto-draft/trigger'; import { db } from '@/lib/db'; @@ -364,31 +365,37 @@ export async function getAppliedShas( return row?.commitShas ?? []; } -// 커밋을 자동 초안 대상에서 제외 (이미 제외된 SHA 는 무시, 단 밀린 커밋을 사용자가 제외하면 user 로 바뀜: shouldOverwriteExcludedReason) +// 커밋을 자동 초안 대상에서 제외 (이미 제외된 SHA 는 무시, 단 밀린 커밋을 사용자가 제외하면 user 로 바뀜: overwriteWhere) export async function excludeCommits( userId: string, repositoryId: string, shas: string[], reason: ExcludedCommitReason, ): Promise { - if (shas.length === 0) return; + // 한 문장 안의 중복 SHA 는 ON CONFLICT DO UPDATE 가 거부함 + const unique = uniqueShas(shas); - await db + if (unique.length === 0) return; + + const insert = db .insert(repositoryExcludedCommit) - .values(shas.map((sha) => ({ userId, repositoryId, sha, reason }))) - .onConflictDoUpdate({ - target: [ - repositoryExcludedCommit.userId, - repositoryExcludedCommit.repositoryId, - repositoryExcludedCommit.sha, - ], - set: { reason }, - // 위 규칙: 기존 사유가 backlog 이고 새 사유가 user 일 때만 덮어씀 - setWhere: - reason === 'user' - ? eq(repositoryExcludedCommit.reason, 'backlog') - : sql`false`, - }); + .values(unique.map((sha) => ({ userId, repositoryId, sha, reason }))); + const setWhere = overwriteWhere(reason); + + if (!setWhere) { + await insert.onConflictDoNothing(); + return; + } + + await insert.onConflictDoUpdate({ + target: [ + repositoryExcludedCommit.userId, + repositoryExcludedCommit.repositoryId, + repositoryExcludedCommit.sha, + ], + set: { reason }, + setWhere, + }); } // 회차를 만들지 못해 밀린 커밋으로 남김 (이미 제외 목록에 있으면 그 사유를 그대로 둠) diff --git a/lib/generation/jobs.test.ts b/lib/generation/jobs.test.ts index 477d160..c0aa10b 100644 --- a/lib/generation/jobs.test.ts +++ b/lib/generation/jobs.test.ts @@ -215,17 +215,19 @@ describe('applyPendingDraftJobs', () => { const error = new Error('sync failed'); vi.mocked(syncFailedComlogBacklog).mockRejectedValueOnce(error); // 반영할 완료 작업이 없도록 orderBy 가 빈 목록을 돌려줌 - builder.orderBy = async () => []; - - await expect( - jobs.applyPendingDraftJobs('u1', 'r1'), - ).resolves.toBeUndefined(); - expect(reportError).toHaveBeenCalledWith( - error, - 'generation.sync-comlog-backlog', - { repositoryId: 'r1' }, - ); - - builder.orderBy = () => builder; + try { + builder.orderBy = async () => []; + + await expect( + jobs.applyPendingDraftJobs('u1', 'r1'), + ).resolves.toBeUndefined(); + expect(reportError).toHaveBeenCalledWith( + error, + 'generation.sync-comlog-backlog', + { repositoryId: 'r1' }, + ); + } finally { + builder.orderBy = () => builder; + } }); }); From a405548c6b9f57c71ab31cc4e35c8e705bb70859 Mon Sep 17 00:00:00 2001 From: Jayden Date: Tue, 1 Dec 2026 16:12:59 +0900 Subject: [PATCH 15/27] =?UTF-8?q?feat(comlog):=20=EC=A0=80=EC=9E=A5?= =?UTF-8?q?=EC=86=8C=20=EC=84=A4=EC=A0=95=EC=9D=98=20comlog=20=ED=86=A0?= =?UTF-8?q?=EA=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../studio/auto-draft-settings-section.tsx | 167 ++++++++++++++++++ lib/actions/comlog.ts | 125 +++++++++++++ lib/comlog/rules.test.ts | 13 ++ lib/comlog/rules.ts | 6 + 4 files changed, 311 insertions(+) create mode 100644 lib/actions/comlog.ts diff --git a/components/studio/auto-draft-settings-section.tsx b/components/studio/auto-draft-settings-section.tsx index b47295d..46bec2e 100644 --- a/components/studio/auto-draft-settings-section.tsx +++ b/components/studio/auto-draft-settings-section.tsx @@ -8,6 +8,8 @@ import { BRAND_BUTTON_CLASS, OUTLINE_BUTTON_CLASS, } from '@/components/studio/studio-styles'; +import { getComlogPanelState, toggleComlog } from '@/lib/actions/comlog'; +import { shouldRecommendPreset } from '@/lib/comlog/rules'; import { getAutoDraftSettings, saveAutoDraftSettings, @@ -57,6 +59,57 @@ const OptionValueTable = () => ( ); +// 커밋 제목 트리거별 동작 (comlog 가 꺼져 있으면 회차는 만들어지지 않음) +const TriggerUsageTable = ({ comlogEnabled }: { comlogEnabled: boolean }) => ( +
+ + + + + + + + + + + + + + + +
+ [comdraft] + + comlog 회차 +
+ [comdraft] post + + 블로그 글 +
+ [comdraft] post log + + 둘 다 (쿼터를 두 번 써요) +
+ {!comlogEnabled && ( +

+ + comlog 를 켜야 회차가 만들어집니다. 꺼져 있으면 [comdraft] 는 블로그 + 글로 동작합니다. + +

+ )} +
+); + const Switch = ({ checked, disabled, @@ -88,6 +141,92 @@ const Switch = ({ ); +/** + * comlog 사용 토글 + * - 열 때 현재 켜짐 여부를 한 번 조회 (조회 전에는 토글을 잠금) + * - 켜져 있는데 프리셋(위 입력값 기준)이 짧으면 회차 품질 안내를 보임 + */ +const ComlogToggle = ({ + repositoryId, + prompt, + enabled, + onEnabledChange, +}: { + repositoryId: string; + prompt: string; + enabled: boolean | null; + onEnabledChange: (next: boolean) => void; +}) => { + const { t } = useLingui(); + const labelId = useId(); + const [notice, setNotice] = useState(null); + const [isToggling, startToggling] = useTransition(); + + const toggle = (next: boolean) => { + setNotice(null); + startToggling(async () => { + try { + const result = await toggleComlog(repositoryId, next); + + if (result.status === 'ok') { + onEnabledChange(next); + } else if (result.status === 'github_unavailable') { + setNotice( + t`GitHub 에서 저장소 정보를 가져오지 못해 켜지 못했습니다. 잠시 후 다시 시도해 주세요.`, + ); + } else { + setNotice(t`저장소를 찾을 수 없습니다.`); + } + } catch (error) { + reportError(error, 'studio.comlog.toggle'); + setNotice(t`설정을 바꾸지 못했습니다. 다시 시도해 주세요.`); + } + }); + }; + + return ( +
+
+
+

+ comlog 사용 +

+

+ + 커밋을 모아 프로젝트의 개발 과정을 회차별로 기록하는 공개 페이지를 + 만듭니다. 끄면 공개 페이지에서 내려가고 기록은 남아 있습니다. + +

+
+ +
+ {notice && ( +

+ {notice} +

+ )} + {enabled && shouldRecommendPreset(prompt) && ( +

+ + 프리셋에 프로젝트 개요와 목적을 적어 두면 회차 품질이 좋아져요 + +

+ )} +
+ ); +}; + const SettingsForm = ({ initial }: { initial: Loaded }) => { const { t } = useLingui(); const { repository, autoDraft } = useStudio(); @@ -100,6 +239,26 @@ const SettingsForm = ({ initial }: { initial: Loaded }) => { const [saveNotice, setSaveNotice] = useState(null); const [isToggling, startToggling] = useTransition(); const [isSaving, startSaving] = useTransition(); + // null: 아직 조회 전 + const [comlogEnabled, setComlogEnabled] = useState(null); + + useEffect(() => { + let isStale = false; + + getComlogPanelState(repository.id) + .then((result) => { + if (!isStale) { + setComlogEnabled(result.status === 'ok' ? result.enabled : false); + } + }) + .catch((error: unknown) => { + reportError(error, 'studio.comlog.load'); + }); + + return () => { + isStale = true; + }; + }, [repository.id]); const toggle = (next: boolean) => { setToggleNotice(null); @@ -195,6 +354,13 @@ const SettingsForm = ({ initial }: { initial: Loaded }) => {

)} + +