forgedock 1.62.0 → 1.64.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 (87) hide show
  1. package/bin/config-schema.mjs +5 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +109 -21
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +9 -1
  10. package/bin/lean/batch.test.mjs +74 -7
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/conformance.e2e.test.mjs +32 -6
  14. package/bin/lean/conformance.mjs +57 -13
  15. package/bin/lean/conformance.test.mjs +93 -1
  16. package/bin/lean/execution.mjs +24 -12
  17. package/bin/lean/execution.test.mjs +59 -9
  18. package/bin/lean/forgedock-lane-workflow.test.mjs +62 -2
  19. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  20. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  21. package/bin/lean/issuewatch.mjs +3 -0
  22. package/bin/lean/lanecheck.test.mjs +13 -1
  23. package/bin/lean/lean.mjs +214 -32
  24. package/bin/lean/lean.test.mjs +406 -21
  25. package/bin/lean/live-execution.mjs +25 -0
  26. package/bin/lean/live-execution.test.mjs +35 -1
  27. package/bin/lean/merged-park.mjs +76 -0
  28. package/bin/lean/merged-park.test.mjs +64 -0
  29. package/bin/lean/mergetrain.mjs +357 -0
  30. package/bin/lean/mergetrain.test.mjs +348 -0
  31. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  32. package/bin/lean/orchestrate-stacking.test.mjs +144 -0
  33. package/bin/lean/orchestrate-train.test.mjs +130 -0
  34. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  35. package/bin/lean/orchestrate.mjs +234 -17
  36. package/bin/lean/prompts.mjs +4 -3
  37. package/bin/lean/release-review.mjs +8 -1
  38. package/bin/lean/release-review.test.mjs +42 -2
  39. package/bin/lean/release-status.test.mjs +53 -1
  40. package/bin/lean/release.mjs +6 -3
  41. package/bin/lean/render.mjs +6 -1
  42. package/bin/lean/run-issue-placement.test.mjs +27 -3
  43. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  44. package/bin/lean/sandbox-remote.mjs +12 -2
  45. package/bin/lean/sched.mjs +19 -2
  46. package/bin/lean/sched.test.mjs +33 -1
  47. package/bin/lean/schedd-health.mjs +2 -1
  48. package/bin/lean/schedd-health.test.mjs +7 -0
  49. package/bin/lean/schedd.mjs +55 -7
  50. package/bin/lean/schedd.test.mjs +42 -1
  51. package/bin/lean/stacking.mjs +140 -0
  52. package/bin/lean/stacking.test.mjs +98 -0
  53. package/bin/lean/statuscomment.mjs +14 -8
  54. package/bin/lean/statuscomment.test.mjs +18 -1
  55. package/bin/lean/validate-catalog.mjs +1 -1
  56. package/bin/lean/validate-catalog.test.mjs +3 -0
  57. package/bin/lean/worktree.mjs +8 -3
  58. package/bin/lean/worktree.test.mjs +18 -0
  59. package/bin/pool/agent.mjs +325 -46
  60. package/bin/pool/cache-sweep.mjs +2 -0
  61. package/bin/pool/cli.mjs +120 -6
  62. package/bin/pool/disk.mjs +43 -0
  63. package/bin/pool/docker.mjs +21 -5
  64. package/bin/pool/health.mjs +95 -0
  65. package/bin/pool/router.mjs +274 -27
  66. package/bin/runner.mjs +3 -1
  67. package/bin/stats/chains.mjs +101 -0
  68. package/bin/stats/chains.test.mjs +53 -0
  69. package/bin/stats/efficiency.mjs +7 -6
  70. package/bin/stats/efficiency.test.mjs +48 -7
  71. package/bin/stats/index.mjs +11 -3
  72. package/bin/stats/stats.test.mjs +9 -0
  73. package/docs/CONFIG.md +23 -1
  74. package/docs/OUTCOME-CODES.md +4 -0
  75. package/package.json +1 -1
  76. package/pool/README.md +10 -0
  77. package/pool/image/Dockerfile +2 -1
  78. package/pool/image/entrypoint.sh +6 -6
  79. package/pool/image/mirror.sh +71 -0
  80. package/pool/install/install-agent-linux.sh +57 -5
  81. package/pool/install/install-agent-macos.sh +148 -0
  82. package/pool/install/install-agent.ps1 +11 -0
  83. package/pool/install/install-agent.sh +59 -7
  84. package/pool/install/uninstall-agent-linux.sh +75 -0
  85. package/pool/install/uninstall-agent-macos.sh +60 -0
  86. package/pool/install/uninstall-agent.ps1 +1 -0
  87. package/scripts/transition-label.sh +11 -0
@@ -7,15 +7,16 @@ import { randomBytes } from "node:crypto";
7
7
  import { execFile, spawn } from "node:child_process";
8
8
  import { promisify } from "node:util";
9
9
  import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, statfsSync, lstatSync, writeFileSync } from "node:fs";
10
- import { basename, join } from "node:path";
10
+ import { basename, dirname, join } from "node:path";
11
11
  import { cpus, hostname } from "node:os";
12
12
  import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
13
13
  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 } from "./health.mjs";
18
- import { planIdleEviction, CACHE_LABEL } from "./cache-sweep.mjs";
17
+ import { hostDiskFree, ensureNatPin, netState } from "./health.mjs";
18
+ import { laneDiskUsedGb, planDiskCap, fstrimDue, runFstrim } from "./disk.mjs";
19
+ import { planIdleEviction, CACHE_LABEL, agentLabel } from "./cache-sweep.mjs";
19
20
 
20
21
  const LABEL = "computeshare=1";
21
22
  const LOG_CHUNK = 256 * 1024;
@@ -68,10 +69,10 @@ export const ENV_ENSURE_GAP_MS = 5 * 60000;
68
69
  * stages `ready` hardlink copies and collects old snapshots. It writes only under /cache/env, on the same volume as the
69
70
  * lane worktrees (/cache/work), so a lane claims a staged copy with a rename. Pure.
70
71
  */
