forgedock 1.67.0 → 1.68.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 (140) hide show
  1. package/bin/config-schema.mjs +1 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +99 -12
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +17 -1
  6. package/bin/help-text.mjs +1 -0
  7. package/bin/lean/admission.mjs +21 -0
  8. package/bin/lean/admission.test.mjs +30 -0
  9. package/bin/lean/advisory.test.mjs +25 -10
  10. package/bin/lean/amendment-schema.mjs +3 -4
  11. package/bin/lean/attempts.mjs +34 -31
  12. package/bin/lean/attempts.test.mjs +33 -19
  13. package/bin/lean/basered.mjs +26 -0
  14. package/bin/lean/batch-health.mjs +17 -12
  15. package/bin/lean/batch-health.test.mjs +39 -11
  16. package/bin/lean/batch.test.mjs +51 -2
  17. package/bin/lean/ci-gate.mjs +2 -90
  18. package/bin/lean/ci-gate.test.mjs +1 -127
  19. package/bin/lean/ci-precheck.mjs +25 -8
  20. package/bin/lean/ci-precheck.test.mjs +24 -0
  21. package/bin/lean/clear-breaker.test.mjs +4 -3
  22. package/bin/lean/commentstate.mjs +10 -5
  23. package/bin/lean/commentstate.test.mjs +12 -1
  24. package/bin/lean/conformance.e2e.test.mjs +9 -6
  25. package/bin/lean/conformance.mjs +56 -196
  26. package/bin/lean/conformance.test.mjs +40 -376
  27. package/bin/lean/depcache.mjs +100 -10
  28. package/bin/lean/depcache.test.mjs +105 -0
  29. package/bin/lean/docsgate.mjs +0 -32
  30. package/bin/lean/docsgate.test.mjs +2 -23
  31. package/bin/lean/effects-cap.test.mjs +9 -1
  32. package/bin/lean/effects-killtree.test.mjs +35 -0
  33. package/bin/lean/effects.mjs +42 -24
  34. package/bin/lean/engine-readmit.test.mjs +35 -0
  35. package/bin/lean/envgap.mjs +93 -0
  36. package/bin/lean/envgap.test.mjs +53 -0
  37. package/bin/lean/execution.mjs +10 -4
  38. package/bin/lean/execution.test.mjs +12 -0
  39. package/bin/lean/failure-census.mjs +170 -0
  40. package/bin/lean/failure-census.test.mjs +59 -0
  41. package/bin/lean/guardgate.test.mjs +2 -3
  42. package/bin/lean/heavy.mjs +33 -4
  43. package/bin/lean/heavy.test.mjs +38 -6
  44. package/bin/lean/hotarea.mjs +0 -36
  45. package/bin/lean/hotarea.test.mjs +1 -22
  46. package/bin/lean/issuewatch-verify.mjs +19 -4
  47. package/bin/lean/issuewatch.mjs +21 -4
  48. package/bin/lean/issuewatch.test.mjs +48 -1
  49. package/bin/lean/lane-audit-gap.mjs +66 -0
  50. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  51. package/bin/lean/lane-audit-llm.mjs +5 -0
  52. package/bin/lean/lane-audit-query.mjs +47 -0
  53. package/bin/lean/lane-audit-query.test.mjs +44 -0
  54. package/bin/lean/lane-audit-signatures.mjs +33 -0
  55. package/bin/lean/lane-audit.mjs +110 -0
  56. package/bin/lean/lane-audit.test.mjs +97 -0
  57. package/bin/lean/lane-recovery.test.mjs +33 -0
  58. package/bin/lean/lanecheck.mjs +5 -3
  59. package/bin/lean/lanecheck.test.mjs +6 -0
  60. package/bin/lean/lean.mjs +206 -148
  61. package/bin/lean/lean.test.mjs +406 -190
  62. package/bin/lean/limits.mjs +17 -0
  63. package/bin/lean/limits.test.mjs +15 -1
  64. package/bin/lean/live-execution.mjs +21 -2
  65. package/bin/lean/live-execution.test.mjs +39 -0
  66. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  67. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  68. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  69. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  70. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  71. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  72. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  73. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  74. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  75. package/bin/lean/orchestrate.mjs +188 -33
  76. package/bin/lean/postdeploy-check.test.mjs +1 -3
  77. package/bin/lean/precheck.mjs +20 -0
  78. package/bin/lean/preflight.mjs +100 -11
  79. package/bin/lean/preflight.test.mjs +44 -4
  80. package/bin/lean/prompts.mjs +10 -21
  81. package/bin/lean/recurrence.mjs +6 -148
  82. package/bin/lean/recurrence.test.mjs +11 -147
  83. package/bin/lean/release-flakes.mjs +14 -2
  84. package/bin/lean/release-flakes.test.mjs +17 -1
  85. package/bin/lean/release-ledger.mjs +19 -1
  86. package/bin/lean/release-ledger.test.mjs +23 -0
  87. package/bin/lean/release-preflight.mjs +28 -0
  88. package/bin/lean/release-preflight.test.mjs +42 -1
  89. package/bin/lean/release-review.mjs +40 -5
  90. package/bin/lean/release-review.test.mjs +43 -2
  91. package/bin/lean/release.mjs +43 -14
  92. package/bin/lean/release.test.mjs +32 -0
  93. package/bin/lean/retry.mjs +1 -1
  94. package/bin/lean/retry.test.mjs +6 -1
  95. package/bin/lean/rotator.mjs +9 -0
  96. package/bin/lean/rotator.test.mjs +11 -1
  97. package/bin/lean/sandbox-remote.mjs +16 -9
  98. package/bin/lean/schedd.mjs +11 -6
  99. package/bin/lean/schedd.test.mjs +65 -5
  100. package/bin/lean/selfreview.mjs +1 -1
  101. package/bin/lean/statuscomment.mjs +4 -1
  102. package/bin/lean/validate-catalog.mjs +108 -0
  103. package/bin/lean/validate-catalog.test.mjs +46 -1
  104. package/bin/lean/verify.mjs +1 -1
  105. package/bin/pool/affinity.test.mjs +91 -0
  106. package/bin/pool/agent.mjs +143 -9
  107. package/bin/pool/cache-sweep.mjs +31 -10
  108. package/bin/pool/ci-autoscale.mjs +160 -0
  109. package/bin/pool/cli.mjs +37 -8
  110. package/bin/pool/docker.mjs +3 -0
  111. package/bin/pool/engine-placement.test.mjs +94 -0
  112. package/bin/pool/lane-target.mjs +41 -0
  113. package/bin/pool/lane-tools.mjs +7 -2
  114. package/bin/pool/lane-tools.test.mjs +9 -0
  115. package/bin/pool/mirror-seed.mjs +15 -11
  116. package/bin/pool/router.mjs +88 -32
  117. package/bin/pool/version.mjs +29 -2
  118. package/bin/review-staging.mjs +11 -3
  119. package/bin/runner.mjs +59 -11
  120. package/bin/stats/release.mjs +7 -0
  121. package/bin/stats/release.test.mjs +20 -0
  122. package/bin/stats/scorecard.mjs +187 -0
  123. package/bin/stats/scorecard.test.mjs +89 -0
  124. package/docs/CONFIG.md +41 -0
  125. package/docs/OUTCOME-CODES.md +1 -0
  126. package/docs/STATS.md +17 -0
  127. package/package.json +1 -1
  128. package/pool/image/Dockerfile +14 -2
  129. package/pool/image/manifest.json +25 -0
  130. package/pool/image/mirror.sh +11 -2
  131. package/pool/install/install-agent.ps1 +11 -4
  132. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  133. package/scripts/ci-local/cli.mjs +1 -1
  134. package/scripts/ci-local/plan.mjs +3 -2
  135. package/scripts/ci-local.test.sh +11 -0
  136. package/scripts/failure-census.mjs +67 -0
  137. package/scripts/review-finalize.sh +5 -5
  138. package/scripts/review-finalize.test.sh +8 -1
  139. package/scripts/verify-phase-trail.sh +11 -0
  140. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -7,6 +7,7 @@
