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
@@ -136,17 +136,19 @@ import { laneSize, SIZES } from "./budget.mjs";
136
136
  import { requeueKey, REQUEUABLE } from "./batch.mjs";
137
137
  import { makeCapWait } from "./capwait.mjs";
138
138
  import { mapLimit } from "./pmap.mjs";
139
- import { quotaRequeue } from "./rotator.mjs";
139
+ import { quotaRequeue, nextAccountAfterAuthFailure } from "./rotator.mjs";
140
+ import { holdExpiryWarnings } from "./limits.mjs";
140
141
  import { joinsDecomposed, addsEpicChildren, selectChildren, edgeText, DEFAULT_POLL_S } from "./autochildren.mjs";
141
142
  import { formatOverload } from "./hostload.mjs";
142
143
  import { normalizeStacking, planAdmissible, stackAdmissible } from "./stacking.mjs";
143
144
  import { lackedTools } from "./toolplace.mjs";
144
145
  import { openPrerequisites } from "./prereq.mjs";
145
146
  import { makeController, classifyRepo, formatConcurrency } from "./concurrency.mjs";
146
- import { admitInput, breach, recordFailure, markEscalated, NO_NEW_INPUT } from "./attempts.mjs";
147
+ import { admitInput, breach, recordFailure, blockerSignature, markEscalated, NO_NEW_INPUT } from "./attempts.mjs";
147
148
 
148
149
  // A dependency that finished like this no longer blocks its dependents.
149
150
  const SATISFIED = new Set(["merged", "invalid"]);
151
+ const PLAN_VERDICT = new Set(["invalid", "needs-human", "decomposed", "budget-exceeded"]); // #5909: plan-lane ends that settle the issue
150
152
  const DEFAULT_TRAIN_EVERY_MS = 30000; // #5836: merge-train poll period
151
153
  // #5836: a lane that ended pr-ready is waiting on the merge train, not failed: its dependents wait
152
154
  const WAITING_ON_TRAIN = (row) => row?.outcome === "pr-ready";
@@ -183,6 +185,12 @@ export const ENGINE_ERROR_RELAUNCHES = 1;
183
185
  export const AGENT_LOST_MIN = 3;
184
186
  export const AGENT_LOST_WINDOW_MS = 60000;
185
187
  export const AGENT_LOST_REQUEUE_MS = 60000;
188
+ // #5988: a backend.auth outage is probed every AUTH_PROBE_MS, holds admissions at most AUTH_ESCALATE_MS, then escalates once.
189
+ export const AUTH_PROBE_MS = 5 * 60000;
190
+ export const AUTH_ESCALATE_MS = 30 * 60000;
191
+ export const HOLD_RAMP_STEP_MS = 30000; // #5988: hold-expiry release ramp: one more lane per step
192
+ /** #5988: a cause that belongs to one placement host: errors are counted per (signature, agent), not batch-wide. */
193
+ const hostSignature = (r, detail) => (/\bsandbox\.exited\b/.test(`${r?.code ?? ""} ${detail ?? ""}`) ? "sandbox.exited" : null);
186
194
  export const HOST_BUSY_RETRY_S = 60;
187
195
  // #4528: a busy host or a full sandbox pool is a wait, not a failure: requeued after its retry-in, never capped.
188
196
  // A lane that could not be resolved because gh/git failed (network blip) is the same kind of wait (#4791).
