import { spawnSync } from "node:child_process"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; /** * 1105/07-01. `check:backend-contract-drift` on a fake paired backend: a git * repository with a small `docs/web/http-contract.md`, and a frontend root * with the pin, the answer table and the table excerpt. The script compared * only the document between the pin and HEAD, so an answer table or an * excerpt that disagreed with the pinned document passed, and no checkout * passed as "skipped". */ type Answer = Readonly<{ section: string; code: string; status: number }>; type Sections = Readonly>; const T2A = [ "| 경우 | status | `error.code` | 클라이언트 행동 |", "| --- | --- | --- | --- |", "| 재생: 같은 키, 첫 요청 완료 | 첫 요청과 같은 성공 status | — (성공 Envelope) | 받아들인다 |", "| 처리 중 | 409 | `IDEMPOTENT_IN_FLIGHT` | 같은 키로 다시 보낸다 |", ]; const T2B = [ "| 경우 | status | `error.code` | 클라이언트 행동 |", "| --- | --- | --- | --- |", "| 결과 불명 | 503 | `IDEMPOTENCY_COMPLETION_UNKNOWN` | 같은 키로 나중에 |", ]; const T4 = [ "| 코드 | status | 언제 |", "| --- | --- | --- |", "| `REQUEST_TIMEOUT` | 503 | 시간 안에 끝나지 않았다 |", "| `RATE_LIMIT_UNAVAILABLE` | 503 | rate-limit 저장소 응답 없음 |", ]; const SECTIONS: Sections = { "2": [T2A, T2B], "4": [T4] }; const ANSWERS: readonly Answer[] = [ { section: "2", code: "IDEMPOTENT_IN_FLIGHT", status: 409 }, { section: "2", code: "IDEMPOTENCY_COMPLETION_UNKNOWN", status: 503 }, { section: "4", code: "REQUEST_TIMEOUT", status: 503 }, ]; const NOT_COPIED = [ { section: "4", code: "RATE_LIMIT_UNAVAILABLE", reason: "fixture" }, ]; function contractDocument(sections: Sections): string { return [ "# HTTP wire 계약", "", "## 1. Envelope", "", "| 응답 | 키 |", "| --- | --- |", "| 성공 | `data` |", "", "## 2. 멱등성 응답", "", ...(sections["2"]?.[0] ?? []), "", "### 저장소가 응답하지 않을 때", "", ...(sections["2"]?.[1] ?? []), "", "## 4. web 전용 오류 코드", "", ...(sections["4"]?.[0] ?? []), "", "## 5. 바꿀 때", "", "- 표를 고치면 짝 프론트에 알린다.", "", ].join("\n"); } const directories: string[] = []; afterEach(async () => { await Promise.all( directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })), ); }); function git(cwd: string, ...args: string[]): string { const result = spawnSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, GIT_AUTHOR_NAME: "drift-fixture", GIT_AUTHOR_EMAIL: "drift-fixture@localhost", GIT_COMMITTER_NAME: "drift-fixture", GIT_COMMITTER_EMAIL: "drift-fixture@localhost", }, }); if (result.error || result.status !== 0) { throw new Error(`fixture git ${args[0]} failed: ${result.stderr || result.error?.message}`); } return result.stdout.trim(); } const DOCUMENT = "docs/web/http-contract.md"; /** * 1105/16-02. One of the backend scaffold files `create:feature * --with-create` copies a fact from (the aggregate's name limit). */ const AGGREGATE = "scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl"; const SCAFFOLD_SOURCES = [ { path: AGGREGATE, fact: "NAME_MAX_LENGTH 100", copiedTo: { file: "scripts/create-feature-write-slice.ts", symbol: "BACKEND_NAME_MAX_LENGTH" }, }, ]; async function commitFiles( backend: string, files: Readonly>, message: string, ): Promise { for (const [file, text] of Object.entries(files)) { await mkdir(path.dirname(path.join(backend, file)), { recursive: true }); await writeFile(path.join(backend, file), text); } git(backend, "add", "--all"); git(backend, "commit", "--quiet", "--no-gpg-sign", "--no-verify", "-m", message); return git(backend, "rev-parse", "HEAD"); } async function drift( options: Readonly<{ answers?: readonly Answer[]; excerpt?: Sections; notCopied?: typeof NOT_COPIED; /** The document of a backend commit after the pin. */ head?: string; /** 1105/16-02. The scaffold aggregate template in that later commit. */ scaffoldHead?: string; /** 1105/16-02. A file the pin does not name, in that later commit. */ otherHead?: string; /** Where the script looks for the backend instead of the fake one. */ backend?: string; flags?: readonly string[]; }> = {}, ) { const root = await mkdtemp(path.join(tmpdir(), "drift-frontend-")); const backend = await mkdtemp(path.join(tmpdir(), "drift-backend-")); directories.push(root, backend); git(backend, "init", "--quiet", "--initial-branch=fixture"); const commit = await commitFiles( backend, { [DOCUMENT]: contractDocument(SECTIONS), [AGGREGATE]: "public static final int NAME_MAX_LENGTH = 100;\n", "README.md": "backend\n", }, "pinned", ); const later = { ...(options.head === undefined ? {} : { [DOCUMENT]: options.head }), ...(options.scaffoldHead === undefined ? {} : { [AGGREGATE]: options.scaffoldHead }), ...(options.otherHead === undefined ? {} : { "README.md": options.otherHead }), }; if (Object.keys(later).length > 0) await commitFiles(backend, later, "after the pin"); const source = { repository: "clean-architecture-backend-template", commit, document: DOCUMENT, }; const write = async (file: string, value: unknown) => { await mkdir(path.dirname(path.join(root, file)), { recursive: true }); await writeFile(path.join(root, file), `${JSON.stringify(value, null, 2)}\n`); }; await write("config/contracts/backend-contract-pin.json", { schemaVersion: 1, backend: { ...source, sectionsCompared: ["1", "2", "4"], scaffoldSources: SCAFFOLD_SOURCES }, frontend: { contractDocument: "docs/architecture/backend-api-and-server-state-contract.md", contractSections: ["4.1", "6", "6.1"], readers: ["src/adapters/http/backend-envelope.ts"], }, tables: { idempotencyAnswers: "config/contracts/backend-idempotency-answers.json", backendExcerpt: "config/contracts/backend-http-contract-excerpt.json", }, notCopied: options.notCopied ?? NOT_COPIED, owner: "fixture", comparedOn: "2026-11-05", }); await write("config/contracts/backend-idempotency-answers.json", { schemaVersion: 1, source, answers: (options.answers ?? ANSWERS).map((answer) => ({ ...answer, refusedBeforeWrite: false, sameKeyResend: true, })), }); await write("config/contracts/backend-http-contract-excerpt.json", { schemaVersion: 1, source, sections: options.excerpt ?? SECTIONS, }); const result = spawnSync( process.execPath, [ path.resolve("scripts/check-backend-contract-drift.ts"), "--backend", options.backend ?? backend, ...(options.flags ?? []), ], { cwd: root, encoding: "utf8" }, ); return { status: result.status, stdout: result.stdout, stderr: result.stderr, readExcerpt: async () => JSON.parse( await readFile(path.join(root, "config/contracts/backend-http-contract-excerpt.json"), "utf8"), ) as { sections: Sections }, }; } describe("check:backend-contract-drift (1105/07-01)", () => { it("passes when the excerpt and the answer table match the pinned document", async () => { const result = await drift(); expect(result.stderr).toBe(""); expect(result.status).toBe(0); }); it("fails when an answer's status is not the pinned document's", async () => { const result = await drift({ answers: ANSWERS.map((answer) => answer.code === "IDEMPOTENCY_COMPLETION_UNKNOWN" ? { ...answer, status: 500 } : answer, ), }); expect(result.status).toBe(1); expect(result.stderr).toContain( "answer 500 IDEMPOTENCY_COMPLETION_UNKNOWN is not a row of the pinned document's §2", ); }); it("fails when the excerpt is not the pinned document's, even if the answers follow it", async () => { const edited = T2B.map((line) => line.replace("| 503 |", "| 500 |")); const result = await drift({ excerpt: { ...SECTIONS, "2": [T2A, edited] }, answers: ANSWERS.map((answer) => answer.code === "IDEMPOTENCY_COMPLETION_UNKNOWN" ? { ...answer, status: 500 } : answer, ), }); expect(result.status).toBe(1); expect(result.stderr).toContain( "excerpt differs from the pinned document: §2 -| 결과 불명 | 500 |", ); expect(result.stderr).toContain( "excerpt differs from the pinned document: §2 +| 결과 불명 | 503 |", ); }); it("fails on a row of the pinned document neither copied nor listed as not copied", async () => { const result = await drift({ notCopied: [] }); expect(result.status).toBe(1); expect(result.stderr).toContain( "§4 503 RATE_LIMIT_UNAVAILABLE is neither in the answer table nor in the pin's notCopied", ); }); // D6g in the 2026-11-05 review: the backend changes a copied row after the pin. it("fails on a copied row the backend changed after the pin", async () => { const result = await drift({ head: contractDocument({ ...SECTIONS, "2": [T2A, T2B.map((line) => line.replace("| 503 |", "| 500 |"))], }), }); expect(result.status).toBe(1); expect(result.stderr).toContain("| 결과 불명 | 500 |"); }); it("does not pass without a backend checkout", async () => { const result = await drift({ backend: path.join(tmpdir(), "no-such-backend-checkout") }); expect(result.status).toBe(2); expect(result.stderr).toContain("not compared"); }); it("writes the excerpt from the pinned document with --write-excerpt", async () => { const result = await drift({ excerpt: { "2": [T2A], "4": [T4.slice(0, 3)] }, flags: ["--write-excerpt"], }); expect(result.stderr).toBe(""); expect(result.status).toBe(0); expect((await result.readExcerpt()).sections).toEqual(SECTIONS); }); }); /** * 1105/16-02. `create:feature --with-create` copies four facts from the * paired backend's feature scaffold (path plural rule, name limit 100, error * codes, check order). The pin and this script covered only * `docs/web/http-contract.md`, so a backend that changed its scaffold left * the frontend generator writing another path, limit or code with no signal. */ describe("check:backend-contract-drift scaffold sources (1105/16-02)", () => { it("reports a scaffold source the generator copies from, with where the copy is", async () => { const result = await drift({ scaffoldHead: "public static final int NAME_MAX_LENGTH = 120;\n" }); expect(result.status, result.stdout + result.stderr).toBe(1); expect(result.stderr).toContain(`scaffold source ${AGGREGATE} changed`); expect(result.stderr).toContain( "recheck BACKEND_NAME_MAX_LENGTH in scripts/create-feature-write-slice.ts", ); }); it("passes a later backend commit that changed neither the document nor a scaffold source", async () => { const result = await drift({ otherHead: "backend, later\n" }); expect(result.stderr).toBe(""); expect(result.status).toBe(0); expect(result.stdout).toContain("1 scaffold sources unchanged"); }); });