7
7
  * base-drift classifier. Pure; lean.mjs owns every effect.
8
8
  */
9
9
 
10
+ import { posix } from "node:path";
10
11
  import { venvPythonRewrite } from "./preflight.mjs";
11
12
 
12
13
  /** Default CI sources read for the derived catalogue (repo-relative). */
@@ -108,3 +109,110 @@ export function rewriteSubprojectVenv(contract, files, exists) {
108
109
  if (t && typeof t === "object" && typeof t.command === "string") out.repro_test = { ...t, command: fix("repro_test", t.command) };
109
110
  return applied.length ? { contract: out, applied } : { contract, applied };
110
111
  }
112
+
113
+ const CI_PY_RUNNER_RE = /\b((?:poetry|uv) run(?: +--[\w-]+(?:[ =][^\s|&;-][^\s|&;]*)?)*) +(?:python3? +-m +)?pytest\b([^\n|&;]*)/; // PY_RUNNER_RE's option grammar
114
+ const PYTEST_SEG_RE = /^(\s*(?:[A-Za-z_]\w*=\S*\s+)*)((?:\S*\/)?\.venv\/bin\/python3?\s+-m\s+pytest|(?:\S*\/)?\.venv\/bin\/pytest|python3?(?:\.\d+)?\s+-m\s+pytest|pytest)(?=\s|$)(.*)$/s;
115
+ const normRel = (p) => { const n = posix.normalize(String(p).replace(/^\.\//, "").replace(/\/+$/, "")); return n === "" ? "." : n.replace(/\/+$/, ""); };
116
+ const under = (p, root) => (root === "." ? !p.startsWith("..") : p === root || p.startsWith(`${root}/`));
117
+ const pathish = (x) => !!x && !x.startsWith("-") && !x.startsWith("$") && !x.includes("=") && (x.includes("/") || /\.py(?:::|$)/.test(x) || x === ".");
118
+ const indent = (l) => /^\s*/.exec(l)[0].length;
119
+
120
+ /**
121
+ * #5753: which env the repo's own CI runs each Python test path in, parsed from CI text (0 LLM calls). Every `poetry run` /
122
+ * `uv run` pytest line, with its step's `working-directory:` (and an inline `cd X &&`), becomes {dir, runner, paths}: `paths`
123
+ * are repo-relative (`../../shared` under `services/worker` is `shared`); no path argument means the whole `dir`. Pure.
124
+ */
125
+ export function deriveTestEnvMap(texts) {
126
+ const out = [], seen = new Set();
127
+ for (const text of (Array.isArray(texts) ? texts : [texts]).filter((t) => typeof t === "string")) {
128
+ const lines = text.split("\n");
129
+ for (let i = 0; i < lines.length; i++) {
130
+ const m = CI_PY_RUNNER_RE.exec(lines[i]);
131
+ if (!m) continue;
132
+ let s = i;
133
+ while (s > 0 && !/^\s*-\s/.test(lines[s])) s--; // the step this line belongs to
134
+ let e = s + 1;
135
+ while (e < lines.length && !(lines[e].trim() && indent(lines[e]) <= indent(lines[s]))) e++;
136
+ const wd = lines.slice(s, e).map((l) => /^\s*-?\s*working-directory:\s*["']?([^"'\s#]+)/.exec(l)).find(Boolean);
137
+ if (wd && wd[1].includes("$")) continue;
138
+ let dir = wd ? normRel(wd[1]) : ".";
139
+ const cd = /\bcd\s+["']?([^"'\s&;]+)["']?\s*&&[^&|;]*$/.exec(lines[i].slice(0, m.index));
140
+ if (cd) {
141
+ if (cd[1].includes("$") || cd[1].startsWith("/")) continue;
142
+ dir = normRel(posix.join(dir, cd[1]));
143
+ }
144
+ if (dir.startsWith("..")) continue;
145
+ const args = m[2].trim().split(/\s+/).filter(pathish).map((x) => x.replace(/::.*$/, ""));
146
+ const paths = (args.length ? args : ["."]).map((p) => normRel(posix.join(dir, p))).filter((p) => !p.startsWith(".."));
147
+ const runner = m[1].trim(), key = `${dir}|${runner}|${paths.join(",")}`;
148
+ if (paths.length && !seen.has(key)) { seen.add(key); out.push({ dir, runner, paths }); }
149
+ }
150
+ }
151
+ return out;
152
+ }
153
+
154
+ /** #5753: one pytest segment run from `cwd` -> {dir, cmd} in its CI env (or its lock's runner), or null when it stays. */
155
+ function ciEnvSegment(seg, cwd, map, files, exists) {
156
+ const m = PYTEST_SEG_RE.exec(seg);
157
+ if (!m) return null;
158
+ const [, envs, interp, rest] = m;
159
+ const venv = /^(\S*?)\.venv\/bin\/(\S+)/.exec(interp);
160
+ if (venv && exists(normRel(posix.join(cwd, `${venv[1]}.venv/bin/${venv[2]}`)))) return null; // #5683: a venv that resolves stays
161
+ const toks = rest.trim() ? rest.trim().split(/\s+/) : [];
162
+ const tests = toks.filter(pathish).map((x) => normRel(posix.join(cwd, x.replace(/::.*$/, ""))));
163
+ const all = tests.length ? tests : [cwd];
164
+ const hit = all.some((p) => p.startsWith("..")) ? null : map.find((en) => all.every((p) => en.paths.some((root) => under(p, root))));
165
+ if (hit) {
166
+ const reRel = (x) => { const [p, ...id] = x.split("::"); return [posix.relative(hit.dir === "." ? "" : hit.dir, normRel(posix.join(cwd, p))) || ".", ...id].join("::"); };
167
+ const args = toks.map((x) => (pathish(x) ? reRel(x) : x));
168
+ return { dir: hit.dir, cmd: `${envs}${hit.runner} pytest${args.length ? ` ${args.join(" ")}` : ""}` };
169
+ }
170
+ if (!venv) return null; // a bare interpreter CI does not map stays (rewriteSubprojectVenv owns the sub-project venv case)
171
+ const proj = normRel(posix.join(cwd, venv[1] || "."));
172
+ if (proj !== cwd) return null;
173
+ const at = (f) => (proj === "." ? f : `${proj}/${f}`);
174
+ const runner = files.includes(at("poetry.lock")) ? "poetry run" : files.includes(at("uv.lock")) ? "uv run" : null;
175
+ return runner ? { dir: cwd, cmd: `${envs}${runner} pytest${rest.replace(/\s+$/, "")}` } : null;
176
+ }
177
+
178
+ /**
179
+ * #5753: the repro and validate pytest commands that run under a bare interpreter (`python -m pytest`, `pytest`) or a
180
+ * `.venv/bin/python` that does not exist, for test paths CI runs in another env (`map`: deriveTestEnvMap), become
181
+ * `cd <dir> && <runner> pytest <dir-relative paths>`. With no map entry, a missing `.venv` with a poetry.lock / uv.lock next
182
+ * to it runs through `poetry run` / `uv run`. Commands already using poetry/uv run, a venv that resolves and unmapped bare
183
+ * commands are unchanged. `files`: tracked paths; `exists(rel)`: repo-relative check. Returns {contract, applied[{id, from, to}]}.
184
+ */
185
+ export function rewriteToCiEnv(contract, map = [], files = [], exists = () => false) {
186
+ if (!contract || typeof contract !== "object") return { contract, applied: [] };
187
+ const fix1 = (command) => {
188
+ const parts = String(command).split(/(&&|\|\||;|\||\n)/);
189
+ let cwd = ".", onlyCd = true, changed = false;
190
+ const out = [];
191
+ for (let i = 0; i < parts.length; i++) {
192
+ const seg = parts[i];
193
+ if (i % 2) { out.push(seg); continue; }
194
+ const cd = /^\s*cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(seg);
195
+ if (cd) {
196
+ const t = cd[1] ?? cd[2] ?? cd[3];
197
+ cwd = cwd === "?" || t.startsWith("/") || t.startsWith("$") ? "?" : normRel(posix.join(cwd, t));
198
+ if (cwd.startsWith("..")) cwd = "?";
199
+ out.push(seg); continue;
200
+ }
201
+ const r = cwd === "?" || /\b(?:poetry|uv)\s+(?:-\S+\s+)*run\b/.test(seg) ? null : ciEnvSegment(seg, cwd, map, files, exists);
202
+ if (!r) { onlyCd = false; out.push(seg); continue; }
203
+ changed = true;
204
+ const lead = /^\s*/.exec(seg)[0], tail = /\s*$/.exec(seg)[0], cmd = r.cmd.trim(), last = i === parts.length - 1;
205
+ if (onlyCd && last) { out.length = 0; out.push(r.dir === "." ? cmd : `cd ${r.dir} && ${cmd}`); } // leading cds give way to the env's dir
206
+ else if (r.dir === cwd) out.push(`${lead}${cmd}${tail}`);
207
+ else { const rel = posix.relative(cwd === "." ? "" : cwd, r.dir === "." ? "" : r.dir) || "."; out.push(`${lead}${last ? `cd ${rel} && ${cmd}` : `(cd ${rel} && ${cmd})`}${tail}`); } // later segments keep their cwd
208
+ onlyCd = false;
209
+ }
210
+ return changed ? out.join("") : String(command);
211
+ };
212
+ const applied = [], fix = (id, cmd) => { const to = fix1(cmd); if (to !== cmd) applied.push({ id, from: cmd, to }); return to; };
213
+ const out = { ...contract };
214
+ if (Array.isArray(contract.validate)) out.validate = contract.validate.map((v) => (v && typeof v.command === "string" ? { ...v, command: fix(v.id, v.command) } : v));
215
+ const t = contract.repro_test;
216
+ if (t && typeof t === "object" && typeof t.command === "string") out.repro_test = { ...t, command: fix("repro_test", t.command) };
217
+ return applied.length ? { contract: out, applied } : { contract, applied };
218
+ }
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { deriveCatalog, mergeRecipes, rewriteMissed, extractTestIds, equivalentRuns, isDriftFailure, rewriteSubprojectVenv } from "./validate-catalog.mjs";
5
+ import { deriveCatalog, mergeRecipes, rewriteMissed, extractTestIds, equivalentRuns, isDriftFailure, rewriteSubprojectVenv, deriveTestEnvMap, rewriteToCiEnv } from "./validate-catalog.mjs";
6
6
  import { applyValidateRecipes } from "./conformance.mjs";
7
7
 
8
8
  const CI = "run: uv run --with-requirements r.txt pytest tests\nrun: npx vitest run";
@@ -56,3 +56,48 @@ describe("#5683 sub-project venv rewrite", () => {
56
56
  assert.equal(rewriteSubprojectVenv(same, files, exists).contract, same);
57
57
  });
58
58
  });
59
+
60
+ describe("#5753 CI test-env map: a test path runs in the env CI runs it in", () => {
61
+ const CI = [
62
+ "jobs:",
63
+ " worker:",
64
+ " steps:",
65
+ " - uses: actions/checkout@v4",
66
+ " - name: Test worker",
67
+ " working-directory: services/worker",
68
+ " run: poetry run pytest tests/ ../../shared -q",
69
+ " - run: |",
70
+ " cd services/api && uv run --frozen pytest",
71
+ "",
72
+ ].join("\n");
73
+ it("deriveTestEnvMap reads working-directory, inline cd and poetry/uv run pytest paths, repo-relative", () => {
74
+ assert.deepEqual(deriveTestEnvMap([CI, ""]), [
75
+ { dir: "services/worker", runner: "poetry run", paths: ["services/worker/tests", "shared"] },
76
+ { dir: "services/api", runner: "uv run --frozen", paths: ["services/api"] },
77
+ ]);
78
+ assert.deepEqual(deriveTestEnvMap(["run: python -m pytest tests", "run: npm test"]), [], "a bare interpreter or no pytest is no env");
79
+ });
80
+ it("a shared/ pytest under a bare interpreter is rewritten to the services/worker env", () => {
81
+ const map = deriveTestEnvMap(CI);
82
+ const c = { validate: [{ id: "V1", command: "python -m pytest shared/detection/test_x.py" }, { id: "V2", command: "cd shared && python3 -m pytest -q detection/test_x.py::test_a" }, { id: "V3", command: "pytest services/api/tests/t.py && echo ok" }] };
83
+ const r = rewriteToCiEnv(c, map, [], () => false);
84
+ assert.deepEqual(r.contract.validate.map((v) => v.command), [
85
+ "cd services/worker && poetry run pytest ../../shared/detection/test_x.py",
86
+ "cd services/worker && poetry run pytest -q ../../shared/detection/test_x.py::test_a",
87
+ "(cd services/api && uv run --frozen pytest tests/t.py) && echo ok",
88
+ ]);
89
+ assert.deepEqual(r.applied.map((a) => a.id), ["V1", "V2", "V3"]);
90
+ });
91
+ it("wrapped, unmapped and resolving-venv commands stay byte-identical", () => {
92
+ const map = deriveTestEnvMap(CI);
93
+ const c = { validate: [{ id: "V1", command: "cd services/worker && poetry run pytest tests" }, { id: "V2", command: "uv run pytest shared/t.py" }, { id: "V3", command: "python -m pytest other/test_y.py" }, { id: "V4", command: "services/worker/.venv/bin/python -m pytest shared/t.py" }], repro_test: { command: "node --test x.test.mjs" } };
94
+ const r = rewriteToCiEnv(c, map, [], (rel) => rel === "services/worker/.venv/bin/python");
95
+ assert.equal(r.contract, c); assert.deepEqual(r.applied, []);
96
+ });
97
+ it("a .venv/bin/python that does not exist falls back to the lock's runner; no lock leaves it", () => {
98
+ const c = { repro_test: { command: "cd services/x && .venv/bin/python -m pytest t.py" } };
99
+ assert.equal(rewriteToCiEnv(c, [], ["services/x/poetry.lock"], () => false).contract.repro_test.command, "cd services/x && poetry run pytest t.py");
100
+ assert.equal(rewriteToCiEnv(c, [], ["services/x/uv.lock"], () => false).contract.repro_test.command, "cd services/x && uv run pytest t.py");
101
+ assert.equal(rewriteToCiEnv(c, [], [], () => false).contract, c);
102
+ });
103
+ });
@@ -300,7 +300,7 @@ export async function cancelSuperseded({ io, branch, head, mode = "off", pushedA
300
300
  return out;
301
301
  }
302
302
 
303
- const VALIDATE_KINDS = ["validate_missing", "validate_failed"], REQUIREMENT_KINDS = ["requirement_unimplemented", "untracked_deferral"];
303
+ const VALIDATE_KINDS = ["validate_missing", "validate_failed"], REQUIREMENT_KINDS = ["requirement_unimplemented", "requirement_no_status", "untracked_deferral"];
304
304
  /**
305
305
  * #4270: the `forgedock/verify` check-run payload from the results the lane already computed (no gate logic of its own).
306
306
  * commands: [{command, rc}] of the last declared-check round, or null (none configured); structure: the structure delta or
@@ -0,0 +1,91 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #6041: per-repo agent affinity (repos.<slug>.agents / exclude_agents) shared by launch, claim, seedAgent and the capacity views.
4
+ import { test } from "node:test";
5
+ import { Readable } from "node:stream";
6
+ import assert from "node:assert/strict";
7
+ import { createRouter } from "./router.mjs";
8
+ import { httpTransport } from "../lean/sandbox-remote.mjs";
9
+ import { tmpDir } from "../tests/_tmp.mjs";
10
+
11
+ const quiet = { info() {}, warn() {}, error() {} };
12
+ const json = (o, status = 200) => new Response(JSON.stringify(o), { status, headers: { "content-type": "application/json" } });
13
+ const spec = (id, slug = "o/x") => ({ id, issue: 1, batch: "b", repo: { slug, url: `https://github.com/${slug}.git` }, command: ["x"] });
14
+
15
+ function fixture(repos, hosts = ["a", "b", "c"]) {
16
+ const posts = [];
17
+ const fetchFn = async (url, init) => {
18
+ const u = new URL(url);
19
+ if (u.pathname === "/capacity") return json({ cpus_free: 8 - hosts.indexOf(u.hostname), mem_free_gb: 16 });
20
+ posts.push(`${u.hostname}${u.pathname}`);
21
+ const p = JSON.parse(init.body);
22
+ return json({ id: p.spec.id, state: "running" }, u.pathname === "/warm/claim" ? 200 : 201);
23
+ };
24
+ const router = createRouter({ state_dir: tmpDir("cs-aff-"), lane: { cpus: 2, mem_gb: 3 }, enroll_token: "e", forgedock_token: "fd", repos }, { fetchFn, now: () => 5_000_000, log: quiet });
25
+ for (const n of hosts) router.store.data.agents[n] = { url: `http://${n}:7711`, token: "t" };
26
+ return { router, posts };
27
+ }
28
+ const placed = async (router, id, slug) => (await router.launch(spec(id, slug))).body.agent;
29
+
30
+ test("allowlist: every launch for the repo goes to an allowed agent", async () => {
31
+ const { router } = fixture({ "o/x": { agents: ["b"] } });
32
+ for (let i = 0; i < 3; i++) assert.equal(await placed(router, `l${i}`, "o/x"), "b");
33
+ assert.equal(await placed(router, "other", "o/y"), "a"); // another repo is unrestricted
34
+ });
35
+
36
+ test("allowlist with no live allowed agent defers, never lands elsewhere", async () => {
37
+ const { router, posts } = fixture({ "o/x": { agents: ["zz"] } });
38
+ const r = await router.launch(spec("d1"));
39
+ assert.equal(r.status, 503);
40
+ assert.deepEqual(posts, []);
41
+ });
42
+
43
+ test("exclude list and both combine", async () => {
44
+ assert.equal(await placed(fixture({ "o/x": { exclude_agents: ["a"] } }).router, "e1", "o/x"), "b");
45
+ const { router } = fixture({ "o/x": { agents: ["a", "b"], exclude_agents: ["a"] } });
46
+ assert.equal(await placed(router, "e2", "o/x"), "b");
47
+ });
48
+
49
+ test("unset, empty or non-array config keeps today's placement (best host first)", async () => {
50
+ for (const repos of [{}, { "o/x": {} }, { "o/x": { agents: [] } }, { "o/x": { agents: "b" } }]) {
51
+ assert.equal(await placed(fixture(repos).router, "u1", "o/x"), "a");
52
+ }
53
+ });
54
+
55
+ test("claim honours the allowlist", async () => {
56
+ const { router, posts } = fixture({ "o/x": { agents: ["c"] } });
57
+ const r = await router.claim(spec("c1"));
58
+ assert.equal(r.body.agent, "c");
59
+ assert.deepEqual(posts, ["c/warm/claim"]);
60
+ });
61
+
62
+ test("seed pick honours the allowlist", async () => {
63
+ const { router, posts } = fixture({ "o/x": { agents: ["b"] } });
64
+ const call = (method, path, body) => new Promise((resolve) => {
65
+ const r = Readable.from(body ? [Buffer.from(JSON.stringify(body))] : []);
66
+ Object.assign(r, { method, url: path, headers: { authorization: "Bearer fd", "content-type": "application/json" }, socket: { remoteAddress: "127.0.0.1" } });
67
+ const chunks = []; const res = { writeHead() { return res; }, setHeader() {}, write(c) { chunks.push(c); }, end(c) { if (c) chunks.push(c); resolve(Buffer.concat(chunks.map(Buffer.from)).toString()); } };
68
+ router.handle(r, res);
69
+ });
70
+ await call("POST", "/sandboxes/s1/seed", { slug: "o/x", data_b64: "AA" });
71
+ assert.deepEqual(posts, ["b/mirrors/seed"]);
72
+ });
73
+
74
+ test("status(repo) counts only the allowed agents; no repo counts all", async () => {
75
+ const { router } = fixture({ "o/x": { agents: ["b", "c"], exclude_agents: ["c"] } });
76
+ assert.equal((await router.status()).total, 3);
77
+ const s = await router.status("o/x");
78
+ assert.equal(s.total, 1); assert.equal(s.online, 1); assert.equal(s.agents[0].name, "b");
79
+ assert.equal((await router.status("o/y")).total, 3);
80
+ });
81
+
82
+ test("transport.capacity appends ?repo= to /status and /agents only when a repo is given", async () => {
83
+ const urls = [];
84
+ const fetchFn = async (url) => { urls.push(url); return json({ agents: [{ ok: true, name: "a" }] }); };
85
+ const t = httpTransport({ endpoint: "http://pool", fetchFn });
86
+ await t.capacity();
87
+ assert.deepEqual(urls, ["http://pool/status", "http://pool/agents"]);
88
+ urls.length = 0;
89
+ await t.capacity({ repo: "o/x y" });
90
+ assert.deepEqual(urls, ["http://pool/status?repo=o%2Fx%20y", "http://pool/agents?repo=o%2Fx%20y"]);
91
+ });
@@ -16,10 +16,24 @@ import { makeWarm } from "./warm.mjs";
16
16
  import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
17
17
  import { hostDiskFree, hostMemFree, ensureNatPin, netState } from "./health.mjs";
18
18
  import { laneDiskUsedGb, planDiskCap, fstrimDue, runFstrim } from "./disk.mjs";
19
+ import { step as laneStep, drainState, pressured } from "./lane-target.mjs";
19
20
  import { makeMirrorSeed, dockerRunner } from "./mirror-seed.mjs";
20
21
  import { planIdleEviction, CACHE_LABEL, agentLabel } from "./cache-sweep.mjs";
22
+ import { cpuQuotaEnv } from "./docker.mjs";
21
23
 
22
24
  const LABEL = "computeshare=1";
25
+ /** #5695: ephemeral CI runner containers; a different label than LABEL so the orphan reaper never removes them. */
26
+ const RUNNER_LABEL = "computeshare.runner=1";
27
+ const RUNNER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
28
+ const netSample = { at: 0, rx: 0 };
29
+ /** Host RX rate in MB/s since the previous call (null on the first call or when /proc/net/dev is unreadable). */
30
+ export function netRx(now = Date.now(), read = () => readFileSync("/proc/net/dev", "utf8")) {
31
+ try {
32
+ const rx = read().split("\n").slice(2).map((l) => l.trim().split(/[:\s]+/)).filter((c) => c[0] && c[0] !== "lo").reduce((a, c) => a + (Number(c[1]) || 0), 0);
33
+ const prev = { ...netSample }; netSample.at = now; netSample.rx = rx;
34
+ return prev.at && now > prev.at && rx >= prev.rx ? { rx_mbps: Math.round(((rx - prev.rx) / 1e6 / ((now - prev.at) / 1000)) * 100) / 100 } : null;
35
+ } catch { return null; }
36
+ }
23
37
  const LOG_CHUNK = 256 * 1024;
24
38
  const run = promisify(execFile);
25
39
 
@@ -172,7 +186,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
172
186
  if (rows.length < (cfg.estimate_min_samples ?? 3)) return { cpus: slice.cpus, mem: slice.mem, samples: rows.length };
173
187
  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 };
174
188
  }
175
- 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 });
189
+ const runners = () => (store.data.runners ??= {}); // #5695: name -> {label, cpus, mem_gb, startedAt}; counted like a lane
190
+ const used = () => Object.values({ ...sb(), ...Object.fromEntries(Object.entries(runners()).map(([k, r]) => [`runner:${k}`, { cpus: r.cpus, mem_gb: r.mem_gb }])) }).filter((s) => s.state !== "exited").reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
176
191
  // #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
