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
@@ -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).
@@ -291,6 +299,7 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
291
299
  const STOP_RETRY_MS = 15 * 1000;
292
300
  const STOP_TIMEOUT_MS = 120 * 1000;
293
301
 
302
+ const OVERLOAD_RECOVERY_MAX_MS = 30 * 60 * 1000; // #5749: longest an env.validate_timeout recovery waits for the host to stop being overloaded
294
303
  const cancellableSleep = (ms, signal) => new Promise((res) => {
295
304
  const t = setTimeout(res, ms);
296
305
  signal?.addEventListener("abort", () => { clearTimeout(t); res(); }, { once: true });
@@ -342,7 +351,7 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
342
351
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
343
352
  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
353
  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,
354
+ 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
355
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
347
356
  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
357
  train = null, trainEveryMs = DEFAULT_TRAIN_EVERY_MS, attempts = null }) {
@@ -358,6 +367,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
358
367
  const keptBoxes = toMap(saved?.kept); // #6008: issue -> {issue, since, phase}: sandboxes kept for adopt (no dispatcher lease)
359
368
  const runRecs = toMap(saved?.running); // issue -> {startedAt, lane, pid?}: persisted so a restart can adopt the lane
360
369
  const pending = [...(saved?.pending ?? [])];
370
+ const selMatched = new Set(saved?.selMatched ?? []); // #6029: issues the selector has matched (persisted: a resumed runner keeps the leave provenance)
361
371
  const notBefore = toMap(saved?.notBefore);
362
372
  const requeues = toMap(saved?.requeues);
363
373
  const deferrals = toMap(saved?.deferrals);
@@ -375,6 +385,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
375
385
  // 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
386
  const envSigs = toMap(saved?.envSigs);
377
387
  const engineSigs = toMap(saved?.engineSigs);
388
+ 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
389
  const readmit = toMap(saved?.readmit); // #5978: re-admission policy state (backoff step, version and base seen) per ended issue
379
390
  const ledgers = toMap(saved?.attempts); // #5986: issue -> attempts ledger; never cleared by releaseHeld, --requeue or --set-env (see attempts.mjs)
380
391
  const deterministic = new Set(saved?.deterministicSigs ?? []);
@@ -382,6 +393,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
382
393
  const ehMaxMs = Number(envHold?.maxMs) > 0 ? Number(envHold.maxMs) : ENV_HOLD_MAX_MS;
383
394
  const ehWatchMs = Number(envHold?.watchMs) > 0 ? Number(envHold.watchMs) : ENV_WATCH_MS;
384
395
  const curVersion = () => { try { return envHold?.version?.() ?? version ?? null; } catch { return version ?? null; } };
396
+ const vmm2 = (x) => (/^v?(\d+\.\d+)/.exec(String(x ?? "")) ?? [])[1] ?? null;
397
+ const agentVersionOf = async () => { try { return (await envHold?.agentVersion?.()) ?? null; } catch { return null; } };
398
+ const curEnvValues = () => { try { return envHold?.envValues?.() ?? null; } catch { return null; } }; // #5931
385
399
  const curEnv = () => { try { return envHold?.envFingerprint?.() ?? null; } catch { return null; } };
386
400
  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
401
  const checked = toMap(saved?.prefilter); // issue -> pre-filter result
@@ -389,6 +403,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
389
403
  const enqueued = toMap(saved?.enqueued); // #4409: issue -> when it last entered the queue (starvation guard)
390
404
  const heads = new Set(saved?.heads ?? []); // #4409: decomposed sub-issues not started yet: the head of their priority band
391
405
  let errorTimes = [...(saved?.errorTimes ?? [])];
406
+ 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
407
+ const holdWarned = new Set(); let holdRamp = null; // #5988: declared early: the hoisted refreshHeld reads them from finish/recovery callbacks
392
408
  // #5859: agent restarts of this batch (one record each, shown by `status --batch`) and the lanes already requeued as `sandbox.lost`
393
409
  const agentRestarts = [...(saved?.agentRestarts ?? [])];
394
410
  const lostOnce = new Set(saved?.lostRequeued ?? []); // a lane lost again after its requeue is an ordinary engine-error
@@ -432,6 +448,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
432
448
  const priorities = toMap(saved?.priorities); // issue -> priority number; only with the registry
433
449
  // #5138: read on every grant, so `--set-max-remote` reaches a running batch (a getter on `remote`); running lanes are never stopped.
434
450
  const remoteMax = () => { const m = remote?.max; return Number.isInteger(m) && m >= 0 ? m : 0; };
451
+ const maxHeldNoted = new Set(); // #5746: issues already announced as waiting on max_remote 0
435
452
  const remoteCapped = new Set(); // #5138: issues waiting for a max_remote slot; polled so a raised live max_remote admits them
436
453
  let poolOfflineSince = null, poolStallNoted = false; // #4788: when sampled online first read 0, and whether the stall was reported
437
454
  const capWait = makeCapWait({ now }); // #4909: a lane refused for capacity waits for a free slot, recorded as queue time
@@ -449,10 +466,16 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
449
466
  const rec = recovering.get(n);
450
467
  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
468
  // #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}` };
469
+ // #5931: a credentials block pinned the issue to the host (ledger hostPin): applied on readmit whatever host fallback says
470
+ if (ledgers.get(n)?.hostPin) return { where: "local", reason: "host pin: ops_credentials block" };
471
+ 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
472
  // #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)
473
+ if (recovering.get(n)?.code === ENV_VALIDATE_PLACEMENT || (MECHANICAL_CODES.includes(recovering.get(n)?.code) && recovering.get(n)?.where === "remote")) {
474
+ if (hostFallbackOn()) return { where: "local", reason: `different placement: recovering ${rec.code} off the remote run` };
475
+ // #5746: the host is not allowed: retry remotely (a fresh sandbox) instead of the orchestrator
476
+ if (!budgetLocal) return { where: "remote", reason: `retry remotely, host fallback off: recovering ${rec.code}` };
477
+ }
478
+ 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
479
  const lk = lackedTools(remote.contractOf?.(n), remote.lacks);
457
480
  if (lk.tools.length) return { where: "local", reason: `host tool: sandbox lacks ${lk.tools.join(", ")}` };
458
481
  }
