forgedock 1.67.0 → 1.69.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 (156) 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 +103 -21
  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 +39 -15
  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.mjs +11 -1
  17. package/bin/lean/batch.test.mjs +51 -2
  18. package/bin/lean/capsample.mjs +25 -0
  19. package/bin/lean/ci-gate.mjs +2 -90
  20. package/bin/lean/ci-gate.test.mjs +1 -127
  21. package/bin/lean/ci-precheck.mjs +25 -8
  22. package/bin/lean/ci-precheck.test.mjs +24 -0
  23. package/bin/lean/clear-breaker.test.mjs +4 -3
  24. package/bin/lean/commentstate.mjs +10 -5
  25. package/bin/lean/commentstate.test.mjs +12 -1
  26. package/bin/lean/conformance.e2e.test.mjs +9 -6
  27. package/bin/lean/conformance.mjs +62 -197
  28. package/bin/lean/conformance.test.mjs +46 -376
  29. package/bin/lean/depcache.mjs +102 -10
  30. package/bin/lean/depcache.test.mjs +105 -0
  31. package/bin/lean/docsgate.mjs +0 -32
  32. package/bin/lean/docsgate.test.mjs +2 -23
  33. package/bin/lean/effects-cap.test.mjs +9 -1
  34. package/bin/lean/effects-killtree.test.mjs +35 -0
  35. package/bin/lean/effects.mjs +57 -25
  36. package/bin/lean/engine-readmit.test.mjs +35 -0
  37. package/bin/lean/envgap.mjs +111 -0
  38. package/bin/lean/envgap.test.mjs +64 -0
  39. package/bin/lean/execution.mjs +13 -4
  40. package/bin/lean/execution.test.mjs +33 -0
  41. package/bin/lean/failure-census.mjs +170 -0
  42. package/bin/lean/failure-census.test.mjs +59 -0
  43. package/bin/lean/failure-stop.mjs +12 -1
  44. package/bin/lean/failure-stop.test.mjs +14 -1
  45. package/bin/lean/guardgate.test.mjs +2 -3
  46. package/bin/lean/heavy.mjs +33 -4
  47. package/bin/lean/heavy.test.mjs +38 -6
  48. package/bin/lean/hostconfig.mjs +54 -0
  49. package/bin/lean/hostconfig.test.mjs +67 -0
  50. package/bin/lean/hotarea.mjs +0 -36
  51. package/bin/lean/hotarea.test.mjs +1 -22
  52. package/bin/lean/issuewatch-verify.mjs +19 -4
  53. package/bin/lean/issuewatch.mjs +21 -4
  54. package/bin/lean/issuewatch.test.mjs +48 -1
  55. package/bin/lean/lane-audit-gap.mjs +66 -0
  56. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  57. package/bin/lean/lane-audit-llm.mjs +52 -0
  58. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  59. package/bin/lean/lane-audit-query.mjs +47 -0
  60. package/bin/lean/lane-audit-query.test.mjs +44 -0
  61. package/bin/lean/lane-audit-signatures.mjs +33 -0
  62. package/bin/lean/lane-audit.mjs +110 -0
  63. package/bin/lean/lane-audit.test.mjs +97 -0
  64. package/bin/lean/lane-recovery.test.mjs +33 -0
  65. package/bin/lean/lanecheck.mjs +5 -3
  66. package/bin/lean/lanecheck.test.mjs +6 -0
  67. package/bin/lean/lean.mjs +247 -152
  68. package/bin/lean/lean.test.mjs +502 -206
  69. package/bin/lean/limits.mjs +17 -0
  70. package/bin/lean/limits.test.mjs +15 -1
  71. package/bin/lean/live-execution.mjs +24 -2
  72. package/bin/lean/live-execution.test.mjs +62 -0
  73. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  74. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  75. package/bin/lean/orchestrate-envhold.test.mjs +62 -1
  76. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  77. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  78. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  79. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  80. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  81. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  82. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  83. package/bin/lean/orchestrate.mjs +215 -42
  84. package/bin/lean/postdeploy-check.test.mjs +1 -3
  85. package/bin/lean/precheck.mjs +20 -0
  86. package/bin/lean/preflight.mjs +110 -14
  87. package/bin/lean/preflight.test.mjs +64 -4
  88. package/bin/lean/prompts.mjs +11 -21
  89. package/bin/lean/recurrence.mjs +6 -148
  90. package/bin/lean/recurrence.test.mjs +11 -147
  91. package/bin/lean/release-deploy.mjs +35 -5
  92. package/bin/lean/release-deploy.test.mjs +50 -3
  93. package/bin/lean/release-flakes.mjs +48 -2
  94. package/bin/lean/release-flakes.test.mjs +45 -1
  95. package/bin/lean/release-ledger.mjs +19 -1
  96. package/bin/lean/release-ledger.test.mjs +23 -0
  97. package/bin/lean/release-preflight.mjs +28 -0
  98. package/bin/lean/release-preflight.test.mjs +42 -1
  99. package/bin/lean/release-review.mjs +40 -5
  100. package/bin/lean/release-review.test.mjs +43 -2
  101. package/bin/lean/release.mjs +45 -15
  102. package/bin/lean/release.test.mjs +32 -0
  103. package/bin/lean/retry.mjs +1 -1
  104. package/bin/lean/retry.test.mjs +6 -1
  105. package/bin/lean/rotator.mjs +9 -0
  106. package/bin/lean/rotator.test.mjs +11 -1
  107. package/bin/lean/sandbox-remote.mjs +51 -13
  108. package/bin/lean/schedd.mjs +13 -8
  109. package/bin/lean/schedd.test.mjs +65 -5
  110. package/bin/lean/selfreview.mjs +1 -1
  111. package/bin/lean/statuscomment.mjs +4 -1
  112. package/bin/lean/validate-catalog.mjs +108 -0
  113. package/bin/lean/validate-catalog.test.mjs +46 -1
  114. package/bin/lean/verify.mjs +1 -1
  115. package/bin/pool/affinity.test.mjs +91 -0
  116. package/bin/pool/agent.mjs +247 -23
  117. package/bin/pool/cache-sweep.mjs +31 -10
  118. package/bin/pool/ci-autoscale.mjs +160 -0
  119. package/bin/pool/cli.mjs +56 -9
  120. package/bin/pool/docker.mjs +5 -0
  121. package/bin/pool/engine-placement.test.mjs +94 -0
  122. package/bin/pool/image-manifest.mjs +24 -0
  123. package/bin/pool/image-manifest.test.mjs +20 -0
  124. package/bin/pool/lane-target.mjs +41 -0
  125. package/bin/pool/lane-tools.mjs +29 -5
  126. package/bin/pool/lane-tools.test.mjs +36 -7
  127. package/bin/pool/mirror-seed.mjs +15 -11
  128. package/bin/pool/project-layer.mjs +142 -0
  129. package/bin/pool/project-layer.test.mjs +73 -0
  130. package/bin/pool/router.mjs +106 -36
  131. package/bin/pool/version.mjs +72 -2
  132. package/bin/review-staging.mjs +11 -3
  133. package/bin/runner.mjs +59 -11
  134. package/bin/stats/release.mjs +7 -0
  135. package/bin/stats/release.test.mjs +20 -0
  136. package/bin/stats/scorecard.mjs +187 -0
  137. package/bin/stats/scorecard.test.mjs +89 -0
  138. package/bin/stats/tool-parks.mjs +29 -0
  139. package/bin/stats/tool-parks.test.mjs +21 -0
  140. package/docs/CONFIG.md +41 -0
  141. package/docs/OUTCOME-CODES.md +1 -0
  142. package/docs/STATS.md +17 -0
  143. package/package.json +1 -1
  144. package/pool/image/Dockerfile +15 -3
  145. package/pool/image/manifest.json +25 -0
  146. package/pool/image/mirror.sh +11 -2
  147. package/pool/install/install-agent.ps1 +11 -4
  148. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  149. package/scripts/ci-local/cli.mjs +1 -1
  150. package/scripts/ci-local/plan.mjs +3 -2
  151. package/scripts/ci-local.test.sh +14 -2
  152. package/scripts/failure-census.mjs +67 -0
  153. package/scripts/review-finalize.sh +5 -5
  154. package/scripts/review-finalize.test.sh +8 -1
  155. package/scripts/verify-phase-trail.sh +11 -0
  156. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -9,14 +9,15 @@ import { promisify } from "node:util";
