Files
clean-architecture-frontend…/scripts/run-ci-gate.ts
DongHyeonka 8fe5c4c59f fix(ci): FE-GATE-013의 PR 선택을 job에서 보고 컨테이너에 들어간다
문제: PR run에서 `ci:gate`는 경로표(config/ci/pr-gate-selection.json)가
고르지 않은 게이트를 건너뛴다. 판정은 job env의 `CI_PR_BASE_REF`로
한다. FE-GATE-013만은 workflow step이
`scripts/run-in-system-container.sh corepack pnpm ci:gate -- FE-GATE-013`
이라 판정이 컨테이너 안에서 일어난다. 래퍼의 `pass_env`에는 그 변수가
없다. 그래서 013에 안 닿는 PR(문서만 바꾼 PR 등)에서도 컨테이너를
띄우고 013을 끝까지 돌린다. 결과는 맞고 runner 3~5분을 쓴다.

고른 방법: workflow step을
`corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment`로
그린다. `ci:gate`는 job에서 PR 선택을 먼저 본다. 건너뛰면 건너뜀 줄과
게이트 로그만 남기고 끝난다. 돌면 계약의 `hostEnvironment`가 정한
래퍼(`HOST_ENVIRONMENT_ENTRY`)로 `corepack pnpm ci:gate -- FE-GATE-013`을
돌리고 그 종료 코드로 끝난다. 래퍼가 신호로 죽으면 신호 이름을 적고
128+번호로 끝난다(래퍼를 직접 부르던 step 셸과 같다). 컨테이너에는
base 브랜치를 넘기지 않으니 안에서 다시 고르거나 fetch하지 않는다.
`scripts/verify.sh`는 지금처럼 래퍼로 바로 감싼다. 실행 검사
(`workflowGateExecutionFailures`)는 계약이 정한 명령과 같은 run 줄만
센다: host 게이트는 플래그를 붙인 줄, 다른 게이트는 플래그 없는 줄.
버린 것:
- `pass_env`에 `CI_PR_BASE_REF`만 더하기: 컨테이너 안 `git fetch`
  (`runGit`의 spawnSync에 timeout 없음)가 막히면 job이 멈출 수 있고,
  건너뛰어도 컨테이너 부팅·복사 시간은 그대로 든다.
- workflow 셸 분기(`판정 || 래퍼`): 종료 코드로 흐름을 정해, 판정
  스크립트가 죽은 경우와 「돌아라」가 구분되지 않는다.
- 선택만 하는 step + step output: 생성기와 step 종류가 늘고, 선택
  step이 실패하면 job이 다른 이유로 빨개진다.
- 플래그 없이 `ci:gate`가 늘 감싸기: 컨테이너 안의 `ci:gate`도 다시
  감싸려 하고, `VERIFY_HOST_ENVIRONMENT=off`(컨테이너를 못 띄우는
  호스트) 경로가 깨진다.

위험·한계: 프로세스 층이 corepack → pnpm → node → 래퍼로 하나 는다.
run 취소 때 신호가 래퍼의 정리(trap)까지 가는지는 실제로 취소해 보지
않았다. 시험은 래퍼 대신 stand-in을 쓰므로, 진짜 래퍼가 이 길로 도는
것은 desktop에서 한 번 따로 돌렸다(아래). 건너뛰는 길이 CI에서 처음
지나는 것은 이 변경 병합 뒤 013을 고르지 않는 첫 PR run이다(이
변경은 scripts/를 바꿔 013을 고른다). matrix·release job 생성은
`hostEnvironment`를 보지 않는다. 지금 host 게이트는 013 하나이고
sequence job에 있다. 시험 timeout은 desktop에서 잰 가장 긴 시험
3688ms(FE-GATE-005의 test:unit, load 14)로 `childProcessTimeout`(60s)을
준다.

검증(desktop `scripts/verify.sh`, 깨끗한 worktree):
- RED: 기준 972139e6 + 새 시험 → 건너뜀 시험(컨테이너 기동 파일이
  생김)과 진입 시험(래퍼로 안 들어감) 실패, 닿는 PR 시험은 통과(지키는
  시험). 리뷰 반영 전 트리 + 새 신호 시험 → 신호 시험만 실패(stderr에
  신호 줄 없음).
