From f600e6b132103811e9953399ea1c7a4c6baa57fa Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:23:47 +0900 Subject: [PATCH] =?UTF-8?q?fix(contracts):=20=EC=A7=9D=20=EB=B0=B1?= =?UTF-8?q?=EC=97=94=EB=93=9C=20pin=EA=B3=BC=20drift=20=EA=B2=80=EC=82=AC?= =?UTF-8?q?=EA=B0=80=20=EC=83=9D=EC=84=B1=EA=B8=B0=20=ED=85=9C=ED=94=8C?= =?UTF-8?q?=EB=A6=BF=20=EC=82=AC=EC=8B=A4=EB=8F=84=20=EB=8C=80=EC=A1=B0?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: create:feature --with-create가 백엔드 생성기 템플릿의 사실 넷을 프론트 문자열로 옮겼다. 경로 복수형(scripts/new-feature.sh), 이름 상한 100 (__Feature__.java.tmpl NAME_MAX_LENGTH), 오류 code _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 --- config/contracts/backend-contract-pin.json | 34 +++++++- .../backend-api-and-server-state-contract.md | 5 ++ scripts/check-backend-contract-drift.ts | 44 +++++++++-- scripts/create-feature-write-slice.ts | 6 ++ tests/unit/backend-contract-drift.test.ts | 79 +++++++++++++++++-- tests/unit/backend-contract-pin.test.ts | 44 +++++++++++ 6 files changed, 196 insertions(+), 16 deletions(-) diff --git a/config/contracts/backend-contract-pin.json b/config/contracts/backend-contract-pin.json index 77f0a234..451e7786 100644 --- a/config/contracts/backend-contract-pin.json +++ b/config/contracts/backend-contract-pin.json @@ -4,7 +4,39 @@ "repository": "clean-architecture-backend-template", "commit": "45d2a478b800586f1d84151723629a560265d58e", "document": "docs/web/http-contract.md", - "sectionsCompared": ["1", "2", "4"] + "sectionsCompared": ["1", "2", "4"], + "scaffoldSources": [ + { + "path": "scripts/new-feature.sh", + "fact": "path segment: camel-case name plus es, ies or s", + "copiedTo": { "file": "scripts/create-feature.ts", "symbol": "backendPathSegment" } + }, + { + "path": "scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl", + "fact": "NAME_MAX_LENGTH 100", + "copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "BACKEND_NAME_MAX_LENGTH" } + }, + { + "path": "scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__ErrorCode.java.tmpl", + "fact": "error codes _INVALID and _NOT_FOUND", + "copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "invalidCode" } + }, + { + "path": "scripts/feature-scaffold/templates/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__ControllerTest.java.tmpl", + "fact": "400 _INVALID and 404 _NOT_FOUND bodies", + "copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "notFoundCode" } + }, + { + "path": "scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__Controller.java.tmpl", + "fact": "POST / answers 201, GET //{id} reads one", + "copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "renderWriteDescriptors" } + }, + { + "path": "scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__UseCase.java.tmpl", + "fact": "permission, then name check, then the write: refused before the write", + "copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "refusedBeforeWrite" } + } + ] }, "frontend": { "contractDocument": "docs/architecture/backend-api-and-server-state-contract.md", diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index d77b614d..2d3a0391 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -184,6 +184,11 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정 비교하고, pin 뒤 백엔드 HEAD에서 바뀐 표 행을 알린다. 1은 어긋남, 2는 비교하지 못함(통과가 아니다)이다. 짝 백엔드를 새로 받을 때마다 돌린다. pin을 올릴 때는 `--write-excerpt`가 사본을 pin 커밋에서 다시 옮긴다. +- `create:feature --with-create`는 백엔드 생성기 템플릿의 사실 넷(경로 복수형, + 이름 상한 100, 오류 code, 검사 순서)을 생성기 문자열로 옮겼다. 그 파일들은 + pin의 `backend.scaffoldSources`에 있고, 각 항목이 옮긴 곳(프론트 파일과 + 이름)을 적는다. drift 검사는 pin 뒤 HEAD에서 이 파일들이 바뀌었는지도 보고, + 바뀐 파일마다 다시 볼 프론트 위치를 말하며 1로 끝난다(1105/16-02). - 프론트에서 Envelope를 읽는 곳: `src/adapters/http/backend-envelope.ts`(스키마와 해석). V3 실행기는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때 쓴다. `create:feature`가 만든 기능은 이 값을 선언한다. 참조 기능은 선언하지 않고 diff --git a/scripts/check-backend-contract-drift.ts b/scripts/check-backend-contract-drift.ts index c5aa78af..59538215 100644 --- a/scripts/check-backend-contract-drift.ts +++ b/scripts/check-backend-contract-drift.ts @@ -18,25 +18,41 @@ import { * 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. + * 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 ] [--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. + * 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/`) 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 }>; + backend: Readonly<{ + repository: string; + commit: string; + document: string; + scaffoldSources?: readonly ScaffoldSource[]; + }>; tables: Readonly<{ idempotencyAnswers: string; backendExcerpt: string }>; notCopied: readonly NotCopiedRow[]; }>; @@ -86,6 +102,7 @@ function main(): void { const pin = readJson(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 . test:unit holds the answer table to ${pin.tables.backendExcerpt}, and only this script holds that copy to the backend.`, @@ -149,20 +166,31 @@ function main(): void { 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} unchanged; 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} and ${PIN_PATH} together.`, + `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; } diff --git a/scripts/create-feature-write-slice.ts b/scripts/create-feature-write-slice.ts index 558967c5..ba02043d 100644 --- a/scripts/create-feature-write-slice.ts +++ b/scripts/create-feature-write-slice.ts @@ -14,6 +14,12 @@ * `--keyed` is for a backend create made KEYED with its IdempotencyExecutor * (its docs/manual/05-idempotency.md). Like the rest of the command, nothing * here imports a sample feature. + * + * 1105/16-02. The backend scaffold facts copied here (name limit, error + * codes, 201 and the endpoints, the check order behind refusedBeforeWrite) + * and the path rule in create-feature.ts are listed with their backend + * files in config/contracts/backend-contract-pin.json `scaffoldSources`; + * `check:backend-contract-drift` says when one of those files changes. */ export type WriteSemantics = "NEVER" | "KEYED"; diff --git a/tests/unit/backend-contract-drift.test.ts b/tests/unit/backend-contract-drift.test.ts index de2144d0..343276e1 100644 --- a/tests/unit/backend-contract-drift.test.ts +++ b/tests/unit/backend-contract-drift.test.ts @@ -98,9 +98,30 @@ function git(cwd: string, ...args: string[]): string { return result.stdout.trim(); } -async function commitDocument(backend: string, text: string, message: string): Promise { - await mkdir(path.join(backend, "docs/web"), { recursive: true }); - await writeFile(path.join(backend, "docs/web/http-contract.md"), text); +const DOCUMENT = "docs/web/http-contract.md"; +/** + * 1105/16-02. One of the backend scaffold files `create:feature + * --with-create` copies a fact from (the aggregate's name limit). + */ +const AGGREGATE = + "scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl"; +const SCAFFOLD_SOURCES = [ + { + path: AGGREGATE, + fact: "NAME_MAX_LENGTH 100", + copiedTo: { file: "scripts/create-feature-write-slice.ts", symbol: "BACKEND_NAME_MAX_LENGTH" }, + }, +]; + +async function commitFiles( + backend: string, + files: Readonly>, + message: string, +): Promise { + for (const [file, text] of Object.entries(files)) { + await mkdir(path.dirname(path.join(backend, file)), { recursive: true }); + await writeFile(path.join(backend, file), text); + } git(backend, "add", "--all"); git(backend, "commit", "--quiet", "--no-gpg-sign", "--no-verify", "-m", message); return git(backend, "rev-parse", "HEAD"); @@ -113,6 +134,10 @@ async function drift( notCopied?: typeof NOT_COPIED; /** The document of a backend commit after the pin. */ head?: string; + /** 1105/16-02. The scaffold aggregate template in that later commit. */ + scaffoldHead?: string; + /** 1105/16-02. A file the pin does not name, in that later commit. */ + otherHead?: string; /** Where the script looks for the backend instead of the fake one. */ backend?: string; flags?: readonly string[]; @@ -122,13 +147,26 @@ async function drift( const backend = await mkdtemp(path.join(tmpdir(), "drift-backend-")); directories.push(root, backend); git(backend, "init", "--quiet", "--initial-branch=fixture"); - const commit = await commitDocument(backend, contractDocument(SECTIONS), "pinned"); - if (options.head !== undefined) await commitDocument(backend, options.head, "after the pin"); + const commit = await commitFiles( + backend, + { + [DOCUMENT]: contractDocument(SECTIONS), + [AGGREGATE]: "public static final int NAME_MAX_LENGTH = 100;\n", + "README.md": "backend\n", + }, + "pinned", + ); + const later = { + ...(options.head === undefined ? {} : { [DOCUMENT]: options.head }), + ...(options.scaffoldHead === undefined ? {} : { [AGGREGATE]: options.scaffoldHead }), + ...(options.otherHead === undefined ? {} : { "README.md": options.otherHead }), + }; + if (Object.keys(later).length > 0) await commitFiles(backend, later, "after the pin"); const source = { repository: "clean-architecture-backend-template", commit, - document: "docs/web/http-contract.md", + document: DOCUMENT, }; const write = async (file: string, value: unknown) => { await mkdir(path.dirname(path.join(root, file)), { recursive: true }); @@ -136,7 +174,7 @@ async function drift( }; await write("config/contracts/backend-contract-pin.json", { schemaVersion: 1, - backend: { ...source, sectionsCompared: ["1", "2", "4"] }, + backend: { ...source, sectionsCompared: ["1", "2", "4"], scaffoldSources: SCAFFOLD_SOURCES }, frontend: { contractDocument: "docs/architecture/backend-api-and-server-state-contract.md", contractSections: ["4.1", "6", "6.1"], @@ -265,3 +303,30 @@ describe("check:backend-contract-drift (1105/07-01)", () => { expect((await result.readExcerpt()).sections).toEqual(SECTIONS); }); }); + +/** + * 1105/16-02. `create:feature --with-create` copies four facts from the + * paired backend's feature scaffold (path plural rule, name limit 100, error + * codes, check order). The pin and this script covered only + * `docs/web/http-contract.md`, so a backend that changed its scaffold left + * the frontend generator writing another path, limit or code with no signal. + */ +describe("check:backend-contract-drift scaffold sources (1105/16-02)", () => { + it("reports a scaffold source the generator copies from, with where the copy is", async () => { + const result = await drift({ scaffoldHead: "public static final int NAME_MAX_LENGTH = 120;\n" }); + + expect(result.status, result.stdout + result.stderr).toBe(1); + expect(result.stderr).toContain(`scaffold source ${AGGREGATE} changed`); + expect(result.stderr).toContain( + "recheck BACKEND_NAME_MAX_LENGTH in scripts/create-feature-write-slice.ts", + ); + }); + + it("passes a later backend commit that changed neither the document nor a scaffold source", async () => { + const result = await drift({ otherHead: "backend, later\n" }); + + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + expect(result.stdout).toContain("1 scaffold sources unchanged"); + }); +}); diff --git a/tests/unit/backend-contract-pin.test.ts b/tests/unit/backend-contract-pin.test.ts index 34dc1ea7..2f5c01c1 100644 --- a/tests/unit/backend-contract-pin.test.ts +++ b/tests/unit/backend-contract-pin.test.ts @@ -38,6 +38,20 @@ const pinSchema = z commit: z.string().regex(COMMIT), document: z.string().min(1), sectionsCompared: z.array(z.string().min(1)).min(1), + // 1105/16-02. Backend scaffold files the generator copies facts from. + scaffoldSources: z + .array( + z + .object({ + path: z.string().min(1), + fact: z.string().min(1), + copiedTo: z + .object({ file: z.string().min(1), symbol: z.string().min(1) }) + .strict(), + }) + .strict(), + ) + .min(1), }) .strict(), frontend: z @@ -163,6 +177,36 @@ describe("paired backend contract pin", () => { expect(answerTableProblems(table.answers, pin.notCopied, rows)).toEqual([]); }); + /** + * 1105/16-02. The `--with-create` slice copies the backend scaffold's path + * rule, name limit, error codes and check order. Each copy names the + * backend file it came from, so check:backend-contract-drift can say which + * frontend line to recheck when that file changes. + */ + it("names the backend scaffold file behind each fact the generator copies", () => { + const paths = pin.backend.scaffoldSources.map((source) => source.path); + expect(new Set(paths).size).toBe(paths.length); + for (const source of pin.backend.scaffoldSources) { + expect(readFileSync(source.copiedTo.file, "utf8"), source.path).toContain( + source.copiedTo.symbol, + ); + } + const copiedFiles = new Set(pin.backend.scaffoldSources.map((source) => source.copiedTo.file)); + expect([...copiedFiles].sort()).toEqual([ + "scripts/create-feature-write-slice.ts", + "scripts/create-feature.ts", + ]); + expect(paths).toEqual( + expect.arrayContaining([ + "scripts/new-feature.sh", + expect.stringMatching(/\/__Feature__\.java\.tmpl$/u), + expect.stringMatching(/\/__Feature__ErrorCode\.java\.tmpl$/u), + expect.stringMatching(/\/__Feature__Controller\.java\.tmpl$/u), + expect.stringMatching(/\/Create__Feature__UseCase\.java\.tmpl$/u), + ]), + ); + }); + it("copies each backend answer once", () => { const keys = table.answers.map((answer) => `${answer.status} ${answer.code}`); expect(new Set(keys).size).toBe(keys.length);