forgedock 1.60.1 → 1.61.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/bin/config-schema.mjs +44 -1
  2. package/bin/engine/runlog.mjs +52 -0
  3. package/bin/engine-cli.mjs +9 -4
  4. package/bin/env/bench.mjs +38 -0
  5. package/bin/env/cli.mjs +134 -0
  6. package/bin/env/env.mjs +339 -0
  7. package/bin/forgedock.mjs +32 -3
  8. package/bin/help-text.mjs +2 -0
  9. package/bin/lean/ci-budget.mjs +3 -1
  10. package/bin/lean/ci-classify.mjs +74 -0
  11. package/bin/lean/ci-classify.test.mjs +147 -0
  12. package/bin/lean/ci-emit.mjs +175 -0
  13. package/bin/lean/ci-emit.test.mjs +177 -0
  14. package/bin/lean/ci-preflight.mjs +183 -0
  15. package/bin/lean/ci-preflight.test.mjs +122 -0
  16. package/bin/lean/ci-runner-health.mjs +213 -0
  17. package/bin/lean/ci-runner-health.test.mjs +113 -0
  18. package/bin/lean/ci-watch.mjs +79 -0
  19. package/bin/lean/ci-watch.test.mjs +80 -0
  20. package/bin/lean/depcache.mjs +38 -8
  21. package/bin/lean/deploy-stages.mjs +514 -0
  22. package/bin/lean/deploy-stages.test.mjs +580 -0
  23. package/bin/lean/effects.mjs +50 -0
  24. package/bin/lean/execution.mjs +8 -1
  25. package/bin/lean/lean.mjs +38 -6
  26. package/bin/lean/lean.test.mjs +61 -0
  27. package/bin/lean/release-deploy.mjs +12 -6
  28. package/bin/lean/release-flakes.mjs +16 -0
  29. package/bin/lean/release-flakes.test.mjs +15 -0
  30. package/bin/lean/release-gates.mjs +24 -1
  31. package/bin/lean/release-ledger.mjs +21 -0
  32. package/bin/lean/release-minutes-timing.test.mjs +57 -0
  33. package/bin/lean/release-minutes.mjs +98 -0
  34. package/bin/lean/release-promote.mjs +444 -0
  35. package/bin/lean/release-promote.test.mjs +470 -0
  36. package/bin/lean/release-rollback.mjs +14 -6
  37. package/bin/lean/release.mjs +31 -2
  38. package/bin/lean/sandbox-remote.mjs +11 -3
  39. package/bin/lean/testengine-recall.mjs +82 -0
  40. package/bin/lean/testengine-recall.test.mjs +103 -0
  41. package/bin/lean/testengine-shard.mjs +150 -0
  42. package/bin/lean/testengine-shard.test.mjs +111 -0
  43. package/bin/lean/testengine.mjs +486 -0
  44. package/bin/lean/testengine.test.mjs +303 -0
  45. package/bin/lean/verify-settle.test.mjs +156 -0
  46. package/bin/lean/verify.mjs +98 -3
  47. package/bin/pool/agent.mjs +57 -6
  48. package/bin/pool/ci-events.mjs +189 -0
  49. package/bin/pool/ci-events.test.mjs +143 -0
  50. package/bin/pool/docker.mjs +7 -0
  51. package/bin/pool/lane-tools.mjs +1 -0
  52. package/bin/pool/router.mjs +25 -1
  53. package/bin/pool/warm.mjs +1 -1
  54. package/bin/stats/ci-awareness.mjs +66 -0
  55. package/bin/stats/index.mjs +44 -3
  56. package/bin/stats/release-ledger.test.mjs +226 -0
  57. package/bin/stats/release.mjs +365 -1
  58. package/bin/stats/stats.test.mjs +36 -0
  59. package/docs/CI.md +31 -0
  60. package/docs/CONFIG.md +235 -2
  61. package/docs/ENV-LIBRARY.md +172 -0
  62. package/docs/STATS.md +43 -0
  63. package/docs/ci-events.md +88 -0
  64. package/docs/test-engine.md +98 -0
  65. package/package.json +1 -1
  66. package/pool/README.md +1 -0
  67. package/pool/image/entrypoint.sh +15 -3
  68. package/pool/services/docker-compose.yml +53 -0
  69. package/pool/services/git-mirror.sh +22 -0
  70. package/templates/github-actions/forge-env/action.yml +65 -0