71
- export function envEnsureArgs({ volume, image, slug, ref = null, laneTools = [], snapshots = {}, net = [], cpus = 2, mem_gb = 4 }) {
72
+ export function envEnsureArgs({ volume, image, slug, ref = null, laneTools = [], snapshots = {}, net = [], cpus = 2, mem_gb = 4, agent = null }) {
72
73
  const int = (v, d) => (Number.isInteger(v) && v >= 0 ? v : d);
73
74
  return [
74
- "--rm", "--name", `cs-envbuild-${volume.replace(/^cs-cache-/, "")}`.slice(0, 120), "--label", "computeshare.env=1",
75
+ "--rm", "--name", `cs-envbuild-${volume.replace(/^cs-cache-/, "")}`.slice(0, 120), "--label", "computeshare.env=1", ...(agent ? ["--label", agent] : []),
75
76
  "--cpus", String(cpus), "--memory", `${Math.round(mem_gb * 1024)}m`, ...net, "-v", `${volume}:/cache`,
76
77
  "-e", "FORGE_ENV_ROOT=/cache/env", "-e", `FORGE_ENV_IMAGE=${image}`, "-e", "FORGE_DEPCACHE_ROOT=/cache/forge-depcache", "-e", "npm_config_store_dir=/cache/pnpm-store",
77
78
  "--entrypoint", "forgedock", image, "env", "ensure", "--mirror", `/cache/git/${String(slug).replace(/\//g, "_")}.git`, ...(ref ? ["--ref", String(ref)] : []),
@@ -85,21 +86,44 @@ const envLine = (k, v) => `${k}=${String(v).replace(/\r?\n/g, " ")}`;
85
86
  * Host agent: runs each sandbox as one docker container inside a fixed reservation (allow_cpus / allow_mem_gb).
86
87
  * A sandbox lives only while its lease is renewed; the reaper removes expired, over-age and orphaned containers.
87
88
  */
88
- export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null } = {}) {
89
+ /** #5919: a build/upgrade failure as text, keeping its END (the failing step's own output), not the Dockerfile echo at its head. */
90
+ export function upgradeErrorText(e, max = 2000) {
91
+ const t = String(e?.stderr || e?.stdout || e?.message || e || "").trim();
92
+ return t.length <= max ? t : `…${t.slice(t.length - max + 1)}`;
93
+ }
94
+ /** #5919: a build failure that a retry can fix (network, registry or DNS), as opposed to a bad Dockerfile or version pin. */
95
+ export const NETWORK_BUILD_RE = /ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENOTFOUND|socket hang up|network timeout|timed out|Could not resolve host|Connection reset|TLS handshake|i\/o timeout|unexpected EOF|curl: \((?:6|7|18|28|35|52|56)\)|npm (?:ERR!|error) (?:code|network) (?:ETIMEDOUT|ECONNRESET|EAI_AGAIN|ENOTFOUND)|503 Service Unavailable|502 Bad Gateway/i;
96
+ /** #5919: run `build`; one retry after `delayMs` when the first failure looks like a network error. */
97
+ export async function buildWithRetry(build, { sleep = (ms) => new Promise((r) => setTimeout(r, ms)), delayMs = 30000, log = null } = {}) {
98
+ try { return await build(); } catch (e) {
99
+ if (!NETWORK_BUILD_RE.test(upgradeErrorText(e, 20000))) throw e;
100
+ log?.warn?.(`lane image build failed on a network error; retrying once: ${upgradeErrorText(e, 300)}`);
101
+ await sleep(delayMs);
102
+ return build();
103
+ }
104
+ }
105
+
106
+ export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, net = netState, vm = vmSize, trim = runFstrim } = {}) {
89
107
  const stateDir = cfg.state_dir;
90
108
  const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
91
109
  const sb = () => store.data.sandboxes;
110
+ const activeRecs = () => Object.values(sb()).filter((s) => s.state !== "exited");
92
111
  // Sandbox ids come from requests: read own keys only, so "__proto__" or "constructor" never resolves to an inherited member (#4566).
93
112
  const own = (id) => (typeof id === "string" && Object.hasOwn(sb(), id) ? sb()[id] : warm.byAlias(id)); // #4912: a claimed warm sandbox also answers to its lane id
94
113
  const leaseTtlMs = (cfg.lease_ttl_s ?? 600) * 1000;
95
114
  const maxLifeMs = (cfg.max_lifetime_s ?? 6 * 3600) * 1000;
96
115
  const keepExitedMs = (cfg.keep_exited_s ?? 2 * 3600) * 1000;
116
+ const keepPressureMs = (cfg.keep_disk_pressure_s ?? 24 * 3600) * 1000; // #5891: a disk-pressure stop keeps its worktree long enough for the requeue
97
117
  const running = versionOf(cfg.code_root ?? repoRoot);
98
118
  // The lane image tracks the installed ForgeDock version; only an explicit non-legacy cfg.image overrides it.
99
119
  const image = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(running.version);
100
120
  const upgrade = { state: "idle", error: null };
101
121
  const prepull = { error: null };
102
122
  const dindImage = cfg.dind_image ?? "docker:27.5.1-dind";
123
+ // #5881: every container/volume this agent creates carries its label; reap and the sweeps list only by it, so a co-resident agent or foreign containers are never touched.
124
+ const agentId = String(cfg.agent_id ?? cfg.name ?? hostname()).toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 60);
125
+ const AGENT = agentLabel(agentId);
126
+ const OWN = [LABEL, AGENT];
103
127
  /** Images a sandbox may need are pulled ahead of time, never inside a launch request (which has a short timeout). */
104
128
  async function prepullImages() {
105
129
  if (await docker.hasImage?.(dindImage)) { prepull.error = null; return; }
@@ -119,6 +143,34 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
119
143
  log.warn?.(`prepull ${dindImage}: ${prepull.error}`);
120
144
  } finally { rmSync(file, { force: true }); }
121
145
  }
146
+ // #5858: advertised capacity is the configured allowance clamped to the measured VM minus a host reserve, less what
147
+ // non-sandbox containers use; admission projects each repo's measured per-sandbox peak, not only the configured slice.
148
+ const r1 = (x) => Math.round(x * 10) / 10, r2 = (x) => Math.round(x * 100) / 100;
149
+ let clampWarned = false;
150
+ let coTenant = { cpus: 0, mem_gb: 0 };
151
+ function effectiveCapacity() {
152
+ let v = {}; try { v = vm() ?? {}; } catch { /* unknown VM: no clamp */ }
153
+ const reserve = cfg.host_reserve_mem_gb ?? Math.max(1, (v.mem_gb ?? 0) * 0.1);
154
+ const cpusEff = v.cpus > 0 ? Math.min(cfg.allow_cpus, v.cpus) : cfg.allow_cpus;
155
+ const memEff = v.mem_gb > 0 ? Math.min(cfg.allow_mem_gb, Math.max(1, r1(v.mem_gb - reserve))) : cfg.allow_mem_gb;
156
+ const clamped = cpusEff < cfg.allow_cpus || memEff < cfg.allow_mem_gb;
157
+ if (clamped && !clampWarned) { clampWarned = true; log.warn?.(`configured capacity ${cfg.allow_cpus} cpus / ${cfg.allow_mem_gb} GB exceeds the VM (${v.cpus} cpus / ${v.mem_gb} GB minus ${r1(reserve)} GB reserve); advertising ${cpusEff} cpus / ${memEff} GB`); }
158
+ return { cpus: cpusEff, mem: memEff, clamped, vm: v };
159
+ }
160
+ const slugOf = (spec) => (spec?.repo?.slug ? String(spec.repo.slug).toLowerCase() : null);
161
+ let histRows = null;
162
+ function usageRows() {
163
+ if (histRows) return histRows;
164
+ try { histRows = readFileSync(join(stateDir, "usage-history.jsonl"), "utf8").split("\n").filter(Boolean).slice(-500).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } catch { histRows = []; }
165
+ return histRows;
166
+ }
167
+ const pct = (xs, p) => { const a = [...xs].sort((x, y) => x - y); return a[Math.min(a.length - 1, Math.ceil(p * a.length) - 1)]; };
168
+ /** Per-sandbox projection for a repo: p90 mem_peak_gb / p75 cpu_avg over the last N finished sandboxes, never below the slice. */
169
+ function estimateFor(repo, slice) {
170
+ const rows = repo ? usageRows().filter((x) => x.repo === repo && Number.isFinite(x.mem_peak_gb) && Number.isFinite(x.cpu_avg)).slice(-(cfg.estimate_window ?? 20)) : [];
171
+ if (rows.length < (cfg.estimate_min_samples ?? 3)) return { cpus: slice.cpus, mem: slice.mem, samples: rows.length };
172
+ return { cpus: Math.max(slice.cpus, pct(rows.map((x) => x.cpu_avg), 0.75)), mem: Math.max(slice.mem, pct(rows.map((x) => x.mem_peak_gb), 0.9)), samples: rows.length };
173
+ }
122
174
  const used = () => Object.values(sb()).filter((s) => s.state !== "exited").reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
123
175
  // #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
124
176
  let diskCache = { at: 0, mb: {} };
@@ -126,7 +178,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
126
178
  let lastCachePrune = -Infinity;
127
179
  // #5757: cache volume hygiene state: per-volume sweep error/size/last use (last use also from launches in this process).
128
180
  let lastCacheSweep = -Infinity;
129
- const cacheErr = new Map(), cacheInfo = new Map(), cacheUsed = new Map();
181
+ 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)
130
182
  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); };
131
183
  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); };
