forgedock 1.66.0 → 1.67.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 (72) hide show
  1. package/bin/config-schema.mjs +2 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +96 -17
  4. package/bin/forgedock.mjs +7 -0
  5. package/bin/help-text.mjs +3 -3
  6. package/bin/introspect-schedule.mjs +98 -0
  7. package/bin/introspect-schedule.test.mjs +67 -0
  8. package/bin/lean/advisory.test.mjs +49 -0
  9. package/bin/lean/amendment-schema.mjs +31 -0
  10. package/bin/lean/attempts.mjs +159 -0
  11. package/bin/lean/attempts.test.mjs +127 -0
  12. package/bin/lean/basered.mjs +55 -0
  13. package/bin/lean/basered.test.mjs +68 -1
  14. package/bin/lean/batch-health.mjs +3 -0
  15. package/bin/lean/batch-health.test.mjs +16 -0
  16. package/bin/lean/batch.mjs +45 -0
  17. package/bin/lean/batch.test.mjs +54 -3
  18. package/bin/lean/capwait.mjs +14 -3
  19. package/bin/lean/capwait.test.mjs +20 -0
  20. package/bin/lean/clear-breaker.mjs +14 -0
  21. package/bin/lean/commentstate.mjs +41 -0
  22. package/bin/lean/commentstate.test.mjs +32 -0
  23. package/bin/lean/concurrency.mjs +89 -0
  24. package/bin/lean/concurrency.test.mjs +113 -0
  25. package/bin/lean/conformance.e2e.test.mjs +4 -2
  26. package/bin/lean/conformance.mjs +35 -3
  27. package/bin/lean/conformance.test.mjs +52 -0
  28. package/bin/lean/efficiency.mjs +162 -0
  29. package/bin/lean/efficiency.test.mjs +79 -0
  30. package/bin/lean/execution.mjs +31 -13
  31. package/bin/lean/execution.test.mjs +46 -0
  32. package/bin/lean/failure-stop.mjs +46 -0
  33. package/bin/lean/failure-stop.test.mjs +45 -0
  34. package/bin/lean/fixtures/capacity-storm.json +609 -0
  35. package/bin/lean/lean.mjs +123 -24
  36. package/bin/lean/lean.test.mjs +137 -46
  37. package/bin/lean/liveness.mjs +37 -0
  38. package/bin/lean/liveness.test.mjs +33 -0
  39. package/bin/lean/orchestrate-attempts.test.mjs +74 -0
  40. package/bin/lean/orchestrate-pause.test.mjs +23 -0
  41. package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
  42. package/bin/lean/orchestrate.mjs +170 -26
  43. package/bin/lean/phaseledger.mjs +6 -0
  44. package/bin/lean/phaseledger.test.mjs +13 -1
  45. package/bin/lean/prompts.mjs +6 -10
  46. package/bin/lean/reconcile.mjs +90 -0
  47. package/bin/lean/recurrence.mjs +38 -2
  48. package/bin/lean/recurrence.test.mjs +56 -1
  49. package/bin/lean/sandbox-remote.mjs +33 -2
  50. package/bin/lean/sched.mjs +19 -0
  51. package/bin/lean/sched.test.mjs +11 -1
  52. package/bin/lean/schedd-health.mjs +4 -4
  53. package/bin/lean/schedd-health.test.mjs +8 -4
  54. package/bin/lean/schedd.mjs +34 -2
  55. package/bin/lean/schedd.test.mjs +55 -2
  56. package/bin/lean/slo.mjs +126 -0
  57. package/bin/lean/slo.test.mjs +112 -0
  58. package/bin/lean/statuscomment.mjs +37 -0
  59. package/bin/lean/statuscomment.test.mjs +48 -1
  60. package/bin/lean/verify.mjs +2 -1
  61. package/bin/pool/agent.mjs +2 -2
  62. package/bin/pool/cli.mjs +16 -1
  63. package/bin/pool/lane-tools.mjs +21 -0
  64. package/bin/stats/attempts.mjs +54 -0
  65. package/bin/stats/attempts.test.mjs +30 -0
  66. package/bin/stats/churn.mjs +49 -0
  67. package/bin/stats/churn.test.mjs +31 -0
  68. package/bin/stats/index.mjs +11 -3
  69. package/commands/orchestrate.md +21 -18
  70. package/docs/OUTCOME-CODES.md +1 -0
  71. package/package.json +1 -1
  72. package/scripts/check-devdocs-freshness.sh +1 -1