- GREEN: `node scripts/run-vitest.ts run
  tests/unit/ci-gate-host-environment.test.ts` 3회 연속 5 통과(최장
  1114ms, load 14), `tests/unit/ci-workflow-generation.test.ts` 통과.
- 컨테이너에 base 브랜치를 안 넘기는 시험은 진짜 래퍼를 docker
  stand-in으로 돌려 `docker exec`의 `-e` 이름을 본다. 변이(래퍼
  `pass_env`에 `CI_PR_BASE_REF`를 더함)에서 그 시험만 실패.
- `lint`·`check:types` rc=0.
- 진짜 래퍼: CI env로 `corepack pnpm ci:gate -- FE-GATE-013
  --enter-host-environment` → 래퍼가 컨테이너를 띄우고 안에서
  `ci:gate -- FE-GATE-013`이 PASS, rc=0(133s), 게이트 로그가
  `artifacts/quality/gates/`로 돌아옴.
- 노트북 `scripts/verify.sh hooks`, `scripts/verify.sh docs` 통과.

Refs: fe-ci-next (2)
2026-11-20 00:43:00 +09:00

306 lines
10 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { lstat } from "node:fs/promises";
import { constants as osConstants } from "node:os";
import path from "node:path";
import {
ciCheckoutIdentityFailures,
ciBuildEnvironmentFailures,
isValidCommitSha,
isValidSourceDateEpoch,
} from "./lib/build-environment.ts";
import { classifyGateStepResult } from "./lib/ci-step-result.ts";
import {
ENTER_HOST_ENVIRONMENT_FLAG,
HOST_ENVIRONMENT_ENTRY,
withCiGatePreflight,
} from "./contracts/ci-gates.ts";
import { validateCiArtifact } from "./lib/ci-artifact-validator.ts";
import { formatGateFailure } from "./lib/ci-gate-failure.ts";
import { writeCiGateLogAtomic } from "./lib/ci-gate-log.ts";
import { prGateSkipReason, skippedGateLine } from "./lib/pr-gate-selection.ts";
const requestedGateId = process.argv
.slice(2)
.find((argument) => /^FE-GATE-\d{3}$/.test(argument));
await withCiGatePreflight(
process.cwd(),
requestedGateId,
async ({ contractIndex, gateId, gate }) => {
const logArtifact = contractIndex.artifacts.get(gate.logArtifactId);
if (!logArtifact) throw new TypeError(`CI gate log artifact disappeared: ${gate.logArtifactId}`);
const logSchema = contractIndex.artifactSchemas.get(logArtifact.schemaId);
if (!logSchema || logSchema.kind !== "text") {
throw new TypeError(`CI gate log schema must be bounded text: ${logArtifact.schemaId}`);
}
// A PR run skips a merge gate whose inputs the PR did not change
// (config/ci/pr-gate-selection.json); main and release runs run it.
const skipReason = prGateSkipReason(gateId, process.env, process.cwd());
if (skipReason !== undefined) {
const line = skippedGateLine(gateId, skipReason);
await writeCiGateLogAtomic({
root: process.cwd(),
relativePath: logArtifact.path,
content: `${line}\n`,
maxBytes: logSchema.maxBytes,
});
process.stdout.write(`${line}\n`);
return;
}
// A gate with a host environment runs there (config/ci/gates.json
// hostEnvironment). The workflow asks for that with the flag, so the PR
// selection above is decided in the job, which has the PR's base branch, and
// a gate the PR skips starts no container. Inside, the gate runs as a plain
// `ci:gate`; the container has no base branch, so it does not select again.
if (process.argv.includes(ENTER_HOST_ENVIRONMENT_FLAG)) {
const entry = gate.hostEnvironment ? HOST_ENVIRONMENT_ENTRY[gate.hostEnvironment] : undefined;
if (!entry) {
throw new TypeError(`${gateId} has no host environment to enter (config/ci/gates.json hostEnvironment)`);
}
const entered = spawnSync(entry, ["corepack", "pnpm", "ci:gate", "--", gateId], {
stdio: "inherit",
env: process.env,
});
if (entered.error) throw entered.error;
if (entered.signal) {
// An OOM kill or a cancelled run: name the signal and end as the step's
// shell did when it ran the wrapper itself (128 + the signal number).
process.stderr.write(`${gateId}: ${entry} ended on ${entered.signal}\n`);
process.exit(128 + osConstants.signals[entered.signal]);
}
process.exit(entered.status ?? 1);
}
const output: string[] = [];
let outputBytes = 0;
let passed = true;
const DEFAULT_STEP_TIMEOUT_MS = 30 * 60 * 1_000;
const MAX_STEP_OUTPUT_BYTES = 16 * 1024 * 1_024;
const LOG_DIAGNOSTIC_RESERVE_BYTES = 4_096;
const freshlyProducedArtifactIds = new Set<string>();
const commandGeneratedEvidence = gate.evidenceArtifactIds
.map((artifactId) => contractIndex.artifacts.get(artifactId))
.filter((artifact) => artifact?.production === "command-generated");
async function observeArtifactGeneration(relativePath: string): Promise<string> {
try {
const metadata = await lstat(path.join(process.cwd(), relativePath), {
bigint: true,
});
return [
metadata.dev,
metadata.ino,
metadata.size,
metadata.mtimeNs,
metadata.ctimeNs,
].join(":");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing";
throw error;
}
}
const appendOutput = (...values: readonly string[]): boolean => {
for (const value of values.filter(Boolean)) {
const addedBytes = Buffer.byteLength(value, "utf8") + 1;
if (outputBytes + addedBytes > logSchema.maxBytes) return false;
output.push(value);
outputBytes += addedBytes;
}
return true;
};
const gateEnvironment = { ...process.env };
if (gateEnvironment.CI === "true") {
const commitMetadata = spawnSync(
"git",
["show", "-s", "--format=%H%n%ct", "HEAD"],
{ encoding: "utf8" },
);
const [commitSha = "", sourceDateEpoch = ""] =
commitMetadata.stdout.trim().split(/\r?\n/);
if (
commitMetadata.status === 0 &&
isValidCommitSha(commitSha) &&
isValidSourceDateEpoch(sourceDateEpoch)
) {
if (!gateEnvironment.SOURCE_DATE_EPOCH?.trim()) {
gateEnvironment.SOURCE_DATE_EPOCH = sourceDateEpoch;
appendOutput(`derived SOURCE_DATE_EPOCH=${sourceDateEpoch} from HEAD`);
}
for (const failure of ciCheckoutIdentityFailures(gateEnvironment, {
commitSha,
sourceDateEpoch,
})) {
appendOutput(failure);
passed = false;
}
} else {
appendOutput(
"unable to resolve the checked-out commit identity and timestamp",
commitMetadata.stderr,
);
passed = false;
}
}
for (const failure of ciBuildEnvironmentFailures(gateEnvironment)) {
appendOutput(failure);
passed = false;
}
for (const variable of gate.requiresEnvironment ?? []) {
if (!gateEnvironment[variable]) {
appendOutput(`missing required environment: ${variable}`);
passed = false;
}
}
let failedCommand: string | undefined;
if (passed) {
for (const commandId of gate.commandIds) {
const step = contractIndex.commands.get(commandId);
if (!step) throw new TypeError(`CI gate command disappeared after validation: ${commandId}`);
const producedArtifacts = commandGeneratedEvidence.filter((artifact) =>
artifact.producerCommandIds.includes(commandId)
);
const generationBefore = new Map(
await Promise.all(
producedArtifacts.map(async (artifact) => [
artifact.id,
await observeArtifactGeneration(artifact.path),
] as const),
),
);
const commandLine = `$ corepack pnpm ${step.script} ${(step.args ?? []).join(" ")}`.trim();
if (!appendOutput(commandLine) || logSchema.maxBytes - outputBytes <= LOG_DIAGNOSTIC_RESERVE_BYTES) {
appendOutput("gate aggregate output budget exhausted before command execution");
passed = false;
break;
}
const result = spawnSync(
"corepack",
["pnpm", step.script, ...(step.args ?? [])],
{
encoding: "utf8",
env: gateEnvironment,
timeout: step.timeoutMs ?? DEFAULT_STEP_TIMEOUT_MS,
maxBuffer: Math.min(
MAX_STEP_OUTPUT_BYTES,
logSchema.maxBytes - outputBytes - LOG_DIAGNOSTIC_RESERVE_BYTES,
),
},
);
const stdout = result.stdout ?? "";
const stderr = result.stderr ?? "";
if (!appendOutput(stdout, stderr)) {
appendOutput("gate aggregate output exceeded the bounded log schema");
passed = false;
break;
}
const expectation = step.expect === "pass"
? ({ kind: "pass" } as const)
: step.expectedExitCode !== undefined && step.expectedDiagnosticId !== undefined
? ({
kind: "fail",
expectedExitCode: step.expectedExitCode,
expectedDiagnosticId: step.expectedDiagnosticId,
} as const)
: (() => {
throw new TypeError(`negative command lost its validated identity: ${step.id}`);
})();
const classification = classifyGateStepResult(expectation, {
status: result.status,
signal: result.signal,
stdout,
stderr,
...(result.error
? { error: { code: (result.error as NodeJS.ErrnoException).code } }
: {}),
});
if (!appendOutput(`classification: ${classification.kind}`)) passed = false;
if (!classification.expectationMet) {
failedCommand = commandLine;
appendOutput(
`expectation failed: expected ${step.expect}, exit=${result.status}, signal=${result.signal ?? "none"}`,
...(step.expect === "fail"
? [
`expected negative fixture identity: exit=${step.expectedExitCode}, diagnostic=${JSON.stringify(step.expectedDiagnosticId)}`,
]
: []),
...(classification.kind === "INFRASTRUCTURE_FAILURE"
? [`infrastructure failure: ${classification.detail}`]
: []),
);
passed = false;
break;
}
for (const artifact of producedArtifacts) {
const generationAfter = await observeArtifactGeneration(artifact.path);
if (generationAfter !== generationBefore.get(artifact.id)) {
freshlyProducedArtifactIds.add(artifact.id);
}
}
}
}
if (passed) {
for (const artifact of commandGeneratedEvidence) {
if (!freshlyProducedArtifactIds.has(artifact.id)) {
appendOutput(`command-generated evidence was not freshly produced: ${artifact.path}`);
passed = false;
}
}
}
await writeCiGateLogAtomic({
root: process.cwd(),
relativePath: logArtifact.path,
content: `${output.filter(Boolean).join("\n")}\n`,
maxBytes: logSchema.maxBytes,
});
if (passed) {
const validationIds = [...new Set([gate.logArtifactId, ...gate.evidenceArtifactIds])];
for (const artifactId of validationIds) {
const artifact = contractIndex.artifacts.get(artifactId);
if (!artifact) throw new TypeError(`CI artifact disappeared: ${artifactId}`);
const schema = contractIndex.artifactSchemas.get(artifact.schemaId);
if (!schema) throw new TypeError(`CI artifact schema disappeared: ${artifact.schemaId}`);
try {
await validateCiArtifact({ root: process.cwd(), artifact, schema });
if (!appendOutput(`validated evidence: ${artifact.path} (${schema.id})`)) passed = false;
} catch (error) {
appendOutput(
`invalid evidence: ${artifact.path}: ${error instanceof Error ? error.message : String(error)}`,
);
passed = false;
}
}
if (!passed) {
await writeCiGateLogAtomic({
root: process.cwd(),
relativePath: logArtifact.path,
content: `${output.filter(Boolean).join("\n")}\n`,
maxBytes: logSchema.maxBytes,
});
}
}
if (!passed) {
process.stderr.write(
`${formatGateFailure({
gateId,
gateName: gate.name,
logPath: logArtifact.path,
failedCommand,
output,
})}\n`,
);
process.exit(1);
}
process.stdout.write(
`${gateId} ${gate.name}: PASS (${gate.retentionClassId})\n`,
);
},
);