@@ -0,0 +1,444 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Build once, promote (#5711, Forge CI W5): CI evidence bound to a commit, a tree and the image digests, so the deploy side
5
+ * can skip re-running what already passed. Off unless forge.yaml `deploy.promote.enabled` is true; `shadow` (default true)
6
+ * records what WOULD be skipped while the full pre-gate still runs.
7
+ *
8
+ * - Attestation: `{commit, tree, images, checks, config_hash}`, written only when every required check concluded `success`
9
+ * on the exact commit. It is the output of a `forge/promote-evidence` check run on that commit (the register
10
+ * `forge/release-gate` already uses): GitHub binds it to the sha, and it is accepted only from `evidence_app`.
11
+ * - `canPromote(evidence, target) -> {ok, reasons}` is pure and fails closed: the same tree, every required check passed,
12
+ * the same digests and the same config hash, else the full pre-gate runs (never weaker).
13
+ * - `planImages` is pure planning (no docker): an unchanged service reuses its previous digest, the others get buildx
14
+ * args with a registry layer cache and the configured cache mounts.
15
+ * Every effect goes through `io.api(method, path, body?)`, `io.gh(args)` and `io.git(args)`. Rationale: devdocs/decisions/5711-release-promote.md.
16
+ */
17
+ import { createHash } from "node:crypto";
18
+ import { load, JSON_SCHEMA } from "../vendor/js-yaml/js-yaml.mjs";
19
+ import { matchesAny } from "./release-unitmap.mjs";
20
+ import { evidenceSkips, catalogueAt, parseCatalogue, parseGatesConfig } from "./release-gates.mjs";
21
+
22
+ export const EVIDENCE_CHECK = "forge/promote-evidence";
23
+ export const DECISION_CHECK = "forge/promote-decision";
24
+ export const ATTEST_SCHEMA = "forgedock.release.attestation/v1";
25
+ export const DECISION_SCHEMA = "forgedock.release.promote/v1";
26
+ export const PLAN_SCHEMA = "forgedock.release.images/v1";
27
+ export const DEFAULT_APP = "github-actions";
28
+ /** Shadow exit criterion (NORTHSTAR 4): this many observed would-skip decisions with zero disagreements. */
29
+ export const SHADOW_EXIT = { observed: 10, disagree: 0 };
30
+ export const PROMOTE_FLAGS = ["--check", "--gate", "--attest", "--observed", "--report", "--images"];
31
+ export const PROMOTE_KEYS = ["enabled", "shadow", "required_checks", "evidence_app", "cache_ref", "cache_mode", "builder", "rebuild_all", "services"];
32
+ const SERVICE_KEYS = ["image", "context", "dockerfile", "paths", "cache_paths", "cache_ref"];
33
+ const DIGEST_RE = /^sha256:[0-9a-f]{64}$/;
34
+ const SHA_RE = /^[0-9a-f]{40,64}$/;
35
+ const NAME_RE = /^[a-z0-9][a-z0-9._-]*$/i;
36
+ const REF_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@-]*$/; // an image or cache ref: no whitespace or comma (a comma would split the buildx option list)
37
+
38
+ const isMap = (v) => !!v && typeof v === "object" && !Array.isArray(v);
39
+ const strList = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string" && x.trim()).map((x) => x.trim()) : typeof v === "string" && v.trim() ? [v.trim()] : []);
40
+ const str = (v) => (typeof v === "string" ? v.trim() : "");
41
+ const isDigest = (d) => typeof d === "string" && DIGEST_RE.test(d);
42
+ const sha256 = (s) => createHash("sha256").update(s).digest("hex");
43
+ /** JSON with sorted keys: the same value always hashes the same. */
44
+ const canonical = (v) => (Array.isArray(v) ? `[${v.map(canonical).join(",")}]` : isMap(v) ? `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}` : JSON.stringify(v ?? null));
45
+ const first = (e) => String(e?.message ?? e).split("\n")[0];
46
+
47
+ /**
48
+ * forge.yaml `deploy.promote` -> the normalized config. Absent, unreadable or `enabled` not true: `{mode: "off"}`.
49
+ * `required_checks` falls back to `gate.required_checks`, then the release policy's `ci.required_checks` list; `services`
50
+ * falls back to the policy `units` that name an image. `findings` lists what is wrong; any finding keeps promote from skipping.
51
+ * @param {string} raw forge.yaml text
52
+ * @param {{policy?: object}} [opts] the parsed `.forge/release.yaml`, when the repo has one
53
+ */
54
+ export function parsePromoteConfig(raw, { policy = null } = {}) {
55
+ const off = { enabled: false, shadow: true, mode: "off", requiredChecks: [], evidenceApp: DEFAULT_APP, cacheRef: "", cacheMode: "max", builder: "", rebuildAll: [], services: {}, findings: [] };
56
+ let y;
57
+ try { y = load(String(raw ?? ""), { schema: JSON_SCHEMA }); } catch (e) { return { ...off, findings: [`forge.yaml: ${first(e)}`] }; }
58
+ const p = y?.deploy?.promote;
59
+ if (!isMap(p) || p.enabled !== true) return off;
60
+ const findings = [];
61
+ for (const k of Object.keys(p)) if (!PROMOTE_KEYS.includes(k)) findings.push(`deploy.promote.${k}: unknown key`);
62
+ if (p.shadow !== undefined && typeof p.shadow !== "boolean") findings.push("deploy.promote.shadow: expected true or false");
63
+ const cacheMode = p.cache_mode === undefined ? "max" : String(p.cache_mode);
64
+ if (!["min", "max"].includes(cacheMode)) findings.push("deploy.promote.cache_mode: expected min or max");
65
+ const refOk = (at, v) => { if (v && !REF_RE.test(v)) findings.push(`${at}: ${JSON.stringify(v)} is not a registry reference`); return v; };
66
+ const services = {};
67
+ const src = isMap(p.services) ? p.services : Object.fromEntries(Object.entries(policy?.units ?? {}).filter(([, u]) => u?.image).map(([id, u]) => [id, { image: u.image, dockerfile: u.dockerfile ?? undefined, paths: u.paths }]));
68
+ if (p.services !== undefined && !isMap(p.services)) findings.push("deploy.promote.services: expected a mapping");
69
+ for (const [name, s] of Object.entries(src)) {
70
+ const at = `deploy.promote.services.${name}`;
71
+ if (!NAME_RE.test(name)) { findings.push(`${at}: invalid service name`); continue; }
72
+ if (!isMap(s)) { findings.push(`${at}: expected a mapping`); continue; }
73
+ for (const k of Object.keys(s)) if (!SERVICE_KEYS.includes(k)) findings.push(`${at}.${k}: unknown key`);
74
+ if (!str(s.image)) findings.push(`${at}.image: required`);
75
+ const context = str(s.context) || ".";
76
+ services[name] = { image: refOk(`${at}.image`, str(s.image)), context, dockerfile: str(s.dockerfile) || (context === "." ? "Dockerfile" : `${context.replace(/\/+$/, "")}/Dockerfile`), paths: strList(s.paths), cachePaths: strList(s.cache_paths), cacheRef: refOk(`${at}.cache_ref`, str(s.cache_ref)) };
77
+ }
78
+ const requiredChecks = strList(p.required_checks).length ? strList(p.required_checks) : strList(y?.gate?.required_checks).length ? strList(y.gate.required_checks) : strList(policy?.ci?.required_checks);
79
+ if (!requiredChecks.length) findings.push("deploy.promote.required_checks: no required checks (set it, or gate.required_checks)");
80
+ const shadow = p.shadow !== false;
81
+ return {
82
+ enabled: true, shadow, mode: shadow ? "shadow" : "enforce", requiredChecks, evidenceApp: str(p.evidence_app) || DEFAULT_APP,
83
+ cacheRef: refOk("deploy.promote.cache_ref", str(p.cache_ref)), cacheMode: ["min", "max"].includes(cacheMode) ? cacheMode : "max", builder: str(p.builder), rebuildAll: strList(p.rebuild_all), services, findings,
84
+ };
85
+ }
86
+
87
+ /** Hash of what the evidence was taken under: the required checks and the service build inputs. A deploy side configured differently never matches. */
88
+ export const configHash = (cfg) => sha256(canonical({ v: 1, required: [...(cfg?.requiredChecks ?? [])].sort(), rebuild_all: [...(cfg?.rebuildAll ?? [])].sort(), services: cfg?.services ?? {} }));
89
+
90
+ const runId = (url) => { const m = /\/actions\/runs\/(\d+)/.exec(String(url ?? "")); return m ? Number(m[1]) : null; };
91
+
92
+ /**
93
+ * Every required check concluded `success` on exactly `sha` (missing, unfinished, neutral, skipped and other-sha runs do not count).
94
+ * @param {{name, conclusion, head?, sha?, id?, run_id?, details_url?}[]} checks
95
+ * @returns {{ok: boolean, reasons: string[], checks: {name, conclusion, id, run_id}[]}}
96
+ */
97
+ export function checkEvidence(checks, required, sha) {
98
+ if (!Array.isArray(checks)) return { ok: false, reasons: ["unreadable input: checks"], checks: [] };
99
+ if (!Array.isArray(required) || !required.length) return { ok: false, reasons: ["unreadable input: no required checks"], checks: [] };
100
+ const reasons = [], out = [];
101
+ for (const name of required) {
102
+ const runs = checks.filter((c) => c?.name === name && (c.head ?? c.sha) === sha);
103
+ if (!runs.length) { reasons.push(`${name}: missing on ${sha}`); continue; }
104
+ const bad = runs.find((c) => c.conclusion !== "success");
105
+ if (bad) { reasons.push(`${name}: ${bad.conclusion ?? "unfinished"}, not success`); continue; }
106
+ const last = runs.reduce((a, b) => (Number(b.id ?? 0) >= Number(a.id ?? 0) ? b : a));
107
+ out.push({ name, conclusion: "success", id: last.id ?? null, run_id: last.run_id ?? runId(last.details_url) });
108
+ }
109
+ return { ok: !reasons.length, reasons, checks: out };
110
+ }
111
+
112
+ /** `{service: digest}` with only well-formed digests; anything else is a finding. */
113
+ function cleanImages(images) {
114
+ const out = {}, bad = [];
115
+ for (const [k, v] of Object.entries(isMap(images) ? images : {})) (isDigest(v) ? (out[k] = v) : bad.push(k));
116
+ return { out, bad };
117
+ }
118
+
119
+ /**
120
+ * The attestation of `commit`, or `{refused}` when a required check did not pass, a digest is malformed or a configured
121
+ * service has no digest. Nothing is written here.
122
+ * @returns {{attestation: object} | {refused: string[]}}
123
+ */
124
+ export function buildAttestation({ commit, tree, checks, images, cfg, now = Date.now() }) {
125
+ const reasons = [...(cfg?.findings ?? [])];
126
+ if (!SHA_RE.test(String(commit ?? ""))) reasons.push("no commit sha");
127
+ if (!SHA_RE.test(String(tree ?? ""))) reasons.push("no tree sha");
128
+ const ev = checkEvidence(checks, cfg?.requiredChecks, commit);
129
+ reasons.push(...ev.reasons);
130
+ const { out, bad } = cleanImages(images);
131
+ bad.forEach((s) => reasons.push(`image ${s}: not a sha256 digest`));
132
+ for (const s of Object.keys(cfg?.services ?? {})) if (!out[s] && !bad.includes(s)) reasons.push(`image ${s}: no digest`);
133
+ if (reasons.length) return { refused: reasons };
134
+ return { attestation: { schema: ATTEST_SCHEMA, commit, tree, images: out, checks: ev.checks, config_hash: configHash(cfg), at: new Date(now).toISOString() } };
135
+ }
136
+
137
+ /**
138
+ * The deploy-side decision, pure and fail-closed.
139
+ * `evidence`: an attestation (null when none). `target`: `{commit, tree, digests?: {service: digest}, required: string[],
140
+ * configHash, checks?}`: what is about to be deployed. `checks` are the check runs read NOW on the attested commit; when
141
+ * given they must still pass (a forged or stale attestation cannot stand in for them).
142
+ * @returns {{ok: boolean, reasons: string[], match?: "commit"|"tree"}}
143
+ */
144
+ export function canPromote(evidence, target) {
145
+ const no = (...reasons) => ({ ok: false, reasons });
146
+ if (!isMap(evidence) || evidence.schema !== ATTEST_SCHEMA) return no("no attestation for this commit");
147
+ if (!isMap(target) || !SHA_RE.test(String(target.commit ?? "")) || !SHA_RE.test(String(target.tree ?? ""))) return no("unreadable target: commit and tree are required");
148
+ if (!SHA_RE.test(String(evidence.commit ?? "")) || !SHA_RE.test(String(evidence.tree ?? ""))) return no("unreadable attestation: commit and tree are required");
149
+ const reasons = [];
150
+ if (evidence.tree !== target.tree) reasons.push(`tree ${target.tree.slice(0, 12)} is not the attested tree ${evidence.tree.slice(0, 12)}`);
151
+ const required = Array.isArray(target.required) ? target.required : [];
152
+ if (!required.length) reasons.push("no required checks configured");
153
+ const attested = Array.isArray(evidence.checks) ? evidence.checks : [];
154
+ for (const name of required) {
155
+ const c = attested.find((x) => x?.name === name);
156
+ if (!c) reasons.push(`${name}: not in the attestation`);
157
+ else if (c.conclusion !== "success") reasons.push(`${name}: attested as ${c.conclusion ?? "unfinished"}`);
158
+ }
159
+ if (target.checks !== undefined && required.length) reasons.push(...checkEvidence(target.checks, required, evidence.commit).reasons.map((r) => `now ${r}`));
160
+ if (!target.configHash || evidence.config_hash !== target.configHash) reasons.push("config hash differs from the attested one");
161
+ const want = isMap(target.digests) ? target.digests : {}, have = isMap(evidence.images) ? evidence.images : {};
162
+ if (Object.keys(have).length && !Object.keys(want).length) reasons.push("target digests unknown");
163
+ for (const [svc, d] of Object.entries(want)) {
164
+ if (!isDigest(d)) reasons.push(`image ${svc}: target digest is not a sha256 digest`);
165
+ else if (have[svc] !== d) reasons.push(`image ${svc}: ${d.slice(0, 19)} is not the attested ${have[svc] ? have[svc].slice(0, 19) : "(none)"}`);
166
+ }
167
+ return reasons.length ? { ok: false, reasons } : { ok: true, reasons: [], match: evidence.commit === target.commit ? "commit" : "tree" };
168
+ }
169
+
170
+ /**
171
+ * The decision document: `skip_pre_gate` is true only in enforce mode with `canPromote` ok and no config finding; shadow
172
+ * reports `would_skip` and never skips. `skips` explains each piece of work the evidence covers; `gates` are the catalogue
173
+ * gates with an `evidence_check` (a safety gate always runs).
174
+ */
175
+ export function decide(cfg, evidence, target, { catalogue = null, safety } = {}) {
176
+ const base = { schema: DECISION_SCHEMA, mode: cfg?.mode ?? "off", commit: target?.commit ?? null };
177
+ if (!cfg?.enabled) return { ...base, mode: "off", would_skip: false, skip_pre_gate: false, reasons: ["deploy.promote is off"], skips: [], gates: [] };
178
+ const v = canPromote(evidence, target);
179
+ const reasons = [...cfg.findings, ...v.reasons];
180
+ const ok = !reasons.length;
181
+ const skips = ok ? [
182
+ ...evidence.checks.filter((c) => target.required.includes(c.name)).map((c) => ({ what: `check:${c.name}`, why: `success on ${evidence.commit.slice(0, 12)}${c.run_id ? ` (run ${c.run_id})` : ""}` })),
183
+ ...Object.entries(target.digests ?? {}).map(([s, d]) => ({ what: `image:${s}`, why: `${d.slice(0, 19)} is the digest CI built and tested` })),
184
+ ] : [];
185
+ return {
186
+ ...base, would_skip: ok, skip_pre_gate: ok && cfg.mode === "enforce", reasons, skips,
187
+ gates: catalogue ? evidenceSkips(catalogue, evidence, { ok, safety }) : [],
188
+ ...(ok ? { evidence_commit: evidence.commit, match: v.match } : {}),
189
+ };
190
+ }
191
+
192
+ /** Human lines of a decision (`release promote --check`). */
193
+ export function formatDecision(d) {
194
+ if (d.mode === "off") return ["release promote: off (forge.yaml deploy.promote.enabled is not true); the full pre-gate runs"];
195
+ const head = d.would_skip
196
+ ? `release promote: ${d.mode === "enforce" ? "the pre-gate is skipped" : "shadow: the pre-gate WOULD be skipped (it still runs)"} for ${String(d.commit).slice(0, 12)} (${d.match === "commit" ? "the attested commit" : `same tree as attested ${String(d.evidence_commit).slice(0, 12)}`})`
197
+ : `release promote: the full pre-gate runs for ${String(d.commit).slice(0, 12)} (${d.mode})`;
198
+ return [head, ...d.reasons.map((r) => ` no: ${r}`), ...d.skips.map((s) => ` skip ${s.what}: ${s.why}`), ...d.gates.map((g) => ` ${g.skip ? "skip" : "keep"} gate:${g.gate}: ${g.why}`)];
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------------------------------------------------
202
+ // GitHub register: check runs on the commit
203
+
204
+ const lines = (s) => String(s ?? "").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
205
+
206
+ /** `{commit, tree, parents}` of `sha` (Git Data API: works in a shallow checkout). */
207
+ export async function readCommit({ io, repo, sha }) {
208
+ const c = await io.api("GET", `repos/${repo}/git/commits/${sha}`);
209
+ return { commit: c.sha, tree: c.tree?.sha, parents: (c.parents ?? []).map((p) => p.sha) };
210
+ }
211
+
212
+ /** Every check run on `sha` (paginated): `{name, conclusion, head, id, run_id, app}`. */
213
+ export async function readChecks({ io, repo, sha }) {
214
+ return lines(await io.gh(["api", "--paginate", `repos/${repo}/commits/${sha}/check-runs?per_page=100`, "--jq", ".check_runs[] | {name, conclusion, head: .head_sha, id, details_url, app: .app.slug}"]))
215
+ .map(({ details_url: u, ...c }) => ({ ...c, run_id: runId(u) }));
216
+ }
217
+
218
+ /** The JSON document of the newest `name` check run on `sha` posted by `app`; null when there is none or it is unreadable. */
219
+ async function readDoc({ io, repo, sha, name, app }) {
220
+ let runs;
221
+ try { runs = (await io.api("GET", `repos/${repo}/commits/${sha}/check-runs?check_name=${encodeURIComponent(name)}&per_page=100`))?.check_runs ?? []; } catch { return null; }
222
+ const mine = runs.filter((r) => r?.name === name && r.head_sha === sha && r.app?.slug === app).sort((a, b) => Number(b.id) - Number(a.id));
223
+ if (!mine.length) return null;
224
+ let text = mine[0].output?.text;
225
+ if (!text) { try { text = (await io.api("GET", `repos/${repo}/check-runs/${mine[0].id}`))?.output?.text; } catch { return null; } }
226
+ try { return JSON.parse(String(text)); } catch { return null; }
227
+ }
228
+
229
+ const postDoc = ({ io, repo, sha, name, title, summary, doc }) =>
230
+ io.api("POST", `repos/${repo}/check-runs`, { name, head_sha: sha, status: "completed", conclusion: "neutral", output: { title, summary, text: JSON.stringify(doc) } });
231
+
232
+ /** Write the attestation as the `forge/promote-evidence` check run of its commit (needs an app token with `checks: write`). */
233
+ export const writeEvidence = ({ io, repo }, attestation) =>
234
+ postDoc({ io, repo, sha: attestation.commit, name: EVIDENCE_CHECK, title: "CI evidence", summary: `Required checks passed on \`${attestation.commit.slice(0, 12)}\` (tree \`${attestation.tree.slice(0, 12)}\`); ${Object.keys(attestation.images).length} image digest(s).`, doc: attestation });
235
+
236
+ /**
237
+ * The attestation that covers `target` ({commit, parents}): the target itself, one of its parents (a merge commit of the
238
+ * attested head) or the head of a pull request merged as it (squash). Accepted only from `app`, and only when it names the
239
+ * commit its check run is on, so a document copied onto another commit is ignored.
240
+ */
241
+ export async function readEvidence({ io, repo, target, app = DEFAULT_APP }) {
242
+ const cands = [target.commit, ...(target.parents ?? [])];
243
+ try { for (const p of (await io.api("GET", `repos/${repo}/commits/${target.commit}/pulls`)) ?? []) if (p?.head?.sha) cands.push(p.head.sha); } catch { /* no associated pull request */ }
244
+ for (const sha of [...new Set(cands)].slice(0, 8)) {
245
+ const doc = await readDoc({ io, repo, sha, name: EVIDENCE_CHECK, app });
246
+ if (doc?.schema === ATTEST_SCHEMA && doc.commit === sha) return doc;
247
+ }
248
+ return null;
249
+ }
250
+
251
+ /**
252
+ * The deploy-side call (W6 `release-deploy.mjs` calls this, or `canPromote` with its own facts): read the target, the
253
+ * evidence and the checks as they are now, decide. Mode off: no read, no write. Any unreadable fact is a reason, never a throw.
254
+ * @param {{io, repo, cfg, sha, digests?: object, catalogue?: object, safety?: string[]}} p
255
+ */
256
+ export async function promoteDecision({ io, repo, cfg, sha, digests, catalogue = null, safety }) {
257
+ if (!cfg?.enabled) return decide(cfg, null, { commit: sha });
258
+ let target, evidence = null, checks;
259
+ try { target = await readCommit({ io, repo, sha }); } catch (e) { return { ...decide(cfg, null, { commit: sha }), reasons: [`cannot read commit ${sha}: ${first(e)}`] }; }
260
+ try { evidence = await readEvidence({ io, repo, target, app: cfg.evidenceApp }); } catch { evidence = null; }
261
+ if (evidence) { try { checks = await readChecks({ io, repo, sha: evidence.commit }); } catch { checks = null; } } // null: unreadable, so `canPromote` refuses
262
+ return decide(cfg, evidence, { ...target, digests, required: cfg.requiredChecks, configHash: configHash(cfg), ...(evidence ? { checks } : {}) }, { catalogue, safety });
263
+ }
264
+
265
+ /** Agreement of one record: a would-skip is right when the pre-gate passed and wrong when it failed; no claim otherwise. */
266
+ export const agreeOf = (wouldSkip, observed) => (wouldSkip && (observed === "pass" || observed === "fail") ? observed === "pass" : null);
267
+
268
+ /** Record a decision as the `forge/promote-decision` check run of the target commit (the audit trail in both modes). */
269
+ export async function recordDecision({ io, repo }, d, { observed = null, minutes = null, now = Date.now() } = {}) {
270
+ const doc = { schema: DECISION_SCHEMA, mode: d.mode, commit: d.commit, would_skip: !!d.would_skip, skipped: !!d.skip_pre_gate, reasons: d.reasons ?? [], evidence_commit: d.evidence_commit ?? null, observed, agree: agreeOf(d.would_skip, observed), minutes, at: new Date(now).toISOString() };
271
+ await postDoc({ io, repo, sha: d.commit, name: DECISION_CHECK, title: `promote ${d.mode}`, summary: `${d.would_skip ? "would skip" : "would not skip"} the pre-gate${observed ? `; the pre-gate ${observed === "pass" ? "passed" : "failed"}` : ""}`, doc });
272
+ return doc;
273
+ }
274
+
275
+ /**
276
+ * Shadow agreement over decision records. `disagree` is the number that matters: promote would have skipped a pre-gate that failed.
277
+ * @returns {{decisions, would_skip, observed, agree, disagree, minutes_saved, exit_met}}
278
+ */
279
+ export function agreement(records) {
280
+ const rs = (records ?? []).filter((r) => r?.schema === DECISION_SCHEMA);
281
+ const claimed = rs.filter((r) => r.would_skip && (r.observed === "pass" || r.observed === "fail"));
282
+ const agree = claimed.filter((r) => r.observed === "pass").length, disagree = claimed.length - agree;
283
+ return {
284
+ decisions: rs.length, would_skip: rs.filter((r) => r.would_skip).length, observed: claimed.length, agree, disagree,
285
+ minutes_saved: Math.round(claimed.filter((r) => r.observed === "pass").reduce((n, r) => n + (Number(r.minutes) > 0 ? Number(r.minutes) : 0), 0) * 10) / 10,
286
+ exit_met: claimed.length >= SHADOW_EXIT.observed && disagree <= SHADOW_EXIT.disagree,
287
+ };
288
+ }
289
+
290
+ // ---------------------------------------------------------------------------------------------------------------------
291
+ // Image build plan (pure)
292
+
293
+ /** The globs that decide whether a service's image changed: its `paths`, its build context and its Dockerfile. */
294
+ export function serviceGlobs(s) {
295
+ const ctx = String(s.context ?? ".").replace(/^\.\//, "").replace(/\/+$/, "");
296
+ return [...(s.paths ?? []), ...(ctx && ctx !== "." ? [`${ctx}/**`] : (s.paths ?? []).length ? [] : ["**"]), s.dockerfile].filter(Boolean);
297
+ }
298
+
299
+ /**
300
+ * Cache mounts of a service: one per `cache_paths` entry, with the id its Dockerfile declares (`RUN --mount=type=cache,target=..`;
301
+ * the id defaults to the target). `declared: false` means the Dockerfile has no such mount, so the path is not cached at all.
302
+ */
303
+ export function cacheMounts(dockerfileText, cachePaths) {
304
+ const found = new Map();
305
+ for (const m of String(dockerfileText ?? "").replace(/\\\r?\n/g, " ").matchAll(/--mount=([^\s]+)/g)) {
306
+ const kv = Object.fromEntries(m[1].split(",").map((p) => { const i = p.indexOf("="); return i < 0 ? [p, ""] : [p.slice(0, i), p.slice(i + 1)]; }));
307
+ const target = kv.target ?? kv.dst ?? kv.destination;
308
+ if (kv.type === "cache" && target) found.set(target.replace(/\/+$/, ""), kv.id || target);
309
+ }
310
+ return (cachePaths ?? []).map((p) => { const t = String(p).replace(/\/+$/, ""); return { target: t, id: found.get(t) ?? t, declared: found.has(t) }; });
311
+ }
312
+
313
+ const shq = (a) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(a) ? a : `'${String(a).replace(/'/g, `'\\''`)}'`);
314
+
315
+ /** `docker` argv of one service build: registry layer cache (`--cache-from`/`--cache-to type=registry`), digest to a metadata file, push. */
316
+ export function buildxArgs(name, s, { sha, cfg }) {
317
+ const ref = s.cacheRef || (cfg.cacheRef ? `${cfg.cacheRef}:${name}` : "");
318
+ return [
319
+ "buildx", "build", ...(cfg.builder ? ["--builder", cfg.builder] : []), "--file", s.dockerfile, "--tag", `${s.image}:${sha}`,
320
+ ...(ref ? ["--cache-from", `type=registry,ref=${ref}`, "--cache-to", `type=registry,ref=${ref},mode=${cfg.cacheMode}`] : []),
321
+ "--metadata-file", `.forge/build/${name}.json`, "--push", s.context,
322
+ ];
323
+ }
324
+
325
+ /** The image digest from a buildx `--metadata-file` (`containerimage.digest`), or null. */
326
+ export function digestFromMetadata(text) {
327
+ try { const d = JSON.parse(String(text))?.["containerimage.digest"]; return isDigest(d) ? d : null; } catch { return null; }
328
+ }
329
+
330
+ /**
331
+ * Which images to build. A service is REUSED (previous digest, no build) only when the changed paths are known, a previous
332
+ * digest exists, no `rebuild_all` path changed and none of its globs matches a changed path; every other case builds.
333
+ * @param {{cfg: object, changed: string[]|null, previous?: {[service: string]: string}, sha: string, dockerfiles?: {[service: string]: string}}} p
334
+ * @returns {{schema, sha, images: object[], build: string[], reuse: string[]}}
335
+ */
336
+ export function planImages({ cfg, changed, previous = {}, sha, dockerfiles = {} }) {
337
+ const files = Array.isArray(changed) ? changed.map((f) => String(f).replace(/^\.\//, "")) : null;
338
+ const all = files?.find((f) => matchesAny(cfg.rebuildAll, f));
339
+ const images = Object.entries(cfg.services ?? {}).map(([name, s]) => {
340
+ const hits = files ? files.filter((f) => matchesAny(serviceGlobs(s), f)) : [];
341
+ const reason = !files ? "changed paths unknown" : !isDigest(previous?.[name]) ? "no previous digest" : all ? `${all} rebuilds every image` : hits.length ? `changed: ${hits[0]}${hits.length > 1 ? ` (+${hits.length - 1})` : ""}` : null;
342
+ const mounts = cacheMounts(dockerfiles[name], s.cachePaths);
343
+ if (!reason) return { service: name, image: s.image, build: false, reason: "no changed path in its build inputs", digest: previous[name], cache_mounts: mounts };
344
+ const args = buildxArgs(name, s, { sha, cfg });
345
+ return { service: name, image: s.image, build: true, reason, tag: `${s.image}:${sha}`, args, command: ["docker", ...args].map(shq).join(" "), cache_mounts: mounts };
346
+ });
347
+ return { schema: PLAN_SCHEMA, sha, images, build: images.filter((i) => i.build).map((i) => i.service), reuse: images.filter((i) => !i.build).map((i) => i.service) };
348
+ }
349
+
350
+ export function formatPlan(plan) {
351
+ if (!plan.images.length) return ["release promote: no services (deploy.promote.services, or units with an image in .forge/release.yaml)"];
352
+ return plan.images.flatMap((i) => [
353
+ i.build ? `build ${i.service}: ${i.reason}` : `reuse ${i.service}: ${i.digest} (${i.reason})`,
354
+ ...(i.build ? [` ${i.command}`] : []),
355
+ ...i.cache_mounts.map((m) => (m.declared ? ` cache mount ${m.id} -> ${m.target}` : ` warning: ${m.target} is in cache_paths but the Dockerfile has no RUN --mount=type=cache,target=${m.target}`)),
356
+ ]);
357
+ }
358
+
359
+ // ---------------------------------------------------------------------------------------------------------------------
360
+ // CLI
361
+
362
+ const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : null; };
363
+ const jsonArg = (v, readFile) => { if (!v) return undefined; const t = v.trim().startsWith("{") ? v : readFile(v); return JSON.parse(t); };
364
+
365
+ /**
366
+ * `forgedock release promote --check | --gate | --attest | --observed pass|fail | --report | --images`.
367
+ * `ctx`: {io, raw: forge.yaml text, policy, readFile, defaultBranch, env, appendFile}. @returns the exit code.
368
+ * `--check` writes nothing. Mode off: one line, no read, no write, exit 0.
369
+ */
370
+ export async function promoteFromCli(argv, ctx) {
371
+ const { io, policy = null, readFile, defaultBranch = "main", env = {} } = ctx;
372
+ const cfg = parsePromoteConfig(ctx.raw, { policy });
373
+ const asJson = argv.includes("--json");
374
+ const out = (doc, text) => (asJson ? [JSON.stringify(doc)] : text).forEach((l) => io.print(l));
375
+ if (!cfg.enabled) { cfg.findings.forEach((f) => io.print(`release promote: ${f}`)); out(decide(cfg, null, {}), formatDecision({ mode: "off" })); return 0; }
376
+ const sha = flagOf(argv, "--sha") ?? String(io.git(["rev-parse", "HEAD"])).trim();
377
+ const repo = flagOf(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
378
+
379
+ if (argv.includes("--images")) {
380
+ const base = flagOf(argv, "--base"), list = flagOf(argv, "--changed");
381
+ let changed = list ? list.split(",").filter(Boolean) : null, previous;
382
+ if (!changed && base) { try { changed = String(io.git(["diff", "--name-only", base, sha])).split("\n").filter(Boolean); } catch { changed = null; } }
383
+ try { previous = jsonArg(flagOf(argv, "--previous"), readFile); } catch (e) { io.print(`release promote: --previous: ${first(e)}`); return 1; }
384
+ if (!previous && base) { // the digests attested for the base commit are the ones an unchanged service keeps
385
+ try { const b = await readCommit({ io, repo, sha: String(io.git(["rev-parse", base])).trim() }); previous = (await readEvidence({ io, repo, target: b, app: cfg.evidenceApp }))?.images; } catch { previous = undefined; }
386
+ }
387
+ const dockerfiles = {};
388
+ for (const [n, s] of Object.entries(cfg.services)) { try { dockerfiles[n] = String(io.git(["show", `${sha}:${s.dockerfile}`])); } catch { /* unreadable: mounts report as undeclared */ } }
389
+ const plan = planImages({ cfg, changed, previous: previous ?? {}, sha, dockerfiles });
390
+ cfg.findings.forEach((f) => io.print(`release promote: ${f}`));
391
+ out(plan, formatPlan(plan));
392
+ return cfg.findings.length ? 1 : 0;
393
+ }
394
+
395
+ if (argv.includes("--report")) {
396
+ const n = Math.min(100, Math.max(1, Number(flagOf(argv, "--last")) || 30));
397
+ const commits = (await io.api("GET", `repos/${repo}/commits?sha=${encodeURIComponent(defaultBranch)}&per_page=${n}`)) ?? [];
398
+ const records = [];
399
+ for (const c of commits) { const d = await readDoc({ io, repo, sha: c.sha, name: DECISION_CHECK, app: cfg.evidenceApp }); if (d) records.push(d); }
400
+ const a = agreement(records);
401
+ out({ schema: DECISION_SCHEMA, report: a, exit: SHADOW_EXIT }, [
402
+ `release promote: ${a.decisions} decision(s) on the last ${commits.length} ${defaultBranch} commit(s); ${a.would_skip} would skip, ${a.observed} with an observed pre-gate: ${a.agree} agree, ${a.disagree} disagree; ${a.minutes_saved} pre-gate minute(s) it would have saved`,
403
+ a.exit_met ? `release promote: exit criterion met (>= ${SHADOW_EXIT.observed} observed, ${SHADOW_EXIT.disagree} disagreements): the owner can set deploy.promote.shadow: false` : `release promote: exit criterion not met (needs >= ${SHADOW_EXIT.observed} observed would-skip decisions and ${SHADOW_EXIT.disagree} disagreements)`,
404
+ ]);
405
+ return a.disagree ? 1 : 0;
406
+ }
407
+
408
+ if (argv.includes("--attest")) {
409
+ let images, commit, checks;
410
+ try { images = jsonArg(flagOf(argv, "--digests"), readFile) ?? {}; } catch (e) { io.print(`release promote: --digests: ${first(e)}`); return 1; }
411
+ try { commit = await readCommit({ io, repo, sha }); checks = await readChecks({ io, repo, sha }); } catch (e) { io.print(`release promote: ${first(e)}`); return 1; }
412
+ const r = buildAttestation({ commit: commit.commit, tree: commit.tree, checks, images, cfg, now: io.now?.() });
413
+ if (r.refused) { r.refused.forEach((x) => io.print(`release promote: not attested: ${x}`)); return 1; }
414
+ if (!argv.includes("--dry-run")) await writeEvidence({ io, repo }, r.attestation);
415
+ out(r.attestation, [`release promote: ${argv.includes("--dry-run") ? "would attest" : "attested"} ${sha.slice(0, 12)} (tree ${commit.tree.slice(0, 12)}, ${r.attestation.checks.length} check(s), ${Object.keys(r.attestation.images).length} image(s))`]);
416
+ return 0;
417
+ }
418
+
419
+ if (argv.includes("--observed")) {
420
+ const observed = flagOf(argv, "--observed");
421
+ if (observed !== "pass" && observed !== "fail") { io.print("release promote: --observed must be pass or fail"); return 1; }
422
+ const prev = await readDoc({ io, repo, sha, name: DECISION_CHECK, app: cfg.evidenceApp });
423
+ if (!prev) { io.print(`release promote: no decision recorded for ${sha.slice(0, 12)}; run release promote --gate first`); return 1; }
424
+ const doc = await recordDecision({ io, repo }, { ...prev, skip_pre_gate: prev.skipped }, { observed, minutes: Number(flagOf(argv, "--minutes")) || null, now: io.now?.() });
425
+ out(doc, [`release promote: pre-gate ${observed} at ${sha.slice(0, 12)}; promote ${doc.would_skip ? "would have skipped it" : "would not have skipped it"}${doc.agree === null ? "" : doc.agree ? " (agree)" : " (DISAGREE: the evidence is not enough to skip)"}`]);
426
+ return 0;
427
+ }
428
+
429
+ // --check (no write) and --gate (the deploy-side call: records the decision)
430
+ let digests;
431
+ try {
432
+ digests = jsonArg(flagOf(argv, "--digests"), readFile);
433
+ if (!digests && policy?.deploy?.expected_digests_command) { const r = await io.rehearse(policy.deploy.expected_digests_command, { timeout: 120_000 }); digests = r?.ok ? JSON.parse(r.output) : undefined; }
434
+ } catch (e) { io.print(`release promote: digests: ${first(e)}`); digests = undefined; }
435
+ const cat = catalogueAt(io, sha);
436
+ const d = await promoteDecision({ io, repo, cfg, sha, digests, catalogue: cat === null ? null : parseCatalogue(cat).catalogue ?? null, safety: parseGatesConfig(policy).safety });
437
+ if (argv.includes("--gate")) {
438
+ try { await recordDecision({ io, repo }, d, { now: io.now?.() }); }
439
+ catch (e) { if (d.skip_pre_gate) { d.skip_pre_gate = false; d.reasons.push(`the decision could not be recorded: ${first(e)}`); } else io.print(`release promote: warning: the decision could not be recorded: ${first(e)}`); }
440
+ if (env.GITHUB_OUTPUT && ctx.appendFile) ctx.appendFile(env.GITHUB_OUTPUT, `skip_pre_gate=${d.skip_pre_gate}\nwould_skip=${d.would_skip}\n`);
441
+ }
442
+ out(d, formatDecision(d));
443
+ return 0;
444
+ }