@@ -463,7 +486,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
463
486
  return { where: p?.where === "remote" ? "remote" : "local", reason: String(p?.reason ?? "") };
464
487
  }
465
488
  return remote.isRemote?.(n) ? { where: "remote", reason: "mode remote" } : { where: "local", reason: "local" };
466
- } catch { return { where: "local", reason: "placement failed" }; }
489
+ } catch { return hostFallbackOn() ? { where: "local", reason: "placement failed" } : { where: "remote", reason: "placement failed, host fallback off: retry remotely" }; } // #5746
467
490
  };
468
491
  const isRemote = (n) => placeOf(n)?.where === "remote";
469
492
  const placed = new Map(); // issue -> {where, reason} granted this pass, picked up by start()
@@ -478,7 +501,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
478
501
  // #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
502
  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
503
  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
504
+ const ENV_ALL_CODES = [...REPEAT_ENV_CODES, ENV_VALIDATE_TIMEOUT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_ENGINE_SKEW]; // #5755, #5931
482
505
  const envKey = (code, d) => `${code}|${code === OUTCOME_CODES.ENV_TOOL_MISSING && toolsOf(d) ? toolsOf(d) : failureSignature(code, d).split("|").slice(1).join("|")}`;
483
506
  const maxFor = (cls) => (cls === "mechanical" ? mechMax : recoveryMax);
484
507
  const classUsed = toMap(saved?.recoveryClasses); // `${issue}:${class}` -> recovery lanes launched in that class
@@ -522,7 +545,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
522
545
  ...(requeueApplied.size ? { requeueApplied: [...requeueApplied], requeued: toObj(requeuedInfo) } : {}),
523
546
  ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}), ...(train ? { train: train.snapshot() } : {}),
524
547
  ...(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) } : {}) });
548
+ ...(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
549
  };
527
550
  const update = (row) => { store?.log?.(row); onUpdate(row); };
528
551
  // #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 +785,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
762
785
  // #5112: opt-in (`execution.fallback_local`): an issue the pool refused `capacityFallbackAfter` times (default CAPACITY_FALLBACK_AFTER)
763
786
  // for `sandbox.capacity` runs on the host when the host-busy guard (`remote.headroom()`, absent = allowed) passes; not ok or a throw waits.
764
787
  const capacityFallback = (n) => {
765
- if (!remote?.offlineFallback) return false;
788
+ if (!remote?.offlineFallback || !hostFallbackOn()) return false; // #5746: host_fallback: false keeps the lane on the pool
766
789
  const after = Number.isInteger(remote.capacityFallbackAfter) && remote.capacityFallbackAfter > 0 ? remote.capacityFallbackAfter : CAPACITY_FALLBACK_AFTER;
767
790
  if ((capDefers.get(n) ?? 0) < after) return false;
768
791
  // #5592: an overloaded host holds every local admission (host_overloaded), so falling back would park the lane indefinitely: keep retrying the pool
@@ -808,7 +831,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
808
831
  }
809
832
  } else if (cap && cap.online > 0) { poolOfflineSince = null; poolStallNoted = false; }
810
833
  // #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) {
834
+ if (remote.offlineFallback && hostFallbackOn() && cap && cap.online === 0) {
812
835
  p = { where: "local", reason: `fallback to local: no pool agent online (${p.reason})` };
813
836
  } else if (capacityFallback(n)) {
814
837
  p = { where: "local", reason: `fallback to local: pool at capacity after ${capDefers.get(n)} deferrals (${p.reason})` };
@@ -824,11 +847,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
824
847
  if (Number.isInteger(cap.free) && capAdmits >= cap.free && remoteRun.size < remoteMax()) { notBefore.set(n, now() + Math.max(pollMs, 1)); return false; }
825
848
  }
