forgedock 1.63.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 (84) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +88 -12
  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 +6 -1
  10. package/bin/lean/batch.test.mjs +71 -6
  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 +15 -6
  17. package/bin/lean/execution.test.mjs +44 -3
  18. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  19. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  20. package/bin/lean/issuewatch.mjs +3 -0
  21. package/bin/lean/lanecheck.test.mjs +13 -1
  22. package/bin/lean/lean.mjs +157 -28
  23. package/bin/lean/lean.test.mjs +289 -21
  24. package/bin/lean/live-execution.mjs +25 -0
  25. package/bin/lean/live-execution.test.mjs +35 -1
  26. package/bin/lean/merged-park.mjs +76 -0
  27. package/bin/lean/merged-park.test.mjs +64 -0
  28. package/bin/lean/mergetrain.mjs +357 -0
  29. package/bin/lean/mergetrain.test.mjs +348 -0
  30. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  31. package/bin/lean/orchestrate-stacking.test.mjs +23 -1
  32. package/bin/lean/orchestrate-train.test.mjs +130 -0
  33. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  34. package/bin/lean/orchestrate.mjs +159 -13
  35. package/bin/lean/prompts.mjs +4 -3
  36. package/bin/lean/release-review.mjs +8 -1
  37. package/bin/lean/release-review.test.mjs +42 -2
  38. package/bin/lean/release-status.test.mjs +53 -1
  39. package/bin/lean/release.mjs +6 -3
  40. package/bin/lean/render.mjs +6 -1
  41. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  42. package/bin/lean/sandbox-remote.mjs +12 -2
  43. package/bin/lean/sched.mjs +19 -2
  44. package/bin/lean/sched.test.mjs +33 -1
  45. package/bin/lean/schedd-health.mjs +2 -1
  46. package/bin/lean/schedd-health.test.mjs +7 -0
  47. package/bin/lean/schedd.mjs +55 -7
  48. package/bin/lean/schedd.test.mjs +42 -1
  49. package/bin/lean/stacking.mjs +45 -0
  50. package/bin/lean/stacking.test.mjs +25 -1
  51. package/bin/lean/statuscomment.mjs +14 -8
  52. package/bin/lean/statuscomment.test.mjs +18 -1
  53. package/bin/lean/validate-catalog.mjs +1 -1
  54. package/bin/lean/validate-catalog.test.mjs +3 -0
  55. package/bin/lean/worktree.mjs +8 -3
  56. package/bin/lean/worktree.test.mjs +18 -0
  57. package/bin/pool/agent.mjs +296 -31
  58. package/bin/pool/cli.mjs +120 -6
  59. package/bin/pool/disk.mjs +43 -0
  60. package/bin/pool/docker.mjs +10 -0
  61. package/bin/pool/health.mjs +95 -0
  62. package/bin/pool/router.mjs +274 -27
  63. package/bin/runner.mjs +3 -1
  64. package/bin/stats/chains.mjs +101 -0
  65. package/bin/stats/chains.test.mjs +53 -0
  66. package/bin/stats/efficiency.mjs +7 -6
  67. package/bin/stats/efficiency.test.mjs +48 -7
  68. package/bin/stats/index.mjs +11 -3
  69. package/bin/stats/stats.test.mjs +9 -0
  70. package/docs/CONFIG.md +8 -1
  71. package/docs/OUTCOME-CODES.md +4 -0
  72. package/package.json +1 -1
  73. package/pool/README.md +10 -0
  74. package/pool/image/Dockerfile +2 -1
  75. package/pool/image/entrypoint.sh +6 -6
  76. package/pool/image/mirror.sh +71 -0
  77. package/pool/install/install-agent-linux.sh +57 -5
  78. package/pool/install/install-agent-macos.sh +148 -0
  79. package/pool/install/install-agent.ps1 +11 -0
  80. package/pool/install/install-agent.sh +59 -7
  81. package/pool/install/uninstall-agent-linux.sh +75 -0
  82. package/pool/install/uninstall-agent-macos.sh +60 -0
  83. package/pool/install/uninstall-agent.ps1 +1 -0
  84. package/scripts/transition-label.sh +11 -0
