forgedock 1.66.0 → 1.68.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 (173) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +2 -0
  3. package/bin/engine-cli.mjs +193 -27
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +24 -1
  6. package/bin/help-text.mjs +4 -3
  7. package/bin/introspect-schedule.mjs +98 -0
  8. package/bin/introspect-schedule.test.mjs +67 -0
  9. package/bin/lean/admission.mjs +21 -0
  10. package/bin/lean/admission.test.mjs +30 -0
  11. package/bin/lean/advisory.test.mjs +64 -0
  12. package/bin/lean/amendment-schema.mjs +30 -0
  13. package/bin/lean/attempts.mjs +162 -0
  14. package/bin/lean/attempts.test.mjs +141 -0
  15. package/bin/lean/basered.mjs +81 -0
  16. package/bin/lean/basered.test.mjs +68 -1
  17. package/bin/lean/batch-health.mjs +20 -12
  18. package/bin/lean/batch-health.test.mjs +55 -11
  19. package/bin/lean/batch.mjs +45 -0
  20. package/bin/lean/batch.test.mjs +105 -5
  21. package/bin/lean/capwait.mjs +14 -3
  22. package/bin/lean/capwait.test.mjs +20 -0
  23. package/bin/lean/ci-gate.mjs +2 -90
  24. package/bin/lean/ci-gate.test.mjs +1 -127
  25. package/bin/lean/ci-precheck.mjs +25 -8
  26. package/bin/lean/ci-precheck.test.mjs +24 -0
  27. package/bin/lean/clear-breaker.mjs +14 -0
  28. package/bin/lean/clear-breaker.test.mjs +4 -3
  29. package/bin/lean/commentstate.mjs +46 -0
  30. package/bin/lean/commentstate.test.mjs +43 -0
  31. package/bin/lean/concurrency.mjs +89 -0
  32. package/bin/lean/concurrency.test.mjs +113 -0
  33. package/bin/lean/conformance.e2e.test.mjs +13 -8
  34. package/bin/lean/conformance.mjs +73 -181
  35. package/bin/lean/conformance.test.mjs +61 -345
  36. package/bin/lean/depcache.mjs +100 -10
  37. package/bin/lean/depcache.test.mjs +105 -0
  38. package/bin/lean/docsgate.mjs +0 -32
  39. package/bin/lean/docsgate.test.mjs +2 -23
  40. package/bin/lean/effects-cap.test.mjs +9 -1
  41. package/bin/lean/effects-killtree.test.mjs +35 -0
  42. package/bin/lean/effects.mjs +42 -24
  43. package/bin/lean/efficiency.mjs +162 -0
  44. package/bin/lean/efficiency.test.mjs +79 -0
  45. package/bin/lean/engine-readmit.test.mjs +35 -0
  46. package/bin/lean/envgap.mjs +93 -0
  47. package/bin/lean/envgap.test.mjs +53 -0
  48. package/bin/lean/execution.mjs +41 -17
  49. package/bin/lean/execution.test.mjs +58 -0
  50. package/bin/lean/failure-census.mjs +170 -0
  51. package/bin/lean/failure-census.test.mjs +59 -0
  52. package/bin/lean/failure-stop.mjs +46 -0
  53. package/bin/lean/failure-stop.test.mjs +45 -0
  54. package/bin/lean/fixtures/capacity-storm.json +609 -0
  55. package/bin/lean/guardgate.test.mjs +2 -3
  56. package/bin/lean/heavy.mjs +33 -4
  57. package/bin/lean/heavy.test.mjs +38 -6
  58. package/bin/lean/hotarea.mjs +0 -36
  59. package/bin/lean/hotarea.test.mjs +1 -22
  60. package/bin/lean/issuewatch-verify.mjs +19 -4
  61. package/bin/lean/issuewatch.mjs +21 -4
  62. package/bin/lean/issuewatch.test.mjs +48 -1
  63. package/bin/lean/lane-audit-gap.mjs +66 -0
  64. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  65. package/bin/lean/lane-audit-llm.mjs +5 -0
  66. package/bin/lean/lane-audit-query.mjs +47 -0
  67. package/bin/lean/lane-audit-query.test.mjs +44 -0
  68. package/bin/lean/lane-audit-signatures.mjs +33 -0
  69. package/bin/lean/lane-audit.mjs +110 -0
  70. package/bin/lean/lane-audit.test.mjs +97 -0
  71. package/bin/lean/lane-recovery.test.mjs +33 -0
  72. package/bin/lean/lanecheck.mjs +5 -3
  73. package/bin/lean/lanecheck.test.mjs +6 -0
  74. package/bin/lean/lean.mjs +311 -154
  75. package/bin/lean/lean.test.mjs +530 -223
  76. package/bin/lean/limits.mjs +17 -0
  77. package/bin/lean/limits.test.mjs +15 -1
  78. package/bin/lean/live-execution.mjs +21 -2
  79. package/bin/lean/live-execution.test.mjs +39 -0
  80. package/bin/lean/liveness.mjs +37 -0
  81. package/bin/lean/liveness.test.mjs +33 -0
  82. package/bin/lean/orchestrate-attempts.test.mjs +82 -0
  83. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  84. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  85. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  86. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  87. package/bin/lean/orchestrate-pause.test.mjs +76 -1
  88. package/bin/lean/orchestrate-reconcile.test.mjs +164 -0
  89. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  90. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  91. package/bin/lean/orchestrate.mjs +344 -45
  92. package/bin/lean/phaseledger.mjs +6 -0
  93. package/bin/lean/phaseledger.test.mjs +13 -1
  94. package/bin/lean/postdeploy-check.test.mjs +1 -3
  95. package/bin/lean/precheck.mjs +20 -0
  96. package/bin/lean/preflight.mjs +100 -11
  97. package/bin/lean/preflight.test.mjs +44 -4
  98. package/bin/lean/prompts.mjs +13 -28
  99. package/bin/lean/reconcile.mjs +90 -0
  100. package/bin/lean/recurrence.mjs +6 -112
  101. package/bin/lean/recurrence.test.mjs +11 -92
  102. package/bin/lean/release-flakes.mjs +14 -2
  103. package/bin/lean/release-flakes.test.mjs +17 -1
  104. package/bin/lean/release-ledger.mjs +19 -1
  105. package/bin/lean/release-ledger.test.mjs +23 -0
  106. package/bin/lean/release-preflight.mjs +28 -0
  107. package/bin/lean/release-preflight.test.mjs +42 -1
  108. package/bin/lean/release-review.mjs +40 -5
  109. package/bin/lean/release-review.test.mjs +43 -2
  110. package/bin/lean/release.mjs +43 -14
  111. package/bin/lean/release.test.mjs +32 -0
  112. package/bin/lean/retry.mjs +1 -1
  113. package/bin/lean/retry.test.mjs +6 -1
  114. package/bin/lean/rotator.mjs +9 -0
  115. package/bin/lean/rotator.test.mjs +11 -1
  116. package/bin/lean/sandbox-remote.mjs +49 -11
  117. package/bin/lean/sched.mjs +19 -0
  118. package/bin/lean/sched.test.mjs +11 -1
  119. package/bin/lean/schedd-health.mjs +4 -4
  120. package/bin/lean/schedd-health.test.mjs +8 -4
  121. package/bin/lean/schedd.mjs +45 -8
  122. package/bin/lean/schedd.test.mjs +120 -7
  123. package/bin/lean/selfreview.mjs +1 -1
  124. package/bin/lean/slo.mjs +126 -0
  125. package/bin/lean/slo.test.mjs +112 -0
  126. package/bin/lean/statuscomment.mjs +40 -0
  127. package/bin/lean/statuscomment.test.mjs +48 -1
  128. package/bin/lean/validate-catalog.mjs +108 -0
  129. package/bin/lean/validate-catalog.test.mjs +46 -1
  130. package/bin/lean/verify.mjs +3 -2
  131. package/bin/pool/affinity.test.mjs +91 -0
  132. package/bin/pool/agent.mjs +144 -10
  133. package/bin/pool/cache-sweep.mjs +31 -10
  134. package/bin/pool/ci-autoscale.mjs +160 -0
  135. package/bin/pool/cli.mjs +53 -9
  136. package/bin/pool/docker.mjs +3 -0
  137. package/bin/pool/engine-placement.test.mjs +94 -0
  138. package/bin/pool/lane-target.mjs +41 -0
  139. package/bin/pool/lane-tools.mjs +26 -0
  140. package/bin/pool/lane-tools.test.mjs +9 -0
  141. package/bin/pool/mirror-seed.mjs +15 -11
  142. package/bin/pool/router.mjs +88 -32
  143. package/bin/pool/version.mjs +29 -2
  144. package/bin/review-staging.mjs +11 -3
  145. package/bin/runner.mjs +59 -11
  146. package/bin/stats/attempts.mjs +54 -0
  147. package/bin/stats/attempts.test.mjs +30 -0
  148. package/bin/stats/churn.mjs +49 -0
  149. package/bin/stats/churn.test.mjs +31 -0
  150. package/bin/stats/index.mjs +11 -3
  151. package/bin/stats/release.mjs +7 -0
  152. package/bin/stats/release.test.mjs +20 -0
  153. package/bin/stats/scorecard.mjs +187 -0
  154. package/bin/stats/scorecard.test.mjs +89 -0
  155. package/commands/orchestrate.md +21 -18
  156. package/docs/CONFIG.md +41 -0
  157. package/docs/OUTCOME-CODES.md +2 -0
  158. package/docs/STATS.md +17 -0
  159. package/package.json +1 -1
  160. package/pool/image/Dockerfile +14 -2
  161. package/pool/image/manifest.json +25 -0
  162. package/pool/image/mirror.sh +11 -2
  163. package/pool/install/install-agent.ps1 +11 -4
  164. package/scripts/check-devdocs-freshness.sh +1 -1
  165. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  166. package/scripts/ci-local/cli.mjs +1 -1
  167. package/scripts/ci-local/plan.mjs +3 -2
  168. package/scripts/ci-local.test.sh +11 -0
  169. package/scripts/failure-census.mjs +67 -0
  170. package/scripts/review-finalize.sh +5 -5
  171. package/scripts/review-finalize.test.sh +8 -1
  172. package/scripts/verify-phase-trail.sh +11 -0
  173. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -1,51 +1,23 @@
