Files
clean-architecture-frontend…/scripts/check-ci-contract.ts
donghyeon.kang f6b2b96c53 ci(gates): 검사기 자기 시험과 gating 검사를 main 단계로 내리고 계약 기준선을 지운다
merge 단계(=PR)가 변경이 아니라 검사기 자신을 시험하는 명령까지 돈다.
검사기가 나쁜 입력을 거부하는지 보는 `*:fixture` 명령 15개, 모든 시험
파일과 검증 script가 게이트에 걸렸는지 보는 ungated 검사, CI 계약의
개수·해시 기준선(`config/ci/contract-baseline.json`)이다. 기준선은 게이트
명령 하나를 더하거나 빼도 OWNER·REASON을 붙여 다시 받아야 했다.
소유자 결정(2026-09-16)은 개수·배선 검사를 main 단계에 두는 것이다.

고른 방법(design-docs repo-structure/03-ci.md 7.3절 F2, README.md 3.3절,
소유자 승인 2026-11-07):
- 새 게이트 FE-GATE-029 `checker-self-tests`, 새 단계 `main`
  (`MAIN_READY`, 승격을 막지 않는다), 새 job `main_gate`. 브랜치 push와
  `workflow_dispatch`(stage=main)에서만 돈다. PR과 태그에서는 돌지 않는다.
- FE-GATE-001·005·008·010·013의 `*:fixture` 명령 15개와 그 증거
  산출물 10개를 FE-GATE-029로 옮긴다.
- `check:ci`의 ungated 검사를 `scripts/check-ci-gating.ts`
  (`check:ci:gating`)로 떼어 FE-GATE-029에 둔다. `check:ci`는 계약·
  workflow 검사만 PR에서 돈다.
- 기준선 파일, `update:ci-contract-baseline`, 그 검사를 지운다(소유자
  결정). 계약 모양은 ci-gates.ts의 의미 검사가 지킨다. 개수를 고정하던
  단위 시험의 개수 단언도 뺐다.

남긴 것: 음성 타입 fixture(`check:types:fixtures`, FE-GATE-003)는
이름이 `*:fixture`여도 merge에 둔다. 검사기가 아니라 src의 포트·계약
타입을 시험한다. `TelemetryPort.emit`을 넓히는 변경을 PR에서 막는다(정리
3단계 9.3절 변이로 확인). merge 단계 명령 참조 64 → 49.

위험: 검사기를 망가뜨린 PR은 merge를 통과하고 main에서 빨개진다. 그
대가로 PR이 검사기 자기 시험을 기다리지 않는다(설계 7.5절의 같은 교환).
FE-GATE-029의 명령이 앞 게이트 산출물 없이 새 checkout에서 도는지는
desktop에서 따로 확인했다(PR 본문).

검증(desktop): check:ci, check:ci:gating, check:types, CI 시험 통과.
merge 단계·FE-GATE-029 실행 결과는 PR 본문에 적는다.

Refs: design-docs repo-structure/03-ci.md 7.3·7.4절, README.md 3.3절
2026-11-08 21:56:37 +09:00

154 lines
5.9 KiB
TypeScript