@@ -0,0 +1,53 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5947: git transport failures (curl 56, early EOF, invalid index-pack output) are `net.transient` deferrals with backoff,
4
+ // never engine-errors, and never reach the circuit breaker; any other engine-error still counts. --clear-breaker reaches a live runner.
5
+ import { describe, it } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { orchestrate, isTransientEngineError, GIT_TRANSPORT_TEXT } from "./orchestrate.mjs";
8
+
9
+ const memStore = () => { let st = null; return { load: () => (st ? JSON.parse(JSON.stringify(st)) : null), save: (s) => { st = JSON.parse(JSON.stringify(s)); }, log: () => {}, peek: () => st }; };
10
+ const EE = (detail) => ({ terminalReason: "engine-error", detail });
11
+ const MERGED = { terminalReason: "merged", pr: 9 };
12
+ const run = async ({ script, issues, breaker = { errors: 2, window_min: 10 }, extra = {} }) => {
13
+ let t = 1_000_000;
14
+ const store = memStore(), updates = [];
15
+ const calls = [];
16
+ const rows = await orchestrate({ issues, parallel: 1, readBody: async () => "", now: () => t, store, pollMs: 1000, breaker,
17
+ sleep: async (ms) => { t += Math.max(1, Number(ms) || 0); },
18
+ runOne: async (n) => { calls.push(n); t += 1000; const l = script[n]; return l[Math.min(calls.filter((c) => c === n).length - 1, l.length - 1)]; },
19
+ onUpdate: (r) => updates.push(r), ...extra });
20
+ return { rows, calls, updates, store };
21
+ };
22
+
23
+ describe("#5947 git transport failures", () => {
24
+ it("classifies git transport text, and not an ordinary failure (negative examples)", () => {
25
+ for (const d of ["error: RPC failed; curl 56 GnuTLS recv error", "fatal: early EOF", "fatal: invalid index-pack output", "fatal: the remote end hung up: unexpected disconnect while reading", "curl 28 Operation timed out", "'/cache/git/x.git' is not a local repository"]) assert.ok(GIT_TRANSPORT_TEXT.test(d) && isTransientEngineError(d), d);
26
+ for (const d of ["TypeError: x is not a function", "validate failed: 56 tests", "curl 5600 bytes"]) assert.equal(GIT_TRANSPORT_TEXT.test(d), false, d);
27
+ });
28
+
29
+ it("engine-errors with curl 56 / invalid index-pack output defer as net.transient; the breaker stays closed", async () => {
30
+ const r = await run({ issues: [1, 2], script: { 1: [EE("fatal: early EOF\nerror: RPC failed; curl 56 recv"), MERGED], 2: [EE("fatal: invalid index-pack output"), MERGED] } });
31
+ const d = r.updates.filter((u) => u.outcome === "deferred");
32
+ assert.equal(d.length, 2);
33
+ assert.ok(d.every((u) => u.code === "net.transient"));
34
+ assert.deepEqual(r.rows.map((x) => x.outcome).sort(), ["merged", "merged"]);
35
+ const st = r.store.peek();
36
+ assert.deepEqual(st.errorTimes, []);
37
+ assert.equal(st.breaker ?? null, null);
38
+ assert.equal(r.updates.some((u) => u.outcome === "breaker" || u.outcome === "engine-error"), false);
39
+ });
40
+
41
+ it("a non-transport engine-error still counts toward the breaker", async () => {
42
+ const r = await run({ issues: [1, 2, 3], breaker: { errors: 2, window_min: 10 }, script: { 1: [EE("boom A")], 2: [EE("boom B")], 3: [MERGED] } });
43
+ assert.ok(r.updates.some((u) => u.outcome === "breaker"), "two real engine-errors trip it");
44
+ });
45
+
46
+ it("getClearBreaker resets a tripped breaker in the running batch and acks", async () => {
47
+ let tripSeen = false; const acks = [];
48
+ const r = await run({ issues: [1, 2, 3], breaker: { errors: 2, window_min: 10 }, script: { 1: [EE("boom A")], 2: [EE("boom B")], 3: [MERGED] },
49
+ extra: { onUpdate: (u) => { if (u.outcome === "breaker") tripSeen = true; }, getClearBreaker: () => tripSeen, ackClearBreaker: (i) => acks.push(i) } });
50
+ assert.ok(acks.length >= 1 && acks[0].cleared === true, "the live runner acked a real clear");
51
+ assert.equal(r.store.peek().breaker ?? null, null);
52
+ });
53
+ });
@@ -143,6 +143,9 @@ import { openPrerequisites } from "./prereq.mjs";
143
143
 
