forgedock 1.63.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 (84) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +88 -12
  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 +6 -1
  10. package/bin/lean/batch.test.mjs +71 -6
  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 +15 -6
  17. package/bin/lean/execution.test.mjs +44 -3
  18. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  19. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  20. package/bin/lean/issuewatch.mjs +3 -0
  21. package/bin/lean/lanecheck.test.mjs +13 -1
  22. package/bin/lean/lean.mjs +157 -28
  23. package/bin/lean/lean.test.mjs +289 -21
  24. package/bin/lean/live-execution.mjs +25 -0
  25. package/bin/lean/live-execution.test.mjs +35 -1
  26. package/bin/lean/merged-park.mjs +76 -0
  27. package/bin/lean/merged-park.test.mjs +64 -0
  28. package/bin/lean/mergetrain.mjs +357 -0
  29. package/bin/lean/mergetrain.test.mjs +348 -0
  30. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  31. package/bin/lean/orchestrate-stacking.test.mjs +23 -1
  32. package/bin/lean/orchestrate-train.test.mjs +130 -0
  33. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  34. package/bin/lean/orchestrate.mjs +159 -13
  35. package/bin/lean/prompts.mjs +4 -3
  36. package/bin/lean/release-review.mjs +8 -1
  37. package/bin/lean/release-review.test.mjs +42 -2
  38. package/bin/lean/release-status.test.mjs +53 -1
  39. package/bin/lean/release.mjs +6 -3
  40. package/bin/lean/render.mjs +6 -1
  41. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  42. package/bin/lean/sandbox-remote.mjs +12 -2
  43. package/bin/lean/sched.mjs +19 -2
  44. package/bin/lean/sched.test.mjs +33 -1
  45. package/bin/lean/schedd-health.mjs +2 -1
  46. package/bin/lean/schedd-health.test.mjs +7 -0
  47. package/bin/lean/schedd.mjs +55 -7
  48. package/bin/lean/schedd.test.mjs +42 -1
  49. package/bin/lean/stacking.mjs +45 -0
  50. package/bin/lean/stacking.test.mjs +25 -1
  51. package/bin/lean/statuscomment.mjs +14 -8
  52. package/bin/lean/statuscomment.test.mjs +18 -1
  53. package/bin/lean/validate-catalog.mjs +1 -1
  54. package/bin/lean/validate-catalog.test.mjs +3 -0
  55. package/bin/lean/worktree.mjs +8 -3
  56. package/bin/lean/worktree.test.mjs +18 -0
  57. package/bin/pool/agent.mjs +296 -31
  58. package/bin/pool/cli.mjs +120 -6
  59. package/bin/pool/disk.mjs +43 -0
  60. package/bin/pool/docker.mjs +10 -0
  61. package/bin/pool/health.mjs +95 -0
  62. package/bin/pool/router.mjs +274 -27
  63. package/bin/runner.mjs +3 -1
  64. package/bin/stats/chains.mjs +101 -0
  65. package/bin/stats/chains.test.mjs +53 -0
  66. package/bin/stats/efficiency.mjs +7 -6
  67. package/bin/stats/efficiency.test.mjs +48 -7
  68. package/bin/stats/index.mjs +11 -3
  69. package/bin/stats/stats.test.mjs +9 -0
  70. package/docs/CONFIG.md +8 -1
  71. package/docs/OUTCOME-CODES.md +4 -0
  72. package/package.json +1 -1
  73. package/pool/README.md +10 -0
  74. package/pool/image/Dockerfile +2 -1
  75. package/pool/image/entrypoint.sh +6 -6
  76. package/pool/image/mirror.sh +71 -0
  77. package/pool/install/install-agent-linux.sh +57 -5
  78. package/pool/install/install-agent-macos.sh +148 -0
  79. package/pool/install/install-agent.ps1 +11 -0
  80. package/pool/install/install-agent.sh +59 -7
  81. package/pool/install/uninstall-agent-linux.sh +75 -0
  82. package/pool/install/uninstall-agent-macos.sh +60 -0
  83. package/pool/install/uninstall-agent.ps1 +1 -0
  84. package/scripts/transition-label.sh +11 -0
