diff --git a/app/[lang]/admin/[adminKey]/(console)/comlog/page.tsx b/app/[lang]/admin/[adminKey]/(console)/comlog/page.tsx
new file mode 100644
index 0000000..3eed610
--- /dev/null
+++ b/app/[lang]/admin/[adminKey]/(console)/comlog/page.tsx
@@ -0,0 +1,156 @@
+import { msg } from '@lingui/core/macro';
+import { Trans } from '@lingui/react/macro';
+import {
+ ADMIN_INPUT_CLASS,
+ ADMIN_TITLE_CLASS,
+} from '@/components/admin/admin-styles';
+import AdminPagination from '@/components/admin/admin-pagination';
+import AdminTable from '@/components/admin/admin-table';
+import ConfirmActionButton from '@/components/admin/confirm-action-button';
+import VisibilityLabel from '@/components/admin/visibility-label';
+import { BRAND_BUTTON_CLASS } from '@/components/studio/studio-styles';
+import {
+ banComlogProject,
+ unbanComlogProject,
+} from '@/lib/actions/admin/comlog';
+import { listComlogProjects } from '@/lib/admin/comlog-queries';
+import { requireAdmin, requireAdminKey } from '@/lib/admin/guard';
+import { ADMIN_PAGE_SIZE } from '@/lib/admin/pagination';
+import { adminPath } from '@/lib/admin/path-key';
+import { canPerform } from '@/lib/admin/roles';
+import { getLocale, initLingui } from '@/lib/i18n/server';
+import { parsePageParam } from '@/lib/posts/post-list';
+
+interface AdminComlogPageProps {
+ searchParams: Promise>;
+}
+
+// 쿼리 값 (여러 번 들어오면 첫 값만, 너무 긴 값은 자름)
+const readParam = (value: string | string[] | undefined): string => {
+ const first = Array.isArray(value) ? value[0] : value;
+
+ return (first ?? '').trim().slice(0, 100);
+};
+
+// 어드민 comlog 프로젝트 목록: 이름·소유자 검색, 숨기기·해제, 50개씩
+export default async function AdminComlogPage({
+ searchParams,
+}: AdminComlogPageProps) {
+ const i18n = await initLingui();
+ const admin = await requireAdmin('view');
+
+ const params = await searchParams;
+ const q = readParam(params.q);
+ const page = parsePageParam(params.page);
+ const locale = await getLocale();
+ const basePath = adminPath(locale, requireAdminKey(), 'comlog');
+ const canModerate = canPerform(admin.role, 'comlog.ban');
+ const { rows, total } = await listComlogProjects({ q, page });
+
+ return (
+
+
comlog
+
+
+
+
프로젝트 },
+ { key: 'owner', label: 소유자 },
+ {
+ key: 'entries',
+ label: 회차 수,
+ className: 'text-right',
+ },
+ { key: 'progress', label: 진행 상태 },
+ { key: 'visibility', label: 공개 범위 },
+ { key: 'status', label: 상태 },
+ ...(canModerate
+ ? [{ key: 'action', label: 조치 }]
+ : []),
+ ]}
+ rows={rows.map((row) => ({
+ id: row.id,
+ cells: {
+ name: {row.name},
+ owner: row.ownerGithubLogin ?? row.ownerEmail,
+ entries: row.entryCount,
+ progress:
+ row.status === 'completed' ? (
+ 완료
+ ) : (
+ 진행 중
+ ),
+ visibility: ,
+ status: (
+
+ {row.bannedAt ? (
+
+ 숨김
+
+ ) : null}
+ {row.enabled ? null : (
+
+ 꺼짐
+
+ )}
+ {row.bannedAt || !row.enabled ? null : '-'}
+
+ ),
+ action: row.bannedAt ? (
+
+ ) : (
+
+ 프로젝트와 모든 회차가 공개 목록, 상세, 사이트맵에서 빠져요.
+
+ }
+ danger
+ reasonField
+ hidden={{ projectId: row.id }}
+ />
+ ),
+ },
+ }))}
+ empty={조건에 맞는 프로젝트가 없어요}
+ />
+
+
+
+ );
+}
diff --git a/app/[lang]/admin/[adminKey]/(console)/page.tsx b/app/[lang]/admin/[adminKey]/(console)/page.tsx
index a83d416..acd7a5a 100644
--- a/app/[lang]/admin/[adminKey]/(console)/page.tsx
+++ b/app/[lang]/admin/[adminKey]/(console)/page.tsx
@@ -1,3 +1,4 @@
+import VisibilityLabel from '@/components/admin/visibility-label';
import type { ReactNode } from 'react';
import { msg } from '@lingui/core/macro';
import { Trans } from '@lingui/react/macro';
@@ -77,9 +78,6 @@ const StatusLabel = ({ status }: { status: string }) => {
return 답변 대기;
};
-const VisibilityLabel = ({ visibility }: { visibility: string }) =>
- visibility === 'public' ? 전체 공개 : 일부 공개;
-
// 어드민 대시보드: 화면을 열 때 한 번 읽고, 새로고침 버튼을 눌렀을 때만 다시 읽음
export default async function AdminDashboardPage({
searchParams,
diff --git a/app/[lang]/admin/[adminKey]/(console)/posts/[postId]/page.tsx b/app/[lang]/admin/[adminKey]/(console)/posts/[postId]/page.tsx
index 8382da5..7f549f8 100644
--- a/app/[lang]/admin/[adminKey]/(console)/posts/[postId]/page.tsx
+++ b/app/[lang]/admin/[adminKey]/(console)/posts/[postId]/page.tsx
@@ -4,6 +4,7 @@ import { msg } from '@lingui/core/macro';
import { Trans } from '@lingui/react/macro';
import { ADMIN_TITLE_CLASS } from '@/components/admin/admin-styles';
import AdminTable from '@/components/admin/admin-table';
+import VisibilityLabel from '@/components/admin/visibility-label';
import ConfirmActionButton from '@/components/admin/confirm-action-button';
import { banPost, deletePost, unbanPost } from '@/lib/actions/admin/posts';
import { requireAdmin, requireAdminKey } from '@/lib/admin/guard';
@@ -103,11 +104,7 @@ export default async function AdminPostDetailPage({
공개 범위}>
- {post.visibility === 'public' ? (
- 전체 공개
- ) : (
- 일부 공개
- )}
+
언어}>{post.locale}
게시일}>
diff --git a/app/[lang]/admin/[adminKey]/(console)/posts/page.tsx b/app/[lang]/admin/[adminKey]/(console)/posts/page.tsx
index ab47ce5..7b98108 100644
--- a/app/[lang]/admin/[adminKey]/(console)/posts/page.tsx
+++ b/app/[lang]/admin/[adminKey]/(console)/posts/page.tsx
@@ -6,6 +6,7 @@ import {
ADMIN_TITLE_CLASS,
} from '@/components/admin/admin-styles';
import AdminPagination from '@/components/admin/admin-pagination';
+import VisibilityLabel from '@/components/admin/visibility-label';
import AdminTable from '@/components/admin/admin-table';
import LocalizedLink from '@/components/shared/localized-link';
import { BRAND_BUTTON_CLASS } from '@/components/studio/studio-styles';
@@ -18,6 +19,7 @@ import {
parseVisibility,
} from '@/lib/admin/post-queries';
import { getLocale, initLingui } from '@/lib/i18n/server';
+import type { AdminPostKindFilter } from '@/lib/posts/kind';
import { parsePageParam } from '@/lib/posts/post-list';
interface AdminPostsPageProps {
@@ -31,6 +33,10 @@ const readParam = (value: string | string[] | undefined): string => {
return (first ?? '').trim().slice(0, 100);
};
+// 종류 필터 (알 수 없는 값은 기본인 일반 글)
+const parseKind = (value: string): AdminPostKindFilter =>
+ value === 'comlog' || value === 'all' ? value : 'post';
+
const formatDate = (date: Date, locale: string) =>
new Intl.DateTimeFormat(locale, {
timeZone: 'Asia/Seoul',
@@ -48,11 +54,13 @@ export default async function AdminPostsPage({
const q = readParam(params.q);
const visibility = parseVisibility(readParam(params.visibility));
const postLocale = parsePostLocale(readParam(params.language));
+ const kind = parseKind(readParam(params.kind));
const page = parsePageParam(params.page);
const locale = await getLocale();
const basePath = adminPath(locale, requireAdminKey(), 'posts');
const { rows, total } = await listPosts({
q,
+ kind,
visibility,
locale: postLocale,
page,
@@ -78,6 +86,16 @@ export default async function AdminPostsPage({
placeholder={i18n._(msg`제목 또는 작성자`)}
className={`${ADMIN_INPUT_CLASS} min-w-48 flex-1`}
/>
+
)}
+
+
+ {/* 자동 초안 기본 옵션은 일반 글 기준 (회차는 유형·길이가 고정이라 따로 고르지 않음) */}
@@ -265,6 +433,7 @@ const SettingsForm = ({ initial }: { initial: Loaded }) => {
[comdraft] friendly short
+
PR 제목이나 병합 커밋 제목을 [comdraft] 로 시작해도 병합될 때 한 번
diff --git a/components/studio/comlog-cover-upload.test.ts b/components/studio/comlog-cover-upload.test.ts
new file mode 100644
index 0000000..9acf7c8
--- /dev/null
+++ b/components/studio/comlog-cover-upload.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ uploadComlogCoverFile,
+ type CoverUploadDeps,
+} from '@/components/studio/comlog-cover-upload';
+
+vi.mock('@/lib/observability/report-error', () => ({ reportError: vi.fn() }));
+
+const file = (name = 'cover.png', type = 'image/png', size = 1000) =>
+ ({ name, type, size }) as File;
+
+const deps = (overrides: Partial = {}): CoverUploadDeps => ({
+ request: vi.fn(async () => ({
+ status: 'ok' as const,
+ uploadId: 'upload-1',
+ path: 'u/upload-1',
+ token: 'token',
+ })),
+ upload: vi.fn(async () => true),
+ finalize: vi.fn(async () => ({
+ status: 'ok' as const,
+ imageId: 'upload-1',
+ url: 'https://x.supabase.co/cover.webp',
+ })),
+ ...overrides,
+});
+
+describe('uploadComlogCoverFile', () => {
+ it('주소 발급 → 원본 올리기 → 변환 순서로 올리고 공개 주소를 돌려줌', async () => {
+ const d = deps();
+
+ await expect(uploadComlogCoverFile(d, 'repo-1', file())).resolves.toEqual({
+ status: 'ok',
+ url: 'https://x.supabase.co/cover.webp',
+ });
+ expect(d.upload).toHaveBeenCalledWith('u/upload-1', 'token', file());
+ expect(d.finalize).toHaveBeenCalledWith('repo-1', 'upload-1');
+ });
+
+ it('형식·크기가 맞지 않으면 요청 없이 unsupported', async () => {
+ const d = deps();
+
+ await expect(
+ uploadComlogCoverFile(d, 'repo-1', file('a.heic', 'image/heic')),
+ ).resolves.toEqual({ status: 'unsupported', reason: 'heic' });
+ await expect(
+ uploadComlogCoverFile(d, 'repo-1', file('a.gif', 'text/plain')),
+ ).resolves.toEqual({ status: 'unsupported', reason: 'type' });
+ await expect(
+ uploadComlogCoverFile(d, 'repo-1', file('a.png', 'image/png', 1e9)),
+ ).resolves.toEqual({ status: 'unsupported', reason: 'too_large' });
+ expect(d.request).not.toHaveBeenCalled();
+ });
+
+ it('주소 발급이 막히면 그 사유', async () => {
+ const d = deps({
+ request: vi.fn(async () => ({ status: 'rate_limited' as const })),
+ });
+
+ await expect(uploadComlogCoverFile(d, 'repo-1', file())).resolves.toEqual({
+ status: 'rate_limited',
+ });
+ expect(d.upload).not.toHaveBeenCalled();
+ });
+
+ it('원본을 올리지 못하면 failed', async () => {
+ const d = deps({ upload: vi.fn(async () => false) });
+
+ await expect(uploadComlogCoverFile(d, 'repo-1', file())).resolves.toEqual({
+ status: 'failed',
+ });
+ expect(d.finalize).not.toHaveBeenCalled();
+ });
+
+ it('서버가 거부한 형식은 unsupported, 던지면 failed', async () => {
+ await expect(
+ uploadComlogCoverFile(
+ deps({
+ finalize: vi.fn(async () => ({
+ status: 'unsupported' as const,
+ reason: 'type' as const,
+ })),
+ }),
+ 'repo-1',
+ file(),
+ ),
+ ).resolves.toEqual({ status: 'unsupported', reason: 'type' });
+
+ await expect(
+ uploadComlogCoverFile(
+ deps({
+ request: vi.fn(async () => {
+ throw new Error('network');
+ }),
+ }),
+ 'repo-1',
+ file(),
+ ),
+ ).resolves.toEqual({ status: 'failed' });
+ });
+});
diff --git a/components/studio/comlog-cover-upload.ts b/components/studio/comlog-cover-upload.ts
new file mode 100644
index 0000000..ab352f4
--- /dev/null
+++ b/components/studio/comlog-cover-upload.ts
@@ -0,0 +1,62 @@
+import type {
+ RequestComlogCoverUploadResult,
+ UploadComlogCoverResult,
+} from '@/lib/actions/images';
+import { checkImageFile } from '@/lib/images/rules';
+import { reportError } from '@/lib/observability/report-error';
+
+/**
+ * comlog 프로젝트 대표 이미지 올리기 (Lingui·React 없음, 테스트 대상)
+ * - 편집기 이미지와 같은 두 단계: 주소 발급 → 임시 버킷에 원본 → 서버가 WebP 로 바꿔 프로젝트에 연결
+ */
+
+export type CoverUploadOutcome =
+ | { status: 'ok'; url: string }
+ | { status: 'unsupported'; reason: 'heic' | 'type' | 'too_large' }
+ | { status: 'rate_limited' | 'not_found' | 'failed' };
+
+export interface CoverUploadDeps {
+ request: (repositoryId: string) => Promise;
+ // 임시 버킷에 원본 올리기 (성공 여부)
+ upload: (path: string, token: string, file: File) => Promise;
+ finalize: (
+ repositoryId: string,
+ uploadId: string,
+ ) => Promise;
+}
+
+/** 서버 액션이 던지거나 네트워크가 끊겨도 던지지 않고 failed */
+export const uploadComlogCoverFile = async (
+ deps: CoverUploadDeps,
+ repositoryId: string,
+ file: File,
+): Promise => {
+ const check = checkImageFile(file);
+
+ // 올리기 전 검사의 크기 사유(size)는 서버 결과와 같은 too_large 로 맞춤
+ if (!check.ok) {
+ return {
+ status: 'unsupported',
+ reason: check.reason === 'size' ? 'too_large' : check.reason,
+ };
+ }
+
+ try {
+ const ticket = await deps.request(repositoryId);
+
+ if (ticket.status !== 'ok') {
+ return { status: ticket.status };
+ }
+
+ if (!(await deps.upload(ticket.path, ticket.token, file))) {
+ return { status: 'failed' };
+ }
+
+ const result = await deps.finalize(repositoryId, ticket.uploadId);
+
+ return result.status === 'ok' ? { status: 'ok', url: result.url } : result;
+ } catch (error) {
+ reportError(error, 'studio.comlog.cover-upload');
+ return { status: 'failed' };
+ }
+};
diff --git a/components/studio/comlog-project-editor.tsx b/components/studio/comlog-project-editor.tsx
new file mode 100644
index 0000000..d8aa526
--- /dev/null
+++ b/components/studio/comlog-project-editor.tsx
@@ -0,0 +1,694 @@
+'use client';
+
+import {
+ useId,
+ useRef,
+ useState,
+ useTransition,
+ type ChangeEvent,
+ type FormEvent,
+ type KeyboardEvent,
+} from 'react';
+import Image from 'next/image';
+import { msg } from '@lingui/core/macro';
+import type { MessageDescriptor } from '@lingui/core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { ExternalLink } from 'lucide-react';
+import LocalizedAnchor from '@/components/shared/localized-anchor';
+import Spinner from '@/components/shared/spinner';
+import {
+ uploadComlogCoverFile,
+ type CoverUploadDeps,
+ type CoverUploadOutcome,
+} from '@/components/studio/comlog-cover-upload';
+import PublishAuthorFields from '@/components/studio/publish-author-fields';
+import { useStudio } from '@/components/studio/studio-context';
+import StudioMobileNav from '@/components/studio/studio-mobile-nav';
+import {
+ BRAND_BUTTON_CLASS,
+ OUTLINE_BUTTON_CLASS,
+ THIN_SCROLL_CLASS,
+} from '@/components/studio/studio-styles';
+import { useLocalizedRouter } from '@/hooks/use-localized-router';
+import { saveComlogProject } from '@/lib/actions/comlog';
+import {
+ requestComlogCoverUpload,
+ uploadComlogCover,
+} from '@/lib/actions/images';
+import { getComlogProjectPath } from '@/lib/comlog/paths';
+import {
+ COMLOG_INTRO_MAX_LENGTH,
+ COMLOG_MAX_TECH,
+ COMLOG_NAME_MAX_LENGTH,
+ type ComlogVisibility,
+} from '@/lib/comlog/rules';
+import type { ComlogProjectStatus } from '@/lib/db/schema/comlog';
+import {
+ IMAGE_ACCEPTED_MIME_TYPES,
+ IMAGE_UPLOAD_BUCKET,
+} from '@/lib/images/rules';
+import { reportError } from '@/lib/observability/report-error';
+import { toAuthorDisplayDraft } from '@/lib/posts/author-display';
+import { addTag } from '@/lib/posts/tags';
+import type { ComlogEditorData } from '@/lib/studio/comlog-editor';
+import {
+ toComlogProjectPatch,
+ type ComlogFormProblem,
+ type ComlogProjectForm,
+} from '@/lib/studio/comlog-project-form';
+import { getBrowserSupabase } from '@/lib/supabase/browser';
+
+const coverDeps: CoverUploadDeps = {
+ request: requestComlogCoverUpload,
+ // 브라우저 클라이언트가 없으면(환경 변수 없음) 올리기 실패
+ upload: async (path, token, file) => {
+ const supabase = getBrowserSupabase();
+
+ if (!supabase) {
+ return false;
+ }
+
+ const { error } = await supabase.storage
+ .from(IMAGE_UPLOAD_BUCKET)
+ .uploadToSignedUrl(path, token, file, { contentType: file.type });
+
+ return !error;
+ },
+ finalize: uploadComlogCover,
+};
+
+const FIELD_CLASS =
+ 'w-full rounded border border-line bg-white px-3 text-[13px] leading-[1.6] text-ink outline-none placeholder:text-ink-subtle focus:border-brand aria-invalid:border-danger';
+const LABEL_CLASS = 'text-[12px] leading-[normal] font-medium text-ink';
+const HINT_CLASS = 'text-[12px] leading-[1.6] break-keep text-ink-faint';
+const NOTICE_CLASS =
+ 'rounded-md bg-surface px-4 py-3 text-[12px] leading-[1.6] break-keep text-ink-muted';
+
+const STATUS_LABELS: Record = {
+ in_progress: msg`진행 중`,
+ completed: msg`완료`,
+};
+
+const VISIBILITY_OPTIONS: Record<
+ ComlogVisibility,
+ { label: MessageDescriptor; description: MessageDescriptor }
+> = {
+ public: {
+ label: msg`공개`,
+ description: msg`누구나 comlog 목록과 검색에서 프로젝트를 찾을 수 있습니다`,
+ },
+ unlisted: {
+ label: msg`일부 공개`,
+ description: msg`주소를 아는 사람만 볼 수 있고 목록·검색에는 나오지 않습니다`,
+ },
+ private: {
+ label: msg`비공개`,
+ description: msg`나만 볼 수 있습니다. 회차도 모두 나만 보입니다`,
+ },
+};
+
+const PROBLEM_MESSAGES: Record = {
+ name: msg`프로젝트 이름은 1~${COMLOG_NAME_MAX_LENGTH}자로 입력해 주세요.`,
+ intro: msg`소개는 ${COMLOG_INTRO_MAX_LENGTH}자까지 쓸 수 있습니다.`,
+ demo_url: msg`데모 링크는 http 또는 https 로 시작하는 주소여야 합니다.`,
+ nickname: msg`작성자 별명을 확인해 주세요.`,
+};
+
+const COVER_MESSAGES: Record<
+ Exclude | 'heic' | 'type' | 'too_large',
+ MessageDescriptor
+> = {
+ heic: msg`HEIC 형식은 지원하지 않습니다`,
+ type: msg`JPEG, PNG, WebP, GIF, AVIF 이미지만 넣을 수 있습니다`,
+ // 올리기 전 용량(5MB)과 서버의 해상도 제한을 함께 안내
+ too_large: msg`이미지가 너무 큽니다. 5MB 이하, 너무 크지 않은 해상도로 올려 주세요.`,
+ unsupported: msg`올릴 수 없는 이미지입니다.`,
+ rate_limited: msg`이미지를 너무 자주 올렸습니다. 잠시 후 다시 시도해 주세요.`,
+ not_found: msg`comlog 프로젝트를 찾을 수 없습니다.`,
+ failed: msg`이미지를 올리지 못했습니다. 다시 시도해 주세요.`,
+};
+
+type SaveNotice = 'saved' | 'invalid' | 'not_found' | 'error' | null;
+
+interface TechStackFieldProps {
+ value: string[];
+ onChange: (next: string[]) => void;
+}
+
+// 기술 스택: 입력 후 엔터나 추가로 넣고, 칩을 눌러 뺌 (저장은 아래 저장 버튼으로 한 번에)
+const TechStackField = ({ value, onChange }: TechStackFieldProps) => {
+ const { t } = useLingui();
+ const inputId = useId();
+ const inputRef = useRef(null);
+ const [input, setInput] = useState('');
+ const [isFull, setIsFull] = useState(false);
+ const max = COMLOG_MAX_TECH;
+
+ const add = () => {
+ const result = addTag(value, input, max);
+
+ setIsFull(result.status === 'full');
+
+ if (result.status === 'added') {
+ onChange(result.tags);
+ }
+
+ if (result.status !== 'full') {
+ setInput('');
+ }
+ };
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ // 한글 조합 중 엔터는 조합을 끝내는 키라 추가하지 않음 (폼 제출도 막음)
+ if (event.key !== 'Enter') {
+ return;
+ }
+
+ event.preventDefault();
+
+ if (!event.nativeEvent.isComposing) {
+ add();
+ }
+ };
+
+ return (
+
+
+ {value.length > 0 && (
+
+ {value.map((tag) => (
+ -
+
+
+ ))}
+
+ )}
+
+ setInput(event.target.value)}
+ onKeyDown={handleKeyDown}
+ className={`h-9 max-w-80 min-w-0 ${FIELD_CLASS}`}
+ />
+
+
+
+ {isFull ? (
+
+ 기술 스택은 {max}개까지 넣을 수 있습니다
+
+ ) : (
+
+ 회차를 게시하면 회차의 기술 태그가 더해집니다. 뺀 기술은 다시
+ 더해지지 않아요.
+
+ )}
+
+
+ );
+};
+
+interface CoverFieldProps {
+ repositoryId: string;
+ initialUrl: string | null;
+}
+
+/**
+ * 대표 이미지: 고르면 바로 올려 프로젝트에 연결 (저장 버튼과 별개)
+ * - "자동 이미지로" 는 직접 올린 이미지를 떼고 이름으로 만든 이미지를 씀
+ */
+const CoverField = ({ repositoryId, initialUrl }: CoverFieldProps) => {
+ const { i18n } = useLingui();
+ const router = useLocalizedRouter();
+ const inputId = useId();
+ const [url, setUrl] = useState(initialUrl);
+ const [notice, setNotice] = useState(null);
+ const [isPending, startTransition] = useTransition();
+
+ const handleFile = (event: ChangeEvent) => {
+ const file = event.target.files?.[0];
+
+ // 같은 파일을 다시 고를 수 있도록 비움
+ event.target.value = '';
+
+ if (!file) {
+ return;
+ }
+
+ setNotice(null);
+ startTransition(async () => {
+ const outcome = await uploadComlogCoverFile(
+ coverDeps,
+ repositoryId,
+ file,
+ );
+
+ if (outcome.status === 'ok') {
+ setUrl(outcome.url);
+ router.refresh();
+ return;
+ }
+
+ setNotice(
+ COVER_MESSAGES[
+ outcome.status === 'unsupported' ? outcome.reason : outcome.status
+ ],
+ );
+ });
+ };
+
+ const resetToAuto = () => {
+ setNotice(null);
+ startTransition(async () => {
+ try {
+ const result = await saveComlogProject(repositoryId, {
+ coverImageId: null,
+ });
+
+ if (result === 'ok') {
+ setUrl(null);
+ router.refresh();
+ return;
+ }
+
+ setNotice(COVER_MESSAGES.failed);
+ } catch (error) {
+ reportError(error, 'studio.comlog.cover-reset');
+ setNotice(COVER_MESSAGES.failed);
+ }
+ });
+ };
+
+ return (
+
+
+ 대표 이미지
+
+ {url ? (
+ // 공개 버킷의 WebP 주소를 그대로 씀
+

+ ) : (
+
+
+ 직접 올린 이미지가 없어 프로젝트 이름으로 만든 자동 이미지를 씁니다.
+
+
+ )}
+
+
+ {url && (
+
+ )}
+ {isPending && (
+
+ 대표 이미지를 바꾸는 중...} />
+
+ )}
+
+ {notice && (
+
+ {i18n._(notice)}
+
+ )}
+
+ );
+};
+
+interface ComlogProjectEditorProps {
+ data: ComlogEditorData;
+}
+
+/**
+ * comlog 프로젝트 소개 편집 (스튜디오 편집기 자리)
+ * - 이름, 상태, 소개, 기술 스택, 대표 이미지, GitHub 링크, 데모 링크, 공개 범위, 작성자 표시
+ * - 대표 이미지는 고르는 즉시 올리고, 나머지는 저장 버튼으로 한 번에 저장
+ * - 꺼짐·숨김 상태와 프리셋 권장은 맨 위 안내로
+ */
+const ComlogProjectEditor = ({ data }: ComlogProjectEditorProps) => {
+ const { t, i18n } = useLingui();
+ const router = useLocalizedRouter();
+ const { repository } = useStudio();
+ const { project, isPrivateRepository, recommendPreset, author } = data;
+ const nameId = useId();
+ const introId = useId();
+ const demoId = useId();
+ const githubId = useId();
+ const [form, setForm] = useState(() => ({
+ name: project.name,
+ intro: project.intro,
+ status: project.status,
+ techStack: project.techStack,
+ githubLinkVisible: project.showGithubLink && !isPrivateRepository,
+ demoUrl: project.demoUrl ?? '',
+ visibility: project.visibility,
+ author: toAuthorDisplayDraft(author.initial),
+ }));
+ const [problem, setProblem] = useState(null);
+ const [notice, setNotice] = useState(null);
+ const [isPending, startTransition] = useTransition();
+ const canOpenPublicPage =
+ project.enabled && !project.isHidden && project.visibility !== 'private';
+
+ const update = (patch: Partial) => {
+ setForm((previous) => ({ ...previous, ...patch }));
+ setNotice(null);
+ };
+
+ const handleSubmit = (event: FormEvent) => {
+ event.preventDefault();
+
+ if (isPending) {
+ return;
+ }
+
+ const result = toComlogProjectPatch(form, { isPrivateRepository });
+
+ if (result.status === 'invalid') {
+ setProblem(result.problem);
+ setNotice(null);
+ return;
+ }
+
+ setProblem(null);
+ startTransition(async () => {
+ try {
+ const saved = await saveComlogProject(repository.id, result.patch);
+
+ setNotice(saved === 'ok' ? 'saved' : saved);
+
+ // 프로젝트 상태(초안 목록의 comlog 항목)와 공개 주소(slug)를 새 값으로
+ if (saved === 'ok') {
+ router.refresh();
+ }
+ } catch (error) {
+ reportError(error, 'studio.comlog.save');
+ setNotice('error');
+ }
+ });
+ };
+
+ return (
+
+
+
+
+
+ 프로젝트 소개
+
+ {canOpenPublicPage && (
+
+ 공개 페이지 보기
+
+
+ )}
+
+
+ {project.isHidden && (
+
+
+ 관리자가 이 프로젝트를 숨겼습니다. 프로젝트와 회차가 공개 화면에
+ 보이지 않습니다.
+
+ {project.banReason && (
+ <>
+ {' '}
+ 사유: {project.banReason}
+ >
+ )}
+
+ )}
+ {!project.enabled && (
+
+
+ comlog 가 꺼져 있어 공개 화면에 보이지 않습니다. 저장소 설정에서
+ 다시 켤 수 있어요.
+
+
+ )}
+ {recommendPreset && (
+
+
+ 프리셋에 프로젝트 개요와 목적을 적어 두면 회차 품질이 좋아져요.
+ 저장소 설정의 자동 초안 프리셋에서 적을 수 있습니다.
+
+
+ )}
+
+
+
+
+ );
+};
+
+export default ComlogProjectEditor;
diff --git a/components/studio/comlog-sidebar.tsx b/components/studio/comlog-sidebar.tsx
new file mode 100644
index 0000000..1b0a1bd
--- /dev/null
+++ b/components/studio/comlog-sidebar.tsx
@@ -0,0 +1,300 @@
+'use client';
+
+import { useId, type CSSProperties } from 'react';
+import Image from 'next/image';
+import { usePathname } from 'next/navigation';
+import { msg } from '@lingui/core/macro';
+import type { MessageDescriptor } from '@lingui/core';
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import {
+ ClockAlert,
+ FileText,
+ PanelLeftClose,
+ PanelLeftOpen,
+ Plus,
+} from 'lucide-react';
+import LocalizedLink from '@/components/shared/localized-link';
+import DraftListItem, {
+ getDisplayedDraft,
+} from '@/components/studio/draft-list-item';
+import { useStudio } from '@/components/studio/studio-context';
+import {
+ getSidebarClass,
+ ICON_BUTTON_CLASS,
+ THIN_SCROLL_CLASS,
+} from '@/components/studio/studio-styles';
+import { useDraftDeletion } from '@/hooks/use-draft-deletion';
+import { useLocale } from '@/hooks/use-locale';
+import { useSidebarCollapsed } from '@/hooks/use-sidebar-width';
+import { formatDate } from '@/lib/dashboard/format';
+import type { StudioComlog, StudioDraftSummary } from '@/lib/studio/queries';
+
+// PC 회차 칸 너비 (초안 목록·커밋 내역과 함께 1320px 에서도 편집 영역이 남도록 고정, 접으면 버튼만)
+const COMLOG_SIDEBAR_WIDTH = { expanded: 240, collapsed: 48 } as const;
+
+// comlog 항목의 프로젝트 상태 문구 (숨김 → 꺼짐 → 진행 상태 순으로 먼저 알릴 것)
+export const getComlogStateLabel = (
+ comlog: StudioComlog,
+): MessageDescriptor => {
+ if (comlog.isHidden) return msg`숨김`;
+ if (!comlog.enabled) return msg`꺼짐`;
+
+ return comlog.status === 'completed' ? msg`완료` : msg`진행 중`;
+};
+
+interface ComlogDraftItemProps {
+ comlog: StudioComlog;
+ entryCount: number;
+}
+
+/**
+ * 초안 목록 맨 위 comlog 항목: 이름, 회차 수, 프로젝트 상태
+ * - 누르면 프로젝트 소개 화면으로 가고 회차 칸이 나타남
+ */
+export const ComlogDraftItem = ({
+ comlog,
+ entryCount,
+}: ComlogDraftItemProps) => {
+ const { i18n } = useLingui();
+ const { comlogPath, isComlogView } = useStudio();
+
+ return (
+
+
+
+ comlog
+
+
+
+ {' · '}
+ {i18n._(getComlogStateLabel(comlog))}
+
+
+ );
+};
+
+// 회차 칸 맨 위 밀린 커밋 안내 (N 이 0 이면 보이지 않음)
+const BacklogNotice = ({ count }: { count: number }) => (
+
+
+
+
+ 할당량 때문에 기록하지 못한 커밋 {count}개. 커밋 내역에서 골라 새 회차로
+ 기록할 수 있어요.
+
+
+
+);
+
+interface ComlogSidebarProps {
+ // 회차 초안 (최신순, 삭제한 초안 포함: 여기서 숨김)
+ entries: StudioDraftSummary[];
+ // 모바일에서 열려 있는지 (PC 는 회차 화면이면 항상 보임)
+ isOpen: boolean;
+}
+
+/**
+ * 회차 칸 (초안 목록과 커밋 내역 사이): 밀린 커밋 안내, 프로젝트 소개, 회차 목록(최신순), 새 회차
+ * - PC 는 접어서 버튼만 남길 수 있고(브라우저에 기억), 모바일은 다른 사이드바처럼 서랍
+ * - comlog 가 꺼져 있으면 회차 열람만 (새 회차 없음)
+ */
+const ComlogSidebar = ({ entries, isOpen }: ComlogSidebarProps) => {
+ const { t } = useLingui();
+ const locale = useLocale();
+ const pathname = usePathname();
+ const listLabelId = useId();
+ const {
+ repository,
+ basePath,
+ comlogPath,
+ activeDraftId,
+ setOpenPanel,
+ draftTitles,
+ draftPublishStates,
+ draftStatuses,
+ removedDraftIds,
+ } = useStudio();
+ const { comlog } = repository;
+ const visibleEntries = entries.filter(({ id }) => !removedDraftIds.has(id));
+ const { removeDraft, error: deleteError } = useDraftDeletion(
+ visibleEntries,
+ activeDraftId,
+ comlogPath,
+ );
+ const { collapsed, setCollapsed } = useSidebarCollapsed('comlog');
+ const newEntryPath = `${comlogPath}/new`;
+ const isIntroActive = pathname.endsWith(comlogPath);
+ const isNewEntryActive = pathname.endsWith(newEntryPath);
+ const width = collapsed
+ ? COMLOG_SIDEBAR_WIDTH.collapsed
+ : COMLOG_SIDEBAR_WIDTH.expanded;
+
+ return (
+
+ );
+};
+
+export default ComlogSidebar;
diff --git a/components/studio/commit-markers.tsx b/components/studio/commit-markers.tsx
index abf53fa..9477912 100644
--- a/components/studio/commit-markers.tsx
+++ b/components/studio/commit-markers.tsx
@@ -5,24 +5,30 @@ import { useLingui } from '@lingui/react/macro';
import Tooltip from '@/components/shared/tooltip';
import { MAX_GENERATION_COMMITS } from '@/lib/generation/limits';
import type { CommitMarker } from '@/lib/auto-draft/markers';
+import type { DraftKind } from '@/lib/studio/options';
const MARKER_ICONS: Record = {
anchor: '/images/studio/flag.svg',
auto: '/images/studio/layers.svg',
excluded: '/images/studio/circle-slash.svg',
consumed: '/images/studio/circle-check.svg',
+ comlog_used: '/images/studio/circle-check.svg',
not_collected: '/images/studio/git-merge.svg',
+ backlog: '/images/studio/clock-alert.svg',
+ applied: '/images/studio/check-check.svg',
};
interface CommitMarkersProps {
markers: CommitMarker[];
+ // 보고 있는 초안의 종류 ("적용됨" 문구를 회차/초안으로 나눔, 새 초안 화면이면 null)
+ draftKind: DraftKind | null;
}
/**
- * 커밋 줄의 자동 초안 표시 아이콘 (기준점, 자동 대상, 제외됨, 이미 사용됨, 수집 안 됨)
+ * 커밋 줄의 자동 초안 표시 아이콘 (기준점, 자동 대상, 제외됨, 이미 사용됨, 수집 안 됨, 밀림, 적용됨)
* - 아이콘마다 같은 문구의 툴팁과 aria-label, 키보드로 포커스해 툴팁을 볼 수 있음
*/
-const CommitMarkers = ({ markers }: CommitMarkersProps) => {
+const CommitMarkers = ({ markers, draftKind }: CommitMarkersProps) => {
const { t } = useLingui();
const max = MAX_GENERATION_COMMITS;
@@ -41,8 +47,16 @@ const CommitMarkers = ({ markers }: CommitMarkersProps) => {
: t`제외한 커밋입니다. 자동 대상에 들어가지 않습니다`;
case 'consumed':
return t`이미 자동 초안에 사용한 커밋입니다`;
+ case 'comlog_used':
+ return t`회차에 사용됨`;
case 'not_collected':
return t`머지 커밋은 내용이 없어 자동 대상에 들어가지 않습니다`;
+ case 'backlog':
+ return t`밀린 커밋: 할당량 때문에 회차로 기록하지 못했습니다`;
+ case 'applied':
+ return draftKind === 'comlog'
+ ? t`이 회차에 적용됨`
+ : t`이 초안에 적용됨`;
}
};
diff --git a/components/studio/commit-sidebar.tsx b/components/studio/commit-sidebar.tsx
index 86937c9..0cba40c 100644
--- a/components/studio/commit-sidebar.tsx
+++ b/components/studio/commit-sidebar.tsx
@@ -20,18 +20,30 @@ import type { StudioCommit } from '@/lib/actions/studio';
import {
getCommitMarkers,
getCommitMenu,
+ getOffMarkers,
type MarkerState,
} from '@/lib/auto-draft/markers';
import { MAX_GENERATION_COMMITS } from '@/lib/generation/limits';
import { shortSha } from '@/lib/studio/draft-content';
+import type { DraftKind } from '@/lib/studio/options';
// 목록 끝이 스크롤 영역 아래 이만큼 가까워지면 다음 30개 요청
const PRELOAD_MARGIN = '200px';
+// 자동 초안이 꺼져 있을 때 표시 계산에 쓰는 값 (적용됨·회차에 사용됨)
+type OffMarkerState = Pick<
+ MarkerState,
+ 'appliedShas' | 'comlogUsedShas' | 'viewKind'
+>;
+
interface CommitRowProps {
commit: StudioCommit;
isSelected: boolean;
onToggle: (sha: string) => void;
+ // 보고 있는 초안의 종류 (적용됨 문구용)
+ draftKind: DraftKind | null;
+ // 자동 초안이 꺼져 있을 때의 표시 (켜져 있거나 상태를 모르면 null)
+ offState: OffMarkerState | null;
// 자동 초안이 꺼져 있거나 상태를 모르면 null (표시와 메뉴를 숨김)
autoDraft: {
markerState: MarkerState;
@@ -45,6 +57,8 @@ const CommitRow = ({
commit,
isSelected,
onToggle,
+ draftKind,
+ offState,
autoDraft,
}: CommitRowProps) => {
const { t } = useLingui();
@@ -86,6 +100,7 @@ const CommitRow = ({
{/* 머지 커밋은 기준점·제외 대상이 아니라 메뉴 자리만 둠 */}
{menu ? (
@@ -100,6 +115,12 @@ const CommitRow = ({
)}
)}
+ {offState && (
+
+ )}
{
const { t } = useLingui();
- const { commitHistory, autoDraft, selectedShas, toggleCommit, setOpenPanel } =
- useStudio();
+ const {
+ commitHistory,
+ autoDraft,
+ activeDraftKind,
+ isComlogView,
+ selectedShas,
+ toggleCommit,
+ setOpenPanel,
+ } = useStudio();
+ // 회차 화면(소개·새 회차·회차)은 "사용됨" 을 회차 작업 기준으로 봄
+ const viewKind: DraftKind = isComlogView ? 'comlog' : 'post';
const { commits, state, hasMore, loadMore } = commitHistory;
const selectedCount = selectedShas.size;
const sidebarWidth = useSidebarWidth('commits');
@@ -270,8 +300,28 @@ const CommitSidebar = ({ isOpen }: CommitSidebarProps) => {
excluded: new Map(
autoDraftState.excluded.map(({ sha, reason }) => [sha, reason]),
),
+ backlogShas: new Set(autoDraftState.backlog),
+ // 회차 화면은 회차 작업에 쓴 커밋 전체 (밀린 커밋 중 쓴 것도 포함됨)
+ comlogUsedShas: new Set([
+ ...autoDraftState.backlogUsed,
+ ...autoDraftState.comlogUsed,
+ ]),
+ appliedShas: new Set(autoDraftState.appliedShas),
+ viewKind,
};
- }, [autoDraftState]);
+ }, [autoDraftState, viewKind]);
+ // 자동 초안이 꺼져 있어도 회차는 스튜디오에서 직접 쓰므로 적용됨·회차에 사용됨은 보임
+ const offState = useMemo(
+ () =>
+ autoDraftState?.status === 'off'
+ ? {
+ appliedShas: new Set(autoDraftState.appliedShas),
+ comlogUsedShas: new Set(autoDraftState.comlogUsed),
+ viewKind,
+ }
+ : null,
+ [autoDraftState, viewKind],
+ );
const { run: runAutoDraftAction, isPending: isAutoDraftPending } = autoDraft;
const rowAutoDraft = useMemo(
() =>
@@ -370,6 +420,8 @@ const CommitSidebar = ({ isOpen }: CommitSidebarProps) => {
commit={commit}
isSelected={selectedShas.has(commit.sha)}
onToggle={toggleCommit}
+ draftKind={activeDraftKind}
+ offState={offState}
autoDraft={rowAutoDraft}
/>
))}
diff --git a/components/studio/draft-list-item.tsx b/components/studio/draft-list-item.tsx
index 54ecc0e..429c65c 100644
--- a/components/studio/draft-list-item.tsx
+++ b/components/studio/draft-list-item.tsx
@@ -3,13 +3,35 @@
import { useId, useState } from 'react';
import Image from 'next/image';
import { Trans, useLingui } from '@lingui/react/macro';
+import { ScrollText } from 'lucide-react';
import ConfirmDialog from '@/components/shared/confirm-dialog';
import LocalizedLink from '@/components/shared/localized-link';
import { getDraftStatusLabel } from '@/components/studio/draft-status';
import { ICON_BUTTON_CLASS } from '@/components/studio/studio-styles';
+import type { DraftPublishState } from '@/components/studio/publish-state';
import { useDropdown } from '@/hooks/use-dropdown';
+import type { DraftStatus } from '@/lib/db/schema';
import type { StudioDraftSummary } from '@/lib/studio/queries';
+// 화면에서 바뀐 게시 상태를 목록 항목에 반영 (초안 목록·회차 칸 공통)
+export const getDisplayedDraft = (
+ draft: StudioDraftSummary,
+ publishOverride: DraftPublishState | undefined,
+ statusOverride: DraftStatus | undefined,
+): StudioDraftSummary => {
+ if (!publishOverride && !statusOverride) {
+ return draft;
+ }
+
+ return {
+ ...draft,
+ status: statusOverride ?? publishOverride?.status ?? draft.status,
+ visibility: publishOverride
+ ? (publishOverride.post?.visibility ?? null)
+ : draft.visibility,
+ };
+};
+
interface DraftItemMenuProps {
title: string;
onDelete: () => void;
@@ -90,18 +112,25 @@ interface DraftListItemProps {
href: string;
isActive: boolean;
onDelete: () => void;
+ // 상태 앞에 붙일 날짜 (회차 목록)
+ date?: string;
+ // 함께 만든 짝 회차로 가는 주소 (일반 초안에만)
+ pairedHref?: string | null;
}
-// 초안 목록 한 항목: 제목/상태 링크 + 더보기 메뉴 (링크 안에 버튼을 둘 수 없어 겹쳐 배치)
+// 초안 목록 한 항목: 제목/상태 링크 + 더보기 메뉴·짝 회차 링크 (링크 안에 링크·버튼을 둘 수 없어 겹쳐 배치)
const DraftListItem = ({
draft,
title,
href,
isActive,
onDelete,
+ date,
+ pairedHref,
}: DraftListItemProps) => {
const { t, i18n } = useLingui();
const [isConfirming, setIsConfirming] = useState(false);
+ const label = title || t`제목 없는 초안`;
// 게시글이 있는 초안(게시·임시 라벨)은 지우면 게시글도 함께 사라짐
const isPublished = draft.visibility !== null;
@@ -123,7 +152,10 @@ const DraftListItem = ({
>
{title || 제목 없는 초안}
-
+
+ {date && {date} · }
{i18n._(getDraftStatusLabel(draft.status, draft.visibility))}
{draft.isAwaitingInput && (
@@ -134,6 +166,16 @@ const DraftListItem = ({
setIsConfirming(true)} />
+ {pairedHref && (
+
+
+ 회차
+
+ )}
{isConfirming && (
{
- if (!publishOverride && !statusOverride) {
- return draft;
- }
-
- return {
- ...draft,
- status: statusOverride ?? publishOverride?.status ?? draft.status,
- visibility: publishOverride
- ? (publishOverride.post?.visibility ?? null)
- : draft.visibility,
- };
-};
-
-const DraftSidebar = ({ drafts, userName, isOpen }: DraftSidebarProps) => {
+const DraftSidebar = ({
+ drafts,
+ entries,
+ userName,
+ isOpen,
+}: DraftSidebarProps) => {
const { t } = useLingui();
const listLabelId = useId();
const {
repository,
basePath,
+ activeDraftId,
setOpenPanel,
draftTitles,
draftPublishStates,
draftStatuses,
removedDraftIds,
} = useStudio();
- const { draftId: activeDraftId } = useParams<{ draftId?: string }>();
const visibleDrafts = drafts.filter(({ id }) => !removedDraftIds.has(id));
+ // 지운 회차로는 짝 링크를 걸지 않음
+ const visibleEntryIds = new Set(
+ entries.filter(({ id }) => !removedDraftIds.has(id)).map(({ id }) => id),
+ );
const { removeDraft, error: deleteError } = useDraftDeletion(
visibleDrafts,
activeDraftId,
);
- const { ownerLogin, name, htmlUrl, branch } = repository;
+ const { ownerLogin, name, htmlUrl, branch, comlog } = repository;
const repositoryLinkLabel = t`GitHub 에서 저장소 열기`;
const sidebarWidth = useSidebarWidth('drafts');
@@ -183,6 +177,9 @@ const DraftSidebar = ({ drafts, userName, isOpen }: DraftSidebarProps) => {
)}
)}
+ {comlog && (
+
+ )}
{visibleDrafts.length > 0 ? (
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..dacd9b9
--- /dev/null
+++ b/docs/superpowers/specs/2026-12-01-comlog-design.md
@@ -0,0 +1,223 @@
+# 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 가 회차 주소(`/comlog/[프로젝트]/[회차]`)를 받음, 프로젝트 소개는 루틴이 공개 프로젝트 페이지를 읽어 검수 (§12)
+- GitHub 링크: 비공개 저장소는 항상 숨김
+- Lambda: `worklog` 문구가 프롬프트 표에 들어가고 일반 글 옵션에는 노출되지 않음
+
+- 이미지 정리: 지금 이미지 정리는 초안·게시글 본문이 가리키는 이미지만 남긴다. `comlog_project.cover_image` 도 남기도록 규칙을 넓힌다.
+
+## 14. 빌더에게 맡기는 것
+
+- 컴포넌트 분리 방식, 회차 칸 접기 상태 저장 방식 (지금 사이드바 너비 저장과 같은 방식 권장)
+- 관리자 콘솔에서 회차를 어떻게 보여 줄지 (섞이지 않게만)
+- 프로젝트 카드 자동 이미지 디자인 (게시글 OG 이미지 생성기 재사용)
+- 밀린 커밋 아이콘 모양 (기존 커밋 표시 아이콘 체계에 맞춤)
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/hooks/use-auto-draft-state.ts b/hooks/use-auto-draft-state.ts
index 8085106..85ecc17 100644
--- a/hooks/use-auto-draft-state.ts
+++ b/hooks/use-auto-draft-state.ts
@@ -8,6 +8,7 @@ import {
type AutoDraftStateResult,
} from '@/lib/actions/auto-draft';
import { reportError } from '@/lib/observability/report-error';
+import type { DraftKind } from '@/lib/studio/options';
export type AutoDraftCommitAction = 'anchor' | 'exclude' | 'restore';
@@ -32,13 +33,17 @@ const ACTIONS: Record<
};
/**
- * 스튜디오 커밋 목록의 자동 초안 상태 (기준점·자동 대상·제외 목록)
- * - 저장소·추적 브랜치가 바뀌면 다시 읽고, 커밋 동작 뒤에도 서버 값으로 다시 읽음
+ * 스튜디오 커밋 목록의 자동 초안 상태 (기준점·자동 대상·제외 목록, 보고 있는 초안에 반영한 커밋)
+ * - 저장소·추적 브랜치·보고 있는 초안이 바뀌면 다시 읽고, 커밋 동작 뒤에도 서버 값으로 다시 읽음
* - 여러 요청이 겹치면 가장 나중에 보낸 응답만 반영
*/
export const useAutoDraftState = (
repositoryId: string,
branch: string,
+ // 보고 있는 초안 (없으면 새 초안·프로젝트 소개 화면)
+ draftId: string | undefined,
+ // 화면 종류 (회차 화면이면 "사용됨" 을 회차 작업 기준으로 받음)
+ viewKind: DraftKind,
): AutoDraftState => {
const [state, setState] = useState(null);
const [isPending, setIsPending] = useState(false);
@@ -49,14 +54,14 @@ export const useAutoDraftState = (
const requestId = ++requestRef.current;
try {
- const result = await loadAutoDraftState(repositoryId);
+ const result = await loadAutoDraftState(repositoryId, draftId, viewKind);
if (requestId === requestRef.current) setState(result);
} catch (error) {
reportError(error, 'studio.auto-draft.state', { repositoryId });
if (requestId === requestRef.current) setState({ status: 'error' });
}
- }, [repositoryId]);
+ }, [repositoryId, draftId, viewKind]);
useEffect(() => {
// 브랜치가 바뀌면 경계도 새로 잡히므로 다시 읽음
diff --git a/hooks/use-draft-deletion.ts b/hooks/use-draft-deletion.ts
index 4c9e255..e29a5ec 100644
--- a/hooks/use-draft-deletion.ts
+++ b/hooks/use-draft-deletion.ts
@@ -27,12 +27,14 @@ export const getNextDraftId = (
/**
* 초안 삭제 흐름
* 1. 목록에서 먼저 숨기고(남은 자동 저장도 멈춤) 서버에 삭제 요청
- * 2. 열려 있던 초안이면 목록의 다음 초안으로, 남은 초안이 없으면 새 초안 화면으로 이동
+ * 2. 열려 있던 초안이면 목록의 다음 초안으로, 남은 초안이 없으면 emptyPath(기본은 새 초안 화면)로 이동
* 3. 실패하거나 AI 작성 중이라 지울 수 없으면 목록에 다시 보이고 사유 표시
*/
export const useDraftDeletion = (
drafts: DraftListEntry[],
activeDraftId: string | undefined,
+ // 남은 초안이 없을 때 갈 경로 (회차 목록은 프로젝트 소개)
+ emptyPath?: string,
) => {
const router = useLocalizedRouter();
const { repository, basePath, markDraftRemoved, unmarkDraftRemoved } =
@@ -57,7 +59,11 @@ export const useDraftDeletion = (
// 이미 삭제된 초안(not_found)도 목록에서 숨긴 상태로 둠
if (result.status === 'deleted' && draftId === activeDraftId) {
- router.replace(nextDraftId ? `${basePath}/${nextDraftId}` : basePath);
+ router.replace(
+ nextDraftId
+ ? `${basePath}/${nextDraftId}`
+ : (emptyPath ?? basePath),
+ );
}
} catch (error) {
reportError(error, 'studio.draft.delete', { draftId });
@@ -68,6 +74,7 @@ export const useDraftDeletion = (
[
drafts,
activeDraftId,
+ emptyPath,
repository.id,
basePath,
router,
diff --git a/hooks/use-sidebar-width.ts b/hooks/use-sidebar-width.ts
index 2dd3dd0..756904f 100644
--- a/hooks/use-sidebar-width.ts
+++ b/hooks/use-sidebar-width.ts
@@ -1,7 +1,9 @@
import { useCallback, useState, useSyncExternalStore } from 'react';
import {
clampSidebarWidth,
+ getSidebarCollapsedStorageKey,
getSidebarWidthStorageKey,
+ parseStoredSidebarCollapsed,
parseStoredSidebarWidth,
SIDEBAR_WIDTH,
type SidebarWidthKey,
@@ -67,3 +69,42 @@ export const useSidebarWidth = (key: SidebarWidthKey) => {
return { width: draft ?? stored, preview, commit };
};
+
+const readStoredCollapsed = (key: SidebarWidthKey) => {
+ try {
+ return parseStoredSidebarCollapsed(
+ window.localStorage.getItem(getSidebarCollapsedStorageKey(key)),
+ );
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * 사이드바 접힘 상태 (브라우저 저장소에 사이드바별로 보관, PC 에서만 의미 있음)
+ * - 서버 렌더와 첫 화면은 펼침, 이후 저장값으로 바뀜
+ */
+export const useSidebarCollapsed = (key: SidebarWidthKey) => {
+ const collapsed = useSyncExternalStore(
+ subscribe,
+ () => readStoredCollapsed(key),
+ () => false,
+ );
+
+ const setCollapsed = useCallback(
+ (next: boolean) => {
+ try {
+ window.localStorage.setItem(
+ getSidebarCollapsedStorageKey(key),
+ next ? '1' : '0',
+ );
+ } catch {
+ // 사생활 보호 모드 등에서 저장소가 막히면 접힘을 바꾸지 못함 (펼친 채로 둠)
+ }
+ window.dispatchEvent(new Event(CHANGE_EVENT));
+ },
+ [key],
+ );
+
+ return { collapsed, setCollapsed };
+};
diff --git a/lib/actions/admin/comlog.ts b/lib/actions/admin/comlog.ts
new file mode 100644
index 0000000..6176fa9
--- /dev/null
+++ b/lib/actions/admin/comlog.ts
@@ -0,0 +1,63 @@
+'use server';
+
+import { revalidatePath } from 'next/cache';
+import { requireAdmin, requireAdminKey } from '@/lib/admin/guard';
+import {
+ parseComlogBanInput,
+ type ComlogBanAction,
+} from '@/lib/admin/comlog-ban';
+import { setComlogProjectBan } from '@/lib/admin/comlog-queries';
+import { adminPath } from '@/lib/admin/path-key';
+import { getRequestLocale } from '@/lib/i18n/request';
+
+const readField = (formData: FormData, name: string): string => {
+ const value = formData.get(name);
+
+ return typeof value === 'string' ? value : '';
+};
+
+// 권한 확인 → 입력 검증 → 숨기기·해제 (두 액션의 공통 흐름)
+const apply = async (
+ formData: FormData,
+ action: ComlogBanAction,
+): Promise => {
+ const admin = await requireAdmin(
+ action === 'ban' ? 'comlog.ban' : 'comlog.unban',
+ );
+ const projectId = readField(formData, 'projectId').trim();
+
+ if (!projectId) {
+ throw new Error('invalid_project');
+ }
+
+ const input = parseComlogBanInput(action, readField(formData, 'reason'));
+
+ if (!input) {
+ throw new Error('invalid_reason');
+ }
+
+ const result = await setComlogProjectBan(
+ projectId,
+ input.action,
+ input.reason,
+ admin.adminId,
+ );
+
+ if (result === 'not_found') {
+ throw new Error('unknown_project');
+ }
+
+ revalidatePath(
+ adminPath(await getRequestLocale(), requireAdminKey(), 'comlog'),
+ );
+};
+
+/** comlog 프로젝트 숨기기: 공개 목록·프로젝트·회차·사이트맵에서 모두 빠짐 */
+export async function banComlogProject(formData: FormData): Promise {
+ await apply(formData, 'ban');
+}
+
+/** comlog 프로젝트 숨김 해제 */
+export async function unbanComlogProject(formData: FormData): Promise {
+ await apply(formData, 'unban');
+}
diff --git a/lib/actions/auto-draft.ts b/lib/actions/auto-draft.ts
index 6fe791e..98ada57 100644
--- a/lib/actions/auto-draft.ts
+++ b/lib/actions/auto-draft.ts
@@ -2,12 +2,16 @@
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,
+ listComlogUsedShas,
listExcludedShas,
restoreCommit,
saveAutoDraftSetting,
@@ -16,14 +20,17 @@ import {
} from '@/lib/auto-draft/store';
import type { ExcludedCommitReason } from '@/lib/db/schema/auto-draft';
import type { GenerationModel } from '@/lib/generation/contract';
+import { isUuid } from '@/lib/images/rules';
import { MAX_GENERATION_PROMPT_LENGTH } from '@/lib/generation/limits';
import { getAllowedModels, isModelAllowed } from '@/lib/generation/models';
import {
DEFAULT_PROMPT_OPTIONS,
- parsePromptOptions,
+ fitOptionsToKind,
+ parseSelectablePromptOptions,
+ type DraftKind,
type PromptOptions,
} from '@/lib/studio/options';
-import { getStudioRepository } from '@/lib/studio/queries';
+import { getStudioRepository, isOwnedDraft } from '@/lib/studio/queries';
import { reportError } from '@/lib/observability/report-error';
export type AutoDraftSettingsResult =
@@ -62,7 +69,8 @@ export async function getAutoDraftSettings(
status: 'ok',
enabled: setting?.enabled ?? false,
prompt: setting?.prompt ?? '',
- options: setting?.options ?? INITIAL_OPTIONS,
+ // 저장된 worklog(회차 전용)는 고를 수 있는 값으로 보여 줌 (그대로 두면 저장이 invalid 로 거부됨)
+ options: fitOptionsToKind('post', setting?.options ?? INITIAL_OPTIONS),
allowedModels: getAllowedModels(user.role),
};
}
@@ -74,7 +82,7 @@ export type SaveAutoDraftSettingsResult =
/**
* 저장소 설정: 자동 초안 요청 문구와 기본 옵션 저장
* - 문구는 비어 있어도 저장 (비어 있으면 실행이 no_preset 으로 기록됨), 앞뒤 공백을 지운 뒤 4,000자 이하
- * - 등급이 쓸 수 없는 모델이면 model_locked
+ * - 등급이 쓸 수 없는 모델이면 model_locked, 고를 수 없는 글 종류(worklog)면 invalid
*/
export async function saveAutoDraftSettings(
repositoryId: string,
@@ -88,7 +96,8 @@ export async function saveAutoDraftSettings(
}
const prompt = typeof input?.prompt === 'string' ? input.prompt.trim() : null;
- const options = parsePromptOptions(input?.options);
+ // 기본 옵션은 일반 글 트리거에 쓰이므로 worklog(회차 전용) 같은 고를 수 없는 글 종류는 거부
+ const options = parseSelectablePromptOptions(input?.options);
if (
prompt === null ||
@@ -141,8 +150,10 @@ export interface AutoDraftSkipped {
}
export type AutoDraftStateResult =
- | { status: 'off' | 'not_found' | 'error' }
- | {
+ | { status: 'not_found' | 'error' }
+ // 자동 초안이 꺼져 있어도 회차는 스튜디오에서 직접 쓰므로 "적용됨" 표시는 함
+ | ({ status: 'off' } & AutoDraftViewState)
+ | ({
status: 'ok';
// 묶음의 첫 커밋 (대상이 없으면 null)
anchorSha: string | null;
@@ -150,11 +161,81 @@ export type AutoDraftStateResult =
// 범위 안에서 건너뛴 커밋 (수집 안 됨·이미 사용됨 표시용)
skipped: AutoDraftSkipped[];
excluded: AutoDraftExcluded[];
- }
- | { status: 'anchor_missing'; excluded: AutoDraftExcluded[] };
+ } & AutoDraftBacklogState)
+ | ({
+ status: 'anchor_missing';
+ excluded: AutoDraftExcluded[];
+ } & AutoDraftBacklogState);
+
+// 보고 있는 화면 기준 표시 (자동 초안이 꺼져 있어도 보냄)
+export interface AutoDraftViewState {
+ // 보고 있는 초안의 최근 완료 작업이 쓴 커밋
+ appliedShas: string[];
+ // 회차 화면일 때 회차 작업에 쓴 커밋 전체 (일반 글 화면은 빈 배열)
+ comlogUsed: string[];
+}
+// 밀린 커밋과 화면 기준 표시 (커밋 줄 표시·회차 사이드바 상단 표시용)
+export interface AutoDraftBacklogState extends AutoDraftViewState {
+ // 밀린 커밋 전체 (회차에 쓴 것 포함)
+ backlog: string[];
+ // 밀린 커밋 중 회차 작업(실패 제외)에 쓴 것
+ backlogUsed: string[];
+ // 아직 회차에 쓰이지 않은 밀린 커밋 수
+ openBacklogCount: number;
+}
+
+// 제외 목록에서 밀린 커밋(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,
+ view: AutoDraftViewState,
+): Promise => {
+ const backlog = Array.from(excluded)
+ .filter(([, reason]) => reason === 'backlog')
+ .map(([sha]) => sha);
+ const used = await findConsumedShas(userId, repositoryId, backlog, 'comlog');
+
+ return {
+ backlog,
+ backlogUsed: Array.from(used),
+ openBacklogCount: countOpenBacklog(backlog, used),
+ ...view,
+ };
+};
+
+/**
+ * 화면 기준 표시 (적용됨·회차에 사용됨)
+ * - 초안 id 는 클라이언트 값이라 형식과 이 저장소의 본인 초안인지 먼저 확인 (아니면 null)
+ */
+const toViewState = async (
+ userId: string,
+ repositoryId: string,
+ draftId: string | undefined,
+ viewKind: unknown,
+): Promise => {
+ if (
+ draftId !== undefined &&
+ (typeof draftId !== 'string' ||
+ !isUuid(draftId) ||
+ !(await isOwnedDraft(userId, repositoryId, draftId)))
+ ) {
+ return null;
+ }
+
+ const [appliedShas, comlogUsed] = await Promise.all([
+ draftId ? getAppliedShas(userId, draftId) : [],
+ viewKind === 'comlog' ? listComlogUsedShas(userId, repositoryId) : [],
+ ]);
+
+ return { appliedShas, comlogUsed };
+};
/**
* 스튜디오 커밋 목록 표시용: 경계 다음 커밋부터 브랜치 끝까지 자동 대상 묶음을 계산 (실행기와 같은 계산)
@@ -163,6 +244,10 @@ const toExcludedList = (excluded: Map) =>
*/
export async function loadAutoDraftState(
repositoryId: string,
+ // 보고 있는 초안 (있으면 그 초안의 최근 완료 작업 커밋에 applied 표시)
+ draftId?: string,
+ // 화면 종류 (comlog 면 "사용됨" 을 회차 작업 기준으로)
+ viewKind?: DraftKind,
): Promise {
const { user } = await requireSession();
const repo = await getAutoDraftRepo(user.id, repositoryId);
@@ -171,17 +256,34 @@ export async function loadAutoDraftState(
return { status: 'not_found' };
}
- const setting = await getAutoDraftSetting(user.id, repositoryId);
+ try {
+ const view = await toViewState(user.id, repositoryId, draftId, viewKind);
- if (!setting?.enabled) {
- return { status: 'off' };
- }
+ if (!view) {
+ return { status: 'error' };
+ }
+
+ const setting = await getAutoDraftSetting(user.id, repositoryId);
+
+ if (!setting?.enabled) {
+ return { status: 'off', ...view };
+ }
- try {
const excluded = await listExcludedShas(user.id, repositoryId);
+ const backlogState = await toBacklogState(
+ user.id,
+ repositoryId,
+ excluded,
+ view,
+ );
+
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 +298,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 +311,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/actions/comlog.ts b/lib/actions/comlog.ts
new file mode 100644
index 0000000..b08408b
--- /dev/null
+++ b/lib/actions/comlog.ts
@@ -0,0 +1,120 @@
+'use server';
+
+import { requireSession } from '@/lib/auth/session';
+import { getAutoDraftSetting } from '@/lib/auto-draft/store';
+import {
+ disableComlog,
+ enableComlog,
+ getComlogProject,
+ refreshProjectRepoPrivacy,
+ updateComlogProject,
+ type ComlogProjectPatch,
+} from '@/lib/comlog/store';
+import { isProjectPatch } from '@/lib/comlog/patch';
+import { revalidateComlogPages } from '@/lib/comlog/revalidate';
+import { reportError } from '@/lib/observability/report-error';
+import { getStudioRepository } from '@/lib/studio/queries';
+
+export type ToggleComlogResult =
+ | { status: 'ok'; enabled: boolean }
+ | { status: 'not_found' | 'github_unavailable' };
+
+/**
+ * 저장소 설정: comlog 켜기/끄기
+ * - 처음 켤 때는 GitHub 에서 저장소 정보를 가져오므로 실패하면 github_unavailable
+ * - 켜고 끌 때 공개 화면과 사이트맵을 비움 (끄면 공개 화면에서 사라짐)
+ */
+export async function toggleComlog(
+ repositoryId: string,
+ enabled: boolean,
+): Promise {
+ const { user } = await requireSession();
+ const repository = await getStudioRepository(user.id, repositoryId);
+
+ if (!repository || typeof enabled !== 'boolean') {
+ return { status: 'not_found' };
+ }
+
+ if (enabled) {
+ try {
+ await enableComlog(user.id, repository.id);
+ } catch (error) {
+ reportError(error, 'comlog.enable', { repositoryId });
+
+ return { status: 'github_unavailable' };
+ }
+ } else {
+ await disableComlog(user.id, repository.id);
+ }
+
+ revalidateComlogPages();
+
+ return { status: 'ok', enabled };
+}
+
+/**
+ * 프로젝트 소개 저장 (본인 저장소의 프로젝트만)
+ * - GitHub 링크 켜기는 저장소 공개 여부로 검증하므로 먼저 공개 여부를 최신으로 맞춤
+ */
+export async function saveComlogProject(
+ repositoryId: string,
+ patch: ComlogProjectPatch,
+): Promise<'ok' | 'not_found' | 'invalid'> {
+ const { user } = await requireSession();
+ const repository = await getStudioRepository(user.id, repositoryId);
+
+ if (!repository) {
+ return 'not_found';
+ }
+
+ // 객체가 아닌 인자(null 등)는 GitHub 를 부르기 전에 거부 (500 이 아니라 invalid)
+ if (!isProjectPatch(patch)) {
+ return 'invalid';
+ }
+
+ await refreshProjectRepoPrivacy(user.id, repository.id);
+
+ const result = await updateComlogProject(user.id, repository.id, patch);
+
+ if (result === 'ok') {
+ revalidateComlogPages();
+ }
+
+ return result;
+}
+
+export type ComlogPanelState =
+ | {
+ status: 'ok';
+ enabled: boolean;
+ project: Awaited>;
+ // 자동 초안 프리셋 길이 (권장 문구 표시 판정용)
+ presetLength: number;
+ }
+ | { status: 'not_found' };
+
+/**
+ * 저장소 설정: comlog 패널 상태 (켜짐 여부, 프로젝트, 프리셋 길이)
+ */
+export async function getComlogPanelState(
+ repositoryId: string,
+): Promise {
+ const { user } = await requireSession();
+ const repository = await getStudioRepository(user.id, repositoryId);
+
+ if (!repository) {
+ return { status: 'not_found' };
+ }
+
+ const [project, setting] = await Promise.all([
+ getComlogProject(user.id, repository.id),
+ getAutoDraftSetting(user.id, repository.id),
+ ]);
+
+ return {
+ status: 'ok',
+ enabled: project?.enabled ?? false,
+ project,
+ presetLength: setting?.prompt.trim().length ?? 0,
+ };
+}
diff --git a/lib/actions/generation.ts b/lib/actions/generation.ts
index 60ce937..1e4c222 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,10 @@ import {
type ParsedRequest,
type SlotRejection,
} from '@/lib/generation/draft-job';
+import {
+ parseRequestedKind,
+ resolveRequestKind,
+} from '@/lib/generation/draft-kind';
import { getGenerationRunner } from '@/lib/generation/get-runner';
import {
applyCompletedJob,
@@ -61,11 +66,17 @@ import {
import { ensureBlankIds, findBlank } from '@/lib/studio/draft-blank';
import { isDraftDocument } from '@/lib/studio/draft-content';
import {
+ applyDraftKindOptions,
DEFAULT_PROMPT_OPTIONS,
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 +86,8 @@ export interface RequestDraftGenerationInput {
draftId: string | null;
prompt: string;
options: unknown;
+ // 초안 종류 (이미 있는 초안은 저장된 종류가 이김, 없으면 일반 글: 배포 중 예전 화면의 요청)
+ draftKind?: DraftKind;
// 선택한 커밋 SHA (최신순, 직접 입력 코드가 있으면 비어도 됨)
commitShas: string[];
// 직접 입력 코드 (저장하지 않고 작성기에만 넘김)
@@ -179,6 +192,34 @@ export async function requestDraftGeneration(
return { status: 'not_found' };
}
+ const requestedKind = parseRequestedKind(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 +235,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/actions/images.ts b/lib/actions/images.ts
index 89b48e2..85b6cc6 100644
--- a/lib/actions/images.ts
+++ b/lib/actions/images.ts
@@ -2,10 +2,13 @@
import { count, eq } from 'drizzle-orm';
import { requireSession } from '@/lib/auth/session';
+import { getComlogProject } from '@/lib/comlog/store';
+import { revalidateComlogPages } from '@/lib/comlog/revalidate';
import { db } from '@/lib/db';
import { image } from '@/lib/db/schema';
import { isDraftEditLocked } from '@/lib/generation/jobs';
import { convertToWebp, UnsupportedImageError } from '@/lib/images/convert';
+import { insertCoverImage } from '@/lib/images/cover';
import { insertImageWithinLimit } from '@/lib/images/records';
import { consumeImageUploadAttempt } from '@/lib/images/upload-limit';
import {
@@ -24,7 +27,7 @@ import {
removeUploads,
} from '@/lib/images/storage';
import { getSupabaseUrl } from '@/lib/supabase/server';
-import { isOwnedDraft } from '@/lib/studio/queries';
+import { getStudioRepository, isOwnedDraft } from '@/lib/studio/queries';
import { reportError } from '@/lib/observability/report-error';
export type RequestImageUploadResult =
@@ -188,3 +191,120 @@ export async function finalizeImageUpload(
return { status: 'failed' };
}
}
+
+export type RequestComlogCoverUploadResult =
+ | { status: 'ok'; uploadId: string; path: string; token: string }
+ | { status: 'rate_limited' | 'not_found' };
+
+export type UploadComlogCoverResult =
+ | { status: 'ok'; imageId: string; url: string }
+ | { status: 'unsupported'; reason: 'heic' | 'type' | 'too_large' }
+ | { status: 'rate_limited' | 'not_found' | 'failed' };
+
+// 본인 저장소이고 comlog 프로젝트가 있을 때만 대표 이미지를 다룸
+const hasComlogProject = async (userId: string, repositoryId: string) => {
+ const repository = await getStudioRepository(userId, repositoryId);
+
+ return Boolean(repository && (await getComlogProject(userId, repository.id)));
+};
+
+/**
+ * 대표 이미지 올리기 준비: 임시 버킷에 직접 올릴 서명 주소 발급
+ * - 서버 액션 본문(1MB)에 5MB 원본이 들어가지 않으므로 초안 이미지와 같은 두 단계 흐름을 씀
+ */
+export async function requestComlogCoverUpload(
+ repositoryId: string,
+): Promise {
+ const { user } = await requireSession();
+
+ if (!(await hasComlogProject(user.id, repositoryId))) {
+ return { status: 'not_found' };
+ }
+
+ if (!(await consumeImageUploadAttempt('upload-url', user.id))) {
+ return { status: 'rate_limited' };
+ }
+
+ const uploadId = crypto.randomUUID();
+ const path = getUploadPath(user.id, uploadId);
+ const { token } = await createUploadUrl(path);
+
+ return { status: 'ok', uploadId, path, token };
+}
+
+/**
+ * 올린 원본을 WebP 로 변환해 프로젝트 대표 이미지로 지정
+ * - 변환·시간당 횟수 제한은 초안 이미지와 같음, 이미지 기록은 draft_id 없이 저장
+ * - 이전 대표 이미지는 지우지 않고 평소 정리에 맡김 (insertCoverImage 참고)
+ * - 공개 화면과 사이트맵을 비움
+ */
+export async function uploadComlogCover(
+ repositoryId: string,
+ uploadId: string,
+): Promise {
+ const { user } = await requireSession();
+
+ if (!isUuid(uploadId) || !(await hasComlogProject(user.id, repositoryId))) {
+ return { status: 'not_found' };
+ }
+
+ const uploadPath = getUploadPath(user.id, uploadId);
+
+ if (!(await consumeImageUploadAttempt('finalize', user.id))) {
+ await removeUploads([uploadPath]);
+ return { status: 'rate_limited' };
+ }
+
+ try {
+ const original = await downloadUpload(uploadPath);
+
+ if (original.length > IMAGE_MAX_BYTES) {
+ throw new UnsupportedImageError('too_large');
+ }
+
+ const converted = await convertToWebp(original);
+ const path = getImagePath(user.id, uploadId);
+ await putImage(path, converted.data);
+
+ let linked: boolean;
+
+ try {
+ linked = await insertCoverImage(repositoryId, {
+ id: uploadId,
+ userId: user.id,
+ path,
+ width: converted.width,
+ height: converted.height,
+ bytes: converted.bytes,
+ });
+ } catch (error) {
+ await removeImages([path]);
+ throw error;
+ }
+
+ await removeUploads([uploadPath]);
+
+ if (!linked) {
+ // 그 사이 프로젝트가 사라짐
+ await removeImages([path]);
+ return { status: 'not_found' };
+ }
+
+ revalidateComlogPages();
+
+ return {
+ status: 'ok',
+ imageId: uploadId,
+ url: getImagePublicUrl(getSupabaseUrl(), path),
+ };
+ } catch (error) {
+ await removeUploads([uploadPath]);
+
+ if (error instanceof UnsupportedImageError) {
+ return { status: 'unsupported', reason: error.reason };
+ }
+
+ reportError(error, 'images.cover-upload', { repositoryId });
+ return { status: 'failed' };
+ }
+}
diff --git a/lib/actions/post-views.ts b/lib/actions/post-views.ts
index 4600a8b..670850b 100644
--- a/lib/actions/post-views.ts
+++ b/lib/actions/post-views.ts
@@ -6,6 +6,7 @@ import { isPostId } from '@/lib/posts/post-id';
import { getViewerKey, VIEWER_COOKIE } from '@/lib/posts/post-view';
import { verifyViewerCookie } from '@/lib/posts/viewer-cookie';
import { consumeAnonymousViewAttempt } from '@/lib/posts/view-limit';
+import { getComlogEntryOwnerId } from '@/lib/comlog/queries';
import { getPostAuthorId, recordViewIfDue } from '@/lib/posts/views';
import { getClientIp } from '@/lib/request-ip';
import { reportError } from '@/lib/observability/report-error';
@@ -17,10 +18,29 @@ import { reportError } from '@/lib/observability/report-error';
* - 비로그인 조회는 IP 당 횟수를 제한 (쿠키를 버리며 반복하는 부풀리기 방지)
*/
export async function recordPostView(postId: string): Promise {
+ await recordView(postId, getPostAuthorId, 'posts.record-view');
+}
+
+/**
+ * comlog 회차 상세의 조회 기록 (규칙은 게시글과 같고, 셀 회차인지만 comlog 공개 규칙으로 판단)
+ * - 일반 게시글 판단(getPostAuthorId)은 회차를 세지 않으므로 따로 둠
+ */
+export async function recordComlogEntryView(postId: string): Promise {
+ await recordView(postId, getComlogEntryOwnerId, 'comlog.record-view');
+}
+
+// 조회를 셀 글이면 작성자 id, 아니면 null 을 돌려주는 조회 함수
+type FindAuthorId = (postId: string) => Promise;
+
+async function recordView(
+ postId: string,
+ findAuthorId: FindAuthorId,
+ errorScope: string,
+): Promise {
if (typeof postId !== 'string' || !isPostId(postId)) return;
try {
- const authorId = await getPostAuthorId(postId);
+ const authorId = await findAuthorId(postId);
if (!authorId) return;
@@ -47,6 +67,6 @@ export async function recordPostView(postId: string): Promise {
await recordViewIfDue(postId, viewerKey);
} catch (error) {
// 조회 기록 실패는 글 읽기에 영향을 주지 않음
- reportError(error, 'posts.record-view', { postId });
+ reportError(error, errorScope, { postId });
}
}
diff --git a/lib/actions/posts.ts b/lib/actions/posts.ts
index 0c903ea..1bfc012 100644
--- a/lib/actions/posts.ts
+++ b/lib/actions/posts.ts
@@ -4,6 +4,14 @@ import type { JSONContent } from '@tiptap/core';
import { refresh } 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 { getComlogEntryPath } from '@/lib/comlog/paths';
+import { revalidateComlogPages } from '@/lib/comlog/revalidate';
import { db } from '@/lib/db';
import { draft, post, type PostVisibility } from '@/lib/db/schema';
import {
@@ -24,11 +32,14 @@ import {
} from '@/lib/posts/author-display';
import { checkPublishable } from '@/lib/posts/post-content';
import { createPostId } from '@/lib/posts/post-id';
+import { getPostPath } from '@/lib/posts/post-path';
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 =
@@ -39,6 +50,8 @@ export type PublishDraftResult =
// 게시하면서 저장한 제목 (화면의 사이드바 제목을 맞추는 데 사용)
title: string;
visibility: PostVisibility;
+ // 게시된 글의 로케일 없는 공개 주소 (일반 글은 /posts/..., 회차는 /comlog/.../...)
+ path: string;
}
// 아직 채우지 않은 빈칸이 남아 있음
| { status: 'has_blanks'; count: number }
@@ -47,6 +60,8 @@ export type PublishDraftResult =
| { status: 'invalid' }
// AI 작성 중이라 편집 잠금
| { status: 'locked' }
+ // comlog 회차인데 프로젝트가 없거나 꺼져 있음 (게시할 수 없음)
+ | { status: 'comlog_disabled' }
| { status: 'not_found' };
/**
@@ -60,6 +75,9 @@ export type PublishDraftResult =
* - 바뀌기 전 초안 본문, 새 초안·게시글 본문에 든 이미지는 같은 트랜잭션에서 마지막 사용 시각을 갱신
* - 게시 후 응답 뒤에 쓰지 않는 이미지를 정리 (게시글 본문의 이미지도 쓰는 것으로 셈)
* - 초안 태그를 정규화해 게시글로 복사
+ * - 초안 종류(post / comlog)를 게시글로 복사. 회차는 비공개 공개 범위도 허용하고,
+ * 프로젝트가 없거나 꺼져 있으면 게시하지 않음
+ * - 회차를 게시하면 프로젝트 기술 스택에 태그를 합치고, 첫 회차면 작성자 표시를 프로젝트에 채움
*/
export async function publishDraft(
repositoryId: string,
@@ -71,15 +89,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 +175,7 @@ export async function publishDraft(
id: createPostId(),
draftId,
userId: user.id,
+ kind,
...values,
...author,
tags,
@@ -178,10 +208,18 @@ export async function publishDraft(
slug: published.slug,
title,
visibility: published.visibility,
+ // 회차는 프로젝트 주소 아래 (위에서 프로젝트가 있음을 확인함)
+ path: project
+ ? getComlogEntryPath(project, published)
+ : getPostPath(published),
};
},
);
+ if (result.status === 'published' && kind === 'comlog') {
+ await afterComlogPublish(user.id, repositoryId, draftId, checkedAuthor);
+ }
+
if (result.status === 'published') {
scheduleDraftImageCleanup(draftId);
// 사이트맵에 새 글 또는 바뀐 수정 시각·공개 범위를 바로 반영
@@ -194,8 +232,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 +289,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 +300,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/actions/studio.ts b/lib/actions/studio.ts
index eb3abad..392f9c1 100644
--- a/lib/actions/studio.ts
+++ b/lib/actions/studio.ts
@@ -39,6 +39,8 @@ export interface StudioCommit {
htmlUrl: string;
// 머지 커밋 판정용 (부모가 둘 이상)
parentShas: string[];
+ // 커밋 시각 (ISO, 회차 위 날짜 범위용 / GitHub 가 주지 않으면 null)
+ committedAt: string | null;
}
export type StudioCommitsResult =
@@ -81,12 +83,15 @@ export async function loadStudioCommits(
return {
status: 'ok',
hasNextPage: result.hasNextPage,
- commits: result.commits.map(({ sha, message, htmlUrl, parentShas }) => ({
- sha,
- subject: getCommitSubject(message),
- htmlUrl,
- parentShas,
- })),
+ commits: result.commits.map(
+ ({ sha, message, htmlUrl, parentShas, committedAt }) => ({
+ sha,
+ subject: getCommitSubject(message),
+ htmlUrl,
+ parentShas,
+ committedAt,
+ }),
+ ),
};
} catch (error) {
if (error instanceof GithubUserTokenError) {
diff --git a/lib/admin/comlog-ban.test.ts b/lib/admin/comlog-ban.test.ts
new file mode 100644
index 0000000..555c579
--- /dev/null
+++ b/lib/admin/comlog-ban.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+import { parseComlogBanInput } from '@/lib/admin/comlog-ban';
+
+describe('parseComlogBanInput', () => {
+ it('ban 은 앞뒤 공백을 뗀 사유가 필요함', () => {
+ expect(parseComlogBanInput('ban', ' 광고 ')).toEqual({
+ action: 'ban',
+ reason: '광고',
+ });
+ });
+
+ it('ban 은 사유가 없거나 공백뿐이면 거절', () => {
+ expect(parseComlogBanInput('ban', null)).toBeNull();
+ expect(parseComlogBanInput('ban', ' ')).toBeNull();
+ });
+
+ it('ban 사유는 500자까지만', () => {
+ expect(parseComlogBanInput('ban', 'a'.repeat(500))).not.toBeNull();
+ expect(parseComlogBanInput('ban', 'a'.repeat(501))).toBeNull();
+ });
+
+ it('unban 은 사유를 무시', () => {
+ expect(parseComlogBanInput('unban', '무시')).toEqual({
+ action: 'unban',
+ reason: null,
+ });
+ expect(parseComlogBanInput('unban', null)).toEqual({
+ action: 'unban',
+ reason: null,
+ });
+ });
+});
diff --git a/lib/admin/comlog-ban.ts b/lib/admin/comlog-ban.ts
new file mode 100644
index 0000000..ffc4c07
--- /dev/null
+++ b/lib/admin/comlog-ban.ts
@@ -0,0 +1,31 @@
+import { MAX_BAN_REASON_LENGTH } from '@/lib/posts/moderation';
+
+/**
+ * comlog 프로젝트 숨기기·해제 입력 검증 (서버 액션용 순수 함수)
+ * - 게시글 검수 요청과 같은 규칙: ban 은 앞뒤 공백을 뗀 사유가 1~500자 필수, unban 은 사유를 무시
+ */
+
+export type ComlogBanAction = 'ban' | 'unban';
+
+export interface ComlogBanInput {
+ action: ComlogBanAction;
+ // 해제는 null
+ reason: string | null;
+}
+
+export const parseComlogBanInput = (
+ action: ComlogBanAction,
+ reason: string | null | undefined,
+): ComlogBanInput | null => {
+ if (action === 'unban') {
+ return { action, reason: null };
+ }
+
+ const trimmed = (reason ?? '').trim();
+
+ if (!trimmed || trimmed.length > MAX_BAN_REASON_LENGTH) {
+ return null;
+ }
+
+ return { action, reason: trimmed };
+};
diff --git a/lib/admin/comlog-queries.ts b/lib/admin/comlog-queries.ts
new file mode 100644
index 0000000..1f7fba2
--- /dev/null
+++ b/lib/admin/comlog-queries.ts
@@ -0,0 +1,153 @@
+import 'server-only';
+import { count, desc, eq, ilike, isNotNull, or, sql } from 'drizzle-orm';
+import { logAdminAction } from '@/lib/admin/audit';
+import type { ComlogBanAction } from '@/lib/admin/comlog-ban';
+import { requireAdmin } from '@/lib/admin/guard';
+import { ADMIN_PAGE_SIZE } from '@/lib/admin/pagination';
+import { escapeLike } from '@/lib/admin/search';
+import { revalidateComlogPages } from '@/lib/comlog/revalidate';
+import { db } from '@/lib/db';
+import {
+ comlogProject,
+ draft,
+ post,
+ user,
+ type ComlogProjectStatus,
+} from '@/lib/db/schema';
+import type { ComlogVisibility } from '@/lib/comlog/rules';
+
+/**
+ * 어드민 comlog 프로젝트 조회·숨기기
+ */
+
+export interface ComlogProjectListFilters {
+ q: string;
+ page: number;
+}
+
+export interface ComlogProjectListRow {
+ id: string;
+ name: string;
+ slug: string;
+ status: ComlogProjectStatus;
+ visibility: ComlogVisibility;
+ enabled: boolean;
+ bannedAt: Date | null;
+ banReason: string | null;
+ ownerEmail: string;
+ ownerGithubLogin: string | null;
+ entryCount: number;
+}
+
+// 프로젝트마다 센 회차 수 (회차 = kind 가 comlog 인 게시글, 프로젝트와는 초안의 사용자·저장소로 이어짐)
+const entryCountSql = sql`(select count(*)::int from ${post} inner join ${draft} on ${draft.id} = ${post.draftId} where ${post.kind} = 'comlog' and ${draft.userId} = ${comlogProject.userId} and ${draft.repositoryId} = ${comlogProject.repositoryId})`;
+
+/**
+ * 프로젝트 목록 (이름·소유자 부분 일치, 숨김 프로젝트가 먼저, 그 안에서는 최근 생성순, 50개씩)
+ * - 소개 같은 본문은 읽지 않음
+ */
+export const listComlogProjects = async ({
+ q,
+ page,
+}: ComlogProjectListFilters): Promise<{
+ rows: ComlogProjectListRow[];
+ total: number;
+}> => {
+ // 페이지를 거치지 않는 호출도 여기서 조회 권한(view)을 확인
+ await requireAdmin('view');
+
+ const term = q.trim();
+ const pattern = `%${escapeLike(term)}%`;
+ const where = term
+ ? or(
+ ilike(comlogProject.name, pattern),
+ ilike(user.email, pattern),
+ ilike(user.githubLogin, pattern),
+ )
+ : undefined;
+
+ const [[totals], rows] = await Promise.all([
+ db
+ .select({ total: count() })
+ .from(comlogProject)
+ .innerJoin(user, eq(user.id, comlogProject.userId))
+ .where(where),
+ db
+ .select({
+ id: comlogProject.id,
+ name: comlogProject.name,
+ slug: comlogProject.slug,
+ status: comlogProject.status,
+ visibility: comlogProject.visibility,
+ enabled: comlogProject.enabled,
+ bannedAt: comlogProject.bannedAt,
+ banReason: comlogProject.banReason,
+ ownerEmail: user.email,
+ ownerGithubLogin: user.githubLogin,
+ entryCount: entryCountSql,
+ })
+ .from(comlogProject)
+ .innerJoin(user, eq(user.id, comlogProject.userId))
+ .where(where)
+ .orderBy(
+ desc(isNotNull(comlogProject.bannedAt)),
+ desc(comlogProject.createdAt),
+ desc(comlogProject.id),
+ )
+ .limit(ADMIN_PAGE_SIZE)
+ .offset((Math.max(1, page) - 1) * ADMIN_PAGE_SIZE),
+ ]);
+
+ return { total: totals.total, rows };
+};
+
+export type ComlogBanResult = 'banned' | 'unbanned' | 'not_found';
+
+const ACTION_BY_BAN = {
+ ban: 'comlog.ban',
+ unban: 'comlog.unban',
+} as const;
+
+/**
+ * 프로젝트 숨기기·해제 (게시글 밴과 같은 구조)
+ * - 권한 확인(requireAdmin) → 갱신 → 감사 기록 → 공개 화면·사이트맵 재검증
+ * - ban: 처음 숨긴 시각은 유지하고 사유만 갱신, unban: 시각과 사유를 비움
+ * - 사유 검증은 parseComlogBanInput 이 먼저 끝낸 값만 받음
+ */
+export const setComlogProjectBan = async (
+ projectId: string,
+ action: ComlogBanAction,
+ reason: string | null,
+ adminId: string,
+): Promise => {
+ await requireAdmin(ACTION_BY_BAN[action]);
+
+ const values =
+ action === 'ban'
+ ? {
+ bannedAt: sql`coalesce(${comlogProject.bannedAt}, now())`,
+ banReason: reason,
+ }
+ : { bannedAt: null, banReason: null };
+
+ const rows = await db
+ .update(comlogProject)
+ .set(values)
+ .where(eq(comlogProject.id, projectId))
+ .returning({ id: comlogProject.id });
+
+ if (rows.length === 0) {
+ return 'not_found';
+ }
+
+ await logAdminAction({
+ adminId,
+ action: ACTION_BY_BAN[action],
+ targetType: 'comlog_project',
+ targetId: projectId,
+ detail: reason ? { reason } : {},
+ });
+ revalidateComlogPages();
+
+ return action === 'ban' ? 'banned' : 'unbanned';
+};
diff --git a/lib/admin/post-queries.ts b/lib/admin/post-queries.ts
index a94f51d..0cf5ef7 100644
--- a/lib/admin/post-queries.ts
+++ b/lib/admin/post-queries.ts
@@ -17,6 +17,7 @@ import { post, postView, POST_VISIBILITIES } from '@/lib/db/schema/post';
import type { PostVisibility } from '@/lib/db/schema/post';
import { LOCALES } from '@/lib/i18n/config';
import type { Locale } from '@/lib/i18n/config';
+import { adminKindCondition, type AdminPostKindFilter } from '@/lib/posts/kind';
/**
* 어드민 게시글 조회 (읽기 전용)
@@ -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/roles.ts b/lib/admin/roles.ts
index ac5ed54..cc9997d 100644
--- a/lib/admin/roles.ts
+++ b/lib/admin/roles.ts
@@ -10,6 +10,8 @@ export const ADMIN_ACTIONS = [
'user.changePlan',
'post.ban',
'post.unban',
+ 'comlog.ban',
+ 'comlog.unban',
'prompt.edit',
'post.delete',
'history.delete',
@@ -29,6 +31,8 @@ const EDITOR_ACTIONS: readonly AdminAction[] = [
'user.changePlan',
'post.ban',
'post.unban',
+ 'comlog.ban',
+ 'comlog.unban',
'prompt.edit',
];
diff --git a/lib/admin/stats-queries.ts b/lib/admin/stats-queries.ts
index e6f2929..aaf9bf2 100644
--- a/lib/admin/stats-queries.ts
+++ b/lib/admin/stats-queries.ts
@@ -18,6 +18,7 @@ import { post } from '@/lib/db/schema/post';
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';
/**
* 어드민 대시보드 조회 (읽기 전용)
@@ -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..c9bbd12 100644
--- a/lib/admin/user-queries.ts
+++ b/lib/admin/user-queries.ts
@@ -11,6 +11,7 @@ import { post } from '@/lib/db/schema/post';
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';
/**
* 어드민 사용자 조회 (읽기 전용)
@@ -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/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/exclusion.test.ts b/lib/auto-draft/exclusion.test.ts
new file mode 100644
index 0000000..237948a
--- /dev/null
+++ b/lib/auto-draft/exclusion.test.ts
@@ -0,0 +1,27 @@
+import { PgDialect } from 'drizzle-orm/pg-core';
+import { describe, expect, it } from 'vitest';
+import { overwriteWhere, uniqueShas } from '@/lib/auto-draft/exclusion';
+
+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();
+ });
+});
+
+describe('uniqueShas', () => {
+ it('겹치는 SHA 를 순서대로 하나만 남김', () => {
+ expect(uniqueShas(['a', 'b', 'a', 'c', 'b'])).toEqual(['a', 'b', 'c']);
+ });
+
+ it('빈 목록은 그대로', () => {
+ expect(uniqueShas([])).toEqual([]);
+ });
+});
diff --git a/lib/auto-draft/exclusion.ts b/lib/auto-draft/exclusion.ts
new file mode 100644
index 0000000..74e7523
--- /dev/null
+++ b/lib/auto-draft/exclusion.ts
@@ -0,0 +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 overwriteWhere = (reason: ExcludedCommitReason): SQL | null =>
+ reason === 'user' ? eq(repositoryExcludedCommit.reason, 'backlog') : null;
diff --git a/lib/auto-draft/markers.test.ts b/lib/auto-draft/markers.test.ts
index deeaff9..b44b412 100644
--- a/lib/auto-draft/markers.test.ts
+++ b/lib/auto-draft/markers.test.ts
@@ -6,6 +6,7 @@ import type { SkipReason } from '@/lib/auto-draft/batch';
import {
getCommitMarkers,
getCommitMenu,
+ getOffMarkers,
isCollectable,
} from '@/lib/auto-draft/markers';
@@ -15,6 +16,10 @@ const state = {
batchShas: ['a', 'b'],
skipped: new Map(),
excluded: new Map(),
+ backlogShas: new Set(),
+ comlogUsedShas: new Set(),
+ appliedShas: new Set(),
+ viewKind: 'post' as const,
};
describe('getCommitMarkers', () => {
@@ -156,3 +161,148 @@ 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' }]);
+ });
+});
+
+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' });
+ });
+});
+
+describe('회차 화면의 사용됨 표시', () => {
+ const comlogView = {
+ ...state,
+ viewKind: 'comlog' as const,
+ // 회차 화면이면 서버가 회차 작업(출처 무관)에 쓴 커밋 전체를 보냄
+ comlogUsedShas: new Set(['b']),
+ skipped: new Map([['c', 'consumed']]),
+ };
+
+ it('회차에 쓴 커밋은 자동 대상 대신 회차에 사용됨', () => {
+ expect(getCommitMarkers({ ...base, sha: 'b' }, comlogView)).toEqual([
+ { kind: 'comlog_used' },
+ ]);
+ });
+
+ it('일반 글 자동 초안에만 쓴 커밋은 회차 화면에서 사용됨이 아님', () => {
+ expect(getCommitMarkers({ ...base, sha: 'c' }, comlogView)).toEqual([]);
+ });
+
+ it('일반 초안 화면은 지금 규칙 (commit_trigger 사용됨만)', () => {
+ const postView = { ...comlogView, viewKind: 'post' as const };
+
+ expect(getCommitMarkers({ ...base, sha: 'c' }, postView)).toEqual([
+ { kind: 'consumed' },
+ ]);
+ expect(getCommitMarkers({ ...base, sha: 'b' }, postView)).toEqual([
+ { kind: 'auto', position: 2 },
+ ]);
+ });
+
+ it('제외가 회차 사용됨보다 먼저', () => {
+ expect(
+ getCommitMarkers(
+ { ...base, sha: 'b' },
+ {
+ ...comlogView,
+ excluded: new Map([['b', 'user']]),
+ },
+ ),
+ ).toEqual([{ kind: 'excluded', reason: 'user' }]);
+ });
+
+ it('회차 사용됨이면서 이 회차에 적용된 커밋은 둘 다', () => {
+ expect(
+ getCommitMarkers(
+ { ...base, sha: 'b' },
+ { ...comlogView, appliedShas: new Set(['b']) },
+ ),
+ ).toEqual([{ kind: 'comlog_used' }, { kind: 'applied' }]);
+ });
+});
+
+describe('getOffMarkers (자동 초안 꺼짐)', () => {
+ const off = {
+ appliedShas: new Set(['a']),
+ comlogUsedShas: new Set(['a', 'b']),
+ viewKind: 'comlog' as const,
+ };
+
+ it('회차 화면은 회차 사용됨과 적용됨', () => {
+ expect(getOffMarkers(base, off)).toEqual([
+ { kind: 'comlog_used' },
+ { kind: 'applied' },
+ ]);
+ expect(getOffMarkers({ ...base, sha: 'b' }, off)).toEqual([
+ { kind: 'comlog_used' },
+ ]);
+ });
+
+ it('일반 초안 화면은 적용됨만', () => {
+ expect(getOffMarkers(base, { ...off, viewKind: 'post' })).toEqual([
+ { kind: 'applied' },
+ ]);
+ });
+
+ it('머지 커밋은 표시 없음', () => {
+ expect(getOffMarkers({ sha: 'a', parentShas: ['x', 'y'] }, off)).toEqual(
+ [],
+ );
+ });
+});
diff --git a/lib/auto-draft/markers.ts b/lib/auto-draft/markers.ts
index cd7d6b2..40c7c1a 100644
--- a/lib/auto-draft/markers.ts
+++ b/lib/auto-draft/markers.ts
@@ -1,20 +1,29 @@
+import type { ExcludedCommitReason } from '@/lib/db/schema/auto-draft';
import { isMergeCommit, type SkipReason } from '@/lib/auto-draft/batch';
+import type { DraftKind } from '@/lib/studio/options';
/**
* 스튜디오 커밋 줄에 붙이는 자동 초안 표시 계산 (순수 함수)
*/
-export type ExcludedReason = 'user' | 'force_push';
+// 스키마 값과 같음 (backlog 는 제외 목록에 함께 저장되지만 표시는 별도 backlogShas 로 다룸)
+export type ExcludedReason = ExcludedCommitReason;
export type CommitMarker =
| { kind: 'anchor' }
// position: 묶음 안 순번 (1부터)
| { kind: 'auto'; position: number }
| { kind: 'excluded'; reason: ExcludedReason }
- // 이전 자동 초안에 이미 쓴 커밋
+ // 이전 자동 초안에 이미 쓴 커밋 (일반 글 화면: commit_trigger 일반 글 작업 기준)
| { kind: 'consumed' }
+ // 회차 화면에서 회차 작업(출처 무관, 실패 제외)에 이미 쓴 커밋
+ | { kind: 'comlog_used' }
// 머지 커밋 (내용이 없어 자동 대상이 아님)
- | { kind: 'not_collected' };
+ | { kind: 'not_collected' }
+ // 회차를 만들지 못해 밀린 커밋 (아직 회차에 쓰이지 않음)
+ | { kind: 'backlog' }
+ // 보고 있는 초안의 최근 완료 작업에 쓴 커밋
+ | { kind: 'applied' };
export interface MarkerCommit {
sha: string;
@@ -27,6 +36,14 @@ export interface MarkerState {
// 서버가 계산한 범위(경계 다음 ~ 브랜치 끝) 안에서 건너뛴 커밋과 사유
skipped: ReadonlyMap;
excluded: ReadonlyMap;
+ // 밀린 커밋 (회차에 쓴 것도 들어 있을 수 있음, 표시는 comlogUsedShas 를 뺀 것만)
+ backlogShas: ReadonlySet;
+ // 회차 작업(실패 제외)에 쓴 커밋 (일반 글 화면은 밀린 커밋 중 쓴 것만, 회차 화면은 전체)
+ comlogUsedShas: ReadonlySet;
+ // 보고 있는 초안의 최근 완료 작업 commit_shas
+ appliedShas: ReadonlySet;
+ // 화면 종류: 회차 화면(소개·새 회차·회차)이면 "사용됨" 을 회차 작업 기준으로 봄
+ viewKind: DraftKind;
}
/**
@@ -45,18 +62,50 @@ 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' }];
+ // 회차 화면은 회차 작업에 쓴 커밋을, 일반 글 화면은 지금처럼 자동 초안에 쓴 커밋을 사용됨으로 봄
+ if (state.viewKind === 'comlog') {
+ if (state.comlogUsedShas.has(commit.sha)) return [{ kind: 'comlog_used' }];
+ } else if (isConsumed(commit, state)) {
+ return [{ kind: 'consumed' }];
+ }
const index = state.batchShas.indexOf(commit.sha);
@@ -71,6 +120,27 @@ export const getCommitMarkers = (
return markers;
};
+/**
+ * 자동 초안이 꺼져 있을 때의 커밋 줄 표시 (기준점·묶음·제외는 없음, 머지 커밋 제외)
+ * - 회차는 스튜디오에서 직접 쓰므로 회차 화면의 "회차에 사용됨" 과 보고 있는 초안의 "적용됨" 은 보여 줌
+ */
+export const getOffMarkers = (
+ commit: MarkerCommit,
+ state: Pick,
+): CommitMarker[] => {
+ if (isMergeCommit(commit)) return [];
+
+ const markers: CommitMarker[] = [];
+
+ if (state.viewKind === 'comlog' && state.comlogUsedShas.has(commit.sha)) {
+ markers.push({ kind: 'comlog_used' });
+ }
+
+ if (state.appliedShas.has(commit.sha)) markers.push({ kind: 'applied' });
+
+ return markers;
+};
+
/**
* 커밋 줄 메뉴 구성 ("여기를 기준점으로" 는 메뉴가 있으면 항상 있음)
* - 머지 커밋: 메뉴 없음 (null)
diff --git a/lib/auto-draft/run.test.ts b/lib/auto-draft/run.test.ts
index 1d5b1be..bbe3085 100644
--- a/lib/auto-draft/run.test.ts
+++ b/lib/auto-draft/run.test.ts
@@ -8,6 +8,7 @@ vi.mock('@/lib/auto-draft/store', () => ({}));
vi.mock('@/lib/generation/draft-job', () => ({}));
vi.mock('@/lib/generation/jobs', () => ({}));
vi.mock('@/lib/generation/get-runner', () => ({}));
+vi.mock('@/lib/observability/report-error', () => ({ reportError: vi.fn() }));
import type { BranchCommit } from '@/lib/auto-draft/batch';
import {
@@ -18,15 +19,21 @@ 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 { reportError } from '@/lib/observability/report-error';
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: {
@@ -46,9 +53,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 = (
@@ -67,15 +80,22 @@ 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 () => {}),
+ clearBoundaryClaim: vi.fn(async () => {}),
getBoundary: vi.fn(async (): Promise => OLD),
getLocale: vi.fn(async () => 'en' as const),
...over,
@@ -156,7 +176,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 () => {
@@ -191,23 +211,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({
@@ -226,10 +248,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');
@@ -253,16 +275,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');
@@ -280,15 +304,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');
@@ -299,15 +325,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',
- expect.objectContaining({ commitShas: ['c3', 'c2'] }),
+ ['c1', 'c2', 'c3'],
+ 'post_trigger',
+ );
+ expect(deps.createDraftJobs).toHaveBeenCalledWith(
+ 'u1',
+ 'r1',
+ [expect.objectContaining({ commitShas: ['c3', 'c2'] })],
'en',
);
});
@@ -323,15 +350,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',
);
});
@@ -339,7 +368,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' });
@@ -359,10 +388,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');
}),
});
@@ -378,7 +407,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 () => {
@@ -396,13 +425,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',
);
});
@@ -414,7 +443,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 () => {
@@ -427,19 +456,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',
);
// 두 번째 묶음은 끝까지 봐서 경계를 푸시 끝으로 선점
@@ -448,20 +482,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' });
@@ -473,15 +507,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' });
@@ -518,14 +552,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');
}),
});
@@ -535,10 +569,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) => {
@@ -561,24 +596,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 };
@@ -590,7 +632,7 @@ describe('runAutoDraft', () => {
expect(await runAutoDraft(target(), push('c3'), deps)).toEqual({
status: 'started',
- jobId: 'j1',
+ jobIds: ['j1'],
});
expect(getBoundary()).toBe('c3');
@@ -601,7 +643,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' }),
);
@@ -624,18 +666,617 @@ 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('저장된 기본 옵션이 worklog 여도 일반 글 작업은 기본 글 종류로 (회차만 worklog)', async () => {
+ const deps = makeDeps();
+ const saved = {
+ ...DEFAULT_PROMPT_OPTIONS,
+ model: 'haiku' as const,
+ postType: 'worklog' as const,
+ };
+ await runAutoDraft(
+ target({ options: saved }, true),
+ push('c3', both),
+ deps,
+ );
+ const requests = vi.mocked(deps.createDraftJobs).mock.calls[0][2];
+ expect(requests.map((r) => [r.draftKind, r.options.postType])).toEqual([
+ ['post', DEFAULT_PROMPT_OPTIONS.postType],
+ ['comlog', 'worklog'],
+ ]);
+ });
+
+ it('comlog 끔 + 저장된 worklog → 일반 글 작업이 worklog 로 돌지 않음', async () => {
+ const deps = makeDeps();
+ await runAutoDraft(
+ target({
+ options: {
+ ...DEFAULT_PROMPT_OPTIONS,
+ model: 'haiku',
+ postType: 'worklog',
+ },
+ }),
+ push('c3'),
+ deps,
+ );
+ expect(deps.createDraftJobs).toHaveBeenCalledWith(
+ 'u1',
+ 'r1',
+ [
+ expect.objectContaining({
+ draftKind: 'post',
+ options: expect.objectContaining({
+ postType: DEFAULT_PROMPT_OPTIONS.postType,
+ }),
+ }),
+ ],
+ '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).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 = () =>
+ 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('밀린 커밋은 실패 행보다 먼저 기록', 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 });
+ vi.mocked(reportError).mockClear();
+
+ const out = await runAutoDraft(target({}, true), push('c3'), deps);
+ expect(out).toEqual({ status: 'skipped', errorCode: 'quota_exceeded' });
+ expect(compare).toHaveBeenCalledTimes(2);
+ expect(deps.recordBacklog).toHaveBeenCalledWith('u1', 'r1', [
+ 'c1',
+ 'c2',
+ 'c3',
+ ]);
+ expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c3');
+ expect(reportError).not.toHaveBeenCalled();
+ });
+
+ it('밀린 커밋 기록(recordBacklog)이 한 번 던져도 다시 시도', async () => {
+ const recordBacklog = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('db'))
+ .mockResolvedValue(undefined);
+ const deps = makeDeps({ gate: quotaGate(), recordBacklog });
+
+ await runAutoDraft(target({}, true), push('c3'), deps);
+ expect(recordBacklog).toHaveBeenCalledTimes(2);
+ expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c3');
+ });
+
+ it('다시 시도해도 실패하면 backlog-failed 로 보고하고 실제 사유로 실패 행을 남김 (커밋 메시지 없음)', async () => {
+ const compare = vi
+ .fn()
+ .mockRejectedValue(new Error('github'));
+ const deps = makeDeps({ gate: quotaGate(), compare });
+ vi.mocked(reportError).mockClear();
+
+ const out = await runAutoDraft(
+ target({}, true),
+ push('c3', {}, 'c5'),
+ deps,
+ );
+ expect(out).toEqual({ status: 'skipped', errorCode: 'quota_exceeded' });
+ expect(compare).toHaveBeenCalledTimes(2);
+ expect(reportError).toHaveBeenCalledTimes(1);
+ expect(reportError).toHaveBeenCalledWith(
+ expect.any(Error),
+ 'auto-draft.backlog-failed',
+ { repositoryId: 'r1', boundary: OLD, headSha: 'c5' },
+ );
+ expect(deps.recordBacklog).not.toHaveBeenCalled();
+ expect(deps.moveBoundary).not.toHaveBeenCalled();
+ expect(deps.recordFailure).toHaveBeenCalledWith(
+ expect.objectContaining({
+ draftKind: 'comlog',
+ errorCode: 'quota_exceeded',
+ }),
+ );
+ });
+
+ it.each([
+ ['behind', 'c5', 'c3'],
+ ['identical', 'c3', 'c3'],
+ ])(
+ '막힌 회차 트리거의 푸시가 경계보다 앞서지 않으면(%s) 경계를 되돌리지 않고 backlog 없음',
+ async (_, boundary, head) => {
+ const deps = makeDeps({
+ gate: quotaGate(),
+ // GitHub compare 는 identical·behind 를 커밋 없는 ok 로 돌려줌
+ compare: vi.fn(async () => ({ status: 'ok' as const, commits: [] })),
+ });
+ const out = await runAutoDraft(
+ target({ boundarySha: boundary }, true),
+ push(head),
+ deps,
+ );
+ expect(out).toEqual({
+ status: 'skipped',
+ errorCode: 'quota_exceeded',
+ });
+ expect(deps.compare).toHaveBeenCalledWith(
+ expect.anything(),
+ boundary,
+ head,
+ );
+ expect(deps.recordBacklog).not.toHaveBeenCalled();
+ expect(deps.moveBoundary).not.toHaveBeenCalled();
+ },
+ );
+
+ it('범위 커밋이 모두 건너뛸 커밋이어도 푸시가 앞서 있으면 경계는 푸시 끝으로', async () => {
+ const deps = makeDeps({
+ gate: quotaGate(),
+ compare: vi.fn(async () => ({
+ status: 'ok' as const,
+ commits: [commit(1, '[comdraft]')],
+ })),
+ listExcludedShas: vi.fn(async () => new Map([['c1', 'user' as const]])),
+ });
+ await runAutoDraft(target({}, true), push('c1'), deps);
+ expect(deps.recordBacklog).not.toHaveBeenCalled();
+ expect(deps.moveBoundary).toHaveBeenCalledWith('u1', 'r1', OLD, 'c1');
+ });
+
+ 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();
+ // 경계를 지나가지 않았으므로 선점 표시를 지운 뒤 실패 처리
+ 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 () => {
+ 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),
@@ -661,9 +1302,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 2ab1962..2f7026f 100644
--- a/lib/auto-draft/run.ts
+++ b/lib/auto-draft/run.ts
@@ -3,21 +3,28 @@ 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,
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 +32,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 {
+ fitOptionsToKind,
+ type DraftKind,
+ type PromptOptions,
+} from '@/lib/studio/options';
import { reportError } from '@/lib/observability/report-error';
/**
@@ -37,10 +48,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 +85,7 @@ export interface FailureRecord {
prompt: string;
options: PromptOptions;
locale: Locale;
+ draftKind: DraftKind;
}
export interface RunDeps {
@@ -64,12 +97,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 +110,10 @@ export interface RunDeps {
failJob: (jobId: string, errorCode: GenerationErrorCode) => Promise;
recordFailure: (record: FailureRecord) => Promise<'recorded' | 'duplicate'>;
moveBoundary: typeof moveBoundary;
+ // 범위 커밋을 밀린 커밋(제외 사유 backlog)으로 남김
+ recordBacklog: typeof recordBacklog;
+ // 경계를 되돌린 작업의 "경계 선점" 표시를 지움 (실패한 회차를 밀린 커밋으로 오인하지 않게)
+ clearBoundaryClaim: typeof clearBoundaryClaim;
// 지금 경계 (설정 행이 없으면 null)
getBoundary: (userId: string, repositoryId: string) => Promise;
getLocale: (userId: string) => Promise;
@@ -115,6 +152,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 +169,21 @@ 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),
+ clearBoundaryClaim: (jobIds) => clearBoundaryClaim(jobIds),
getBoundary: async (userId, repositoryId) =>
(await getAutoDraftSetting(userId, repositoryId))?.boundarySha ?? null,
getLocale: getLatestLocale,
@@ -162,26 +203,80 @@ const slotErrorCode = (
return status === 'busy' ? 'too_many_active' : status;
};
+// 트리거로 만들 작업 하나의 종류와 옵션
+interface PlannedKind {
+ kind: DraftKind;
+ options: PromptOptions;
+}
+
+/**
+ * 종류별 옵션
+ * - 일반 글: 저장소 기본 옵션 위에 트리거 단어(톤·글 종류·길이), worklog 는 고를 수 없어 기본 글 종류로
+ * - 회차: 저장소 기본 옵션에 고정 옵션(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,
+ // 일반 글에 저장된 worklog(회차 전용)는 기본 글 종류로 맞춤 → [comdraft] post 가 회차 형식으로 쓰이지 않게
+ options: fitOptionsToKind(
+ kind,
+ kind === 'comlog'
+ ? 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,22 +285,37 @@ 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,
+ // 이 사유로 막혔을 때 밀린 커밋으로 남기는지 (회차를 만들 트리거 + 할당량·속도 제한 계열)
+ const willBacklog = (errorCode: GenerationErrorCode) =>
+ kinds.includes('comlog') && isBacklogErrorCode(errorCode);
+
+ /**
+ * 시작 전 실패: (밀린 커밋 기록 →) 종류마다 행을 남기고 결과로 변환
+ * - backlogFrom: 막힌 시점의 경계 (회차가 할당량 등으로 막혔으면 여기서부터 밀린 커밋으로 남김)
+ * - 밀린 커밋을 실패 행보다 먼저 기록 (제외 목록 INSERT 와 경계 CAS 는 여러 번 해도 결과가 같음)
+ * - 밀린 커밋 기록이 끝내 실패해도 실제 사유로 실패 행은 남김 (보고는 recordRangeBacklogWithRetry 가 함)
+ */
+ const skip = async (
+ errorCode: GenerationErrorCode,
+ backlogFrom: string | null = null,
+ ): Promise => {
+ if (backlogFrom !== null && willBacklog(errorCode)) {
+ await recordRangeBacklogWithRetry(target, push, deps, backlogFrom, scope);
+ }
+
+ const recorded = await recordFailures(
+ target,
+ push,
+ plans,
errorCode,
- prompt: setting.prompt,
- options,
locale,
- });
+ deps,
+ );
return recorded === 'duplicate'
? { status: 'duplicate' }
@@ -217,7 +327,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 +343,17 @@ export async function runAutoDraft(
const result = await tryStartBatch(target, push, deps, {
boundary,
excluded,
- options,
+ plans,
+ scope,
+ willBacklog,
locale,
githubToken: gate.githubToken,
});
- if (result.status === 'skip') return skip(result.errorCode);
+ // 작업을 못 만들었으면 (선점한 범위를 이미 밀린 커밋으로 남긴 경우가 아니면) 지금 경계부터 밀린 커밋으로 봄
+ if (result.status === 'skip') {
+ return skip(result.errorCode, result.backlogRecorded ? null : boundary);
+ }
if (result.status !== 'conflict') return result;
// 다른 트리거가 먼저 경계를 옮기거나 커밋을 썼음 → 지금 경계로 다시 계산
@@ -248,13 +365,90 @@ export async function runAutoDraft(
}
}
+/**
+ * 막힌 회차 트리거의 범위 커밋(경계 다음 ~ 푸시 끝, 20개 제한 없음)을 밀린 커밋으로 남기고 경계를 푸시 끝으로
+ * - 범위를 계산하지 못하면(anchor_missing) 실패 행만 남긴 채 그대로 둠
+ * - 푸시 끝이 경계보다 앞서지 않으면(identical·behind) 아무것도 하지 않음
+ * - 경계는 막힌 시점 값일 때만 옮김 (그 사이 다른 트리거가 옮겼으면 그쪽을 따름)
+ */
+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;
+ // 푸시 끝이 경계보다 앞서지 않음(identical·behind: 늦게 온 웹훅·수동 재전송) → 경계를 옛 커밋으로 되돌리지 않음
+ if (!isAheadRange(plan)) return;
+
+ if (plan.batchShas.length > 0) {
+ await deps.recordBacklog(userId, repositoryId, plan.batchShas);
+ }
+ await deps.moveBoundary(userId, repositoryId, boundary, push.headSha);
+}
+
+/**
+ * 범위에 커밋이 하나라도 있는지 (푸시 끝이 경계보다 앞섬)
+ * - 개수 제한 없이 계산한 묶음은 범위 커밋이 모두 묶음이나 건너뜀에 들어가므로 둘 다 비면 범위가 빈 것
+ * (compare 가 identical·behind 를 커밋 없는 ok 로 돌려줌)
+ */
+const isAheadRange = (plan: {
+ batchShas: string[];
+ skipped: Map;
+}) => plan.batchShas.length > 0 || plan.skipped.size > 0;
+
+/**
+ * 밀린 커밋 기록을 한 번 다시 시도 (GitHub compare 일시 오류 등)
+ * - 웹훅은 이미 202 로 답해 GitHub 가 다시 보내지 않으므로, 여기서 포기하면 그 커밋이 다음 트리거 묶음에 섞임 (§2 실패 조건)
+ * → 다시 실패하면 전용 태그로 보고해 알아챌 수 있게 하고, 실패 행은 실제 사유로 남김
+ * - 보고에는 식별자와 SHA 만 (커밋 메시지는 넣지 않음)
+ */
+async function recordRangeBacklogWithRetry(
+ target: PushTarget,
+ push: TriggerPush,
+ deps: RunDeps,
+ boundary: string,
+ scope: ConsumedScope,
+): Promise {
+ try {
+ await recordRangeBacklog(target, push, deps, boundary, scope);
+ } catch {
+ try {
+ await recordRangeBacklog(target, push, deps, boundary, scope);
+ } catch (error) {
+ reportError(error, 'auto-draft.backlog-failed', {
+ repositoryId: target.repositoryId,
+ boundary,
+ headSha: push.headSha,
+ });
+ }
+ }
+}
+
// 다른 트리거와 겹쳤을 때 묶음을 다시 계산하는 최대 횟수
const MAX_BATCH_ATTEMPTS = 3;
interface BatchAttempt {
boundary: string;
excluded: ReadonlyMap;
- options: PromptOptions;
+ plans: PlannedKind[];
+ scope: ConsumedScope;
+ willBacklog: (errorCode: GenerationErrorCode) => boolean;
locale: Locale;
githubToken: string;
}
@@ -262,7 +456,12 @@ interface BatchAttempt {
type AttemptResult =
| Exclude
| { status: 'skipped'; errorCode: 'runner_unavailable' }
- | { status: 'skip'; errorCode: GenerationErrorCode }
+ // backlogRecorded: 선점한 범위를 이미 밀린 커밋으로 남김 (경계는 푸시 끝 그대로)
+ | {
+ status: 'skip';
+ errorCode: GenerationErrorCode;
+ backlogRecorded?: boolean;
+ }
| { status: 'conflict' };
/**
@@ -274,7 +473,15 @@ async function tryStartBatch(
target: PushTarget,
push: TriggerPush,
deps: RunDeps,
- { boundary, excluded, options, locale, githubToken }: BatchAttempt,
+ {
+ boundary,
+ excluded,
+ plans,
+ scope,
+ willBacklog,
+ locale,
+ githubToken,
+ }: BatchAttempt,
): Promise {
const { userId, repositoryId, setting } = target;
const plan = await computeAutoDraftBatch(
@@ -285,6 +492,7 @@ async function tryStartBatch(
boundarySha: boundary,
endSha: push.headSha,
excluded,
+ consumedScope: scope,
},
deps,
);
@@ -314,22 +522,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,
- },
+ requests,
locale,
);
} catch (error) {
@@ -340,29 +553,72 @@ async function tryStartBatch(
throw error;
}
+ if (created.status === 'duplicate' || created.status === 'overlap') {
+ await revert();
+
+ 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 };
+ }
+
await revert();
- if (created.status === 'duplicate') return { status: 'duplicate' };
- if (created.status === 'overlap') return { status: 'conflict' };
+ return { status: 'skip', errorCode };
+ }
+
+ const jobIds = created.jobs.map((job) => job.jobId);
+ const failedJobIds: string[] = [];
- return { status: 'skip', errorCode: slotErrorCode(created.status) };
+ for (const jobId of jobIds) {
+ try {
+ await deps.startRunner({ jobId, githubToken });
+ } catch (error) {
+ reportError(error, 'auto-draft.start-runner', { jobId, repositoryId });
+ failedJobIds.push(jobId);
+ }
}
- try {
- await deps.startRunner({ jobId: created.jobId, githubToken });
- } catch (error) {
- reportError(error, 'auto-draft.start-runner', {
- jobId: created.jobId,
- repositoryId,
- });
- // 작업 행이 이미 있으므로 실패 행을 따로 남기지 않음
- // 경계를 먼저 되돌려 failJob 이 실패해도 항상 복구
+ // 하나도 시작하지 못했을 때만 경계를 되돌림 (하나라도 시작했으면 그 작업이 커밋을 쓰고 있음)
+ // 경계를 먼저 되돌려 failJob 이 실패해도 항상 복구
+ const noneStarted = failedJobIds.length === jobIds.length;
+ if (noneStarted && claimTo !== null) {
await revert();
- await deps.failJob(created.jobId, 'runner_unavailable');
+ // 경계를 지나가지 않았으므로 실패한 회차의 커밋을 밀린 커밋으로 남기지 않게 표시를 지움
+ await deps.clearBoundaryClaim(jobIds);
+ }
+ // 작업 행이 이미 있으므로 실패 행을 따로 남기지 않음
+ 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..0d57dd7 100644
--- a/lib/auto-draft/store.ts
+++ b/lib/auto-draft/store.ts
@@ -1,11 +1,24 @@
import 'server-only';
-import { and, arrayOverlaps, eq, inArray, isNull, sql } from 'drizzle-orm';
+import {
+ and,
+ arrayOverlaps,
+ eq,
+ desc,
+ 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 { 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';
import {
account,
+ comlogProject,
draftPrompt,
githubInstallation,
githubRepository,
@@ -47,6 +60,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 +290,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 +330,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),
),
@@ -307,19 +343,103 @@ export async function findConsumedShas(
);
}
-// 커밋을 자동 초안 대상에서 제외 (이미 제외된 SHA 는 무시)
+/**
+ * 이 사용자·저장소의 회차 작업(출처 무관, 진행 중·되묻기·완료)이 쓴 커밋 전체
+ * - 회차 화면의 커밋 목록 "회차에 사용됨" 표시용 (화면이 어떤 커밋을 불러왔는지 서버는 모르므로 범위 없이)
+ * - 조건은 findConsumedShas 의 comlog 범위와 같음
+ */
+export async function listComlogUsedShas(
+ userId: string,
+ repositoryId: string,
+): Promise {
+ const rows = await db
+ .select({ commitShas: draftPrompt.commitShas })
+ .from(draftPrompt)
+ .where(
+ and(
+ eq(draftPrompt.userId, userId),
+ eq(draftPrompt.repositoryId, repositoryId),
+ eq(draftPrompt.kind, 'draft'),
+ consumedScopeCondition('comlog'),
+ inArray(draftPrompt.status, CONSUMING_STATUSES),
+ ),
+ );
+
+ return [...new Set(rows.flatMap((row) => row.commitShas))];
+}
+
+// 초안의 최근 완료된 초안 작성 작업이 쓴 커밋 (커밋 줄의 "이 초안에 반영됨" 표시용, 없으면 빈 배열)
+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 는 무시, 단 밀린 커밋을 사용자가 제외하면 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 })))
- .onConflictDoNothing();
+ .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,
+ });
+}
+
+// 회차를 만들지 못해 밀린 커밋으로 남김 (이미 제외 목록에 있으면 그 사유를 그대로 둠)
+export async function recordBacklog(
+ userId: string,
+ repositoryId: string,
+ shas: string[],
+): Promise {
+ 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));
}
// 제외한 커밋을 다시 대상으로 되돌림
@@ -339,6 +459,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 +495,7 @@ export async function findPushTargets(
requiredBlocks: repositoryAutoDraft.requiredBlocks,
model: repositoryAutoDraft.model,
boundarySha: repositoryAutoDraft.boundarySha,
+ comlogEnabled: comlogProject.enabled,
})
.from(userRepository)
.innerJoin(
@@ -380,6 +514,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 +545,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 c65bf67..d45763a 100644
--- a/lib/auto-draft/trigger.test.ts
+++ b/lib/auto-draft/trigger.test.ts
@@ -1,19 +1,27 @@
import { describe, expect, it, vi } from 'vitest';
import { DEFAULT_PROMPT_OPTIONS } from '@/lib/studio/options';
-import { mergeTriggerOptions, parseTrigger } from '@/lib/auto-draft/trigger';
+import {
+ consumedScopeFor,
+ 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 +29,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 +72,50 @@ 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('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 96bc9d8..c12ed22 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,31 @@ 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'];
+}
+
+/**
+ * 묶음에서 건너뛸 "사용됨" 커밋을 셀 범위 (설계 §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 4e1e57a..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,
};
@@ -122,7 +138,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 +208,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 +233,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 +253,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 +269,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/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/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/comlog/entries.test.ts b/lib/comlog/entries.test.ts
new file mode 100644
index 0000000..aadec64
--- /dev/null
+++ b/lib/comlog/entries.test.ts
@@ -0,0 +1,232 @@
+import { describe, expect, it } from 'vitest';
+import type { ComlogAccess } from '@/lib/comlog/rules';
+import {
+ isLinkablePairedPost,
+ pickAdjacentEntries,
+ summarizeListedProjects,
+ toEntryListItems,
+ type ComlogEntryRow,
+} from '@/lib/comlog/entries';
+
+const OWNER = 'owner';
+
+const access = (overrides: Partial = {}): ComlogAccess => ({
+ enabled: true,
+ bannedAt: null,
+ ownerId: OWNER,
+ projectVisibility: 'public',
+ ...overrides,
+});
+
+const row = (
+ id: string,
+ day: number,
+ overrides: Partial = {},
+): ComlogEntryRow => ({
+ id,
+ slug: `slug-${id}`,
+ title: `title-${id}`,
+ excerpt: '',
+ visibility: 'public',
+ bannedAt: null,
+ publishedAt: new Date(Date.UTC(2026, 10, day)),
+ thumbnailUrl: null,
+ ...overrides,
+});
+
+// 최신순으로 들어오는 회차: e4 (비공개), e3 (밴), e2 (일부 공개), e1 (공개)
+const rows = [
+ row('e4', 4, { visibility: 'private' }),
+ row('e3', 3, { bannedAt: new Date() }),
+ row('e2', 2, { visibility: 'unlisted' }),
+ row('e1', 1),
+];
+
+describe('toEntryListItems', () => {
+ it('남에게는 비공개·밴·일부 공개 회차를 빼고 최신순을 유지한다', () => {
+ const items = toEntryListItems(rows, access(), 'someone');
+
+ expect(items.map((item) => item.id)).toEqual(['e1']);
+ expect(items.every((item) => !item.isPrivate)).toBe(true);
+ });
+
+ it('일부 공개 프로젝트를 주소로 연 사람에게도 공개 회차는 목록에 나온다', () => {
+ const items = toEntryListItems(
+ rows,
+ access({ projectVisibility: 'unlisted' }),
+ null,
+ );
+
+ expect(items.map((item) => item.id)).toEqual(['e1']);
+ });
+
+ it('지금 연 일부 공개 회차는 keepId 로 남겨 이전/다음 기준으로 쓴다', () => {
+ const items = toEntryListItems(rows, access(), null, 'e2');
+
+ expect(items.map((item) => item.id)).toEqual(['e2', 'e1']);
+ // 볼 수 없는 회차는 keepId 여도 남기지 않음
+ expect(
+ toEntryListItems(rows, access(), null, 'e4').map((item) => item.id),
+ ).toEqual(['e1']);
+ });
+
+ it('작성자에게는 비공개·일부 공개 회차가 표시와 함께 남는다 (밴은 작성자에게도 숨김)', () => {
+ const items = toEntryListItems(rows, access(), OWNER);
+
+ expect(
+ items.map((item) => [item.id, item.isPrivate, item.isUnlisted]),
+ ).toEqual([
+ ['e4', true, false],
+ ['e2', false, true],
+ ['e1', false, false],
+ ]);
+ });
+
+ it('프로젝트가 비공개면 작성자에게는 모든 회차가 비공개 표시', () => {
+ const items = toEntryListItems(
+ rows,
+ access({ projectVisibility: 'private' }),
+ OWNER,
+ );
+
+ expect(items.every((item) => item.isPrivate)).toBe(true);
+ expect(
+ toEntryListItems(rows, access({ projectVisibility: 'private' }), null),
+ ).toEqual([]);
+ });
+
+ it('꺼짐·밴된 프로젝트는 작성자에게도 빈 목록', () => {
+ expect(toEntryListItems(rows, access({ enabled: false }), OWNER)).toEqual(
+ [],
+ );
+ expect(
+ toEntryListItems(rows, access({ bannedAt: new Date() }), OWNER),
+ ).toEqual([]);
+ });
+
+ it('행의 공개 범위·밴 칸은 화면 항목에 남기지 않는다', () => {
+ const [item] = toEntryListItems([row('e1', 1)], access(), null);
+
+ expect(item).toEqual({
+ id: 'e1',
+ slug: 'slug-e1',
+ title: 'title-e1',
+ excerpt: '',
+ publishedAt: new Date(Date.UTC(2026, 10, 1)),
+ thumbnailUrl: null,
+ isPrivate: false,
+ isUnlisted: false,
+ });
+ });
+});
+
+describe('pickAdjacentEntries', () => {
+ it('이전(더 오래된)·다음(더 최근) 회차는 목록에 오르는 회차 사이에서 고른다 (비공개·밴·일부 공개는 건너뜀)', () => {
+ const items = toEntryListItems(
+ [row('e5', 5), ...rows, row('e0', 0)],
+ access(),
+ 'someone',
+ );
+
+ // 남에게는 e4(비공개)·e3(밴)·e2(일부 공개)가 없으므로 e1 의 다음은 e5
+ expect(pickAdjacentEntries(items, 'e1')).toEqual({
+ previous: expect.objectContaining({ id: 'e0' }),
+ next: expect.objectContaining({ id: 'e5' }),
+ });
+ });
+
+ it('일부 공개 회차를 직접 열면 그 회차 기준으로 앞뒤 공개 회차를 고른다', () => {
+ const items = toEntryListItems(
+ [row('e5', 5), ...rows, row('e0', 0)],
+ access(),
+ null,
+ 'e2',
+ );
+
+ expect(pickAdjacentEntries(items, 'e2')).toEqual({
+ previous: expect.objectContaining({ id: 'e1' }),
+ next: expect.objectContaining({ id: 'e5' }),
+ });
+ // 공개 회차의 이전/다음에는 일부 공개 회차가 끼지 않음
+ expect(
+ pickAdjacentEntries(toEntryListItems(rows, access(), null, 'e1'), 'e1'),
+ ).toEqual({ previous: null, next: null });
+ });
+
+ it('작성자에게는 비공개·일부 공개 회차도 이전/다음에 들어간다', () => {
+ const items = toEntryListItems(rows, access(), OWNER);
+
+ expect(pickAdjacentEntries(items, 'e2').next?.id).toBe('e4');
+ expect(pickAdjacentEntries(items, 'e1').next?.id).toBe('e2');
+ });
+
+ it('목록에 없는 회차면 둘 다 null', () => {
+ const items = toEntryListItems(rows, access(), null);
+
+ expect(pickAdjacentEntries(items, 'e3')).toEqual({
+ previous: null,
+ next: null,
+ });
+ });
+});
+
+describe('summarizeListedProjects', () => {
+ const at = (day: number) => new Date(Date.UTC(2026, 10, day));
+
+ it('목록에 오를 회차만 세고, 최근 회차 게시순으로 정렬한다', () => {
+ const summaries = summarizeListedProjects([
+ { projectId: 'a', access: access(), entry: row('a1', 1) },
+ { projectId: 'a', access: access(), entry: row('a2', 5) },
+ // 일부 공개 회차는 목록 기준이 아님 (최근이어도 정렬에 쓰지 않음)
+ {
+ projectId: 'a',
+ access: access(),
+ entry: row('a3', 9, { visibility: 'unlisted' }),
+ },
+ { projectId: 'b', access: access(), entry: row('b1', 7) },
+ // 공개 회차가 없는 프로젝트는 빠짐
+ {
+ projectId: 'c',
+ access: access(),
+ entry: row('c1', 8, { visibility: 'private' }),
+ },
+ // 프로젝트가 공개가 아니면 빠짐
+ {
+ projectId: 'd',
+ access: access({ projectVisibility: 'unlisted' }),
+ entry: row('d1', 8),
+ },
+ ]);
+
+ expect(summaries).toEqual([
+ { projectId: 'b', entryCount: 1, latestPublishedAt: at(7) },
+ { projectId: 'a', entryCount: 2, latestPublishedAt: at(5) },
+ ]);
+ });
+});
+
+describe('isLinkablePairedPost', () => {
+ const paired = {
+ kind: 'post' as const,
+ visibility: 'public' as const,
+ bannedAt: null,
+ };
+
+ it('게시된 일반 글이 공개·일부 공개이고 밴이 아니면 링크', () => {
+ expect(isLinkablePairedPost(paired)).toBe(true);
+ expect(isLinkablePairedPost({ ...paired, visibility: 'unlisted' })).toBe(
+ true,
+ );
+ });
+
+ it('없거나, 비공개거나, 밴이거나, 회차면 링크하지 않음', () => {
+ expect(isLinkablePairedPost(null)).toBe(false);
+ expect(isLinkablePairedPost({ ...paired, visibility: 'private' })).toBe(
+ false,
+ );
+ expect(isLinkablePairedPost({ ...paired, bannedAt: new Date() })).toBe(
+ false,
+ );
+ expect(isLinkablePairedPost({ ...paired, kind: 'comlog' })).toBe(false);
+ });
+});
diff --git a/lib/comlog/entries.ts b/lib/comlog/entries.ts
new file mode 100644
index 0000000..3b7703f
--- /dev/null
+++ b/lib/comlog/entries.ts
@@ -0,0 +1,160 @@
+// comlog 공개 화면의 행→화면 변환 (DB 를 import 하지 않는 순수 함수, 공개 판단은 모두 rules 의 함수로)
+
+import {
+ canViewEntry,
+ effectiveVisibility,
+ isListedEntry,
+ type ComlogAccess,
+ type ComlogVisibility,
+} from '@/lib/comlog/rules';
+import type { DraftKind } from '@/lib/studio/options';
+
+// 프로젝트 페이지·이전/다음 계산에 쓰는 회차 행 (본문 없이 가벼운 칸만)
+export interface ComlogEntryRow {
+ id: string;
+ slug: string;
+ title: string;
+ excerpt: string;
+ visibility: ComlogVisibility;
+ bannedAt: Date | null;
+ publishedAt: Date;
+ // 본문 첫 이미지 주소 (없으면 null)
+ thumbnailUrl: string | null;
+}
+
+// 화면에 그리는 회차 항목 (공개 범위·밴 칸은 남기지 않음)
+export interface ComlogEntryListItem {
+ id: string;
+ slug: string;
+ title: string;
+ excerpt: string;
+ publishedAt: Date;
+ thumbnailUrl: string | null;
+ // 실효 비공개 (작성자에게만 보이므로 작성자 화면에서만 true 가 나옴)
+ isPrivate: boolean;
+ // 회차 자체가 일부 공개 (작성자 화면의 표시용, 남에게는 keepId 로 남긴 회차에서만 true)
+ isUnlisted: boolean;
+}
+
+/**
+ * 프로젝트 회차 목록·이전/다음에 오르는 회차인지
+ * - 볼 수 있어야 하고(canViewEntry), 작성자가 아니면 회차 자체가 일부 공개인 것은 주소로만 열림 (목록에서 뺌)
+ * - 회차가 공개면 프로젝트가 일부 공개여도(주소로 연 프로젝트 페이지) 목록에 오름
+ * - keepId: 지금 연 회차 (일부 공개여도 이전/다음 계산 기준으로 남김)
+ */
+const isOnProjectList = (
+ row: ComlogEntryRow,
+ access: ComlogAccess,
+ viewerId: string | null,
+ keepId?: string,
+): boolean =>
+ canViewEntry(access, row, viewerId) &&
+ (viewerId === access.ownerId ||
+ row.visibility !== 'unlisted' ||
+ row.id === keepId);
+
+/**
+ * 프로젝트 회차 목록에 오르는 회차만 화면 항목으로 (들어온 순서 = 최신순 유지)
+ * - 비공개·일부 공개 회차는 작성자에게만 남고 각각 표시를 붙임
+ * - 밴된 회차, 꺼짐·밴된 프로젝트의 회차는 작성자에게도 빠짐
+ */
+export const toEntryListItems = (
+ rows: ComlogEntryRow[],
+ access: ComlogAccess,
+ viewerId: string | null,
+ keepId?: string,
+): ComlogEntryListItem[] =>
+ rows
+ .filter((row) => isOnProjectList(row, access, viewerId, keepId))
+ .map((row) => ({
+ id: row.id,
+ slug: row.slug,
+ title: row.title,
+ excerpt: row.excerpt,
+ publishedAt: row.publishedAt,
+ thumbnailUrl: row.thumbnailUrl,
+ isPrivate:
+ effectiveVisibility(access.projectVisibility, row.visibility) ===
+ 'private',
+ isUnlisted: row.visibility === 'unlisted',
+ }));
+
+/**
+ * 회차 상세의 이전(더 오래된)·다음(더 최근) 회차
+ * - items 는 toEntryListItems(…, 지금 연 회차 id) 결과(최신순)라 목록에 오르지 않는 회차는 이미 빠져 있음
+ */
+export const pickAdjacentEntries = (
+ items: T[],
+ currentId: string,
+): { previous: T | null; next: T | null } => {
+ const index = items.findIndex((item) => item.id === currentId);
+
+ if (index === -1) {
+ return { previous: null, next: null };
+ }
+
+ return {
+ previous: items[index + 1] ?? null,
+ next: items[index - 1] ?? null,
+ };
+};
+
+export interface ListedProjectRow {
+ projectId: string;
+ access: ComlogAccess;
+ entry: Pick;
+}
+
+export interface ListedProjectSummary {
+ projectId: string;
+ // 목록에 오를(실효 공개) 회차 수
+ entryCount: number;
+ // 목록에 오를 회차 중 가장 최근 게시 시각 (목록 정렬 기준, "최근 업데이트")
+ latestPublishedAt: Date;
+}
+
+/**
+ * /comlog 목록에 오를 프로젝트: 목록에 오를 회차가 하나 이상인 것만, 최근 회차 게시순
+ * - 같은 시각이면 프로젝트 ID 역순이라 쪽 사이에 빠지거나 겹치지 않음
+ */
+export const summarizeListedProjects = (
+ rows: ListedProjectRow[],
+): ListedProjectSummary[] => {
+ const byProject = new Map();
+
+ for (const { projectId, access, entry } of rows) {
+ if (!isListedEntry(access, entry)) {
+ continue;
+ }
+
+ const current = byProject.get(projectId);
+
+ byProject.set(projectId, {
+ projectId,
+ entryCount: (current?.entryCount ?? 0) + 1,
+ latestPublishedAt:
+ current && current.latestPublishedAt > entry.publishedAt
+ ? current.latestPublishedAt
+ : entry.publishedAt,
+ });
+ }
+
+ return [...byProject.values()].sort(
+ (a, b) =>
+ b.latestPublishedAt.getTime() - a.latestPublishedAt.getTime() ||
+ b.projectId.localeCompare(a.projectId),
+ );
+};
+
+interface PairedPostAccess {
+ kind: DraftKind;
+ visibility: ComlogVisibility;
+ bannedAt: Date | null;
+}
+
+/** 짝 블로그 글 링크: 게시된 일반 글이 공개·일부 공개이고 밴이 아닐 때만 */
+export const isLinkablePairedPost = (post: PairedPostAccess | null): boolean =>
+ post !== null &&
+ post.kind === 'post' &&
+ post.bannedAt === null &&
+ post.visibility !== 'private';
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/metadata.test.ts b/lib/comlog/metadata.test.ts
new file mode 100644
index 0000000..152c3d8
--- /dev/null
+++ b/lib/comlog/metadata.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildComlogEntryMetadata,
+ buildComlogProjectMetadata,
+ toProjectDescription,
+} from '@/lib/comlog/metadata';
+import type {
+ ComlogEntryPage,
+ ComlogProjectPage,
+ ComlogProjectView,
+} from '@/lib/comlog/queries';
+
+const ORIGIN = 'https://comdraft.dev';
+const PROJECT_ID = '0f8fad5b-d9cb-469f-a165-70867728950e';
+const author = { name: '작성자', image: null, profileUrl: null };
+
+const project: ComlogProjectView = {
+ id: PROJECT_ID,
+ slug: 'app',
+ name: 'App',
+ intro: '첫 줄\n\n 둘째 줄',
+ status: 'in_progress',
+ techStack: ['nextjs'],
+ coverUrl: null,
+ demoUrl: null,
+ githubUrl: null,
+ visibility: 'public',
+ updatedAt: new Date(0),
+ author,
+};
+
+const projectPage = (isIndexable: boolean): ComlogProjectPage => ({
+ project,
+ entries: [],
+ isOwner: false,
+ isIndexable,
+});
+
+const entryPage = (isIndexable: boolean): ComlogEntryPage => ({
+ project,
+ entry: {
+ id: 'a1B2c3D4e5',
+ slug: 'log',
+ title: '회차',
+ excerpt: '요약',
+ content: { type: 'doc' },
+ locale: 'en',
+ tags: [],
+ publishedAt: new Date(0),
+ updatedAt: new Date(0),
+ author,
+ isPrivate: false,
+ },
+ previous: null,
+ next: null,
+ pairedPost: null,
+ isIndexable,
+});
+
+describe('toProjectDescription', () => {
+ it('줄바꿈·연속 공백을 하나로 모으고 160자에서 자른다', () => {
+ expect(toProjectDescription('첫 줄\n\n 둘째 줄')).toBe('첫 줄 둘째 줄');
+ expect(Array.from(toProjectDescription('가'.repeat(200)))).toHaveLength(
+ 160,
+ );
+ });
+});
+
+describe('buildComlogProjectMetadata', () => {
+ it('공개 프로젝트는 언어별 대표 주소로 검색에 노출', () => {
+ const metadata = buildComlogProjectMetadata(
+ projectPage(true),
+ ORIGIN,
+ 'ko',
+ '기본 설명',
+ );
+
+ expect(metadata.alternates?.canonical).toBe(
+ `${ORIGIN}/ko/comlog/app-${PROJECT_ID}`,
+ );
+ expect(metadata.description).toBe('첫 줄 둘째 줄');
+ expect(metadata.robots).toBeUndefined();
+ });
+
+ it('검색 노출 대상이 아니면 noindex, 소개가 비면 기본 설명', () => {
+ const metadata = buildComlogProjectMetadata(
+ { ...projectPage(false), project: { ...project, intro: ' ' } },
+ ORIGIN,
+ 'ko',
+ '기본 설명',
+ );
+
+ expect(metadata.robots).toEqual({ index: false });
+ expect(metadata.description).toBe('기본 설명');
+ });
+});
+
+describe('buildComlogEntryMetadata', () => {
+ it('대표 주소는 게시 언어의 회차 주소', () => {
+ const metadata = buildComlogEntryMetadata(entryPage(true), ORIGIN);
+
+ expect(metadata.alternates?.canonical).toBe(
+ `${ORIGIN}/en/comlog/app-${PROJECT_ID}/log-a1B2c3D4e5`,
+ );
+ expect(metadata.robots).toBeUndefined();
+ });
+
+ it('일부 공개·비공개 회차는 noindex', () => {
+ expect(buildComlogEntryMetadata(entryPage(false), ORIGIN).robots).toEqual({
+ index: false,
+ });
+ });
+});
diff --git a/lib/comlog/metadata.ts b/lib/comlog/metadata.ts
new file mode 100644
index 0000000..c341119
--- /dev/null
+++ b/lib/comlog/metadata.ts
@@ -0,0 +1,94 @@
+import type { Metadata } from 'next';
+import {
+ getEncodedComlogEntryPath,
+ getEncodedComlogProjectPath,
+} from '@/lib/comlog/paths';
+import type { ComlogEntryPage, ComlogProjectPage } from '@/lib/comlog/queries';
+import { localizePath, type Locale } from '@/lib/i18n/config';
+import { buildWebsiteOpenGraph } from '@/lib/seo/open-graph';
+import { OG_LOCALES, SITE_NAME } from '@/lib/seo/site';
+import { buildLocalizedAlternates } from '@/lib/seo/urls';
+
+// 검색 결과 설명으로 쓸 소개 앞부분 길이
+const DESCRIPTION_MAX = 160;
+
+// 검색에 노출하지 않는 화면 (일부 공개·작성자만 보는 비공개)
+const NOINDEX = { robots: { index: false } } as const;
+
+/** 소개 본문을 한 줄 설명으로 (줄바꿈·연속 공백을 하나로, 앞부분만) */
+export const toProjectDescription = (intro: string): string =>
+ Array.from(intro.replace(/\s+/g, ' ').trim())
+ .slice(0, DESCRIPTION_MAX)
+ .join('');
+
+/**
+ * 프로젝트 페이지 메타데이터
+ * - 소개에는 게시 언어가 없으므로 언어별 대표 주소와 hreflang (목록·고정 페이지와 같음)
+ * - 소개가 비어 있으면 fallbackDescription
+ * - 검색 노출 대상이 아니면(일부 공개·비공개) noindex
+ */
+export const buildComlogProjectMetadata = (
+ { project, isIndexable }: ComlogProjectPage,
+ origin: string,
+ locale: Locale,
+ fallbackDescription: string,
+): Metadata => {
+ const description =
+ toProjectDescription(project.intro) || fallbackDescription;
+ const alternates = buildLocalizedAlternates(
+ origin,
+ getEncodedComlogProjectPath(project),
+ locale,
+ );
+
+ return {
+ title: project.name,
+ description,
+ ...(project.techStack.length > 0 ? { keywords: project.techStack } : {}),
+ alternates,
+ openGraph: buildWebsiteOpenGraph({
+ locale,
+ title: project.name,
+ description,
+ url: alternates.canonical,
+ }),
+ twitter: { card: 'summary_large_image', title: project.name, description },
+ ...(isIndexable ? {} : NOINDEX),
+ };
+};
+
+/**
+ * 회차 상세 메타데이터 (게시글 상세와 같은 모양, 대표 주소는 게시할 때의 언어 기준)
+ * - 검색 노출 대상이 아니면(실효 일부 공개·비공개) noindex
+ */
+export const buildComlogEntryMetadata = (
+ { project, entry, isIndexable }: ComlogEntryPage,
+ origin: string,
+): Metadata => {
+ const url = `${origin}${localizePath(entry.locale, getEncodedComlogEntryPath(project, entry))}`;
+
+ return {
+ title: entry.title,
+ description: entry.excerpt,
+ ...(entry.tags.length > 0 ? { keywords: entry.tags } : {}),
+ alternates: { canonical: url },
+ openGraph: {
+ type: 'article',
+ siteName: SITE_NAME,
+ locale: OG_LOCALES[entry.locale],
+ title: entry.title,
+ description: entry.excerpt,
+ url,
+ publishedTime: entry.publishedAt.toISOString(),
+ modifiedTime: entry.updatedAt.toISOString(),
+ authors: [entry.author.name],
+ tags: entry.tags,
+ },
+ twitter: {
+ card: 'summary_large_image',
+ title: entry.title,
+ description: entry.excerpt,
+ },
+ ...(isIndexable ? {} : NOINDEX),
+ };
+};
diff --git a/lib/comlog/patch.test.ts b/lib/comlog/patch.test.ts
new file mode 100644
index 0000000..b82bd8e
--- /dev/null
+++ b/lib/comlog/patch.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+import { buildProjectUpdate, isProjectPatch } 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,
+ });
+ });
+});
+
+describe('isProjectPatch', () => {
+ it('객체만 수정 입력으로 받음', () => {
+ expect(isProjectPatch({})).toBe(true);
+ expect(isProjectPatch({ name: 'a' })).toBe(true);
+ });
+
+ it('null·배열·원시값은 거부 (서버 액션 인자를 신뢰하지 않음)', () => {
+ for (const value of [null, undefined, [], 'name', 1, true]) {
+ expect(isProjectPatch(value)).toBe(false);
+ }
+ });
+
+ it('buildProjectUpdate 도 객체가 아니면 던지지 않고 null', () => {
+ expect(buildProjectUpdate(current, null as never)).toBeNull();
+ expect(buildProjectUpdate(current, undefined as never)).toBeNull();
+ });
+});
diff --git a/lib/comlog/patch.ts b/lib/comlog/patch.ts
new file mode 100644
index 0000000..d9b3550
--- /dev/null
+++ b/lib/comlog/patch.ts
@@ -0,0 +1,199 @@
+import {
+ COMLOG_INTRO_MAX_LENGTH,
+ COMLOG_MAX_TECH,
+ COMLOG_NAME_MAX_LENGTH,
+ 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 에서 따로 함
+ */
+
+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);
+
+/** 서버 액션 인자는 아무 값이나 올 수 있으므로 객체(배열 제외)만 수정 입력으로 받음 */
+export const isProjectPatch = (value: unknown): value is ComlogProjectPatch =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/** 올바르지 않은 값이 하나라도 있으면 null (부분 저장 없음) */
+export function buildProjectUpdate(
+ current: CurrentProject,
+ patch: ComlogProjectPatch,
+): ComlogProjectUpdate | null {
+ if (!isProjectPatch(patch)) return 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/paths.test.ts b/lib/comlog/paths.test.ts
new file mode 100644
index 0000000..02f83a6
--- /dev/null
+++ b/lib/comlog/paths.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getComlogEntryPath,
+ getComlogProjectPath,
+ getEncodedComlogEntryPath,
+ getEncodedComlogProjectPath,
+ parseComlogEntryParam,
+ parseComlogEntrySegment,
+ parseComlogProjectParam,
+ parseComlogProjectPath,
+} from '@/lib/comlog/paths';
+
+const PROJECT_ID = '0f8fad5b-d9cb-469f-a165-70867728950e';
+const POST_ID = 'a1B2c3D4e5';
+
+describe('getComlogProjectPath', () => {
+ it('slug 가 있으면 slug-id, 없으면 id 만', () => {
+ expect(getComlogProjectPath({ id: PROJECT_ID, slug: 'comdraft' })).toBe(
+ `/comlog/comdraft-${PROJECT_ID}`,
+ );
+ expect(getComlogProjectPath({ id: PROJECT_ID, slug: '' })).toBe(
+ `/comlog/${PROJECT_ID}`,
+ );
+ });
+
+ it('인코딩 주소는 slug 를 퍼센트 인코딩', () => {
+ expect(getEncodedComlogProjectPath({ id: PROJECT_ID, slug: '한글' })).toBe(
+ `/comlog/${encodeURIComponent(`한글-${PROJECT_ID}`)}`,
+ );
+ });
+});
+
+describe('getComlogEntryPath', () => {
+ it('프로젝트 주소 뒤에 게시글 id-slug 조각을 붙인다', () => {
+ expect(
+ getComlogEntryPath(
+ { id: PROJECT_ID, slug: 'comdraft' },
+ { id: POST_ID, slug: 'first-log' },
+ ),
+ ).toBe(`/comlog/comdraft-${PROJECT_ID}/first-log-${POST_ID}`);
+ expect(
+ getComlogEntryPath(
+ { id: PROJECT_ID, slug: '' },
+ { id: POST_ID, slug: '' },
+ ),
+ ).toBe(`/comlog/${PROJECT_ID}/${POST_ID}`);
+ });
+
+ it('인코딩 주소는 두 조각을 각각 퍼센트 인코딩', () => {
+ expect(
+ getEncodedComlogEntryPath(
+ { id: PROJECT_ID, slug: '프로젝트' },
+ { id: POST_ID, slug: '회차' },
+ ),
+ ).toBe(
+ `/comlog/${encodeURIComponent(`프로젝트-${PROJECT_ID}`)}/${encodeURIComponent(`회차-${POST_ID}`)}`,
+ );
+ });
+});
+
+describe('parseComlogProjectPath', () => {
+ it('만든 주소 조각을 되돌린다 (slug 안의 - 와 UUID 의 - 를 구분)', () => {
+ for (const project of [
+ { id: PROJECT_ID, slug: 'my-cool-app' },
+ { id: PROJECT_ID, slug: '한글-프로젝트' },
+ { id: PROJECT_ID, slug: '' },
+ ]) {
+ const segment = getComlogProjectPath(project).slice('/comlog/'.length);
+
+ expect(parseComlogProjectPath(segment)).toEqual(project);
+ }
+ });
+
+ it('UUID 로 끝나지 않거나 구분자가 없으면 null', () => {
+ expect(parseComlogProjectPath('')).toBeNull();
+ expect(parseComlogProjectPath('comdraft')).toBeNull();
+ expect(parseComlogProjectPath(`comdraft${PROJECT_ID}`)).toBeNull();
+ expect(parseComlogProjectPath(`comdraft-${PROJECT_ID}x`)).toBeNull();
+ expect(
+ parseComlogProjectPath(`comdraft-${PROJECT_ID.toUpperCase()}`),
+ ).toBeNull();
+ expect(parseComlogProjectPath(`-${PROJECT_ID}`)).toBeNull();
+ });
+});
+
+describe('parseComlogEntrySegment', () => {
+ it('게시글 주소 조각 규칙을 그대로 따른다', () => {
+ expect(parseComlogEntrySegment(`first-log-${POST_ID}`)).toEqual({
+ id: POST_ID,
+ slug: 'first-log',
+ });
+ expect(parseComlogEntrySegment(POST_ID)).toEqual({ id: POST_ID, slug: '' });
+ expect(parseComlogEntrySegment('first-log-short')).toBeNull();
+ });
+});
+
+describe('parseComlogProjectParam / parseComlogEntryParam', () => {
+ it('인코딩된 라우트 조각을 디코드해 파싱', () => {
+ expect(
+ parseComlogProjectParam(encodeURIComponent(`한글-${PROJECT_ID}`)),
+ ).toEqual({ id: PROJECT_ID, slug: '한글' });
+ expect(
+ parseComlogEntryParam(encodeURIComponent(`회차-${POST_ID}`)),
+ ).toEqual({ id: POST_ID, slug: '회차' });
+ });
+
+ it('잘못된 퍼센트 인코딩이면 null', () => {
+ expect(parseComlogProjectParam(`%E0%A4%A-${PROJECT_ID}`)).toBeNull();
+ expect(parseComlogEntryParam(`%E0%A4%A-${POST_ID}`)).toBeNull();
+ });
+});
diff --git a/lib/comlog/paths.ts b/lib/comlog/paths.ts
new file mode 100644
index 0000000..140c9a9
--- /dev/null
+++ b/lib/comlog/paths.ts
@@ -0,0 +1,87 @@
+// comlog 공개 주소(`/comlog/{slug}-{projectId}/{slug}-{postId}`) 생성과 파싱.
+// 로케일 접두사는 붙이지 않는다(링크 컴포넌트가 붙임). 스튜디오(클라이언트)도 쓰므로 server-only 를 붙이지 않는다.
+
+import { isUuid } from '@/lib/images/rules';
+import { getPostPath, parsePostPath } from '@/lib/posts/post-path';
+
+export const COMLOG_PATH = '/comlog';
+
+const SEPARATOR = '-';
+
+// 프로젝트 id 는 UUID(36자)라 그 안에도 `-` 가 있음: 마지막 `-` 가 아니라 끝 36자로 나눈다
+const UUID_LENGTH = 36;
+
+interface PathTarget {
+ id: string;
+ slug: string;
+}
+
+const joinSegment = ({ id, slug }: PathTarget) =>
+ slug ? `${slug}${SEPARATOR}${id}` : id;
+
+// 게시글 주소 조각 규칙(`slug-id`)은 게시글 주소에서 그대로 가져옴
+const entrySegment = (entry: PathTarget) =>
+ getPostPath(entry).slice('/posts/'.length);
+
+/** 프로젝트 페이지의 로케일 없는 주소. slug 가 비면 ID 만 쓴다. */
+export const getComlogProjectPath = (project: PathTarget): string =>
+ `${COMLOG_PATH}/${joinSegment(project)}`;
+
+/** 회차 상세의 로케일 없는 주소 (프로젝트 주소 뒤에 게시글 주소 조각) */
+export const getComlogEntryPath = (
+ project: PathTarget,
+ entry: PathTarget,
+): string => `${getComlogProjectPath(project)}/${entrySegment(entry)}`;
+
+/** 헤더나 절대 주소에 쓸 수 있도록 slug 를 퍼센트 인코딩한 프로젝트 주소 (리다이렉트, 대표 주소용) */
+export const getEncodedComlogProjectPath = (project: PathTarget): string =>
+ `${COMLOG_PATH}/${encodeURIComponent(joinSegment(project))}`;
+
+/** 퍼센트 인코딩한 회차 주소 (리다이렉트, 대표 주소, 사이트맵용) */
+export const getEncodedComlogEntryPath = (
+ project: PathTarget,
+ entry: PathTarget,
+): string =>
+ `${getEncodedComlogProjectPath(project)}/${encodeURIComponent(entrySegment(entry))}`;
+
+/**
+ * URL 디코드된 프로젝트 주소 조각을 slug 와 ID 로 나눈다.
+ * 끝 36자가 UUID 가 아니거나, 앞에 slug 가 있는데 `-` 로 이어지지 않으면 null.
+ */
+export const parseComlogProjectPath = (segment: string): PathTarget | null => {
+ if (isUuid(segment)) {
+ return { id: segment, slug: '' };
+ }
+
+ const id = segment.slice(-UUID_LENGTH);
+ const head = segment.slice(0, -UUID_LENGTH);
+
+ if (!isUuid(id) || !head.endsWith(SEPARATOR)) {
+ return null;
+ }
+
+ const slug = head.slice(0, -SEPARATOR.length);
+
+ return slug ? { id, slug } : null;
+};
+
+/** URL 디코드된 회차 주소 조각 (게시글 주소 조각과 같은 규칙) */
+export const parseComlogEntrySegment = (segment: string): PathTarget | null =>
+ parsePostPath(segment);
+
+// 라우트 params 는 퍼센트 인코딩된 채로 오므로 디코드 후 파싱 (잘못된 인코딩이면 null)
+const decodeThen =
+ (parse: (segment: string) => PathTarget | null) =>
+ (raw: string): PathTarget | null => {
+ try {
+ return parse(decodeURIComponent(raw));
+ } catch {
+ return null;
+ }
+ };
+
+/** 라우트 params 의 프로젝트 조각 (인코딩된 그대로) */
+export const parseComlogProjectParam = decodeThen(parseComlogProjectPath);
+
+/** 라우트 params 의 회차 조각 (인코딩된 그대로) */
+export const parseComlogEntryParam = decodeThen(parseComlogEntrySegment);
diff --git a/lib/comlog/queries.ts b/lib/comlog/queries.ts
new file mode 100644
index 0000000..811581f
--- /dev/null
+++ b/lib/comlog/queries.ts
@@ -0,0 +1,607 @@
+import 'server-only';
+import { cache } from 'react';
+import { and, desc, eq, inArray, isNull, type SQL } from 'drizzle-orm';
+import type { JSONContent } from '@tiptap/core';
+import {
+ pickAdjacentEntries,
+ summarizeListedProjects,
+ toEntryListItems,
+ isLinkablePairedPost,
+ type ComlogEntryListItem,
+ type ComlogEntryRow,
+} from '@/lib/comlog/entries';
+import {
+ canViewEntry,
+ canViewProject,
+ effectiveVisibility,
+ isIndexable,
+ isIndexableProject,
+ isListedEntry,
+ showGithubLink,
+ type ComlogAccess,
+ type ComlogVisibility,
+} from '@/lib/comlog/rules';
+import { db } from '@/lib/db';
+import {
+ comlogProject,
+ draft,
+ githubRepository,
+ image,
+ post,
+ user,
+ type ComlogProjectStatus,
+} from '@/lib/db/schema';
+import type { Locale } from '@/lib/i18n/config';
+import { getImagePublicUrl, isUuid } from '@/lib/images/rules';
+import { resolvePostAuthor, type PostAuthor } from '@/lib/posts/author-display';
+import { firstImageSrc } from '@/lib/posts/queries';
+import type { SitemapComlog } from '@/lib/seo/sitemap';
+import { getSupabaseUrl } from '@/lib/supabase/server';
+
+/**
+ * comlog 공개 화면 조회 (/comlog 목록, 프로젝트 페이지, 회차 상세, 사이트맵, 조회 기록)
+ * - 볼 수 있는지·목록에 오르는지는 모두 lib/comlog/rules 의 함수로 판단 (SQL 조건은 조회량을 줄이는 사전 거르기만)
+ * - 회차 = kind 가 comlog 인 게시글, 프로젝트와는 초안의 (사용자, 저장소) 로 이어짐
+ */
+
+// /comlog 목록 한 쪽의 프로젝트 수
+export const COMLOG_PROJECT_PAGE_SIZE = 24;
+
+// 카드에 보여 줄 소개 앞부분 (나머지는 화면에서 줄 수로 자름)
+const CARD_INTRO_MAX = 200;
+
+// 회차 게시글과 프로젝트를 잇는 조인 조건 (같은 사용자·같은 저장소)
+const projectOfDraft = (): SQL =>
+ and(
+ eq(comlogProject.userId, draft.userId),
+ eq(comlogProject.repositoryId, draft.repositoryId),
+ ) as SQL;
+
+// 목록·사이트맵 사전 거르기: 켜져 있고 밴이 아닌 공개 프로젝트 (최종 판단은 rules 함수)
+const publicProjectCondition = () =>
+ and(
+ eq(comlogProject.enabled, true),
+ isNull(comlogProject.bannedAt),
+ eq(comlogProject.visibility, 'public'),
+ );
+
+const projectAccessColumns = {
+ enabled: comlogProject.enabled,
+ bannedAt: comlogProject.bannedAt,
+ ownerId: comlogProject.userId,
+ projectVisibility: comlogProject.visibility,
+};
+
+const toAccess = (row: ComlogAccess): ComlogAccess => ({
+ enabled: row.enabled,
+ bannedAt: row.bannedAt,
+ ownerId: row.ownerId,
+ projectVisibility: row.projectVisibility,
+});
+
+// 대표 이미지 주소 (없으면 null: 화면은 이름으로 만든 자동 이미지를 씀)
+const toCoverUrl = (path: string | null): string | null =>
+ path ? getImagePublicUrl(getSupabaseUrl(), path) : null;
+
+// 프로젝트 카드·페이지 공통 칸 (작성자는 프로젝트의 작성자 표시 설정을 따름)
+const projectCardColumns = {
+ id: comlogProject.id,
+ slug: comlogProject.slug,
+ name: comlogProject.name,
+ intro: comlogProject.intro,
+ status: comlogProject.status,
+ techStack: comlogProject.techStack,
+ coverPath: image.path,
+ authorName: user.name,
+ authorImage: user.image,
+ authorGithubLogin: user.githubLogin,
+ authorDisplay: comlogProject.authorDisplay,
+ authorNickname: comlogProject.authorNickname,
+ showAuthorProfile: comlogProject.showAuthorProfile,
+};
+
+interface ProjectAuthorRow {
+ authorName: string;
+ authorImage: string | null;
+ authorGithubLogin: string | null;
+ authorDisplay: (typeof comlogProject.$inferSelect)['authorDisplay'];
+ authorNickname: string | null;
+ showAuthorProfile: boolean;
+}
+
+const toAuthor = (row: ProjectAuthorRow): PostAuthor =>
+ resolvePostAuthor(
+ {
+ name: row.authorName,
+ image: row.authorImage,
+ githubLogin: row.authorGithubLogin,
+ },
+ {
+ mode: row.authorDisplay,
+ nickname: row.authorNickname,
+ showProfile: row.showAuthorProfile,
+ },
+ );
+
+export interface ComlogProjectCard {
+ id: string;
+ slug: string;
+ name: string;
+ // 소개 앞부분 (비어 있을 수 있음)
+ intro: string;
+ status: ComlogProjectStatus;
+ coverUrl: string | null;
+ author: PostAuthor;
+ // 목록에 오른(실효 공개) 회차 수
+ entryCount: number;
+ // 가장 최근 회차 게시 시각 (목록 정렬 기준)
+ latestPublishedAt: Date;
+}
+
+export interface ComlogProjectCardPage {
+ projects: ComlogProjectCard[];
+ // 전체 쪽 수 (목록에 오를 프로젝트가 없으면 0)
+ totalPages: number;
+}
+
+/**
+ * /comlog 목록 한 쪽: 켜짐·밴 아님·공개 프로젝트 중 목록에 오를 회차가 하나 이상인 것, 최근 회차 게시순
+ * - 정렬 기준(최근 회차 게시 시각)을 계산하려고 후보 회차를 모두 읽고 rules 함수로 거른 뒤 쪽을 자름
+ */
+export const listComlogProjects = async (
+ page: number,
+): Promise => {
+ const rows = await db
+ .select({
+ projectId: comlogProject.id,
+ ...projectAccessColumns,
+ visibility: post.visibility,
+ entryBannedAt: post.bannedAt,
+ publishedAt: post.publishedAt,
+ })
+ .from(post)
+ .innerJoin(draft, eq(post.draftId, draft.id))
+ .innerJoin(comlogProject, projectOfDraft())
+ .where(and(eq(post.kind, 'comlog'), publicProjectCondition()));
+
+ const summaries = summarizeListedProjects(
+ rows.map((row) => ({
+ projectId: row.projectId,
+ access: toAccess(row),
+ entry: {
+ visibility: row.visibility,
+ bannedAt: row.entryBannedAt,
+ publishedAt: row.publishedAt,
+ },
+ })),
+ );
+ const shown = summaries.slice(
+ (page - 1) * COMLOG_PROJECT_PAGE_SIZE,
+ page * COMLOG_PROJECT_PAGE_SIZE,
+ );
+ const totalPages = Math.ceil(summaries.length / COMLOG_PROJECT_PAGE_SIZE);
+
+ if (shown.length === 0) {
+ return { projects: [], totalPages };
+ }
+
+ const cards = await db
+ .select(projectCardColumns)
+ .from(comlogProject)
+ .innerJoin(user, eq(user.id, comlogProject.userId))
+ .leftJoin(image, eq(image.id, comlogProject.coverImageId))
+ .where(
+ inArray(
+ comlogProject.id,
+ shown.map((summary) => summary.projectId),
+ ),
+ );
+ const cardById = new Map(cards.map((card) => [card.id, card]));
+
+ return {
+ projects: shown.flatMap((summary) => {
+ const card = cardById.get(summary.projectId);
+
+ return card
+ ? [
+ {
+ id: card.id,
+ slug: card.slug,
+ name: card.name,
+ intro: card.intro.slice(0, CARD_INTRO_MAX),
+ status: card.status,
+ coverUrl: toCoverUrl(card.coverPath),
+ author: toAuthor(card),
+ entryCount: summary.entryCount,
+ latestPublishedAt: summary.latestPublishedAt,
+ },
+ ]
+ : [];
+ }),
+ totalPages,
+ };
+};
+
+export interface ComlogProjectView {
+ id: string;
+ slug: string;
+ name: string;
+ intro: string;
+ status: ComlogProjectStatus;
+ techStack: string[];
+ coverUrl: string | null;
+ demoUrl: string | null;
+ // 비공개 저장소이거나 표시를 끈 경우 null (저장소 full name 은 내보내지 않음)
+ githubUrl: string | null;
+ visibility: ComlogVisibility;
+ updatedAt: Date;
+ author: PostAuthor;
+}
+
+interface LoadedProject {
+ view: ComlogProjectView;
+ access: ComlogAccess;
+ repositoryId: string;
+}
+
+// 프로젝트 한 행 + 저장소 공개 여부 + 작성자 (판단 없이 읽기만, 한 요청에서 한 번)
+const loadProject = cache(
+ async (projectId: string): Promise => {
+ if (!isUuid(projectId)) return null;
+
+ const [row] = await db
+ .select({
+ ...projectCardColumns,
+ ...projectAccessColumns,
+ repositoryId: comlogProject.repositoryId,
+ demoUrl: comlogProject.demoUrl,
+ showGithubLink: comlogProject.showGithubLink,
+ updatedAt: comlogProject.updatedAt,
+ repoIsPrivate: githubRepository.isPrivate,
+ repoHtmlUrl: githubRepository.htmlUrl,
+ })
+ .from(comlogProject)
+ .innerJoin(
+ githubRepository,
+ eq(githubRepository.id, comlogProject.repositoryId),
+ )
+ .innerJoin(user, eq(user.id, comlogProject.userId))
+ .leftJoin(image, eq(image.id, comlogProject.coverImageId))
+ .where(eq(comlogProject.id, projectId))
+ .limit(1);
+
+ if (!row) return null;
+
+ return {
+ access: toAccess(row),
+ repositoryId: row.repositoryId,
+ view: {
+ id: row.id,
+ slug: row.slug,
+ name: row.name,
+ intro: row.intro,
+ status: row.status,
+ techStack: row.techStack,
+ coverUrl: toCoverUrl(row.coverPath),
+ demoUrl: row.demoUrl,
+ // 저장된 표시 설정만으로는 부족: 마지막으로 확인한 저장소 공개 여부까지 보고 정함
+ githubUrl: showGithubLink(row, { isPrivate: row.repoIsPrivate })
+ ? row.repoHtmlUrl
+ : null,
+ visibility: row.projectVisibility,
+ updatedAt: row.updatedAt,
+ author: toAuthor(row),
+ },
+ };
+ },
+);
+
+/** 보는 사람이 볼 수 있는 프로젝트의 소개 (회차 없이, 오픈그래프 이미지용, 볼 수 없으면 null) */
+export const getViewableComlogProject = async (
+ projectId: string,
+ viewerId: string | null,
+): Promise => {
+ const loaded = await loadProject(projectId);
+
+ return loaded && canViewProject(loaded.access, viewerId) ? loaded.view : null;
+};
+
+// 한 프로젝트의 회차 (본문 없이, 최신순)
+const listEntryRows = (
+ ownerId: string,
+ repositoryId: string,
+): Promise =>
+ db
+ .select({
+ id: post.id,
+ slug: post.slug,
+ title: post.title,
+ excerpt: post.excerpt,
+ visibility: post.visibility,
+ bannedAt: post.bannedAt,
+ publishedAt: post.publishedAt,
+ thumbnailUrl: firstImageSrc(),
+ })
+ .from(post)
+ .innerJoin(draft, eq(post.draftId, draft.id))
+ .where(
+ and(
+ eq(post.kind, 'comlog'),
+ eq(draft.userId, ownerId),
+ eq(draft.repositoryId, repositoryId),
+ ),
+ )
+ .orderBy(desc(post.publishedAt), desc(post.id));
+
+export interface ComlogProjectPage {
+ project: ComlogProjectView;
+ entries: ComlogEntryListItem[];
+ // 보는 사람이 작성자 (비공개 표시 안내용)
+ isOwner: boolean;
+ // 검색 노출 대상 (아니면 noindex)
+ isIndexable: boolean;
+}
+
+/**
+ * 프로젝트 페이지 (볼 수 없으면 null → 404)
+ * - 회차는 보는 사람이 볼 수 있는 것만 최신순, 작성자에게는 비공개 회차도 표시와 함께
+ */
+export const getComlogProjectPage = cache(
+ async (
+ projectId: string,
+ viewerId: string | null,
+ ): Promise => {
+ const loaded = await loadProject(projectId);
+
+ if (!loaded || !canViewProject(loaded.access, viewerId)) return null;
+
+ const rows = await listEntryRows(
+ loaded.access.ownerId,
+ loaded.repositoryId,
+ );
+
+ // 보는 사람과 무관하게 목록에 오를 회차 수로 색인 여부를 정함 (작성자에게도 같은 meta)
+ const listedCount = rows.filter((row) =>
+ isListedEntry(loaded.access, row),
+ ).length;
+
+ return {
+ project: loaded.view,
+ entries: toEntryListItems(rows, loaded.access, viewerId),
+ isOwner: viewerId === loaded.access.ownerId,
+ isIndexable: isIndexableProject(loaded.access, listedCount),
+ };
+ },
+);
+
+export interface ComlogEntryDetail {
+ id: string;
+ slug: string;
+ title: string;
+ excerpt: string;
+ content: JSONContent;
+ locale: Locale;
+ tags: string[];
+ publishedAt: Date;
+ updatedAt: Date;
+ // 회차를 게시할 때 고른 작성자 표시 (프로젝트 설정이 아님)
+ author: PostAuthor;
+ // 실효 비공개 (작성자에게만 보임)
+ isPrivate: boolean;
+}
+
+type EntryLink = Pick;
+
+export interface ComlogEntryPage {
+ project: ComlogProjectView;
+ entry: ComlogEntryDetail;
+ // 보는 사람이 볼 수 있는 회차 사이의 이전(더 오래된)·다음(더 최근)
+ previous: EntryLink | null;
+ next: EntryLink | null;
+ // 함께 만든 블로그 글 (게시되어 있고 공개·일부 공개이며 밴이 아닐 때만)
+ pairedPost: { id: string; slug: string } | null;
+ isIndexable: boolean;
+}
+
+// 짝 초안의 게시글 (게시 전이거나 지워졌으면 null)
+const findPairedPost = async (ownerId: string, pairedDraftId: string) => {
+ const [row] = await db
+ .select({
+ id: post.id,
+ slug: post.slug,
+ kind: post.kind,
+ visibility: post.visibility,
+ bannedAt: post.bannedAt,
+ })
+ .from(post)
+ .where(and(eq(post.draftId, pairedDraftId), eq(post.userId, ownerId)))
+ .limit(1);
+
+ return row && isLinkablePairedPost(row)
+ ? { id: row.id, slug: row.slug }
+ : null;
+};
+
+const toEntryLink = (item: ComlogEntryListItem | null): EntryLink | null =>
+ item && { id: item.id, slug: item.slug, title: item.title };
+
+/** 회차 상세 (볼 수 없거나 그 프로젝트의 회차가 아니면 null → 404) */
+export const getComlogEntryPage = cache(
+ async (
+ projectId: string,
+ postId: string,
+ viewerId: string | null,
+ ): Promise => {
+ const loaded = await loadProject(projectId);
+
+ if (!loaded) return null;
+
+ const { access, repositoryId, view } = loaded;
+ const [row] = await db
+ .select({
+ id: post.id,
+ slug: post.slug,
+ title: post.title,
+ excerpt: post.excerpt,
+ content: post.content,
+ locale: post.locale,
+ tags: post.tags,
+ visibility: post.visibility,
+ bannedAt: post.bannedAt,
+ publishedAt: post.publishedAt,
+ updatedAt: post.updatedAt,
+ authorName: user.name,
+ authorImage: user.image,
+ authorGithubLogin: user.githubLogin,
+ authorDisplay: post.authorDisplay,
+ authorNickname: post.authorNickname,
+ showAuthorProfile: post.showAuthorProfile,
+ pairedDraftId: draft.pairedDraftId,
+ })
+ .from(post)
+ .innerJoin(draft, eq(post.draftId, draft.id))
+ .innerJoin(user, eq(user.id, post.userId))
+ .where(
+ and(
+ eq(post.id, postId),
+ eq(post.kind, 'comlog'),
+ eq(draft.userId, access.ownerId),
+ eq(draft.repositoryId, repositoryId),
+ ),
+ )
+ .limit(1);
+
+ if (!row || !canViewEntry(access, row, viewerId)) return null;
+
+ const [rows, pairedPost] = await Promise.all([
+ listEntryRows(access.ownerId, repositoryId),
+ row.pairedDraftId
+ ? findPairedPost(access.ownerId, row.pairedDraftId)
+ : Promise.resolve(null),
+ ]);
+ const { previous, next } = pickAdjacentEntries(
+ // 지금 연 회차는 일부 공개여도 기준으로 남김 (앞뒤는 목록에 오르는 회차만)
+ toEntryListItems(rows, access, viewerId, row.id),
+ row.id,
+ );
+
+ return {
+ project: view,
+ entry: {
+ id: row.id,
+ slug: row.slug,
+ title: row.title,
+ excerpt: row.excerpt,
+ content: row.content as JSONContent,
+ locale: row.locale,
+ tags: row.tags,
+ publishedAt: row.publishedAt,
+ updatedAt: row.updatedAt,
+ author: toAuthor(row),
+ isPrivate:
+ effectiveVisibility(access.projectVisibility, row.visibility) ===
+ 'private',
+ },
+ previous: toEntryLink(previous),
+ next: toEntryLink(next),
+ pairedPost,
+ isIndexable: isIndexable(access, row),
+ };
+ },
+);
+
+/** 사이트맵: 검색 노출 대상 프로젝트 페이지와 목록에 오를 회차 (일부 공개·비공개·꺼짐·밴, 회차가 없는 프로젝트는 빠짐) */
+export const listComlogSitemapEntries = async (): Promise => {
+ const [projects, entries] = await Promise.all([
+ db
+ .select({
+ id: comlogProject.id,
+ slug: comlogProject.slug,
+ updatedAt: comlogProject.updatedAt,
+ ...projectAccessColumns,
+ })
+ .from(comlogProject)
+ .where(publicProjectCondition()),
+ db
+ .select({
+ projectId: comlogProject.id,
+ projectSlug: comlogProject.slug,
+ ...projectAccessColumns,
+ id: post.id,
+ slug: post.slug,
+ locale: post.locale,
+ visibility: post.visibility,
+ entryBannedAt: post.bannedAt,
+ updatedAt: post.updatedAt,
+ })
+ .from(post)
+ .innerJoin(draft, eq(post.draftId, draft.id))
+ .innerJoin(comlogProject, projectOfDraft())
+ .where(and(eq(post.kind, 'comlog'), publicProjectCondition()))
+ .orderBy(desc(post.publishedAt), desc(post.id)),
+ ]);
+
+ const listedEntries = entries.filter((row) =>
+ isListedEntry(toAccess(row), {
+ visibility: row.visibility,
+ bannedAt: row.entryBannedAt,
+ }),
+ );
+ // 프로젝트별 목록에 오를 회차 수 (회차가 없는 프로젝트는 사이트맵에서 뺌)
+ const listedCounts = new Map();
+
+ for (const row of listedEntries) {
+ listedCounts.set(row.projectId, (listedCounts.get(row.projectId) ?? 0) + 1);
+ }
+
+ return {
+ projects: projects
+ .filter((project) =>
+ isIndexableProject(
+ toAccess(project),
+ listedCounts.get(project.id) ?? 0,
+ ),
+ )
+ .map(({ id, slug, updatedAt }) => ({ id, slug, updatedAt })),
+ entries: listedEntries.map((row) => ({
+ project: { id: row.projectId, slug: row.projectSlug },
+ id: row.id,
+ slug: row.slug,
+ locale: row.locale,
+ updatedAt: row.updatedAt,
+ })),
+ };
+};
+
+/**
+ * 회차 조회 기록용 작성자 id (조회를 셀 회차가 아니면 null)
+ * - 비로그인 기준으로 볼 수 있는 회차만 셈: 비공개는 작성자만 보고, 작성자 조회는 원래 세지 않음
+ * - 꺼짐·밴된 프로젝트, 밴된 회차는 세지 않음
+ */
+export const getComlogEntryOwnerId = async (
+ postId: string,
+): Promise => {
+ const [row] = await db
+ .select({
+ ...projectAccessColumns,
+ visibility: post.visibility,
+ entryBannedAt: post.bannedAt,
+ })
+ .from(post)
+ .innerJoin(draft, eq(post.draftId, draft.id))
+ .innerJoin(comlogProject, projectOfDraft())
+ .where(and(eq(post.id, postId), eq(post.kind, 'comlog')))
+ .limit(1);
+
+ if (!row) return null;
+
+ const access = toAccess(row);
+
+ return canViewEntry(
+ access,
+ { visibility: row.visibility, bannedAt: row.entryBannedAt },
+ null,
+ )
+ ? access.ownerId
+ : null;
+};
diff --git a/lib/comlog/revalidate.ts b/lib/comlog/revalidate.ts
new file mode 100644
index 0000000..9b7dad0
--- /dev/null
+++ b/lib/comlog/revalidate.ts
@@ -0,0 +1,13 @@
+import 'server-only';
+import { revalidatePath } from 'next/cache';
+import { LOCALES, localizePath } from '@/lib/i18n/config';
+import { revalidateSitemap } from '@/lib/seo/revalidate-sitemap';
+
+/** comlog 공개 화면 캐시 비우기: /comlog 아래(목록·프로젝트·회차)를 모든 로케일에서 한 번에, 사이트맵과 함께 */
+export const revalidateComlogPages = () => {
+ for (const locale of LOCALES) {
+ revalidatePath(localizePath(locale, '/comlog'), 'layout');
+ }
+
+ revalidateSitemap();
+};
diff --git a/lib/comlog/rules.test.ts b/lib/comlog/rules.test.ts
new file mode 100644
index 0000000..883ed2c
--- /dev/null
+++ b/lib/comlog/rules.test.ts
@@ -0,0 +1,221 @@
+import { describe, expect, it } from 'vitest';
+import {
+ COMLOG_MAX_TECH,
+ canViewEntry,
+ canViewProject,
+ effectiveVisibility,
+ isIndexable,
+ isIndexableProject,
+ isListedEntry,
+ mergeTechStack,
+ parseDemoUrl,
+ removeTech,
+ shouldRecommendPreset,
+ 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);
+ });
+});
+
+describe('isIndexableProject', () => {
+ it('공개 프로젝트에 목록에 오를 회차가 하나 이상 있으면 색인', () => {
+ expect(isIndexableProject(access(), 1)).toBe(true);
+ expect(isIndexableProject(access(), 3)).toBe(true);
+ });
+
+ it('목록에 오를 회차가 없으면 공개 프로젝트여도 색인하지 않음 (켜자마자 저장소 정보가 노출되지 않게)', () => {
+ expect(isIndexableProject(access(), 0)).toBe(false);
+ });
+
+ it('일부 공개·꺼짐·밴 프로젝트는 회차가 있어도 색인하지 않음', () => {
+ expect(
+ isIndexableProject(access({ projectVisibility: 'unlisted' }), 2),
+ ).toBe(false);
+ expect(isIndexableProject(access({ enabled: false }), 2)).toBe(false);
+ expect(isIndexableProject(access({ bannedAt: new Date() }), 2)).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();
+ });
+});
+
+describe('shouldRecommendPreset', () => {
+ it('프리셋이 비었거나 100자 미만이면 권장', () => {
+ expect(shouldRecommendPreset('')).toBe(true);
+ expect(shouldRecommendPreset(' ')).toBe(true);
+ expect(shouldRecommendPreset('a'.repeat(99))).toBe(true);
+ });
+
+ it('100자 이상이면 권장하지 않음', () => {
+ expect(shouldRecommendPreset('a'.repeat(100))).toBe(false);
+ });
+});
diff --git a/lib/comlog/rules.ts b/lib/comlog/rules.ts
new file mode 100644
index 0000000..cfbc8cf
--- /dev/null
+++ b/lib/comlog/rules.ts
@@ -0,0 +1,184 @@
+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 const COMLOG_NAME_MAX_LENGTH = 60;
+export const COMLOG_INTRO_MAX_LENGTH = 2000;
+
+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 => isListedEntry(access, entry);
+
+/**
+ * 프로젝트 페이지의 검색 색인·사이트맵 대상 (/comlog 목록 규칙과 같음, 설계 §10)
+ * - 공개 프로젝트라도 목록에 오를 회차가 하나도 없으면 제외
+ * (켜자마자 기본 공개라, 아무것도 게시하기 전에 저장소 이름·소개·언어가 검색에 노출되지 않게)
+ */
+export const isIndexableProject = (
+ access: ComlogAccess,
+ listedEntryCount: number,
+): boolean =>
+ isLive(access) &&
+ access.projectVisibility === 'public' &&
+ listedEntryCount > 0;
+
+// 기술 스택 병합: 사용자가 뺀 것은 다시 넣지 않고, 기존 순서 뒤에 새 것을 붙임
+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;
+ }
+};
+
+// 프리셋(자동 초안 요청 문구)이 이 길이 미만이면 회차 품질 안내를 보임
+export const COMLOG_PRESET_RECOMMENDED_LENGTH = 100;
+
+export const shouldRecommendPreset = (prompt: string): boolean =>
+ prompt.trim().length < COMLOG_PRESET_RECOMMENDED_LENGTH;
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 });
+ }
+}
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/draft-job.ts b/lib/generation/draft-job.ts
index b4b6147..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 {
@@ -28,7 +30,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,11 +59,15 @@ export interface ParsedRequest {
export interface DraftJobRequest extends ParsedRequest {
source: DraftPromptSource;
triggerSha: string | null;
+ // 초안 종류 (새 초안이면 draft.kind 로 저장, 작업 행에도 남김)
+ draftKind: DraftKind;
+ // 이 작업이 자동 초안 경계를 먼저 가져갔는지 (실패 때 되돌릴 대상 표시)
+ boundaryClaimed: boolean;
}
// 초안 작업 만들기 결과
// - duplicate: 같은 트리거 SHA 로 이미 만듦
-// - overlap: 자동 초안 커밋 중 일부를 다른 자동 초안이 먼저 씀 (묶음을 다시 계산해야 함)
+// - overlap: 자동 초안 커밋 중 일부를 다른 작업이 먼저 씀 (묶음을 다시 계산해야 함)
export type CreateDraftJobResult =
| CreateJobResult<{
draftId: string;
@@ -70,92 +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 });
-
- 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,
- });
+ await pairNewDrafts(tx, planned);
return reserved;
});
@@ -175,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/draft-kind.test.ts b/lib/generation/draft-kind.test.ts
new file mode 100644
index 0000000..28fabb7
--- /dev/null
+++ b/lib/generation/draft-kind.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// vitest 는 Lingui 매크로를 변환하지 않으므로 라벨 정의만 통과시킴 (종류 목록이 options 에 있음)
+vi.mock('@lingui/core/macro', () => ({ msg: (id: unknown) => id }));
+
+import {
+ parseRequestedKind,
+ 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');
+ });
+});
+
+describe('parseRequestedKind', () => {
+ it('종류를 보내지 않은 예전 화면의 요청은 일반 글', () => {
+ expect(parseRequestedKind(undefined)).toBe('post');
+ });
+
+ it('알려진 종류는 그대로', () => {
+ expect(parseRequestedKind('post')).toBe('post');
+ expect(parseRequestedKind('comlog')).toBe('comlog');
+ });
+
+ it('알 수 없는 값은 null', () => {
+ expect(parseRequestedKind('note')).toBeNull();
+ expect(parseRequestedKind(null)).toBeNull();
+ expect(parseRequestedKind(1)).toBeNull();
+ });
+});
diff --git a/lib/generation/draft-kind.ts b/lib/generation/draft-kind.ts
new file mode 100644
index 0000000..3df6e68
--- /dev/null
+++ b/lib/generation/draft-kind.ts
@@ -0,0 +1,21 @@
+import { DRAFT_KINDS, type DraftKind } from '@/lib/studio/options';
+
+/**
+ * 요청에 적용할 초안 종류
+ * - 이미 있는 초안은 만들 때 정해진 종류가 이김 (클라이언트가 다른 종류를 보내도 바꿀 수 없음)
+ * - 새 초안(기존 종류 null)은 요청한 종류
+ */
+export const resolveRequestKind = (
+ existingDraftKind: DraftKind | null,
+ requestedKind: DraftKind,
+): DraftKind => existingDraftKind ?? requestedKind;
+
+/**
+ * 요청에 실린 초안 종류 확인 (서버 액션 인자는 신뢰하지 않음)
+ * - 종류를 보내지 않으면 일반 글: 배포 중 예전 화면이 보낸 요청도 그대로 받음
+ * - 알 수 없는 값은 null
+ */
+export const parseRequestedKind = (value: unknown): DraftKind | null =>
+ value === undefined
+ ? 'post'
+ : (DRAFT_KINDS.find((kind) => kind === value) ?? null);
diff --git a/lib/generation/jobs.test.ts b/lib/generation/jobs.test.ts
index 5f5b705..c0aa10b 100644
--- a/lib/generation/jobs.test.ts
+++ b/lib/generation/jobs.test.ts
@@ -17,8 +17,15 @@ builder.where = (condition: SQL) => {
};
builder.limit = async () => [];
vi.mock('@/lib/db', () => ({ db: builder }));
+// 실패한 회차의 밀린 커밋 반영은 backlog.test.ts 에서 다룸
+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', () => {
@@ -126,6 +133,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]);
@@ -178,12 +193,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(
@@ -194,3 +209,25 @@ describe('isTriggerDuplicateConflict', () => {
expect(jobs.isTriggerDuplicateConflict(null)).toBe(false);
});
});
+
+describe('applyPendingDraftJobs', () => {
+ it('밀린 커밋 반영이 실패해도 던지지 않고 보고만 한다', async () => {
+ const error = new Error('sync failed');
+ vi.mocked(syncFailedComlogBacklog).mockRejectedValueOnce(error);
+ // 반영할 완료 작업이 없도록 orderBy 가 빈 목록을 돌려줌
+ 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;
+ }
+ });
+});
diff --git a/lib/generation/jobs.ts b/lib/generation/jobs.ts
index 0b797dd..a259085 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';
@@ -46,6 +47,7 @@ import { parseImagePath, removeDisallowedImages } from '@/lib/images/rules';
import { normalizeTags } from '@/lib/posts/tags';
import { ensureBlankIds, replaceBlank } from '@/lib/studio/draft-blank';
import { extractDraftTitle, isDraftDocument } from '@/lib/studio/draft-content';
+import type { DraftKind } from '@/lib/studio/options';
import { getSupabaseUrl } from '@/lib/supabase/server';
import { reportError } from '@/lib/observability/report-error';
@@ -66,6 +68,8 @@ export interface GenerationJobView {
id: string;
// 작업 종류 (fill 은 편집기 전체가 아니라 blankId 의 빈칸만 막음)
kind: GenerationJobKind;
+ // 초안 종류 (일반 글 / comlog 회차)
+ draftKind: DraftKind;
// 빈칸 채우기 대상 빈칸 id (초안 작성 작업은 null)
blankId: string | null;
channel: string;
@@ -96,6 +100,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 +115,7 @@ const jobViewColumns = {
interface JobViewRow {
id: string;
kind: GenerationJobKind;
+ draftKind: DraftKind;
blankId: string | null;
channel: string;
status: GenerationStatus;
@@ -135,6 +141,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,
@@ -548,6 +555,14 @@ export const applyPendingDraftJobs = async (
for (const { id } of pending) {
await applyCompletedJob(id);
}
+
+ // Lambda 가 직접 failed 로 남긴 회차 작업의 커밋도 다음 조회 때 밀린 커밋으로 반영
+ // 부가 반영이라 실패해도 스튜디오 화면 로드를 막지 않음
+ try {
+ await syncFailedComlogBacklog(userId, repositoryId);
+ } catch (error) {
+ reportError(error, 'generation.sync-comlog-backlog', { repositoryId });
+ }
};
// 초안을 바꿀 수 없는 상태인지 (정리 후 진행 중인 초안 작성 작업이 남아 있으면 잠금, 빈칸 채우기는 잠그지 않음)
@@ -689,6 +704,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);
@@ -705,7 +722,7 @@ export const reserveGenerationSlot = async (
),
);
- return decideGenerationSlot({ recentJobs, activeJobs });
+ return decideGenerationSlot({ recentJobs, activeJobs, required });
};
// 유일 인덱스(constraint) 위반 오류인지 (오류 자신 또는 cause 가 23505)
@@ -726,7 +743,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/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';
}
diff --git a/lib/images/cleanup.ts b/lib/images/cleanup.ts
index a800101..9f17819 100644
--- a/lib/images/cleanup.ts
+++ b/lib/images/cleanup.ts
@@ -2,9 +2,10 @@ import 'server-only';
import { and, eq, inArray, isNull, or, sql } from 'drizzle-orm';
import { after } from 'next/server';
import { db } from '@/lib/db';
-import { draft, image, post } from '@/lib/db/schema';
+import { comlogProject, draft, image, post } from '@/lib/db/schema';
import {
collectOwnImagePaths,
+ excludeProtectedImages,
excludeReferencedImages,
findCleanupCandidates,
} from '@/lib/images/rules';
@@ -45,10 +46,35 @@ export class ImageRemovalError extends Error {
}
/**
- * 이미지 파일을 지우고, 성공하면 행도 지움
+ * 후보 중 comlog 프로젝트 대표 이미지로 쓰이는 것의 id (쿼리 하나)
+ * - 대표 이미지는 draft_id 가 비어 '주인 없는 이미지'로 보이므로, 지우기 직전에 한 번 더 걸러냄
+ */
+const findProtectedImageIds = async (ids: string[]): Promise> => {
+ if (ids.length === 0) {
+ return new Set();
+ }
+
+ const rows = await db
+ .select({ id: comlogProject.coverImageId })
+ .from(comlogProject)
+ .where(inArray(comlogProject.coverImageId, ids));
+
+ return new Set(rows.flatMap(({ id }) => (id ? [id] : [])));
+};
+
+/**
+ * 이미지 파일을 지우고, 성공하면 행도 지움 (이미지 삭제의 유일한 길목)
+ * - comlog 대표 이미지는 어떤 호출에서도 지우지 않음
* - Storage 삭제가 실패하면 행을 남기고 ImageRemovalError
*/
-export const removeDraftImages = async (images: ImageRef[]): Promise => {
+export const removeDraftImages = async (
+ requested: ImageRef[],
+): Promise => {
+ const images = excludeProtectedImages(
+ requested,
+ await findProtectedImageIds(requested.map(({ id }) => id)),
+ );
+
if (images.length === 0) {
return;
}
diff --git a/lib/images/cover.ts b/lib/images/cover.ts
new file mode 100644
index 0000000..901f854
--- /dev/null
+++ b/lib/images/cover.ts
@@ -0,0 +1,41 @@
+import 'server-only';
+import { and, eq } from 'drizzle-orm';
+import { db } from '@/lib/db';
+import { comlogProject, image } from '@/lib/db/schema';
+
+type NewCoverImage = Omit;
+
+/**
+ * comlog 프로젝트 대표 이미지 기록을 넣고 프로젝트에 연결 (한 트랜잭션)
+ * - draft_id 는 비움: 초안에 속하지 않으므로 장 수 상한(초안당)은 적용하지 않고 시간당 업로드 횟수 제한이 막음
+ * - 이전 대표 이미지는 지우지 않음: 연결이 풀려 '주인 없는 이미지'가 되고 평소 정리(유예 10분)가 지움
+ * @returns 연결했으면 true, 그 사용자의 프로젝트가 없으면 false (기록도 넣지 않음)
+ */
+export const insertCoverImage = async (
+ repositoryId: string,
+ values: NewCoverImage,
+): Promise =>
+ db.transaction(async (tx) => {
+ const [project] = await tx
+ .select({ id: comlogProject.id })
+ .from(comlogProject)
+ .where(
+ and(
+ eq(comlogProject.userId, values.userId),
+ eq(comlogProject.repositoryId, repositoryId),
+ ),
+ )
+ .for('update');
+
+ if (!project) {
+ return false;
+ }
+
+ await tx.insert(image).values({ ...values, draftId: null });
+ await tx
+ .update(comlogProject)
+ .set({ coverImageId: values.id })
+ .where(eq(comlogProject.id, project.id));
+
+ return true;
+ });
diff --git a/lib/images/rules.test.ts b/lib/images/rules.test.ts
index 4e829a7..bc83d52 100644
--- a/lib/images/rules.test.ts
+++ b/lib/images/rules.test.ts
@@ -6,12 +6,14 @@ import {
checkImageFile,
collectImageSrcs,
collectOwnImagePaths,
+ excludeProtectedImages,
excludeReferencedImages,
findCleanupCandidates,
findUnusedImages,
getImagePath,
getImagePublicUrl,
getUploadPath,
+ isProtectedImage,
isUuid,
parseImagePath,
removeDisallowedImages,
@@ -615,6 +617,32 @@ describe('excludeReferencedImages', () => {
});
});
+describe('대표 이미지 보호', () => {
+ it('보호 id 에 든 이미지만 보호됨', () => {
+ const protectedIds = new Set(['cover']);
+ expect(isProtectedImage('cover', protectedIds)).toBe(true);
+ expect(isProtectedImage('other', protectedIds)).toBe(false);
+ expect(isProtectedImage('cover', new Set())).toBe(false);
+ });
+
+ it('정리 후보 목록에서 보호 id 가 빠짐 (유예가 지난 주인 없는 이미지여도)', () => {
+ const now = new Date('2026-12-01T12:00:00Z');
+ const old = new Date(now.getTime() - IMAGE_CLEANUP_GRACE_MS - 1);
+ const orphans = [
+ { id: 'cover', path: `${USER}/cover.webp`, lastUsedAt: old },
+ { id: 'stale', path: `${USER}/stale.webp`, lastUsedAt: old },
+ ];
+ const candidates = findCleanupCandidates([], orphans, new Set(), now);
+
+ expect(candidates.map(({ id }) => id)).toEqual(['cover', 'stale']);
+ expect(
+ excludeProtectedImages(candidates, new Set(['cover'])).map(
+ ({ id }) => id,
+ ),
+ ).toEqual(['stale']);
+ });
+});
+
describe('isUuid', () => {
it('UUID 형식만 통과시킨다', () => {
expect(isUuid('3f2b8c1e-9a4d-4e7b-8c21-5d6f7a8b9c0d')).toBe(true);
diff --git a/lib/images/rules.ts b/lib/images/rules.ts
index f333033..ae61f17 100644
--- a/lib/images/rules.ts
+++ b/lib/images/rules.ts
@@ -268,6 +268,22 @@ export function excludeReferencedImages(
return images.filter((image) => !referencedPaths.has(image.path));
}
+/** 지우면 안 되는 이미지인지 (comlog 프로젝트 대표 이미지 id 모음에 든 것) */
+export function isProtectedImage(
+ imageId: string,
+ protectedIds: Set,
+): boolean {
+ return protectedIds.has(imageId);
+}
+
+/** 정리 후보에서 보호된 이미지를 뺌 */
+export function excludeProtectedImages(
+ images: T[],
+ protectedIds: Set,
+): T[] {
+ return images.filter((image) => !isProtectedImage(image.id, protectedIds));
+}
+
/**
* 임시 버킷 목록에서 만든 지 maxAgeMs 가 지난 파일 이름 (지울 대상)
* - 폴더(id 없음)와 만든 시각을 알 수 없는 항목은 건너뜀
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/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 c26e84d..f1d44c5 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 {
+ POST_VISIBILITIES,
+ REGULAR_POST_VISIBILITIES,
+ type PostVisibility,
+} from '@/lib/db/schema/post';
import type { Locale } from '@/lib/i18n/config';
import {
extractPostExcerpt,
@@ -7,14 +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)
-export const parsePostVisibility = (value: unknown): PostVisibility | null => {
- return POST_VISIBILITIES.find((visibility) => visibility === value) ?? null;
+// - private 은 comlog 회차만 (DB 검사 제약과 같은 규칙)
+export const parsePostVisibility = (
+ value: unknown,
+ 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/posts/queries.ts b/lib/posts/queries.ts
index 32bc77a..3071c8f 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;
@@ -94,6 +95,16 @@ export const getPublishedPost = cache(
},
);
+/**
+ * 게시글 본문의 첫 번째 이미지 주소 (게시 때 공개 버킷 주소로 정리됨, 없으면 null)
+ * - 본문 전체를 가져오지 않고 DB 에서 첫 이미지 주소만 뽑음 (인용구 등 안쪽 이미지도 본문 순서대로)
+ * - 게시글 목록과 comlog 회차 목록이 같은 규칙을 씀
+ */
+export const firstImageSrc = () =>
+ sql<
+ string | null
+ >`nullif(jsonb_path_query_first(${post.content}, 'strict $.**?(@.type == "image").attrs.src') #>> '{}', '')`;
+
export interface PostListItem {
id: string;
slug: string;
@@ -120,6 +131,7 @@ export const getPostListPage = async (
filters: PostListFilters,
): Promise => {
const where = and(
+ regularPostCondition(),
eq(post.visibility, 'public'),
// 임시 조치된 글은 목록에서 뺌
isNull(post.bannedAt),
@@ -133,9 +145,7 @@ export const getPostListPage = async (
slug: post.slug,
title: post.title,
excerpt: post.excerpt,
- thumbnailUrl: sql<
- string | null
- >`nullif(jsonb_path_query_first(${post.content}, 'strict $.**?(@.type == "image").attrs.src') #>> '{}', '')`,
+ thumbnailUrl: firstImageSrc(),
})
.from(post)
.where(where)
@@ -165,7 +175,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/tags.test.ts b/lib/posts/tags.test.ts
index e453ee4..4231b45 100644
--- a/lib/posts/tags.test.ts
+++ b/lib/posts/tags.test.ts
@@ -57,6 +57,14 @@ describe('addTag', () => {
expect(addTag(tenTags, 'new')).toEqual({ status: 'full' });
});
+ it('최대 개수를 따로 주면 그 개수까지 (comlog 기술 스택 20개)', () => {
+ expect(addTag(tenTags, 'new', 20)).toEqual({
+ status: 'added',
+ tags: [...tenTags, 'new'],
+ });
+ expect(addTag(tenTags, 'new', 10)).toEqual({ status: 'full' });
+ });
+
it('정규화해서 끝에 추가', () => {
expect(addTag(['react'], 'Vercel')).toEqual({
status: 'added',
diff --git a/lib/posts/tags.ts b/lib/posts/tags.ts
index ff7bed0..ec27dda 100644
--- a/lib/posts/tags.ts
+++ b/lib/posts/tags.ts
@@ -44,8 +44,12 @@ export type AddTagResult =
| { status: 'added'; tags: string[] }
| { status: 'empty' | 'duplicate' | 'full' };
-// 편집기에서 태그 하나 추가 (추가할 수 없으면 이유를 돌려줌)
-export const addTag = (tags: string[], input: string): AddTagResult => {
+// 편집기에서 태그 하나 추가 (추가할 수 없으면 이유를 돌려줌, max 는 comlog 기술 스택처럼 개수가 다를 때)
+export const addTag = (
+ tags: string[],
+ input: string,
+ max: number = MAX_TAGS,
+): AddTagResult => {
const tag = normalizeTag(input);
if (!tag) {
@@ -56,7 +60,7 @@ export const addTag = (tags: string[], input: string): AddTagResult => {
return { status: 'duplicate' };
}
- if (tags.length >= MAX_TAGS) {
+ if (tags.length >= max) {
return { status: 'full' };
}
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/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),
+ ),
),
]);
diff --git a/lib/seo/copy.ts b/lib/seo/copy.ts
index b5b8204..84766e2 100644
--- a/lib/seo/copy.ts
+++ b/lib/seo/copy.ts
@@ -13,6 +13,13 @@ export const POSTS_TITLE = msg`개발 블로그 게시글`;
export const POSTS_DESCRIPTION = msg`comdraft 로 작성한 기술 개발 블로그 글을 최신순으로 모았습니다. 실제 커밋과 코드 변경을 바탕으로 쓴 개발 경험을 읽어 보세요.`;
+// comlog 목록 (화면 제목 아래 한 줄 설명은 COMLOG_TAGLINE, en 은 "Build logs from real commits")
+export const COMLOG_TAGLINE = msg`프로젝트 제작기`;
+
+export const COMLOG_TITLE = msg`comlog 프로젝트 제작기`;
+
+export const COMLOG_DESCRIPTION = msg`실제 커밋을 바탕으로 기록한 프로젝트 제작 과정을 모았습니다. 프로젝트마다 작업 기록을 최근 순으로 읽어 보세요.`;
+
// 오픈그래프 이미지의 한 줄 소개와 기능 요약
export const OG_TAGLINE = msg`커밋으로 쓰는 AI 기술 블로그 초안`;
diff --git a/lib/seo/json-ld.ts b/lib/seo/json-ld.ts
index 0e9265d..89bba8a 100644
--- a/lib/seo/json-ld.ts
+++ b/lib/seo/json-ld.ts
@@ -12,9 +12,18 @@ interface BlogPostingInput {
authorUrl: string | null;
tags: string[];
locale: Locale;
+ // comlog 회차가 속한 프로젝트 페이지 (일반 게시글은 없음)
+ isPartOf?: { name: string; url: string };
}
-// 게시글 상세의 구조화 데이터 (schema.org BlogPosting)
+// 작성자 (GitHub 프로필 주소가 없으면 넣지 않음)
+const person = (name: string, url: string | null) => ({
+ '@type': 'Person',
+ name,
+ ...(url ? { url } : {}),
+});
+
+// 게시글·comlog 회차 상세의 구조화 데이터 (schema.org BlogPosting)
export const buildBlogPostingJsonLd = (input: BlogPostingInput) => ({
'@context': 'https://schema.org',
'@type': 'BlogPosting',
@@ -27,11 +36,45 @@ export const buildBlogPostingJsonLd = (input: BlogPostingInput) => ({
dateModified: input.updatedAt.toISOString(),
inLanguage: input.locale,
...(input.tags.length > 0 ? { keywords: input.tags.join(', ') } : {}),
- author: {
- '@type': 'Person',
- name: input.authorName,
- ...(input.authorUrl ? { url: input.authorUrl } : {}),
- },
+ author: person(input.authorName, input.authorUrl),
+ ...(input.isPartOf
+ ? {
+ isPartOf: {
+ '@type': 'CollectionPage',
+ name: input.isPartOf.name,
+ url: input.isPartOf.url,
+ },
+ }
+ : {}),
+});
+
+interface ComlogProjectInput {
+ url: string;
+ name: string;
+ description: string;
+ image: string;
+ updatedAt: Date;
+ authorName: string;
+ authorUrl: string | null;
+ techStack: string[];
+}
+
+/**
+ * comlog 프로젝트 페이지의 구조화 데이터 (회차를 모은 페이지라 schema.org CollectionPage)
+ * - 작성자는 프로젝트의 작성자 표시 설정을 따른 값
+ */
+export const buildComlogProjectJsonLd = (input: ComlogProjectInput) => ({
+ '@context': 'https://schema.org',
+ '@type': 'CollectionPage',
+ name: input.name,
+ ...(input.description ? { description: input.description } : {}),
+ url: input.url,
+ image: input.image,
+ dateModified: input.updatedAt.toISOString(),
+ ...(input.techStack.length > 0
+ ? { keywords: input.techStack.join(', ') }
+ : {}),
+ author: person(input.authorName, input.authorUrl),
});
/**
diff --git a/lib/seo/seo.test.ts b/lib/seo/seo.test.ts
index a503a1a..1239555 100644
--- a/lib/seo/seo.test.ts
+++ b/lib/seo/seo.test.ts
@@ -1,10 +1,17 @@
import { describe, expect, it } from 'vitest';
import { isAuthorizedCronRequest } from '@/lib/seo/cron';
-import { buildBlogPostingJsonLd, serializeJsonLd } from '@/lib/seo/json-ld';
+import {
+ buildBlogPostingJsonLd,
+ buildComlogProjectJsonLd,
+ serializeJsonLd,
+} from '@/lib/seo/json-ld';
import { buildWebsiteOpenGraph } from '@/lib/seo/open-graph';
import { truncateOgText } from '@/lib/seo/og-text';
import { buildRobots } from '@/lib/seo/robots';
-import { buildSitemapEntries } from '@/lib/seo/sitemap';
+import {
+ buildComlogSitemapEntries,
+ buildSitemapEntries,
+} from '@/lib/seo/sitemap';
import { buildLocalizedAlternates } from '@/lib/seo/urls';
const ORIGIN = 'https://comdraft.dev';
@@ -69,6 +76,51 @@ describe('buildSitemapEntries', () => {
});
});
+describe('buildComlogSitemapEntries', () => {
+ const projectId = '0f8fad5b-d9cb-469f-a165-70867728950e';
+ const updatedAt = new Date('2026-11-20T00:00:00Z');
+ const entries = buildComlogSitemapEntries(ORIGIN, {
+ projects: [{ id: projectId, slug: '프로젝트', updatedAt }],
+ entries: [
+ {
+ project: { id: projectId, slug: '프로젝트' },
+ id: 'a1B2c3D4e5',
+ slug: '회차',
+ locale: 'en',
+ updatedAt,
+ },
+ ],
+ });
+ const projectSegment = encodeURIComponent(`프로젝트-${projectId}`);
+
+ it('목록과 프로젝트 페이지는 언어마다 한 줄씩 hreflang 으로 묶는다', () => {
+ expect(entries.slice(0, 4).map((e) => e.url)).toEqual([
+ 'https://comdraft.dev/ko/comlog',
+ 'https://comdraft.dev/en/comlog',
+ `https://comdraft.dev/ko/comlog/${projectSegment}`,
+ `https://comdraft.dev/en/comlog/${projectSegment}`,
+ ]);
+ expect(entries[2]).toEqual({
+ url: `https://comdraft.dev/ko/comlog/${projectSegment}`,
+ lastModified: updatedAt,
+ alternates: {
+ languages: {
+ ko: `https://comdraft.dev/ko/comlog/${projectSegment}`,
+ en: `https://comdraft.dev/en/comlog/${projectSegment}`,
+ },
+ },
+ });
+ });
+
+ it('회차는 게시 언어의 인코딩된 대표 주소와 수정 시각', () => {
+ expect(entries[4]).toEqual({
+ url: `https://comdraft.dev/en/comlog/${projectSegment}/${encodeURIComponent('회차-a1B2c3D4e5')}`,
+ lastModified: updatedAt,
+ changeFrequency: 'monthly',
+ });
+ });
+});
+
describe('buildRobots', () => {
it('비공개 화면과 API 를 막고 사이트맵 주소를 알린다', () => {
expect(buildRobots(ORIGIN)).toEqual({
@@ -149,6 +201,56 @@ describe('JSON-LD', () => {
expect(ld).not.toHaveProperty('keywords');
});
+ it('회차는 속한 프로젝트를 isPartOf 로 가리킨다', () => {
+ const ld = buildBlogPostingJsonLd({
+ url: 'u',
+ title: 't',
+ description: 'd',
+ image: 'i',
+ publishedAt: new Date(0),
+ updatedAt: new Date(0),
+ authorName: 'a',
+ authorUrl: null,
+ tags: [],
+ locale: 'ko',
+ isPartOf: { name: 'comdraft', url: 'p' },
+ });
+
+ expect(ld.isPartOf).toEqual({
+ '@type': 'CollectionPage',
+ name: 'comdraft',
+ url: 'p',
+ });
+ });
+
+ it('comlog 프로젝트는 CollectionPage 로 이름·소개·기술 스택·작성자를 담는다', () => {
+ expect(
+ buildComlogProjectJsonLd({
+ url: 'u',
+ name: 'comdraft',
+ description: '',
+ image: 'i',
+ updatedAt: new Date(0),
+ authorName: 'a',
+ authorUrl: 'https://github.com/akodm',
+ techStack: ['nextjs'],
+ }),
+ ).toEqual({
+ '@context': 'https://schema.org',
+ '@type': 'CollectionPage',
+ name: 'comdraft',
+ url: 'u',
+ image: 'i',
+ dateModified: '1970-01-01T00:00:00.000Z',
+ keywords: 'nextjs',
+ author: {
+ '@type': 'Person',
+ name: 'a',
+ url: 'https://github.com/akodm',
+ },
+ });
+ });
+
it('script 안에 넣어도 태그가 닫히지 않도록 < 를 이스케이프', () => {
const text = serializeJsonLd({ headline: '