forgedock 1.65.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 (80) 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 +143 -19
  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 +13 -5
  15. package/bin/lean/batch-health.test.mjs +16 -0
  16. package/bin/lean/batch.mjs +62 -0
  17. package/bin/lean/batch.test.mjs +119 -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/depcache.mjs +9 -0
  29. package/bin/lean/efficiency.mjs +162 -0
  30. package/bin/lean/efficiency.test.mjs +79 -0
  31. package/bin/lean/execution.mjs +31 -13
  32. package/bin/lean/execution.test.mjs +46 -0
  33. package/bin/lean/failure-stop.mjs +46 -0
  34. package/bin/lean/failure-stop.test.mjs +45 -0
  35. package/bin/lean/fixtures/capacity-storm.json +609 -0
  36. package/bin/lean/lean.mjs +130 -30
  37. package/bin/lean/lean.test.mjs +138 -47
  38. package/bin/lean/liveness.mjs +37 -0
  39. package/bin/lean/liveness.test.mjs +33 -0
  40. package/bin/lean/orchestrate-attempts.test.mjs +74 -0
  41. package/bin/lean/orchestrate-envhold.test.mjs +17 -0
  42. package/bin/lean/orchestrate-pause.test.mjs +84 -0
  43. package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
  44. package/bin/lean/orchestrate.mjs +202 -28
  45. package/bin/lean/phaseledger.mjs +6 -0
  46. package/bin/lean/phaseledger.test.mjs +13 -1
  47. package/bin/lean/prompts.mjs +6 -10
  48. package/bin/lean/reconcile.mjs +90 -0
  49. package/bin/lean/recurrence.mjs +38 -2
  50. package/bin/lean/recurrence.test.mjs +56 -1
  51. package/bin/lean/sandbox-remote.mjs +33 -2
  52. package/bin/lean/sched.mjs +19 -0
  53. package/bin/lean/sched.test.mjs +11 -1
  54. package/bin/lean/schedd-health.mjs +8 -1
  55. package/bin/lean/schedd-health.test.mjs +19 -0
  56. package/bin/lean/schedd.mjs +97 -10
  57. package/bin/lean/schedd.test.mjs +138 -1
  58. package/bin/lean/slo.mjs +126 -0
  59. package/bin/lean/slo.test.mjs +112 -0
  60. package/bin/lean/statuscomment.mjs +37 -0
  61. package/bin/lean/statuscomment.test.mjs +48 -1
  62. package/bin/lean/verify.mjs +2 -1
  63. package/bin/pool/agent.mjs +46 -8
  64. package/bin/pool/cache-sweep.mjs +41 -4
  65. package/bin/pool/cli.mjs +28 -1
  66. package/bin/pool/health.mjs +18 -0
  67. package/bin/pool/lane-tools.mjs +21 -0
  68. package/bin/pool/mirror-seed.mjs +21 -2
  69. package/bin/pool/router.mjs +6 -2
  70. package/bin/stats/attempts.mjs +54 -0
  71. package/bin/stats/attempts.test.mjs +30 -0
  72. package/bin/stats/churn.mjs +49 -0
  73. package/bin/stats/churn.test.mjs +31 -0
  74. package/bin/stats/index.mjs +11 -3
  75. package/commands/orchestrate.md +21 -18
  76. package/docs/CONFIG.md +1 -0
  77. package/docs/OUTCOME-CODES.md +1 -0
  78. package/package.json +1 -1
  79. package/pool/image/entrypoint.sh +2 -1
  80. package/scripts/check-devdocs-freshness.sh +1 -1
