forgedock 1.62.0 → 1.64.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 (87) hide show
  1. package/bin/config-schema.mjs +5 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +109 -21
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +9 -1
  10. package/bin/lean/batch.test.mjs +74 -7
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/conformance.e2e.test.mjs +32 -6
  14. package/bin/lean/conformance.mjs +57 -13
  15. package/bin/lean/conformance.test.mjs +93 -1
  16. package/bin/lean/execution.mjs +24 -12
  17. package/bin/lean/execution.test.mjs +59 -9
  18. package/bin/lean/forgedock-lane-workflow.test.mjs +62 -2
  19. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  20. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  21. package/bin/lean/issuewatch.mjs +3 -0
  22. package/bin/lean/lanecheck.test.mjs +13 -1
  23. package/bin/lean/lean.mjs +214 -32
  24. package/bin/lean/lean.test.mjs +406 -21
  25. package/bin/lean/live-execution.mjs +25 -0
  26. package/bin/lean/live-execution.test.mjs +35 -1
  27. package/bin/lean/merged-park.mjs +76 -0
  28. package/bin/lean/merged-park.test.mjs +64 -0
  29. package/bin/lean/mergetrain.mjs +357 -0
  30. package/bin/lean/mergetrain.test.mjs +348 -0
  31. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  32. package/bin/lean/orchestrate-stacking.test.mjs +144 -0
  33. package/bin/lean/orchestrate-train.test.mjs +130 -0
  34. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  35. package/bin/lean/orchestrate.mjs +234 -17
  36. package/bin/lean/prompts.mjs +4 -3
  37. package/bin/lean/release-review.mjs +8 -1
  38. package/bin/lean/release-review.test.mjs +42 -2
  39. package/bin/lean/release-status.test.mjs +53 -1
  40. package/bin/lean/release.mjs +6 -3
  41. package/bin/lean/render.mjs +6 -1
  42. package/bin/lean/run-issue-placement.test.mjs +27 -3
  43. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  44. package/bin/lean/sandbox-remote.mjs +12 -2
  45. package/bin/lean/sched.mjs +19 -2
  46. package/bin/lean/sched.test.mjs +33 -1
  47. package/bin/lean/schedd-health.mjs +2 -1
  48. package/bin/lean/schedd-health.test.mjs +7 -0
  49. package/bin/lean/schedd.mjs +55 -7
  50. package/bin/lean/schedd.test.mjs +42 -1
  51. package/bin/lean/stacking.mjs +140 -0
  52. package/bin/lean/stacking.test.mjs +98 -0
  53. package/bin/lean/statuscomment.mjs +14 -8
  54. package/bin/lean/statuscomment.test.mjs +18 -1
  55. package/bin/lean/validate-catalog.mjs +1 -1
  56. package/bin/lean/validate-catalog.test.mjs +3 -0
  57. package/bin/lean/worktree.mjs +8 -3
  58. package/bin/lean/worktree.test.mjs +18 -0
  59. package/bin/pool/agent.mjs +325 -46
  60. package/bin/pool/cache-sweep.mjs +2 -0
  61. package/bin/pool/cli.mjs +120 -6
  62. package/bin/pool/disk.mjs +43 -0
  63. package/bin/pool/docker.mjs +21 -5
  64. package/bin/pool/health.mjs +95 -0
  65. package/bin/pool/router.mjs +274 -27
  66. package/bin/runner.mjs +3 -1
  67. package/bin/stats/chains.mjs +101 -0
  68. package/bin/stats/chains.test.mjs +53 -0
  69. package/bin/stats/efficiency.mjs +7 -6
  70. package/bin/stats/efficiency.test.mjs +48 -7
  71. package/bin/stats/index.mjs +11 -3
  72. package/bin/stats/stats.test.mjs +9 -0
  73. package/docs/CONFIG.md +23 -1
  74. package/docs/OUTCOME-CODES.md +4 -0
  75. package/package.json +1 -1
  76. package/pool/README.md +10 -0
  77. package/pool/image/Dockerfile +2 -1
  78. package/pool/image/entrypoint.sh +6 -6
  79. package/pool/image/mirror.sh +71 -0
  80. package/pool/install/install-agent-linux.sh +57 -5
  81. package/pool/install/install-agent-macos.sh +148 -0
  82. package/pool/install/install-agent.ps1 +11 -0
  83. package/pool/install/install-agent.sh +59 -7
  84. package/pool/install/uninstall-agent-linux.sh +75 -0
  85. package/pool/install/uninstall-agent-macos.sh +60 -0
  86. package/pool/install/uninstall-agent.ps1 +1 -0
  87. package/scripts/transition-label.sh +11 -0
@@ -137,11 +137,15 @@ import { mapLimit } from "./pmap.mjs";
137
137
  import { quotaRequeue } from "./rotator.mjs";
138
138
  import { joinsDecomposed, addsEpicChildren, selectChildren, edgeText, DEFAULT_POLL_S } from "./autochildren.mjs";
139
139
  import { formatOverload } from "./hostload.mjs";
140
+ import { normalizeStacking, planAdmissible, stackAdmissible } from "./stacking.mjs";
140
141
  import { lackedTools } from "./toolplace.mjs";
141
142
  import { openPrerequisites } from "./prereq.mjs";
142
143
 
143
144
  // A dependency that finished like this no longer blocks its dependents.
144
145
  const SATISFIED = new Set(["merged", "invalid"]);
146
+ const DEFAULT_TRAIN_EVERY_MS = 30000; // #5836: merge-train poll period
147
+ // #5836: a lane that ended pr-ready is waiting on the merge train, not failed: its dependents wait
148
+ const WAITING_ON_TRAIN = (row) => row?.outcome === "pr-ready";
145
149
  // #5162: a dependent of a root that ended like this is held (resumable), not skipped. #5805: also behind a root held on an engine/env change.
146
150
  const HOLD_ROOT = new Set(["needs-human", "engine-error", "deferred", "budget-exceeded", "held"]);
147
151
  /** #5162: members of a real dependency cycle (a nontrivial SCC or a self-loop) among `nodes`; `edgesOf(n)` lists n's dependencies. */
@@ -170,11 +174,15 @@ export const MAX_REQUEUES = 2;
170
174
  export const DEFAULT_MAX_DEFERRALS = 3;
171
175
  // Relaunches of an issue whose lane ended engine-error.
172
176
  export const ENGINE_ERROR_RELAUNCHES = 1;
177
+ // #5859: lanes of one pool agent lost without a result within the window that make it an agent restart (`sandbox.lost`), and their requeue delay
178
+ export const AGENT_LOST_MIN = 3;
179
+ export const AGENT_LOST_WINDOW_MS = 60000;
180
+ export const AGENT_LOST_REQUEUE_MS = 60000;
173
181
  export const HOST_BUSY_RETRY_S = 60;
174
182
  // #4528: a busy host or a full sandbox pool is a wait, not a failure: requeued after its retry-in, never capped.
175
183
  // A lane that could not be resolved because gh/git failed (network blip) is the same kind of wait (#4791).
176
184
  // #4788: an unreachable pool is a wait too (the lane already retried for unreachable_window_min); a stall is reported by poolStall.
177
- const UNCAPPED_DEFERRALS = new Set(["host.busy", "sandbox.capacity", "sandbox.unreachable", "lane.unresolved"]);
185
+ const UNCAPPED_DEFERRALS = new Set(["host.busy", "sandbox.capacity", "sandbox.unreachable", "sandbox.repo_missing", "lane.unresolved"]);
178
186
  export const POOL_OFFLINE_ALERT_MIN = 10;
179
187
  // #5112: `sandbox.capacity` deferrals of one issue after which `execution.fallback_local` runs it on the host (headroom permitting).
180
188
  export const CAPACITY_FALLBACK_AFTER = 3;
@@ -182,7 +190,9 @@ export const RATE_LIMIT_FALLBACK_S = 15 * 60;
182
190
  export const DEFER_BACKOFF_S = 120;
