forgedock 1.60.1 → 1.61.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/bin/config-schema.mjs +44 -1
  2. package/bin/engine/runlog.mjs +52 -0
  3. package/bin/engine-cli.mjs +9 -4
  4. package/bin/env/bench.mjs +38 -0
  5. package/bin/env/cli.mjs +134 -0
  6. package/bin/env/env.mjs +339 -0
  7. package/bin/forgedock.mjs +32 -3
  8. package/bin/help-text.mjs +2 -0
  9. package/bin/lean/ci-budget.mjs +3 -1
  10. package/bin/lean/ci-classify.mjs +74 -0
  11. package/bin/lean/ci-classify.test.mjs +147 -0
  12. package/bin/lean/ci-emit.mjs +175 -0
  13. package/bin/lean/ci-emit.test.mjs +177 -0
  14. package/bin/lean/ci-preflight.mjs +183 -0
  15. package/bin/lean/ci-preflight.test.mjs +122 -0
  16. package/bin/lean/ci-runner-health.mjs +213 -0
  17. package/bin/lean/ci-runner-health.test.mjs +113 -0
  18. package/bin/lean/ci-watch.mjs +79 -0
  19. package/bin/lean/ci-watch.test.mjs +80 -0
  20. package/bin/lean/depcache.mjs +38 -8
  21. package/bin/lean/deploy-stages.mjs +514 -0
  22. package/bin/lean/deploy-stages.test.mjs +580 -0
  23. package/bin/lean/effects.mjs +50 -0
  24. package/bin/lean/execution.mjs +8 -1
  25. package/bin/lean/lean.mjs +38 -6
  26. package/bin/lean/lean.test.mjs +61 -0
  27. package/bin/lean/release-deploy.mjs +12 -6
  28. package/bin/lean/release-flakes.mjs +16 -0
  29. package/bin/lean/release-flakes.test.mjs +15 -0
  30. package/bin/lean/release-gates.mjs +24 -1
  31. package/bin/lean/release-ledger.mjs +21 -0
  32. package/bin/lean/release-minutes-timing.test.mjs +57 -0
  33. package/bin/lean/release-minutes.mjs +98 -0
  34. package/bin/lean/release-promote.mjs +444 -0
  35. package/bin/lean/release-promote.test.mjs +470 -0
  36. package/bin/lean/release-rollback.mjs +14 -6
  37. package/bin/lean/release.mjs +31 -2
  38. package/bin/lean/sandbox-remote.mjs +11 -3
  39. package/bin/lean/testengine-recall.mjs +82 -0
  40. package/bin/lean/testengine-recall.test.mjs +103 -0
  41. package/bin/lean/testengine-shard.mjs +150 -0
  42. package/bin/lean/testengine-shard.test.mjs +111 -0
  43. package/bin/lean/testengine.mjs +486 -0
  44. package/bin/lean/testengine.test.mjs +303 -0
  45. package/bin/lean/verify-settle.test.mjs +156 -0
  46. package/bin/lean/verify.mjs +98 -3
  47. package/bin/pool/agent.mjs +57 -6
  48. package/bin/pool/ci-events.mjs +189 -0
  49. package/bin/pool/ci-events.test.mjs +143 -0
  50. package/bin/pool/docker.mjs +7 -0
  51. package/bin/pool/lane-tools.mjs +1 -0
  52. package/bin/pool/router.mjs +25 -1
  53. package/bin/pool/warm.mjs +1 -1
  54. package/bin/stats/ci-awareness.mjs +66 -0
  55. package/bin/stats/index.mjs +44 -3
  56. package/bin/stats/release-ledger.test.mjs +226 -0
  57. package/bin/stats/release.mjs +365 -1
  58. package/bin/stats/stats.test.mjs +36 -0
  59. package/docs/CI.md +31 -0
  60. package/docs/CONFIG.md +235 -2
  61. package/docs/ENV-LIBRARY.md +172 -0
  62. package/docs/STATS.md +43 -0
  63. package/docs/ci-events.md +88 -0
  64. package/docs/test-engine.md +98 -0
  65. package/package.json +1 -1
  66. package/pool/README.md +1 -0
  67. package/pool/image/entrypoint.sh +15 -3
  68. package/pool/services/docker-compose.yml +53 -0
  69. package/pool/services/git-mirror.sh +22 -0
  70. package/templates/github-actions/forge-env/action.yml +65 -0
