forgedock 1.53.0 → 1.54.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 (185) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +6 -3
  12. package/bin/engine/telemetry-seam.mjs +8 -2
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +57 -20
  15. package/bin/first-run.mjs +122 -0
  16. package/bin/forgedock.mjs +128 -146
  17. package/bin/help-text.mjs +144 -0
  18. package/bin/hooks/pre-tool-use.mjs +7 -0
  19. package/bin/journey.mjs +82 -83
  20. package/bin/lean/acceptance.mjs +313 -0
  21. package/bin/lean/acceptance.test.mjs +215 -0
  22. package/bin/lean/activation.mjs +18 -0
  23. package/bin/lean/activation.test.mjs +23 -1
  24. package/bin/lean/batch-health.mjs +74 -1
  25. package/bin/lean/batch-health.test.mjs +54 -1
  26. package/bin/lean/batch.test.mjs +11 -9
  27. package/bin/lean/branchlock.mjs +54 -0
  28. package/bin/lean/branchlock.test.mjs +49 -0
  29. package/bin/lean/ceiling.mjs +72 -0
  30. package/bin/lean/ceiling.test.mjs +54 -0
  31. package/bin/lean/ci-budget.mjs +366 -0
  32. package/bin/lean/ci-budget.test.mjs +167 -0
  33. package/bin/lean/conformance.e2e.test.mjs +7 -0
  34. package/bin/lean/conformance.mjs +77 -19
  35. package/bin/lean/conformance.test.mjs +129 -3
  36. package/bin/lean/context.mjs +35 -6
  37. package/bin/lean/context.test.mjs +27 -1
  38. package/bin/lean/depcache.mjs +25 -1
  39. package/bin/lean/depcache.test.mjs +26 -0
  40. package/bin/lean/e2e.mjs +18 -2
  41. package/bin/lean/e2e.test.mjs +26 -1
  42. package/bin/lean/effects.mjs +40 -11
  43. package/bin/lean/execution.test.mjs +24 -0
  44. package/bin/lean/facts.mjs +3 -3
  45. package/bin/lean/facts.test.mjs +5 -0
  46. package/bin/lean/fixround.mjs +14 -0
  47. package/bin/lean/fixround.test.mjs +25 -2
  48. package/bin/lean/gh-assoc.test.mjs +2 -1
  49. package/bin/lean/integration.mjs +100 -9
  50. package/bin/lean/integration.test.mjs +98 -0
  51. package/bin/lean/issuewatch-parity.mjs +64 -0
  52. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  53. package/bin/lean/issuewatch-release.test.mjs +1 -1
  54. package/bin/lean/issuewatch.mjs +34 -5
  55. package/bin/lean/issuewatch.test.mjs +3 -2
  56. package/bin/lean/lean.mjs +316 -74
  57. package/bin/lean/lean.test.mjs +397 -24
  58. package/bin/lean/mechfix.mjs +124 -0
  59. package/bin/lean/mechfix.test.mjs +75 -0
  60. package/bin/lean/orchestrate.mjs +20 -2
  61. package/bin/lean/phaseledger.mjs +47 -5
  62. package/bin/lean/phaseledger.test.mjs +30 -1
  63. package/bin/lean/precheck.mjs +23 -4
  64. package/bin/lean/precheck.test.mjs +14 -1
  65. package/bin/lean/prereq.mjs +28 -0
  66. package/bin/lean/prereq.test.mjs +20 -0
  67. package/bin/lean/probe.mjs +4 -2
  68. package/bin/lean/prodparity.mjs +52 -0
  69. package/bin/lean/prodparity.test.mjs +67 -0
  70. package/bin/lean/prompts.mjs +69 -12
  71. package/bin/lean/recovery.test.mjs +1 -1
  72. package/bin/lean/release-io.test.mjs +42 -0
  73. package/bin/lean/release-postmerge.mjs +6 -0
  74. package/bin/lean/release-preflight.mjs +58 -0
  75. package/bin/lean/release-preflight.test.mjs +114 -0
  76. package/bin/lean/release-rehearsal.mjs +8 -7
  77. package/bin/lean/release-review.mjs +67 -11
  78. package/bin/lean/release-review.test.mjs +128 -1
  79. package/bin/lean/release-snapshot.mjs +188 -0
  80. package/bin/lean/release-snapshot.test.mjs +190 -0
  81. package/bin/lean/release.mjs +80 -12
  82. package/bin/lean/release.test.mjs +95 -0
  83. package/bin/lean/render.mjs +1 -1
  84. package/bin/lean/replan.mjs +184 -0
  85. package/bin/lean/replan.test.mjs +110 -0
  86. package/bin/lean/resume.mjs +9 -7
  87. package/bin/lean/resume.test.mjs +16 -0
  88. package/bin/lean/schedd.mjs +34 -1
  89. package/bin/lean/schedd.test.mjs +21 -1
  90. package/bin/lean/selfreview.mjs +94 -0
  91. package/bin/lean/selfreview.test.mjs +58 -1
  92. package/bin/lean/selftest-gate.mjs +22 -0
  93. package/bin/lean/selftest-gate.test.mjs +18 -1
  94. package/bin/lean/selftest-journey.mjs +234 -0
  95. package/bin/lean/selftest-journey.test.mjs +130 -0
  96. package/bin/lean/selftest-live.mjs +2 -1
  97. package/bin/lean/seqlease.mjs +35 -1
  98. package/bin/lean/seqlease.test.mjs +15 -0
  99. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  100. package/bin/lean/seqreserve.mjs +73 -0
  101. package/bin/lean/seqreserve.test.mjs +134 -0
  102. package/bin/lean/sequence.mjs +35 -6
  103. package/bin/lean/seqversioned.mjs +147 -0
  104. package/bin/lean/stagestamp.mjs +28 -0
  105. package/bin/lean/stagestamp.test.mjs +32 -0
  106. package/bin/lean/surfaces.mjs +75 -0
  107. package/bin/lean/surfaces.test.mjs +59 -0
  108. package/bin/lean/toolplace.mjs +28 -0
  109. package/bin/lean/toolplace.test.mjs +24 -0
  110. package/bin/lean/toolstats.mjs +3 -1
  111. package/bin/lean/toolstats.test.mjs +11 -0
  112. package/bin/lean/validatebest.mjs +28 -0
  113. package/bin/lean/validatebest.test.mjs +27 -0
  114. package/bin/pool/agent.mjs +9 -0
  115. package/bin/pool/docker.mjs +5 -0
  116. package/bin/pool/router.mjs +8 -4
  117. package/bin/prereqs.mjs +111 -0
  118. package/bin/replay-timelapse.mjs +149 -0
  119. package/bin/review-staging.mjs +100 -16
  120. package/bin/review-staging.test.mjs +18 -0
  121. package/bin/runner.mjs +43 -6
  122. package/bin/splash-install.mjs +157 -0
  123. package/bin/stats/aggregate.mjs +8 -1
  124. package/bin/stats/conformance-outcomes.mjs +100 -19
  125. package/bin/stats/conformance-outcomes.test.mjs +87 -1
  126. package/bin/stats/depth.mjs +88 -31
  127. package/bin/stats/depth.test.mjs +63 -38
  128. package/bin/stats/efficiency.mjs +26 -5
  129. package/bin/stats/efficiency.test.mjs +45 -1
  130. package/bin/stats/first-review.mjs +77 -0
  131. package/bin/stats/first-review.test.mjs +36 -0
  132. package/bin/stats/firstmerge.mjs +40 -0
  133. package/bin/stats/firstmerge.test.mjs +41 -0
  134. package/bin/stats/github-source.mjs +51 -13
  135. package/bin/stats/index.mjs +91 -15
  136. package/bin/stats/local-source.mjs +1 -0
  137. package/bin/stats/origin.mjs +80 -0
  138. package/bin/stats/origin.test.mjs +58 -0
  139. package/bin/stats/render.mjs +3 -1
  140. package/bin/stats/scoreboard.mjs +137 -0
  141. package/bin/stats/scoreboard.test.mjs +87 -0
  142. package/bin/stats/stats.test.mjs +80 -0
  143. package/bin/tui.mjs +3 -2
  144. package/commands/bootstrap.md +15 -14
  145. package/commands/deploy-pr.md +18 -3
  146. package/commands/forge-stats.md +1 -1
  147. package/commands/forgedock-ci-setup.md +28 -0
  148. package/commands/forgedock-init.md +4 -5
  149. package/commands/issue.md +2 -0
  150. package/commands/milestone.md +9 -1
  151. package/commands/replay.md +2 -0
  152. package/commands/review-pr-staging.md +4 -1
  153. package/commands/work-on/close.md +8 -0
  154. package/docs/CONFIG.md +105 -10
  155. package/docs/ISSUE-WATCH.md +23 -0
  156. package/docs/OUTCOME-CODES.md +1 -0
  157. package/docs/REPLAY.md +9 -0
  158. package/docs/SELFTEST.md +11 -0
  159. package/docs/STATS.md +19 -2
  160. package/docs/eval/README.md +6 -0
  161. package/docs/eval/adversarial-bench.md +68 -0
  162. package/docs/eval/corpus/adversarial-v1.json +285 -0
  163. package/docs/eval/feature-bench.md +42 -0
  164. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  165. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  166. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  167. package/docs/site/start-a-new-project.md +2 -1
  168. package/package.json +5 -2
  169. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  170. package/plugins/forgedock-splash/README.md +27 -0
  171. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  172. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  173. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  174. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  175. package/scripts/bench-adversarial.mjs +216 -0
  176. package/scripts/bench-feature.mjs +170 -0
  177. package/scripts/bench-lightlane.mjs +2 -2
  178. package/scripts/bootstrap-create.mjs +2 -2
  179. package/scripts/bootstrap-validate.mjs +35 -2
  180. package/scripts/check-spec-size.sh +4 -3
  181. package/scripts/check-spec-size.test.sh +3 -0
  182. package/scripts/plan-validate-live.mjs +40 -6
  183. package/scripts/review-pr-staging-scope.test.sh +1 -1
  184. package/scripts/review-staging-post.sh +23 -0
  185. package/scripts/review-staging-post.test.sh +8 -0