@@ -0,0 +1,126 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Batch efficiency SLOs (#5987): `orchestrate.slo.*` thresholds with defaults, breach evaluation over an efficiency.json ledger
5
+ * (efficiency.mjs), and the filer that turns a breach into one rolling `engine-gap` issue per signature `slo:<code>:<repo>`.
6
+ * Filing is opt-in (`orchestrate.slo.file_issues: true` enables; default off, nothing is posted off-host); breaches are always recorded in efficiency.json.
7
+ * The filer takes an injected `gh(args) -> stdout`, appends a counter comment on a re-breach at most once per 6 h, and closes the
8
+ * issue after 24 h green. Its state lives in efficiency.json (`slo.sigs`), so a daemon restart neither re-files nor re-comments.
9
+ */
10
+ export const DEFAULT_SLO = Object.freeze({ concurrencyMin: 0.6, concurrencyMinutes: 30, repeatMax: 3, attemptsMax: 2, commentsMax: 20, interventionsMax: 6,
11
+ phaseRatioMax: 1.5, capacityRefusalsMax: 20, idleShareMax: 0.2, fileIssues: false, repo: "RapierCraftStudios/ForgeDock", label: "engine-gap" });
12
+ export const SLO_UPDATE_MS = 6 * 3_600_000;
13
+ export const SLO_CLOSE_GREEN_MS = 24 * 3_600_000;
14
+ const SNAKE = { concurrencyMin: "concurrency_min", concurrencyMinutes: "concurrency_minutes", repeatMax: "repeat_max", attemptsMax: "attempts_max", commentsMax: "comments_max",
15
+ interventionsMax: "interventions_max", phaseRatioMax: "phase_ratio_max", capacityRefusalsMax: "capacity_refusals_max", idleShareMax: "idle_share_max" };
16
+
17
+ /** forge.yaml (parsed) -> SLO config; the parser may nest (`orchestrate.slo.x`) or flatten (`orchestrate.x`). Bad values fall back. */
18
+ export function parseSloConfig(yaml) {
19
+ const o = yaml?.orchestrate && typeof yaml.orchestrate === "object" ? yaml.orchestrate : {};
20
+ const s = { ...o, ...(o.slo && typeof o.slo === "object" ? o.slo : {}) };
21
+ const out = { ...DEFAULT_SLO };
22
+ for (const [k, snake] of Object.entries(SNAKE)) { const v = s[snake] ?? s[`slo_${snake}`]; if (v !== undefined && String(v).trim() !== "" && Number.isFinite(Number(v)) && Number(v) >= 0) out[k] = Number(v); }
23
+ const f = s.file_issues ?? s.slo_file_issues;
24
+ out.fileIssues = f !== undefined && String(f).trim().toLowerCase() === "true";
25
+ const repo = String(s.repo ?? s.slo_repo ?? "").trim();
26
+ if (/^[\w.-]+\/[\w.-]+$/.test(repo)) out.repo = repo;
27
+ return out;
28
+ }
29
+
30
+ /** `[{code, sig, detail, issues, cause}]` for the ledger's current breaches. Pure. */
31
+ export function evaluateSlo(eff, cfg = DEFAULT_SLO, { repo = eff?.repo ?? "unknown" } = {}) {
32
+ if (!eff) return [];
33
+ const out = [], add = (code, detail, issues = [], cause = "") => out.push({ code, sig: `slo:${code}:${repo}`, detail, issues, cause });
34
+ const c = eff.concurrency ?? {};
35
+ if (c.ready > 0 && c.lowSinceMin >= cfg.concurrencyMinutes) add("concurrency", `achieved/ceiling ${c.achieved}/${c.ceiling} below ${cfg.concurrencyMin} for ${c.lowSinceMin} min with ${c.ready} ready`, [], `limiter ${(eff.limiters ?? []).join(", ") || "unknown"}`);
36
+ for (const r of eff.repeats ?? []) if (r.count >= cfg.repeatMax) add("repeat", `signature "${r.signature}" repeated ${r.count}x`, r.issues, "the same failure is retried without a change");
37
+ if (eff.attemptsPerMerged != null && eff.attemptsPerMerged > cfg.attemptsMax) add("attempts", `${eff.attemptsPerMerged} attempts per merged issue (max ${cfg.attemptsMax}, 24 h)`, [], "retry loop");
38
+ const cm = eff.commentsPerIssue ?? {};
39
+ if (cm.max > cfg.commentsMax) add("comments", `${cm.max} engine comments on one issue (max ${cfg.commentsMax})`, (cm.issues ?? []).filter((i) => i.comments > cfg.commentsMax).map((i) => i.issue), "comment bloat");
40
+ if (eff.interventionsPerDay > cfg.interventionsMax) add("interventions", `${eff.interventionsPerDay} operator interventions in 24 h (max ${cfg.interventionsMax})`, [], "the batch needs hand-holding");
41
+ const slow = Object.entries(eff.phases ?? {}).filter(([, v]) => v.ratio != null && v.ratio > cfg.phaseRatioMax);
42
+ if (slow.length) add("phase", slow.map(([id, v]) => `${id} p90 ${v.ratio}x baseline`).join("; "), [], `phase regression: ${slow.map(([id]) => id).join(", ")}`);
43
+ if (eff.capacityRefusalsPerHour > cfg.capacityRefusalsMax) add("capacity", `${eff.capacityRefusalsPerHour} capacity refusals in the last hour (max ${cfg.capacityRefusalsMax})`, [], "sandbox capacity");
44
+ for (const [cause, share] of Object.entries(eff.idle?.share ?? {})) if (cause !== "no-ready" && share > cfg.idleShareMax) add(`idle-${cause}`, `${Math.round(share * 100)}% of slot time idle for ${cause} (max ${Math.round(cfg.idleShareMax * 100)}%)`, [], `idle cause ${cause}`);
45
+ return out;
46
+ }
47
+
48
+ const body = (eff, b, { count = 1 } = {}) => [
49
+ `<!-- forge-slo: ${b.sig} -->`, `**SLO breach \`${b.code}\`** (batch \`${eff.batch}\`, repo \`${eff.repo}\`), occurrence ${count}`, "",
50
+ "| field | value |", "| --- | --- |", `| evidence | ${b.detail.replace(/\|/g, "/")} |`, `| window | 24 h to ${eff.at} (concurrency ${eff.concurrency?.windowMin} min) |`,
51
+ `| offending issues | ${b.issues.length ? b.issues.map((n) => `#${n}`).join(", ") : "none named"} |`, `| suggested cause | ${b.cause || "unknown"} |`,
52
+ `| signature | \`${b.sig}\` |`].join("\n");
53
+
54
+ /**
55
+ * Apply the filing rules. Returns `{slo, actions}` where `slo` is the next `slo.sigs` state (persist it in efficiency.json).
56
+ * With `enabled` false nothing is called and the state is unchanged. Never throws: a gh failure leaves that signature's state as it was.
57
+ */
58
+ export async function fileSloIssues({ eff, breaches, gh, cfg = DEFAULT_SLO, now = Date.now(), enabled = cfg.fileIssues, reportPath = null }) {
59
+ const sigs = { ...(eff?.slo?.sigs ?? {}) }, actions = [];
60
+ if (!enabled || typeof gh !== "function") return { slo: { sigs }, actions };
61
+ const live = new Set(breaches.map((b) => b.sig));
62
+ for (const b of breaches) {
63
+ const prev = sigs[b.sig];
64
+ try {
65
+ if (!prev?.issue) {
66
+ let found = null;
67
+ try { found = JSON.parse(String(await gh(["issue", "list", "--repo", cfg.repo, "--label", cfg.label, "--state", "open", "--search", `"${b.sig}" in:body`, "--json", "number,body"])) || "[]").find((i) => String(i.body ?? "").includes(b.sig)); } catch { found = null; }
68
+ if (found) { sigs[b.sig] = { issue: found.number, count: 1, openedAt: now, updatedAt: now, greenSince: null }; actions.push({ op: "adopt", sig: b.sig, issue: found.number }); continue; }
69
+ const out = String(await gh(["issue", "create", "--repo", cfg.repo, "--label", cfg.label, "--title", `engine-gap: ${b.code} SLO breach (${eff.repo})`, "--body", body(eff, b, { reportPath })]));
70
+ const n = Number(out.match(/(\d+)\s*$/)?.[1]);
71
+ if (Number.isSafeInteger(n)) { sigs[b.sig] = { issue: n, count: 1, openedAt: now, updatedAt: now, greenSince: null }; actions.push({ op: "create", sig: b.sig, issue: n }); }
72
+ continue;
73
+ }
74
+ if (now - prev.updatedAt < SLO_UPDATE_MS) { sigs[b.sig] = { ...prev, greenSince: null }; continue; } // alert noise: one update per signature per 6 h
75
+ const count = (prev.count ?? 1) + 1;
76
+ await gh(["issue", "comment", String(prev.issue), "--repo", cfg.repo, "--body", body(eff, b, { count, reportPath })]);
77
+ sigs[b.sig] = { ...prev, count, updatedAt: now, greenSince: null };
78
+ actions.push({ op: "comment", sig: b.sig, issue: prev.issue, count });
79
+ } catch { /* advisory: retried on the next pass */ }
80
+ }
81
+ for (const [sig, st] of Object.entries(sigs)) {
82
+ if (live.has(sig)) continue;
83
+ const since = st.greenSince ?? now;
84
+ if (now - since < SLO_CLOSE_GREEN_MS) { sigs[sig] = { ...st, greenSince: since }; continue; }
85
+ try { await gh(["issue", "close", String(st.issue), "--repo", cfg.repo, "--comment", `SLO \`${sig}\` has been green for 24 h; closing.`]); delete sigs[sig]; actions.push({ op: "close", sig, issue: st.issue }); } catch { /* retried */ }
86
+ }
87
+ return { slo: { sigs }, actions };
88
+ }
89
+
90
+ /** One advisory ledger pass for a batch: compute, evaluate, file (when enabled), persist. Never throws. */
91
+ export async function ledgerPass({ batch, sample, cfg, gh, now = Date.now(), repo = null, compute, readEff, writeEff, reportPath = null, operator = [] }) {
92
+ try {
93
+ const rows = batch.readLog(), prev = readEff(batch.dir);
94
+ let eff = compute({ rows, state: batch.store.peek(), prev, sample, now, batchId: batch.id, repo, operator, concurrencyMin: cfg.concurrencyMin });
95
+ const breaches = evaluateSlo(eff, cfg, { repo: repo ?? "unknown" });
96
+ const { slo, actions } = await fileSloIssues({ eff, breaches, gh, cfg, now, reportPath });
97
+ eff = { ...eff, slo, breaches: breaches.map((b) => ({ code: b.code, sig: b.sig, detail: b.detail, issue: slo.sigs[b.sig]?.issue ?? null })) };
98
+ writeEff(batch.dir, eff);
99
+ return { eff, breaches, actions };
100
+ } catch { return null; }
101
+ }
102
+
103
+ /**
104
+ * Introspect findings (#5987): file the `forgedock stats --conformance-outcomes` report as one rolling `engine-gap` issue per
105
+ * signature `introspect:<scope>`. Deduped against an open issue carrying the signature and against the prior report (`prior`
106
+ * = last filed `{hash, issue}`): an unchanged report files nothing. Returns `{action, issue?, hash}`; never throws.
107
+ */
108
+ export async function fileIntrospect({ report, scope, gh, cfg = DEFAULT_SLO, prior = null, reportPath = null }) {
109
+ const text = String(report ?? "").trim(), sig = `introspect:${scope}`;
110
+ if (!text || typeof gh !== "function") return { action: "none", hash: null };
111
+ const { createHash } = await import("node:crypto");
112
+ const hash = createHash("sha1").update(text).digest("hex").slice(0, 12);
113
+ if (prior?.hash === hash) return { action: "unchanged", hash, issue: prior.issue ?? null };
114
+ const body = `<!-- forge-slo: ${sig} -->\n**fd-introspect** (${scope})\n\n\`\`\`\n${text.slice(0, 6000)}\n\`\`\``;
115
+ try {
116
+ let found = null;
117
+ try { found = JSON.parse(String(await gh(["issue", "list", "--repo", cfg.repo, "--label", cfg.label, "--state", "open", "--search", `"${sig}" in:body`, "--json", "number,body"])) || "[]").find((i) => String(i.body ?? "").includes(sig)); } catch { found = null; }
118
+ if (found || prior?.issue) {
119
+ const n = found?.number ?? prior.issue;
120
+ await gh(["issue", "comment", String(n), "--repo", cfg.repo, "--body", body]);
121
+ return { action: "comment", issue: n, hash };
122
+ }
123
+ const out = String(await gh(["issue", "create", "--repo", cfg.repo, "--label", cfg.label, "--title", `engine-gap: fd-introspect findings (${scope})`, "--body", body]));
124
+ return { action: "create", issue: Number(out.match(/(\d+)\s*$/)?.[1]) || null, hash };
125
+ } catch { return { action: "failed", hash }; }
126
+ }
@@ -0,0 +1,112 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { computeEfficiency } from "./efficiency.mjs";
6
+ import { DEFAULT_SLO, ledgerPass, SLO_CLOSE_GREEN_MS, SLO_UPDATE_MS, evaluateSlo, fileSloIssues, parseSloConfig } from "./slo.mjs";
7
+
8
+ const eff = (o = {}) => ({ batch: "b1", repo: "o/r", at: "t", concurrency: { ready: 0, lowSinceMin: 0, windowMin: 15 }, repeats: [], commentsPerIssue: { max: 0, issues: [] }, phases: {}, idle: { share: {} }, ...o });
9
+ const codes = (o) => evaluateSlo(eff(o), DEFAULT_SLO).map((b) => b.code);
10
+ const fakeGh = () => { const calls = []; return { calls, gh: async (a) => { calls.push(a); return a[1] === "list" ? "[]" : a[1] === "create" ? "https://github.com/x/y/issues/42\n" : ""; } }; };
11
+
12
+ describe("#5987 SLOs", () => {
13
+ it("defaults and file_issues off unless explicitly true", () => {
14
+ const c = parseSloConfig({});
15
+ assert.equal(c.fileIssues, false); assert.equal(DEFAULT_SLO.fileIssues, false);
16
+ assert.equal(parseSloConfig({ orchestrate: { slo: { file_issues: "yes" } } }).fileIssues, false); assert.equal(c.repeatMax, 3); assert.equal(c.concurrencyMin, 0.6);
17
+ assert.equal(parseSloConfig({ orchestrate: { slo: { file_issues: "true", repeat_max: "5", attempts_max: "bad" } } }).repeatMax, 5);
18
+ assert.equal(parseSloConfig({ orchestrate: { file_issues: "true" } }).fileIssues, true);
19
+ assert.equal(parseSloConfig({ orchestrate: { slo: { file_issues: "false" } } }).fileIssues, false);
20
+ assert.equal(parseSloConfig({ orchestrate: { slo: { attempts_max: "bad" } } }).attemptsMax, 2);
21
+ });
22
+
23
+ it("each SLO breaches past its limit and not at it", () => {
24
+ assert.deepEqual(codes({ concurrency: { ready: 3, lowSinceMin: 30, achieved: 1, ceiling: 4, windowMin: 15 } }), ["concurrency"]);
25
+ assert.deepEqual(codes({ concurrency: { ready: 0, lowSinceMin: 90 } }), [], "nothing ready is not a breach");
26
+ assert.deepEqual(codes({ repeats: [{ signature: "s", count: 3, issues: [1] }] }), ["repeat"]);
27
+ assert.deepEqual(codes({ repeats: [{ signature: "s", count: 2, issues: [1] }] }), []);
28
+ assert.deepEqual(codes({ attemptsPerMerged: 2.5 }), ["attempts"]);
29
+ assert.deepEqual(codes({ attemptsPerMerged: 2 }), []);
30
+ assert.deepEqual(codes({ commentsPerIssue: { max: 21, issues: [{ issue: 5, comments: 21 }] } }), ["comments"]);
31
+ assert.deepEqual(codes({ interventionsPerDay: 7 }), ["interventions"]);
32
+ assert.deepEqual(codes({ interventionsPerDay: 6 }), []);
33
+ assert.deepEqual(codes({ phases: { fix: { ratio: 1.6 } } }), ["phase"]);
34
+ assert.deepEqual(codes({ phases: { fix: { ratio: 1.5 } } }), []);
35
+ assert.deepEqual(codes({ capacityRefusalsPerHour: 21 }), ["capacity"]);
36
+ assert.deepEqual(codes({ idle: { share: { hold: 0.3, "no-ready": 0.9 } } }), ["idle-hold"]);
37
+ });
38
+
39
+ it("files nothing unless enabled", async () => {
40
+ const f = fakeGh(), b = evaluateSlo(eff({ interventionsPerDay: 9 }), DEFAULT_SLO);
41
+ const r = await fileSloIssues({ eff: eff(), breaches: b, gh: f.gh, cfg: { ...DEFAULT_SLO, fileIssues: false }, now: 1e9 });
42
+ assert.equal(f.calls.length, 0); assert.deepEqual(r.slo.sigs, {});
43
+ });
44
+
45
+ it("posted bodies carry no local path", async () => {
46
+ const f = fakeGh(), cfg = { ...DEFAULT_SLO, fileIssues: true }, b = evaluateSlo(eff({ interventionsPerDay: 9 }), cfg);
47
+ await fileSloIssues({ eff: eff(), breaches: b, gh: f.gh, cfg, now: 1e12, reportPath: "/home/u/.forge/introspect/x.txt" });
48
+ assert.ok(f.calls.some((c) => c[1] === "create"));
49
+ assert.ok(!f.calls.some((c) => c.join(" ").includes("/home/u")), "reportPath never posted");
50
+ });
51
+
52
+ it("one issue per signature, a re-breach inside 6 h is silent, after 6 h a counter comment, 24 h green closes", async () => {
53
+ const f = fakeGh(), cfg = { ...DEFAULT_SLO, fileIssues: true }, b = evaluateSlo(eff({ interventionsPerDay: 9, attemptsPerMerged: 5 }), cfg);
54
+ let now = 1e12, e = eff();
55
+ const pass = async (br) => { const r = await fileSloIssues({ eff: e, breaches: br, gh: f.gh, cfg, now }); e = { ...e, slo: r.slo }; return r; };
56
+ let r = await pass(b);
57
+ assert.equal(f.calls.filter((c) => c[1] === "create").length, 2, "one create per signature");
58
+ assert.equal(e.slo.sigs["slo:interventions:o/r"].issue, 42);
59
+ now += SLO_UPDATE_MS - 1; r = await pass(b);
60
+ assert.deepEqual(r.actions, [], "no update inside 6 h");
61
+ now += 2; r = await pass(b);
62
+ assert.deepEqual(r.actions.map((a) => [a.op, a.count]), [["comment", 2], ["comment", 2]]);
63
+ now += 1000; r = await pass([]);
64
+ assert.deepEqual(r.actions, []);
65
+ now += SLO_CLOSE_GREEN_MS - 1; r = await pass([]);
66
+ assert.deepEqual(r.actions, []);
67
+ now += 2; r = await pass([]);
68
+ assert.deepEqual(r.actions.map((a) => a.op), ["close", "close"]);
69
+ assert.deepEqual(e.slo.sigs, {});
70
+ });
71
+
72
+ it("adopts an open issue found by signature instead of creating a second", async () => {
73
+ const calls = [], cfg = { ...DEFAULT_SLO, fileIssues: true }, b = evaluateSlo(eff({ interventionsPerDay: 9 }), cfg);
74
+ const gh = async (a) => { calls.push(a); return a[1] === "list" ? JSON.stringify([{ number: 7, body: `<!-- forge-slo: ${b[0].sig} -->` }]) : ""; };
75
+ const r = await fileSloIssues({ eff: eff(), breaches: b, gh, cfg, now: 1 });
76
+ assert.equal(r.slo.sigs[b[0].sig].issue, 7); assert.ok(!calls.some((c) => c[1] === "create"));
77
+ });
78
+
79
+ it("a gh failure never throws", async () => {
80
+ const cfg = { ...DEFAULT_SLO, fileIssues: true };
81
+ const r = await fileSloIssues({ eff: eff(), breaches: evaluateSlo(eff({ interventionsPerDay: 9 }), cfg), gh: async () => { throw new Error("down"); }, cfg, now: 1 });
82
+ assert.deepEqual(r.slo.sigs, {});
83
+ });
84
+
85
+ // R8: replay of the slow batches (11-20..11-24), rows in the shape orchestrate.mjs update() writes; no recorded batch is checked in files exactly one issue per breached signature; a healthy batch files none
86
+ const replay = async (rows, running) => {
87
+ const NOW = Date.parse("2026-11-24T12:00:00Z"), calls = [], cfg = { ...DEFAULT_SLO, fileIssues: true };
88
+ const prev = { v: 1, samples: Array.from({ length: 40 }, (_, i) => ({ t: NOW - (40 - i) * 60000, running, ceiling: 12, ready: 5 })) };
89
+ let stored = prev;
90
+ const batch = { id: "b", dir: "d", readLog: () => rows, store: { peek: () => null } };
91
+ const gh = async (a) => { calls.push(a); return a[1] === "list" ? "[]" : a[1] === "create" ? `https://github.com/x/y/issues/${100 + calls.length}\n` : ""; };
92
+ const operator = Array.from({ length: 5 }, (_, i) => ({ at: NOW - (100 - i) * 60000, kind: i % 2 ? "requeue" : "hold" }));
93
+ const run = () => ledgerPass({ batch, sample: null, operator, cfg, gh, now: NOW, repo: "o/r", compute: computeEfficiency, readEff: () => stored, writeEff: (_d, e) => { stored = e; } });
94
+ const first = await run(), second = await run();
95
+ return { first, second, creates: calls.filter((c) => c[1] === "create") };
96
+ };
97
+ it("fixture replay: slow batch files one issue per signature, healthy files none", async () => {
98
+ const at = (m, r) => ({ at: new Date(Date.parse("2026-11-24T12:00:00Z") - m * 60000).toISOString(), ...r });
99
+ const slow = [
100
+ ...[1, 2, 3, 4].map((i) => at(300 - i, { issue: 7, outcome: "engine-error", reason: "sandbox.capacity", minutes: 30 })),
101
+ at(200, { issue: 7, outcome: "merged", minutes: 20 }), at(190, { issue: 8, outcome: "ci-failed", minutes: 10 }), at(180, { issue: 8, outcome: "merged", minutes: 10 }),
102
+ at(110, { issue: null, outcome: "added", detail: "9" }), at(105, { issue: 9, outcome: "deferred", code: "run.interrupted", detail: "interrupted: upgrade; requeued" }),
103
+ ];
104
+ const r = await replay(slow, 3);
105
+ const sigs = r.first.breaches.map((b) => b.sig);
106
+ for (const c of ["concurrency", "repeat", "attempts", "interventions"]) assert.ok(sigs.includes(`slo:${c}:o/r`), c);
107
+ assert.equal(r.creates.length, new Set(sigs).size, "one create per signature, the second pass adds none");
108
+ assert.equal(r.second.actions.length, 0);
109
+ const ok = await replay([at(60, { issue: 1, outcome: "merged", minutes: 20 })], 11);
110
+ assert.equal(ok.creates.length, 0);
111
+ });
112
+ });
@@ -17,6 +17,8 @@
17
17
 
18
18
  export const STATUS_MARKER = "FORGE:STATUS";
19
19
  export const STATUS_SEP = "<!-- FORGE:STATUS:SEP -->";
20
+ import { createHash } from "node:crypto";
21
+
20
22
  /** Markers folded into the status comment, keyed by the FIRST marker of a post. */
21
23
  export const STATUS_SECTIONS = Object.freeze(["FORGE:STARTED", "FORGE:CONTEXT", "FORGE:LANE_BRANCH", "FORGE:LITE", "FORGE:TRAJECTORY", "FORGE:DECISION"]);
22
24
  /** Sections that keep their last N entries instead of only the newest. */
@@ -24,6 +26,8 @@ export const APPEND_SECTIONS = Object.freeze({ "FORGE:DECISION": 5 });
24
26
  export const ENTRY_SEP = "\n\n---\n\n";
25
27
  /** Markers posted once and edited in place (the marker leads the comment body, so anchored readers still match). */
26
28
  export const UPSERT_MARKERS = Object.freeze(["FORGE:INVESTIGATION", "FORGE:IMPLEMENTATION", "FORGE:PARKED"]);
29
+ /** #5979: markers re-derived on every pass; a repeat of the same state posts nothing (FACTS and DEPENDENCY are edited in place, NEEDS_HUMAN stays a new comment when it changed). */
30
+ export const IN_PLACE_MARKERS = Object.freeze(["FORGE:FACTS", "FORGE:DEPENDENCY", "FORGE:NEEDS_HUMAN"]);
27
31
 
28
32
  const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
29
33
  const markLine = (m) => `<!-- ${m} -->`;
@@ -149,6 +153,39 @@ export async function postUpsert({ gh, repo, issue, markers, body, comments = nu
149
153
  return newUrl(gh, repo, issue, full);
150
154
  }
151
155
 
156
+ /** #5986: markers posted once per (kind, content hash): an identical payload updates one comment and bumps its counter. */
157
+ export const KEYED_MARKERS = Object.freeze(["FORGE:AMENDMENT", "FORGE:NEEDS_HUMAN", "FORGE:FACTS"]);
158
+ export const isKeyedPost = (marker) => KEYED_MARKERS.includes(asArr(marker)[0]);
159
+ /** Hard cap of engine comments per issue: beyond it a post edits an existing comment in place and never adds one. */
160
+ export const MAX_ENGINE_COMMENTS = 12;
161
+ export const engineCommentCount = (comments, trusted) => (comments ?? []).filter((c) => /^\s*<!--\s*FORGE:/.test(String(c?.body ?? "")) && trusted(c)).length;
162
+ const contentKey = (body) => createHash("sha256").update(String(body)).digest("hex").slice(0, 12);
163
+
164
+ /**
165
+ * Post `body` under `marker` keyed by (marker, content hash): a trusted comment with the same hash is edited with `n` bumped, a new
166
+ * payload is a new comment, and at `limit` engine comments the newest comment of that kind is edited in place (none: nothing is posted, null).
167
+ * The comments are always read fresh. Returns the comment url.
168
+ */
169
+ export async function postKeyed({ gh, repo, issue, marker, body, cap = (s) => s, trusted, limit = MAX_ENGINE_COMMENTS, comments = null }) {
170
+ const t = trusted ?? (await import("./prefilter.mjs")).isTrustedIssueComment;
171
+ const list = comments ?? await viewComments(gh, repo, issue), key = contentKey(String(body).replace(/\n\n_[^\n]*_\s*$/, "")); // the trailing usage line varies per run
172
+ const mine = list.filter((c) => new RegExp(`^\\s*<!--\\s*${esc(marker)}(?![A-Za-z0-9_:])`).test(String(c?.body ?? "")) && t(c) && commentId(c));
173
+ const keyLine = (c) => /<!-- forge-key hash=(\w+) n=(\d+) -->\s*$/.exec(String(c.body)); // trailing: the leading marker line stays exactly `<!-- MARKER -->` for every reader
174
+ const same = [...mine].reverse().find((c) => keyLine(c)?.[1] === key);
175
+ const render = (n) => cap(`<!-- ${marker} -->\n${body}${n > 1 ? `\n\n_Identical update seen ${n} times._` : ""}\n<!-- forge-key hash=${key} n=${n} -->`);
176
+ const edit = async (c, n) => { try { await patchWith(gh, repo)(commentId(c), render(n)); return c.url ?? null; } catch { return undefined; } };
177
+ if (same) {
178
+ const n = Number(keyLine(same)[2]) + 1;
179
+ const u = await edit(same, n); if (u !== undefined) return u;
180
+ }
181
+ if (engineCommentCount(list, t) >= limit) {
182
+ const last = mine[mine.length - 1];
183
+ if (!last) return null;
184
+ const u = await edit(last, 1); return u === undefined ? null : u;
185
+ }
186
+ return newUrl(gh, repo, issue, render(1));
187
+ }
188
+
152
189
  /** #5592: labels that mean "parked / waiting for a person or the remediation queue"; a live or finished issue must not keep them. */
153
190
  export const isPipelineLabel = (name) => { const n = String(name ?? ""); return n === "needs-human" || n.startsWith("needs-human:") || n.startsWith("parked:") || n === "remediation-queue"; };
154
191
  /** The pipeline labels among `labels` (names, or `{name}` objects). */
@@ -3,7 +3,7 @@
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
5
  import { STATUS_SEP, parseStatus, renderStatus, putSection, writeStatus, findStatus, findLeading, hasSection, sectionText, commentId, isStatusPost, isUpsertPost,
6
- postStatusSection, postUpsert, clearPipelineLabels, pipelineLabels, isPipelineLabel } from "./statuscomment.mjs";
6
+ postStatusSection, postUpsert, postKeyed, isKeyedPost, engineCommentCount, MAX_ENGINE_COMMENTS, clearPipelineLabels, pipelineLabels, isPipelineLabel } from "./statuscomment.mjs";
7
7
 
8
8
  const BOT = { author: { login: "rapiercraft-forgedock" }, authorAssociation: "CONTRIBUTOR" };
9
9
  const trusted = (c) => c.author?.login === "rapiercraft-forgedock";
@@ -148,3 +148,50 @@ describe("#5592 gh helpers", () => {
148
148
  assert.deepEqual(read, [[]]);
149
149
  });
150
150
  });
