forgedock 1.64.0 → 1.66.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.
@@ -149,6 +149,42 @@ describe("schedd host scheduler (#4192)", () => {
149
149
  } finally { await h.cleanup(); }
150
150
  });
151
151
 
152
+ it("#5964 a hosted clear-breaker not acked within its wait answers pending, and the request is still honoured by the runner (never dropped)", async () => {
153
+ const h = host();
154
+ try {
155
+ await h.daemon();
156
+ const all = capture(() => h.inWork(() => orchestrateFromCli(["1", "2", "--parallel", "1", "--repo", "o/r", "--no-prefilter"], h.client)));
157
+ await until(() => h.launched().length === 1 && h.lanePids().length === 1);
158
+ const [id] = listBatches(h.root);
159
+ const b = openBatch(h.root, id);
160
+ // a 1 ms wait only polls the ack once, so the reply is pending unless the runner happened to ack in that instant: retry until it does not
161
+ let r = null;
162
+ for (let i = 0; i < 40 && !r?.pending; i++) r = await request(await connectDaemon({ dir: h.sched, spawnDaemon: null }), { op: "clear-breaker", id, waitMs: 1 }, undefined, { timeoutMs: 20000 });
163
+ assert.deepEqual({ hosted: r.hosted, acknowledged: r.acknowledged, pending: r.pending }, { hosted: true, acknowledged: false, pending: true });
164
+ // the old code deleted the request here and rewrote state.json, so no ack would ever follow
165
+ await until(() => b.readClearBreakerAck() && !existsSync(join(h.root, id, "clear-breaker")));
166
+ writeFileSync(h.release, "");
167
+ await all;
168
+ } finally { await h.cleanup(); }
169
+ });
170
+
171
+ it("#5964 cli prints pending message when the hosted runner has not acked within its wait", async () => {
172
+ const h = host();
173
+ try {
174
+ await h.daemon();
175
+ const all = capture(() => h.inWork(() => orchestrateFromCli(["1", "2", "--parallel", "1", "--repo", "o/r", "--no-prefilter"], h.client)));
176
+ await until(() => h.launched().length === 1 && h.lanePids().length === 1);
177
+ const [id] = listBatches(h.root);
178
+ const lines = []; let r = null;
179
+ for (let i = 0; i < 40 && !r?.pending; i++) { lines.length = 0; r = await runBatch({ argv: ["--clear-breaker", id], deps: { batchRoot: h.root, scheddDir: h.sched, pollMs: 1 }, sink: { line: (l) => lines.push(l) } }); }
180
+ assert.equal(r.pending, true);
181
+ assert.match(lines[0], /pending: the runner will clear it on its next pass/);
182
+ assert.doesNotMatch(lines[0], /did not acknowledge/);
183
+ writeFileSync(h.release, "");
184
+ await all;
185
+ } finally { await h.cleanup(); }
186
+ });
187
+
152
188
  it("#5947 clear-breaker on a hosted batch reaches the live runner, which acknowledges it (no daemon restart)", async () => {
153
189
  const h = host();
154
190
  try {
@@ -757,6 +793,90 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
757
793
  } finally { await d2?.close?.(); }
758
794
  });
759
795
 