826
849
  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; }
850
+ if (p.where === "remote" && (!remote.fallbackLocal || !hostFallbackOn())) { // #5746: host_fallback: false never runs a capped remote lane on the host
851
+ 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" }); }
852
+ remoteCapped.add(n); return false;
853
+ }
828
854
  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
855
  } else {
830
856
  noteBudget(adm.reason);
831
- if (remote.onBudget !== "local" && !remote.fallbackLocal) { budgetStop = adm.reason; return false; }
857
+ if ((remote.onBudget !== "local" && !remote.fallbackLocal) || !hostFallbackOn()) { budgetStop = adm.reason; return false; } // #5746: host_fallback: false stops instead of using the host
832
858
  budgetLocal = true; // falls through to the host path
833
859
  p = { where: "local", reason: `fallback to local: execution budget: ${adm.reason}` };
834
860
  }
@@ -884,6 +910,51 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
884
910
  // #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
911
  // restart: `sandbox.lost`, requeued once (after `remote.agentHealthy(agent)` answers, when the provider has it), never counted by the
886
912
  // breaker or the engine-error relaunch. Lanes of the burst that settled as engine-errors first are rolled back. One batch event each.
913
+ // #5988: one backend.auth outage at a time: probed on a clock, rotated, escalated once; `authPass` runs every loop pass.
914
+ let authOutage = null;
915
+ const authPass = async () => {
916
+ const o = authOutage; if (!o) return;
917
+ const t = now();
918
+ if (!o.escalated && t - o.since >= AUTH_ESCALATE_MS) {
919
+ o.escalated = true;
920
+ 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`;
921
+ try { holds.clear(o.key); } catch { /* fail-open */ }
922
+ for (const m of o.issues) notBefore.delete(m);
923
+ for (const f of o.failed) limitedAccounts.delete(f);
924
+ update({ issue: null, outcome: "auth-escalation", detail });
925
+ try { await onEscalate?.({ detail, issues: [...o.issues], batch: batchId ?? null }); } catch { /* advisory */ }
926
+ return;
927
+ }
928
+ if (o.escalated || !authProbe || t < o.nextProbe) return;
929
+ const next = nextAccountAfterAuthFailure(rotator, o.last ? [o.last] : []); // the account after the one that failed last
930
+ let ok = false; try { ok = Boolean((await authProbe({ account: next, configDir: next ? rotator?.configDir?.(next) ?? null : null }))?.ok); } catch { ok = false; }
931
+ if (ok) {
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
+ authOutage = null;
936
+ update({ issue: null, outcome: "auth-resumed", detail: `backend.auth recovered after ${Math.round((t - o.since) / 60000)} min; admissions resumed${next ? ` on account ${next}` : ""}` });
937
+ } else {
938
+ if (next) o.last = next;
939
+ o.nextProbe = t + AUTH_PROBE_MS;
940
+ }
941
+ };
942
+ // #5988: engine-errors with one host-bound signature on one agent are counted per (signature, agent): at the breaker's threshold only that
943
+ // agent is quarantined (its cache reseeded once); the batch breaker never sees them, so unaffected agents keep admitting.
944
+ const QUARANTINE_REQUEUES = 3, quarantineRequeues = new Map(), scopedSeen = new Map(), quarantined = new Map(), reseeded = new Set(); // quarantined: key -> until
945
+ const scopedEngineError = async (agent, sig) => {
946
+ const t = now(), key = `${sig}|${agent}`, windowMs = breaker.window_min * 60000, win = [...(scopedSeen.get(key) ?? []).filter((x) => t - x < windowMs), t];
947
+ scopedSeen.set(key, win);
948
+ if (quarantined.get(key) > t) return { quarantined: true };
949
+ if (win.length >= breaker.errors) {
950
+ quarantined.set(key, t + windowMs);
951
+ if (!reseeded.has(agent)) { reseeded.add(agent); try { await reseedCache?.({ agent, signature: sig }); } catch { /* advisory */ } }
952
+ try { await quarantineAgent?.({ agent, signature: sig, errors: win.length }); } catch { /* advisory */ }
953
+ update({ issue: null, outcome: "agent-quarantine", detail: `agent ${agent} quarantined: ${win.length} engine-errors (${sig}) within ${breaker.window_min} min; other agents keep admitting` });
954
+ return { quarantined: true };
955
+ }
956
+ return { quarantined: false };
957
+ };
887
958
  const lostSeen = new Map(); // agent -> [{n, at, err, ee, tr, sig}]: lost lanes settled as ordinary engine-errors in the window
888
959
  const openRestart = (agent, t) => agentRestarts.find((g) => g.agent === agent && !g.closed && t - g.last < AGENT_LOST_WINDOW_MS);
889
960
  const markLost = (agent, n, row, why) => {
@@ -924,9 +995,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
924
995
  // #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
996
  const recordAttempt = async (n, row, r) => {
926
997
  try {
998
+ if (row.placement?.where === "remote" && r?.engineVersion) attempts.noteSandboxVersion?.(r.engineVersion); // #5931: the version the lane ran feeds the input hash
927
999
  const hash = (await attempts.hash?.(n)) ?? null;
928
1000
  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 });
1001
+ l = recordFailure(l, { signature: failureSignature(row.code ?? r?.code, row.detail), hash, spend: Number(row.cost_usd) || 0, run: r?.runUrl ?? null,
1002
+ 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
1003
  const b = breach(l, attempts.cfg);
931
1004
  if (b && !l.escalated) {
932
1005
  l = markEscalated(l);
@@ -992,7 +1065,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
992
1065
  results.set(n, row); done(); save(); update(row);
993
1066
  return;
994
1067
  }
995
- if (rec?.plan) {
1068
+ const planVerdict = rec?.plan && r?.terminalReason !== "planned" && PLAN_VERDICT.has(row.outcome);
1069
+ if (planVerdict) { // #5909: a verdict end (invalid, needs-human, ...) is the issue's answer: it settles as a final row below, no build lane
1070
+ planMs.set(n, (planMs.get(n) ?? 0) + Math.max(0, now() - rec.startedAt));
1071
+ store?.log?.({ event: "STACK_PLAN_FAILED", issue: n, reason: row.outcome });
1072
+ } else if (rec?.plan) {
996
1073
  // #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
1074
  // never counts toward the breaker, the engine-error relaunch, the deferral or the requeue budgets (it returns before them).
998
1075
  done();
@@ -1021,6 +1098,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1021
1098
  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
1099
  update(final);
1023
1100
  };
1101
+ // #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)
1102
+ const ranVersion = r?.engineVersion ?? /ForgeDock\s*[·-]\s*v?(\d+\.\d+(?:\.\d+)?)/.exec(String(r?.banner ?? row.detail ?? ""))?.[1] ?? null;
1103
+ if (ranVersion && row.placement?.where === "remote") row.engineVersion = String(ranVersion); // R3: the engine that actually ran stays on the row
1104
+ const vmm = (v) => (/^v?(\d+\.\d+)/.exec(String(v ?? "")) ?? [])[1] ?? null;
1105
+ if (row.placement?.where === "remote" && ranVersion && vmm(curVersion()) && vmm(ranVersion) !== vmm(curVersion()) && ["needs-human", "failed", "invalid", "budget-exceeded"].includes(row.outcome)) {
1106
+ row.code = OUTCOME_CODES.ENV_ENGINE_SKEW;
1107
+ 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 ?? "")}`;
1108
+ 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()}` });
1109
+ }
1024
1110
  if (row.outcome === "dependency-open" && depList.length) {
1025
1111
  // #4387: a parked dependency is not pulled in again (fail-open on an unreadable label).
1026
1112
  let parked;
@@ -1065,6 +1151,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1065
1151
  update({ ...row, detail: `stopped by cancel: ${r?.code ?? row.outcome}${r?.detail ? ` ${r.detail}` : ""}` });
1066
1152
  return;
1067
1153
  }
1154
+ if (!(row.outcome === "deferred" && r?.code === "sandbox.capacity")) capDefers.delete(n); // #5746: a lane the pool accepted resets the capacity count
1068
1155
  if (row.outcome === "deferred" && (r?.code === "stack.replan" || r?.code === "stack.restart") && !cancelled) {
1069
1156
  // #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
1157
  // rules decide while its dependency is unsatisfied); restart: it may stack again on the dependency's new head, from the frozen contract.
@@ -1088,7 +1175,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1088
1175
  capWait.refused(n, r.reason ?? null);
1089
1176
  concEmit(conc.refused({ issue: n, code: r.code, reason: r.reason, live: r.live ?? null })); // #5985
1090
1177
  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
1178
+ // #5112: counted for the fallback_local capacity fallback; #5746: a host-busy refusal is not pool capacity
1179
+ if (!/host[ _-]?busy|headroom/i.test(String(r.detail ?? ""))) capDefers.set(n, (capDefers.get(n) ?? 0) + 1);
1092
1180
  try { const c = remote?.capacity?.(); capGated = Number.isInteger(c?.free) || capWait.conditional(n, c); } catch { capGated = false; }
1093
1181
  }
1094
1182
  if (!pol.capped) {
@@ -1111,12 +1199,21 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1111
1199
  if (!(Number.isFinite(rotAt) && rotAt > now())) rotAt = null;
1112
1200
  }
1113
1201
  // #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;
1202
+ let holdMs = usage && rotAt !== null ? rotAt - now() : pol.delayMs;
1203
+ if (r?.code === "backend.auth") { // #5988: probe every 5 min, never hold past the 30 min escalation, rotate to the next account
1204
+ const t0 = now();
1205
+ if (!authOutage) authOutage = { since: t0, nextProbe: t0 + AUTH_PROBE_MS, failed: new Set(), escalated: false, key: r?.backendId ?? identity(), issues: new Set() };
1206
+ authOutage.issues.add(n);
1207
+ 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 */ }
1208
+ holdMs = Math.min(holdMs, AUTH_PROBE_MS);
1209
+ if (t0 - authOutage.since >= AUTH_ESCALATE_MS) { await authPass(); holdMs = 0; }
1210
+ }
1115
1211
  if (rq) {
1116
1212
  delayMs = rq.delayMs;
1117
1213
  // #5095 + #5094: the pool account's own hold (not the host's) still routes hybrid lanes local until its reset.
1118
1214
  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 */ }
1215
+ } 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 */ }
1216
+ else delayMs = AUTH_PROBE_MS; // #5988: escalated: no hold; the lane retries as its own probe
1120
1217
  const q = quota.get(n) ?? { cost_usd: 0, minutes: 0, rotations: 0 };
1121
1218
  const resumeAt = usage ? now() + (rq ? rq.delayMs : holdMs) : Math.max(now() + (rq ? rq.delayMs : pol.delayMs), rotAt ?? 0);
1122
1219
  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 +1230,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1133
1230
  }
1134
1231
  row.detail = `gave up after ${deferrals.get(n) ?? 0} deferrals: ${r?.detail ?? r?.code ?? ""}`;
1135
1232
  }
1233
+ // #6081: a held issue whose lane died without a result was stopped by the operator (SIGTERM / kill / sandbox stop), not by the engine:
1234
+ // a hold row, no engine-error, no breaker count, no relaunch budget spent; the issue waits pending for --release.
1235
+ if (row.outcome === "engine-error" && !cancelled && (r?.lostWithoutResult || /exited without a result|interrupted by SIG/i.test(String(r?.detail ?? ""))) && (refreshHeld(), opHeld.has(n))) {
1236
+ requeue(n, 0); done(); save();
1237
+ 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" });
1238
+ update({ ...row, outcome: "hold", detail: `#${n} stopped by operator hold: ${firstLine(row.detail) || "lane ended without a result"}` });
1239
+ return;
1240
+ }
1136
1241
  const la = row.outcome === "engine-error" && r?.lostWithoutResult && !cancelled && !lostOnce.has(n) ? (r.agent ?? r.sandbox?.agent ?? null) : null;
