Files
clean-architecture-frontend…/scripts/check-backend-contract-drift.ts
DongHyeonka f600e6b132 fix(contracts): 짝 백엔드 pin과 drift 검사가 생성기 템플릿 사실도 대조한다
문제: create:feature --with-create가 백엔드 생성기 템플릿의 사실 넷을
프론트 문자열로 옮겼다. 경로 복수형(scripts/new-feature.sh), 이름 상한 100
(__Feature__.java.tmpl NAME_MAX_LENGTH), 오류 code <FEATURE>_INVALID·
_NOT_FOUND(__Feature__ErrorCode·ControllerTest 템플릿), 201과 검사 순서
(Controller·Create__Feature__UseCase 템플릿)다. 그러나 pin
(config/contracts/backend-contract-pin.json)과 check:backend-contract-drift는
docs/web/http-contract.md(1105/07-01 뒤로는 그 문서의 표 사본과 답 표)만
본다. 백엔드가 템플릿을 바꾸면 생성 기능이 다른 경로·상한·code를 써도 아무
신호가 없다.

고른 방법: pin의 backend.scaffoldSources에 백엔드 템플릿 파일 여섯과 각
파일에서 옮긴 사실, 옮긴 프론트 위치(파일과 이름)를 적는다. drift 검사는
1105/07-01의 사본·답 표 대조와 종료 코드(0 일치, 1 어긋남, 2 비교 못 함)를
그대로 두고, pin 뒤 HEAD에서 이 파일들도 diff한다. 바뀐 파일마다 다시 볼
프론트 위치를 failures에 더해 exit 1한다. pin 단위 테스트는 각 항목의 프론트
이름이 실제로 그 파일에 있는지 본다. drift 단위 테스트는 07-01의 가짜 백엔드
fixture에 생성기 템플릿 파일 하나를 더하고, 그 파일이 바뀐 경우(exit 1, 프론트
위치 출력)와 pin이 이름 붙이지 않은 파일만 바뀐 경우(exit 0, "1 scaffold
sources unchanged")를 더한다. 07-01의 경우들은 그대로다. 계약 문서 4.1절과
생성기 머리 주석에 같은 내용을 적었다.
버린 대안: 백엔드가 생성기 사실을 JSON으로 내고 프론트가 읽기 — 두 repo를
바꿔야 한다(백엔드는 이번에 읽기만 한다).

위험·한계: drift 검사는 여전히 게이트 밖이고 형제 checkout이 있을 때만
돈다. 파일 단위 diff라 템플릿의 무관한 줄이 바뀌어도 알린다(사람이 다시
본다). pin의 commit(45d2a478)은 그대로다. 네 사실이 그 커밋과 같다는 대조는
리뷰(1105/16 영역)가 했고 이번에는 이름 상한만 다시 읽었다. 07-01과 같은
파일을 고쳐서 fix/r1105-contracts-core-sq 위에 다시 쌓았다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/backend-contract-drift.test.ts
tests/unit/backend-contract-pin.test.ts
corepack pnpm check:backend-contract-drift (desktop 형제 checkout 기준, 참고)

Refs: 1105/16-02
2026-11-06 01:23:48 +09:00

199 lines
7.9 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,
* 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 <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 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/<name>`) 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<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;
const scaffoldSources = pin.backend.scaffoldSources ?? [];
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)");
}
}
// 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();