144
144
  // A dependency that finished like this no longer blocks its dependents.
145
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";
146
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.
147
150
  const HOLD_ROOT = new Set(["needs-human", "engine-error", "deferred", "budget-exceeded", "held"]);
148
151
  /** #5162: members of a real dependency cycle (a nontrivial SCC or a self-loop) among `nodes`; `edgesOf(n)` lists n's dependencies. */
@@ -171,11 +174,15 @@ export const MAX_REQUEUES = 2;
171
174
  export const DEFAULT_MAX_DEFERRALS = 3;
172
175
  // Relaunches of an issue whose lane ended engine-error.
173
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;
174
181
  export const HOST_BUSY_RETRY_S = 60;
175
182
  // #4528: a busy host or a full sandbox pool is a wait, not a failure: requeued after its retry-in, never capped.
176
183
  // A lane that could not be resolved because gh/git failed (network blip) is the same kind of wait (#4791).
177
184
  // #4788: an unreachable pool is a wait too (the lane already retried for unreachable_window_min); a stall is reported by poolStall.
178
- 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"]);
179
186
  export const POOL_OFFLINE_ALERT_MIN = 10;
180
187
  // #5112: `sandbox.capacity` deferrals of one issue after which `execution.fallback_local` runs it on the host (headroom permitting).
181
188
  export const CAPACITY_FALLBACK_AFTER = 3;
@@ -183,7 +190,9 @@ export const RATE_LIMIT_FALLBACK_S = 15 * 60;
183
190
  export const DEFER_BACKOFF_S = 120;
184
191
  export const DEFER_BACKOFF_MAX_S = 30 * 60;
185
192
  // #4685 + #5161: an engine-error detail that names a link or gateway failure (curl's "returned error: 502", HTTP/1.1 503, ...).
186
- 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");
187
196
  /** #5161: a transient engine failure (model gateway 5xx, connection reset): retried with backoff, not the single relaunch. */
188
197
  export const isTransientEngineError = (detail) => TRANSPORT_TEXT.test(String(detail ?? ""));
189
198
  // #5161: transient engine-error retries per issue (forge.yaml `orchestration.transient_retries`) and their backoff: 30s, 2m, 8m, then 15m.
@@ -326,12 +335,14 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
326
335
  * @returns {Promise<Array<{issue:number, outcome:string, pr:?number, cost_usd:number, minutes:number, detail?:string}>>}
327
336
  */
328
337
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
329
- 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,
330
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,
331
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,
332
341
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
333
- 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 }) {
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 }) {
334
344
  const saved = store?.load?.() ?? null;
345
+ if (train && saved?.train) train.restore(saved.train); // #5836: the merge train resumes with the batch
335
346
  const order = saved ? [...saved.order] : [];
336
347
  const set = new Set(order);
337
348
  const deps = toMap(saved?.deps); // issue -> declared dependencies (any issue); only those in `set` are edges
@@ -344,6 +355,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
344
355
  const notBefore = toMap(saved?.notBefore);
345
356
  const requeues = toMap(saved?.requeues);
346
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)
347
359
  const capDefers = toMap(saved?.capDeferrals); // #5112: issue -> `sandbox.capacity` deferrals (uncapped, so not in `deferrals`)
348
360
  const capFellBack = new Set(); // #5112: issues already reported as a capacity fallback (one decision each)
349
361
  const engineErrors = toMap(saved?.engineErrors);
@@ -369,6 +381,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
369
381
  const enqueued = toMap(saved?.enqueued); // #4409: issue -> when it last entered the queue (starvation guard)
370
382
  const heads = new Set(saved?.heads ?? []); // #4409: decomposed sub-issues not started yet: the head of their priority band
371
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
372
387
  // A legacy batch-local `holdUntil` (pre-#4190) names no account and is ignored: a same-account lane re-sets the hold.
373
388
  const holds = limits ?? memoryLimits(now);
374
389
  // #5205: accounts lanes reported limited (account -> until ms), persisted with the batch, excluded from headroom until then.
@@ -468,6 +483,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
468
483
  const stackedTried = new Set(saved?.stackedTried ?? []);
469
484
  const planned = toMap(saved?.planned);
470
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)
471
487
  const recovering = toMap(saved?.recovering); // issue -> {code, attempt, detail, outcome, ...} of the recovery lane queued or running