177
192
  let diskCache = { at: 0, mb: {} };
178
193
  let lastWorkSweep = -Infinity;
@@ -263,7 +278,55 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
263
278
  const PRIORITIES = ["reserved", "normal", "borrow"];
264
279
  const reservations = () => (Array.isArray(cfg.reservations) ? cfg.reservations.filter((r) => r && typeof r.name === "string" && r.cpus > 0 && r.mem_gb > 0) : []);
265
280
  const prioOf = (r) => r.priority ?? "normal";
266
- 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 });
281
+ const peakUse = () => 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 });
282
+ // #6047: heavy tokens (cfg.elastic_lanes, default off). A lane is admitted on its base reservation; each heavy step leases a token
283
+ // (weight = max(default, p90 history - base)) from this host's pool. Tokens live in store.data.heavy and expire with their lease,
284
+ // when the sandbox exits or when it is destroyed.
285
+ const elastic = () => cfg.elastic_lanes === true;
286
+ const heavyTtlMs = () => (cfg.heavy_ttl_s ?? 300) * 1000;
287
+ const heavyDefault = () => ({ cpus: cfg.heavy_weight?.cpus ?? 1, mem: cfg.heavy_weight?.mem_gb ?? 2 });
288
+ const heavyTokens = () => (store.data.heavy ??= {});
289
+ function heavyHeld() {
290
+ let dropped = false;
291
+ for (const [k, t] of Object.entries(heavyTokens())) { const r = sb()[t.sandbox]; if (t.expires <= now() || !r || r.state === "exited") { delete heavyTokens()[k]; dropped = true; } }
292
+ if (dropped) store.save();
293
+ return Object.values(heavyTokens()).reduce((a, t) => ({ cpus: a.cpus + t.cpus, mem: a.mem + t.mem, n: a.n + 1 }), { cpus: 0, mem: 0, n: 0 });
294
+ }
295
+ const baseUse = () => activeRecs().reduce((a, r) => ({ cpus: a.cpus + r.cpus, mem: a.mem + r.mem_gb }), { cpus: 0, mem: 0 });
296
+ /** Elastic: base reservations plus held tokens; flat: each lane's projected peak (#5858). */
297
+ const projectedUse = () => { if (!elastic()) return peakUse(); const b = baseUse(), h = heavyHeld(); return { cpus: b.cpus + h.cpus, mem: b.mem + h.mem }; };
298
+ /** Lane ceiling derived from the token pool when elastic: a multiple of the default-weight heavy steps the host holds. */
299
+ function derivedCeiling() {
300
+ const e = effectiveCapacity(), w = heavyDefault();
301
+ return Math.max(1, Math.floor(Math.min((e.cpus - coTenant.cpus) / w.cpus, (e.mem - coTenant.mem_gb) / w.mem) * (cfg.elastic_lane_factor ?? 3)));
302
+ }
303
+ function heavyAcquire(r) {
304
+ const held = heavyHeld(), mine = Object.entries(heavyTokens()).find(([, t]) => t.sandbox === r.id);
305
+ const ttl = Math.round(heavyTtlMs() / 1000);
306
+ if (mine) { mine[1].refs = (mine[1].refs ?? 1) + 1; mine[1].expires = now() + heavyTtlMs(); store.save(); return { status: 200, body: { granted: true, token: mine[0], ttl_s: ttl } }; }
307
+ const est = estimateFor(r.repo ?? null, { cpus: r.cpus, mem: r.mem_gb }), d = heavyDefault();
308
+ const w = { cpus: Math.max(d.cpus, est.cpus - r.cpus), mem: Math.max(d.mem, est.mem - r.mem_gb) };
309
+ const e = effectiveCapacity(), b = baseUse(), live_ = live(cfg), ram = Number.isFinite(live_?.mem_available_gb) ? live_.mem_available_gb : Infinity;
310
+ const fits = b.cpus + held.cpus + w.cpus <= e.cpus - coTenant.cpus + 1e-9 && b.mem + held.mem + w.mem <= e.mem - coTenant.mem_gb + 1e-9 && w.mem <= ram + 1e-9;
311
+ if (held.n > 0 && !fits) return { status: 200, body: { granted: false, retry_after_s: 15, held: held.n } }; // the first holder always runs: a step larger than the host must not starve
312
+ const token = randomBytes(12).toString("hex");
313
+ heavyTokens()[token] = { sandbox: r.id, cpus: w.cpus, mem: w.mem, at: now(), refs: 1, expires: now() + heavyTtlMs() };
314
+ store.save();
315
+ return { status: 200, body: { granted: true, token, ttl_s: ttl, weight: { cpus: w.cpus, mem_gb: w.mem } } };
316
+ }
317
+ function heavyTouch(r, action, token) {
318
+ heavyHeld();
319
+ const t = heavyTokens()[token];
320
+ if (!t || t.sandbox !== r.id) return { status: 200, body: { ok: action === "release", granted: false } };
321
+ if (action === "release") { if ((t.refs = (t.refs ?? 1) - 1) <= 0) delete heavyTokens()[token]; } else t.expires = now() + heavyTtlMs();
322
+ store.save();
323
+ return { status: 200, body: { ok: true, granted: action === "renew" } };
324
+ }
325
+ function heavyView() {
326
+ if (!elastic()) return {};
327
+ const h = heavyHeld(), e = effectiveCapacity(), b = baseUse();
328
+ return { elastic_lanes: true, heavy_tokens: h.n, heavy_held: { cpus: r2(h.cpus), mem_gb: r2(h.mem) }, cpus_free_elastic: r2(e.cpus - b.cpus - h.cpus - coTenant.cpus), mem_free_gb_elastic: r2(e.mem - b.mem - h.mem - coTenant.mem_gb), lanes_ceiling_derived: derivedCeiling() };
329
+ }
267
330
  const sumRecs = (rs) => rs.reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