151
+
152
+ describe("#5986 keyed upsert and the engine comment cap", () => {
153
+ // a tiny in-memory issue: comment posts append, PATCH edits
154
+ const issue = (seed = []) => {
155
+ const comments = [...seed], log = [];
156
+ const gh = async (a) => {
157
+ log.push(a);
158
+ if (a[1] === "view") return JSON.stringify({ comments });
159
+ if (a[1] === "comment") { const id = 100 + comments.length; comments.push({ ...BOT, url: url(id), body: a[a.indexOf("--body") + 1] }); return url(id); }
160
+ if (a[0] === "api") { const id = /comments\/(\d+)/.exec(a[3])[1]; comments.find((c) => c.url.endsWith(`-${id}`)).body = a[a.indexOf("-f") + 1].slice(5); return ""; }
161
+ return "";
162
+ };
163
+ return { gh, comments, log };
164
+ };
165
+ const post = (i, marker, body) => postKeyed({ gh: i.gh, repo: "o/r", issue: 7, marker, body, trusted });
166
+
167
+ it("an identical amendment payload posted twice yields one comment, updated with a counter", async () => {
168
+ const i = issue();
169
+ await post(i, "FORGE:AMENDMENT", "## Contract amended\n- add-deliverable a.mjs");
170
+ await post(i, "FORGE:AMENDMENT", "## Contract amended\n- add-deliverable a.mjs");
171
+ assert.equal(i.comments.length, 1);
172
+ assert.match(i.comments[0].body, /^<!-- FORGE:AMENDMENT -->\n[\s\S]*<!-- forge-key hash=[0-9a-f]{12} n=2 -->$/);
173
+ await post(i, "FORGE:AMENDMENT", "## Contract amended\n- add-deliverable b.mjs");
174
+ assert.equal(i.comments.length, 2, "a different payload is a new comment");
175
+ });
176
+ it("the trailing usage line does not make a repeat look new", async () => {
177
+ const i = issue();
178
+ await post(i, "FORGE:NEEDS_HUMAN", "## Needs human\nwhy\n\n_cost $0.10, wall 3 min_");
179
+ await post(i, "FORGE:NEEDS_HUMAN", "## Needs human\nwhy\n\n_cost $0.20, wall 5 min_");
180
+ assert.equal(i.comments.length, 1);
181
+ });
182
+ it("at 12 engine comments a new payload edits the newest comment of its kind in place and never adds one", async () => {
183
+ const i = issue(Array.from({ length: MAX_ENGINE_COMMENTS - 1 }, (_, k) => ({ ...BOT, url: url(k + 1), body: `<!-- FORGE:FACTS -->\nfact ${k}\n<!-- forge-key hash=${String(k).padStart(12, "0")} n=1 -->` })));
184
+ await post(i, "FORGE:AMENDMENT", "first");
185
+ assert.equal(i.comments.length, MAX_ENGINE_COMMENTS);
186
+ await post(i, "FORGE:AMENDMENT", "second");
187
+ await post(i, "FORGE:AMENDMENT", "third");
188
+ assert.equal(i.comments.length, MAX_ENGINE_COMMENTS, "capped");
189
+ assert.match(i.comments.at(-1).body, /third/);
190
+ assert.equal(await post(i, "FORGE:NEEDS_HUMAN", "no comment of this kind yet"), null, "nothing posted past the cap");
191
+ assert.equal(i.comments.length, MAX_ENGINE_COMMENTS);
192
+ });
193
+ it("only trusted FORGE comments count; keyed markers are recognised", () => {
194
+ assert.equal(engineCommentCount([{ ...BOT, body: "<!-- FORGE:FACTS -->" }, { author: { login: "x" }, body: "<!-- FORGE:FACTS -->" }, { ...BOT, body: "hi" }], trusted), 1);
195
+ assert.ok(isKeyedPost("FORGE:FACTS") && isKeyedPost(["FORGE:AMENDMENT"]) && !isKeyedPost("FORGE:PARKED"));
196
+ });
197
+ });
@@ -100,7 +100,8 @@ export function parseVerify(sec = {}) {
100
100
  const baselines = parseBaselines(s.baselines); // #5448: suites validate runs when matching paths change
101
101
  const precheckBlock = str(s.precheck_block).toLowerCase() === "true"; // #5079: a still-failing declared check stops the lane (ci.red)
102
102
  const guardBlock = str(s.guard_block).toLowerCase() !== "false"; // #5239: verify.invariants (the pre-merge guard set) block the merge unless false
103
- return { ...(settle !== "fixed" ? { settle } : {}), ...(parseCancelSuperseded(s.cancel_superseded) !== "off" ? { cancelSuperseded: parseCancelSuperseded(s.cancel_superseded) } : {}), mode, workflow, pathsInput, skipPaths, maxRounds, precheckTimeoutSeconds, precheckTotalSeconds, checkRun, checks, postMerge, flaky, duplicateExports, enumeratingMechanical, invariants, ...(precheckBlock ? { precheckBlock } : {}), ...(guardBlock ? {} : { guardBlock: false }), ...(Object.keys(guardCommand).length ? { guardCommand } : {}), ...(baselines.length ? { baselines } : {}), ...(Object.keys(sandboxes).length ? { sandboxes } : {}), e2e: parseE2e(s) };
103
+ const guardBypass = str(s.guard_bypass).toLowerCase() === "true"; // #5992: opt in: a lane clear of a red guard's files proceeds; the guard is re-run at merge
104
+ return { ...(settle !== "fixed" ? { settle } : {}), ...(parseCancelSuperseded(s.cancel_superseded) !== "off" ? { cancelSuperseded: parseCancelSuperseded(s.cancel_superseded) } : {}), mode, workflow, pathsInput, skipPaths, maxRounds, precheckTimeoutSeconds, precheckTotalSeconds, checkRun, checks, postMerge, flaky, duplicateExports, enumeratingMechanical, invariants, ...(precheckBlock ? { precheckBlock } : {}), ...(guardBlock ? {} : { guardBlock: false }), ...(Object.keys(guardCommand).length ? { guardCommand } : {}), ...(baselines.length ? { baselines } : {}), ...(Object.keys(sandboxes).length ? { sandboxes } : {}), e2e: parseE2e(s), ...(guardBypass ? { guardBypass } : {}) };
104
105
  }