@@ -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(".*")}$`);
@@ -14,7 +14,7 @@ import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs"
14
14
  import { jsonStore } from "./store.mjs";
15
15
  import { makeWarm } from "./warm.mjs";
16
16
  import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
17
- import { hostDiskFree, ensureNatPin, netState } from "./health.mjs";
17
+ import { hostDiskFree, hostMemFree, ensureNatPin, netState } from "./health.mjs";
18
18
  import { laneDiskUsedGb, planDiskCap, fstrimDue, runFstrim } from "./disk.mjs";
19
19
  import { makeMirrorSeed, dockerRunner } from "./mirror-seed.mjs";
20
20
  import { planIdleEviction, CACHE_LABEL, agentLabel } from "./cache-sweep.mjs";
@@ -104,7 +104,7 @@ export async function buildWithRetry(build, { sleep = (ms) => new Promise((r) =>
104
104
  }
105
105
  }
106
106
 
107
- export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
107
+ export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, hostMem = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
108
108
  const stateDir = cfg.state_dir;
109
109
  const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
110
110
  const sb = () => store.data.sandboxes;
@@ -179,6 +179,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
179
179
  let lastCachePrune = -Infinity;
180
180
  // #5757: cache volume hygiene state: per-volume sweep error/size/last use (last use also from launches in this process).
181
181
  let lastCacheSweep = -Infinity;
182
+ let lastLaunchSweep = -Infinity;
182
183
  const cacheErr = new Map(), cacheInfo = new Map(), cacheUsed = new Map(), adoptedCache = new Set(); // adoptedCache: pre-label volumes this agent mounts (labels cannot be added to an existing volume)
183
184
  const sweepFail = (v, what, e) => { const m = `${what} ${v}: ${String(e.stderr || e.message).slice(0, 200)}`; cacheErr.set(`${what}:${v}`, m); log.warn?.(m); };
184
185
  const dirMb = (d) => { let n = 0, seen = 0; const walk = (x) => { if (seen++ > 200000) return; let st; try { st = lstatSync(x); } catch { return; } n += st.size; if (st.isDirectory()) { try { for (const e of readdirSync(x)) walk(join(x, e)); } catch { /* unreadable */ } } }; walk(d); return Math.round(n / 1048576); };
@@ -227,6 +228,19 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
227
228
  const a = hostSamples[0], b = hostSamples[hostSamples.length - 1];
228
229
  return a && b && b.t - a.t >= 60000 ? Math.round(((a.gb - b.gb) / ((b.t - a.t) / 3600000)) * 10) / 10 : null;
229
230
  }
231
+ // #5967: free physical memory of the Windows host (neighbour WSL VMs squeeze the lane VM invisibly); null off WSL or unreadable: no field, no gate.
232
+ let hostMemCache = { at: -Infinity, v: null };
233
+ const readHostMem = () => {
234
+ if (now() - hostMemCache.at >= 30000) hostMemCache = { at: now(), v: (hostMem ?? hostMemFree)() };
235
+ return hostMemCache.v;
236
+ };
237
+ const memFloorGb = () => cfg.host_mem_floor_gb ?? 4;
238
+ const memPausedRecs = () => activeRecs().filter((r) => r.memPaused);
239
+ function hostMemView() {
240
+ let hm = null; try { hm = readHostMem(); } catch { hm = null; }
241
+ if (!hm || !Number.isFinite(hm.free_gb)) return {};
242
+ return { host_mem_free_gb: hm.free_gb, host_mem_low: hm.free_gb < memFloorGb() || memPausedRecs().length > 0, host_mem_floor_gb: memFloorGb(), ...(Array.isArray(hm.vmmem) && hm.vmmem.length ? { vmmem: hm.vmmem } : {}), ...(memPausedRecs().length ? { mem_paused: memPausedRecs().length } : {}) };
243
+ }
230
244
  let netCache = { at: -Infinity, v: null };
231
245
  const readNet = () => { if (now() - netCache.at > 60000) netCache = { at: now(), v: net() }; return netCache.v; };
232
246
  // #5884: lane disk cap (cfg.lane_disk_cap_gb, unset = off, nothing added to /capacity): sandbox dirs plus cache volumes.
@@ -360,7 +374,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
360
374
  const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
361
375
  const e = effectiveCapacity();
362
376
  const h = live(cfg);
363
- 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 }])) } : {}), 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), 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 }])) };
364
378
  }
365
379
 
366
380
  /** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
@@ -395,6 +409,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
395
409
  if (existing?.drained && existing.state === "exited") { await destroy(existing.id, "drained: relaunch"); existing = null; } // #5856: the router/dispatcher rescheduled a drained lane under the same id
396
410
  if (existing?.diskPressure && existing.state === "exited") { await destroy(existing.id, "disk pressure: resume", { keepWork: true }); existing = null; } // #5891: the worktree stays, the lane adopts it
397
411
  if (existing) { existing.lease = now(); store.save(); return { status: 200, body: view(existing) }; }
412
+ if (now() - lastLaunchSweep > 60000) { lastLaunchSweep = now(); await cacheSweep(now()).catch(() => {}); } // #5901: trim the depcache to its cap before this lane can write a new entry (throttled; the periodic sweep also runs)
398
413
  if (Number.isInteger(spec.warm)) warm.configure({ spec, cpus, mem_gb, limit, n: spec.warm }); // #4912: the lane's execution.warm_sandboxes sizes the repo's pool
399
414
  const prio = spec.priority ?? "normal";
400
415
  if (!PRIORITIES.includes(prio)) throw Object.assign(new Error(`spec.priority must be one of ${PRIORITIES.join(", ")}`), { status: 400 });
@@ -414,12 +429,16 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
414
429
  const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
415
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 };
416
431
  }
417
- 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 };
418
433
  const gate = hostDiskView(c.active, spec.repo?.slug ?? null);
419
434
  if (gate.host_disk_low) { // #5733: before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
420
435
  const floor = floorGb();
421
436
  return { status: 503, body: { error: `host disk low: ${gate.host_disk_free_gb} GB free, floor ${floor} GB with ${c.active} running`, code: "pool.disk_low", host_disk_free_gb: gate.host_disk_free_gb, floor_gb: floor }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
422
437
  }
438
+ const mg = hostMemView();
439
+ if (mg.host_mem_low) { // #5967: after the disk gate, before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
440
+ return { status: 503, body: { error: `host memory low: ${mg.host_mem_free_gb} GB free, floor ${mg.host_mem_floor_gb} GB`, code: "pool.host_mem", reason: "host_mem", host_mem_free_gb: mg.host_mem_free_gb, floor_gb: mg.host_mem_floor_gb }, retryAfter: cfg.host_mem_retry_after_s ?? 60 };
441
+ }
423
442
  if (c.disk_capped) { // #5884: lane disk is at the hard cap; pressure prune runs in reap(), the lane defers like pool.disk_low
424
443
  return { status: 503, body: { error: `lane disk full: ${c.lane_disk_used_gb} GB of ${c.lane_disk_cap_gb} GB cap`, code: "pool.disk_cap", lane_disk_used_gb: c.lane_disk_used_gb, cap_gb: c.lane_disk_cap_gb }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
425
444
  }
@@ -506,7 +525,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
506
525
  return { status: 201, body: view(rec) };
507
526
  }
508
527
 
509
- const view = (r) => ({ id: r.id, state: r.state, issue: r.issue, cpus: r.cpus, mem_gb: r.mem_gb, started_at: new Date(r.startedAt).toISOString(), ...(r.error ? { error: r.error } : {}), ...(r.diskPaused ? { status_detail: "paused (disk)" } : {}), ...(r.diskPressure ? { code: "sandbox.disk_pressure", status_detail: "stopped (disk pressure): worktree kept for resume" } : {}) });
528
+ const view = (r) => ({ id: r.id, state: r.state, issue: r.issue, cpus: r.cpus, mem_gb: r.mem_gb, started_at: new Date(r.startedAt).toISOString(), ...(r.error ? { error: r.error } : {}), ...(r.diskPaused ? { status_detail: "paused (disk)" } : {}), ...(r.memPaused ? { status_detail: "paused (host memory)" } : {}), ...(r.diskPressure ? { code: "sandbox.disk_pressure", status_detail: "stopped (disk pressure): worktree kept for resume" } : {}) });
510
529
 
511
530
  const warm = makeWarm({ store, sb, own, now, launch, destroy: (id, why) => destroy(id, why), view, log });
512
531
 
@@ -515,7 +534,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
515
534
  const s = await docker.inspect(r.name);
516
535
  if (!s) { r.state = "exited"; r.finishedAt ??= now(); }
517
536
  else if (!s.running && r.state !== "starting") { r.state = "exited"; r.exitCode = s.exitCode; r.finishedAt = Date.parse(s.finishedAt) || now(); }
518
- else if (s.running) r.state = r.diskPaused ? "paused" : "running";
537
+ else if (s.running) r.state = r.diskPaused || r.memPaused ? "paused" : "running";
519
538
  return r;
520
539
  }
521
540
 
@@ -609,7 +628,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
609
628
  for (const v of await ownCacheVolumes()) {
610
629
  if (never.includes(v)) continue;
611
630
  try {
612
- const r = await docker.sweepCache(v, image, { maxAgeDays: cfg.cache_max_age_days ?? 14, maxGb: cfg.cache_max_gb ?? null, keep, now: t });
631
+ const r = await docker.sweepCache(v, image, { maxAgeDays: cfg.cache_max_age_days ?? 14, maxGb: cfg.cache_max_gb ?? null, maxDepcacheGb: cfg.depcache_max_gb ?? 40, keep, now: t });
613
632
  cacheInfo.set(v, r); cacheErr.delete(`cache sweep:${v}`);
614
633
  if (r.errors?.length) cacheErr.set(`cache sweep:${v}`, `cache sweep ${v}: ${r.errors[0]}`);
615
634
  volumes.push({ name: v, lastUsedMs: Math.max(r.last_used_ms ?? -Infinity, cacheUsed.get(v) ?? -Infinity) });
@@ -691,6 +710,24 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
691
710
  log.error?.(`stopped ${victim.id} (sandbox.disk_pressure): host free ${free} GB < ${hard} GB`);
692
711
  }
693
712
  }
713
+ // #5967: runtime host-memory control, once per reap. Below floor/2 pause the newest running sandbox (lease kept); at floor + margin resume.
714
+ async function hostMemPressure(t) {
715
+ hostMemCache.at = -Infinity;
716
+ let hm = null; try { hm = readHostMem(); } catch { hm = null; }
717
+ if (!hm || !Number.isFinite(hm.free_gb)) return;
718
+ const free = hm.free_gb, floor = memFloorGb();
719
+ for (const r of memPausedRecs()) r.lease = t; // a paused lane stays leased: it is not lost
720
+ if (free >= floor + (cfg.host_mem_resume_margin_gb ?? 1)) {
721
+ for (const r of memPausedRecs()) {
722
+ try { for (const n of cntNames(r)) await docker.unpause?.(n); r.memPaused = false; r.state = r.diskPaused ? "paused" : "running"; log.info?.(`resumed ${r.id}: host memory ${free} GB`); } catch (e) { log.warn?.(`unpause ${r.id}: ${String(e.stderr || e.message).slice(0, 200)}`); }
723
+ }
724
+ return;
725
+ }
726
+ if (free >= floor / 2 || memPausedRecs().length) return; // one paused sandbox at a time; resumes only above floor + margin
727
+ const victim = activeRecs().filter((r) => r.state === "running").sort((a, b) => b.startedAt - a.startedAt)[0];
728
+ if (!victim) return;
729
+ try { for (const n of cntNames(victim)) await docker.pause?.(n); victim.memPaused = true; victim.state = "paused"; victim.lease = t; log.warn?.(`paused ${victim.id} (memory): host free ${free} GB < ${floor / 2} GB`); } catch (e) { log.warn?.(`pause ${victim.id}: ${String(e.stderr || e.message).slice(0, 200)}`); }
730
+ }
694
731
  /** #5884: at the prune threshold of lane_disk_cap_gb prune this agent's own leftovers and sweep caches; fstrim on an interval and after a prune. Log lines only. */
695
732
  let lastFstrim = -Infinity;
696
733
  async function diskPressure(t) {
@@ -715,10 +752,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
715
752
  const t = now();
716
753
  for (const r of Object.values(sb())) {
717
754
  try { await refresh(r); } catch { /* docker hiccup: judge by lease only */ }
718
- const why = t - r.lease > leaseTtlMs && !r.diskPaused ? "lease expired" : t - r.startedAt > maxLifeMs ? "max lifetime" : r.state === "exited" && r.finishedAt && t - r.finishedAt > (r.diskPressure ? keepPressureMs : keepExitedMs) ? "exited retention" : null;
755
+ const why = t - r.lease > leaseTtlMs && !r.diskPaused && !r.memPaused ? "lease expired" : t - r.startedAt > maxLifeMs ? "max lifetime" : r.state === "exited" && r.finishedAt && t - r.finishedAt > (r.diskPressure ? keepPressureMs : keepExitedMs) ? "exited retention" : null;
719
756
  if (why) await destroy(r.id, why);
720
757
  }
721
758
  await hostDiskPressure(t); // #5891
759
+ await hostMemPressure(t); // #5967
722
760
  const known = new Set(Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)]));
723
761
  for (const name of await docker.listLabelled(OWN)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
724
762
  await sampleUsage();
@@ -8,8 +8,10 @@ import { existsSync, readFileSync, rmSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
 
10
10
  export const CACHE_LABEL = "computeshare.cache=1";
11
+ /** #5969: dirs older entrypoints (and volumes/images already out there) export as lane cache dirs; still swept, capped and pruned. */
12
+ export const LEGACY_STORES = ["uv", "npm", "pip", "poetry"];
11
13
  /** #5955: every package-manager store the lanes write (depcache.mjs env(), agent.mjs pnpm store), relative to the /cache volume root. One list for the sweep and pruneCaches. */
12
- export const PACKAGE_STORES = ["pnpm-store", ...["pnpm-store", "npm-cache", "uv-cache", "poetry-cache", "pip-cache"].map((n) => `forge-depcache/stores/${n}`)];
14
+ export const PACKAGE_STORES = ["pnpm-store", ...["pnpm-store", "npm-cache", "uv-cache", "poetry-cache", "pip-cache"].map((n) => `forge-depcache/stores/${n}`), ...LEGACY_STORES];
13
15
  /** #5881: owner label; the reaper and sweeps touch only containers and volumes carrying their own agent's label. */
14
16
  export const agentLabel = (id) => `computeshare.agent=${id}`;
15
17
  const DAY = 86400000;
@@ -31,6 +33,14 @@ export function planCacheCap(entries, capBytes) {
31
33
  return { delete: out, total, after };
32
34
  }
33
35
 
36
+ /**
37
+ * #5901: least-recently-used plan for one repo's depcache snapshots ({path, bytes, lastUsedMs, live}). Same rule as
38
+ * `planCacheCap` with last use as the order; live (locked) snapshots count towards the total and are never chosen.
39
+ */
40
+ export function planDepcacheCap(entries, capBytes) {
41
+ return planCacheCap(entries.map((e) => ({ ...e, mtimeMs: e.lastUsedMs })), capBytes);
42
+ }
43
+
34
44
  /**
35
45
  * Cache volumes to remove: last use known (`lastUsedMs` a number), older than `idleMs`, no sandbox record references
36
46
  * it and it is not in the never-evict list. `volumes` is [{name, lastUsedMs}].
@@ -44,8 +54,34 @@ const sh = (cmd, args) => { try { return execFileSync(cmd, args, { encoding: "ut
44
54
  const sizeOf = (p) => (Number(sh("du", ["-sk", p]).split(/\s/)[0]) || 0) * 1024;
45
55
  const kids = (dir) => sh("find", [dir, "-mindepth", "1", "-maxdepth", "1", "-printf", "%p\t%T@\n"]).split("\n").filter(Boolean).map((l) => { const i = l.lastIndexOf("\t"); return { path: l.slice(0, i), mtimeMs: Number(l.slice(i + 1)) * 1000 }; });
46
56
 
57
+ const SNAP = /^[a-z]+-[0-9a-f]{16}$/;
58
+ /** Last use of a depcache snapshot: its `last-used` file (epoch ms, written on every hit), else the directory mtime. */
59
+ const snapLastUsed = (k) => { try { const n = Number(readFileSync(join(k.path, "last-used"), "utf8").trim()); if (n > 0) return n; } catch { /* none yet */ } return k.mtimeMs; };
60
+
61
+ /**
62
+ * #5901: depcache is `<dc>/<repoKey>/<eco>-<key>/`. Each snapshot (not the repo dir, whose mtime moves with every new
63
+ * snapshot) ages out by its last use and is trimmed least-recently-used past the per-repo cap. A snapshot with a lock file
64
+ * is in use and kept. Fills `depcacheBytes[repoKey]` with what remains.
65
+ */
66
+ function sweepDepcache(dc, { cutoff, capBytes, rm, depcacheBytes }) {
67
+ for (const repo of kids(dc)) {
68
+ const rk = repo.path.slice(dc.length + 1);
69
+ if (rk === "stores") continue;
70
+ if (SNAP.test(rk)) { if (repo.mtimeMs < cutoff) rm(repo.path); continue; } // an entry of the flat layout (no repo level)
71
+ let snaps = kids(repo.path).filter((k) => SNAP.test(k.path.slice(repo.path.length + 1)));
72
+ const live = (k) => existsSync(`${k.path}.lock`);
73
+ snaps = snaps.map((k) => ({ ...k, lastUsedMs: snapLastUsed(k), live: live(k) }));
74
+ for (const k of snaps.filter((x) => x.lastUsedMs < cutoff && !x.live)) rm(k.path);
75
+ snaps = snaps.filter((x) => existsSync(x.path));
76
+ if (!snaps.length) { if (repo.mtimeMs < cutoff) rm(repo.path); continue; } // nothing left in it and untouched for the max age
77
+ for (const k of snaps) k.bytes = sizeOf(k.path);
78
+ if (capBytes !== null) for (const p of planDepcacheCap(snaps, capBytes).delete) rm(p);
79
+ depcacheBytes[rk] = snaps.filter((x) => existsSync(x.path)).reduce((a, x) => a + x.bytes, 0);
80
+ }
81
+ }
82
+
47
83
  /** Runs inside the container. Returns {size_bytes, last_used_ms, removed, errors}. */
48
- export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, keep = [], now = Date.now() } = {}) {
84
+ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, maxDepcacheGb = null, keep = [], now = Date.now() } = {}) {
49
85
  const errors = [], removed = [];
50
86
  const rm = (p) => { try { rmSync(p, { recursive: true, force: true }); removed.push(p); } catch (e) { errors.push(`${p}: ${e.message}`); } };
51
87
  const cutoff = now - maxAgeDays * DAY;
@@ -57,7 +93,8 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ke
57
93
  }
58
94
  const ageOut = (dir, skip = []) => { for (const k of kids(dir)) if (k.mtimeMs < cutoff && !skip.includes(k.path)) rm(k.path); };
59
95
  const dc = join(root, "forge-depcache");
60
- if (existsSync(dc)) { ageOut(join(dc, "stores")); ageOut(dc, [join(dc, "stores")]); } // snapshots, then store entries
96
+ const depcacheBytes = {};
97
+ if (existsSync(dc)) { ageOut(join(dc, "stores")); sweepDepcache(dc, { cutoff, capBytes: Number.isFinite(maxDepcacheGb) ? maxDepcacheGb * 1024 ** 3 : null, rm, depcacheBytes }); } // store entries, then snapshots per repo
61
98
  if (existsSync(join(root, "env"))) ageOut(join(root, "env"));
62
99
  const ps = join(root, "pnpm-store");
63
100
  if (existsSync(ps)) sh("pnpm", ["store", "prune", "--store-dir", ps]);
@@ -72,7 +109,7 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ke
72
109
  }
73
110
  let last = null;
74
111
  try { const n = Number(readFileSync(join(root, ".last-used"), "utf8").trim()); if (Number.isFinite(n) && n > 0) last = n * 1000; } catch { /* never recorded */ }
75
- return { size_bytes: sizeOf(root), last_used_ms: last, removed: removed.length, errors: errors.slice(0, 5) };
112
+ return { size_bytes: sizeOf(root), last_used_ms: last, depcache_bytes: depcacheBytes, removed: removed.length, errors: errors.slice(0, 5) };
76
113
  }
77
114
 
78
115
  if (process.env.CS_CACHE_SWEEP_OPTS) process.stdout.write(JSON.stringify(sweepVolume(JSON.parse(process.env.CS_CACHE_SWEEP_OPTS))) + "\n");
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) {
@@ -69,6 +82,16 @@ export function statusTable(agents) {
69
82
  }
70
83
 
71
84
  /** The `forgedock pool` verbs (and the `computeshare` script). Throws on usage or router errors; `deps` injects the HTTP client and config. */
85
+ /** #5901: one line per agent cache volume with each repo's depcache size, from the router's /agents view. */
86
+ export function depcacheLines(agents) {
87
+ const out = [];
88
+ for (const a of agents ?? []) for (const [vol, v] of Object.entries(a.cache_volumes ?? {})) {
89
+ const repos = Object.entries(v.depcache_gb ?? {}).map(([k, gb]) => `${k} ${gb} GB`).join(", ");
90
+ if (repos) out.push(`${a.name} ${vol}: depcache ${repos}`);
91
+ }
92
+ return out;
93
+ }
94
+
72
95
  export async function runPoolCli(argv, deps = {}) {
73
96
  const [cmd, ...rest] = argv;
74
97
  const call = deps.call ?? httpCall;
@@ -114,9 +137,12 @@ export async function runPoolCli(argv, deps = {}) {
114
137
  case "status": {
115
138
  const cfg = routerConfig();
116
139
  const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "GET", `/agents${flag("account") ? `?account=${encodeURIComponent(flag("account"))}` : ""}`, { token: cfg.forgedock_token });
117
- 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));
118
142
  else if (!r.ok) throw new Error(`router refused: HTTP ${r.status} ${JSON.stringify(r.data)}`);
119
143
  else console.log(statusTable(r.data?.agents ?? []));
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
120
146
  // #5735: lane sandboxes used/ceiling per agent, and the lane total across all batches
121
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 ?? "-"}`);
122
148
  if (Number.isInteger(r.data?.remote_lanes)) console.log(`remote lanes across batches: ${r.data.remote_lanes}`);
