forgedock 1.56.0 → 1.58.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 (140) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +2 -1
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +48 -12
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +4 -2
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +118 -20
  14. package/bin/lean/conformance.test.mjs +172 -3
  15. package/bin/lean/decisions.mjs +98 -1
  16. package/bin/lean/decisions.test.mjs +30 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +16 -3
  32. package/bin/lean/issuewatch-parity.test.mjs +32 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +110 -24
  39. package/bin/lean/lean.test.mjs +183 -4
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +3 -2
  44. package/bin/lean/orphan-pr.test.mjs +8 -1
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +28 -3
  52. package/bin/lean/release-config.mjs +169 -0
  53. package/bin/lean/release-config.test.mjs +132 -0
  54. package/bin/lean/release-control.mjs +171 -0
  55. package/bin/lean/release-control.test.mjs +167 -0
  56. package/bin/lean/release-deploy.mjs +209 -0
  57. package/bin/lean/release-deploy.test.mjs +217 -0
  58. package/bin/lean/release-fence.mjs +50 -0
  59. package/bin/lean/release-fence.test.mjs +105 -0
  60. package/bin/lean/release-flakes.mjs +139 -0
  61. package/bin/lean/release-flakes.test.mjs +116 -0
  62. package/bin/lean/release-gates.mjs +230 -0
  63. package/bin/lean/release-gates.test.mjs +146 -0
  64. package/bin/lean/release-ledger.mjs +176 -0
  65. package/bin/lean/release-ledger.test.mjs +226 -0
  66. package/bin/lean/release-minutes.mjs +102 -0
  67. package/bin/lean/release-minutes.test.mjs +107 -0
  68. package/bin/lean/release-nightly.mjs +75 -0
  69. package/bin/lean/release-nightly.test.mjs +48 -0
  70. package/bin/lean/release-postmerge.mjs +8 -2
  71. package/bin/lean/release-review.e2e.test.mjs +1 -0
  72. package/bin/lean/release-review.mjs +54 -7
  73. package/bin/lean/release-review.test.mjs +76 -7
  74. package/bin/lean/release-status.mjs +300 -0
  75. package/bin/lean/release-status.test.mjs +220 -0
  76. package/bin/lean/release-unitmap.mjs +35 -0
  77. package/bin/lean/release-unitmap.test.mjs +41 -0
  78. package/bin/lean/release-verify.mjs +221 -0
  79. package/bin/lean/release-verify.test.mjs +176 -0
  80. package/bin/lean/release.mjs +244 -22
  81. package/bin/lean/release.test.mjs +44 -0
  82. package/bin/lean/render.mjs +3 -1
  83. package/bin/lean/run-issue-placement.test.mjs +82 -0
  84. package/bin/lean/sandbox-remote.mjs +16 -0
  85. package/bin/lean/schedd.mjs +1 -1
  86. package/bin/lean/seam.mjs +115 -0
  87. package/bin/lean/seam.test.mjs +118 -0
  88. package/bin/lean/selftest-journey.mjs +40 -2
  89. package/bin/lean/selftest-journey.test.mjs +43 -3
  90. package/bin/lean/statuscomment.mjs +168 -0
  91. package/bin/lean/statuscomment.test.mjs +133 -0
  92. package/bin/lean/ui-quality.mjs +57 -0
  93. package/bin/lean/ui-quality.test.mjs +55 -0
  94. package/bin/lean/visual-gate.test.mjs +63 -0
  95. package/bin/pool/agent.mjs +16 -2
  96. package/bin/pool/router.mjs +5 -1
  97. package/bin/review-staging.mjs +5 -3
  98. package/bin/stats/card.mjs +117 -0
  99. package/bin/stats/card.test.mjs +109 -0
  100. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  101. package/bin/stats/depth.mjs +1 -1
  102. package/bin/stats/gh-retry.test.mjs +152 -0
  103. package/bin/stats/github-source.mjs +147 -14
  104. package/bin/stats/index.mjs +35 -2
  105. package/bin/stats/stats.test.mjs +31 -3
  106. package/bin/vendor/js-yaml/LICENSE +21 -0
  107. package/bin/vendor/js-yaml/PIN.md +7 -0
  108. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  109. package/commands/design-render-critique-loop.md +2 -0
  110. package/commands/design.md +2 -0
  111. package/commands/issue.md +1 -1
  112. package/commands/milestone.md +1 -1
  113. package/commands/review-pr-agents/frontend.md +1 -0
  114. package/commands/review-pr-staging.md +5 -0
  115. package/docs/CONFIG.md +95 -2
  116. package/docs/ISSUE-WATCH.md +7 -0
  117. package/docs/OUTCOME-CODES.md +1 -0
  118. package/docs/STATS.md +10 -0
  119. package/docs/design/visual-gate.md +25 -0
  120. package/docs/eval/adversarial-bench.md +2 -2
  121. package/docs/eval/corpus/adversarial-v1.json +3 -3
  122. package/docs/site/start-a-new-project.md +7 -0
  123. package/docs/spec/forge-protocol-v1.md +31 -0
  124. package/package.json +1 -1
  125. package/pool/README.md +2 -0
  126. package/scripts/acceptance-red-green.sh +15 -1
  127. package/scripts/acceptance-red-green.test.sh +12 -0
  128. package/scripts/bench-adversarial.mjs +4 -0
  129. package/scripts/bench-lightlane.mjs +4 -1
  130. package/scripts/bootstrap-create.mjs +8 -2
  131. package/scripts/ci-local/scoping.mjs +19 -0
  132. package/scripts/ci-local.test.sh +16 -3
  133. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  134. package/scripts/plan-validate-live.mjs +9 -6
  135. package/scripts/review-prepare.sh +7 -1
  136. package/scripts/review-roster.sh +5 -2
  137. package/scripts/review-roster.test.sh +9 -0
  138. package/scripts/visual-gate.mjs +64 -0
  139. package/templates/bootstrap/technical-spike.md +17 -0
  140. package/templates/contracts/seam-check.mjs +236 -0