@@ -209,6 +217,9 @@ export const transientRetryDelayMs = (k) => Math.min(TRANSIENT_BACKOFF_S * 4 **
209
217
  // the batch stays open up to ENV_HOLD_MAX_MS re-checking every ENV_WATCH_MS for an engine version change, a batch env change or the tool.
210
218
  export const ENV_HOLD_MAX_MS = 24 * 3600_000;
211
219
  export const ENV_WATCH_MS = 30_000;
220
+ /** #6123: after a re-admit (env issue closed / tool probe passed) ends in the same env signature, the next re-admit waits 15 m, then 1 h, then 4 h. */
221
+ export const ENV_READMIT_BACKOFF_MS = [15 * 60_000, 3600_000, 4 * 3600_000];
222
+ export const envReadmitBackoffMs = (k) => ENV_READMIT_BACKOFF_MS[Math.min(Math.max(1, k), ENV_READMIT_BACKOFF_MS.length) - 1];
212
223
  /** #5805: `code|first message line`, with times, hex ids and numbers normalised, so a pid or path id does not make a repeat look new. */
213
224
  export function failureSignature(code, detail) {
214
225
  const line = String(detail ?? "").split("\n").find((l) => l.trim()) ?? "";
@@ -291,6 +302,7 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
291
302
  const STOP_RETRY_MS = 15 * 1000;
292
303
  const STOP_TIMEOUT_MS = 120 * 1000;
293
304
 
305
+ const OVERLOAD_RECOVERY_MAX_MS = 30 * 60 * 1000; // #5749: longest an env.validate_timeout recovery waits for the host to stop being overloaded
294
306
  const cancellableSleep = (ms, signal) => new Promise((res) => {
295
307
  const t = setTimeout(res, ms);
296
308
  signal?.addEventListener("abort", () => { clearTimeout(t); res(); }, { once: true });
@@ -342,7 +354,7 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
342
354
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
343
355
  store = null, adopt = null, getParallel = null, usageRows = null, repoSlug = null, repoOf = null, getAdded = null, getRequeued = null, reconcile = null, select = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000, getClearBreaker = null, consumeClearBreaker = null, ackClearBreaker = null,
344
356
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null, baseProbe = null,
345
- recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getPause = null, expirePause = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, suspendLane = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
357
+ recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, heldFacts = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getPause = null, expirePause = null, getHoldInfo = null, authProbe = null, onEscalate = null, quarantineAgent = null, reseedCache = null, suspendLane = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
346
358
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
347
359
  getChildren = null, autoChildren = null, baseWait = null, rotator = null, stacking = "off", readPrReady = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null, envHold = null, envIssue = null, logicalDeps = null,
348
360
  train = null, trainEveryMs = DEFAULT_TRAIN_EVERY_MS, attempts = null }) {
@@ -358,6 +370,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
358
370
  const keptBoxes = toMap(saved?.kept); // #6008: issue -> {issue, since, phase}: sandboxes kept for adopt (no dispatcher lease)
359
371
  const runRecs = toMap(saved?.running); // issue -> {startedAt, lane, pid?}: persisted so a restart can adopt the lane
360
372
  const pending = [...(saved?.pending ?? [])];
373
+ const selMatched = new Set(saved?.selMatched ?? []); // #6029: issues the selector has matched (persisted: a resumed runner keeps the leave provenance)
361
374
  const notBefore = toMap(saved?.notBefore);
362
375
  const requeues = toMap(saved?.requeues);
363
376
  const deferrals = toMap(saved?.deferrals);
@@ -371,10 +384,12 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
371
384
  // `deterministic`: `version|signature` seen twice (never relaunched again on that version); `toolReadmits`: `issue|signature`
372
385
  // already re-admitted because the probe found the tool (a lane that still misses it waits for an engine or env change instead).
373
386
  const ehOn = !!envHold || !!envIssue;
387
+ const envReadmits = new Map(); // #6123: issue -> {sig, count, at} of the last env-issue/tool-probe re-admit
374
388
  // #5755: env.* failures are one engine/env defect per signature: `envSigs` signature -> {issues, number} (the env issue the `envIssue` seam
375
389
  // filed or updated); affected product issues are held on it (never needs-human) and 2+ issues on a signature stop admitting lanes that need it.
376
390
  const envSigs = toMap(saved?.envSigs);
377
391
  const engineSigs = toMap(saved?.engineSigs);
392
+ const heldSigs = toMap(saved?.heldSigs); // #5893: root -> {sig, removedAt} of the needs-human block last released; an identical block needs a newer removal event
378
393
  const readmit = toMap(saved?.readmit); // #5978: re-admission policy state (backoff step, version and base seen) per ended issue
379
394
  const ledgers = toMap(saved?.attempts); // #5986: issue -> attempts ledger; never cleared by releaseHeld, --requeue or --set-env (see attempts.mjs)
380
395
  const deterministic = new Set(saved?.deterministicSigs ?? []);
@@ -382,6 +397,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
382
397
  const ehMaxMs = Number(envHold?.maxMs) > 0 ? Number(envHold.maxMs) : ENV_HOLD_MAX_MS;
383
398
  const ehWatchMs = Number(envHold?.watchMs) > 0 ? Number(envHold.watchMs) : ENV_WATCH_MS;
384
399
  const curVersion = () => { try { return envHold?.version?.() ?? version ?? null; } catch { return version ?? null; } };
400
+ const vmm2 = (x) => (/^v?(\d+\.\d+)/.exec(String(x ?? "")) ?? [])[1] ?? null;
401
+ const agentVersionOf = async () => { try { return (await envHold?.agentVersion?.()) ?? null; } catch { return null; } };
402
+ const curEnvValues = () => { try { return envHold?.envValues?.() ?? null; } catch { return null; } }; // #5931
385
403
  const curEnv = () => { try { return envHold?.envFingerprint?.() ?? null; } catch { return null; } };
386
404
  const missingTools = async (tools) => { if (typeof envHold?.missingTools !== "function") return null; try { const m = await envHold.missingTools(tools); return Array.isArray(m) ? m : null; } catch { return null; } };
387
405
  const checked = toMap(saved?.prefilter); // issue -> pre-filter result
@@ -389,6 +407,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
389
407
  const enqueued = toMap(saved?.enqueued); // #4409: issue -> when it last entered the queue (starvation guard)
390
408
  const heads = new Set(saved?.heads ?? []); // #4409: decomposed sub-issues not started yet: the head of their priority band
391
409
  let errorTimes = [...(saved?.errorTimes ?? [])];
410
+ const ceilingK = () => { let k = null; try { k = getParallel?.(); } catch { k = null; } return Number.isInteger(k) && k >= 1 ? k : parallel; }; // #5988: declared early: refreshHeld reads it
411
+ const holdWarned = new Set(); let holdRamp = null; // #5988: declared early: the hoisted refreshHeld reads them from finish/recovery callbacks
392
412
  // #5859: agent restarts of this batch (one record each, shown by `status --batch`) and the lanes already requeued as `sandbox.lost`
393
413
  const agentRestarts = [...(saved?.agentRestarts ?? [])];
394
414
  const lostOnce = new Set(saved?.lostRequeued ?? []); // a lane lost again after its requeue is an ordinary engine-error
@@ -432,6 +452,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
432
452
  const priorities = toMap(saved?.priorities); // issue -> priority number; only with the registry
433
453
  // #5138: read on every grant, so `--set-max-remote` reaches a running batch (a getter on `remote`); running lanes are never stopped.
434
454
  const remoteMax = () => { const m = remote?.max; return Number.isInteger(m) && m >= 0 ? m : 0; };
455
+ const maxHeldNoted = new Set(); // #5746: issues already announced as waiting on max_remote 0
435
456
  const remoteCapped = new Set(); // #5138: issues waiting for a max_remote slot; polled so a raised live max_remote admits them
436
457
  let poolOfflineSince = null, poolStallNoted = false; // #4788: when sampled online first read 0, and whether the stall was reported
437
458
  const capWait = makeCapWait({ now }); // #4909: a lane refused for capacity waits for a free slot, recorded as queue time
@@ -440,7 +461,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
440
461
  let budgetLocal = false; // the execution budget refused a remote lane under on_budget local: the rest run on the host
441
462
  // #4256: where a lane goes before capacity: `remote.place` (hybrid) or `remote.isRemote` (remote mode).
442
463
  const hostFallbackOn = () => remote?.hostFallback !== false; // #5652: unset keeps the host re-placement
443
- const placeOf = (n) => {
464
+ const placeRaw = (n) => {
444
465
  if (!remote) return null;
445
466
  // #4542: a lane recovering from a remote capability block runs on the host, which has the capability.
446
467
  // #4785: a tool-missing recovery too: the sandbox that lacked the tool is not chosen again.
@@ -449,10 +470,16 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
449
470
  const rec = recovering.get(n);
450
471
  if (rec?.code === OUTCOME_CODES.ENV_TOOL_MISSING && rec.where === "remote" && !rec.toolNoRecipe && (rec.attempt ?? 1) <= 1 && !budgetLocal) return { where: "remote", reason: "retry remotely after sandbox provisioning" };
451
472
  // #5652: with host fallback off (execution.host_fallback / host.role: orchestrator) the host is orchestrator-only: no re-placement here
452
- if (hostFallbackOn() && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
473
+ // #5931: a credentials block pinned the issue to the host (ledger hostPin): applied on readmit whatever host fallback says
474
+ if (ledgers.get(n)?.hostPin) return { where: "local", reason: "host pin: ops_credentials block" };
475
+ if (hostFallbackOn() && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_ENGINE_SKEW].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
453
476
  // #5371: a mechanical recovery never repeats the placement of the run that failed (a remote sandbox env defect recurs there), and a remote validate failure is rerun on the host
454
- if (recovering.get(n)?.code === ENV_VALIDATE_PLACEMENT || (MECHANICAL_CODES.includes(recovering.get(n)?.code) && recovering.get(n)?.where === "remote")) return { where: "local", reason: `different placement: recovering ${recovering.get(n).code} off the remote run` };
455
- { // #5331: a frozen contract naming a tool the sandbox is known to lack runs on the host (`remote.lacks`, `remote.contractOf(n)`; both optional)
477
+ if (recovering.get(n)?.code === ENV_VALIDATE_PLACEMENT || (MECHANICAL_CODES.includes(recovering.get(n)?.code) && recovering.get(n)?.where === "remote")) {
478
+ if (hostFallbackOn()) return { where: "local", reason: `different placement: recovering ${rec.code} off the remote run` };
479
+ // #5746: the host is not allowed: retry remotely (a fresh sandbox) instead of the orchestrator
480
+ if (!budgetLocal) return { where: "remote", reason: `retry remotely, host fallback off: recovering ${rec.code}` };
481
+ }
482
+ if (hostFallbackOn()) { // #5331: a frozen contract naming a tool the sandbox is known to lack runs on the host (`remote.lacks`, `remote.contractOf(n)`; both optional)
456
483
  const lk = lackedTools(remote.contractOf?.(n), remote.lacks);
457
484
  if (lk.tools.length) return { where: "local", reason: `host tool: sandbox lacks ${lk.tools.join(", ")}` };
458
485
  }
@@ -463,7 +490,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
463
490
  return { where: p?.where === "remote" ? "remote" : "local", reason: String(p?.reason ?? "") };
464
491
  }
465
492
  return remote.isRemote?.(n) ? { where: "remote", reason: "mode remote" } : { where: "local", reason: "local" };
466
- } catch { return { where: "local", reason: "placement failed" }; }
493
+ } catch { return hostFallbackOn() ? { where: "local", reason: "placement failed" } : { where: "remote", reason: "placement failed, host fallback off: retry remotely" }; } // #5746
494
+ };
495
+ // #5746: in remote mode the host is orchestrator-only unless host_fallback is true: whatever branch below picks the host (a `needs`
496
+ // capability, a host pin, a failed placement), the lane is placed remotely instead. An operator's live `--set-placement local` is not a fallback.
497
+ const placeOf = (n) => {
498
+ const p = placeRaw(n);
499
+ if (p?.where === "local" && remote?.mode === "remote" && !hostFallbackOn() && p.reason !== "live placement: local") return { where: "remote", reason: `host fallback off, not on the host: ${p.reason}` };
500
+ return p;
467
501
  };
468
502
  const isRemote = (n) => placeOf(n)?.where === "remote";
469
503
  const placed = new Map(); // issue -> {where, reason} granted this pass, picked up by start()
@@ -478,7 +512,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
478
512
  // #5592: env.tool_missing repeats are the same defect when the same tools are missing, whatever else the detail says (probe lines, ids, paths vary per run)
479
513
  const toolsOf = (d) => { const m = /(?:host|sandbox) is missing ([^\n]+?), so validate command/i.exec(String(d ?? "")); return m ? m[1].split(/\s*,\s*/).sort().join(",") : null; };
480
514
  const envSig = (code, d) => (code === OUTCOME_CODES.ENV_TOOL_MISSING ? toolsOf(d) : null) ?? sigOf(d);
481
- const ENV_ALL_CODES = [...REPEAT_ENV_CODES, ENV_VALIDATE_TIMEOUT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE]; // #5755
515
+ const ENV_ALL_CODES = [...REPEAT_ENV_CODES, ENV_VALIDATE_TIMEOUT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_ENGINE_SKEW]; // #5755, #5931
482
516
  const envKey = (code, d) => `${code}|${code === OUTCOME_CODES.ENV_TOOL_MISSING && toolsOf(d) ? toolsOf(d) : failureSignature(code, d).split("|").slice(1).join("|")}`;
483
517
  const maxFor = (cls) => (cls === "mechanical" ? mechMax : recoveryMax);
484
518
  const classUsed = toMap(saved?.recoveryClasses); // `${issue}:${class}` -> recovery lanes launched in that class
@@ -522,7 +556,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
522
556
  ...(requeueApplied.size ? { requeueApplied: [...requeueApplied], requeued: toObj(requeuedInfo) } : {}),
523
557
  ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}), ...(train ? { train: train.snapshot() } : {}),
524
558
  ...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), ...(heads.size ? { heads: [...heads] } : {}),