105
106
 
106
107
  const globRe = (g) => new RegExp(`^${g.split("**").map((p) => p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]")).join(".*")}$`);
@@ -374,7 +374,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
374
374
  const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
375
375
  const e = effectiveCapacity();
376
376
  const h = live(cfg);
377
- return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), net: readNet(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
377
+ return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), net: readNet(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
378
378
  }
379
379
 
380
380
  /** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
@@ -429,7 +429,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
429
429
  const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
430
430
  if (pu.mem + nm > availMem + 1e-9 || pu.cpus + nc > availCpus + 1e-9) return { status: 503, body: { error: `projected peak ${r1(pu.mem + nm)} GB / ${r1(pu.cpus + nc)} cpus exceeds capacity ${r1(availMem)} GB / ${r1(availCpus)} cpus`, code: "pool.projected_peak", capacity: c }, retryAfter: 60 };
431
431
  }
432
- if (!h.ok && prio !== "reserved") return { status: 503, body: { error: `host busy: ${h.reason}`, live: h }, retryAfter: 60 };
432
+ if (!h.ok && prio !== "reserved") return { status: 503, body: { error: `host busy: ${h.reason}`, code: "pool.host_load", live: h }, retryAfter: 60 };
433
433
  const gate = hostDiskView(c.active, spec.repo?.slug ?? null);
434
434
  if (gate.host_disk_low) { // #5733: before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
435
435
  const floor = floorGb();
package/bin/pool/cli.mjs CHANGED
@@ -46,6 +46,19 @@ function rejectUnknownFlags(cmd, rest) {
46
46
  }
47
47
  }
48
48
 
49
+ /** #6008: sandboxes kept for adopt across the batches under `root` (issue, batch, age, phase): lanes no live dispatcher awaits. */
50
+ export async function keptRows(root, { now = Date.now() } = {}) {
51
+ try {
52
+ const B = await import("../lean/batch.mjs"), out = [];
53
+ for (const id of B.listBatches(root)) {
54
+ const b = B.openBatch(root, id), last = b.lastProgressMs();
55
+ const live = !b.readReport() && last !== null && now - last <= 10 * 60000;
56
+ for (const k of b.keptSandboxes(live)) out.push({ batch: id, ...k });
57
+ }
58
+ return out;
59
+ } catch { return []; }
60
+ }
61
+ export const keptLines = (rows) => rows.length ? [`kept sandboxes (${rows.length}):`, ...rows.map((k) => ` #${k.issue} batch ${k.batch} age ${Math.round((k.ageMs ?? 0) / 60000)}m phase ${k.phase ?? "?"}`)] : [];
49
62
  const num = (x) => (Number.isFinite(x) ? String(Math.round(x * 10) / 10) : "-");
