forgedock 1.68.0 → 1.70.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 (68) hide show
  1. package/bin/engine-cli.mjs +4 -9
  2. package/bin/lean/advisory.test.mjs +14 -5
  3. package/bin/lean/batch.mjs +11 -1
  4. package/bin/lean/capsample.mjs +25 -0
  5. package/bin/lean/conformance.mjs +9 -1
  6. package/bin/lean/conformance.test.mjs +7 -0
  7. package/bin/lean/depcache.mjs +2 -0
  8. package/bin/lean/effects.mjs +15 -1
  9. package/bin/lean/envgap.mjs +18 -0
  10. package/bin/lean/envgap.test.mjs +12 -1
  11. package/bin/lean/execution.mjs +3 -0
  12. package/bin/lean/execution.test.mjs +21 -0
  13. package/bin/lean/failure-stop.mjs +12 -1
  14. package/bin/lean/failure-stop.test.mjs +14 -1
  15. package/bin/lean/hostconfig.mjs +54 -0
  16. package/bin/lean/hostconfig.test.mjs +67 -0
  17. package/bin/lean/issuewatch-parity.test.mjs +1 -1
  18. package/bin/lean/lane-audit-llm.mjs +51 -4
  19. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  20. package/bin/lean/lane-audit.mjs +1 -1
  21. package/bin/lean/lean.mjs +63 -26
  22. package/bin/lean/lean.test.mjs +100 -19
  23. package/bin/lean/live-execution.mjs +3 -0
  24. package/bin/lean/live-execution.test.mjs +23 -0
  25. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  26. package/bin/lean/orchestrate-envhold.test.mjs +15 -1
  27. package/bin/lean/orchestrate.mjs +27 -9
  28. package/bin/lean/preflight.mjs +10 -3
  29. package/bin/lean/preflight.test.mjs +21 -1
  30. package/bin/lean/prompts.mjs +1 -0
  31. package/bin/lean/release-cigreen.mjs +204 -0
  32. package/bin/lean/release-cigreen.test.mjs +115 -0
  33. package/bin/lean/release-deploy.mjs +35 -5
  34. package/bin/lean/release-deploy.test.mjs +50 -3
  35. package/bin/lean/release-fixloop.mjs +1 -1
  36. package/bin/lean/release-flakes.mjs +34 -0
  37. package/bin/lean/release-flakes.test.mjs +28 -0
  38. package/bin/lean/release-ledger.test.mjs +4 -4
  39. package/bin/lean/release-preflight.test.mjs +2 -2
  40. package/bin/lean/release-rehearsal.test.mjs +1 -1
  41. package/bin/lean/release-review.e2e.test.mjs +4 -3
  42. package/bin/lean/release-review.mjs +136 -56
  43. package/bin/lean/release-review.test.mjs +97 -12
  44. package/bin/lean/release-status.mjs +3 -2
  45. package/bin/lean/release-status.test.mjs +2 -2
  46. package/bin/lean/release.mjs +6 -3
  47. package/bin/lean/release.test.mjs +33 -12
  48. package/bin/lean/sandbox-remote.mjs +35 -4
  49. package/bin/lean/schedd.mjs +2 -2
  50. package/bin/pool/agent.mjs +105 -15
  51. package/bin/pool/cli.mjs +22 -4
  52. package/bin/pool/docker.mjs +2 -0
  53. package/bin/pool/image-manifest.mjs +24 -0
  54. package/bin/pool/image-manifest.test.mjs +20 -0
  55. package/bin/pool/lane-tools.mjs +23 -4
  56. package/bin/pool/lane-tools.test.mjs +27 -7
  57. package/bin/pool/project-layer.mjs +142 -0
  58. package/bin/pool/project-layer.test.mjs +73 -0
  59. package/bin/pool/router.mjs +20 -6
  60. package/bin/pool/version.mjs +45 -2
  61. package/bin/review-staging.mjs +63 -21
  62. package/bin/stats/tool-parks.mjs +29 -0
  63. package/bin/stats/tool-parks.test.mjs +21 -0
  64. package/commands/review-pr-staging.md +1 -1
  65. package/docs/CONFIG.md +20 -0
  66. package/package.json +1 -1
  67. package/pool/image/Dockerfile +1 -1
  68. package/scripts/ci-local.test.sh +3 -2
@@ -20,6 +20,7 @@ function world(o = {}) {
20
20
  if (a[0] === "run" && a[1] === "list") { const r = w.runs[Math.min(w.reran ?? 0, w.runs.length - 1)]; return JSON.stringify(r ? [r] : []); }
21
21
  if (a[0] === "run" && a[1] === "view") return w.log;
22
22
  if (a[0] === "run" && a[1] === "rerun") { w.reran = (w.reran ?? 0) + 1; return ""; }
23
+ if (a[0] === "issue") { w.issues = w.issues ?? []; w.issues.push({ a, at: w.reran ?? 0 }); return a[1] === "list" ? "[]" : a[1] === "create" ? "https://github.com/o/r/issues/77" : ""; }
23
24
  if (a[0] === "workflow" || a[0] === "pr") return "";
24
25
  throw new Error(`unexpected gh ${a.join(" ")}`);
25
26
  },
