forgedock 1.59.2 → 1.60.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) 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 +19 -6
  7. package/bin/lean/conformance.test.mjs +37 -3
  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 +144 -21
  22. package/bin/lean/lean.test.mjs +180 -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 +67 -3
  32. package/bin/lean/preflight.test.mjs +37 -1
  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 +110 -0
  80. package/bin/lean/validate-catalog.test.mjs +55 -0
  81. package/bin/pool/agent.mjs +12 -1
  82. package/bin/pool/lane-tools.mjs +146 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/router.mjs +3 -1
  85. package/bin/pool/warm.mjs +14 -3
  86. package/docs/CONFIG.md +225 -1
  87. package/docs/ISSUE-WATCH.md +1 -0
  88. package/docs/design/visual-gate.md +10 -0
  89. package/docs/eval/adversarial-bench.md +1 -0
  90. package/package.json +1 -1
  91. package/pool/README.md +2 -0
  92. package/scripts/acceptance-red-green.sh +5 -2
  93. package/scripts/acceptance-red-green.test.sh +11 -0
  94. package/scripts/bench-adversarial.mjs +4 -0
  95. package/scripts/bench-lightlane.mjs +2 -1
  96. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  97. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -0,0 +1,277 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Rollback ladder (#5563, epic #5549 Phase 3, I8/I10/I26, Q8): `forgedock release rollback <id> [--to flag|unit|full] --reason "..."`.
5
+ * The engine picks the lowest sufficient rung and records why: flag (kill the wave's rollout flags), unit (the service pipeline's
6
+ * rollback action with the recorded previous per-unit digests), full (the standalone rollback workflow), stop (hold, page, incident).
7
+ * Every dispatch is `fenced()` with `forge_epoch` and built by `buildDispatchArgs` (I26). After a unit or full rung the rollback
8
+ * result record must show matching per-service (and per-host) counts; a mismatch, an unreadable record or a failed health
9
+ * command escalates to stop. Rollback to code that predates a destructive migration is refused (I8). This module never talks to
10
+ * a database: the destructive-migration patterns live in release-config.mjs and are only matched against migration file text.
11
+ * Afterwards: a revert PR (default == live, I10), the wave's issues reopened, one incident issue, later waves held.
12
+ * Rationale: devdocs/decisions/5563-release-rollback.md.
13
+ */
14
+ import { mkdtempSync, rmSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ import { fenced } from "./release-fence.mjs";
18
+ import { buildDispatchArgs, runControl } from "./release-control.mjs";
19
+ import { acquireLease } from "./release-ledger.mjs";
20
+ import { releaseIssues } from "./release-verify.mjs";
21
+ import { DESTRUCTIVE_SQL, MIGRATION_PATHS } from "./release-config.mjs";
22
+
23
+ export const RUNGS = ["flag", "unit", "full", "stop"];
24
+ export const ROLLBACK_TRIGGERS = ["smoke", "health", "livecheck", "sli", "crashloop", "human"];
25
+ export const INCIDENT_MARKER = "FORGE:INCIDENT";
26
+ export const ROLLBACK_BOUNDS = { pollMs: 10_000, startPolls: 6, donePolls: 180 };
27
+ const FLAG_OK = ["smoke", "health", "sli", "crashloop", "human"]; // a wrong deploy (livecheck) is not fixed by a flag
28
+ const json = (s) => { try { return JSON.parse(String(s || "null")); } catch { return null; } };
29
+ const short = (s) => String(s ?? "").slice(0, 8);
30
+ const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
31
+
32
+ /** Trigger class of a recorded reason (release-verify / release-deploy wording). */
33
+ export function classifyTrigger(reason) {
34
+ const r = String(reason ?? "");
35
+ if (/SLI/i.test(r)) return "sli";
36
+ if (/crash/i.test(r)) return "crashloop";
37
+ if (/LIVE_CHECK|live sha|digest/i.test(r)) return "livecheck";
38
+ if (/health/i.test(r)) return "health";
39
+ if (/smoke|edge|verify/i.test(r)) return "smoke";
40
+ return "human";
41
+ }
42
+
43
+ /**
44
+ * The lowest sufficient rung at or after `from` (`--to` or an escalation floor), honouring `rollback.ladder`.
45
+ * @returns {{rung: string, why: string}}
46
+ */
47
+ export function chooseRung({ trigger, from = "flag", rb = {}, target = null }) {
48
+ const ladder = (rb.ladder?.length ? rb.ladder : RUNGS).filter((r) => RUNGS.includes(r));
49
+ const ok = {
50
+ flag: () => (!(rb.flags ?? []).some((f) => f?.kill_command) ? "no rollout flag has a kill_command" : FLAG_OK.includes(trigger) ? null : `a ${trigger} trigger is not fixed by a flag`),
51
+ unit: () => (!rb.unit_workflow ? "rollback.unit_workflow is not set" : Object.keys(target?.images ?? {}).length ? null : "no recorded previous per-unit digests"),
52
+ full: () => (rb.full_workflow ? null : "rollback.full_workflow is not set"),
53
+ stop: () => null,
54
+ };
55
+ const skipped = [];
56
+ for (const rung of RUNGS.slice(RUNGS.indexOf(from))) {
57
+ if (!ladder.includes(rung) && rung !== "stop") { skipped.push(`${rung}: not in rollback.ladder`); continue; }
58
+ const why = ok[rung]();
59
+ if (!why) return { rung, why: `${trigger}: lowest sufficient rung is ${rung}${skipped.length ? ` (skipped ${skipped.join("; ")})` : ""}` };
60
+ skipped.push(`${rung}: ${why}`);
61
+ }
62
+ return { rung: "stop", why: `${trigger}: no rung sufficient (${skipped.join("; ")})` };
63
+ }
64
+
65
+ /**
66
+ * I8: destructive migrations between the rollback target and the live sha, read from migration file text only.
67
+ * @returns {{ok: true} | {refused: string}} unreadable git history refuses (fail closed)
68
+ */
69
+ export function refuseAcross({ io, target, live, paths = MIGRATION_PATHS }) {
70
+ let files;
71
+ try { files = String(io.git(["diff", "--name-only", "--diff-filter=AM", `${target}..${live}`, "--", ...paths])).split("\n").filter(Boolean); }
72
+ catch (e) { return { refused: `cannot list migrations between ${short(target)} and ${short(live)}: ${String(e?.message ?? e).split("\n")[0]}` }; }
73
+ for (const f of files) {
74
+ let text;
75
+ try { text = String(io.git(["show", `${live}:${f}`])); } catch (e) { return { refused: `cannot read migration ${f}: ${String(e?.message ?? e).split("\n")[0]}` }; }
76
+ if (DESTRUCTIVE_SQL.test(text)) return { refused: `rollback to ${short(target)} crosses destructive migration ${f} (I8); roll forward instead` };
77
+ }
78
+ return { ok: true };
79
+ }
80
+
81
+ /** Per-service (and per-host) counts of the rollback result record against the recorded previous set (Q8). @returns {string|null} the mismatch */
82
+ export function checkCounts(record, target) {
83
+ const units = record?.units;
84
+ if (!units || typeof units !== "object" || !Object.keys(units).length) return "rollback result record is unreadable or empty";
85
+ const images = target?.images ?? {};
86
+ const missing = Object.keys(images).filter((u) => !units[u]);
87
+ if (missing.length) return `result record has no entry for ${missing.join(", ")}`;
88
+ for (const [u, x] of Object.entries(units)) {
89
+ if (images[u] && x?.digest && x.digest !== images[u]) return `${u}: rolled to ${x.digest}, recorded previous digest is ${images[u]}`;
90
+ for (const [h, c] of Object.entries(x?.hosts ?? { all: x })) {
91
+ if (!Number.isInteger(c?.expected) || !Number.isInteger(c?.rolled)) return `${u}@${h}: counts missing`;
92
+ if (c.rolled !== c.expected) return `${u}@${h}: ${c.rolled} of ${c.expected} rolled back`;
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ async function poll(io, polls, ms, fn) {
99
+ for (let i = 0; i < polls; i++) { const v = await fn(); if (v) return v; if (i < polls - 1) await io.sleep(ms); }
100
+ return null;
101
+ }
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] ??= {};
106
+ const list = async () => json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--json", "databaseId,status,conclusion", "--limit", "10"])) ?? [];
107
+ 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}`));
109
+ if (!had) {
110
+ const key = `${ctx.fence?.lease?.release ?? ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:rollback:${rung}`;
111
+ 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
+ if (f.refused) return { err: `dispatch ${f.refused}` };
113
+ rec.dispatched = true; ctx.save();
114
+ }
115
+ const newer = async () => (await list()).find((r) => r.databaseId > rec.baseId) ?? null;
116
+ 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)` };
118
+ const done = await poll(io, b.donePolls, b.pollMs, async () => { const r = await newer(); return r?.status === "completed" ? r : null; });
119
+ if (!done) return { err: `${workflow} run ${run.databaseId} did not finish` };
120
+ return done.conclusion === "success" ? { run: done } : { err: `${workflow} run ${done.databaseId} concluded ${done.conclusion}` };
121
+ }
122
+
123
+ async function healthy(io, rb) {
124
+ if (!rb.health_command) return { ok: true, note: "health: unchecked (rollback.health_command unset)" };
125
+ const r = await io.rehearse(rb.health_command, { timeout: 120_000 });
126
+ return r?.ok ? { ok: true, note: "health: ok" } : { ok: false, why: `health command failed: ${String(r?.output ?? "").trim().slice(-200)}` };
127
+ }
128
+
129
+ /** Execute one rung. @returns {{ok: true, note} | {fail: string}} */
130
+ async function runRung(ctx, rung, rb, b, reason) {
131
+ const { io } = ctx, d = ctx.state.deploy, target = d.target;
132
+ if (rung === "flag") {
133
+ for (const f of rb.flags ?? []) {
134
+ if (!f?.kill_command) continue;
135
+ const r = await fenced(ctx.fence, { action: "flag-kill", key: `${ctx.fence?.lease?.release ?? ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:rollback:flag:${f.flag}` }, () => io.rehearse(f.kill_command, { timeout: 120_000 }));
136
+ if (r.refused) return { fail: `flag ${f.flag}: ${r.refused}` };
137
+ if (!r.value?.ok) return { fail: `flag ${f.flag}: kill command failed` };
138
+ }
139
+ const h = await healthy(io, rb);
140
+ return h.ok ? { ok: true, note: h.note } : { fail: h.why };
141
+ }
142
+ const workflow = rung === "unit" ? rb.unit_workflow : rb.full_workflow;
143
+ const inputs = rung === "unit"
144
+ ? { action: rb.unit_action ?? "rollback", sha: target.sha, digests: JSON.stringify(target.images ?? {}) }
145
+ : { sha: target.sha, reason: String(reason).slice(0, 200) };
146
+ const r = await dispatchRung(ctx, rung, workflow, inputs, b);
147
+ if (r.err) return { fail: r.err };
148
+ const rr = rb.result_command ? await io.rehearse(rb.result_command, { timeout: 120_000 }) : null;
149
+ const bad = checkCounts(rr?.ok ? json(rr.output) : null, target);
150
+ if (bad) return { fail: `counts check: ${bad}` };
151
+ const h = await healthy(io, rb);
152
+ return h.ok ? { ok: true, note: `counts match the recorded set; ${h.note}` } : { fail: h.why };
153
+ }
154
+
155
+ const ensureIssue = async (ctx, title, body, marker) => { // exactly one issue per marker, any state
156
+ const { io, repo } = ctx;
157
+ const found = json(await io.gh(["issue", "list", "--repo", repo, "--state", "all", "--search", `"${marker}" in:body`, "--json", "number,body", "--limit", "20"])) ?? [];
158
+ const hit = found.find((i) => String(i.body ?? "").includes(marker));
159
+ if (hit) return { number: hit.number, created: false };
160
+ const url = String(await io.gh(["issue", "create", "--repo", repo, "--title", title, "--body", `${body}\n\n<!-- ${marker} -->`])).trim();
161
+ return { number: Number(/\/issues\/(\d+)/.exec(url)?.[1]) || url, created: true };
162
+ };
163
+
164
+ /** Revert PR to the default branch (I10), built in a throwaway worktree so the caller's checkout is never touched. */
165
+ async function revertPr(ctx, reason) {
166
+ const { io, repo, def } = ctx, sha = ctx.state.deploy.merge, branch = `rollback/${ctx.state.id}`;
167
+ const open = json(await io.gh(["pr", "list", "--repo", repo, "--head", branch, "--state", "open", "--json", "number,url"])) ?? [];
168
+ if (open[0]) return { pr: open[0].number, reused: true };
169
+ const dir = mkdtempSync(join(ctx.tmp ?? tmpdir(), "forge-rollback-"));
170
+ const g = (...a) => io.git(["-C", dir, ...a]);
171
+ try {
172
+ io.git(["fetch", "origin", def]);
173
+ io.git(["worktree", "add", "--detach", dir, `origin/${def}`]);
174
+ const parents = String(g("rev-list", "--parents", "-n", "1", sha)).trim().split(/\s+/).length - 1;
175
+ g("checkout", "-b", branch);
176
+ g("revert", "--no-edit", ...(parents > 1 ? ["-m", "1"] : []), sha);
177
+ const f = await fenced(ctx.fence, { action: "revert-pr", key: `${ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:rollback:revert` }, () => { g("push", "origin", branch); });
178
+ if (f.refused) return { err: f.refused };
179
+ } catch (e) { return { err: `revert PR not created: ${String(e?.message ?? e).split("\n")[0]}` }; }
180
+ finally { try { io.git(["worktree", "remove", "--force", dir]); } catch { rmSync(dir, { recursive: true, force: true }); } }
181
+ const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `Revert release ${ctx.state.id} (rollback)`, "--body", `Rollback of ${short(sha)} so ${def} matches live (I10).\n\nCause: ${reason}`])).trim();
182
+ return { pr: Number(/\/pull\/(\d+)/.exec(url)?.[1]) || url, reused: false };
183
+ }
184
+
185
+ async function reopenIssues(ctx, reason) {
186
+ const { io, repo } = ctx, out = [];
187
+ for (const n of releaseIssues(ctx.state)) {
188
+ const info = json(await io.gh(["issue", "view", String(n), "--repo", repo, "--json", "state"]));
189
+ if (String(info?.state).toUpperCase() !== "CLOSED") continue;
190
+ const f = await fenced(ctx.fence, { action: "reopen", key: `${ctx.state.id}:${ctx.fence?.lease?.epoch ?? 0}:rollback:reopen:${n}` }, () => io.gh(["issue", "reopen", String(n), "--repo", repo, "--comment", `Reopened: release ${ctx.state.id} was rolled back (${reason}).`]));
191
+ if (!f.refused) out.push(n);
192
+ }
193
+ return out;
194
+ }
195
+
196
+ async function page(ctx, webhook, text) {
197
+ if (!webhook) return "no events.webhook_url";
198
+ try { const r = await (ctx.io.post ?? ((u, body) => fetch(u, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })))(webhook, { text }); return r?.ok === false ? `webhook answered ${r.status}` : "paged"; }
199
+ catch (e) { return `page failed: ${String(e?.message ?? e).split("\n")[0]}`; }
200
+ }
201
+
202
+ /**
203
+ * Run the ladder for `ctx.state` (a deployed release). `ctx`: {io, repo, def, state, save, fence?, policy, actor, host, config?}.
204
+ * `args`: {reason, to?, trigger?, later?: [release ids to hold]}. State in `state.rollbackRun`; reruns skip finished post-steps.
205
+ * @returns {Promise<{ok: boolean, rung: string, why: string, history: object[], refused?: string, post: object}>}
206
+ */
207
+ export async function runRollback(ctx, { reason, to = "flag", trigger = null, later = [] }) {
208
+ const { io, state } = ctx, rb = ctx.policy?.rollback ?? {}, b = { ...ROLLBACK_BOUNDS, ...(ctx.config?.rollbackBounds ?? {}) };
209
+ const run = (state.rollbackRun ??= { history: [], post: {} });
210
+ const d = state.deploy;
211
+ if (!d?.target?.sha || !d.merge) return { ok: false, rung: "none", why: "no recorded rollback target (I9); nothing to roll back", history: run.history, refused: "no recorded rollback target", post: run.post };
212
+ const trig = trigger ?? classifyTrigger(reason);
213
+ if (rb.triggers?.length && trig !== "human" && !rb.triggers.includes(trig)) return { ok: false, rung: "none", why: `trigger ${trig} is not in rollback.triggers`, history: run.history, refused: `trigger ${trig} is not enabled`, post: run.post };
214
+ run.reason = reason; run.trigger = trig; ctx.save();
215
+ const across = refuseAcross({ io, target: d.target.sha, live: d.merge });
216
+ let from = to, refused = null, rung, why, note = "";
217
+ for (;;) {
218
+ ({ rung, why } = chooseRung({ trigger: trig, from, rb, target: d.target }));
219
+ if (across.refused && (rung === "unit" || rung === "full")) { refused = across.refused; run.history.push({ rung, why: `refused: ${across.refused}` }); from = "stop"; continue; }
220
+ run.rung = rung; run.why = why; ctx.save();
221
+ if (rung === "stop") break;
222
+ const r = await runRung(ctx, rung, rb, b, reason);
223
+ run.history.push({ rung, why, result: r.ok ? r.note : r.fail });
224
+ if (r.ok) { note = r.note; break; }
225
+ from = rung === "flag" ? "unit" : "stop"; // a failed flag kill tries code; a failed unit/full or counts mismatch stops (Q8)
226
+ }
227
+ const ok = rung !== "stop";
228
+ const post = run.post;
229
+ if (rung === "unit" || rung === "full") { if (rb.open_revert_pr !== false) post.revert ??= await revertPr(ctx, reason); }
230
+ if (ok) post.reopened ??= await reopenIssues(ctx, reason);
231
+ 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}`));
232
+ post.incident = inc;
233
+ if (rung === "stop") post.paged ??= await page(ctx, ctx.policy?.events?.webhook_url, `Release ${state.id} rollback stopped at rung stop: ${reason}. Incident #${inc.number}.`);
234
+ post.held ??= [];
235
+ for (const id of io.api ? later.filter((x) => x !== state.id && !post.held.includes(x)) : []) { // later waves are held through the audited control path
236
+ const h = await runControl("hold", [id, "--reason", `release ${state.id} rolled back: ${reason}`], { io, repo: ctx.repo, policy: ctx.policy, actor: ctx.actor, host: ctx.host, now: io.now?.() });
237
+ if (h.ok) post.held.push(id);
238
+ }
239
+ run.done = true; ctx.save();
240
+ return { ok, rung, why, history: run.history, ...(refused ? { refused } : {}), post };
241
+ }
242
+
243
+ /** The lease that fences the rollback's effects (own epoch, `forge_epoch` on every dispatch); unmanaged (no `io.api`): no fence. */
244
+ export async function takeFence(ctx, holder, ttlS = 300) {
245
+ if (!ctx.io.api) return { fence: null };
246
+ const lctx = { io: ctx.io, repo: ctx.repo, credential: "driver" };
247
+ const l = await acquireLease(lctx, { holder, release: ctx.state.id, issue: ctx.state.steps?.["release-pr"]?.result?.pr, ttlS, now: ctx.io.now() });
248
+ if (!l.ok) return { refused: l.refused ?? "lease lost the race" };
249
+ const record = async (rec) => { const a = (ctx.state.intents ??= []); const i = a.findIndex((x) => x.key === rec.key); if (i < 0) a.push(rec); else a[i] = rec; ctx.save(); };
250
+ return { fence: { lctx, lease: l.lease, record, now: () => new Date(ctx.io.now()).toISOString() } };
251
+ }
252
+
253
+ /** `forgedock release rollback <id> --reason "..." [--to flag|unit|full] [--later id,id] [--repo R] [--json]`; @returns 0 rolled back, 1 refused, 3 stopped. */
254
+ export async function rollbackFromCli(argv, { io, rel, policy, def, actor, host }) {
255
+ const id = argv.find((a, i) => !a.startsWith("--") && !["--reason", "--to", "--later", "--repo"].includes(argv[i - 1]));
256
+ const reason = flagOf(argv, "--reason"), to = flagOf(argv, "--to") ?? "flag", json_ = argv.includes("--json");
257
+ const say = (o, line) => io.print(json_ ? JSON.stringify(o) : line);
258
+ const refuse = (error) => { say({ ok: false, error }, `release rollback: refused: ${error}`); return 1; };
259
+ if (!id) return refuse("release id required");
260
+ if (!reason || !reason.trim() || reason.startsWith("--")) return refuse("--reason is required");
261
+ if (!RUNGS.slice(0, 3).includes(to)) return refuse(`--to must be one of ${RUNGS.slice(0, 3).join("|")}`);
262
+ const state = rel.load();
263
+ if (!state) return refuse(`no release ${id}`);
264
+ const repo = flagOf(argv, "--repo") ?? state.repo;
265
+ const ctx = { io, repo, def, state, save: () => rel.save(state), policy, actor, host };
266
+ if (io.api) { // mutating: audited like every control verb (#5556)
267
+ const c = await runControl("rollback", [id, "--reason", reason, "--to", to], { io, repo, policy, actor, host, now: io.now?.() });
268
+ if (!c.ok) return refuse(c.error);
269
+ }
270
+ const f = await takeFence(ctx, io.holder ?? `host-${process.pid}`);
271
+ if (f.refused) return refuse(f.refused);
272
+ ctx.fence = f.fence;
273
+ const r = await runRollback(ctx, { reason, to, trigger: null, later: (flagOf(argv, "--later") ?? "").split(",").filter(Boolean) });
274
+ if (r.refused && r.rung === "none") return refuse(r.refused);
275
+ say(r, `release rollback ${id}: ${r.ok ? "rolled back" : "stopped"} at rung ${r.rung} (${r.why})${r.refused ? `; refused: ${r.refused}` : ""}`);
276
+ return r.ok ? 0 : 3;
277
+ }
@@ -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
+ }