796
+ it("#5966: a handover under an active unit exits non-zero after close, and the hard bound fires when a batch stop hangs", async () => {
797
+ for (const hang of [false, true]) {
798
+ const dir = tmpDir("schedd-exit-"), root = join(dir, "batches"), lines = [], exits = [];
799
+ let version = "1.51.0";
800
+ const d = await startDaemon({ dir, root, log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => "active",
801
+ exit: (c) => exits.push(c), stopMs: hang ? 60_000 : 1000, hardExitMs: 200,
802
+ runBatch: ({ sink, signal }) => { sink.batch({ id: "x", dir }); return new Promise((_, rej) => { if (!hang) signal.addEventListener("abort", () => rej(Object.assign(new Error("stopped"), { code: "batch.stopped" }))); }); } });
803
+ request(await connectDaemon({ dir, spawnDaemon: null }), { op: "submit", argv: ["x"], cwd: dir, env: {} }).catch(() => {});
804
+ await until(() => lines.some((l) => l.includes("listening")));
805
+ version = "1.52.0";
806
+ await until(() => exits.length > 0);
807
+ assert.deepEqual(exits, [1], `hang=${hang}`);
808
+ assert.equal(d.stopCode(), 1);
809
+ if (hang) assert.ok(lines.some((l) => l.includes("did not finish within")), lines.join("\n"));
810
+ await d.close();
811
+ }
812
+ });
813
+
814
+ it("#5966 R1: without a unit, a handover whose successor never listens keeps hosting (re-hosted here); if that fails it exits non-zero", async () => {
815
+ const dir = tmpDir("schedd-nosucc-"), root = join(dir, "batches"), lines = [], exits = [];
816
+ let version = "1.51.0", spawns = 0;
817
+ const d = await startDaemon({ dir, root, log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
818
+ exit: (c) => exits.push(c), respawn: () => { spawns++; }, probe: async () => false, successorMs: 50, successorPollMs: 10, runBatch: async () => ({}) });
819
+ version = "1.52.0";
820
+ await until(() => d.rehosted());
821
+ const d2 = d.rehosted();
822
+ try {
823
+ assert.equal(d2.running, true, "a daemon hosts again and holds the lock");
824
+ assert.equal(readFileSync(scheddPaths(dir).lock, "utf8").trim(), String(process.pid));
825
+ assert.deepEqual(exits, [], "no exit while hosting continues");
826
+ assert.equal(spawns, 2, "the successor was started twice");
827
+ assert.ok(lines.some((l) => l.includes("hosting the batches again")));
828
+ } finally { await d2.close(); }
829
+ // re-host impossible -> exit non-zero
830
+ const dir2 = tmpDir("schedd-nosucc2-"), exits2 = [];
831
+ let v2 = "1.51.0";
832
+ await startDaemon({ dir: dir2, root: join(dir2, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => v2, unit: () => null,
833
+ exit: (c) => exits2.push(c), respawn: () => {}, probe: async () => false, successorMs: 30, successorPollMs: 10, rehost: async () => null, runBatch: async () => ({}) });
834
+ v2 = "1.52.0";
835
+ await until(() => exits2.length > 0);
836
+ assert.deepEqual(exits2, [1]);
837
+ });
838
+
839
+ it("#5984 handover: settled() outlives closed until the successor is spawned and probed (CLI exits only after it)", async () => {
840
+ const dir = tmpDir("schedd-settled-"), order = [];
841
+ let version = "1.51.0";
842
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
843
+ exit: (c) => order.push(`exit${c}`), respawn: () => order.push("respawn"), probe: async () => { order.push("probe"); return true; }, successorMs: 200, successorPollMs: 10, runBatch: async () => ({}) });
844
+ version = "1.52.0";
845
+ await d.closed;
846
+ order.push("closed-seen"); // what scheddFromCli used to exit on
847
+ await d.settled();
848
+ order.push("settled");
849
+ assert.ok(order.indexOf("respawn") < order.indexOf("settled") && order.indexOf("probe") < order.indexOf("settled"), order.join(","));
850
+ assert.equal(d.stopCode(), 1);
851
+ });
852
+
853
+ it("#5984 rehost: settled() of the stopped daemon resolves once the rehosted daemon is up; lost-lock/idle close settles via closed", async () => {
854
+ const dir = tmpDir("schedd-settled2-");
855
+ let version = "1.51.0";
856
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
857
+ exit: () => {}, respawn: () => {}, probe: async () => false, successorMs: 30, successorPollMs: 10, runBatch: async () => ({}) });
858
+ version = "1.52.0";
859
+ await d.closed; await d.settled();
860
+ const d2 = d.rehosted();
861
+ assert.equal(d2?.running, true, "rehosted before settled resolves");
862
+ await d2.close();
863
+ const dir3 = tmpDir("schedd-settled3-");
864
+ const d3 = await startDaemon({ dir: dir3, root: join(dir3, "batches"), log: () => {}, resumeOnStart: false, runBatch: async () => ({}) });
865
+ await d3.close();
866
+ await d3.settled();
867
+ assert.equal(d3.stopCode(), null);
868
+ });
869
+
870
+ it("#5966: a stall-recovery restart also exits (shared self-stop path)", async () => {
871
+ const dir = tmpDir("schedd-stallexit-"), root = join(dir, "batches"), exits = [];
872
+ let version = "1.51.0";
873
+ const d = await startDaemon({ dir, root, log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => "active", exit: (c) => exits.push(c), runBatch: async () => ({}) });
874
+ version = "1.52.0";
875
+ await until(() => exits.length > 0);
876
+ assert.deepEqual(exits, [1]);
877
+ await d.closed;
878
+ });
879
+
760
880
  it("#5204: readInstalledVersion reads this install's package.json version, null when unreadable", () => {
761
881
  assert.equal(readInstalledVersion(), JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version);
762
882
  const dir = tmpDir("schedd-ver-");
@@ -14,8 +14,9 @@ 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
+ import { makeMirrorSeed, dockerRunner } from "./mirror-seed.mjs";
19
20
  import { planIdleEviction, CACHE_LABEL, agentLabel } from "./cache-sweep.mjs";
20
21
 
21
22
  const LABEL = "computeshare=1";
@@ -103,7 +104,7 @@ export async function buildWithRetry(build, { sleep = (ms) => new Promise((r) =>
103
104
  }
104
105
  }
105
106
 
106
- export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, net = netState, vm = vmSize, trim = runFstrim } = {}) {
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 } = {}) {
107
108
  const stateDir = cfg.state_dir;
108
109
  const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
109
110
  const sb = () => store.data.sandboxes;
@@ -178,6 +179,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
178
179
  let lastCachePrune = -Infinity;
179
180
  // #5757: cache volume hygiene state: per-volume sweep error/size/last use (last use also from launches in this process).
180
181
  let lastCacheSweep = -Infinity;
182
+ let lastLaunchSweep = -Infinity;
181
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)
182
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); };
183
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); };
@@ -226,6 +228,19 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
226
228
  const a = hostSamples[0], b = hostSamples[hostSamples.length - 1];