@@ -67,7 +68,7 @@ describe("release deploy stages (#5560)", () => {
67
68
  it("rerun_max bounds the reruns, then escalates", async () => {
68
69
  const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
69
70
  const out = await deployStep(mk(io));
70
- assert.match(out.reason, /recovery spent/); assert.equal(w.reran, 2);
71
+ assert.match(out.reason, /recovery spent/); assert.equal(w.reran, 1);
71
72
  });
72
73
  it("max_attempts bounds the actions", async () => {
73
74
  const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
@@ -111,7 +112,8 @@ describe("release deploy stages (#5560)", () => {
111
112
  const c = mk(io);
112
113
  try { await deployStep(c); } catch { /* killed */ }
113
114
  const out = await deployStep(c);
114
- assert.equal(out.live, true, dieOn);
115
+ if (dieOn === "run rerun") assert.ok(out.blocked, dieOn); // #6015: a crash after the counted rerun leaves a second recorded failure: stop, never a third attempt
116
+ else assert.equal(out.live, true, dieOn);
115
117
  assert.ok((w.reran ?? 0) <= 1, `${dieOn}: one rerun`);
116
118
  assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0, dieOn);
117
119
  }
@@ -152,7 +154,7 @@ describe("deploy observation and recovery (#5560)", () => {
152
154
  assert.equal((await deployStep(mk(ok.io))).live, true); assert.equal(ok.w.reran, undefined);
153
155
  const bad = world({ live: [OLD], runs: [{ databaseId: 9, status: "completed", conclusion: "cancelled" }], log: "the runner received a shutdown signal" });
154
156
  const out = await deployStep(mk(bad.io));
155
- assert.equal(bad.w.reran, 2); assert.match(out.reason, /recovery spent/);
157
+ assert.equal(bad.w.reran, 1); assert.match(out.reason, /recovery spent/);
156
158
  });
157
159
  it("shared INFRA_SIGNATURES count as transient without any configured signature", async () => {
158
160
  const { w, io } = world({ live: [OLD, SHA], log: "fatal: ECONNRESET", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }, { databaseId: 9, status: "completed", conclusion: "success" }] });
@@ -223,3 +225,48 @@ describe("deploy helpers", () => {
223
225
  assert.ok(validatePolicy({ ...base, deploy: { ...POLICY, recovery: { rerun_max: "2" } } }).some((f) => /rerun_max/.test(f)));
224
226
  });
225
227
  });
228
+
229
+ describe("deploy failure classification and one issue (#6015)", () => {
230
+ const FAIL = [{ databaseId: 9, status: "completed", conclusion: "failure" }];
231
+ const creates = (w) => (w.issues ?? []).filter((i) => i.a[1] === "create");
232
+ it("two failed attempts yield exactly one issue and no third rerun", async () => {
233
+ const { w, io } = world({ live: [OLD], log: "build\tCompile\t2026 429 Too Many Requests", runs: FAIL });
234
+ const out = await deployStep(mk(io));
235
+ assert.equal(creates(w).length, 1); assert.equal(w.reran, 1); assert.equal(out.hold?.kind, "deploy-failed"); assert.match(out.reason, /issues\/77/);
236
+ assert.equal((w.issues ?? []).filter((i) => i.a[1] === "comment").length, 1);
237
+ const again = await deployStep(mk(io, { state: { steps: { "post-merge": { result: { merge: SHA } } }, deploy: undefined } })); // a fresh state still finds the marker, never a third rerun beyond the cap
238
+ assert.ok((w.reran ?? 0) <= 2); assert.ok(again.blocked || again.live === undefined);
239
+ });
240
+ it("the cap cannot be raised above 2 by deploy.recovery", async () => {
241
+ const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: FAIL });
242
+ await deployStep(mk(io, {}, { ...POLICY, recovery: { rerun_max: 9, max_attempts: 9, signatures: ["429"] } }));
243
+ assert.equal(w.reran, 1);
244
+ });
245
+ it("a secrets decrypt or SSH failure is never rerun, but the issue is filed", async () => {
246
+ for (const [log, cls] of [["deploy\tDecrypt secrets\t2026 sops: failed to decrypt ETIMEDOUT", "secrets"], ["deploy\tDeploy via SSH\t2026 ssh: connect to host x port 22: ETIMEDOUT", "ssh"]]) {
247
+ const { w, io } = world({ live: [OLD], log, runs: FAIL });
248
+ const c = mk(io); const out = await deployStep(c);
249
+ assert.equal(w.reran, undefined, cls); assert.equal(out.hold?.kind, cls); assert.equal(creates(w).length, 1);
250
+ assert.equal(c.state.deploy.failures[0].class, cls); assert.equal(c.state.deploy.failures[0].runId, 9);
251
+ }
252
+ });
253
+ it("the issue is filed before the rerun", async () => {
254
+ const { w, io } = world({ live: [OLD, SHA], log: "ECONNRESET", runs: [...FAIL, { databaseId: 9, status: "completed", conclusion: "success" }] });
255
+ const order = []; const g = io.gh;
256
+ io.gh = async (a) => { if (a[0] === "issue" && a[1] === "create") order.push("issue"); if (a[1] === "rerun") order.push("rerun"); return g(a); };
257
+ const out = await deployStep(mk(io));
258
+ assert.deepEqual(order, ["issue", "rerun"]); assert.equal(out.live, true);
259
+ });
260
+ it("a class is rerun once only", async () => {
261
+ const { w, io } = world({ live: [OLD], log: "ECONNRESET", runs: FAIL });
262
+ const c = mk(io, {}, { ...POLICY, recovery: { rerun_max: 2, max_attempts: 3 } });
263
+ c.state.deploy = { phase: "DEPLOYING", attempts: 1, reruns: 1, rerunClasses: ["infra"], failures: [{ class: "infra", step: null, runId: 9, excerpt: "x", rerunsAt: 0 }] };
264
+ await deployStep(c); assert.equal(w.reran, undefined);
265
+ });
266
+ it("a failing issue filing blocks the rerun", async () => {
267
+ const { w, io } = world({ live: [OLD], log: "ECONNRESET", runs: FAIL }); const g = io.gh;
268
+ io.gh = async (a) => { if (a[0] === "issue") throw new Error("HTTP 500"); return g(a); };
269
+ const out = await deployStep(mk(io));
270
+ assert.match(out.reason, /tracking issue/); assert.equal(w.reran, undefined);
271
+ });
272
+ });
@@ -33,7 +33,7 @@ export function collectFindings({ head, jobs = [], findings = [], guards = [] })
33
33
  .map((j) => ({ name: j.name, ...classifyFailure(j.log), inputHash: j.inputHash ?? null, tail: String(j.log ?? "").slice(-LOG_TAIL) }))
34
34
  .sort((a, b) => byText(a.name, b.name));
35
35
  const review = findings
36
- .map((f) => ({ id: f.id ?? null, title: String(f.title ?? f.id ?? "finding"), severity: String(f.severity ?? "").toUpperCase() || null, property: f.property ?? f.invariant ?? f.category ?? null, inWave: f.wave !== false, blocking: f.blocking !== false && /^(CRITICAL|HIGH)$/i.test(String(f.severity ?? "")) }))
36
+ .map((f) => ({ id: f.id ?? null, title: String(f.title ?? f.id ?? "finding"), severity: String(f.severity ?? "").toUpperCase() || null, property: f.property ?? f.invariant ?? f.category ?? null, inWave: f.wave !== false, filed: f.filed === true, blocking: f.blocking !== false && /^(CRITICAL|HIGH)$/i.test(String(f.severity ?? "")) }))
37
37
  .sort((a, b) => byText(a.title, b.title) || byText(String(a.id), String(b.id)));
38
38
  const gs = guards.map((g) => ({ name: g.name, why: String(g.why ?? "") })).sort((a, b) => byText(a.name, b.name));
39
39
  return { head, ci, review, guards: gs };
@@ -40,6 +40,40 @@ export function classifyFailure(text) {
40
40
  const hit = INFRA_SIGNATURES.find(([, re]) => re.test(String(text ?? "")));
41
41
  return hit ? { class: "infra", signature: hit[0] } : { class: "unknown", signature: null };
42
42
  }