472
488
  const freeRecovered = new Set(); // #5727: issues whose one free (no-attempt) recovery for a recipe-less remote tool miss was spent
473
489
  const requeueApplied = new Set(saved?.requeueApplied ?? []); // #4550: `--requeue` entries already applied (batch `requeue` file)
@@ -483,14 +499,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
483
499
  const save = () => {
484
500
  if (!store || halted) return;
485
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),
486
- 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) } : {}),
487
- 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 } } : {}),
488
504
  ...(reg ? { priorities: toObj(priorities) } : {}), ...(sandboxUse.size ? { sandbox: toObj(sandboxUse) } : {}),
489
505
  ...(recoveries.size || recovering.size ? { recoveries: toObj(recoveries), recovering: toObj(recovering), recoveryClasses: toObj(classUsed) } : {}),
490
506
  ...(planned.size || planTried.size ? { planned: toObj(planned), planTried: [...planTried] } : {}),
491
507
  ...(stackedTried.size ? { stacked: toObj(stackedOf), stackedTried: [...stackedTried] } : {}),
492
508
  ...(requeueApplied.size ? { requeueApplied: [...requeueApplied], requeued: toObj(requeuedInfo) } : {}),
493
- ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}),
509
+ ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}), ...(train ? { train: train.snapshot() } : {}),
494
510
  ...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), ...(heads.size ? { heads: [...heads] } : {}),
495
511
  ...(engineSigs.size ? { engineSigs: toObj(engineSigs) } : {}), ...(deterministic.size ? { deterministicSigs: [...deterministic] } : {}), ...(toolReadmits.size ? { toolReadmits: [...toolReadmits] } : {}), ...(envSigs.size ? { envSigs: toObj(envSigs) } : {}) });
496
512
  };
@@ -830,6 +846,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
830
846
  };
831
847
  const requeue = (n, delayMs) => { pending.push(n); enqueued.set(n, now()); if (delayMs > 0) notBefore.set(n, now() + delayMs); else notBefore.delete(n); };
832
848
  const TRANSPORT_COOLDOWN_MS = 5 * 60000;
849
+ const netTransients = new Map(); // #5947: issue -> net.transient deferrals (backoff step)
833
850
  let transportErrors = 0; // #4685: engine-errors in the current window that were link failures
834
851
  const noteEngineError = (detail = "") => {
835
852
  if (!breaker) return;
@@ -840,20 +857,68 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
840
857
  tripped = { at: t, ...(transportErrors >= errorTimes.length ? { transport: true } : {}), detail: `circuit breaker: ${errorTimes.length} engine-errors within ${breaker.window_min} min; admissions stopped` };
841
858
  update({ issue: null, outcome: "breaker", detail: tripped.detail });
842
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();
843
900
  };
844
901
 
845
902
  // Apply one lane's result: requeue it (deferred, dependency-open, engine-error) or record its final row.
846
903
  const settleLane = async (n, r, rec, pf) => {
847
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
+ }
848
911
  // #5241: the lane ended: its lease goes with it. #5654: also an interrupted or engine-error end, which is requeued at once
849
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 */ } }
850
913
  // #4304: the pre-filter runs once per issue; a recovery pass's row adds the earlier attempt's cost, which already holds it.
851
914
  const pfCost = recovering.has(n) ? 0 : (pf?.cost_usd ?? 0);
852
- 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 } : {}), ...(rec?.stackedOn ? { stacked: true, stackedOn: rec.stackedOn } : {}),
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 } : {}),
853
916
  ...(() => { const w = capWait.take(n, r?.waits); return w && typeof w === "object" ? { waits: w } : {}; })(), ...(Number.isInteger(r?.heavyQueueMax) ? { heavyQueueMax: r.heavyQueueMax } : {}),
854
917
  ...(Number.isFinite(r?.wall_ms) ? { wall_ms: r.wall_ms } : {}), ...(Number.isFinite(r?.model_ms) ? { model_ms: r.model_ms } : {}), // #4451
855
918
  ...(phasesOf(r, rec) ? { phases: phasesOf(r, rec) } : {}), // #4908
856
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
857
922
  ...(Number.isFinite(r?.precheckMs) ? { precheck_ms: r.precheckMs } : {}), ...(Number.isInteger(r?.precheckDeferred) && r.precheckDeferred > 0 ? { precheck_deferred: r.precheckDeferred } : {}), // #4331