package/bin/pool/cli.mjs CHANGED
@@ -15,17 +15,23 @@ 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] | status | 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 = {
22
22
  router: { value: ["--config"], bool: [] },
23
23
  agent: { value: ["--config"], bool: [] },
24
- status: { value: ["--config"], bool: [] },
24
+ status: { value: ["--config", "--account"], bool: ["--json"] },
25
+ link: { value: ["--config", "--account"], bool: [] },
26
+ policy: { value: ["--config", "--cpus", "--mem"], bool: ["--idle-only", "--no-idle-only", "--pause", "--resume-policy"] },
27
+ pause: { value: ["--config"], bool: [] },
28
+ resume: { value: ["--config"], bool: [] },
29
+ uninstall: { value: ["--config"], bool: ["--yes"] },
25
30
  upgrade: { value: ["--config"], bool: [] },
26
31
  remove: { value: ["--config"], bool: [] },
27
- enroll: { value: ["--config", "--cpus", "--mem", "--agent-url"], bool: [] },
28
- "install-command": { value: ["--config", "--cpus", "--mem", "--agent-url"], bool: [] },
32
+ limit: { value: ["--config", "--lanes"], bool: [] },
33
+ enroll: { value: ["--config", "--cpus", "--mem", "--agent-url"], bool: ["--outbound", "--one-liner"] },
34
+ "install-command": { value: ["--config", "--cpus", "--mem", "--agent-url"], bool: ["--outbound", "--one-liner"] },
29
35
  resize: { value: ["--config", "--cpus", "--mem", "--vm-cpus", "--vm-mem", "--vm-swap"], bool: ["--drain"] },
30
36
  };
31
37
 
@@ -40,6 +46,28 @@ function rejectUnknownFlags(cmd, rest) {
40
46
  }
41
47
  }
42
48
 
49
+ const num = (x) => (Number.isFinite(x) ? String(Math.round(x * 10) / 10) : "-");
50
+ /** #5885: one row per host: used/borrowable/total cpus and memory, lane counts, pause state and why lanes are throttled or drained. */
51
+ export function statusTable(agents) {
52
+ const withAccount = agents.some((a) => a.account); // #5886: the column appears only when an agent has an account
53
+ const head = ["HOST", ...(withAccount ? ["ACCOUNT"] : []), "CPUS used/borrow/total", "MEM GB used/borrow/total", "ACTIVE", "THROTTLED", "PAUSED", "REASON"];
54
+ const rows = agents.map((a) => {
55
+ const name = a.name ?? a.host ?? "?";
56
+ const acct = withAccount ? [a.account ?? "-"] : [];
57
+ if (a.ok === false) return [name, ...acct, "-", "-", "-", "-", "-", `unreachable${a.error ? `: ${a.error}` : ""}`];
58
+ const used = (tot, free) => (Number.isFinite(tot) && Number.isFinite(free) ? tot - Math.max(0, free) : null);
59
+ const borrow = (b, free) => num(b ?? free);
60
+ const paused = a.owner_paused ? "owner" : a.paused ? (a.pending_resize ? "resize" : "yes") : "no";
61
+ const why = [a.owner_paused ? "paused by owner" : null, a.paused && !a.owner_paused && a.pending_resize ? "draining for resize" : null,
62
+ a.idle_gate ? `owner busy: ${a.idle_gate}` : null, a.last_drain ? `last drain ${a.last_drain.sandbox} at ${a.last_drain.at}: ${a.last_drain.reason}` : null].filter(Boolean).join("; ");
63
+ return [name, ...acct, `${num(used(a.cpus_total, a.cpus_free))}/${borrow(a.cpus_borrowable, a.cpus_free)}/${num(a.cpus_total)}`,
64
+ `${num(used(a.mem_total_gb, a.mem_free_gb))}/${borrow(a.mem_borrowable_gb, a.mem_free_gb)}/${num(a.mem_total_gb)}`,
65
+ String(a.active ?? "-"), String(a.throttled ?? 0), paused, why || "-"];
66
+ });
67
+ const w = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
68
+ return [head, ...rows].map((r) => r.map((c, i) => (i === r.length - 1 ? c : c.padEnd(w[i]))).join(" ")).join("\n");
69
+ }
70
+
43
71
  /** The `forgedock pool` verbs (and the `computeshare` script). Throws on usage or router errors; `deps` injects the HTTP client and config. */