@@ -124,6 +150,7 @@ export async function runPoolCli(argv, deps = {}) {
124
150
  if (a.transport) console.log(`${a.name}: transport ${a.transport}`); // #5882
125
151
  const n = a.net; // #5923
126
152
  if (n?.mirrored) console.log(`${a.name}: net mirrored, port range ${n.port_range ?? "?"}, NAT pin ${n.nat_pin ? "present" : "MISSING"}${n.degraded ? " DEGRADED" : ""}`);
153
+ if (Number.isFinite(a.host_mem_free_gb)) console.error(`${a.name}: host_mem_free_gb ${a.host_mem_free_gb}${Array.isArray(a.vmmem) && a.vmmem.length ? `, other VMs: ${a.vmmem.map((v) => `${v.name} ${v.gb} GB`).join(", ")}` : ""}${a.host_mem_low ? " WARNING: host memory below the floor, new sandboxes are refused" : ""}`); // #5967
127
154
  if (!Number.isFinite(a.host_disk_free_gb)) continue;
128
155
  console.error(`${a.name}: host_disk_free_gb ${a.host_disk_free_gb}${Number.isFinite(a.host_disk_growth_gb_per_h) ? `, growth ${a.host_disk_growth_gb_per_h} GB/h` : ""}${a.disk_warning ? ` WARNING: ${a.disk_warning}` : ""}`);
129
156
  }