858
923
  ...(typeof r?.firstPass === "boolean" ? { first_pass: r.firstPass } : {}), // #4362
859
924
  ...(r?.turns && typeof r.turns === "object" ? { turns: r.turns } : {}), // #4392
@@ -880,10 +945,18 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
880
945
  }
881
946
  if (sandboxUse.has(n)) row.sandbox = { ...sandboxUse.get(n), ...(sandboxUse.get(n).by_agent ? { by_agent: { ...sandboxUse.get(n).by_agent } } : {}) };
882
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
+ }
883
955
  if (rec?.plan) {
884
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
885
957
  // never counts toward the breaker, the engine-error relaunch, the deferral or the requeue budgets (it returns before them).
886
958
  done();
959
+ planMs.set(n, (planMs.get(n) ?? 0) + Math.max(0, now() - rec.startedAt)); // #5834
887
960
  const ok = r?.terminalReason === "planned" && r?.planned?.contractHash && r?.planned?.baseSha;
888
961
  if (ok) planned.set(n, { contractHash: r.planned.contractHash, baseSha: r.planned.baseSha });
889
962
  store?.log?.({ event: ok ? "STACK_PLANNED" : "STACK_PLAN_FAILED", issue: n, ...(ok ? { contractHash: r.planned.contractHash, baseSha: r.planned.baseSha } : { reason: row.outcome }) });
@@ -952,12 +1025,25 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
952
1025
  update({ ...row, detail: `stopped by cancel: ${r?.code ?? row.outcome}${r?.detail ? ` ${r.detail}` : ""}` });
953
1026
  return;
954
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
+ }
955
1040
  if (row.outcome === "deferred") {
956
1041
  const pol = deferPolicy(r, { now: now(), deferrals: deferrals.get(n) ?? 0, maxDeferrals });
957
1042
  let capGated = false; // #4909: the pool reports free slots, so the slot (not the retry-in timer) gates the relaunch
958
1043
  if (r?.code === "sandbox.unreachable") notePool(true, r.detail ?? "sandbox unreachable");
959
1044
  if (r?.code === "sandbox.capacity") {
960
1045
  capWait.refused(n);
1046
+ if (r.detail) capReasons.set(n, String(r.detail).slice(0, 300));
961
1047
  capDefers.set(n, (capDefers.get(n) ?? 0) + 1); // #5112: counted for the fallback_local capacity fallback
962
1048
  try { capGated = Number.isInteger(remote?.capacity?.()?.free); } catch { capGated = false; }
963
1049
  }
@@ -1003,8 +1089,27 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1003
1089
  }
1004
1090
  row.detail = `gave up after ${deferrals.get(n) ?? 0} deferrals: ${r?.detail ?? r?.code ?? ""}`;
