forgedock 1.60.1 → 1.61.0

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 +183 -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 +18 -0
  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,470 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5711: build once, promote. Pure functions, the off switch, the check-run register and the CLI over a fake io.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import {
7
+ parsePromoteConfig, configHash, checkEvidence, buildAttestation, canPromote, decide, formatDecision, readEvidence, promoteDecision,
8
+ agreeOf, agreement, serviceGlobs, cacheMounts, buildxArgs, digestFromMetadata, planImages, formatPlan, promoteFromCli,
9
+ EVIDENCE_CHECK, DECISION_CHECK, ATTEST_SCHEMA, DECISION_SCHEMA, SHADOW_EXIT, PROMOTE_KEYS,
10
+ } from "./release-promote.mjs";
11
+ import { evidenceSkips, validateCatalogue } from "./release-gates.mjs";
12
+ import { releaseFromCli } from "./release.mjs";
13
+ import { validateForgeYaml, CLOSED } from "../config-schema.mjs";
14
+ import { tmpDir } from "../tests/_tmp.mjs";
15
+ import { writeFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+
18
+ const h = (c, n = 40) => c.repeat(n);
19
+ const A = h("a"), M = h("b"), T = h("1"), T2 = h("2"), P0 = h("c");
20
+ const dg = (c) => `sha256:${h(c, 64)}`;
21
+ // Three ecosystems: a Node web app, a Python API (uv) and a Go worker.
22
+ const YAML = `project:
23
+ owner: acme
24
+ deploy:
25
+ promote:
26
+ enabled: true
27
+ required_checks: [unit, build]
28
+ cache_ref: registry.example/acme/buildcache
29
+ rebuild_all: ["docker/base/**"]
30
+ services:
31
+ web:
32
+ image: registry.example/acme/web
33
+ context: web
34
+ cache_paths: ["/app/.next/cache", "/root/.npm"]
35
+ api:
36
+ image: registry.example/acme/api
37
+ context: services/api
38
+ dockerfile: services/api/Dockerfile.prod
39
+ paths: ["libs/shared/**", "uv.lock"]
40
+ cache_paths: ["/root/.cache/uv"]
41
+ worker:
42
+ image: registry.example/acme/worker
43
+ context: .
44
+ dockerfile: cmd/worker/Dockerfile
45
+ paths: ["cmd/worker/**", "internal/**", "go.sum"]
46
+ cache_paths: ["/root/.cache/go-build"]
47
+ `;
48
+ const ENFORCE = YAML.replace("enabled: true", "enabled: true\n shadow: false");
49
+ const cfg = parsePromoteConfig(YAML), cfgE = parsePromoteConfig(ENFORCE);
50
+ const IMAGES = { web: dg("1"), api: dg("2"), worker: dg("3") };
51
+ const run = (name, conclusion = "success", head = A, id = 1) => ({ name, conclusion, head, id, details_url: `https://example.invalid/acme/app/actions/runs/${900 + id}/job/5` });
52
+ const CHECKS = [run("unit", "success", A, 1), run("build", "success", A, 2), run("lint", "failure", A, 3)];
53
+ const att = (over = {}) => ({ ...buildAttestation({ commit: A, tree: T, checks: CHECKS, images: IMAGES, cfg, now: 0 }).attestation, ...over });
54
+ const target = (over = {}) => ({ commit: M, tree: T, digests: IMAGES, required: cfg.requiredChecks, configHash: configHash(cfg), ...over });
55
+
56
+ describe("deploy.promote config", () => {
57
+ it("is off when absent, false or unreadable, and off reads no service", () => {
58
+ for (const raw of ["", "project:\n owner: acme\n", "deploy:\n workflow: deploy.yml\n", YAML.replace("enabled: true", "enabled: false"), YAML.replace("enabled: true", 'enabled: "yes"')]) {
59
+ const c = parsePromoteConfig(raw);
60
+ assert.deepEqual([c.enabled, c.mode, Object.keys(c.services), c.findings], [false, "off", [], []]);
61
+ }
62
+ assert.equal(parsePromoteConfig("a: [1\n").mode, "off");
63
+ });
64
+ it("defaults to shadow once enabled; shadow: false is enforce", () => {
65
+ assert.deepEqual([cfg.mode, cfg.shadow, cfgE.mode], ["shadow", true, "enforce"]);
66
+ assert.deepEqual(cfg.findings, []);
67
+ assert.deepEqual(cfg.requiredChecks, ["unit", "build"]);
68
+ assert.equal(cfg.evidenceApp, "github-actions");
69
+ });
70
+ it("normalizes services: Dockerfile under the context by default", () => {
71
+ assert.equal(cfg.services.web.dockerfile, "web/Dockerfile");
72
+ assert.equal(cfg.services.api.dockerfile, "services/api/Dockerfile.prod");
73
+ assert.deepEqual(cfg.services.worker.paths, ["cmd/worker/**", "internal/**", "go.sum"]);
74
+ });
75
+ it("falls back to gate.required_checks, then the policy list, and to policy units for services", () => {
76
+ const bare = "gate:\n required_checks: [ci]\ndeploy:\n promote:\n enabled: true\n";
77
+ assert.deepEqual(parsePromoteConfig(bare).requiredChecks, ["ci"]);
78
+ const policy = { ci: { required_checks: ["tests"] }, units: { svc: { image: "registry.example/acme/svc", paths: ["svc/**"], dockerfile: "svc/Dockerfile" }, docs: { paths: ["docs/**"] } } };
79
+ const c = parsePromoteConfig("deploy:\n promote:\n enabled: true\n", { policy });
80
+ assert.deepEqual(c.requiredChecks, ["tests"]);
81
+ assert.deepEqual(Object.keys(c.services), ["svc"]);
82
+ assert.equal(c.services.svc.dockerfile, "svc/Dockerfile");
83
+ });
84
+ it("reports findings: no required checks, unknown keys, bad refs, bad mode", () => {
85
+ const c = parsePromoteConfig("deploy:\n promote:\n enabled: true\n shadwo: false\n cache_mode: all\n cache_ref: \"reg.example/x,mode=max\"\n services:\n web:\n contxt: web\n");
86
+ assert.deepEqual(c.findings.sort(), ["deploy.promote.cache_mode: expected min or max", 'deploy.promote.cache_ref: "reg.example/x,mode=max" is not a registry reference', "deploy.promote.required_checks: no required checks (set it, or gate.required_checks)", "deploy.promote.services.web.contxt: unknown key", "deploy.promote.services.web.image: required", "deploy.promote.shadwo: unknown key"]);
87
+ assert.equal(c.mode, "shadow", "a typo of shadow never turns enforce on");
88
+ });
89
+ it("the schema check knows the block and flags a typo", () => {
90
+ assert.deepEqual(CLOSED["deploy.promote"], PROMOTE_KEYS);
91
+ assert.deepEqual(validateForgeYaml(YAML), []);
92
+ assert.deepEqual(validateForgeYaml(YAML.replace("cache_ref:", "cache_reff:")).map((f) => f.key), ["deploy.promote.cache_reff"]);
93
+ assert.deepEqual(validateForgeYaml(YAML.replace("enabled: true", "enabled: maybe")).map((f) => f.code), ["wrong-type"]);
94
+ });
95
+ it("the config hash moves with required checks and service inputs, not with shadow or key order", () => {
96
+ assert.equal(configHash(cfg), configHash(cfgE));
97
+ assert.notEqual(configHash(cfg), configHash({ ...cfg, requiredChecks: ["unit"] }));
98
+ assert.notEqual(configHash(cfg), configHash(parsePromoteConfig(YAML.replace("context: web", "context: web2"))));
99
+ assert.equal(configHash(cfg), configHash({ ...cfg, requiredChecks: ["build", "unit"] }));
100
+ });
101
+ });
102
+
103
+ describe("attestation", () => {
104
+ it("records commit, tree, digests, checks with run ids and the config hash", () => {
105
+ assert.deepEqual(att(), { schema: ATTEST_SCHEMA, commit: A, tree: T, images: IMAGES, checks: [{ name: "unit", conclusion: "success", id: 1, run_id: 901 }, { name: "build", conclusion: "success", id: 2, run_id: 902 }], config_hash: configHash(cfg), at: "1970-01-01T00:00:00.000Z" });
106
+ });
107
+ it("is refused unless every required check is success on the exact commit", () => {
108
+ const refused = (checks) => buildAttestation({ commit: A, tree: T, checks, images: IMAGES, cfg }).refused;
109
+ assert.deepEqual(refused([run("unit")]), [`build: missing on ${A}`]);
110
+ assert.deepEqual(refused([run("unit"), run("build", "failure")]), ["build: failure, not success"]);
111
+ assert.deepEqual(refused([run("unit"), run("build", null)]), ["build: unfinished, not success"]);
112
+ assert.deepEqual(refused([run("unit"), run("build", "skipped")]), ["build: skipped, not success"]);
113
+ assert.deepEqual(refused([run("unit"), run("build", "success", M)]), [`build: missing on ${A}`]);
114
+ assert.deepEqual(refused([run("unit"), run("build", "success", A, 2), run("build", "failure", A, 9)]), ["build: failure, not success"]);
115
+ assert.deepEqual(refused(null), ["unreadable input: checks"]);
116
+ });
117
+ it("is refused for a missing or malformed digest of a configured service, or a config finding", () => {
118
+ const r = buildAttestation({ commit: A, tree: T, checks: CHECKS, images: { web: dg("1"), api: "latest" }, cfg }).refused;
119
+ assert.deepEqual(r, ["image api: not a sha256 digest", "image worker: no digest"]);
120
+ assert.match(buildAttestation({ commit: A, tree: T, checks: CHECKS, images: IMAGES, cfg: { ...cfg, findings: ["deploy.promote.x: unknown key"] } }).refused.join(), /unknown key/);
121
+ assert.deepEqual(buildAttestation({ commit: "", tree: "", checks: CHECKS, images: IMAGES, cfg }).refused.slice(0, 2), ["no commit sha", "no tree sha"]);
122
+ });
123
+ it("checkEvidence fails closed without required checks", () => {
124
+ assert.equal(checkEvidence(CHECKS, [], A).ok, false);
125
+ assert.equal(checkEvidence(CHECKS, undefined, A).ok, false);
126
+ });
127
+ });
128
+
129
+ describe("canPromote", () => {
130
+ it("accepts the attested commit and a merge commit with the same tree", () => {
131
+ assert.deepEqual(canPromote(att(), target({ commit: A })), { ok: true, reasons: [], match: "commit" });
132
+ assert.deepEqual(canPromote(att(), target()), { ok: true, reasons: [], match: "tree" });
133
+ assert.equal(canPromote(att(), target({ checks: CHECKS })).ok, true);
134
+ });
135
+ const no = (ev, tg, re) => { const v = canPromote(ev, tg); assert.equal(v.ok, false); assert.match(v.reasons.join("; "), re); };
136
+ it("refuses without evidence or with unreadable input", () => {
137
+ no(null, target(), /no attestation/);
138
+ no({ schema: "other" }, target(), /no attestation/);
139
+ no(att(), null, /unreadable target/);
140
+ no(att(), target({ tree: undefined }), /unreadable target/);
141
+ no(att({ tree: null }), target(), /unreadable attestation/);
142
+ });
143
+ it("refuses a different tree", () => no(att(), target({ tree: T2 }), /is not the attested tree/));
144
+ it("refuses a required check missing from, or not success in, the attestation", () => {
145
+ no(att(), target({ required: ["unit", "build", "migrations"] }), /migrations: not in the attestation/);
146
+ no(att({ checks: [{ name: "unit", conclusion: "success" }, { name: "build", conclusion: "failure" }] }), target(), /build: attested as failure/);
147
+ no(att(), target({ required: [] }), /no required checks configured/);
148
+ });
149
+ it("refuses when the checks no longer pass on the attested commit, or cannot be read", () => {
150
+ no(att(), target({ checks: [run("unit"), run("build", "failure")] }), /now build: failure/);
151
+ no(att(), target({ checks: [run("unit")] }), /now build: missing/);
152
+ no(att(), target({ checks: null }), /now unreadable input: checks/);
153
+ });
154
+ it("refuses a digest mismatch, a service that was never attested, and unknown target digests", () => {
155
+ no(att(), target({ digests: { ...IMAGES, web: dg("9") } }), /image web: .* is not the attested/);
156
+ no(att(), target({ digests: { ...IMAGES, cron: dg("4") } }), /image cron: .*\(none\)/);
157
+ no(att(), target({ digests: { web: "web:latest" } }), /not a sha256 digest/);
158
+ no(att(), target({ digests: undefined }), /target digests unknown/);
159
+ assert.equal(canPromote(att(), target({ digests: { web: IMAGES.web } })).ok, true, "a deploy of a subset of the attested images");
160
+ });
161
+ it("refuses a config-hash mismatch", () => {
162
+ no(att(), target({ configHash: h("f", 64) }), /config hash differs/);
163
+ no(att(), target({ configHash: undefined }), /config hash differs/);
164
+ });
165
+ it("a repo without images promotes on tree and checks alone", () => {
166
+ const c = parsePromoteConfig("deploy:\n promote:\n enabled: true\n required_checks: [unit]\n");
167
+ const a = buildAttestation({ commit: A, tree: T, checks: CHECKS, images: {}, cfg: c }).attestation;
168
+ assert.equal(canPromote(a, { commit: M, tree: T, required: ["unit"], configHash: configHash(c) }).ok, true);
169
+ });
170
+ });
171
+
172
+ describe("decide", () => {
173
+ it("off never skips and gives no skips", () => {
174
+ const d = decide(parsePromoteConfig(""), att(), target());
175
+ assert.deepEqual([d.mode, d.would_skip, d.skip_pre_gate, d.skips], ["off", false, false, []]);
176
+ });
177
+ it("shadow records would_skip and never skips; enforce skips", () => {
178
+ const s = decide(cfg, att(), target()), e = decide(cfgE, att(), target());
179
+ assert.deepEqual([s.mode, s.would_skip, s.skip_pre_gate], ["shadow", true, false]);
180
+ assert.deepEqual([e.mode, e.would_skip, e.skip_pre_gate, e.match, e.evidence_commit], ["enforce", true, true, "tree", A]);
181
+ assert.deepEqual(e.skips.map((x) => x.what), ["check:unit", "check:build", "image:web", "image:api", "image:worker"]);
182
+ assert.match(e.skips[0].why, /run 901/);
183
+ });
184
+ it("any mismatch or config finding means the full pre-gate, in enforce too", () => {
185
+ const d = decide(cfgE, att(), target({ tree: T2 }));
186
+ assert.deepEqual([d.would_skip, d.skip_pre_gate, d.skips], [false, false, []]);
187
+ const f = decide({ ...cfgE, findings: ["deploy.promote.x: unknown key"] }, att(), target());
188
+ assert.deepEqual([f.would_skip, f.skip_pre_gate], [false, false]);
189
+ assert.equal(decide(cfgE, null, target()).skip_pre_gate, false);
190
+ });
191
+ it("formats the explanation", () => {
192
+ assert.match(formatDecision(decide(cfg, att(), target()))[0], /shadow: the pre-gate WOULD be skipped \(it still runs\)/);
193
+ assert.match(formatDecision(decide(cfgE, att(), target({ commit: A })))[0], /the pre-gate is skipped .* \(the attested commit\)/);
194
+ const lines = formatDecision(decide(cfgE, att(), target({ tree: T2 })));
195
+ assert.match(lines[0], /the full pre-gate runs/);
196
+ assert.match(lines[1], /no: tree/);
197
+ assert.match(formatDecision({ mode: "off" })[0], /off/);
198
+ });
199
+ });
200
+
201
+ describe("gate catalogue: CI evidence", () => {
202
+ const G = { id: "tests-rerun", protects_against: "#1", where: "deploy.yml", determinism: "high", pre_merge_artifact: "ci", version: "v1", mode: "block", owner: "ops", review_by: "2027-01-01" };
203
+ const cat = { schema: 1, gates: [{ ...G, evidence_check: "unit" }, { ...G, id: "backup-freshness", evidence_check: "unit" }, { ...G, id: "migration:rehearsal", evidence_check: "build" }, { ...G, id: "smoke" }, { ...G, id: "contract", evidence_check: "contract-tests" }] };
204
+ it("evidence_check is a valid catalogue key", () => assert.deepEqual(validateCatalogue(cat), []));
205
+ it("skips only a non-safety gate whose check is attested, and only when the evidence was accepted", () => {
206
+ const r = evidenceSkips(cat, att(), { ok: true });
207
+ assert.deepEqual(r.map((g) => [g.gate, g.skip]), [["tests-rerun", true], ["backup-freshness", false], ["migration:rehearsal", false], ["contract", false]]);
208
+ assert.match(r[1].why, /safety gate/);
209
+ assert.match(r[3].why, /contract-tests is not in the attestation/);
210
+ assert.deepEqual(r[0].record, { gate: "tests-rerun", outcome: "skip", class: "unknown", minutes: 0, evidence: `promote: unit passed on ${A.slice(0, 12)}` });
211
+ assert.deepEqual(evidenceSkips(cat, att(), { ok: false }).filter((g) => g.skip), []);
212
+ assert.deepEqual(evidenceSkips(cat, att()).filter((g) => g.skip), [], "not accepted by default");
213
+ assert.deepEqual(evidenceSkips(null, att(), { ok: true }), []);
214
+ });
215
+ it("decide lists the gates", () => {
216
+ assert.deepEqual(decide(cfgE, att(), target(), { catalogue: cat }).gates.filter((g) => g.skip).map((g) => g.gate), ["tests-rerun"]);
217
+ assert.deepEqual(decide(cfgE, att(), target({ tree: T2 }), { catalogue: cat }).gates.filter((g) => g.skip), []);
218
+ });
219
+ });
220
+
221
+ describe("shadow agreement", () => {
222
+ const rec = (would_skip, observed, minutes = 20) => ({ schema: DECISION_SCHEMA, would_skip, observed, minutes });
223
+ it("a would-skip agrees with a passing pre-gate and disagrees with a failing one; no claim otherwise", () => {
224
+ assert.deepEqual([agreeOf(true, "pass"), agreeOf(true, "fail"), agreeOf(false, "pass"), agreeOf(false, "fail"), agreeOf(true, null)], [true, false, null, null, null]);
225
+ });
226
+ it("counts and applies the exit criterion", () => {
227
+ const some = [rec(true, "pass"), rec(true, "pass", 23.7), rec(true, "fail"), rec(false, "fail"), rec(true, null), { schema: "other" }];
228
+ assert.deepEqual(agreement(some), { decisions: 5, would_skip: 4, observed: 3, agree: 2, disagree: 1, minutes_saved: 43.7, exit_met: false });
229
+ assert.equal(agreement(Array.from({ length: SHADOW_EXIT.observed }, () => rec(true, "pass"))).exit_met, true);
230
+ assert.equal(agreement([...Array.from({ length: 20 }, () => rec(true, "pass")), rec(true, "fail")]).exit_met, false);
231
+ assert.equal(agreement(Array.from({ length: SHADOW_EXIT.observed - 1 }, () => rec(true, "pass"))).exit_met, false);
232
+ assert.equal(agreement(null).decisions, 0);
233
+ });
234
+ });
235
+
236
+ describe("image build plan", () => {
237
+ const plan = (changed, previous = IMAGES, c = cfg) => planImages({ cfg: c, changed, previous, sha: A });
238
+ it("globs: paths, the context and the Dockerfile; a root context without paths is everything", () => {
239
+ assert.deepEqual(serviceGlobs(cfg.services.web), ["web/**", "web/Dockerfile"]);
240
+ assert.deepEqual(serviceGlobs(cfg.services.worker), ["cmd/worker/**", "internal/**", "go.sum", "cmd/worker/Dockerfile"]);
241
+ assert.deepEqual(serviceGlobs({ context: ".", dockerfile: "Dockerfile", paths: [] }), ["**", "Dockerfile"]);
242
+ });
243
+ it("an unchanged service reuses its previous digest; a changed one builds", () => {
244
+ const p = plan(["web/src/app/page.tsx", "web/package-lock.json", "README.md"]);
245
+ assert.deepEqual([p.build, p.reuse], [["web"], ["api", "worker"]]);
246
+ assert.deepEqual(p.images[1], { service: "api", image: "registry.example/acme/api", build: false, reason: "no changed path in its build inputs", digest: IMAGES.api, cache_mounts: [{ target: "/root/.cache/uv", id: "/root/.cache/uv", declared: false }] });
247
+ assert.equal(p.images[0].reason, "changed: web/src/app/page.tsx (+1)");
248
+ });
249
+ it("each ecosystem's lockfile and shared paths rebuild only their service", () => {
250
+ assert.deepEqual(plan(["uv.lock"]).build, ["api"]);
251
+ assert.deepEqual(plan(["libs/shared/models.py"]).build, ["api"]);
252
+ assert.deepEqual(plan(["go.sum", "internal/queue/q.go"]).build, ["worker"]);
253
+ assert.deepEqual(plan(["services/api/Dockerfile.prod"]).build, ["api"]);
254
+ assert.deepEqual(plan(["docs/x.md"]).build, []);
255
+ assert.deepEqual(plan([]).build, []);
256
+ });
257
+ it("builds when the changed paths are unknown, there is no (valid) previous digest, or a rebuild_all path changed", () => {
258
+ assert.deepEqual(plan(null).build, ["web", "api", "worker"]);
259
+ assert.equal(plan(null).images[0].reason, "changed paths unknown");
260
+ assert.deepEqual(plan(["docs/x.md"], {}).build, ["web", "api", "worker"]);
261
+ assert.deepEqual(plan(["docs/x.md"], { ...IMAGES, api: "api:latest" }).build, ["api"]);
262
+ const p = plan(["docker/base/Dockerfile"]);
263
+ assert.deepEqual(p.build, ["web", "api", "worker"]);
264
+ assert.equal(p.images[2].reason, "docker/base/Dockerfile rebuilds every image");
265
+ });
266
+ it("emits buildx args with a registry layer cache per service", () => {
267
+ assert.deepEqual(buildxArgs("web", cfg.services.web, { sha: A, cfg }), [
268
+ "buildx", "build", "--file", "web/Dockerfile", "--tag", `registry.example/acme/web:${A}`,
269
+ "--cache-from", "type=registry,ref=registry.example/acme/buildcache:web", "--cache-to", "type=registry,ref=registry.example/acme/buildcache:web,mode=max",
270
+ "--metadata-file", ".forge/build/web.json", "--push", "web",
271
+ ]);
272
+ const c2 = parsePromoteConfig(YAML.replace("cache_ref: registry.example/acme/buildcache", "builder: ci-builder\n cache_mode: min").replace("context: web\n", "context: web\n cache_ref: registry.example/acme/web:cache\n"));
273
+ assert.deepEqual(c2.findings, []);
274
+ const a = buildxArgs("web", c2.services.web, { sha: A, cfg: c2 });
275
+ assert.deepEqual(a.slice(2, 4), ["--builder", "ci-builder"]);
276
+ assert.ok(a.includes("type=registry,ref=registry.example/acme/web:cache,mode=min"));
277
+ assert.equal(buildxArgs("api", c2.services.api, { sha: A, cfg: c2 }).includes("--cache-from"), false, "no cache ref: no cache flags");
278
+ assert.match(plan(["web/a"]).images[0].command, /^docker buildx build --file web\/Dockerfile /);
279
+ });
280
+ it("cache mounts come from the Dockerfile; an undeclared cache path is a warning", () => {
281
+ const df = "FROM node:22\nRUN --mount=type=cache,id=next,target=/app/.next/cache \\\n --mount=type=cache,target=/root/.npm npm run build\nRUN --mount=type=secret,id=tok,target=/x true\n";
282
+ assert.deepEqual(cacheMounts(df, ["/app/.next/cache", "/root/.npm/", "/x", "/root/.cache/uv"]), [
283
+ { target: "/app/.next/cache", id: "next", declared: true }, { target: "/root/.npm", id: "/root/.npm", declared: true },
284
+ { target: "/x", id: "/x", declared: false }, { target: "/root/.cache/uv", id: "/root/.cache/uv", declared: false },
285
+ ]);
286
+ const p = planImages({ cfg, changed: ["web/a"], previous: IMAGES, sha: A, dockerfiles: { web: df } });
287
+ const text = formatPlan(p).join("\n");
288
+ assert.match(text, /build web: changed: web\/a/);
289
+ assert.match(text, /cache mount next -> \/app\/\.next\/cache/);
290
+ assert.match(text, /reuse api: sha256:2+ /);
291
+ assert.match(text, /warning: \/root\/\.cache\/uv is in cache_paths but the Dockerfile has no RUN --mount=type=cache/);
292
+ assert.match(formatPlan(planImages({ cfg: parsePromoteConfig(""), changed: [], sha: A }))[0], /no services/);
293
+ });
294
+ it("reads a digest from buildx metadata", () => {
295
+ assert.equal(digestFromMetadata(JSON.stringify({ "containerimage.digest": dg("7") })), dg("7"));
296
+ assert.equal(digestFromMetadata("{}"), null);
297
+ assert.equal(digestFromMetadata("nope"), null);
298
+ });
299
+ });
300
+
301
+ /** A fake GitHub: commits, check runs (evidence and decisions are check runs too), pulls. Records every call. */
302
+ function fakeIo({ commits = {}, checks = {}, pulls = {}, app = "github-actions", denyPost = false } = {}) {
303
+ const calls = [], printed = [], runs = [];
304
+ let nextId = 100;
305
+ const io = {
306
+ calls, printed, runs, print: (l) => printed.push(l), now: () => 0,
307
+ git: (args) => { calls.push(`git ${args.join(" ")}`); if (args[0] === "rev-parse") return `${args[1] === "HEAD" ? M : args[1]}\n`; if (args[0] === "diff") return "web/a.ts\n"; throw new Error("no such object"); },
308
+ gh: async (args) => {
309
+ calls.push(`gh ${args.join(" ")}`);
310
+ if (args[0] === "repo") return JSON.stringify({ nameWithOwner: "acme/app" });
311
+ const m = /commits\/([0-9a-f]+)\/check-runs/.exec(args[2] ?? "");
312
+ if (m) return (checks[m[1]] ?? []).map((c) => JSON.stringify({ name: c.name, conclusion: c.conclusion, head: c.head, id: c.id, details_url: c.details_url, app: "github-actions" })).join("\n");
313
+ throw new Error(`unexpected gh ${args.join(" ")}`);
314
+ },
315
+ api: async (method, path, body) => {
316
+ calls.push(`${method} ${path}`);
317
+ let m;
318
+ if (method === "POST" && /\/check-runs$/.test(path)) {
319
+ if (denyPost) throw Object.assign(new Error("HTTP 403"), { status: 403 });
320
+ runs.push({ id: nextId++, name: body.name, head_sha: body.head_sha, app: { slug: app }, output: { text: body.output.text }, conclusion: body.conclusion });
321
+ return { id: nextId - 1 };
322
+ }
323
+ if ((m = /git\/commits\/([0-9a-f]+)$/.exec(path))) { const c = commits[m[1]]; if (!c) throw Object.assign(new Error("HTTP 404"), { status: 404 }); return { sha: m[1], tree: { sha: c.tree }, parents: (c.parents ?? []).map((sha) => ({ sha })) }; }
324
+ if ((m = /commits\/([0-9a-f]+)\/check-runs\?check_name=([^&]+)/.exec(path))) return { check_runs: runs.filter((r) => r.head_sha === m[1] && r.name === decodeURIComponent(m[2])) };
325
+ if ((m = /commits\/([0-9a-f]+)\/pulls$/.exec(path))) return pulls[m[1]] ?? [];
326
+ if (/\/commits\?sha=/.test(path)) return Object.keys(commits).map((sha) => ({ sha }));
327
+ throw new Error(`unexpected api ${method} ${path}`);
328
+ },
329
+ };
330
+ return io;
331
+ }
332
+ const WORLD = { commits: { [A]: { tree: T, parents: [P0] }, [M]: { tree: T, parents: [P0, A] } }, checks: { [A]: CHECKS } };
333
+ const cli = (argv, io, raw = YAML, extra = {}) => promoteFromCli(argv, { io, raw, env: {}, readFile: () => { throw new Error("no file"); }, ...extra });
334
+ const DIG = JSON.stringify(IMAGES);
335
+
336
+ describe("register and CLI", () => {
337
+ it("off: one line, exit 0, no read and no write", async () => {
338
+ const io = fakeIo(WORLD);
339
+ assert.equal(await cli(["--gate", "--sha", M], io, "project:\n owner: acme\n"), 0);
340
+ assert.deepEqual(io.calls, []);
341
+ assert.match(io.printed.join("\n"), /release promote: off/);
342
+ const io2 = fakeIo(WORLD);
343
+ await cli(["--check", "--json"], io2, YAML.replace("enabled: true", "enabled: false"));
344
+ assert.deepEqual([io2.calls, JSON.parse(io2.printed[0]).skip_pre_gate], [[], false]);
345
+ });
346
+ it("release promote <gate> --fixture is still the control verb; the promote flags route here", async () => {
347
+ const dir = tmpDir("promote-cli-");
348
+ writeFileSync(join(dir, "forge.yaml"), "project:\n owner: acme\n");
349
+ const io = fakeIo(WORLD);
350
+ assert.equal(await releaseFromCli(["promote", "--check"], { io, cwd: dir, env: {} }), 0);
351
+ assert.deepEqual(io.calls, [], "off reads nothing, not even the policy");
352
+ assert.match(io.printed[0], /release promote: off/);
353
+ });
354
+ it("--attest writes the evidence check run on the commit; --check then explains; --check writes nothing", async () => {
355
+ const io = fakeIo(WORLD);
356
+ assert.equal(await cli(["--attest", "--sha", A, "--digests", DIG], io), 0);
357
+ assert.deepEqual(io.runs.map((r) => [r.name, r.head_sha, r.conclusion]), [[EVIDENCE_CHECK, A, "neutral"]]);
358
+ assert.deepEqual(JSON.parse(io.runs[0].output.text).tree, T);
359
+ const before = io.runs.length;
360
+ assert.equal(await cli(["--check", "--sha", M, "--digests", DIG], io), 0);
361
+ assert.equal(io.runs.length, before);
362
+ assert.equal(io.calls.filter((c) => c.startsWith("POST")).length, 1);
363
+ assert.match(io.printed.join("\n"), /shadow: the pre-gate WOULD be skipped .*same tree as attested aaaaaaaaaaaa/);
364
+ });
365
+ it("--attest refuses (no write, exit 1) when a required check failed; --dry-run writes nothing", async () => {
366
+ const io = fakeIo({ ...WORLD, checks: { [A]: [run("unit"), run("build", "failure")] } });
367
+ assert.equal(await cli(["--attest", "--sha", A, "--digests", DIG], io), 1);
368
+ assert.deepEqual(io.runs, []);
369
+ assert.match(io.printed.join("\n"), /not attested: build: failure/);
370
+ const io2 = fakeIo(WORLD);
371
+ assert.equal(await cli(["--attest", "--sha", A, "--digests", DIG, "--dry-run"], io2), 0);
372
+ assert.deepEqual(io2.runs, []);
373
+ });
374
+ it("evidence is found on a parent (merge commit) or a merged pull request head (squash), never on an unrelated commit", async () => {
375
+ const io = fakeIo({ ...WORLD, commits: { ...WORLD.commits, [h("d")]: { tree: T, parents: [P0] } }, pulls: { [h("d")]: [{ head: { sha: A } }] } });
376
+ await cli(["--attest", "--sha", A, "--digests", DIG], io);
377
+ assert.equal((await readEvidence({ io, repo: "acme/app", target: { commit: M, parents: [P0, A] } })).commit, A);
378
+ assert.equal((await readEvidence({ io, repo: "acme/app", target: { commit: h("d"), parents: [P0] } })).commit, A);
379
+ assert.equal(await readEvidence({ io, repo: "acme/app", target: { commit: h("e"), parents: [P0] } }), null);
380
+ });
381
+ it("evidence from another app, or a document naming another commit, is ignored", async () => {
382
+ const other = fakeIo({ ...WORLD, app: "some-other-app" });
383
+ await cli(["--attest", "--sha", A, "--digests", DIG], other);
384
+ assert.equal(await readEvidence({ io: other, repo: "acme/app", target: { commit: A } }), null);
385
+ const io = fakeIo(WORLD);
386
+ io.runs.push({ id: 1, name: EVIDENCE_CHECK, head_sha: M, app: { slug: "github-actions" }, output: { text: JSON.stringify(att()) } }); // A's attestation copied onto M
387
+ assert.equal(await readEvidence({ io, repo: "acme/app", target: { commit: M, parents: [] } }), null);
388
+ io.runs.push({ id: 2, name: EVIDENCE_CHECK, head_sha: A, app: { slug: "github-actions" }, output: { text: "not json" } });
389
+ assert.equal(await readEvidence({ io, repo: "acme/app", target: { commit: A } }), null);
390
+ });
391
+ it("promoteDecision re-reads the checks: a check that turned red after the attestation blocks the skip", async () => {
392
+ const world = { ...WORLD, checks: { [A]: [...CHECKS] } };
393
+ const io = fakeIo(world);
394
+ await cli(["--attest", "--sha", A, "--digests", DIG], io);
395
+ assert.equal((await promoteDecision({ io, repo: "acme/app", cfg: cfgE, sha: M, digests: IMAGES })).skip_pre_gate, true);
396
+ world.checks[A].push(run("build", "failure", A, 50));
397
+ const d = await promoteDecision({ io, repo: "acme/app", cfg: cfgE, sha: M, digests: IMAGES });
398
+ assert.deepEqual([d.skip_pre_gate, d.reasons], [false, ["now build: failure, not success"]]);
399
+ });
400
+ it("promoteDecision: no evidence, an unreadable commit and mode off never skip", async () => {
401
+ const io = fakeIo(WORLD);
402
+ assert.deepEqual((await promoteDecision({ io, repo: "acme/app", cfg: cfgE, sha: M, digests: IMAGES })).reasons, ["no attestation for this commit"]);
403
+ const d = await promoteDecision({ io, repo: "acme/app", cfg: cfgE, sha: h("9"), digests: IMAGES });
404
+ assert.equal(d.skip_pre_gate, false);
405
+ assert.match(d.reasons[0], /cannot read commit/);
406
+ const off = fakeIo(WORLD);
407
+ assert.equal((await promoteDecision({ io: off, repo: "acme/app", cfg: parsePromoteConfig(""), sha: M })).mode, "off");
408
+ assert.deepEqual(off.calls, []);
409
+ });
410
+ it("shadow: --gate records would-skip but tells the workflow to run the pre-gate; --observed records agreement; --report counts", async () => {
411
+ const io = fakeIo(WORLD), outputs = [];
412
+ await cli(["--attest", "--sha", A, "--digests", DIG], io);
413
+ assert.equal(await cli(["--gate", "--sha", M, "--digests", DIG, "--json"], io, YAML, { env: { GITHUB_OUTPUT: "/out" }, appendFile: (f, t) => outputs.push([f, t]) }), 0);
414
+ assert.deepEqual(outputs, [["/out", "skip_pre_gate=false\nwould_skip=true\n"]]);
415
+ const dec = io.runs.filter((r) => r.name === DECISION_CHECK);
416
+ assert.deepEqual([dec.length, dec[0].head_sha], [1, M]);
417
+ assert.deepEqual((({ would_skip, skipped, observed, agree, mode }) => ({ would_skip, skipped, observed, agree, mode }))(JSON.parse(dec[0].output.text)), { would_skip: true, skipped: false, observed: null, agree: null, mode: "shadow" });
418
+ assert.equal(await cli(["--observed", "pass", "--sha", M, "--minutes", "23.7"], io), 0);
419
+ const last = JSON.parse(io.runs.at(-1).output.text);
420
+ assert.deepEqual([last.observed, last.agree, last.minutes, last.would_skip], ["pass", true, 23.7, true]);
421
+ io.printed.length = 0;
422
+ assert.equal(await cli(["--report", "--json"], io), 0);
423
+ assert.deepEqual(JSON.parse(io.printed[0]).report, { decisions: 1, would_skip: 1, observed: 1, agree: 1, disagree: 0, minutes_saved: 23.7, exit_met: false });
424
+ });
425
+ it("shadow disagreement: a would-skip whose pre-gate failed is reported and fails the report", async () => {
426
+ const io = fakeIo(WORLD);
427
+ await cli(["--attest", "--sha", A, "--digests", DIG], io);
428
+ await cli(["--gate", "--sha", M, "--digests", DIG], io);
429
+ await cli(["--observed", "fail", "--sha", M], io);
430
+ assert.match(io.printed.at(-1), /DISAGREE/);
431
+ assert.equal(await cli(["--report"], io), 1);
432
+ assert.match(io.printed.join("\n"), /1 disagree/);
433
+ assert.equal(await cli(["--observed", "maybe", "--sha", M], io), 1);
434
+ assert.equal(await cli(["--observed", "pass", "--sha", A], io), 1, "no decision recorded for that commit");
435
+ });
436
+ it("enforce: --gate skips on accepted evidence, and falls back when the decision cannot be recorded", async () => {
437
+ const io = fakeIo(WORLD), outputs = [];
438
+ await cli(["--attest", "--sha", A, "--digests", DIG], io, ENFORCE);
439
+ await cli(["--gate", "--sha", M, "--digests", DIG], io, ENFORCE, { env: { GITHUB_OUTPUT: "/out" }, appendFile: (f, t) => outputs.push(t) });
440
+ assert.deepEqual(outputs, ["skip_pre_gate=true\nwould_skip=true\n"]);
441
+ const deny = fakeIo({ ...WORLD, denyPost: true });
442
+ deny.runs.push({ id: 1, name: EVIDENCE_CHECK, head_sha: A, app: { slug: "github-actions" }, output: { text: JSON.stringify(att()) } });
443
+ const outs2 = [];
444
+ await cli(["--gate", "--sha", M, "--digests", DIG, "--json"], deny, ENFORCE, { env: { GITHUB_OUTPUT: "/out" }, appendFile: (f, t) => outs2.push(t) });
445
+ assert.deepEqual(outs2, ["skip_pre_gate=false\nwould_skip=true\n"]);
446
+ assert.match(JSON.parse(deny.printed.at(-1)).reasons.join(), /could not be recorded/);
447
+ });
448
+ it("enforce: wrong digests at the deploy side run the full pre-gate", async () => {
449
+ const io = fakeIo(WORLD), outputs = [];
450
+ await cli(["--attest", "--sha", A, "--digests", DIG], io, ENFORCE);
451
+ await cli(["--gate", "--sha", M, "--digests", JSON.stringify({ ...IMAGES, api: dg("8") })], io, ENFORCE, { env: { GITHUB_OUTPUT: "/out" }, appendFile: (f, t) => outputs.push(t) });
452
+ assert.deepEqual(outputs, ["skip_pre_gate=false\nwould_skip=false\n"]);
453
+ assert.match(io.printed.join("\n"), /no: image api/);
454
+ });
455
+ it("--images: changed paths from --base, previous digests from the base commit's attestation", async () => {
456
+ const io = fakeIo(WORLD);
457
+ await cli(["--attest", "--sha", A, "--digests", DIG], io);
458
+ io.printed.length = 0;
459
+ assert.equal(await cli(["--images", "--base", A, "--sha", M, "--json"], io), 0);
460
+ const p = JSON.parse(io.printed[0]);
461
+ assert.deepEqual([p.build, p.reuse], [["web"], ["api", "worker"]]);
462
+ assert.ok(io.calls.includes(`git diff --name-only ${A} ${M}`));
463
+ io.printed.length = 0;
464
+ await cli(["--images", "--sha", M], io);
465
+ assert.match(io.printed.join("\n"), /build api: changed paths unknown/);
466
+ io.printed.length = 0;
467
+ await cli(["--images", "--changed", "docs/a.md", "--previous", DIG, "--sha", M, "--json"], io);
468
+ assert.deepEqual(JSON.parse(io.printed[0]).build, []);
469
+ });
470
+ });
@@ -100,26 +100,31 @@ async function poll(io, polls, ms, fn) {
100
100
  return null;
101
101
  }
102
102
 
103
- /** A fenced dispatch of `workflow` and the run it makes (newer than every run seen before). Never redispatched once an intent exists (I7). */
104
- async function dispatchRung(ctx, rung, workflow, inputs, b) {
105
- const { io, repo } = ctx, st = ctx.state.rollbackRun, rec = (st.dispatch ??= {})[rung] ??= {};
103
+ /**
104
+ * A fenced dispatch of `workflow` and the run it makes (newer than every run seen before). Never redispatched once an intent
105
+ * exists (I7). `rec` is the caller's persisted record of this dispatch; `tag` ends the intent key; `what` names it in messages.
106
+ */
107
+ export async function dispatchOnce(ctx, rec, { workflow, inputs, tag, what }, b) {
108
+ const { io, repo } = ctx;
106
109
  const list = async () => json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--json", "databaseId,status,conclusion", "--limit", "10"])) ?? [];
107
110
  if (rec.baseId == null) { rec.baseId = Math.max(0, ...(await list()).map((r) => r.databaseId)); ctx.save(); }
108
- const had = rec.dispatched || (ctx.state.intents ?? []).some((i) => i.action === "dispatch" && String(i.key).endsWith(`:rollback:${rung}`));
111
+ const had = rec.dispatched || (ctx.state.intents ?? []).some((i) => i.action === "dispatch" && String(i.key).endsWith(`:${tag}`));
109
112
  if (!had) {
110
- const key = `${ctx.fence?.lease?.release ?? ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:rollback:${rung}`;
113
+ const key = `${ctx.fence?.lease?.release ?? ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:${tag}`;
111
114
  const f = await fenced(ctx.fence, { action: "dispatch", key }, (epoch) => io.gh(buildDispatchArgs({ workflow, repo, ref: ctx.def, inputs: { ...inputs, ...(epoch != null ? { forge_epoch: epoch } : {}) } })));
112
115
  if (f.refused) return { err: `dispatch ${f.refused}` };
113
116
  rec.dispatched = true; ctx.save();
114
117
  }
115
118
  const newer = async () => (await list()).find((r) => r.databaseId > rec.baseId) ?? null;
116
119
  const run = await poll(io, b.startPolls, b.pollMs, newer);
117
- if (!run) return { err: `no ${workflow} run appeared after the ${rung} rollback dispatch (never redispatched; check the Actions tab)` };
120
+ if (!run) return { err: `no ${workflow} run appeared after the ${what} (never redispatched; check the Actions tab)` };
118
121
  const done = await poll(io, b.donePolls, b.pollMs, async () => { const r = await newer(); return r?.status === "completed" ? r : null; });
119
122
  if (!done) return { err: `${workflow} run ${run.databaseId} did not finish` };
120
123
  return done.conclusion === "success" ? { run: done } : { err: `${workflow} run ${done.databaseId} concluded ${done.conclusion}` };
121
124
  }
122
125
 
126
+ const dispatchRung = (ctx, rung, workflow, inputs, b) => dispatchOnce(ctx, ((ctx.state.rollbackRun.dispatch ??= {})[rung] ??= {}), { workflow, inputs, tag: `rollback:${rung}`, what: `${rung} rollback dispatch` }, b);
127
+
123
128
  async function healthy(io, rb) {
124
129
  if (!rb.health_command) return { ok: true, note: "health: unchecked (rollback.health_command unset)" };
125
130
  const r = await io.rehearse(rb.health_command, { timeout: 120_000 });
@@ -226,6 +231,9 @@ export async function runRollback(ctx, { reason, to = "flag", trigger = null, la
226
231
  }
227
232
  const ok = rung !== "stop";
228
233
  const post = run.post;
234
+ if ((rung === "unit" || rung === "full") && d.stages && !post.stages_cleared) { // #5712: no stage checkpoint survives a code rollback
235
+ try { await (await import("./deploy-stages.mjs")).clearStages(ctx); post.stages_cleared = true; } catch (e) { d.stages = {}; io.print?.(`release rollback: the shared stage checkpoints were not cleared (${String(e?.message ?? e).split("\n")[0]}); the next deploy relies on stage checks`); }
236
+ }
229
237
  if (rung === "unit" || rung === "full") { if (rb.open_revert_pr !== false) post.revert ??= await revertPr(ctx, reason); }
230
238
  if (ok) post.reopened ??= await reopenIssues(ctx, reason);
231
239
  const inc = await (post.incident ? Promise.resolve(post.incident) : ensureIssue(ctx, `incident: rollback of release ${state.id}`, `Release ${state.id} (${short(d.merge)}) was rolled back via rung ${rung}.\n\nTrigger: ${trig}\nReason: ${reason}\nWhy this rung: ${why}\n${refused ? `Refused: ${refused}\n` : ""}${note ? `Result: ${note}\n` : ""}Ladder: ${run.history.map((h) => `${h.rung} -> ${h.result ?? h.why}`).join("; ") || "none"}`, `${INCIDENT_MARKER} ${state.id}`));
@@ -8,7 +8,7 @@
8
8
  * live in release-review.mjs / release-postmerge.mjs (stubs that block until their parts land). Promotion is opt-in: without
9
9
  * `--merge` or forge.yaml `release.auto_merge: true` the job stops at GATE_PASS and prints the merge command.
10
10
  */
11
- import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
11
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
12
12
  import { execFileSync } from "node:child_process";
13
13
  import { homedir } from "node:os";
14
14
  import { join } from "node:path";
@@ -478,7 +478,7 @@ export function realReleaseIo({ env = process.env, exec = execFileSync, print =
478
478
  }
479
479
 
480
480
  const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
481
- export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>] | forgedock release p0 <#issue | --branch B> [--units a,b] [--preempt] [--yes] | forgedock release verify <sha | release id> [--repo owner/repo] | forgedock release recover <release id> [--repo owner/repo] | forgedock release rollback <release id> --reason <text> [--to flag|unit|full] [--later id,id] [--repo owner/repo] [--json] | forgedock release plan [--lane auto|train|release|p0] [--milestone <slug>] [--issues N,N] [--repo owner/repo] [--json] | forgedock release start [--plan <id|hash>] [--approve] [--wave train|release|all] [--milestone <slug>] [--repo owner/repo] | forgedock release go <id> [--plan|--merge|--activate <key>] [--repo owner/repo] | forgedock release status [<id>] [--watch] [--interval s] [--json] | forgedock release explain <id | #issue | PR> [--json] | forgedock release check-config [--ref <git ref>] [--coverage] | forgedock release init [--conductor] | forgedock release control <hold|resume|cancel|lane|exempt|freeze|unfreeze> ... --reason <text> [--repo owner/repo] [--json] (the verbs also work as `forgedock release <verb>`) | forgedock release gates [check [--base <ref>] | demote] [--since 30d] [--json] | forgedock release gates record <release-id> --file <jsonl> | forgedock release report";
481
+ export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>] | forgedock release p0 <#issue | --branch B> [--units a,b] [--preempt] [--yes] | forgedock release verify <sha | release id> [--repo owner/repo] | forgedock release recover <release id> [--repo owner/repo] | forgedock release deploy --plan [<release id>] [--sha <sha>] [--json] | forgedock release deploy --resume <release id> [--sha <sha>] | forgedock release rollback <release id> --reason <text> [--to flag|unit|full] [--later id,id] [--repo owner/repo] [--json] | forgedock release plan [--lane auto|train|release|p0] [--milestone <slug>] [--issues N,N] [--repo owner/repo] [--json] | forgedock release start [--plan <id|hash>] [--approve] [--wave train|release|all] [--milestone <slug>] [--repo owner/repo] | forgedock release go <id> [--plan|--merge|--activate <key>] [--repo owner/repo] | forgedock release status [<id>] [--watch] [--interval s] [--json] | forgedock release explain <id | #issue | PR> [--json] | forgedock release check-config [--ref <git ref>] [--coverage] | forgedock release init [--conductor] | forgedock release control <hold|resume|cancel|lane|exempt|freeze|unfreeze> ... --reason <text> [--repo owner/repo] [--json] (the verbs also work as `forgedock release <verb>`) | forgedock release gates [check [--base <ref>] | demote] [--since 30d] [--json] | forgedock release gates record <release-id> --file <jsonl> | forgedock release promote --check|--gate [--sha <sha>] [--digests <file|json>] [--json] | forgedock release promote --attest [--sha <sha>] [--digests <file|json>] [--dry-run] | forgedock release promote --observed pass|fail [--sha <sha>] [--minutes N] | forgedock release promote --report [--last N] | forgedock release promote --images [--base <ref> | --changed a,b] [--previous <file|json>] [--json] | forgedock release report";
482
482
 
483
483
  /** `forgedock release ...`; @returns the process exit code (0 done or stopped at GATE_PASS, 1 refused, 3 blocked on a manual step). */
484
484
  export async function releaseFromCli(argv, deps = {}) {
@@ -573,6 +573,20 @@ export async function releaseFromCli(argv, deps = {}) {
573
573
  const def = readBranches(cwd).default || "main";
574
574
  return recoverFromCli(argv.slice(1), { io, policy: readPolicy({ io, defaultBranch: def, cwd }).policy ?? {}, def, actor: deps.actor ?? env.GITHUB_ACTOR, host: deps.host });
575
575
  }
576
+ if (argv[0] === "deploy") { // #5712: the deploy stage engine; --plan is read-only, --resume falls through to the release job below
577
+ const { deployFromCli, readEngine } = await import("./deploy-stages.mjs");
578
+ const { readPolicy } = await import("./release-config.mjs");
579
+ const def = readBranches(cwd).default || "main", root = releaseRoot(env), rest = argv.slice(1);
580
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: the engine is off */ }
581
+ const pol = readPolicy({ io, defaultBranch: def, cwd }).policy, managed = !!readReleaseConfig(raw).managed && !!io.api;
582
+ const repo = flag(rest, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
583
+ const lctx = managed ? { io, repo, credential: "driver" } : null;
584
+ const load = async (id) => (ID_RE.test(String(id)) ? openRelease(root, id).load() ?? (lctx ? (await readLedger(lctx, id))?.state ?? null : null) : null);
585
+ const r = await deployFromCli(rest, { io, load, engine: readEngine({ raw, io, def }), config: { deploy: pol?.deploy, policy: pol }, def, repo, lctx });
586
+ if (typeof r === "number") return r;
587
+ argv = ["--resume", r.resume, "--repo", repo, ...(flag(rest, "--lane") ? ["--lane", flag(rest, "--lane")] : [])];
588
+ deps = { ...deps, deploySha: r.sha };
589
+ }
576
590
  if (argv[0] === "gates") { // #5583: catalogue, telemetry report, admission check; release-gates is loaded lazily
577
591
  const g = await import("./release-gates.mjs");
578
592
  const { readPolicy } = await import("./release-config.mjs");
@@ -597,6 +611,16 @@ export async function releaseFromCli(argv, deps = {}) {
597
611
  const { checkConfigFromCli, initFromCli } = await import("./release-config.mjs");
598
612
  return (argv[0] === "init" ? initFromCli : checkConfigFromCli)(argv.slice(1), { io, cwd });
599
613
  }
614
+ if (argv[0] === "promote") { // #5711: build once, promote; `promote <gate> --fixture` stays the control verb below
615
+ const P = await import("./release-promote.mjs");
616
+ if (P.PROMOTE_FLAGS.some((f) => argv.includes(f))) {
617
+ const { readPolicy } = await import("./release-config.mjs");
618
+ const defaultBranch = readBranches(cwd).default || "main";
619
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: off */ }
620
+ const policy = P.parsePromoteConfig(raw).enabled ? readPolicy({ io, defaultBranch, cwd }).policy : null; // off: nothing else is read
621
+ return P.promoteFromCli(argv.slice(1), { io, raw, policy, defaultBranch, env, readFile: (f) => readFileSync(f, "utf8"), appendFile: appendFileSync });
622
+ }
623
+ }
600
624
  const cv = argv[0] === "control" ? argv[1] : argv[0]; // #5556: one implementation, the bare verbs are aliases
601
625
  if (CONTROL_VERBS.includes(cv)) {
602
626
  const { controlFromCli } = await import("./release-control.mjs");
@@ -620,6 +644,11 @@ export async function releaseFromCli(argv, deps = {}) {
620
644
  let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
621
645
  const config = readReleaseConfig(raw);
622
646
  if (config.managed) config.ciPolicy = readCiPolicy(cwd);
647
+ if (/^deploy:/m.test(raw)) { // #5712: the deploy stage engine, off unless forge.yaml deploy.engine.enabled
648
+ const { readEngine } = await import("./deploy-stages.mjs");
649
+ const engine = readEngine({ raw, io, def: readBranches(cwd).default || "main" });
650
+ if (engine) { config.deployEngine = engine; if (deps.deploySha) config.deploySha = deps.deploySha; }
651
+ }
623
652
  if (config.managed) { // #5560: deploy stages come from the default-branch policy only (I13)
624
653
  const { readPolicy } = await import("./release-config.mjs");
625
654
  const pol = readPolicy({ io, defaultBranch: readBranches(cwd).default || "main", cwd }).policy;