50
63
  /** #5885: one row per host: used/borrowable/total cpus and memory, lane counts, pause state and why lanes are throttled or drained. */
51
64
  export function statusTable(agents) {
@@ -124,10 +137,12 @@ export async function runPoolCli(argv, deps = {}) {
124
137
  case "status": {
125
138
  const cfg = routerConfig();
126
139
  const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "GET", `/agents${flag("account") ? `?account=${encodeURIComponent(flag("account"))}` : ""}`, { token: cfg.forgedock_token });
127
- if (rest.includes("--json")) console.log(JSON.stringify(r.data, null, 2));
140
+ const kept = await keptRows((await import("../lean/batch.mjs")).batchRoot());
141
+ if (rest.includes("--json")) console.log(JSON.stringify(r.data && typeof r.data === "object" && !Array.isArray(r.data) && kept.length ? { ...r.data, kept_sandboxes: kept } : r.data, null, 2));
128
142
  else if (!r.ok) throw new Error(`router refused: HTTP ${r.status} ${JSON.stringify(r.data)}`);
129
143
  else console.log(statusTable(r.data?.agents ?? []));
130
144
  if (!rest.includes("--json") && r.ok) for (const l of depcacheLines(r.data?.agents)) console.log(l); // #5901
145
+ if (!rest.includes("--json")) for (const l of keptLines(kept)) console.log(l); // #6008
131
146
  // #5735: lane sandboxes used/ceiling per agent, and the lane total across all batches
132
147
  for (const a of Array.isArray(r.data?.agents) ? r.data.agents : []) if (a?.lanes) console.log(`${a.name}: lanes ${a.lanes.used}/${a.lanes.ceiling ?? "-"}`);
133
148
  if (Number.isInteger(r.data?.remote_lanes)) console.log(`remote lanes across batches: ${r.data.remote_lanes}`);
@@ -70,6 +70,27 @@ export function installCommands(entry, { root = true } = {}) {
70
70
  return RECIPES[recipe].steps(recipe === name ? version : null).map((s) => (root ? sh(s) : `sudo sh -c ${JSON.stringify(sh(s))}`));
71
71
  }
72
72
 
73
+ /**
74
+ * Generic install for a tool no recipe covers (2026-11-26 unclog): a missing Python module is pip-installed, a missing
75
+ * Node package npm-installed into the worktree, a missing command apt-installed. Replaces adding one recipe per tool
76
+ * (77 of 215 needs-human parks on open issues were "Remote sandbox lacks X"). `miss`: {kind, tool} from the validate
77
+ * preflight. Returns [] for an unsafe name or a kind nothing can install (environment, forgedock-path).
78
+ */
79
+ const PYPI = { yaml: "PyYAML", PIL: "Pillow", cv2: "opencv-python-headless", bs4: "beautifulsoup4", sklearn: "scikit-learn", dateutil: "python-dateutil", jwt: "PyJWT", dotenv: "python-dotenv", google: "protobuf", attr: "attrs", magic: "python-magic", Crypto: "pycryptodome", OpenSSL: "pyOpenSSL", serial: "pyserial", usb: "pyusb", zmq: "pyzmq", git: "GitPython", jose: "python-jose", multipart: "python-multipart" };
80
+ const SAFE = /^@?[A-Za-z0-9][A-Za-z0-9._/+-]*$/;
81
+ export function genericInstallCommands(miss, { root = true } = {}) {
82
+ const tool = String(miss?.tool ?? "").trim();
83
+ if (!tool || !SAFE.test(tool) || tool.includes("..")) return [];
84
+ const su = (c) => (root ? c : `sudo sh -c ${JSON.stringify(c)}`);
85
+ if (miss.kind === "python-module") {
86
+ const pkg = PYPI[tool.split(".")[0]] ?? tool.split(".")[0];
87
+ return [`python3 -m pip install --user --quiet ${pkg} || python3 -m pip install --user --quiet --break-system-packages ${pkg}`];
88
+ }
89
+ if (miss.kind === "node-module") return [`npm install --no-save --no-audit --no-fund ${tool}`];
90
+ if (miss.kind === "command" && !tool.includes("/")) return [su(`apt-get update -qq && apt-get install -y --no-install-recommends ${tool} && rm -rf /var/lib/apt/lists/*`)];
91
+ return [];
92
+ }
93
+
73
94
  /**
74
95
  * Installs `tools` in the running sandbox through the injected `run({command, timeoutMs})` -> {rc, stdout, stderr}.
75
96
  * Never throws: {ok:true} or {ok:false, tool, stderrTail}.
@@ -0,0 +1,54 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5986: attempts per merged issue and per-issue engine comment count for `forgedock stats --attempts`, from the repo's local batch
5
+ * files (state.json `attempts` ledger, report.json rows). No network, no model. The ledger counts failed lanes; the merging lane is
6
+ * one more, so a merged-first-try issue is 1 attempt.
7
+ */
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { listBatches } from "../lean/batch.mjs";
11
+ import { sameRepo, windowLabel } from "./efficiency.mjs";
12
+
13
+ const readJson = (f) => { try { return JSON.parse(readFileSync(f, "utf8")); } catch { return null; } };
14
+ const round1 = (x) => Math.round(x * 10) / 10;
15
+ const p50 = (xs) => { if (!xs.length) return null; const s = [...xs].sort((a, b) => a - b), m = s.length >> 1; return round1(s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2); };
16
+
17
+ /** Per issue (latest row wins across batches): attempts for merged issues, and the engine comment count where a ledger recorded it. */
18
+ export function attemptMetrics(rows, ledgers) {
19
+ const by = new Map();
20
+ for (const r of rows ?? []) if (Number.isSafeInteger(r?.issue)) by.set(r.issue, r);
21
+ const detail = [];
22
+ for (const [n, r] of by) {
23
+ if (r.outcome !== "merged") continue;
24
+ const l = ledgers?.[n] ?? null;
25
+ detail.push({ issue: n, attempts: (Number.isInteger(l?.attempts) ? l.attempts : 0) + 1, comments: Number.isInteger(l?.comments) ? l.comments : null });
26
+ }
27
+ const att = detail.map((d) => d.attempts), com = detail.map((d) => d.comments).filter((c) => c !== null);
28
+ return { merged: detail.length, attempts_p50: p50(att), attempts_mean: att.length ? round1(att.reduce((a, b) => a + b, 0) / att.length) : null, attempts_max: att.length ? Math.max(...att) : null,
29
+ comments_p50: p50(com), comments_max: com.length ? Math.max(...com) : null, detail };
30
+ }
31
+
32
+ export function attemptsReport({ batchRoot, repo = null, windows, now = Date.now() }) {
33
+ const batches = (existsSync(batchRoot) ? listBatches(batchRoot) : []).map((id) => {
34
+ const dir = join(batchRoot, id), plan = readJson(join(dir, "plan.json")) ?? {};
35
+ return { dir, plan, created: Date.parse(plan.created ?? "") };
36
+ }).filter((b) => Number.isFinite(b.created) && (!repo || sameRepo(b.plan.repo, repo))).sort((a, b) => a.created - b.created);
37
+ const out = {};
38
+ for (const w of windows) {
39
+ const inWin = batches.filter((b) => b.created <= now && now - b.created <= w), rows = [], ledgers = {};
40
+ for (const b of inWin) { // oldest first: a later batch's row and ledger replace an earlier one for the same issue
41
+ rows.push(...(readJson(join(b.dir, "report.json"))?.rows ?? []));
42
+ Object.assign(ledgers, readJson(join(b.dir, "state.json"))?.attempts ?? {});
43
+ }
44
+ const { detail, ...m } = attemptMetrics(rows, ledgers);
45
+ out[windowLabel(w)] = { batches: inWin.length, ...m, detail };
46
+ }
47
+ return out;
48
+ }
49
+
50
+ export function formatAttemptLines(windows) {
51
+ return Object.entries(windows).flatMap(([w, m]) => [`attempts ${w}: ${m.batches} batch${m.batches === 1 ? "" : "es"}, ${m.merged} merged issue${m.merged === 1 ? "" : "s"}`,
52
+ ` attempts per merged issue: ${m.attempts_mean == null ? "n/a" : `mean ${m.attempts_mean}, p50 ${m.attempts_p50}, max ${m.attempts_max}`}`,
53
+ ` engine comments per issue: ${m.comments_p50 == null ? "n/a" : `p50 ${m.comments_p50}, max ${m.comments_max}`}`]);
54
+ }
@@ -0,0 +1,30 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "../tests/_tmp.mjs";
8
+ import { attemptMetrics, attemptsReport, formatAttemptLines } from "./attempts.mjs";
9
+
10
+ describe("attempts per merged issue (#5986)", () => {
11
+ it("counts failed ledger lanes plus the merging lane, and the recorded comment count", () => {
12
+ const m = attemptMetrics([{ issue: 1, outcome: "merged" }, { issue: 2, outcome: "merged" }, { issue: 3, outcome: "needs-human" }], { 2: { attempts: 3, comments: 9 }, 3: { attempts: 4 } });
13
+ assert.equal(m.merged, 2);
14
+ assert.deepEqual(m.detail, [{ issue: 1, attempts: 1, comments: null }, { issue: 2, attempts: 4, comments: 9 }]);
15
+ assert.equal(m.attempts_max, 4); assert.equal(m.attempts_mean, 2.5); assert.equal(m.comments_max, 9);
16
+ });
17
+ it("attemptsReport reads report.json and state.json; the repo filter excludes other repos", () => {
18
+ const root = tmpDir("attempts-"), dir = join(root, "b1");
19
+ mkdirSync(dir);
20
+ const now = Date.parse("2026-11-23T00:00:00Z");
21
+ writeFileSync(join(dir, "plan.json"), JSON.stringify({ created: "2026-11-22T00:00:00Z", repo: "o/r" }));
22
+ writeFileSync(join(dir, "report.json"), JSON.stringify({ rows: [{ issue: 5, outcome: "merged" }] }));
23
+ writeFileSync(join(dir, "state.json"), JSON.stringify({ attempts: { 5: { attempts: 2, comments: 7 } } }));
24
+ const w = attemptsReport({ batchRoot: root, repo: "o/r", windows: [7 * 86400000], now });
25
+ assert.equal(w["7d"].merged, 1); assert.equal(w["7d"].attempts_max, 3); assert.equal(w["7d"].comments_max, 7);
26
+ assert.equal(attemptsReport({ batchRoot: root, repo: "x/y", windows: [86400000], now })["1d"].merged, 0);
27
+ assert.match(formatAttemptLines(w).join("\n"), /attempts per merged issue: mean 3, p50 3, max 3[\s\S]*comments per issue: p50 7, max 7/);
28
+ assert.match(formatAttemptLines(attemptsReport({ batchRoot: root, repo: "x/y", windows: [86400000], now })).join("\n"), /n\/a/);
29
+ });
30
+ });
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5979: comment churn per issue. Counts the engine's own comments (a `<!-- FORGE:... -->` marker) on each issue and the
5
+ * repeated failures (the same `sig=<hash>` on more than one NEEDS_HUMAN/PARKED comment), so a noisy issue is visible. Pure,
6
+ * except `readChurn`, which is read-only and best effort.
7
+ */
8
+ const FORGE_RE = /<!--\s*FORGE:[A-Z_:-]+/;
9
+ const FAIL_RE = /<!--\s*FORGE:(?:NEEDS_HUMAN|PARKED)(?![A-Za-z0-9_])/;
10
+ const SIG_RE = /\bsig=([0-9a-f]{12})\b/;
11
+
12
+ const median = (xs) => { const s = [...xs].sort((a, b) => a - b); return s.length ? (s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2) : 0; };
13
+
14
+ /** @param {{issue:number, comments:{body:string}[]}[]} issues @returns {{perIssue:{issue:number, comments:number, repeats:number}[], max:number, median:number, repeated:number}} */
15
+ export function churnStats(issues) {
16
+ const perIssue = [];
17
+ for (const it of Array.isArray(issues) ? issues : []) {
18
+ const sigs = new Map();
19
+ let comments = 0;
20
+ for (const c of Array.isArray(it?.comments) ? it.comments : []) {
21
+ const body = String(c?.body ?? "");
22
+ if (!FORGE_RE.test(body)) continue;
23
+ comments++;
24
+ const sig = FAIL_RE.test(body) ? SIG_RE.exec(body)?.[1] : null;
25
+ if (sig) sigs.set(sig, (sigs.get(sig) ?? 0) + 1);
26
+ }
27
+ perIssue.push({ issue: it?.issue, comments, repeats: [...sigs.values()].filter((n) => n > 1).length });
28
+ }
29
+ const counts = perIssue.map((p) => p.comments);
30
+ return { perIssue, max: Math.max(0, ...counts), median: median(counts), repeated: perIssue.reduce((a, p) => a + p.repeats, 0) };
31
+ }
32
+
33
+ /** Report lines; none when there is nothing to count. */
34
+ export function formatChurnLines(stats) {
35
+ if (!stats?.perIssue?.length) return [];
36
+ const top = [...stats.perIssue].sort((a, b) => b.comments - a.comments).slice(0, 3).filter((p) => p.comments > 0);
37
+ return [`comments per issue: max ${stats.max}, median ${stats.median}${top.length ? ` (${top.map((p) => `#${p.issue}: ${p.comments}`).join(", ")})` : ""}; repeated failures: ${stats.repeated}`];
38
+ }
39
+
40
+ /** Read the comments of `issues` through `gh` and return the report lines; never throws. */
41
+ export async function readChurn({ gh, repo, issues }) {
42
+ try {
43
+ const out = [];
44
+ for (const n of (issues ?? []).slice(0, 50)) {
45
+ try { out.push({ issue: n, comments: JSON.parse(String(await gh(["issue", "view", String(n), "-R", repo, "--json", "comments"])))?.comments ?? [] }); } catch { /* skip an unreadable issue */ }
46
+ }
47
+ return formatChurnLines(churnStats(out));
48
+ } catch { return []; }
49
+ }