183
191
  export const DEFER_BACKOFF_MAX_S = 30 * 60;
184
192
  // #4685 + #5161: an engine-error detail that names a link or gateway failure (curl's "returned error: 502", HTTP/1.1 503, ...).
185
- export const TRANSPORT_TEXT = /fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|socket hang up|HTTP 50[234]|returned error: 5\d\d|HTTP\/\d(\.\d)? 5\d\d|Bad Gateway|Service Unavailable|overloaded/i;
193
+ // #5947: git transport failures (a dropped clone/fetch, a half-built mirror): a `net.transient` deferral, never an engine-error.
194
+ export const GIT_TRANSPORT_TEXT = /curl (56|28)\b|early EOF|RPC failed|invalid index-pack output|unexpected disconnect|is not a local repository/i;
195
+ export const TRANSPORT_TEXT = new RegExp(`fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|socket hang up|HTTP 50[234]|returned error: 5\\d\\d|HTTP\\/\\d(\\.\\d)? 5\\d\\d|Bad Gateway|Service Unavailable|overloaded|${GIT_TRANSPORT_TEXT.source}`, "i");
186
196
  /** #5161: a transient engine failure (model gateway 5xx, connection reset): retried with backoff, not the single relaunch. */
187
197
  export const isTransientEngineError = (detail) => TRANSPORT_TEXT.test(String(detail ?? ""));
188
198
  // #5161: transient engine-error retries per issue (forge.yaml `orchestration.transient_retries`) and their backoff: 30s, 2m, 8m, then 15m.
@@ -325,12 +335,14 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
325
335
  * @returns {Promise<Array<{issue:number, outcome:string, pr:?number, cost_usd:number, minutes:number, detail?:string}>>}
326
336
  */
327
337
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
328
- store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000,
338
+ store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000, getClearBreaker = null, ackClearBreaker = null,
329
339
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
330
340
  recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
331
341
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
332
- getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null, envHold = null, envIssue = null, logicalDeps = null }) {
342
+ 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,
343
+ train = null, trainEveryMs = DEFAULT_TRAIN_EVERY_MS }) {
333
344
  const saved = store?.load?.() ?? null;
345
+ if (train && saved?.train) train.restore(saved.train); // #5836: the merge train resumes with the batch
334
346
  const order = saved ? [...saved.order] : [];
335
347
  const set = new Set(order);
336
348
  const deps = toMap(saved?.deps); // issue -> declared dependencies (any issue); only those in `set` are edges
@@ -343,6 +355,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
343
355
  const notBefore = toMap(saved?.notBefore);
344
356
  const requeues = toMap(saved?.requeues);
345
357
  const deferrals = toMap(saved?.deferrals);
358
+ const capReasons = toMap(saved?.capReasons); // #5938: issue -> the pool's last `sandbox.capacity` / host-disk reason (read by the batch health stall verdict)
346
359
  const capDefers = toMap(saved?.capDeferrals); // #5112: issue -> `sandbox.capacity` deferrals (uncapped, so not in `deferrals`)
347
360
  const capFellBack = new Set(); // #5112: issues already reported as a capacity fallback (one decision each)
348
361
  const engineErrors = toMap(saved?.engineErrors);
@@ -368,6 +381,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
368
381
  const enqueued = toMap(saved?.enqueued); // #4409: issue -> when it last entered the queue (starvation guard)
369
382
  const heads = new Set(saved?.heads ?? []); // #4409: decomposed sub-issues not started yet: the head of their priority band
370
383
  let errorTimes = [...(saved?.errorTimes ?? [])];
384
+ // #5859: agent restarts of this batch (one record each, shown by `status --batch`) and the lanes already requeued as `sandbox.lost`
385
+ const agentRestarts = [...(saved?.agentRestarts ?? [])];
386
+ const lostOnce = new Set(saved?.lostRequeued ?? []); // a lane lost again after its requeue is an ordinary engine-error
371
387
  // A legacy batch-local `holdUntil` (pre-#4190) names no account and is ignored: a same-account lane re-sets the hold.
372
388
  const holds = limits ?? memoryLimits(now);
373
389
  // #5205: accounts lanes reported limited (account -> until ms), persisted with the batch, excluded from headroom until then.
@@ -457,6 +473,17 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
457
473
  const maxFor = (cls) => (cls === "mechanical" ? mechMax : recoveryMax);
458
474
  const classUsed = toMap(saved?.recoveryClasses); // `${issue}:${class}` -> recovery lanes launched in that class
459
475
  const recoveries = toMap(saved?.recoveries); // issue -> recovery lanes launched (#4267)
476
+ // #5831 stacked lanes: `planned` = issue -> {contractHash, baseSha} of its finished plan lane; `planTried` = issues that had their one plan lane
477
+ const stackOn = normalizeStacking(stacking) !== "off";
478
+ // #5832 phase 2 (`full`): `prReady` = running issue -> {pr, branch, sha} of its PR-ready lane head (FORGE:STATE via `readPrReady`);
479
+ // `stackedTried` = issues whose one stacked build was admitted; `stackedOf` = issue -> {dependency, branch, sha} of that build.
480
+ const stackFull = normalizeStacking(stacking) === "full" && typeof readPrReady === "function";
481
+ const prReady = new Map();
482
+ const stackedOf = toMap(saved?.stacked);
483
+ const stackedTried = new Set(saved?.stackedTried ?? []);
484
+ const planned = toMap(saved?.planned);
485
+ const planTried = new Set(saved?.planTried ?? []);
486
+ const firstAdmit = new Map(), planMs = new Map(); // #5834: issue -> first admission ms; issue -> plan lane run ms (chain metrics)
460
487
  const recovering = toMap(saved?.recovering); // issue -> {code, attempt, detail, outcome, ...} of the recovery lane queued or running
461
488
  const freeRecovered = new Set(); // #5727: issues whose one free (no-attempt) recovery for a recipe-less remote tool miss was spent
462
489
  const requeueApplied = new Set(saved?.requeueApplied ?? []); // #4550: `--requeue` entries already applied (batch `requeue` file)
@@ -472,12 +499,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
472
499
  const save = () => {
473
500
  if (!store || halted) return;
474
501
  store.save({ v: 1, ...(setup ? { phase: "setup", setup: { ...setup } } : {}), engineVersion: version, order, deps: toObj(deps), lanes: toObj(lanes), crossSeen: [...crossSeen], results: toObj(results), running: toObj(runRecs),
475
- pending, notBefore: toObj(notBefore), requeues: toObj(requeues), deferrals: toObj(deferrals), engineErrors: toObj(engineErrors), ...(transients.size ? { transientRetries: toObj(transients) } : {}), ...(quota.size ? { quota: toObj(quota) } : {}), ...(limitedAccounts.size ? { limitedAccounts: toObj(limitedAccounts) } : {}), ...(capDefers.size ? { capDeferrals: toObj(capDefers) } : {}),
476
- prefilter: toObj(checked), errorTimes, breaker: tripped, ...(budget ? { classes: toObj(classes), dispatch: { ...dispatch } } : {}),
502
+ pending, notBefore: toObj(notBefore), requeues: toObj(requeues), deferrals: toObj(deferrals), engineErrors: toObj(engineErrors), ...(transients.size ? { transientRetries: toObj(transients) } : {}), ...(quota.size ? { quota: toObj(quota) } : {}), ...(limitedAccounts.size ? { limitedAccounts: toObj(limitedAccounts) } : {}), ...(capDefers.size ? { capDeferrals: toObj(capDefers) } : {}), ...(capReasons.size ? { capReasons: toObj(capReasons) } : {}),
503
+ prefilter: toObj(checked), errorTimes, breaker: tripped, ...(agentRestarts.length ? { agentRestarts, lostRequeued: [...lostOnce] } : {}), ...(budget ? { classes: toObj(classes), dispatch: { ...dispatch } } : {}),
477
504
  ...(reg ? { priorities: toObj(priorities) } : {}), ...(sandboxUse.size ? { sandbox: toObj(sandboxUse) } : {}),
478
505
  ...(recoveries.size || recovering.size ? { recoveries: toObj(recoveries), recovering: toObj(recovering), recoveryClasses: toObj(classUsed) } : {}),
506
+ ...(planned.size || planTried.size ? { planned: toObj(planned), planTried: [...planTried] } : {}),
507
+ ...(stackedTried.size ? { stacked: toObj(stackedOf), stackedTried: [...stackedTried] } : {}),
479
508
  ...(requeueApplied.size ? { requeueApplied: [...requeueApplied], requeued: toObj(requeuedInfo) } : {}),
480
- ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}),
509
+ ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}), ...(train ? { train: train.snapshot() } : {}),
481
510
  ...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), ...(heads.size ? { heads: [...heads] } : {}),