1137
1242
  let lostNow = null;
1138
1243
  if (la) { // #5859
@@ -1152,7 +1257,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1152
1257
  lostSeen.set(la, [...win, lostNow]);
1153
1258
  }
1154
1259
  if (row.outcome === "engine-error") {
1155
- const errAt = noteEngineError(r?.detail);
1260
+ const ag = r?.agent ?? r?.sandbox?.agent ?? null, hs = ag && breaker ? hostSignature(r, row.detail) : null;
1261
+ const sc = hs ? await scopedEngineError(ag, hs) : null;
1262
+ 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)
1263
+ 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
1264
+ requeue(n, AGENT_LOST_REQUEUE_MS); done(); save();
1265
+ update({ ...row, outcome: "requeued", detail: `requeued: agent ${ag} is quarantined (${hs}); retried in ${Math.round(AGENT_LOST_REQUEUE_MS / 1000)}s` });
1266
+ return;
1267
+ }
1268
+ const errAt = hs && !sc?.quarantined ? undefined : noteEngineError(r?.detail);
1156
1269
  if (lostNow) lostNow.err = errAt;
1157
1270
  // #5161: a transient failure (gateway 5xx, reset) waits out the outage with backoff instead of the single immediate relaunch.
1158
1271
  if (transientMax > 0 && isTransientEngineError(row.detail)) {
@@ -1263,6 +1376,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1263
1376
  // #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
1377
  const noHostRecovery = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
1265
1378
  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" });
1379
+ // #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)
1380
+ if (overload && row.code === ENV_VALIDATE_TIMEOUT && classifyNeedsHuman(facts) === "recoverable" && used < max) {
1381
+ const isOver = () => { try { return overload()?.overloaded === true; } catch { return false; } };
1382
+ const t0 = now();
1383
+ if (isOver()) {
1384
+ 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" });
1385
+ while (isOver() && now() - t0 < OVERLOAD_RECOVERY_MAX_MS) await sleep(Math.max(pollMs, 1));
1386
+ }
1387
+ }
1266
1388
  // #5979: failure.repeated is a typed park (not in RECOVERABLE_CODES): never relaunched, reported parked below
1267
1389
  if (!repeatEnv && !noHostRecovery && !sameHostReplay && row.code !== OUTCOME_CODES.FAILURE_REPEATED && classifyNeedsHuman(facts) === "recoverable" && used < max) {
1268
1390
  // #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
@@ -1358,7 +1480,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1358
1480
  if (!["merged", "invalid", "deferred"].includes(gone?.outcome)) gone = null; // #4920: deferred = another lane owns the issue (lease or open PR on GitHub)
1359
1481
  }
1360
1482
  // #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; } }
1483
+ 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
1484
  if (halted) return; // #4454: stopped before launch; no pid, so a resume queues it again
1363
1485
  let r;
1364
1486
  if (cancelled) r = { terminalReason: "deferred", code: "run.interrupted", cost_usd: 0, detail: "cancelled before launch" }; // #4376
@@ -1467,7 +1589,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1467
1589
  // the `getAdded` path below; closed or moved pending issues leave; ended deferred/held/engine-error/conformance rows are requeued
1468
1590
  // through `drainRequeues` by policy (reconcile.mjs). Same DAG, priority and lane rules as an operator `--add`/`--requeue`.
1469
1591
  let nextReconcile = 0, parkedDigest = "";
1470
- const selFresh = [], autoRequeues = [], selMatched = new Set(); // #6022: issues the selector has matched in this run
1592
+ const selFresh = [], autoRequeues = []; // #6022: selMatched (declared with the restores) = issues the selector has matched
1471
1593
  const reconcileTick = async () => {
1472
1594
  if (!reconcile) return;
1473
1595
  const t = now();
@@ -1478,18 +1600,20 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1478
1600
  const labels = new Map((open ?? []).map((o) => [o.number, o.labels ?? []]));
1479
1601
  if (open) {
1480
1602
  const { join, leave } = diffSelection({ open, members: [...set], pending, running, results, matched: selMatched });
1603
+ const matchedBefore = selMatched.size;
1481
1604
  for (const o of open) selMatched.add(o.number);
1482
1605
  selFresh.push(...join);
1483
1606
  for (const n of leave) {
1484
1607
  pending.splice(pending.indexOf(n), 1);
1485
1608
  skip(n, "left the selector: closed or moved");
1486
1609
  }
1487
- if (leave.length) save();
1610
+ if (leave.length || selMatched.size > matchedBefore) save();
1488
1611
  }
1489
1612
  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
1613
  let base = null;
1491
1614
  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) ?? [] });