@@ -0,0 +1,171 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * One audited control verb set (#5556, epic #5549 Phase 0, invariants I15/I20/I24/I26): `forgedock release control <verb>`
5
+ * (hold, resume, cancel, lane, exempt, freeze, unfreeze); `forgedock release <verb>` is an alias of the same `runControl`.
6
+ * Every mutation needs `--reason`, is one key-scoped `updateActive` commit (state in `_active.json`, one `controls.jsonl`
7
+ * line {at, actor, host, verb, reason, before, after, epoch}) and posts a `FORGE:CONTROL` comment on the tracker (the lease's
8
+ * issue). `holdCheck` is read by `fenced()` before every irreversible action, so every driver obeys a hold (I24).
9
+ * `buildDispatchArgs` is the only workflow-dispatch builder: it never carries a human break-glass input (I26).
10
+ */
11
+ import { hostname } from "node:os";
12
+ import { readActive, readLedger, updateActive } from "./release-ledger.mjs";
13
+ import { isSafetyGate, parseGatesConfig, DEMOTE_MODES } from "./release-gates.mjs";
14
+ import { UNSKIPPABLE_CLASSES, isUnskippable, parseFlakeConfig, canQuarantine } from "./release-flakes.mjs";
15
+
16
+ export const CONTROL_SCHEMA = "forgedock.release.control/v1";
17
+ export const CONTROL_MARKER = "FORGE:CONTROL";
18
+ export const VERBS = ["hold", "resume", "cancel", "lane", "exempt", "freeze", "unfreeze", "demote", "promote"];
19
+ export { UNSKIPPABLE_CLASSES as UNSKIPPABLE };
20
+ export const EXEMPT_MAX_H = { skip: 24, quarantine: 14 * 24 };
21
+ export const LANES = ["train", "release", "p0", "exclude"];
22
+ const OWNED = ["holds", "cancelled", "lanes", "exemptions", "freeze", "gateModes"];
23
+ export const DEMOTE_MAX_H = 30 * 24;
24
+ const BREAK_GLASS = /^(override_freeze|acknowledge_hotfix_revert|override_.*|acknowledge_.*)$/;
25
+
26
+ /** Argv of `gh workflow run`; rejects a break-glass input (I26). */
27
+ export function buildDispatchArgs({ workflow, repo, ref, inputs = {} }) {
28
+ for (const k of Object.keys(inputs)) if (BREAK_GLASS.test(k)) throw new Error(`dispatch input ${k} is a human break-glass input; the engine never sets it (I26)`);
29
+ return ["workflow", "run", workflow, "--repo", repo, "--ref", ref, ...Object.entries(inputs).flatMap(([k, v]) => ["-f", `${k}=${v}`])];
30
+ }
31
+
32
+ /** The release-PR-body section listing live exemptions (I20: a demoted check appears in the PR body); "" when none. */
33
+ export function exemptionsSection(exemptions, now = Date.now()) {
34
+ const live = Object.entries(exemptions ?? {}).filter(([, e]) => e?.until && Date.parse(e.until) > now);
35
+ if (!live.length) return "";
36
+ return `\n\n<!-- FORGE:EXEMPT -->\n### Exempted checks\n${live.map(([c, e]) => `- \`${c}\` (${e.mode}) until ${e.until}, issue #${e.issue}, by ${e.actor}: ${e.reason}`).join("\n")}\n`;
37
+ }
38
+
39
+ /** Why release `id` must not act (held or cancelled), else null. Throws when `_active` cannot be read (callers refuse, I5). */
40
+ export async function holdCheck(lctx, id) {
41
+ const a = await readActive(lctx);
42
+ const h = a.holds?.[id] ?? a.holds?.["*"];
43
+ if (h) return `held (${h.reason ?? "no reason"})`;
44
+ if (a.cancelled?.[id]) return `cancelled (${a.cancelled[id].reason ?? "no reason"})`;
45
+ return null;
46
+ }
47
+
48
+ const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
49
+ const FLAGS = ["--repo", "--reason", "--mode", "--issue", "--until", "--force", "--fixture"];
50
+ const positionals = (argv) => argv.filter((a, i) => !a.startsWith("--") && !FLAGS.includes(argv[i - 1]));
51
+ const ttlHours = (s) => { const m = /^(\d+)([hd])$/.exec(String(s ?? "")); return m ? Number(m[1]) * (m[2] === "d" ? 24 : 1) : null; };
52
+
53
+ /**
54
+ * Run one control verb. `argv` is what follows the verb. `ctx`: {io, repo, policy, actor, host, now}.
55
+ * @returns {{schema, ok: boolean, verb, error?, ...}}; never throws for a refusal.
56
+ */
57
+ export async function runControl(verb, argv, ctx) {
58
+ const { io, repo, policy = null } = ctx;
59
+ const fail = (error) => ({ schema: CONTROL_SCHEMA, ok: false, verb, error });
60
+ if (!VERBS.includes(verb)) return fail(`unknown control verb ${verb}; one of ${VERBS.join("|")}`);
61
+ const reason = flagOf(argv, "--reason");
62
+ if (!reason || !reason.trim() || reason.startsWith("--")) return fail(`${verb}: --reason is required`);
63
+ const actor = ctx.actor ?? process.env.GITHUB_ACTOR ?? process.env.USER ?? "unknown", host = ctx.host ?? hostname();
64
+ const pos = positionals(argv);
65
+ const lctx = { io, repo, credential: "driver" };
66
+ const at = new Date(ctx.now ?? Date.now()).toISOString();
67
+ let apply; // (active) => {patch, before, after} | {refuse}
68
+ let after = null;
69
+ if (verb === "hold" || verb === "resume" || verb === "cancel") {
70
+ const id = pos[0];
71
+ if (!id) return fail(`${verb}: release id required`);
72
+ if (verb === "cancel") {
73
+ const led = await readLedger(lctx, id).catch(() => null);
74
+ const s = led?.state;
75
+ if (!s) return fail(`cancel: no ledger for release ${id}`);
76
+ if (s.steps?.promotion?.result?.merged || s.steps?.["post-merge"]?.done || s.status === "MERGED") return fail(`cancel: release ${id} is already MERGED; the only exits are LIVE or rollback`);
77
+ }
78
+ const key = verb === "cancel" ? "cancelled" : "holds";
79
+ apply = (a) => {
80
+ const before = a[key]?.[id] ?? null, next = { ...(a[key] ?? {}) };
81
+ if (verb === "resume") delete next[id]; else next[id] = { reason, actor, at };
82
+ return { patch: { [key]: next }, before, after: next[id] ?? null };
83
+ };
84
+ } else if (verb === "lane") {
85
+ const force = flagOf(argv, "--force");
86
+ if (!LANES.includes(force)) return fail(`lane: --force must be one of ${LANES.join("|")}`);
87
+ const issues = pos.map((p) => p.replace(/^#/, "")).filter((p) => /^\d+$/.test(p));
88
+ if (!issues.length) return fail("lane: at least one #issue required");
89
+ apply = (a) => {
90
+ const next = { ...(a.lanes ?? {}) }, before = {};
91
+ for (const n of issues) { before[n] = next[n] ?? null; next[n] = { force, reason, actor, at }; }
92
+ return { patch: { lanes: next }, before, after: Object.fromEntries(issues.map((n) => [n, force])) };
93
+ };
94
+ } else if (verb === "exempt") {
95
+ const check = pos[0], mode = flagOf(argv, "--mode"), issue = flagOf(argv, "--issue"), hours = ttlHours(flagOf(argv, "--until"));
96
+ if (!check) return fail("exempt: check or test name required");
97
+ if (!(mode in EXEMPT_MAX_H)) return fail("exempt: --mode must be skip or quarantine");
98
+ if (!/^#?\d+$/.test(issue ?? "")) return fail("exempt: --issue N is required");
99
+ if (hours == null) return fail("exempt: --until <Nh|Nd> is required");
100
+ if (hours > EXEMPT_MAX_H[mode]) return fail(`exempt: ${mode} expires in at most ${EXEMPT_MAX_H[mode]}h (got ${hours}h)`);
101
+ const cfg = parseFlakeConfig(policy);
102
+ if (isUnskippable(check, cfg.unskippable)) return fail(`exempt: ${check} is an unskippable class (${cfg.unskippable.join(", ")}) (I20)`);
103
+ const trusted = policy?.trust?.actors ?? [];
104
+ if (trusted.length && !trusted.includes(actor)) return fail(`exempt: actor ${actor} is not trusted (policy trust.actors)`);
105
+ const num = String(issue).replace("#", "");
106
+ let iv = null;
107
+ try { iv = JSON.parse(String(await io.gh(["issue", "view", num, "--repo", repo, "--json", "number,state,labels"]))); } catch { /* unreadable: refused below */ }
108
+ if (!iv || String(iv.number) !== num) return fail(`exempt: issue #${num} does not exist or is unreadable`);
109
+ const nowMs = ctx.now ?? Date.now(), labels = (iv.labels ?? []).map((l) => l.name ?? l);
110
+ const entry = { mode, issue: num, reason, actor, at, until: new Date(nowMs + hours * 3_600_000).toISOString() };
111
+ apply = (a) => {
112
+ if (mode === "quarantine") {
113
+ const q = canQuarantine({ target: check, exemptions: a.exemptions, issueLabels: labels, issueOpen: String(iv.state).toUpperCase() === "OPEN", cfg, now: nowMs });
114
+ if (!q.ok) return { refuse: `exempt: ${q.why}` };
115
+ }
116
+ return { patch: { exemptions: { ...(a.exemptions ?? {}), [check]: entry } }, before: a.exemptions?.[check] ?? null, after: entry };
117
+ };
118
+ } else if (verb === "demote" || verb === "promote") { // #5583: false-block policy on a deploy gate, same audited path
119
+ const gate = pos[0];
120
+ if (!gate) return fail(`${verb}: gate id required`);
121
+ if (verb === "demote") {
122
+ const mode = flagOf(argv, "--mode"), issue = flagOf(argv, "--issue"), hours = ttlHours(flagOf(argv, "--until"));
123
+ if (!DEMOTE_MODES.includes(mode)) return fail(`demote: --mode must be ${DEMOTE_MODES.join(" or ")}`);
124
+ if (!/^#?\d+$/.test(issue ?? "")) return fail("demote: --issue N is required");
125
+ if (hours == null) return fail("demote: --until <Nh|Nd> is required");
126
+ if (hours > DEMOTE_MAX_H) return fail(`demote: expires in at most ${DEMOTE_MAX_H}h (got ${hours}h)`);
127
+ if (isSafetyGate(gate, parseGatesConfig(policy).safety)) return fail(`demote: ${gate} is on the safety allowlist and is never demoted`);
128
+ const entry = { mode, issue: String(issue).replace("#", ""), reason, actor, at, until: new Date((ctx.now ?? Date.now()) + hours * 3_600_000).toISOString() };
129
+ apply = (a) => ({ patch: { gateModes: { ...(a.gateModes ?? {}), [gate]: entry } }, before: a.gateModes?.[gate] ?? null, after: entry });
130
+ } else {
131
+ const fixture = flagOf(argv, "--fixture");
132
+ if (!fixture || !fixture.trim() || fixture.startsWith("--")) return fail("promote: --fixture <ref> is required (re-promotion needs a fixture reference)");
133
+ apply = (a) => {
134
+ if (!a.gateModes?.[gate]) return { refuse: `promote: ${gate} is not demoted` };
135
+ const next = { ...a.gateModes }; delete next[gate];
136
+ return { patch: { gateModes: next }, before: a.gateModes[gate], after: { promoted: true, fixture } };
137
+ };
138
+ }
139
+ } else { // freeze | unfreeze: the repo's own deploy variable (6.4), not a second mechanism
140
+ const name = policy?.deploy?.freeze_variable;
141
+ if (!name) return fail(`${verb}: policy deploy.freeze_variable is not set`);
142
+ apply = (a) => ({ patch: { freeze: verb === "freeze" ? { variable: name, reason, actor, at } : null }, before: a.freeze ?? null, after: verb === "freeze" ? { variable: name } : null });
143
+ ctx.afterCommit = async () => { await io.gh(verb === "freeze" ? ["variable", "set", name, "--repo", repo, "--body", "1"] : ["variable", "delete", name, "--repo", repo]); };
144
+ }
145
+ let line;
146
+ const r = await updateActive(lctx, OWNED, (a) => {
147
+ const o = apply(a);
148
+ if (o.refuse) return { refuse: o.refuse };
149
+ after = o.after;
150
+ line = { at, actor, host, verb, reason, before: o.before ?? null, after: o.after ?? null, epoch: a.epoch ?? null };
151
+ return { patch: o.patch, control: line };
152
+ });
153
+ if (!r.ok) return fail(r.refused ?? `could not commit the control (lost the race after ${r.attempts} attempts)`);
154
+ if (ctx.afterCommit) await ctx.afterCommit();
155
+ const issue = r.active.lease?.issue;
156
+ let comment = null;
157
+ if (issue) {
158
+ const body = `<!-- ${CONTROL_MARKER} -->\n**${verb}** by ${actor}@${host} at ${at} (epoch ${line.epoch ?? "none"})\nreason: ${reason}\n\n<!-- ${CONTROL_MARKER} ${JSON.stringify(line)} -->`;
159
+ comment = (await io.api("POST", `repos/${repo}/issues/${issue}/comments`, { body }))?.id ?? null;
160
+ }
161
+ return { schema: CONTROL_SCHEMA, ok: true, verb, entry: line, comment };
162
+ }
163
+
164
+ /** CLI: `[--repo R] [--json]` plus the verb's flags; prints one line or the JSON result; @returns the exit code. */
165
+ export async function controlFromCli(verb, argv, { io, policy, actor, host }) {
166
+ const repo = flagOf(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
167
+ const r = await runControl(verb, argv.filter((a) => a !== "--json"), { io, repo, policy, actor, host, now: io.now?.() });
168
+ if (argv.includes("--json")) io.print(JSON.stringify(r));
169
+ else io.print(r.ok ? `release ${verb}: recorded (${r.entry.at})` : `release ${verb}: refused: ${r.error}`);
170
+ return r.ok ? 0 : 1;
171
+ }
@@ -0,0 +1,167 @@
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 { runControl, controlFromCli, buildDispatchArgs, holdCheck, exemptionsSection, CONTROL_SCHEMA } from "./release-control.mjs";
6
+ import { fenced } from "./release-fence.mjs";
7
+
8
+ // A tiny in-memory GitHub: _active branch (active.json + controls.jsonl) and one release ledger.
9
+ function world({ active = { epoch: 1, lease: { holder: "A", epoch: 1, release: "r20260101-000000-1", issue: 9 } }, state = null } = {}) {
10
+ const w = { active, controls: "", comments: [], vars: [], gh: [], files: {}, sha: 0 };
11
+ w.io = {
12
+ now: () => 1_700_000_000_000, print: (l) => (w.out ??= []).push(l),
13
+ gh: async (a) => { w.gh.push(a); if (a[0] === "repo") return JSON.stringify({ nameWithOwner: "o/r" }); if (a[0] === "variable") w.vars.push(a); if (a[0] === "issue" && a[1] === "view") return a[2] === "404" ? "" : JSON.stringify({ number: Number(a[2]), state: "OPEN", labels: [{ name: "flake" }] }); return ""; },
14
+ api: async (method, path, body) => {
15
+ if (method === "GET" && /git\/ref\/heads\/_active$/.test(path)) return { object: { sha: "h0" } };
16
+ if (method === "GET" && /contents\/active\.json/.test(path)) return { content: Buffer.from(JSON.stringify(w.active)).toString("base64") };
17
+ if (method === "GET" && /contents\/controls\.jsonl/.test(path)) return { content: Buffer.from(w.controls).toString("base64") };
18
+ if (method === "GET" && /git\/commits\//.test(path)) return { tree: { sha: "t0" } };
19
+ if (method === "POST" && /git\/trees/.test(path)) { for (const t of body.tree) w.files[t.path] = t.content; return { sha: "t1" }; }
20
+ if (method === "POST" && /git\/commits/.test(path)) return { sha: `c${++w.sha}` };
21
+ if (method === "PATCH" && /git\/refs/.test(path)) { w.active = JSON.parse(w.files["active.json"]); w.controls = w.files["controls.jsonl"] ?? w.controls; return {}; }
22
+ if (method === "POST" && /issues\/\d+\/comments/.test(path)) { w.comments.push(body.body); return { id: w.comments.length }; }
23
+ throw new Error(`unrouted ${method} ${path}`);
24
+ },
25
+ };
26
+ return w;
27
+ }
28
+ const RID = "r20260101-000000-1";
29
+ const base = (w, extra = {}) => ({ io: w.io, repo: "o/r", actor: "op", host: "h1", now: 1_700_000_000_000, ...extra });
30
+
31
+ describe("release control (#5556)", () => {
32
+ it("every mutation needs --reason (I15)", async () => {
33
+ const w = world();
34
+ for (const [v, a] of [["hold", [RID]], ["resume", [RID]], ["cancel", [RID]], ["lane", ["#1", "--force", "p0"]], ["exempt", ["lint", "--mode", "skip", "--issue", "3", "--until", "2h"]], ["freeze", []], ["unfreeze", []]]) {
35
+ const r = await runControl(v, a, base(w, { policy: { deploy: { freeze_variable: "DEPLOY_FREEZE" } } }));
36
+ assert.equal(r.ok, false, v); assert.match(r.error, /--reason is required/);
37
+ }
38
+ assert.equal(w.comments.length, 0);
39
+ });
40
+
41
+ it("exempt of an unskippable class (migration) is rejected; so is a policy-added one", async () => {
42
+ const w = world();
43
+ const a = ["--mode", "skip", "--issue", "3", "--until", "2h", "--reason", "x"];
44
+ assert.match((await runControl("exempt", ["migration", ...a], base(w))).error, /unskippable/);
45
+ for (const c of ["security", "rollback", "backup-restore", "secrets"]) assert.equal((await runControl("exempt", [c, ...a], base(w))).ok, false);
46
+ assert.equal((await runControl("exempt", ["custom", ...a], base(w, { policy: { ci: { unskippable: ["custom"] } } }))).ok, false);
47
+ assert.equal(w.controls, "");
48
+ });
49
+
50
+ it("exempt: mode ttl caps, required issue, trusted actor", async () => {
51
+ const w = world();
52
+ const ok = ["lint", "--mode", "skip", "--issue", "3", "--until", "24h", "--reason", "flaky"];
53
+ assert.match((await runControl("exempt", ["lint", "--mode", "skip", "--issue", "3", "--until", "25h", "--reason", "r"], base(w))).error, /at most 24h/);
54
+ assert.match((await runControl("exempt", ["lint", "--mode", "quarantine", "--issue", "3", "--until", "15d", "--reason", "r"], base(w))).error, /at most 336h/);
55
+ assert.match((await runControl("exempt", ["lint", "--mode", "skip", "--until", "1h", "--reason", "r"], base(w))).error, /--issue/);
56
+ assert.match((await runControl("exempt", ok, base(w, { policy: { trust: { actors: ["boss"] } } }))).error, /not trusted/);
57
+ assert.equal((await runControl("exempt", ["lint", "--mode", "quarantine", "--issue", "3", "--until", "14d", "--reason", "r"], base(w))).ok, true);
58
+ assert.equal((await runControl("exempt", ok, base(w, { policy: { trust: { actors: ["op"] } } }))).ok, true);
59
+ });
60
+
61
+ it("exempt without an existing issue is refused (#5568)", async () => {
62
+ const w = world();
63
+ const r = await runControl("exempt", ["lint", "--mode", "skip", "--issue", "404", "--until", "2h", "--reason", "x"], base(w));
64
+ assert.equal(r.ok, false); assert.match(r.error, /does not exist/);
65
+ assert.equal(w.controls, "");
66
+ });
67
+
68
+ it("quarantine is refused at the cap and without a flake-labelled issue, and a live one shows in the PR body (#5568)", async () => {
69
+ const at = new Date(1_700_000_000_000).toISOString(), until = new Date(1_700_000_000_000 + 3_600_000).toISOString();
70
+ const full = Object.fromEntries(Array.from({ length: 2 }, (_, i) => [`t${i}`, { mode: "quarantine", issue: "3", at, until }]));
71
+ const w = world({ active: { epoch: 1, lease: { holder: "A", epoch: 1, release: RID, issue: 9 }, exemptions: full } });
72
+ const a = ["--mode", "quarantine", "--issue", "3", "--until", "1d", "--reason", "x"];
73
+ assert.match((await runControl("exempt", ["new", ...a], base(w, { policy: { quarantine: { max: 2 } } }))).error, /cap 2/);
74
+ const gh = w.io.gh;
75
+ w.io.gh = async (x) => (x[0] === "issue" ? JSON.stringify({ number: 3, state: "OPEN", labels: [] }) : gh(x));
76
+ assert.match((await runControl("exempt", ["new", ...a], base(w))).error, /labelled flake/);
77
+ w.io.gh = gh;
78
+ const ok = await runControl("exempt", ["new", ...a], base(w));
79
+ assert.equal(ok.ok, true);
80
+ assert.match(exemptionsSection(w.active.exemptions, 1_700_000_000_000), /FORGE:EXEMPT[\s\S]*`new` \(quarantine\)/);
81
+ assert.equal(exemptionsSection({}, 0), "");
82
+ });
83
+
84
+ it("a mutation appends the audit line and posts a FORGE:CONTROL comment", async () => {
85
+ const w = world();
86
+ const r = await runControl("hold", [RID, "--reason", "pause for incident"], base(w));
87
+ assert.equal(r.schema, CONTROL_SCHEMA); assert.equal(r.ok, true);
88
+ const line = JSON.parse(w.controls.trim().split("\n").pop());
89
+ assert.deepEqual({ ...line, after: undefined }, { at: "2023-11-14T22:13:20.000Z", actor: "op", host: "h1", verb: "hold", reason: "pause for incident", before: null, after: undefined, epoch: 1 });
90
+ assert.equal(line.after.reason, "pause for incident");
91
+ assert.match(w.comments[0], /FORGE:CONTROL/);
92
+ assert.equal(w.active.holds[RID].actor, "op");
93
+ });
94
+
95
+ it("hold is obeyed: fenced() refuses every irreversible action; resume lifts it", async () => {
96
+ const w = world();
97
+ const fence = { lctx: { io: w.io, repo: "o/r", credential: "driver" }, lease: w.active.lease, now: () => "t", record: async () => {} };
98
+ let ran = 0;
99
+ assert.equal((await fenced(fence, { action: "merge", key: "k" }, async () => { ran++; })).ok, true);
100
+ await runControl("hold", [RID, "--reason", "r"], base(w));
101
+ assert.match(await holdCheck(fence.lctx, RID), /held/);
102
+ const r = await fenced(fence, { action: "merge", key: "k2" }, async () => { ran++; });
103
+ assert.match(r.refused, /held/); assert.equal(ran, 1);
104
+ await runControl("resume", [RID, "--reason", "done"], base(w));
105
+ assert.equal((await fenced(fence, { action: "merge", key: "k3" }, async () => { ran++; })).ok, true);
106
+ assert.equal(ran, 2);
107
+ });
108
+
109
+ it("cancel is refused once MERGED", async () => {
110
+ const w = world();
111
+ const orig = w.io.api;
112
+ w.io.api = async (m, p, b) => (/forge-ledger%2F|contents\/state\.json/.test(p) && m === "GET" && /state\.json/.test(p)
113
+ ? { content: Buffer.from(JSON.stringify({ v: 1, id: RID, steps: { promotion: { done: true, result: { merged: true } } } })).toString("base64") } : orig(m, p, b));
114
+ const r = await runControl("cancel", [RID, "--reason", "r"], base(w));
115
+ assert.equal(r.ok, false); assert.match(r.error, /MERGED|no ledger/);
116
+ });
117
+
118
+ it("lane force and freeze/unfreeze (the repo's own variable)", async () => {
119
+ const w = world();
120
+ assert.equal((await runControl("lane", ["#4", "#5", "--force", "exclude", "--reason", "r"], base(w))).ok, true);
121
+ assert.equal(w.active.lanes["4"].force, "exclude");
122
+ assert.match((await runControl("lane", ["#4", "--force", "bogus", "--reason", "r"], base(w))).error, /--force/);
123
+ assert.match((await runControl("freeze", ["--reason", "r"], base(w))).error, /freeze_variable/);
124
+ const policy = { deploy: { freeze_variable: "DEPLOY_FREEZE" } };
125
+ assert.equal((await runControl("freeze", ["--reason", "r"], base(w, { policy }))).ok, true);
126
+ assert.deepEqual(w.vars[0], ["variable", "set", "DEPLOY_FREEZE", "--repo", "o/r", "--body", "1"]);
127
+ assert.equal((await runControl("unfreeze", ["--reason", "r"], base(w, { policy }))).ok, true);
128
+ assert.equal(w.vars[1][1], "delete");
129
+ });
130
+
131
+ it("I26: a dispatch with override_freeze or acknowledge_hotfix_revert is rejected", () => {
132
+ assert.throws(() => buildDispatchArgs({ workflow: "p.yml", repo: "o/r", ref: "main", inputs: { override_freeze: "true" } }), /break-glass/);
133
+ assert.throws(() => buildDispatchArgs({ workflow: "p.yml", repo: "o/r", ref: "main", inputs: { acknowledge_hotfix_revert: "1" } }), /break-glass/);
134
+ assert.deepEqual(buildDispatchArgs({ workflow: "p.yml", repo: "o/r", ref: "main", inputs: { forge_epoch: 2 } }), ["workflow", "run", "p.yml", "--repo", "o/r", "--ref", "main", "-f", "forge_epoch=2"]);
135
+ });
136
+
137
+ it("CLI: --json prints the stable schema; --repo is accepted; exit 1 on a refusal", async () => {
138
+ const w = world();
139
+ assert.equal(await controlFromCli("hold", [RID, "--repo", "o/r", "--reason", "r", "--json"], { io: w.io, actor: "op", host: "h" }), 0);
140
+ assert.equal(JSON.parse(w.out[0]).schema, CONTROL_SCHEMA);
141
+ assert.equal(await controlFromCli("hold", [RID, "--json"], { io: w.io }), 1);
142
+ });
143
+ });
144
+
145
+ describe("demote / promote (#5583)", () => {
146
+ const dem = (g, extra = []) => [g, "--mode", "warn", "--issue", "7", "--until", "14d", "--reason", "fb", ...extra];
147
+ it("demote records an expiry and an audit line; promote needs a fixture", async () => {
148
+ const w = world();
149
+ const r = await runControl("demote", dem("smoke"), base(w));
150
+ assert.equal(r.ok, true);
151
+ assert.equal(r.entry.verb, "demote");
152
+ assert.equal(w.active.gateModes.smoke.until, new Date(1_700_000_000_000 + 14 * 86_400_000).toISOString());
153
+ assert.match(w.controls, /"verb":"demote"/);
154
+ const no = await runControl("promote", ["smoke", "--reason", "ok"], base(w));
155
+ assert.match(no.error, /--fixture/);
156
+ assert.ok(w.active.gateModes.smoke);
157
+ assert.equal((await runControl("promote", ["smoke", "--fixture", "tests/f.json", "--reason", "ok"], base(w))).ok, true);
158
+ assert.equal(w.active.gateModes.smoke, undefined);
159
+ });
160
+ it("refuses a safety-allowlisted or unskippable gate, a bad mode and a long expiry", async () => {
161
+ const w = world();
162
+ for (const g of ["backup-freshness", "migration", "secrets:x"]) assert.match((await runControl("demote", dem(g), base(w))).error, /safety allowlist/);
163
+ assert.match((await runControl("demote", ["g", "--mode", "skip", "--issue", "7", "--until", "1d", "--reason", "r"], base(w))).error, /--mode/);
164
+ assert.match((await runControl("demote", ["g", "--mode", "warn", "--issue", "7", "--until", "90d", "--reason", "r"], base(w))).error, /at most/);
165
+ assert.match((await runControl("promote", ["g", "--fixture", "f", "--reason", "r"], base(w))).error, /not demoted/);
166
+ });
167
+ });
@@ -0,0 +1,209 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Deploy stages of `forgedock release` (#5560, epic #5549 Phase 3): MERGED -> DEPLOYING -> LIVE_CHECK -> RECOVERING -> VERIFYING -> LIVE (verification layers, FORGE:VERIFIED and close-after-verified live in release-verify.mjs, #5562).
5
+ * Off unless the policy has `deploy.pipelines` (`ctx.config.deploy`): without it the step is `{skipped}` and leaves no trace.
6
+ * Every step is observe -> decide -> fenced act -> verify, and progress lives in `state.deploy`, so a resume re-observes GitHub
7
+ * (the run, the live record, the freeze variable) before it acts and repeats no dispatch or rerun. Waits are bounded and end in
8
+ * `{blocked}`, never a throw. The engine never sets a break-glass input and never reruns a deploy while a freeze is set (I26);
9
+ * a run that concluded `success` while live is not the merge sha (or the expected digests) is a failed deploy (I28); no deploy
10
+ * starts without a recorded rollback target (I9). Rationale: devdocs/decisions/5560-release-deploy.md.
11
+ */
12
+ import { fenced } from "./release-fence.mjs";
13
+ import { buildDispatchArgs } from "./release-control.mjs";
14
+ import { INFRA_SIGNATURES } from "./release-flakes.mjs";
15
+ import { verifyStep, verifyConfigured } from "./release-verify.mjs";
16
+
17
+ export const BOUNDS = { pollMs: 10_000, runPollMs: 20_000, defaultStageS: 3600, rerunMax: 2, maxAttempts: 3 };
18
+ const json = (s) => JSON.parse(String(s || "null"));
19
+ const blocked = (reason) => ({ blocked: true, reason });
20
+ const tail = (s, n = 400) => String(s ?? "").trim().slice(-n);
21
+
22
+ /** `{sha, images}` from the live-release command output: JSON `{sha, images|units: {unit: digest}}` or a bare sha. */
23
+ export function parseLiveRelease(out) {
24
+ const t = String(out ?? "").trim();
25
+ if (!t) return null;
26
+ if (t.startsWith("{")) { try { const o = JSON.parse(t); return o?.sha ? { sha: String(o.sha), images: o.images ?? o.units ?? {} } : null; } catch { return null; } }
27
+ const sha = t.split(/\s+/)[0];
28
+ return /^[0-9a-f]{7,64}$/i.test(sha) ? { sha, images: {} } : null;
29
+ }
30
+
31
+ const sameSha = (a, b) => !!a && !!b && (a.startsWith(b) || b.startsWith(a));
32
+
33
+ /** LIVE_CHECK (I28): the digests decide when expected ones are recorded, else the sha. */
34
+ export function liveMatches(live, mergeSha, expected) {
35
+ if (!live) return false;
36
+ const units = Object.entries(expected ?? {});
37
+ return units.length ? units.every(([u, d]) => live.images?.[u] === d) : sameSha(live.sha, mergeSha);
38
+ }
39
+
40
+ async function readTarget(io, cmd) {
41
+ if (!cmd) return null;
42
+ const r = await io.rehearse(cmd, { timeout: 120_000 });
43
+ return r?.ok ? parseLiveRelease(r.output) : null;
44
+ }
45
+
46
+ /** The freeze variable's value ("" when unset or unreadable-as-absent). A gh failure means unset: `gh variable get` exits non-zero for a missing variable. */
47
+ async function freezeValue(io, repo, name) {
48
+ if (!name) return "";
49
+ try { return String(await io.gh(["variable", "get", name, "--repo", repo])).trim(); } catch { return ""; }
50
+ }
51
+
52
+ /** The newest run for `(workflow, sha)`; a `skipped` run (a push the workflow chose not to run) is expected and not a run. */
53
+ async function latestRun({ io, repo, workflow, sha }) {
54
+ const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--commit", sha, "--json", "databaseId,status,conclusion", "--limit", "5"])) ?? [];
55
+ return runs.find((r) => r.conclusion !== "skipped") ?? null;
56
+ }
57
+
58
+ /** A cancelled run is a concurrency-group supersede (expected) when the workflow has a newer run. */
59
+ async function superseded({ io, repo, workflow }, run) {
60
+ const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--json", "databaseId,status", "--limit", "10"])) ?? [];
61
+ return runs.some((r) => r.databaseId > run.databaseId);
62
+ }
63
+
64
+ async function poll(io, polls, ms, fn) {
65
+ for (let i = 0; i < polls; i++) {
66
+ const v = await fn();
67
+ if (v) return v;
68
+ if (i < polls - 1) await io.sleep(ms);
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /** Intent key `(release, step, epoch, what)`: one irreversible action per epoch, named in the write-ahead intent (R10). */
74
+ const idemKey = (ctx, what) => `${ctx.fence?.lease?.release ?? ctx.state.id ?? "-"}:deploy:${ctx.fence?.lease?.epoch ?? 0}:${what}`;
75
+
76
+ /** A dispatch (fenced, write-ahead intent) and the run it makes; observe first so a crashed driver never dispatches twice. */
77
+ export async function runFor(ctx, { workflow, sha, inputs, key, startPolls, b }) {
78
+ const { io, repo } = ctx;
79
+ const look = () => latestRun({ io, repo, workflow, sha });
80
+ let run = await poll(io, startPolls, b.pollMs, look);
81
+ if (run) return { run, dispatched: false };
82
+ if ((ctx.state.intents ?? []).some((i) => i.action === "dispatch" && String(i.key).endsWith(`:${key}`))) { // a dispatch intent (any epoch, done or not) may have taken effect: wait for its run, never repeat it (I7)
83
+ run = await poll(io, Math.max(startPolls, Math.ceil((ctx.config.deploy?.start_timeout_s ?? 60) * 1000 / b.pollMs)), b.pollMs, look);
84
+ return run ? { run, dispatched: false } : { err: `a ${workflow} dispatch for ${sha.slice(0, 8)} was already recorded but no run appeared; check the Actions tab, then resume (never redispatched)` };
85
+ }
86
+ const f = await fenced(ctx.fence, { action: "dispatch", key: idemKey(ctx, key) }, (epoch) => io.gh(buildDispatchArgs({ workflow, repo, ref: ctx.def, inputs: { ...inputs, ...(epoch != null ? { forge_epoch: epoch } : {}) } })));
87
+ if (f.refused) return { err: `dispatch ${f.refused}` };
88
+ run = await poll(io, startPolls, b.pollMs, look);
89
+ return run ? { run, dispatched: true } : { err: `no ${workflow} run for ${sha.slice(0, 8)} after a dispatch on ${ctx.def}; check the Actions tab, then resume` };
90
+ }
91
+
92
+ export async function finished(ctx, workflow, sha, polls, b) {
93
+ const { io, repo } = ctx;
94
+ return poll(io, polls, b.runPollMs, async () => { const r = await latestRun({ io, repo, workflow, sha }); return r?.status === "completed" ? r : null; });
95
+ }
96
+
97
+ /** transient: shared infra signatures (release-flakes) or configured ones; migration: a rehearsal-class failure; else a deterministic build failure. */
98
+ export function classifyDeploy(log, sigs) {
99
+ if (INFRA_SIGNATURES.some(([, re]) => re.test(log)) || (sigs ?? []).some((s) => { try { return new RegExp(s, "i").test(log); } catch { return log.includes(s); } })) return "transient";
100
+ return /migrat/i.test(log) ? "migration" : "deterministic";
101
+ }
102
+
103
+ const hold = (reason, kind) => ({ blocked: `${reason} (owner ask: decide rollback or fix; label needs-agent when no host is attached)`, hold: { kind, label: "needs-agent" } });
104
+
105
+ /**
106
+ * Recovery (6.5): one action at a time, bounded. @returns {{rerun: true}|{blocked: string}}
107
+ * No rerun while a freeze is set (I26); only a failed run with a configured transient log signature is rerun.
108
+ */
109
+ async function recover(ctx, d, run, why, freezeNow, b, workflow) {
110
+ const { io, repo, state } = ctx;
111
+ const st = state.deploy, rec = d.recovery ?? {};
112
+ const rerunMax = rec.rerun_max ?? b.rerunMax, maxAttempts = rec.max_attempts ?? b.maxAttempts;
113
+ if (freezeNow) return { blocked: `${why}; ${d.freeze_variable} is set, so the engine never reruns or redispatches the deploy (I26): roll back, or a human runs the workflow with override_freeze` };
114
+ if (!run || !["failure", "timed_out", "cancelled"].includes(run.conclusion)) return { blocked: `${why}; nothing to rerun (a run that finished without changing live is not retried)` };
115
+ if (run.conclusion === "cancelled" && await superseded({ io, repo, workflow }, run)) return { blocked: `${why}; run ${run.databaseId} was cancelled by a newer run of the concurrency group: expected, not rerun` };
116
+ if (st.reruns >= rerunMax || st.attempts >= maxAttempts) return { blocked: `${why}; recovery spent (${st.reruns}/${rerunMax} reruns, ${st.attempts}/${maxAttempts} actions): hand off to the rollback ladder (#5563)` };
117
+ let log = ""; try { log = String(await io.gh(["run", "view", String(run.databaseId), "--repo", repo, "--log-failed"])); } catch { /* unreadable log: not transient */ }
118
+ const cls = classifyDeploy(log, rec.signatures);
119
+ if (cls !== "transient") return hold(`${why}; ${cls === "migration" ? "migration failure" : "deterministic build failure"}, never retried blindly: ${tail(log, 200)}`, cls);
120
+ st.reruns += 1; st.attempts += 1; ctx.save(); // counted before the act: a crash can only spend budget, never exceed it
121
+ const f = await fenced(ctx.fence, { action: "rerun", key: idemKey(ctx, `rerun:${run.databaseId}:${st.reruns}`) }, () => io.gh(["run", "rerun", String(run.databaseId), "--repo", repo, "--failed"]));
122
+ if (f.refused) return { blocked: `rerun ${f.refused}` };
123
+ await io.sleep(b.pollMs); // the rerun flips the run back to in_progress before the next observation
124
+ return { rerun: true };
125
+ }
126
+
127
+ /**
128
+ * reconcile(): re-observe GitHub before acting on a persisted phase (resume after a crash or a moved world).
129
+ * A LIVE_CHECKED phase whose live record no longer matches goes back to DEPLOYING (the run is observed, never redispatched);
130
+ * a phase with no recorded run adopts the run GitHub already has for the merge sha.
131
+ */
132
+ export async function reconcile(ctx, d, pipe, sha) {
133
+ const { io, repo } = ctx, st = ctx.state.deploy;
134
+ if (st.phase === "LIVE_CHECKED") {
135
+ if (!liveMatches(await readTarget(io, d.live_release_command), sha, st.expected)) { st.phase = "DEPLOYING"; ctx.save(); }
136
+ } else if (st.phase === "DEPLOYING" && !st.runId) {
137
+ const run = await latestRun({ io, repo, workflow: pipe.workflow, sha });
138
+ if (run) { st.runId = run.databaseId; ctx.save(); }
139
+ }
140
+ return st.phase;
141
+ }
142
+
143
+ const stageS = (d) => (typeof d.stage_timeout_s === "number" ? d.stage_timeout_s : BOUNDS.defaultStageS);
144
+
145
+ /** @returns {Promise<{skipped: true}|{live: true, merge, run, reruns}|{blocked: true, reason, hold?}|{stopped: true, why}>} */
146
+ export async function deployStep(ctx) {
147
+ const { io, repo, state } = ctx;
148
+ const d = ctx.config.deploy;
149
+ if (!d?.pipelines || !Object.keys(d.pipelines).length) return { skipped: true };
150
+ const b = { ...BOUNDS, ...(ctx.config.deployBounds ?? {}) };
151
+ const pipe = d.pipelines[ctx.config.deployPipeline ?? "full"] ?? Object.values(d.pipelines)[0];
152
+ if (!pipe?.workflow) return blocked("deploy.pipelines has no workflow for this release");
153
+ let sha = state.steps["post-merge"]?.result?.merge ?? null;
154
+ if (!sha) {
155
+ const pr = state.steps["release-pr"]?.result?.pr;
156
+ const v = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "state,mergeCommit"]));
157
+ sha = v?.state === "MERGED" ? v.mergeCommit?.oid : null;
158
+ if (!sha) return { stopped: true, why: `release PR #${pr} is not merged; nothing to deploy yet` };
159
+ }
160
+ const st = (state.deploy ??= { phase: "MERGED", attempts: 0, reruns: 0 });
161
+
162
+ if (!st.target) { // MERGED -> DEPLOYING guard (I9, 6.3): the rollback target is frozen before anything is dispatched
163
+ const target = await readTarget(io, d.live_release_command);
164
+ if (!target) return blocked("rollback target unknown: deploy.live_release_command is unset or returned no live sha (I9); nothing was dispatched");
165
+ let expected = null;
166
+ if (d.expected_digests_command) {
167
+ const r = await io.rehearse(d.expected_digests_command, { timeout: 120_000 });
168
+ try { expected = r?.ok ? json(r.output) : null; } catch { expected = null; }
169
+ if (!expected) return blocked("deploy.expected_digests_command returned no digests; refusing to deploy without them");
170
+ }
171
+ st.target = target; st.expected = expected; st.merge = sha; st.freezeBefore = await freezeValue(io, repo, d.freeze_variable); st.phase = "DEPLOYING";
172
+ ctx.save();
173
+ }
174
+
175
+ await reconcile(ctx, d, pipe, sha);
176
+ if (st.phase !== "LIVE_CHECKED" && st.phase !== "LIVE") {
177
+ for (;;) {
178
+ st.phase = "DEPLOYING"; ctx.save();
179
+ const r = await runFor(ctx, { workflow: pipe.workflow, sha, inputs: pipe.inputs ?? {}, key: `deploy:${sha}`, startPolls: pipe.trigger === "dispatch" ? 1 : Math.max(1, Math.ceil((d.start_timeout_s ?? 60) * 1000 / b.pollMs)), b });
180
+ if (r.err) return blocked(r.err);
181
+ st.runId = r.run.databaseId; ctx.save();
182
+ const done = await finished(ctx, pipe.workflow, sha, Math.ceil(stageS(d) * 1000 / b.runPollMs), b);
183
+ if (!done) return blocked(`${pipe.workflow} run ${st.runId} did not finish within stage_timeout_s; check the live record before any rerun, then resume`);
184
+ st.phase = "LIVE_CHECK"; ctx.save();
185
+ const live = await readTarget(io, d.live_release_command);
186
+ const freezeNow = await freezeValue(io, repo, d.freeze_variable);
187
+ const frozenByRun = !!freezeNow && !st.freezeBefore;
188
+ let why = null;
189
+ if (done.conclusion === "failure" || done.conclusion === "timed_out") why = `${pipe.workflow} run ${done.databaseId} concluded ${done.conclusion}`;
190
+ else if (!liveMatches(live, sha, st.expected)) why = `LIVE_CHECK failed: run ${done.databaseId} concluded ${done.conclusion} but live is ${live?.sha?.slice(0, 8) ?? "unreadable"}, not ${sha.slice(0, 8)} (I28)${frozenByRun ? `; the run set ${d.freeze_variable}` : ""}`;
191
+ else if (frozenByRun) why = `LIVE_CHECK failed: the run set ${d.freeze_variable}`;
192
+ if (!why) { st.phase = "LIVE_CHECKED"; ctx.save(); break; }
193
+ const rec = await recover(ctx, d, done, why, !!freezeNow, b, pipe.workflow);
194
+ if (rec.blocked) return { ...blocked(rec.blocked), ...(rec.hold ? { hold: rec.hold } : {}) };
195
+ }
196
+ }
197
+
198
+ let verify = null;
199
+ if (st.phase !== "LIVE") {
200
+ st.phase = "VERIFYING"; ctx.save();
201
+ if (verifyConfigured(ctx.config.verify)) { // #5562: layers, FORGE:VERIFIED, guarded close; unconfigured stays a bare transition
202
+ verify = await verifyStep(ctx, sha);
203
+ if (verify.blocked) return { ...blocked(verify.reason), ...(verify.hold ? { hold: verify.hold } : {}), ...(verify.rollback ? { rollback: verify.rollback } : {}) };
204
+ }
205
+ st.phase = "LIVE"; ctx.save();
206
+ }
207
+ io.print?.(`release: live at ${sha.slice(0, 8)} (run ${st.runId}, ${st.reruns} rerun(s))`);
208
+ return { live: true, merge: sha, run: st.runId, reruns: st.reruns, ...(verify ? { verify } : {}) };
209
+ }