Files
clean-architecture-frontend…/tests/unit/deletable-history-documents.test.ts
DongHyeonka 2816a42f66 test(layout): 이력 문서 검사가 목록 대신 git의 코드·설정 파일을 본다
「지워도 되는 문서를 읽지 않는다」 검사가 손으로 관리하는 history-free
목록만 훑어, Playwright 설정 다섯 개와 Service Worker 빌드 설정,
.storybook이 이력 문서를 읽어도 통과한다.

git이 무시하지 않는 파일 가운데 확장자 목록에 든 것에서 문서·이력·
추적하지 않는 항목만 빼고 본다. history-free 목록은 검사가 꼭 닿아야
하는 루트로 남긴다. 목록에 손으로 더하는 안은 새 파일이 또 빠져서
쓰지 않는다. git ls-files에는 64 MiB 출력 한도와 자기 기한을 준다.
docs-system의 treeFiles는 git이 실패하면 조용히 폴더 순회로 넘어가고
기한이 없어 쓰지 않는다.

새로 보게 된 py 문서 검사기와 그 시험은 폴더 이름을 적은 다섯 줄만
빼고, 맞지 않는 예외는 실패시킨다. 원래 빼던 TS 검사기와 그 시험은
파일째 남는다. git이 무시하는 파일, 목록 밖 확장자(txt 등)와 확장자
없는 파일(Dockerfile 제외)은 보지 않는다.

검증: playwright.visual 설정과 py 검사기에 이력 문서 읽기를 넣으면
실패한다. 1 MiB를 넘는 목록도 읽는다. timeout 값은 desktop test:unit·
coverage 묶음 실측 최장 2145 ms(부하 12~16)에서 얻었다.

Refs: REV-FE-0019
2026-11-22 21:28:49 +09:00

