문제: 배포 슬롯을 채우거나 제품 전용 merge 검사를 더하려면 템플릿 소유 config/ci/gates.json(약 3,000줄)과 생성 workflow를 고쳐야 했다. 문서도 "deployment job을 gates.json에서 고치라"고 적었다. 템플릿 gates.json이 바뀔 때마다 제품은 큰 JSON과 생성 YAML의 충돌을 손으로 풀어야 했고, 다운스트림 tech-log는 이미 제품 커밋 3개에서 gates.json을 고쳤다. 고른 방법: 제품 소유 config/ci/product-gates.json을 둔다. 템플릿은 빈 파일로 싣고 고치지 않는다. 담을 수 있는 것은 둘뿐이다. - deployment: deploy package script와 vars.*·secrets.* 바인딩. 나머지 슬롯(promoted-release download, digest로 확인하는 extract, deploy)은 템플릿이 렌더링하고, 채운 계약을 다시 parse해 슬롯 규칙(앞 커밋)을 그대로 적용한다. secret은 deploy 단계에만 간다. gates.json과 overlay 양쪽에서 슬롯을 채우면 거절한다. - mergeGates: PRODUCT-GATE-NNN id의 package script. 템플릿 job 뒤의 product_merge_gate job이 merge와 같은 조건에서 matrix로 돈다. FE-GATE id·명령·산출물·readiness 공식은 건드리지 못한다. loadCiGateContract와 생성기, check:ci가 두 파일을 함께 읽고, 계약 기준선(contract-baseline.json)은 템플릿 계약만 센다. 없는 script는 거절하고, 제품 gate script는 ungated 검사에서 gated로 센다. 버린 대안: 저장소 변수로 배포 명령만 받기(제품 게이트를 못 풀고 실행할 명령이 저장소 밖에 숨는다), 제품 전용 workflow 파일(Gitea에서 run 사이 산출물 전달이 검증되지 않았다). 위험·한계: 제품 gate는 ci:gate의 로그·증거 산출물과 readiness 공식 밖이다. merge를 막으려면 제품이 그 job을 필수 검사로 지정한다. 생성 workflow는 여전히 커밋되는 파일이라, 템플릿 변경과 같은 줄을 건드리면 재생성이 필요하다. 실제 Gitea runner에서는 돌리지 않았다. 검증: tests/unit/product-ci-overlay.test.ts 11건(빈 overlay, 슬롯 채우기와 기준선 유지, 양쪽 채우기 거절, 없는 script 거절, 제품 job 렌더링과 실행 확인, 스키마 거절 6건). 작업 트리에서 overlay와 script를 채워 generate:ci-workflow → check:ci PASS, CI workflow bytes PASS, 생성 YAML 파싱 확인 후 되돌렸다. 그 상태의 workflow와 gates.json에 템플릿 변경(게이트 이름 2개)을 diff3로 3-way 병합하면 충돌 0이다. ci-workflow-generation 425건, check:ci PASS. Refs: docs/reviews/2026-11-03-maturity-review/12-guardrails-ci.md 12-07
147 lines
5.5 KiB
TypeScript
147 lines
5.5 KiB
TypeScript
import { readFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
|
|
import { z } from "zod";
|
|
|
|
/**
|
|
* 1103/12-07. The product's own part of CI, kept out of the template-owned
|
|
* config/ci/gates.json so a template sync never meets it. The template ships
|
|
* this file empty and does not change it. It may hold only:
|
|
*
|
|
* - `deployment`: the package script that deploys the promoted release, and
|
|
* its `vars.*` / `secrets.*` bindings. The template renders the rest of the
|
|
* slot (download the promoted-release transfer, extract it against the
|
|
* candidate digest, then run the script); secrets reach the deploy step only
|
|
* (1103/13-05).
|
|
* - `mergeGates`: product checks that run on every merge-stage run, in a job
|
|
* of their own (`product_merge_gate`). Their ids are `PRODUCT-GATE-NNN`, so
|
|
* they never take or change a template gate (`FE-GATE-NNN`), its commands,
|
|
* artifacts or readiness formula. The template contract baseline counts
|
|
* only the template contract.
|
|
*/
|
|
export const PRODUCT_CI_OVERLAY_PATH = "config/ci/product-gates.json";
|
|
|
|
const scriptName = z
|
|
.string()
|
|
.max(128)
|
|
.regex(/^[A-Za-z0-9:_-]+$/u, "a product script is a package script name ([A-Za-z0-9:_-])");
|
|
const binding = z
|
|
.object({
|
|
name: z.string().regex(/^[A-Z][A-Z0-9_]*$/u),
|
|
value: z
|
|
.string()
|
|
.regex(
|
|
/^\$\{\{ (?:vars|secrets)\.[A-Za-z_][A-Za-z0-9_]* \}\}$/u,
|
|
"a product binding must be a vars.* or secrets.* value",
|
|
),
|
|
})
|
|
.strict();
|
|
const productGate = z
|
|
.object({
|
|
id: z
|
|
.string()
|
|
.regex(/^PRODUCT-GATE-\d{3}$/u, "product gate ids are PRODUCT-GATE-NNN; FE-GATE-NNN ids belong to the template"),
|
|
name: z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/u),
|
|
script: scriptName,
|
|
})
|
|
.strict();
|
|
|
|
const productCiOverlaySchema = z
|
|
.object({
|
|
schemaVersion: z.literal(1),
|
|
deployment: z
|
|
.object({ script: scriptName, environment: z.array(binding).max(32) })
|
|
.strict()
|
|
.nullable(),
|
|
mergeGates: z.array(productGate).max(32),
|
|
})
|
|
.strict()
|
|
.superRefine((overlay, context) => {
|
|
const issue = (message: string) => context.addIssue({ code: "custom", message });
|
|
const names = overlay.deployment?.environment.map(({ name }) => name) ?? [];
|
|
if (new Set(names).size !== names.length) issue("duplicate deployment binding name");
|
|
if (names.includes("CANDIDATE_ARCHIVE_SHA256")) {
|
|
issue("CANDIDATE_ARCHIVE_SHA256 is bound by the template to the immutable_build digest");
|
|
}
|
|
for (const field of ["id", "name"] as const) {
|
|
const values = overlay.mergeGates.map((gate) => gate[field]);
|
|
if (new Set(values).size !== values.length) issue(`duplicate product gate ${field}`);
|
|
}
|
|
});
|
|
|
|
export type ProductCiOverlay = z.infer<typeof productCiOverlaySchema>;
|
|
export type ProductDeployment = NonNullable<ProductCiOverlay["deployment"]>;
|
|
export type ProductGate = ProductCiOverlay["mergeGates"][number];
|
|
|
|
const EMPTY_PRODUCT_CI_OVERLAY: ProductCiOverlay = Object.freeze({
|
|
schemaVersion: 1,
|
|
deployment: null,
|
|
mergeGates: [],
|
|
});
|
|
|
|
export function parseProductCiOverlay(value: unknown): ProductCiOverlay {
|
|
const result = productCiOverlaySchema.safeParse(value);
|
|
if (!result.success) {
|
|
throw new TypeError(
|
|
`${PRODUCT_CI_OVERLAY_PATH} invalid:\n${result.error.issues
|
|
.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`)
|
|
.join("\n")}`,
|
|
);
|
|
}
|
|
return result.data;
|
|
}
|
|
|
|
/** The overlay of `root`; a checkout without the file (synced before it existed) has none. */
|
|
export async function loadProductCiOverlay(root: string): Promise<ProductCiOverlay> {
|
|
let text: string;
|
|
try {
|
|
text = await readFile(path.join(root, PRODUCT_CI_OVERLAY_PATH), "utf8");
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return EMPTY_PRODUCT_CI_OVERLAY;
|
|
throw error;
|
|
}
|
|
return parseProductCiOverlay(JSON.parse(text));
|
|
}
|
|
|
|
const PROMOTED_DOWNLOAD_PATH = ".release/deployment";
|
|
/** Where the slot extracts the promoted archive; the deploy script uploads `<this>/dist`. */
|
|
export const PROMOTED_RELEASE_ROOT = ".release/promoted-release";
|
|
|
|
/**
|
|
* The template contract document with its empty deployment slot filled from
|
|
* the overlay. The caller parses the result, so the slot rules of the
|
|
* template contract still apply. A slot the template contract already
|
|
* filled is refused: the slot has one owner.
|
|
*/
|
|
export function withProductDeployment(contract: unknown, deployment: ProductDeployment): unknown {
|
|
const document = structuredClone(contract) as { jobs?: { id?: unknown; steps?: unknown; environment?: unknown }[] };
|
|
const slot = document.jobs?.find(({ id }) => id === "deployment");
|
|
if (
|
|
!slot ||
|
|
JSON.stringify(slot.steps) !== JSON.stringify([{ kind: "deploy" }]) ||
|
|
JSON.stringify(slot.environment) !== "[]"
|
|
) {
|
|
throw new TypeError(
|
|
`the deployment slot is filled in config/ci/gates.json and in ${PRODUCT_CI_OVERLAY_PATH}; ` +
|
|
`keep the template slot empty and fill ${PRODUCT_CI_OVERLAY_PATH}`,
|
|
);
|
|
}
|
|
slot.environment = [
|
|
{ name: "CANDIDATE_ARCHIVE_SHA256", value: "${{ needs.immutable_build.outputs.archive_sha256 }}" },
|
|
...deployment.environment,
|
|
];
|
|
slot.steps = [
|
|
{ kind: "checkout" },
|
|
{ kind: "setup-node" },
|
|
{ kind: "frozen-install" },
|
|
{ kind: "download", transferId: "promoted-release", path: PROMOTED_DOWNLOAD_PATH },
|
|
{
|
|
kind: "extract",
|
|
archivePath: `${PROMOTED_DOWNLOAD_PATH}/release-candidate.tar.gz`,
|
|
targetRoot: PROMOTED_RELEASE_ROOT,
|
|
},
|
|
{ kind: "deploy", script: deployment.script },
|
|
];
|
|
return document;
|
|
}
|