132
184
  function diskView() {
@@ -134,7 +186,13 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
134
186
  try { const f = statfsSync(stateDir); out.disk_free_gb = Math.round((Number(f.bavail) * Number(f.bsize)) / 107374182.4) / 10; } catch { /* unknown */ }
135
187
  if (Date.now() - diskCache.at > 60000) {
136
188
  const mb = {};
137
- for (const r of Object.values(sb())) if (r.state !== "exited") mb[r.id] = dirMb(join(stateDir, "sandboxes", safeName(r.id)));
189
+ for (const r of Object.values(sb())) if (r.state !== "exited") {
190
+ mb[r.id] = dirMb(join(stateDir, "sandboxes", safeName(r.id)));
191
+ // #5891: peak size (feeds the repo's p90 reservation) and growth rate (picks the sandbox to pause)
192
+ r.diskPeakMb = Math.max(r.diskPeakMb ?? 0, mb[r.id]);
193
+ if (r.diskPrev && now() > r.diskPrev.at) r.growthMbH = Math.round(((mb[r.id] - r.diskPrev.mb) / ((now() - r.diskPrev.at) / 3600000)));
194
+ r.diskPrev = { at: now(), mb: mb[r.id] };
195
+ }
138
196
  diskCache = { at: Date.now(), mb };
139
197
  }
140
198
  out.sandbox_disk_mb = diskCache.mb;
@@ -146,12 +204,43 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
146
204
  if (now() - hostDiskCache.at > 60000) hostDiskCache = { at: now(), v: hostDiskFree({ path: cfg.host_disk_path ?? null }) };
147
205
  return hostDiskCache.v;
148
206
  });
149
- /** Under the floor now, or once the running sandboxes plus the new one grow the vhdx by sandbox_disk_growth_gb each. */
150
- const hostDiskLow = (free, active) => { const floor = cfg.min_host_disk_free_gb ?? 25; return free < floor || free - (cfg.sandbox_disk_growth_gb ?? 3.5) * (active + 1) < floor; };
151
- function hostDiskView(active) {
207
+ // #5891: disk is a reserved resource. A lane reserves the p90 of its repo's measured peak sandbox_disk_mb (fallback sandbox_disk_growth_gb);
208
+ // admission needs host free minus every reservation to stay above the floor. Host free already contains the current use.
209
+ const floorGb = () => cfg.host_disk_floor_gb ?? cfg.min_host_disk_free_gb ?? 25;
210
+ const hist = () => (store.data.disk_hist ??= {});
211
+ const reservationGb = (slug) => {
212
+ const xs = [...(hist()[slug] ?? [])].sort((a, b) => a - b);
213
+ return xs.length >= (cfg.disk_min_samples ?? 3) ? Math.max(0.1, xs[Math.min(xs.length - 1, Math.ceil(xs.length * 0.9) - 1)] / 1024) : (cfg.sandbox_disk_growth_gb ?? 3.5);
214
+ };
215
+ const diskPaused = () => activeRecs().some((r) => r.diskPaused);
216
+ const hostDiskLow = (free, active, slug = null) => free < floorGb() || diskPaused() || free - (activeRecs().reduce((a, r) => a + reservationGb(r.slug), 0) + reservationGb(slug)) < floorGb();
217
+ const hostSamples = []; // [{t, gb}] over the last 3h: the drive's growth rate and time-to-full
218
+ function noteHostDisk(gb) {
219
+ const t = now();
220
+ if (hostSamples.length && hostSamples[hostSamples.length - 1].t === t) hostSamples.pop();
221
+ hostSamples.push({ t, gb });
222
+ while (hostSamples.length > 2 && t - hostSamples[0].t > 3 * 3600000) hostSamples.shift();
223
+ }
224
+ /** GB/h the host drive shrinks (negative = freeing), or null until two samples at least a minute apart exist. */
225
+ function hostGrowthPerH() {
226
+ const a = hostSamples[0], b = hostSamples[hostSamples.length - 1];
227
+ return a && b && b.t - a.t >= 60000 ? Math.round(((a.gb - b.gb) / ((b.t - a.t) / 3600000)) * 10) / 10 : null;
228
+ }
229
+ let netCache = { at: -Infinity, v: null };
230
+ const readNet = () => { if (now() - netCache.at > 60000) netCache = { at: now(), v: net() }; return netCache.v; };
231
+ // #5884: lane disk cap (cfg.lane_disk_cap_gb, unset = off, nothing added to /capacity): sandbox dirs plus cache volumes.
232
+ function laneDiskView() {
233
+ if (!(Number(cfg.lane_disk_cap_gb) > 0)) return {};
234
+ const used = laneDiskUsedGb({ sandboxMb: diskView().sandbox_disk_mb, cacheVolumes: Object.fromEntries(cacheInfo) });
235
+ const state = planDiskCap({ usedGb: used, capGb: cfg.lane_disk_cap_gb, pruneAtPct: cfg.disk_prune_at_pct });
236
+ return { lane_disk_used_gb: used, lane_disk_cap_gb: Number(cfg.lane_disk_cap_gb), disk_capped: state === "full" };
237
+ }
238
+ function hostDiskView(active, slug = null) {
152
239
  let hd = null; try { hd = readHostDisk(); } catch { hd = null; }
153
240
  if (!hd || !Number.isFinite(hd.gb)) return {};
154
- return { host_disk_free_gb: hd.gb, host_disk_low: hostDiskLow(hd.gb, active) };
241
+ noteHostDisk(hd.gb);
242
+ const g = hostGrowthPerH();
243
+ return { host_disk_free_gb: hd.gb, host_disk_low: hostDiskLow(hd.gb, active, slug), ...(g === null ? {} : { host_disk_growth_gb_per_h: g, ...(g > 0 ? { host_disk_full_in_h: Math.round((hd.gb / g) * 10) / 10 } : {}) }), ...(diskPaused() ? { disk_paused: activeRecs().filter((r) => r.diskPaused).length } : {}) };
155
244
  }
156
245
  // #5856: priority classes. `reserved` sandboxes are admitted up to a named reservation (cfg.reservations) and may reclaim
157
246
  // capacity from `borrow` ones (throttle first, then SIGTERM so the lane checkpoints and reports run.interrupted);
@@ -159,7 +248,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
159
248
  const PRIORITIES = ["reserved", "normal", "borrow"];
160
249
  const reservations = () => (Array.isArray(cfg.reservations) ? cfg.reservations.filter((r) => r && typeof r.name === "string" && r.cpus > 0 && r.mem_gb > 0) : []);
161
250
  const prioOf = (r) => r.priority ?? "normal";
162
- const activeRecs = () => Object.values(sb()).filter((s) => s.state !== "exited");
251
+ const projectedUse = () => activeRecs().reduce((a, r) => { const e = estimateFor(r.repo ?? null, { cpus: r.cpus, mem: r.mem_gb }); return { cpus: a.cpus + Math.max(r.cpus, e.cpus), mem: a.mem + Math.max(r.mem_gb, e.mem) }; }, { cpus: 0, mem: 0 });
163
252
  const sumRecs = (rs) => rs.reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
164
253
  const weighted = () => reservations().length > 0 || Boolean(cfg.idle_only);
165
254
  const SHARES = () => ({ reserved: 4096, normal: 1024, borrow: 128, throttled: 2, ...(cfg.cpu_shares ?? {}) });
@@ -168,8 +257,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
168
257
  const act = activeRecs(), rs = reservations();
169
258
  const tot = rs.reduce((a, r) => ({ cpus: a.cpus + r.cpus, mem: a.mem + r.mem_gb }), { cpus: 0, mem: 0 });
170
259
  const u = sumRecs(act), nonRes = sumRecs(act.filter((s) => prioOf(s) !== "reserved"));
171
- const free = { cpus: cfg.allow_cpus - u.cpus, mem: cfg.allow_mem_gb - u.mem };
172
- return { act, rs, tot, free, unreserved: { cpus: Math.max(0, Math.min(free.cpus, cfg.allow_cpus - tot.cpus - nonRes.cpus)), mem: Math.max(0, Math.min(free.mem, cfg.allow_mem_gb - tot.mem - nonRes.mem)) } };
260
+ const e = effectiveCapacity();
261
+ const free = { cpus: e.cpus - u.cpus - coTenant.cpus, mem: e.mem - u.mem - coTenant.mem_gb };
262
+ return { act, rs, tot, free, unreserved: { cpus: Math.max(0, Math.min(free.cpus, e.cpus - tot.cpus - nonRes.cpus)), mem: Math.max(0, Math.min(free.mem, e.mem - tot.mem - nonRes.mem)) } };
173
263
  }
174
264
  /** Owner load per core with this agent's own sandboxes subtracted (the box's primary workload), or null when unknown. */
