Files
clean-architecture-frontend…/tests/unit/pr-gate-selection.test.ts
DongHyeonka 94f8434f85 ci(gates): FE-GATE-020을 merge 단계에서 main 단계로 옮긴다
문제:
프론트 PR 실행 p50이 17.7분으로 15분 목표를 넘고, 기능·scaffold 제거 드릴
FE-GATE-020이 PR 대부분(34건 중 25건)에서 돌아 약 6분을 차지한다.
CI-X-0002 (다) 결정에 따라 FE-GATE-020을 merge 단계에서 main 단계로 옮긴다.

고른 방법과 버린 대안:
- config/ci/gates.json, scripts/contracts/ci-gates.ts(expectedJobOwnership),
  scripts/lib/promotion-readiness.ts(MERGE_READY·MAIN_READY)에서 FE-GATE-020을
  merge/merge_test에서 main/main_gate(FE-GATE-029 다음, FE-GATE-030 앞)로
  옮기고 workflow와 스냅샷을 재생성한다.
- scripts/lib/feature-scaffold-drill.ts는 되돌림 시 재귀를 막으려 자기 스크립트
  (test:sample-removal·test:feature-scaffold)를 제외 목록에 남기되 merge 밖
  stale 거절에서만 면제한다. 고른 드릴 명령 29개는 기존과 같다.
- config/ci/pr-gate-selection.json의 accessibility-records·scaffold 줄에서
  FE-GATE-020을 빼고, scaffold 줄은 되돌림과 계약 시험을 위해 남긴다.
- 버린 대안: FE-GATE-020 전용 드릴 입력 목록(효과 미미·거짓 초록 위험),
  제외 목록에서 자기 스크립트 삭제(되돌림 시 재귀·미사용 상수 발생).

위험·한계:
- 기능·scaffold 드릴 회귀가 PR이 아니라 병합 뒤 main 빨강으로 드러나며,
  release·tag run과 RELEASE_READY도 FE-GATE-020을 요구하지 않는다.
- .claude/skills/fe-structure/SKILL.md:53은 .claude/ 수정 금지 가드로 바꾸지
  않았으며, 같은 안내는 docs/work/reference/gates.md에 반영했다.
- 생성기·드릴·src/features·src/contexts 규칙을 바꾸는 PR은
  scripts/verify.sh gate FE-GATE-020을 직접 돌린다.

검증:
- C1 RED (트리 38592b2283d7): ci-workflow-generation rc=1, promotion-readiness rc=1
- C2 RED (트리 06a01260818a): feature-scaffold-drill rc=1 (outside the merge stage)
- laptop-gate check:types, lint, verify:documentation, 단위 시험 7파일(538 passed) rc=0
- scripts/verify.sh docs rc=0, scripts/verify.sh hooks rc=0 (112 tests)

Refs: CI-FE-0005
2026-12-04 07:45:06 +09:00