1615
+ const agentV = await agentVersionOf(); // R6: the agent that would run the lane, so an agent upgrade re-admits
1616
+ 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
1617
  for (const q of requeue) autoRequeues.push({ issue: q.issue, at: `reconcile-${t}`, reason: q.reason, by: "reconcile" });
1494
1618
  const digest = needsDecisionDigest(parked);
1495
1619
  if (digest !== parkedDigest) {
@@ -1666,12 +1790,21 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1666
1790
  if (!getHeld) return;
1667
1791
  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
1792
  let due = []; try { due = expireHolds() ?? []; } catch { due = []; }
1793
+ if (due.length > 1) holdRamp = { at: now() };
1794
+ 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
1795
  for (const e of due) {
1670
1796
  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
1797
  update({ issue: null, outcome: "hold-expired", detail: `#${e.issue} (${e.owner}, since ${e.since})` });
1672
1798
  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
1799
  }
1674
1800
  }
1801
+ if (expireHolds) { // #5988: one alert per hold at T-30 min
1802
+ let info = null; try { info = getHoldInfo?.() ?? null; } catch { info = null; }
1803
+ for (const w of holdExpiryWarnings(info, { now: now(), warned: holdWarned })) {
1804
+ holdWarned.add(w.key);
1805
+ 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` });
1806
+ }
1807
+ }
1675
1808
  let got = [];
1676
1809
  try { got = getHeld() ?? []; } catch { got = opHeld.size ? [...opHeld] : []; }
1677
1810
  const next = new Set((Array.isArray(got) ? got : []).filter((n) => Number.isSafeInteger(n) && n > 0));
@@ -1787,8 +1920,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1787
1920
  let l = ledgers.get(n) ?? null;
1788
1921
  if (!l) { l = (await attempts.load?.(n)) ?? null; if (l) ledgers.set(n, l); }
1789
1922
  if (!l) return true;
1790
- const hash = (await attempts.hash?.(n)) ?? null, a = admitInput(l, hash, attempts.cfg);
1791
- if (a.ok) return true;
1923
+ const hash = (await attempts.hash?.(n)) ?? null, a = admitInput(l, hash, attempts.cfg, { engineVersion: curVersion(), placement: placeOf(n)?.where ?? null, env: curEnvValues() });
1924
+ if (a.ok) { if (a.reason) update({ issue: n, event: "readmit.signature_changed", detail: `readmitted: ${a.reason}`, batch: batchId ?? null }); return true; }
1792
1925
  const key = `${n}|${hash}|${a.code}`;
1793
1926
  if (!refusedNoted.has(key)) {
1794
1927
  refusedNoted.add(key);
@@ -1841,7 +1974,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1841
1974
  }
1842
1975
  let why = null;
1843
1976
  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}`;
1977
+ // 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
1978
+ // the lane needs, the hold stays; an agent upgrade (not the orchestrator's) is the trigger.
1979
+ const av = r.placement?.where === "remote" ? await agentVersionOf() : null;
1980
+ if (av) {
1981
+ const needMM = vmm2(v), ranV = String(h.sig ?? "").startsWith(`${OUTCOME_CODES.ENV_ENGINE_SKEW}|`) ? h.sig.split("|")[1] : null;
1982
+ if (ranV) { if (vmm2(av) === needMM && vmm2(av) !== vmm2(ranV)) why = `agent engine upgraded v${ranV} → v${av}`; }
1983
+ else if (needMM && vmm2(av) === needMM && v && h.version && v !== h.version) why = `engine version changed v${h.version} → v${v}`;
1984
+ } else if (!why && v && h.version && v !== h.version) why = `engine version changed v${h.version} → v${v}`;
1845
1985
  if (why) { /* env issue closed */ } else if (fp && h.env && fp !== h.env) why = "batch env changed (--set-env)";
1846
1986
  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
1987
  if (why) { if (!(await gateAdmit(n))) continue; engineSigs.delete(n); releaseHeld(n, true, `re-admitted: ${why}`); continue; }
@@ -1860,8 +2000,19 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1860
2000
  if (ro === undefined || running.has(root) || settled.has(root)) continue;
1861
2001
  if (restoredHeld.has(root) && ["needs-human", "budget-exceeded"].includes(ro) && typeof issueLabels === "function") { // label removed: requeue the root, its subtree follows
1862
2002
  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; }
2003
+ try { names = await issueLabels(root, { fresh: true }); } catch { names = null; } // #5893: never the memoized read
2004
+ if (Array.isArray(names) && !names.includes("needs-human")) {
2005
+ let sig = null;
2006
+ if (typeof heldFacts === "function") { // the removal must post-date the block; unreadable evidence fails closed
2007
+ let f = null; try { f = (await heldFacts(root)) ?? null; } catch { f = null; }
2008
+ if (!f || !Number.isFinite(f.removedAt) || !Number.isFinite(f.blockedAt) || f.removedAt <= f.blockedAt) continue;
2009
+ const prev = heldSigs.get(root);
2010
+ sig = { sig: `${ro}:${f.askKey ?? ""}`, removedAt: f.removedAt };
2011
+ if (prev && prev.sig === sig.sig && f.removedAt <= prev.removedAt) continue; // identical block, no new removal event
2012
+ }
2013
+ if (await gateAdmit(root, { relabel: true })) { if (sig) heldSigs.set(root, sig); releaseHeld(root, true, "needs-human label removed"); }
2014
+ continue;
2015
+ }
1865
2016
  }
1866
2017
  if (!dispatchCheck) continue;
1867
2018
  let g = null;
@@ -1920,12 +2071,12 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1920
2071
  }