175
265
  function ownerLoad(h) {
@@ -188,6 +278,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
188
278
  }
189
279
  // Throttle = low cpu weight + a halved soft memory limit (`--memory-reservation`: under host memory pressure the kernel reclaims from containers over it first; the docker CLI has no memory.high).
190
280
  const throttle = async (r, shares) => { const memMb = Math.round(r.mem_gb * (shares === SHARES().throttled ? 512 : 1024)); for (const n of r.docker ? [r.name, dindName(r.name)] : [r.name]) { try { await docker.update?.(n, { cpuShares: shares, memoryReservationMb: memMb }); } catch (e) { log.warn?.(`throttle ${n}: ${String(e.stderr || e.message).slice(0, 160)}`); } } r.throttled = shares === SHARES().throttled; };
281
+ let lastDrain = null; // #5885: the most recent drain, for capacity().last_drain
191
282
  /** SIGTERM (the lane checkpoints and reports run.interrupted), wait out the grace, then SIGKILL; the router/dispatcher reschedules the lane. */
192
283
  async function drainOne(r, why) {
193
284
  for (const n of r.docker ? [r.name, dindName(r.name)] : [r.name]) { try { await docker.kill(n, "TERM"); } catch { /* gone */ } }
@@ -195,6 +286,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
195
286
  try { await docker.kill(r.name, "KILL"); } catch { /* already exited */ }
196
287
  if (r.docker) { try { await docker.remove(dindName(r.name)); } catch { /* destroy retries */ } }
197
288
  r.state = "exited"; r.finishedAt = now(); r.drained = why;
289
+ lastDrain = { reason: why, at: new Date(now()).toISOString(), sandbox: r.id }; // #5885: shown by `pool status`
198
290
  log.info?.(`drained borrowed sandbox ${r.id} (${why})`);
199
291
  }
200
292
  /** Admission by class: `{ victims }` (borrow sandboxes to reclaim, reserved only) or `{ refuse }` (a 503/400 body). */
@@ -219,6 +311,42 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
219
311
  }
220
312
  return needC > 0 || needM > 0 ? { refuse: { status: 503 } } : { victims };
221
313
  }
314
+ /** #5885: why borrowed lanes are throttled or drained (weighted agents only, like priorityView). */
315
+ function throttleView(h) {
316
+ if (!weighted()) return {};
317
+ return { idle_gate: notIdle(h), throttled: activeRecs().filter((r) => r.throttled).length, last_drain: lastDrain };
318
+ }
319
+ /** #5885: the owner's own pause, distinct from the resize drain's cfg.paused; a file beside the agent config keeps it across restarts. */
320
+ const ownerPauseFile = join(cfg.config_path ? dirname(cfg.config_path) : stateDir, "owner-paused");
321
+ let ownerPaused = existsSync(ownerPauseFile);
322
+ function setOwnerPause(on) {
323
+ if (on) writeFileSync(ownerPauseFile, `${new Date(now()).toISOString()}\n`, { mode: 0o600 });
324
+ else rmSync(ownerPauseFile, { force: true });
325
+ ownerPaused = on;
326
+ log.info?.(`owner ${on ? "paused" : "resumed"} this agent`);
327
+ return { status: 200, body: { ok: true, owner_paused: on, active: capacity().active } };
328
+ }
329
+ /** #5886: a router-pushed policy (allowlisted keys, persisted beside the agent config). Its `paused` is separate from the owner's pause: the router can set or clear only its own, never the owner's. */
330
+ let policyPaused = Boolean(cfg.policy_paused);
331
+ function applyPolicy(body) {
332
+ const p = body && typeof body === "object" ? body : {}, int = (v, lo, hi) => (Number.isInteger(v) && v >= lo && v <= hi);
333
+ if ((p.cpus !== undefined && !int(p.cpus, 1, 256)) || (p.mem_gb !== undefined && !int(p.mem_gb, 1, 1024)) || (p.idle_only !== undefined && typeof p.idle_only !== "boolean") || (p.paused !== undefined && typeof p.paused !== "boolean")
334
+ || (p.floors !== undefined && !(p.floors && typeof p.floors === "object" && Object.keys(p.floors).every((k) => k === "host_disk_gb" && Number.isFinite(p.floors[k]) && p.floors[k] >= 0)))) return { status: 400, body: { error: "invalid policy" } };
335
+ const set = {};
336
+ if (p.cpus !== undefined) set.allow_cpus = p.cpus;
337
+ if (p.mem_gb !== undefined) set.allow_mem_gb = p.mem_gb;
338
+ if (p.idle_only !== undefined) set.idle_only = p.idle_only;
339
+ if (p.floors?.host_disk_gb !== undefined) set.host_disk_floor_gb = p.floors.host_disk_gb;
340
+ if (p.paused !== undefined) set.policy_paused = p.paused;
341
+ if (cfg.config_path) {
342
+ try { const c = JSON.parse(readFileSync(cfg.config_path, "utf8")); writeFileSync(cfg.config_path, JSON.stringify({ ...c, ...set }, null, 2), { mode: 0o600 }); }
343
+ catch (e) { log.warn?.(`policy not persisted: ${e.message}`); }
344
+ }
345
+ Object.assign(cfg, set);
346
+ if (p.paused !== undefined) policyPaused = p.paused;
347
+ log.info?.(`policy applied: ${Object.keys(set).join(", ") || "none"}`);
348
+ return { status: 200, body: { ok: true, applied: Object.keys(p), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused } };
349
+ }
222
350
  /** #5856: reserved vs borrowable headroom for the router (only when reservations or idle_only are configured). */
223
351
  function priorityView() {
224
352
  if (!weighted()) return {};
@@ -229,7 +357,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
229
357
  function capacity() {
230
358
  const u = used();
231
359
  const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
232
- return { host: cfg.name ?? hostname(), ...running, vm: vmSize(), ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(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: cfg.allow_cpus, mem_total_gb: cfg.allow_mem_gb, cpus_free: cfg.allow_cpus - u.cpus, mem_free_gb: cfg.allow_mem_gb - u.mem, active, ...priorityView(), ...diskView(), ...hostDiskView(active), paused: Boolean(cfg.paused), live: live(cfg), usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
360
+ const e = effectiveCapacity();
361
+ 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 }])) };
233
363
  }
234
364
 