312 lines
14 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts";
import { planFeature, type InstalledFacts } from "../../scripts/create-feature.ts";
import {
loadPrGateSelectionTable,
pathPatternRegExp,
prChangedFiles,
prGateSkipReason,
PR_BASE_REF_VARIABLE,
selectPrGates,
SKIPPED_GATE_LINE,
skippedGateLine,
} from "../../scripts/lib/pr-gate-selection.ts";
const table = loadPrGateSelectionTable(process.cwd());
/** Longest desktop run of the `git ls-files` test (2026-11-13, three runs at load 17 to 23). */
const GIT_LS_FILES_MS = 48;
/** Longest desktop run of the shallow-clone test (2026-11-13, three runs at load 24). */
const SHALLOW_CLONE_MS = 291;
const ALWAYS = ["FE-GATE-001", "FE-GATE-002", "FE-GATE-003", "FE-GATE-010"];
function covered(file: string): boolean {
const patterns = [...table.global, ...table.rules.flatMap((rule) => rule.paths)];
return patterns.some((pattern) => pathPatternRegExp(pattern).test(file));
}
function selected(files: readonly string[]): readonly string[] | "all" {
const selection = selectPrGates(table, files);
return selection.kind === "all" ? "all" : [...selection.gates].sort();
}
function relativePaths(text: string): string[] {
return [...text.matchAll(/["'`](\.\.?\/[^"'`\s]*)/gu)].map((match) => match[1]!);
}
function isRepositoryFile(target: string): boolean {
return !target.startsWith("../") && statSync(target, { throwIfNoEntry: false })?.isFile() === true;
}
/** What `planFeature` renders for each combination of create:feature's options. */
function generatorPlans() {
const installed: InstalledFacts = {
appIds: ["template-app"],
featureIds: [],
contexts: [{ id: "installed-context", routePath: "installed/*" }],
contextDirectories: ["installed-context"],
routes: [],
topics: [],
messageKeys: [],
};
const contractPackage = {
packageId: "@org-contracts/path-table",
version: "1.0.0",
digest: `sha256:${"ab".repeat(32)}`,
sourceRevision: "0a1b2c3d",
};
return ([undefined, "NEVER", "KEYED"] as const).flatMap((write) =>
[undefined, "installed-context", "named-context"].flatMap((context) =>
[undefined, contractPackage].map((pinned) =>
planFeature({ id: "path-table-feature", write, context, contractPackage: pinned }, installed),
),
),
);
}
/**
* REV-FE-0007. The generator's templates import relative to the file they
* render, so each path is resolved from that file in the rendered plan. A path
* that is no file is `unresolved`, and so is a path in the generator's source
* that no render shows (an option `generatorPlans` does not pass) and that is
* not the script's own import.
*/
function generatorImports(templates: readonly string[]) {
const named = new Set<string>();
const rendered = new Set<string>();
const unresolved = new Set<string>();
for (const { files } of generatorPlans()) {
for (const [file, content] of files) {
for (const specifier of relativePaths(content)) {
rendered.add(specifier);
const target = path.posix.join(path.posix.dirname(file), specifier);
if (files.has(target)) continue;
if (isRepositoryFile(target)) named.add(target);
else unresolved.add(`${file}: ${specifier}`);
}
}
}
for (const script of templates) {
for (const specifier of relativePaths(readFileSync(script, "utf8"))) {
if (isRepositoryFile(path.posix.join(path.posix.dirname(script), specifier))) continue;
const shape = pathPatternRegExp(specifier.replace(/\$\{[^}]*\}/gu, "*"));
if (![...rendered].some((shown) => shape.test(shown))) unresolved.add(`${script}: ${specifier}`);
}
}
return { named, unresolved: [...unresolved] };
}
type GitCall = readonly string[];
function fakeGit(answers: Readonly<Record<string, Readonly<{ status?: number; stdout?: string; stderr?: string }>>>) {
const calls: GitCall[] = [];
const git = (args: readonly string[]) => {
calls.push(args);
const answer = answers[args[0]!] ?? {};
return { status: answer.status ?? 0, stdout: answer.stdout ?? "", stderr: answer.stderr ?? "" };
};
return { git, calls };
}
describe("PR path table (contract)", () => {
it("puts every merge gate on a row or in always", async () => {
const contract = await loadCiGateContract(process.cwd());
const merge = contract.stages.find((stage) => stage.id === "merge")!.gateIds;
const listed = new Set([...table.always, ...table.rules.flatMap((rule) => rule.gates)]);
expect(merge.filter((gate) => !listed.has(gate))).toEqual([]);
expect([...listed].filter((gate) => !merge.includes(gate))).toEqual([]);
});
// FE-6 (decisions.md): FE-GATE-008 leaves the @a11y browser tests to
// FE-GATE-009, so a PR that runs 008 without 009 would run them nowhere.
it("runs FE-GATE-009 wherever it runs FE-GATE-008", () => {
expect(table.always.includes("FE-GATE-008")).toBe(table.always.includes("FE-GATE-009"));
const with008 = table.rules.filter((rule) => rule.gates.includes("FE-GATE-008"));
expect(with008.length).toBeGreaterThan(0);
for (const rule of with008) expect(rule.gates, rule.id).toContain("FE-GATE-009");
});
it("matches every tracked file with a row or the global list", () => {
const tracked = spawnSync("git", ["ls-files"], { encoding: "utf8" }).stdout.split("\n").filter(Boolean);
expect(tracked.length).toBeGreaterThan(100);
expect(tracked.filter((file) => !covered(file))).toEqual([]);
}, childProcessTimeout(GIT_LS_FILES_MS));
it("covers every repository path the scaffold and removal drills name with the scaffold row", () => {
const scaffold = table.rules.find((rule) => rule.id === "scaffold")!;
const templates = ["scripts/create-feature.ts", "scripts/create-feature-write-slice.ts"];
const drills = [
...templates,
"scripts/lib/generated-feature.ts",
"scripts/lib/feature-scaffold-drill.ts",
"scripts/test-feature-scaffold.ts",
"scripts/test-sample-removal.ts",
];
const named = new Set(
drills.flatMap((file) =>
[...readFileSync(file, "utf8").matchAll(/["'`]((?:src|tests)\/[\w./-]+)/gu)].map((match) => match[1]!),
),
);
expect(named.size).toBeGreaterThan(5);
const imports = generatorImports(templates);
expect(imports.unresolved).toEqual([]);
expect(imports.named.size).toBeGreaterThan(5);
for (const imported of imports.named) named.add(imported);
const uncovered = [...named].filter(
(name) =>
!scaffold.paths.some((pattern) =>
[name, `${name.replace(/\/$/u, "")}/x`].some((candidate) => pathPatternRegExp(pattern).test(candidate)),
),
);
expect(uncovered).toEqual([]);
// The other way: an exact src path on the row is one a render imports, so
// the scaffold row stays aligned with generator imports for rollback.
const notImported = scaffold.paths.filter(
(pattern) => pattern.startsWith("src/") && !/[*?]/u.test(pattern) && !imports.named.has(pattern),
);
expect(notImported).toEqual([]);
});
});
describe("PR gate selection", () => {
it("runs the static gates and the unit gate for documents only", () => {
expect(selected(["docs/work/README.md", "README.md", "src/presentation/AGENTS.md", ".claude/rules/tests.md"])).toEqual(
[...ALWAYS, "FE-GATE-005"].sort(),
);
});
it("adds the accessibility gate for the accessibility records without the main-stage removal drill", () => {
expect(selected(["docs/accessibility/route-reviews/APP_HOME.md"])).toEqual(
[...ALWAYS, "FE-GATE-005", "FE-GATE-009"].sort(),
);
});
it("runs the application gates without the main-stage scaffold drill for code changes", () => {
const gates = selected(["src/presentation/pages/home-page.tsx", "tests/e2e/app-shell.spec.ts"]);
expect(gates).not.toBe("all");
expect(gates).toContain("FE-GATE-008");
expect(gates).toContain("FE-GATE-013");
expect(gates).not.toContain("FE-GATE-020");
});
it("keeps the scaffold row aligned for application gates while FE-GATE-020 runs in main", () => {
for (const file of ["src/features/reference/index.ts", "tests/mocks/scenarios/catalog.ts"]) {
const gates = selected([file]);
expect(gates).not.toBe("all");
expect(gates).toContain("FE-GATE-008");
expect(gates).toContain("FE-GATE-013");
expect(gates).not.toContain("FE-GATE-020");
}
});
it("runs every gate for a global file, an unknown file or an empty diff", () => {
expect(selectPrGates(table, ["package.json"])).toEqual({ kind: "all", reason: "전역 파일 package.json이 바뀜" });
expect(selected(["scripts/verify.sh", "docs/x.md"])).toBe("all");
expect(selected(["playwright.visual.config.ts"])).toBe("all");
expect(selectPrGates(table, ["new-root-file.txt"])).toMatchObject({ kind: "all" });
expect(selectPrGates(table, [])).toMatchObject({ kind: "all" });
});
it("reads path patterns as segments", () => {
expect(pathPatternRegExp("**/*.md").test("README.md")).toBe(true);
expect(pathPatternRegExp("**/*.md").test("docs/a/b.md")).toBe(true);
expect(pathPatternRegExp("docs/**").test("docs/a/b.txt")).toBe(true);
expect(pathPatternRegExp("docs/**").test("docsx/a")).toBe(false);
expect(pathPatternRegExp("tsconfig*.json").test("tsconfig.app.json")).toBe(true);
expect(pathPatternRegExp("tsconfig*.json").test("src/tsconfig.json")).toBe(false);
expect(pathPatternRegExp("index.html").test("indexXhtml")).toBe(false);
});
});
describe("skipped gate log line", () => {
it("has the fixed form of design-docs ci/manual.md 4.1", () => {
const line = skippedGateLine("FE-GATE-020", "바뀐 파일 3개가 경로표에서 이 게이트에 안 걸림");
expect(line).toBe("건너뜀: FE-GATE-020 — 바뀐 파일 3개가 경로표에서 이 게이트에 안 걸림");
expect(SKIPPED_GATE_LINE.test(line)).toBe(true);
expect(SKIPPED_GATE_LINE.test("건너뜀: merge / tests — 트리 abc1234가 PR #12 run 34에서 초록")).toBe(true);
expect(SKIPPED_GATE_LINE.test("skipped: FE-GATE-020")).toBe(false);
expect(SKIPPED_GATE_LINE.test("건너뜀: FE-GATE-020 —")).toBe(false);
});
});
describe("PR diff and the skip decision", () => {
it("unshallows the checkout, fetches the base and diffs from the merge base", () => {
const { git, calls } = fakeGit({
"rev-parse": { stdout: "true\n" },
"merge-base": { stdout: "abc123\n" },
diff: { stdout: "docs/a.md\nsrc/b.ts\n" },
});
expect(prChangedFiles("main", git)).toEqual({ files: ["docs/a.md", "src/b.ts"] });
expect(calls[1]).toEqual(["fetch", "--no-tags", "--quiet", "--unshallow", "origin", "+refs/heads/main:refs/remotes/origin/main"]);
expect(calls[2]).toEqual(["merge-base", "refs/remotes/origin/main", "HEAD"]);
expect(calls[3]).toEqual(["diff", "--name-only", "--no-renames", "abc123", "HEAD"]);
});
it("reads a shallow PR checkout's changes from the merge base with real git", () => {
const root = mkdtempSync(path.join(tmpdir(), "pr-gate-selection-"));
try {
const git = (cwd: string, ...args: string[]) => {
const result = spawnSync(
"git",
["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "init.defaultBranch=main", ...args],
{ cwd, encoding: "utf8" },
);
if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`);
return result;
};
const origin = path.join(root, "origin");
mkdirSync(origin);
git(origin, "init", "--quiet");
writeFileSync(path.join(origin, "a.ts"), "1\n");
git(origin, "add", ".");
git(origin, "commit", "--quiet", "-m", "base");
git(origin, "switch", "--quiet", "-c", "pr");
mkdirSync(path.join(origin, "docs"));
writeFileSync(path.join(origin, "docs", "x.md"), "x\n");
git(origin, "add", ".");
git(origin, "commit", "--quiet", "-m", "pr");
git(origin, "switch", "--quiet", "main");
writeFileSync(path.join(origin, "a.ts"), "2\n");
git(origin, "commit", "--quiet", "-am", "main moves on");
git(root, "clone", "--quiet", "--depth", "1", "--branch", "pr", `file://${origin}`, "checkout");
const checkout = path.join(root, "checkout");
const inCheckout = (args: readonly string[]) => {
const result = spawnSync("git", args, { cwd: checkout, encoding: "utf8" });
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
};
// main's own later change (a.ts) is not the PR's.
expect(prChangedFiles("main", inCheckout)).toEqual({ files: ["docs/x.md"] });
} finally {
rmSync(root, { recursive: true, force: true });
}
}, childProcessTimeout(SHALLOW_CLONE_MS));
it("reports a fetch failure or an odd base name instead of guessing", () => {
expect(prChangedFiles("main", fakeGit({ fetch: { status: 128, stderr: "denied" } }).git)).toEqual({
error: "base 브랜치를 받지 못함: denied",
});
expect(prChangedFiles("main; rm -rf /", fakeGit({}).git)).toMatchObject({ error: expect.stringContaining("이상함") });
});
it("skips only in a pull_request run, only gates the diff does not reach", () => {
const docsOnly = () =>
fakeGit({ "rev-parse": { stdout: "false\n" }, "merge-base": { stdout: "abc\n" }, diff: { stdout: "docs/a.md\n" } }).git;
const root = process.cwd();
expect(prGateSkipReason("FE-GATE-008", {}, root, docsOnly())).toBeUndefined();
expect(prGateSkipReason("FE-GATE-008", { [PR_BASE_REF_VARIABLE]: "" }, root, docsOnly())).toBeUndefined();
expect(prGateSkipReason("FE-GATE-008", { [PR_BASE_REF_VARIABLE]: "main" }, root, docsOnly())).toMatch(
/^바뀐 파일 1개가 경로표/u,
);
expect(prGateSkipReason("FE-GATE-005", { [PR_BASE_REF_VARIABLE]: "main" }, root, docsOnly())).toBeUndefined();
expect(
prGateSkipReason("FE-GATE-008", { [PR_BASE_REF_VARIABLE]: "main" }, root, fakeGit({ fetch: { status: 1 } }).git),
).toBeUndefined();
});
});