268
331
  const weighted = () => reservations().length > 0 || Boolean(cfg.idle_only);
269
332
  const SHARES = () => ({ reserved: 4096, normal: 1024, borrow: 128, throttled: 2, ...(cfg.cpu_shares ?? {}) });
@@ -343,9 +406,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
343
406
  }
344
407
  /** #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. */
345
408
  let policyPaused = Boolean(cfg.policy_paused);
409
+ const laneS = { target: null, greenSince: null, busySince: null };
410
+ const laneTargetOn = () => cfg.lane_autoscale !== false && Number.isInteger(cfg.max_lanes) && cfg.max_lanes >= 1;
411
+ const laneNow = () => laneS.target ?? Math.min(cfg.max_lanes, cfg.lane_start ?? 1);
346
412
  function applyPolicy(body) {
347
413
  const p = body && typeof body === "object" ? body : {}, int = (v, lo, hi) => (Number.isInteger(v) && v >= lo && v <= hi);
348
- 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")
414
+ 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") || (p.elastic_lanes !== undefined && typeof p.elastic_lanes !== "boolean")
349
415
  || (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" } };
350
416
  const set = {};
351
417
  if (p.cpus !== undefined) set.allow_cpus = p.cpus;
@@ -353,6 +419,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
353
419
  if (p.idle_only !== undefined) set.idle_only = p.idle_only;
354
420
  if (p.floors?.host_disk_gb !== undefined) set.host_disk_floor_gb = p.floors.host_disk_gb;
355
421
  if (p.paused !== undefined) set.policy_paused = p.paused;
422
+ if (p.elastic_lanes !== undefined) set.elastic_lanes = p.elastic_lanes;
356
423
  if (cfg.config_path) {
357
424
  try { const c = JSON.parse(readFileSync(cfg.config_path, "utf8")); writeFileSync(cfg.config_path, JSON.stringify({ ...c, ...set }, null, 2), { mode: 0o600 }); }
358
425
  catch (e) { log.warn?.(`policy not persisted: ${e.message}`); }
@@ -374,7 +441,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
374
441
  const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
375
442
  const e = effectiveCapacity();
376
443
  const h = live(cfg);
377
- return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), net: readNet(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
444
+ return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), ...heavyView(), runners: Object.entries(runners()).map(([name, r]) => ({ name, label: r.label })), net: (() => { const rx = netRx(now()); const n = readNet(); return rx ? { ...(n ?? {}), ...rx } : n; })(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, ...laneTargetView(), ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
378
445
  }
379
446
 
380
447
  /** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
@@ -391,6 +458,36 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
391
458
  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)}`));
392
459
  }
393
460
 
461
+ /** #5695: start one --ephemeral runner from a JIT config (one job, then the container exits and --rm removes it). */
462
+ async function startRunner({ name, label, jitconfig, cpus = 1, mem_gb = 2 } = {}) {
463
+ if (typeof name !== "string" || !RUNNER_NAME.test(name) || typeof label !== "string" || !RUNNER_NAME.test(label) || typeof jitconfig !== "string" || !/^[A-Za-z0-9+/=_-]+$/.test(jitconfig)) throw Object.assign(new Error("name, label and jitconfig are required"), { status: 400 });
464
+ if (!(cpus > 0 && mem_gb > 0)) throw Object.assign(new Error("cpus and mem_gb must be positive"), { status: 400 });
465
+ if (runners()[name]) return { status: 200, body: { name, state: "running" } };
466
+ const c = capacity();
467
+ if (c.paused || c.cpus_free < cpus || c.mem_free_gb < mem_gb) return { status: 503, body: { error: "no capacity", capacity: c }, retryAfter: 60 };
468
+ const dir = join(stateDir, "runners");
469
+ mkdirSync(dir, { recursive: true });
470
+ const envFile = join(dir, `${name}.env`); // the JIT config is a credential: an 0600 env file, never argv
471
+ writeFileSync(envFile, `ACTIONS_RUNNER_INPUT_JITCONFIG=${jitconfig}\n`, { mode: 0o600 });
472
+ try {
473
+ await docker.run(["--rm", "--name", `cs-runner-${name}`.slice(0, 120), "--label", RUNNER_LABEL, "--label", `computeshare.runner.label=${label}`, "--cpus", String(cpus), "--memory", `${Math.round(mem_gb * 1024)}m`, "--env-file", envFile, cfg.runner_image ?? "ghcr.io/actions/actions-runner:latest", "/home/runner/run.sh"]);
474
+ } finally { rmSync(envFile, { force: true }); }
475
+ runners()[name] = { label, cpus, mem_gb, startedAt: now() }; store.save();
476
+ return { status: 201, body: { name, state: "running" } };
477
+ }
478
+ async function stopRunner(name) {
479
+ if (!runners()[name]) return false;
480
+ try { await docker.remove(`cs-runner-${name}`.slice(0, 120)); } catch { /* already gone */ }
481
+ delete runners()[name]; store.save();
482
+ return true;
483
+ }
484
+ /** Forget runners whose container exited (an ephemeral runner ends after its job). */
485
+ async function sweepRunners() {
486
+ if (!Object.keys(runners()).length) return;
487
+ const live = new Set(await docker.listLabelled(RUNNER_LABEL));
488
+ for (const n of Object.keys(runners())) if (!live.has(`cs-runner-${n}`.slice(0, 120)) && now() - runners()[n].startedAt > 60000) delete runners()[n];
489
+ store.save();
490
+ }
394
491
  /** cgroup cpu weight per class (docker --cpu-shares); a borrowed lane yields to a reserved one under contention. */
395
492
  const sharesArgs = (prio) => (weighted() ? ["--cpu-shares", String(SHARES()[prio])] : []);
396
493
 
@@ -403,7 +500,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
403
500
  } });
