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
This commit is contained in:
DongHyeonka
2026-11-05 22:17:57 +09:00
parent 3b62ccd5db
commit daf3474252
9 changed files with 717 additions and 48 deletions
+128 -41
View File
@@ -1,82 +1,169 @@
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
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. Local only, outside every gate: CI checks this repository out
* alone. Tells whether the paired backend checkout next to this one has moved
* past the commit `config/contracts/backend-contract-pin.json` pins, and
* whether the contract document changed since.
* 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
*
* corepack pnpm check:backend-contract-drift [--backend <dir>]
* 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.
*
* Exit 0: no checkout to compare, the pinned commit itself, or a later commit
* whose contract document is unchanged. Exit 1: the document changed after
* the pin. Recheck the frontend contract 6.1 table, the copied answer table
* and the pin in one change. Exit 2: the checkout cannot be compared.
* 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 backendDirectory(pin: Pin): string {
const flag = process.argv.indexOf("--backend");
const given = flag >= 0 ? process.argv[flag + 1] : undefined;
return given
? path.resolve(given)
: path.resolve("..", pin.backend.repository);
}
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 = JSON.parse(readFileSync(PIN_PATH, "utf8")) as Pin;
const pin = readJson<Pin>(PIN_PATH);
const directory = backendDirectory(pin);
const { commit, document } = pin.backend;
if (!existsSync(path.join(directory, ".git"))) {
console.log(
`Backend contract drift: skipped, no ${pin.backend.repository} checkout at ${directory} (pass --backend <dir>)`,
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) {
console.error(
`Backend contract drift: cannot compare ${directory} with the pinned ${commit.slice(0, 12)}; fetch the backend history first`,
cannotCompare(
`${directory} does not have the pinned ${commit.slice(0, 12)}; fetch the backend history first.`,
);
process.exitCode = 2;
return;
}
const headCommit = head.stdout.trim();
if (headCommit === commit) {
console.log(`Backend contract drift: ${directory} is at the pinned ${commit.slice(0, 12)}`);
const pinned = git(directory, "show", `${commit}:${document}`);
if (pinned.status !== 0) {
cannotCompare(`${document} is not in the pinned ${commit.slice(0, 12)}.`);
return;
}
const changed = git(directory, "diff", "--unified=0", `${commit}..HEAD`, "--", document);
const tableLines = changed.stdout
.split("\n")
.filter((line) => /^[+-]\|/u.test(line));
if (changed.stdout.trim() === "") {
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: HEAD ${headCommit.slice(0, 12)} is past the pin ${commit.slice(0, 12)}, ${document} unchanged`,
`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(
`Backend contract drift: ${document} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}.`,
`Recheck docs/architecture/backend-api-and-server-state-contract.md 6.1, ${pin.tables.idempotencyAnswers}, ${pin.tables.backendExcerpt} and ${PIN_PATH} together.`,
);
console.error(
`Recheck docs/architecture/backend-api-and-server-state-contract.md 6.1, config/contracts/backend-idempotency-answers.json and ${PIN_PATH} together.`,
);
for (const line of tableLines) console.error(` ${line}`);
if (tableLines.length === 0) {
console.error(" (no table rows changed; read the prose changes with git diff)");
}
process.exitCode = 1;
}
+187
View File
@@ -0,0 +1,187 @@
/**
* 1105/07-01. The paired backend's `http-contract.md` tables the frontend
* copies at the pinned commit (`config/contracts/backend-http-contract-excerpt.json`),
* read the same way from the backend document and from the copy.
*
* - `tests/unit/backend-contract-pin.test.ts` (test:unit) holds the answer
* table JSON to the copy. It needs no backend checkout.
* - `scripts/check-backend-contract-drift.ts` (local, outside the gates) holds
* the copy to the backend document at the pin and reports what changed at
* the backend's HEAD.
*/
/** Section number (`"2"` for `## 2. ...`) → its tables, each the `|` lines in order. */
export type ExcerptSections = Readonly<Record<string, readonly (readonly string[])[]>>;
export type ContractAnswerRow = Readonly<{
section: string;
code: string;
status: number;
}>;
export type NotCopiedRow = Readonly<{
section: string;
code: string;
reason: string;
}>;
const SECTION_HEADING = /^## (\d+)\.\s/u;
const ANY_SECTION_HEADING = /^## /u;
const CODE_HEADERS = new Set(["error.code", "코드"]);
const STATUS_HEADER = "status";
const CODE_CELL = /^`([A-Z][A-Z0-9_]*)`/u;
const STATUS_CELL = /^\d{3}$/u;
const SEPARATOR_ROW = /^\|(?:\s*:?-+:?\s*\|)+\s*$/u;
/**
* The tables of the `## N.` sections named: every run of lines that start
* with `|`, kept as written. A `###` heading stays inside its section.
*/
export function readExcerptSections(
markdown: string,
sections: readonly string[],
): ExcerptSections {
const tables: Record<string, string[][]> = {};
let section: string | undefined;
let table: string[] | undefined;
for (const line of markdown.split(/\r?\n/u)) {
if (ANY_SECTION_HEADING.test(line)) {
section = SECTION_HEADING.exec(line)?.[1];
table = undefined;
continue;
}
if (section === undefined || !sections.includes(section) || !line.startsWith("|")) {
table = undefined;
continue;
}
if (table === undefined) {
table = [];
(tables[section] ??= []).push(table);
}
table.push(line);
}
return Object.freeze(
Object.fromEntries(
sections.map((name) => [
name,
Object.freeze((tables[name] ?? []).map((rows) => Object.freeze([...rows]))),
]),
),
);
}
function cells(line: string): string[] {
return line
.replace(/^\|/u, "")
.replace(/\|\s*$/u, "")
.split("|")
.map((cell) => cell.trim());
}
/**
* The rows that answer with one error code and one status: the code column
* is headed `error.code` or `코드`, the status column `status`. A row without
* a code (§2's replay) or without one three-digit status is not an answer.
*/
export function excerptAnswerRows(sections: ExcerptSections): readonly ContractAnswerRow[] {
const rows: ContractAnswerRow[] = [];
for (const [section, tables] of Object.entries(sections)) {
for (const table of tables) {
const [header = "", ...body] = table;
const headings = cells(header).map((cell) => cell.replaceAll("`", ""));
const codeColumn = headings.findIndex((cell) => CODE_HEADERS.has(cell));
const statusColumn = headings.indexOf(STATUS_HEADER);
if (codeColumn < 0 || statusColumn < 0) continue;
for (const line of body) {
if (SEPARATOR_ROW.test(line)) continue;
const row = cells(line);
const code = CODE_CELL.exec(row[codeColumn] ?? "")?.[1];
const status = row[statusColumn] ?? "";
if (code !== undefined && STATUS_CELL.test(status)) {
rows.push(Object.freeze({ section, code, status: Number(status) }));
}
}
}
}
return Object.freeze(rows);
}
/**
* What the copied answer table gets wrong against the excerpt: an answer the
* named section does not have, an excerpt row neither copied nor listed as
* not copied, and a not-copied entry the excerpt does not have. An answer
* covers an excerpt row of any section with the same code and status (§4
* repeats §2's `IDEMPOTENCY_KEY_INVALID`).
*/
export function answerTableProblems(
answers: readonly ContractAnswerRow[],
notCopied: readonly NotCopiedRow[],
excerpt: readonly ContractAnswerRow[],
): readonly string[] {
const problems: string[] = [];
for (const answer of answers) {
const inSection = excerpt.some(
(row) =>
row.section === answer.section &&
row.code === answer.code &&
row.status === answer.status,
);
if (!inSection) {
problems.push(
`answer ${answer.status} ${answer.code} is not a row of the pinned document's §${answer.section}`,
);
}
}
for (const row of excerpt) {
const copied = answers.some(
(answer) => answer.code === row.code && answer.status === row.status,
);
const skipped = notCopied.some(
(entry) => entry.section === row.section && entry.code === row.code,
);
if (copied && skipped) {
problems.push(
`§${row.section} ${row.status} ${row.code} is both copied and listed in notCopied`,
);
} else if (!copied && !skipped) {
problems.push(
`§${row.section} ${row.status} ${row.code} is neither in the answer table nor in the pin's notCopied`,
);
}
}
for (const entry of notCopied) {
if (!excerpt.some((row) => row.section === entry.section && row.code === entry.code)) {
problems.push(
`notCopied ${entry.code} is not a row of the pinned document's §${entry.section}`,
);
}
}
return Object.freeze(problems);
}
/**
* The lines one excerpt has and the other does not, per section: `-` only
* in `expected`, `+` only in `actual`. Empty when they are the same.
*/
export function excerptDifferences(
expected: ExcerptSections,
actual: ExcerptSections,
): readonly string[] {
const differences: string[] = [];
const names = [...new Set([...Object.keys(expected), ...Object.keys(actual)])].sort();
for (const name of names) {
const before = (expected[name] ?? []).flat();
const after = (actual[name] ?? []).flat();
const sameTables =
JSON.stringify(expected[name] ?? []) === JSON.stringify(actual[name] ?? []);
if (sameTables) continue;
const removed = before.filter((line) => !after.includes(line));
const added = after.filter((line) => !before.includes(line));
for (const line of removed) differences.push(`§${name} -${line}`);
for (const line of added) differences.push(`§${name} +${line}`);
if (removed.length === 0 && added.length === 0) {
differences.push(`§${name} the same rows, split into tables or ordered differently`);
}
}
return Object.freeze(differences);
}