1921
2072
  if (back.size) save();
1922
2073
  };
1923
- const ceilingK = () => { let k = null; try { k = getParallel?.(); } catch { k = null; } return Number.isInteger(k) && k >= 1 ? k : parallel; };
1924
2074
  // #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
2075
  // #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
2076
  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
2077
  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"); };
2078
+ // #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.
2079
+ 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
2080
  // #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
2081
  // needs-human row through the normal settle path, so in-batch recovery requeues a fix lane.
1931
2082
  let lastTrainTick = -Infinity;
@@ -2002,6 +2153,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2002
2153
  baseHit.clear();
2003
2154
  refreshHeld();
2004
2155
  refreshPause();
2156
+ await authPass(); // #5988
2005
2157
  await refreshBlocked();
2006
2158
  await refreshBaseWaits();
2007
2159
  checkGates();
@@ -2143,8 +2295,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2143
2295
  // #4685: a breaker tripped only by link failures (a router restart) closes itself after a cooldown
2144
2296
  if (tripped?.transport && now() - tripped.at >= TRANSPORT_COOLDOWN_MS) { tripped = null; errorTimes = []; transportErrors = 0; save(); }
2145
2297
  // #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; }
2298
+ if (tripped && !tripped.transport) { // #6042: every batch, not only a standing order
2299
+ let healthy = true; try { healthy = reconcile?.poolHealthy ? reconcile.poolHealthy() !== false : true; } catch { healthy = true; }
2148
2300
  const d = decideAutoReset({ tripped, now: now(), cooldownMs: BREAKER_COOLDOWN_MS, environmental: tripped.environmental === true, poolHealthy: healthy });
2149
2301
  if (d.reset) {
2150
2302
  tripped = null; errorTimes = []; transportErrors = 0; save();
@@ -2165,6 +2317,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2165
2317
  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
2318
  }
2167
2319
  }