227
229
  return a && b && b.t - a.t >= 60000 ? Math.round(((a.gb - b.gb) / ((b.t - a.t) / 3600000)) * 10) / 10 : null;
228
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
+ }
229
244
  let netCache = { at: -Infinity, v: null };
230
245
  const readNet = () => { if (now() - netCache.at > 60000) netCache = { at: now(), v: net() }; return netCache.v; };
231
246
  // #5884: lane disk cap (cfg.lane_disk_cap_gb, unset = off, nothing added to /capacity): sandbox dirs plus cache volumes.
@@ -359,7 +374,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
359
374
  const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
360
375
  const e = effectiveCapacity();
361
376
  const h = live(cfg);
362
- 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, live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
363
378
  }
364
379
 
365
380
  /** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
@@ -379,12 +394,22 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
379
394
  /** cgroup cpu weight per class (docker --cpu-shares); a borrowed lane yields to a reserved one under contention. */
380
395
  const sharesArgs = (prio) => (weighted() ? ["--cpu-shares", String(SHARES()[prio])] : []);
381
396
 
397
+ /** The per-repo cache volume (`/cache`: worktrees, bare mirror, stores). An explicit agent_id gives this agent its own volume. */
398
+ const cacheVolumeOf = (key) => `cs-cache-${cfg.agent_id ? `${agentId}-` : ""}${String(key ?? "default").toLowerCase().replace(/[^a-z0-9_.-]/g, "-")}`;
399
+ /** #5949: dispatcher-seeded mirrors (GET /mirrors, POST /mirrors/seed); git runs in a helper container on the cache volume. */
400
+ const mirrors = makeMirrorSeed({ seedDir: join(stateDir, "seed"), runnerFor: ({ slug, cache_key }) => {
401
+ const volume = cacheVolumeOf(cache_key ?? slug), run = (mirrorRunner ?? dockerRunner)({ volume, image, seedDir: join(stateDir, "seed") });
402
+ return async (script, env) => { try { await docker.createVolume?.(volume, [CACHE_LABEL, AGENT]); } catch { /* an unlabelled volume still works */ } cacheUsed.set(volume, now()); return run(script, env); };
403
+ } });
404
+ const seedFail = (e) => { if (e.status) throw Object.assign(new Error(e.message), { status: e.status, body: { error: e.message, ...(e.extra ?? {}) } }); throw e; };
405
+
382
406
  async function launch({ spec, cpus, mem_gb, limit = null }) {
383
407
  if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id) || !Array.isArray(spec.command) || !spec.command.length) throw Object.assign(new Error("spec.id ([A-Za-z0-9._-], max 128) and spec.command are required"), { status: 400 });
