Files
clean-architecture-frontend…/tests/unit/pr-gate-selection.test.ts
T
DongHyeonka 9f8b2c1ce5
frontend-quality-gates / merge / static checks (pull_request) Successful in 1m20s
frontend-quality-gates / merge / tests (pull_request) Failing after 10m12s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 5m38s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
frontend-quality-gates / main / self-tests and removal drills (pull_request) Skipped
ci(gates): PR run이 경로표로 바뀐 범위의 merge 게이트만 돈다
PR run은 무엇을 바꿨든 merge 게이트 14개를 전부 돈다. 문서만 고친 PR도
scaffold 드릴(FE-GATE-020, run 241 tests job 15:58 중 약 8.5분)과 브라우저
게이트를 돈다. 소유자가 「PR은 바뀐 범위만, 문서만이면 문서 검사, 공용
파일이면 전체, 건너뛴 검사는 로그에, 경로표는 계약 시험으로」를
정했다(2026-11-13, design-docs ci/manual.md 4절, 계획 FE-2).

config/ci/pr-gate-selection.json이 경로표다. global 파일(config/,
scripts/, .gitea/, 도구 설정, lockfile 등)이나 어느 줄에도 안 걸리는
파일이 하나라도 바뀌면 전부 돈다. 아니면 파일마다 rules를 위에서부터
보고, 처음 맞는 줄의 게이트를 always(001·002·003·010)에 더한다.
- 문서(docs/**, **/*.md, .claude/**)는 FE-GATE-005까지 돈다.
- 접근성 기록은 009·020까지, recipes는 007·012까지 돈다.
- scaffold 드릴 입력(src/features 등)은 앱 게이트와 020을 돈다.
- 그 밖의 src·tests는 020을 뺀 앱 게이트를 돈다.
scripts/lib/pr-gate-selection.ts가 판정한다. run-ci-gate.ts는
CI_PR_BASE_REF(pull_request run에서만 base 브랜치, 나머지는 빈 값)가
있을 때만 판정을 부른다. 안 도는 게이트는 `건너뜀: <ID> — <이유>`를
찍고 게이트 로그도 그 한 줄로 남긴 뒤 성공으로 끝난다. diff는 base와의
merge base에서 잰다. checkout이 얕아 처음 한 번 history를 받는다. 받지
못하거나 diff를 못 읽으면 이유를 찍고 전부 돈다. merge job 셋의 env
바인딩은 계약(expectedEnvironmentBindings)과 gates.json에 두고 workflow를
다시 만들었다.

버린 대안:
- workflow on.paths·job if:로 건너뛰기: 필수 검사가 보고 없이 남는다
  (매뉴얼 4.4절).
- 고르는 job을 따로 두기: needs job이 줄 끝으로 간다.
- vitest --changed: coverage 문턱이 전체 실행을 전제한다.
- 맞는 줄을 모두 합치기: src 아래 AGENTS.md 같은 문서가 앱 게이트 전부를
  불렀다.

위험·한계:
- 경로표가 놓친 실패는 main push가 잡는다. main은 늘 전부 돈다.
- scaffold 줄은 드릴 스크립트가 이름으로 부르는 src·tests 경로를 손으로
  옮긴 것이다. 계약 시험이 그 이름들이 scaffold 줄에 걸리는지 본다.
- 공개 repo라 checkout의 origin에서 인증 없이 fetch한다. 비공개로 바뀌면
  fetch가 실패하고 전부 돈다(로그에 이유).

검증(desktop): pr-gate-selection 시험(표가 merge 게이트 전부를 덮음, 추적
파일 1631개 전부가 줄에 걸림, scaffold 드릴 이름 범위, 문서만·접근성·
앱·scaffold·전역·모르는 파일·빈 diff 선택, 건너뜀 문구 형식, 실제 git
얕은 clone에서 merge base diff, fetch 실패면 전부)을 3회 통과했다.
test-timeout-declarations 통과. 자식 프로세스 시험 둘의 timeout은 잰 값
48 ms·291 ms다. check:ci-workflow, check:types:node·test, eslint 통과.
scripts/verify.sh merge(CI=true, main 950ea11a 위, 트리 e031a8a5): 14개
전부 rc=0(008 282초, 020 404초). gate FE-GATE-029 rc=0.
2026-11-14 00:26:20 +09:00

222 lines
10 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, 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 {
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();
}
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([]);
});
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 drills = [
"scripts/create-feature.ts",
"scripts/create-feature-write-slice.ts",
"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 uncovered = [...named].filter(
(name) =>
!scaffold.paths.some((pattern) =>
[name, `${name.replace(/\/$/u, "")}/x`].some((candidate) => pathPatternRegExp(pattern).test(candidate)),
),
);
expect(uncovered).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 and the removal drill for the accessibility records", () => {
expect(selected(["docs/accessibility/route-reviews/APP_HOME.md"])).toEqual(
[...ALWAYS, "FE-GATE-005", "FE-GATE-009", "FE-GATE-020"].sort(),
);
});
it("runs the application gates but not the scaffold drill for code outside its inputs", () => {
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("runs the scaffold drill when its inputs change", () => {
expect(selected(["src/features/reference/index.ts"])).toContain("FE-GATE-020");
expect(selected(["src/features/reference/index.ts"])).toContain("FE-GATE-008");
expect(selected(["tests/mocks/scenarios/catalog.ts"])).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-020", {}, root, docsOnly())).toBeUndefined();
expect(prGateSkipReason("FE-GATE-020", { [PR_BASE_REF_VARIABLE]: "" }, root, docsOnly())).toBeUndefined();
expect(prGateSkipReason("FE-GATE-020", { [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-020", { [PR_BASE_REF_VARIABLE]: "main" }, root, fakeGit({ fetch: { status: 1 } }).git),
).toBeUndefined();
});
});