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
@@ -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", "pool"]); // 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 {
@@ -445,6 +491,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
445
491
  } catch (e) { log.warn?.(`lease ${id} on ${s.agent}: ${e.message}`); }
446
492
  }
447
493
  store.save();
494
+ if (cfg.ci_autoscale?.enabled) await autoscale().reconcile().catch((e) => log.warn?.(`ci-autoscale reconcile: ${e.message}`));
448
495
  }
449
496
 
450
497
  function enroll(body) {
@@ -468,12 +515,13 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
468
515
  /** #5886: per-box policy, allowlisted keys only; pushed to the agent's /admin/policy (the agent keeps its owner pause). */
469
516
  function validPolicy(b) {
470
517
  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));
518
+ const bad = Object.keys(b).filter((k) => !["cpus", "mem_gb", "idle_only", "paused", "floors", "elastic_lanes"].includes(k));
472
519
  if (bad.length) return `unknown policy key: ${bad[0]}`;
473
520
  const int = (v, hi) => Number.isInteger(v) && v >= 1 && v <= hi;
474
521
  if ("cpus" in b && !int(b.cpus, 256)) return "cpus must be an integer 1-256";
475
522
  if ("mem_gb" in b && !int(b.mem_gb, 1024)) return "mem_gb must be an integer 1-1024";
476
523
  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";
524
+ if ("elastic_lanes" in b && typeof b.elastic_lanes !== "boolean") return "elastic_lanes must be a boolean";
477
525
  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
526
  return null;
479
527
  }
@@ -606,8 +654,8 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
606
654
  [route("GET", "/health"), { fn: async () => ({ status: 200, body: { ok: true, agents: Object.keys(agents()).length, sandboxes: Object.keys(sbx()).length } }), auth: "none" }],
607
655
  [route("POST", "/sandboxes"), fd(async (_p, body) => launch(body))],
608
656
  [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))],
657
+ [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)
658
+ [route("POST", "/sandboxes/:id/seed"), fd(async ({ id }, body) => seedForward(id, "POST", "/mirrors/seed", { ...(body ?? {}), uploader: id }, body?.slug))],
611
659
  [route("GET", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}`))],
612
660
  [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
661
  [route("GET", "/sandboxes/:id/result"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/result`))],
@@ -619,11 +667,12 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
619
667
  [route("POST", "/sandboxes/:id/relay/:rid"), fd(async (p, body) => relayAnswer(p, body))],
620
668
  [route("POST", "/sandboxes/:id/stop"), fd(async ({ id }) => forward(id, "POST", `/sandboxes/${encodeURIComponent(id)}/stop`))], // #5274
621
669
  [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() }))],
670
+ [route("GET", "/status"), fd(async (_p, _b, url) => ({ status: 200, body: await status(url.searchParams.get("repo") ?? undefined) }))],
623
671
  [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
672
  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; }
673
+ const repo = url.searchParams.get("repo"), view = repo ? { repo: { slug: repo } } : null; // #6041: ?repo= is the per-repo view (allowlist and exclude list)
674
+ 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 = {};
675
+ 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
676
  const remote_lanes = Object.keys(sbx()).filter(isLane).length; // #5735: lane sandboxes across all batches and agents
628
677
  return { status: 200, body: { agents: caps.map((c) => ({ ...c, lanes: laneView(c.name), ...diskReport(c) })), sandboxes: out, remote_lanes } };
629
678
  })],
@@ -641,9 +690,15 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
641
690
  [route("POST", "/agent/reply/:rid"), { fn: async (p, body, _u, req) => agentReply(req, p, body), auth: "agent" }],
642
691
  [route("GET", "/agent/bundle"), { fn: async () => ({ bundle: true }), auth: "agent" }],
643
692
  [route("GET", "/agent/images/:ref"), { fn: async ({ ref }) => ({ image: ref }), auth: "agent" }],
