forgedock 1.59.1 → 1.60.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 (94) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -3
  2. package/bin/engine-cli.mjs +50 -10
  3. package/bin/labels.json +5 -0
  4. package/bin/lean/batch.mjs +21 -2
  5. package/bin/lean/batch.test.mjs +116 -1
  6. package/bin/lean/conformance.mjs +12 -5
  7. package/bin/lean/conformance.test.mjs +30 -2
  8. package/bin/lean/depcache.mjs +34 -15
  9. package/bin/lean/depcache.test.mjs +100 -1
  10. package/bin/lean/design-gate.mjs +15 -10
  11. package/bin/lean/design-gate.test.mjs +21 -0
  12. package/bin/lean/effects.mjs +18 -2
  13. package/bin/lean/execution.mjs +23 -5
  14. package/bin/lean/execution.test.mjs +81 -1
  15. package/bin/lean/gatewatch.test.mjs +5 -5
  16. package/bin/lean/issuewatch-triage.mjs +68 -0
  17. package/bin/lean/issuewatch-triage.test.mjs +98 -0
  18. package/bin/lean/issuewatch.mjs +34 -6
  19. package/bin/lean/issuewatch.test.mjs +11 -0
  20. package/bin/lean/lanelock.mjs +5 -4
  21. package/bin/lean/lean.mjs +123 -17
  22. package/bin/lean/lean.test.mjs +154 -6
  23. package/bin/lean/orchestrate-cancel.test.mjs +33 -0
  24. package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
  25. package/bin/lean/orchestrate-recovering.test.mjs +42 -0
  26. package/bin/lean/orchestrate.mjs +23 -10
  27. package/bin/lean/pagegate.mjs +50 -12
  28. package/bin/lean/pagegate.test.mjs +38 -1
  29. package/bin/lean/phaseledger.mjs +65 -2
  30. package/bin/lean/phaseledger.test.mjs +70 -2
  31. package/bin/lean/preflight.mjs +5 -2
  32. package/bin/lean/preflight.test.mjs +7 -0
  33. package/bin/lean/prompts.mjs +2 -1
  34. package/bin/lean/recovery.test.mjs +11 -6
  35. package/bin/lean/release-classify.mjs +143 -0
  36. package/bin/lean/release-classify.test.mjs +130 -0
  37. package/bin/lean/release-conductor.mjs +163 -0
  38. package/bin/lean/release-conductor.test.mjs +194 -0
  39. package/bin/lean/release-config.mjs +60 -8
  40. package/bin/lean/release-config.test.mjs +43 -1
  41. package/bin/lean/release-control.mjs +22 -5
  42. package/bin/lean/release-control.test.mjs +22 -0
  43. package/bin/lean/release-credentials.mjs +40 -0
  44. package/bin/lean/release-credentials.test.mjs +42 -0
  45. package/bin/lean/release-deploy.mjs +3 -3
  46. package/bin/lean/release-deploy.test.mjs +8 -0
  47. package/bin/lean/release-docs.test.mjs +93 -0
  48. package/bin/lean/release-fence.mjs +2 -0
  49. package/bin/lean/release-gate.mjs +88 -0
  50. package/bin/lean/release-gate.test.mjs +116 -0
  51. package/bin/lean/release-gates.mjs +5 -1
  52. package/bin/lean/release-ledger.mjs +47 -1
  53. package/bin/lean/release-ledger.test.mjs +33 -1
  54. package/bin/lean/release-mergeback.mjs +148 -0
  55. package/bin/lean/release-mergeback.test.mjs +129 -0
  56. package/bin/lean/release-p0.mjs +193 -0
  57. package/bin/lean/release-p0.test.mjs +127 -0
  58. package/bin/lean/release-plan.mjs +267 -0
  59. package/bin/lean/release-plan.test.mjs +202 -0
  60. package/bin/lean/release-preflight.mjs +16 -0
  61. package/bin/lean/release-regate.mjs +141 -0
  62. package/bin/lean/release-regate.test.mjs +149 -0
  63. package/bin/lean/release-review.mjs +5 -3
  64. package/bin/lean/release-rollback.mjs +277 -0
  65. package/bin/lean/release-rollback.test.mjs +245 -0
  66. package/bin/lean/release-snapshot.mjs +48 -9
  67. package/bin/lean/release-snapshot.test.mjs +43 -1
  68. package/bin/lean/release-start.mjs +164 -0
  69. package/bin/lean/release-start.test.mjs +171 -0
  70. package/bin/lean/release-status.mjs +6 -2
  71. package/bin/lean/release-train.mjs +159 -0
  72. package/bin/lean/release-train.test.mjs +139 -0
  73. package/bin/lean/release.mjs +127 -5
  74. package/bin/lean/release.test.mjs +80 -0
  75. package/bin/lean/sandbox-remote.mjs +2 -0
  76. package/bin/lean/schedd-load.test.mjs +82 -0
  77. package/bin/lean/schedd.mjs +67 -31
  78. package/bin/lean/schedd.test.mjs +80 -1
  79. package/bin/lean/validate-catalog.mjs +94 -0
  80. package/bin/lean/validate-catalog.test.mjs +42 -0
  81. package/bin/pool/agent.mjs +4 -1
  82. package/bin/pool/lane-tools.mjs +115 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/warm.mjs +1 -1
  85. package/docs/CONFIG.md +225 -1
  86. package/docs/ISSUE-WATCH.md +1 -0
  87. package/docs/design/visual-gate.md +10 -0
  88. package/docs/eval/adversarial-bench.md +1 -0
  89. package/package.json +5 -2
  90. package/pool/README.md +2 -0
  91. package/scripts/bench-adversarial.mjs +4 -0
  92. package/scripts/bench-lightlane.mjs +2 -1
  93. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  94. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -0,0 +1,245 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { readFileSync } from "node:fs";