9
9
  import { join } from "node:path";
10
10
  import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
11
11
  import { createCiEvents, MAX_WAIT_S } from "./ci-events.mjs";
12
+ import { createAutoscaler } from "./ci-autoscale.mjs";
12
13
  import { jsonStore } from "./store.mjs";
13
- import { versionOf } from "./version.mjs";
14
+ import { cmpVersion, versionOf } from "./version.mjs";
14
15
 
15
16
  /**
16
17
  * What the router ships to pool agents (self-update and bootstrap). Every module the agent can load statically from
17
18
  * bin/pool/agent.mjs must live under these paths; bin/tests/pool-agent-bundle.test.mjs enforces it.
18
19
  */
19
- export const AGENT_BUNDLE_PATHS = Object.freeze(["package.json", "bin/pool", "pool"]);
20
+ export const AGENT_BUNDLE_PATHS = Object.freeze(["package.json", "bin/pool", "bin/lean/concurrency.mjs", "bin/lean/depcache.mjs", "bin/lean/ledger.mjs", "pool"]); // depcache.mjs+ledger.mjs: pool/project-layer.mjs (#6038); concurrency.mjs: thresholds imported by pool/lane-target.mjs (#6061); it has no imports
20
21
 
21
22
  const run = promisify(execFile);
22
23
 
@@ -229,6 +230,9 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
229
230
  const agentCall = (a, method, path, body, timeoutMs) => a.transport === "poll"
230
231
  ? pollCall(a, method, path, body, timeoutMs)
231
232
  : call(a.url, method, path, { body, token: a.token, timeoutMs, fetchFn });
233
+ // #5695: CI runner autoscaler (off unless cfg.ci_autoscale.enabled); webhook demand in, reconcile on the tick.
234
+ let autoscaler = null;
235
+ const autoscale = () => (autoscaler ??= createAutoscaler({ cfg, now, log, capacities: () => capacities(), agentCall, githubToken, fetchFn, agents }));
232
236
 
233
237
  /** #5891: host drive figures per agent, plus a warning when the projected time until the drive is full is under disk_warn_hours (2). */
234
238
  const diskWarned = new Map();
@@ -244,26 +248,49 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
244
248
  }
245
249
  /** #5967: host free memory and the other-VM (vmmem) working sets per agent. */
246
250
  const memReport = (c) => Number.isFinite(c.host_mem_free_gb) ? { host_mem_free_gb: c.host_mem_free_gb, ...(Array.isArray(c.vmmem) && c.vmmem.length ? { vmmem: c.vmmem } : {}), ...(c.host_mem_low === true ? { host_mem_low: true } : {}) } : {};
251
+ const pending = new Map(); // agent -> Set of lane ids reserved by an in-flight launch or claim
252
+ const dropPending = (name) => { pending.delete(name); }; // #6061: a worker that stopped answering must not hold batch slots
253
+ const reportedTarget = new Map(); // #6061: agent -> lane_target from its last answered /capacity
247
254
  async function capacities() {
248
255
  const out = [];
249
256
  for (const [name, a] of Object.entries(agents())) {
250
257
  try {
251
258
  const r = await agentCall(a, "GET", "/capacity", undefined, 5000);
259
+ if (r.ok && Number.isInteger(r.data?.lane_target)) reportedTarget.set(name, r.data.lane_target); else reportedTarget.delete(name);
260
+ if (!r.ok) dropPending(name);
252
261
  out.push(r.ok ? { name, ok: true, ...(a.transport ? { transport: a.transport } : {}), ...r.data } : { name, ok: false, error: `HTTP ${r.status}` });
253
- } catch (e) { out.push({ name, ok: false, ...(a.transport ? { transport: a.transport } : {}), error: String(e.message ?? e) }); }
262
+ } catch (e) { reportedTarget.delete(name); dropPending(name); out.push({ name, ok: false, ...(a.transport ? { transport: a.transport } : {}), error: String(e.message ?? e) }); }
254
263
  }
255
264
  return out;
256
265
  }
257
266
 
267
+ const repoCfg = (spec) => cfg.repos?.[spec?.repo?.slug] ?? {};
268
+ /** #5886: a spec naming an account is placed only on that account's agents; without one, any enrolled agent (as before). */
269
+ const inAccount = (c, spec) => typeof spec?.account !== "string" || own(agents(), c.name)?.account === spec.account;
270
+ /** #6041: per-repo placement. `repos.<slug>.agents` (honoured only when a non-empty string array) is an allowlist; `exclude_agents` subtracts from it. Unset = any agent, as before. */
271
+ const names = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
272
+ const placeable = (c, spec) => {
273
+ if (!inAccount(c, spec) || c.draining || c.accepting === false) return false; // #6061: a draining worker takes no new lanes
274
+ const rc = repoCfg(spec), allow = names(rc.agents);
275
+ return (!allow.length || allow.includes(c.name)) && !names(rc.exclude_agents).includes(c.name);
276
+ };
277
+ /** Lane-engine version: the agent's /capacity version against the router's own target. Unknown (older agent) never skews or refuses. */
278
+ const targetVersion = () => { try { return versionOf(cfg.repo_root).version; } catch { return undefined; } };
279
+ const engineOf = (c) => (typeof c?.version === "string" ? c.version : undefined);
280
+ const engineBelow = (c, want) => { const d = cmpVersion(engineOf(c), want); return d !== null && d < 0; };
281
+ const engineRank = (c, target) => (engineBelow(c, target) ? 1 : 0); // 0 = on (or above) the orchestrator's engine, 1 = behind it
282
+ const byEngine = (target) => (a, b) => engineRank(a, target) - engineRank(b, target);
283
+ /** R2: with spec.min_lane_engine set, agents below it are dropped; unset keeps lower agents as the fallback. */
284
+ const minEngine = (spec) => (typeof spec?.min_lane_engine === "string" && spec.min_lane_engine ? spec.min_lane_engine : null);
285
+ const engineOld = (spec, below) => ({ status: 503, body: { error: `no host runs lane engine ${minEngine(spec)} or newer`, code: "pool.engine_old", min_lane_engine: minEngine(spec), agents: below.map((c) => ({ name: c.name, version: engineOf(c) })) }, retryAfter: cfg.engine_old_retry_after_s ?? cfg.retry_after_s ?? 60 });
258
286
  /** Agent liveness for the scheduler (#4547): an agent is online when it answers and is not paused. */
259
- async function status() {
260
- const caps = await capacities();
261
- const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused), transport: c.transport ?? "direct", ...diskReport(c), ...memReport(c) }));
287
+ async function status(repo) {
288
+ const caps = (await capacities()).filter((c) => placeable(c, repo ? { repo: { slug: repo } } : null));
289
+ const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused), transport: c.transport ?? "direct", ...(engineOf(c) ? { engine_version: engineOf(c), engine_skew: engineBelow(c, targetVersion()) } : {}), ...diskReport(c), ...memReport(c) }));
262
290
  return { online: agentsView.filter((a) => a.ok && !a.paused).length, total: agentsView.length, agents: agentsView };
263
291
  }
264
292
 