235
365
  /** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
@@ -242,7 +372,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
242
372
  function ensureEnv({ volume, spec, net }) {
243
373
  if (now() - (envEnsured.get(volume) ?? -Infinity) < ENV_ENSURE_GAP_MS) return null;
244
374
  envEnsured.set(volume, now());
245
- const args = envEnsureArgs({ volume, image: envImageOf(spec), slug: spec.repo.slug, ref: spec.repo.ref ?? null, laneTools: spec.lane_tools ?? [], snapshots: spec.env_snapshots, net, cpus: cfg.env_build_cpus ?? 2, mem_gb: cfg.env_build_mem_gb ?? 4 });
375
+ const args = envEnsureArgs({ volume, image: envImageOf(spec), slug: spec.repo.slug, ref: spec.repo.ref ?? null, laneTools: spec.lane_tools ?? [], snapshots: spec.env_snapshots, net, cpus: cfg.env_build_cpus ?? 2, mem_gb: cfg.env_build_mem_gb ?? 4, agent: AGENT });
246
376
  return Promise.resolve().then(() => docker.run(args)).then(() => log.info?.(`env snapshot helper started for ${spec.repo.slug}`), (e) => log.warn?.(`env snapshot helper: ${String(e.stderr || e.message).slice(0, 200)}`));
247
377
  }
248
378
 
@@ -253,6 +383,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
253
383
  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 });
254
384
  let existing = own(spec.id);
255
385
  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
+ 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
256
387
  if (existing) { existing.lease = now(); store.save(); return { status: 200, body: view(existing) }; }
257
388
  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
258
389
  const prio = spec.priority ?? "normal";
@@ -268,14 +399,19 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
268
399
  }
269
400
  // Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
270
401
  // A reserved launch skips the load gate: it must never be refused because lanes are busy (they are throttled/drained below).
402
+ if (prio !== "reserved") { // #5858: ramp-aware: the admitted lanes' projected peaks plus this one must fit, however low the load is right now
403
+ const e = effectiveCapacity(), pu = projectedUse(), est = estimateFor(slugOf(spec), { cpus, mem: mem_gb }), nm = Math.max(mem_gb, est.mem), nc = Math.max(cpus, est.cpus);
404
+ const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
405
+ 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 };
406
+ }
271
407
  if (!h.ok && prio !== "reserved") return { status: 503, body: { error: `host busy: ${h.reason}`, live: h }, retryAfter: 60 };
272
- if (prio === "reserved") {
273
- for (const r of tiers().act.filter((s) => prioOf(s) === "borrow")) await throttle(r, SHARES().throttled); // throttle every borrower first,
274
- for (const v of adm.victims) await drainOne(v, `reserved ${reservation} arrived`); // then stop only as many as the reservation needs
408
+ const gate = hostDiskView(c.active, spec.repo?.slug ?? null);
409
+ if (gate.host_disk_low) { // #5733: before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
410
+ const floor = floorGb();
411
+ 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 };
275
412
  }
276
- if (c.host_disk_low) { // #5733: before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
277
- const floor = cfg.min_host_disk_free_gb ?? 25;
278
- return { status: 503, body: { error: `host disk low: ${c.host_disk_free_gb} GB free, floor ${floor} GB with ${c.active} running`, code: "pool.disk_low", host_disk_free_gb: c.host_disk_free_gb, floor_gb: floor }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
413
+ 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
+ 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 };
279
415
  }
280
416
  if (spec.lane_tools?.length) { // #5650 follow-up: never build inside the launch request (router timeout); 503 + retry while it builds
281
417
  let st;
@@ -283,6 +419,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
283
419
  if (st.building) return { status: 503, body: { error: `lane image ${st.tag} building`, code: "lane_tools.building" }, retryAfter: LANE_BUILD_RETRY_AFTER_S };
284
420
  if (st.failed) return { status: 422, body: { error: st.failed, code: "lane_tools.build_failed" } };
285
421
  }
422
+ // Last refusal point passed: only now stop borrowed lanes (#5897), a launch refused above must not have drained any.
423
+ if (prio === "reserved") {
424
+ for (const r of tiers().act.filter((s) => prioOf(s) === "borrow")) await throttle(r, SHARES().throttled); // throttle every borrower first,
425
+ for (const v of adm.victims) await drainOne(v, `reserved ${reservation} arrived`); // then stop only as many as the reservation needs
426
+ }
286
427
  const name = safeName(spec.id);
287
428
  const dir = join(stateDir, "sandboxes", name);
288
429
  mkdirSync(join(dir, "result"), { recursive: true });
@@ -294,14 +435,15 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
294
435
  const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_RELAY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/relay`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? "", CS_WORK_DIR: workDirOf(name),
295
436
  ...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
296
437
  writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
297
- const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, 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 } : {}) } : {}) };
438
+ 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 } : {}) } : {}) };
298
439
  sb()[spec.id] = rec;
299
440
  store.save();
300
441
  const cacheKey = String(spec.cache?.key ?? spec.repo?.slug ?? "default").toLowerCase().replace(/[^a-z0-9_.-]/g, "-");
301
- rec.cacheVolume = `cs-cache-${cacheKey}`;
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
302
443
  rec.workDir = workDirOf(name);
303
444
  cacheUsed.set(rec.cacheVolume, now());
304
- try { await docker.createVolume?.(rec.cacheVolume, [CACHE_LABEL]); } catch (e) { log.warn?.(`label ${rec.cacheVolume}: ${String(e.stderr || e.message).slice(0, 200)}`); } // an unlabelled volume still works
445
+ 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
446
+ try { if (docker.volumeLabels && (await docker.volumeLabels(rec.cacheVolume))["computeshare.agent"] !== agentId) adoptedCache.add(rec.cacheVolume); } catch { /* best effort */ }
305
447
  // Public resolvers: host resolvers like Tailscale MagicDNS are not reachable from the container network.
306
448
  const netArgs = ["--add-host", "host.docker.internal:host-gateway", ...(cfg.dns ?? ["1.1.1.1", "8.8.8.8"]).flatMap((d) => ["--dns", String(d)])];
307
449
  let laneCpus = cpus, laneMem = mem_gb, laneNet = netArgs, work = [];
@@ -319,7 +461,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
319
461
  ({ cpus: dCpus, mem: dMem } = clampToVm(dCpus, dMem));
320
462
  work = cacheMount; // the daemon sees the checkout at the same /cache/work path as the lane
321
463
  await docker.run([
322
- "--name", dindName(name), "--label", LABEL, "--label", `computeshare.id=${spec.id}`, "--label", "computeshare.role=dind",
464
+ "--name", dindName(name), "--label", LABEL, "--label", AGENT, "--label", `computeshare.id=${spec.id}`, "--label", "computeshare.role=dind",
323
465
  "--privileged", "--cpus", String(dCpus), ...sharesArgs(prio), "--memory", mb(dMem), "--memory-swap", mb(dMem + swapFor(limit?.dind_swap_gb)),
324
466
  ...netArgs, ...work,
325
467
  // Bypass dockerd-entrypoint: it adds tcp://0.0.0.0:2375 (reachable from other sandboxes on the bridge).
@@ -332,7 +474,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
332
474
  if (limit && !withDocker) { laneCpus = limit.lane_cpus; laneMem = limit.lane_mem_gb; }
333
475
  ({ cpus: laneCpus, mem: laneMem } = clampToVm(laneCpus, laneMem));
334
476
  await docker.run([
335
- "--name", name, "--label", LABEL, "--label", `computeshare.id=${spec.id}`,
477
+ "--name", name, "--label", LABEL, "--label", AGENT, "--label", `computeshare.id=${spec.id}`,
336
478
  // Hard burst cap per container; the (smaller) reservation is only what placement counts.
337
479
  // --memory-swap above --memory lets a rare spike page out instead of being OOM-killed (swap deal).
338
480
  "--cpus", String(laneCpus), ...sharesArgs(prio), "--memory", mb(laneMem), "--memory-swap", mb(laneMem + swapFor(limit?.lane_swap_gb)), "--pids-limit", "4096",
@@ -355,7 +497,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
355
497
  return { status: 201, body: view(rec) };
356
498
  }
357
499
 
358
- 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 } : {}) });
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" } : {}) });
359
501
 
360
502
  const warm = makeWarm({ store, sb, own, now, launch, destroy: (id, why) => destroy(id, why), view, log });
361
503
 
@@ -364,7 +506,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
364
506
  const s = await docker.inspect(r.name);
365
507
  if (!s) { r.state = "exited"; r.finishedAt ??= now(); }
366
508
  else if (!s.running && r.state !== "starting") { r.state = "exited"; r.exitCode = s.exitCode; r.finishedAt = Date.parse(s.finishedAt) || now(); }
367
- else if (s.running) r.state = "running";
509
+ else if (s.running) r.state = r.diskPaused ? "paused" : "running";
368
510
  return r;
369
511
  }
370
512
 
@@ -386,20 +528,22 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
386
528
  try { return JSON.parse(readFileSync(join(r.dir, "result", basename(r.result_file)), "utf8")); } catch { return null; }
387
529
  }
388
530
 
