Files
clean-architecture-frontend…/scripts/check-backend-contract-drift.ts
T
DongHyeonka daf3474252 fix(contracts): 짝 백엔드 답 표를 pin한 백엔드 표의 사본과 대조한다
문제: 짝 백엔드 답 표 JSON(backend-idempotency-answers.json)이 pin한
백엔드 http-contract.md와 같은지 아무 검사도 보지 않는다.
backend-contract-pin.test.ts는 pin과 답 표 두 파일만 읽고, drift
스크립트는 pin과 HEAD 사이에 문서 글자가 바뀌었는지만 본다. 그래서
답 표 status 오타나 옮기지 않은 행(§4 RATE_LIMIT_*)은 어디서도 걸리지
않는다. drift 스크립트는 옆 checkout이 없으면 "skipped"로 rc=0이고
(worktree에서 늘 그렇다), 매뉴얼에는 스크립트가 없다.

고른 방법: 게이트가 백엔드 checkout 없이 볼 수 있게, 백엔드 §2·§4 표의
`|` 줄을 pin 커밋 그대로 config/contracts/backend-http-contract-excerpt.json
에 옮겼다. 읽는 함수는 scripts/lib/backend-contract-excerpt.ts 하나다.
- test:unit(backend-contract-pin.test.ts): 답 표의 행마다 사본의 같은 절에
  같은 code·status 행이 있는지, 사본의 행마다 답 표에 있거나 pin의
  `notCopied`에 이유와 함께 있는지 본다. `notCopied`에는 RATE_LIMIT_* 둘을
  적었다(리뷰가 지적한 sectionsCompared §4의 실제 범위).
- check:backend-contract-drift(게이트 밖): pin 커밋의 문서에서 같은 표를
  읽어 사본과 글자 단위로 비교하고, 답 표도 그 표와 비교하고, pin 뒤
  HEAD에서 바뀐 사본 표 행을 찍는다. checkout이 없거나 pin 커밋·문서가
  없으면 rc=2("not compared")로 끝난다. 기본 경로는 main checkout 옆이라
  linked worktree에서도 같은 백엔드를 찾는다. `--write-excerpt`는 pin을
  올릴 때 사본을 pin 커밋에서 다시 옮긴다.
- 매뉴얼 01 Envelope 단계와 계약 문서 4.1에 언제 무엇을 돌리는지 적었다.
버린 대안: 백엔드 문서의 digest만 pin에 두는 것. 게이트는 digest로 답
표를 확인할 수 없다. 계약 패키지(리뷰 안 D)는 배포 경로가 아직 없다.

위험·한계: 사본과 백엔드 문서의 일치는 여전히 백엔드 checkout이 있을
때만 drift 스크립트가 본다. 게이트는 답 표와 사본의 일치만 본다. 사본을
손으로 같이 고치면 게이트는 통과한다(drift 스크립트가 잡는다). 답 표의
refusedBeforeWrite·sameKeyResend는 백엔드 문장(클라이언트 행동)을 사람이
읽은 값이라 기계로 대조하지 않는다. 그 문장이 바뀌면 사본 diff와 drift
출력에 보인다. 백엔드 표 형식(머리글 `error.code`·`코드`·`status`)이
바뀌면 파서도 고친다. pin의 comparedOn을 사본을 옮긴 날로 올렸다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/backend-contract-pin.test.ts tests/unit/backend-contract-drift.test.ts
drift 테스트는 가짜 백엔드 git repo로 D6g(pin 뒤 status 변경), 답 표
status 오타, 사본 오타, 옮기지도 적지도 않은 행, checkout 없음,
--write-excerpt를 돈다.

Refs: 1105/07-01
2026-11-05 22:17:57 +09:00

171 lines
6.7 KiB
TypeScript

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.
*
* corepack pnpm check:backend-contract-drift [--backend <dir>] [--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 three hold. Exit 1: one does not; the output names the rows.
* Recheck the frontend contract 6.1 table, the answer table, the excerpt 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/<name>`) finds
* the same one.
*/
type Pin = Readonly<{
backend: Readonly<{ repository: string; commit: string; document: string }>;
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<T>(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>(PIN_PATH);
const directory = backendDirectory(pin);
const { commit, document } = pin.backend;
if (!existsSync(path.join(directory, ".git"))) {
cannotCompare(
`No ${pin.backend.repository} checkout at ${directory}; pass --backend <dir>. 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<Excerpt>(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<Excerpt>(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<Answers>(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)");
}
}
}
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} 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} and ${PIN_PATH} together.`,
);
process.exitCode = 1;
}
main();