@@ -0,0 +1,514 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Deploy stage engine (#5712): a resumable stage machine behind forge.yaml `deploy.engine.enabled` (default off: `deployStep`
5
+ * in release-deploy.mjs is untouched). The repo declares ordered stages; each is a host command (`run`) or a dispatched
6
+ * workflow, so ssh/compose/k8s stay in the repo. Every stage has a checkpoint `{key, parts, status, outputs, sha}`: the key
7
+ * hashes the stage definition, the git blobs matching its `inputs` globs, the service slice, the outputs of the stages it
8
+ * needs (or, for a stage without outputs, that stage's key) and the live baseline. A stage is skipped only when its checkpoint is `done`, the key is unchanged and its optional
9
+ * read-only `check` still passes; everything else re-runs, so a resume starts at the first failed or incomplete stage and a
10
+ * fix commit re-runs only the stages whose inputs it touched.
11
+ * A failure before traffic moves leaves the old colour serving: no shift, no hold, no rollback trigger. A failure at or after
12
+ * the shift moves traffic back with `rollback.shift_back_command` inside `rollback.budget_s`; if that fails, the rollback
13
+ * ladder (#5563) is triggered as before. Services with an unchanged image digest and config hash are skipped (`services.mode`:
14
+ * shadow records what would be skipped and whether that agreed; enforce skips). Canary steps and waits come from the risk
15
+ * class (`riskOf`). Rationale and idempotency contracts: devdocs/decisions/5712-deploy-stage-engine.md.
16
+ */
17
+ import { createHash } from "node:crypto";
18
+ import { load, JSON_SCHEMA } from "../vendor/js-yaml/js-yaml.mjs";
19
+ import { fenced } from "./release-fence.mjs";
20
+ import { readTarget, liveMatches, freezeValue, BOUNDS } from "./release-deploy.mjs";
21
+ import { dispatchOnce } from "./release-rollback.mjs";
22
+ import { verifyStep, verifyConfigured } from "./release-verify.mjs";
23
+ import { deriveFacts, riskOf } from "./release-classify.mjs";
24
+ import { unitGlobToRegExp } from "./release-unitmap.mjs";
25
+ import { readActive, updateActive, heartbeat } from "./release-ledger.mjs";
26
+
27
+ /** Stage kinds and the idempotency contract a stage of that kind must keep (the engine may run any stage twice). */
28
+ export const KINDS = {
29
+ build: "Content-addressed: the same inputs give the same image digests; a re-run reuses or rebuilds them and changes nothing that serves.",
30
+ migrate: "Expand only (additive, compatible with the old colour); the migration tool skips what is already applied.",
31
+ deploy: "Converges the idle (new) colour to the given digests; never touches the serving colour or the router; a re-run replaces the idle colour.",
32
+ smoke: "Read-only, against the new colour's own address; moves no traffic and writes no production data.",
33
+ shift: "Sets the new colour's share of traffic to FORGE_TRAFFIC_PCT; setting the same share again is a no-op.",
34
+ verify: "Read-only: the live record check, the stage's own command, then the verification layers; a passed layer is not repeated.",
35
+ retire: "Stops the old colour; a no-op when it is already stopped. After it there is no instant shift-back.",
36
+ contract: "Contract (destructive) migrations, only after the old colour is retired; the migration tool skips what is already applied.",
37
+ run: "Declared by the repo: the command must be safe to run twice.",
38
+ };
39
+ const READ_ONLY = ["smoke", "verify"];
40
+ export const CANARY = { low: { steps: [100], wait_s: 0 }, medium: { steps: [10, 100], wait_s: 120 }, high: { steps: [10, 50, 100], wait_s: 300 } };
41
+ export const STAGES_KEY = "deploy_stages";
42
+ export const ENGINE_KEYS = ["enabled", "live_release_command", "stage_timeout_s", "colour", "services", "canary", "rollback", "stages"];
43
+ const STAGE_KEYS = ["id", "kind", "run", "workflow", "inputs", "needs", "services", "check", "outputs_command", "timeout_s"];
44
+ const PART_NAMES = { def: "stage definition", paths: "files matching inputs", services: "service digests or config", needs: "an earlier stage it needs changed", base: "live baseline or colour" };
45
+
46
+ const blocked = (reason, extra = {}) => ({ blocked: true, reason, ...extra });
47
+ const tail = (s, n = 300) => String(s ?? "").trim().slice(-n);
48
+ const short = (s) => String(s ?? "").slice(0, 8);
49
+ const stable = (v) => (Array.isArray(v) ? `[${v.map(stable).join(",")}]` : v && typeof v === "object" ? `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable(v[k])}`).join(",")}}` : JSON.stringify(v ?? null));
50
+ const hash = (v) => createHash("sha256").update(typeof v === "string" ? v : stable(v)).digest("hex").slice(0, 32);
51
+ const quote = (v) => `'${String(v ?? "").replace(/'/g, `'\\''`)}'`;
52
+ /** `cmd` with `env` exported in front of it: the existing `io.rehearse(cmd)` hook takes no environment. */
53
+ export const withEnv = (cmd, env) => `export ${Object.entries(env).map(([k, v]) => `${k}=${quote(v)}`).join(" ")}; ${cmd}`;
54
+ const parseJson = (s) => { try { const o = JSON.parse(String(s ?? "").trim()); return o && typeof o === "object" && !Array.isArray(o) ? o : null; } catch { return null; } };
55
+
56
+ export const engineOn = (e) => !!e && e.enabled === true;
57
+ /** True when the `deploy:` section of the text has an `engine:` child (a line scan: used only when the YAML does not parse). */
58
+ function hasEngineBlock(text) {
59
+ let inDeploy = false;
60
+ for (const line of String(text).split(/\r?\n/)) {
61
+ if (/^\S/.test(line)) inDeploy = line.startsWith("deploy:");
62
+ else if (inDeploy && line.trimStart().startsWith("engine:")) return true;
63
+ }
64
+ return false;
65
+ }
66
+
67
+ /**
68
+ * forge.yaml `deploy.engine`, or null when it is off. No git call unless the working copy turns it on; then the default
69
+ * branch's forge.yaml wins when the file is tracked there, so a checkout of another branch cannot change the stages (I13).
70
+ */
71
+ export function readEngine({ raw, io, def }) {
72
+ const text = String(raw ?? "");
73
+ if (!/^deploy:/m.test(text)) return null;
74
+ const pick = (t) => { try { return load(String(t), { schema: JSON_SCHEMA })?.deploy?.engine ?? null; } catch (e) { return hasEngineBlock(t) ? { enabled: true, error: `forge.yaml is not valid YAML (${String(e?.message ?? e).split("\n")[0]})` } : null; } };
75
+ let e = pick(text);
76
+ if (!engineOn(e)) return null;
77
+ if (io?.git && def) { let t = null; try { t = io.git(["show", `origin/${def}:forge.yaml`]); } catch { t = null; } if (t != null) e = pick(t); }
78
+ return engineOn(e) ? e : null;
79
+ }
80
+
81
+ /** The engine block with defaults filled in. */
82
+ export function normalise(e) {
83
+ const stages = (Array.isArray(e?.stages) ? e.stages : []).map((s) => ({ ...s, kind: s?.kind ?? "run", inputs: s?.inputs ?? ["**"] }));
84
+ const sv = e?.services ?? {};
85
+ return {
86
+ stages, live_release_command: e?.live_release_command, stage_timeout_s: e?.stage_timeout_s ?? BOUNDS.defaultStageS,
87
+ colour: { names: e?.colour?.names ?? ["blue", "green"], active_command: e?.colour?.active_command ?? null },
88
+ services: { mode: sv.mode ?? (sv.desired_command ? "shadow" : "off"), desired_command: sv.desired_command ?? null, live_command: sv.live_command ?? null },
89
+ canary: e?.canary ?? {},
90
+ rollback: { budget_s: e?.rollback?.budget_s ?? 60, shift_back_command: e?.rollback?.shift_back_command ?? null, abort_command: e?.rollback?.abort_command ?? null },
91
+ };
92
+ }
93
+
94
+ /** @returns {string[]} findings; empty when the block is a valid stage machine. */
95
+ export function validateEngine(e) {
96
+ const out = [];
97
+ if (e?.error) return [e.error];
98
+ for (const k of Object.keys(e ?? {})) if (!ENGINE_KEYS.includes(k)) out.push(`${k}: unknown key`);
99
+ const stages = e?.stages;
100
+ if (!Array.isArray(stages) || !stages.length) return [...out, "stages: a non-empty list is required"];
101
+ const seen = [];
102
+ stages.forEach((s, i) => {
103
+ const at = `stages[${i}]${s?.id ? ` (${s.id})` : ""}`;
104
+ if (!s || typeof s !== "object") return void out.push(`${at}: expected a mapping`);
105
+ for (const k of Object.keys(s)) if (!STAGE_KEYS.includes(k)) out.push(`${at}.${k}: unknown key`);
106
+ if (typeof s.id !== "string" || !/^[a-z][\w-]*$/i.test(s.id)) out.push(`${at}: id is required (letters, digits, - and _)`);
107
+ else if (seen.includes(s.id)) out.push(`${at}: duplicate id`);
108
+ const kind = s.kind ?? "run";
109
+ if (!(kind in KINDS)) out.push(`${at}: kind ${JSON.stringify(kind)} is not one of ${Object.keys(KINDS).join("|")}`);
110
+ const execs = [s.run, s.workflow].filter((x) => typeof x === "string" && x.trim()).length;
111
+ if (execs > 1 || (execs === 0 && kind !== "verify")) out.push(`${at}: exactly one of run or workflow is required`);
112
+ for (const k of ["inputs", "needs"]) if (s[k] !== undefined && !(Array.isArray(s[k]) && s[k].every((x) => typeof x === "string"))) out.push(`${at}.${k}: expected a list of strings`);
113
+ for (const n of Array.isArray(s.needs) ? s.needs : []) if (!seen.includes(n)) out.push(`${at}.needs: ${n} is not an earlier stage`);
114
+ if (s.timeout_s !== undefined && !(typeof s.timeout_s === "number" && s.timeout_s > 0)) out.push(`${at}.timeout_s: expected a positive number`);
115
+ seen.push(s.id);
116
+ });
117
+ const kinds = stages.map((s) => s?.kind ?? "run"), first = (k) => kinds.indexOf(k), last = (k) => kinds.lastIndexOf(k);
118
+ if (first("verify") < 0) out.push("stages: a verify stage is required (the engine never goes live without the live check)");
119
+ if (first("shift") >= 0) {
120
+ if (!(first("smoke") >= 0 && first("smoke") < first("shift"))) out.push("stages: a smoke stage must come before the first shift stage (the new colour is smoked before traffic moves)");
121
+ if (first("verify") >= 0 && last("verify") < last("shift")) out.push("stages: a verify stage must come after the last shift stage");
122
+ if (first("deploy") > first("shift")) out.push("stages: deploy stages come before the first shift stage");
123
+ }
124
+ for (const k of ["retire", "contract"]) if (first(k) >= 0 && first("verify") >= 0 && first(k) < last("verify")) out.push(`stages: ${k} stages come after verify (the old colour is the rollback path until then)`);
125
+ if (first("contract") >= 0 && first("retire") > first("contract")) out.push("stages: contract stages come after retire");
126
+ const mode = e.services?.mode;
127
+ if (mode !== undefined && !["off", "shadow", "enforce"].includes(mode)) out.push(`services.mode: ${JSON.stringify(mode)} is not one of off|shadow|enforce`);
128
+ for (const [risk, c] of Object.entries(e.canary ?? {})) {
129
+ if (risk === "health_command") continue;
130
+ if (!(risk in CANARY)) { out.push(`canary.${risk}: unknown risk class (low|medium|high)`); continue; }
131
+ const st = c?.steps;
132
+ if (st !== undefined && !(Array.isArray(st) && st.length && st.every((p, i) => Number.isInteger(p) && p > 0 && p <= 100 && (i === 0 || p > st[i - 1])) && st.at(-1) === 100)) out.push(`canary.${risk}.steps: ascending percentages ending in 100`);
133
+ if (c?.wait_s !== undefined && !(typeof c.wait_s === "number" && c.wait_s >= 0)) out.push(`canary.${risk}.wait_s: expected a number >= 0`);
134
+ }
135
+ const b = e.rollback?.budget_s;
136
+ if (b !== undefined && !(typeof b === "number" && b > 0)) out.push("rollback.budget_s: expected a positive number");
137
+ return out;
138
+ }
139
+
140
+ /** Canary steps (percent of traffic on the new colour) and the wait after each step below 100, by risk class. */
141
+ export function canaryPlan(eng, risk) {
142
+ const c = { ...(CANARY[risk] ?? CANARY.high), ...(eng.canary?.[risk] ?? {}) };
143
+ return { steps: c.steps, wait_s: c.wait_s };
144
+ }
145
+
146
+ /** Risk class of the deploy (`riskOf` over the files between the rollback target and `sha`); an unreadable diff is high. */
147
+ export function deployRisk(ctx, sha, target) {
148
+ if (ctx.config.deployRisk) return { risk: ctx.config.deployRisk, rule: "config" };
149
+ try {
150
+ const rows = String(ctx.io.git(["diff", "--numstat", `${target}..${sha}`])).split("\n").filter(Boolean).map((l) => l.split("\t"));
151
+ const policy = ctx.config.policy ?? {};
152
+ return riskOf(policy, deriveFacts(policy, rows.map((r) => r[2] ?? ""), { diffLines: rows.reduce((n, r) => n + (Number(r[0]) || 0) + (Number(r[1]) || 0), 0) }));
153
+ } catch { return { risk: "high", rule: "unreadable diff" }; }
154
+ }
155
+
156
+ const normServices = (m) => Object.fromEntries(Object.entries(m ?? {}).map(([k, v]) => [k, typeof v === "string" ? { digest: v, config: null } : { digest: v?.digest ?? null, config: v?.config ?? null }]));
157
+
158
+ /**
159
+ * Which services must be deployed. A service is unchanged only when the desired and the running side both report the same
160
+ * image digest AND the same config hash; anything missing counts as changed (never skipped on a guess).
161
+ * @returns {{changed: {service, why}[], unchanged: string[]}}
162
+ */
163
+ export function diffServices(desired, live) {
164
+ const d = normServices(desired), l = normServices(live), changed = [], unchanged = [];
165
+ for (const s of Object.keys(d).sort()) {
166
+ const x = d[s], y = l[s];
167
+ const why = !x.digest ? "no desired digest reported" : !x.config ? "no config hash reported" : !y ? "not running" : y.digest !== x.digest ? "image digest changed" : y.config !== x.config ? "config changed" : null;
168
+ if (why) changed.push({ service: s, why }); else unchanged.push(s);
169
+ }
170
+ return { changed, unchanged };
171
+ }
172
+
173
+ /** Hash of the git blobs at `sha` matching `globs` (`["**"]`: the tree id); unreadable history names the sha, so it never matches. */
174
+ function treeHash(io, sha, globs, cache) {
175
+ try {
176
+ if (globs.length === 1 && globs[0] === "**") return String(io.git(["rev-parse", `${sha}^{tree}`])).trim();
177
+ cache.ls ??= String(io.git(["ls-tree", "-r", "-z", sha])).split("\0").filter(Boolean).map((l) => { const t = l.indexOf("\t"); return [l.slice(t + 1), l.slice(0, t).split(" ")[2]]; });
178
+ const res = globs.map((g) => unitGlobToRegExp(String(g)));
179
+ return hash(cache.ls.filter(([p]) => res.some((re) => re.test(p))).map(([p, oid]) => `${oid} ${p}`).join("\n"));
180
+ } catch { return `unreadable:${sha}`; }
181
+ }
182
+
183
+ /** The hashed parts of a stage's inputs; the checkpoint key is their hash. */
184
+ export function stageParts({ stage, tree, services, needs, base }) {
185
+ return { def: hash({ kind: stage.kind, run: stage.run ?? null, workflow: stage.workflow ?? null, check: stage.check ?? null, outputs_command: stage.outputs_command ?? null }), paths: tree, services: services == null ? "-" : hash(services), needs: hash(needs), base: hash(base) };
186
+ }
187
+ export const partsKey = (parts) => hash(parts);
188
+ /** What a later stage hashes for a stage it needs: its outputs, or, when it declares none, its key (so a changed input is never invisible downstream). */
189
+ const token = (outputs, key) => (Object.keys(outputs ?? {}).length ? outputs : { ran: key ?? null });
190
+ /** Keep the lease heartbeat fresh during a long deploy (the conductor takes over a stale lease, #5564). @returns {Promise<string|null>} why to stop */
191
+ async function beat(ctx) {
192
+ const f = ctx.fence;
193
+ if (!f?.lctx || !f.lease) return null;
194
+ try { return (await heartbeat(f.lctx, f.lease)).fenced ? "fenced: another host took over the release lease" : null; } catch { return null; }
195
+ }
196
+
197
+ /** Run or skip a stage from its checkpoint. @returns {{run: boolean, why: string}} */
198
+ export function decide(cp, parts) {
199
+ if (!cp) return { run: true, why: "no checkpoint" };
200
+ if (cp.status !== "done") return { run: true, why: `${cp.status} last time${cp.reason ? `: ${cp.reason}` : ""}` };
201
+ const diff = Object.keys(parts).filter((k) => cp.parts?.[k] !== parts[k]);
202
+ if (diff.length) return { run: true, why: `inputs changed: ${diff.map((k) => PART_NAMES[k]).join(", ")}` };
203
+ return { run: false, why: `done at ${short(cp.sha)}, inputs unchanged` };
204
+ }
205
+
206
+ /**
207
+ * Checkpoint store. The release state (`state.deploy.stages`) always holds them; a managed release also keeps them in
208
+ * `_active.deploy_stages` on the ledger, so the next release starts from what the last attempt finished.
209
+ */
210
+ export function stageStore(ctx) {
211
+ const local = () => (ctx.state.deploy.stages ??= {});
212
+ const lctx = ctx.fence?.lctx ?? ctx.lctx ?? null;
213
+ const shared = async (fn) => { const r = await updateActive(lctx, [STAGES_KEY], (a) => ({ patch: { [STAGES_KEY]: fn({ ...(a[STAGES_KEY] ?? {}) }) } })); if (!r.ok) throw new Error("the checkpoint write to the ledger lost the race"); };
214
+ return {
215
+ async load() { return lctx ? Object.assign(local(), (await readActive(lctx))[STAGES_KEY] ?? {}) : local(); },
216
+ async put(id, cp) { local()[id] = cp; ctx.save(); if (lctx && !ctx.dry) await shared((m) => ({ ...m, [id]: cp })); },
217
+ /** Keep the record (and its attempt count, so a workflow stage is dispatched afresh) but make the stage run again. */
218
+ async mark(ids, status) { const hit = ids.filter((id) => local()[id]); for (const id of hit) local()[id] = { ...local()[id], status }; ctx.save(); if (lctx && !ctx.dry && hit.length) await shared((m) => ({ ...m, ...Object.fromEntries(hit.map((id) => [id, local()[id]])) })); },
219
+ async drop(ids) { for (const id of ids) delete local()[id]; ctx.save(); if (lctx && !ctx.dry) await shared((m) => Object.fromEntries(Object.entries(m).filter(([k]) => !ids.includes(k)))); },
220
+ };
221
+ }
222
+
223
+ /** After a unit or full rollback the environment no longer matches any checkpoint: forget them all. */
224
+ export async function clearStages(ctx) {
225
+ const store = ctx.stageStore ?? stageStore(ctx);
226
+ await store.drop(Object.keys(await store.load()));
227
+ if (ctx.state.deploy?.engine) { delete ctx.state.deploy.engine.shift; delete ctx.state.deploy.engine.dispatch; }
228
+ ctx.save();
229
+ }
230
+
231
+ const rehearseJson = async (io, cmd, env) => { const r = await io.rehearse(withEnv(cmd, env), { timeout: 120_000 }); return r?.ok ? parseJson(String(r.output).trim().split("\n").at(-1)) : null; };
232
+
233
+ /**
234
+ * Everything the stage loop needs that is observed, not acted on: colours, service diff, risk, checkpoints.
235
+ * `ctx.promote` (the build-once/promote interface: `serviceDigests(sha)`, `liveDigests()`, `canPromote({service, digest, sha})`)
236
+ * wins over the `services.*_command` pair. @returns {Promise<object | {blocked: true, reason}>}
237
+ */
238
+ async function prepare(ctx, eng, sha, target) {
239
+ const { io, state } = ctx, st = state.deploy ?? {}, promote = ctx.promote ?? ctx.config.promote ?? null;
240
+ const base = { FORGE_SHA: sha, FORGE_TARGET_SHA: target?.sha ?? "", FORGE_RELEASE: state.id ?? "" };
241
+ let colour = st.engine?.colour ?? null;
242
+ if (!colour && eng.colour.active_command) {
243
+ const r = await io.rehearse(withEnv(eng.colour.active_command, base), { timeout: 120_000 });
244
+ const old = r?.ok ? String(r.output).trim().split(/\s+/).at(-1) : "";
245
+ if (!eng.colour.names.includes(old)) return blocked(`colour.active_command did not name the serving colour (${eng.colour.names.join("|")}); nothing was deployed`);
246
+ colour = { old, new: eng.colour.names.find((n) => n !== old) };
247
+ }
248
+ colour ??= { old: "", new: "" };
249
+ const sv = { mode: eng.services.mode, changed: [], unchanged: [], active: null, desired: null };
250
+ if (sv.mode !== "off") {
251
+ const desired = promote?.serviceDigests ? await promote.serviceDigests(sha) : eng.services.desired_command ? await rehearseJson(io, eng.services.desired_command, base) : null;
252
+ const live = promote?.liveDigests ? await promote.liveDigests() : eng.services.live_command ? await rehearseJson(io, eng.services.live_command, base) : null;
253
+ if (!desired) return blocked("services: the desired digests are unreadable (services.desired_command or the promote interface); nothing was deployed");
254
+ const diff = diffServices(desired, live ?? {}), all = Object.keys(desired).sort();
255
+ Object.assign(sv, diff, { desired: normServices(desired), active: sv.mode === "enforce" ? diff.changed.map((c) => c.service) : all });
256
+ if (promote?.canPromote) for (const s of sv.active) {
257
+ const ok = await promote.canPromote({ service: s, digest: sv.desired[s].digest, sha });
258
+ if (!ok?.ok) return blocked(`service ${s} cannot be promoted: ${ok?.why ?? "no promotion evidence"}; nothing was deployed`);
259
+ }
260
+ }
261
+ const risk = deployRisk(ctx, sha, target?.sha);
262
+ const store = ctx.stageStore ?? stageStore(ctx);
263
+ let cps;
264
+ try { cps = await store.load(); } catch (e) { return blocked(`cannot read the stage checkpoints (I5): ${String(e?.message ?? e).split("\n")[0]}`); }
265
+ const kinds = eng.stages.map((s) => s.kind), shiftAt = kinds.indexOf("shift");
266
+ const trafficAt = shiftAt >= 0 ? shiftAt : kinds.indexOf("deploy") >= 0 ? kinds.indexOf("deploy") : kinds.length;
267
+ const env = { ...base, FORGE_COLOUR: colour.new, FORGE_OLD_COLOUR: colour.old, FORGE_RISK: risk.risk, FORGE_SERVICES: (sv.active ?? []).join(","), FORGE_SERVICES_SKIPPED: sv.mode === "enforce" ? sv.unchanged.join(",") : "" };
268
+ return { eng, colour, sv, risk, store, cps, trafficAt, retireAt: kinds.indexOf("retire"), env, cache: {}, outputs: {}, base: { target: target?.sha ?? null, colour: colour.new } };
269
+ }
270
+
271
+ const partsFor = (ctx, x, stage, i, sha) => stageParts({
272
+ stage, tree: treeHash(ctx.io, sha, stage.inputs, x.cache), base: x.base,
273
+ services: stage.services && x.sv.active ? Object.fromEntries(x.sv.active.map((s) => [s, x.sv.desired[s]])) : null,
274
+ needs: Object.fromEntries((stage.needs ?? x.eng.stages.slice(0, i).map((s) => s.id)).map((id) => [id, x.outputs[id] ?? {}])),
275
+ });
276
+
277
+ /**
278
+ * Which stages would run for `sha` and why, without acting (`release deploy --plan`). Checks are not probed and outputs of
279
+ * stages that will run are not known yet, so a skipped stage after one that runs is "skipped unless its outputs change".
280
+ */
281
+ export async function planStages(ctx, sha, d = ctx.config.deploy ?? {}) {
282
+ const bad = validateEngine(ctx.config.deployEngine);
283
+ if (bad.length) return blocked(`deploy.engine is invalid: ${bad.join("; ")}`);
284
+ const eng = normalise(ctx.config.deployEngine);
285
+ ctx.state.deploy ??= {};
286
+ const target = ctx.state.deploy.target ?? await readTarget(ctx.io, d.live_release_command ?? eng.live_release_command);
287
+ const x = await prepare({ ...ctx, dry: true }, eng, sha, target);
288
+ if (x.blocked) return x;
289
+ const stages = [], rerun = [];
290
+ eng.stages.forEach((stage, i) => {
291
+ const cp = x.cps[stage.id], parts = partsFor(ctx, x, stage, i, sha);
292
+ let dec = decide(cp, parts);
293
+ if (stage.services && x.sv.mode === "enforce" && !x.sv.active.length) dec = { run: false, why: "no changed services" };
294
+ else if (!dec.run) dec.why += `${stage.check ? "; its check is probed at run time" : ""}${rerun.length ? `; re-runs if the outputs of ${rerun.join(", ")} change` : ""}`;
295
+ if (dec.run) rerun.push(stage.id);
296
+ x.outputs[stage.id] = token(cp?.outputs, dec.run ? partsKey(parts) : cp?.key); // a stage that will run has no outputs yet: assume declared outputs stay as they were
297
+ stages.push({ stage: stage.id, kind: stage.kind, run: dec.run, why: dec.why, contract: KINDS[stage.kind] });
298
+ });
299
+ return { sha, target: target?.sha ?? null, colour: x.colour, risk: x.risk, canary: canaryPlan(eng, x.risk.risk), services: { mode: x.sv.mode, changed: x.sv.changed, unchanged: x.sv.unchanged }, stages };
300
+ }
301
+
302
+ export function renderPlan(p) {
303
+ const lines = [`deploy plan for ${short(p.sha)} (live ${short(p.target) || "unknown"}; risk ${p.risk.risk}, rule ${p.risk.rule}; canary ${p.canary.steps.join(" -> ")}%${p.canary.wait_s ? `, ${p.canary.wait_s}s between steps` : ""}${p.colour.new ? `; new colour ${p.colour.new}` : ""})`];
304
+ for (const s of p.stages) lines.push(` ${s.run ? "run " : "skip"} ${s.stage} (${s.kind}): ${s.why}`);
305
+ if (p.services.mode !== "off") lines.push(` services (${p.services.mode}): ${p.services.changed.length} changed${p.services.changed.length ? ` (${p.services.changed.map((c) => `${c.service}: ${c.why}`).join("; ")})` : ""}, ${p.services.unchanged.length} unchanged${p.services.mode === "shadow" ? " (deployed anyway; the skip is only recorded)" : " (skipped)"}`);
306
+ return lines.join("\n");
307
+ }
308
+
309
+ /** One execution of a stage's command or workflow. @returns {{ok: true, output?} | {fail: string} | {refused: string}} */
310
+ async function execStage(ctx, x, stage, env, tag, attempt) {
311
+ const { io, state } = ctx, timeout = (stage.timeout_s ?? x.eng.stage_timeout_s) * 1000;
312
+ const e = { ...env, FORGE_STAGE: stage.id };
313
+ if (stage.workflow) {
314
+ const b = { ...BOUNDS, ...(ctx.config.deployBounds ?? {}) };
315
+ const rec = ((state.deploy.engine.dispatch ??= {})[`${tag}:${attempt}`] ??= {});
316
+ const inputs = Object.fromEntries(Object.entries({ stage: stage.id, sha: e.FORGE_SHA, release: e.FORGE_RELEASE, colour: e.FORGE_COLOUR, old_colour: e.FORGE_OLD_COLOUR, services: e.FORGE_SERVICES, traffic_pct: e.FORGE_TRAFFIC_PCT }).filter(([, v]) => v !== undefined && v !== ""));
317
+ const r = await dispatchOnce(ctx, rec, { workflow: stage.workflow, inputs, tag: `stage:${tag}:${attempt}`, what: `${stage.id} stage dispatch` }, { pollMs: b.pollMs, startPolls: 6, donePolls: Math.max(1, Math.ceil(timeout / b.pollMs)) });
318
+ return r.err ? (/^dispatch refused/.test(r.err) ? { refused: r.err } : { fail: r.err }) : { ok: true, output: "" };
319
+ }
320
+ const act = () => io.rehearse(withEnv(stage.run, e), { timeout });
321
+ const f = READ_ONLY.includes(stage.kind) ? { value: await act() } : await fenced(ctx.fence, { action: "stage", key: `${ctx.fence?.lease?.release ?? state.id ?? "-"}:${ctx.fence?.lease?.epoch ?? 0}:stage:${tag}:${attempt}` }, act);
322
+ if (f.refused) return { refused: f.refused };
323
+ return f.value?.ok ? { ok: true, output: f.value.output } : { fail: `${f.value?.timedOut ? "timed out; " : ""}${tail(f.value?.output) || "command failed"}` };
324
+ }
325
+
326
+ /** Canary: each step sets the share, waits (below 100) and checks health. Progress is kept, so a resume never restarts the wait. */
327
+ async function runShift(ctx, x, stage, key, attempt) {
328
+ const { io, state } = ctx, eg = state.deploy.engine, plan = canaryPlan(x.eng, x.risk.risk), now = () => io.now?.() ?? Date.now();
329
+ if (eg.shift?.key !== key) eg.shift = { key, step: 0, since: null };
330
+ const sh = eg.shift;
331
+ while (sh.step < plan.steps.length) {
332
+ const pct = plan.steps[sh.step], env = { ...x.env, FORGE_TRAFFIC_PCT: String(pct) };
333
+ if (sh.since == null) {
334
+ eg.traffic_at ??= new Date(now()).toISOString();
335
+ const r = await execStage(ctx, x, stage, env, `${stage.id}:${key.slice(0, 12)}:${pct}`, attempt);
336
+ if (!r.ok) return r;
337
+ sh.since = now(); ctx.save();
338
+ }
339
+ for (let wait = pct < 100 ? sh.since + plan.wait_s * 1000 - now() : 0; wait > 0; wait -= 60_000) { // sliced, so the lease stays fresh through a long wait
340
+ await io.sleep(Math.min(wait, 60_000));
341
+ const lost = await beat(ctx);
342
+ if (lost) return { refused: lost };
343
+ }
344
+ if (x.eng.canary.health_command) {
345
+ const h = await io.rehearse(withEnv(x.eng.canary.health_command, { ...env, FORGE_STAGE: stage.id }), { timeout: 120_000 });
346
+ if (!h?.ok) return { fail: `canary health failed at ${pct}%: ${tail(h?.output) || "health command failed"}` };
347
+ }
348
+ sh.step += 1; sh.since = null; ctx.save();
349
+ }
350
+ return { ok: true, output: "" };
351
+ }
352
+
353
+ /** verify: the live record (I28), the stage's own command, then the verification layers (#5562). */
354
+ async function runVerify(ctx, x, stage, key, attempt, sha, d) {
355
+ const { io, state } = ctx, st = state.deploy;
356
+ st.phase = "LIVE_CHECK"; ctx.save();
357
+ const live = await readTarget(io, d.live_release_command);
358
+ if (!liveMatches(live, sha, st.expected)) return { fail: `LIVE_CHECK failed: live is ${live?.sha ? short(live.sha) : "unreadable"}, not ${short(sha)} (I28)` };
359
+ if (stage.run || stage.workflow) { const r = await execStage(ctx, x, stage, x.env, `${stage.id}:${key.slice(0, 12)}`, attempt); if (!r.ok) return r; }
360
+ st.phase = "VERIFYING"; ctx.save();
361
+ if (!verifyConfigured(ctx.config.verify)) return { ok: true, output: "" };
362
+ const v = await verifyStep({ ...ctx, rollbackTrigger: undefined }, sha); // the engine shifts back itself; the ladder is triggered only if that fails
363
+ if (!v.blocked) return { ok: true, output: "", verify: v };
364
+ return v.rollback ? { fail: String(v.reason).replace(/; rollback trigger emitted.*$/, "") } : { wait: v.reason, hold: v.hold };
365
+ }
366
+
367
+ async function bounded(ctx, x, cmd, extra = {}) {
368
+ const now = () => ctx.io.now?.() ?? Date.now(), t0 = now();
369
+ const act = () => ctx.io.rehearse(withEnv(cmd, { ...x.env, ...extra }), { timeout: x.eng.rollback.budget_s * 1000 });
370
+ let f;
371
+ try { f = await fenced(ctx.fence, { action: "stage-rollback", key: `${ctx.fence?.lease?.release ?? ctx.state.id ?? "-"}:${ctx.fence?.lease?.epoch ?? 0}:stage-rollback:${t0}` }, act); } catch (e) { f = { refused: String(e?.message ?? e).split("\n")[0] }; }
372
+ return { ok: !f.refused && !!f.value?.ok, ms: now() - t0, why: f.refused ?? (f.value?.timedOut ? `did not finish within ${x.eng.rollback.budget_s}s` : tail(f.value?.output, 200) || "failed") };
373
+ }
374
+
375
+ /** What a failed stage leaves behind, by where traffic is. */
376
+ async function onFailure(ctx, x, i, stage, fail) {
377
+ const { state } = ctx, eg = state.deploy.engine, ids = (from, to) => x.eng.stages.slice(from, to).map((s) => s.id);
378
+ const reason = `stage ${stage.id} (${stage.kind}) failed: ${fail}`, resume = `fix it, then \`forgedock release deploy --resume ${state.id ?? "<id>"}\``;
379
+ if (i < x.trafficAt) { // nothing serves the new code: the old colour never stopped serving
380
+ let rb = { kind: "none", ok: true, ms: 0 };
381
+ if (x.eng.rollback.abort_command) {
382
+ const r = await bounded(ctx, x, x.eng.rollback.abort_command, { FORGE_STAGE: stage.id });
383
+ rb = { kind: "abort", ok: r.ok, ms: r.ms, ...(r.ok ? {} : { why: r.why }) };
384
+ const firstDeploy = x.eng.stages.findIndex((s) => s.kind === "deploy");
385
+ if (firstDeploy >= 0) await x.store.mark(ids(firstDeploy), "aborted"); // the idle colour is gone (or half gone): deploy again next time
386
+ }
387
+ eg.last = { stage: stage.id, pre_traffic: true, rollback: rb }; ctx.save();
388
+ return blocked(`${reason}; no traffic moved${x.colour.old ? `, ${x.colour.old} keeps serving` : ""} (no freeze, no hold); ${resume}`, { preTraffic: true, stage: stage.id, engine: eg.last });
389
+ }
390
+ if (x.retireAt >= 0 && i >= x.retireAt) { // the old colour is stopped (or half stopped): roll forward
391
+ eg.last = { stage: stage.id, pre_traffic: false, rollback: { kind: "none", ok: false, why: "old colour retired" } }; ctx.save();
392
+ return blocked(`${reason}; the old colour is retired, so there is no shift-back (owner ask: roll forward, or run the rollback ladder; label needs-agent when no host is attached)`, { stage: stage.id, hold: { kind: "deploy-engine", label: "needs-agent" }, engine: eg.last });
393
+ }
394
+ const sb = x.eng.rollback.shift_back_command ? await bounded(ctx, x, x.eng.rollback.shift_back_command, { FORGE_TRAFFIC_PCT: "0", FORGE_STAGE: stage.id }) : { ok: false, ms: 0, why: "rollback.shift_back_command is not set" };
395
+ await x.store.mark(ids(x.trafficAt), "rolled-back"); // traffic is back on the old colour (or its state is unknown): shift and everything after it start over
396
+ delete eg.shift; delete state.verify;
397
+ eg.last = { stage: stage.id, pre_traffic: false, rollback: { kind: "shift-back", ok: sb.ok, ms: sb.ms, ...(sb.ok ? {} : { why: sb.why }) } }; ctx.save();
398
+ if (sb.ok) return blocked(`${reason}; traffic shifted back${x.colour.old ? ` to ${x.colour.old}` : ""} in ${sb.ms} ms; ${resume}`, { rolledBack: true, stage: stage.id, engine: eg.last });
399
+ ctx.rollbackTrigger?.({ reason, sha: state.deploy.merge });
400
+ return blocked(`${reason}; shift-back failed (${sb.why}); rollback trigger emitted to the ladder (#5563)`, { stage: stage.id, rollback: { reason }, engine: eg.last });
401
+ }
402
+
403
+ /**
404
+ * Run the stage machine for `sha` (called by `deployStep` once the rollback target is recorded, I9).
405
+ * @returns {Promise<{live: true, merge, run: null, reruns: 0, engine}|{blocked: true, reason, preTraffic?, rolledBack?, hold?, rollback?}>}
406
+ */
407
+ export async function runStages(ctx, sha, d) {
408
+ const { io, repo, state } = ctx, st = state.deploy, now = () => io.now?.() ?? Date.now();
409
+ const bad = validateEngine(ctx.config.deployEngine);
410
+ if (bad.length) return blocked(`deploy.engine is invalid: ${bad.join("; ")}; nothing was deployed`);
411
+ const eng = normalise(ctx.config.deployEngine);
412
+ if (await freezeValue(io, repo, d.freeze_variable)) return blocked(`${d.freeze_variable} is set; the engine never deploys while a freeze is set (I26)`);
413
+ const eg = (st.engine ??= { started_at: new Date(now()).toISOString() });
414
+ if (st.merge !== sha) { // a fix commit (--sha): verified from scratch, against its own expected digests
415
+ if (d.expected_digests_command) {
416
+ const r = await io.rehearse(withEnv(d.expected_digests_command, { FORGE_SHA: sha }), { timeout: 120_000 });
417
+ st.expected = r?.ok ? parseJson(r.output) : null;
418
+ if (!st.expected) return blocked("deploy.expected_digests_command returned no digests for the new sha; nothing was deployed");
419
+ }
420
+ delete state.verify; st.merge = sha;
421
+ }
422
+ st.phase = "DEPLOYING"; ctx.save();
423
+ const x = await prepare(ctx, eng, sha, st.target);
424
+ if (x.blocked) return x;
425
+ eg.colour = x.colour; eg.risk = x.risk;
426
+ if (x.sv.mode !== "off") st.services = { mode: x.sv.mode, changed: x.sv.changed, [x.sv.mode === "enforce" ? "skipped" : "would_skip"]: x.sv.unchanged };
427
+ ctx.save();
428
+
429
+ const log = [];
430
+ let drift = null, verify = null;
431
+ for (const [i, stage] of eng.stages.entries()) {
432
+ const parts = partsFor(ctx, x, stage, i, sha), key = partsKey(parts), cp = x.cps[stage.id];
433
+ let dec = drift ? { run: true, why: `the environment drifted at ${drift}` } : decide(cp, parts);
434
+ if (!dec.run && stage.check) { // observe before trusting a checkpoint: the effect must still hold
435
+ const c = await io.rehearse(withEnv(stage.check, { ...x.env, FORGE_STAGE: stage.id }), { timeout: 120_000 });
436
+ if (!c?.ok) { drift = stage.id; dec = { run: true, why: "its check failed: the recorded effect no longer holds" }; }
437
+ }
438
+ if (dec.run && stage.services && x.sv.mode === "enforce" && !x.sv.active.length) dec = { run: false, why: "no changed services" };
439
+ if (!dec.run) { x.outputs[stage.id] = token(cp?.outputs, cp?.key); log.push({ stage: stage.id, run: false, why: dec.why }); io.print?.(`deploy ${stage.id}: skipped (${dec.why})`); continue; }
440
+ const attempt = (cp && cp.status !== "done" && cp.key === key ? cp.attempt ?? 1 : 0) + 1, t0 = now();
441
+ const lost = await beat(ctx);
442
+ if (lost) return blocked(`stage ${stage.id}: ${lost}`);
443
+ st.stage = stage.id; st.attempt = attempt; ctx.save();
444
+ io.print?.(`deploy ${stage.id}: running (${dec.why})`);
445
+ let r;
446
+ try {
447
+ r = stage.kind === "shift" ? await runShift(ctx, x, stage, key, attempt)
448
+ : stage.kind === "verify" ? await runVerify(ctx, x, stage, key, attempt, sha, d)
449
+ : await execStage(ctx, x, stage, x.env, `${stage.id}:${key.slice(0, 12)}`, attempt);
450
+ } catch (e) { r = { fail: String(e?.message ?? e).split("\n")[0] }; }
451
+ const rec = { key, parts, sha, release: state.id ?? null, at: new Date(now()).toISOString(), ms: now() - t0, attempt };
452
+ if (r.refused) return blocked(`stage ${stage.id}: ${r.refused}`);
453
+ if (r.wait) return blocked(`stage ${stage.id}: ${r.wait}`, r.hold ? { hold: r.hold } : {});
454
+ if (!r.ok) {
455
+ await x.store.put(stage.id, { ...rec, status: "failed", reason: tail(r.fail, 200) });
456
+ return onFailure(ctx, x, i, stage, r.fail);
457
+ }
458
+ let outputs = {};
459
+ if (stage.outputs_command) outputs = (await rehearseJson(io, stage.outputs_command, { ...x.env, FORGE_STAGE: stage.id })) ?? {};
460
+ else if (stage.run && stage.kind !== "shift") outputs = parseJson(String(r.output ?? "").trim().split("\n").at(-1)) ?? {};
461
+ x.outputs[stage.id] = token(outputs, key);
462
+ if (r.verify) verify = r.verify;
463
+ await x.store.put(stage.id, { ...rec, status: "done", outputs });
464
+ log.push({ stage: stage.id, run: true, why: dec.why, ms: rec.ms });
465
+ }
466
+
467
+ if (x.sv.mode === "shadow" && x.sv.unchanged.length) { // would the skip have been right? the full redeploy must leave those services as they were
468
+ const promote = ctx.promote ?? ctx.config.promote;
469
+ const live = promote?.liveDigests ? await promote.liveDigests() : eng.services.live_command ? await rehearseJson(io, eng.services.live_command, x.env) : null;
470
+ const dis = live ? diffServices(Object.fromEntries(x.sv.unchanged.map((s) => [s, x.sv.desired[s]])), live).changed : null;
471
+ st.services.agreement = dis ? { agree: x.sv.unchanged.length - dis.length, disagree: dis } : { unreadable: true };
472
+ }
473
+ delete eg.last; delete st.stage;
474
+ st.phase = "LIVE"; ctx.save();
475
+ const ran = log.filter((l) => l.run).map((l) => l.stage);
476
+ io.print?.(`release: live at ${short(sha)} (deploy engine: ran ${ran.join(", ") || "nothing"}; skipped ${log.length - ran.length})`);
477
+ return { live: true, merge: sha, run: null, reruns: 0, engine: { stages: log }, ...(verify ? { verify } : {}) };
478
+ }
479
+
480
+ const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
481
+
482
+ /**
483
+ * `forgedock release deploy --plan [<id>] [--sha S] [--json]` (read-only) and `forgedock release deploy --resume <id> [--sha S]`.
484
+ * `--sha` names a default-branch commit that contains the release's merge (a fix that landed after it), deployed under the
485
+ * same release record. @returns {Promise<number | {resume: string, sha: string|null}>} an exit code, or the resume to run.
486
+ */
487
+ export async function deployFromCli(argv, { io, load, engine, config = {}, def, repo, lctx }) {
488
+ const say = (l) => io.print(l);
489
+ const vals = ["--sha", "--repo", "--resume", "--lane"], id = flagOf(argv, "--resume") ?? argv.find((a, i) => !a.startsWith("--") && !vals.includes(argv[i - 1])) ?? null;
490
+ const plan = argv.includes("--plan"), resume = argv.includes("--resume");
491
+ if (plan === resume) { say("release deploy: pass exactly one of --plan or --resume <id>"); return 1; }
492
+ if (!engine) { say("release deploy: forge.yaml deploy.engine.enabled is not on; nothing to plan or resume (use `forgedock release --resume <id>`)"); return 1; }
493
+ const state = id ? await load(id) : null;
494
+ if (id && !state) { say(`release deploy: no release ${id}`); return 1; }
495
+ const merged = state?.steps?.["post-merge"]?.result?.merge ?? state?.deploy?.merge ?? null;
496
+ let sha = flagOf(argv, "--sha");
497
+ if (sha) {
498
+ try {
499
+ sha = String(io.git(["rev-parse", "--verify", `${sha}^{commit}`])).trim();
500
+ io.git(["merge-base", "--is-ancestor", sha, `origin/${def}`]);
501
+ if (merged) io.git(["merge-base", "--is-ancestor", merged, sha]);
502
+ } catch { say(`release deploy: --sha must be a commit on origin/${def}${merged ? ` that contains the release merge ${short(merged)}` : ""}`); return 1; }
503
+ }
504
+ if (resume) {
505
+ if (!id) { say("release deploy: --resume needs a release id"); return 1; }
506
+ if (!merged) { say(`release deploy: release ${id} is not merged yet; use \`forgedock release --resume ${id}\``); return 1; }
507
+ return { resume: id, sha: sha ?? null };
508
+ }
509
+ try { sha ??= state?.deploy?.merge ?? merged ?? String(io.git(["rev-parse", `origin/${def}`])).trim(); } catch { say(`release deploy: cannot resolve origin/${def}`); return 1; }
510
+ const p = await planStages({ io, repo, def, lctx, state: structuredClone(state ?? {}), save() {}, config: { ...config, deployEngine: engine } }, sha);
511
+ if (p.blocked) { say(`release deploy: ${p.reason}`); return 1; }
512
+ say(argv.includes("--json") ? JSON.stringify(p) : renderPlan(p));
513
+ return 0;
514
+ }