2320
+ // #6042: a breaker pauses admission; it ends the run only when nothing can clear it (a non-environmental trip with no hosted clear channel)
2321
+ const breakerClearable = Boolean(tripped && pending.length && !cancelled && !budgetStop && !signal?.aborted && (tripped.environmental || tripped.transport || getClearBreaker));
2322
+ if (tripped && !running.size && breakerClearable) { await nap(pollMs); continue; }
2168
2323
  if (tripped && !running.size) { await drainAdds(); break; } // breaker: let running lanes finish, keep the rest pending for a resume
2169
2324
  if (cancelled && !running.size) { await drainAdds(); break; } // #4376: cancel: the rest end held for a resume
2170
2325
  if (budgetStop && !running.size) { await drainAdds(); break; } // execution budget (stop): the same, the rest end held
@@ -2202,7 +2357,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2202
2357
  if (running.size && envWaiting()) wake = Math.min(wake ?? ehWatchMs, ehWatchMs); // #5805: re-check engine/env holds while lanes run
2203
2358
  if (train?.size()) wake = Math.min(wake ?? trainEveryMs, Math.max(0, trainEveryMs - (now() - lastTrainTick))); // #5836
2204
2359
  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;
2360
+ if (tripped) wake = getClearBreaker || tripped.environmental || tripped.transport ? Math.min(wake ?? pollMs, pollMs) : null;
2206
2361
  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