384
408
  let existing = own(spec.id);
385
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
386
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
387
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)
388
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
389
414
  const prio = spec.priority ?? "normal";
390
415
  if (!PRIORITIES.includes(prio)) throw Object.assign(new Error(`spec.priority must be one of ${PRIORITIES.join(", ")}`), { status: 400 });
@@ -410,6 +435,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
410
435
  const floor = floorGb();
411
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 };
412
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
+ }
413
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
414
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 };
415
444
  }
@@ -438,8 +467,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
438
467
  const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, slug: spec.repo?.slug ?? null, repo: slugOf(spec), batch: spec.batch ?? null, cpus, mem_gb, result_file: spec.result_file ?? null, state: "starting", startedAt: now(), finishedAt: null, lease: now(), credToken, docker: withDocker, ...(weighted() || spec.priority ? { priority: prio, ...(reservation ? { reservation } : {}) } : {}) };
439
468
  sb()[spec.id] = rec;
440
469
  store.save();
441
- const cacheKey = String(spec.cache?.key ?? spec.repo?.slug ?? "default").toLowerCase().replace(/[^a-z0-9_.-]/g, "-");
442
- rec.cacheVolume = `cs-cache-${cfg.agent_id ? `${agentId}-` : ""}${cacheKey}`; // an explicit agent_id gives this agent its own volume: a shared one would let its work sweep delete a co-resident agent's worktrees
470
+ rec.cacheVolume = cacheVolumeOf(spec.cache?.key ?? spec.repo?.slug); // an explicit agent_id gives this agent its own volume: a shared one would let its work sweep delete a co-resident agent's worktrees
443
471
  rec.workDir = workDirOf(name);
444
472
  cacheUsed.set(rec.cacheVolume, now());
445
473
  try { await docker.createVolume?.(rec.cacheVolume, [CACHE_LABEL, AGENT]); } catch (e) { log.warn?.(`label ${rec.cacheVolume}: ${String(e.stderr || e.message).slice(0, 200)}`); } // an unlabelled volume still works
@@ -497,7 +525,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
497
525
  return { status: 201, body: view(rec) };
498
526
  }
499
527
 
500
- 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" } : {}) });
501
529
 
502
530
  const warm = makeWarm({ store, sb, own, now, launch, destroy: (id, why) => destroy(id, why), view, log });
503
531
 
@@ -506,7 +534,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
506
534
  const s = await docker.inspect(r.name);
507
535
  if (!s) { r.state = "exited"; r.finishedAt ??= now(); }
