Files
clean-architecture-frontend…/scripts/lib/feature-scaffold-drill.ts
DongHyeonka 6cba1f5056 ci(gates): FE-GATE-005가 unit·contract 시험을 coverage 실행에서 한 번만 돈다
문제:
- FE-GATE-005는 `test:unit`·`test:contract`로 `tests/unit`·`tests/contract`를
  돈 뒤, `test:coverage`로 같은 파일을 다시 돈다. coverage의 경로가 두
  폴더를 품는다. runner에서 005의 약 3분 가운데 `test:unit`이 31~33%다
  (design-docs `ci/06-frontend-ci-speed-handoff.md` 4.3절).

고른 방법:
- 005의 명령에서 `test-unit`·`test-contract`를 빼고, 계약에서도 지운다.
  두 package script는 작업 중에 쓰는 명령으로 남는다.
- `scripts/lib/coverage-bundle-junit-reporter.ts`를 `test:coverage`의 reporter로
  더한다.
  - 같은 coverage 실행에서 두 폴더의 결과를 Vitest의 JUnit reporter로
    `artifacts/tests/unit.xml`·`contract.xml`에 쓴다. 폴더마다 그 폴더의
    test module만 넘긴다.
  - 증거 이름, 형식, 게이트 ID는 그대로다. 두 증거의 producer는
    `test-coverage`이고, freshness 검사(`run-ci-gate.ts`)도 그대로
    통과한다.
  - 한 폴더에서 시험 파일이 하나도 돌지 않으면 그 실행이 실패한다. 일반
    실행도 시험 파일이 없는 폴더에서 실패했다. 빈 보고서는 증거 검사를
    그대로 통과하기 때문이다.
  - 쓴 보고서를 다시 읽어 `<testsuite name>` 목록이 그 폴더에서 돈 파일과
    같은지 본다. 다르거나 읽을 수 없으면 실패하고, 남는 파일과 빠진
    파일을 앞 3개씩 댄다. Vitest를 올려 JUnit reporter가 넘겨받은 module
    대신 전체를 쓰게 바뀌면 여기서 걸린다.
- 드릴의 「coverage가 덮는 묶음」(`SCAFFOLD_DRILL_COVERED_SUITES`)에서
  unit·contract를 뺀다. merge 단계가 더는 그 둘을 따로 부르지 않는다.
- 시험(`tests/unit/coverage-bundle-junit-reporter.test.ts`, 9개)이 본다:
  - reporter가 폴더마다 그 폴더의 파일만 넘긴다. 빈 폴더면 실패한다.
  - 보고서가 넘기지 않은 파일을 담거나, 돈 파일을 빼거나, 써지지 않으면
    실패한다. suite 이름을 읽는다.
  - 005의 두 증거가 `test:coverage`에서 나온다.
  - `test:coverage`가 reporter를 부르고, 그 경로가 두 폴더를 품는다.
  - merge 단계에서 두 폴더를 도는 명령이 005의 `test:coverage` 하나뿐이다.
- `docs/work/reference/decisions.md`에 FE-4 행을 더한다. 운영 문서, 시험 층
  표, 매뉴얼, 지역 지침 둘, fe-testing 스킬의 005 설명도 고친다.

버린 것:
- coverage 실행 한 번이 FE-GATE-004·006·007의 증거까지 내기(약 −1:30). 세
  게이트가 005의 결과를 읽게 된다. coverage 실행이 죽으면 세 게이트도
  판정을 못 내고, 혼자 돌릴 수 없다. FE-6에서 버린 꼴과 같다. 004는 005보다
  앞이라 차례도 바꿔야 했다. 총괄이 정했다(2026-11-20).
- coverage의 JUnit을 나중에 XML로 나누기: 저장소에 XML 파서가 없다.
  Vitest의 reporter로 쓰면 형식이 일반 실행과 같다.

위험·한계:
- unit·contract 시험은 이제 coverage 계측 아래에서만 돈다. 시간에 기대는
  시험이 가려질 수 있다. 일반 실행은 기본 worker 수, coverage 실행은
  `--maxWorkers=4`로 돈다. environment·setupFiles·pool·include·exclude는
  같다.
- 004·006·007의 묶음은 coverage에서 한 번 더 돈다(약 0:33).
- `unit.xml`의 시험 시간은 이제 coverage 실행의 시간이다.

검증(desktop `scripts/verify.sh`):
- 분할한 `unit.xml`·`contract.xml`이 같은 트리의 일반 `test:unit`·
  `test:contract` 결과와 파일·testcase·결과까지 같다(unit 242파일 3469,
  contract 3파일 26). 기준 main의 일반 실행과는 이 커밋이 더한 시험 파일
  하나만 다르다.
