import { spawnSync } from "node:child_process"; import { existsSync, readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import { answerTableProblems, excerptAnswerRows, excerptDifferences, readExcerptSections, type ExcerptSections, type NotCopiedRow, } from "./lib/backend-contract-excerpt.ts"; /** * 1103/12-06, 1105/07-01. Local only, outside every gate: CI checks this * repository out alone. With the paired backend checkout it checks that * * 1. the table excerpt (`tables.backendExcerpt`) is word for word the * backend document's tables at the pinned commit, * 2. the answer table JSON matches that excerpt (test:unit checks this too), * 3. the document has not changed between the pin and the backend's HEAD, * 4. 1105/16-02: neither have the backend scaffold files * (`backend.scaffoldSources`) that `create:feature --with-create` copies * four facts from (path plural rule, name limit, error codes, check * order). Each changed file names the frontend copy to recheck. * * corepack pnpm check:backend-contract-drift [--backend ] [--write-excerpt] * * `--write-excerpt` copies the excerpt from the pinned commit first: run it * after moving the pin, then fix the answer table until this passes. * * Exit 0: all four hold. Exit 1: one does not; the output names the rows or * files. Recheck the frontend contract 6.1 table, the answer table, the * excerpt, the generator copies and the pin in one change. Exit 2: nothing * was compared (no checkout, or the pinned commit or document is missing), * which is not a pass. * * Without `--backend` the checkout is looked for beside the main checkout of * this repository, so a linked worktree (`.claude/worktrees/`) finds * the same one. */ type ScaffoldSource = Readonly<{ path: string; fact: string; copiedTo: Readonly<{ file: string; symbol: string }>; }>; type Pin = Readonly<{ backend: Readonly<{ repository: string; commit: string; document: string; scaffoldSources?: readonly ScaffoldSource[]; }>; tables: Readonly<{ idempotencyAnswers: string; backendExcerpt: string }>; notCopied: readonly NotCopiedRow[]; }>; type Answers = Readonly<{ answers: readonly Readonly<{ section: string; code: string; status: number }>[]; }>; type Excerpt = Readonly<{ schemaVersion: 1; source: Readonly<{ repository: string; commit: string; document: string }>; sections: ExcerptSections; }>; const PIN_PATH = "config/contracts/backend-contract-pin.json"; function git(directory: string, ...args: string[]) { return spawnSync("git", ["-C", directory, ...args], { encoding: "utf8" }); } function backendDirectory(pin: Pin): string { const flag = process.argv.indexOf("--backend"); const given = flag >= 0 ? process.argv[flag + 1] : undefined; if (given) return path.resolve(given); const common = spawnSync( "git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf8" }, ); const mainCheckout = common.status === 0 && common.stdout.trim() !== "" ? path.dirname(common.stdout.trim()) : process.cwd(); return path.resolve(mainCheckout, "..", pin.backend.repository); } function readJson(file: string): T { return JSON.parse(readFileSync(file, "utf8")) as T; } function cannotCompare(message: string): void { console.error(`Backend contract drift: not compared. ${message}`); process.exitCode = 2; } function main(): void { const pin = readJson(PIN_PATH); const directory = backendDirectory(pin); const { commit, document } = pin.backend; const scaffoldSources = pin.backend.scaffoldSources ?? []; if (!existsSync(path.join(directory, ".git"))) { cannotCompare( `No ${pin.backend.repository} checkout at ${directory}; pass --backend . test:unit holds the answer table to ${pin.tables.backendExcerpt}, and only this script holds that copy to the backend.`, ); return; } const head = git(directory, "rev-parse", "HEAD"); if (head.status !== 0 || git(directory, "cat-file", "-e", `${commit}^{commit}`).status !== 0) { cannotCompare( `${directory} does not have the pinned ${commit.slice(0, 12)}; fetch the backend history first.`, ); return; } const pinned = git(directory, "show", `${commit}:${document}`); if (pinned.status !== 0) { cannotCompare(`${document} is not in the pinned ${commit.slice(0, 12)}.`); return; } const sectionNames = Object.keys(readJson(pin.tables.backendExcerpt).sections); const pinnedSections = readExcerptSections(pinned.stdout, sectionNames); if (process.argv.includes("--write-excerpt")) { const written: Excerpt = { schemaVersion: 1, source: { repository: pin.backend.repository, commit, document }, sections: pinnedSections, }; writeFileSync(pin.tables.backendExcerpt, `${JSON.stringify(written, null, 2)}\n`); console.log( `Backend contract drift: wrote ${pin.tables.backendExcerpt} from ${commit.slice(0, 12)} §${sectionNames.join(", §")}`, ); } const excerpt = readJson(pin.tables.backendExcerpt); const failures: string[] = []; const source = excerpt.source; if (source.repository !== pin.backend.repository || source.commit !== commit || source.document !== document) { failures.push(`${pin.tables.backendExcerpt} names ${source.commit.slice(0, 12)}, the pin ${commit.slice(0, 12)}`); } for (const line of excerptDifferences(excerpt.sections, pinnedSections)) { failures.push(`excerpt differs from the pinned document: ${line}`); } const answers = readJson(pin.tables.idempotencyAnswers).answers; for (const problem of answerTableProblems(answers, pin.notCopied, excerptAnswerRows(pinnedSections))) { failures.push(`answer table: ${problem}`); } const headCommit = head.stdout.trim(); if (headCommit !== commit) { const changed = git(directory, "diff", "--unified=0", `${commit}..HEAD`, "--", document); if (changed.stdout.trim() !== "") { failures.push( `${document} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}`, ); const current = git(directory, "show", `HEAD:${document}`); const tableChanges = current.status === 0 ? excerptDifferences(pinnedSections, readExcerptSections(current.stdout, sectionNames)) : []; for (const line of tableChanges) failures.push(` copied table at HEAD: ${line}`); if (tableChanges.length === 0) { failures.push(" (no copied table row changed; read the other changes with git diff)"); } } // 1105/16-02. The generator's copies of backend scaffold facts. for (const scaffold of scaffoldSources) { const scaffoldDiff = git(directory, "diff", "--unified=0", `${commit}..HEAD`, "--", scaffold.path); if (scaffoldDiff.stdout.trim() === "") continue; failures.push( `scaffold source ${scaffold.path} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}`, ); failures.push( ` the generator copies "${scaffold.fact}" from it: recheck ${scaffold.copiedTo.symbol} in ${scaffold.copiedTo.file}`, ); } } if (failures.length === 0) { console.log( headCommit === commit ? `Backend contract drift: ${directory} is at the pinned ${commit.slice(0, 12)}; the excerpt and the answer table match it` : `Backend contract drift: HEAD ${headCommit.slice(0, 12)} is past the pin ${commit.slice(0, 12)}, ${document} and ${scaffoldSources.length} scaffold sources unchanged; the excerpt and the answer table match it`, ); return; } console.error("Backend contract drift:"); for (const failure of failures) console.error(` ${failure}`); console.error( `Recheck docs/architecture/backend-api-and-server-state-contract.md 6.1, ${pin.tables.idempotencyAnswers}, ${pin.tables.backendExcerpt}, the generator copies of changed scaffold sources and ${PIN_PATH} together.`, ); process.exitCode = 1; } main();