forgedock 1.52.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 (233) 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 +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,254 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Review and fix steps of `forgedock release` (#5208 part 2, #5212). `reviewStep` runs the staging panel the way an operator
5
+ * session would (commands/review-pr-staging.md) but as one job: pre-dispatch, one isolated runner session per brief plus the
6
+ * spec-owned panel, the /test-gate output, a head check (a moved head is a `--delta` pass, never a finalize), finalize with
7
+ * one re-ask of reviewers whose findings block is missing, filing, NOTEs in the PR body, then `--summary`. `fixStep` starts a
8
+ * fix lane per blocking finding on the staging branch and re-reviews the delta, bounded like lanes. Every effect goes through
9
+ * a seam (`ctx.io.review`, default `realSeam`) so the steps are unit-tested without gh, git or a model.
10
+ */
11
+ import { execFileSync, spawn } from "node:child_process";
12
+ import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, rmSync } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { delimiter, join } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+ import { runHostPreflight } from "./release-preflight.mjs";
17
+ import { reviewStagingJson, reviewStagingIo, CI_EXCLUDED_CHECKS } from "../review-staging.mjs";
18
+ import { pickFixes, recut } from "./release-snapshot.mjs";
19
+
20
+ /** Delta passes after a head move, and fix-lane rounds: past either the job blocks for the manual path. */
21
+ export const MAX_DELTA_PASSES = 2;
22
+ export const MAX_FIX_ROUNDS = 2;
23
+ const REVIEW_MS = 45 * 60_000, LANE_MS = 3 * 60 * 60_000;
24
+ const ROOT = fileURLToPath(new URL("../..", import.meta.url));
25
+ const SEVERE = new Set(["CRITICAL", "HIGH"]);
26
+ const MANUAL = "use the manual path: forgedock review-staging <PR> (commands/review-pr-staging.md)";
27
+ const blocked = (why) => ({ blocked: true, reason: `${why}; ${MANUAL}` });
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
+
42
+ /** Reviewers whose prompts are prose in the spec (not briefed by the pre-dispatch): marker domain -> spec phase. */
43
+ export const SPEC_PANEL = [
44
+ { domain: "material-change", phase: "Phase 2 (material-change)" },
45
+ { domain: "bug-hunter-general", phase: "Phase 3 (bug hunters)" },
46
+ { domain: "code-quality", phase: "Phase 4 (code-quality)" },
47
+ { domain: "regression-risk", phase: "Phase 6 (regression-risk)" },
48
+ ];
49
+
50
+ const specPrompt = (p, m, def) => [
51
+ `You are the ${p.domain} reviewer of the staging -> ${def} release review of PR #${m.pr}, head ${m.headSha}.`,
52
+ `Read commands/review-pr-staging.md, ${p.phase}, and do exactly what that phase asks for this PR (bundle PRs: ${(m.bundle ?? []).join(" ") || "none"}; scope mode ${m.scopeMode}; the scope lists are in ${m.pr}_scope.json next to ${m.contextFile}).`,
53
+ `Post your own comment on the PR with \`gh pr comment\`: it starts with \`<!-- FORGE:REVIEW-AGENT:${p.domain} -->\`, then the line \`Reviewed-SHA: ${m.headSha}\`, and ends with the structured findings block (REVIEW-FINDINGS-START/END, FINDING markers; an empty block when nothing is found).`,
54
+ "Read-only git rule: never checkout, switch, reset, stash or merge in the shared checkout.",
55
+ ].join("\n\n");
56
+
57
+ /** `Reviewers` named by a finalize stop: delivery (`missing findings comment(s) for: a b`) or extract (`no structured findings block from: a, b.`). */
58
+ export function missingReviewers(lines) {
59
+ const t = (lines ?? []).join("\n");
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);
61
+ return m ? m[1].split(/[\s,]+/).filter((d) => /^[a-z0-9-]+$/.test(d)) : [];
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("; ")}` : "");
69
+ const headMoved = (lines) => /head moved since/.test((lines ?? []).join("\n"));
70
+
71
+ /** One review round at the current head: dispatch, test gate, head check, finalize. @returns {{moved: string}|{fail}|{ok}} */
72
+ async function reviewRound({ seam, pr, def, delta }) {
73
+ const pre = await seam.pre({ pr, delta });
74
+ const m = pre.data;
75
+ if (pre.code !== 0 || !m?.headSha) return { fail: `the pre-dispatch stopped (exit ${pre.code}): ${(pre.lines ?? []).slice(-2).join(" | ").slice(0, 300)}` };
76
+ m.pr ??= pr;
77
+ // A delta pass credits the spec panel from the earlier pass: only the briefs the delta touches are dispatched.
78
+ const agents = [
79
+ ...m.briefs.map((b) => ({ domain: b.domain, prompt: () => seam.readFile(b.path) })),
80
+ ...(m.delta ? [] : SPEC_PANEL.map((p) => ({ domain: p.domain, prompt: () => specPrompt(p, m, def) }))),
81
+ ];
82
+ const prompts = new Map(agents.map((a) => [a.domain, a.prompt()]));
83
+ seam.markLaunched(m.launchedFile, agents.map((a) => a.domain), m.headSha);
84
+ const send = (domain, note = "") => seam.runAgent({ role: `release-review-${domain}`, issue: pr, prompt: note ? `${prompts.get(domain)}\n\n${note}` : prompts.get(domain) });
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)));
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.` });
89
+ const gateFile = seam.saveTestGate(pr, gate?.text ?? "");
90
+
91
+ // The head moved while the panel ran: finalize would refuse, and must never run at the moved head. Delta from what was reviewed.
92
+ if ((await seam.headOf(pr)) !== m.headSha) return { moved: m.headSha };
93
+ let fin = await seam.finalize({ pr, testGateOutput: gateFile });
94
+ if (fin.code !== 0 || !fin.data) {
95
+ if (headMoved(fin.lines)) return { moved: m.headSha };
96
+ const missing = missingReviewers(fin.lines).filter((d) => prompts.has(d));
97
+ if (!missing.length) return { fail: `finalize stopped (exit ${fin.code}): ${(fin.lines ?? []).slice(-2).join(" | ").slice(0, 300)}${failureNote(failures)}` };
98
+ // once: the same brief with the note the spec prescribes; a second miss is a degraded panel
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.")));
100
+ fin = await seam.finalize({ pr, testGateOutput: gateFile });
101
+ if (fin.code !== 0 || !fin.data) {
102
+ if (headMoved(fin.lines)) return { moved: m.headSha };
103
+ return { fail: `reviewer findings block still missing after one re-ask (${missing.join(", ")}): degraded panel${failureNote(failures)}` };
104
+ }
105
+ }
106
+ return { ok: fin.data };
107
+ }
108
+
109
+ /** The whole review of PR `pr`: rounds until one finalizes at its own head. @returns the step result or `{blocked}`. */
110
+ async function runReview({ seam, pr, def, delta = null }) {
111
+ let st = null;
112
+ for (let pass = 0; ; pass++) {
113
+ const r = await reviewRound({ seam, pr, def, delta });
114
+ if (r.fail) return blocked(r.fail);
115
+ if (r.ok) { st = r.ok; break; }
116
+ if (pass >= MAX_DELTA_PASSES) return blocked(`head of #${pr} kept moving during the review (${MAX_DELTA_PASSES} delta passes)`);
117
+ delta = r.moved;
118
+ }
119
+ const filed = [], blocking = [];
120
+ for (const item of st.toFile ?? []) {
121
+ const n = await seam.fileIssue({ item, pr, head: st.head });
122
+ if (!n) return blocked(`could not file the finding "${item.title ?? item.id}"`);
123
+ filed.push(n);
124
+ if (SEVERE.has(String(item.severity ?? "").toUpperCase())) blocking.push(n);
125
+ }
126
+ if ((st.notes ?? []).length) await seam.addNotes(pr, st.notes);
127
+ const sum = await seam.summary({ pr, filed });
128
+ if (!sum.data) return blocked(`the gate summary was not posted (exit ${sum.code}): ${(sum.lines ?? []).slice(-1).join("").slice(0, 200)}`);
129
+ return { pr, head: st.head, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, filed, blocking, delta: st.delta?.from ?? null };
130
+ }
131
+
132
+ /** Review step. @returns {{pr, head, verdict, marker, filed, blocking}|{blocked: true, reason: string}} */
133
+ export async function reviewStep(ctx) {
134
+ const pr = ctx.state?.steps?.["release-pr"]?.result?.pr;
135
+ if (!pr) return blocked("no release PR recorded by the release-pr step");
136
+ return runReview({ seam: seamOf(ctx), pr, def: ctx.def });
137
+ }
138
+
139
+ /** Fix step: nothing to do on GATE_PASS; else a lane per blocking issue on the staging branch, then a delta review, up to MAX_FIX_ROUNDS. */
140
+ export async function fixStep(ctx) {
141
+ let r = ctx.state?.steps?.review?.result;
142
+ if (!r?.pr) return blocked("no review result recorded by the review step");
143
+ const seam = seamOf(ctx);
144
+ for (let round = 0; r.marker !== "FORGE:GATE_PASS"; round++) {
145
+ if (round >= MAX_FIX_ROUNDS) return blocked(`still ${r.verdict} after ${MAX_FIX_ROUNDS} fix round(s)`);
146
+ // Blocking findings are already filed issues; red CI has none, so it gets one issue naming the failing checks.
147
+ const issues = [...(r.blocking ?? [])];
148
+ if (r.ciFailing > 0) {
149
+ const n = await seam.fileCiIssue({ pr: r.pr, head: r.head });
150
+ if (!n) return blocked(`could not file an issue for the red CI of #${r.pr}`);
151
+ issues.push(n);
152
+ }
153
+ if (!issues.length) return blocked(`${r.verdict} with neither a blocking finding nor red CI to fix`);
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;
157
+ const lane = await seam.runLane({ issue, lane: ctx.staging });
158
+ if (lane?.terminalReason !== "merged") return blocked(`fix lane for #${issue} ended ${lane?.terminalReason ?? "without a result"}`);
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
+ }
170
+ const next = await runReview({ seam, pr: r.pr, def: ctx.def, delta: r.head });
171
+ if (next.blocked) return next;
172
+ r = next;
173
+ ctx.state.steps.review = { ...ctx.state.steps.review, result: r };
174
+ ctx.save();
175
+ }
176
+ return { verdict: r.verdict, head: r.head };
177
+ }
178
+
179
+ const seamOf = (ctx) => ctx.io.review ?? (ctx.seam ??= realSeam(ctx));
180
+
181
+ /** Real effects of the review steps: the review-staging library, the engine runner, the filing scripts, gh and a lane process. */
182
+ export function realSeam({ repo, def, env = process.env, cwd = process.cwd(), makeRunner = null, gh: ghIn = null }) {
183
+ const rs = { ...reviewStagingIo(), cwd, env };
184
+ const sd = env.FORGE_SCRATCHPAD || join(cwd, ".forge-scratch");
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 }));
195
+ return {
196
+ pre: ({ pr, delta }) => reviewStagingJson([String(pr), ...(delta ? ["--delta", delta] : [])], rs),
197
+ finalize: ({ pr, testGateOutput }) => reviewStagingJson([String(pr), "--finalize", "--test-gate-output", testGateOutput], rs),
198
+ summary: ({ pr, filed }) => reviewStagingJson([String(pr), "--summary", ...(filed.length ? ["--filed", filed.join(",")] : [])], rs),
199
+ headOf: (pr) => gh(["pr", "view", String(pr), "-R", repo, "--json", "headRefOid", "--jq", ".headRefOid"]).trim(),
200
+ readFile: (p) => readFileSync(p, "utf8"),
201
+ markLaunched: (file, domains, head) => { appendFileSync(file, domains.map((d) => `${d}\n`).join("")); writeFileSync(`${file}.head`, `${head}\n`); },
202
+ saveTestGate: (pr, text) => { mkdirSync(sd, { recursive: true }); const f = join(sd, `${pr}_test_gate_output.txt`); writeFileSync(f, text); return f; },
203
+ runAgent: async ({ role, issue, prompt }) => {
204
+ runner ??= makeRunner ? makeRunner() : (await import("./effects.mjs")).makeLeanRunner();
205
+ // not readOnly: each reviewer posts its own PR comment
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; }
214
+ },
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 */ }
222
+ const rows = JSON.parse(gh(["pr", "checks", String(pr), "-R", repo, "--json", "name,bucket"]));
223
+ const names = rows.filter((c) => c.bucket === "fail" && !CI_EXCLUDED_CHECKS.includes(c.name)).map((c) => c.name);
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 });
225
+ },
226
+ fileIssue: async ({ item, pr }) => {
227
+ const dir = mkdtempSync(join(tmpdir(), "release-finding-"));
228
+ try {
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");
230
+ const bodyFile = join(dir, "body.md");
231
+ writeFileSync(bodyFile, withIntegrityMarker(body, `release-${pr}-${item.id ?? item.title ?? "finding"}`));
232
+ let out = "";
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 ?? ""); }
234
+ try {
235
+ return Number(/ISSUE_NUM=(\d+)/.exec(execFileSync("bash", [join(ROOT, "scripts", "review-finalize.sh"), "file-verify", "--pr", String(pr), "--repo", repo, "--context", join(sd, `review-ctx-${pr}.json`)], { encoding: "utf8", input: out, cwd, env }))?.[1]) || null;
236
+ } catch { return null; }
237
+ } finally { rmSync(dir, { recursive: true, force: true }); }
238
+ },
239
+ addNotes: async (pr, notes) => {
240
+ const body = JSON.parse(gh(["pr", "view", String(pr), "-R", repo, "--json", "body"])).body ?? "";
241
+ const list = notes.map((n) => (n.startsWith("-") ? n : `- ${n}`)).join("\n");
242
+ const next = body.includes("## Non-blocking notes") ? `${body.trimEnd()}\n${list}\n` : `${body.trimEnd()}\n\n## Non-blocking notes\n${list}\n`;
243
+ gh(["pr", "edit", String(pr), "-R", repo, "--body-file", "-"], next);
244
+ },
245
+ runLane: ({ issue, lane }) => new Promise((resolve) => {
246
+ const dir = mkdtempSync(join(tmpdir(), "release-lane-"));
247
+ const rf = join(dir, "result.json");
248
+ const child = spawn(process.execPath, [join(ROOT, "bin", "forgedock.mjs"), "run-issue", String(issue), "--lane", lane, "--result-file", rf], { cwd, env, stdio: "ignore" });
249
+ const timer = setTimeout(() => child.kill("SIGTERM"), LANE_MS);
250
+ const done = () => { clearTimeout(timer); let r = null; try { r = JSON.parse(readFileSync(rf, "utf8")); } catch { /* no result */ } rmSync(dir, { recursive: true, force: true }); resolve(r); };
251
+ child.on("error", done); child.on("exit", done);
252
+ }),
253
+ };
254
+ }
@@ -0,0 +1,307 @@
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 { reviewStep, fixStep, missingReviewers, SPEC_PANEL, MAX_DELTA_PASSES, MAX_FIX_ROUNDS, realSeam, withIntegrityMarker } from "./release-review.mjs";
6
+ import { readFileSync } from "node:fs";
7
+ import { reviewStagingJson } from "../review-staging.mjs";
8
+
9
+ const H1 = "a".repeat(40), H2 = "b".repeat(40);
10
+ const manifest = (head, delta = null) => ({ pr: 7, headSha: head, bundle: [1, 2], scopeMode: "full", contextFile: "/sd/review-ctx-7.json", launchedFile: "/sd/7_launched", briefs: [{ domain: "security", path: "/sd/brief-security.md" }], delta });
11
+ const fin = (extra = {}) => ({ code: 0, data: { head: H1, toFile: [], notes: [], ...extra }, lines: [] });
12
+
13
+ /** Seam fake: `heads` is what headOf answers in turn; `fins` what finalize answers in turn. */
14
+ function fakeSeam({ heads = [H1], fins = [fin()], summary, lanes = [] } = {}) {
15
+ const log = [], agents = [];
16
+ let h = 0, f = 0, l = 0, n = 100;
17
+ return {
18
+ log, agents,
19
+ pre: async (a) => { log.push(["pre", a.delta]); return { code: 0, data: manifest(a.delta ? heads[heads.length - 1] : H1, a.delta ? { from: a.delta, files: ["x"] } : null), lines: [] }; },
20
+ finalize: async () => { log.push(["finalize"]); return fins[Math.min(f++, fins.length - 1)]; },
21
+ summary: async (a) => { log.push(["summary", a.filed]); return summary ?? { code: 0, data: { verdict: "APPROVE FOR DEPLOY", marker: "FORGE:GATE_PASS", ciFailing: 0 }, lines: [] }; },
22
+ headOf: async () => heads[Math.min(h++, heads.length - 1)],
23
+ readFile: (p) => `brief ${p}`,
24
+ markLaunched: (file, domains) => log.push(["launched", domains]),
25
+ saveTestGate: () => "/sd/7_test_gate_output.txt",
26
+ runAgent: async (a) => { agents.push(a.role + (a.prompt.includes("findings block required") ? ":reask" : "")); return { text: "ok" }; },
27
+ fileIssue: async ({ item }) => { log.push(["file", item.title]); return n++; },
28
+ fileCiIssue: async () => { log.push(["ci-issue"]); return n++; },
29
+ issueMerged: async () => false,
30
+ addNotes: async (pr, notes) => log.push(["notes", notes]),
31
+ runLane: async (a) => { log.push(["lane", a.issue, a.lane]); return lanes[l++] ?? { terminalReason: "merged" }; },
32
+ };
33
+ }
34
+ const ctx = (seam, steps = {}) => ({ io: { review: seam }, repo: "o/r", def: "main", staging: "staging", state: { steps: { "release-pr": { result: { pr: 7 } }, ...steps } }, save() {} });
35
+
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
+
54
+ it("realSeam exposes every effect the steps use, matching the fake seam", () => {
55
+ const real = Object.keys(realSeam({ repo: "o/r", def: "main", env: {}, cwd: "/tmp" })).sort();
56
+ assert.deepEqual(real, Object.keys(fakeSeam()).filter((k) => k !== "log" && k !== "agents").sort());
57
+ });
58
+
59
+ it("runs the briefs and the spec panel in parallel, then test gate, finalize and summary in order", async () => {
60
+ const s = fakeSeam();
61
+ const r = await reviewStep(ctx(s));
62
+ assert.equal(r.marker, "FORGE:GATE_PASS");
63
+ assert.deepEqual(s.agents.slice().sort(), ["release-review-security", "release-test-gate", ...SPEC_PANEL.map((p) => `release-review-${p.domain}`)].sort());
64
+ assert.deepEqual(s.log.map((e) => e[0]), ["pre", "launched", "finalize", "summary"]);
65
+ assert.deepEqual(s.log[1][1], ["security", ...SPEC_PANEL.map((p) => p.domain)]);
66
+ });
67
+
68
+ it("R2: a head move triggers a --delta pass from the reviewed sha and never finalizes at the moved head", async () => {
69
+ const s = fakeSeam({ heads: [H2, H2] });
70
+ const r = await reviewStep(ctx(s));
71
+ const pres = s.log.filter((e) => e[0] === "pre");
72
+ assert.deepEqual(pres.map((e) => e[1]), [null, H1], "second pass is --delta <reviewed sha>");
73
+ assert.equal(s.log.filter((e) => e[0] === "finalize").length, 1, "finalize ran once, after the delta pass");
74
+ assert.ok(s.log.findIndex((e) => e[0] === "finalize") > s.log.findLastIndex((e) => e[0] === "pre"));
75
+ assert.equal(r.verdict, "APPROVE FOR DEPLOY");
76
+ // the delta pass credits the spec panel: only the briefs are re-run
77
+ assert.equal(s.agents.filter((a) => a === "release-review-material-change").length, 1);
78
+ });
79
+
80
+ it("a finalize refusal for a moved head also becomes a delta pass", async () => {
81
+ const s = fakeSeam({ fins: [{ code: 1, data: null, lines: ["REVIEW_RESULT: status: BLOCKED, blocker: head moved since the review (aaaaaaa -> bbbbbbb)"] }, fin()] });
82
+ await reviewStep(ctx(s));
83
+ assert.equal(s.log.filter((e) => e[0] === "pre").length, 2);
84
+ });
85
+
86
+ it("blocks when the head keeps moving", async () => {
87
+ const s = fakeSeam();
88
+ let i = 0;
89
+ s.headOf = async () => String(++i).padStart(40, "c");
90
+ const r = await reviewStep(ctx(s));
91
+ assert.equal(r.blocked, true);
92
+ assert.match(r.reason, new RegExp(`${MAX_DELTA_PASSES} delta passes`));
93
+ });
94
+
95
+ it("re-asks only the reviewer with a missing findings block, once, then finalizes", async () => {
96
+ const s = fakeSeam({ fins: [{ code: 1, data: null, lines: ["REVIEW DELIVERY FAILURE: missing findings comment(s) for: security code-quality"] }, fin()] });
97
+ const r = await reviewStep(ctx(s));
98
+ assert.equal(r.blocked, undefined);
99
+ assert.deepEqual(s.agents.filter((a) => a.endsWith(":reask")).sort(), ["release-review-code-quality:reask", "release-review-security:reask"]);
100
+ });
101
+
102
+ it("a second miss is a degraded panel (blocked, no further re-ask)", async () => {
103
+ const bad = { code: 1, data: null, lines: ["REVIEW DELIVERY FAILURE: no structured findings block from: security."] };
104
+ const s = fakeSeam({ fins: [bad] });
105
+ const r = await reviewStep(ctx(s));
106
+ assert.equal(r.blocked, true);
107
+ assert.match(r.reason, /degraded panel/);
108
+ assert.equal(s.agents.filter((a) => a.endsWith(":reask")).length, 1);
109
+ assert.equal(s.log.filter((e) => e[0] === "summary").length, 0);
110
+ });
111
+
112
+ it("files each FILE item, lists NOTEs in the PR body, then summarises with --filed", async () => {
113
+ const s = fakeSeam({ fins: [fin({ toFile: [{ title: "a", severity: "HIGH" }, { title: "b", severity: "LOW" }], notes: ["- n1"] })] });
114
+ const r = await reviewStep(ctx(s));
115
+ assert.deepEqual(s.log.slice(-4).map((e) => e[0]), ["file", "file", "notes", "summary"]);
116
+ assert.deepEqual(s.log.at(-1)[1], [100, 101]);
117
+ assert.deepEqual(r.blocking, [100], "only CRITICAL/HIGH findings block");
118
+ });
119
+
120
+ it("blocks when filing fails, before any summary is posted", async () => {
121
+ const s = fakeSeam({ fins: [fin({ toFile: [{ title: "a", severity: "HIGH" }] })] });
122
+ s.fileIssue = async () => null;
123
+ const r = await reviewStep(ctx(s));
124
+ assert.equal(r.blocked, true);
125
+ assert.equal(s.log.filter((e) => e[0] === "summary").length, 0);
126
+ });
127
+
128
+ it("blocks without a release PR", async () => {
129
+ assert.equal((await reviewStep({ ...ctx(fakeSeam()), state: { steps: {} } })).blocked, true);
130
+ });
131
+ });
132
+
133
+ describe("fixStep", () => {
134
+ const failed = { pr: 7, head: H1, verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", blocking: [101], filed: [101], ciFailing: 0 };
135
+
136
+ it("does nothing on GATE_PASS", async () => {
137
+ const s = fakeSeam();
138
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, verdict: "APPROVE FOR DEPLOY", marker: "FORGE:GATE_PASS" } } }));
139
+ assert.equal(r.blocked, undefined);
140
+ assert.equal(s.log.length, 0);
141
+ });
142
+
143
+ it("runs a lane on the staging branch per blocking issue, then a delta review from the reviewed head", async () => {
144
+ const s = fakeSeam({ heads: [H2] });
145
+ const c = ctx(s, { review: { result: failed } });
146
+ const r = await fixStep(c);
147
+ assert.deepEqual(s.log[0], ["lane", 101, "staging"]);
148
+ assert.deepEqual(s.log[1], ["pre", H1]);
149
+ assert.equal(r.verdict, "APPROVE FOR DEPLOY");
150
+ });
151
+
152
+ it("is bounded: blocks once the rounds are spent", async () => {
153
+ const bad = { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] };
154
+ const s = fakeSeam({ heads: [H2], summary: bad, fins: [fin({ toFile: [{ title: "x", severity: "CRITICAL" }] })] });
155
+ const r = await fixStep(ctx(s, { review: { result: failed } }));
156
+ assert.equal(r.blocked, true);
157
+ assert.equal(s.log.filter((e) => e[0] === "lane").length, MAX_FIX_ROUNDS);
158
+ });
159
+
160
+ it("blocks when a lane does not merge", async () => {
161
+ const s = fakeSeam({ lanes: [{ terminalReason: "needs-human" }] });
162
+ assert.equal((await fixStep(ctx(s, { review: { result: failed } }))).blocked, true);
163
+ });
164
+
165
+ it("red CI with no finding files one CI issue and runs a lane on it, then reviews the delta", async () => {
166
+ const s = fakeSeam({ heads: [H2] });
167
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], ciFailing: 2 } } }));
168
+ assert.deepEqual(s.log.slice(0, 3), [["ci-issue"], ["lane", 100, "staging"], ["pre", H1]]);
169
+ assert.equal(r.blocked, undefined);
170
+ });
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
+
189
+ it("a blocking finding and red CI together get a lane each", async () => {
190
+ const s = fakeSeam({ heads: [H2] });
191
+ await fixStep(ctx(s, { review: { result: { ...failed, ciFailing: 1 } } }));
192
+ assert.deepEqual(s.log.filter((e) => e[0] === "lane").map((e) => e[1]), [101, 100]);
193
+ });
194
+
195
+ it("blocks when the verdict is not a pass but there is nothing to fix", async () => {
196
+ assert.match((await fixStep(ctx(fakeSeam(), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
197
+ });
198
+ });
199
+
200
+ describe("missingReviewers", () => {
201
+ it("reads the names from the delivery and extract messages", () => {
202
+ assert.deepEqual(missingReviewers(["x", "REVIEW DELIVERY FAILURE: missing findings comment(s) for: a b-c"]), ["a", "b-c"]);
203
+ assert.deepEqual(missingReviewers(["REVIEW DELIVERY FAILURE: no structured findings block from: a, b. Re-dispatch them once"]), ["a", "b"]);
204
+ assert.deepEqual(missingReviewers(["nothing"]), []);
205
+ });
206
+ });
207
+
208
+ describe("reviewStagingJson (library entry)", () => {
209
+ const io = (gh) => ({ root: "/r", env: {}, cwd: "/c", run: async () => ({ code: 0, stdout: "", stderr: "" }), gh, readFile: () => { throw new Error("nofile"); }, writeFile() {}, rm() {}, mkdir() {}, out: () => assert.fail("printed"), err: () => assert.fail("printed") });
210
+ it("returns a stop as {code, lines} without printing and never throws", async () => {
211
+ const r = await reviewStagingJson(["--summary"], io(async () => { throw new Error("no gh"); }));
212
+ assert.equal(r.data, null);
213
+ assert.ok(r.code >= 1);
214
+ assert.ok(r.lines.length > 0);
215
+ });
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
+ });