diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 031ae443..fc962ae0 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -639,7 +639,8 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature 기능 폴더를 가리키는 커버리지 정책 행, owner가 기능 ID인 증거 정책 행을 지움 → 레지스트리 기준선을 다시 찍음 (빼는 변경은 breaking이라서) → 타입·아키텍처·레지스트리·테스트·커버리지·CI 계약·빌드 게이트 - → src와 tests에 기능 ID나 폴더 이름이 남았는지 찾음 + → 지운 기능을 가리키는 파일이 남았는지 찾음 + (src: 기능 ID·폴더 이름을 담은 파일, tests: 이름에 기능 ID가 있거나 기능 폴더에서 import하는 파일) ``` ① **정할 것**: 없음. 확인 단계다. @@ -651,9 +652,10 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature ③ **잡는 검사 / 못 잡는 것** -- 남은 파일이 기능 ID나 폴더 이름을 담고 있으면 실패한다. +- 남은 파일이 지운 기능을 가리키면 실패한다. `src`는 기능 ID나 폴더 이름을 담은 파일, `tests`는 이름에 기능 ID가 있거나 기능 폴더에서 import하는 파일이다. - 메시지: ` removal failed:` 다음 줄 `fixture-id-residue: residue: ` -- **못 잡음**: 기능 ID를 담지 않은 폴더 밖 파일. 예: route ID만 적은 e2e spec, `artifacts/tests/a11y-manual/.md`. 드릴은 `src`와 `tests`만 찾고, a11y 기록은 남아도 검사가 실패하지 않는다. + - 템플릿 테스트가 예시 ID(`invoice-feature` 등)를 데이터로 쓰는 것은 잔여로 세지 않는다(1105/16-04). 그래서 매뉴얼 예시 이름으로 만든 기능도 이 단계를 통과한다. +- **못 잡음**: 기능을 가리키지 않는 폴더 밖 파일. 예: route ID만 적은 e2e spec, `artifacts/tests/a11y-manual/.md`. `tests` 안에서 기능 ID를 글자로만 적은 테스트도 잔여로 세지 않는다. 그 테스트가 지운 기능에 기대면 같은 드릴의 `test:all`이 실패한다. 드릴은 `src`와 `tests`만 찾고, a11y 기록은 남아도 검사가 실패하지 않는다. ④ **쓸 스킬**: `documentation-and-adrs`, `deprecation-and-migration` diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index c0461617..d1b3ed55 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -194,6 +194,6 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | 메시지 | 원인 | 고칠 곳 | |---|---|---| -| ` removal failed:` 다음 `fixture-id-residue: residue: ` (`test:sample-removal`) | 기능을 지운 뒤에도 `src`·`tests`에 기능 ID를 담은 파일이 남았다 | 그 파일을 기능 폴더 안으로 옮기거나, 기능 ID를 담지 않게 한다 | +| ` removal failed:` 다음 `fixture-id-residue: residue: ` (`test:sample-removal`) | 기능을 지운 뒤에도 그 기능을 가리키는 파일이 남았다. `src`는 기능 ID나 폴더 이름을 담은 파일, `tests`는 이름이 기능 ID를 담거나 기능 폴더(`src/features//`, `tests/features//`)에서 import하는 파일이다 | 그 파일을 기능 폴더 안으로 옮기거나, 기능을 가리키지 않게 한다. 목록에 템플릿 파일이 나오면 템플릿 결함이다. 그 파일을 고치지 말고 템플릿에 알린다 | | `No installed feature declares FEATURE_MODULE_ID ""` | `--feature=`에 없는 기능 ID | 명령 인자 | | `feature scaffold failed:` 다음 `: ` (`test:feature-scaffold`) | 생성한 기능이 게이트 하나를 통과하지 못했다 | `scripts/create-feature.ts`의 템플릿. 제품 팀이 아니라 템플릿을 고칠 일이다 | diff --git a/scripts/lib/feature-residue.ts b/scripts/lib/feature-residue.ts new file mode 100644 index 00000000..2bcfc934 --- /dev/null +++ b/scripts/lib/feature-residue.ts @@ -0,0 +1,62 @@ +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; + +/** + * 1105/16-04. What a product feature leaves behind after + * `test:sample-removal -- --feature=` deleted its folders, in the copy the + * drill made. + * + * - `src/`: any file whose path or text still names the feature ID or its + * folder. Platform source never names a product feature, so a name left + * there is a reference the type checker cannot see (a catalog key, a + * runtime override, a link). + * - `tests/`: a file named after the feature, or one that imports from the + * feature's `src/features//` or `tests/features//`. The test + * text is not searched for the bare name: the template's own tests use + * example IDs as data (`tests/unit/create-feature.test.ts` writes + * `invoice-feature`, the manual's example, 51 times), and the drill flagged + * them as residue of a product feature that took that name. A test that + * still depends on the removed feature fails `test:all`, which the drill + * runs. + * + * The reference sample keeps its own, wider pattern in + * scripts/test-sample-removal.ts: the template owns all of its files. + */ +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); +} + +async function filesUnder(directory: string): Promise { + const entries = await readdir(directory, { withFileTypes: true }).catch(() => []); + const nested = await Promise.all( + entries.map((entry) => { + const target = path.join(directory, entry.name); + return entry.isDirectory() ? filesUnder(target) : Promise.resolve([target]); + }), + ); + return nested.flat(); +} + +export async function productFeatureResidue( + root: string, + featureId: string, + directory: string, +): Promise { + const names = [...new Set([featureId, directory])].map(escapeRegExp).join("|"); + const named = new RegExp(names, "iu"); + const imported = new RegExp( + String.raw`(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\bmock\s*\(\s*)["'][^"'\n]*/features/(?:${names})/`, + "u", + ); + const residue: string[] = []; + const relative = (file: string) => path.relative(root, file).split(path.sep).join("/"); + for (const file of await filesUnder(path.join(root, "src"))) { + const name = relative(file); + if (named.test(`${name}\n${await readFile(file, "utf8")}`)) residue.push(name); + } + for (const file of await filesUnder(path.join(root, "tests"))) { + const name = relative(file); + if (named.test(name) || imported.test(await readFile(file, "utf8"))) residue.push(name); + } + return residue.sort(); +} diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index 2fe4c041..d8e9e69a 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -11,6 +11,7 @@ import path from "node:path"; import { ROUTE_FEATURE_OWNER } from "../src/features/installed-feature-contracts.ts"; import { createFileSystemDeclarationSource } from "./generate-product-feature-index.ts"; +import { productFeatureResidue } from "./lib/feature-residue.ts"; import { isProductionModulePath } from "./lib/risk-coverage.ts"; import { createRemovalFixtureRoot, @@ -415,14 +416,20 @@ try { await regenerateRemovalFixtureWorkflow(fixtureRoot); const residue: string[] = []; - for (const root of ["src", "tests"]) { - for (const file of await filesBelow(path.join(fixtureRoot, root))) { - const relative = path.relative(fixtureRoot, file); - const content = await readFile(file, "utf8"); - if (extras.residue.test(`${relative}\n${content}`)) { - residue.push(relative); + if (isSample) { + for (const root of ["src", "tests"]) { + for (const file of await filesBelow(path.join(fixtureRoot, root))) { + const relative = path.relative(fixtureRoot, file); + const content = await readFile(file, "utf8"); + if (extras.residue.test(`${relative}\n${content}`)) { + residue.push(relative); + } } } + } else { + // 1105/16-04. Template tests use example feature IDs as data; only what + // still points at the removed feature counts (scripts/lib/feature-residue.ts). + residue.push(...(await productFeatureResidue(fixtureRoot, featureId, located.directory))); } const missingCommonTests: string[] = []; diff --git a/tests/unit/feature-residue.test.ts b/tests/unit/feature-residue.test.ts new file mode 100644 index 00000000..7ebbeff4 --- /dev/null +++ b/tests/unit/feature-residue.test.ts @@ -0,0 +1,73 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterAll, describe, expect, it } from "vitest"; + +import { productFeatureResidue } from "../../scripts/lib/feature-residue.ts"; + +/** + * 1105/16-04. The manual's example ID is `invoice-feature` (01 1단계), and + * its step 11 removes that feature with + * `test:sample-removal -- --feature=invoice-feature`. The drill searched every + * file under `src` and `tests` for the ID as a substring, so the template's + * own tests/unit/create-feature.test.ts, which writes that example ID 51 + * times as data, failed the removal (`fixture-id-residue`), and the advice + * was to edit that template file. + */ +const ID = "invoice-feature"; +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function fixture(files: Readonly>): Promise { + const root = await mkdtemp(path.join(tmpdir(), "feature-residue-")); + roots.push(root); + for (const [file, content] of Object.entries(files)) { + await mkdir(path.dirname(path.join(root, file)), { recursive: true }); + await writeFile(path.join(root, file), content); + } + return root; +} + +// Built at run time so this file does not itself read as an import of the +// feature when the repository is searched below. +const importOf = (target: string) => ["import { x } from", JSON.stringify(target)].join(" "); + +describe("product feature residue (1105/16-04)", () => { + it("does not count the template's own tests that name the manual's example ID", async () => { + expect(await productFeatureResidue(process.cwd(), ID, ID)).toEqual([]); + }); + + it("counts what still points at the removed feature", async () => { + const root = await fixture({ + "src/contracts/leftover.ts": `export const OWNER = "${ID}";\n`, + "src/platform/clean.ts": "export const NOTHING = 1;\n", + [`tests/e2e/${ID}.spec.ts`]: "test('opens', () => {});\n", + "tests/unit/imports-feature.test.ts": `${importOf(`../../src/features/${ID}/feature-module.ts`)};\n`, + "tests/unit/imports-feature-tests.test.ts": `${importOf(`../features/${ID}/helpers.ts`)};\n`, + "tests/unit/example-data.test.ts": `const request = { id: "${ID}" };\nconst path = "src/features/${ID}/feature-module.ts";\n`, + }); + + expect(await productFeatureResidue(root, ID, ID)).toEqual([ + "src/contracts/leftover.ts", + `tests/e2e/${ID}.spec.ts`, + "tests/unit/imports-feature-tests.test.ts", + "tests/unit/imports-feature.test.ts", + ]); + }); + + it("matches the folder name as well as the ID", async () => { + const root = await fixture({ + "src/contracts/leftover.ts": 'export const DIRECTORY = "invoices";\n', + "tests/unit/x.test.ts": `${importOf("../../src/features/invoices/index.ts")};\n`, + }); + + expect(await productFeatureResidue(root, ID, "invoices")).toEqual([ + "src/contracts/leftover.ts", + "tests/unit/x.test.ts", + ]); + }); +});