482
511
  ...(engineSigs.size ? { engineSigs: toObj(engineSigs) } : {}), ...(deterministic.size ? { deterministicSigs: [...deterministic] } : {}), ...(toolReadmits.size ? { toolReadmits: [...toolReadmits] } : {}), ...(envSigs.size ? { envSigs: toObj(envSigs) } : {}) });
483
512
  };
@@ -817,6 +846,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
817
846
  };
818
847
  const requeue = (n, delayMs) => { pending.push(n); enqueued.set(n, now()); if (delayMs > 0) notBefore.set(n, now() + delayMs); else notBefore.delete(n); };
819
848
  const TRANSPORT_COOLDOWN_MS = 5 * 60000;
849
+ const netTransients = new Map(); // #5947: issue -> net.transient deferrals (backoff step)
820
850
  let transportErrors = 0; // #4685: engine-errors in the current window that were link failures
821
851
  const noteEngineError = (detail = "") => {
822
852
  if (!breaker) return;
@@ -827,20 +857,68 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
827
857
  tripped = { at: t, ...(transportErrors >= errorTimes.length ? { transport: true } : {}), detail: `circuit breaker: ${errorTimes.length} engine-errors within ${breaker.window_min} min; admissions stopped` };
828
858
  update({ issue: null, outcome: "breaker", detail: tripped.detail });
829
859
  }
860
+ return t;
861
+ };
862
+ // #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
863
+ // restart: `sandbox.lost`, requeued once (after `remote.agentHealthy(agent)` answers, when the provider has it), never counted by the
864
+ // breaker or the engine-error relaunch. Lanes of the burst that settled as engine-errors first are rolled back. One batch event each.
865
+ const lostSeen = new Map(); // agent -> [{n, at, err, ee, tr, sig}]: lost lanes settled as ordinary engine-errors in the window
866
+ const openRestart = (agent, t) => agentRestarts.find((g) => g.agent === agent && !g.closed && t - g.last < AGENT_LOST_WINDOW_MS);
867
+ const markLost = (agent, n, row, why) => {
868
+ lostOnce.add(n);
869
+ let g = openRestart(agent, now());
870
+ if (!g) agentRestarts.push(g = { agent, at: new Date(now()).toISOString(), last: now(), lanes: [] });
871
+ if (!g.lanes.includes(n)) g.lanes.push(n);
872
+ g.last = now(); g.requeued = g.lanes.length;
873
+ update({ ...row, outcome: "deferred", code: OUTCOME_CODES.SANDBOX_LOST, detail: `requeued: ${OUTCOME_CODES.SANDBOX_LOST} (agent ${agent} restarted): ${why ?? ""}` });
874
+ };
875
+ const rollBackLost = (agent, x) => {
876
+ if (x.err !== undefined) { const i = errorTimes.lastIndexOf(x.err); if (i >= 0) errorTimes.splice(i, 1); transportErrors = Math.min(transportErrors, errorTimes.length); }
877
+ if (!pending.includes(x.n) && !running.has(x.n)) return; // it already ended (its relaunch was used before): only the breaker count goes
878
+ for (const [m, v] of [[engineErrors, x.ee], [transients, x.tr], [engineSigs, x.sig]]) { if (v === undefined) m.delete(x.n); else m.set(x.n, v); }
879
+ if (pending.includes(x.n)) notBefore.set(x.n, now() + AGENT_LOST_REQUEUE_MS);
880
+ markLost(agent, x.n, { issue: x.n }, "settled as an engine-error before the restart was visible; rolled back");
881
+ };
882
+ const closeRestart = (g) => {
883
+ g.closed = true; g.requeued = g.lanes.length; g.detail = `agent ${g.agent} restarted at ${g.at}; ${g.lanes.length} lanes requeued`;
884
+ const ev = { event: "agent.restarted", batch: batchId ?? null, agent: g.agent, at: g.at, requeued: g.lanes.length, issues: [...g.lanes], detail: g.detail };
885
+ try { store?.log?.(ev); } catch { /* best effort */ }
886
+ onUpdate(ev);
887
+ };
888
+ const agentLostPass = async (t) => {
889
+ let changed = false;
890
+ for (const g of agentRestarts) {
891
+ if (g.closed) continue;
892
+ if (!g.healthyAt) {
893
+ let ok = true;
894
+ if (typeof remote?.agentHealthy === "function") { try { ok = (await remote.agentHealthy(g.agent)) === true; } catch { ok = false; } }
895
+ if (ok) { g.healthyAt = new Date(t).toISOString(); changed = true; } else for (const m of g.lanes) if (pending.includes(m)) notBefore.set(m, Math.max(notBefore.get(m) ?? 0, t + pollMs));
896
+ }
897
+ if (g.healthyAt && t - g.last >= AGENT_LOST_WINDOW_MS) { closeRestart(g); changed = true; }
898
+ }
899
+ if (changed) save();
830
900
  };
831
901
 
832
902
  // Apply one lane's result: requeue it (deferred, dependency-open, engine-error) or record its final row.
833
903
  const settleLane = async (n, r, rec, pf) => {
834
904
  if (halted) return; // #4454: a resume adopts the lane and settles it
905
+ // #5947: a git transport failure ends the lane as a `net.transient` deferral with backoff; the breaker never sees it.
906
+ if (!cancelled && (r?.terminalReason ?? "engine-error") === "engine-error" && GIT_TRANSPORT_TEXT.test(String(r?.detail ?? ""))) {
907
+ const k = (netTransients.get(n) ?? 0) + 1;
908
+ netTransients.set(n, k);
909
+ r = { ...r, terminalReason: "deferred", code: OUTCOME_CODES.NET_TRANSIENT, retryInSeconds: Math.round(transientRetryDelayMs(k) / 1000), detail: r.detail };
910
+ }
835
911
  // #5241: the lane ended: its lease goes with it. #5654: also an interrupted or engine-error end, which is requeued at once
836
912
  if (releaseLease && (cancelled || (r?.terminalReason ?? "engine-error") === "engine-error" || (r?.terminalReason === "deferred" && r?.code === "run.interrupted"))) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } }
837
913
  // #4304: the pre-filter runs once per issue; a recovery pass's row adds the earlier attempt's cost, which already holds it.
838
914
  const pfCost = recovering.has(n) ? 0 : (pf?.cost_usd ?? 0);