43
+ /** #6015: a deploy or rehearsal workflow is never a CI flake: its failures go through release-deploy recover (classify, file, bounded rerun). */
44
+ export const isDeployWorkflow = (name) => /deploy|rehears|migrat/i.test(String(name ?? ""));
45
+
46
+ const STEP_SECRETS = /decrypt|sops|secrets?\b|age[- ]key|gpg/i, STEP_SSH = /\bssh\b|scp\b|rsync/i;
47
+ const LOG_SECRETS = /failed to decrypt|decryption failed|sops.*(error|failed)|no matching keys|cannot decrypt|age: error/i;
48
+ const LOG_SSH = /permission denied \(publickey|ssh: connect to host|ssh_exchange_identification|kex_exchange_identification|host key verification failed|ssh: .*(timed out|refused)/i;
49
+
50
+ /** The step named by the first `--log-failed` line (`job<TAB>step<TAB>time line`) or the first failed step of `steps` [{name, conclusion}]. */
51
+ function failedStepName(steps, log) {
52
+ const s = (steps ?? []).find((x) => x?.conclusion === "failure" || x?.conclusion === "timed_out");
53
+ if (s?.name) return String(s.name);
54
+ const m = /^[^\t\n]*\t([^\t\n]+)\t/m.exec(String(log ?? ""));
55
+ return m ? m[1].trim() : null;
56
+ }
57
+
58
+ /**
59
+ * #6015: name the failed deploy step (DEPLOY_FREEZE / LIVE_CHECK semantics of #5560 via `reason`). Pure.
60
+ * Secrets decrypt, SSH, rehearsal, migration, freeze and live-check failures are never transient; only a network/infra signature
61
+ * (shared INFRA_SIGNATURES or `sigs`) in some other step is. @returns {{class, transient: boolean, step: string|null, excerpt: string}}
62
+ */
63
+ export function classifyFailedStep({ steps, log, reason, sigs } = {}) {
64
+ const text = String(log ?? ""), step = failedStepName(steps, text), name = step ?? "";
65
+ const excerpt = text.trim().slice(-400), out = (cls, transient = false) => ({ class: cls, transient, step, excerpt });
66
+ if (/DEPLOY_FREEZE|\bfreeze\b/i.test(String(reason ?? ""))) return out("freeze");
67
+ if (/LIVE_CHECK/.test(String(reason ?? ""))) return out("live-check");
68
+ if (STEP_SECRETS.test(name) || LOG_SECRETS.test(text)) return out("secrets");
69
+ if (STEP_SSH.test(name) || (!step && LOG_SSH.test(text))) return out("ssh");
70
+ if (/rehears/i.test(name)) return out("rehearsal");
71
+ if (/migrat/i.test(name) || (!step && /migrat/i.test(text))) return out("migration");
72
+ const configured = (sigs ?? []).some((x) => { try { return new RegExp(x, "i").test(text); } catch { return text.includes(x); } });
73
+ if (INFRA_SIGNATURES.some(([, re]) => re.test(text)) || configured) return out("infra", true);
74
+ return /migrat/i.test(text) ? out("migration") : out("deterministic");
75
+ }
76
+
43
77
  export const signatureHash = (check, test, signature) => createHash("sha256").update([check, test ?? "", signature ?? ""].join("\0")).digest("hex").slice(0, 16);
44
78
 
45
79
  /** Same-SHA flips in `runs` [{sha, check, test?, conclusion, id, at}]: a check that failed and then passed on one sha. */
@@ -145,3 +145,31 @@ t6014("#6014: attempt cap refuses a third rerun, records attempt and forfeited r
145
145
  assert6014.equal(e.attempt, 2); assert6014.match(e.reuse_forfeited, /reuse forfeited/);
146
146
  assert6014.equal("attempt" in flakeEntry({ check: "c", kind: "infra", at: "t" }), false);
147
147
  });
148
+
149
+ describe("classifyFailedStep and deploy-class reruns (#6015)", async () => {
150
+ const { classifyFailedStep, isDeployWorkflow } = await import("./release-flakes.mjs");
151
+ const L = (step, msg) => `deploy\t${step}\t2026-01-01T00:00:00Z ${msg}`;
152
+ it("names the class and transience of the failed step", () => {
153
+ const k = (o) => { const r = classifyFailedStep(o); return [r.class, r.transient]; };
154
+ assert.deepEqual(k({ log: L("Decrypt secrets", "sops: failed to decrypt") }), ["secrets", false]);
155
+ assert.deepEqual(k({ log: L("Deploy via SSH", "ssh: connect to host h port 22: Connection timed out ETIMEDOUT") }), ["ssh", false]);
156
+ assert.deepEqual(k({ log: L("Migration Rehearsal", "ECONNRESET") }), ["rehearsal", false]);
157
+ assert.deepEqual(k({ log: L("Run migrations", "failed") }), ["migration", false]);
158
+ assert.deepEqual(k({ log: L("Pull images", "ECONNRESET") }), ["infra", true]);
159
+ assert.deepEqual(k({ log: L("Build", "tsc error") }), ["deterministic", false]);
160
+ assert.deepEqual(k({ log: "", reason: "LIVE_CHECK failed" }), ["live-check", false]);
161
+ assert.deepEqual(k({ log: "", reason: "the run set DEPLOY_FREEZE" }), ["freeze", false]);
162
+ assert.equal(classifyFailedStep({ steps: [{ name: "Deploy via SSH", conclusion: "failure" }], log: "" }).step, "Deploy via SSH");
163
+ });
164
+ it("matches no deploy class for ordinary CI names", () => {
165
+ assert.equal(isDeployWorkflow("Migration Rehearsal"), true); assert.equal(isDeployWorkflow("Deploy production"), true);
166
+ assert.equal(isDeployWorkflow("unit"), false); assert.equal(isDeployWorkflow("lint"), false);
167
+ });
168
+ it("rerunInfraFlakes skips deploy-class runs", async () => {
169
+ const calls = [];
170
+ const io = { now: () => NOW, api: async () => ({}), gh: async (a) => { calls.push(a); return a[1] === "list" ? JSON.stringify([{ databaseId: 5, name: "Deploy production" }]) : "Unable to upload artifact"; } };
171
+ const fence = { lctx: { io, repo: "o/r", credential: "driver" }, lease: { holder: "A", epoch: 1, release: "r1" }, record: async () => {}, now: () => "t" };
172
+ const r = await rerunInfraFlakes({ io, repo: "o/r", head: "abc", fence, policy: { ci: { rerun_budget_min: 30 } } });
173
+ assert.deepEqual(r.reran, []); assert.match(r.skipped[0].why, /deploy-class/); assert.equal(calls.filter((c) => c[1] === "rerun").length, 0);
174
+ });
175
+ });
@@ -137,13 +137,13 @@ describe("release ledger (#5550)", () => {
137
137
  const g = fakeGh(), seen = [];
138
138
  const mkIo = () => ({ print() {}, now: () => 1_700_000_000_000, runningLanes: async () => [], batches: async () => [], setParallel: async () => {}, gh: async () => { throw new Error("no gh"); }, api: g.api });
139
139
  const step = (name, die) => async () => { if (die) throw new Error("kill -9"); seen.push(name); return {}; };
140
- const all = (dieAt) => ({ preflight: step("preflight"), "host-preflight": async () => ({ skipped: true }), deploy: async () => ({ skipped: true }), "release-pr": async () => { if (dieAt === "release-pr") throw new Error("kill -9"); seen.push("release-pr"); return { pr: 7 }; }, review: step("review"), fixes: step("fixes"), "mark-ready": async () => ({ skipped: true }), rehearsal: async () => ({ skipped: true }), promotion: step("promotion"), "post-merge": step("post-merge") });
140
+ const all = (dieAt) => ({ preflight: step("preflight"), "host-preflight": async () => ({ skipped: true }), deploy: async () => ({ skipped: true }), "release-pr": async () => { if (dieAt === "release-pr") throw new Error("kill -9"); seen.push("release-pr"); return { pr: 7 }; }, "ci-green": step("ci-green"), review: step("review"), fixes: step("fixes"), "mark-ready": async () => ({ skipped: true }), rehearsal: async () => ({ skipped: true }), promotion: step("promotion"), "post-merge": step("post-merge") });
141
141
  const run = (io, dieAt, root) => runRelease({ io, repo: REPO, root, mounts: DISK, id: ID, opts: {}, config: { managed: true }, branches: {}, steps: all(dieAt) });
142
142
  await assert.rejects(() => run(mkIo(), "release-pr", tmpDir("ledgerA-")), /kill -9/);
143
143
  assert.deepEqual(seen, ["preflight"]);
144
144
  const out = await run(mkIo(), null, tmpDir("ledgerB-")); // host B: empty disk
145
145
  assert.equal(out.status, "done");
146
- assert.deepEqual(seen, ["preflight", "release-pr", "review", "fixes", "promotion", "post-merge"]);
146
+ assert.deepEqual(seen, ["preflight", "release-pr", "ci-green", "review", "fixes", "promotion", "post-merge"]);
147
147
  });