389
- async function destroy(id, why) {
531
+ async function destroy(id, why, { keepWork = false } = {}) {
390
532
  const r = own(id);
391
533
  if (!r) return false;
392
- const history = r.usage?.samples ? JSON.stringify({ at: new Date(now()).toISOString(), id: r.id, issue: r.issue, docker: Boolean(r.docker), minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10, ...usageView(r) }) : null;
534
+ if (r.slug && r.diskPeakMb) { const h = (hist()[r.slug] ??= []); h.push(r.diskPeakMb); if (h.length > 50) h.shift(); }
535
+ const history = r.usage?.samples ? JSON.stringify({ at: new Date(now()).toISOString(), id: r.id, issue: r.issue, repo: r.repo ?? null, docker: Boolean(r.docker), minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10, ...usageView(r) }) : null;
393
536
  await docker.remove(r.name);
394
537
  if (r.docker) await docker.remove(dindName(r.name));
395
- if (r.workDir) { try { await docker.removeWorkDir(r.cacheVolume, image, r.workDir); } catch (e) { sweepFail(r.cacheVolume, "work dir", e); } }
538
+ if (r.workDir && keepWork) { /* #5891: a disk-pressure stop keeps the worktree and cache volume for the resumed lane */ }
539
+ else if (r.workDir) { try { await docker.removeWorkDir(r.cacheVolume, image, r.workDir); } catch (e) { sweepFail(r.cacheVolume, "work dir", e); } }
396
540
  else if (r.docker) await docker.removeVolume(workVolume(r.name)); // sandbox launched before #5696
397
541
  try { await docker.wipe(r.dir, image); } catch (e) { log.warn?.(`wipe ${r.name}: ${String(e.stderr || e.message).slice(0, 200)}`); }
398
542
  rmSync(r.dir, { recursive: true, force: true });
399
543
  delete sb()[r.id];
400
544
  store.save();
401
545
  // Written once, after the sandbox is really gone (a teardown that throws and is retried must not log it twice).
402
- if (history) { try { appendFileSync(join(stateDir, "usage-history.jsonl"), history + "\n"); } catch { /* best effort */ } }
546
+ if (history) { try { appendFileSync(join(stateDir, "usage-history.jsonl"), history + "\n"); } catch { /* best effort */ } if (histRows) histRows.push(JSON.parse(history)); }
403
547
  log.info?.(`destroyed ${id} (${why})`);
404
548
  return true;
405
549
  }
@@ -432,19 +576,28 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
432
576
  lastCachePrune = t;
433
577
  try { await docker.builderPrune?.(cfg.build_cache_keep_gb ?? 20); } catch (e) { log.warn?.(`builder prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
434
578
  try {
435
- for (const v of (await docker.listDanglingVolumes?.()) ?? []) {
579
+ for (const v of (await docker.listDanglingVolumes?.(AGENT)) ?? []) {
436
580
  if (!/^[0-9a-f]{64}$/.test(v)) continue;
437
581
  try { await docker.removeVolume(v); log.info?.(`removed anonymous volume ${v.slice(0, 12)}`); } catch (e) { log.warn?.(`rm volume ${v.slice(0, 12)}: ${String(e.stderr || e.message).slice(0, 200)}`); }
438
582
  }
439
583
  } catch (e) { log.warn?.(`anonymous volume sweep: ${String(e.stderr || e.message).slice(0, 200)}`); }
440
584
  }
441
585
 
586
+ /** Cache volumes the sweeps cover: those labelled for this agent plus pre-label ones it mounts (adopted or referenced by a sandbox record). */
587
+ async function ownCacheVolumes() {
588
+ const labelled = await docker.listVolumes("cs-cache-", AGENT);
589
+ const mine = new Set([...adoptedCache, ...Object.values(sb()).map((r) => r.cacheVolume).filter(Boolean)]);
590
+ if (!mine.size) return labelled;
591
+ const all = await docker.listVolumes("cs-cache-");
592
+ return [...new Set([...labelled, ...all.filter((v) => mine.has(v))])];
593
+ }
594
+
442
595
  /** #5757: age-out / size cap inside each cache volume, then idle eviction. Never-evict volumes are left alone; failures go to /capacity. */
443
596
  async function cacheSweep(t) {
444
597
  const never = cfg.cache_never_evict ?? [];
445
598
  const keep = Object.values(sb()).map((r) => r.workDir).filter(Boolean);
446
599
  const volumes = [];
447
- for (const v of await docker.listVolumes("cs-cache-")) {
600
+ for (const v of await ownCacheVolumes()) {
448
601
  if (never.includes(v)) continue;
449
602
  try {
450
603
  const r = await docker.sweepCache(v, image, { maxAgeDays: cfg.cache_max_age_days ?? 14, maxGb: cfg.cache_max_gb ?? null, keep, now: t });
@@ -474,15 +627,91 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
474
627
  if (!act.some((r) => prioOf(r) === "reserved")) for (const r of borrowed.filter((x) => x.throttled)) await throttle(r, SHARES().borrow);
475
628
  }
476
629
 
630
+
631
+ // #5891: runtime disk control, once per reap. Below the floor: prune rebuildables, then pause the fastest grower (lease kept),
632
+ // then below floor/2 stop it with sandbox.disk_pressure (worktree + volume kept). Above floor + margin: unpause.
633
+ const freshHostDisk = () => { if (!hostDisk) hostDiskCache.at = -Infinity; try { const hd = readHostDisk(); return hd && Number.isFinite(hd.gb) ? hd.gb : null; } catch { return null; } };
634
+ const cntNames = (r) => (r.docker ? [r.name, dindName(r.name)] : [r.name]);
635
+ /** Removes the exited container(s) of sandboxes dead for ttlMs (their data stays for a resume), and orphan fdrsbx-* volumes. Never cs-cache-*. */
636
+ async function reapDead(t, ttlMs) {
637
+ for (const r of Object.values(sb())) {
638
+ if (r.state !== "exited" || r.containerReaped || !r.finishedAt || t - r.finishedAt < ttlMs) continue;
639
+ try { for (const n of cntNames(r)) await docker.remove(n); r.containerReaped = true; log.info?.(`removed dead sandbox container ${r.name}`); } catch (e) { log.warn?.(`reap ${r.name}: ${String(e.stderr || e.message).slice(0, 200)}`); }
640
+ }
641
+ const names = Object.values(sb()).flatMap((r) => [r.id, r.name]); // a volume named after a known sandbox stays for its resume
642
+ try {
643
+ for (const v of (await docker.listVolumes?.("fdrsbx-")) ?? []) {
644
+ if (!v.startsWith("fdrsbx-") || v.startsWith("cs-cache-") || names.some((n) => v === n || v.startsWith(`${n}-`) || v.startsWith(`${n}_`))) continue;
645
+ try { await docker.removeVolume(v); log.info?.(`removed dead sandbox volume ${v}`); } catch (e) { log.warn?.(`rm volume ${v}: ${String(e.stderr || e.message).slice(0, 200)}`); }
646
+ }
647
+ } catch (e) { log.warn?.(`dead volume sweep: ${String(e.stderr || e.message).slice(0, 200)}`); }
648
+ }
649
+ async function reclaimDisk(t) {
650
+ try { await docker.builderPrune?.(0); } catch (e) { log.warn?.(`builder prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
651
+ try { await docker.pruneImages?.(); } catch (e) { log.warn?.(`image prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
652
+ const heavy = activeRecs().sort((a, b) => (diskCache.mb[b.id] ?? 0) - (diskCache.mb[a.id] ?? 0)).slice(0, cfg.disk_reclaim_sandboxes ?? 3);
653
+ for (const r of heavy) { try { await docker.pruneCaches?.(r.name); } catch { /* best effort: package-manager caches only */ } }
654
+ await reapDead(t, 0);
655
+ }
656
+ async function hostDiskPressure(t) {
657
+ let free = freshHostDisk();
658
+ if (free === null) { await reapDead(t, (cfg.dead_ttl_s ?? 600) * 1000); return; }
659
+ noteHostDisk(free);
660
+ const floor = floorGb(), hard = floor / 2;
661
+ if (free >= floor) {
662
+ await reapDead(t, (cfg.dead_ttl_s ?? 600) * 1000);
663
+ if (free >= floor + (cfg.disk_resume_margin_gb ?? 2)) for (const r of activeRecs().filter((x) => x.diskPaused)) {
664
+ try { for (const n of cntNames(r)) await docker.unpause?.(n); r.diskPaused = false; r.state = "running"; log.info?.(`resumed ${r.id}: host disk ${free} GB`); } catch (e) { log.warn?.(`unpause ${r.id}: ${String(e.stderr || e.message).slice(0, 200)}`); }
665
+ }
666
+ for (const r of activeRecs().filter((x) => x.diskPaused)) r.lease = t;
667
+ return;
668
+ }
669
+ await reclaimDisk(t);
670
+ free = freshHostDisk() ?? free;
671
+ if (free >= floor) return; // pruning was enough: nothing paused or stopped
672
+ let victim = activeRecs().find((r) => r.diskPaused);
673
+ if (!victim) {
674
+ victim = activeRecs().filter((r) => r.state === "running").sort((a, b) => (b.growthMbH ?? 0) - (a.growthMbH ?? 0) || (diskCache.mb[b.id] ?? 0) - (diskCache.mb[a.id] ?? 0))[0];
675
+ if (victim) { try { for (const n of cntNames(victim)) await docker.pause?.(n); victim.diskPaused = true; victim.state = "paused"; log.warn?.(`paused ${victim.id} (disk): host free ${free} GB < floor ${floor} GB`); } catch (e) { log.warn?.(`pause ${victim.id}: ${String(e.stderr || e.message).slice(0, 200)}`); victim = null; } }
676
+ }
677
+ for (const r of activeRecs().filter((x) => x.diskPaused)) r.lease = t; // the paused lane stays leased: it is not lost
678
+ if (victim && free < hard) { // the guest is about to fill: stop it to save every other sandbox; worktree and volume stay
679
+ for (const n of cntNames(victim)) { try { await docker.unpause?.(n); } catch { /* not paused */ } }
680
+ for (const n of cntNames(victim)) { try { await docker.kill(n, "KILL"); } catch { /* gone */ } }
681
+ victim.diskPaused = false; victim.state = "exited"; victim.finishedAt = t; victim.diskPressure = true;
682
+ log.error?.(`stopped ${victim.id} (sandbox.disk_pressure): host free ${free} GB < ${hard} GB`);
683
+ }
684
+ }
685
+ /** #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
+ let lastFstrim = -Infinity;
687
+ async function diskPressure(t) {
688
+ const v = laneDiskView();
689
+ const state = "lane_disk_cap_gb" in v ? planDiskCap({ usedGb: v.lane_disk_used_gb, capGb: v.lane_disk_cap_gb, pruneAtPct: cfg.disk_prune_at_pct }) : "ok";
690
+ if (state !== "ok") {
691
+ log.warn?.(`lane disk ${v.lane_disk_used_gb}/${v.lane_disk_cap_gb} GB (${state}): pruning`);
692
+ for (const [what, fn] of [["container prune", docker.containerPrune], ["image prune", docker.imagePrune]]) {
693
+ try { await fn?.call(docker, OWN); } catch (e) { log.warn?.(`${what}: ${String(e.stderr || e.message).slice(0, 200)}`); }
694
+ }
695
+ try { await docker.builderPrune?.(cfg.build_cache_keep_gb ?? 20); } catch (e) { log.warn?.(`builder prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
696
+ lastCacheSweep = t;
697
+ await cacheSweep(t);
698
+ }
699
+ if (cfg.fstrim === false || !fstrimDue({ now: t, last: lastFstrim, intervalS: cfg.fstrim_interval_s, force: state !== "ok" })) return;
700
+ lastFstrim = t;
701
+ const r = await trim({ root: cfg.docker_root });
702
+ if (!r.ok) log.warn?.(`fstrim: ${r.error}`);
703
+ }
704
+
477
705
  async function reap() {
478
706
  const t = now();
479
707
  for (const r of Object.values(sb())) {
480
708
  try { await refresh(r); } catch { /* docker hiccup: judge by lease only */ }
481
- const why = t - r.lease > leaseTtlMs ? "lease expired" : t - r.startedAt > maxLifeMs ? "max lifetime" : r.state === "exited" && r.finishedAt && t - r.finishedAt > keepExitedMs ? "exited retention" : null;
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;
482
710
  if (why) await destroy(r.id, why);
483
711
  }
712
+ await hostDiskPressure(t); // #5891
484
713
  const known = new Set(Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)]));
485
- for (const name of await docker.listLabelled(LABEL)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
714
+ for (const name of await docker.listLabelled(OWN)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
486
715
  await sampleUsage();
487
716
  await reclaimIdle();
488
717
  await warm.maintain(maxLifeMs);
@@ -491,15 +720,16 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
491
720
  log.info?.(`pending resize applied: HTTP ${r.status} ${JSON.stringify(r.body)}`);
492
721
  }
493
722
  const knownVols = new Set(Object.values(sb()).filter((r) => !r.workDir).map((r) => workVolume(r.name)));
494
- for (const v of await docker.listVolumes("cs-work-")) if (!knownVols.has(v)) { await docker.removeVolume(v); log.info?.(`removed orphan volume ${v}`); }
723
+ for (const v of await docker.listVolumes("cs-work-", AGENT)) if (!knownVols.has(v)) { await docker.removeVolume(v); log.info?.(`removed orphan volume ${v}`); }
495
724
  if (t - lastWorkSweep >= WORK_SWEEP_MS) {
496
725
  lastWorkSweep = t;
497
726
  const keep = Object.values(sb()).map((r) => r.workDir).filter(Boolean);
498
- for (const v of await docker.listVolumes("cs-cache-")) {
727
+ for (const v of await ownCacheVolumes()) {
499
728
  try { await docker.pruneWorkDirs(v, image, keep); cacheErr.delete(`work sweep:${v}`); } catch (e) { sweepFail(v, "work sweep", e); }
500
729
  }
501
730
  }
502
731
  await sweepBuildCache(t);
732
+ try { await diskPressure(t); } catch (e) { log.warn?.(`disk pressure: ${String(e.message).slice(0, 200)}`); }
503
733
  if (t - lastCacheSweep >= (cfg.cache_sweep_interval_s ?? 3600) * 1000) {
504
734
  lastCacheSweep = t;
505
735
  await cacheSweep(t);
@@ -567,7 +797,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
567
797
  if (want.image !== running.image || want.version !== running.version) {
568
798
  const nextImage = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(want.version);
569
799
  log.info?.(`rebuilding ${nextImage} (${running.version}/${running.image} -> ${want.version}/${want.image})`);
570
- await docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version));
800
+ await buildWithRetry(() => docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version)), { log }); // #5919
571
801
  }