525
- ...(engineSigs.size ? { engineSigs: toObj(engineSigs) } : {}), ...(deterministic.size ? { deterministicSigs: [...deterministic] } : {}), ...(toolReadmits.size ? { toolReadmits: [...toolReadmits] } : {}), ...(select ? { select } : {}), ...(readmit.size ? { readmit: toObj(readmit) } : {}), ...(envSigs.size ? { envSigs: toObj(envSigs) } : {}), ...(ledgers.size ? { attempts: toObj(ledgers) } : {}) });
559
+ ...(engineSigs.size ? { engineSigs: toObj(engineSigs) } : {}), ...(heldSigs.size ? { heldSigs: toObj(heldSigs) } : {}), ...(deterministic.size ? { deterministicSigs: [...deterministic] } : {}), ...(toolReadmits.size ? { toolReadmits: [...toolReadmits] } : {}), ...(select ? { select } : {}), ...(readmit.size ? { readmit: toObj(readmit) } : {}), ...(envSigs.size ? { envSigs: toObj(envSigs) } : {}), ...(ledgers.size ? { attempts: toObj(ledgers) } : {}), ...(selMatched.size ? { selMatched: [...selMatched] } : {}) });
526
560
  };
527
561
  const update = (row) => { store?.log?.(row); onUpdate(row); };
528
562
  // #5978 R11: a merge into a staging lane branch does not fire `Closes`: the seam closes the issue and folds its post-deploy checks into the release rollup.
@@ -762,7 +796,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
762
796
  // #5112: opt-in (`execution.fallback_local`): an issue the pool refused `capacityFallbackAfter` times (default CAPACITY_FALLBACK_AFTER)
763
797
  // for `sandbox.capacity` runs on the host when the host-busy guard (`remote.headroom()`, absent = allowed) passes; not ok or a throw waits.
764
798
  const capacityFallback = (n) => {
765
- if (!remote?.offlineFallback) return false;
799
+ if (!remote?.offlineFallback || !hostFallbackOn()) return false; // #5746: host_fallback: false keeps the lane on the pool
766
800
  const after = Number.isInteger(remote.capacityFallbackAfter) && remote.capacityFallbackAfter > 0 ? remote.capacityFallbackAfter : CAPACITY_FALLBACK_AFTER;
767
801
  if ((capDefers.get(n) ?? 0) < after) return false;
768
802
  // #5592: an overloaded host holds every local admission (host_overloaded), so falling back would park the lane indefinitely: keep retrying the pool
@@ -808,7 +842,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
808
842
  }
809
843
  } else if (cap && cap.online > 0) { poolOfflineSince = null; poolStallNoted = false; }
810
844
  // #4547: opt-in (`execution.fallback_local`): every pool agent offline or asleep (sampled online 0) runs the lane on the host.
811
- if (remote.offlineFallback && cap && cap.online === 0) {
845
+ if (remote.offlineFallback && hostFallbackOn() && cap && cap.online === 0) {
812
846
  p = { where: "local", reason: `fallback to local: no pool agent online (${p.reason})` };
813
847
  } else if (capacityFallback(n)) {
814
848
  p = { where: "local", reason: `fallback to local: pool at capacity after ${capDefers.get(n)} deferrals (${p.reason})` };
@@ -824,11 +858,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
824
858
  if (Number.isInteger(cap.free) && capAdmits >= cap.free && remoteRun.size < remoteMax()) { notBefore.set(n, now() + Math.max(pollMs, 1)); return false; }
825
859
  }
826
860
  if (p.where === "remote" && remoteRun.size < remoteMax()) { remoteCapped.delete(n); capWait.admitted(n); remoteRun.add(n); capAdmits++; placed.set(n, p); return true; }
827
- if (p.where === "remote" && !remote.fallbackLocal) { remoteCapped.add(n); return false; }
861
+ if (p.where === "remote" && (!remote.fallbackLocal || !hostFallbackOn())) { // #5746: host_fallback: false never runs a capped remote lane on the host
862
+ if (remoteMax() < 1 && !maxHeldNoted.has(n)) { maxHeldNoted.add(n); decided({ issue: n, what: `waiting: max_remote 0 (#${n} is queued, not run on the host)`, why: "remote mode holds admissions while max_remote is 0", alternative: "raise max_remote or set execution.host_fallback: true" }); }
863
+ remoteCapped.add(n); return false;
864
+ }
828
865
  if (p.where === "remote") p = { where: "local", reason: `fallback to local: max_remote ${remoteMax()} reached (${p.reason})` }; // #4256: hybrid runs it on the host
829
866
  } else {
830
867
  noteBudget(adm.reason);
831
- if (remote.onBudget !== "local" && !remote.fallbackLocal) { budgetStop = adm.reason; return false; }
868
+ if ((remote.onBudget !== "local" && !remote.fallbackLocal) || !hostFallbackOn()) { budgetStop = adm.reason; return false; } // #5746: host_fallback: false stops instead of using the host
832
869
  budgetLocal = true; // falls through to the host path
833
870
  p = { where: "local", reason: `fallback to local: execution budget: ${adm.reason}` };
834
871
  }
@@ -884,6 +921,51 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
884
921
  // #5859: sandboxes of one pool agent ending without a result in a burst (AGENT_LOST_MIN within AGENT_LOST_WINDOW_MS) are an agent/VM
885
922
  // restart: `sandbox.lost`, requeued once (after `remote.agentHealthy(agent)` answers, when the provider has it), never counted by the
886
923
  // breaker or the engine-error relaunch. Lanes of the burst that settled as engine-errors first are rolled back. One batch event each.