@@ -11,9 +11,11 @@
11
11
  import { execFileSync, spawn } from "node:child_process";
12
12
  import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, rmSync } from "node:fs";
13
13
  import { tmpdir } from "node:os";
14
- import { join } from "node:path";
14
+ import { delimiter, join } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
+ import { runHostPreflight } from "./release-preflight.mjs";
16
17
  import { reviewStagingJson, reviewStagingIo, CI_EXCLUDED_CHECKS } from "../review-staging.mjs";
18
+ import { pickFixes, recut } from "./release-snapshot.mjs";
17
19
 
18
20
  /** Delta passes after a head move, and fix-lane rounds: past either the job blocks for the manual path. */
19
21
  export const MAX_DELTA_PASSES = 2;
@@ -24,6 +26,19 @@ const SEVERE = new Set(["CRITICAL", "HIGH"]);
24
26
  const MANUAL = "use the manual path: forgedock review-staging <PR> (commands/review-pr-staging.md)";
25
27
  const blocked = (why) => ({ blocked: true, reason: `${why}; ${MANUAL}` });
26
28
 
29
+ /**
30
+ * scripts/issue-create.sh (programmatic mode) refuses a body file without exactly one `FORGE:BODY-INTEGRITY` marker, so a
31
+ * finding body gets one appended unless it already carries exactly one. The id is reduced to the marker's allowed chars.
32
+ */
33
+ export function withIntegrityMarker(body, id) {
34
+ const text = String(body ?? "");
35
+ const n = (text.match(/<!-- FORGE:BODY-INTEGRITY:[^>]+ -->/g) ?? []).length;
36
+ if (n === 1) return text;
37
+ const clean = text.replace(/<!-- FORGE:BODY-INTEGRITY:[^>]+ -->\n?/g, "").trimEnd();
38
+ const tag = String(id ?? "finding").replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "finding";
39
+ return `${clean}\n\n<!-- FORGE:BODY-INTEGRITY:${tag} -->\n`;
40
+ }
41
+
27
42
  /** Reviewers whose prompts are prose in the spec (not briefed by the pre-dispatch): marker domain -> spec phase. */