572
802
  await pruneLaneImages([laneImageTag(want.version)]);
573
803
  await prepullImages();
@@ -578,7 +808,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
578
808
  upgrade.state = "restarting";
579
809
  setTimeout(() => process.exit(0), 500);
580
810
  } catch (e) {
581
- upgrade.state = "failed"; upgrade.error = String(e.stderr || e.message).slice(0, 500);
811
+ upgrade.state = "failed"; upgrade.error = upgradeErrorText(e); // #5919: the tail, where the failing command's output is
812
+ try { writeFileSync(join(stateDir, "upgrade.log"), `${new Date(now()).toISOString()}\n${upgradeErrorText(e, 200000)}\n`); upgrade.log = join(stateDir, "upgrade.log"); } catch { /* best effort */ }
582
813
  log.error?.(`self-update failed: ${upgrade.error}`);
583
814
  }
584
815
  }
@@ -590,8 +821,16 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
590
821
  /** Peak and average CPU (cores) and memory (GB) per sandbox, lane + docker sidecar, against what it reserved. */
591
822
  async function sampleUsage() {
592
823
  let st;
593
- try { st = await docker.stats?.(LABEL); } catch { return; }
824
+ try { st = await docker.stats?.(OWN); } catch { return; }
594
825
  if (!st) return;
826
+ try { // #5858: containers that are not this agent's sandboxes (all containers minus the labelled ones and known sandboxes)
827
+ const all = await docker.stats?.([]);
828
+ if (all) {
829
+ const mine = new Set([...Object.keys(st), ...Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)])]);
830
+ const others = Object.entries(all).filter(([n]) => !mine.has(n)).map(([, x]) => x);
831
+ coTenant = { cpus: others.reduce((a, x) => a + (x.cpu || 0), 0), mem_gb: others.reduce((a, x) => a + (x.mem_gb || 0), 0) };
832
+ }
833
+ } catch { /* keep the last reading */ }
595
834
  for (const r of Object.values(sb())) {
596
835
  if (r.state === "exited") continue;
597
836
  const parts = [st[r.name], r.docker ? st[dindName(r.name)] : null].filter(Boolean);
@@ -669,7 +908,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
669
908
  [route("POST", "/warm/claim"), async (_p, body) => warm.claim(body ?? {})],
670
909
  [route("GET", "/sandboxes/:id"), async ({ id }) => { const r = own(id); if (!r) return { status: 404, body: { state: "gone" } }; await refresh(r); store.save(); return { status: 200, body: view(r) }; }],
671
910
  [route("GET", "/sandboxes/:id/logs"), async ({ id }, _b, url) => { const r = own(id); return r ? { status: 200, body: readLog(r, url.searchParams.get("cursor")) } : { status: 404, body: { text: "", cursor: 0 } }; }],
672
- [route("GET", "/sandboxes/:id/result"), async ({ id }) => { const r = own(id); const x = r && readResult(r); if (!x && r?.drained) return { status: 200, body: { drained: true, reason: r.drained } }; return x ? { status: 200, body: x } : { status: 404, body: { error: "no result" } }; }], // #5856: a drained lane without its own result is reported so the dispatcher reschedules it
911
+ [route("GET", "/sandboxes/:id/result"), async ({ id }) => { const r = own(id); const x = r && readResult(r); if (!x && r?.drained) return { status: 200, body: { drained: true, reason: r.drained } }; if (!x && r?.diskPressure) return { status: 200, body: { disk_pressure: true, code: "sandbox.disk_pressure", reason: "host drive below the hard floor" } }; /* #5891 */ return x ? { status: 200, body: x } : { status: 404, body: { error: "no result" } }; }], // #5856: a drained lane without its own result is reported so the dispatcher reschedules it
673
912
  [route("GET", "/sandboxes/:id/usage"), async ({ id }) => { const r = own(id); return r ? { status: 200, body: { minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10 } } : { status: 404, body: {} }; }],
674
913
  [route("POST", "/sandboxes/:id/lease"), async ({ id }) => { const r = own(id); if (!r) return { status: 404, body: { state: "gone" } }; r.lease = now(); store.save(); return { status: 200, body: { ok: true } }; }],
675
914
  // #5274: SIGTERM the lane (PID 1) so its teardown checkpoints and reports deferred run.interrupted; the sandbox is kept, never destroyed.
@@ -687,6 +926,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
687
926
  return { status: 200, body: { rows: rows.slice(-500) } };
688
927
  }],