44
72
  export async function runPoolCli(argv, deps = {}) {
45
73
  const [cmd, ...rest] = argv;
@@ -85,8 +113,79 @@ export async function runPoolCli(argv, deps = {}) {
85
113
  }
86
114
  case "status": {
87
115
  const cfg = routerConfig();
88
- const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "GET", "/agents", { token: cfg.forgedock_token });
89
- console.log(JSON.stringify(r.data, null, 2));
116
+ const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "GET", `/agents${flag("account") ? `?account=${encodeURIComponent(flag("account"))}` : ""}`, { token: cfg.forgedock_token });
117
+ if (rest.includes("--json")) console.log(JSON.stringify(r.data, null, 2));
118
+ else if (!r.ok) throw new Error(`router refused: HTTP ${r.status} ${JSON.stringify(r.data)}`);
119
+ else console.log(statusTable(r.data?.agents ?? []));
120
+ // #5735: lane sandboxes used/ceiling per agent, and the lane total across all batches
121
+ 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
+ if (Number.isInteger(r.data?.remote_lanes)) console.log(`remote lanes across batches: ${r.data.remote_lanes}`);
123
+ for (const a of r.data?.agents ?? []) {
124
+ if (a.transport) console.log(`${a.name}: transport ${a.transport}`); // #5882
125
+ const n = a.net; // #5923
126
+ if (n?.mirrored) console.log(`${a.name}: net mirrored, port range ${n.port_range ?? "?"}, NAT pin ${n.nat_pin ? "present" : "MISSING"}${n.degraded ? " DEGRADED" : ""}`);
127
+ if (!Number.isFinite(a.host_disk_free_gb)) continue;
128
+ 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
+ }
130
+ break;
131
+ }
132
+ case "link": {
133
+ // #5886: approve the user code a box printed (`install ... --device`), binding it to an account; the box then enrolls itself.
134
+ const code = rest.find((x) => !x.startsWith("--") && x !== flag("config") && x !== flag("account"));
135
+ if (!code) throw new Error("usage: forgedock pool link <user_code> [--account A]");
136
+ const cfg = routerConfig();
137
+ const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "POST", "/device/approve", { body: { user_code: code, ...(flag("account") ? { account: flag("account") } : {}) }, token: cfg.forgedock_token });
138
+ if (!r.ok) throw new Error(`router refused: HTTP ${r.status} ${JSON.stringify(r.data)}`);
139
+ console.log(`linked ${code} to account ${r.data.account}; the box enrolls on its next poll`);
140
+ break;
141
+ }
142
+ case "policy": {
143
+ // #5886: a per-box policy the router stores and pushes; the box owner's own pause is never cleared by it.
144
+ const name = rest.find((x) => !x.startsWith("--") && x !== flag("config") && x !== flag("cpus") && x !== flag("mem"));
145
+ if (!name) throw new Error("usage: forgedock pool policy <agent> [--cpus N --mem GB --idle-only --pause]");
146
+ const body = { ...(flag("cpus") ? { cpus: Number(flag("cpus")) } : {}), ...(flag("mem") ? { mem_gb: Number(flag("mem")) } : {}),
147
+ ...(rest.includes("--idle-only") ? { idle_only: true } : rest.includes("--no-idle-only") ? { idle_only: false } : {}),
148
+ ...(rest.includes("--pause") ? { paused: true } : rest.includes("--resume-policy") ? { paused: false } : {}) };
149
+ if (!Object.keys(body).length) throw new Error("usage: forgedock pool policy <agent> [--cpus N --mem GB --idle-only --pause]");
150
+ const cfg = routerConfig();
151
+ const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "PUT", `/agents/${encodeURIComponent(name)}/policy`, { body, token: cfg.forgedock_token, timeoutMs: 30000 });
152
+ if (!r.ok && r.status !== 202) throw new Error(`${name}: HTTP ${r.status} ${JSON.stringify(r.data)}`);
153
+ console.log(`${name}: policy ${JSON.stringify(r.data?.policy ?? body)}${r.data?.pushed === false ? " (stored; the box is unreachable, it is re-pushed when it returns)" : ""}`);
154
+ break;
155
+ }
156
+ case "limit": {
157
+ // #5735: forgedock pool limit <agent> --lanes N|none: the agent's lane sandbox ceiling across all batches.
158
+ const name = rest.find((x, i) => !x.startsWith("--") && !["--lanes", "--config"].includes(rest[i - 1]));
159
+ const v = flag("lanes");
160
+ if (!name || v === undefined) throw new Error("usage: forgedock pool limit <agent> --lanes N|none");
161
+ if (v !== "none" && !/^\d+$/.test(v)) throw new Error("usage: --lanes must be a non-negative integer or none");
162
+ const max_lanes = v === "none" ? null : parseInt(v, 10);
163
+ const cfg = routerConfig();
164
+ const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "POST", `/agents/${encodeURIComponent(name)}/limit`, { body: { max_lanes }, token: cfg.forgedock_token, timeoutMs: 30000 });
165
+ if (!r.ok) throw new Error(`${name}: HTTP ${r.status} ${JSON.stringify(r.data)}`);
166
+ console.log(`${name}: max_lanes ${max_lanes ?? "none"}`);
167
+ break;
168
+ }
169
+ case "pause":
170
+ case "resume": {
171
+ // #5885: the host owner stops (or restarts) new lanes on this box; running lanes finish. Loopback to the local agent, not via the router.
172
+ const cfg = agentConfig();
173
+ const host = !cfg.listen?.host || cfg.listen.host === "0.0.0.0" ? "127.0.0.1" : cfg.listen.host;
174
+ const r = await call(`http://${host}:${cfg.listen.port}`, "POST", `/${cmd}`, { token: cfg.token, timeoutMs: 10000 });
175
+ if (!r.ok) throw new Error(`agent refused ${cmd}: HTTP ${r.status} ${JSON.stringify(r.data)}`);
176
+ console.log(cmd === "pause" ? `${cfg.name ?? "agent"}: paused; no new lanes start here (${r.data?.active ?? 0} running lane(s) finish). Undo with \`forgedock pool resume\`.` : `${cfg.name ?? "agent"}: resumed; lanes may start here again.`);
177
+ break;
178
+ }
179
+ case "uninstall": {
180
+ // #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";
182
+ 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"]]];
187
+ 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}`); }
188
+ console.log("agent uninstalled from this box. Remove it from the router with: forgedock pool remove <agent>");
90
189
  break;
91
190
  }
92
191
  case "enroll":
@@ -96,6 +195,21 @@ export async function runPoolCli(argv, deps = {}) {
96
195
  const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "POST", "/codes", { token: cfg.forgedock_token });
97
196
  if (!r.ok) throw new Error(`router refused: HTTP ${r.status}`);
98
197
  const size = `${flag("cpus") ? `&cpus=${Number(flag("cpus"))}` : ""}${flag("mem") ? `&mem=${Number(flag("mem"))}` : ""}`;
198
+ const sizeFlags = `${flag("cpus") ? ` --cpus ${Number(flag("cpus"))}` : ""}${flag("mem") ? ` --mem ${Number(flag("mem"))}` : ""}`;
199
+ if (rest.includes("--outbound") || rest.includes("--one-liner")) { // #5883: Linux/macOS one command, served by GET /install (always outbound)
200
+ console.log(`curl -fsSL '${cfg.public_url}/install' | sh -s -- --code '${r.data.code}'${sizeFlags}`);
201
+ console.error("(run as root: as a sudo user, write `| sudo sh -s -- ...`)");
202
+ if (!rest.includes("--outbound")) {
203
+ console.error(`(one-time code, expires ${r.data.expires_at}; outbound-only: the agent polls ${cfg.public_url}; uninstall: curl -fsSL '${cfg.public_url}/install' | sh -s -- --uninstall)`);
204
+ break;
205
+ }
206
+ console.error("(or, from a ForgeDock checkout on Linux:)");
207
+ }
208
+ if (rest.includes("--outbound")) { // #5882: the agent dials this router; no agent URL, no inbound port
209
+ console.log(`OUTBOUND=1 pool/install/install-agent-linux.sh --router '${cfg.public_url}' --token '${r.data.code}'${flag("cpus") ? ` --cpus ${Number(flag("cpus"))}` : ""}${flag("mem") ? ` --mem ${Number(flag("mem"))}` : ""}`);
210
+ console.error(`(one-time code, expires ${r.data.expires_at}; outbound-only: the agent polls ${cfg.public_url})`);
211
+ break;
212
+ }
99
213
  const agentUrl = flag("agent-url"); // #5856: a host reachable only through an SSH tunnel (no Tailscale) enrolls with its tunnel URL
100
214
  if (agentUrl) {
101
215
  let u; try { u = new URL(agentUrl); } catch { u = null; }
@@ -0,0 +1,43 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5884: lane disk hard cap, pressure prune and fstrim for pool agents. Pure planners plus one best-effort runner;
4
+ // nothing here imports outside bin/pool (agent bundle closure).
5
+ import { execFile } from "node:child_process";
6
+
7
+ const GB = 1024;
8
+ const r1 = (n) => Math.round(n * 10) / 10;
9
+
10
+ /** GB used by lanes: running sandbox dirs (`sandboxMb` {id: MB}) plus this agent's cache volumes (`cacheVolumes` {name: {size_bytes}}). */
11
+ export function laneDiskUsedGb({ sandboxMb = {}, cacheVolumes = {} } = {}) {
12
+ const sb = Object.values(sandboxMb).reduce((a, mb) => a + (Number(mb) || 0), 0) / GB;
13
+ const cache = Object.values(cacheVolumes).reduce((a, v) => a + (Number(v?.size_bytes) || 0), 0) / 2 ** 30;
14
+ return r1(sb + cache);
15
+ }
16
+
17
+ /** 'ok' under the prune threshold (or no cap set), 'prune' from `pruneAtPct` of the cap, 'full' at or over the cap. */
18
+ export function planDiskCap({ usedGb, capGb, pruneAtPct = 80 }) {
19
+ const cap = Number(capGb);
20
+ if (!Number.isFinite(cap) || cap <= 0 || !Number.isFinite(usedGb)) return "ok";
21
+ if (usedGb >= cap) return "full";
22
+ return usedGb >= (cap * (Number(pruneAtPct) || 80)) / 100 ? "prune" : "ok";
23
+ }
24
+
25
+ /** fstrim is due when never run or `intervalS` (default 6 h) has passed; `force` after a pressure prune. */
26
+ export function fstrimDue({ now, last, intervalS = 6 * 3600, force = false }) {
27
+ return force || !Number.isFinite(last) || now - last >= intervalS * 1000;
28
+ }
29
+
30
+ /** argv for fstrim of `root`: through `sudo -n` when not root. */
31
+ export function fstrimArgv({ root = "/var/lib/docker", uid = process.getuid?.() ?? 0 } = {}) {
32
+ return uid === 0 ? ["fstrim", "-v", root] : ["sudo", "-n", "fstrim", "-v", root];
33
+ }
34
+
35
+ const execRun = (argv) => new Promise((resolve, reject) => {
36
+ execFile(argv[0], argv.slice(1), { timeout: 10 * 60000 }, (err, stdout) => (err ? reject(err) : resolve(String(stdout))));
37
+ });
38
+
39
+ /** Best-effort fstrim: `{ ok, out }` or `{ ok:false, error }`; never throws (unavailable fstrim, no sudo, unsupported fs). */
40
+ export async function runFstrim({ run = execRun, root, uid } = {}) {
41
+ try { return { ok: true, out: String(await run(fstrimArgv({ root, uid }))).trim() }; }
42
+ catch (e) { return { ok: false, error: String(e.stderr || e.message).slice(0, 200) }; }
43
+ }
@@ -58,6 +58,16 @@ export const dockerCli = {
58
58
  const out = await docker(["ps", "-a", "--format", "{{.Image}}"], { timeoutMs: 30000 });
59
59
  return out ? [...new Set(out.split("\n").filter(Boolean))] : [];
60
60
  },
61
+ /** #5891: freezes / thaws a container (its processes keep their state; the lane is paused, not failed). A gone container is not an error. */
62
+ async pause(name) { try { await docker(["pause", name], { timeoutMs: 20000 }); } catch (e) { if (!/No such container|already paused/i.test(e.stderr ?? "")) throw e; } },
63
+ async unpause(name) { try { await docker(["unpause", name], { timeoutMs: 20000 }); } catch (e) { if (!/No such container|not paused/i.test(e.stderr ?? "")) throw e; } },
64
+ /** #5891: dangling images (rebuildable) only; never a tagged or in-use one. */
65
+ async pruneImages() { return docker(["image", "prune", "-f"], { timeoutMs: 10 * 60000 }); },
66
+ /** #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
+ /** #5884: removes this agent's stopped containers and dangling images only (`label` carries the agent id, #5881). */
69
+ async containerPrune(label) { return docker(["container", "prune", "-f", ...[].concat(label).flatMap((l) => ["--filter", `label=${l}`])], { timeoutMs: 120000 }); },
70
+ async imagePrune(label) { return docker(["image", "prune", "-f", ...[].concat(label).flatMap((l) => ["--filter", `label=${l}`])], { timeoutMs: 120000 }); },
61
71
  async builderPrune(keepGb) { return docker(["builder", "prune", "-f", "--keep-storage", `${keepGb}gb`], { timeoutMs: 10 * 60000 }); },
62
72
  /** Volumes no container references (anonymous ones are named by 64 hex chars). */
63
73
  async listDanglingVolumes(label = []) {
@@ -66,3 +66,98 @@ export function hostDiskFree({ path = null, osrelease = readRelease, statfs = st
66
66
  return Number.isFinite(gb) ? { gb, path: drive } : null;
67
67
  } catch { return null; }
68
68
  }
69
+
70
+ /** #5923: WSL mirrored networking gives the guest a narrow source-port slice; docker MASQUERADE must stay inside it or replies drop. */
71
+ const DEFAULT_RANGE = [32768, 60999];
72
+ const NAT_BRIDGE_FMT = '{{.Name}}|{{index .Options "com.docker.network.bridge.name"}}|{{range .IPAM.Config}}{{.Subnet}} {{end}}';
73
+ const parseRange = (s) => { const m = /(\d+)\s+(\d+)/.exec(String(s ?? "")); return m ? [Number(m[1]), Number(m[2])] : null; };
74
+ const narrow = (r) => Boolean(r) && (r[0] > DEFAULT_RANGE[0] || r[1] < DEFAULT_RANGE[1]);
75
+
76
+ /** iptables arg lists (tcp and udp per subnet) pinning NAT source ports to `range` ([lo, hi]); subnets are {subnet, bridge}. */
77
+ export function natPinRules(range, subnets) {
78
+ const [lo, hi] = range;
79
+ return subnets.flatMap(({ subnet, bridge }) => ["tcp", "udp"].map((proto) => ["-t", "nat", "-I", "POSTROUTING", "1", "-s", subnet, "!", "-o", bridge, "-p", proto, "-j", "MASQUERADE", "--to-ports", `${lo}-${hi}`]));
80
+ }
81
+ const checkArgs = (rule) => ["-t", "nat", "-C", "POSTROUTING", ...rule.slice(5)];
82
+
83
+ /** Same rules as the installed script: the script text below is embedded verbatim in pool/install/install-agent.sh. */
84
+ export function natPinScript() {
85
+ return `#!/bin/sh
86
+ # cs-nat-portrange: pin docker NAT source ports to the guest ip_local_port_range (WSL mirrored networking)
87
+ set -eu
88
+ set -- $(sysctl -n net.ipv4.ip_local_port_range) || exit 0
89
+ lo=$1; hi=$2
90
+ [ "$lo" -gt 32768 ] || [ "$hi" -lt 60999 ] || exit 0
91
+ docker network ls --filter driver=bridge -q | while read -r id; do
92
+ info=$(docker network inspect -f '${NAT_BRIDGE_FMT}' "$id") || continue
93
+ name=\${info%%|*}; rest=\${info#*|}; bridge=\${rest%%|*}; subnets=\${rest#*|}
94
+ if [ -z "$bridge" ]; then if [ "$name" = bridge ]; then bridge=docker0; else bridge="br-$(echo "$id" | cut -c1-12)"; fi; fi
95
+ for subnet in $subnets; do
96
+ case "$subnet" in *:*) continue ;; esac
97
+ for proto in tcp udp; do
98
+ iptables -t nat -C POSTROUTING -s "$subnet" ! -o "$bridge" -p "$proto" -j MASQUERADE --to-ports "$lo-$hi" 2>/dev/null ||
99
+ iptables -t nat -I POSTROUTING 1 -s "$subnet" ! -o "$bridge" -p "$proto" -j MASQUERADE --to-ports "$lo-$hi"
100
+ done
101
+ done
102
+ done
103
+ `;
104
+ }
105
+ export function natPinUnit() {
106
+ return `[Unit]
107
+ Description=Pin docker NAT source ports to the WSL guest port range
108
+ After=docker.service
109
+ PartOf=docker.service
110
+
111
+ [Service]
112
+ Type=oneshot
113
+ RemainAfterExit=yes
114
+ ExecStart=/usr/local/sbin/cs-nat-portrange
115
+
116
+ [Install]
117
+ WantedBy=docker.service
118
+ `;
119
+ }
120
+
121
+ /** Every bridge network docker has (default 172.17.0.0/16 plus each custom one) as [{subnet, bridge}] (IPv4 only). */
122
+ export function bridgeSubnets({ run = sh } = {}) {
123
+ const out = [];
124
+ const ids = (run("docker", ["network", "ls", "--filter", "driver=bridge", "-q"]) ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
125
+ for (const id of ids) {
126
+ const info = (run("docker", ["network", "inspect", "-f", NAT_BRIDGE_FMT, id]) ?? "").trim();
127
+ const [name, opt, subs] = info.split("|");
128
+ if (subs === undefined) continue;
129
+ const bridge = opt || (name === "bridge" ? "docker0" : `br-${id.slice(0, 12)}`);
130
+ for (const subnet of subs.split(/\s+/).filter((s) => s && !s.includes(":"))) out.push({ subnet, bridge });
131
+ }
132
+ if (!out.length) out.push({ subnet: "172.17.0.0/16", bridge: "docker0" });
133
+ return out;
134
+ }
135
+
136
+ const guestRange = (run, read) => parseRange(run("sysctl", ["-n", "net.ipv4.ip_local_port_range"])) ?? (() => { try { return parseRange(read("/proc/sys/net/ipv4/ip_local_port_range")); } catch { return null; } })();
137
+ const isWsl = (osrelease) => { try { return /microsoft/i.test(String(osrelease() ?? "")); } catch { return false; } };
138
+ const isMirrored = (run, range) => { const m = run("wslinfo", ["--networking-mode"]); return m !== null ? /mirrored/i.test(m) : narrow(range); };
139
+
140
+ /** Idempotent: `iptables -C` before `-I`, per rule. `{ applied, range }`, or null when not a mirrored WSL guest. */
141
+ export function ensureNatPin({ run = sh, read = (p) => readFileSync(p, "utf8"), osrelease = readRelease } = {}) {
142
+ if (!isWsl(osrelease)) return null;
143
+ const range = guestRange(run, read);
144
+ if (!range || !isMirrored(run, range)) return null;
145
+ let applied = 0;
146
+ for (const rule of natPinRules(range, bridgeSubnets({ run }))) {
147
+ if (run("iptables", checkArgs(rule)) !== null) continue;
148
+ if (run("iptables", rule) !== null) applied++;
149
+ }
150
+ return { applied, range: `${range[0]}-${range[1]}` };
151
+ }
152
+
153
+ /** `/health` net block: `{ mirrored, port_range, nat_pin, degraded }`; degraded = mirrored without the pin. Off WSL: not mirrored, not degraded. */
154
+ export function netState({ osrelease = readRelease, read = (p) => readFileSync(p, "utf8"), run = sh } = {}) {
155
+ const off = { mirrored: false, port_range: null, nat_pin: null, degraded: false };
156
+ try {
157
+ if (!isWsl(osrelease)) return off;
158
+ const range = guestRange(run, read);
159
+ if (!isMirrored(run, range)) return { ...off, port_range: range ? `${range[0]}-${range[1]}` : null };
160
+ const pinned = Boolean(range) && natPinRules(range, bridgeSubnets({ run })).every((r) => run("iptables", checkArgs(r)) !== null);
161
+ return { mirrored: true, port_range: range ? `${range[0]}-${range[1]}` : null, nat_pin: pinned, degraded: !pinned };
162
+ } catch { return off; }
163
+ }