269 lines
11 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
parseRepositoryLayout,
REPOSITORY_LAYOUT,
selectRepositoryEntries,
type RepositoryLayoutEntry,
} from "../../scripts/lib/repository-layout.ts";
import {
childProcessTimeout,
DEFAULT_TEST_TIMEOUT_MS,
} from "../helpers/child-process-timeout.ts";
/**
* README.md, 「복사한 뒤 지워도 되는 것」, tells a new project that
* the build and the gates read none of the history documents except
* `docs/reviews/adapters/INVENTORY.md`. The removal fixtures rely on the same
* promise: they do not copy `docs/`. A test that opens a review document broke
* all three removal checks (fix of 11-04), so the promise is checked here.
* The root instruction files left the list on 2026-11-07: they are the
* template's contract, which a copy keeps (template-contract-documents.test.ts).
*/
// The scan follows git's files. config/repository-layout.json says which root
// items hold no code, and its history-free set is what the scan has to reach
// (R2). The registry itself names every root item, history documents included
// (R1); naming a root item is not reading it.
const NOT_CODE_KINDS: ReadonlySet<string> = new Set(["document", "history", "untracked"]);
const CODE_FILE = /(?:\.(?:[cm]?[jt]sx?|json|ya?ml|py|sh|css|html|conf)|Dockerfile)$/u;
// The longest of the tests that list the files, on desktop 2026-11-22 under
// load 12 to 16: 2145 ms in test:unit, 352 ms in test:coverage's suites.
const SCAN_TIMEOUT = childProcessTimeout(2_145);
const LAYOUT_REGISTRY = "config/repository-layout.json";
// Built from pieces so that this file does not match itself.
const REVIEWS = ["docs", "reviews", ""].join("/");
const HISTORY = ["docs", "history"].join("/");
const KEPT = `${REVIEWS}adapters/INVENTORY.md`;
// The 2026-09-25 round's task folder moved into the history folder on
// 2026-11-07 (docs/README.md §3), so the history pattern covers it. A pattern
// for the old root folder would now only catch a product's own route or
// folder of that name.
const DELETABLE = [
new RegExp(`${REVIEWS}(?!adapters/INVENTORY\\.md)`, "u"),
new RegExp(["docs", "superpowers"].join("/"), "u"),
new RegExp(HISTORY, "u"),
new RegExp(`\\b${"SPEC"}\\.md\\b`, "u"),
];
/**
* 1101/14-01. A section number without a document name cannot be followed,
* and the scale design it meant used to live only in the history bundle a
* copy deletes. Cite it as `scale-architecture.md §N`
* (docs/architecture/scale-architecture.md, a current contract).
*/
const UNNAMED_SECTION = new RegExp(`\\b${"spec"} ?§`, "iu");
function scannedFiles(
listed: readonly string[],
layout: readonly RepositoryLayoutEntry[] = REPOSITORY_LAYOUT,
): string[] {
const skipped = new Set(
layout.filter(({ kind }) => NOT_CODE_KINDS.has(kind)).map((entry) => entry.path),
);
return listed.filter((file) => CODE_FILE.test(file) && !skipped.has(file.split("/")[0]!));
}
/** Without the GIT_* a hook sets, which would point git at another repository. */
function ownRepositoryEnvironment(): NodeJS.ProcessEnv {
return Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_")));
}
/** Tracked files, and new ones git does not ignore: a file counts before `git add`. */
function repositoryFiles(root = "."): string[] {
const listed = spawnSync(
"git",
["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
{
cwd: root,
encoding: "utf8",
env: ownRepositoryEnvironment(),
// Shorter than the test's own timeout, so a git that hangs fails as itself.
timeout: DEFAULT_TEST_TIMEOUT_MS,
killSignal: "SIGKILL",
// As treeFiles in scripts/lib/docs-system.ts: the list grows with files the scan skips.
maxBuffer: 64 * 1024 * 1024,
},
);
if (listed.error || listed.status !== 0) {
throw new Error(`git ls-files failed: ${listed.error?.message ?? listed.stderr}`);
}
// A tracked file deleted in the work tree is still listed.
return listed.stdout.split("\0").filter((file) => file !== "" && existsSync(path.join(root, file)));
}
/**
* The document checker (docs/README.md 「5. 문서 검사」) names the record
* folders to read the head block of whatever records are there and nothing
* else of them. A copy that deleted them passes it ("passes a copy that
* deleted its history" in its test), so it is not a reader this promise is
* about.
*/
const RECORD_FOLDER_CHECKERS: ReadonlySet<string> = new Set([
"scripts/lib/docs-system.ts",
"tests/unit/docs-system.test.ts",
]);
/**
* scripts/check-work-docs.py repeats that checker's folder lists
* (TypeScriptRulesTest in its test keeps the two equal), and its test writes
* records in a temporary repository. These lines are excused, not the files:
* another line there that names a history document may well read it.
*/
const RECORD_FOLDER_LINES: readonly Readonly<{ file: string; text: string }>[] = [
{
file: "scripts/check-work-docs.py",
text: `RECORD_FOLDERS = ("docs/design/", "${HISTORY}/", "${REVIEWS}")`,
},
{
file: "scripts/check-work-docs.py",
text: `RECORD_KINDS = ("docs/design/", "${HISTORY}/plans/", "${HISTORY}/evidence/", "${HISTORY}/packages/",`,
},
{
file: "scripts/check-work-docs.py",
text: `"${HISTORY}/study/", "docs/adr/")`,
},
{
file: "scripts/tests/test_check_work_docs.py",
text: `("${HISTORY}/old.md", f"\\n\`{deleted}\`\\n"),`,
},
{
file: "scripts/tests/test_check_work_docs.py",
text: `("${REVIEWS}old-review.md", f"\\n\`{deleted}\`\\n"),`,
},
];
type Match = Readonly<{ file: string; line: number; text: string }>;
function matchingLines(file: string, content: string, patterns: readonly RegExp[]): Match[] {
return content
.split("\n")
.map((text, index) => ({ file, line: index + 1, text: text.trim() }))
.filter(({ text }) => patterns.some((pattern) => pattern.test(text)));
}
function unexcused(matches: readonly Match[]): Match[] {
return matches.filter(
({ file, text }) =>
!RECORD_FOLDER_CHECKERS.has(file) &&
!RECORD_FOLDER_LINES.some((line) => line.file === file && line.text === text),
);
}
async function linesMatching(patterns: readonly RegExp[]): Promise<Match[]> {
const matches: Match[] = [];
for (const file of scannedFiles(repositoryFiles())) {
if (file === LAYOUT_REGISTRY) continue;
matches.push(...matchingLines(file, await readFile(file, "utf8"), patterns));
}
return matches;
}
function locations(matches: readonly Match[]): string[] {
return matches.map(({ file, line }) => `${file}:${line}`);
}
describe("deletable history documents", () => {
// REV-FE-0019. A list kept by hand left out five Playwright configurations,
// the service worker build and .storybook/, so the scan follows the files.
it("are looked for in code and configuration that no list names", () => {
const layout = parseRepositoryLayout({
schemaVersion: 1,
entries: [
{ path: "app", kind: "source", role: "code", readBy: "build", sets: ["history-free"] },
{ path: "notes", kind: "document", role: "text", readBy: "people" },
{ path: "old-rounds", kind: "history", role: "records", readBy: "people" },
{ path: "local-output", kind: "untracked", role: "output", readBy: "tools", optional: true },
{ path: ".gallery", kind: "tool-convention", role: "gallery", readBy: "tools" },
{ path: "gallery.config.ts", kind: "tool-convention", role: "gallery", readBy: "tools" },
],
});
const read = [
"app/main.tsx",
"app/tool.py",
"app/run.sh",
"app/runner.Dockerfile",
"app/theme.css",
"app/index.html",
"app/proxy.conf",
".gallery/preview.tsx",
"gallery.config.ts",
"not-registered-yet.json",
];
const left = [
"app/README.md",
"app/logo.png",
"notes/table.json",
"old-rounds/evidence.ts",
"local-output/report.json",
];
expect(scannedFiles([...read, ...left], layout)).toEqual(read);
});
it("are looked for however long git's list of files is", () => {
const root = mkdtempSync(path.join(tmpdir(), "history-scan-"));
try {
// 1300 files under an 880 byte folder: a list just over Node's 1 MiB default.
const folder = Array.from({ length: 4 }, () => "f".repeat(219)).join("/");
const files = Array.from({ length: 1300 }, (_, index) => `${folder}/${index}.ts`).sort();
mkdirSync(path.join(root, folder), { recursive: true });
for (const file of files) writeFileSync(path.join(root, file), "");
const made = spawnSync("git", ["init", "--quiet"], {
cwd: root,
env: ownRepositoryEnvironment(),
timeout: DEFAULT_TEST_TIMEOUT_MS,
killSignal: "SIGKILL",
});
expect(made.status).toBe(0);
expect(Buffer.byteLength(files.join("\0"))).toBeGreaterThan(1024 * 1024);
expect(repositoryFiles(root).sort()).toEqual(files);
} finally {
rmSync(root, { recursive: true, force: true });
}
}, SCAN_TIMEOUT);
it("are excused in a work document checker by the line, not by the file", () => {
const named = `RECORD_FOLDERS = ("docs/design/", "${HISTORY}/", "${REVIEWS}")`;
const read = `text = (root / "${REVIEWS}round9.md").read_text()`;
const file = "scripts/check-work-docs.py";
const matches = matchingLines(file, [named, read].join("\n"), DELETABLE);
expect(locations(unexcused(matches))).toEqual([`${file}:2`]);
});
it("are looked for in each history-free root", () => {
const files = scannedFiles(repositoryFiles());
expect(files.length).toBeGreaterThan(0);
// A removal drill may delete an optional root, or leave it empty.
const unreached = selectRepositoryEntries("history-free").filter(
({ path: root, optional }) =>
!optional && !files.some((file) => file === root || file.startsWith(`${root}/`)),
);
expect(unreached, "roots the scan does not reach").toEqual([]);
}, SCAN_TIMEOUT);
it("are read by no code, test, script or configuration", async () => {
const found = await linesMatching(DELETABLE);
expect(locations(unexcused(found)), `only ${KEPT} may be read`).toEqual([]);
// A copy may lack the checker; an excuse is stale only where its file is.
expect(
RECORD_FOLDER_LINES.filter(
({ file, text }) =>
existsSync(file) && !found.some((match) => match.file === file && match.text === text),
),
"RECORD_FOLDER_LINES entries that match no line any more",
).toEqual([]);
}, SCAN_TIMEOUT);
it("are not cited as an unnamed design section", async () => {
expect(
locations(unexcused(await linesMatching([UNNAMED_SECTION]))),
"name the document: scale-architecture.md §N",
).toEqual([]);
}, SCAN_TIMEOUT);
});