Files
clean-architecture-frontend…/scripts/check-backend-contract-drift.ts
T
DongHyeonka ba2b4f4c6d feat(contracts): 짝 백엔드 계약 기준점을 기계가 읽는 pin과 답 표로 둔다
문제
짝 백엔드 계약의 기준 커밋은 계약 문서의 문장(백엔드 5786126c)뿐이고, 이
SHA를 읽는 코드·설정·테스트가 없다. 쓰기 전 거절 표 REFUSED_BEFORE_WRITE와
5xx 판정은 백엔드 http-contract.md §2를 손으로 옮긴 것이다. 리뷰 중 백엔드에
bbe944bd가 들어와 503 IDEMPOTENCY_COMPLETION_UNKNOWN이 새로 생겼는데 프론트의
어떤 검사도 알리지 않았다(README 10.6).

고른 방법 (결정 D6 (1)+(2))
- config/contracts/backend-contract-pin.json: repo, 전체 SHA(bbe944bd), 대조한
  문서와 절(§1·§2·§4), 프론트 쪽 계약 절·판정 파일, 담당.
- config/contracts/backend-idempotency-answers.json: 백엔드 §2 표 여섯 행과
  §4 REQUEST_TIMEOUT을 code·status·쓰기 전 거절·같은 키 재전송 열로 옮겼다.
  백엔드가 문서에 적은 사실만 담는다.
- tests/unit/backend-contract-pin.test.ts: 두 JSON의 모양과 같은 SHA를
  확인하고, 답마다 프론트 판정이 그 두 열에서 나오는 값인지(쓰기 전 거절이면서
  같은 키 재전송이 아니면 NOT_APPLIED, 아니면 MAYBE_APPLIED, 자동 재전송은
  둘 다 참일 때만) 본다. 반대로 프론트 표의 행이 모두 이 답 표나 6.1절
  읽기(VALIDATION_FAILED)로 뒷받침되는지 본다. 그래서 백엔드 표에 행이
  늘거나 status가 바뀐 JSON을 넣으면 실패한다.
- scripts/check-backend-contract-drift.ts(check:backend-contract-drift):
  형제 디렉터리(또는 --backend)의 백엔드 checkout이 pin 뒤에 http-contract.md를
  바꿨는지 알리고 바뀐 표 행을 보인다. CI에는 백엔드가 없어 게이트 밖이다.
  ungated-scripts.json에 이유를 적었다.
- 계약 문서 4.1·6절의 기준 커밋을 bbe944bd와 pin 파일로 옮겼다. 6.1절 표는
  5786126c..bbe944bd 사이 바뀐 백엔드 파일 다섯을 다시 읽었다. 판정은 같고
  줄 번호만 옮겼다(IdempotencyExecutor, GlobalExceptionHandler →
  HttpStatusErrorCodes, FailureCategory, PersistenceExceptionTranslator).

버린 대안
- 백엔드 error-codes.yaml과 문서 다이제스트를 기록: 다이제스트는 바뀐 것만
  알리고 무엇을 고칠지 말하지 않는다.
- 백엔드가 계약 패키지를 발행: 백엔드 빌드에 JS 발행이 생긴다. 지금 규모에는
  pin과 표가 작다.

위험·한계
- 답 표 JSON은 사람이 백엔드 문서에서 옮긴다. 옮기는 실수는 drift 스크립트와
  리뷰가 잡는다. 백엔드 쪽이 같은 JSON을 자기 레지스트리와 대조하는 일은
  백엔드 저장소 몫이다.
- 백엔드 HEAD는 이미 pin 뒤로 갔다(지금 c508b1ba). http-contract.md §2의 500
  IDEMPOTENCY_RECOVERY_REQUIRED 행이 "같은 키 재전송은 안전하다"로 바뀌었다.
  프론트 판정(MAYBE_APPLIED, 자동 재전송 없음, 사용자 재전송은 같은 키)은 그
  문장과도 맞는다. pin은 지시대로 bbe944bd에 두었다.

검증
- 새 테스트 10건 통과. 변이 4종 검출: 답 표에 503 새 code 행 추가, 프론트
  표에서 COMPLETION_UNKNOWN 제거, 프론트 표에 근거 없는 400 BAD_PARAMETER
  추가, 답 표의 RECOVERY_REQUIRED status 변경.
- check:backend-contract-drift: worktree에서 skipped(exit 0), 실제 백엔드
  checkout으로 exit 1과 바뀐 RECOVERY_REQUIRED 행 출력.
- test:unit 178파일 2,645건, check:ci, check:types, eslint,
  verify:documentation 통과.

Refs: docs/reviews/2026-11-03-maturity-review/12-guardrails-ci.md 12-06
Refs: docs/reviews/2026-11-03-maturity-review/README.md 10.6
2026-11-04 21:03:40 +09:00

84 lines
3.1 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
/**
* 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.
*
* corepack pnpm check:backend-contract-drift [--backend <dir>]
*
* 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.
*/
type Pin = Readonly<{
backend: Readonly<{ repository: string; commit: string; document: string }>;
}>;
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 main(): void {
const pin = JSON.parse(readFileSync(PIN_PATH, "utf8")) as Pin;
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>)`,
);
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`,
);
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)}`);
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() === "") {
console.log(
`Backend contract drift: HEAD ${headCommit.slice(0, 12)} is past the pin ${commit.slice(0, 12)}, ${document} unchanged`,
);
return;
}
console.error(
`Backend contract drift: ${document} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}.`,
);
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;
}
main();