508
536
  else if (!s.running && r.state !== "starting") { r.state = "exited"; r.exitCode = s.exitCode; r.finishedAt = Date.parse(s.finishedAt) || now(); }
509
- else if (s.running) r.state = r.diskPaused ? "paused" : "running";
537
+ else if (s.running) r.state = r.diskPaused || r.memPaused ? "paused" : "running";
510
538
  return r;
511
539
  }
512
540
 
@@ -600,7 +628,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
600
628
  for (const v of await ownCacheVolumes()) {
601
629
  if (never.includes(v)) continue;
602
630
  try {
603
- 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 });
604
632
  cacheInfo.set(v, r); cacheErr.delete(`cache sweep:${v}`);
605
633
  if (r.errors?.length) cacheErr.set(`cache sweep:${v}`, `cache sweep ${v}: ${r.errors[0]}`);
606
634
  volumes.push({ name: v, lastUsedMs: Math.max(r.last_used_ms ?? -Infinity, cacheUsed.get(v) ?? -Infinity) });
@@ -682,6 +710,24 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
682
710
  log.error?.(`stopped ${victim.id} (sandbox.disk_pressure): host free ${free} GB < ${hard} GB`);
683
711
  }
684
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
+ }
685
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. */
686
732
  let lastFstrim = -Infinity;
687
733
  async function diskPressure(t) {
@@ -706,10 +752,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
706
752
  const t = now();
707
753
  for (const r of Object.values(sb())) {
708
754
  try { await refresh(r); } catch { /* docker hiccup: judge by lease only */ }
709
- 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;
710
756
  if (why) await destroy(r.id, why);
711
757
  }
712
758
  await hostDiskPressure(t); // #5891
759
+ await hostMemPressure(t); // #5967
713
760
  const known = new Set(Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)]));