265
293
  /** Per-repo extras: the gitignored forge.yaml, and a private Docker daemon (with a bigger reservation) when enabled. */
266
- const repoCfg = (spec) => cfg.repos?.[spec?.repo?.slug] ?? {};
267
294
  // Placement counts the (small) reservation; `limit` is each container's hard burst cap (burst model, when configured).
268
295
  const sizeFor = (spec) => {
269
296
  const docker = Boolean(repoCfg(spec).docker), dind = cfg.dind ?? { cpus: 1, mem_gb: 2 };
@@ -288,13 +315,17 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
288
315
  // awaited agent call, so concurrent launches cannot overshoot.
289
316
  const isLane = (id) => typeof id === "string" && id.startsWith("fdrsbx-");
290
317
  const validCeiling = (v) => Number.isInteger(v) && v >= 0;
291
- function ceilingOf(name) {
318
+ function configuredCeiling(name) {
292
319
  const st = own(agents(), name)?.max_lanes;
293
320
  if (validCeiling(st)) return st;
294
321
  const c = cfg.agents && Object.hasOwn(cfg.agents, name) ? cfg.agents[name]?.max_lanes : undefined;
295
322
  return validCeiling(c) ? c : null;
296
323
  }
297
- const pending = new Map(); // agent -> Set of lane ids reserved by an in-flight launch or claim
324
+ // #6061: the lower of the configured ceiling and the agent's own lane_target (from its last /capacity).
325
+ function ceilingOf(name) {
326
+ const c = configuredCeiling(name), t = reportedTarget.get(name);
327
+ return t === undefined ? c : c === null ? t : Math.min(c, t);
328
+ }
298
329
  const lanesOn = (name) => {
299
330
  const ids = new Set(pending.get(name) ?? []);
300
331
  for (const [id, s] of Object.entries(sbx())) if (s?.agent === name && isLane(id)) ids.add(id);
@@ -326,8 +357,9 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
326
357
  const r = c.reservations.find((x) => x.name === spec.reservation) ?? (spec.reservation ? null : c.reservations.length === 1 ? c.reservations[0] : null);
327
358
  return Boolean(r) && r.cpus_free >= size.cpus && r.mem_free_gb >= size.mem_gb;
328
359
  }
329
- const cpusFree = prio === "normal" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : c.cpus_free;
330
- const memFree = prio === "normal" && Number.isFinite(c.mem_free_unreserved_gb) ? c.mem_free_unreserved_gb : c.mem_free_gb;
360
+ const elastic = c.elastic_lanes === true && Number.isFinite(c.cpus_free_elastic) && Number.isFinite(c.mem_free_gb_elastic); // #6047: base reservations plus held heavy tokens
361
+ const cpusFree = prio === "normal" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : elastic ? c.cpus_free_elastic : c.cpus_free;
362
+ const memFree = prio === "normal" && Number.isFinite(c.mem_free_unreserved_gb) ? c.mem_free_unreserved_gb : elastic ? c.mem_free_gb_elastic : c.mem_free_gb;
331
363
  return cpusFree >= size.cpus && memFree >= size.mem_gb;
332
364
  };
333
365
  const headroom = (c, spec) => (spec?.priority === "borrow" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : 0);
@@ -335,28 +367,35 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
335
367
  // when it is known, else the best-fitting one) and remembered, so launch() prefers it and the seeded mirror is the one the lane uses.
336
368
  const seedPick = new Map(); // sandbox id -> {agent, at}
337
369
  const SEED_CHUNK_B64_MAX = 768 * 1024;
338
- async function seedAgent(id) {
370
+ async function seedAgent(id, slug) {
339
371
  const known = own(sbx(), id);
340
372
  if (known && own(agents(), known.agent)) return known.agent;
341
373
  const hit = seedPick.get(id);
342
374
  if (hit && own(agents(), hit.agent) && now() - hit.at < 30 * 60000) return hit.agent;
343
375
  for (const [k, v] of seedPick) if (now() - v.at >= 30 * 60000) seedPick.delete(k);
344
- const fits = (await capacities()).filter((c) => c.ok && !c.paused && c.host_disk_low !== true && c.disk_capped !== true).sort((a, b) => b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
376
+ const spec = slug ? { repo: { slug } } : null; // the repo is known from the seed request when it names one
377
+ const tv = targetVersion();
378
+ const fits = (await capacities()).filter((c) => c.ok && !c.paused && placeable(c, spec) && c.host_disk_low !== true && c.disk_capped !== true).sort((a, b) => byEngine(tv)(a, b) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
345
379
  if (!fits.length) return null;
346
380
  seedPick.set(id, { agent: fits[0].name, at: now() });
347
381
  return fits[0].name;
348
382
  }
349
- async function seedForward(id, method, path, body) {
383
+ async function seedForward(id, method, path, body, slug) {
350
384
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(id)) return { status: 400, body: { error: "bad sandbox id" } };
351
385
  if (typeof body?.data_b64 === "string" && body.data_b64.length > SEED_CHUNK_B64_MAX) return { status: 413, body: { error: "chunk too large" } };
352
- const name = await seedAgent(id), a = name && own(agents(), name);
386
+ const name = await seedAgent(id, typeof slug === "string" ? slug : undefined), a = name && own(agents(), name);
353
387
  if (!a) return { status: 503, body: { error: "no agent available to seed" }, retryAfter: cfg.retry_after_s ?? 60 };
354
388
  try { const r = await agentCall(a, method, path, body, 120000); return { status: r.status, body: agentBody(r, name) }; }
355
389
  catch (e) { return { status: 502, body: { error: `agent ${name} unreachable: ${e.message}` } }; }
356
390
  }
357
- /** #5886: a spec naming an account is placed only on that account's agents; without one, any enrolled agent (as before). */
358
- const inAccount = (c, spec) => typeof spec?.account !== "string" || own(agents(), c.name)?.account === spec.account;
359
- async function launch(spec) {
391
+ /** #6063: router.json repos.<slug>.priority (reserved|normal|borrow) and .reservation override the lane spec's class; invalid = ignored. */
392
+ const withRepoPriority = (spec) => {
393
+ const rc = repoCfg(spec);
394
+ if (!["reserved", "normal", "borrow"].includes(rc.priority)) return spec;
395
+ return { ...spec, priority: rc.priority, ...(typeof rc.reservation === "string" ? { reservation: rc.reservation } : {}) };
396
+ };
397
+ async function launch(spec0) {
398
+ const spec = spec0 && typeof spec0 === "object" ? withRepoPriority(spec0) : spec0;
360
399
  if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id)) return { status: 400, body: { error: "spec.id required ([A-Za-z0-9._-], max 128)" } };
361
400
  const known = own(sbx(), spec.id);
362
401
  if (known && own(agents(), known.agent)) {
@@ -367,11 +406,14 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
367
406
  delete sbx()[spec.id]; store.save();
368
407
  }
369
408
  const size = sizeFor(spec);
370
- const sized = (await capacities()).filter((c) => c.ok && !c.paused && inAccount(c, spec) && fitsPriority(c, spec, size));
409
+ const tv = targetVersion(), min = minEngine(spec);
410
+ const placed = (await capacities()).filter((c) => c.ok && !c.paused && placeable(c, spec) && fitsPriority(c, spec, size));
411
+ const tooOld = min ? placed.filter((c) => engineBelow(c, min)) : [];
412
+ const sized = tooOld.length ? placed.filter((c) => !tooOld.includes(c)) : placed;
371
413
  const diskLow = sized.filter((c) => c.host_disk_low === true).map((c) => c.name); // #5733: never POST to a host whose drive is short
372
414
  const capped = sized.filter((c) => c.disk_capped === true && c.host_disk_low !== true).map((c) => c.name); // #5884: lane disk at its hard cap
373
415
  const memLow = sized.filter((c) => c.host_mem_low === true && c.host_disk_low !== true && c.disk_capped !== true).map((c) => c.name); // #5967: host memory under the floor
374
- const fits = sized.filter((c) => c.host_disk_low !== true && c.disk_capped !== true && c.host_mem_low !== true).sort((a, b) => headroom(b, spec) - headroom(a, spec) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
416
+ const fits = sized.filter((c) => c.host_disk_low !== true && c.disk_capped !== true && c.host_mem_low !== true).sort((a, b) => byEngine(tv)(a, b) || headroom(b, spec) - headroom(a, spec) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
375
417
  const laneId = isLane(spec.id), laneCapped = []; // #5735: agents skipped because their lane ceiling is reached
376
418
  let busy = null; // the last agent 503 (e.g. lane_tools image building): its body and Retry-After are passed back
377
419
  const seeded = seedPick.get(spec.id)?.agent; // #5949: the agent holding this lane's seeded mirror goes first
@@ -380,14 +422,15 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
380
422
  if (laneId && atCeiling(c.name)) { laneCapped.push({ name: c.name, ...laneView(c.name) }); continue; }
381
423
  if (laneId) reserve(c.name, spec.id);
382
424
  try {
383
- const r = await agentCall(own(agents(), c.name), "POST", "/sandboxes", { spec: withForgeYaml(spec), ...size }, 120000);
425
+ const r = await agentCall(own(agents(), c.name), "POST", "/sandboxes", { spec: withForgeYaml(spec), ...size, ...(ceilingOf(c.name) !== null ? { max_lanes: ceilingOf(c.name) } : {}) }, 120000);
384
426
  if (r.status === 503) { busy = { r, name: c.name }; continue; } // raced with another launch, or still building; try the next host
385
427
  if (r.ok) { sbx()[spec.id] = { agent: c.name, issue: spec.issue ?? null, batch: spec.batch ?? null, createdAt: now(), touched: now() }; store.save(); }
386
- return { status: r.status, body: { ...agentBody(r, c.name), agent: c.name } };
428
+ return { status: r.status, body: { ...agentBody(r, c.name), agent: c.name, ...(engineOf(c) ? { engine_version: engineOf(c) } : {}) } };
387
429
  } finally { if (laneId) release(c.name, spec.id); }
388
430
  }
389
431
  if (laneCapped.length && !busy) return { status: 503, body: { error: "pool.host_lane_ceiling", code: "pool.host_lane_ceiling", agents: laneCapped }, retryAfter: cfg.retry_after_s ?? 60 };
390
432
  if (busy) return { status: 503, body: { ...agentBody(busy.r, busy.name), agent: busy.name }, retryAfter: busy.r.retryAfter ?? cfg.retry_after_s ?? 60 };
433
+ if (tooOld.length && !sized.length) return engineOld(spec, tooOld); // a deferral: the lane waits for an upgraded host
391
434
  if (diskLow.length) return { status: 503, body: { error: "no host has free disk", code: "pool.disk_low", agents: diskLow }, retryAfter: cfg.disk_low_retry_after_s ?? 300 }; // a capacity deferral, not a failure
392
435
  if (capped.length) return { status: 503, body: { error: "no host has lane disk below its cap", code: "pool.disk_cap", agents: capped }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
393
436
  if (memLow.length) return { status: 503, body: { error: "no host has free memory", code: "pool.host_mem", reason: "host_mem", agents: memLow }, retryAfter: cfg.host_mem_retry_after_s ?? 60 }; // a capacity deferral, not a failure
@@ -395,12 +438,15 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
395
438
  }
396
439
 
397
440
  /** #4912: hand the lane to an agent's ready warm sandbox; 404 when no agent has one (the caller then launches cold). */
398
- async function claim(spec) {
441
+ async function claim(spec0) {
442
+ const spec = spec0 && typeof spec0 === "object" ? withRepoPriority(spec0) : spec0; // #6063
399
443
  if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id)) return { status: 400, body: { error: "spec.id required ([A-Za-z0-9._-], max 128)" } };
400
444
  if (own(sbx(), spec.id)) return launch(spec); // already placed: the same idempotent path
401
445
  const size = sizeFor(spec);
402
446
  const laneId = isLane(spec.id);
403
- for (const c of (await capacities()).filter((x) => x.ok && !x.paused && inAccount(x, spec))) {
447
+ const tv = targetVersion(), min = minEngine(spec);
448
+ const claimable = (await capacities()).filter((x) => x.ok && !x.paused && placeable(x, spec) && !(min && engineBelow(x, min))).sort(byEngine(tv));
449
+ for (const c of claimable) {
404
450
  if (laneId && atCeiling(c.name)) continue; // #5735: the 404 makes the caller cold-launch, which gets the ceiling 503
405
451
  if (laneId) reserve(c.name, spec.id);
406
452
  try {
@@ -414,6 +460,18 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
414
460
  return { status: 404, body: { error: "no warm sandbox ready" } };
415
461
  }
416
462
 
463
+ // #6117: a destroyed sandbox's placing agent, for the agent's log grace period: a late log/result/runlog read still reaches it.
464
+ const graced = new Map(); // id -> {agent, until}
465
+ const GRACE_MS = Number(cfg.keep_log_s ?? 600) * 1000;
466
+ const grace = (id, agent) => { const t = now(); for (const [k, v] of graced) if (v.until <= t) graced.delete(k); graced.set(id, { agent, until: t + GRACE_MS }); }; // expired entries go on every insert
467
+ async function forwardRead(id, path) {
468
+ if (own(sbx(), id)) return forward(id, "GET", path);
469
+ const g = graced.get(id);
470
+ if (!g || g.until <= now()) { graced.delete(id); return { status: 404, body: { state: "gone" } }; }
471
+ const a = own(agents(), g.agent);
472
+ if (!a) return { status: 404, body: { state: "gone" } };
473
+ try { const r = await agentCall(a, "GET", path); return { status: r.status, body: agentBody(r, g.agent) }; } catch (e) { return { status: 502, body: { error: `agent ${g.agent} unreachable: ${e.message}` } }; }
474
+ }
417
475
  async function forward(id, method, path, timeoutMs) {
418
476
  const s = own(sbx(), id);
419
477
  const a = s && own(agents(), s.agent);
@@ -421,7 +479,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
421
479
  s.touched = now(); store.save();
422
480
  try {
423
481
  const r = await agentCall(a, method, path, undefined, timeoutMs);
424
- if (method === "DELETE" && (r.ok || r.status === 404)) { delete sbx()[id]; relayQ.delete(id); store.save(); }
482
+ if (method === "DELETE" && (r.ok || r.status === 404)) { if (r.ok && GRACE_MS > 0) grace(id, s.agent); delete sbx()[id]; relayQ.delete(id); store.save(); }
425
483
  return { status: r.status, body: agentBody(r, s.agent) };
426
484
  } catch (e) { return { status: 502, body: { error: `agent ${s.agent} unreachable: ${e.message}` } }; }
427
485
  }
@@ -437,7 +495,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
437
495
  try {
438
496
  if (now() - s.touched > abandonMs) {
439
497
  const r = await agentCall(a, "DELETE", `/sandboxes/${encodeURIComponent(id)}`, undefined, DESTROY_TIMEOUT_MS);
440
- if (r.ok || r.status === 404) { delete sbx()[id]; relayQ.delete(id); log.info?.(`abandoned ${id} destroyed on ${s.agent}`); }
498
+ if (r.ok || r.status === 404) { if (r.ok && GRACE_MS > 0) grace(id, s.agent); delete sbx()[id]; relayQ.delete(id); log.info?.(`abandoned ${id} destroyed on ${s.agent}`); }
441
499
  } else {
442
500
  const r = await agentCall(a, "POST", `/sandboxes/${encodeURIComponent(id)}/lease`);
443
501
  if (r.status === 404) { delete sbx()[id]; relayQ.delete(id); log.info?.(`${id} gone on ${s.agent}`); }
@@ -445,6 +503,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
445
503
  } catch (e) { log.warn?.(`lease ${id} on ${s.agent}: ${e.message}`); }
446
504
  }
447
505
  store.save();
506
+ if (cfg.ci_autoscale?.enabled) await autoscale().reconcile().catch((e) => log.warn?.(`ci-autoscale reconcile: ${e.message}`));
448
507
  }
449
508
 
450
509
  function enroll(body) {
@@ -468,12 +527,13 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
468
527
  /** #5886: per-box policy, allowlisted keys only; pushed to the agent's /admin/policy (the agent keeps its owner pause). */
469
528
  function validPolicy(b) {
470
529
  if (!b || typeof b !== "object" || Array.isArray(b)) return "policy must be an object";
471
- const bad = Object.keys(b).filter((k) => !["cpus", "mem_gb", "idle_only", "paused", "floors"].includes(k));
530
+ const bad = Object.keys(b).filter((k) => !["cpus", "mem_gb", "idle_only", "paused", "floors", "elastic_lanes"].includes(k));
472
531
  if (bad.length) return `unknown policy key: ${bad[0]}`;
473
532
  const int = (v, hi) => Number.isInteger(v) && v >= 1 && v <= hi;
474
533
  if ("cpus" in b && !int(b.cpus, 256)) return "cpus must be an integer 1-256";
475
534
  if ("mem_gb" in b && !int(b.mem_gb, 1024)) return "mem_gb must be an integer 1-1024";
476
535
  if (("idle_only" in b && typeof b.idle_only !== "boolean") || ("paused" in b && typeof b.paused !== "boolean")) return "idle_only and paused must be booleans";
536
+ if ("elastic_lanes" in b && typeof b.elastic_lanes !== "boolean") return "elastic_lanes must be a boolean";
477
537
  if ("floors" in b && !(b.floors && typeof b.floors === "object" && Object.keys(b.floors).every((k) => k === "host_disk_gb" && Number.isFinite(b.floors[k]) && b.floors[k] >= 0))) return "floors accepts only host_disk_gb >= 0";
478
538
  return null;
479
539
  }
@@ -606,11 +666,12 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
606
666
  [route("GET", "/health"), { fn: async () => ({ status: 200, body: { ok: true, agents: Object.keys(agents()).length, sandboxes: Object.keys(sbx()).length } }), auth: "none" }],
607
667
  [route("POST", "/sandboxes"), fd(async (_p, body) => launch(body))],
608
668
  [route("POST", "/sandboxes/claim"), fd(async (_p, body) => claim(body))],
609
- [route("GET", "/sandboxes/:id/mirrors"), fd(async ({ id }, _b, url) => seedForward(id, "GET", `/mirrors?${new URLSearchParams([...url.searchParams].filter(([k]) => ["slug", "cache_key", "upload"].includes(k)))}`))], // #5949
610
- [route("POST", "/sandboxes/:id/seed"), fd(async ({ id }, body) => seedForward(id, "POST", "/mirrors/seed", body))],
669
+ [route("GET", "/sandboxes/:id/mirrors"), fd(async ({ id }, _b, url) => seedForward(id, "GET", `/mirrors?${new URLSearchParams([...[...url.searchParams].filter(([k]) => ["slug", "cache_key", "upload"].includes(k)), ["uploader", id]])}`, undefined, url.searchParams.get("slug")))], // #5949; uploader: per-sandbox part file (concurrent identical bundles)
670
+ [route("POST", "/sandboxes/:id/seed"), fd(async ({ id }, body) => seedForward(id, "POST", "/mirrors/seed", { ...(body ?? {}), uploader: id }, body?.slug))],
611
671
  [route("GET", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}`))],
612
- [route("GET", "/sandboxes/:id/logs"), fd(async ({ id }, _b, url) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/logs?cursor=${encodeURIComponent(url.searchParams.get("cursor") ?? "0")}`))],
613
- [route("GET", "/sandboxes/:id/result"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/result`))],
672
+ [route("GET", "/sandboxes/:id/logs"), fd(async ({ id }, _b, url) => forwardRead(id, `/sandboxes/${encodeURIComponent(id)}/logs?cursor=${encodeURIComponent(url.searchParams.get("cursor") ?? "0")}`))],
673
+ [route("GET", "/sandboxes/:id/result"), fd(async ({ id }) => forwardRead(id, `/sandboxes/${encodeURIComponent(id)}/result`))],
674
+ [route("GET", "/sandboxes/:id/runlog"), fd(async ({ id }) => forwardRead(id, `/sandboxes/${encodeURIComponent(id)}/runlog`))], // #6117
614
675
  [route("GET", "/sandboxes/:id/usage"), fd(async ({ id }) => { // #4549: the placing agent rides along for per-agent minutes
615
676
  const agent = own(sbx(), id)?.agent, r = await forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/usage`);
616
677
  return agent && r.status === 200 && r.body && typeof r.body === "object" ? { ...r, body: { ...r.body, agent } } : r;
@@ -619,12 +680,14 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
619
680
  [route("POST", "/sandboxes/:id/relay/:rid"), fd(async (p, body) => relayAnswer(p, body))],
620
681
  [route("POST", "/sandboxes/:id/stop"), fd(async ({ id }) => forward(id, "POST", `/sandboxes/${encodeURIComponent(id)}/stop`))], // #5274
621
682
  [route("DELETE", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "DELETE", `/sandboxes/${encodeURIComponent(id)}`, DESTROY_TIMEOUT_MS))],
622
- [route("GET", "/status"), fd(async () => ({ status: 200, body: await status() }))],
683
+ [route("GET", "/status"), fd(async (_p, _b, url) => ({ status: 200, body: await status(url.searchParams.get("repo") ?? undefined) }))],
623
684
  [route("GET", "/agents"), fd(async (_p, _b, url) => { // #5535: each sandbox carries disk_used_mb from its agent's sandbox_disk_mb when the agent reports it
624
685
  const acct = url.searchParams.get("account"); // #5886: ?account= is the per-account view; `account` and `policy` ride on enrolled records that have them
625
- const caps = (await capacities()).filter((c) => acct === null || own(agents(), c.name)?.account === acct).map((c) => { const a = own(agents(), c.name); return { ...c, ...(a?.account ? { account: a.account } : {}), ...(a?.policy ? { policy: a.policy } : {}) }; }), byName = new Map(caps.map((c) => [c.name, c])), out = {};
626
- for (const [id, s] of Object.entries(sbx())) { if (acct !== null && !byName.has(s?.agent)) continue; const mb = byName.get(s?.agent)?.sandbox_disk_mb?.[id]; out[id] = Number.isFinite(mb) ? { ...s, disk_used_mb: mb } : s; }
686
+ const repo = url.searchParams.get("repo"), view = repo ? { repo: { slug: repo } } : null; // #6041: ?repo= is the per-repo view (allowlist and exclude list)
687
+ const caps = (await capacities()).filter((c) => (acct === null || own(agents(), c.name)?.account === acct) && placeable(c, view)).map((c) => { const a = own(agents(), c.name); return { ...c, ...(a?.account ? { account: a.account } : {}), ...(a?.policy ? { policy: a.policy } : {}) }; }), byName = new Map(caps.map((c) => [c.name, c])), out = {};
688
+ for (const [id, s] of Object.entries(sbx())) { if ((acct !== null || repo) && !byName.has(s?.agent)) continue; const mb = byName.get(s?.agent)?.sandbox_disk_mb?.[id]; out[id] = Number.isFinite(mb) ? { ...s, disk_used_mb: mb } : s; }
627
689
  const remote_lanes = Object.keys(sbx()).filter(isLane).length; // #5735: lane sandboxes across all batches and agents
690
+ // #6062: usage_summary rides on each capacity record (spread above) unchanged
628
691
  return { status: 200, body: { agents: caps.map((c) => ({ ...c, lanes: laneView(c.name), ...diskReport(c) })), sandboxes: out, remote_lanes } };
629
692
  })],
630
693
  [route("POST", "/device/code"), { fn: async () => deviceStart(), auth: "none" }], // #5886
@@ -641,9 +704,15 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
641
704
  [route("POST", "/agent/reply/:rid"), { fn: async (p, body, _u, req) => agentReply(req, p, body), auth: "agent" }],
642
705
  [route("GET", "/agent/bundle"), { fn: async () => ({ bundle: true }), auth: "agent" }],
643
706
  [route("GET", "/agent/images/:ref"), { fn: async ({ ref }) => ({ image: ref }), auth: "agent" }],
644
- [route("POST", "/agents/:name/upgrade"), fd(async ({ name }) => {
707
+ [route("POST", "/agents/:name/upgrade"), fd(async ({ name }, body) => {
645
708
  const a = own(agents(), name);
646
709
  if (!a) return { status: 404, body: { error: "unknown agent" } };
710
+ // The host is shared: an upgrade restarts the agent under its live sandboxes, so it needs force:true while any run.
711
+ if (body?.force !== true) {
712
+ const cap = await agentCall(a, "GET", "/capacity", undefined, 5000).catch(() => null);
713
+ const active = Number(cap?.data?.active);
714
+ if (active > 0) return { status: 409, body: { error: `${active} active sandbox(es); retry when idle or pass force:true`, active } };
715
+ }
647
716
  const r = await agentCall(a, "POST", "/admin/update", {});
648
717
  return { status: r.status, body: { ...(r.data ?? {}), target: versionOf(cfg.repo_root) } };
649
718
  })],
@@ -672,6 +741,7 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
672
741
  const c = ciQuery(url);
673
742
  return c.q ? { status: 200, body: await ciEvents.wait(c.q, c.since, c.waitS) } : c;
674
743
  })],
744
+ [route("POST", "/ci/workflow-job"), { fn: async (_p, body) => ({ status: 202, body: autoscale().ingest(body) }), auth: "ci" }], // #5695
675
745
  [route("POST", "/enroll"), { fn: async (_p, body) => enroll(body), auth: "none" }],
676
746
  [route("GET", "/install"), { fn: async () => ({ status: 200, body: installScript() }), auth: "none" }], // #5883: script text only, the code comes as --code
677
747
  [route("GET", "/bootstrap/install.ps1"), { fn: async (_p, _b, url) => ({ status: 200, body: bootstrapScript(url.searchParams.get("token"), url) }), auth: "enroll" }],
@@ -711,7 +781,7 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
711
781
  }
712
782
  }
713
783
 
714
- return { handle, launch, claim, tick, enroll, issueCode, capacities, status, store };
784
+ return { handle, launch, claim, tick, autoscale, enroll, issueCode, capacities, status, store, forward, forwardRead };
715
785
  }
716
786
 
717
787
  /** tokenbaton's usage dir (#5165): router.json `usage_source`, else `$TOKENBATON_HOME`, else `~/.tokenbaton`. */
@@ -27,15 +27,85 @@ export function versionOf(root = repoRoot) {
27
27
  export const laneImageTag = (version) => `forgedock-lane:${version}`;
28
28
  export const laneBuildArgs = (version) => ({ FORGEDOCK_VERSION: version });
29
29
 
30
+ /** Numeric dotted-version compare (1.10 > 1.9): negative, 0 or positive; null when either side is not a version. */
31
+ export function cmpVersion(a, b) {
32
+ const parts = (v) => (typeof v === "string" && /^v?\d+(\.\d+)*/.test(v.trim()) ? v.trim().replace(/^v/, "").split(/[-+]/)[0].split(".").map(Number) : null);
33
+ const x = parts(a), y = parts(b);
34
+ if (!x || !y) return null;
35
+ for (let i = 0; i < Math.max(x.length, y.length); i++) { const d = (x[i] ?? 0) - (y[i] ?? 0); if (d) return d; }
36
+ return 0;
37
+ }
38
+
39
+ /** Agents (from the router /status view) whose lane engine is below the target version: [{name, version}]. */
40
+ export const agentsLeftBehind = (agents, target) => (agents ?? []).filter((a) => a?.ok !== false && cmpVersion(a?.engine_version, target) < 0).map((a) => ({ name: a.name, version: a.engine_version }));
41
+ export const leftBehindLine = (rows, target) => `agents left behind on an older engine (target ${target}): ${rows.map((r) => `${r.name} ${r.version}`).join(", ")}`;
42
+
43
+ /** The router config the pool CLI uses: router.json plus the forgedock token (inline, `forgedock_token_file`, or forgedock.token beside it). */
44
+ export function readRouterConfig(configPath) {
45
+ const cfg = JSON.parse(readFileSync(configPath, "utf8"));
46
+ let token = cfg.forgedock_token;
47
+ if (!token) { try { token = readFileSync(cfg.forgedock_token_file ?? join(dirname(configPath), "forgedock.token"), "utf8").trim(); } catch { token = undefined; } }
48
+ return { ...cfg, forgedock_token: token };
49
+ }
50
+
51
+ /** Ask the local router which agents lag the target engine; [] when the router is unreachable. */
52
+ async function fetchLeftBehind(configPath) {
53
+ try {
54
+ const cfg = readRouterConfig(configPath);
55
+ const base = `http://${cfg.listen.host}:${cfg.listen.port}`;
56
+ const { call } = await import("./http.mjs");
57
+ const [st, v] = await Promise.all([call(base, "GET", "/status", { token: cfg.forgedock_token }), call(base, "GET", "/version", { token: cfg.forgedock_token })]);
58
+ return { target: v.data?.version, rows: agentsLeftBehind(st.data?.agents, v.data?.version) };
59
+ } catch { return { target: undefined, rows: [] }; }
60
+ }
61
+
62
+ /**
63
+ * The local router runs the installed bin/pool code (its /version `code` hash equals versionOf().code). When it does not,
64
+ * restart it through `restart()` (systemd user unit by default) and poll `/version` for up to `waitMs`. Returns
65
+ * {ok, running, installed, why}. `probe(configPath)` returns the router's /version data or null.
66
+ */
67
+ export async function routerFresh(configPath, { installed = installedFor(configPath), probe = probeRouterVersion, restart = restartRouterUnit, waitMs = 30000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
68
+ const same = (v) => v && v.code === installed.code && v.version === installed.version;
69
+ let v = await probe(configPath);
70
+ if (same(v)) return { ok: true, running: v.version, installed: installed.version };
71
+ if (!v) return { ok: false, running: null, installed: installed.version, why: "router unreachable" };
72
+ if (!(await restart())) return { ok: false, running: v.version, installed: installed.version, why: "could not restart the router" };
73
+ for (let t = 0; t < waitMs; t += 1000) { await sleep(1000); v = await probe(configPath); if (same(v)) return { ok: true, running: v.version, installed: installed.version }; }
74
+ return { ok: false, running: v?.version ?? null, installed: installed.version, why: "router did not come back on the installed code" };
75
+ }
76
+ /** What the router would hash: its configured repo_root, else this package. */
77
+ function installedFor(configPath) {
78
+ try { const c = JSON.parse(readFileSync(configPath, "utf8")); return versionOf(c.repo_root ?? repoRoot); } catch { return versionOf(); }
79
+ }
80
+ async function probeRouterVersion(configPath) {
81
+ try {
82
+ const cfg = readRouterConfig(configPath);
83
+ const { call } = await import("./http.mjs");
84
+ const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "GET", "/version", { token: cfg.forgedock_token });
85
+ const d = r?.data;
86
+ return d && typeof d.code === "string" && typeof d.version === "string" ? d : null; // a 401/500 body is "unknown", never "stale"
87
+ } catch { return null; }
88
+ }
89
+ async function restartRouterUnit() {
90
+ try { const { execFileSync } = await import("node:child_process"); execFileSync("systemctl", ["--user", "restart", "computeshare-router.service"], { stdio: "ignore", timeout: 30000 }); return true; } catch { return false; }
91
+ }
92
+
30
93
  /**
31
94
  * `forgedock update` hook: push the new code and lane image to every enrolled agent. A no-op on hosts without a
32
- * pool router config; never throws (a failed push must not fail the update). Returns "skipped" | "upgraded" | "failed".
95
+ * pool router config; never throws (a failed push must not fail the update). Returns "skipped" | "upgraded" | "failed";
96
+ * agents still on an older engine afterwards are named through `warn` (and `onLeftBehind`).
33
97
  */
34
- export async function upgradeAgentsAfterUpdate({ configPath = process.env.COMPUTESHARE_CONFIG ?? join(homedir(), ".config/computeshare/router.json"), runPoolCli, warn = console.warn } = {}) {
98
+ export async function upgradeAgentsAfterUpdate({ configPath = process.env.COMPUTESHARE_CONFIG ?? join(homedir(), ".config/computeshare/router.json"), runPoolCli, warn = console.warn, leftBehind = fetchLeftBehind, onLeftBehind, ensureRouterFresh } = {}) {
35
99
  if (!existsSync(configPath)) return "skipped";
36
100
  try {
101
+ // The router builds the agent bundle from the code it is RUNNING: a router still on the old version ships an incomplete
102
+ // bundle and the upgraded agent crash-loops at import. Restart it onto the installed code first, or do not push.
103
+ const fresh = await (ensureRouterFresh ?? routerFresh)(configPath);
104
+ if (!fresh.ok) { warn(`pool upgrade skipped: the router runs ${fresh.running ?? "unknown"} code but ${fresh.installed} is installed (${fresh.why}); restart computeshare-router, then run forgedock pool upgrade`); return "skipped"; }
37
105
  const run = runPoolCli ?? (await import("./cli.mjs")).runPoolCli;
38
106
  await run(["upgrade", "--config", configPath]);
107
+ const { target, rows } = await leftBehind(configPath);
108
+ if (rows.length) { warn(leftBehindLine(rows, target)); onLeftBehind?.(rows); }
39
109
  return "upgraded";
40
110
  } catch (e) {
41
111
  warn(`pool upgrade after update failed: ${e.message}`);
@@ -29,6 +29,7 @@ import { parseForgeYaml } from "./forge-utils.mjs";
29
29
  import { selftestGate, readMarkerComments } from "./lean/selftest-gate.mjs";
30
30
  import { gateByRef } from "./lean/acceptance.mjs";
31
31
  import { DEFAULT_FEATURE_PATTERN } from "./lean/lane.mjs";
32
+ import { attemptGuard } from "./lean/release-flakes.mjs";
32
33
  import { requiredChecksRead } from "./lean/effects.mjs";
33
34
 
34
35
  const INSTALL_ROOT = fileURLToPath(new URL("..", import.meta.url));
@@ -568,11 +569,18 @@ export function cancelOnlyChecks(checks, required = []) {
568
569
 
569
570
  const CI_POLL_MS = 20_000, CI_POLL_MAX = 45;
570
571
 
571
- /** One `gh run rerun` per cancelled run of the cancel-only required checks, then wait until none of them is pending. @returns the re-read checks, or `checks` when nothing could be rerun. */
572
+ /** One `gh run rerun --failed` per cancelled run of the cancel-only required checks (#6014: never past RERUN_ATTEMPT_CAP reruns of a run), then wait until none of them is pending. @returns the re-read checks, or `checks` when nothing could be rerun. */
572
573
  async function rerunCancelled(io, c, pr, env, checks, only) {
573
574
  const ids = [...new Set(only.map((k) => /\/actions\/runs\/(\d+)/.exec(k.link)?.[1]).filter(Boolean))];
574
- if (!ids.length) return checks;
575
- for (const id of ids) await io.run("gh", ["run", "rerun", id, "-R", c.ghRepo], { env, cwd: io.cwd });
575
+ const todo = [];
576
+ for (const id of ids) {
577
+ const v = await io.run("gh", ["run", "view", id, "--json", "attempt", "-R", c.ghRepo], { env, cwd: io.cwd });
578
+ let attempt = null; try { attempt = v.code === 0 ? JSON.parse(v.stdout)?.attempt : null; } catch { /* unreadable: the guard allows an unknown attempt */ }
579
+ const g = attemptGuard({ attempt });
580
+ if (g.allow) todo.push(id); else io.err?.(`rerun of run ${id} refused: ${g.why}`);
581
+ }
582
+ if (!todo.length) return checks;
583
+ for (const id of todo) await io.run("gh", ["run", "rerun", id, "--failed", "-R", c.ghRepo], { env, cwd: io.cwd });
576
584
  const sleep = io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
577
585
  const names = new Set(only.map((k) => k.name));
578
586
  let cur = checks;
package/bin/runner.mjs CHANGED
@@ -304,6 +304,13 @@ export function assertOpenCodeNativeRuntime({
304
304
  const CLI_AVAILABILITY_CACHE_TTL_MS = 60_000;
305
305
  const CLI_AVAILABILITY_CACHE_MAX_SIZE = 100;
306
306
  const cliAvailabilityCache = new Map();
307
+ // #5844: cwds whose last probe timed out (host load). A timeout says nothing about absence, so it is never written to
308
+ // the cache above; this marker lets callers tell "busy" from "absent". Cleared by the next probe that gets an answer.
309
+ const cliProbeTimeouts = new Set();
310
+ const CLI_PROBE_RETRY_FACTOR = 3;
311
+ const isProbeTimeout = (err) => err?.code === "ETIMEDOUT" || err?.killed === true || err?.signal === "SIGTERM";
312
+ /** True when the last probe for `cwd` timed out instead of answering (#5844). */
313
+ export const cliProbeTimedOut = (cwd = process.cwd()) => cliProbeTimeouts.has(cwd);
307
314
  // Windows path types emitted by npm's shim generator. Native executables are
308
315
  // directly spawnable; .cmd/.bat files must be resolved to their trusted native
309
316
  // target before spawning because Node cannot exec them with shell:false.
@@ -668,21 +675,31 @@ export function isClaudeCliAvailable(
668
675
  let available;
669
676
  let cliPath = null;
670
677
  let version = null;
678
+ const probe = (timeout) => execImpl(
679
+ `${resolveCmd} && echo ${CLI_PROBE_OUTPUT_SENTINEL} && claude --version`,
680
+ { cwd, stdio: ["ignore", "pipe", "ignore"], encoding: "utf-8", timeout },
681
+ );
682
+ let raw;
671
683
  try {
672
- const raw = execImpl(
673
- `${resolveCmd} && echo ${CLI_PROBE_OUTPUT_SENTINEL} && claude --version`,
674
- {
675
- cwd,
676
- stdio: ["ignore", "pipe", "ignore"],
677
- encoding: "utf-8",
678
- timeout: CLI_PROBE_TIMEOUT_MS,
679
- },
680
- );
684
+ try {
685
+ raw = probe(CLI_PROBE_TIMEOUT_MS);
686
+ } catch (err) {
687
+ if (!isProbeTimeout(err)) throw err;
688
+ raw = probe(CLI_PROBE_TIMEOUT_MS * CLI_PROBE_RETRY_FACTOR); // #5844: one longer retry under host load
689
+ }
681
690
  available = true;
682
691
  cliPath = selectResolvedCliPath(parseProbeOutput(raw), { platform, existsImpl });
683
692
  version = parseCliVersion(raw);
684
- } catch {
693
+ cliProbeTimeouts.delete(cwd);
694
+ } catch (err) {
685
695
  available = false;
696
+ if (isProbeTimeout(err)) {
697
+ // #5844: still timed out: not evidence of absence, so no negative cache entry
698
+ cliProbeTimeouts.add(cwd);
699
+ cliAvailabilityCache.delete(cwd);
700
+ return false;
701
+ }
702
+ cliProbeTimeouts.delete(cwd);
686
703
  }
687
704
  // Re-inserting an existing key moves it to the end of Map's iteration
688
705
  // order (delete+set), so eviction below always drops the true oldest
@@ -1387,8 +1404,11 @@ export function redactCliText(text) {
1387
1404
  /**
1388
1405
  * forge#5762: the facts a failed CLI run reports: `result` and `is_error` (redacted, capped) and whether the CLI never
1389
1406
  * reached the API (`duration_api_ms` 0, read from the raw text when the envelope is cut off). Never throws.
1390
- * @returns {{cliResult?:string, cliIsError?:boolean, cliApiMs?:number}}
1407
+ * @returns {{cliResult?:string, cliIsError?:boolean, cliApiMs?:number, cliTerminalReason?:string, cliSessionId?:string}}
1391
1408
  */
1409
+ /** #6105: terminal reasons of a session the API cut short (overload, 5xx, stream reset): transient, the session itself is fine to resume. */
1410
+ const API_TERMINAL_RE = /^(api_error|overloaded(_error)?|server_error|internal_server_error|service_unavailable|stream_(reset|error|interrupted)|connection_(reset|error))$/i;
1411
+ export const isApiTerminalReason = (r) => typeof r === "string" && API_TERMINAL_RE.test(r.trim());
1392
1412
  export function cliFailureFacts(stdout) {
1393
1413
  const env = parseCliEnvelope(stdout);
1394
1414
  const facts = {};
@@ -1396,6 +1416,8 @@ export function cliFailureFacts(stdout) {
1396
1416
  if (typeof env.result === "string") facts.cliResult = sanitizeAndCap(redactCliText(env.result), MAX_CLI_RESULT_LEN);
1397
1417
  if (typeof env.is_error === "boolean") facts.cliIsError = env.is_error;
1398
1418
  if (typeof env.duration_api_ms === "number") facts.cliApiMs = env.duration_api_ms;
1419
+ if (typeof env.terminal_reason === "string") facts.cliTerminalReason = sanitizeAndCap(env.terminal_reason, 80); // #6105
1420
+ if (typeof env.session_id === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(env.session_id)) facts.cliSessionId = env.session_id; // #6105: what `--resume` takes
1399
1421
  } else if (typeof stdout === "string") {
1400
1422
  const m = /"duration_api_ms"\s*:\s*(\d+)/.exec(stdout.slice(0, 4096));
1401
1423
  if (m) facts.cliApiMs = Number(m[1]);
@@ -1607,6 +1629,21 @@ export function promptGoesViaStdin(prompt, otherArgs = [], platform = process.pl
1607
1629
  }
1608
1630
 
1609
1631
  /** forge#4129: spawn errnos that fail the same way on every rerun (argv too big, binary missing or not executable). */
1632
+ /**
1633
+ * #5844: true only when `bin` is genuinely absent: a path that does not exist, or a bare name found on no PATH entry
1634
+ * (x PATHEXT on win32). Decides whether an ENOENT spawn error is deterministic.
1635
+ */
1636
+ export function spawnTargetMissing(bin, env = process.env, { platform = process.platform, existsImpl = existsSync } = {}) {
1637
+ if (typeof bin !== "string" || !bin) return true;
1638
+ if (/[\\/]/.test(bin)) return !existsImpl(bin);
1639
+ const win = platform === "win32";
1640
+ const sepr = win ? ";" : ":";
1641
+ const exts = win ? ["", ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
1642
+ for (const dir of String(env.PATH ?? env.Path ?? "").split(sepr).filter(Boolean)) {
1643
+ for (const ext of exts) if (existsImpl(join(dir, bin + ext))) return false;
1644
+ }
1645
+ return true;
1646
+ }
1610
1647
  export const DETERMINISTIC_SPAWN_ERRNOS = Object.freeze(["E2BIG", "ENOENT", "EACCES", "ENOEXEC", "ENAMETOOLONG"]);
1611
1648
 
1612
1649
  export function runCliBackend({
@@ -1661,6 +1698,10 @@ export function runCliBackend({
1661
1698
  // `mkdtempSync` succeeds — before `writeFileSync` runs — so a failure in
1662
1699
  // `writeFileSync` still leaves `tmpDir` set and the already-created
1663
1700
  // directory gets cleaned up.
1701
+ // 2026-11-26: a NUL byte in the prompt (from a file read or tool output) made the spawn throw "args[1] must be a string without null bytes"
1702
+ // (engine-error, lane held); NULs carry no meaning in a prompt, so they are dropped from both the prompt and the system prompt
1703
+ if (typeof userMessage === "string" && userMessage.includes("\0")) userMessage = userMessage.replace(/\0/g, "");
1704
+ if (typeof systemPrompt === "string" && systemPrompt.includes("\0")) systemPrompt = systemPrompt.replace(/\0/g, "");
1664
1705
  let tmpDir = null;
1665
1706
  // forge#4129: a prompt over the argv bound is sent on stdin instead of as the `--print` argument.
1666
1707
  // forge#4763: the other argv (flags, system-prompt file path) counts toward the Windows command-line cap.
@@ -1791,6 +1832,11 @@ export function runCliBackend({
1791
1832
  if (["EAGAIN", "ENOMEM", "EMFILE"].includes(result.error.code)) {
1792
1833
  error.spawnErrno = result.error.code;
1793
1834
  error.code = "CLI_SPAWN_TRANSIENT";
1835
+ } else if (result.error.code === "ENOENT" && !spawnTargetMissing(bin, childEnv)) {
1836
+ // #5844: ENOENT while the binary resolves (or the cwd vanished) is not proof the CLI is absent: transient,
1837
+ // so the engine relaunches instead of ending needs-human cli.spawn_failed
1838
+ error.spawnErrno = "ENOENT";
1839
+ error.code = "CLI_SPAWN_TRANSIENT";
1794
1840
  } else if (DETERMINISTIC_SPAWN_ERRNOS.includes(result.error.code)) {
1795
1841
  // forge#4129: certain to fail again on a rerun; flagged so callers do not retry it. E2BIG (argv too large) gets
1796
1842
  // its own code; ENOENT and the other errnos keep theirs (forge#4021 contract).
@@ -1906,6 +1952,8 @@ export function runCliBackend({
1906
1952
  // forge#5762: keep the CLI's own result text; an exit that never reached the API and is no login or limit is transient.
1907
1953
  Object.assign(err, cliFailureFacts(stdout));
1908
1954
  if (!err.usageLimit && !err.authFailure && err.cliApiMs === 0 && result.status === 1) err.cliFailed = true;
1955
+ // forge#6105: a session that did real work and then ended is_error with an API terminal reason can be resumed by id (never a relaunch)
1956
+ if (!err.usageLimit && !err.authFailure && !err.cliFailed && err.cliIsError === true && isApiTerminalReason(err.cliTerminalReason)) err.apiError = true;
1909
1957
  if (resetAt) {
1910
1958
  err.resetAt = resetAt;
1911
1959
  // forge#2524: also attach a machine-usable epoch-ms timestamp so