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
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, main950ea11a위, 트리e031a8a5): 14개 전부 rc=0(008 282초, 020 404초). gate FE-GATE-029 rc=0.
1485 lines
66 KiB
TypeScript
1485 lines
66 KiB
TypeScript
import { readFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
|
|
import { z } from "zod";
|
|
|
|
import { DEPENDENCY_ADVISORIES_RECORD_PATH } from "../lib/dependency-advisories.ts";
|
|
import { PR_BASE_REF_VARIABLE } from "../lib/pr-gate-selection.ts";
|
|
import { selectRepositoryPaths } from "../lib/repository-layout.ts";
|
|
import { PROMOTION_FORMULA } from "../lib/promotion-readiness.ts";
|
|
import {
|
|
RELEASE_CANDIDATE_EVIDENCE_PATHS,
|
|
RELEASE_CANDIDATE_MANIFEST_PATH,
|
|
} from "../lib/release-candidate.ts";
|
|
import {
|
|
validateInstallScriptPolicy,
|
|
validateNpmScopeEnvironment,
|
|
validatePackageScriptGraph,
|
|
} from "../lib/package-script-graph.ts";
|
|
import { loadProductCiOverlay, withProductDeployment } from "./product-ci-overlay.ts";
|
|
import { PROMOTED_UPLOAD_PATHS } from "./promotion-artifacts.ts";
|
|
|
|
const ciActionRegistrationSchema = z
|
|
.object({
|
|
repository: z
|
|
.string()
|
|
.regex(
|
|
/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u,
|
|
"CI action repository must be an absolute upstream GitHub URL",
|
|
),
|
|
revision: z
|
|
.string()
|
|
.regex(/^[0-9a-f]{40}$/u, "CI action revision must be a full 40-hex commit SHA"),
|
|
version: z.string().min(1).max(64),
|
|
})
|
|
.strict()
|
|
.readonly();
|
|
|
|
const ciActionRegistrySchema = z
|
|
.object({
|
|
checkout: ciActionRegistrationSchema,
|
|
setupNode: ciActionRegistrationSchema,
|
|
uploadArtifact: ciActionRegistrationSchema,
|
|
downloadArtifact: ciActionRegistrationSchema,
|
|
cache: ciActionRegistrationSchema,
|
|
})
|
|
.strict()
|
|
.readonly();
|
|
|
|
export type CiActionRegistry = z.infer<typeof ciActionRegistrySchema>;
|
|
export type CiActionId = keyof CiActionRegistry;
|
|
|
|
export function parseCiActionRegistry(value: unknown): CiActionRegistry {
|
|
const result = ciActionRegistrySchema.safeParse(value);
|
|
if (!result.success) {
|
|
const diagnostic = result.error.issues
|
|
.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`)
|
|
.join("\n");
|
|
throw new TypeError(`CI action registry invalid:\n${diagnostic}`);
|
|
}
|
|
return result.data;
|
|
}
|
|
|
|
export const CI_ACTION_REGISTRY = parseCiActionRegistry({
|
|
checkout: {
|
|
repository: "https://github.com/actions/checkout",
|
|
revision: "34e114876b0b11c390a56381ad16ebd13914f8d5",
|
|
version: "v4.3.1",
|
|
},
|
|
setupNode: {
|
|
repository: "https://github.com/actions/setup-node",
|
|
revision: "49933ea5288caeca8642d1e84afbd3f7d6820020",
|
|
version: "v4.4.0",
|
|
},
|
|
uploadArtifact: {
|
|
repository: "https://github.com/ChristopherHX/gitea-upload-artifact",
|
|
revision: "81f940d004763f986ba3582c007fd842dd5cb0d7",
|
|
version: "v4 branch",
|
|
},
|
|
downloadArtifact: {
|
|
repository: "https://github.com/ChristopherHX/gitea-download-artifact",
|
|
revision: "75635f32b4c1c41c4b3d64e8f85210112ed4c9c7",
|
|
version: "v4 branch",
|
|
},
|
|
// The same pin as the paired backend's JDK, Gradle and Trivy caches.
|
|
cache: {
|
|
repository: "https://github.com/actions/cache",
|
|
revision: "0057852bfaa89a56745cba8c7296529d2fc39830",
|
|
version: "v4.3.0",
|
|
},
|
|
});
|
|
|
|
const actionIdByStepKind = Object.freeze({
|
|
checkout: "checkout",
|
|
"setup-node": "setupNode",
|
|
upload: "uploadArtifact",
|
|
download: "downloadArtifact",
|
|
"dependency-cache": "cache",
|
|
} as const satisfies Readonly<Record<string, CiActionId>>);
|
|
|
|
export function resolveCiActionUses(actionId: CiActionId): string {
|
|
const action = CI_ACTION_REGISTRY[actionId];
|
|
if (!action) throw new TypeError(`unknown CI action: ${String(actionId)}`);
|
|
return `${action.repository}@${action.revision}`;
|
|
}
|
|
|
|
/** An action a registered repository holds below its root (`actions/cache/restore`), at the same pin. */
|
|
export function resolveCiSubActionUses(actionId: CiActionId, subpath: "restore"): string {
|
|
const action = CI_ACTION_REGISTRY[actionId];
|
|
if (!action) throw new TypeError(`unknown CI action: ${String(actionId)}`);
|
|
return `${action.repository}/${subpath}@${action.revision}`;
|
|
}
|
|
|
|
/**
|
|
* Decision (2026-11-13, lead): the dependency cache is for the merge jobs
|
|
* only; the jobs that produce supply-chain evidence install fresh every time
|
|
* (docs/work/reference/decisions.md). A merge job restores the Node toolcache, the corepack
|
|
* download and pnpm's store and metadata cache (with its record of the
|
|
* lockfile's supply-chain verification) before setup-node, keyed by
|
|
* `.nvmrc` and the lockfile. Only a run on main saves an entry, the paired
|
|
* backend's rule for its caches: an entry is trusted input to the next run
|
|
* (the verification record lets pnpm skip the check), so a branch must not
|
|
* write one. The frozen install always runs after it: a missing or damaged
|
|
* entry only makes pnpm download what it lacks, and node_modules is the same
|
|
* (desktop, 2026-11-13: cold 13.9 s, warm 1.6 s, 40 broken store and 40
|
|
* broken metadata files 3.6 s with 27 packages fetched again; the same tree
|
|
* hash in all five installs).
|
|
*
|
|
* The cache folder is outside the checkout, on its filesystem
|
|
* (scripts/ci/dependency-cache-root.sh): with the store in the job's `/tmp`,
|
|
* a warm runner install still took 17 to 26 s, as pnpm copied node_modules
|
|
* across filesystems (run 230). The script logs the devices it compared and
|
|
* the load average at the job's start, and sets the variables below through
|
|
* `$GITHUB_ENV`, so every pnpm call of the job, the system container's
|
|
* included, reads the same folder.
|
|
*/
|
|
export const DEPENDENCY_CACHE = Object.freeze({
|
|
keyPrefix: "fe-dependencies-${{ runner.os }}-${{ runner.arch }}-",
|
|
// `.nvmrc` and `pnpm-lock.yaml` (config/repository-layout.json).
|
|
keyInputs: selectRepositoryPaths("dependency-cache-key"),
|
|
rootStepId: "dependency-cache-root",
|
|
rootScript: "scripts/ci/dependency-cache-root.sh",
|
|
/** Folders outside the checkout to try, in order (shell words). */
|
|
rootCandidates: Object.freeze(['"$RUNNER_TEMP"', '"$(dirname "$GITHUB_WORKSPACE")"'] as const),
|
|
paths: Object.freeze([
|
|
"/opt/hostedtoolcache/node",
|
|
"${{ steps.dependency-cache-root.outputs.root }}",
|
|
] as const),
|
|
/** What the script writes to `$GITHUB_ENV`. */
|
|
environmentNames: Object.freeze(["COREPACK_HOME", "PNPM_CONFIG_STORE_DIR", "PNPM_CONFIG_CACHE_DIR"] as const),
|
|
/** The jobs that may hold the step: the three merge jobs. */
|
|
jobIds: Object.freeze(["merge_static", "merge_test", "merge_browser"] as const),
|
|
});
|
|
|
|
export function resolveCiStepActionUses(stepKind: string): string | null {
|
|
const actionId = actionIdByStepKind[stepKind as keyof typeof actionIdByStepKind];
|
|
return actionId ? resolveCiActionUses(actionId) : null;
|
|
}
|
|
|
|
function hasAsciiControl(value: string): boolean {
|
|
return [...value].some((character) => {
|
|
const codePoint = character.codePointAt(0)!;
|
|
return codePoint <= 0x1f || codePoint === 0x7f;
|
|
});
|
|
}
|
|
|
|
function hasForbiddenLineOrControl(value: string): boolean {
|
|
return [...value].some((character) => {
|
|
const codePoint = character.codePointAt(0)!;
|
|
return (
|
|
codePoint <= 0x1f ||
|
|
codePoint === 0x7f ||
|
|
codePoint === 0x85 ||
|
|
codePoint === 0x2028 ||
|
|
codePoint === 0x2029
|
|
);
|
|
});
|
|
}
|
|
|
|
const nonEmpty = z
|
|
.string()
|
|
.min(1)
|
|
.max(4_096)
|
|
.refine((value) => !hasForbiddenLineOrControl(value), "control and Unicode line-break characters are forbidden")
|
|
.refine((value) => value === value.trim(), "leading/trailing whitespace is forbidden");
|
|
const id = nonEmpty.max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/u);
|
|
const repositoryPath = nonEmpty.superRefine((value, context) => {
|
|
if (
|
|
value.includes("\\") ||
|
|
value.includes("\0") ||
|
|
path.posix.isAbsolute(value) ||
|
|
path.posix.normalize(value) !== value ||
|
|
value === "." ||
|
|
value === ".." ||
|
|
value.startsWith("../") ||
|
|
value.includes("/../")
|
|
) {
|
|
context.addIssue({ code: "custom", message: `unsafe repository path: ${value}` });
|
|
}
|
|
});
|
|
const workflowValue = nonEmpty.refine(
|
|
(value) => !value.includes("\0") && !value.includes("\r"),
|
|
"workflow values must not contain NUL or carriage returns",
|
|
);
|
|
const workflowPath = workflowValue.superRefine((value, context) => {
|
|
if (
|
|
value.includes("\\") ||
|
|
path.posix.isAbsolute(value) ||
|
|
path.posix.normalize(value) !== value ||
|
|
value === "." ||
|
|
value === ".." ||
|
|
value.startsWith("../") ||
|
|
value.includes("/../")
|
|
) {
|
|
context.addIssue({ code: "custom", message: `unsafe workflow path: ${value}` });
|
|
}
|
|
});
|
|
|
|
const commandSchema = z
|
|
.object({
|
|
id,
|
|
script: nonEmpty.regex(/^[A-Za-z0-9:_-]+$/u),
|
|
args: z.array(z.string().max(512).refine((value) => !hasAsciiControl(value), "command arguments contain controls")).max(32).optional(),
|
|
timeoutMs: z.number().int().min(1_000).max(3_600_000).optional(),
|
|
expect: z.enum(["pass", "fail"]),
|
|
expectedExitCode: z.number().int().min(1).max(255).optional(),
|
|
expectedDiagnosticId: nonEmpty.max(256).optional(),
|
|
})
|
|
.strict()
|
|
.superRefine((command, context) => {
|
|
const hasNegativeIdentity =
|
|
command.expectedExitCode !== undefined ||
|
|
command.expectedDiagnosticId !== undefined;
|
|
if (command.expect === "pass" && hasNegativeIdentity) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: `pass command carries negative identity: ${command.id}`,
|
|
});
|
|
}
|
|
if (
|
|
command.expect === "fail" &&
|
|
(command.expectedExitCode === undefined || !command.expectedDiagnosticId)
|
|
) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: `negative command lacks exact identity: ${command.id}`,
|
|
});
|
|
}
|
|
if (
|
|
command.expectedDiagnosticId &&
|
|
/[\n\r\0]/u.test(command.expectedDiagnosticId)
|
|
) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: `negative command diagnostic is unsafe: ${command.id}`,
|
|
});
|
|
}
|
|
});
|
|
|
|
const artifactSchemaSchema = z.discriminatedUnion("kind", [
|
|
z.object({ id, kind: z.literal("text"), maxBytes: z.number().int().min(1).max(268_435_456) }).strict(),
|
|
z
|
|
.object({
|
|
id,
|
|
kind: z.literal("json"),
|
|
maxBytes: z.number().int().min(1).max(268_435_456),
|
|
executableSchemaId: z.enum([
|
|
"automated-a11y",
|
|
"manual-a11y",
|
|
"architecture-dependency-report",
|
|
"design-system-contract",
|
|
"i18n-contract",
|
|
"diagnostics-contract",
|
|
"realtime-boundaries",
|
|
"optional-recipes",
|
|
"optional-recipe-fixtures",
|
|
"registry-compatibility-fixtures",
|
|
"reproducible-build",
|
|
"supply-chain-fixtures",
|
|
"supply-chain-provider-fixtures",
|
|
"compatibility-fixtures",
|
|
"documentation-review",
|
|
"hosting-headers",
|
|
"coverage-summary-v8",
|
|
"risk-coverage-v3",
|
|
"build-manifest",
|
|
"module-inventory",
|
|
"dependency-inventory",
|
|
"registry-snapshot",
|
|
"registry-governance-run",
|
|
"bundle-performance",
|
|
"sbom",
|
|
"provenance",
|
|
"dependency-diff",
|
|
"license-report",
|
|
"vulnerability-report",
|
|
"field-web-vitals",
|
|
"lab-performance",
|
|
"release-verification",
|
|
"runbook-record",
|
|
"supply-chain-verification",
|
|
"release-candidate",
|
|
"supply-chain-coherence",
|
|
"http-scenario-receipt",
|
|
"test-evidence-report",
|
|
"provider-vulnerability",
|
|
"provider-provenance",
|
|
"provider-verification",
|
|
"ci-contract-report",
|
|
"deployment-admission",
|
|
]),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
id,
|
|
kind: z.literal("json-schema"),
|
|
maxBytes: z.number().int().min(1).max(268_435_456),
|
|
})
|
|
.strict(),
|
|
z.object({ id, kind: z.literal("junit"), maxBytes: z.number().int().min(1).max(268_435_456) }).strict(),
|
|
z.object({ id, kind: z.literal("html"), maxBytes: z.number().int().min(1).max(268_435_456) }).strict(),
|
|
z.object({ id, kind: z.literal("markdown"), maxBytes: z.number().int().min(1).max(268_435_456) }).strict(),
|
|
z.object({ id, kind: z.literal("sarif"), maxBytes: z.number().int().min(1).max(268_435_456) }).strict(),
|
|
z
|
|
.object({ id, kind: z.literal("candidate-archive"), maxBytes: z.number().int().min(1).max(268_435_456) })
|
|
.strict(),
|
|
]);
|
|
|
|
const artifactBaseShape = { id, path: repositoryPath, schemaId: id } as const;
|
|
const artifactSchema = z.discriminatedUnion("production", [
|
|
z.object({ ...artifactBaseShape, production: z.literal("source-controlled") }).strict(),
|
|
z
|
|
.object({
|
|
...artifactBaseShape,
|
|
production: z.literal("command-generated"),
|
|
producerCommandIds: z.array(id).min(1).max(32),
|
|
})
|
|
.strict(),
|
|
z.object({ ...artifactBaseShape, production: z.literal("runner-generated") }).strict(),
|
|
]);
|
|
|
|
const gateSchema = z
|
|
.object({
|
|
id: z.string().regex(/^FE-GATE-\d{3}$/u),
|
|
name: nonEmpty.regex(/^[a-z0-9][a-z0-9-]*$/u),
|
|
commandIds: z.array(id).min(1).max(128),
|
|
logArtifactId: id,
|
|
evidenceArtifactIds: z.array(id).min(1).max(128),
|
|
retentionClassId: id,
|
|
requiresEnvironment: z.array(z.string().max(128).regex(/^[A-Z][A-Z0-9_]*$/u)).max(32).optional(),
|
|
/**
|
|
* 1105/12-01. What the runner host must provide for the gate to pass, one
|
|
* line each. The workflow shows them as comments beside the job's
|
|
* `runs-on`; a line cannot hold a line break, so it cannot leave the
|
|
* comment. They are part of the reviewed gate shape
|
|
* (canonicalGateShapeSha256): dropping or changing one needs a new
|
|
* contract baseline, like any other change to what a gate demands.
|
|
*/
|
|
hostRequirements: z.array(nonEmpty.max(512)).min(1).max(8).optional(),
|
|
/**
|
|
* Where the gate runs when the job container cannot meet its host
|
|
* requirements. "system-container": scripts/run-in-system-container.sh
|
|
* runs the gate in a disposable privileged systemd container
|
|
* (config/ci/system-container.Dockerfile), in CI through the runner's
|
|
* Docker daemon and on desktop through scripts/verify.sh.
|
|
*/
|
|
hostEnvironment: z.enum(["system-container"]).optional(),
|
|
})
|
|
.strict();
|
|
|
|
const stageSchema = z
|
|
.object({
|
|
id,
|
|
readiness: z.enum([
|
|
"MERGE_READY",
|
|
"RELEASE_READY",
|
|
"PROD_PROMOTION_READY",
|
|
"FIELD_SLO_READY",
|
|
"DOCUMENTATION_READY",
|
|
"MAIN_READY",
|
|
]),
|
|
needs: z.array(id).max(16),
|
|
gateIds: z.array(id).min(1).max(64),
|
|
})
|
|
.strict();
|
|
|
|
const environmentBindingSchema = z
|
|
.object({ name: z.string().regex(/^[A-Z][A-Z0-9_]*$/u), value: workflowValue })
|
|
.strict();
|
|
|
|
const checkoutStep = z.object({ kind: z.literal("checkout") }).strict();
|
|
const setupNodeStep = z.object({ kind: z.literal("setup-node") }).strict();
|
|
const frozenInstallStep = z.object({ kind: z.literal("frozen-install") }).strict();
|
|
const dependencyCacheStep = z.object({ kind: z.literal("dependency-cache") }).strict();
|
|
/**
|
|
* `image`: the job runs in Playwright's own image for the pinned
|
|
* @playwright/test version, which already holds the browsers and their OS
|
|
* libraries (tests/unit/ci-browser-image.test.ts keeps the versions equal).
|
|
* Without it the step downloads them, about 900 MB and 3 to 4 minutes a job.
|
|
*/
|
|
export const PLAYWRIGHT_JOB_IMAGE_PATTERN =
|
|
/^mcr\.microsoft\.com\/playwright:v(\d+\.\d+\.\d+)-noble@sha256:[0-9a-f]{64}$/u;
|
|
const browserInstallStep = z.object({
|
|
kind: z.literal("browser-install"),
|
|
image: z.string().regex(PLAYWRIGHT_JOB_IMAGE_PATTERN).optional(),
|
|
}).strict();
|
|
const runGateStep = z.object({ kind: z.literal("run-gate") }).strict();
|
|
const archiveCandidateStep = z
|
|
.object({
|
|
kind: z.literal("archive-candidate"),
|
|
stepId: id,
|
|
archivePath: workflowPath,
|
|
members: z.array(repositoryPath).min(1).max(128),
|
|
archiveOutputName: id,
|
|
distOutputName: id,
|
|
})
|
|
.strict();
|
|
const uploadStep = z
|
|
.object({
|
|
kind: z.literal("upload"),
|
|
transferId: id,
|
|
name: workflowValue,
|
|
paths: z.array(workflowPath).min(1).max(128),
|
|
always: z.boolean().optional(),
|
|
})
|
|
.strict();
|
|
const downloadStep = z
|
|
.object({ kind: z.literal("download"), transferId: id, path: workflowPath })
|
|
.strict();
|
|
const extractStep = z
|
|
.object({
|
|
kind: z.literal("extract"),
|
|
archivePath: workflowPath,
|
|
targetRoot: workflowPath,
|
|
})
|
|
.strict();
|
|
const providerStep = z
|
|
.object({
|
|
kind: z.literal("run-provider"),
|
|
provider: z.enum(["vulnerability", "provenance"]),
|
|
stepId: id,
|
|
})
|
|
.strict();
|
|
const validateProviderStep = z
|
|
.object({
|
|
kind: z.literal("validate-provider-evidence"),
|
|
provider: z.enum(["vulnerability", "provenance"]),
|
|
})
|
|
.strict();
|
|
const promotionStep = z
|
|
.object({ kind: z.literal("verify-promotion"), stepId: id })
|
|
.strict();
|
|
const cleanupPromotionStep = z
|
|
.object({ kind: z.literal("cleanup-promotion"), finalizerStepId: id })
|
|
.strict();
|
|
/**
|
|
* 1101/13-01. The project's own deployment of the promoted release: a package
|
|
* script, run after the steps before it. Without `script` the slot is empty;
|
|
* it reports `deployed=false` and FE-GATE-019 ends UNVERIFIED.
|
|
*/
|
|
const deployStep = z
|
|
.object({ kind: z.literal("deploy"), script: nonEmpty.regex(/^[A-Za-z0-9:_-]+$/u).optional() })
|
|
.strict();
|
|
|
|
const jobStepSchema = z.discriminatedUnion("kind", [
|
|
checkoutStep,
|
|
dependencyCacheStep,
|
|
setupNodeStep,
|
|
frozenInstallStep,
|
|
browserInstallStep,
|
|
runGateStep,
|
|
archiveCandidateStep,
|
|
uploadStep,
|
|
downloadStep,
|
|
extractStep,
|
|
providerStep,
|
|
validateProviderStep,
|
|
promotionStep,
|
|
cleanupPromotionStep,
|
|
deployStep,
|
|
]);
|
|
|
|
const jobSchema = z
|
|
.object({
|
|
id,
|
|
displayName: workflowValue,
|
|
kind: z.enum(["gate-matrix", "gate-sequence", "gate-single", "immutable", "provider", "promotion", "deployment"]),
|
|
needs: z.array(id).max(32),
|
|
condition: z.enum(["always", "needs-success", "merge", "main", "release", "production", "field", "documentation"]),
|
|
timeoutMinutes: z.number().int().positive(),
|
|
gateIds: z.array(id).max(64),
|
|
browserGateIds: z.array(id).max(64),
|
|
environment: z.array(environmentBindingSchema).max(32),
|
|
steps: z.array(jobStepSchema).min(1).max(64),
|
|
// 1101/13-03. What the runner of a job without a gate needs (the provider
|
|
// jobs' sandbox). Rendered beside its runner label like a gate's.
|
|
hostRequirements: z.array(nonEmpty.max(512)).min(1).max(8).optional(),
|
|
})
|
|
.strict();
|
|
|
|
const retentionSchema = z
|
|
.object({
|
|
durationStatus: nonEmpty,
|
|
classes: z.array(z.object({ id, policy: nonEmpty }).strict()).min(1).max(32),
|
|
})
|
|
.strict();
|
|
|
|
const ciGateContractBaseSchema = z
|
|
.object({
|
|
schemaVersion: z.literal(2),
|
|
providerAdapter: repositoryPath,
|
|
commands: z.array(commandSchema).min(1).max(256),
|
|
artifactSchemas: z.array(artifactSchemaSchema).min(1).max(128),
|
|
artifacts: z.array(artifactSchema).min(1).max(512),
|
|
gates: z.array(gateSchema).min(1).max(64),
|
|
stages: z.array(stageSchema).min(1).max(16),
|
|
jobs: z.array(jobSchema).min(1).max(32),
|
|
retention: retentionSchema,
|
|
})
|
|
.strict();
|
|
|
|
const ciGateContractSchema = ciGateContractBaseSchema.superRefine(
|
|
(contract, context) => validateContractSemantics(contract, context),
|
|
);
|
|
|
|
export type CiGateContract = z.infer<typeof ciGateContractSchema>;
|
|
export type CiGateCommand = CiGateContract["commands"][number];
|
|
export type CiGateArtifactSchema = CiGateContract["artifactSchemas"][number];
|
|
export type CiGateArtifact = CiGateContract["artifacts"][number];
|
|
export type CiGate = CiGateContract["gates"][number];
|
|
export type CiWorkflowJob = CiGateContract["jobs"][number];
|
|
export type CiWorkflowStep = CiWorkflowJob["steps"][number];
|
|
|
|
export type CiGateContractIndex = Readonly<{
|
|
commands: ReadonlyMap<string, CiGateCommand>;
|
|
artifactSchemas: ReadonlyMap<string, CiGateArtifactSchema>;
|
|
artifacts: ReadonlyMap<string, CiGateArtifact>;
|
|
gates: ReadonlyMap<string, CiGate>;
|
|
stages: ReadonlyMap<string, CiGateContract["stages"][number]>;
|
|
jobs: ReadonlyMap<string, CiWorkflowJob>;
|
|
retentionClasses: ReadonlyMap<string, CiGateContract["retention"]["classes"][number]>;
|
|
}>;
|
|
|
|
/**
|
|
* D-14. FE-GATE-016 (rollback-drill) ran the same FE-RB-005 drill as
|
|
* FE-GATE-025 and counted it twice toward production readiness. Its id stays
|
|
* retired so no later gate reuses it with a different meaning.
|
|
*/
|
|
export const RETIRED_GATE_IDS: readonly string[] = Object.freeze(["FE-GATE-016"]);
|
|
|
|
export const CANONICAL_GATE_IDS: readonly string[] = Object.freeze(
|
|
Array.from({ length: 30 }, (_, index) => `FE-GATE-${String(index + 1).padStart(3, "0")}`)
|
|
.filter((gateId) => !RETIRED_GATE_IDS.includes(gateId)),
|
|
);
|
|
|
|
function retentionRegistryFailures(contract: CiGateContract): string[] {
|
|
const expectedRetentionClasses = [
|
|
{ id: "merge-cycle", policy: "at least through pull-request readiness decision" },
|
|
{ id: "release-coherence", policy: "at least until the next release is promoted" },
|
|
{ id: "prod-drill", policy: "at least until the next production promotion decision" },
|
|
{ id: "field", policy: "through the 28-day window and aggregation" },
|
|
{ id: "documentation", policy: "through documentation readiness review" },
|
|
];
|
|
return JSON.stringify(contract.retention.classes) === JSON.stringify(expectedRetentionClasses)
|
|
? []
|
|
: ["retention registry must contain exactly the five canonical retention classes"];
|
|
}
|
|
|
|
export function parseCiGateContract(value: unknown): CiGateContract {
|
|
const result = ciGateContractSchema.safeParse(value);
|
|
if (!result.success) {
|
|
const diagnostic = result.error.issues
|
|
.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`)
|
|
.join("\n");
|
|
throw new TypeError(`CI gate contract invalid:\n${diagnostic}`);
|
|
}
|
|
const failures = retentionRegistryFailures(result.data);
|
|
if (failures.length > 0) {
|
|
throw new TypeError(`CI gate contract invalid:\n${failures.map((failure) => `root: ${failure}`).join("\n")}`);
|
|
}
|
|
return result.data;
|
|
}
|
|
|
|
export async function loadCiGateContract(
|
|
root = process.cwd(),
|
|
): Promise<CiGateContract> {
|
|
const [rawContract, rawPackage, overlay] = await Promise.all([
|
|
readFile(path.join(root, "config/ci/gates.json"), "utf8"),
|
|
readFile(path.join(root, "package.json"), "utf8"),
|
|
loadProductCiOverlay(root),
|
|
]);
|
|
const template = parseCiGateContract(JSON.parse(rawContract));
|
|
// 1103/12-07. The product fills the deployment slot in its own overlay; the
|
|
// filled contract is parsed again, so the template's slot rules hold.
|
|
const contract = overlay.deployment === null
|
|
? template
|
|
: parseCiGateContract(withProductDeployment(JSON.parse(rawContract), overlay.deployment));
|
|
const packageDocument = z
|
|
.object({ scripts: z.record(z.string(), z.string()).default({}) })
|
|
.passthrough()
|
|
.parse(JSON.parse(rawPackage));
|
|
// 1101/13-01. A filled deployment slot runs a package script in CI, under the
|
|
// same existence and script-graph rules as a gate command. So does a
|
|
// product merge gate (1103/12-07).
|
|
const deployScripts = [
|
|
...contract.jobs.flatMap(({ steps }) =>
|
|
steps.flatMap((step) => (step.kind === "deploy" && step.script ? [step.script] : [])),
|
|
),
|
|
...overlay.mergeGates.map(({ script }) => script),
|
|
];
|
|
const missing = [...contract.commands.map((command) => command.script), ...deployScripts]
|
|
.filter((script, index, scripts) => scripts.indexOf(script) === index)
|
|
.filter((script) => !packageDocument.scripts[script]);
|
|
if (missing.length > 0) {
|
|
throw new TypeError(`CI gate contract missing package scripts: ${missing.join(", ")}`);
|
|
}
|
|
const expectedCheckCi =
|
|
"corepack pnpm check:artifact-schemas && node scripts/check-ci-contract.ts && corepack pnpm check:ci-workflow";
|
|
if (packageDocument.scripts["check:ci"] !== expectedCheckCi) {
|
|
throw new TypeError("check:ci must use the exact canonical non-recursive orchestration");
|
|
}
|
|
const canonicalCheckCiDependencies = {
|
|
// R-0. The schema generator imports src, which loads the gitignored
|
|
// product index, so the index is rendered first.
|
|
"check:artifact-schemas":
|
|
"node scripts/generate-product-feature-index.ts && node scripts/generate-artifact-schemas.ts --check",
|
|
"check:ci-workflow": "node scripts/generate-ci-workflow.ts --check",
|
|
} as const;
|
|
for (const [script, expected] of Object.entries(canonicalCheckCiDependencies)) {
|
|
if (packageDocument.scripts[script] !== expected) {
|
|
throw new TypeError(`canonical check:ci dependency drift: ${script}`);
|
|
}
|
|
}
|
|
const contractEntryScripts = [
|
|
...new Set([...contract.commands.map((command) => command.script), ...deployScripts]),
|
|
];
|
|
const graphFailures = [
|
|
...validatePackageScriptGraph(packageDocument.scripts, "check:ci"),
|
|
...contractEntryScripts.flatMap((script) =>
|
|
validatePackageScriptGraph(packageDocument.scripts, script)
|
|
),
|
|
];
|
|
if (graphFailures.length > 0) {
|
|
throw new TypeError(
|
|
`CI package script graph invalid:\n${[...new Set(graphFailures)].join("\n")}`,
|
|
);
|
|
}
|
|
const installPolicyFailures = validateInstallScriptPolicy(
|
|
packageDocument.scripts,
|
|
contractEntryScripts,
|
|
);
|
|
if (installPolicyFailures.length > 0) {
|
|
throw new TypeError(
|
|
`CI package script install policy invalid:\n${installPolicyFailures.join("\n")}`,
|
|
);
|
|
}
|
|
return contract;
|
|
}
|
|
|
|
export async function withCiGatePreflight<Result>(
|
|
root: string,
|
|
gateId: string | undefined,
|
|
execute: (context: Readonly<{
|
|
contract: CiGateContract;
|
|
contractIndex: CiGateContractIndex;
|
|
gateId: string;
|
|
gate: CiGate;
|
|
}>) => Promise<Result> | Result,
|
|
): Promise<Result> {
|
|
const npmScopeEnvironmentFailures = validateNpmScopeEnvironment(process.env);
|
|
if (npmScopeEnvironmentFailures.length > 0) {
|
|
throw new TypeError(
|
|
`CI runner npm scope environment invalid:\n${npmScopeEnvironmentFailures.join("\n")}`,
|
|
);
|
|
}
|
|
const contract = await loadCiGateContract(root);
|
|
const contractIndex = indexCiGateContract(contract);
|
|
const gate = gateId ? contractIndex.gates.get(gateId) : undefined;
|
|
if (!gateId || !gate) {
|
|
throw new TypeError("CI gate id must be FE-GATE-001..FE-GATE-026");
|
|
}
|
|
return execute({ contract, contractIndex, gateId, gate });
|
|
}
|
|
|
|
export function indexCiGateContract(contract: CiGateContract): CiGateContractIndex {
|
|
return Object.freeze({
|
|
commands: new Map(contract.commands.map((entry) => [entry.id, entry])),
|
|
artifactSchemas: new Map(contract.artifactSchemas.map((entry) => [entry.id, entry])),
|
|
artifacts: new Map(contract.artifacts.map((entry) => [entry.id, entry])),
|
|
gates: new Map(contract.gates.map((entry) => [entry.id, entry])),
|
|
stages: new Map(contract.stages.map((entry) => [entry.id, entry])),
|
|
jobs: new Map(contract.jobs.map((entry) => [entry.id, entry])),
|
|
retentionClasses: new Map(contract.retention.classes.map((entry) => [entry.id, entry])),
|
|
});
|
|
}
|
|
|
|
function validateContractSemantics(
|
|
contract: z.infer<typeof ciGateContractBaseSchema>,
|
|
context: z.RefinementCtx,
|
|
): void {
|
|
const issue = (message: string, path: PropertyKey[] = []) =>
|
|
context.addIssue({ code: "custom", message, path });
|
|
if (contract.providerAdapter !== ".gitea/workflows/quality-gates.yml") {
|
|
issue("providerAdapter must target the canonical generated workflow");
|
|
}
|
|
const registries = [
|
|
["command", contract.commands],
|
|
["artifact schema", contract.artifactSchemas],
|
|
["artifact", contract.artifacts],
|
|
["gate", contract.gates],
|
|
["stage", contract.stages],
|
|
["job", contract.jobs],
|
|
["retention class", contract.retention.classes],
|
|
] as const;
|
|
for (const [label, entries] of registries) {
|
|
const seen = new Set<string>();
|
|
for (const entry of entries) {
|
|
if (seen.has(entry.id)) issue(`duplicate ${label} id: ${entry.id}`);
|
|
seen.add(entry.id);
|
|
}
|
|
}
|
|
|
|
const commandTuples = new Map<string, string>();
|
|
for (const command of contract.commands) {
|
|
const { id: _id, ...tuple } = command;
|
|
const key = JSON.stringify(tuple);
|
|
const previous = commandTuples.get(key);
|
|
if (previous) issue(`duplicate command tuple: ${previous}, ${command.id}`);
|
|
commandTuples.set(key, command.id);
|
|
}
|
|
const artifactPaths = new Map<string, string>();
|
|
for (const artifact of contract.artifacts) {
|
|
const previous = artifactPaths.get(artifact.path);
|
|
if (previous) issue(`duplicate artifact path: ${previous}, ${artifact.id}`);
|
|
artifactPaths.set(artifact.path, artifact.id);
|
|
}
|
|
|
|
const commandIds = new Set(contract.commands.map(({ id }) => id));
|
|
const schemaIds = new Set(contract.artifactSchemas.map(({ id }) => id));
|
|
const artifactIds = new Set(contract.artifacts.map(({ id }) => id));
|
|
const gateIds = new Set(contract.gates.map(({ id }) => id));
|
|
const stageIds = new Set(contract.stages.map(({ id }) => id));
|
|
const jobIds = new Set(contract.jobs.map(({ id }) => id));
|
|
const retentionIds = new Set(contract.retention.classes.map(({ id }) => id));
|
|
|
|
for (const artifact of contract.artifacts) {
|
|
if (!schemaIds.has(artifact.schemaId)) {
|
|
issue(`unknown artifact schema ${artifact.schemaId} for ${artifact.id}`);
|
|
}
|
|
if (artifact.production === "command-generated") {
|
|
if (new Set(artifact.producerCommandIds).size !== artifact.producerCommandIds.length) {
|
|
issue(`duplicate producer command reference for artifact: ${artifact.id}`);
|
|
}
|
|
for (const producerCommandId of artifact.producerCommandIds) {
|
|
if (!commandIds.has(producerCommandId)) {
|
|
issue(`unknown producer command ${producerCommandId} for ${artifact.id}`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for (const gate of contract.gates) {
|
|
if (new Set(gate.commandIds).size !== gate.commandIds.length) {
|
|
issue(`duplicate command reference within gate: ${gate.id}`);
|
|
}
|
|
if (new Set(gate.evidenceArtifactIds).size !== gate.evidenceArtifactIds.length) {
|
|
issue(`duplicate artifact reference within gate: ${gate.id}`);
|
|
}
|
|
for (const commandId of gate.commandIds) {
|
|
if (!commandIds.has(commandId)) issue(`unknown command ${commandId} for ${gate.id}`);
|
|
}
|
|
for (const artifactId of [gate.logArtifactId, ...gate.evidenceArtifactIds]) {
|
|
if (!artifactIds.has(artifactId)) issue(`unknown artifact ${artifactId} for ${gate.id}`);
|
|
}
|
|
const logArtifact = contract.artifacts.find(({ id }) => id === gate.logArtifactId);
|
|
if (logArtifact && logArtifact.production !== "runner-generated") {
|
|
issue(`gate log must be runner-generated: ${gate.id}`);
|
|
}
|
|
for (const artifactId of gate.evidenceArtifactIds) {
|
|
const artifact = contract.artifacts.find(({ id }) => id === artifactId);
|
|
if (
|
|
artifact?.production === "command-generated" &&
|
|
!artifact.producerCommandIds.some((producerCommandId) =>
|
|
gate.commandIds.includes(producerCommandId)
|
|
)
|
|
) {
|
|
issue(`gate lacks a bound producer command for ${artifact.id}: ${gate.id}`);
|
|
}
|
|
}
|
|
if (!retentionIds.has(gate.retentionClassId)) {
|
|
issue(`unknown retention class ${gate.retentionClassId} for ${gate.id}`);
|
|
}
|
|
}
|
|
const referencedRetentionClasses = new Set(
|
|
contract.gates.map(({ retentionClassId }) => retentionClassId),
|
|
);
|
|
for (const retentionClass of contract.retention.classes) {
|
|
if (!referencedRetentionClasses.has(retentionClass.id)) {
|
|
issue(`orphan retention class: ${retentionClass.id}`);
|
|
}
|
|
}
|
|
const referencedCommands = new Set(contract.gates.flatMap(({ commandIds }) => commandIds));
|
|
for (const command of contract.commands) {
|
|
if (!referencedCommands.has(command.id)) issue(`orphan command: ${command.id}`);
|
|
}
|
|
const referencedArtifacts = new Set(
|
|
contract.gates.flatMap((gate) => [gate.logArtifactId, ...gate.evidenceArtifactIds]),
|
|
);
|
|
for (const artifact of contract.artifacts) {
|
|
if (!referencedArtifacts.has(artifact.id)) issue(`orphan artifact: ${artifact.id}`);
|
|
}
|
|
const referencedSchemas = new Set(contract.artifacts.map(({ schemaId }) => schemaId));
|
|
for (const schema of contract.artifactSchemas) {
|
|
if (!referencedSchemas.has(schema.id)) issue(`orphan artifact schema: ${schema.id}`);
|
|
}
|
|
for (const stage of contract.stages) {
|
|
for (const dependency of stage.needs) {
|
|
if (dependency === stage.id) issue(`stage self dependency: ${stage.id}`);
|
|
else if (!stageIds.has(dependency)) issue(`unknown stage dependency ${dependency} for ${stage.id}`);
|
|
}
|
|
for (const gateId of stage.gateIds) {
|
|
if (!gateIds.has(gateId)) issue(`unknown gate ${gateId} for stage ${stage.id}`);
|
|
}
|
|
}
|
|
for (const cycle of findCycles(contract.stages.map((stage) => [stage.id, stage.needs] as const))) {
|
|
issue(`stage dependency cycle: ${cycle.join(" -> ")}`);
|
|
}
|
|
|
|
const expectedGateIds = CANONICAL_GATE_IDS;
|
|
if (JSON.stringify(contract.gates.map(({ id }) => id)) !== JSON.stringify(expectedGateIds)) {
|
|
issue(`gate registry must contain FE-GATE-001..030 without retired ${RETIRED_GATE_IDS.join(", ")} in canonical order`);
|
|
}
|
|
const expectedStages: ReadonlyArray<readonly [string, string, readonly string[], readonly string[]]> = [
|
|
["merge", "MERGE_READY", [], PROMOTION_FORMULA.MERGE_READY],
|
|
["release", "RELEASE_READY", ["merge"], PROMOTION_FORMULA.RELEASE_READY],
|
|
["production", "PROD_PROMOTION_READY", ["release"], PROMOTION_FORMULA.PROD_PROMOTION_READY],
|
|
["field", "FIELD_SLO_READY", ["production"], PROMOTION_FORMULA.FIELD_SLO_READY],
|
|
["documentation", "DOCUMENTATION_READY", [], PROMOTION_FORMULA.DOCUMENTATION_READY],
|
|
["main", "MAIN_READY", [], PROMOTION_FORMULA.MAIN_READY],
|
|
];
|
|
const stageShape = contract.stages.map(({ id, readiness, needs, gateIds }) => [id, readiness, needs, gateIds]);
|
|
if (JSON.stringify(stageShape) !== JSON.stringify(expectedStages)) {
|
|
issue("stage formula/order/ownership drift");
|
|
}
|
|
const stageOwners = new Map<string, string[]>();
|
|
for (const stage of contract.stages) {
|
|
for (const gateId of stage.gateIds) {
|
|
stageOwners.set(gateId, [...(stageOwners.get(gateId) ?? []), stage.id]);
|
|
}
|
|
}
|
|
for (const gateId of expectedGateIds) {
|
|
if ((stageOwners.get(gateId) ?? []).length !== 1) issue(`gate must belong to exactly one stage: ${gateId}`);
|
|
}
|
|
|
|
const owners = new Map<string, string[]>();
|
|
for (const job of contract.jobs) {
|
|
for (const [label, values] of [
|
|
["needs", job.needs],
|
|
["gateIds", job.gateIds],
|
|
["browserGateIds", job.browserGateIds],
|
|
] as const) {
|
|
if (new Set(values).size !== values.length) {
|
|
issue(`duplicate ${label} reference in job: ${job.id}`);
|
|
}
|
|
}
|
|
if (job.timeoutMinutes !== 45) issue(`job timeout must be 45 minutes: ${job.id}`);
|
|
for (const dependency of job.needs) {
|
|
if (dependency === job.id) issue(`job self dependency: ${job.id}`);
|
|
else if (!jobIds.has(dependency)) issue(`unknown job dependency ${dependency} for ${job.id}`);
|
|
}
|
|
for (const gateId of job.gateIds) {
|
|
if (!gateIds.has(gateId)) issue(`unknown gate ${gateId} for job ${job.id}`);
|
|
owners.set(gateId, [...(owners.get(gateId) ?? []), job.id]);
|
|
}
|
|
for (const browserGateId of job.browserGateIds) {
|
|
if (!job.gateIds.includes(browserGateId)) {
|
|
issue(`browser gate ${browserGateId} is not owned by ${job.id}`);
|
|
}
|
|
}
|
|
validateJobStepKinds(job, issue);
|
|
if (job.steps.some(({ kind }) => kind === "dependency-cache")) {
|
|
if (!(DEPENDENCY_CACHE.jobIds as readonly string[]).includes(job.id)) {
|
|
issue(`the dependency cache is for the merge jobs only: ${job.id}`);
|
|
}
|
|
for (const name of DEPENDENCY_CACHE.environmentNames) {
|
|
if (job.environment.some((binding) => binding.name === name)) {
|
|
issue(`job ${job.id} binds ${name}, which its dependency cache sets`);
|
|
}
|
|
}
|
|
}
|
|
for (const step of job.steps) {
|
|
const uses = resolveCiStepActionUses(step.kind);
|
|
if (uses && !/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+@[0-9a-f]{40}$/u.test(uses)) {
|
|
issue(`CI action ref is not an absolute upstream URL pinned to a full commit SHA: ${step.kind}`);
|
|
}
|
|
}
|
|
const envNames = new Set(job.environment.map(({ name }) => name));
|
|
for (const gateId of job.gateIds) {
|
|
const gate = contract.gates.find(({ id }) => id === gateId);
|
|
for (const required of gate?.requiresEnvironment ?? []) {
|
|
if (!envNames.has(required)) issue(`job ${job.id} lacks environment ${required} for ${gateId}`);
|
|
}
|
|
}
|
|
}
|
|
for (const gate of contract.gates) {
|
|
const gateOwners = owners.get(gate.id) ?? [];
|
|
if (gateOwners.length === 0) issue(`unowned gate: ${gate.id}`);
|
|
if (gateOwners.length > 1) issue(`multiply owned gate: ${gate.id} by ${gateOwners.join(", ")}`);
|
|
}
|
|
const expectedJobOwnership: Readonly<Record<string, readonly string[]>> = {
|
|
// The merge stage runs as three jobs, one install each (design-docs
|
|
// repo-structure/03-ci.md F1): checks that read the source and build it,
|
|
// tests, and the gates that need browsers. Each runs its gates one after
|
|
// another in this order; a failed gate does not skip the next.
|
|
// 15-01. The bundle budget (FE-GATE-012) runs on every PR: a feature that
|
|
// pushes initial JavaScript over budget fails before it merges, not at the
|
|
// next tagged release.
|
|
merge_static: ["FE-GATE-001", "FE-GATE-002", "FE-GATE-003", "FE-GATE-010", "FE-GATE-011", "FE-GATE-012"],
|
|
merge_test: ["FE-GATE-004", "FE-GATE-005", "FE-GATE-006", "FE-GATE-007", "FE-GATE-013", "FE-GATE-020"],
|
|
merge_browser: ["FE-GATE-008", "FE-GATE-009"],
|
|
release_gate: ["FE-GATE-014", "FE-GATE-026", "FE-GATE-028"],
|
|
immutable_build: ["FE-GATE-015", "FE-GATE-027"],
|
|
vulnerability_provider: [],
|
|
provenance_provider: [],
|
|
promotion: [],
|
|
// 1101/13-01. The project's deployment slot. It owns no gate, so a project
|
|
// fills it without touching gate ownership.
|
|
deployment: [],
|
|
production_gate: ["FE-GATE-019", "FE-GATE-021", "FE-GATE-022", "FE-GATE-023", "FE-GATE-024", "FE-GATE-025"],
|
|
field_gate: ["FE-GATE-018"],
|
|
documentation_gate: ["FE-GATE-017"],
|
|
// F2. The checkers' own negative fixtures and the gating coverage check
|
|
// run after a merge to main, not on every pull request. So do the optional
|
|
// runtime removal drills (FE-GATE-030, owner decision 2026-11-12 p): about
|
|
// seven of a pull request's thirty runner minutes, the same shape as the
|
|
// paired backend's nightly lanes.
|
|
main_gate: ["FE-GATE-029", "FE-GATE-030"],
|
|
};
|
|
// 1101/13-03. The provider jobs run FE-GATE-013's sandbox (systemd-run
|
|
// scope, bwrap with the same namespace options), so they need its host.
|
|
const sandboxRequirements = JSON.stringify(
|
|
contract.gates.find(({ id: gateId }) => gateId === "FE-GATE-013")?.hostRequirements ?? [],
|
|
);
|
|
for (const job of contract.jobs) {
|
|
if (job.kind === "provider") {
|
|
if (JSON.stringify(job.hostRequirements ?? []) !== sandboxRequirements) {
|
|
issue(`provider job host requirements must equal FE-GATE-013's: ${job.id}`);
|
|
}
|
|
} else if (job.hostRequirements !== undefined) {
|
|
issue(`only a provider job declares host requirements of its own: ${job.id}`);
|
|
}
|
|
}
|
|
if (JSON.stringify(contract.jobs.map(({ id }) => id)) !== JSON.stringify(Object.keys(expectedJobOwnership))) {
|
|
issue("job registry must contain the exact thirteen canonical jobs in semantic order");
|
|
}
|
|
for (const [jobId, gateIds] of Object.entries(expectedJobOwnership)) {
|
|
const job = contract.jobs.find(({ id }) => id === jobId);
|
|
if (!job || JSON.stringify(job.gateIds) !== JSON.stringify(gateIds)) {
|
|
issue(`exact gate execution ownership drift: ${jobId}`);
|
|
}
|
|
}
|
|
const expectedJobGraph: Readonly<Record<string, readonly [CiWorkflowJob["kind"], readonly string[], CiWorkflowJob["condition"]]>> = {
|
|
merge_static: ["gate-sequence", [], "merge"],
|
|
merge_test: ["gate-sequence", [], "merge"],
|
|
merge_browser: ["gate-sequence", [], "merge"],
|
|
release_gate: ["gate-matrix", ["merge_static", "merge_test", "merge_browser"], "release"],
|
|
immutable_build: ["immutable", ["release_gate"], "release"],
|
|
vulnerability_provider: ["provider", ["immutable_build"], "always"],
|
|
provenance_provider: ["provider", ["immutable_build"], "always"],
|
|
promotion: ["promotion", ["immutable_build", "vulnerability_provider", "provenance_provider"], "needs-success"],
|
|
deployment: ["deployment", ["immutable_build", "promotion"], "production"],
|
|
production_gate: ["gate-matrix", ["immutable_build", "promotion", "deployment"], "production"],
|
|
field_gate: ["gate-single", ["production_gate"], "field"],
|
|
documentation_gate: ["gate-single", [], "documentation"],
|
|
main_gate: ["gate-sequence", [], "main"],
|
|
};
|
|
for (const [jobId, [kind, needs, condition]] of Object.entries(expectedJobGraph)) {
|
|
const job = contract.jobs.find(({ id }) => id === jobId);
|
|
if (!job || job.kind !== kind || JSON.stringify(job.needs) !== JSON.stringify(needs) || job.condition !== condition) {
|
|
issue(`job graph drift: ${jobId}`);
|
|
}
|
|
}
|
|
const expectedStepKinds: Readonly<Record<string, readonly CiWorkflowStep["kind"][]>> = {
|
|
merge_static: ["checkout", "dependency-cache", "setup-node", "frozen-install", "run-gate", "upload"],
|
|
merge_test: ["checkout", "dependency-cache", "setup-node", "frozen-install", "run-gate", "upload"],
|
|
merge_browser: ["checkout", "dependency-cache", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"],
|
|
release_gate: ["checkout", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"],
|
|
immutable_build: ["checkout", "setup-node", "frozen-install", "run-gate", "archive-candidate", "upload", "upload"],
|
|
vulnerability_provider: ["checkout", "setup-node", "frozen-install", "download", "run-provider", "validate-provider-evidence", "upload"],
|
|
provenance_provider: ["checkout", "setup-node", "frozen-install", "download", "run-provider", "validate-provider-evidence", "upload"],
|
|
promotion: ["checkout", "setup-node", "frozen-install", "download", "download", "download", "verify-promotion", "upload", "cleanup-promotion"],
|
|
// deployment: the project's steps; validateJobStepKinds bounds them.
|
|
production_gate: ["checkout", "setup-node", "frozen-install", "download", "extract", "run-gate", "upload"],
|
|
field_gate: ["checkout", "setup-node", "frozen-install", "run-gate", "upload"],
|
|
documentation_gate: ["checkout", "setup-node", "frozen-install", "run-gate", "upload"],
|
|
main_gate: ["checkout", "setup-node", "frozen-install", "run-gate", "upload"],
|
|
};
|
|
for (const [jobId, expected] of Object.entries(expectedStepKinds)) {
|
|
const actual = contract.jobs.find(({ id }) => id === jobId)?.steps.map(({ kind }) => kind);
|
|
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
|
|
issue(`canonical job step sequence drift: ${jobId}`);
|
|
}
|
|
}
|
|
const PR_BASE_REF_BINDING = Object.freeze({
|
|
name: PR_BASE_REF_VARIABLE,
|
|
value: "${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}",
|
|
});
|
|
const expectedEnvironmentBindings: Readonly<Record<string, readonly Readonly<{ name: string; value: string }> []>> = {
|
|
// PR gate selection (config/ci/pr-gate-selection.json): the base branch
|
|
// of a pull_request run, empty in every other run, which runs every gate.
|
|
merge_static: [PR_BASE_REF_BINDING],
|
|
merge_test: [PR_BASE_REF_BINDING],
|
|
merge_browser: [PR_BASE_REF_BINDING],
|
|
release_gate: [
|
|
// 1112/05-01 (R9-D7, release tag). FE-GATE-028 compares each signed
|
|
// record's Release ID with the tag being released. A run that is not a
|
|
// tag run (a release stage dispatched on a branch) gets an empty value,
|
|
// and run-ci-gate.ts fails the gate on it.
|
|
{ name: "RELEASE_TAG", value: "${{ startsWith(gitea.ref, 'refs/tags/v') && gitea.ref_name || '' }}" },
|
|
],
|
|
immutable_build: [
|
|
// FE-GATE-027 admits the built artifact to a named environment, so both
|
|
// the profile it was built from and the destination it is claimed for are
|
|
// declared inputs. An absent RELEASE_TARGET is a refusal, not a default.
|
|
{ name: "APP_PROFILE", value: "${{ vars.APP_PROFILE }}" },
|
|
{ name: "RELEASE_TARGET", value: "${{ vars.RELEASE_TARGET }}" },
|
|
],
|
|
vulnerability_provider: [
|
|
{ name: "CANDIDATE_ARCHIVE_SHA256", value: "${{ needs.immutable_build.outputs.archive_sha256 }}" },
|
|
{ name: "CANDIDATE_ARCHIVE_PATH", value: ".release/vulnerability-candidate/release-candidate-${{ gitea.run_id }}-${{ gitea.run_attempt }}.tar.gz" },
|
|
{ name: "CI_RUN_ID", value: "${{ gitea.run_id }}" },
|
|
{ name: "CI_RUN_ATTEMPT", value: "${{ gitea.run_attempt }}" },
|
|
{ name: "EXPECTED_SOURCE_REVISION", value: "${{ gitea.sha }}" },
|
|
{ name: "VULNERABILITY_PUBLIC_KEY_PATH", value: "${{ vars.VULNERABILITY_PUBLIC_KEY_PATH }}" },
|
|
{ name: "VULNERABILITY_KEY_ID", value: "${{ vars.VULNERABILITY_KEY_ID }}" },
|
|
{ name: "VULNERABILITY_PROVIDER_COMMAND", value: "${{ vars.VULNERABILITY_PROVIDER_COMMAND }}" },
|
|
{ name: "VULNERABILITY_REPORT_PATH", value: "provider-evidence/untrusted/vulnerability-report.json" },
|
|
{ name: "VALIDATED_PROVIDER_REPORT_PATH", value: "provider-evidence/vulnerability-report.json" },
|
|
],
|
|
provenance_provider: [
|
|
{ name: "CANDIDATE_ARCHIVE_SHA256", value: "${{ needs.immutable_build.outputs.archive_sha256 }}" },
|
|
{ name: "CANDIDATE_ARCHIVE_PATH", value: ".release/provenance-candidate/release-candidate-${{ gitea.run_id }}-${{ gitea.run_attempt }}.tar.gz" },
|
|
{ name: "CI_RUN_ID", value: "${{ gitea.run_id }}" },
|
|
{ name: "CI_RUN_ATTEMPT", value: "${{ gitea.run_attempt }}" },
|
|
{ name: "EXPECTED_SOURCE_REVISION", value: "${{ gitea.sha }}" },
|
|
{ name: "PROVENANCE_PUBLIC_KEY_PATH", value: "${{ vars.PROVENANCE_PUBLIC_KEY_PATH }}" },
|
|
{ name: "PROVENANCE_KEY_ID", value: "${{ vars.PROVENANCE_KEY_ID }}" },
|
|
{ name: "PROVENANCE_PROVIDER_COMMAND", value: "${{ vars.PROVENANCE_PROVIDER_COMMAND }}" },
|
|
{ name: "PROVENANCE_ATTESTATION_PATH", value: "provider-evidence/untrusted/provenance-attestation.json" },
|
|
{ name: "VALIDATED_PROVIDER_REPORT_PATH", value: "provider-evidence/provenance-attestation.json" },
|
|
],
|
|
promotion: [
|
|
{ name: "CANDIDATE_ARCHIVE_SHA256", value: "${{ needs.immutable_build.outputs.archive_sha256 }}" },
|
|
{ name: "CANDIDATE_ARCHIVE_PATH", value: ".release/candidate/release-candidate-${{ gitea.run_id }}-${{ gitea.run_attempt }}.tar.gz" },
|
|
{ name: "CI_RUN_ID", value: "${{ gitea.run_id }}" },
|
|
{ name: "CI_RUN_ATTEMPT", value: "${{ gitea.run_attempt }}" },
|
|
{ name: "VULNERABILITY_REPORT_PATH", value: "${{ gitea.workspace }}/.release/vulnerability/vulnerability-report.json" },
|
|
{ name: "PROVENANCE_ATTESTATION_PATH", value: "${{ gitea.workspace }}/.release/provenance/provenance-attestation.json" },
|
|
{ name: "VULNERABILITY_PUBLIC_KEY_PATH", value: "${{ vars.VULNERABILITY_PUBLIC_KEY_PATH }}" },
|
|
{ name: "VULNERABILITY_KEY_ID", value: "${{ vars.VULNERABILITY_KEY_ID }}" },
|
|
{ name: "PROVENANCE_PUBLIC_KEY_PATH", value: "${{ vars.PROVENANCE_PUBLIC_KEY_PATH }}" },
|
|
{ name: "PROVENANCE_KEY_ID", value: "${{ vars.PROVENANCE_KEY_ID }}" },
|
|
{ name: "VULNERABILITY_INVOCATION_NONCE", value: "${{ needs.vulnerability_provider.outputs.invocation_nonce }}" },
|
|
{ name: "PROVENANCE_INVOCATION_NONCE", value: "${{ needs.provenance_provider.outputs.invocation_nonce }}" },
|
|
],
|
|
// 13-05: FE-GATE-019 probes the promoted release after the deployment
|
|
// slot has deployed it, so the live base URL belongs to the production stage.
|
|
// 13-03: the drills extract the promoted archive and check it against the
|
|
// digest immutable_build recorded.
|
|
// 1101/13-01: whether the slot deployed anything; an empty slot leaves
|
|
// FE-GATE-019 UNVERIFIED instead of probing an earlier release.
|
|
production_gate: [
|
|
{ name: "HOSTING_BASE_URL", value: "${{ vars.HOSTING_BASE_URL }}" },
|
|
{ name: "CANDIDATE_ARCHIVE_SHA256", value: "${{ needs.immutable_build.outputs.archive_sha256 }}" },
|
|
{ name: "RELEASE_DEPLOYED", value: "${{ needs.deployment.outputs.deployed }}" },
|
|
],
|
|
field_gate: [
|
|
{ name: "FIELD_WEB_VITALS_INPUT", value: "${{ vars.FIELD_WEB_VITALS_INPUT }}" },
|
|
{ name: "MIN_ELIGIBLE_SAMPLES", value: "${{ vars.MIN_ELIGIBLE_SAMPLES }}" },
|
|
],
|
|
documentation_gate: [],
|
|
main_gate: [],
|
|
};
|
|
for (const job of contract.jobs) {
|
|
const environmentNames = job.environment.map(({ name }) => name);
|
|
const duplicate = new Set(environmentNames).size !== environmentNames.length;
|
|
if (job.kind === "deployment") {
|
|
// 1101/13-01. The slot's variables are the project's: its host and
|
|
// credentials, plus the digest its extract step checks. No other job's
|
|
// output reaches it.
|
|
const foreign = job.environment.filter(({ name, value }) =>
|
|
name === "CANDIDATE_ARCHIVE_SHA256"
|
|
? value !== "${{ needs.immutable_build.outputs.archive_sha256 }}"
|
|
: !/^\$\{\{ (?:vars|secrets)\.[A-Za-z_][A-Za-z0-9_]* \}\}$/u.test(value),
|
|
);
|
|
if (duplicate || foreign.length > 0) {
|
|
issue(`deployment slot binding must be the candidate digest or a vars.* or secrets.* value: ${job.id}`);
|
|
}
|
|
for (const failure of deploymentSlotInputFailures(job)) issue(failure);
|
|
} else if (duplicate || JSON.stringify(job.environment) !== JSON.stringify(expectedEnvironmentBindings[job.id])) {
|
|
issue(`job environment binding drift: ${job.id}`);
|
|
}
|
|
}
|
|
if (owners.get("FE-GATE-015")?.[0] !== "immutable_build") {
|
|
issue("FE-GATE-015 must be owned only by immutable_build");
|
|
}
|
|
for (const job of contract.jobs.filter(({ kind }) => kind === "gate-matrix")) {
|
|
if (job.gateIds.includes("FE-GATE-015")) issue(`release matrix duplicates FE-GATE-015: ${job.id}`);
|
|
}
|
|
const browserGateIds = contract.jobs.flatMap(({ browserGateIds }) => browserGateIds).sort(asciiCompare);
|
|
if (JSON.stringify(browserGateIds) !== JSON.stringify(["FE-GATE-008", "FE-GATE-009", "FE-GATE-026"])) {
|
|
issue(`browser gate set drift: ${browserGateIds.join(",")}`);
|
|
}
|
|
for (const job of contract.jobs) {
|
|
const browserSteps = job.steps.filter(({ kind }) => kind === "browser-install").length;
|
|
const expected = job.browserGateIds.length > 0 ? 1 : 0;
|
|
if (browserSteps !== expected) issue(`browser install step drift: ${job.id}`);
|
|
// A matrix job's non-browser lanes would run in the browser image too.
|
|
const imaged = job.steps.some((step) => step.kind === "browser-install" && step.image !== undefined);
|
|
if (imaged && job.kind !== "gate-sequence") issue(`browser job image outside a gate sequence: ${job.id}`);
|
|
}
|
|
for (const cycle of findCycles(contract.jobs.map((job) => [job.id, job.needs] as const))) {
|
|
issue(`job dependency cycle: ${cycle.join(" -> ")}`);
|
|
}
|
|
|
|
const uploads = new Map<string, { producer: string; step: z.infer<typeof uploadStep> }>();
|
|
for (const job of contract.jobs) {
|
|
for (const step of job.steps) {
|
|
if (step.kind !== "upload") continue;
|
|
const previous = uploads.get(step.transferId);
|
|
if (previous) issue(`duplicate upload transfer ${step.transferId}: ${previous.producer}, ${job.id}`);
|
|
uploads.set(step.transferId, { producer: job.id, step });
|
|
}
|
|
}
|
|
const dependencies = new Map(contract.jobs.map((job) => [job.id, job.needs]));
|
|
for (const job of contract.jobs) {
|
|
for (const step of job.steps) {
|
|
if (step.kind !== "download") continue;
|
|
const upload = uploads.get(step.transferId);
|
|
if (!upload) issue(`unknown download transfer ${step.transferId} for ${job.id}`);
|
|
else if (!isDependencyReachable(job.id, upload.producer, dependencies)) {
|
|
issue(`download producer ${upload.producer} is unreachable from ${job.id}`);
|
|
}
|
|
}
|
|
}
|
|
const promotion = contract.jobs.find(({ id }) => id === "promotion");
|
|
if (promotion) {
|
|
if (promotion.kind !== "promotion") issue("promotion job kind drift");
|
|
if (promotion.gateIds.length > 0 || promotion.steps.some(({ kind }) => kind === "run-gate")) {
|
|
issue("promotion job must not own or run a gate");
|
|
}
|
|
const forbidden = promotion.steps.filter(({ kind }) =>
|
|
["archive-candidate", "run-provider"].includes(kind),
|
|
);
|
|
if (forbidden.length > 0) issue("promotion job must not build or rebuild candidate bytes");
|
|
const order = promotion.steps.map(({ kind }) => kind);
|
|
const verificationIndex = order.indexOf("verify-promotion");
|
|
const uploadIndex = order.indexOf("upload");
|
|
if (verificationIndex < 0 || uploadIndex !== verificationIndex + 1) {
|
|
issue("promotion verification and upload must be immediately adjacent");
|
|
}
|
|
const upload = promotion.steps[uploadIndex];
|
|
if (upload?.kind === "upload" && upload.always) {
|
|
issue("promotion upload must not use always");
|
|
}
|
|
const cleanupIndex = order.indexOf("cleanup-promotion");
|
|
if (
|
|
order.includes("extract") ||
|
|
verificationIndex < order.lastIndexOf("download") ||
|
|
uploadIndex < verificationIndex ||
|
|
cleanupIndex !== uploadIndex + 1
|
|
) {
|
|
issue("promotion formula order must download, finalize, upload, then cleanup without extraction");
|
|
}
|
|
}
|
|
const immutable = contract.jobs.find(({ id }) => id === "immutable_build");
|
|
const archive = immutable?.steps.find(({ kind }) => kind === "archive-candidate");
|
|
const expectedArchiveMembers = ["dist", ...RELEASE_CANDIDATE_EVIDENCE_PATHS, RELEASE_CANDIDATE_MANIFEST_PATH];
|
|
if (
|
|
!archive ||
|
|
archive.kind !== "archive-candidate" ||
|
|
JSON.stringify(archive.members) !== JSON.stringify(expectedArchiveMembers)
|
|
) {
|
|
issue("immutable candidate archive member set drift");
|
|
}
|
|
if (
|
|
archive?.kind === "archive-candidate" &&
|
|
(archive.stepId !== "candidate" ||
|
|
archive.archivePath !== ".release/release-candidate-${{ gitea.run_id }}-${{ gitea.run_attempt }}.tar.gz" ||
|
|
archive.archiveOutputName !== "archive_sha256" ||
|
|
archive.distOutputName !== "dist_sha256")
|
|
) {
|
|
issue("immutable candidate output identity drift");
|
|
}
|
|
const promotionUpload = promotion?.steps.find(
|
|
(step) => step.kind === "upload" && step.transferId === "promoted-release",
|
|
);
|
|
if (!promotionUpload || promotionUpload.kind !== "upload" || JSON.stringify(promotionUpload.paths) !== JSON.stringify(PROMOTED_UPLOAD_PATHS)) {
|
|
issue("promotion upload bundle must contain the exact five typed paths");
|
|
}
|
|
|
|
validateCanonicalStepFields(contract, issue);
|
|
}
|
|
|
|
const IMMUTABLE_GATE_EVIDENCE_TRANSFER_ID = "immutable-gate-evidence";
|
|
|
|
/**
|
|
* 1105/13-01. What immutable_build uploads besides the candidate: the log and
|
|
* evidence artifacts of each gate it runs, in gate order, then the advisory
|
|
* record of scan:dependency-advisories (FE-GATE-027), which is not a gate
|
|
* evidence artifact because it never blocks.
|
|
*/
|
|
function immutableGateEvidencePaths(
|
|
contract: Pick<z.infer<typeof ciGateContractBaseSchema>, "artifacts" | "gates">,
|
|
immutable: Pick<z.infer<typeof jobSchema>, "gateIds">,
|
|
): string[] {
|
|
const paths = immutable.gateIds.flatMap((gateId) => {
|
|
const gate = contract.gates.find(({ id }) => id === gateId);
|
|
return gate
|
|
? [gate.logArtifactId, ...gate.evidenceArtifactIds].flatMap((artifactId) =>
|
|
contract.artifacts.filter(({ id }) => id === artifactId).map(({ path: artifactPath }) => artifactPath),
|
|
)
|
|
: [];
|
|
});
|
|
return [...new Set([...paths, DEPENDENCY_ADVISORIES_RECORD_PATH])];
|
|
}
|
|
|
|
function validateCanonicalStepFields(
|
|
contract: z.infer<typeof ciGateContractBaseSchema>,
|
|
issue: (message: string, path?: PropertyKey[]) => void,
|
|
): void {
|
|
const immutable = contract.jobs.find(({ id }) => id === "immutable_build");
|
|
const immutableArchive = immutable?.steps.find(({ kind }) => kind === "archive-candidate");
|
|
const immutableUpload = immutable?.steps.find(
|
|
(step) => step.kind === "upload" && step.transferId === "release-candidate",
|
|
);
|
|
if (
|
|
!immutableArchive ||
|
|
immutableArchive.kind !== "archive-candidate" ||
|
|
!immutableUpload ||
|
|
immutableUpload.kind !== "upload" ||
|
|
JSON.stringify(immutableUpload.paths) !== JSON.stringify([immutableArchive.archivePath])
|
|
) {
|
|
issue("immutable archive and upload fields must remain linked");
|
|
}
|
|
// 1105/13-01. ci:gate writes command output only to the gate log and prints
|
|
// one PASS/FAIL line, and this job uploaded only the candidate, on success.
|
|
// Why FE-GATE-015 or FE-GATE-027 failed, and the advisory record FE-GATE-027
|
|
// writes, went with the runner's workspace. A separate transfer, always and
|
|
// last, carries them; the candidate archive's member set stays as it is.
|
|
const gateEvidence = immutable?.steps.find(
|
|
(step) => step.kind === "upload" && step.transferId === IMMUTABLE_GATE_EVIDENCE_TRANSFER_ID,
|
|
);
|
|
if (
|
|
!immutable ||
|
|
gateEvidence?.kind !== "upload" ||
|
|
gateEvidence.always !== true ||
|
|
immutable.steps.at(-1) !== gateEvidence ||
|
|
JSON.stringify(gateEvidence.paths) !== JSON.stringify(immutableGateEvidencePaths(contract, immutable))
|
|
) {
|
|
issue(
|
|
"immutable_build must upload its gates' logs and evidence and the dependency advisory record " +
|
|
`as ${IMMUTABLE_GATE_EVIDENCE_TRANSFER_ID}, with always, as its last step`,
|
|
);
|
|
}
|
|
|
|
const providerExpectations = {
|
|
vulnerability_provider: {
|
|
provider: "vulnerability",
|
|
stepId: "supervise_vulnerability",
|
|
downloadPath: ".release/vulnerability-candidate",
|
|
archivePath: ".release/vulnerability-candidate/release-candidate-${{ gitea.run_id }}-${{ gitea.run_attempt }}.tar.gz",
|
|
rawPath: "provider-evidence/untrusted/vulnerability-report.json",
|
|
rawName: "VULNERABILITY_REPORT_PATH",
|
|
sealedPath: "provider-evidence/vulnerability-report.json",
|
|
transferId: "vulnerability-provider-evidence",
|
|
},
|
|
provenance_provider: {
|
|
provider: "provenance",
|
|
stepId: "supervise_provenance",
|
|
downloadPath: ".release/provenance-candidate",
|
|
archivePath: ".release/provenance-candidate/release-candidate-${{ gitea.run_id }}-${{ gitea.run_attempt }}.tar.gz",
|
|
rawPath: "provider-evidence/untrusted/provenance-attestation.json",
|
|
rawName: "PROVENANCE_ATTESTATION_PATH",
|
|
sealedPath: "provider-evidence/provenance-attestation.json",
|
|
transferId: "provenance-provider-evidence",
|
|
},
|
|
} as const;
|
|
for (const [jobId, expected] of Object.entries(providerExpectations)) {
|
|
const job = contract.jobs.find(({ id }) => id === jobId);
|
|
const environment = new Map(job?.environment.map(({ name, value }) => [name, value]));
|
|
const download = job?.steps.find(({ kind }) => kind === "download");
|
|
const runProvider = job?.steps.find(({ kind }) => kind === "run-provider");
|
|
const validateProvider = job?.steps.find(({ kind }) => kind === "validate-provider-evidence");
|
|
const upload = job?.steps.find(
|
|
(step) => step.kind === "upload" && step.transferId === expected.transferId,
|
|
);
|
|
if (
|
|
!download || download.kind !== "download" || download.transferId !== "release-candidate" || download.path !== expected.downloadPath ||
|
|
!runProvider || runProvider.kind !== "run-provider" || runProvider.provider !== expected.provider || runProvider.stepId !== expected.stepId ||
|
|
!validateProvider || validateProvider.kind !== "validate-provider-evidence" || validateProvider.provider !== expected.provider ||
|
|
environment.get("CANDIDATE_ARCHIVE_PATH") !== expected.archivePath ||
|
|
environment.get(expected.rawName) !== expected.rawPath ||
|
|
environment.get("VALIDATED_PROVIDER_REPORT_PATH") !== expected.sealedPath ||
|
|
!upload || upload.kind !== "upload" || JSON.stringify(upload.paths) !== JSON.stringify([expected.sealedPath])
|
|
) {
|
|
issue(`provider archive, extraction, evidence, and upload fields must remain linked: ${jobId}`);
|
|
}
|
|
}
|
|
|
|
const promotion = contract.jobs.find(({ id }) => id === "promotion");
|
|
const promotionDownloads = promotion?.steps.filter(({ kind }) => kind === "download");
|
|
const expectedDownloads = [
|
|
{ kind: "download", transferId: "release-candidate", path: ".release/candidate" },
|
|
{ kind: "download", transferId: "vulnerability-provider-evidence", path: ".release/vulnerability" },
|
|
{ kind: "download", transferId: "provenance-provider-evidence", path: ".release/provenance" },
|
|
];
|
|
const promotionFinalizer = promotion?.steps.find(({ kind }) => kind === "verify-promotion");
|
|
const promotionCleanup = promotion?.steps.find(({ kind }) => kind === "cleanup-promotion");
|
|
if (
|
|
JSON.stringify(promotionDownloads) !== JSON.stringify(expectedDownloads) ||
|
|
!promotionFinalizer ||
|
|
promotionFinalizer.kind !== "verify-promotion" ||
|
|
promotionFinalizer.stepId !== "finalize" ||
|
|
!promotionCleanup ||
|
|
promotionCleanup.kind !== "cleanup-promotion" ||
|
|
promotionCleanup.finalizerStepId !== "finalize"
|
|
) {
|
|
issue("promotion download fields and finalizer/cleanup step identities must remain linked");
|
|
}
|
|
|
|
// 13-03: the production stage drills the promoted archive it downloads. It
|
|
// used to rebuild from source, so the drilled bytes were not the release.
|
|
// 1101/13-01: the same holds for FE-GATE-019, which rebuilt with the local
|
|
// profile; every production gate command reads the extracted archive.
|
|
const production = contract.jobs.find(({ id }) => id === "production_gate");
|
|
const promotedDownload = production?.steps.find(
|
|
(step) => step.kind === "download" && step.transferId === "promoted-release",
|
|
);
|
|
const promotedExtract = production?.steps.find(({ kind }) => kind === "extract");
|
|
if (
|
|
!production ||
|
|
promotedDownload?.kind !== "download" ||
|
|
promotedExtract?.kind !== "extract" ||
|
|
promotedExtract.archivePath !== `${promotedDownload.path}/release-candidate.tar.gz`
|
|
) {
|
|
issue("production_gate must download the promoted release and extract its release-candidate.tar.gz");
|
|
} else {
|
|
for (const gateId of production.gateIds) {
|
|
const commands = (contract.gates.find(({ id }) => id === gateId)?.commandIds ?? [])
|
|
.map((commandId) => contract.commands.find(({ id }) => id === commandId));
|
|
for (const command of commands) {
|
|
const args = command?.args ?? [];
|
|
const releaseRoot = args.indexOf("--release-root");
|
|
if (releaseRoot < 0 || args[releaseRoot + 1] !== promotedExtract.targetRoot) {
|
|
issue(`production gate command must pass --release-root ${promotedExtract.targetRoot} (the promoted archive), not rebuild: ${command?.id ?? gateId}`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 1103/13-01. A slot that runs a deploy script deploys the promoted candidate:
|
|
* it downloads the promoted-release transfer and extracts its
|
|
* release-candidate.tar.gz, checked against the digest immutable_build
|
|
* recorded, before the script runs. A slot that rebuilt instead passed the
|
|
* contract under the name deploy-promoted-release, and FE-GATE-019 could not
|
|
* tell the rebuild from the candidate.
|
|
*/
|
|
function deploymentSlotInputFailures(job: z.infer<typeof jobSchema>): string[] {
|
|
const deploy = job.steps.find((step) => step.kind === "deploy");
|
|
if (deploy?.kind !== "deploy" || deploy.script === undefined) return [];
|
|
const failures: string[] = [];
|
|
const downloads = job.steps.filter((step) => step.kind === "download");
|
|
const download = downloads[0];
|
|
const extract = job.steps.find((step) => step.kind === "extract");
|
|
if (
|
|
downloads.length !== 1 ||
|
|
download?.kind !== "download" ||
|
|
download.transferId !== "promoted-release" ||
|
|
extract?.kind !== "extract" ||
|
|
extract.archivePath !== `${download.path}/release-candidate.tar.gz` ||
|
|
job.steps.indexOf(download) > job.steps.indexOf(extract)
|
|
) {
|
|
failures.push(
|
|
`deployment slot with a deploy script must download only the promoted-release transfer and extract its release-candidate.tar.gz before deploying: ${job.id}`,
|
|
);
|
|
}
|
|
if (
|
|
!job.environment.some(
|
|
({ name, value }) =>
|
|
name === "CANDIDATE_ARCHIVE_SHA256" &&
|
|
value === "${{ needs.immutable_build.outputs.archive_sha256 }}",
|
|
)
|
|
) {
|
|
failures.push(
|
|
`deployment slot with a deploy script must bind CANDIDATE_ARCHIVE_SHA256 so its extract step checks the promoted archive: ${job.id}`,
|
|
);
|
|
}
|
|
return failures;
|
|
}
|
|
|
|
function validateJobStepKinds(
|
|
job: z.infer<typeof jobSchema>,
|
|
issue: (message: string, path?: PropertyKey[]) => void,
|
|
): void {
|
|
const allowed: Readonly<Record<z.infer<typeof jobSchema>["kind"], ReadonlySet<string>>> = {
|
|
"gate-matrix": new Set(["checkout", "setup-node", "frozen-install", "browser-install", "download", "extract", "run-gate", "upload"]),
|
|
"gate-sequence": new Set(["checkout", "dependency-cache", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"]),
|
|
"gate-single": new Set(["checkout", "setup-node", "frozen-install", "run-gate", "upload"]),
|
|
immutable: new Set(["checkout", "setup-node", "frozen-install", "run-gate", "archive-candidate", "upload"]),
|
|
provider: new Set(["checkout", "setup-node", "frozen-install", "download", "extract", "run-provider", "validate-provider-evidence", "upload"]),
|
|
promotion: new Set(["checkout", "setup-node", "frozen-install", "download", "verify-promotion", "upload", "cleanup-promotion"]),
|
|
deployment: new Set(["checkout", "setup-node", "frozen-install", "download", "extract", "deploy"]),
|
|
};
|
|
for (const step of job.steps) {
|
|
if (!allowed[job.kind].has(step.kind)) {
|
|
issue(`step kind ${step.kind} is forbidden for ${job.kind} job ${job.id}`);
|
|
}
|
|
}
|
|
const kinds = job.steps.map(({ kind }) => kind);
|
|
// 1101/13-01. The deploy step reports deployed=true only after everything
|
|
// before it succeeded, so it is the one last step.
|
|
if (job.kind === "deployment" && (kinds.at(-1) !== "deploy" || kinds.filter((kind) => kind === "deploy").length !== 1)) {
|
|
issue(`deployment slot must end with exactly one deploy step: ${job.id}`);
|
|
}
|
|
if (job.kind === "provider") {
|
|
const providerIndex = kinds.indexOf("run-provider");
|
|
const validateProviderIndex = kinds.indexOf("validate-provider-evidence");
|
|
const uploadIndex = kinds.indexOf("upload");
|
|
if (
|
|
providerIndex < kinds.lastIndexOf("download") ||
|
|
validateProviderIndex < providerIndex ||
|
|
uploadIndex < validateProviderIndex
|
|
) {
|
|
issue(`provider execution/validation/upload order drift: ${job.id}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
function findCycles(entries: readonly (readonly [string, readonly string[]])[]): string[][] {
|
|
const graph = new Map(entries);
|
|
const visiting = new Set<string>();
|
|
const visited = new Set<string>();
|
|
const stack: string[] = [];
|
|
const cycles: string[][] = [];
|
|
const visit = (node: string): void => {
|
|
if (visiting.has(node)) {
|
|
const start = stack.indexOf(node);
|
|
cycles.push([...stack.slice(start), node]);
|
|
return;
|
|
}
|
|
if (visited.has(node) || !graph.has(node)) return;
|
|
visiting.add(node);
|
|
stack.push(node);
|
|
for (const next of graph.get(node) ?? []) visit(next);
|
|
stack.pop();
|
|
visiting.delete(node);
|
|
visited.add(node);
|
|
};
|
|
for (const node of graph.keys()) visit(node);
|
|
return cycles;
|
|
}
|
|
|
|
function isDependencyReachable(
|
|
consumer: string,
|
|
producer: string,
|
|
graph: ReadonlyMap<string, readonly string[]>,
|
|
): boolean {
|
|
const pending = [...(graph.get(consumer) ?? [])];
|
|
const visited = new Set<string>();
|
|
while (pending.length > 0) {
|
|
const current = pending.shift()!;
|
|
if (current === producer) return true;
|
|
if (visited.has(current)) continue;
|
|
visited.add(current);
|
|
pending.push(...(graph.get(current) ?? []));
|
|
}
|
|
return false;
|
|
}
|
|
|
|
export function asciiCompare(left: string, right: string): number {
|
|
return left < right ? -1 : left > right ? 1 : 0;
|
|
}
|