644
- [route("POST", "/agents/:name/upgrade"), fd(async ({ name }) => {
693
+ [route("POST", "/agents/:name/upgrade"), fd(async ({ name }, body) => {
645
694
  const a = own(agents(), name);
646
695
  if (!a) return { status: 404, body: { error: "unknown agent" } };
696
+ // The host is shared: an upgrade restarts the agent under its live sandboxes, so it needs force:true while any run.
697
+ if (body?.force !== true) {
698
+ const cap = await agentCall(a, "GET", "/capacity", undefined, 5000).catch(() => null);
699
+ const active = Number(cap?.data?.active);
700
+ if (active > 0) return { status: 409, body: { error: `${active} active sandbox(es); retry when idle or pass force:true`, active } };
701
+ }
647
702
  const r = await agentCall(a, "POST", "/admin/update", {});
648
703
  return { status: r.status, body: { ...(r.data ?? {}), target: versionOf(cfg.repo_root) } };
649
704
  })],
@@ -672,6 +727,7 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
672
727
  const c = ciQuery(url);
673
728
  return c.q ? { status: 200, body: await ciEvents.wait(c.q, c.since, c.waitS) } : c;
674
729
  })],
730
+ [route("POST", "/ci/workflow-job"), { fn: async (_p, body) => ({ status: 202, body: autoscale().ingest(body) }), auth: "ci" }], // #5695
675
731
  [route("POST", "/enroll"), { fn: async (_p, body) => enroll(body), auth: "none" }],
676
732
  [route("GET", "/install"), { fn: async () => ({ status: 200, body: installScript() }), auth: "none" }], // #5883: script text only, the code comes as --code
677
733
  [route("GET", "/bootstrap/install.ps1"), { fn: async (_p, _b, url) => ({ status: 200, body: bootstrapScript(url.searchParams.get("token"), url) }), auth: "enroll" }],
@@ -711,7 +767,7 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
711
767
  }
712
768
  }
713
769
 
714
- return { handle, launch, claim, tick, enroll, issueCode, capacities, status, store };
770
+ return { handle, launch, claim, tick, autoscale, enroll, issueCode, capacities, status, store };
715
771
  }
716
772
 
717
773
  /** tokenbaton's usage dir (#5165): router.json `usage_source`, else `$TOKENBATON_HOME`, else `~/.tokenbaton`. */
@@ -27,15 +27,42 @@ 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
+ /** Ask the local router which agents lag the target engine; [] when the router is unreachable. */
44
+ async function fetchLeftBehind(configPath) {
45
+ try {
46
+ const cfg = JSON.parse(readFileSync(configPath, "utf8"));
47
+ const base = `http://${cfg.listen.host}:${cfg.listen.port}`;
48
+ const { call } = await import("./http.mjs");
49
+ const [st, v] = await Promise.all([call(base, "GET", "/status", { token: cfg.forgedock_token }), call(base, "GET", "/version", { token: cfg.forgedock_token })]);
50
+ return { target: v.data?.version, rows: agentsLeftBehind(st.data?.agents, v.data?.version) };
51
+ } catch { return { target: undefined, rows: [] }; }
52
+ }
53
+
30
54
  /**
31
55
  * `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".
56
+ * pool router config; never throws (a failed push must not fail the update). Returns "skipped" | "upgraded" | "failed";
57
+ * agents still on an older engine afterwards are named through `warn` (and `onLeftBehind`).
33
58
  */