714
761
  for (const name of await docker.listLabelled(OWN)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
715
762
  await sampleUsage();
@@ -901,6 +948,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
901
948
 
902
949
  const routes = [
903
950
  [route("GET", "/health"), async () => ({ status: 200, body: { ok: true, ...capacity() } })],
951
+ [route("GET", "/mirrors"), async (_p, _b, url) => ({ status: 200, body: await mirrors.tips({ slug: url.searchParams.get("slug"), cache_key: url.searchParams.get("cache_key"), upload: url.searchParams.get("upload") }).catch(seedFail) })], // #5949
952
+ [route("POST", "/mirrors/seed"), async (_p, body) => { try { return { status: 200, body: body?.finish ? await mirrors.finish(body) : mirrors.chunk(body) }; } catch (e) { return { status: e.status ?? 500, body: { error: e.message, ...(e.extra ?? {}) } }; } }],
904
953
  [route("GET", "/capacity"), async () => ({ status: 200, body: capacity() })],
905
954
  [route("POST", "/sandboxes"), async (_p, body) => { const r = await launch(body ?? {}); if (Number.isInteger(body?.spec?.warm)) warm.replenish().catch((e) => log.warn?.(`warm replenish: ${e.message}`)); return r; }],
906
955
  [route("GET", "/warm"), async () => ({ status: 200, body: { warm: warm.list() } })],
@@ -8,6 +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"];
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. */
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];
11
15
  /** #5881: owner label; the reaper and sweeps touch only containers and volumes carrying their own agent's label. */
12
16
  export const agentLabel = (id) => `computeshare.agent=${id}`;
13
17
  const DAY = 86400000;
@@ -29,6 +33,14 @@ export function planCacheCap(entries, capBytes) {
29
33
  return { delete: out, total, after };
30
34
  }
31
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
+
32
44
  /**
33
45
  * Cache volumes to remove: last use known (`lastUsedMs` a number), older than `idleMs`, no sandbox record references
34
46
  * it and it is not in the never-evict list. `volumes` is [{name, lastUsedMs}].
@@ -42,12 +54,38 @@ const sh = (cmd, args) => { try { return execFileSync(cmd, args, { encoding: "ut
42
54
  const sizeOf = (p) => (Number(sh("du", ["-sk", p]).split(/\s/)[0]) || 0) * 1024;
43
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 }; });
44
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
+
45
83
  /** Runs inside the container. Returns {size_bytes, last_used_ms, removed, errors}. */
46
- 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() } = {}) {
47
85
  const errors = [], removed = [];
48
86
  const rm = (p) => { try { rmSync(p, { recursive: true, force: true }); removed.push(p); } catch (e) { errors.push(`${p}: ${e.message}`); } };
49
87
  const cutoff = now - maxAgeDays * DAY;
50
- for (const d of ["uv", "npm", "pip", "poetry"]) { // package caches: old files out, then the empty dirs
88
+ for (const d of PACKAGE_STORES) { // package caches: old files out, then the empty dirs
51
89
  const dir = join(root, d);
52
90
  if (!existsSync(dir)) continue;
53
91
  sh("find", [dir, "-type", "f", "-mtime", `+${maxAgeDays}`, "-delete"]);
@@ -55,7 +93,8 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ke
55
93
  }
56
94
  const ageOut = (dir, skip = []) => { for (const k of kids(dir)) if (k.mtimeMs < cutoff && !skip.includes(k.path)) rm(k.path); };
57
95
  const dc = join(root, "forge-depcache");
58
- 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
59
98
  if (existsSync(join(root, "env"))) ageOut(join(root, "env"));
60
99
  const ps = join(root, "pnpm-store");
61
100
  if (existsSync(ps)) sh("pnpm", ["store", "prune", "--store-dir", ps]);
@@ -64,13 +103,13 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ke
64
103
  const entries = [];
65
104
  const keepSet = new Set(keep);
66
105
  for (const k of kids(join(root, "work"))) entries.push({ ...k, bytes: sizeOf(k.path), live: keepSet.has(k.path) });
67
- for (const d of ["uv", "npm", "pip", "poetry", "env", "forge-depcache", "forge-depcache/stores"]) for (const k of kids(join(root, d))) if (!k.path.endsWith("/stores")) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
106
+ for (const d of [...PACKAGE_STORES, "env", "forge-depcache", "forge-depcache/stores"]) for (const k of kids(join(root, d))) if (!k.path.endsWith("/stores")) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
68
107
  const plan = planCacheCap(entries, maxGb * 1024 ** 3);
69
108
  for (const p of plan.delete) rm(p);
70
109
  }
71
110
  let last = null;
72
111
  try { const n = Number(readFileSync(join(root, ".last-used"), "utf8").trim()); if (Number.isFinite(n) && n > 0) last = n * 1000; } catch { /* never recorded */ }
73
- 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) };
74
113
  }
75
114
 
76
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
@@ -15,7 +15,7 @@ import { call as httpCall } from "./http.mjs";
15
15
  const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
16
16
  const loadJson = (p) => JSON.parse(readFileSync(p, "utf8"));
17
17
 
18
- const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB --agent-url URL | --outbound | --one-liner] | status [--json] [--account A] | link <user_code> [--account A] | policy <agent> [--cpus N --mem GB --idle-only --pause --resume-policy] | limit <agent> --lanes N|none | pause | resume | uninstall --yes | upgrade [agent] | remove <agent> [--config path]";
18
+ const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB --agent-url URL | --outbound | --one-liner] | status [--json] [--account A] | link <user_code> [--account A] | policy <agent> [--cpus N --mem GB --idle-only --pause --resume-policy] | limit <agent> --lanes N|none | pause | resume | uninstall [--yes] | upgrade [agent] | remove <agent> [--config path]";
19
19
  const HELP_FLAGS = ["--help", "-h"];
20
20
  // Flags each verb accepts: `value` flags consume the next token, `bool` flags stand alone. Anything else dash-prefixed is rejected (#5008).