839
- const row = { issue: n, outcome: r?.terminalReason ?? "engine-error", pr: r?.pr ?? null, cost_usd: (r?.cost_usd ?? 0) + pfCost, minutes: Math.round((now() - rec.startedAt) / 6000) / 10, detail: r?.detail, ...(r?.code ? { code: r.code } : {}), ...(pf ? { prefilter: pf } : {}),
915
+ const row = { issue: n, outcome: r?.terminalReason ?? "engine-error", pr: r?.pr ?? null, cost_usd: (r?.cost_usd ?? 0) + pfCost, minutes: Math.round((now() - rec.startedAt) / 6000) / 10, detail: r?.detail, ...(r?.code ? { code: r.code } : {}), ...(r?.culprit ? { culprit: r.culprit } : {}), ...(pf ? { prefilter: pf } : {}), ...(rec?.stackedOn ? { stacked: true, stackedOn: rec.stackedOn } : {}),
840
916
  ...(() => { const w = capWait.take(n, r?.waits); return w && typeof w === "object" ? { waits: w } : {}; })(), ...(Number.isInteger(r?.heavyQueueMax) ? { heavyQueueMax: r.heavyQueueMax } : {}),
841
917
  ...(Number.isFinite(r?.wall_ms) ? { wall_ms: r.wall_ms } : {}), ...(Number.isFinite(r?.model_ms) ? { model_ms: r.model_ms } : {}), // #4451
842
918
  ...(phasesOf(r, rec) ? { phases: phasesOf(r, rec) } : {}), // #4908
843
919
  ...(Array.isArray(r?.followups) && r.followups.length ? { followups: r.followups } : {}), // #5078
920
+ ...(r?.cascade ? { cascade: r.cascade, cascades: Array.isArray(r.cascades) ? r.cascades : [r.cascade], ...(Number.isFinite(r.cascade_cost_usd) ? { cascade_cost_usd: r.cascade_cost_usd } : {}), ...(Number.isFinite(r.cascade_minutes) ? { cascade_minutes: r.cascade_minutes } : {}) } : {}), // #5833
921
+ ...(edges(n).length ? { deps: edges(n) } : {}), ...(firstAdmit.has(n) ? { admitted_at: firstAdmit.get(n), ended_at: now() } : {}), ...(planMs.has(n) ? { plan_minutes: Math.round(planMs.get(n) / 6000) / 10 } : {}), // #5834
844
922
  ...(Number.isFinite(r?.precheckMs) ? { precheck_ms: r.precheckMs } : {}), ...(Number.isInteger(r?.precheckDeferred) && r.precheckDeferred > 0 ? { precheck_deferred: r.precheckDeferred } : {}), // #4331
845
923
  ...(typeof r?.firstPass === "boolean" ? { first_pass: r.firstPass } : {}), // #4362
846
924
  ...(r?.turns && typeof r.turns === "object" ? { turns: r.turns } : {}), // #4392
@@ -867,6 +945,26 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
867
945
  }
868
946
  if (sandboxUse.has(n)) row.sandbox = { ...sandboxUse.get(n), ...(sandboxUse.get(n).by_agent ? { by_agent: { ...sandboxUse.get(n).by_agent } } : {}) };
869
947
  const done = () => { running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); };
948
+ if (train && row.outcome === "pr-ready" && Number.isInteger(r?.pr) && r?.head) { // #5836: the slot frees now; the train merges the PR
949
+ const p = recovering.get(n);
950
+ if (p) { recovering.delete(n); row.cost_usd = Math.round(((Number(row.cost_usd) || 0) + (Number(p.cost_usd) || 0)) * 1e6) / 1e6; row.minutes = Math.round(((Number(row.minutes) || 0) + (Number(p.minutes) || 0)) * 10) / 10; }
951
+ train.add({ issue: n, pr: r.pr, head: r.head, required: Array.isArray(r.required) ? r.required : [], policy: r.policy, lane: r.lane ?? rec?.lane ?? null, milestone: r.milestone, postMerge: r.postMerge, laneSide: r.laneSide });
952
+ results.set(n, row); done(); save(); update(row);
953
+ return;
954
+ }
955
+ if (rec?.plan) {
956
+ // #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
957
+ // never counts toward the breaker, the engine-error relaunch, the deferral or the requeue budgets (it returns before them).
958
+ done();
959
+ planMs.set(n, (planMs.get(n) ?? 0) + Math.max(0, now() - rec.startedAt)); // #5834
960
+ const ok = r?.terminalReason === "planned" && r?.planned?.contractHash && r?.planned?.baseSha;
961
+ if (ok) planned.set(n, { contractHash: r.planned.contractHash, baseSha: r.planned.baseSha });
962
+ store?.log?.({ event: ok ? "STACK_PLANNED" : "STACK_PLAN_FAILED", issue: n, ...(ok ? { contractHash: r.planned.contractHash, baseSha: r.planned.baseSha } : { reason: row.outcome }) });
963
+ requeue(n, 0); save();
964
+ if (!ok) decided({ issue: n, what: `plan lane for #${n} ended ${row.outcome}; it will run as a normal build lane after its dependencies`, why: firstLine(row.detail) || row.outcome, alternative: "retry the plan lane" });
965
+ update({ ...row, outcome: ok ? "planned" : "plan-failed", ...(ok ? { detail: `contract ${r.planned.contractHash} frozen at ${String(r.planned.baseSha).slice(0, 12)}` } : {}) });
966
+ return;
967
+ }
870
968
  // #5805: an engine/env-caused end that would repeat as-is: held with its signature, re-admitted by watchEnvHolds, never terminal.
871
969
  const holdEnv = ({ kind, sig, tools = null, why, envIssueNo = null }) => {
872
970
  const p = recovering.get(n);
@@ -927,12 +1025,25 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
927
1025
  update({ ...row, detail: `stopped by cancel: ${r?.code ?? row.outcome}${r?.detail ? ` ${r.detail}` : ""}` });
928
1026
  return;
929
1027
  }
1028
+ if (row.outcome === "deferred" && (r?.code === "stack.replan" || r?.code === "stack.restart") && !cancelled) {
1029
+ // #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
1030
+ // rules decide while its dependency is unsatisfied); restart: it may stack again on the dependency's new head, from the frozen contract.
1031
+ const so = stackedOf.get(n);
1032
+ stackedOf.delete(n); planned.delete(n);
1033
+ if (r.code === "stack.restart") { stackedTried.delete(n); if (so) prReady.delete(so.dependency); }
1034
+ requeue(n, 0); done(); save();
1035
+ store?.log?.({ event: "STACK_CASCADE", issue: n, cascade: r.cascade, ...(so ? { dependency: so.dependency } : {}) });
1036
+ decided({ issue: n, what: `stacked cascade ${r.cascade} for #${n}`, why: firstLine(row.detail) || "the stacked dependency moved or ended", alternative: "keep the stacked PR" });
1037
+ update({ ...row, detail: `requeued after cascade ${r.cascade}: ${firstLine(row.detail)}` });
1038
+ return;
1039
+ }
930
1040
  if (row.outcome === "deferred") {
931
1041
  const pol = deferPolicy(r, { now: now(), deferrals: deferrals.get(n) ?? 0, maxDeferrals });
932
1042
  let capGated = false; // #4909: the pool reports free slots, so the slot (not the retry-in timer) gates the relaunch
933
1043
  if (r?.code === "sandbox.unreachable") notePool(true, r.detail ?? "sandbox unreachable");
934
1044
  if (r?.code === "sandbox.capacity") {
935
1045
  capWait.refused(n);
1046
+ if (r.detail) capReasons.set(n, String(r.detail).slice(0, 300));
936
1047
  capDefers.set(n, (capDefers.get(n) ?? 0) + 1); // #5112: counted for the fallback_local capacity fallback
937
1048
  try { capGated = Number.isInteger(remote?.capacity?.()?.free); } catch { capGated = false; }
938
1049
  }
@@ -978,8 +1089,27 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
978
1089
  }
979
1090
  row.detail = `gave up after ${deferrals.get(n) ?? 0} deferrals: ${r?.detail ?? r?.code ?? ""}`;
980
1091
  }