148
148
  });
149
149
 
@@ -165,7 +165,7 @@ describe("release fencing through the job (#5553)", () => {
165
165
  throw new Error(`unexpected gh ${j}`);
166
166
  } });
167
167
  const skip = async () => ({ skipped: true }), ok = async () => ({});
168
- const steps = (over = {}) => withStubs({ preflight: ok, "host-preflight": skip, "release-pr": async () => ({ pr: 7 }), review: ok, fixes: ok, "mark-ready": skip, rehearsal: skip, "post-merge": ok, ...over });
168
+ const steps = (over = {}) => withStubs({ preflight: ok, "host-preflight": skip, "release-pr": async () => ({ pr: 7 }), "ci-green": ok, review: ok, fixes: ok, "mark-ready": skip, rehearsal: skip, "post-merge": ok, ...over });
169
169
  const go = (io, st, root) => runRelease({ io, repo: REPO, root, mounts: DISK, id: ID, opts: { merge: true }, config: { managed: true }, branches: { staging: "staging", default: "main" }, steps: st ?? steps() });
170
170
 
171
171
  it("the job takes the lease after release-pr and the merge carries the Forge-Epoch trailer and a write-ahead intent", async () => {
@@ -215,7 +215,7 @@ describe("release fencing through the job (#5553)", () => {
215
215
  for (const dieAt of RELEASE_STEPS) {
216
216
  const g = fakeGh(), calls = [], ran = [];
217
217
  const track = (name, fn) => async (...a) => { if (name === dieAt && !ran.includes(`die:${name}`)) { ran.push(`die:${name}`); throw new Error("kill -9"); } ran.push(name); return fn(...a); };
218
- const base = { preflight: ok, "host-preflight": skip, "release-pr": async () => ({ pr: 7 }), review: ok, fixes: ok, "mark-ready": skip, rehearsal: skip, "post-merge": ok, deploy: skip };
218
+ const base = { preflight: ok, "host-preflight": skip, "release-pr": async () => ({ pr: 7 }), "ci-green": ok, review: ok, fixes: ok, "mark-ready": skip, rehearsal: skip, "post-merge": ok, deploy: skip };
219
219
  const wrapped = withStubs(Object.fromEntries(Object.entries(withStubs(base)).map(([k, fn]) => [k, track(k, fn)])));
220
220
  await assert.rejects(() => go(mkIo(g, "hostA", calls), wrapped, tmpDir("fe1-")), /kill -9/, dieAt);
221
221
  const out = await go(mkIo(g, "hostB", calls), wrapped, tmpDir("fe2-")); // another host, empty disk
@@ -33,7 +33,7 @@ function fakeIo({ preflightOk = () => true, draft = true } = {}) {
33
33
  },
34
34
  };
35
35
  }
36
- const run = (io, config, over = {}) => runRelease({ io, repo: REPO, root: tmpDir("rel-pf-"), mounts: DISK, id: newReleaseId(), opts: {}, config, branches: { staging: "staging", default: "main" }, steps: withStubs({ review: ok, fixes: ok, promotion: ok, "post-merge": ok, ...over }) });
36
+ const run = (io, config, over = {}) => runRelease({ io, repo: REPO, root: tmpDir("rel-pf-"), mounts: DISK, id: newReleaseId(), opts: {}, config, branches: { staging: "staging", default: "main" }, steps: withStubs({ "ci-green": ok, review: ok, fixes: ok, promotion: ok, "post-merge": ok, ...over }) });
37
37
  const CFG = readReleaseConfig("release:\n preflight_command: npm test\n");
38
38
 
39
39
  describe("release host preflight (#5277)", () => {
@@ -103,7 +103,7 @@ describe("release host preflight (#5277)", () => {
103
103
  headOf: async () => HEAD, runLane: async () => ({ terminalReason: "merged" }), fileFixIssue: async () => 3, failedJobs: async () => [],
104
104
  calls: [],
105
105
  };
106
- return { io, seam, ctx: { io: Object.assign(io, { review: seam }), repo: REPO, def: "main", staging: "staging", config: CFG, save() {}, state: { steps: { review: { result: { pr: 9, marker: "FORGE:GATE_FAILURE", verdict: "X", head: "b".repeat(40), blocking: [11], ciFailing: 0 } } } } } };
106
+ return { io, seam, ctx: { io: Object.assign(io, { review: seam }), repo: REPO, def: "main", staging: "staging", config: { ...CFG, reviewFixes: true }, save() {}, state: { steps: { review: { result: { pr: 9, marker: "FORGE:GATE_FAILURE", verdict: "X", head: "b".repeat(40), blocking: [11], ciFailing: 0 } } } } } };
107
107
  };
108
108
  const red = mk(false);
109
109
  const out = await fixStep(red.ctx);
@@ -35,7 +35,7 @@ function fakeIo({ run = { ok: true }, issues = [], body = "Bundle" } = {}) {
35
35
  return io;
36
36
  }
37
37
  const go = async (io, config, root = tmpDir("rehearsal-"), id = newReleaseId()) => ({
38
- out: await runRelease({ io, repo: REPO, root, mounts: DISK, id, opts: { merge: true }, config, branches: { staging: "staging", default: "main" }, steps: withStubs({ review: ok, fixes: ok, "post-merge": ok }) }),
38
+ out: await runRelease({ io, repo: REPO, root, mounts: DISK, id, opts: { merge: true }, config, branches: { staging: "staging", default: "main" }, steps: withStubs({ "ci-green": ok, review: ok, fixes: ok, "post-merge": ok }) }),
39
39
  root, id,
40
40
  });
41
41
  const cfg = (o = {}) => ({ rehearsal: parseRehearsalConfig({ rehearsal_command: "./dry-run.sh", ...o }) });
@@ -1,7 +1,7 @@
1
1
  // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  /**
4
- * End-to-end run of `forgedock release` through the real job (preflight, release-pr, review, fixes, promotion) against an
4
+ * (Legacy, `release.review_fixes: true`; the default flow stops at review blockers: release-review.test.mjs.) End-to-end run of `forgedock release` through the real job (preflight, release-pr, review, fixes, promotion) against an
5
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
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
7
  * model and the lane process are in memory (as in conformance.e2e.test.mjs); the job, steps, state and resume are real.
@@ -29,6 +29,7 @@ function world() {
29
29
  throw new Error(`unexpected gh ${j}`);
30
30
  },
31
31
  };
32
+ io.ciGreen = { now: () => 0, sleep: async () => {}, isDraft: async () => false, headOf: async () => sha(w.head), checks: async () => [], required: async () => [] }; // CI is green at once
32
33
  io.review = {
33
34
  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
35
  headOf: async () => sha(w.head),
@@ -55,7 +56,7 @@ function world() {
55
56
  describe("forgedock release, review to gate (e2e on in-memory GitHub)", () => {
56
57
  it("reviews, files the blocking finding, fixes it on staging, re-reviews the delta and stops at GATE_PASS with the merge command", async () => {
57
58
  const { w, io } = world();
58
- const out = await runRelease({ io, repo: "o/r", root: tmpDir("rel-e2e-"), mounts: DISK, id: newReleaseId(), opts: {}, config: {}, branches: { staging: "staging", default: "main" } });
59
+ const out = await runRelease({ io, repo: "o/r", root: tmpDir("rel-e2e-"), mounts: DISK, id: newReleaseId(), opts: {}, config: { reviewFixes: true }, branches: { staging: "staging", default: "main" } });
59
60
  assert.equal(out.status, "stopped");
60
61
  assert.equal(out.step, "promotion");
61
62
  assert.match(out.reason, /GATE_PASS/);
@@ -69,7 +70,7 @@ describe("forgedock release, review to gate (e2e on in-memory GitHub)", () => {
69
70
  it("a killed job resumes after the review step without re-running it", async () => {
70
71
  const { w, io } = world();
71
72
  const root = tmpDir("rel-e2e-"), id = newReleaseId();
72
- const args = { io, repo: "o/r", root, mounts: DISK, id, opts: {}, config: {}, branches: { staging: "staging", default: "main" } };
73
+ const args = { io, repo: "o/r", root, mounts: DISK, id, opts: {}, config: { reviewFixes: true }, branches: { staging: "staging", default: "main" } };
73
74
  await runRelease(args);
74
75
  const agents = w.agents.length;
75
76
  assert.equal(openRelease(root, id, DISK).load().steps.fixes.done, true);
@@ -18,15 +18,17 @@ import { lowerPriority } from "./hostload.mjs";
18
18
  import { reviewStagingJson, reviewStagingIo, CI_EXCLUDED_CHECKS } from "../review-staging.mjs";
19
19
  import { pickFixes, recut, revertLast } from "./release-snapshot.mjs";
20
20
  import { parseFixConfig, collectFindings, blockingOf, compileBrief, roundsAt, recordRound, secondPush, secondPushOf, holdForOwner, jobsToRerun, inputHash, deferredOf } from "./release-fixloop.mjs";
21
- import { coStartCi } from "./release-preflight.mjs";
22
21
  import { laneEnv } from "./release-credentials.mjs";
22
+ import { ciGreenWait, addTiming, blockSetOf } from "./release-cigreen.mjs";
23
23
 
24
24
  /** Delta passes after a head move: past it the job blocks for the manual path. Fix rounds are `ci.fix.max_rounds` (release-fixloop.mjs, default 1, #5567). */
25
25
  export const MAX_DELTA_PASSES = 2;
26
26
  const REVIEW_MS = 45 * 60_000, LANE_MS = 3 * 60 * 60_000;
27
27
  const CI_WAIT_MS = 10 * 60_000, CI_POLL_MS = 60_000; // #5779: bounded fail-late CI wait of the fix step
28
28
  const ROOT = fileURLToPath(new URL("../..", import.meta.url));
29
- const SEVERE = new Set(["CRITICAL", "HIGH"]);
29
+ const DEFAULT_BLOCK = new Set(["CRITICAL", "HIGH"]);
30
+ /** Default policy (no off switch): a finding blocks only when CONFIRMED and at or above the blocking severity (default HIGH; forge.yaml release.block_severity tightens or loosens it). Everything else is filed for the next release. */
31
+ const isBlocking = (item, st, set) => set.has(String(item.severity ?? "").toUpperCase()) && (!Array.isArray(st.confirmedIds) || st.confirmedIds.includes(item.id));
30
32
  const MANUAL = "use the manual path: forgedock review-staging <PR> (commands/review-pr-staging.md)";
31
33
  const blocked = (why) => ({ blocked: true, reason: `${why}; ${MANUAL}` });
32
34
 
@@ -177,35 +179,49 @@ async function reviewRound({ seam, pr, def, delta }) {
177
179
  }
178
180
 
179
181
  /** The whole review of PR `pr`: rounds until one finalizes at its own head. @returns the step result or `{blocked}`. */
180
- async function runReview({ seam, pr, def, delta = null }) {
182
+ async function runReview({ seam, pr, def, delta = null, green = null, blockSet = DEFAULT_BLOCK, maxDelta = 0 }) {
181
183
  let st = null;
182
184
  for (let pass = 0; ; pass++) {
183
185
  const r = await reviewRound({ seam, pr, def, delta });
184
186
  if (r.fail) return blocked(r.fail);
185
187
  if (r.ok) { st = r.ok; break; }
186
- if (pass >= MAX_DELTA_PASSES) return blocked(`head of #${pr} kept moving during the review (${MAX_DELTA_PASSES} delta passes)`);
188
+ // Default flow: ONE review pass on the green head. A head that moves under the review is not reviewed again in place: re-run the release (ci-green re-checks the new head).
189
+ if (!maxDelta) return blocked(`head of #${pr} moved during the review (${String(r.moved).slice(0, 7)} -> ${String(await seam.headOf(pr)).slice(0, 7)}); re-run the release: ci-green re-checks the new head, then one review pass`);
190
+ if (pass >= maxDelta) return blocked(`head of #${pr} kept moving during the review (${maxDelta} delta passes)`);
187
191
  delta = r.moved;
192
+ if (green) { const g = await green(); if (g?.blocked) return g; } // a head move goes back through ci-green before the delta review
188
193
  }
189
194
  const filed = [], blocking = [];
190
195
  for (const item of st.toFile ?? []) {
191
196
  const n = await seam.fileIssue({ item, pr, head: st.head });
192
197
  if (!n) return blocked(`could not file the finding "${item.title ?? item.id}"`);
193
198
  filed.push(n);
194
- if (SEVERE.has(String(item.severity ?? "").toUpperCase())) blocking.push(n);
199
+ if (isBlocking(item, st, blockSet)) blocking.push(n);
195
200
  }
196
201
  if ((st.notes ?? []).length) await seam.addNotes(pr, st.notes);
197
202
  const sum = await seam.summary({ pr, filed });
198
203
  if (!sum.data) return blocked(`the gate summary was not posted (exit ${sum.code}): ${(sum.lines ?? []).slice(-1).join("").slice(0, 200)}`);
199
- return { pr, head: st.head, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, ciCancelOnly: Boolean(sum.data.ciCancelOnly), ciPendingOnly: Boolean(sum.data.ciPendingOnly), filed, blocking, items: st.toFile ?? [], guards: st.guards ?? [], delta: st.delta?.from ?? null };
204
+ return { pr, head: st.head, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, ciCancelOnly: Boolean(sum.data.ciCancelOnly), ciPendingOnly: Boolean(sum.data.ciPendingOnly), filed, blocking, items: (st.toFile ?? []).map((i) => ({ ...i, blocking: isBlocking(i, st, blockSet), filed: true })), guards: st.guards ?? [], delta: st.delta?.from ?? null };
200
205
  }
201
206
 
202
- /** Review step. @returns {{pr, head, verdict, marker, filed, blocking}|{blocked: true, reason: string}} */
207
+ /**
208
+ * Review step: ONE review pass on a head whose required checks are green (the v1.0 contract, commands/review-pr-staging.md at dcfb86bf).
209
+ * Every finding is filed (Phase 7) and nothing the review finds is fixed in the release PR. The `release.review_fixes` knob (default
210
+ * off) restores the #5212 delta passes. @returns {{pr, head, verdict, marker, filed, blocking}|{blocked: true, reason: string}}
211
+ */
212
+ export const seamOf = (ctx) => ctx.io.review ?? (ctx.seam ??= realSeam(ctx));
203
213
  export async function reviewStep(ctx) {
204
214
  const pr = ctx.state?.steps?.["release-pr"]?.result?.pr;
205
215
  if (!pr) return blocked("no release PR recorded by the release-pr step");
206
- const started = await coStartCi(ctx, { pr }); // #5567: CI and the panel start on the same head (off unless ci.fix is configured)
207
- if (started?.refused) return { refused: started.refused };
208
- return runReview({ seam: seamOf(ctx), pr, def: ctx.def });
216
+ const g = await ciGreenWait(ctx, pr); // cheap when already green; covers a head that moved since the ci-green step (a resume)
217
+ if (g.blocked) return g;
218
+ const legacy = Boolean(ctx.config?.reviewFixes);
219
+ return timedReview(ctx, () => runReview({ seam: seamOf(ctx), pr, def: ctx.def, green: () => ciGreenWait(ctx, pr), blockSet: blockSetOf(ctx.config), maxDelta: legacy ? MAX_DELTA_PASSES : 0 }));
220
+ }
221
+ /** Review minutes and passes of this release go to `state.timing` (read by release status and the ledger). */
222
+ async function timedReview(ctx, fn) {
223
+ const t0 = Date.now();
224
+ try { return await fn(); } finally { addTiming(ctx, "review_min", Date.now() - t0); addTiming(ctx, "review_passes", 1, { raw: true }); }
209
225
  }
210
226
 
211
227
  /** Re-read the gate summary into the review result (after a rerun or a re-summarise). */
@@ -243,7 +259,7 @@ async function secondRound(ctx, seam, r, cfg) {
243
259
  const head = await seam.headOf(r.pr);
244
260
  recordRound(ctx.state, { from: r.head, to: head, kind: "revert", failedBefore: rec.ci.map((j) => j.name) });
245
261
  ctx.save();
246
- const next = await runReview({ seam, pr: r.pr, def: ctx.def, delta: r.head });
262
+ const next = await runReview({ seam, pr: r.pr, def: ctx.def, delta: r.head, maxDelta: MAX_DELTA_PASSES });
247
263
  if (next.blocked) return next;
248
264
  ctx.state.steps.review = { ...ctx.state.steps.review, result: next };
249
265
  ctx.save();
@@ -251,11 +267,96 @@ async function secondRound(ctx, seam, r, cfg) {
251
267
  }
252
268
 
253
269
  /**
254
- * Fix step: nothing to do on GATE_PASS; else ONE round (`ci.fix.max_rounds`, counted per head sha): collect every failed job, finding
270
+ * One fix round on release PR `r.pr`: collect every failed CI job, blocking finding and guard on `r.head`, compile one brief, file one fix
271
+ * issue, run one lane, bring the fix onto the release branch and record the head move. No review here: the caller sends the new head back
272
+ * through ci-green and then ONE delta review. @returns {{head, rec}|{blocked: true, reason}}
273
+ */
274
+ export async function fixRound(ctx, seam, r) {
275
+ const cfg = parseFixConfig(ctx.config?.fix);
276
+ // #5779: with blocking findings in hand the fix round starts now (completed runs go into the brief); else the wait is bounded
277
+ const seen = r.ciFailing > 0 ? await seam.failedJobs({ pr: r.pr, head: r.head, wait: !r.blocking?.length }) : [];
278
+ // #6013: failures the staging-health gate named earlier ride along in the same brief, so all fixes are dispatched together.
279
+ const known = (ctx.state.knownFailures ?? []).filter((k) => !seen.some((j) => j.name === k.name)).map((k) => ({ name: k.name, conclusion: "failure", log: `failed on staging (${k.cause})` }));
280
+ const jobs = Object.assign([...seen, ...known], { pending: seen.pending });
281
+ const rec = collectFindings({ head: r.head, jobs, findings: r.items ?? [], guards: r.guards ?? [] });
282
+ const b = blockingOf(rec);
283
+ if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && jobs.pending?.length) return blocked(`required checks of #${r.pr} still running (${jobs.pending.join(", ")}), with no failure to fix yet; re-run the release once CI finishes`);
284
+ if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && !(r.ciFailing > 0)) return blocked(`${r.verdict} (${r.marker}) on #${r.pr} at ${String(r.head).slice(0, 7)} with neither a blocking finding nor red CI to fix: nothing is pending or failing, so the gate summary names the actual blocker; read it and re-run the release`);
285
+ const hashesNow = Object.fromEntries(rec.ci.map((j) => [j.name, j.inputHash ?? inputHash(j.name, r.head)]));
286
+ const brief = compileBrief(rec, { commands: ctx.config?.preflight ? [ctx.config.preflight.command] : [], rerunChecks: jobsToRerun(hashesNow, ctx.state.fixloop?.hashes ?? {}) });
287
+ // Non-blocking and out-of-wave findings become next-plan issues, once per head; they are never part of the fix and never merged after READY (I16).
288
+ const fl = (ctx.state.fixloop ??= { heads: {} });
289
+ fl.hashes = hashesNow;
290
+ if (!fl.deferred?.includes(r.head)) {
291
+ const later = deferredOf(rec).filter((x) => !x.filed); // review findings are already filed for the next release by the review round
292
+ if (later.length) await seam.fileDeferred?.({ pr: r.pr, head: r.head, items: later });
293
+ fl.deferred = [...(fl.deferred ?? []), r.head];
294
+ ctx.save();
295
+ }
296
+ // One issue carries the whole brief (blocking findings stay filed as their own issues and are referenced); its lane is the one fix lane.
297
+ const issue = await seam.fileFixIssue({ pr: r.pr, head: r.head, brief, blocking: r.blocking ?? [] });
298
+ if (!issue) return blocked(`could not file the fix issue for #${r.pr}`);
299
+ // A resume after the fix already merged (by this job or by an intake lane): its lane would end invalid on a closed issue.
300
+ if (!(await seam.issueMerged?.(issue))) {
301
+ const lane = await seam.runLane({ issue, lane: ctx.staging });
302
+ if (lane?.terminalReason !== "merged") return blocked(`fix lane for #${issue} ended ${lane?.terminalReason ?? "without a result"}`);
303
+ }
304
+ // Snapshot mode (#5276): the fixes are merged on staging; bring exactly those onto release/<id> (or recut it) before the delta review.
305
+ if (ctx.config?.mode === "snapshot") {
306
+ const moved = ctx.config.fixMode === "recut" ? await recut(ctx) : await pickFixes(ctx, { issues: [issue, ...(r.blocking ?? [])] });
307
+ if (moved.err) return blocked(moved.err);
308
+ }
309
+ // The host preflight re-runs on the head the fixes produced, before the delta review (the draft PR has no Actions CI yet, #5277).
310
+ const head = await seam.headOf(r.pr);
311
+ if (ctx.config?.preflight) {
312
+ const pf = await runHostPreflight(ctx, { head, pr: r.pr });
313
+ if (!pf.ok && pf.blocking) return blocked(`host preflight failed at ${pf.head} after the fix round (release-blocker #${pf.issue})`);
314
+ }
315
+ recordRound(ctx.state, { from: r.head, to: head, failedBefore: rec.ci.map((j) => j.name) });
316
+ ctx.save();
317
+ addTiming(ctx, "fix_rounds", Object.values(ctx.state.fixloop?.heads ?? {}).filter((h) => !h.second).length, { set: true });
318
+ return { head, rec };
319
+ }
320
+
321
+ /**
322
+ * Verdict step (default flow, the v1.0 contract at dcfb86bf): GATE_PASS passes. A CONFIRMED CRITICAL/HIGH blocker (or a failed guard)
323
+ * STOPS the release: no fix lane, no delta pass. The blocker issues are queued into the repo's open orchestrate batch, the release PR is
324
+ * closed with the verdict, and the next release starts fresh once they merge (the open-finding gate enforces that). Everything else the
325
+ * review found is already filed for later. The `release.review_fixes` knob (default off) restores the #5212 fix lanes below.
326
+ */
327
+ export async function fixStep(ctx) {
328
+ const r = ctx.state?.steps?.review?.result;
329
+ if (!r?.pr) return blocked("no review result recorded by the review step");
330
+ if (ctx.config?.reviewFixes) return legacyFixStep(ctx);
331
+ const seam = seamOf(ctx);
332
+ if (ctx.state.reviewBlocked?.head === r.head) return { blocked: true, reason: ctx.state.reviewBlocked.reason }; // a resume of a stopped release says the same thing, queues nothing twice
333
+ let res = r;
334
+ // #5912: a CI-only gap at an unmoved head is re-summarised once, so CI that finished green since posts GATE_PASS.
335
+ if (res.marker !== "FORGE:GATE_PASS" && !res.blocking?.length && !res.guards?.length && (res.ciPendingOnly || res.ciCancelOnly || !(res.ciFailing > 0)) && (await seam.headOf(res.pr)) === res.head) {
336
+ const s = await resummarise(ctx, seam, res);
337
+ if (s.err) return blocked(s.err);
338
+ res = s.r;
339
+ }
340
+ if (res.marker === "FORGE:GATE_PASS") return { verdict: res.verdict, head: res.head };
341
+ if (res.blocking?.length || res.guards?.length) {
342
+ const names = res.blocking?.length ? res.blocking.map((n) => `#${n}`).join(" ") : (res.guards ?? []).map((g) => g.name).join(", ");
343
+ const queued = res.blocking?.length ? await seam.queueBlockers?.({ pr: res.pr, blockers: res.blocking }) : null;
344
+ const closed = await seam.holdReleasePr?.({ pr: res.pr, blockers: res.blocking ?? [], guards: res.guards ?? [], queued, verdict: res.verdict });
345
+ const reason = `review blockers ${names}${queued?.batch ? ` (queued in batch ${queued.batch})` : ""}; release PR #${res.pr} ${closed?.closed ? "closed" : "held"}; the next release starts fresh after they merge`;
346
+ ctx.state.reviewBlocked = { head: res.head, blockers: res.blocking ?? [], batch: queued?.batch ?? null, reason };
347
+ ctx.save();
348
+ return { blocked: true, held: true, reason };
349
+ }
350
+ if (res.ciFailing > 0) return blocked(`required checks of #${res.pr} are not green at ${String(res.head).slice(0, 7)} (${res.ciPendingOnly ? "pending" : "red"}); re-run the release: ci-green waits and fixes CI once, then one review pass`);
351
+ return blocked(`${res.verdict} (${res.marker}) on #${res.pr} at ${String(res.head).slice(0, 7)} with no blocking finding and no red CI: the gate summary names the blocker; read it and re-run the release`);
352
+ }
353
+
354
+ /**
355
+ * Legacy review-fix step (#5212, #5567), only with `release.review_fixes: true` (default off): nothing to do on GATE_PASS; else ONE round (`ci.fix.max_rounds`, counted per head sha): collect every failed job, finding
255
356
  * and guard on the head, compile one invariant-grouped brief, file one fix issue, run one lane, push once, delta-review the fix commits.
256
357
  * A still-failing head after the budget gets only a mechanical revert or an infra-flake rerun, once; else HELD with an owner ask.
257
358
  */
258
- export async function fixStep(ctx) {
359
+ async function legacyFixStep(ctx) {
259
360
  let r = ctx.state?.steps?.review?.result;
260
361
  if (!r?.pr) return blocked("no review result recorded by the review step");
261
362
  const seam = seamOf(ctx);
@@ -285,48 +386,13 @@ export async function fixStep(ctx) {
285
386
  r = s.r;
286
387
  continue;
287
388
  }
288
- // #5779: with blocking findings in hand the fix round starts now (completed runs go into the brief); else the wait is bounded
289
- const seen = r.ciFailing > 0 ? await seam.failedJobs({ pr: r.pr, head: r.head, wait: !r.blocking?.length }) : [];
290
- // #6013: failures the staging-health gate named earlier ride along in the same brief, so all fixes are dispatched together.
291
- const known = (ctx.state.knownFailures ?? []).filter((k) => !seen.some((j) => j.name === k.name)).map((k) => ({ name: k.name, conclusion: "failure", log: `failed on staging (${k.cause})` }));
292
- const jobs = Object.assign([...seen, ...known], { pending: seen.pending });
293
- const rec = collectFindings({ head: r.head, jobs, findings: r.items ?? [], guards: r.guards ?? [] });
294
- const b = blockingOf(rec);
295
- if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && jobs.pending?.length) return blocked(`required checks of #${r.pr} still running (${jobs.pending.join(", ")}), with no failure to fix yet; re-run the release once CI finishes`);
296
- if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && !(r.ciFailing > 0)) return blocked(`${r.verdict} (${r.marker}) on #${r.pr} at ${String(r.head).slice(0, 7)} with neither a blocking finding nor red CI to fix: nothing is pending or failing, so the gate summary names the actual blocker; read it and re-run the release`);
297
- const hashesNow = Object.fromEntries(rec.ci.map((j) => [j.name, j.inputHash ?? inputHash(j.name, r.head)]));
298
- const brief = compileBrief(rec, { commands: ctx.config?.preflight ? [ctx.config.preflight.command] : [], rerunChecks: jobsToRerun(hashesNow, ctx.state.fixloop?.hashes ?? {}) });
299
- // Non-blocking and out-of-wave findings become next-plan issues, once per head; they are never part of the fix and never merged after READY (I16).
300
- const fl = (ctx.state.fixloop ??= { heads: {} });
301
- fl.hashes = hashesNow;
302
- if (!fl.deferred?.includes(r.head)) {
303
- const later = deferredOf(rec);
304
- if (later.length) await seam.fileDeferred?.({ pr: r.pr, head: r.head, items: later });
305
- fl.deferred = [...(fl.deferred ?? []), r.head];
306
- ctx.save();
307
- }
308
- // One issue carries the whole brief (blocking findings stay filed as their own issues and are referenced); its lane is the one fix lane.
309
- const issue = await seam.fileFixIssue({ pr: r.pr, head: r.head, brief, blocking: r.blocking ?? [] });
310
- if (!issue) return blocked(`could not file the fix issue for #${r.pr}`);
311
- // A resume after the fix already merged (by this job or by an intake lane): its lane would end invalid on a closed issue.
312
- if (!(await seam.issueMerged?.(issue))) {
313
- const lane = await seam.runLane({ issue, lane: ctx.staging });
314
- if (lane?.terminalReason !== "merged") return blocked(`fix lane for #${issue} ended ${lane?.terminalReason ?? "without a result"}`);
315
- }
316
- // Snapshot mode (#5276): the fixes are merged on staging; bring exactly those onto release/<id> (or recut it) before the delta review.
317
- if (ctx.config?.mode === "snapshot") {
318
- const moved = ctx.config.fixMode === "recut" ? await recut(ctx) : await pickFixes(ctx, { issues: [issue, ...(r.blocking ?? [])] });
319
- if (moved.err) return blocked(moved.err);
320
- }
321
- // The host preflight re-runs on the head the fixes produced, before the delta review (the draft PR has no Actions CI yet, #5277).
322
- const head = await seam.headOf(r.pr);
323
- if (ctx.config?.preflight) {
324
- const pf = await runHostPreflight(ctx, { head, pr: r.pr });
325
- if (!pf.ok && pf.blocking) return blocked(`host preflight failed at ${pf.head} after the fix round (release-blocker #${pf.issue})`);
326
- }
327
- recordRound(ctx.state, { from: r.head, to: head, failedBefore: rec.ci.map((j) => j.name) });
328
- ctx.save();
329
- const next = await runReview({ seam, pr: r.pr, def: ctx.def, delta: r.head });
389
+ const f = await fixRound(ctx, seam, r);
390
+ if (f.blocked) return f;
391
+ const { head, rec } = f;
392
+ // The fix moved the head: ci-green first (it never starts a second fix), then ONE delta review limited to what the fix touched.
393
+ const g = await ciGreenWait(ctx, r.pr, { noFix: true });
394
+ if (g.blocked || g.red) return g.blocked ? g : blocked(`required checks of #${r.pr} are still red after the fix round (${g.failing.join(", ")})`);
395
+ const next = await timedReview(ctx, () => runReview({ seam, pr: r.pr, def: ctx.def, delta: r.head, green: () => ciGreenWait(ctx, r.pr, { noFix: true }), blockSet: blockSetOf(ctx.config), maxDelta: MAX_DELTA_PASSES }));
330
396
  if (next.blocked) return next;
331
397
  if (next.head && next.head !== head) { recordRound(ctx.state, { from: r.head, to: next.head, failedBefore: rec.ci.map((j) => j.name) }); ctx.save(); } // the reviewed head is the one the budget is keyed on
332
398
  r = next;
@@ -336,7 +402,6 @@ export async function fixStep(ctx) {
336
402
  return { verdict: r.verdict, head: r.head };
337
403
  }
338
404
 
339
- const seamOf = (ctx) => ctx.io.review ?? (ctx.seam ??= realSeam(ctx));
340
405
 
341
406
  /** Real effects of the review steps: the review-staging library, the engine runner, the filing scripts, gh and a lane process. */
342
407
  /** #6098: CPU niceness of reviewer processes (ionice idle class is applied alongside). */
@@ -408,6 +473,21 @@ export function realSeam({ repo, def, env = process.env, laneStrip = [], cwd = p
408
473
  return Object.assign(jobs, { pending: open(runs) });
409
474
  },
410
475
  // #5567: findings that do not block (or lie outside the wave) are filed for the next plan, labelled so the release never picks them up
476
+ // Default flow: a blocking verdict queues the blocker issues into the repo's open orchestrate batch (when one exists) and closes the release PR.
477
+ queueBlockers: async ({ blockers }) => {
478
+ try {
479
+ const batches = (await io?.batches?.(repo)) ?? [];
480
+ if (!batches.length) return { batch: null };
481
+ const add = io?.addToBatch ?? (async (id, nums) => { const { orchestrateFromCli } = await import("../engine-cli.mjs"); await orchestrateFromCli(["--add", id, ...nums.map(String)]); });
482
+ await add(batches[0].id, blockers);
483
+ return { batch: batches[0].id };
484
+ } catch (e) { return { batch: null, error: String(e?.message ?? e).split("\n")[0] }; }
485
+ },
486
+ holdReleasePr: async ({ pr, blockers, guards, queued, verdict }) => {
487
+ const what = blockers.length ? `confirmed CRITICAL/HIGH finding(s) ${blockers.map((n) => `#${n}`).join(" ")}` : `failed guard(s) ${guards.map((g) => g.name).join(", ")}`;
488
+ const body = `Release stopped: ${verdict ?? "BLOCK DEPLOY"}. ${what} block this release. ${queued?.batch ? `They are queued in orchestrate batch ${queued.batch}.` : "No orchestrate batch is open: start one with `forgedock orchestrate " + blockers.join(" ") + "`."} Nothing found by the review is fixed inside the release PR; the next release starts fresh after they merge (the open-finding gate enforces it).`;
489
+ try { gh(["pr", "close", String(pr), "-R", repo, "--comment", body]); return { closed: true }; } catch { try { gh(["pr", "comment", String(pr), "-R", repo, "--body", body]); } catch { /* the blocked result still stops the job */ } return { closed: false }; }
490
+ },
411
491
  async fileDeferred({ pr, items }) {
412
492
  const out = [];
413
493
  for (const f of items) { const n = await this.fileIssue({ item: { title: `Next plan: ${f.title}`, severity: f.severity ?? "LOW", body: `Not blocking release PR #${pr} (non-blocking or outside the wave); deferred to the next plan.` }, pr }); if (n) out.push(n); }