689
928
  [route("POST", "/admin/resize"), async (_p, body) => resize(body ?? {})],
929
+ [route("POST", "/admin/policy"), async (_p, body) => applyPolicy(body)], // #5886
930
+ [route("POST", "/pause"), async () => setOwnerPause(true)], // #5885: box-local `forgedock pool pause`; running lanes finish
931
+ [route("POST", "/resume"), async () => setOwnerPause(false)],
690
932
  [route("POST", "/admin/update"), async () => { selfUpdate(); return { status: 202, body: { ok: true, from: running } }; }],
691
933
  [route("DELETE", "/sandboxes/:id"), async ({ id }) => ((await destroy(id, "requested")) ? { status: 200, body: { ok: true } } : { status: 404, body: { state: "gone" } })],
692
934
  ];
@@ -730,10 +972,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
730
972
  * WSL with mirrored networking often has no IPv6 default route, yet dockerd still dials registries over IPv6 and fails
731
973
  * ("network is unreachable"). Turn IPv6 off inside the distro (persistently) and restart docker while it is idle.
732
974
  */
733
- export async function wslNetworkFixup({ run: runCmd = run, log = console, idle = () => true } = {}) {
975
+ export async function wslNetworkFixup({ run: runCmd = run, log = console, idle = () => true, pin = ensureNatPin } = {}) {
734
976
  let release = "";
735
977
  try { release = readFileSync("/proc/sys/kernel/osrelease", "utf8"); } catch { return "not linux"; }
736
978
  if (!/microsoft/i.test(release)) return "not wsl";
979
+ try { const p = pin(); if (p?.applied) log.info?.(`WSL mirrored: pinned docker NAT source ports to ${p.range} (${p.applied} rules)`); } catch (e) { log.warn?.(`NAT port pin failed: ${e.message}`); }
737
980
  try {
738
981
  const { stdout } = await runCmd("ip", ["-6", "route", "show", "default"]);
739
982
  if (String(stdout).trim()) return "ipv6 route present";
@@ -747,6 +990,40 @@ export async function wslNetworkFixup({ run: runCmd = run, log = console, idle =
747
990
  return "applied";
748
991
  }
749
992
 
993
+ /**
994
+ * #5882: outbound-only transport. Long-polls the router (`GET /agent/poll`, which doubles as the heartbeat), runs each queued
995
+ * request against this agent's own bearer-checked HTTP API and posts the answer to `/agent/reply/:rid`. The router never dials in.
996
+ * `dispatch` defaults to a loopback call on cfg.listen; tests inject their own.
997
+ */
998
+ export function startPoll(cfg, { log = console, fetchFn = globalThis.fetch, waitS = 25, dispatch = null, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
999
+ let stopped = false, backoff = 1000;
1000
+ const host = !cfg.listen?.host || cfg.listen.host === "0.0.0.0" ? "127.0.0.1" : cfg.listen.host;
1001
+ const local = dispatch ?? ((m, path, body) => call(`http://${host}:${cfg.listen.port}`, m, path, { body, token: cfg.token, timeoutMs: 180000 }));
1002
+ const reply = (rid, r) => call(cfg.router_url, "POST", `/agent/reply/${encodeURIComponent(rid)}`, { body: { status: r.status, data: r.data, retry_after: r.retryAfter ?? null }, token: cfg.token, timeoutMs: 30000, fetchFn });
1003
+ async function serve({ rid, method, path, body }) {
1004
+ let r;
1005
+ if (typeof path !== "string" || !/^\/(?!\/)/.test(path) || !["GET", "POST", "DELETE"].includes(method)) r = { status: 400, data: { error: "bad request" } };
1006
+ else r = await local(method, path, body).catch((e) => ({ status: 502, data: { error: `agent local dispatch failed: ${e.message}` } }));
1007
+ await reply(rid, r).catch((e) => log.warn?.(`poll reply ${rid}: ${e.message}`));
1008
+ }
1009
+ const done = (async () => {
1010
+ while (!stopped) {
1011
+ try {
1012
+ const r = await call(cfg.router_url, "GET", `/agent/poll?wait=${waitS}`, { token: cfg.token, timeoutMs: (waitS + 15) * 1000, fetchFn });
1013
+ if (r.status !== 204 && (!r.ok || !r.data?.rid)) throw new Error(`poll HTTP ${r.status}`);
1014
+ backoff = 1000;
1015
+ if (r.status !== 204) serve(r.data).catch((e) => log.warn?.(`poll serve: ${e.message}`));
1016
+ } catch (e) {
1017
+ if (stopped) break;
1018
+ log.warn?.(`router poll failed: ${e.message}; retry in ${backoff}ms`);
1019
+ await sleep(backoff);
1020
+ backoff = Math.min(backoff * 2, 30000);
1021
+ }
1022
+ }
1023
+ })();
1024
+ return { stop: () => { stopped = true; }, done };
1025
+ }
1026
+
750
1027
  export function startAgent(cfg, deps) {
751
1028
  const agent = createAgent(cfg, deps);
752
1029
  const server = createServer(agent.handle);
@@ -757,5 +1034,7 @@ export function startAgent(cfg, deps) {
757
1034
  wslNetworkFixup({ idle: () => agent.capacity().active === 0 })
758
1035
  .catch((e) => console.error("wsl network fixup failed", e))
759
1036
  .finally(() => agent.prepullImages());
760
- return { agent, server, close: () => { clearInterval(timer); server.close(); } };
1037
+ // #5882: outbound mode keeps the local listener for the lanes' credential calls (bind it to the docker bridge, not a public interface).
1038
+ const poll = cfg.outbound ? startPoll(cfg, { log: deps?.log }) : null;
1039
+ return { agent, server, close: () => { clearInterval(timer); poll?.stop(); server.close(); } };
761
1040
  }