404
501
  const seedFail = (e) => { if (e.status) throw Object.assign(new Error(e.message), { status: e.status, body: { error: e.message, ...(e.extra ?? {}) } }); throw e; };
405
502
 
406
- async function launch({ spec, cpus, mem_gb, limit = null }) {
503
+ async function launch({ spec, cpus, mem_gb, limit = null, max_lanes = null }) {
407
504
  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 });
408
505
  let existing = own(spec.id);
409
506
  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
@@ -417,6 +514,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
417
514
  const c = capacity();
418
515
  const h = live(cfg);
419
516
  const adm = admit({ prio, cpus, mem_gb, reservation, h });
517
+ if (c.draining && !c.paused) return { status: 503, body: { error: `draining: ${c.draining_reason}`, code: "pool.draining", capacity: c }, retryAfter: 60 }; // #6061: finish running lanes, accept none
518
+ if (laneTargetOn() && !c.paused && c.active >= laneNow()) return { status: 503, body: { error: `lane target ${laneNow()} reached (${c.active} running)`, code: "pool.lane_target", lane_target: laneNow(), capacity: c }, retryAfter: 60 };
420
519
  if (c.paused || adm.refuse) {
421
520
  const f = adm.refuse ?? {};
422
521
  if (f.status === 400) return { status: 400, body: { error: f.error } };
@@ -425,10 +524,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
425
524
  // Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
426
525
  // A reserved launch skips the load gate: it must never be refused because lanes are busy (they are throttled/drained below).
427
526
  if (prio !== "reserved") { // #5858: ramp-aware: the admitted lanes' projected peaks plus this one must fit, however low the load is right now
428
- 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);
527
+ const e = effectiveCapacity(), pu = projectedUse(), est = elastic() ? { cpus, mem: mem_gb } : estimateFor(slugOf(spec), { cpus, mem: mem_gb }), nm = Math.max(mem_gb, est.mem), nc = Math.max(cpus, est.cpus);
429
528
  const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
430
529
  if (pu.mem + nm > availMem + 1e-9 || pu.cpus + nc > availCpus + 1e-9) return { status: 503, body: { error: `projected peak ${r1(pu.mem + nm)} GB / ${r1(pu.cpus + nc)} cpus exceeds capacity ${r1(availMem)} GB / ${r1(availCpus)} cpus`, code: "pool.projected_peak", capacity: c }, retryAfter: 60 };
431
530
  }