1092
+ const la = row.outcome === "engine-error" && r?.lostWithoutResult && !cancelled && !lostOnce.has(n) ? (r.agent ?? r.sandbox?.agent ?? null) : null;
1093
+ let lostNow = null;
1094
+ if (la) { // #5859
1095
+ const t = now(), win = (lostSeen.get(la) ?? []).filter((x) => t - x.at < AGENT_LOST_WINDOW_MS);
1096
+ if (openRestart(la, t) || win.length + 1 >= AGENT_LOST_MIN) {
1097
+ lostSeen.delete(la);
1098
+ for (const x of win) rollBackLost(la, x);
1099
+ if (tripped && !tripped.transport && breaker && errorTimes.length < breaker.errors && win.length && tripped.at >= win[0].at) {
1100
+ tripped = null;
1101
+ update({ issue: null, outcome: "breaker", detail: `circuit breaker cleared: the engine-errors were agent ${la} restarting (${OUTCOME_CODES.SANDBOX_LOST})` });
1102
+ }
1103
+ markLost(la, n, row, row.detail);
1104
+ requeue(n, AGENT_LOST_REQUEUE_MS); done(); save();
1105
+ return;
1106
+ }
1107
+ lostNow = { n, at: t, ee: engineErrors.get(n), tr: transients.get(n), sig: engineSigs.get(n) };
1108
+ lostSeen.set(la, [...win, lostNow]);
1109
+ }
981
1110
  if (row.outcome === "engine-error") {
982
- noteEngineError(r?.detail);
1111
+ const errAt = noteEngineError(r?.detail);
1112
+ if (lostNow) lostNow.err = errAt;
983
1113
  // #5161: a transient failure (gateway 5xx, reset) waits out the outage with backoff instead of the single immediate relaunch.
984
1114
  if (transientMax > 0 && isTransientEngineError(row.detail)) {
985
1115
  const k = (transients.get(n) ?? 0) + 1;
@@ -1152,7 +1282,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1152
1282
  const k = laneRetries.get(n) ?? 0; laneRetries.set(n, k + 1);
1153
1283
  return { terminalReason: "deferred", code: "lane.unresolved", retryInSeconds: Math.min(DEFER_BACKOFF_S * 2 ** k, DEFER_BACKOFF_MAX_S), cost_usd: 0, detail: l.detail };
1154
1284
  })().then((x) => settle(n, x, rec, null)));