1005
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
+ }
1006
1110
  if (row.outcome === "engine-error") {
1007
- noteEngineError(r?.detail);
1111
+ const errAt = noteEngineError(r?.detail);
1112
+ if (lostNow) lostNow.err = errAt;
1008
1113
  // #5161: a transient failure (gateway 5xx, reset) waits out the outage with backoff instead of the single immediate relaunch.
1009
1114
  if (transientMax > 0 && isTransientEngineError(row.detail)) {
1010
1115
  const k = (transients.get(n) ?? 0) + 1;
@@ -1192,7 +1297,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1192
1297
  const queueMs = Number.isFinite(enqueued.get(n)) ? Math.max(0, now() - enqueued.get(n)) : null; // #4908: queue_wait in the phase ledger
1193
1298
  heads.delete(n); enqueued.delete(n); busyNoted.delete(n);
1194
1299
  const rec = { startedAt: now(), ...(plan ? { plan: true } : {}), ...(stackedOn ? { stackedOn } : {}), ...(queueMs != null ? { queueMs } : {}), ...(lane ? { lane } : {}), ...(remoteRun.has(n) ? { remote: true } : {}), ...(pl ? { placement: pl } : {}) };
1195
- runRecs.set(n, rec); notBefore.delete(n); save();
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();
1196
1302
  track(n, (async () => {
1197
1303
  // Pre-filter once per issue (a requeued issue is not re-checked); fail-open: an error means a normal lane.
1198
1304
  if (prefilter && !checked.has(n)) { let pf = null; try { pf = await prefilter(n, lane); } catch { pf = null; } checked.set(n, pf); save(); }
@@ -1387,6 +1493,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1387
1493
  continue;
1388
1494
  }
1389
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
1390
1497
  const moved = [e.issue], priors = new Map([[e.issue, row]]);
1391
1498
  results.delete(e.issue);
1392
1499
  for (let i = 0; i < moved.length; i++) { // dependents skipped behind a requeued issue (fixpoint)
@@ -1681,6 +1788,38 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1681
1788
  if (back.size) save();
1682
1789
  };
1683
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
+ };
1684
1823
  let firstPass = true; // #5805: a resume (e.g. after an upgrade) re-checks the engine/env holds at once
1685
1824
  try {
1686
1825
  for (;;) {
@@ -1688,10 +1827,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1688
1827
  await drainAdds();
1689
1828
  await drainRequeues();
1690
1829
  checkCancel();
1830
+ await runTrain();
1691
1831
  await watchBlockers(!pending.length && !running.size);
1692
1832
  await watchEnvHolds(firstPass || (!pending.length && !running.size)); // #5805
1693
1833
  firstPass = false;
1694
- if (!pending.length && !running.size) {
1834
+ if (!pending.length && !running.size && !train?.size()) {
1695
1835
  if (envWaiting() && !signal?.aborted) { await nap(ehWatchMs); continue; } // #5805: only engine/env holds remain: keep re-checking them
1696
1836
  break;
1697
1837
  }
@@ -1701,7 +1841,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1701
1841
  for (let i = pending.length - 1; i >= 0; i--) {
1702
1842
  const n = pending[i];
1703
1843
  if (results.has(n)) { pending.splice(i, 1); continue; }
1704
- 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)));
1705
1845
  if (bad !== undefined) {
1706
1846
  pending.splice(i, 1); again = true;
1707
1847
  const br = results.get(bad), root = br.root ?? bad, ro = results.get(root)?.outcome ?? br.outcome;
@@ -1710,6 +1850,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1710
1850
  }
1711
1851
  }
1712
1852
  }
1853
+ if (agentRestarts.length) await agentLostPass(now()); // #5859
1713
1854
  const t = now();
1714
1855
  const holdUntil = heldUntil();
1715
1856
  let started = 0;
@@ -1841,6 +1982,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1841
1982
  if (reg) withdrawExcept(wanted);
1842
1983
  // #4685: a breaker tripped only by link failures (a router restart) closes itself after a cooldown
1843
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 */ } } }
1844
1987
  if (tripped && !running.size) { await drainAdds(); break; } // breaker: let running lanes finish, keep the rest pending for a resume
1845
1988
  if (cancelled && !running.size) { await drainAdds(); break; } // #4376: cancel: the rest end held for a resume
1846
1989
  if (budgetStop && !running.size) { await drainAdds(); break; } // execution budget (stop): the same, the rest end held
@@ -1875,12 +2018,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1875
2018
  if (syncParked && running.size && parkedPrs().length) wake = Math.min(wake ?? syncEveryMs, Math.max(0, syncEveryMs - (t - (lastParkedSync ?? t)))); // #4525
1876
2019
  if (running.size && watchable()) wake = Math.min(wake ?? WATCH_EVERY_MS, WATCH_EVERY_MS); // #4595: re-check the blockers of skipped rows
1877
2020
  if (running.size && envWaiting()) wake = Math.min(wake ?? ehWatchMs, ehWatchMs); // #5805: re-check engine/env holds while lanes run
1878
- 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;
1879
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
1880
2024
  if (running.size) {
1881
2025
  if (wake === null) await race(running.values());
1882
2026
  else { const ac = new AbortController(); await race([...running.values(), sleep(wake, ac.signal)]); ac.abort(); }
1883
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
1884
2029
  else if (pending.length && offered.size) await nap(wake); // waiting for a host slot
1885
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
1886
2031
  else if (pending.length && blockedHit.size) await nap(wake ?? pollMs); // #4773: only blocked issues wait: poll for the label's removal
@@ -1914,6 +2059,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1914
2059
  throw e;
1915
2060
  }
1916
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
1917
2063
  if (reg) withdrawExcept(new Set());
1918
2064
  await relabelQueued();