531
+ if (elastic() && prio !== "reserved" && !Number.isInteger(max_lanes) && activeRecs().length >= derivedCeiling()) return { status: 503, body: { error: `derived lane ceiling ${derivedCeiling()} reached`, code: "pool.host_lane_ceiling", capacity: c }, retryAfter: 60 };
432
532
  if (!h.ok && prio !== "reserved") return { status: 503, body: { error: `host busy: ${h.reason}`, code: "pool.host_load", live: h }, retryAfter: 60 };
433
533
  const gate = hostDiskView(c.active, spec.repo?.slug ?? null);
434
534
  if (gate.host_disk_low) { // #5733: before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
@@ -461,7 +561,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
461
561
  const envFile = join(dir, "env");
462
562
  const credToken = randomBytes(24).toString("hex");
463
563
  const withDocker = Boolean(spec.docker);
464
- 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),
564
+ const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), ...(elastic() ? { CS_HEAVY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/heavy` } : {}), 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, ...cpuQuotaEnv(limit?.lane_cpus ?? cpus), 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),
465
565
  ...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
466
566
  writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
467
567
  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 } : {}) } : {}) };
@@ -506,6 +606,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
506
606
  // Hard burst cap per container; the (smaller) reservation is only what placement counts.
507
607
  // --memory-swap above --memory lets a rare spike page out instead of being OOM-killed (swap deal).
508
608
  "--cpus", String(laneCpus), ...sharesArgs(prio), "--memory", mb(laneMem), "--memory-swap", mb(laneMem + swapFor(limit?.lane_swap_gb)), "--pids-limit", "4096",
609
+ "--init", // lane-compute audit 2026-11-26: PID 1 never reaped children (72–1408 zombies/lane in 17 min; the worst lane would reach the 4096 pid limit in ~50 min)
509
610
  "--env-file", envFile, ...laneNet, ...work,
510
611
  ...(spec.claim_dir ? ["-v", `${join(dir, "claim")}:/claim`] : []), // #4912: warm sandboxes receive their lane here
511
612
  ...(withDocker ? [] : cacheMount), "-v", `${join(dir, "result")}:/result`, "-v", `${join(dir, "out")}:/csout`,
@@ -748,6 +849,25 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
748
849
  if (!r.ok) log.warn?.(`fstrim: ${r.error}`);
749
850
  }
750
851
 
852
+ // #6061: per-worker lane target, evaluated once per reap. Active only with an integer cfg.max_lanes (the ceiling) unless cfg.lane_autoscale is false.
853
+ // Draining refuses new launches only; running lanes are never stopped here (drainOne stays for idle_only borrowed lanes).
854
+ function laneDrain() {
855
+ const paused = Boolean(cfg.paused || ownerPaused || policyPaused);
856
+ return drainState({ paused, ownerPaused, policyPaused, busyForMs: laneS.busySince === null ? 0 : now() - laneS.busySince, drainAfterMs: (cfg.drain_busy_s ?? 300) * 1000 });
857
+ }
858
+ function laneTargetView() {
859
+ const d = laneDrain();
860
+ return { draining: d.draining, ...(d.reason ? { draining_reason: d.reason } : {}), accepting: !d.draining, ...(laneTargetOn() ? { lane_target: laneNow(), lane_ceiling: cfg.max_lanes } : {}) };
861
+ }
862
+ function laneTick() {
863
+ const h = live(cfg), t = now();
864
+ laneS.busySince = pressured(h) ? (laneS.busySince ?? t) : null;
865
+ if (!laneTargetOn()) { laneS.target = null; return; }
866
+ const r = laneStep({ target: laneNow(), ceiling: cfg.max_lanes, live: h, now: t, greenSince: laneS.greenSince, holdMs: (cfg.lane_hold_s ?? 60) * 1000 });
867
+ laneS.target = r.target; laneS.greenSince = r.greenSince;
868
+ if (r.change) log.info?.(`lane target ${r.change} to ${r.target}/${cfg.max_lanes}`);
869
+ }
870
+
751
871
  async function reap() {
752
872
  const t = now();
753
873
  for (const r of Object.values(sb())) {
@@ -759,8 +879,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
759
879
  await hostMemPressure(t); // #5967
760
880
  const known = new Set(Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)]));
761
881
  for (const name of await docker.listLabelled(OWN)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
882
+ await sweepRunners().catch((e) => log.warn?.(`runner sweep: ${e.message}`));
762
883
  await sampleUsage();
763
884
  await reclaimIdle();
885
+ laneTick(); // #6061
764
886
  await warm.maintain(maxLifeMs);
765
887
  if (pendingResize && capacity().active === 0) {
766
888
  const r = await resize(pendingResize);
@@ -844,7 +966,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
844
966
  if (want.image !== running.image || want.version !== running.version) {
845
967
  const nextImage = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(want.version);
846
968
  log.info?.(`rebuilding ${nextImage} (${running.version}/${running.image} -> ${want.version}/${want.image})`);
847
- await buildWithRetry(() => docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version)), { log }); // #5919
969
+ // 2026-11-26: a host pre-seeded with the image (docker load from another host) skips the build: on a slow or memory-tight
970
+ // host the build itself is the risk (an upgrade build coincided with a host crash)
971
+ if (await docker.hasImage?.(nextImage)) log.info?.(`${nextImage} already present; no build`);
972
+ else await buildWithRetry(() => docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version)), { log }); // #5919
848
973
  }
849
974
  await pruneLaneImages([laneImageTag(want.version)]);
850
975
  await prepullImages();
@@ -948,10 +1073,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
948
1073
 
949
1074
  const routes = [
950
1075
  [route("GET", "/health"), async () => ({ status: 200, body: { ok: true, ...capacity() } })],
951
- [route("GET", "/mirrors"), async (_p, _b, url) => ({ status: 200, body: await mirrors.tips({ slug: url.searchParams.get("slug"), cache_key: url.searchParams.get("cache_key"), upload: url.searchParams.get("upload") }).catch(seedFail) })], // #5949
1076
+ [route("GET", "/mirrors"), async (_p, _b, url) => ({ status: 200, body: await mirrors.tips({ slug: url.searchParams.get("slug"), cache_key: url.searchParams.get("cache_key"), upload: url.searchParams.get("upload"), uploader: url.searchParams.get("uploader") }).catch(seedFail) })], // #5949
952
1077
  [route("POST", "/mirrors/seed"), async (_p, body) => { try { return { status: 200, body: body?.finish ? await mirrors.finish(body) : mirrors.chunk(body) }; } catch (e) { return { status: e.status ?? 500, body: { error: e.message, ...(e.extra ?? {}) } }; } }],
953
1078
  [route("GET", "/capacity"), async () => ({ status: 200, body: capacity() })],
954
1079
  [route("POST", "/sandboxes"), async (_p, body) => { const r = await launch(body ?? {}); if (Number.isInteger(body?.spec?.warm)) warm.replenish().catch((e) => log.warn?.(`warm replenish: ${e.message}`)); return r; }],
1080
+ [route("POST", "/runners"), async (_p, body) => startRunner(body ?? {})], // #5695
1081
+ [route("DELETE", "/runners/:name"), async ({ name }) => ((await stopRunner(name)) ? { status: 200, body: { ok: true } } : { status: 404, body: { state: "gone" } })],
955
1082
  [route("GET", "/warm"), async () => ({ status: 200, body: { warm: warm.list() } })],
956
1083
  [route("POST", "/warm"), async (_p, body) => { const r = warm.configure({ ...(body ?? {}), n: body?.n }); await warm.replenish(); return { status: 200, body: { ...r, warm: warm.list() } }; }],
957
1084
  [route("POST", "/warm/claim"), async (_p, body) => warm.claim(body ?? {})],
@@ -989,6 +1116,13 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
989
1116
  if (cred) { const r = await sandboxCred(decodeURIComponent(cred[1]), cred[2], req); return send(res, r.status, r.body, r.retryAfter ? { "retry-after": String(r.retryAfter) } : {}); }
990
1117
  const limited = req.method === "POST" && /^\/sandboxes\/([^/]+)\/creds\/claude\/limited$/.exec(url.pathname); // #5205
991
1118
  if (limited) { const r = await sandboxCredLimited(decodeURIComponent(limited[1]), req, await readJson(req)); return send(res, r.status, r.body); }
1119
+ const heavy = req.method === "POST" && /^\/sandboxes\/([^/]+)\/heavy\/(acquire|release|renew)$/.exec(url.pathname); // #6047
1120
+ if (heavy) {
1121
+ const id = decodeURIComponent(heavy[1]);
1122
+ if (!sandboxAuthed(id, req)) return send(res, SANDBOX_UNAUTHORIZED.status, SANDBOX_UNAUTHORIZED.body);
1123
+ const body = await readJson(req, 4096), r0 = own(id), r = heavy[2] === "acquire" ? heavyAcquire(r0) : heavyTouch(r0, heavy[2], body?.token);
1124
+ return send(res, r.status, r.body);
1125
+ }
992
1126
  const relay = (req.method === "POST" && /^\/sandboxes\/([^/]+)\/relay$/.exec(url.pathname)) || (req.method === "GET" && /^\/sandboxes\/([^/]+)\/relay\/([^/]+)$/.exec(url.pathname));
993
1127
  if (relay) { const r = await sandboxRelay(decodeURIComponent(relay[1]), relay[2] ? decodeURIComponent(relay[2]) : null, req); return send(res, r.status, r.body ?? {}); }
994
1128
  if (url.pathname !== "/health" && !bearerOk(req, cfg.token)) return send(res, 401, { error: "unauthorized", hop: "agent", reason: "agent auth: router token rejected by agent" });