28
43
  export const SPEC_PANEL = [
29
44
  { domain: "material-change", phase: "Phase 2 (material-change)" },
@@ -45,6 +60,12 @@ export function missingReviewers(lines) {
45
60
  const m = /missing findings comment\(s\) for:\s*([^\n]+)/.exec(t) ?? /no structured findings block from:\s*([^\n]+?)\.?(?:\s+Re-dispatch|\n|$)/.exec(t);
46
61
  return m ? m[1].split(/[\s,]+/).filter((d) => /^[a-z0-9-]+$/.test(d)) : [];
47
62
  }
63
+ /** A reviewer session's failure as one line: exit status and the last lines of what it said. */
64
+ const sessionFailure = (e) => {
65
+ const out = String(e?.stderr || e?.message || e || "").trim().split("\n").slice(-3).join(" | ").slice(0, 300);
66
+ return `exit ${e?.code ?? e?.status ?? e?.exitCode ?? "?"}: ${out}`;
67
+ };
68
+ const failureNote = (failures) => (failures.size ? `; session failures: ${[...failures].map(([d, f]) => `${d} (${f})`).join("; ")}` : "");
48
69
  const headMoved = (lines) => /head moved since/.test((lines ?? []).join("\n"));
49
70
 
50
71
  /** One review round at the current head: dispatch, test gate, head check, finalize. @returns {{moved: string}|{fail}|{ok}} */
@@ -61,7 +82,9 @@ async function reviewRound({ seam, pr, def, delta }) {
61
82
  const prompts = new Map(agents.map((a) => [a.domain, a.prompt()]));
62
83
  seam.markLaunched(m.launchedFile, agents.map((a) => a.domain), m.headSha);
63
84
  const send = (domain, note = "") => seam.runAgent({ role: `release-review-${domain}`, issue: pr, prompt: note ? `${prompts.get(domain)}\n\n${note}` : prompts.get(domain) });
64
- await Promise.all(agents.map((a) => send(a.domain).catch((e) => ({ error: e.message }))));
85
+ const failures = new Map();
86
+ const attempt = (domain, note) => send(domain, note).catch((e) => { failures.set(domain, sessionFailure(e)); return null; });
87
+ await Promise.all(agents.map((a) => attempt(a.domain)));
65
88
  const gate = await seam.runAgent({ role: "release-test-gate", issue: pr, prompt: `/test-gate --prs "${(m.bundle ?? []).join(" ")}" --base ${def}\n\nPrint the complete gate output, ending with its FORGE:TEST_GATE:RESULT= marker.` });
66
89
  const gateFile = seam.saveTestGate(pr, gate?.text ?? "");
67
90
 
@@ -71,13 +94,13 @@ async function reviewRound({ seam, pr, def, delta }) {
71
94
  if (fin.code !== 0 || !fin.data) {
72
95
  if (headMoved(fin.lines)) return { moved: m.headSha };
73
96
  const missing = missingReviewers(fin.lines).filter((d) => prompts.has(d));
74
- if (!missing.length) return { fail: `finalize stopped (exit ${fin.code}): ${(fin.lines ?? []).slice(-2).join(" | ").slice(0, 300)}` };
97
+ if (!missing.length) return { fail: `finalize stopped (exit ${fin.code}): ${(fin.lines ?? []).slice(-2).join(" | ").slice(0, 300)}${failureNote(failures)}` };
75
98
  // once: the same brief with the note the spec prescribes; a second miss is a degraded panel
76
- await Promise.all(missing.map((d) => send(d, "structured findings block required: post your findings comment again, ending with the REVIEW-FINDINGS-START/END block.").catch(() => null)));
99
+ await Promise.all(missing.map((d) => attempt(d, "structured findings block required: post your findings comment again, ending with the REVIEW-FINDINGS-START/END block.")));
77
100
  fin = await seam.finalize({ pr, testGateOutput: gateFile });
78
101
  if (fin.code !== 0 || !fin.data) {
79
102
  if (headMoved(fin.lines)) return { moved: m.headSha };
80
- return { fail: `reviewer findings block still missing after one re-ask (${missing.join(", ")}): degraded panel` };
103
+ return { fail: `reviewer findings block still missing after one re-ask (${missing.join(", ")}): degraded panel${failureNote(failures)}` };
81
104
  }
82
105
  }
83
106
  return { ok: fin.data };
@@ -129,9 +152,21 @@ export async function fixStep(ctx) {
129
152
  }
130
153
  if (!issues.length) return blocked(`${r.verdict} with neither a blocking finding nor red CI to fix`);
131
154
  for (const issue of issues) {
155
+ // A resume after the fix already merged (by this job or by an intake lane): its lane would end invalid on a closed issue.
156
+ if (await seam.issueMerged?.(issue)) continue;
132
157
  const lane = await seam.runLane({ issue, lane: ctx.staging });
133
158
  if (lane?.terminalReason !== "merged") return blocked(`fix lane for #${issue} ended ${lane?.terminalReason ?? "without a result"}`);
134
159
  }
160
+ // Snapshot mode (#5276): the fixes are merged on staging; bring exactly those onto release/<id> (or recut it) before the delta review.
161
+ if (ctx.config?.mode === "snapshot") {
162
+ const moved = ctx.config.fixMode === "recut" ? await recut(ctx) : await pickFixes(ctx, { issues });
163
+ if (moved.err) return blocked(moved.err);
164
+ }
165
+ // The host preflight re-runs on the head the fixes produced, before the delta review (the draft PR has no Actions CI yet, #5277).
166
+ if (ctx.config?.preflight) {
167
+ const pf = await runHostPreflight(ctx, { head: await seam.headOf(r.pr), pr: r.pr });
168
+ if (!pf.ok && pf.blocking) return blocked(`host preflight failed at ${pf.head} after the fix round (release-blocker #${pf.issue})`);
169
+ }
135
170
  const next = await runReview({ seam, pr: r.pr, def: ctx.def, delta: r.head });
136
171
  if (next.blocked) return next;
137
172
  r = next;
@@ -144,11 +179,19 @@ export async function fixStep(ctx) {
144
179
  const seamOf = (ctx) => ctx.io.review ?? (ctx.seam ??= realSeam(ctx));
145
180
 
146
181
  /** Real effects of the review steps: the review-staging library, the engine runner, the filing scripts, gh and a lane process. */
147
- export function realSeam({ repo, def, env = process.env, cwd = process.cwd() }) {
182
+ export function realSeam({ repo, def, env = process.env, cwd = process.cwd(), makeRunner = null, gh: ghIn = null }) {
148
183
  const rs = { ...reviewStagingIo(), cwd, env };
149
184
  const sd = env.FORGE_SCRATCHPAD || join(cwd, ".forge-scratch");
150
- let runner = null;
151
- const gh = (args, input) => execFileSync("gh", args, { encoding: "utf8", input, maxBuffer: 64 << 20, env });
185
+ let runner = null, shimEnv = null;
186
+ // Reviewer briefs say `forgedock ...`: pin that name to this release job's own build, whatever is installed globally.
187
+ const pinnedEnv = () => {
188
+ if (shimEnv) return shimEnv;
189
+ const dir = mkdtempSync(join(tmpdir(), "release-forgedock-"));
190
+ writeFileSync(join(dir, "forgedock"), `#!/bin/sh\nexec "${process.execPath}" "${join(ROOT, "bin", "forgedock.mjs")}" "$@"\n`, { mode: 0o755 });
191
+ process.once("exit", () => rmSync(dir, { recursive: true, force: true }));
192
+ return (shimEnv = { ...env, PATH: `${dir}${delimiter}${env.PATH ?? ""}` });
193
+ };
194
+ const gh = ghIn ?? ((args, input) => execFileSync("gh", args, { encoding: "utf8", input, maxBuffer: 64 << 20, env }));
152
195
  return {
153
196
  pre: ({ pr, delta }) => reviewStagingJson([String(pr), ...(delta ? ["--delta", delta] : [])], rs),
154
197
  finalize: ({ pr, testGateOutput }) => reviewStagingJson([String(pr), "--finalize", "--test-gate-output", testGateOutput], rs),
@@ -158,11 +201,24 @@ export function realSeam({ repo, def, env = process.env, cwd = process.cwd() })
158
201
  markLaunched: (file, domains, head) => { appendFileSync(file, domains.map((d) => `${d}\n`).join("")); writeFileSync(`${file}.head`, `${head}\n`); },
159
202
  saveTestGate: (pr, text) => { mkdirSync(sd, { recursive: true }); const f = join(sd, `${pr}_test_gate_output.txt`); writeFileSync(f, text); return f; },
160
203
  runAgent: async ({ role, issue, prompt }) => {
161
- runner ??= (await import("./effects.mjs")).makeLeanRunner();
204
+ runner ??= makeRunner ? makeRunner() : (await import("./effects.mjs")).makeLeanRunner();
162
205
  // not readOnly: each reviewer posts its own PR comment
163
- return runner({ role, issue, cwd, prompt, system: "You are an isolated reviewer of one release PR. Do only what the prompt asks.", maxMs: REVIEW_MS, idleMs: 10 * 60_000 });
206
+ return runner({ role, issue, cwd, env: pinnedEnv(), prompt, system: "You are an isolated reviewer of one release PR. Do only what the prompt asks.", maxMs: REVIEW_MS, idleMs: 10 * 60_000 });
207
+ },
208
+ // closed by a merged fix: state CLOSED with the workflow:merged label (a read failure is "not merged", so the lane runs)
209
+ issueMerged: async (issue) => {
210
+ try {
211
+ const v = JSON.parse(gh(["issue", "view", String(issue), "-R", repo, "--json", "state,labels"]));
212
+ return v.state === "CLOSED" && (v.labels ?? []).some((l) => l.name === "workflow:merged");
213
+ } catch { return false; }
164
214
  },
165
215
  async fileCiIssue({ pr, head }) {
216
+ // one issue per release head: a resume reuses the issue filed for the same head instead of filing a duplicate
217
+ const title = `Release PR #${pr}: CI red at ${head.slice(0, 7)}`;
218
+ try {
219
+ const hit = JSON.parse(gh(["issue", "list", "-R", repo, "--state", "all", "--search", `"${title}" in:title`, "--json", "number,title"])).find((i) => i.title === title);
220
+ if (hit) return hit.number;
221
+ } catch { /* no lookup: file a new one */ }
166
222
  const rows = JSON.parse(gh(["pr", "checks", String(pr), "-R", repo, "--json", "name,bucket"]));
167
223
  const names = rows.filter((c) => c.bucket === "fail" && !CI_EXCLUDED_CHECKS.includes(c.name)).map((c) => c.name);
168
224
  return this.fileIssue({ item: { title: `Release PR #${pr}: CI red at ${head.slice(0, 7)}`, severity: "HIGH", body: `Failing required checks on the release PR #${pr} at ${head}:\n${names.map((n) => `- ${n}`).join("\n")}\n\nFix them on the staging branch.` }, pr });
@@ -172,7 +228,7 @@ export function realSeam({ repo, def, env = process.env, cwd = process.cwd() })
172
228
  try {
173
229
  const body = item.body ?? [`Found by the staging review of PR #${pr}.`, ...Object.entries(item).filter(([k, v]) => k !== "title" && ["string", "number"].includes(typeof v)).map(([k, v]) => `- **${k}**: ${v}`)].join("\n");
174
230
  const bodyFile = join(dir, "body.md");
175
- writeFileSync(bodyFile, body);
231
+ writeFileSync(bodyFile, withIntegrityMarker(body, `release-${pr}-${item.id ?? item.title ?? "finding"}`));
176
232
  let out = "";
177
233
  try { out = execFileSync("bash", [join(ROOT, "scripts", "issue-create.sh"), "--title", item.title, "--body-file", bodyFile, "--label", "review-finding", "--label", "staging-review", "--repo", repo], { encoding: "utf8", cwd, env }); } catch (e) { out = String(e.stdout ?? ""); }
178
234
  try {
@@ -2,7 +2,8 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { reviewStep, fixStep, missingReviewers, SPEC_PANEL, MAX_DELTA_PASSES, MAX_FIX_ROUNDS, realSeam } from "./release-review.mjs";
5
+ import { reviewStep, fixStep, missingReviewers, SPEC_PANEL, MAX_DELTA_PASSES, MAX_FIX_ROUNDS, realSeam, withIntegrityMarker } from "./release-review.mjs";
6
+ import { readFileSync } from "node:fs";
6
7
  import { reviewStagingJson } from "../review-staging.mjs";
7
8
 
8
9
  const H1 = "a".repeat(40), H2 = "b".repeat(40);
@@ -25,6 +26,7 @@ function fakeSeam({ heads = [H1], fins = [fin()], summary, lanes = [] } = {}) {
25
26
  runAgent: async (a) => { agents.push(a.role + (a.prompt.includes("findings block required") ? ":reask" : "")); return { text: "ok" }; },
26
27
  fileIssue: async ({ item }) => { log.push(["file", item.title]); return n++; },
27
28
  fileCiIssue: async () => { log.push(["ci-issue"]); return n++; },
29
+ issueMerged: async () => false,
28
30
  addNotes: async (pr, notes) => log.push(["notes", notes]),
29
31
  runLane: async (a) => { log.push(["lane", a.issue, a.lane]); return lanes[l++] ?? { terminalReason: "merged" }; },
30
32
  };
@@ -32,6 +34,23 @@ function fakeSeam({ heads = [H1], fins = [fin()], summary, lanes = [] } = {}) {
32
34
  const ctx = (seam, steps = {}) => ({ io: { review: seam }, repo: "o/r", def: "main", staging: "staging", state: { steps: { "release-pr": { result: { pr: 7 } }, ...steps } }, save() {} });
33
35
 
34
36
  describe("reviewStep", () => {
37
+ it("reviewer sessions run the release job's own forgedock build", async () => {
38
+ let seen = null;
39
+ const real = realSeam({ repo: "o/r", def: "main", env: { PATH: "/usr/bin" }, cwd: "/tmp", makeRunner: () => async (a) => { seen = a; return { text: "" }; } });
40
+ await real.runAgent({ role: "release-review-security", issue: 7, prompt: "p" });
41
+ const [dir, ...rest] = seen.env.PATH.split(":");
42
+ assert.equal(rest.join(":"), "/usr/bin");
43
+ const shim = readFileSync(`${dir}/forgedock`, "utf8");
44
+ assert.ok(shim.includes(process.execPath) && shim.includes("bin/forgedock.mjs"), shim);
45
+ });
46
+
47
+ it("a failed reviewer session is reported with its exit and tail", async () => {
48
+ const s = fakeSeam({ fins: [{ code: 1, data: null, lines: ["finalize failed"] }] });
49
+ s.runAgent = async (a) => { if (a.role === "release-review-security") throw Object.assign(new Error("forgedock: unknown option --post-reviewer"), { code: 2 }); return { text: "ok" }; };
50
+ const r = await reviewStep(ctx(s));
51
+ assert.match(r.reason, /session failures: security \(exit 2: forgedock: unknown option --post-reviewer\)/);
52
+ });
53
+
35
54
  it("realSeam exposes every effect the steps use, matching the fake seam", () => {
36
55
  const real = Object.keys(realSeam({ repo: "o/r", def: "main", env: {}, cwd: "/tmp" })).sort();
37
56
  assert.deepEqual(real, Object.keys(fakeSeam()).filter((k) => k !== "log" && k !== "agents").sort());
@@ -150,6 +169,23 @@ describe("fixStep", () => {
150
169
  assert.equal(r.blocked, undefined);
151
170
  });
152
171
 
172
+ it("a resume skips fix issues already closed as merged and goes on to the delta review", async () => {
173
+ const s = fakeSeam({ heads: [H2] });
174
+ s.issueMerged = async (n) => n === 101;
175
+ const r = await fixStep(ctx(s, { review: { result: failed } }));
176
+ assert.equal(s.log.filter((e) => e[0] === "lane").length, 0);
177
+ assert.deepEqual(s.log[0], ["pre", H1]);
178
+ assert.equal(r.blocked, undefined);
179
+ });
180
+
181
+ it("realSeam.fileCiIssue reuses the issue already filed for the same release head", async () => {
182
+ const calls = [];
183
+ const gh = (args) => { calls.push(args); if (args[0] === "issue" && args[1] === "list") return JSON.stringify([{ number: 5396, title: "Release PR #7: CI red at b48bae6" }]); throw new Error("unexpected"); };
184
+ const seam = realSeam({ repo: "o/r", def: "main", env: {}, cwd: "/tmp", gh });
185
+ assert.equal(await seam.fileCiIssue({ pr: 7, head: "b48bae6628432906aa96f509eddfe6d49608e725" }), 5396);
186
+ assert.equal(calls.length, 1);
187
+ });
188
+
153
189
  it("a blocking finding and red CI together get a lane each", async () => {
154
190
  const s = fakeSeam({ heads: [H2] });
155
191
  await fixStep(ctx(s, { review: { result: { ...failed, ciFailing: 1 } } }));
@@ -178,3 +214,94 @@ describe("reviewStagingJson (library entry)", () => {
178
214
  assert.ok(r.lines.length > 0);
179
215
  });
180
216
  });
217
+
218
+ describe("fixStep in snapshot mode (#5276)", () => {
219
+ const failed = { pr: 7, head: H1, verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", blocking: [101], filed: [101], ciFailing: 0 };
220
+ const SNAP = "1".repeat(40), TIP = "2".repeat(40), ORIG = "3".repeat(40), PICK = "4".repeat(40);
221
+ /** git/gh fakes for one blocker fix (PR 55, closes issue 101) merged on staging; `conflict` makes merge-tree fail. */
222
+ const world = ({ conflict = false } = {}) => {
223
+ const git = [], gh = [];
224
+ const io = {
225
+ git: (a) => {
226
+ git.push(a);
227
+ if (a[0] === "rev-parse") return `${TIP}\n`;
228
+ if (a[0] === "merge-base") { if (a[3] === SNAP) throw new Error("not an ancestor"); return ""; }
229
+ if (a[0] === "rev-list") return `${ORIG} ${"5".repeat(40)}\n`;
230
+ if (a[0] === "merge-tree") { if (conflict) throw new Error("CONFLICT"); return "tree\n"; }
231
+ if (a[0] === "log") return a.includes("--format=%B") ? "fix: blocker\n" : "An\nae@x\n2026-01-01T00:00:00Z\n";
232
+ if (a[0] === "commit-tree") return `${PICK}\n`;
233
+ return "";
234
+ },
235
+ gh: async (a) => {
236
+ gh.push(a);
237
+ if (a[1] === "list" && a[0] === "issue") return "[]";
238
+ if (a[0] === "pr" && a[1] === "list") return JSON.stringify([{ number: 55, mergeCommit: { oid: ORIG }, mergedAt: "t", labels: [], closingIssuesReferences: [{ number: 101 }] }]);
239
+ if (a[0] === "pr" && a[1] === "view") return JSON.stringify({ body: "" });
240
+ return "";
241
+ },
242
+ };
243
+ return { io, git, gh };
244
+ };
245
+ const snapCtx = (seam, w, fixMode) => {
246
+ const c = ctx(seam, { review: { result: failed } });
247
+ c.io = { ...c.io, ...w.io };
248
+ c.git = w.io.git;
249
+ c.config = { mode: "snapshot", ...(fixMode ? { fixMode } : {}) };
250
+ c.state.release = { branch: "release/x", snapshot: SNAP, range: {}, picks: [] };
251
+ return c;
252
+ };
253
+
254
+ it("R2: after the fix lane merges, its commit is cherry-picked onto the release branch before the delta review", async () => {
255
+ const s = fakeSeam({ heads: [H2] }), w = world();
256
+ const c = snapCtx(s, w);
257
+ const r = await fixStep(c);
258
+ assert.equal(r.blocked, undefined);
259
+ assert.deepEqual(c.state.release.picks, [{ sha: PICK, orig: ORIG, pr: 55 }]);
260
+ assert.ok(w.git.some((a) => a[0] === "push" && a.includes(`${PICK}:refs/heads/release/x`)));
261
+ assert.ok(w.gh.some((a) => a[1] === "edit" && a[a.indexOf("--body") + 1].includes("FORGE:RELEASE")), "the record is written to the PR");
262
+ assert.deepEqual(s.log.slice(0, 2), [["lane", 101, "staging"], ["pre", H1]]);
263
+ });
264
+
265
+ it("a conflicting cherry-pick blocks the job instead of reviewing a head that lacks the fix", async () => {
266
+ const s = fakeSeam({ heads: [H2] });
267
+ const r = await fixStep(snapCtx(s, world({ conflict: true })));
268
+ assert.equal(r.blocked, true);
269
+ assert.match(r.reason, /conflicts/);
270
+ assert.ok(!s.log.some((e) => e[0] === "pre"));
271
+ });
272
+
273
+ it("fix_mode recut moves the branch to the staging tip instead of picking", async () => {
274
+ const s = fakeSeam({ heads: [H2] }), w = world();
275
+ const c = snapCtx(s, w, "recut");
276
+ await fixStep(c);
277
+ assert.ok(w.git.some((a) => a[0] === "push" && a.includes("--force") && a.includes(`${TIP}:refs/heads/release/x`)));
278
+ assert.equal(c.state.release.snapshot, TIP);
279
+ assert.deepEqual(c.state.release.picks, []);
280
+ });
281
+
282
+ it("freeze mode (no mode) never touches git", async () => {
283
+ const s = fakeSeam({ heads: [H2] }), w = world();
284
+ const c = snapCtx(s, w);
285
+ c.config = {};
286
+ await fixStep(c);
287
+ assert.deepEqual(w.git, []);
288
+ });
289
+ });
290
+
291
+ describe("withIntegrityMarker (filing release findings through issue-create.sh)", () => {
292
+ const count = (s) => (s.match(/<!-- FORGE:BODY-INTEGRITY:[^>]+ -->/g) ?? []).length;
293
+ it("appends exactly one marker to a body that has none", () => {
294
+ const out = withIntegrityMarker("Found by the staging review of PR #5389.\n- **severity**: HIGH", "release-5389-REG-1");
295
+ assert.equal(count(out), 1);
296
+ assert.match(out, /<!-- FORGE:BODY-INTEGRITY:release-5389-REG-1 -->\n$/);
297
+ });
298
+ it("keeps a body that already has exactly one marker unchanged", () => {
299
+ const body = "x\n<!-- FORGE:BODY-INTEGRITY:abc -->\n";
300
+ assert.equal(withIntegrityMarker(body, "y"), body);
301
+ });
302
+ it("collapses several markers to one and sanitises the id", () => {
303
+ const out = withIntegrityMarker("a <!-- FORGE:BODY-INTEGRITY:1 -->\nb <!-- FORGE:BODY-INTEGRITY:2 -->", "fix: auto-spawned schedd (review finding)");
304
+ assert.equal(count(out), 1);
305
+ assert.match(out, /FORGE:BODY-INTEGRITY:fix-auto-spawned-schedd-review-finding -->/);
306
+ });
307
+ });
@@ -0,0 +1,188 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Snapshot releases of `forgedock release` (#5276): `release.mode: snapshot` cuts `release/<id>` from a staging SHA instead of
5
+ * freezing staging. The release PR head is that branch; blockers are fixed on staging and cherry-picked onto it, and every pick
6
+ * is appended to the `FORGE:RELEASE` record (kept in `state.release` and as a hidden marker in the PR body). `checkChain` is the
7
+ * provenance verifier: head = snapshot + exactly the recorded picks, each one a clean cherry-pick of a staging commit.
8
+ * Picks are built with plumbing (merge-tree + commit-tree), so no working tree is needed. Every effect goes through `git`
9
+ * (`(args, {env, input}) => stdout`, throws on failure) and `io.gh`, so the module is testable with a real temp repo.
10
+ */
11
+ const REMOTE = "origin";
12
+ import { BLOCKER_LABEL } from "./release-rehearsal.mjs";
13
+ export const DEFAULT_PATTERN = "release/{date}-{n}";
14
+ const MARKER = "FORGE:RELEASE";
15
+ const REF_RE = /^[A-Za-z0-9._/-]+$/;
16
+ const json = (s) => JSON.parse(String(s || "null"));
17
+
18
+ /** `<!-- FORGE:RELEASE {...} -->`: the record as a hidden PR-body marker. */
19
+ export const recordMarker = (rec) => `<!-- ${MARKER} ${JSON.stringify(rec)} -->`;
20
+ export function parseRecord(text) {
21
+ const m = /<!-- FORGE:RELEASE (\{.*?\}) -->/s.exec(String(text ?? ""));
22
+ if (!m) return null;
23
+ try { return JSON.parse(m[1]); } catch { return null; }
24
+ }
25
+ /** `body` with its FORGE:RELEASE marker replaced (or appended). */
26
+ export const withRecord = (body, rec) => {
27
+ const text = String(body ?? "").replace(/\n*<!-- FORGE:RELEASE \{.*?\} -->\n*/s, "\n").trimEnd();
28
+ return `${text}\n\n${recordMarker(rec)}\n`;
29
+ };
30
+
31
+ /** Ref prefix of `pattern` (up to the first `{`): every branch under it counts as a release in flight. */
32
+ export const patternPrefix = (pattern = DEFAULT_PATTERN) => {
33
+ const i = pattern.indexOf("{");
34
+ return i < 0 ? pattern : pattern.slice(0, i);
35
+ };
36
+ const dateOf = (now) => new Date(now).toISOString().slice(0, 10).replace(/-/g, "");
37
+ export function branchName(pattern, now, n) {
38
+ const date = dateOf(now);
39
+ const name = pattern.replace("{date}", date).replace("{n}", String(n));
40
+ if (!REF_RE.test(name) || name.includes("..") || name.startsWith("/") || name.endsWith("/")) throw new Error(`release.branch_pattern gives an invalid branch name: ${JSON.stringify(name)}`);
41
+ return name;
42
+ }
43
+
44
+ const isAncestor = (git, a, b) => { try { git(["merge-base", "--is-ancestor", a, b]); return true; } catch { return false; } };
45
+ const fetchRef = (git, ref) => git(["fetch", "--quiet", REMOTE, `+refs/heads/${ref}:refs/remotes/${REMOTE}/${ref}`]);
46
+ const tipOf = (git, ref) => git(["rev-parse", `refs/remotes/${REMOTE}/${ref}`]).trim();
47
+ const committer = (git) => {
48
+ const cfg = (k) => { try { return git(["config", k]).trim(); } catch { return ""; } };
49
+ return { GIT_COMMITTER_NAME: cfg("user.name") || "ForgeDock release", GIT_COMMITTER_EMAIL: cfg("user.email") || "release@forgedock.invalid" };
50
+ };
51
+
52
+ /** The tree of `orig` applied onto `onto` (what `git cherry-pick` would produce); throws on a conflict. */
53
+ function pickTree(git, onto, orig) {
54
+ const parents = git(["rev-list", "--parents", "-n", "1", orig]).trim().split(/\s+/).slice(1);
55
+ if (!parents.length) throw new Error(`${orig} is a root commit`);
56
+ return git(["merge-tree", "--write-tree", `--merge-base=${parents[0]}`, onto, orig]).split("\n")[0].trim();
57
+ }
58
+
59
+ /**
60
+ * Cut `branch` from the staging tip. One release in flight: any branch under the pattern prefix refuses.
61
+ * @returns {{refused: string}|{branch, record}}
62
+ */
63
+ export async function cutSnapshot({ io, git, repo, staging, def, pattern = DEFAULT_PATTERN, id, bundle = [] }) {
64
+ const prefix = patternPrefix(pattern);
65
+ const live = git(["ls-remote", "--heads", REMOTE, `${prefix}*`]).trim().split("\n").filter(Boolean).map((l) => l.split(/\s+/)[1]?.replace("refs/heads/", ""));
66
+ if (live.length) return { refused: `a release branch is already in flight (${live.join(", ")}); one release per repo: finish it with forgedock release --resume <id> or delete the branch` };
67
+ const day = pattern.replace("{date}", dateOf(io.now())).split("{n}")[0];
68
+ const prior = (json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--state", "all", "--limit", "100", "--json", "headRefName"])) ?? []).filter((p) => String(p.headRefName).startsWith(day)).length;
69
+ const branch = branchName(pattern, io.now(), prior + 1);
70
+ fetchRef(git, staging); fetchRef(git, def);
71
+ const snapshot = tipOf(git, staging);
72
+ git(["push", "--quiet", REMOTE, `${snapshot}:refs/heads/${branch}`]);
73
+ const issues = [...new Set(bundle.flatMap((p) => (p.closingIssuesReferences ?? []).map((i) => i.number)))].sort((a, b) => a - b);
74
+ return { branch, record: { v: 1, id, branch, snapshot, range: { base: tipOf(git, def), head: snapshot }, bundle: bundle.map((p) => p.number), issues, picks: [] } };
75
+ }
76
+
77
+ /** The PR head record into the PR body and the state. */
78
+ export async function writeRecord(ctx) {
79
+ const { io, repo, state } = ctx;
80
+ const { pr } = state.steps["release-pr"].result;
81
+ const body = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "body"]))?.body ?? "";
82
+ await io.gh(["pr", "edit", String(pr), "--repo", repo, "--body", withRecord(body, state.release)]);
83
+ }
84
+
85
+ /** Merged staging PRs that fix a blocker: labelled `release-blocker`, or closing one of `issues` or an issue labelled so. */
86
+ async function blockerPrs({ io, repo, staging, issues }) {
87
+ const labelled = new Set((json(await io.gh(["issue", "list", "--repo", repo, "--label", BLOCKER_LABEL, "--state", "all", "--limit", "200", "--json", "number"])) ?? []).map((i) => i.number));
88
+ for (const n of issues) labelled.add(n);
89
+ const prs = json(await io.gh(["pr", "list", "--repo", repo, "--base", staging, "--state", "merged", "--limit", "200", "--json", "number,mergeCommit,mergedAt,labels,closingIssuesReferences"])) ?? [];
90
+ return prs
91
+ .filter((p) => p.mergeCommit?.oid && ((p.labels ?? []).some((l) => l.name === BLOCKER_LABEL) || (p.closingIssuesReferences ?? []).some((i) => labelled.has(i.number))))
92
+ .sort((a, b) => String(a.mergedAt).localeCompare(String(b.mergedAt)));
93
+ }
94
+
95
+ /**
96
+ * Cherry-pick the merged blocker fixes (not yet on the branch) onto `release/<id>`, fast-forward the branch and record the picks.
97
+ * The new picks are saved in the state before the push, so a kill in between is repaired by the push of the last pick at the next call.
98
+ * @returns {{picked: number[]}|{err: string}}
99
+ */
100
+ export async function pickFixes(ctx, { issues = [] } = {}) {
101
+ const { io, git, repo, staging, state } = ctx;
102
+ const rec = state.release;
103
+ if (!rec) return { err: "no FORGE:RELEASE record in the release state" };
104
+ const push = (sha) => git(["push", "--quiet", REMOTE, `${sha}:refs/heads/${rec.branch}`]);
105
+ if (rec.picks.length) { try { push(rec.picks.at(-1).sha); } catch { /* already there, or the objects are gone: the checks below decide */ } }
106
+ fetchRef(git, staging);
107
+ const stagingTip = tipOf(git, staging);
108
+ let head = rec.picks.at(-1)?.sha ?? rec.snapshot;
109
+ const picked = [];
110
+ for (const p of await blockerPrs({ io, repo, staging, issues })) {
111
+ const orig = p.mergeCommit.oid;
112
+ if (rec.picks.some((k) => k.orig === orig) || isAncestor(git, orig, head)) continue;
113
+ if (!isAncestor(git, orig, stagingTip)) return { err: `fix #${p.number} (${orig}) is not on ${staging}` };
114
+ let tree;
115
+ try { tree = pickTree(git, head, orig); } catch (e) { return { err: `cherry-pick of #${p.number} (${orig}) onto ${rec.branch} conflicts: resolve it by hand or use release.fix_mode: recut` }; }
116
+ const [an, ae, ad] = git(["log", "-1", "--format=%an%n%ae%n%aI", orig]).trim().split("\n");
117
+ const msg = `${git(["log", "-1", "--format=%B", orig]).trimEnd()}\n\n(cherry picked from commit ${orig})\n`;
118
+ const sha = git(["commit-tree", tree, "-p", head, "-F", "-"], { input: msg, env: { GIT_AUTHOR_NAME: an, GIT_AUTHOR_EMAIL: ae, GIT_AUTHOR_DATE: ad, ...committer(git) } }).trim();
119
+ rec.picks.push({ sha, orig, pr: p.number });
120
+ picked.push(p.number);
121
+ head = sha;
122
+ }
123
+ if (!picked.length) return { picked };
124
+ ctx.save();
125
+ push(head);
126
+ await writeRecord(ctx);
127
+ return { picked };
128
+ }
129
+
130
+ /** `fix_mode: recut`: move the (unmerged) release branch to the current staging tip and start the record's picks over. */
131
+ export async function recut(ctx) {
132
+ const { git, staging, state } = ctx;
133
+ const rec = state.release;
134
+ fetchRef(git, staging);
135
+ const tip = tipOf(git, staging);
136
+ if (tip === (rec.picks.at(-1)?.sha ?? rec.snapshot) && !rec.picks.length) return { recut: false };
137
+ rec.recuts = (rec.recuts ?? 0) + 1;
138
+ rec.snapshot = tip; rec.picks = []; rec.range = { ...rec.range, head: tip };
139
+ ctx.save();
140
+ git(["push", "--quiet", "--force", REMOTE, `${tip}:refs/heads/${rec.branch}`]);
141
+ await writeRecord(ctx);
142
+ return { recut: true, snapshot: tip };
143
+ }
144
+
145
+ /**
146
+ * Provenance check: `sha` = snapshot + the first k recorded picks (all of them with `exact`), linear, each commit the clean
147
+ * cherry-pick of its staging commit (same tree as `git cherry-pick` of it onto the previous commit).
148
+ * @returns {{ok: true, picks: number}|{ok: false, why: string}}
149
+ */
150
+ export function checkChain({ git, record, sha, staging, exact = false }) {
151
+ const no = (why) => ({ ok: false, why });
152
+ try {
153
+ fetchRef(git, staging);
154
+ const stagingTip = tipOf(git, staging);
155
+ if (!record?.snapshot) return no("no FORGE:RELEASE record");
156
+ if (!isAncestor(git, record.snapshot, stagingTip)) return no(`snapshot ${record.snapshot} is not on ${staging}`);
157
+ if (sha !== record.snapshot && !isAncestor(git, record.snapshot, sha)) return no(`${sha} does not descend from the snapshot ${record.snapshot}`);
158
+ const rows = git(["rev-list", "--reverse", "--parents", `${record.snapshot}..${sha}`]).trim().split("\n").filter(Boolean).map((l) => l.split(/\s+/));
159
+ if (rows.length > record.picks.length) return no(`${rows.length} commit(s) on the release branch, ${record.picks.length} recorded cherry-pick(s): ${rows.slice(record.picks.length).map((r) => r[0].slice(0, 12)).join(", ")} not recorded`);
160
+ if (exact && rows.length !== record.picks.length) return no(`head is at ${rows.length} of ${record.picks.length} recorded cherry-picks`);
161
+ let prev = record.snapshot;
162
+ for (const [i, [c, ...parents]] of rows.entries()) {
163
+ const pick = record.picks[i];
164
+ if (c !== pick.sha) return no(`commit ${c.slice(0, 12)} is not the recorded pick ${pick.sha.slice(0, 12)}`);
165
+ if (parents.length !== 1 || parents[0] !== prev) return no(`commit ${c.slice(0, 12)} is not a linear child of ${prev.slice(0, 12)}`);
166
+ if (!isAncestor(git, pick.orig, stagingTip)) return no(`${pick.orig} is not a ${staging} commit`);
167
+ if (!git(["log", "-1", "--format=%B", c]).includes(`(cherry picked from commit ${pick.orig})`)) return no(`commit ${c.slice(0, 12)} does not name ${pick.orig} as its cherry-pick source`);
168
+ if (git(["rev-parse", `${c}^{tree}`]).trim() !== pickTree(git, prev, pick.orig)) return no(`commit ${c.slice(0, 12)} differs from the cherry-pick of ${pick.orig.slice(0, 12)}`);
169
+ prev = c;
170
+ }
171
+ return { ok: true, picks: rows.length };
172
+ } catch (e) { return no(`could not verify: ${String(e.message).split("\n")[0]}`); }
173
+ }
174
+
175
+ /** `forgedock release verify <sha>`: the record from the PR whose head is `sha`, then `checkChain`. */
176
+ export async function verifyRelease({ io, git, repo, staging, sha }) {
177
+ let prs = [];
178
+ try { prs = json(await io.gh(["api", `repos/${repo}/commits/${sha}/pulls`, "--jq", "[.[] | {number, body}]"])) ?? []; } catch { /* unknown commit: no record below */ }
179
+ const found = prs.map((p) => ({ number: p.number, record: parseRecord(p.body) })).find((p) => p.record);
180
+ if (!found) return { ok: false, why: `no pull request with a FORGE:RELEASE record contains ${sha}` };
181
+ try { git(["fetch", "--quiet", REMOTE, sha]); } catch { /* sha may already be local, or not fetchable by id */ }
182
+ return { ...checkChain({ git, record: found.record, sha, staging }), pr: found.number };
183
+ }
184
+
185
+ /** Delete the release branch after post-merge; a missing branch is fine. */
186
+ export function cleanupSnapshot({ git, branch }) {
187
+ try { git(["push", "--quiet", REMOTE, "--delete", branch]); return { deleted: true }; } catch (e) { return { deleted: false, why: String(e.message).split("\n")[0] }; }
188
+ }