import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import {
evaluatePromotionReadiness,
PROMOTION_FORMULA,
type GateResult,
} from "./lib/promotion-readiness.ts";
import {
CANONICAL_GATE_IDS,
loadCiGateContract,
indexCiGateContract,
} from "./contracts/ci-gates.ts";
import {
generateCiWorkflow,
renderCiWorkflow,
workflowGateExecutionFailures,
} from "./generate-ci-workflow.ts";
import { loadProductCiOverlay } from "./contracts/product-ci-overlay.ts";
import {
ciContractReportSchema,
} from "./lib/ci-contract-report.ts";
import {
validateInstallScriptPolicy,
validatePackageScriptGraph,
} from "./lib/package-script-graph.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
const contract = await loadCiGateContract(process.cwd());
const index = indexCiGateContract(contract);
// 1103/12-07. The product's merge gates run in the generated workflow too.
const { mergeGates: productGates } = await loadProductCiOverlay(process.cwd());
const [packageDocument, nodeVersion] = await Promise.all([
readFile("package.json", "utf8").then((value) => JSON.parse(value) as { scripts?: Record<string, string> }),
readFile(".nvmrc", "utf8").then((value) => value.trim()),
]);
const packageScripts = packageDocument.scripts ?? {};
const failures: string[] = [];
if (!/^\d+\.\d+\.\d+$/u.test(nodeVersion)) {
failures.push(".nvmrc must contain one exact Node.js semantic version");
}
for (const script of [
"build:release-candidate",
"verify:local-evidence",
"verify:promotion",
"generate:ci-workflow",
"check:ci-workflow",
"check:ci",
]) {
if (!packageScripts[script]) failures.push(`package script missing ${script}`);
}
for (const removedScript of [
"build:release",
"verify:supply-chain",
"verify:supply-chain:promotion",
]) {
if (packageScripts[removedScript]) failures.push(`legacy package script remains ${removedScript}`);
}
if (/\b(?:build|rebuild)(?::[\w-]+)?\b/u.test(packageScripts["verify:promotion"] ?? "")) {
failures.push("verify:promotion must not build or rebuild candidate bytes");
}
failures.push(...validatePackageScriptGraph(packageScripts, "check:ci"));
failures.push(
...validateInstallScriptPolicy(
packageScripts,
[...new Set(contract.commands.map(({ script }) => script))],
),
);
// 12-04. Whether every test file and verification script is reached by a
// gate is checked by check:ci:gating (scripts/check-ci-gating.ts) in the main
// stage (FE-GATE-029), not on every pull request (design-docs
// repo-structure/03-ci.md F2).
const immutable = index.gates.get("FE-GATE-015");
const immutableCommands = immutable?.commandIds.map((id) => index.commands.get(id)?.script);
if (JSON.stringify(immutableCommands) !== JSON.stringify(["build:release-candidate", "verify:local-evidence"])) {
failures.push("FE-GATE-015 must build candidate bytes once and verify local evidence only");
}
const architecture = index.gates.get("FE-GATE-010");
if (!architecture?.commandIds.some((id) => index.commands.get(id)?.script === "check:ci")) {
failures.push("a blocking gate must execute check:ci");
}
if (!architecture?.evidenceArtifactIds.some((id) => index.artifacts.get(id)?.path === "artifacts/quality/ci-contract.json")) {
failures.push("FE-GATE-010 must publish the typed CI contract report");
}
const expectedGateIds = CANONICAL_GATE_IDS;
const passingResults: Record<string, GateResult> = Object.fromEntries(
expectedGateIds.map((gateId) => [gateId, "PASS"]),
);
const allPass = evaluatePromotionReadiness(passingResults);
const negativeFixtures: Array<{
readiness: keyof typeof PROMOTION_FORMULA;
failedGate: string;
passed: boolean;
}> = [];
for (const readiness of Object.keys(PROMOTION_FORMULA) as Array<keyof typeof PROMOTION_FORMULA>) {
const failedGate = PROMOTION_FORMULA[readiness][0];
if (!failedGate) throw new TypeError(`${readiness} has no configured gates`);
const evaluated = evaluatePromotionReadiness({ ...passingResults, [failedGate]: "FAIL" });
const passed = evaluated[readiness] === false;
negativeFixtures.push({ readiness, failedGate, passed });
if (!passed) failures.push(`${readiness} did not fail closed`);
}
if (!Object.values(allPass).every(Boolean)) failures.push("all-PASS formula did not produce every readiness state");
const renderedWorkflow = renderCiWorkflow(contract, productGates);
const workflowCheck = await generateCiWorkflow({
root: process.cwd(),
contract,
productGates,
check: true,
});
if (!workflowCheck.matches) {
failures.push(
`generated workflow drift at byte ${workflowCheck.firstDifferenceByte ?? "missing"}, line ${workflowCheck.firstDifferenceLine ?? "missing"}`,
);
}
let checkedWorkflowBytes = Buffer.from(renderedWorkflow, "utf8");
try {
checkedWorkflowBytes = await readFile(workflowCheck.target);
} catch (error) {
failures.push(`generated workflow is unreadable: ${error instanceof Error ? error.message : String(error)}`);
}
failures.push(
...workflowGateExecutionFailures(contract, checkedWorkflowBytes.toString("utf8"), productGates),
);
const report = ciContractReportSchema.parse({
schemaVersion: 2,
nodeVersion,
gateCount: contract.gates.length,
commandDefinitionCount: contract.commands.length,
commandReferenceCount: contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0),
artifactCount: contract.artifacts.length,
jobCount: contract.jobs.length,
workflowSha256: createHash("sha256").update(checkedWorkflowBytes).digest("hex"),
durationStatus: contract.retention.durationStatus,
negativeFixtures,
failures,
passed: failures.length === 0,
});
await writeValidatedJsonArtifact({
path: "artifacts/quality/ci-contract.json",
schema: ciContractReportSchema,
value: report,
});
if (failures.length > 0) {
process.stderr.write(`CI contract failed:\n${failures.join("\n")}\n`);
process.exit(1);
}
process.stdout.write(`CI contract: ${CANONICAL_GATE_IDS.length} gates, strict v2 graph and generated workflow model PASS\n`);