Files
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

188 lines
6.5 KiB
TypeScript

/**
* 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);
}