1155
- const start = (n) => {
1285
+ const start = (n, { plan = false, stackedOn = null } = {}) => {
1156
1286
  const ln = lanes.get(n);
1157
1287
  if (ln && !ln.ok && ln.transient && resolveLane) { retryLane(n, runRecs.get(n) ?? { startedAt: now() }); return; }
1158
1288
  if (ln && !ln.ok) { // settled synchronously: nothing runs, no lease, no comment
@@ -1166,8 +1296,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1166
1296
  placed.delete(n);
1167
1297
  const queueMs = Number.isFinite(enqueued.get(n)) ? Math.max(0, now() - enqueued.get(n)) : null; // #4908: queue_wait in the phase ledger
1168
1298
  heads.delete(n); enqueued.delete(n); busyNoted.delete(n);
1169
- const rec = { startedAt: now(), ...(queueMs != null ? { queueMs } : {}), ...(lane ? { lane } : {}), ...(remoteRun.has(n) ? { remote: true } : {}), ...(pl ? { placement: pl } : {}) };
1170
- runRecs.set(n, rec); notBefore.delete(n); save();
1299
+ const rec = { startedAt: now(), ...(plan ? { plan: true } : {}), ...(stackedOn ? { stackedOn } : {}), ...(queueMs != null ? { queueMs } : {}), ...(lane ? { lane } : {}), ...(remoteRun.has(n) ? { remote: true } : {}), ...(pl ? { placement: pl } : {}) };
1300
+ if (!firstAdmit.has(n)) firstAdmit.set(n, rec.startedAt); // #5834: chain wall time starts at the first admission, plan lane included
1301
+ runRecs.set(n, rec); notBefore.delete(n); capReasons.delete(n); save();
1171
1302
  track(n, (async () => {
1172
1303
  // Pre-filter once per issue (a requeued issue is not re-checked); fail-open: an error means a normal lane.
1173
1304
  if (prefilter && !checked.has(n)) { let pf = null; try { pf = await prefilter(n, lane); } catch { pf = null; } checked.set(n, pf); save(); }
@@ -1189,7 +1320,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1189
1320
  else if (pf?.parked) r = { terminalReason: pf.kind, cost_usd: 0, detail: `pre-filter: ${pf.detail}` };
1190
1321
  else {
1191
1322
  try {
1192
- r = await runOne(n, lane, { ...(signal ? { signal } : {}), remote: !!rec.remote, ...(rec.placement ? { placement: rec.placement } : {}), ...(recovering.has(n) ? { recover: { code: recovering.get(n).code, attempt: recovering.get(n).attempt, final: recovering.get(n).attempt >= (recovering.get(n).max ?? recoveryMax) } } : {}), onStart: (info) => {
1323
+ r = await runOne(n, lane, { ...(signal ? { signal } : {}), remote: !!rec.remote, ...(rec.placement ? { placement: rec.placement } : {}), ...(plan ? { plan: true } : planned.has(n) ? { planned: planned.get(n) } : {}), ...(rec.stackedOn ? { stackedOn: rec.stackedOn } : {}), ...(recovering.has(n) ? { recover: { code: recovering.get(n).code, attempt: recovering.get(n).attempt, final: recovering.get(n).attempt >= (recovering.get(n).max ?? recoveryMax) } } : {}), onStart: (info) => {
1193
1324
  Object.assign(rec, info ?? {}); save();
1194
1325
  if (rec.remote && remoteRun.has(n)) noteRemote(n, rec.handle);
1195
1326
  if (cancelled) stop(n, rec); // #4376: launched while the cancel arrived
@@ -1362,6 +1493,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1362
1493
  continue;
1363
1494
  }
1364
1495
  if (!row || !REQUEUABLE(row.outcome) || running.has(e.issue)) continue;
1496
+ train?.drop(e.issue); // #5836: a requeued pr-ready row leaves the train
1365
1497
  const moved = [e.issue], priors = new Map([[e.issue, row]]);
1366
1498
  results.delete(e.issue);
1367
1499
  for (let i = 0; i < moved.length; i++) { // dependents skipped behind a requeued issue (fixpoint)
@@ -1656,6 +1788,38 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1656
1788
  if (back.size) save();
1657
1789
  };
1658
1790
  const K = () => { let k = null; try { k = getParallel?.(); } catch { k = null; } return Number.isInteger(k) && k >= 1 ? k : parallel; };
1791
+ // #5836: one train poll (throttled): a merged PR becomes a merged row; a red, conflicting or moved-head PR is handed back as a
1792
+ // needs-human row through the normal settle path, so in-batch recovery requeues a fix lane.
1793
+ let lastTrainTick = -Infinity;
1794
+ const runTrain = async () => {
1795
+ if (!train?.size() || signal?.aborted || now() - lastTrainTick < trainEveryMs) return;
1796
+ lastTrainTick = now();
1797
+ let evs = [];
1798
+ try { evs = await train.tick(); } catch { evs = []; }
1799
+ for (const e of evs) {
1800
+ const n = e.issue, prev = results.get(n) ?? { issue: n };
1801
+ if (e.kind === "merged") {
1802
+ const { waiting, ...rest } = prev;
1803
+ const row = { ...rest, outcome: "merged", detail: e.detail };
1804
+ results.set(n, row);
1805
+ if (lifecycle && e.entry.milestone) lifecycleTitles.add(String(e.entry.milestone));
1806
+ if (integration?.onMerged && String(e.entry.lane ?? "").startsWith("milestone/")) {
1807
+ try { await integration.onMerged(n, { ...row, lane: e.entry.lane }, { milestone: e.entry.milestone }); } catch (err) { update({ issue: n, outcome: "integration", detail: `integration check failed: ${String(err?.message ?? err).slice(0, 300)}` }); }
1808
+ }
1809
+ save(); update(row);
1810
+ } else {
1811
+ results.delete(n);
1812
+ // #5838: a bisection culprit broke the merged tree of its batch, not its own head; the recovery note leads with that.
1813
+ const c = e.culprit, detail = c ? `Recovery note: PR #${c.pr} broke the merged tree of train batch ${c.batch} (required check ${c.check}${c.url ? ` ${c.url}` : ""}), not its own head; fix it against ${e.entry.lane ?? "the base"} with the PRs merged before it.\n${e.detail}` : e.detail;
1814
+ await settleLane(n, { terminalReason: "needs-human", code: e.code, detail, pr: e.pr, cost_usd: prev.cost_usd ?? 0, lane: e.entry.lane, ...(c ? { culprit: c } : {}) }, { startedAt: now() - Math.round((Number(prev.minutes) || 0) * 60000), lane: e.entry.lane }, null);
1815
+ if (results.get(n)?.outcome === "needs-human" && !everRelabelled.has(n) && typeof relabelNeedsHuman === "function") {
1816
+ everRelabelled.add(n);
1817
+ try { await relabelNeedsHuman({ issue: n, evidence: detail }); } catch { /* best effort */ }
1818
+ }
1819
+ }
1820
+ }
1821
+ save();
1822
+ };
1659
1823
  let firstPass = true; // #5805: a resume (e.g. after an upgrade) re-checks the engine/env holds at once
1660
1824
  try {
1661
1825
  for (;;) {
@@ -1663,10 +1827,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1663
1827
  await drainAdds();
1664
1828
  await drainRequeues();
1665
1829
  checkCancel();
1830
+ await runTrain();
1666
1831
  await watchBlockers(!pending.length && !running.size);
1667
1832
  await watchEnvHolds(firstPass || (!pending.length && !running.size)); // #5805
1668
1833
  firstPass = false;
1669
- if (!pending.length && !running.size) {
1834
+ if (!pending.length && !running.size && !train?.size()) {
1670
1835
  if (envWaiting() && !signal?.aborted) { await nap(ehWatchMs); continue; } // #5805: only engine/env holds remain: keep re-checking them
1671
1836
  break;
1672
1837
  }
@@ -1676,7 +1841,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1676
1841
  for (let i = pending.length - 1; i >= 0; i--) {
1677
1842
  const n = pending[i];
1678
1843
  if (results.has(n)) { pending.splice(i, 1); continue; }
1679
- const bad = edges(n).find((d) => results.has(d) && !SATISFIED.has(results.get(d).outcome));
1844
+ const bad = edges(n).find((d) => results.has(d) && !SATISFIED.has(results.get(d).outcome) && !WAITING_ON_TRAIN(results.get(d)));
1680
1845
  if (bad !== undefined) {
1681
1846
  pending.splice(i, 1); again = true;
1682
1847
  const br = results.get(bad), root = br.root ?? bad, ro = results.get(root)?.outcome ?? br.outcome;
@@ -1685,6 +1850,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1685
1850
  }
1686
1851
  }
1687
1852
  }
1853
+ if (agentRestarts.length) await agentLostPass(now()); // #5859
1688
1854
  const t = now();
1689
1855
  const holdUntil = heldUntil();
1690
1856
  let started = 0;
@@ -1709,13 +1875,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1709
1875
  if (pfNoted.size && !keys.size) update({ issue: null, outcome: "preflight", detail: "preflight cleared; admissions resumed" });
1710
1876
  pfNoted = keys;
1711
1877
  }
1878
+ let planPass = false; // #5831: the plan pass evaluates every other gate but the in-batch dependencies
1712
1879
  await gateEnvSigs(); // #5755
1713
1880
  const isReady = (n) => {
1714
1881
  if (pfAll || (pfRemote && isRemote(n))) return false;
1715
1882
  if (opHeld.has(n)) { opHeldHit.add(n); return false; }
1716
1883
  if (blocked.has(n)) { blockedHit.add(n); return false; } // #4773
1717
1884
  if (baseHeld.has(n)) { baseHit.add(n); return false; } // #5031
1718
- if (!((notBefore.get(n) ?? 0) <= t && edges(n).every((d) => results.has(d) && SATISFIED.has(results.get(d).outcome)))) return false;
1885
+ if (!((notBefore.get(n) ?? 0) <= t && (planPass || edges(n).every((d) => results.has(d) && SATISFIED.has(results.get(d).outcome))))) return false;
1719
1886
  if (integration?.holds) {
1720
1887
  let why = null;
1721
1888
  try { why = integration.holds(n, { lane: lanes.get(n)?.lane ?? null }); } catch { why = null; }
@@ -1767,9 +1934,56 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1767
1934
  if (grant(n, new Set()) === true) { pending.splice(pending.indexOf(n), 1); start(n); started++; }
1768
1935
  }
1769
1936
  }
1937
+ // #5832: stacked lanes (phase 2, `full`). A dependent whose one unmerged in-batch dependency is PR-ready (precheck green, review
1938
+ // passed) builds now on that lane head; its PR targets the dependency branch and the merge step holds it until the dependency merged.
1939
+ if (stackFull && !tripped && !cancelled && !holdUntil && !pfAll && running.size < K()) {
1940
+ const watch = new Set(pending.filter((n) => !stackedTried.has(n)).flatMap((n) => edges(n)).filter((d) => running.has(d) && !results.has(d)));
1941
+ for (const d of watch) {
1942
+ if (prReady.has(d)) continue;
1943
+ let rd = null;
1944
+ try { rd = await readPrReady(d); } catch { rd = null; }
1945
+ if (rd?.branch && rd?.sha) prReady.set(d, rd);
1946
+ }
1947
+ planPass = true;
1948
+ let sc = [];
1949
+ try { sc = rank(pending.filter((n) => stackAdmissible({ n, edges: edges(n), results, pending, running, prReady, stackedTried, satisfied: SATISFIED }) && isReady(n))); } finally { planPass = false; }
1950
+ for (const n of sc) {
1951
+ if (running.size >= K()) break;
1952
+ if (lanes.get(n)?.ok === false || (notBefore.get(n) ?? 0) > t) continue;
1953
+ const so = stackAdmissible({ n, edges: edges(n), results, pending, running, prReady, stackedTried, satisfied: SATISFIED });
1954
+ if (!so || grant(n, new Set()) !== true) continue;
1955
+ pending.splice(pending.indexOf(n), 1);
1956
+ stackedTried.add(n); stackedOf.set(n, so);
1957
+ store?.log?.({ event: "STACK_BUILD_START", issue: n, stacked: true, stackedOn: so });
1958
+ decided({ issue: n, what: `stacked build for #${n} on #${so.dependency}'s lane head ${String(so.sha).slice(0, 12)}`, why: "orchestration.stacking: full builds a dependent once its dependency's PR is ready; the PR targets the dependency branch and merges only after the dependency", alternative: "wait for the dependency to merge" });
1959
+ start(n, { stackedOn: so }); started++;
1960
+ }
1961
+ if (sc.length) save();
1962
+ }
1963
+ // #5831: stacked lanes (phase 1). After every ready issue, an idle slot plans a dependent whose only unmet gates are in-batch
1964
+ // dependencies still pending or running: one plan lane per issue per batch (contract frozen, no build).
1965
+ if (stackOn && !tripped && !cancelled && !holdUntil && !pfAll && running.size < K() && !pending.some(isReady)) {
1966
+ planPass = true;
1967
+ let cands = [];
1968
+ try { cands = rank(pending.filter((n) => planAdmissible({ n, edges: edges(n), results, pending, running, planTried, satisfied: SATISFIED }) && isReady(n))); } finally { planPass = false; }
1969
+ for (const n of cands) {
1970
+ if (running.size >= K()) break;
1971
+ if (lanes.get(n)?.ok === false || (notBefore.get(n) ?? 0) > t) continue;
1972
+ if (grant(n, new Set()) !== true) continue;
1973
+ pending.splice(pending.indexOf(n), 1);
1974
+ planTried.add(n);
1975
+ const open = edges(n).filter((d) => !results.has(d));
1976
+ store?.log?.({ event: "STACK_PLAN_START", issue: n, dependencies: open });
1977
+ decided({ issue: n, what: `plan lane for #${n} while ${open.map((d) => `#${d}`).join(", ")} ${open.length > 1 ? "are" : "is"} still open`, why: "orchestration.stacking: plan admits a dependent in an idle slot; the contract freezes now and the build starts after its dependencies merged", alternative: "leave the slot idle until the dependencies merge" });
1978
+ start(n, { plan: true }); started++;
1979
+ }
1980
+ if (cands.length) save();
1981
+ }
1770
1982
  if (reg) withdrawExcept(wanted);
1771
1983
  // #4685: a breaker tripped only by link failures (a router restart) closes itself after a cooldown
1772
1984
  if (tripped?.transport && now() - tripped.at >= TRANSPORT_COOLDOWN_MS) { tripped = null; errorTimes = []; transportErrors = 0; save(); }
1985
+ // #5947: --clear-breaker on a schedd-hosted batch reaches this runner through the batch's request file
1986
+ if (getClearBreaker) { let req = false; try { req = Boolean(getClearBreaker()); } catch { req = false; } if (req) { const was = Boolean(tripped); tripped = null; errorTimes = []; transportErrors = 0; save(); try { ackClearBreaker?.({ cleared: was }); } catch { /* advisory */ } } }
1773
1987
  if (tripped && !running.size) { await drainAdds(); break; } // breaker: let running lanes finish, keep the rest pending for a resume
1774
1988
  if (cancelled && !running.size) { await drainAdds(); break; } // #4376: cancel: the rest end held for a resume
1775
1989
  if (budgetStop && !running.size) { await drainAdds(); break; } // execution budget (stop): the same, the rest end held
@@ -1804,12 +2018,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1804
2018
  if (syncParked && running.size && parkedPrs().length) wake = Math.min(wake ?? syncEveryMs, Math.max(0, syncEveryMs - (t - (lastParkedSync ?? t)))); // #4525
1805
2019
  if (running.size && watchable()) wake = Math.min(wake ?? WATCH_EVERY_MS, WATCH_EVERY_MS); // #4595: re-check the blockers of skipped rows
1806
2020
  if (running.size && envWaiting()) wake = Math.min(wake ?? ehWatchMs, ehWatchMs); // #5805: re-check engine/env holds while lanes run
1807
- if (tripped) wake = null;
2021
+ if (train?.size()) wake = Math.min(wake ?? trainEveryMs, Math.max(0, trainEveryMs - (now() - lastTrainTick))); // #5836
2022
+ if (tripped) wake = getClearBreaker ? Math.min(wake ?? pollMs, pollMs) : null;
1808
2023
  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
1809
2024
  if (running.size) {
1810
2025
  if (wake === null) await race(running.values());
1811
2026
  else { const ac = new AbortController(); await race([...running.values(), sleep(wake, ac.signal)]); ac.abort(); }
1812
2027
  } else if (started) continue; // only lane-refused rows settled (synchronously): re-resolve skips first
2028
+ else if (train?.size()) await nap(wake ?? trainEveryMs); // #5836: only train-held PRs are left: poll the train
1813
2029
  else if (pending.length && offered.size) await nap(wake); // waiting for a host slot
1814
2030
  else if (pending.length && (pfAll || pfRemote)) await nap(Math.min(wake ?? pollMs, pollMs)); // #4866: a failing lane preflight is re-checked on the next poll
1815
2031
  else if (pending.length && blockedHit.size) await nap(wake ?? pollMs); // #4773: only blocked issues wait: poll for the label's removal
@@ -1843,6 +2059,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1843
2059
  throw e;
1844
2060
  }
1845
2061
  await Promise.allSettled([...postRuns]); // #5437
2062
+ if (agentRestarts.some((g) => !g.closed) && !halted) { for (const g of agentRestarts) if (!g.closed) closeRestart(g); save(); } // #5859
1846
2063
  if (reg) withdrawExcept(new Set());
1847
2064
  await relabelQueued();
1848
2065
  // #4657: a milestone whose `close_on` state is reached closes here; a failure is a row, never an outcome change.
@@ -136,7 +136,7 @@ export function routeDigestPrompt({ contract = null, read = [], buildReads = "",
136
136
  const rows = (x) => (Array.isArray(x) ? x.filter((v) => v && typeof v === "object") : []);
137
137
  const deliverables = rows(c.deliverables).map((d) => `${d.path ?? "?"}${d.change ? `: ${one(d.change, 160)}` : ""}`);
138
138
  const decisions = rows(c.decisions).map((k) => `${k.id ?? "K?"} ${one(k.choice, 200)}${k.justification ? ` (${one(k.justification, 160)})` : ""}`);
139
- const open = rows(c.requirements).filter((r) => r.disposition && r.disposition !== "deliver").map((r) => `${r.id ?? "R?"} ${r.disposition}: ${one(r.quote, 160)}`);
139
+ const open = rows(c.requirements).filter((r) => r.disposition && r.disposition !== "deliver").map((r) => (r.disposition === "guidance" ? `${r.id ?? "R?"} guidance (non-binding, not open work; ${one(r.why, 80)}): ${one(r.quote, 120)}` : `${r.id ?? "R?"} ${r.disposition}: ${one(r.quote, 160)}`));
140
140
  const reads = [...new Set((Array.isArray(read) ? read : []).filter((p) => typeof p === "string" && p))];
141
141
  const budget = Math.max(2048, Number(maxBytes) || 0);
142
142
  const st = String(stat ?? "").trim(), br = String(buildReads ?? "").trim().slice(0, 3000), ck = String(check ?? "").trim().slice(0, 2000);
@@ -215,12 +215,12 @@ A trusted comment recording a prod failure after the merged fix overrides ancest
215
215
  If the issue is already fixed or invalid, write ${RESULT_FILE} {"status":"already-fixed|invalid","summary":"one line","evidence":["file:line ..."]} and stop. A feature already reachable (another name, or a stdlib or wrapped dependency function) is a duplicate: INVALID, naming the equivalent and its path; its deprecation counts against an alias. If it is blocked, write {"status":"blocked","summary":"",...} with a typed "block" (rules below) and stop.
216
216
 
217
217
  2. Otherwise write ${CONTRACT_FILE}, the frozen hand-off: a developer who never saw the issue must be able to implement and verify from this file alone.
218
- {"requirements":[{"id":"R1","quote":"<verbatim sentence or checklist item from the issue>","disposition":"deliver|defer|post-deploy|not-applicable","why":"<defer, post-deploy>","bucket":"<defer, post-deploy: post-deploy|verify-now|date:YYYY-MM-DD|owner:<action>|host>","check":"<post-deploy: id in .forge/post-deploy-checks.json>","evidence":"<file:line, required for not-applicable>","verify":"<optional: in_lane|out_of_band>"}],
218
+ {"requirements":[{"id":"R1","quote":"<verbatim sentence or checklist item from the issue>","disposition":"deliver|defer|post-deploy|not-applicable|guidance","why":"<defer, post-deploy, guidance>","bucket":"<defer, post-deploy: post-deploy|verify-now|date:YYYY-MM-DD|owner:<action>|host>","check":"<post-deploy: id in .forge/post-deploy-checks.json>","evidence":"<file:line, required for not-applicable>","verify":"<optional: in_lane|out_of_band>"}],
219
219
  "deliverables":[{"id":"D1","path":"<file to change>","change":"<what>","requirements":["R1"]}],
220
220
  "preserve":[{"id":"P1","what":"<caller, contract or behaviour that must not change, with its path>"}],
221
221
  "validate":[{"id":"V1","command":"<exact command: the new regression test plus the existing tests that reference the files you change; a git diff compares against the merge base (origin/<lane>...HEAD), never the moving origin/<lane> tip>"}],
222
222
  "decisions":[{"id":"K1","choice":"<a non-obvious choice: a new dependency, a copied pattern, a boundary relied on>","justification":"<why, with file:line>","source":"doc|lint|precedent|spec"}]}
223
- Every requirement and acceptance criterion in the issue and its maintainers' comments is one requirement, quoted verbatim (others' comments are context, not requirements). Never drop or narrow one silently: "defer" (separate work) and "post-deploy" (only checkable after a deploy) are judged by the reviewer and, if accepted, filed by the engine into an aggregate. Every defer or post-deploy row has one "bucket": post-deploy (needs a release), verify-now (parent already on the default branch), date:YYYY-MM-DD (absolute, never a relative wait), owner:<action> (only credentials, spend, an account, a third party, a customer; defer, never post-deploy) or host (read-only prod data: obs-psql, *-monitor). In-repo work: deliver or block split-required. A post-promotion check without a check id is post-deploy. One sentence is one row. An outcome criterion this change can ship as a test, metric or alert is "deliver". A deliver requirement whose result is only measured outside the lane (Lighthouse, field perf, a nightly or report-only suite) is "verify":"out_of_band" with "evidence" naming the job or workflow that measures it (delivered by its instrumentation). The engine tags such quotes itself; set "verify":"in_lane" when this change can check it. List every file you will change as a deliverable; tests are always allowed.
223
+ Every requirement and acceptance criterion in the issue and its maintainers' comments is one requirement, quoted verbatim (others' comments are context, not requirements). Outcome rows (symptom, success statement) bind; a proposed fix is "guidance" (why = follow|adapt|reject: reason). Prescription-only issue: deliver row with "derived_outcome", or block needs-human. Never drop or narrow one silently: "defer" (separate work) and "post-deploy" (only checkable after a deploy) are judged by the reviewer and, if accepted, filed by the engine into an aggregate. Every defer or post-deploy row has one "bucket": post-deploy (needs a release), verify-now (parent already on the default branch), date:YYYY-MM-DD (absolute, never a relative wait), owner:<action> (only credentials, spend, an account, a third party, a customer; defer, never post-deploy) or host (read-only prod data: obs-psql, *-monitor). In-repo work: deliver or block split-required. A post-promotion check without a check id is post-deploy. One sentence is one row. An outcome criterion this change can ship as a test, metric or alert is "deliver". A deliver requirement whose result is only measured outside the lane (Lighthouse, field perf, a nightly or report-only suite) is "verify":"out_of_band" with "evidence" naming the job or workflow that measures it (delivered by its instrumentation). The engine tags such quotes itself; set "verify":"in_lane" when this change can check it. List every file you will change as a deliverable; tests are always allowed.
224
224
  First reviews most often find defects in:
225
225
  ${Object.entries(PLANNER_TIGHTENING).map(([k, x]) => `- ${k}: ${x}`).join("\n")}
226
226
  A new default-off flag or rollout key needs an activation row: defer, bucket \`owner:promote:<flag>\`, why = first cohort, guard metrics, shadow evidence (an AC naming shadow/cohort/treated fails if it ships off).
@@ -522,6 +522,7 @@ export const REVIEWER_SYSTEM = `You are an independent conformance reviewer of o
522
522
 
523
523
  You receive the GitHub issue with its comments, the frozen contract (requirements quoted from the issue, deliverables, preserve constraints, validate commands) with typed amendments, the builder's result with validation output, the changed files, the diff, and a row skeleton with one row per contract id and changed file. The engine computes the verdict from your rows; a reply without rows is rejected, so fill the skeleton rather than composing rows: fill EVERY row (set each empty status, evidence and validated_by, and each null deferral_ok; keep the ids and files as given):
524
524
  - issue_coverage: one row per requirement or acceptance criterion in the issue, quoted verbatim, saying whether the contract covers it, narrows it, or misses it. The skeleton lists the contract's quotes; add a row for any issue requirement the contract does not quote.
525
+ - guidance: a guidance requirement (pre-filled covered / not-applicable) is a proposed change, non-binding: judge whether the outcome rows are met, never whether the proposal was followed. Set misclassified: true on its issue_coverage row only when the quote is really a symptom or success criterion. A deliver row with derived_outcome is judged against derived_outcome, like amendment.text.
525
526
  - amendment: a requirement with an \`amendment\` is judged against amendment.text and its why, not the quote; its issue_coverage row is covered when the amendment follows from its why. A requirement with \`amended_from\` was contracted defer or post-deploy and flipped to deliver: compare amended_from.quote and amended_from.why with amendment.text side by side, and mark the row partial when the rewording drops the original work or only trivially restates it. If it does not hold, mark the row partial with note "amendment: <what to change>".
526
527
  - requirements: one row per contract requirement id: implemented|partial|missing|deferred|post-deploy|not-applicable, with evidence as a backtick-quoted repo-relative path:line copied verbatim from the changed files, including (group), [slug] and [...slug] folders (e.g. \`apps/web/app/(console)/layout.tsx:12\`, not route.ts:12) and the validate id or test that proves it (validated_by). For a defer or post-deploy requirement add deferral_ok: true only if it is genuinely separate work or only checkable after a deploy, false if it belongs in this change, including an outcome criterion (a metric, rate or log expectation) this change could ship as a test, metric or alert, or a read-only production check possible now (bucket verify-now). For a verify out_of_band row (measured by the named job, not in this lane) set instrumented: true only when its budget test or bench is committed and that job is configured, with that path:line as evidence; false otherwise. Do not judge the measured result.
527
528
  - post-deploy requirements: deferral_ok is false when the requirement has no \`check\` id, or its check is neither in .forge/post-deploy-checks.json on the default branch nor added by this change (the commands run from that file only).
@@ -234,6 +234,13 @@ export async function fixStep(ctx) {
234
234
  if (!r?.pr) return blocked("no review result recorded by the review step");
235
235
  const seam = seamOf(ctx);
236
236
  const cfg = parseFixConfig(ctx.config?.fix);
237
+ // #5912: a resume reads the result saved while CI was still running. A CI-only failure at an unmoved head is re-summarised once, so CI
238
+ // that finished green since posts GATE_PASS instead of the stale "still pending" block.
239
+ if (r.marker !== "FORGE:GATE_PASS" && !r.blocking?.length && !r.guards?.length && (r.ciPendingOnly || !(r.ciFailing > 0)) && (await seam.headOf(r.pr)) === r.head) {
240
+ const s = await resummarise(ctx, seam, r);
241
+ if (s.err) return blocked(s.err);
242
+ r = s.r;
243
+ }
237
244
  while (r.marker !== "FORGE:GATE_PASS") {
238
245
  // Only cancelled duplicate runs are red (#5502): nothing to fix. The summary reruns them once; re-summarise without spending the round.
239
246
  if (!r.blocking?.length && r.ciFailing > 0 && r.ciCancelOnly) {
@@ -257,7 +264,7 @@ export async function fixStep(ctx) {
257
264
  const rec = collectFindings({ head: r.head, jobs, findings: r.items ?? [], guards: r.guards ?? [] });
258
265
  const b = blockingOf(rec);
259
266
  if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && jobs.pending?.length) return blocked(`required checks of #${r.pr} still running (${jobs.pending.join(", ")}), with no failure to fix yet; re-run the release once CI finishes`);
260
- if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && !(r.ciFailing > 0)) return blocked(`${r.verdict} with neither a blocking finding nor red CI to fix`);
267
+ if (!b.ci.length && !b.review.length && !b.guards.length && !r.blocking?.length && !(r.ciFailing > 0)) return blocked(`${r.verdict} (${r.marker}) on #${r.pr} at ${String(r.head).slice(0, 7)} with neither a blocking finding nor red CI to fix: nothing is pending or failing, so the gate summary names the actual blocker; read it and re-run the release`);
261
268
  const hashesNow = Object.fromEntries(rec.ci.map((j) => [j.name, j.inputHash ?? inputHash(j.name, r.head)]));
262
269
  const brief = compileBrief(rec, { commands: ctx.config?.preflight ? [ctx.config.preflight.command] : [], rerunChecks: jobsToRerun(hashesNow, ctx.state.fixloop?.hashes ?? {}) });
263
270
  // Non-blocking and out-of-wave findings become next-plan issues, once per head; they are never part of the fix and never merged after READY (I16).