1919
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).
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
5
5
  import { reviewStep, fixStep, missingReviewers, SPEC_PANEL, MAX_DELTA_PASSES, realSeam, withIntegrityMarker, TEST_GATE_SKIP_NO_TESTS, testGatePrompt, integrationTestCount, resolveSkillName } from "./release-review.mjs";
6
6
  import { readFileSync } from "node:fs";
7
7
  import { EventEmitter } from "node:events";
8
- import { reviewStagingJson } from "../review-staging.mjs";
8
+ import { reviewStagingJson, classifyChecks, cancelOnlyChecks } from "../review-staging.mjs";
9
9
 
10
10
  const H1 = "a".repeat(40), H2 = "b".repeat(40);
11
11
  const manifest = (head, delta = null) => ({ pr: 7, headSha: head, bundle: [1, 2], scopeMode: "full", contextFile: "/sd/review-ctx-7.json", launchedFile: "/sd/7_launched", briefs: [{ domain: "security", path: "/sd/brief-security.md" }], delta });
@@ -266,6 +266,7 @@ describe("fixStep", () => {
266
266
 
267
267
  it("only pending CI (#5519): blocks without a CI issue or lane; a real failure alongside still files", async () => {
268
268
  const s = fakeSeam();
269
+ s.summary = async () => ({ code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 1, ciPendingOnly: true }, lines: [] });
269
270
  const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 1, ciPendingOnly: true } } }));
270
271
  assert.match(r.reason, /still pending/);
271
272
  assert.deepEqual(s.log, []);
@@ -274,8 +275,47 @@ describe("fixStep", () => {
274
275
  assert.ok(s2.log.some((e) => e[0] === "fix-issue"));
275
276
  });
276
277
 
278
+ it("#5912: a stale pending-only GATE_FAILURE is re-summarised on resume and passes once CI is green", async () => {
279
+ const s = fakeSeam();
280
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 3, ciPendingOnly: true } } }));
281
+ assert.equal(r.verdict, "APPROVE FOR DEPLOY");
282
+ assert.deepEqual(s.log, [["summary", []]]);
283
+ });
284
+
285
+ it("#5912: a GATE_FAILURE with a blocking finding is not re-summarised away", async () => {
286
+ const s = fakeSeam();
287
+ await fixStep(ctx(s, { review: { result: { ...failed, ciFailing: 0, ciPendingOnly: false } } }));
288
+ assert.ok(s.log.some((e) => e[0] === "fix-issue"));
289
+ });
290
+
291
+ it("#5912: a moved head is not re-summarised on resume", async () => {
292
+ const s = fakeSeam({ heads: [H2] });
293
+ await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 3, ciPendingOnly: true } } }));
294
+ assert.ok(!s.log.some((e) => e[0] === "summary"));
295
+ });
296
+
297
+ it("#5912: still pending after the re-summarise blocks with the pending reason", async () => {
298
+ const s = fakeSeam({ summary: { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 2, ciPendingOnly: true }, lines: [] } });
299
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 3, ciPendingOnly: true } } }));
300
+ assert.match(r.reason, /still pending/);
301
+ assert.equal(s.log.filter((e) => e[0] === "summary").length, 1);
302
+ });
303
+
304
+ it("#5912: nothing pending and nothing failed names the verdict and never says still pending", async () => {
305
+ const s = fakeSeam({ summary: { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] } });
306
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 0 } } }));
307
+ assert.match(r.reason, /BLOCK DEPLOY \(FORGE:GATE_FAILURE\).*neither/);
308
+ assert.doesNotMatch(r.reason, /still pending/);
309
+ });
310
+
311
+ it("#5912: only forge/deploy-gate and the gate marker non-green gives zero blocking checks", () => {
312
+ const checks = [{ name: "build", bucket: "pass" }, { name: "forge/deploy-gate", bucket: "fail" }, { name: "Check for FORGE gate markers", bucket: "pending" }];
313
+ assert.equal(classifyChecks(checks, ["build"]).blocking, 0);
314
+ assert.deepEqual(cancelOnlyChecks(checks, ["build"]), []);
315
+ });
316
+
277
317
  it("blocks when the verdict is not a pass but there is nothing to fix", async () => {
278
- assert.match((await fixStep(ctx(fakeSeam(), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
318
+ assert.match((await fixStep(ctx(Object.assign(fakeSeam(), { summary: async () => ({ code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] }) }), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
279
319
  });
280
320
  });
281
321