34
- export async function upgradeAgentsAfterUpdate({ configPath = process.env.COMPUTESHARE_CONFIG ?? join(homedir(), ".config/computeshare/router.json"), runPoolCli, warn = console.warn } = {}) {
59
+ export async function upgradeAgentsAfterUpdate({ configPath = process.env.COMPUTESHARE_CONFIG ?? join(homedir(), ".config/computeshare/router.json"), runPoolCli, warn = console.warn, leftBehind = fetchLeftBehind, onLeftBehind } = {}) {
35
60
  if (!existsSync(configPath)) return "skipped";
36
61
  try {
37
62
  const run = runPoolCli ?? (await import("./cli.mjs")).runPoolCli;
38
63
  await run(["upgrade", "--config", configPath]);
64
+ const { target, rows } = await leftBehind(configPath);
65
+ if (rows.length) { warn(leftBehindLine(rows, target)); onLeftBehind?.(rows); }
39
66
  return "upgraded";
40
67
  } catch (e) {
41
68
  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
@@ -108,6 +108,7 @@ export const LEDGER_METRICS = Object.freeze([
108
108
  { key: "queue_s_p90", label: "Queue time (p90)", unit: "s", phase1: 30, end: 30 },
109
109
  { key: "failed_minute_share", label: "CI minutes in failed jobs", unit: "pct" },
110
110
  { key: "cancelled_minute_share", label: "CI minutes in cancelled jobs", unit: "pct" },
111
+ { key: "snapshot_rounds_per_release_p50", label: "Snapshot rounds per release (p50)", unit: "n", phase1: 3, end: 2 },
111
112
  { key: "ci_round_fail_rate", label: "CI rounds that fail", unit: "pct" },
112
113
  { key: "deploy_live_rate", label: "Deploy attempts that reached live", unit: "pct", higherBetter: true },
113
114
  ]);
@@ -209,6 +210,12 @@ export function computeReleaseLedger(data, cfg = {}) {
209
210
  m.ci_round_job_min_p50 = round1(p50(judged.map((r) => r.jobMin)));
210
211
  m.ci_round_fail_rate = judged.length ? round1(judged.filter((r) => r.outcome === "fail").length / judged.length, 3) : null;
211
212
  n.rounds = judged.length;
213
+ // ledger rounds (#6013): snapshots per release, wall time and cause of each round
214
+ const led = (data.ledger ?? []).filter((l) => l.snapshots > 0);
215
+ m.snapshot_rounds_per_release_p50 = round1(p50(led.map((l) => l.snapshots)));
216
+ m.snapshot_rounds_per_release_max = led.length ? Math.max(...led.map((l) => l.snapshots)) : null;
217
+ m.snapshot_wall_min_total = round1(led.reduce((a, l) => a + (l.wallMin || 0), 0));
218
+ for (const c of ["regression", "flake", "runner"]) m[`snapshot_rounds_${c}`] = led.reduce((a, l) => a + (l.causes?.[c] || 0), 0);
212
219
  m.pushes_per_release_pr_p50 = round1(p50(pushes.map((x) => x.pushes))); m.pushes_per_release_pr_max = pushes.length ? Math.max(...pushes.map((x) => x.pushes)) : null;
213
220
  n.release_prs = plan.releases.length; n.release_prs_with_ci = pushes.length;
214
221
 
@@ -66,3 +66,23 @@ describe("--by / --post-metrics parsing (#4628)", () => {
66
66
  assert.throws(() => parseArgs(["--by", "version", "--post-metrics", "x"]), /PR number/);
67
67
  });
68
68
  });
69
+
70
+ describe("ledger snapshot rounds (#6013)", () => {
71
+ it("reports rounds per release, wall time and cause counts, and trends rounds", async () => {
72
+ const { computeReleaseLedger, LEDGER_METRICS, ledgerTable } = await import("./release.mjs");
73
+ const ledger = [
74
+ { pr: 1, snapshots: 3, wallMin: 90, causes: { regression: 2, flake: 1, runner: 0 } },
75
+ { pr: 2, snapshots: 1, wallMin: 30, causes: { regression: 0, flake: 0, runner: 1 } },
76
+ { pr: 3, snapshots: 0, wallMin: 0, causes: { regression: 0, flake: 0, runner: 0 } },
77
+ ];
78
+ const r = computeReleaseLedger({ repo: "o/r", sinceMs: 0, untilMs: 1, base: "main", prs: [], runs: [], jobs: {}, ledger }, {});
79
+ assert.equal(r.metrics.snapshot_rounds_per_release_p50, 2);
80
+ assert.equal(r.metrics.snapshot_rounds_per_release_max, 3);
81
+ assert.equal(r.metrics.snapshot_wall_min_total, 120);
82
+ assert.deepEqual([r.metrics.snapshot_rounds_regression, r.metrics.snapshot_rounds_flake, r.metrics.snapshot_rounds_runner], [2, 1, 1]);
83
+ assert.ok(LEDGER_METRICS.some((d) => d.key === "snapshot_rounds_per_release_p50" && d.end === 2), "trended against a target");
84
+ const row = ledgerTable(r.metrics).find((x) => x.key === "snapshot_rounds_per_release_p50");
85
+ assert.equal(row.today, 2);
86
+ assert.equal(row.status, "end-met");
87
+ });
88
+ });