@@ -67,6 +67,24 @@ export function hostDiskFree({ path = null, osrelease = readRelease, statfs = st
67
67
  } catch { return null; }
68
68
  }
69
69
 
70
+ /**
71
+ * #5967: Windows host free physical memory and the vmmem working sets (other WSL/Hyper-V VMs), via powershell.exe over the interop
72
+ * socket. `{ free_gb, vmmem: [{name, gb}] }` (1 decimal), or null off WSL or on any error (absent means unknown: no gate). All I/O injectable.
73
+ */
74
+ const PS_MEM = "$f=(Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory; $v=@(Get-Process vmmem* -ErrorAction SilentlyContinue | ForEach-Object { @{ name=$_.ProcessName; bytes=$_.WorkingSet64 } }); @{ free_kb=$f; vmmem=$v } | ConvertTo-Json -Compress -Depth 3";
75
+ export function hostMemFree({ osrelease = readRelease, run = winRun, env = process.env } = {}) {
76
+ try {
77
+ if (!/microsoft/i.test(String(osrelease() ?? ""))) return null;
78
+ const out = run("/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", PS_MEM], env);
79
+ if (!out) return null;
80
+ const j = JSON.parse(String(out).trim());
81
+ const kb = Number(j?.free_kb);
82
+ if (!Number.isFinite(kb) || kb < 0) return null;
83
+ const vm = j.vmmem == null ? [] : Array.isArray(j.vmmem) ? j.vmmem : [j.vmmem];
84
+ return { free_gb: Math.round(kb / 104857.6) / 10, vmmem: vm.filter((p) => Number.isFinite(Number(p?.bytes))).map((p) => ({ name: String(p.name ?? "vmmem"), gb: Math.round(Number(p.bytes) / 107374182.4) / 10 })) };
85
+ } catch { return null; }
86
+ }
87
+
70
88
  /** #5923: WSL mirrored networking gives the guest a narrow source-port slice; docker MASQUERADE must stay inside it or replies drop. */
71
89
  const DEFAULT_RANGE = [32768, 60999];
72
90
  const NAT_BRIDGE_FMT = '{{.Name}}|{{index .Options "com.docker.network.bridge.name"}}|{{range .IPAM.Config}}{{.Subnet}} {{end}}';
@@ -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}.