- 두 실행의 vitest 설정을 풀어 보니 coverage 켜짐과 maxWorkers만 다르다.
- FE-GATE-005 rc=0. 게이트 로그의 vitest 호출은 `test:coverage` 하나이고,
  자기 대조 불만은 0이다.
- `tests/unit` 시험 하나를 깨뜨리면 005 rc=1(`unit.xml` failures=1).
  `tests/component` 시험 하나를 깨뜨리면 005·006 rc=1.
- 변이 여덟이 각자 대상 시험에서 실패한다: reporter 인자 빼기, coverage
  경로에서 `tests/contract` 빼기(게이트도 「No test file of tests/contract
  ran」으로 실패), 005에 `test-unit` 다시 넣기, 폴더 거름을 `includes`로
  (두 번), 자기 대조 끄기(두 번), 자기 대조를 남는 이름만 보게 약하게.
- lint·check:types·FE-GATE-010 rc=0.
- 리뷰: 새 눈 1회(Low 2와 확인 못 한 것 1) 반영, 확인 1회(Low 2) 반영, 다시
  확인 발견 0.
- merge 단계와 FE-GATE-029·030은 PR 본문에 적는다.

Refs: fe-ci-next (5), FE-4
2026-11-20 19:10:10 +09:00

173 lines
7.7 KiB
TypeScript