1
1
  // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  /**
4
- * #5751: recurrence routing. A new issue that matches at least `threshold` earlier merged fixes by symptom (subject recall
5
- * or an explicit `Recurs #n` link) AND by area (the fix touched a path the issue names) is a recurrence: the lane runs as a
6
- * design lane (no light lane, a stricter plan prompt, a contract `design` block) instead of adding a further fix.
7
- * Deterministic: zero LLM calls. The engine's inputs are subjectHistory rows (context.mjs) and the merged PRs' file lists.
4
+ * forge.yaml `recurrence.hot_areas` (#5751): areas where one lane at a time may work (branch lock), and `pathsOverlap`.
5
+ * The recurrence design routing (symptom/area detection, design lane, design block requirement) was cut in #6083: it had no
6
+ * measured catch and 15 parks on 11 issues in 25 days.
8
7
  */
9
- import { OUTCOME_CODES as C } from "../engine/outcome-codes.mjs";
10
- import { subjectHistory } from "./context.mjs";
11
-
12
- export const RECURRENCE_DEFAULTS = Object.freeze({ mode: "on", threshold: 2 });
13
- /** At most this many merged rows have their file lists read (one GitHub call each). */
14
- export const MAX_RECURRENCE_ROWS = 6;
15
-
16
8
  const clean = (p) => String(p ?? "").trim().replace(/^\.?\/+/, "").replace(/\/+$/, "");
17
9
  const list = (v) => (Array.isArray(v) ? v : typeof v === "string" ? v.split(",") : []).map((x) => String(x).trim()).filter(Boolean);
18
- const COUNTER_SEP = " -- "; // `pattern -- glob, glob`: the git grep pathspec separator
19
10
 
20
11
  /**
21
- * forge.yaml `recurrence:` (absent: the defaults, mode on). `hot_areas` is a list of {name, paths} or a block map
22
- * {name: "glob, glob"}; `counters` a list of {name, pattern, paths} or a block map {name: "pattern -- glob, glob"}.
23
- * @returns {{mode:"on"|"off", threshold:number, hotAreas:{name:string, paths:string[]}[], counters:{name:string, pattern:string, paths:string[]}[]}}
12
+ * forge.yaml `recurrence:`: `hot_areas` is a list of {name, paths} or a block map {name: "glob, glob"}.
13
+ * @returns {{hotAreas:{name:string, paths:string[]}[]}}
24
14
  */
25
15
  export function parseRecurrenceConfig(raw) {
26
16
  const r = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
27
- const m = String(r.mode ?? "").trim().toLowerCase();
28
- const mode = r.mode === false || m === "off" || m === "false" ? "off" : RECURRENCE_DEFAULTS.mode;
29
- const t = Number(r.threshold);
30
- const threshold = Number.isInteger(t) && t >= 1 ? t : RECURRENCE_DEFAULTS.threshold;
31
17
  const rows = (v) => (Array.isArray(v) ? v : v && typeof v === "object" ? Object.entries(v).map(([name, val]) => ({ name, val })) : []);
32
18
  const hotAreas = rows(r.hot_areas).map((x) => ({ name: String(x?.name ?? "").trim(), paths: list(x?.paths ?? x?.val).map(clean) }))
33
19
  .filter((a) => a.name && a.paths.length);
34
- const counters = rows(r.counters).map((x) => {
35
- if (x?.val !== undefined) {
36
- const s = String(x.val), i = s.lastIndexOf(COUNTER_SEP);
37
- return { name: String(x.name).trim(), pattern: (i >= 0 ? s.slice(0, i) : s).trim(), paths: i >= 0 ? list(s.slice(i + COUNTER_SEP.length)).map(clean) : [] };
38
- }
39
- return { name: String(x?.name ?? "").trim(), pattern: String(x?.pattern ?? "").trim(), paths: list(x?.paths).map(clean) };
40
- }).filter((c) => c.name && c.pattern);
41
- return { mode, threshold, hotAreas, counters };
42
- }
43
-
44
- /** Issue numbers named by `Recurs #n` (also `Recurs: #n`, `Recurs of #n`, `Recurs #n, #m`). */
45
- export function recursLinks(body = "") {
46
- const out = new Set();
47
- for (const m of String(body ?? "").matchAll(/\brecurs(?:\s+of)?\s*:?\s*((?:#\d+[\s,]*(?:and\s+)?)+)/gi)) for (const n of m[1].matchAll(/#(\d+)/g)) out.add(Number(n[1]));
48
- return [...out].filter((n) => Number.isSafeInteger(n) && n > 0);
20
+ return { hotAreas };
49
21
  }
50
22
 
51
23
  /** Two paths overlap when they are equal or one is a directory prefix of the other. */
@@ -53,81 +25,3 @@ export function pathsOverlap(a, b) {
53
25
  const x = clean(a), y = clean(b);
54
26
  return Boolean(x && y) && (x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`));
55
27
  }
56
-
57
- /**
58
- * Count earlier merged fixes on the same symptom and the same area. A subjectHistory row counts when it is a merged PR
59
- * whose files (`mergedPrFiles[number]`) overlap a path the issue names. A `Recurs #n` link is an explicit symptom match:
60
- * it counts when its files overlap or are unknown (the author declared the same area). Rows without overlap never count.
61
- * @returns {{recurs:boolean, count:number, threshold:number, evidence:{number:number, title:string, via:string, paths:string[]}[], reason:string}}
62
- */
63
- export function detectRecurrence({ rows = [], mergedPrFiles = {}, body = "", namedPaths = [], threshold = RECURRENCE_DEFAULTS.threshold } = {}) {
64
- const named = [...new Set((namedPaths ?? []).map(clean).filter(Boolean))];
65
- const filesOf = (n) => (mergedPrFiles instanceof Map ? mergedPrFiles.get(n) : mergedPrFiles?.[n]);
66
- const evidence = [], seen = new Set();
67
- for (const r of rows ?? []) {
68
- const n = Number(r?.number);
69
- if (!Number.isSafeInteger(n) || seen.has(n) || r?.kind !== "PR" || r?.status !== "merged") continue;
70
- const paths = (filesOf(n) ?? []).map(clean).filter((f) => named.some((p) => pathsOverlap(f, p)));
71
- if (!paths.length) continue;
72
- seen.add(n);
73
- evidence.push({ number: n, title: String(r.title ?? ""), via: `subject (${(r.matched ?? []).join(", ")})`, paths: [...new Set(paths)] });
74
- }
75
- for (const n of recursLinks(body)) {
76
- if (seen.has(n)) continue;
77
- const files = filesOf(n);
78
- const paths = Array.isArray(files) ? files.map(clean).filter((f) => named.some((p) => pathsOverlap(f, p))) : null;
79
- if (paths && !paths.length) continue;
80
- seen.add(n);
81
- evidence.push({ number: n, title: "", via: "Recurs link", paths: paths ?? [] });
82
- }
83
- const t = Number.isInteger(threshold) && threshold >= 1 ? threshold : RECURRENCE_DEFAULTS.threshold;
84
- const count = evidence.length, recurs = count >= t;
85
- const reason = recurs
86
- ? `recurrence: ${count} earlier merged fix(es) on the same symptom and area (threshold ${t}): ${evidence.map((e) => `#${e.number}${e.paths.length ? ` (${e.paths.slice(0, 3).join(", ")})` : ""}`).join(", ")}`
87
- : "";
88
- return { recurs, count, threshold: t, evidence, reason };
89
- }
90
-
91
- /**
92
- * The engine-side gather: subjectHistory rows plus one file-list read per merged row (capped). `io`: {gh, git}. Never
93
- * throws: a failed source contributes nothing and lands in `errors`.
94
- */
95
- export async function recurrenceFacts({ io, repo, issue, title = "", body = "", base = null, namedPaths = [], threshold, exclude = [] }) {
96
- const errors = [];
97
- let rows = [];
98
- try { const h = await subjectHistory({ io, repo, issue, title, body, base, exclude }); rows = h.rows ?? []; errors.push(...(h.errors ?? [])); } catch (e) { errors.push(`recurrence: ${String(e?.message ?? e).slice(0, 80)}`); }
99
- const wanted = [...new Set([...rows.filter((r) => r?.kind === "PR" && r?.status === "merged").map((r) => Number(r.number)), ...recursLinks(body)])].slice(0, MAX_RECURRENCE_ROWS);
100
- const mergedPrFiles = {};
101
- if (namedPaths.length) {
102
- for (const n of wanted) {
103
- try {
104
- const out = String(await io.gh(["api", `repos/${repo}/pulls/${n}/files`, "--paginate", "--jq", ".[].filename"]));
105
- mergedPrFiles[n] = out.split("\n").map((x) => x.trim()).filter(Boolean);
106
- } catch { /* not a PR (an issue link) or unreadable: unknown files */ }
107
- }
108
- }
109
- return { ...detectRecurrence({ rows, mergedPrFiles, body, namedPaths, threshold }), errors };
110
- }
111
-
112
- /** The design lane's plan instruction (#5751): why the earlier fixes failed, delete or replace, a measurable outcome. */
113
- export function designLaneNote(detection) {
114
- if (!detection?.recurs) return "";
115
- const ev = detection.evidence.map((e) => `- #${e.number}${e.title ? ` ${e.title}` : ""} [${e.via}]${e.paths.length ? `: ${e.paths.join(", ")}` : ""}`).join("\n");
116
- return `\n\nDESIGN LANE (#5751): this issue recurs. ${detection.count} earlier merged fix(es) hit the same symptom in the same area:\n${ev}\nDo not add another patch on top of them. Read each earlier fix (gh pr view N, git show) as an active input, then put a "design" object in .forge-lean/contract.json:
117
- {"design":{"why_failed":"<why the earlier fixes did not hold, naming them>","disposition":"delete|replace|extend","outcome":{"metric":"<what is measured>","target":"<the value that shows it held>"}}}
118
- Prefer "delete" or "replace" of the earlier fixes; "extend" needs its reason in why_failed. The outcome needs a validate (test, counter or check) that measures it. When the redesign is too big for one lane, decompose it into ordinary lanes with the split-required block.`;
119
- }
120
-
121
- /** #5751: a design lane's contract must carry design {why_failed, disposition delete|replace|extend, outcome {metric, target}}. */
122
- export function designContractFailures(contract, detection) {
123
- if (!detection?.recurs) return [];
124
- const d = contract?.design, problems = [];
125
- const s = (v) => typeof v === "string" && v.trim();
126
- if (!d || typeof d !== "object" || Array.isArray(d)) problems.push("no design block");
127
- else {
128
- if (!s(d.why_failed)) problems.push("design.why_failed is empty");
129
- if (!["delete", "replace", "extend"].includes(String(d.disposition ?? "").trim())) problems.push("design.disposition is not delete, replace or extend");
130
- if (!s(d.outcome?.metric) || !(s(d.outcome?.target) || Number.isFinite(d.outcome?.target))) problems.push("design.outcome needs a metric and a target");
131
- }
132
- return problems.length ? [{ code: C.RECURRENCE_DESIGN_MISSING, kind: "design_missing", detail: `recurring issue (${detection.count} earlier fixes) routed to a design lane: ${problems.join("; ")}` }] : [];
133
- }
@@ -2,98 +2,17 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { parseRecurrenceConfig, detectRecurrence, recursLinks, pathsOverlap, recurrenceFacts, designLaneNote, designContractFailures } from "./recurrence.mjs";
5
+ import { parseRecurrenceConfig, pathsOverlap } from "./recurrence.mjs";
6
6
 
7
- const row = (number, o = {}) => ({ number, kind: "PR", status: "merged", title: `fix leak ${number}`, matched: ["reservation", "leak"], ...o });
8
- const NAMED = ["src/billing/reserve.js"];
9
-
10
- describe("recurrence config (#5751)", () => {
11
- it("defaults to mode on, threshold 2, no hot areas or counters", () => {
12
- assert.deepEqual(parseRecurrenceConfig(undefined), { mode: "on", threshold: 2, hotAreas: [], counters: [] });
13
- });
14
- it("reads mode off, a threshold, list and block-map hot areas and counters", () => {
15
- const c = parseRecurrenceConfig({ mode: "off", threshold: "3", hot_areas: { billing: "src/billing/**, ./src/pay.js" }, counters: [{ name: "flags", pattern: "FLAG_[A-Z]+", paths: "src/**" }] });
16
- assert.equal(c.mode, "off");
17
- assert.equal(c.threshold, 3);
18
- assert.deepEqual(c.hotAreas, [{ name: "billing", paths: ["src/billing/**", "src/pay.js"] }]);
19
- assert.deepEqual(c.counters, [{ name: "flags", pattern: "FLAG_[A-Z]+", paths: ["src/**"] }]);
20
- assert.deepEqual(parseRecurrenceConfig({ counters: { exports: "^export (a|b) -- bin/*.mjs" } }).counters, [{ name: "exports", pattern: "^export (a|b)", paths: ["bin/*.mjs"] }]);
21
- assert.equal(parseRecurrenceConfig({ mode: false, threshold: 0 }).mode, "off");
22
- assert.equal(parseRecurrenceConfig({ threshold: 0 }).threshold, 2, "an invalid threshold keeps the default");
23
- });
24
- });
25
-
26
- describe("recurrence detection (#5751)", () => {
27
- it("two merged fixes on the same symptom touching a named path route to a design lane and record the reason", () => {
28
- const d = detectRecurrence({ rows: [row(10), row(11)], mergedPrFiles: { 10: ["src/billing/reserve.js"], 11: ["src/billing/reserve.js", "README.md"] }, namedPaths: NAMED });
29
- assert.equal(d.recurs, true);
30
- assert.equal(d.count, 2);
31
- assert.deepEqual(d.evidence.map((e) => e.number), [10, 11]);
32
- assert.match(d.reason, /^recurrence: 2 earlier merged fix\(es\) on the same symptom and area \(threshold 2\): #10 \(src\/billing\/reserve\.js\), #11/);
33
- });
34
- it("one matching fix does not route", () => {
35
- const d = detectRecurrence({ rows: [row(10)], mergedPrFiles: { 10: NAMED }, namedPaths: NAMED });
36
- assert.equal(d.recurs, false);
37
- assert.equal(d.count, 1);
38
- assert.equal(d.reason, "");
39
- });
40
- it("symptom matches without path overlap, unmerged rows and issues do not count", () => {
41
- const d = detectRecurrence({ rows: [row(10), row(11), row(12, { status: "closed unmerged" }), row(13, { kind: "issue", status: "completed" })],
42
- mergedPrFiles: { 10: ["src/other.js"], 11: ["docs/x.md"], 12: NAMED, 13: NAMED }, namedPaths: NAMED });
43
- assert.equal(d.recurs, false);
44
- assert.equal(d.count, 0);
45
- assert.equal(detectRecurrence({ rows: [row(10), row(11)], mergedPrFiles: { 10: NAMED, 11: NAMED }, namedPaths: [] }).recurs, false, "an issue naming no path has no area");
46
- });
47
- it("a directory named by the issue overlaps the files under it", () => {
48
- assert.equal(pathsOverlap("src/billing/reserve.js", "src/billing"), true);
49
- assert.equal(pathsOverlap("src/billingx.js", "src/billing"), false);
50
- assert.equal(detectRecurrence({ rows: [row(10), row(11)], mergedPrFiles: { 10: ["src/billing/a.js"], 11: ["src/billing/b.js"] }, namedPaths: ["src/billing/"] }).recurs, true);
51
- });
52
- it("Recurs #n links count: unknown files are the author's declaration, files elsewhere are not", () => {
53
- assert.deepEqual(recursLinks("Recurs #10, #11\nalso recurs of #12 and Recurs: #13"), [10, 11, 12, 13]);
54
- const d = detectRecurrence({ rows: [row(10)], mergedPrFiles: { 10: NAMED }, body: "Recurs #10, #20", namedPaths: NAMED });
55
- assert.equal(d.count, 2, "#10 counts once; #20 (files unknown) counts");
56
- assert.deepEqual(d.evidence.map((e) => [e.number, e.via]), [[10, "subject (reservation, leak)"], [20, "Recurs link"]]);
57
- assert.equal(detectRecurrence({ rows: [row(10)], mergedPrFiles: { 10: NAMED, 21: ["elsewhere.js"] }, body: "Recurs #21", namedPaths: NAMED }).recurs, false);
58
- });
59
- it("the threshold is configurable", () => {
60
- assert.equal(detectRecurrence({ rows: [row(10), row(11)], mergedPrFiles: { 10: NAMED, 11: NAMED }, namedPaths: NAMED, threshold: 3 }).recurs, false);
61
- assert.equal(detectRecurrence({ rows: [row(10)], mergedPrFiles: { 10: NAMED }, namedPaths: NAMED, threshold: 1 }).recurs, true);
62
- });
63
- it("recurrenceFacts reads subject history and each merged PR's files, with no LLM call", async () => {
64
- const calls = [];
65
- const gh = async (a) => {
66
- calls.push(a.join(" "));
67
- if (a.includes("search/issues")) return [10, 11].map((n) => JSON.stringify({ number: n, title: `fix ${n}`, pr: true, merged: true })).join("\n");
68
- const m = /pulls\/(\d+)\/files/.exec(a.join(" "));
69
- if (m) return m[1] === "10" ? "src/billing/reserve.js\n" : "src/billing/reserve.js\nx.md\n";
70
- throw new Error("unexpected");
71
- };
72
- const d = await recurrenceFacts({ io: { gh }, repo: "o/r", issue: 7, title: "reservation leak on 429", body: "See src/billing/reserve.js", namedPaths: NAMED, threshold: 2 });
73
- assert.equal(d.recurs, true);
74
- assert.deepEqual(d.evidence.map((e) => e.number), [11, 10]);
75
- assert.ok(calls.some((c) => c.includes("pulls/10/files")) && calls.some((c) => c.includes("pulls/11/files")));
76
- });
77
- });
78
-
79
- describe("design lane (#5751)", () => {
80
- const det = detectRecurrence({ rows: [row(10), row(11)], mergedPrFiles: { 10: NAMED, 11: NAMED }, namedPaths: NAMED });
81
- it("the plan note names the earlier fixes and asks why they failed, delete or replace, a measurable outcome and allows a split", () => {
82
- const n = designLaneNote(det);
83
- assert.match(n, /DESIGN LANE/);
84
- assert.match(n, /#10 fix leak 10/);
85
- assert.match(n, /why_failed/);
86
- assert.match(n, /delete\|replace\|extend/);
87
- assert.match(n, /"metric"/);
88
- assert.match(n, /split-required/);
89
- assert.equal(designLaneNote({ recurs: false }), "");
90
- assert.equal(designLaneNote(null), "");
91
- });
92
- it("a design lane's contract must carry why_failed, a disposition and a measurable outcome", () => {
93
- assert.equal(designContractFailures({}, det)[0].kind, "design_missing");
94
- assert.match(designContractFailures({}, det)[0].detail, /no design block/);
95
- assert.match(designContractFailures({ design: { why_failed: "", disposition: "replace", outcome: { metric: "m", target: 0 } } }, det)[0].detail, /why_failed is empty/);
96
- assert.deepEqual(designContractFailures({ design: { why_failed: "w", disposition: "delete", outcome: { metric: "m", target: 0 } } }, det), []);
97
- assert.deepEqual(designContractFailures({}, { recurs: false }), [], "an ordinary lane needs no design block");
7
+ describe("recurrence config (#5751; design routing cut in #6083)", () => {
8
+ it("reads list and block-map hot areas, and nothing else", () => {
9
+ assert.deepEqual(parseRecurrenceConfig(undefined), { hotAreas: [] });
10
+ const r = parseRecurrenceConfig({ hot_areas: { api: "src/api/**, src/routes/**" } });
11
+ assert.deepEqual(r.hotAreas, [{ name: "api", paths: ["src/api/**", "src/routes/**"] }]);
12
+ assert.deepEqual(parseRecurrenceConfig({ hot_areas: [{ name: "db", paths: ["db/"] }] }).hotAreas, [{ name: "db", paths: ["db"] }]);
13
+ });
14
+ it("a directory overlaps the files under it", () => {
15
+ assert.ok(pathsOverlap("src/a", "src/a/b.mjs"));
16
+ assert.ok(!pathsOverlap("src/a", "src/ab/b.mjs"));
98
17
  });
99
18
  });
@@ -54,8 +54,8 @@ export function detectSameShaFlip(runs) {
54
54
  }
55
55
 
56
56
  /** One `flakes.json` entry. */
57
- export const flakeEntry = ({ check, test = null, signature = null, kind, sha = null, runIds = [], at, rerun = false }) =>
58
- ({ check, test, signature, signature_hash: signatureHash(check, test, signature), kind, sha, run_ids: runIds, at, ...(rerun ? { rerun: true } : {}) });
57
+ export const flakeEntry = ({ check, test = null, signature = null, kind, sha = null, runIds = [], at, rerun = false, attempt = null, reuseForfeited = false }) =>
58
+ ({ check, test, signature, signature_hash: signatureHash(check, test, signature), kind, sha, run_ids: runIds, at, ...(rerun ? { rerun: true } : {}), ...(attempt != null ? { attempt } : {}), ...(reuseForfeited ? { reuse_forfeited: "deploy test reuse forfeited" } : {}) });
59
59
 
60
60
  /** Append entries to `flakes.json` and the `_active` `flakes` key in one commit. */
61
61
  export async function recordFlakes(lctx, entries, now = Date.now()) {
@@ -67,6 +67,17 @@ export async function recordFlakes(lctx, entries, now = Date.now()) {
67
67
  return r.ok ? { ok: true, recorded: entries.length } : { ok: false, error: r.refused ?? "lost the race recording flakes" };
68
68
  }
69
69
 
70
+ /** #6014: a release-PR CI run is rerun at most this many times (Actions run_attempt 1 is the first run, so attempt 3 is the last allowed). */
71
+ export const RERUN_ATTEMPT_CAP = 2;
72
+
73
+ /** @param {{attempt?: number|null, cap?: number}} p @returns {{allow: boolean, why: string}} refuse once `attempt - 1` reruns have already happened. */
74
+ export function attemptGuard({ attempt, cap = RERUN_ATTEMPT_CAP }) {
75
+ const n = Number(attempt);
76
+ if (!Number.isFinite(n) || n < 1) return { allow: true, why: "attempt unknown" };
77
+ if (n - 1 >= cap) return { allow: false, why: `run is on attempt ${n}: already rerun ${n - 1} times (cap ${cap}); needs a recorded classification and a filed issue for the failing job` };
78
+ return { allow: true, why: `attempt ${n}, ${n - 1} of ${cap} reruns used` };
79
+ }
80
+
70
81
  /**
71
82
  * Which failed jobs to `rerun --failed`: infra class only, once per job (`done` = keys of jobs already rerun), and only while the
72
83
  * minutes already spent stay inside `ci.rerun_budget_min`. Every job gets a decision, so a skipped rerun is never silent.
@@ -76,6 +87,7 @@ export function planRerun({ jobs, done = [], spentMin = 0, budgetMin }) {
76
87
  const seen = new Set(done);
77
88
  let spent = spentMin;
78
89
  return jobs.map((j) => {
90
+ if (j.attempt != null) { const g = attemptGuard({ attempt: j.attempt }); if (!g.allow) return { ...j, rerun: false, capped: true, why: g.why }; }
79
91
  if (j.class !== "infra") return { ...j, rerun: false, why: "not an infra flake" };
80
92
  if (seen.has(j.key)) return { ...j, rerun: false, why: "already rerun once" };
81
93
  const cost = j.minutes ?? 0;
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { parseFlakeConfig, classifyFailure, detectSameShaFlip, flakeEntry, planRerun, repeatedFlakes, fileFlakeIssue, canQuarantine, activeQuarantines, shouldWriteMarker, isUnskippable, recordFlakes, UNSKIPPABLE_CLASSES } from "./release-flakes.mjs";
5
+ import { parseFlakeConfig, classifyFailure, detectSameShaFlip, flakeEntry, planRerun, attemptGuard, RERUN_ATTEMPT_CAP, repeatedFlakes, fileFlakeIssue, canQuarantine, activeQuarantines, shouldWriteMarker, isUnskippable, recordFlakes, UNSKIPPABLE_CLASSES } from "./release-flakes.mjs";
6
6
  import { rerunInfraFlakes } from "./release.mjs";
7
7
 
8
8
  const NOW = Date.parse("2026-11-12T00:00:00Z"), DAY = 86_400_000;
@@ -129,3 +129,19 @@ describe("quarantineReport (#5710)", async () => {
129
129
  assert.deepEqual(quarantineReport(all, { mode: "off" }, now), []);
130
130
  });
131
131
  });
132
+
133
+ import { test as t6014 } from "node:test";
134
+ import assert6014 from "node:assert/strict";
135
+ t6014("#6014: attempt cap refuses a third rerun, records attempt and forfeited reuse", () => {
136
+ assert6014.equal(RERUN_ATTEMPT_CAP, 2);
137
+ assert6014.equal(attemptGuard({ attempt: 2 }).allow, true);
138
+ assert6014.equal(attemptGuard({ attempt: 3 }).allow, false);
139
+ assert6014.equal(attemptGuard({ attempt: 5 }).allow, false);
140
+ assert6014.equal(attemptGuard({ attempt: null }).allow, true);
141
+ const [a, b] = planRerun({ jobs: [{ key: "x", class: "infra", attempt: 3 }, { key: "y", class: "infra", attempt: 2 }], budgetMin: 30 });
142
+ assert6014.equal(a.rerun, false); assert6014.match(a.why, /attempt 3/);
143
+ assert6014.equal(b.rerun, true);
144
+ const e = flakeEntry({ check: "c", kind: "infra", at: "t", rerun: true, attempt: 2, reuseForfeited: true });
145
+ assert6014.equal(e.attempt, 2); assert6014.match(e.reuse_forfeited, /reuse forfeited/);
146
+ assert6014.equal("attempt" in flakeEntry({ check: "c", kind: "infra", at: "t" }), false);
147
+ });
@@ -221,6 +221,24 @@ export async function recordTrain(ctx, rec, now = Date.now()) {
221
221
  return updateActive(ctx, ["train"], (active) => ({ patch: { train: { ...(active.train ?? {}), [rec.release ?? "-"]: { ...rec, lane: "train", rollout_invalidated: true, at } } }, control: { at, verb: "train", lane: "train", release: rec.release ?? null, state: rec.state ?? null, units: rec.units?.length ?? 0, rollout_invalidated: true } }));
222
222
  }
223
223
 
224
+ const CAUSES = ["regression", "flake", "runner"];
225
+ /** #6013: append one snapshot round `{n, pr, head, outcome, cause, startedAt, endedAt}` to `state.rounds` (n is assigned, cause normalised). */
226
+ export function recordReleaseRound(state, r) {
227
+ state.rounds ??= [];
228
+ const round = { n: state.rounds.length + 1, pr: r.pr ?? null, head: r.head ?? null, outcome: r.outcome ?? null, cause: CAUSES.includes(r.cause) ? r.cause : null, startedAt: r.startedAt ?? null, endedAt: r.endedAt ?? null };
229
+ state.rounds.push(round);
230
+ return round;
231
+ }
232
+
233
+ /** `{rounds, snapshots, wallMin, causes}` derived from `state.rounds`; wall time is first start -> last end. */
234
+ export function roundStats(rounds = []) {
235
+ const list = Array.isArray(rounds) ? rounds : [];
236
+ const t = list.flatMap((r) => [Date.parse(r.startedAt), Date.parse(r.endedAt)]).filter(Number.isFinite);
237
+ const causes = { regression: 0, flake: 0, runner: 0 };
238
+ for (const r of list) if (r.cause in causes) causes[r.cause]++;
239
+ return { rounds: list, snapshots: list.length, wallMin: t.length ? Math.round((Math.max(...t) - Math.min(...t)) / 600) / 100 : 0, causes };
240
+ }
241
+
224
242
  /**
225
243
  * #5718: release state for `forgedock stats --release-ledger`. One record per managed release started at or after `sinceMs`:
226
244
  * `{id, pr, startedAt, status, live, deployAttempts}` (read-only; a release without a readable state is skipped). The id
@@ -237,7 +255,7 @@ export async function releaseRecords(ctx, { sinceMs = 0 } = {}) {
237
255
  const pr = s.steps?.["release-pr"]?.result?.pr ?? s.pr ?? null;
238
256
  const phase = String(s.deploy?.phase ?? "");
239
257
  out.push({ id, pr: pr == null ? null : Number(pr), startedAt: s.startedAt ?? null, status: s.status ?? null,
240
- live: ["live", "done"].includes(String(s.status ?? "").toLowerCase()) || phase.startsWith("LIVE"), deployAttempts: Number(s.deploy?.attempts) || 0 });
258
+ live: ["live", "done"].includes(String(s.status ?? "").toLowerCase()) || phase.startsWith("LIVE"), deployAttempts: Number(s.deploy?.attempts) || 0, ...(Array.isArray(s.rounds) ? roundStats(redactDeep(s.rounds)) : {}) });
241
259
  }
242
260
  return out;
243
261
  }
@@ -256,3 +256,26 @@ describe("recordSync (#5566)", async () => {
256
256
  assert.equal(line.milestones, 1);
257
257
  });
258
258
  });
259
+
260
+ describe("release ledger rounds (#6013)", () => {
261
+ it("records rounds with count, wall time and cause, redacted on write and read back", async () => {
262
+ const { recordReleaseRound, roundStats } = await import("./release-ledger.mjs");
263
+ const gh = fakeGh(), ctx = ctxOf(gh);
264
+ const state = { status: "running" };
265
+ recordReleaseRound(state, { pr: 9, head: "a1", outcome: "fail", cause: "regression", startedAt: "2026-11-01T10:00:00Z", endedAt: "2026-11-01T10:30:00Z" });
266
+ recordReleaseRound(state, { pr: 10, head: "b2", outcome: "pass", cause: "bogus", startedAt: "2026-11-01T11:00:00Z", endedAt: "2026-11-01T11:45:00Z" });
267
+ assert.deepEqual(state.rounds.map((r) => r.n), [1, 2]);
268
+ assert.equal(state.rounds[1].cause, null, "unknown cause is not recorded");
269
+ const s = roundStats(state.rounds);
270
+ assert.equal(s.snapshots, 2);
271
+ assert.equal(s.wallMin, 105);
272
+ assert.deepEqual(s.causes, { regression: 1, flake: 0, runner: 0 });
273
+ assert.equal(roundStats(undefined).snapshots, 0);
274
+ state.rounds[0].head = "ghp_" + "a".repeat(36);
275
+ await createReleaseLedger(ctx, ID, state);
276
+ const back = (await readLedger(ctx, ID)).state;
277
+ assert.equal(back.rounds.length, 2);
278
+ assert.ok(!JSON.stringify(back).includes("ghp_aaaa"), "secrets are redacted");
279
+ assert.equal(roundStats(back.rounds).snapshots, 2);
280
+ });
281
+ });
@@ -7,6 +7,7 @@
7
7
  * retries. With no command set every function here is a no-op. No model call. Effects go through `ctx.io`.
8
8
  */
9
9
  import { fileBlocker, tail } from "./release-rehearsal.mjs";
10
+ import { classifyFailure } from "./release-flakes.mjs";
10
11
  import { fenced } from "./release-fence.mjs";
11
12
 
12
13
  export const PREFLIGHT_TIMEOUT_MS = 20 * 60_000;
@@ -62,6 +63,33 @@ export async function hostPreflightStep(ctx) {
62
63
  return !r.ok && r.blocking ? stopOf(r) : r;
63
64
  }
64
65
 
66
+ const BAD = new Set(["failure", "timed_out", "cancelled", "action_required", "startup_failure"]);
67
+
68
+ /**
69
+ * Staging-health gate (#6013): before a snapshot is cut, every check-run of the staging head must be finished and green. Names ALL
70
+ * failed checks of the run (class: regression|runner via classifyFailure; a flake is a failure a rerun cleared, recorded by the
71
+ * round ledger) and pending ones (staging is behind). `config.allowRedStaging` proceeds with a recorded warning. No model call.
72
+ * Failed checks that the staging branch protection does not require are reported as `parityGap` (lane-check parity).
73
+ * @returns {{ok: true, head, warning?: string, failed?: object[]}|{refused: string, head, failed: object[], pending: string[]}}
74
+ */
75
+ export async function stagingHealthStep(ctx) {
76
+ const { io, repo, staging, config } = ctx;
77
+ const head = String(await io.gh(["api", `repos/${repo}/commits/${staging}`, "--jq", ".sha"])).trim();
78
+ const runs = await io.gh(["api", `repos/${repo}/commits/${head}/check-runs?per_page=100`, "--jq", "[.check_runs[]|{name,status,conclusion,text:((.output.title//\"\")+\" \"+(.output.summary//\"\"))}]"]).then((t) => { try { const v = json(t); return Array.isArray(v) ? v.filter((c) => c && typeof c.status === "string") : []; } catch { return []; } }, () => []);
79
+ const failed = (runs ?? []).filter((c) => c.status === "completed" && BAD.has(c.conclusion))
80
+ .map((c) => ({ name: c.name, conclusion: c.conclusion, cause: classifyFailure(c.text).class === "infra" ? "runner" : "regression" }))
81
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
82
+ const pending = (runs ?? []).filter((c) => c.status !== "completed").map((c) => c.name).sort();
83
+ if (!failed.length && !pending.length) return { ok: true, head };
84
+ // Lane-check parity (R3): a check red on staging that lane merges do not require is a gap the lane gate let through.
85
+ const req = await io.gh(["api", `repos/${repo}/branches/${staging}/protection/required_status_checks`, "--jq", "[.contexts[]?, .checks[]?.context]"]).then((t) => { try { const v = json(t); return Array.isArray(v) ? v : null; } catch { return null; } }, () => null);
86
+ const parityGap = req ? failed.map((f) => f.name).filter((n) => !req.includes(n)) : [];
87
+ const what = [failed.length ? `failed: ${failed.map((f) => `${f.name} (${f.cause})`).join(", ")}` : "", pending.length ? `pending: ${pending.join(", ")}` : ""].filter(Boolean).join("; ");
88
+ const gap = parityGap.length ? ` lane-check parity gap (not required for lane merges): ${parityGap.join(", ")}` : "";
89
+ if (config?.allowRedStaging) return { ok: true, head, failed, parityGap, warning: `staging ${staging}@${head} is not green (${what}); release.allow_red_staging is set` };
90
+ return { refused: `staging ${staging}@${head} is not green (${what}); fix every failure against ${staging} in one batch, then resume.${gap}`, head, failed, pending, parityGap };
91
+ }
92
+
65
93
  /** Step after `fixes`: preflight on the final head, then mark the draft release PR ready so Actions CI runs once on it. */
66
94
  export async function markReadyStep(ctx) {
67
95
  if (!ctx.config.preflight) return { skipped: true };
@@ -4,7 +4,7 @@ import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
5
  import { tmpDir } from "../tests/_tmp.mjs";
6
6
  import { runRelease, withStubs, readReleaseConfig, newReleaseId } from "./release.mjs";
7
- import { parsePreflightConfig, markReadyStep, coStartCi } from "./release-preflight.mjs";
7
+ import { parsePreflightConfig, markReadyStep, coStartCi, stagingHealthStep } from "./release-preflight.mjs";
8
8
  import { fixStep } from "./release-review.mjs";
9
9
 
10
10
  const DISK = [{ mount: "/", type: "ext4" }];
@@ -128,3 +128,44 @@ describe("co-start CI (#5567)", () => {
128
128
  assert.ok(calls.some((c) => c.startsWith("pr ready")) && calls.some((c) => c.startsWith("workflow run full.yml")));
129
129
  });
130
130
  });
131
+
132
+ describe("staging-health gate (#6013)", () => {
133
+ const checks = (list) => ({ ...fakeIo(), gh: async (a) => (a[1].includes("/check-runs") ? JSON.stringify(list) : `${HEAD}\n`) });
134
+ const ctxOf = (io, config = {}) => ({ io, repo: REPO, staging: "staging", config });
135
+ const red = [
136
+ { name: "black", status: "completed", conclusion: "failure", text: "would reformat" },
137
+ { name: "suite", status: "completed", conclusion: "failure", text: "ECONNRESET while pulling image" },
138
+ { name: "lint", status: "completed", conclusion: "success", text: "" },
139
+ ];
140
+
141
+ it("refuses a red head naming every failed check with its cause", async () => {
142
+ const r = await stagingHealthStep(ctxOf(checks(red)));
143
+ assert.match(r.refused, /black \(regression\)/);
144
+ assert.match(r.refused, /suite \(runner\)/);
145
+ assert.equal(r.failed.length, 2);
146
+ });
147
+ it("R3: names failed checks that lane merges do not require as a parity gap", async () => {
148
+ const io = { ...fakeIo(), gh: async (a) => (a[1].includes("/check-runs") ? JSON.stringify(red) : a[1].includes("required_status_checks") ? JSON.stringify(["suite"]) : `${HEAD}\n`) };
149
+ const r = await stagingHealthStep(ctxOf(io));
150
+ assert.deepEqual(r.parityGap, ["black"]);
151
+ assert.match(r.refused, /parity gap.*black/);
152
+ });
153
+ it("proceeds on green; refuses pending; override proceeds with a warning", async () => {
154
+ assert.equal((await stagingHealthStep(ctxOf(checks([{ name: "a", status: "completed", conclusion: "success" }])))).ok, true);
155
+ const pend = await stagingHealthStep(ctxOf(checks([{ name: "slow", status: "in_progress", conclusion: null }])));
156
+ assert.match(pend.refused, /pending: slow/);
157
+ const o = await stagingHealthStep(ctxOf(checks(red), { allowRedStaging: true }));
158
+ assert.equal(o.ok, true);
159
+ assert.match(o.warning, /allow_red_staging/);
160
+ assert.equal(readReleaseConfig("release:\n allow_red_staging: true\n").allowRedStaging, true);
161
+ });
162
+ it("N known failures resolve in 2 rounds: gate refuses once, then the cut proceeds", async () => {
163
+ let fixed = false, cuts = 0;
164
+ const io = { ...fakeIo(), gh: async (a) => (a[1].includes("/check-runs") ? JSON.stringify(fixed ? [] : red) : `${HEAD}\n`) };
165
+ const one = await stagingHealthStep(ctxOf(io));
166
+ assert.equal(one.failed.length, 2); // round 1: all failures named together, no snapshot cut
167
+ fixed = true; // one batched fix merged
168
+ if ((await stagingHealthStep(ctxOf(io))).ok) cuts++; // round 2
169
+ assert.equal(cuts, 1);
170
+ });
171
+ });
@@ -10,10 +10,11 @@
10
10
  */
11
11
  import { execFileSync, spawn } from "node:child_process";
12
12
  import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, rmSync } from "node:fs";
13
- import { tmpdir, homedir } from "node:os";
13
+ import { tmpdir, homedir, cpus } from "node:os";
14
14
  import { delimiter, join } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import { runHostPreflight } from "./release-preflight.mjs";
17
+ import { lowerPriority } from "./hostload.mjs";
17
18
  import { reviewStagingJson, reviewStagingIo, CI_EXCLUDED_CHECKS } from "../review-staging.mjs";
18
19
  import { pickFixes, recut, revertLast } from "./release-snapshot.mjs";
19
20
  import { parseFixConfig, collectFindings, blockingOf, compileBrief, roundsAt, recordRound, secondPush, secondPushOf, holdForOwner, jobsToRerun, inputHash, deferredOf } from "./release-fixloop.mjs";
@@ -106,6 +107,30 @@ export function resolveSkillName(name, { configDir, read = (p) => readFileSync(p
106
107
  try { return /"forgedock(@[^"]*)?"\s*:/.test(read(join(configDir, "plugins", "installed_plugins.json"))) ? `forgedock:${name}` : name; } catch { return name; }
107
108
  }
108
109
 
110
+ /** #6098: default reviewer fan-out on this host: max(2, cores / 2). */
111
+ export const defaultReviewParallel = (cores = cpus().length || 1) => Math.max(2, Math.floor(cores / 2));
112
+ /** #6098: forge.yaml `review.max_parallel` (a positive integer) read from raw text; null when absent or invalid. */
113
+ export function reviewMaxParallel(raw) {
114
+ const lines = String(raw ?? "").split("\n");
115
+ const at = lines.findIndex((l) => /^review:\s*(#.*)?$/.test(l));
116
+ if (at < 0) return null;
117
+ for (let i = at + 1; i < lines.length; i++) {
118
+ const l = lines[i];
119
+ if (!l.trim() || /^\s*#/.test(l)) continue;
120
+ if (/^\S/.test(l)) break;
121
+ const m = /^\s+max_parallel:\s*["']?(\d+)["']?\s*(#.*)?$/.exec(l);
122
+ if (m) return Number(m[1]) > 0 ? Number(m[1]) : null;
123
+ }
124
+ return null;
125
+ }
126
+ /** #6098: run `fn` over `items` with at most `cap` in flight; the rest queue. Results keep the input order; a rejection rejects the batch. */
127
+ export async function mapLimit(items, cap, fn) {
128
+ const n = Math.max(1, Math.floor(Number(cap)) || 1), out = new Array(items.length);
129
+ let next = 0;
130
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => { for (;;) { const i = next++; if (i >= items.length) return; out[i] = await fn(items[i], i); } }));
131
+ return out;
132
+ }
133
+
109
134
  /** One review round at the current head: dispatch, test gate, head check, finalize. @returns {{moved: string}|{fail}|{ok}} */
110
135
  async function reviewRound({ seam, pr, def, delta }) {
111
136
  const pre = await seam.pre({ pr, delta });
@@ -122,7 +147,8 @@ async function reviewRound({ seam, pr, def, delta }) {
122
147
  const send = (domain, note = "") => seam.runAgent({ role: `release-review-${domain}`, issue: pr, prompt: note ? `${prompts.get(domain)}\n\n${note}` : prompts.get(domain) });
123
148
  const failures = new Map();
124
149
  const attempt = (domain, note) => send(domain, note).catch((e) => { failures.set(domain, sessionFailure(e)); return null; });
125
- await Promise.all(agents.map((a) => attempt(a.domain)));
150
+ const cap = Math.max(1, Math.floor(Number(seam.maxParallel?.()) || 0)) || defaultReviewParallel(); // #6098: queue beyond the cap, never every reviewer at once
151
+ await mapLimit(agents, cap, (a) => attempt(a.domain));
126
152
  // #5516: the missing-config guard of commands/test-gate.md is deterministic, so no session decides it; otherwise the gate
127
153
  // session gets a full tool set (Skill, Task, Bash) and the resolved skill name, never a bare `/test-gate`.
128
154
  const plan = await seam.testGatePlan();
@@ -138,7 +164,7 @@ async function reviewRound({ seam, pr, def, delta }) {
138
164
  const missing = missingReviewers(fin.lines).filter((d) => prompts.has(d));
139
165
  if (!missing.length) return { fail: `finalize stopped (exit ${fin.code}): ${(fin.lines ?? []).slice(-2).join(" | ").slice(0, 300)}${failureNote(failures)}` };
140
166
  // once: the same brief with the note the spec prescribes; a second miss is a degraded panel
141
- 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.")));
167
+ await mapLimit(missing, cap, (d) => attempt(d, "structured findings block required: post your findings comment again, ending with the REVIEW-FINDINGS-START/END block."));
142
168
  fin = await seam.finalize({ pr, testGateOutput: gateFile });
143
169
  if (fin.code !== 0 || !fin.data) {
144
170
  if (headMoved(fin.lines)) return { moved: m.headSha };
@@ -260,7 +286,10 @@ export async function fixStep(ctx) {
260
286
  continue;
261
287
  }
262
288
  // #5779: with blocking findings in hand the fix round starts now (completed runs go into the brief); else the wait is bounded
263
- const jobs = r.ciFailing > 0 ? await seam.failedJobs({ pr: r.pr, head: r.head, wait: !r.blocking?.length }) : [];
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 });
264
293
  const rec = collectFindings({ head: r.head, jobs, findings: r.items ?? [], guards: r.guards ?? [] });
265
294
  const b = blockingOf(rec);
266
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`);
@@ -310,6 +339,8 @@ export async function fixStep(ctx) {
310
339
  const seamOf = (ctx) => ctx.io.review ?? (ctx.seam ??= realSeam(ctx));
311
340
 
312
341
  /** Real effects of the review steps: the review-staging library, the engine runner, the filing scripts, gh and a lane process. */
342
+ /** #6098: CPU niceness of reviewer processes (ionice idle class is applied alongside). */
343
+ export const REVIEW_NICE = 19;
313
344
  export function realSeam({ repo, def, env = process.env, laneStrip = [], cwd = process.cwd(), makeRunner = null, gh: ghIn = null, io = null, spawn: spawnIn = spawn }) {
314
345
  const sleep = io?.sleep ?? ((ms) => new Promise((res) => setTimeout(res, ms))), now = io?.now ?? (() => Date.now());
315
346
  const say = io?.print ?? ((m) => process.stderr.write(`${m}\n`));
@@ -334,10 +365,14 @@ export function realSeam({ repo, def, env = process.env, laneStrip = [], cwd = p
334
365
  readFile: (p) => readFileSync(p, "utf8"),
335
366
  markLaunched: (file, domains, head) => { appendFileSync(file, domains.map((d) => `${d}\n`).join("")); writeFileSync(`${file}.head`, `${head}\n`); },
336
367
  saveTestGate: (pr, text) => { mkdirSync(sd, { recursive: true }); const f = join(sd, `${pr}_test_gate_output.txt`); writeFileSync(f, text); return f; },
368
+ maxParallel: () => { // #6098
369
+ try { return reviewMaxParallel(readFileSync(env.FORGE_CONFIG || join(cwd, "forge.yaml"), "utf8")) ?? defaultReviewParallel(); } catch { return defaultReviewParallel(); }
370
+ },
337
371
  runAgent: async ({ role, issue, prompt, fullSession = false }) => {
338
372
  runner ??= makeRunner ? makeRunner() : (await import("./effects.mjs")).makeLeanRunner();
339
373
  // not readOnly: each reviewer posts its own PR comment; the test gate (#5516) needs Skill/Task, so a full session
340
- return runner({ role, issue, cwd, env: pinnedEnv(), prompt, fullSession, system: "You are an isolated reviewer of one release PR. Do only what the prompt asks.", maxMs: REVIEW_MS, idleMs: 10 * 60_000 });
374
+ return runner({ role, issue, cwd, env: pinnedEnv(), prompt, fullSession, system: "You are an isolated reviewer of one release PR. Do only what the prompt asks.", maxMs: REVIEW_MS, idleMs: 10 * 60_000,
375
+ onSpawn: (child) => lowerPriority(child?.pid, { level: REVIEW_NICE }) }); // #6098: reviewers run at nice 19 / ionice idle on the orchestrator host
341
376
  },
342
377
  testGatePlan: async () => {
343
378
  let raw = null;