924
+ // #5988: one backend.auth outage at a time: probed on a clock, rotated, escalated once; `authPass` runs every loop pass.
925
+ let authOutage = null;
926
+ const authPass = async () => {
927
+ const o = authOutage; if (!o) return;
928
+ const t = now();
929
+ if (!o.escalated && t - o.since >= AUTH_ESCALATE_MS) {
930
+ o.escalated = true;
931
+ const detail = `backend.auth: the claude login has failed for ${Math.round((t - o.since) / 60000)} min (accounts tried: ${[...o.failed].join(", ") || "none"}); admissions no longer held, operator action needed`;
932
+ try { holds.clear(o.key); } catch { /* fail-open */ }
933
+ for (const m of o.issues) notBefore.delete(m);
934
+ for (const f of o.failed) limitedAccounts.delete(f);
935
+ update({ issue: null, outcome: "auth-escalation", detail });
936
+ try { await onEscalate?.({ detail, issues: [...o.issues], batch: batchId ?? null }); } catch { /* advisory */ }
937
+ return;
938
+ }
939
+ if (o.escalated || !authProbe || t < o.nextProbe) return;
940
+ const next = nextAccountAfterAuthFailure(rotator, o.last ? [o.last] : []); // the account after the one that failed last
941
+ let ok = false; try { ok = Boolean((await authProbe({ account: next, configDir: next ? rotator?.configDir?.(next) ?? null : null }))?.ok); } catch { ok = false; }
942
+ if (ok) {
943
+ try { holds.clear(o.key); } catch { /* fail-open */ }
944
+ for (const m of o.issues) notBefore.delete(m);
945
+ for (const f of o.failed) limitedAccounts.delete(f);
946
+ authOutage = null;
947
+ update({ issue: null, outcome: "auth-resumed", detail: `backend.auth recovered after ${Math.round((t - o.since) / 60000)} min; admissions resumed${next ? ` on account ${next}` : ""}` });
948
+ } else {
949
+ if (next) o.last = next;
950
+ o.nextProbe = t + AUTH_PROBE_MS;
951
+ }
952
+ };
953
+ // #5988: engine-errors with one host-bound signature on one agent are counted per (signature, agent): at the breaker's threshold only that
954
+ // agent is quarantined (its cache reseeded once); the batch breaker never sees them, so unaffected agents keep admitting.
955
+ const QUARANTINE_REQUEUES = 3, quarantineRequeues = new Map(), scopedSeen = new Map(), quarantined = new Map(), reseeded = new Set(); // quarantined: key -> until
956
+ const scopedEngineError = async (agent, sig) => {
957
+ const t = now(), key = `${sig}|${agent}`, windowMs = breaker.window_min * 60000, win = [...(scopedSeen.get(key) ?? []).filter((x) => t - x < windowMs), t];
958
+ scopedSeen.set(key, win);
959
+ if (quarantined.get(key) > t) return { quarantined: true };
960
+ if (win.length >= breaker.errors) {
961
+ quarantined.set(key, t + windowMs);
962
+ if (!reseeded.has(agent)) { reseeded.add(agent); try { await reseedCache?.({ agent, signature: sig }); } catch { /* advisory */ } }
963
+ try { await quarantineAgent?.({ agent, signature: sig, errors: win.length }); } catch { /* advisory */ }
964
+ update({ issue: null, outcome: "agent-quarantine", detail: `agent ${agent} quarantined: ${win.length} engine-errors (${sig}) within ${breaker.window_min} min; other agents keep admitting` });
965
+ return { quarantined: true };
966
+ }
967
+ return { quarantined: false };
968
+ };
887
969
  const lostSeen = new Map(); // agent -> [{n, at, err, ee, tr, sig}]: lost lanes settled as ordinary engine-errors in the window
888
970
  const openRestart = (agent, t) => agentRestarts.find((g) => g.agent === agent && !g.closed && t - g.last < AGENT_LOST_WINDOW_MS);