import { spawnSync } from "node:child_process";
import type { CiGateContract } from "../contracts/ci-gates.ts";
import { classifyGateStepResult, type GateStepExpectation } from "./ci-step-result.ts";
import { FIXTURE_PNPM_ENVIRONMENT } from "./fixture-node-modules.ts";
import type { RemovalCheck } from "./removal-fixture.ts";
/**
* 1103/12-02. test:feature-scaffold proves that a feature from
* `create:feature` passes the merge gates. It ran a hand-kept list of 15
* commands while the merge stage has 88, so a template change that broke a
* generated feature in any other merge command passed FE-GATE-020.
*
* The drill now runs the merge stage of the copy's config/ci/gates.json, in
* stage order, each command once. A command added to the merge stage runs here
* unless this list names it, with the reason it cannot run in the drill.
*/
const BROWSER =
"needs Playwright browsers. FE-GATE-020 runs in a merge job without them " +
"(merge_test installs none). The generated routes in the browser " +
"gates are reviewed as 1103/12-01 and 12-03.";
const DRILL =
"a removal drill copies the repository again. The drill runs the generated " +
"feature's own removal instead (feature-removal).";
/**
* The drill runs FE-GATE-005's test:coverage in the same copy, and its paths
* hold every path of these suites (tests/unit/removal-drill-test-paths.test.ts).
* Running them plain as well found nothing more and cost about 80 s a drill.
* tests/unit and tests/contract are not here: the merge stage runs them only in
* test:coverage (FE-4, scripts/lib/coverage-bundle-junit-reporter.ts).
*/
const COVERED =
"test:coverage runs the same test files in this copy " +
"(tests/unit/removal-drill-test-paths.test.ts checks the paths).";
export const SCAFFOLD_DRILL_COVERED_SUITES: readonly string[] = Object.freeze([
"test:runtime-schema",
"test:component",
"test:integration",
]);
/**
* What a removal drill runs next to test:coverage so that every test:all path
* still runs once in the copy (scripts/test-sample-removal.ts). The rest of
* test:all, check:release-coherence included, is inside coverage's paths.
*/
export const REMOVAL_DRILL_SUITES_OUTSIDE_COVERAGE: readonly string[] = Object.freeze([
"test:recipes",
]);
export const SCAFFOLD_DRILL_EXCLUDED_SCRIPTS: Readonly<Record<string, string>> = Object.freeze({
"verify:lockfile":
"runs pnpm install, which writes into the node_modules the copy links from " +
"the repository (scripts/lib/fixture-node-modules.ts).",
"test:e2e": BROWSER,
"test:browser-capabilities": BROWSER,
"verify:browser-capability-evidence": `reads the test:browser-capabilities results; ${BROWSER}`,
"test:storybook": BROWSER,
"test:visual": BROWSER,
"check:test-evidence:browser": `reads the browser gates' results; ${BROWSER}`,
"test:a11y": BROWSER,
"test:system":
"needs the CI runner's bubblewrap, systemd and cgroup v2 " +
"(scripts/check-system-test-prerequisites.ts). It tests the provider " +
"sandbox, which a feature does not reach.",
...Object.fromEntries(SCAFFOLD_DRILL_COVERED_SUITES.map((script) => [script, COVERED])),
"test:sample-removal": DRILL,
"test:feature-scaffold": "is this drill.",
});
export type ScaffoldDrillCommand = Readonly<{
/** `<gate>:<command id>`, the check's name in the drill report. */
name: string;
script: string;
args: readonly string[];
expectation: GateStepExpectation;
}>;
type ContractShape = Pick<CiGateContract, "commands" | "gates" | "stages">;
export function scaffoldDrillCommands(
contract: ContractShape,
excluded: Readonly<Record<string, string>> = SCAFFOLD_DRILL_EXCLUDED_SCRIPTS,
): readonly ScaffoldDrillCommand[] {
const merge = contract.stages.find(({ id }) => id === "merge");
if (!merge) throw new TypeError("the CI contract has no merge stage");
const commands = new Map(contract.commands.map((command) => [command.id, command]));
const mergeScripts = new Set<string>();
const seen = new Set<string>();
const selected: ScaffoldDrillCommand[] = [];
// A covered suite is left out only while the drill runs test:coverage. A
// copy whose merge stage lost it runs the suites plain again.
const runsCoverage = !Object.hasOwn(excluded, "test:coverage") && merge.gateIds.some((gateId) =>
contract.gates.find(({ id }) => id === gateId)?.commandIds.some((commandId) =>
commands.get(commandId)?.script === "test:coverage"));
const leftOut = (script: string) =>
Object.hasOwn(excluded, script) &&
(runsCoverage || !SCAFFOLD_DRILL_COVERED_SUITES.includes(script) || excluded[script] !== COVERED);
for (const gateId of merge.gateIds) {
const gate = contract.gates.find(({ id }) => id === gateId);
if (!gate) throw new TypeError(`the merge stage names an undefined gate: ${gateId}`);
for (const commandId of gate.commandIds) {
const command = commands.get(commandId);
if (!command) throw new TypeError(`${gateId} names an undefined command: ${commandId}`);
mergeScripts.add(command.script);
if (seen.has(commandId) || leftOut(command.script)) continue;
seen.add(commandId);
selected.push(Object.freeze({
name: `${gateId}:${commandId}`,
script: command.script,
args: Object.freeze([...(command.args ?? [])]),
expectation: command.expect === "pass"
? Object.freeze({ kind: "pass" as const })
: Object.freeze({
kind: "fail" as const,
expectedExitCode: command.expectedExitCode ?? 1,
expectedDiagnosticId: command.expectedDiagnosticId ?? "",
}),
}));
}
}
// An exclusion for a command that moved out of the merge stage would hide
// nothing today and silently drop it if it came back. A command the contract
// no longer has at all (a removal drill pruned its capability) is not stale.
const contractScripts = new Set(contract.commands.map(({ script }) => script));
const stale = Object.keys(excluded).filter(
(script) => contractScripts.has(script) && !mergeScripts.has(script),
);
if (stale.length > 0) {
throw new TypeError(
`the scaffold drill excludes scripts the contract runs outside the merge stage: ${stale.join(", ")}`,
);
}
return Object.freeze(selected);
}
/**
* Runs one merge command in the fixture. A negative fixture command passes
* only with its registered exit code and diagnostic, as in run-ci-gate.ts.
*/
export function runScaffoldDrillCommand(
command: ScaffoldDrillCommand,
root: string,
pnpmCli: string,
): RemovalCheck {
const capture = command.expectation.kind === "fail";
const result = spawnSync(process.execPath, [pnpmCli, command.script, ...command.args], {
cwd: root,
encoding: "utf8",
stdio: capture ? "pipe" : "inherit",
maxBuffer: 64 * 1024 * 1024,
env: { ...process.env, ...FIXTURE_PNPM_ENVIRONMENT },
});
if (capture) {
process.stdout.write(result.stdout ?? "");
process.stderr.write(result.stderr ?? "");
}
const classification = classifyGateStepResult(command.expectation, {
status: result.status,
signal: result.signal,
stdout: result.stdout ?? "",
stderr: result.stderr ?? "",
...(result.error ? { error: { code: (result.error as NodeJS.ErrnoException).code } } : {}),
});
if (classification.expectationMet) return { name: command.name, passed: true };
const invocation = `corepack pnpm ${[command.script, ...command.args].join(" ")}`;
return {
name: command.name,
passed: false,
failure: command.expectation.kind === "fail"
? `${invocation}: ${classification.kind}, expected exit ${command.expectation.expectedExitCode} with ${JSON.stringify(command.expectation.expectedDiagnosticId)}, got exit ${result.status ?? result.signal}`
: `${invocation} exited ${result.status ?? result.signal ?? "on a spawn error"}`,
};
}