6
+ import { runRollback, chooseRung, checkCounts, refuseAcross, classifyTrigger, rollbackFromCli } from "./release-rollback.mjs";
7
+
8
+ const TARGET = { sha: "aaaa1111", images: { api: "sha256:old-api", web: "sha256:old-web" } };
9
+ const POLICY = {
10
+ rollback: { ladder: ["flag", "unit", "full", "stop"], flags: [{ flag: "f1", kill_command: "kill f1" }], unit_workflow: "svc.yml", full_workflow: "rb.yml", result_command: "result", health_command: "health", open_revert_pr: true },
11
+ events: { webhook_url: "https://hook.test/x" },
12
+ };
13
+ const GOOD = { units: { api: { digest: "sha256:old-api", hosts: { h1: { expected: 1, rolled: 1 }, h2: { expected: 1, rolled: 1 } } }, web: { digest: "sha256:old-web", expected: 2, rolled: 2 } } };
14
+
15
+ function world({ policy = POLICY, record = GOOD, healthOk = true, runConclusion = "success", migrations = {}, closed = [1, 2], incidents = [], gitFail = false } = {}) {
16
+ const w = { gh: [], dispatches: [], rehearsed: [], git: [], holds: [], pages: [], issues: [...incidents], saved: 0, out: [] };
17
+ let runId = 100, dispatched = false;
18
+ const state = { id: "r20260101-000000-1", repo: "o/r", deploy: { phase: "LIVE_CHECKED", merge: "bbbb2222", target: TARGET }, steps: { "release-pr": { result: { pr: 7, issues: [1, 2] } } } };
19
+ const io = {
20
+ now: () => 1_700_000_000_000, sleep: async () => {}, print: (l) => w.out.push(l),
21
+ post: async (u, b) => { w.pages.push({ u, b }); return { ok: true }; },
22
+ rehearse: async (cmd) => {
23
+ w.rehearsed.push(cmd);
24
+ if (cmd === "result") return record ? { ok: true, output: JSON.stringify(record) } : { ok: false, output: "" };
25
+ if (cmd === "health") return { ok: healthOk, output: "unhealthy" };
26
+ return { ok: true, output: "" };
27
+ },
28
+ git: (a) => {
29
+ w.git.push(a);
30
+ if (gitFail && a[0] === "diff") throw new Error("bad revision");
31
+ if (a[0] === "diff") return Object.keys(migrations).join("\n");
32
+ if (a[0] === "show") return migrations[a[1].split(":")[1]] ?? "";
33
+ if (a.includes("rev-list")) return "bbbb2222 p1 p2";
34
+ return "";
35
+ },
36
+ gh: async (a) => {
37
+ w.gh.push(a);
38
+ if (a[0] === "workflow") { dispatched = true; w.dispatches.push(a); return ""; }
39
+ if (a[0] === "run") return JSON.stringify(dispatched ? [{ databaseId: ++runId > 101 ? 101 : 101, status: "completed", conclusion: runConclusion }] : [{ databaseId: 50, status: "completed", conclusion: "success" }]);
40
+ if (a[0] === "pr" && a[1] === "list") return "[]";
41
+ if (a[0] === "pr" && a[1] === "create") return "https://github.com/o/r/pull/77";
42
+ if (a[0] === "issue" && a[1] === "view") return JSON.stringify({ state: closed.includes(Number(a[2])) ? "CLOSED" : "OPEN" });
43
+ if (a[0] === "issue" && a[1] === "reopen") return "";
44
+ if (a[0] === "issue" && a[1] === "list") return JSON.stringify(w.issues);
45
+ if (a[0] === "issue" && a[1] === "create") { w.issues.push({ number: 99, body: a[a.indexOf("--body") + 1] }); return "https://github.com/o/r/issues/99"; }
46
+ throw new Error(`unrouted gh ${a.join(" ")}`);
47
+ },
48
+ };
49
+ const fence = { lctx: {}, lease: { holder: "h", epoch: 5, release: state.id }, intents: [], record: async (i) => { fence.intents.push(i); }, now: () => "t" };
50
+ return { w, state, io, fence, policy };
51
+ }
52
+ const ctxOf = (x, extra = {}) => ({ io: x.io, repo: "o/r", def: "main", state: x.state, save: () => { x.w.saved++; }, policy: x.policy, actor: "op", host: "h", config: { rollbackBounds: { pollMs: 0, startPolls: 2, donePolls: 2 } }, ...extra });
53
+ // A fence whose gate always passes: fenced() re-reads _active through lctx, so stub the module-level check via a lease-free fence-like object.
54
+ const noFence = null;
55
+
56
+ describe("rung choice", () => {
57
+ it("picks the lowest sufficient rung and says why", () => {
58
+ const r = chooseRung({ trigger: "smoke", rb: POLICY.rollback, target: TARGET });
59
+ assert.equal(r.rung, "flag"); assert.match(r.why, /smoke/);
60
+ });
61
+ it("a livecheck mismatch skips the flag rung; no digests skips unit", () => {
62
+ assert.equal(chooseRung({ trigger: "livecheck", rb: POLICY.rollback, target: TARGET }).rung, "unit");
63
+ const r = chooseRung({ trigger: "livecheck", rb: POLICY.rollback, target: { sha: "a", images: {} } });
64
+ assert.equal(r.rung, "full"); assert.match(r.why, /no recorded previous per-unit digests/);
65
+ });
66
+ it("--to raises the floor and nothing configured ends at stop", () => {
67
+ assert.equal(chooseRung({ trigger: "human", from: "full", rb: POLICY.rollback, target: TARGET }).rung, "full");
68
+ assert.equal(chooseRung({ trigger: "human", rb: {}, target: TARGET }).rung, "stop");
69
+ });
70
+ it("classifies the recorded trigger reasons", () => {
71
+ assert.equal(classifyTrigger("SLI breach over 15 min"), "sli");
72
+ assert.equal(classifyTrigger("smoke.yml (smoke) run 3 concluded failure"), "smoke");
73
+ assert.equal(classifyTrigger("LIVE_CHECK failed"), "livecheck");
74
+ });
75
+ });
76
+
77
+ describe("injected failure per rung (fake io)", () => {
78
+ it("rung 0 flag: kills the flags, checks health, records the reason", async () => {
79
+ const x = world();
80
+ const r = await runRollback(ctxOf(x), { reason: "smoke red", trigger: "smoke" });
81
+ assert.equal(r.rung, "flag"); assert.equal(r.ok, true);
82
+ assert.deepEqual(x.w.rehearsed.filter((c) => c === "kill f1"), ["kill f1"]);
83
+ assert.equal(x.w.dispatches.length, 0);
84
+ assert.equal(x.state.rollbackRun.reason, "smoke red");
85
+ assert.match(x.state.rollbackRun.why, /lowest sufficient rung is flag/);
86
+ assert.equal(r.post.revert, undefined); // code is unchanged: default already equals live
87
+ });
88
+ it("rung 0 health failure escalates to the unit rung", async () => {
89
+ const x = world({ healthOk: false });
90
+ const r = await runRollback(ctxOf(x), { reason: "smoke red", trigger: "smoke" });
91
+ assert.equal(r.history[0].rung, "flag"); assert.match(r.history[0].result, /health command failed/);
92
+ assert.equal(r.history[1].rung, "unit");
93
+ });
94
+ it("rung 1 unit: dispatches the service rollback with the previous digests and the epoch", async () => {
95
+ const x = world();
96
+ const r = await runRollback(ctxOf(x, { fence: okFence(x) }), { reason: "deploy mismatch", trigger: "livecheck" });
97
+ assert.equal(r.rung, "unit"); assert.equal(r.ok, true);
98
+ const a = x.w.dispatches[0];
99
+ assert.deepEqual(a.slice(0, 3), ["workflow", "run", "svc.yml"]);
100
+ assert.ok(a.includes("action=rollback")); assert.ok(a.includes("forge_epoch=5"));
101
+ assert.ok(a.includes(`digests=${JSON.stringify(TARGET.images)}`));
102
+ assert.equal(r.post.revert.pr, 77);
103
+ });
104
+ it("rung 2 full: dispatches the standalone workflow with the target sha", async () => {
105
+ const x = world({ policy: { ...POLICY, rollback: { ...POLICY.rollback, unit_workflow: undefined } } });
106
+ const r = await runRollback(ctxOf(x, { fence: okFence(x) }), { reason: "x", trigger: "livecheck" });
107
+ assert.equal(r.rung, "full");
108
+ const a = x.w.dispatches[0];
109
+ assert.equal(a[2], "rb.yml"); assert.ok(a.includes("sha=aaaa1111")); assert.ok(a.includes("forge_epoch=5"));
110
+ assert.ok(!a.some((v) => /override_|acknowledge_/.test(v)));
111
+ });
112
+ it("rung 3 stop: nothing configured holds, pages and opens the incident", async () => {
113
+ const x = world({ policy: { rollback: { ladder: ["stop"] }, events: POLICY.events } });
114
+ const r = await runRollback(ctxOf(x), { reason: "crash loop", trigger: "crashloop", later: [] });
115
+ assert.equal(r.rung, "stop"); assert.equal(r.ok, false);
116
+ assert.equal(x.w.pages.length, 1); assert.match(x.w.pages[0].b.text, /crash loop/);
117
+ assert.equal(r.post.incident.number, 99);
118
+ });
119
+ });
120
+
121
+ describe("counts check (Q8)", () => {
122
+ it("a matching record passes", () => assert.equal(checkCounts(GOOD, TARGET), null));
123
+ it("a per-host mismatch fails", () => {
124
+ const bad = structuredClone(GOOD); bad.units.api.hosts.h2.rolled = 0;
125
+ assert.match(checkCounts(bad, TARGET), /api@h2: 0 of 1/);
126
+ });
127
+ it("a missing unit, a wrong digest and an unreadable record fail", () => {
128
+ assert.match(checkCounts({ units: { api: GOOD.units.api } }, TARGET), /no entry for web/);
129
+ const w = structuredClone(GOOD); w.units.web.digest = "sha256:new"; assert.match(checkCounts(w, TARGET), /web: rolled to/);
130
+ assert.match(checkCounts(null, TARGET), /unreadable/);
131
+ });
132
+ it("a mismatch after rung 1 escalates to rung 3; a matching one completes", async () => {
133
+ const bad = structuredClone(GOOD); bad.units.api.hosts.h2.rolled = 0;
134
+ const x = world({ record: bad });
135
+ const r = await runRollback(ctxOf(x, { fence: okFence(x) }), { reason: "x", trigger: "livecheck" });
136
+ assert.equal(r.rung, "stop"); assert.match(r.history[0].result, /counts check/);
137
+ assert.equal(x.w.pages.length, 1);
138
+ const y = world();
139
+ assert.equal((await runRollback(ctxOf(y, { fence: okFence(y) }), { reason: "x", trigger: "livecheck" })).ok, true);
140
+ const z = world({ record: null });
141
+ assert.equal((await runRollback(ctxOf(z, { fence: okFence(z) }), { reason: "x", trigger: "livecheck" })).rung, "stop");
142
+ });
143
+ it("a failed rollback run escalates to rung 3", async () => {
144
+ const x = world({ runConclusion: "failure" });
145
+ const r = await runRollback(ctxOf(x, { fence: okFence(x) }), { reason: "x", trigger: "livecheck" });
146
+ assert.equal(r.rung, "stop"); assert.match(r.history[0].result, /concluded failure/);
147
+ });
148
+ });
149
+
150
+ describe("refuse_across (I8)", () => {
151
+ const DESTRUCTIVE = { "db/migrations/0042.sql": "ALTER TABLE users DROP COLUMN legacy;" };
152
+ it("refuses across a destructive migration and never reaches a code rung", async () => {
153
+ const x = world({ migrations: DESTRUCTIVE });
154
+ const r = await runRollback(ctxOf(x, { fence: okFence(x) }), { reason: "x", trigger: "livecheck" });
155
+ assert.match(r.refused, /crosses destructive migration db\/migrations\/0042.sql/);
156
+ assert.equal(r.rung, "stop"); assert.equal(x.w.dispatches.length, 0);
157
+ });
158
+ it("a harmless migration, none, or an unreadable history", () => {
159
+ const x = world({ migrations: { "db/migrations/0043.sql": "CREATE TABLE t (id int);" } });
160
+ assert.equal(refuseAcross({ io: x.io, target: "a", live: "b" }).ok, true);
161
+ assert.match(refuseAcross({ io: world({ gitFail: true }).io, target: "a", live: "b" }).refused, /cannot list migrations/);
162
+ });
163
+ it("the flag rung is still allowed across a destructive migration (no code moves)", async () => {
164
+ const x = world({ migrations: DESTRUCTIVE });
165
+ const r = await runRollback(ctxOf(x), { reason: "smoke", trigger: "smoke" });
166
+ assert.equal(r.rung, "flag"); assert.equal(r.ok, true);
167
+ });
168
+ it("the module has no SQL verb and no database client (static)", () => {
169
+ const src = readFileSync(new URL("./release-rollback.mjs", import.meta.url), "utf8").replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, "");
170
+ assert.doesNotMatch(src, /\b(SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|TRUNCATE|GRANT)\b/);
171
+ assert.doesNotMatch(src, /\b(psql|mysql|sqlite3?|pg_dump|knex|sequelize)\b/i);
172
+ });
173
+ });
174
+
175
+ describe("after a rollback", () => {
176
+ it("reopens the wave's issues, one incident (a second run creates none), holds later waves", async () => {
177
+ const x = world();
178
+ const r = await runRollback(ctxOf(x, { fence: okFence(x) }), { reason: "smoke red", trigger: "livecheck", later: ["r20260102-000000-2"] });
179
+ assert.deepEqual(r.post.reopened, [1, 2]);
180
+ assert.equal(x.w.gh.filter((a) => a[0] === "issue" && a[1] === "create").length, 1);
181
+ assert.deepEqual(r.post.held, []); // unmanaged (no io.api): no control path, nothing faked
182
+ delete x.state.rollbackRun.post.incident; // a fresh process: the marker search finds the issue
183
+ await runRollback(ctxOf(x, { fence: okFence(x) }), { reason: "smoke red", trigger: "livecheck" });
184
+ assert.equal(x.w.gh.filter((a) => a[0] === "issue" && a[1] === "create").length, 1);
185
+ });
186
+ it("the revert PR runs in a throwaway worktree and is reused when one is open", async () => {
187
+ const x = world();
188
+ await runRollback(ctxOf(x, { fence: okFence(x) }), { reason: "x", trigger: "livecheck" });
189
+ assert.ok(x.w.git.some((a) => a[0] === "worktree" && a[1] === "add"));
190
+ assert.ok(x.w.git.some((a) => a.includes("revert") && a.includes("-m")));
191
+ assert.ok(x.w.git.some((a) => a[0] === "worktree" && a[1] === "remove"));
192
+ assert.ok(x.w.gh.some((a) => a[0] === "pr" && a[1] === "create"));
193
+ });
194
+ });
195
+
196
+ describe("later waves are held through the control path", () => {
197
+ it("writes a hold per later wave into _active", async () => {
198
+ const x = world();
199
+ const files = {}, active = { epoch: 5, lease: { holder: "h", epoch: 5, release: x.state.id } }; let cur = active;
200
+ x.io.api = async (m, p, body) => {
201
+ if (m === "GET" && /git\/ref\/heads\/_active$/.test(p)) return { object: { sha: "h0" } };
202
+ if (m === "GET" && /contents\/active\.json/.test(p)) return { content: Buffer.from(JSON.stringify(cur)).toString("base64") };
203
+ if (m === "GET" && /contents\/controls\.jsonl/.test(p)) return { content: "" };
204
+ if (m === "GET" && /git\/commits\//.test(p)) return { tree: { sha: "t0" } };
205
+ if (m === "POST" && /git\/trees/.test(p)) { for (const t of body.tree) files[t.path] = t.content; return { sha: "t1" }; }
206
+ if (m === "POST" && /git\/commits/.test(p)) return { sha: "c1" };
207
+ if (m === "PATCH" && /git\/refs/.test(p)) { cur = JSON.parse(files["active.json"]); return {}; }
208
+ if (m === "POST" && /comments/.test(p)) return { id: 1 };
209
+ throw new Error(`unrouted ${m} ${p}`);
210
+ };
211
+ const r = await runRollback(ctxOf(x), { reason: "smoke red", trigger: "smoke", later: ["r20260102-000000-2"] });
212
+ assert.deepEqual(r.post.held, ["r20260102-000000-2"]);
213
+ assert.match(cur.holds["r20260102-000000-2"].reason, /rolled back: smoke red/);
214
+ });
215
+ });
216
+
217
+ describe("CLI", () => {
218
+ it("refuses without a reason, an id or a valid --to", async () => {
219
+ const x = world();
220
+ const rel = { load: () => x.state, save: () => {} };
221
+ const run = (argv) => rollbackFromCli(argv, { io: x.io, rel, policy: x.policy, def: "main" });
222
+ assert.equal(await run(["r1", "--json"]), 1);
223
+ assert.equal(await run(["--reason", "x"]), 1);
224
+ assert.equal(await run(["r1", "--reason", "x", "--to", "stop"]), 1);
225
+ assert.match(x.w.out.join("\n"), /--reason is required/);
226
+ });
227
+ it("an unmanaged run takes the flag rung and exits 0", async () => {
228
+ const x = world();
229
+ const rel = { load: () => x.state, save: () => {} };
230
+ assert.equal(await rollbackFromCli(["r20260101-000000-1", "--reason", "smoke red"], { io: x.io, rel, policy: x.policy, def: "main" }), 0);
231
+ assert.match(x.w.out.at(-1), /rolled back at rung flag/);
232
+ });
233
+ });
234
+
235
+ // A fence for the fake io: the real fenced() re-reads _active through fence.lctx, which this world does not serve,
236
+ // so the dispatch tests use a fence-shaped object whose gate is the lease check against a stubbed _active.
237
+ function okFence(x) {
238
+ const active = { epoch: 5, lease: { holder: "h", epoch: 5, release: x.state.id } };
239
+ const lctx = { io: { api: async (m, p) => {
240
+ if (/git\/ref\/heads\/_active$/.test(p)) return { object: { sha: "h0" } };
241
+ if (/contents\/active\.json/.test(p)) return { content: Buffer.from(JSON.stringify(active)).toString("base64") };
242
+ throw new Error(`unrouted ${m} ${p}`);
243
+ } }, repo: "o/r", credential: "driver" };
244
+ return { lctx, lease: active.lease, record: async (rec) => { (x.state.intents ??= []).push(rec); }, now: () => "t" };
245
+ }
@@ -12,6 +12,10 @@ const REMOTE = "origin";
12
12
  /** Head movement after the cut (#5567): the fix push, a recorded `main-sync` cherry-pick of a staging commit, or a mechanical `revert`. */
13
13
  export const PICK_KINDS = ["fix", "main-sync", "revert"];
14
14
  import { BLOCKER_LABEL } from "./release-rehearsal.mjs";
15
+ import { roleRefusal } from "./release-credentials.mjs";
16
+ /** #5561 (I12): a push to release/* or train/* refuses for a lane-role context, except the one fix push; no credential given means the driver (the release host). */
17
+ const pushRefusal = (credential, branch, fixPush = false) => roleRefusal(credential ?? "driver", "push", { branch, fixPush });
18
+
15
19
  export const DEFAULT_PATTERN = "release/{date}-{n}";
16
20
  const MARKER = "FORGE:RELEASE";
17
21
  const REF_RE = /^[A-Za-z0-9._/-]+$/;
@@ -43,7 +47,7 @@ export function branchName(pattern, now, n) {
43
47
  return name;
44
48
  }
45
49
 
46
- const isAncestor = (git, a, b) => { try { git(["merge-base", "--is-ancestor", a, b]); return true; } catch { return false; } };
50
+ export const isAncestor = (git, a, b) => { try { git(["merge-base", "--is-ancestor", a, b]); return true; } catch { return false; } };
47
51
  const fetchRef = (git, ref) => git(["fetch", "--quiet", REMOTE, `+refs/heads/${ref}:refs/remotes/${REMOTE}/${ref}`]);
48
52
  const tipOf = (git, ref) => git(["rev-parse", `refs/remotes/${REMOTE}/${ref}`]).trim();
49
53
  const committer = (git) => {
@@ -62,7 +66,7 @@ function pickTree(git, onto, orig) {
62
66
  * Cut `branch` from the staging tip. One release in flight: any branch under the pattern prefix refuses.
63
67
  * @returns {{refused: string}|{branch, record}}
64
68
  */
65
- export async function cutSnapshot({ io, git, repo, staging, def, pattern = DEFAULT_PATTERN, id, bundle = [] }) {
69
+ export async function cutSnapshot({ io, git, repo, staging, def, pattern = DEFAULT_PATTERN, id, bundle = [], credential }) {
66
70
  const prefix = patternPrefix(pattern);
67
71
  const live = git(["ls-remote", "--heads", REMOTE, `${prefix}*`]).trim().split("\n").filter(Boolean).map((l) => l.split(/\s+/)[1]?.replace("refs/heads/", ""));
68
72
  if (live.length) return { refused: `a release branch is already in flight (${live.join(", ")}); one release per repo: finish it with forgedock release --resume <id> or delete the branch` };
@@ -71,6 +75,7 @@ export async function cutSnapshot({ io, git, repo, staging, def, pattern = DEFAU
71
75
  const branch = branchName(pattern, io.now(), prior + 1);
72
76
  fetchRef(git, staging); fetchRef(git, def);
73
77
  const snapshot = tipOf(git, staging);
78
+ const noPush = pushRefusal(credential, branch); if (noPush) return { refused: noPush };
74
79
  git(["push", "--quiet", REMOTE, `${snapshot}:refs/heads/${branch}`]);
75
80
  const issues = [...new Set(bundle.flatMap((p) => (p.closingIssuesReferences ?? []).map((i) => i.number)))].sort((a, b) => a - b);
76
81
  return { branch, record: { v: 1, id, branch, snapshot, range: { base: tipOf(git, def), head: snapshot }, bundle: bundle.map((p) => p.number), issues, picks: [] } };
@@ -103,6 +108,7 @@ export async function pickFixes(ctx, { issues = [] } = {}) {
103
108
  const { io, git, repo, staging, state } = ctx;
104
109
  const rec = state.release;
105
110
  if (!rec) return { err: "no FORGE:RELEASE record in the release state" };
111
+ const noPush = pushRefusal(ctx.fence?.lctx?.credential ?? ctx.credential, rec.branch, true); if (noPush) return { err: noPush };
106
112
  const push = (sha) => git(["push", "--quiet", REMOTE, `${sha}:refs/heads/${rec.branch}`]);
107
113
  if (rec.picks.length) { try { push(rec.picks.at(-1).sha); } catch { /* already there, or the objects are gone: the checks below decide */ } }
108
114
  fetchRef(git, staging);
@@ -156,13 +162,40 @@ export async function recut(ctx) {
156
162
  const rec = state.release;
157
163
  fetchRef(git, staging);
158
164
  const tip = tipOf(git, staging);
159
- if (tip === (rec.picks.at(-1)?.sha ?? rec.snapshot) && !rec.picks.length) return { recut: false };
160
- rec.recuts = (rec.recuts ?? 0) + 1;
161
- rec.snapshot = tip; rec.picks = []; rec.range = { ...rec.range, head: tip };
165
+ const noPush = pushRefusal(ctx.fence?.lctx?.credential ?? ctx.credential, rec.branch); if (noPush) return { recut: false, refused: noPush };
166
+ const unchanged = tip === (rec.picks.at(-1)?.sha ?? rec.snapshot) && !rec.picks.length;
167
+ let head = unchanged ? tip : null;
168
+ if (!unchanged) {
169
+ rec.recuts = (rec.recuts ?? 0) + 1;
170
+ rec.snapshot = tip; rec.picks = []; rec.range = { ...rec.range, head: tip };
171
+ head = tip;
172
+ }
173
+ const sync = ctx.def ? syncDefault(ctx, head) : null; // #5565: a p0 that landed on the default branch after the cut comes in as one main-sync pick
174
+ if (sync?.err) return { recut: false, err: sync.err };
175
+ if (sync) { head = sync.sha; rec.picks.push({ sha: sync.sha, orig: sync.orig, kind: "main-sync", merge: true }); rec.range = { ...rec.range, head }; }
176
+ if (unchanged && !sync) return { recut: false };
162
177
  ctx.save();
163
- git(["push", "--quiet", "--force", REMOTE, `${tip}:refs/heads/${rec.branch}`]);
178
+ git(["push", "--quiet", "--force", REMOTE, `${head}:refs/heads/${rec.branch}`]);
164
179
  await writeRecord(ctx);
165
- return { recut: true, snapshot: tip };
180
+ return { recut: true, snapshot: tip, ...(sync ? { mainSync: sync.orig } : {}) };
181
+ }
182
+
183
+ /** #5565: true when the default branch has commits the release head does not contain (a p0 landed after the cut); the release merge refuses then. */
184
+ export function defaultBehind({ git, def, head }) {
185
+ fetchRef(git, def);
186
+ return !isAncestor(git, `${REMOTE}/${def}`, head);
187
+ }
188
+
189
+ /** Merge the default-branch tip into `head` (plumbing, no working tree) unless it is already an ancestor. @returns {{sha, orig}|{err}|null} */
190
+ function syncDefault(ctx, head) {
191
+ const { git, def } = ctx;
192
+ fetchRef(git, def);
193
+ const orig = tipOf(git, def);
194
+ if (isAncestor(git, orig, head)) return null;
195
+ let tree;
196
+ try { tree = git(["merge-tree", "--write-tree", head, orig]).split("\n")[0].trim(); } catch { return { err: `merging ${def} into ${ctx.state.release.branch} conflicts: resolve it by hand` }; }
197
+ const sha = git(["commit-tree", tree, "-p", head, "-p", orig, "-F", "-"], { input: `Merge ${def} into ${ctx.state.release.branch} (main-sync)\n`, env: committer(git) }).trim();
198
+ return { sha, orig };
166
199
  }
167
200
 
168
201
  /**
@@ -178,13 +211,18 @@ export function checkChain({ git, record, sha, staging, exact = false }) {
178
211
  if (!record?.snapshot) return no("no FORGE:RELEASE record");
179
212
  if (!isAncestor(git, record.snapshot, stagingTip)) return no(`snapshot ${record.snapshot} is not on ${staging}`);
180
213
  if (sha !== record.snapshot && !isAncestor(git, record.snapshot, sha)) return no(`${sha} does not descend from the snapshot ${record.snapshot}`);
181
- const rows = git(["rev-list", "--reverse", "--parents", `${record.snapshot}..${sha}`]).trim().split("\n").filter(Boolean).map((l) => l.split(/\s+/));
214
+ const rows = git(["rev-list", "--reverse", "--first-parent", "--parents", `${record.snapshot}..${sha}`]).trim().split("\n").filter(Boolean).map((l) => l.split(/\s+/));
182
215
  if (rows.length > record.picks.length) return no(`${rows.length} commit(s) on the release branch, ${record.picks.length} recorded cherry-pick(s): ${rows.slice(record.picks.length).map((r) => r[0].slice(0, 12)).join(", ")} not recorded`);
183
216
  if (exact && rows.length !== record.picks.length) return no(`head is at ${rows.length} of ${record.picks.length} recorded cherry-picks`);
184
217
  let prev = record.snapshot;
185
218
  for (const [i, [c, ...parents]] of rows.entries()) {
186
219
  const pick = record.picks[i];
187
220
  if (c !== pick.sha) return no(`commit ${c.slice(0, 12)} is not the recorded pick ${pick.sha.slice(0, 12)}`);
221
+ if (pick.kind === "main-sync" && pick.merge) { // #5565: the default branch merged in after a p0 landed: parents are the previous pick and the recorded default tip
222
+ if (parents.length !== 2 || parents[0] !== prev || parents[1] !== pick.orig) return no(`commit ${c.slice(0, 12)} is not the recorded merge of ${String(pick.orig).slice(0, 12)} onto ${prev.slice(0, 12)}`);
223
+ prev = c;
224
+ continue;
225
+ }
188
226
  if (parents.length !== 1 || parents[0] !== prev) return no(`commit ${c.slice(0, 12)} is not a linear child of ${prev.slice(0, 12)}`);
189
227
  if (pick.kind && !PICK_KINDS.includes(pick.kind)) return no(`commit ${c.slice(0, 12)} has the unrecorded pick kind ${JSON.stringify(pick.kind)}`);
190
228
  if (pick.kind === "revert") { // #5567: a mechanical revert of the previous pick: same tree as before it, and it names it
@@ -214,6 +252,7 @@ export async function verifyRelease({ io, git, repo, staging, sha }) {
214
252
  }
215
253
 
216
254
  /** Delete the release branch after post-merge; a missing branch is fine. */
217
- export function cleanupSnapshot({ git, branch }) {
255
+ export function cleanupSnapshot({ git, branch, credential }) {
256
+ const noPush = pushRefusal(credential, branch); if (noPush) return { deleted: false, why: noPush };
218
257
  try { git(["push", "--quiet", REMOTE, "--delete", branch]); return { deleted: true }; } catch (e) { return { deleted: false, why: String(e.message).split("\n")[0] }; }
219
258
  }
@@ -6,7 +6,7 @@ import { execFileSync } from "node:child_process";
6
6
  import { writeFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { tmpDir } from "../tests/_tmp.mjs";
9
- import { cutSnapshot, pickFixes, revertLast, recut, checkChain, verifyRelease, cleanupSnapshot, parseRecord, withRecord, branchName, patternPrefix } from "./release-snapshot.mjs";
9
+ import { cutSnapshot, pickFixes, revertLast, recut, checkChain, verifyRelease, defaultBehind, cleanupSnapshot, parseRecord, withRecord, branchName, patternPrefix } from "./release-snapshot.mjs";
10
10
 
11
11
  const ENV = { GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" };
12
12
  const mk = (cwd) => (args, { env, input } = {}) => execFileSync("git", args, { cwd, encoding: "utf8", input, env: { ...process.env, ...ENV, ...env }, stdio: ["pipe", "pipe", "pipe"] });
@@ -183,6 +183,34 @@ describe("cherry-picks and the verifier (#5276)", () => {
183
183
  assert.equal(parseRecord(s.w.body).snapshot, tip);
184
184
  });
185
185
 
186
+ it("#5565: a p0 landed on the default branch after the cut is recut in as exactly one main-sync pick; the chain verifies", async () => {
187
+ const { s, c } = await blockerWorld();
188
+ await pickFixes(s.ctx);
189
+ s.git(["checkout", "-q", "main"]);
190
+ writeFileSync(join(s.work, "p0.txt"), "p0\n"); s.git(["add", "."]); s.git(["commit", "-qm", "p0 fix"]); s.git(["push", "-q", "origin", "main"]);
191
+ const mainTip = s.git(["rev-parse", "HEAD"]).trim();
192
+ s.git(["checkout", "-q", "staging"]);
193
+ const head0 = s.git(["ls-remote", "origin", `refs/heads/${c.branch}`]).split("\t")[0];
194
+ assert.equal(defaultBehind({ git: s.git, def: "main", head: head0 }), true);
195
+ const out = await recut(s.ctx);
196
+ assert.equal(out.recut, true); assert.equal(out.mainSync, mainTip);
197
+ const rec = s.ctx.state.release;
198
+ assert.deepEqual(rec.picks.map((p) => p.kind), ["main-sync"]);
199
+ const head = s.git(["ls-remote", "origin", `refs/heads/${c.branch}`]).split("\t")[0];
200
+ assert.equal(head, rec.picks[0].sha);
201
+ assert.equal(defaultBehind({ git: s.git, def: "main", head }), false);
202
+ assert.deepEqual(checkChain({ git: s.git, record: rec, sha: head, staging: "staging", exact: true }), { ok: true, picks: 1 });
203
+ assert.equal((await recut(s.ctx)).recut, true); // idempotent: still exactly one main-sync pick
204
+ assert.equal(s.ctx.state.release.picks.length, 1);
205
+ });
206
+
207
+ it("#5565: with nothing landed on the default branch recut adds no main-sync pick", async () => {
208
+ const s = await setup();
209
+ await cut(s);
210
+ assert.deepEqual(await recut(s.ctx), { recut: false });
211
+ assert.deepEqual(s.ctx.state.release.picks, []);
212
+ });
213
+
186
214
  it("R10: verifyRelease reads the record from the PR that contains the sha, then checks the chain", async () => {
187
215
  const { s } = await blockerWorld();
188
216
  await pickFixes(s.ctx);
@@ -205,3 +233,17 @@ describe("cherry-picks and the verifier (#5276)", () => {
205
233
  assert.equal(parseRecord(twice).a, 2);
206
234
  });
207
235
  });
236
+
237
+ describe("lane role may not push release branches (#5561, I12)", () => {
238
+ it("cutSnapshot, recut and cleanupSnapshot refuse a lane credential naming role and action; pickFixes allows only the fix push", async () => {
239
+ const s = await setup();
240
+ const refused = await cutSnapshot({ io: s.io, git: s.git, repo: "o/r", staging: "staging", def: "main", id: "r1", credential: "lane" });
241
+ assert.match(refused.refused, /role lane may not push on release\//);
242
+ const c = await cut(s);
243
+ s.ctx.credential = "lane";
244
+ s.commit("n.txt", "n\n", "feat: n");
245
+ assert.match((await recut(s.ctx)).refused, /role lane may not push/);
246
+ assert.match(cleanupSnapshot({ git: s.git, branch: c.branch, credential: "lane" }).why, /role lane may not push/);
247
+ assert.equal(cleanupSnapshot({ git: s.git, branch: c.branch }).deleted, true);
248
+ });
249
+ });
@@ -0,0 +1,164 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5571: `forgedock release start|go`. The managed runner above the planner (#5559), train lane (#5570) and release run: it drives the
4
+ // plan's waves in order (all trains, then the release wave), gates the release CUT on the last train being WAVE_DONE, applies the
5
+ // feature flag policy, keeps the milestone lane explicit, soaks the release wave at full strength and resumes from the ledger.
6
+ import { fenced } from "./release-fence.mjs";
7
+ import { planFromCli, approvalOf } from "./release-plan.mjs";
8
+
9
+ export const WAVE_STATES = ["PENDING", "BUILT", "CUT", "LIVE", "WAVE_DONE"];
10
+ export const FLAG_POLICIES = ["require", "warn", "off"];
11
+ export const MERGE_DECISION = (hash) => `<!-- FORGE:DECISION merge ${hash} -->`;
12
+ export const PLAN_DECISION = (hash) => `<!-- FORGE:DECISION plan ${hash} -->`;
13
+ const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
14
+ const isTrain = (w) => w.lane === "train";
15
+
16
+ /** Waves in run order: trains (plan order) strictly before the release wave. */
17
+ export const orderWaves = (plan) => [...plan.waves.filter(isTrain), ...plan.waves.filter((w) => !isTrain(w))];
18
+
19
+ /** The recorded state of wave `id` (`PENDING` when it has none). */
20
+ export const waveState = (state, id) => state?.waves?.[id]?.state ?? "PENDING";
21
+
22
+ /** A wave is WAVE_DONE only when verified live, merged and merged back (validated); anything less stays LIVE. */
23
+ export const waveSettled = (r) => !!(r?.verified && r.merged && r.mergedBack);
24
+
25
+ /** CUT of a release wave is refused until every train of the plan is WAVE_DONE; a train CUT only needs the trains before it. Building is never gated. */
26
+ export function cutAllowed(state, plan, wave) {
27
+ const trains = plan.waves.filter(isTrain);
28
+ const before = isTrain(wave) ? trains.slice(0, trains.findIndex((t) => t.id === wave.id)) : trains;
29
+ const open = before.filter((t) => waveState(state, t.id) !== "WAVE_DONE");
30
+ return open.length ? { ok: false, reason: `CUT of ${wave.id} refused: ${open.map((t) => t.id).join(", ")} not WAVE_DONE` } : { ok: true };
31
+ }
32
+
33
+ /**
34
+ * `features.flag_policy` (a lane's own `flag_policy` wins) applied to a feature wave: `info` = {feature, added: new rollout keys, offKeys: new default-off keys}.
35
+ * A feature wave that adds no rollout key is `missing`: require refuses, warn prints, off is silent. Default-off keys are returned as `keepOff`: never activated here.
36
+ */
37
+ export function flagPolicyOutcome(policy, lane, info) {
38
+ const mode = policy?.lanes?.[lane]?.flag_policy ?? policy?.features?.flag_policy ?? "off";
39
+ if (!info?.feature) return { mode, action: "none", keepOff: [] };
40
+ const missing = !(info.added ?? []).length;
41
+ return { mode, action: !missing || mode === "off" ? "none" : mode === "require" ? "error" : "warn", missing, keepOff: [...(info.offKeys ?? [])].sort() };
42
+ }
43
+
44
+ /** Activation of a default-off key is its own recorded step, never part of a wave deploy. */
45
+ export function recordActivation(state, key, actor, at) {
46
+ (state.activations ??= []).push({ key, actor, at });
47
+ return state;
48
+ }
49
+
50
+ /** The milestone lane: one release wave of every planned issue, base = the milestone branch, pipeline `full`. Explicit `--milestone` only. */
51
+ export function milestonePlan(plan, slug, pattern = "milestone/{slug}") {
52
+ if (!slug) throw new Error("release: the milestone lane needs --milestone <slug> (it is never auto-planned)");
53
+ const issues = plan.waves.flatMap((w) => w.issues), units = [...new Set(plan.waves.flatMap((w) => w.units))].sort();
54
+ return { ...plan, waves: issues.length ? [{ id: "release", lane: "release", issues, units, base: pattern.replace("{slug}", slug), pipeline: "full" }] : [] };
55
+ }
56
+
57
+ /**
58
+ * Run the plan. `ctx`: {io, plan, approval, state, save, managed, wave: "train"|"release"|"all", policy, fence?, runners: {build?, train, release, verify, mergeback, rollouts?}}.
59
+ * Approval is the only input: nothing here needs a hand-posted status. @returns {Promise<{status: "done"|"unmanaged"|"awaiting-approval"|"stopped"|"refused", wave?, reason?, ran: string[]}>}
60
+ */
61
+ export async function startRelease(ctx) {
62
+ const { io, plan, state, runners, policy } = ctx, ran = [], say = (l) => io.print(l);
63
+ if (!ctx.managed) { say("release start: unmanaged repo, nothing written (release.managed is off)"); return { status: "unmanaged", ran }; }
64
+ if (ctx.approval?.state !== "approved") { say(`release start: plan ${plan.plan_hash.slice(0, 12)} is not approved (${ctx.approval?.state ?? "none"}); run: forgedock release go <id> --plan`); return { status: "awaiting-approval", ran }; }
65
+ const only = ctx.wave ?? "all", waves = orderWaves(plan), save = async () => ctx.save?.();
66
+ state.waves ??= {};
67
+ const rel = waves.find((w) => !isTrain(w));
68
+ if (rel && runners.build && only !== "train" && waveState(state, rel.id) === "PENDING") { // pipelining: the release wave builds while trains deploy; never CUT here
69
+ const b = await runners.build(rel);
70
+ if (b?.ok === false) return { status: "stopped", wave: rel.id, reason: b.reason ?? "build failed", ran };
71
+ state.waves[rel.id] = { ...state.waves[rel.id], state: "BUILT" }; await save(); ran.push(`build:${rel.id}`);
72
+ }
73
+ for (const w of waves) {
74
+ if (only !== "all" && (only === "train") !== isTrain(w)) continue;
75
+ if (waveState(state, w.id) === "WAVE_DONE") { say(`wave ${w.id}: already WAVE_DONE, skipped`); continue; }
76
+ const gate = cutAllowed(state, plan, w);
77
+ if (!gate.ok) { say(`release start: ${gate.reason}`); return { status: "refused", wave: w.id, reason: gate.reason, ran }; }
78
+ const lane = isTrain(w) ? "train" : "release", fp = flagPolicyOutcome(policy, lane, await runners.rollouts?.(w, plan));
79
+ if (fp.action === "error") return { status: "refused", wave: w.id, reason: `features.flag_policy=require: feature wave ${w.id} adds no rollout key`, ran };
80
+ if (fp.action === "warn") say(`WARN: feature wave ${w.id} adds no rollout key (features.flag_policy=warn)`);
81
+ if (fp.keepOff.length) { // I25: the key stays off at deploy; the activation_missing line stays until `release go <id> --activate <key>` records it
82
+ const pending = fp.keepOff.filter((k) => !(state.activations ?? []).some((a) => a.key === k));
83
+ (state.waves[w.id] ??= {}).keepOff = fp.keepOff;
84
+ if (pending.length) say(`activation_missing: default-off ${pending.join(", ")} stays off at deploy; record activation with: forgedock release go ${state.id} --activate <key>`);
85
+ }
86
+ const fl = waveState(state, w.id) === "LIVE" || !ctx.takeFence ? { fence: ctx.fence } : await ctx.takeFence(state); // a fresh lease per wave: the train takes its own epoch inside
87
+ if (fl.refused) return { status: "refused", wave: w.id, reason: fl.refused, ran };
88
+ const f = waveState(state, w.id) === "LIVE" ? { value: { status: "live" } } : await fenced(fl.fence, { action: "wave", key: `wave:${plan.plan_hash}:${w.id}` }, async () => {
89
+ state.waves[w.id] = { ...state.waves[w.id], state: "CUT" }; await save();
90
+ const r = isTrain(w) ? await runners.train(w) : await runners.release(w, { soak: "full", pipeline: w.pipeline ?? "full", base: w.base });
91
+ return r;
92
+ });
93
+ if (f.refused) return { status: "refused", wave: w.id, reason: f.refused, ran };
94
+ const r = f.value;
95
+ if (!["live", "done"].includes(r?.status)) { say(`wave ${w.id}: ${r?.status ?? "no result"}${r?.reason ? `: ${r.reason}` : ""}`); return { status: "stopped", wave: w.id, reason: r?.reason ?? r?.status, ran }; }
96
+ state.waves[w.id] = { ...state.waves[w.id], state: "LIVE" }; await save();
97
+ const done = { verified: (await runners.verify(w, r))?.verified, merged: r.status === "done" || r.merged !== false, mergedBack: (await runners.mergeback(w, r))?.validated };
98
+ if (!waveSettled(done)) { const why = !done.verified ? "not verified live" : !done.mergedBack ? "merge-back not validated" : "not merged"; say(`wave ${w.id}: LIVE but ${why}`); return { status: "stopped", wave: w.id, reason: why, ran }; }
99
+ state.waves[w.id] = { ...state.waves[w.id], state: "WAVE_DONE" }; await save(); ran.push(w.id); say(`wave ${w.id}: WAVE_DONE`);
100
+ }
101
+ return { status: "done", ran };
102
+ }
103
+
104
+ /** Plan record of `ref` (a release id or a plan hash) from the ledger. */
105
+ async function loadPlan(ref, { ledger }) {
106
+ const byId = await ledger.read(ref);
107
+ if (byId?.state?.plan) return { id: ref, ...byId };
108
+ for (const id of (await ledger.list?.()) ?? []) { const l = await ledger.read(id); if (l?.state?.plan?.plan_hash?.startsWith(ref)) return { id, ...l }; }
109
+ return null;
110
+ }
111
+
112
+ /**
113
+ * `forgedock release start [--plan <id|hash>] [--approve] [--wave train|release|all] [--milestone <slug>] [--lane milestone]`.
114
+ * Without `--plan` a fresh plan is made (and recorded when managed). `deps`: {io, policy, policySha, managed, newId, ledger: {read, write, list}, decisions, post, runners, fence, actor, ...}.
115
+ * @returns the exit code.
116
+ */
117
+ export async function startFromCli(argv, deps) {
118
+ const { io, managed } = deps, ms = flagOf(argv, "--milestone"), wave = flagOf(argv, "--wave") ?? "all";
119
+ if (!["train", "release", "all"].includes(wave)) throw new Error("release start: --wave must be train|release|all");
120
+ if (flagOf(argv, "--lane") === "milestone" && !ms) throw new Error("release start: the milestone lane needs --milestone <slug> (it is never auto-planned)");
121
+ if (!managed) { io.print("release start: unmanaged repo, nothing written (release.managed is off)"); return 0; }
122
+ let rec, ref = flagOf(argv, "--plan");
123
+ if (ref) rec = await loadPlan(ref, deps);
124
+ else {
125
+ await planFromCli([...(ms ? ["--milestone", ms] : []), ...(flagOf(argv, "--repo") ? ["--repo", flagOf(argv, "--repo")] : [])], {
126
+ ...deps, managed: true, ledger: async ({ id, plan }) => { rec = { id, state: { v: 1, id, kind: "plan", status: "planned", plan }, head: null }; await deps.ledger.create(id, rec.state); rec = await deps.ledger.read(id) ?? rec; rec.id = id; },
127
+ });
128
+ }
129
+ if (!rec?.state?.plan) { io.print(`release start: no plan ${ref ?? ""} found`); return 1; }
130
+ let plan = rec.state.plan;
131
+ if (ms) plan = milestonePlan(plan, ms, deps.policy?.branches?.feature_pattern);
132
+ const decisions = async () => approvalOf(plan, await deps.decisions(), deps.policy);
133
+ let approval = await decisions();
134
+ if (argv.includes("--approve") && approval.state !== "approved") { await deps.post(PLAN_DECISION(plan.plan_hash)); approval = await decisions(); }
135
+ const state = rec.state;
136
+ const save = async () => { const w = await deps.ledger.write(rec.id, state, rec.head); if (w?.ok) rec.head = w.sha; };
137
+ const r = await startRelease({ io, plan, approval, state, save, managed, wave, policy: deps.policy, fence: deps.fence, takeFence: deps.takeFence, runners: deps.runners });
138
+ io.print(`release start ${rec.id}: ${r.status}${r.reason ? `: ${r.reason}` : ""}`);
139
+ return r.status === "done" || r.status === "unmanaged" || r.status === "awaiting-approval" ? 0 : 1;
140
+ }
141
+
142
+ /** `forgedock release go <id> [--plan|--merge|--activate <key>]`: writes the typed approval comment (`--plan` default) bound to the plan hash. */
143
+ export async function goFromCli(argv, { io, ledger, post, managed, actor, now = () => new Date().toISOString() }) {
144
+ const id = argv[0];
145
+ if (!id || id.startsWith("--")) throw new Error("release go needs a release id; usage: forgedock release go <id> [--plan|--merge]");
146
+ if (!managed) { io.print("release go: unmanaged repo, nothing written (release.managed is off)"); return 0; }
147
+ const rec = await ledger.read(id);
148
+ if (!rec?.state?.plan) { io.print(`release go: no plan record for ${id}`); return 1; }
149
+ const act = flagOf(argv, "--activate");
150
+ if (act) { // the separate recorded activation step of a default-off rollout key (I25)
151
+ if (!(rec.state.waves && Object.values(rec.state.waves).some((w) => (w.keepOff ?? []).includes(act)))) { io.print(`release go: ${act} is not a default-off key of a wave of ${id}`); return 1; }
152
+ recordActivation(rec.state, act, actor ?? null, now());
153
+ const w = await ledger.write(id, rec.state, rec.head);
154
+ if (!w?.ok) { io.print(`release go: could not record activation (ledger moved); retry`); return 1; }
155
+ await post(`<!-- FORGE:DECISION activate ${act} -->`);
156
+ io.print(`release go ${id}: activation of ${act} recorded`);
157
+ return 0;
158
+ }
159
+ const hash = rec.state.plan.plan_hash, merge = argv.includes("--merge");
160
+ await post(merge ? MERGE_DECISION(hash) : PLAN_DECISION(hash));
161
+ io.print(`release go ${id}: ${merge ? "merge" : "plan"} approval recorded for ${hash.slice(0, 12)}`);
162
+ return 0;
163
+ }
164
+