889
971
  const markLost = (agent, n, row, why) => {
@@ -924,9 +1006,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
924
1006
  // #5986: a failed lane lands in the issue's ledger; a lifetime-budget breach escalates once (FORGE:ESCALATION, needs-human) and parks the row.
925
1007
  const recordAttempt = async (n, row, r) => {
926
1008
  try {
1009
+ if (row.placement?.where === "remote" && r?.engineVersion) attempts.noteSandboxVersion?.(r.engineVersion); // #5931: the version the lane ran feeds the input hash
927
1010
  const hash = (await attempts.hash?.(n)) ?? null;
928
1011
  let l = ledgers.get(n) ?? (await attempts.load?.(n)) ?? null;
929
- l = recordFailure(l, { signature: failureSignature(row.code ?? r?.code, row.detail), hash, spend: Number(row.cost_usd) || 0, run: r?.runUrl ?? null });
1012
+ l = recordFailure(l, { signature: failureSignature(row.code ?? r?.code, row.detail), hash, spend: Number(row.cost_usd) || 0, run: r?.runUrl ?? null,
1013
+ blocker: blockerSignature({ code: row.code ?? r?.code, detail: row.detail, contractHash: r?.contractHash ?? null, engineVersion: r?.engineVersion ?? (row.placement?.where === "remote" ? null : curVersion()), placement: row.placement?.where ?? null, env: curEnvValues() }) });
930
1014
  const b = breach(l, attempts.cfg);
931
1015
  if (b && !l.escalated) {
932
1016
  l = markEscalated(l);
@@ -992,7 +1076,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
992
1076
  results.set(n, row); done(); save(); update(row);
993
1077
  return;
994
1078
  }
995
- if (rec?.plan) {
1079
+ const planVerdict = rec?.plan && r?.terminalReason !== "planned" && PLAN_VERDICT.has(row.outcome);
1080
+ if (planVerdict) { // #5909: a verdict end (invalid, needs-human, ...) is the issue's answer: it settles as a final row below, no build lane
1081
+ planMs.set(n, (planMs.get(n) ?? 0) + Math.max(0, now() - rec.startedAt));
1082
+ store?.log?.({ event: "STACK_PLAN_FAILED", issue: n, reason: row.outcome });
1083
+ } else if (rec?.plan) {
996
1084
  // #5831: a plan lane ends `planned` or `plan-failed` and goes back to pending for its build lane. It is never a final row and
997
1085
  // never counts toward the breaker, the engine-error relaunch, the deferral or the requeue budgets (it returns before them).
998
1086
  done();
@@ -1014,13 +1102,27 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1014
1102
  row.minutes = Math.round(((Number(row.minutes) || 0) + (Number(p.minutes) || 0)) * 10) / 10;
1015
1103
  }
1016
1104
  const triggers = [...(envIssueNo ? [`env issue #${envIssueNo} closing`] : []), "an engine upgrade", ...(envHold?.envFingerprint ? ["a --set-env"] : []), ...(tools?.length && envHold?.missingTools ? [`${tools.join(", ")} found on the host`] : [])];
1017
- const final = { ...row, outcome: "held", detail: `waiting on engine/env change: ${why}; re-admitted on ${triggers.join(" or ")}\n${String(row.detail ?? "")}`,
1018
- envHold: { kind, sig, from: row.outcome, version: curVersion(), env: curEnv(), ...(tools?.length ? { tools } : {}), ...(envIssueNo ? { envIssue: envIssueNo } : {}), since: now() }, waiting: true };
1105
+ // #6123: the previous re-admit (env issue closed / tool found) ended in this same signature: back off before the next one
1106
+ const prior = envReadmits.get(n);
1107
+ let notBefore = null;
1108
+ if (prior && prior.sig === sig) { prior.count += 1; notBefore = now() + envReadmitBackoffMs(prior.count); }
1109
+ else if (prior) envReadmits.delete(n);
1110
+ const final = { ...row, outcome: "held", detail: `waiting on engine/env change: ${why}; re-admitted on ${triggers.join(" or ")}${notBefore ? ` (not before ${new Date(notBefore).toISOString()}: the same ${sig.split("|")[0]} repeated after a re-admit)` : ""}\n${String(row.detail ?? "")}`,
1111
+ envHold: { kind, sig, from: row.outcome, version: curVersion(), env: curEnv(), ...(tools?.length ? { tools } : {}), ...(envIssueNo ? { envIssue: envIssueNo } : {}), ...(notBefore ? { notBefore } : {}), since: now() }, waiting: true };
1019
1112
  results.set(n, final); done(); save();
1020
1113
  decided({ issue: n, what: `held: waiting on engine/env change (${why})`, why: firstLine(row.detail) || row.outcome,
1021
1114
  alternative: kind === "engine" ? "relaunch into the same engine-error, or end engine-error and wait for a manual --requeue" : "launch a recovery that fails the same way, or end needs-human and wait for a manual --requeue" });
1022
1115
  update(final);
1023
1116
  };
1117
+ // #5931: a remote lane that ran another engine version than the host is an environment outcome, never conformance (gates fixed in the host version still fire there)
1118
+ const ranVersion = r?.engineVersion ?? /ForgeDock\s*[·-]\s*v?(\d+\.\d+(?:\.\d+)?)/.exec(String(r?.banner ?? row.detail ?? ""))?.[1] ?? null;
1119
+ if (ranVersion && row.placement?.where === "remote") row.engineVersion = String(ranVersion); // R3: the engine that actually ran stays on the row
1120
+ const vmm = (v) => (/^v?(\d+\.\d+)/.exec(String(v ?? "")) ?? [])[1] ?? null;
1121
+ if (row.placement?.where === "remote" && ranVersion && vmm(curVersion()) && vmm(ranVersion) !== vmm(curVersion()) && ["needs-human", "failed", "invalid", "budget-exceeded"].includes(row.outcome)) {
1122
+ row.code = OUTCOME_CODES.ENV_ENGINE_SKEW;
1123
+ row.detail = `${OUTCOME_CODES.ENV_ENGINE_SKEW}: the sandbox ran engine v${ranVersion}, the host is v${curVersion()}; not a conformance result. Place it locally or upgrade the agent.\n${String(row.detail ?? "")}`;
1124
+ if (ehOn) return holdEnv({ kind: "env", sig: `${OUTCOME_CODES.ENV_ENGINE_SKEW}|${ranVersion}|${curVersion()}`, why: `sandbox engine v${ranVersion} differs from the host v${curVersion()}` });
1125
+ }
1024
1126
  if (row.outcome === "dependency-open" && depList.length) {
1025
1127
  // #4387: a parked dependency is not pulled in again (fail-open on an unreadable label).
1026
1128
  let parked;
@@ -1065,6 +1167,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1065
1167
  update({ ...row, detail: `stopped by cancel: ${r?.code ?? row.outcome}${r?.detail ? ` ${r.detail}` : ""}` });
1066
1168
  return;
1067
1169
  }
1170
+ if (!(row.outcome === "deferred" && r?.code === "sandbox.capacity")) capDefers.delete(n); // #5746: a lane the pool accepted resets the capacity count
1068
1171
  if (row.outcome === "deferred" && (r?.code === "stack.replan" || r?.code === "stack.restart") && !cancelled) {
1069
1172
  // #5833: the stacked dependent's PR and branch were dropped. replan: it builds as a normal lane on the lane base (today's held/skipped
1070
1173
  // rules decide while its dependency is unsatisfied); restart: it may stack again on the dependency's new head, from the frozen contract.
@@ -1088,7 +1191,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1088
1191
  capWait.refused(n, r.reason ?? null);
1089
1192
  concEmit(conc.refused({ issue: n, code: r.code, reason: r.reason, live: r.live ?? null })); // #5985
1090
1193
  if (r.detail) capReasons.set(n, String(r.detail).slice(0, 300));
1091
- capDefers.set(n, (capDefers.get(n) ?? 0) + 1); // #5112: counted for the fallback_local capacity fallback
1194
+ // #5112: counted for the fallback_local capacity fallback; #5746: a host-busy refusal is not pool capacity
1195
+ if (!/host[ _-]?busy|headroom/i.test(String(r.detail ?? ""))) capDefers.set(n, (capDefers.get(n) ?? 0) + 1);
1092
1196
  try { const c = remote?.capacity?.(); capGated = Number.isInteger(c?.free) || capWait.conditional(n, c); } catch { capGated = false; }
1093
1197
  }
1094
1198
  if (!pol.capped) {
@@ -1111,12 +1215,21 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1111
1215
  if (!(Number.isFinite(rotAt) && rotAt > now())) rotAt = null;
1112
1216
  }
1113
1217
  // #5203: no account has headroom: the hold lasts until the earliest reset across accounts, not this lane's own reset.
1114
- const holdMs = usage && rotAt !== null ? rotAt - now() : pol.delayMs;
1218
+ let holdMs = usage && rotAt !== null ? rotAt - now() : pol.delayMs;
1219
+ if (r?.code === "backend.auth") { // #5988: probe every 5 min, never hold past the 30 min escalation, rotate to the next account
1220
+ const t0 = now();
1221
+ if (!authOutage) authOutage = { since: t0, nextProbe: t0 + AUTH_PROBE_MS, failed: new Set(), escalated: false, key: r?.backendId ?? identity(), issues: new Set() };
1222
+ authOutage.issues.add(n);
1223
+ try { const cur = authOutage.escalated ? null : rotator?.current?.(); if (cur) { authOutage.failed.add(cur); authOutage.last = cur; limitedAccounts.set(cur, t0 + AUTH_PROBE_MS); try { rotator.markLimited?.(cur, t0 + AUTH_PROBE_MS); } catch { /* best effort */ } } } catch { /* fail-open */ }
1224
+ holdMs = Math.min(holdMs, AUTH_PROBE_MS);
1225
+ if (t0 - authOutage.since >= AUTH_ESCALATE_MS) { await authPass(); holdMs = 0; }
1226
+ }
1115
1227
  if (rq) {
1116
1228
  delayMs = rq.delayMs;
1117
1229
  // #5095 + #5094: the pool account's own hold (not the host's) still routes hybrid lanes local until its reset.
1118
1230
  try { const pool = remote?.identity?.(); if (!rq.rotated && pool && r?.backendId === pool) holds.set(pool, now() + pol.delayMs, `batch ${batchId ?? "?"} #${n}`); } catch { /* fail-open */ }
1119
- } else try { holds.set(r?.backendId ?? identity(), rotAt ?? now() + holdMs, `batch ${batchId ?? "?"} #${n}`); delayMs = 0; } catch { /* fail-open */ }
1231
+ } else if (holdMs > 0 || r?.code !== "backend.auth") try { holds.set(r?.backendId ?? identity(), rotAt ?? now() + holdMs, `batch ${batchId ?? "?"} #${n}`); delayMs = 0; } catch { /* fail-open */ }
1232
+ else delayMs = AUTH_PROBE_MS; // #5988: escalated: no hold; the lane retries as its own probe
1120
1233
  const q = quota.get(n) ?? { cost_usd: 0, minutes: 0, rotations: 0 };
1121
1234
  const resumeAt = usage ? now() + (rq ? rq.delayMs : holdMs) : Math.max(now() + (rq ? rq.delayMs : pol.delayMs), rotAt ?? 0);
1122
1235
  quota.set(n, { cost_usd: Math.round(((Number(q.cost_usd) || 0) + (Number(row.cost_usd) || 0)) * 1e6) / 1e6, minutes: Math.round(((Number(q.minutes) || 0) + (Number(row.minutes) || 0)) * 10) / 10,
@@ -1133,6 +1246,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1133
1246
  }
1134
1247
  row.detail = `gave up after ${deferrals.get(n) ?? 0} deferrals: ${r?.detail ?? r?.code ?? ""}`;
1135
1248
  }
1249
+ // #6081: a held issue whose lane died without a result was stopped by the operator (SIGTERM / kill / sandbox stop), not by the engine:
1250
+ // a hold row, no engine-error, no breaker count, no relaunch budget spent; the issue waits pending for --release.
1251
+ if (row.outcome === "engine-error" && !cancelled && (r?.lostWithoutResult || /exited without a result|interrupted by SIG/i.test(String(r?.detail ?? ""))) && (refreshHeld(), opHeld.has(n))) {
1252
+ requeue(n, 0); done(); save();
1253
+ decided({ issue: n, what: `#${n} stopped while held by the operator; not an engine-error, not counted toward the breaker`, why: firstLine(row.detail) || "lane ended without a result", alternative: "count it as an engine-error and relaunch" });
1254
+ update({ ...row, outcome: "hold", detail: `#${n} stopped by operator hold: ${firstLine(row.detail) || "lane ended without a result"}` });
1255
+ return;
1256
+ }
1136
1257
  const la = row.outcome === "engine-error" && r?.lostWithoutResult && !cancelled && !lostOnce.has(n) ? (r.agent ?? r.sandbox?.agent ?? null) : null;
1137
1258
  let lostNow = null;
1138
1259
  if (la) { // #5859
@@ -1152,7 +1273,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1152
1273
  lostSeen.set(la, [...win, lostNow]);
1153
1274
  }
1154
1275
  if (row.outcome === "engine-error") {
1155
- const errAt = noteEngineError(r?.detail);
1276
+ const ag = r?.agent ?? r?.sandbox?.agent ?? null, hs = ag && breaker ? hostSignature(r, row.detail) : null;
1277
+ const sc = hs ? await scopedEngineError(ag, hs) : null;
1278
+ const qn = sc?.quarantined ? (quarantineRequeues.get(n) ?? 0) + 1 : 0; // a lane waits out the quarantine a bounded number of times, then counts as an ordinary engine-error (batch breaker included)
1279
+ if (sc?.quarantined && qn <= QUARANTINE_REQUEUES) { quarantineRequeues.set(n, qn); // #5988: an agent in quarantine: its lane waits and is requeued without a relaunch or breaker count; unaffected agents keep admitting
1280
+ requeue(n, AGENT_LOST_REQUEUE_MS); done(); save();
1281
+ update({ ...row, outcome: "requeued", detail: `requeued: agent ${ag} is quarantined (${hs}); retried in ${Math.round(AGENT_LOST_REQUEUE_MS / 1000)}s` });
1282
+ return;
1283
+ }
1284
+ const errAt = hs && !sc?.quarantined ? undefined : noteEngineError(r?.detail);
1156
1285
  if (lostNow) lostNow.err = errAt;
1157
1286
  // #5161: a transient failure (gateway 5xx, reset) waits out the outage with backoff instead of the single immediate relaunch.
1158
1287
  if (transientMax > 0 && isTransientEngineError(row.detail)) {
@@ -1263,6 +1392,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1263
1392
  // #5652: a remote lane's tool/capability end is not recovered on the host when host fallback is off; the lane message names the fix
1264
1393
  const noHostRecovery = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
1265
1394
  if (noHostRecovery) decided({ issue: n, what: `no host re-placement for ${row.code}: host fallback is off (execution.host_fallback / host.role: orchestrator)`, why: firstLine(row.detail), alternative: "re-place the lane on the host" });
1395
+ // #5749: an env.validate_timeout is host load, so its recovery lane is not started while the host is overloaded (it would time out again)
1396
+ if (overload && row.code === ENV_VALIDATE_TIMEOUT && classifyNeedsHuman(facts) === "recoverable" && used < max) {
1397
+ const isOver = () => { try { return overload()?.overloaded === true; } catch { return false; } };
1398
+ const t0 = now();
1399
+ if (isOver()) {
1400
+ decided({ issue: n, what: `recovery for ${row.code} deferred: the host is overloaded`, why: firstLine(row.detail) || row.code, alternative: "start the recovery lane under load and time out again" });
1401
+ while (isOver() && now() - t0 < OVERLOAD_RECOVERY_MAX_MS) await sleep(Math.max(pollMs, 1));
1402
+ }
1403
+ }
1266
1404
  // #5979: failure.repeated is a typed park (not in RECOVERABLE_CODES): never relaunched, reported parked below
1267
1405
  if (!repeatEnv && !noHostRecovery && !sameHostReplay && row.code !== OUTCOME_CODES.FAILURE_REPEATED && classifyNeedsHuman(facts) === "recoverable" && used < max) {
1268
1406
  // #5727: the first remote end on a tool no recipe can install, before any build work, is re-placed on the host without spending an attempt
@@ -1340,7 +1478,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1340
1478
  }
1341
1479
  const lane = ln?.lane;
1342
1480
  if (relabelled.delete(n)) save(); // #4315: the recovery lane launches after all; it removes needs-human itself
1343
- const pl = placed.get(n);
1481
+ // #5746: every running entry records where it runs; a lane admitted without a recorded placement (a requeue path) is derived, never left blank
1482
+ const pl = placed.get(n) ?? (remote ? (remoteRun.has(n) ? { where: "remote", reason: "mode remote" } : (placeOf(n) ?? undefined)) : undefined);
1344
1483
  placed.delete(n);
1345
1484
  const queueMs = Number.isFinite(enqueued.get(n)) ? Math.max(0, now() - enqueued.get(n)) : null; // #4908: queue_wait in the phase ledger
1346
1485
  heads.delete(n); enqueued.delete(n); busyNoted.delete(n);
@@ -1358,7 +1497,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1358
1497
  if (!["merged", "invalid", "deferred"].includes(gone?.outcome)) gone = null; // #4920: deferred = another lane owns the issue (lease or open PR on GitHub)
1359
1498
  }
1360
1499
  // #5526: a hold placed since the pass read is honoured at launch: the issue goes back to pending, no lane
1361
- if (!cancelled && !halted) { refreshHeld(); refreshPause(); if (opHeld.has(n) || opPause) { running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); requeue(n, 0); save(); return; } }
1500
+ if (!cancelled && !halted) { refreshHeld(); refreshPause(); if (opHeld.has(n) || opPause) { await null; /* #6081: track() registers this promise after the sync prefix; delete after it, or the entry leaks and the runner never ends */ running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); requeue(n, 0); save(); return; } }
1362
1501
  if (halted) return; // #4454: stopped before launch; no pid, so a resume queues it again
1363
1502
  let r;
1364
1503
  if (cancelled) r = { terminalReason: "deferred", code: "run.interrupted", cost_usd: 0, detail: "cancelled before launch" }; // #4376
@@ -1467,7 +1606,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1467
1606
  // the `getAdded` path below; closed or moved pending issues leave; ended deferred/held/engine-error/conformance rows are requeued
1468
1607
  // through `drainRequeues` by policy (reconcile.mjs). Same DAG, priority and lane rules as an operator `--add`/`--requeue`.
1469
1608
  let nextReconcile = 0, parkedDigest = "";
1470
- const selFresh = [], autoRequeues = [], selMatched = new Set(); // #6022: issues the selector has matched in this run
1609
+ const selFresh = [], autoRequeues = []; // #6022: selMatched (declared with the restores) = issues the selector has matched
1471
1610
  const reconcileTick = async () => {
1472
1611
  if (!reconcile) return;
1473
1612
  const t = now();
@@ -1478,18 +1617,20 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1478
1617
  const labels = new Map((open ?? []).map((o) => [o.number, o.labels ?? []]));
1479
1618
  if (open) {
1480
1619
  const { join, leave } = diffSelection({ open, members: [...set], pending, running, results, matched: selMatched });
1620
+ const matchedBefore = selMatched.size;
1481
1621
  for (const o of open) selMatched.add(o.number);
1482
1622
  selFresh.push(...join);
1483
1623
  for (const n of leave) {
1484
1624
  pending.splice(pending.indexOf(n), 1);
1485
1625
  skip(n, "left the selector: closed or moved");
1486
1626
  }
1487
- if (leave.length) save();
1627
+ if (leave.length || selMatched.size > matchedBefore) save();
1488
1628
  }
1489
1629
  for (const e of envSigs.values()) if (Number.isInteger(e.number) && !set.has(e.number)) selFresh.push(e.number); // R7: the engine-filed env.* issue joins the order
1490
1630
  let base = null;
1491
1631
  try { base = (await reconcile.base?.()) ?? null; } catch { base = null; }
1492
- const { requeue, parked } = readmitDue({ results, state: readmit, now: t, version: reconcile.version?.() ?? null, base, labels: (n) => labels.get(n) ?? [] });
1632
+ const agentV = await agentVersionOf(); // R6: the agent that would run the lane, so an agent upgrade re-admits
1633
+ const { requeue, parked } = readmitDue({ results, state: readmit, now: t, version: agentV ? `${reconcile.version?.() ?? ""}|agent=${agentV}` : reconcile.version?.() ?? null, base, labels: (n) => labels.get(n) ?? [] });
1493
1634
  for (const q of requeue) autoRequeues.push({ issue: q.issue, at: `reconcile-${t}`, reason: q.reason, by: "reconcile" });
1494
1635
  const digest = needsDecisionDigest(parked);
1495
1636
  if (digest !== parkedDigest) {
@@ -1666,12 +1807,21 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1666
1807
  if (!getHeld) return;
1667
1808
  if (expireHolds) { // #5469: a hold past its expiry is released here; the diff below then admits it. A dead owner session is an alert.
1668
1809
  let due = []; try { due = expireHolds() ?? []; } catch { due = []; }
1810
+ if (due.length > 1) holdRamp = { at: now() };
1811
+ if (due.length > 1) concEmit({ event: "concurrency", change: "hold-release", k: conc.operating("light"), ceiling: ceilingK(), factor: "hold expiry", inputs: { released: due.length } }); // #5988: the release is paced by K(), never all at once
1669
1812
  for (const e of due) {
1670
1813
  decided({ issue: null, what: `hold on #${e.issue} expired (held by ${e.owner} since ${e.since}${e.reason ? `: ${e.reason}` : ""}); re-admitted`, why: "hold expiry (--hold --for)", alternative: "hold it again" });
1671
1814
  update({ issue: null, outcome: "hold-expired", detail: `#${e.issue} (${e.owner}, since ${e.since})` });
1672
1815
  if (e.ownerGone) update({ issue: null, outcome: "hold-alert", detail: `#${e.issue}: the hold owner session (${e.owner}) is gone; the hold expired and the issue was re-admitted` });
1673
1816
  }
1674
1817
  }
1818
+ if (expireHolds) { // #5988: one alert per hold at T-30 min
1819
+ let info = null; try { info = getHoldInfo?.() ?? null; } catch { info = null; }
1820
+ for (const w of holdExpiryWarnings(info, { now: now(), warned: holdWarned })) {
1821
+ holdWarned.add(w.key);
1822
+ update({ issue: null, outcome: "hold-alert", detail: `#${w.issue}: the hold expires at ${w.expiresAt} (in ${Math.round(w.inMs / 60000)} min); release or extend it, or it re-admits through the concurrency controller` });
1823
+ }
1824
+ }
1675
1825
  let got = [];
1676
1826
  try { got = getHeld() ?? []; } catch { got = opHeld.size ? [...opHeld] : []; }
1677
1827
  const next = new Set((Array.isArray(got) ? got : []).filter((n) => Number.isSafeInteger(n) && n > 0));
@@ -1787,8 +1937,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1787
1937
  let l = ledgers.get(n) ?? null;
1788
1938
  if (!l) { l = (await attempts.load?.(n)) ?? null; if (l) ledgers.set(n, l); }
1789
1939
  if (!l) return true;
1790
- const hash = (await attempts.hash?.(n)) ?? null, a = admitInput(l, hash, attempts.cfg);
1791
- if (a.ok) return true;
1940
+ const hash = (await attempts.hash?.(n)) ?? null, a = admitInput(l, hash, attempts.cfg, { engineVersion: curVersion(), placement: placeOf(n)?.where ?? null, env: curEnvValues() });
1941
+ if (a.ok) { if (a.reason) update({ issue: n, event: "readmit.signature_changed", detail: `readmitted: ${a.reason}`, batch: batchId ?? null }); return true; }
1792
1942
  const key = `${n}|${hash}|${a.code}`;
1793
1943
  if (!refusedNoted.has(key)) {
1794
1944
  refusedNoted.add(key);
@@ -1839,12 +1989,20 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1839
1989
  continue;
1840
1990
  }
1841
1991
  }
1842
- let why = null;
1843
- if (h.envIssue && typeof envIssue?.isClosed === "function") { let c = false; try { c = (await envIssue.isClosed(h.envIssue)) === true; } catch { c = false; } if (c) why = `env issue #${h.envIssue} closed`; }
1844
- if (!why && v && h.version && v !== h.version) why = `engine version changed v${h.version} → v${v}`;
1992
+ let why = null, probeOrIssue = false;
1993
+ const backedOff = Number(h.notBefore) > now(); // #6123
1994
+ if (!backedOff && h.envIssue && typeof envIssue?.isClosed === "function") { let c = false; try { c = (await envIssue.isClosed(h.envIssue)) === true; } catch { c = false; } if (c) { why = `env issue #${h.envIssue} closed`; probeOrIssue = true; } }
1995
+ // R6/R8: a remote lane runs on a pool agent, so its engine is the agent's, not this host's. While every placeable agent is below the engine
1996
+ // the lane needs, the hold stays; an agent upgrade (not the orchestrator's) is the trigger.
1997
+ const av = r.placement?.where === "remote" ? await agentVersionOf() : null;
1998
+ if (av) {
1999
+ const needMM = vmm2(v), ranV = String(h.sig ?? "").startsWith(`${OUTCOME_CODES.ENV_ENGINE_SKEW}|`) ? h.sig.split("|")[1] : null;
2000
+ if (ranV) { if (vmm2(av) === needMM && vmm2(av) !== vmm2(ranV)) why = `agent engine upgraded v${ranV} → v${av}`; }
2001
+ else if (needMM && vmm2(av) === needMM && v && h.version && v !== h.version) why = `engine version changed v${h.version} → v${v}`;
2002
+ } else if (!why && v && h.version && v !== h.version) why = `engine version changed v${h.version} → v${v}`;
1845
2003
  if (why) { /* env issue closed */ } else if (fp && h.env && fp !== h.env) why = "batch env changed (--set-env)";
1846
- else if (h.tools?.length && !toolReadmits.has(`${n}|${h.sig}`) && (await missingTools(h.tools))?.length === 0) { why = `${h.tools.join(", ")} now found on the host`; toolReadmits.add(`${n}|${h.sig}`); }
1847
- if (why) { if (!(await gateAdmit(n))) continue; engineSigs.delete(n); releaseHeld(n, true, `re-admitted: ${why}`); continue; }
2004
+ else if (!backedOff && h.tools?.length && !toolReadmits.has(`${n}|${h.sig}`) && (await missingTools(h.tools))?.length === 0) { why = `${h.tools.join(", ")} now found on the host`; toolReadmits.add(`${n}|${h.sig}`); probeOrIssue = true; }
2005
+ if (why) { if (!(await gateAdmit(n))) continue; engineSigs.delete(n); if (probeOrIssue) envReadmits.set(n, { sig: h.sig, count: envReadmits.get(n)?.sig === h.sig ? envReadmits.get(n).count : 0, at: now() }); releaseHeld(n, true, `re-admitted: ${why}`); continue; }
1848
2006
  if (now() - (Number(h.since) || 0) >= ehMaxMs && !/no engine\/env change within/.test(r.detail ?? "")) { // the wait is over: the row stays held (resumable, --requeue), the batch may end
1849
2007
  const { waiting, ...rest } = r;
1850
2008
  const [head, ...tail] = String(rest.detail ?? "").split("\n");
@@ -1860,8 +2018,19 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1860
2018
  if (ro === undefined || running.has(root) || settled.has(root)) continue;
1861
2019
  if (restoredHeld.has(root) && ["needs-human", "budget-exceeded"].includes(ro) && typeof issueLabels === "function") { // label removed: requeue the root, its subtree follows
1862
2020
  let names = null;
1863
- try { names = await issueLabels(root); } catch { names = null; }
1864
- if (Array.isArray(names) && !names.includes("needs-human")) { if (await gateAdmit(root, { relabel: true })) releaseHeld(root, true, "needs-human label removed"); continue; }
2021
+ try { names = await issueLabels(root, { fresh: true }); } catch { names = null; } // #5893: never the memoized read
2022
+ if (Array.isArray(names) && !names.includes("needs-human")) {
2023
+ let sig = null;
2024
+ if (typeof heldFacts === "function") { // the removal must post-date the block; unreadable evidence fails closed
2025
+ let f = null; try { f = (await heldFacts(root)) ?? null; } catch { f = null; }
2026
+ if (!f || !Number.isFinite(f.removedAt) || !Number.isFinite(f.blockedAt) || f.removedAt <= f.blockedAt) continue;
2027
+ const prev = heldSigs.get(root);
2028
+ sig = { sig: `${ro}:${f.askKey ?? ""}`, removedAt: f.removedAt };
2029
+ if (prev && prev.sig === sig.sig && f.removedAt <= prev.removedAt) continue; // identical block, no new removal event
2030
+ }
2031
+ if (await gateAdmit(root, { relabel: true })) { if (sig) heldSigs.set(root, sig); releaseHeld(root, true, "needs-human label removed"); }
2032
+ continue;
2033
+ }
1865
2034
  }
1866
2035
  if (!dispatchCheck) continue;
1867
2036
  let g = null;
@@ -1920,12 +2089,12 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1920
2089
  }
1921
2090
  if (back.size) save();
1922
2091
  };
1923
- const ceilingK = () => { let k = null; try { k = getParallel?.(); } catch { k = null; } return Number.isInteger(k) && k >= 1 ? k : parallel; };
1924
2092
  // #5985: K is the ceiling; the controller's operating point (and a lower heavy-lane cap) sits under it. A pool with no load/memory data leaves K unchanged.
1925
2093
  // #5985: light/heavy per lane (its repo's recent cpu_avg from usage-history rows, array or getter); heavy lanes have their own concurrent cap
1926
2094
  const laneClassOf = (n) => { let rows = null; try { rows = typeof usageRows === "function" ? usageRows() : usageRows; } catch { rows = null; } let repo = repoSlug; try { repo = repoOf?.(n) ?? repoSlug; } catch { repo = repoSlug; } return rows && repo ? classifyRepo(rows, repo) : "light"; };
1927
2095
  const heavyFull = (n) => { if (laneClassOf(n) !== "heavy") return false; let h = 0; for (const m of running.keys()) if (m !== n && laneClassOf(m) === "heavy") h++; if (h < conc.heavyLimit()) return false; if (!heavyHeldHit) { heavyHeldHit = true; concEmit({ event: "concurrency", change: "heavy-cap", k: conc.operating("light"), ceiling: ceilingK(), factor: "heavy cap", inputs: { heavy_limit: conc.heavyLimit() } }); } return true; };
1928
- const K = () => { conc.setCeiling(ceilingK()); return conc.operating("light"); };
2096
+ // #5988: a hold expiry releasing several issues re-admits them on a ramp (one more lane per HOLD_RAMP_STEP_MS), as new work ramps, not all at once.
2097
+ const K = () => { conc.setCeiling(ceilingK()); const k = conc.operating("light"); if (!holdRamp) return k; const step = 1 + Math.floor((now() - holdRamp.at) / HOLD_RAMP_STEP_MS); if (step >= k) { holdRamp = null; return k; } return step; };
1929
2098
  // #5836: one train poll (throttled): a merged PR becomes a merged row; a red, conflicting or moved-head PR is handed back as a
1930
2099
  // needs-human row through the normal settle path, so in-batch recovery requeues a fix lane.
1931
2100
  let lastTrainTick = -Infinity;
@@ -2002,6 +2171,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2002
2171
  baseHit.clear();
2003
2172
  refreshHeld();
2004
2173
  refreshPause();
2174
+ await authPass(); // #5988
2005
2175
  await refreshBlocked();
2006
2176
  await refreshBaseWaits();
2007
2177
  checkGates();
@@ -2143,8 +2313,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2143
2313
  // #4685: a breaker tripped only by link failures (a router restart) closes itself after a cooldown
2144
2314
  if (tripped?.transport && now() - tripped.at >= TRANSPORT_COOLDOWN_MS) { tripped = null; errorTimes = []; transportErrors = 0; save(); }
2145
2315
  // #5978: a standing order's breaker closes itself after a cooldown when the failures were environmental and the pool is healthy
2146
- if (tripped && reconcile && !tripped.transport) {
2147
- let healthy = true; try { healthy = reconcile.poolHealthy ? reconcile.poolHealthy() !== false : true; } catch { healthy = true; }
2316
+ if (tripped && !tripped.transport) { // #6042: every batch, not only a standing order
2317
+ let healthy = true; try { healthy = reconcile?.poolHealthy ? reconcile.poolHealthy() !== false : true; } catch { healthy = true; }
2148
2318
  const d = decideAutoReset({ tripped, now: now(), cooldownMs: BREAKER_COOLDOWN_MS, environmental: tripped.environmental === true, poolHealthy: healthy });
2149
2319
  if (d.reset) {
2150
2320
  tripped = null; errorTimes = []; transportErrors = 0; save();
@@ -2165,6 +2335,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2165
2335
  if (d.clear && wasTripped) continue; // admission ran before this check: re-run the pass so the cleared batch resumes instead of falling to the "nothing runnable" skip
2166
2336
  }
2167
2337
  }
2338
+ // #6042: a breaker pauses admission; it ends the run only when nothing can clear it (a non-environmental trip with no hosted clear channel)
2339
+ const breakerClearable = Boolean(tripped && pending.length && !cancelled && !budgetStop && !signal?.aborted && (tripped.environmental || tripped.transport || getClearBreaker));
2340
+ if (tripped && !running.size && breakerClearable) { await nap(pollMs); continue; }
2168
2341
  if (tripped && !running.size) { await drainAdds(); break; } // breaker: let running lanes finish, keep the rest pending for a resume
2169
2342
  if (cancelled && !running.size) { await drainAdds(); break; } // #4376: cancel: the rest end held for a resume
2170
2343
  if (budgetStop && !running.size) { await drainAdds(); break; } // execution budget (stop): the same, the rest end held
@@ -2202,7 +2375,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2202
2375
  if (running.size && envWaiting()) wake = Math.min(wake ?? ehWatchMs, ehWatchMs); // #5805: re-check engine/env holds while lanes run
2203
2376
  if (train?.size()) wake = Math.min(wake ?? trainEveryMs, Math.max(0, trainEveryMs - (now() - lastTrainTick))); // #5836
2204
2377
  if (reconcile && running.size) wake = Math.min(wake ?? reconcile.everyMs ?? RECONCILE_MS, reconcile.everyMs ?? RECONCILE_MS); // #5978
2205
- if (tripped) wake = getClearBreaker ? Math.min(wake ?? pollMs, pollMs) : null;
2378
+ if (tripped) wake = getClearBreaker || tripped.environmental || tripped.transport ? Math.min(wake ?? pollMs, pollMs) : null;
2206
2379
  if (getCancelled && running.size && (!cancelled || [...running.keys()].some((n) => { const x = stopSent.get(n); return x && !(x.accepted && x.reported); }))) wake = Math.min(wake ?? pollMs, pollMs); // #5241: a cancel keeps polling a lane whose stop is unconfirmed // #4376: notice a cancel while lanes run
2207
2380
  if (running.size) {
2208
2381
  if (wake === null) await race(running.values());
@@ -2352,7 +2525,7 @@ export function formatTable(rows) {
2352
2525
  */
2353
2526
  export function phasesOf(r, rec) {
2354
2527
  if (!r?.phases || typeof r.phases !== "object" || !Object.keys(r.phases).length) return null;
2355
- return { ...(Number.isFinite(rec?.queueMs) && rec.queueMs > 0 ? { queue_wait: { ms: Math.round(rec.queueMs) } } : {}), ...r.phases };
2528
+ return { ...(Number.isFinite(rec?.queueMs) && rec.queueMs > 0 ? { queue_wait: { ms: Math.round(rec.queueMs), ...((r.sandbox?.agent ?? r.agent) ? { worker: r.sandbox?.agent ?? r.agent } : {}) } } : {}), ...r.phases };
2356
2529
  }
2357
2530
 
2358
2531
  export function formatWaitSummary(rows, heavyStats = null) {