2362
  if (running.size) {
2208
2363
  if (wake === null) await race(running.values());
@@ -94,7 +94,7 @@ describe("post-deploy named checks (#4626)", () => {
94
94
  assert.equal(r.state, "recorded-fail"); assert.deepEqual(w.spawned, []);
95
95
  });
96
96
 
97
- it("contract: post-deploy needs a check id; amendment too; precheck rejects an unknown id; followup item names it", () => {
97
+ it("contract: post-deploy needs a check id; amendment too; followup item names it", () => {
98
98
  const Q = "The deploy-time health row must exist after promotion.";
99
99
  const c = { requirements: [{ id: "R1", quote: Q, disposition: "post-deploy", why: "w" }], deliverables: [], preserve: [], validate: [{ id: "V1", command: "true" }] };
100
100
  assert.ok(validateContract(c, Q).problems.some((p) => /needs a check id/.test(p)));
@@ -105,8 +105,6 @@ describe("post-deploy named checks (#4626)", () => {
105
105
  assert.equal(deferred.contract.requirements[0].disposition, "defer");
106
106
  const ok = applyAmendments(frozen, [{ kind: "post-deploy", requirement: "R1", why: "w", check: "smoke" }], Q);
107
107
  assert.equal(ok.contract.requirements[0].check, "smoke");
108
- const pc = precheck({ contract: { ...c, requirements: [{ ...c.requirements[0], check: "ghost" }] }, result: { requirements: [] }, changedFiles: [], checkIds: new Set(["smoke"]) });
109
- assert.ok(pc.failures.some((f) => f.kind === "check_unknown"));
110
108
  assert.match(followupItems([{ ...c.requirements[0], check: "smoke" }])[0].why, /^post-deploy: \[check:smoke\] w/);
111
109
  });
112
110
  });
@@ -234,6 +234,26 @@ export function quietFailure(output, { lines = QUIET_TAIL_LINES, maxChars = Infi
234
234
  return out.join("\n");
235
235
  }
236
236
 
237
+ /** #6107: masks credential-looking text before a check's output reaches a needs-human comment or the run log. Generic patterns only. */
238
+ export function redactSecrets(text) {
239
+ return String(text ?? "")
240
+ .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, "[redacted private key]")
241
+ .replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "[redacted]")
242
+ .replace(/\b(?:ghp|gho|ghu|ghs|ghr|github_pat|glpat|xox[abprs]|npm|AKIA|ASIA)[_-]?[A-Za-z0-9_-]{12,}/g, "[redacted]")
243
+ .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/=-]{8,}/gi, "$1 [redacted]")
244
+ .replace(/\b([A-Za-z0-9_.-]*(?:token|secret|password|passwd|api[_-]?key|private[_-]?key|credential|authorization)[A-Za-z0-9_.-]*)(["']?\s*[:=]\s*["']?)[^\s"',}]{4,}/gi, "$1$2[redacted]")
245
+ .replace(/\b([a-z][a-z0-9+.-]*:\/\/[^\s:@\/]+:)[^\s@\/]+@/gi, "$1[redacted]@");
246
+ }
247
+
248
+ /**
249
+ * #6107: one failed check as park/run-log text: its name (a CI job name, else the command) and the last `lines` lines of
250
+ * its output, secrets redacted, within `maxChars`.
251
+ */
252
+ export function checkFailureTail(f, { name = null, lines = QUIET_TAIL_LINES, maxChars = 4000 } = {}) {
253
+ const label = name ? `${name} (\`${f.command}\`)` : `\`${f.command}\``;
254
+ return `\n\nFailing check ${label}, exit ${f.rc}, last ${lines} lines of its output:\n${redactSecrets(quietFailure(f.output, { lines, maxChars }))}`;
255
+ }
256
+
237
257
  /** #4364: the compact pass/fail table `forgedock check` prints; #4390: each failure quiet (`quietFailure`), within `cap` chars. */
238
258
  export function formatCheckTable(r, cap = LOG_CAP) {
239
259
  const word = (x) => (x.status === "ci" ? "CI" : x.status ? "DEFERRED" : x.rc === 0 ? "PASS" : `FAIL exit ${x.rc}`);