21
21
  const VERB_FLAGS = {
@@ -26,7 +26,7 @@ const VERB_FLAGS = {
26
26
  policy: { value: ["--config", "--cpus", "--mem"], bool: ["--idle-only", "--no-idle-only", "--pause", "--resume-policy"] },
27
27
  pause: { value: ["--config"], bool: [] },
28
28
  resume: { value: ["--config"], bool: [] },
29
- uninstall: { value: ["--config"], bool: ["--yes"] },
29
+ uninstall: { value: [], bool: ["--yes"] },
30
30
  upgrade: { value: ["--config"], bool: [] },
31
31
  remove: { value: ["--config"], bool: [] },
32
32
  limit: { value: ["--config", "--lanes"], bool: [] },
@@ -69,6 +69,16 @@ export function statusTable(agents) {
69
69
  }
70
70
 
71
71
  /** The `forgedock pool` verbs (and the `computeshare` script). Throws on usage or router errors; `deps` injects the HTTP client and config. */
72
+ /** #5901: one line per agent cache volume with each repo's depcache size, from the router's /agents view. */
73
+ export function depcacheLines(agents) {
74
+ const out = [];
75
+ for (const a of agents ?? []) for (const [vol, v] of Object.entries(a.cache_volumes ?? {})) {
76
+ const repos = Object.entries(v.depcache_gb ?? {}).map(([k, gb]) => `${k} ${gb} GB`).join(", ");
77
+ if (repos) out.push(`${a.name} ${vol}: depcache ${repos}`);
78
+ }
79
+ return out;
80
+ }
81
+
72
82
  export async function runPoolCli(argv, deps = {}) {
73
83
  const [cmd, ...rest] = argv;
74
84
  const call = deps.call ?? httpCall;
@@ -117,6 +127,7 @@ export async function runPoolCli(argv, deps = {}) {
117
127
  if (rest.includes("--json")) console.log(JSON.stringify(r.data, null, 2));
118
128
  else if (!r.ok) throw new Error(`router refused: HTTP ${r.status} ${JSON.stringify(r.data)}`);
119
129
  else console.log(statusTable(r.data?.agents ?? []));
130
+ if (!rest.includes("--json") && r.ok) for (const l of depcacheLines(r.data?.agents)) console.log(l); // #5901
120
131
  // #5735: lane sandboxes used/ceiling per agent, and the lane total across all batches
121
132
  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
133
  if (Number.isInteger(r.data?.remote_lanes)) console.log(`remote lanes across batches: ${r.data.remote_lanes}`);
@@ -124,6 +135,7 @@ export async function runPoolCli(argv, deps = {}) {
124
135
  if (a.transport) console.log(`${a.name}: transport ${a.transport}`); // #5882
125
136
  const n = a.net; // #5923
126
137
  if (n?.mirrored) console.log(`${a.name}: net mirrored, port range ${n.port_range ?? "?"}, NAT pin ${n.nat_pin ? "present" : "MISSING"}${n.degraded ? " DEGRADED" : ""}`);
138
+ 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
139
  if (!Number.isFinite(a.host_disk_free_gb)) continue;
128
140
  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
141
  }
@@ -178,13 +190,18 @@ export async function runPoolCli(argv, deps = {}) {
178
190
  }
179
191
  case "uninstall": {
180
192
  // #5885: the owner removes this box's agent. Destructive, so it needs --yes; running lanes are not waited for.
181
- const win = (deps.platform ?? process.platform) === "win32";
193
+ // The shipped per-OS scripts (#5883) own the teardown at fixed install paths; no path from the command line reaches a delete, and
194
+ // without --yes the script's own --dry-run is the preview, so what is shown is what --yes does.
195
+ const platform = deps.platform ?? process.platform;
182
196
  const run = deps.spawn ?? spawnSync;
183
- if (!rest.includes("--yes")) { console.log(win ? "would run pool/install/uninstall-agent.ps1 (removes the keep-alive task, firewall rules and the computeshare WSL distro)" : "would stop and disable computeshare-agent, delete its systemd unit and /etc/computeshare"); console.log("re-run with --yes to proceed"); break; }
184
- const steps = win
185
- ? [["powershell", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", join(repoRoot, "pool", "install", "uninstall-agent.ps1")]]]
186
- : [["systemctl", ["disable", "--now", "computeshare-agent"]], ["rm", ["-f", "/etc/systemd/system/computeshare-agent.service"]], ["systemctl", ["daemon-reload"]], ["rm", ["-rf", flag("config") ? dirname(flag("config")) : "/etc/computeshare"]]];
197
+ const dir = join(repoRoot, "pool", "install");
198
+ const dry = !rest.includes("--yes");
199
+ const steps = platform === "win32"
200
+ ? (dry ? [] : [["powershell", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", join(dir, "uninstall-agent.ps1")]]])
201
+ : [["bash", [join(dir, platform === "darwin" ? "uninstall-agent-macos.sh" : "uninstall-agent-linux.sh"), ...(dry ? ["--dry-run"] : [])]]];
202
+ if (dry && platform === "win32") console.log("would run pool/install/uninstall-agent.ps1 (removes the keep-alive task, firewall rules and the computeshare WSL distro)");
187
203
  for (const [bin, args] of steps) { const r = run(bin, args, { stdio: "inherit" }); if (r.status !== 0) throw new Error(`${bin} ${args[0]} exited ${r.status}`); }
204
+ if (dry) { console.log("re-run with --yes to proceed"); break; }
188
205
  console.log("agent uninstalled from this box. Remove it from the router with: forgedock pool remove <agent>");
189
206
  break;
190
207
  }
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { execFile } from "node:child_process";
4
4
  import { readFileSync } from "node:fs";
5
+ import { PACKAGE_STORES } from "./cache-sweep.mjs";
5
6
 
6
7
  /** #5757: work-dir and cache sweeps walk big trees (node_modules): 10 min, not the 120 s of a small rm. */
7
8
  export const SWEEP_TIMEOUT_MS = 10 * 60000;
@@ -64,7 +65,7 @@ export const dockerCli = {
64
65
  /** #5891: dangling images (rebuildable) only; never a tagged or in-use one. */
65
66
  async pruneImages() { return docker(["image", "prune", "-f"], { timeoutMs: 10 * 60000 }); },
66
67
  /** #5891: package-manager caches inside a running sandbox (rebuildable); the worktree and lane state are untouched. Best effort. */
67
- async pruneCaches(name) { try { await docker(["exec", name, "sh", "-c", "rm -rf \"$HOME\"/.npm/_cacache \"$HOME\"/.cache/pip \"$HOME\"/.cache/yarn \"$HOME\"/.cache/pnpm /root/.npm/_cacache /root/.cache/pip 2>/dev/null; true"], { timeoutMs: 120000 }); } catch (e) { if (!/No such container|is not running|is paused/i.test(e.stderr ?? "")) throw e; } },
68
+ async pruneCaches(name) { try { await docker(["exec", name, "sh", "-c", `rm -rf ${PACKAGE_STORES.map((d) => `/cache/${d}`).join(" ")} 2>/dev/null; true`], { timeoutMs: 120000 }); } catch (e) { if (!/No such container|is not running|is paused/i.test(e.stderr ?? "")) throw e; } },
68
69
  /** #5884: removes this agent's stopped containers and dangling images only (`label` carries the agent id, #5881). */
69
70
  async containerPrune(label) { return docker(["container", "prune", "-f", ...[].concat(label).flatMap((l) => ["--filter", `label=${l}`])], { timeoutMs: 120000 }); },
70
71
  async imagePrune(label) { return docker(["image", "prune", "-f", ...[].concat(label).flatMap((l) => ["--filter", `label=${l}`])], { timeoutMs: 120000 }); },
@@ -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}}';