forgedock 1.52.0 → 1.53.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 (93) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -0
  2. package/bin/engine/telemetry-seam.mjs +4 -2
  3. package/bin/engine-cli.mjs +53 -16
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +15 -1
  7. package/bin/lean/account-watch.mjs +28 -0
  8. package/bin/lean/account-watch.test.mjs +30 -0
  9. package/bin/lean/activation.mjs +20 -0
  10. package/bin/lean/activation.test.mjs +14 -1
  11. package/bin/lean/basered.mjs +115 -0
  12. package/bin/lean/basered.test.mjs +66 -0
  13. package/bin/lean/batch-health.mjs +40 -6
  14. package/bin/lean/batch-health.test.mjs +34 -1
  15. package/bin/lean/batch.mjs +41 -2
  16. package/bin/lean/batch.test.mjs +104 -2
  17. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  18. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  19. package/bin/lean/conformance.e2e.test.mjs +1 -1
  20. package/bin/lean/conformance.mjs +195 -22
  21. package/bin/lean/conformance.test.mjs +152 -5
  22. package/bin/lean/effects.mjs +8 -4
  23. package/bin/lean/execution.mjs +19 -3
  24. package/bin/lean/execution.test.mjs +39 -0
  25. package/bin/lean/findinglabel.mjs +16 -0
  26. package/bin/lean/findinglabel.test.mjs +39 -0
  27. package/bin/lean/issuewatch-release.mjs +6 -2
  28. package/bin/lean/issuewatch-release.test.mjs +16 -0
  29. package/bin/lean/issuewatch.mjs +11 -1
  30. package/bin/lean/lanelock.mjs +14 -0
  31. package/bin/lean/lean.mjs +165 -34
  32. package/bin/lean/lean.test.mjs +289 -9
  33. package/bin/lean/light.mjs +48 -7
  34. package/bin/lean/light.test.mjs +37 -3
  35. package/bin/lean/limits.test.mjs +142 -9
  36. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  37. package/bin/lean/orchestrate.mjs +96 -26
  38. package/bin/lean/postdeploy-check.test.mjs +39 -0
  39. package/bin/lean/prompts.mjs +8 -7
  40. package/bin/lean/quota.mjs +39 -0
  41. package/bin/lean/recovery.test.mjs +10 -0
  42. package/bin/lean/relaxation.mjs +73 -0
  43. package/bin/lean/relaxation.test.mjs +54 -0
  44. package/bin/lean/release-postmerge.mjs +119 -0
  45. package/bin/lean/release-rehearsal.mjs +63 -0
  46. package/bin/lean/release-rehearsal.test.mjs +93 -0
  47. package/bin/lean/release-review.e2e.test.mjs +77 -0
  48. package/bin/lean/release-review.mjs +198 -0
  49. package/bin/lean/release-review.test.mjs +180 -0
  50. package/bin/lean/release.mjs +228 -0
  51. package/bin/lean/release.test.mjs +292 -0
  52. package/bin/lean/rotator.mjs +150 -31
  53. package/bin/lean/rotator.test.mjs +105 -2
  54. package/bin/lean/sandbox-remote.mjs +9 -2
  55. package/bin/lean/schedd.mjs +49 -4
  56. package/bin/lean/schedd.test.mjs +87 -6
  57. package/bin/lean/verifier.mjs +3 -2
  58. package/bin/lean/verify.mjs +2 -1
  59. package/bin/lean/verify.test.mjs +6 -0
  60. package/bin/pool/agent.mjs +18 -4
  61. package/bin/pool/router.mjs +66 -24
  62. package/bin/review-staging.mjs +23 -0
  63. package/bin/stats/conformance-outcomes.mjs +208 -0
  64. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  65. package/bin/stats/depth.mjs +218 -0
  66. package/bin/stats/depth.test.mjs +133 -0
  67. package/bin/stats/experiment.mjs +7 -5
  68. package/bin/stats/github-source.mjs +2 -2
  69. package/bin/stats/index.mjs +64 -2
  70. package/bin/stats/local-source.mjs +11 -0
  71. package/bin/stats/query.mjs +69 -0
  72. package/bin/stats/selffiled.mjs +52 -0
  73. package/bin/stats/selffiled.test.mjs +71 -0
  74. package/commands/orchestrate.md +1 -1
  75. package/commands/review-pr-agents/security.md +4 -0
  76. package/commands/review-pr-staging.md +2 -0
  77. package/commands/work-on/build.md +4 -6
  78. package/docs/CONFIG.md +65 -8
  79. package/docs/ISSUE-WATCH.md +2 -0
  80. package/docs/OUTCOME-CODES.md +3 -0
  81. package/docs/STATS.md +44 -0
  82. package/docs/TELEMETRY.md +1 -1
  83. package/package.json +1 -1
  84. package/pool/README.md +1 -1
  85. package/pool/image/cs-cred +14 -1
  86. package/scripts/backfill-finding-labels.mjs +50 -0
  87. package/scripts/backfill-finding-labels.test.mjs +36 -0
  88. package/scripts/doctor-pipeline-state.sh +21 -6
  89. package/scripts/file-deferred-followups.sh +59 -251
  90. package/scripts/file-deferred-followups.test.sh +85 -206
  91. package/scripts/followup-route.mjs +12 -0
  92. package/scripts/owner-route-parity.test.sh +17 -1
  93. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -0,0 +1,77 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * End-to-end run of `forgedock release` through the real job (preflight, release-pr, review, fixes, promotion) against an
5
+ * in-memory GitHub (#5212, R1): the release PR exists, the panel runs, a HIGH finding is filed and blocks, a fix lane merges
6
+ * to staging, the delta review passes, and the job stops at GATE_PASS with the merge command, with no manual step. GitHub, the
7
+ * model and the lane process are in memory (as in conformance.e2e.test.mjs); the job, steps, state and resume are real.
8
+ */
9
+ import { describe, it } from "node:test";
10
+ import assert from "node:assert/strict";
11
+ import { tmpDir } from "../tests/_tmp.mjs";
12
+ import { runRelease, newReleaseId, openRelease } from "./release.mjs";
13
+
14
+ const DISK = [{ mount: "/", type: "ext4" }];
15
+ const sha = (n) => String(n).padStart(40, "a");
16
+
17
+ /** In-memory GitHub + panel: one release PR whose head is a counter; comments are the register. */
18
+ function world() {
19
+ const w = { head: 1, comments: [], issues: [], lanes: [], printed: [], fixed: false, agents: [], launched: [] };
20
+ const io = {
21
+ now: () => 1_700_000_000_000, print: (l) => w.printed.push(l),
22
+ runningLanes: async () => [], batches: async () => [], setParallel: async () => {},
23
+ gh: async (a) => {
24
+ const j = a.join(" ");
25
+ if (a[0] === "pr" && a[1] === "list") return JSON.stringify(a.includes("--head") && a[a.indexOf("--state") + 1] === "open" ? [{ number: 7, headRefOid: sha(w.head), url: "u" }] : []);
26
+ if (j.includes("headRefOid")) return JSON.stringify({ headRefOid: sha(w.head) });
27
+ if (j.includes("--json comments")) return JSON.stringify({ comments: w.comments.map((body) => ({ body })) });
28
+ if (a[0] === "api") return JSON.stringify([{ name: "forge/deploy-gate", conclusion: "success" }]);
29
+ throw new Error(`unexpected gh ${j}`);
30
+ },
31
+ };
32
+ io.review = {
33
+ pre: async ({ delta }) => ({ code: 0, lines: [], data: { pr: 7, headSha: sha(w.head), bundle: [1, 2], scopeMode: "full", contextFile: "/sd/ctx.json", launchedFile: "/sd/l", briefs: [{ domain: "security", path: "/sd/b" }], delta: delta ? { from: delta, files: ["f"] } : null } }),
34
+ headOf: async () => sha(w.head),
35
+ readFile: () => "brief",
36
+ markLaunched: (_f, domains) => { w.launched = domains; },
37
+ saveTestGate: () => "/sd/gate.txt",
38
+ runAgent: async ({ role }) => { w.agents.push(role); return { text: "FORGE:TEST_GATE:RESULT=PASS" }; },
39
+ finalize: async () => ({ code: 0, lines: [], data: { head: sha(w.head), notes: ["- nit"], toFile: w.fixed ? [] : [{ title: "leak", severity: "HIGH" }] } }),
40
+ fileIssue: async ({ item }) => { w.issues.push(item.title); return 100 + w.issues.length; },
41
+ fileCiIssue: async () => 999,
42
+ addNotes: async () => {},
43
+ summary: async ({ filed }) => {
44
+ const pass = w.fixed;
45
+ w.comments.push(pass ? "<!-- FORGE:GATE_PASS -->" : "<!-- FORGE:GATE_FAILURE -->");
46
+ return { code: pass ? 0 : 1, lines: [], data: { verdict: pass ? "APPROVE FOR DEPLOY" : "BLOCK DEPLOY", marker: pass ? "FORGE:GATE_PASS" : "FORGE:GATE_FAILURE", ciFailing: 0, filed } };
47
+ },
48
+ runLane: async ({ issue, lane }) => { w.lanes.push([issue, lane]); w.fixed = true; w.head++; return { terminalReason: "merged" }; },
49
+ };
50
+ return { w, io };
51
+ }
52
+
53
+ describe("forgedock release, review to gate (e2e on in-memory GitHub)", () => {
54
+ it("reviews, files the blocking finding, fixes it on staging, re-reviews the delta and stops at GATE_PASS with the merge command", async () => {
55
+ const { w, io } = world();
56
+ const out = await runRelease({ io, repo: "o/r", root: tmpDir("rel-e2e-"), mounts: DISK, id: newReleaseId(), opts: {}, config: {}, branches: { staging: "staging", default: "main" } });
57
+ assert.equal(out.status, "stopped");
58
+ assert.equal(out.step, "promotion");
59
+ assert.match(out.reason, /GATE_PASS/);
60
+ assert.deepEqual(w.issues, ["leak"], "the finding was filed");
61
+ assert.deepEqual(w.lanes, [[101, "staging"]], "one fix lane on the staging branch");
62
+ assert.deepEqual(w.comments, ["<!-- FORGE:GATE_FAILURE -->", "<!-- FORGE:GATE_PASS -->"], "failure at the first head, pass after the delta review");
63
+ assert.ok(w.agents.includes("release-review-security") && w.agents.includes("release-review-regression-risk") && w.agents.includes("release-test-gate"), "the full panel ran");
64
+ assert.ok(w.printed.some((l) => l.includes(`--match-head-commit ${sha(2)}`)), "merge command at the fixed head");
65
+ });
66
+
67
+ it("a killed job resumes after the review step without re-running it", async () => {
68
+ const { w, io } = world();
69
+ const root = tmpDir("rel-e2e-"), id = newReleaseId();
70
+ const args = { io, repo: "o/r", root, mounts: DISK, id, opts: {}, config: {}, branches: { staging: "staging", default: "main" } };
71
+ await runRelease(args);
72
+ const agents = w.agents.length;
73
+ assert.equal(openRelease(root, id, DISK).load().steps.fixes.done, true);
74
+ await runRelease(args);
75
+ assert.equal(w.agents.length, agents, "review and fixes are done: nothing re-dispatched");
76
+ });
77
+ });
@@ -0,0 +1,198 @@
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 { join } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+ import { reviewStagingJson, reviewStagingIo, CI_EXCLUDED_CHECKS } from "../review-staging.mjs";
17
+
18
+ /** Delta passes after a head move, and fix-lane rounds: past either the job blocks for the manual path. */
19
+ export const MAX_DELTA_PASSES = 2;
20
+ export const MAX_FIX_ROUNDS = 2;
21
+ const REVIEW_MS = 45 * 60_000, LANE_MS = 3 * 60 * 60_000;
22
+ const ROOT = fileURLToPath(new URL("../..", import.meta.url));
23
+ const SEVERE = new Set(["CRITICAL", "HIGH"]);
24
+ const MANUAL = "use the manual path: forgedock review-staging <PR> (commands/review-pr-staging.md)";
25
+ const blocked = (why) => ({ blocked: true, reason: `${why}; ${MANUAL}` });
26
+
27
+ /** Reviewers whose prompts are prose in the spec (not briefed by the pre-dispatch): marker domain -> spec phase. */
28
+ export const SPEC_PANEL = [
29
+ { domain: "material-change", phase: "Phase 2 (material-change)" },
30
+ { domain: "bug-hunter-general", phase: "Phase 3 (bug hunters)" },
31
+ { domain: "code-quality", phase: "Phase 4 (code-quality)" },
32
+ { domain: "regression-risk", phase: "Phase 6 (regression-risk)" },
33
+ ];
34
+
35
+ const specPrompt = (p, m, def) => [
36
+ `You are the ${p.domain} reviewer of the staging -> ${def} release review of PR #${m.pr}, head ${m.headSha}.`,
37
+ `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}).`,
38
+ `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).`,
39
+ "Read-only git rule: never checkout, switch, reset, stash or merge in the shared checkout.",
40
+ ].join("\n\n");
41
+
42
+ /** `Reviewers` named by a finalize stop: delivery (`missing findings comment(s) for: a b`) or extract (`no structured findings block from: a, b.`). */
43
+ export function missingReviewers(lines) {
44
+ const t = (lines ?? []).join("\n");
45
+ 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
+ return m ? m[1].split(/[\s,]+/).filter((d) => /^[a-z0-9-]+$/.test(d)) : [];
47
+ }
48
+ const headMoved = (lines) => /head moved since/.test((lines ?? []).join("\n"));
49
+
50
+ /** One review round at the current head: dispatch, test gate, head check, finalize. @returns {{moved: string}|{fail}|{ok}} */
51
+ async function reviewRound({ seam, pr, def, delta }) {
52
+ const pre = await seam.pre({ pr, delta });
53
+ const m = pre.data;
54
+ if (pre.code !== 0 || !m?.headSha) return { fail: `the pre-dispatch stopped (exit ${pre.code}): ${(pre.lines ?? []).slice(-2).join(" | ").slice(0, 300)}` };
55
+ m.pr ??= pr;
56
+ // A delta pass credits the spec panel from the earlier pass: only the briefs the delta touches are dispatched.
57
+ const agents = [
58
+ ...m.briefs.map((b) => ({ domain: b.domain, prompt: () => seam.readFile(b.path) })),
59
+ ...(m.delta ? [] : SPEC_PANEL.map((p) => ({ domain: p.domain, prompt: () => specPrompt(p, m, def) }))),
60
+ ];
61
+ const prompts = new Map(agents.map((a) => [a.domain, a.prompt()]));
62
+ seam.markLaunched(m.launchedFile, agents.map((a) => a.domain), m.headSha);
63
+ 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 }))));
65
+ 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
+ const gateFile = seam.saveTestGate(pr, gate?.text ?? "");
67
+
68
+ // The head moved while the panel ran: finalize would refuse, and must never run at the moved head. Delta from what was reviewed.
69
+ if ((await seam.headOf(pr)) !== m.headSha) return { moved: m.headSha };
70
+ let fin = await seam.finalize({ pr, testGateOutput: gateFile });
71
+ if (fin.code !== 0 || !fin.data) {
72
+ if (headMoved(fin.lines)) return { moved: m.headSha };
73
+ 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)}` };
75
+ // 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)));
77
+ fin = await seam.finalize({ pr, testGateOutput: gateFile });
78
+ if (fin.code !== 0 || !fin.data) {
79
+ if (headMoved(fin.lines)) return { moved: m.headSha };
80
+ return { fail: `reviewer findings block still missing after one re-ask (${missing.join(", ")}): degraded panel` };
81
+ }
82
+ }
83
+ return { ok: fin.data };
84
+ }
85
+
86
+ /** The whole review of PR `pr`: rounds until one finalizes at its own head. @returns the step result or `{blocked}`. */
87
+ async function runReview({ seam, pr, def, delta = null }) {
88
+ let st = null;
89
+ for (let pass = 0; ; pass++) {
90
+ const r = await reviewRound({ seam, pr, def, delta });
91
+ if (r.fail) return blocked(r.fail);
92
+ if (r.ok) { st = r.ok; break; }
93
+ if (pass >= MAX_DELTA_PASSES) return blocked(`head of #${pr} kept moving during the review (${MAX_DELTA_PASSES} delta passes)`);
94
+ delta = r.moved;
95
+ }
96
+ const filed = [], blocking = [];
97
+ for (const item of st.toFile ?? []) {
98
+ const n = await seam.fileIssue({ item, pr, head: st.head });
99
+ if (!n) return blocked(`could not file the finding "${item.title ?? item.id}"`);
100
+ filed.push(n);
101
+ if (SEVERE.has(String(item.severity ?? "").toUpperCase())) blocking.push(n);
102
+ }
103
+ if ((st.notes ?? []).length) await seam.addNotes(pr, st.notes);
104
+ const sum = await seam.summary({ pr, filed });
105
+ if (!sum.data) return blocked(`the gate summary was not posted (exit ${sum.code}): ${(sum.lines ?? []).slice(-1).join("").slice(0, 200)}`);
106
+ return { pr, head: st.head, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, filed, blocking, delta: st.delta?.from ?? null };
107
+ }
108
+
109
+ /** Review step. @returns {{pr, head, verdict, marker, filed, blocking}|{blocked: true, reason: string}} */
110
+ export async function reviewStep(ctx) {
111
+ const pr = ctx.state?.steps?.["release-pr"]?.result?.pr;
112
+ if (!pr) return blocked("no release PR recorded by the release-pr step");
113
+ return runReview({ seam: seamOf(ctx), pr, def: ctx.def });
114
+ }
115
+
116
+ /** 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. */
117
+ export async function fixStep(ctx) {
118
+ let r = ctx.state?.steps?.review?.result;
119
+ if (!r?.pr) return blocked("no review result recorded by the review step");
120
+ const seam = seamOf(ctx);
121
+ for (let round = 0; r.marker !== "FORGE:GATE_PASS"; round++) {
122
+ if (round >= MAX_FIX_ROUNDS) return blocked(`still ${r.verdict} after ${MAX_FIX_ROUNDS} fix round(s)`);
123
+ // Blocking findings are already filed issues; red CI has none, so it gets one issue naming the failing checks.
124
+ const issues = [...(r.blocking ?? [])];
125
+ if (r.ciFailing > 0) {
126
+ const n = await seam.fileCiIssue({ pr: r.pr, head: r.head });
127
+ if (!n) return blocked(`could not file an issue for the red CI of #${r.pr}`);
128
+ issues.push(n);
129
+ }
130
+ if (!issues.length) return blocked(`${r.verdict} with neither a blocking finding nor red CI to fix`);
131
+ for (const issue of issues) {
132
+ const lane = await seam.runLane({ issue, lane: ctx.staging });
133
+ if (lane?.terminalReason !== "merged") return blocked(`fix lane for #${issue} ended ${lane?.terminalReason ?? "without a result"}`);
134
+ }
135
+ const next = await runReview({ seam, pr: r.pr, def: ctx.def, delta: r.head });
136
+ if (next.blocked) return next;
137
+ r = next;
138
+ ctx.state.steps.review = { ...ctx.state.steps.review, result: r };
139
+ ctx.save();
140
+ }
141
+ return { verdict: r.verdict, head: r.head };
142
+ }
143
+
144
+ const seamOf = (ctx) => ctx.io.review ?? (ctx.seam ??= realSeam(ctx));
145
+
146
+ /** 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() }) {
148
+ const rs = { ...reviewStagingIo(), cwd, env };
149
+ 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 });
152
+ return {
153
+ pre: ({ pr, delta }) => reviewStagingJson([String(pr), ...(delta ? ["--delta", delta] : [])], rs),
154
+ finalize: ({ pr, testGateOutput }) => reviewStagingJson([String(pr), "--finalize", "--test-gate-output", testGateOutput], rs),
155
+ summary: ({ pr, filed }) => reviewStagingJson([String(pr), "--summary", ...(filed.length ? ["--filed", filed.join(",")] : [])], rs),
156
+ headOf: (pr) => gh(["pr", "view", String(pr), "-R", repo, "--json", "headRefOid", "--jq", ".headRefOid"]).trim(),
157
+ readFile: (p) => readFileSync(p, "utf8"),
158
+ markLaunched: (file, domains, head) => { appendFileSync(file, domains.map((d) => `${d}\n`).join("")); writeFileSync(`${file}.head`, `${head}\n`); },
159
+ saveTestGate: (pr, text) => { mkdirSync(sd, { recursive: true }); const f = join(sd, `${pr}_test_gate_output.txt`); writeFileSync(f, text); return f; },
160
+ runAgent: async ({ role, issue, prompt }) => {
161
+ runner ??= (await import("./effects.mjs")).makeLeanRunner();
162
+ // 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 });
164
+ },
165
+ async fileCiIssue({ pr, head }) {
166
+ const rows = JSON.parse(gh(["pr", "checks", String(pr), "-R", repo, "--json", "name,bucket"]));
167
+ const names = rows.filter((c) => c.bucket === "fail" && !CI_EXCLUDED_CHECKS.includes(c.name)).map((c) => c.name);
168
+ 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 });
169
+ },
170
+ fileIssue: async ({ item, pr }) => {
171
+ const dir = mkdtempSync(join(tmpdir(), "release-finding-"));
172
+ try {
173
+ 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
+ const bodyFile = join(dir, "body.md");
175
+ writeFileSync(bodyFile, body);
176
+ let out = "";
177
+ 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
+ try {
179
+ 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;
180
+ } catch { return null; }
181
+ } finally { rmSync(dir, { recursive: true, force: true }); }
182
+ },
183
+ addNotes: async (pr, notes) => {
184
+ const body = JSON.parse(gh(["pr", "view", String(pr), "-R", repo, "--json", "body"])).body ?? "";
185
+ const list = notes.map((n) => (n.startsWith("-") ? n : `- ${n}`)).join("\n");
186
+ const next = body.includes("## Non-blocking notes") ? `${body.trimEnd()}\n${list}\n` : `${body.trimEnd()}\n\n## Non-blocking notes\n${list}\n`;
187
+ gh(["pr", "edit", String(pr), "-R", repo, "--body-file", "-"], next);
188
+ },
189
+ runLane: ({ issue, lane }) => new Promise((resolve) => {
190
+ const dir = mkdtempSync(join(tmpdir(), "release-lane-"));
191
+ const rf = join(dir, "result.json");
192
+ const child = spawn(process.execPath, [join(ROOT, "bin", "forgedock.mjs"), "run-issue", String(issue), "--lane", lane, "--result-file", rf], { cwd, env, stdio: "ignore" });
193
+ const timer = setTimeout(() => child.kill("SIGTERM"), LANE_MS);
194
+ 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); };
195
+ child.on("error", done); child.on("exit", done);
196
+ }),
197
+ };
198
+ }
@@ -0,0 +1,180 @@
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 } from "./release-review.mjs";
6
+ import { reviewStagingJson } from "../review-staging.mjs";
7
+
8
+ const H1 = "a".repeat(40), H2 = "b".repeat(40);
9
+ 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 });
10
+ const fin = (extra = {}) => ({ code: 0, data: { head: H1, toFile: [], notes: [], ...extra }, lines: [] });
11
+
12
+ /** Seam fake: `heads` is what headOf answers in turn; `fins` what finalize answers in turn. */
13
+ function fakeSeam({ heads = [H1], fins = [fin()], summary, lanes = [] } = {}) {
14
+ const log = [], agents = [];
15
+ let h = 0, f = 0, l = 0, n = 100;
16
+ return {
17
+ log, agents,
18
+ 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: [] }; },
19
+ finalize: async () => { log.push(["finalize"]); return fins[Math.min(f++, fins.length - 1)]; },
20
+ summary: async (a) => { log.push(["summary", a.filed]); return summary ?? { code: 0, data: { verdict: "APPROVE FOR DEPLOY", marker: "FORGE:GATE_PASS", ciFailing: 0 }, lines: [] }; },
21
+ headOf: async () => heads[Math.min(h++, heads.length - 1)],
22
+ readFile: (p) => `brief ${p}`,
23
+ markLaunched: (file, domains) => log.push(["launched", domains]),
24
+ saveTestGate: () => "/sd/7_test_gate_output.txt",
25
+ runAgent: async (a) => { agents.push(a.role + (a.prompt.includes("findings block required") ? ":reask" : "")); return { text: "ok" }; },
26
+ fileIssue: async ({ item }) => { log.push(["file", item.title]); return n++; },
27
+ fileCiIssue: async () => { log.push(["ci-issue"]); return n++; },
28
+ addNotes: async (pr, notes) => log.push(["notes", notes]),
29
+ runLane: async (a) => { log.push(["lane", a.issue, a.lane]); return lanes[l++] ?? { terminalReason: "merged" }; },
30
+ };
31
+ }
32
+ const ctx = (seam, steps = {}) => ({ io: { review: seam }, repo: "o/r", def: "main", staging: "staging", state: { steps: { "release-pr": { result: { pr: 7 } }, ...steps } }, save() {} });
33
+
34
+ describe("reviewStep", () => {
35
+ it("realSeam exposes every effect the steps use, matching the fake seam", () => {
36
+ const real = Object.keys(realSeam({ repo: "o/r", def: "main", env: {}, cwd: "/tmp" })).sort();
37
+ assert.deepEqual(real, Object.keys(fakeSeam()).filter((k) => k !== "log" && k !== "agents").sort());
38
+ });
39
+
40
+ it("runs the briefs and the spec panel in parallel, then test gate, finalize and summary in order", async () => {
41
+ const s = fakeSeam();
42
+ const r = await reviewStep(ctx(s));
43
+ assert.equal(r.marker, "FORGE:GATE_PASS");
44
+ assert.deepEqual(s.agents.slice().sort(), ["release-review-security", "release-test-gate", ...SPEC_PANEL.map((p) => `release-review-${p.domain}`)].sort());
45
+ assert.deepEqual(s.log.map((e) => e[0]), ["pre", "launched", "finalize", "summary"]);
46
+ assert.deepEqual(s.log[1][1], ["security", ...SPEC_PANEL.map((p) => p.domain)]);
47
+ });
48
+
49
+ it("R2: a head move triggers a --delta pass from the reviewed sha and never finalizes at the moved head", async () => {
50
+ const s = fakeSeam({ heads: [H2, H2] });
51
+ const r = await reviewStep(ctx(s));
52
+ const pres = s.log.filter((e) => e[0] === "pre");
53
+ assert.deepEqual(pres.map((e) => e[1]), [null, H1], "second pass is --delta <reviewed sha>");
54
+ assert.equal(s.log.filter((e) => e[0] === "finalize").length, 1, "finalize ran once, after the delta pass");
55
+ assert.ok(s.log.findIndex((e) => e[0] === "finalize") > s.log.findLastIndex((e) => e[0] === "pre"));
56
+ assert.equal(r.verdict, "APPROVE FOR DEPLOY");
57
+ // the delta pass credits the spec panel: only the briefs are re-run
58
+ assert.equal(s.agents.filter((a) => a === "release-review-material-change").length, 1);
59
+ });
60
+
61
+ it("a finalize refusal for a moved head also becomes a delta pass", async () => {
62
+ const s = fakeSeam({ fins: [{ code: 1, data: null, lines: ["REVIEW_RESULT: status: BLOCKED, blocker: head moved since the review (aaaaaaa -> bbbbbbb)"] }, fin()] });
63
+ await reviewStep(ctx(s));
64
+ assert.equal(s.log.filter((e) => e[0] === "pre").length, 2);
65
+ });
66
+
67
+ it("blocks when the head keeps moving", async () => {
68
+ const s = fakeSeam();
69
+ let i = 0;
70
+ s.headOf = async () => String(++i).padStart(40, "c");
71
+ const r = await reviewStep(ctx(s));
72
+ assert.equal(r.blocked, true);
73
+ assert.match(r.reason, new RegExp(`${MAX_DELTA_PASSES} delta passes`));
74
+ });
75
+
76
+ it("re-asks only the reviewer with a missing findings block, once, then finalizes", async () => {
77
+ const s = fakeSeam({ fins: [{ code: 1, data: null, lines: ["REVIEW DELIVERY FAILURE: missing findings comment(s) for: security code-quality"] }, fin()] });
78
+ const r = await reviewStep(ctx(s));
79
+ assert.equal(r.blocked, undefined);
80
+ assert.deepEqual(s.agents.filter((a) => a.endsWith(":reask")).sort(), ["release-review-code-quality:reask", "release-review-security:reask"]);
81
+ });
82
+
83
+ it("a second miss is a degraded panel (blocked, no further re-ask)", async () => {
84
+ const bad = { code: 1, data: null, lines: ["REVIEW DELIVERY FAILURE: no structured findings block from: security."] };
85
+ const s = fakeSeam({ fins: [bad] });
86
+ const r = await reviewStep(ctx(s));
87
+ assert.equal(r.blocked, true);
88
+ assert.match(r.reason, /degraded panel/);
89
+ assert.equal(s.agents.filter((a) => a.endsWith(":reask")).length, 1);
90
+ assert.equal(s.log.filter((e) => e[0] === "summary").length, 0);
91
+ });
92
+
93
+ it("files each FILE item, lists NOTEs in the PR body, then summarises with --filed", async () => {
94
+ const s = fakeSeam({ fins: [fin({ toFile: [{ title: "a", severity: "HIGH" }, { title: "b", severity: "LOW" }], notes: ["- n1"] })] });
95
+ const r = await reviewStep(ctx(s));
96
+ assert.deepEqual(s.log.slice(-4).map((e) => e[0]), ["file", "file", "notes", "summary"]);
97
+ assert.deepEqual(s.log.at(-1)[1], [100, 101]);
98
+ assert.deepEqual(r.blocking, [100], "only CRITICAL/HIGH findings block");
99
+ });
100
+
101
+ it("blocks when filing fails, before any summary is posted", async () => {
102
+ const s = fakeSeam({ fins: [fin({ toFile: [{ title: "a", severity: "HIGH" }] })] });
103
+ s.fileIssue = async () => null;
104
+ const r = await reviewStep(ctx(s));
105
+ assert.equal(r.blocked, true);
106
+ assert.equal(s.log.filter((e) => e[0] === "summary").length, 0);
107
+ });
108
+
109
+ it("blocks without a release PR", async () => {
110
+ assert.equal((await reviewStep({ ...ctx(fakeSeam()), state: { steps: {} } })).blocked, true);
111
+ });
112
+ });
113
+
114
+ describe("fixStep", () => {
115
+ const failed = { pr: 7, head: H1, verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", blocking: [101], filed: [101], ciFailing: 0 };
116
+
117
+ it("does nothing on GATE_PASS", async () => {
118
+ const s = fakeSeam();
119
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, verdict: "APPROVE FOR DEPLOY", marker: "FORGE:GATE_PASS" } } }));
120
+ assert.equal(r.blocked, undefined);
121
+ assert.equal(s.log.length, 0);
122
+ });
123
+
124
+ it("runs a lane on the staging branch per blocking issue, then a delta review from the reviewed head", async () => {
125
+ const s = fakeSeam({ heads: [H2] });
126
+ const c = ctx(s, { review: { result: failed } });
127
+ const r = await fixStep(c);
128
+ assert.deepEqual(s.log[0], ["lane", 101, "staging"]);
129
+ assert.deepEqual(s.log[1], ["pre", H1]);
130
+ assert.equal(r.verdict, "APPROVE FOR DEPLOY");
131
+ });
132
+
133
+ it("is bounded: blocks once the rounds are spent", async () => {
134
+ const bad = { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] };
135
+ const s = fakeSeam({ heads: [H2], summary: bad, fins: [fin({ toFile: [{ title: "x", severity: "CRITICAL" }] })] });
136
+ const r = await fixStep(ctx(s, { review: { result: failed } }));
137
+ assert.equal(r.blocked, true);
138
+ assert.equal(s.log.filter((e) => e[0] === "lane").length, MAX_FIX_ROUNDS);
139
+ });
140
+
141
+ it("blocks when a lane does not merge", async () => {
142
+ const s = fakeSeam({ lanes: [{ terminalReason: "needs-human" }] });
143
+ assert.equal((await fixStep(ctx(s, { review: { result: failed } }))).blocked, true);
144
+ });
145
+
146
+ it("red CI with no finding files one CI issue and runs a lane on it, then reviews the delta", async () => {
147
+ const s = fakeSeam({ heads: [H2] });
148
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], ciFailing: 2 } } }));
149
+ assert.deepEqual(s.log.slice(0, 3), [["ci-issue"], ["lane", 100, "staging"], ["pre", H1]]);
150
+ assert.equal(r.blocked, undefined);
151
+ });
152
+
153
+ it("a blocking finding and red CI together get a lane each", async () => {
154
+ const s = fakeSeam({ heads: [H2] });
155
+ await fixStep(ctx(s, { review: { result: { ...failed, ciFailing: 1 } } }));
156
+ assert.deepEqual(s.log.filter((e) => e[0] === "lane").map((e) => e[1]), [101, 100]);
157
+ });
158
+
159
+ it("blocks when the verdict is not a pass but there is nothing to fix", async () => {
160
+ assert.match((await fixStep(ctx(fakeSeam(), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
161
+ });
162
+ });
163
+
164
+ describe("missingReviewers", () => {
165
+ it("reads the names from the delivery and extract messages", () => {
166
+ assert.deepEqual(missingReviewers(["x", "REVIEW DELIVERY FAILURE: missing findings comment(s) for: a b-c"]), ["a", "b-c"]);
167
+ assert.deepEqual(missingReviewers(["REVIEW DELIVERY FAILURE: no structured findings block from: a, b. Re-dispatch them once"]), ["a", "b"]);
168
+ assert.deepEqual(missingReviewers(["nothing"]), []);
169
+ });
170
+ });
171
+
172
+ describe("reviewStagingJson (library entry)", () => {
173
+ 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") });
174
+ it("returns a stop as {code, lines} without printing and never throws", async () => {
175
+ const r = await reviewStagingJson(["--summary"], io(async () => { throw new Error("no gh"); }));
176
+ assert.equal(r.data, null);
177
+ assert.ok(r.code >= 1);
178
+ assert.ok(r.lines.length > 0);
179
+ });
180
+ });