forgedock 1.52.0 → 1.54.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 (233) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,143 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5241: --cancel --stop-remote confirms or reports each lane, releases its lease; dead-lease requeue; active-batch skip.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { orchestrate } from "./orchestrate.mjs";
8
+ import { openBatch, activeBatchOf, cancelledOwners } from "./batch.mjs";
9
+ import { clearLease } from "./lanelock.mjs";
10
+ import { providerLanes } from "./execution.mjs";
11
+ import { orchestrateFromCli } from "../engine-cli.mjs";
12
+
13
+ process.env.FORGEDOCK_SCHED_DIR = tmpDir("cancel-sched-");
14
+ const until = async (cond, ms = 5000) => {
15
+ const end = Date.now() + ms;
16
+ while (!cond()) { if (Date.now() > end) throw new Error("timed out waiting"); await new Promise((r) => setTimeout(r, 5)); }
17
+ };
18
+ const clock = () => { const c = { t: 1_000_000 }; return { now: () => c.t, tick: (ms) => { c.t += ms; } }; };
19
+
20
+ describe("cancel --stop-remote teardown (#5241)", () => {
21
+ it("retries a stop that was not accepted, reports a lane still running after the timeout, then releases its lease when it ends", async () => {
22
+ let cancel = null, saved = null, release;
23
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: () => {} };
24
+ const gate = new Promise((r) => { release = r; });
25
+ const { now, tick } = clock();
26
+ const tries = [], released = [], rows = [];
27
+ const done = orchestrate({ issues: [7], parallel: 1, pollMs: 5, now, stopRetryMs: 1000, stopTimeoutMs: 5000, readBody: async () => "", store, getCancelled: () => cancel, onUpdate: (r) => rows.push(r),
28
+ stopLane: (n, rec) => { tries.push(n); rec.stopNote = "the pool does not support stop (404/405)"; return false; },
29
+ releaseLease: async (n) => { released.push(n); },
30
+ runOne: async (n, _l, ctx) => { ctx.onStart?.({ remote: true, handle: { id: "sbx" } }); await gate; return { terminalReason: "deferred", code: "run.interrupted" }; } });
31
+ await until(() => saved?.running?.[7]);
32
+ cancel = { at: "2026-01-01T00:00:00Z", reason: "operator", stopRemote: true };
33
+ await until(() => tries.length >= 1);
34
+ tick(1500); await until(() => tries.length >= 2); // retried: the first stop was refused
35
+ tick(6000); await until(() => rows.some((r) => /#7 not confirmed stopped/.test(r.detail ?? "")));
36
+ assert.match(rows.find((r) => /not confirmed stopped/.test(r.detail ?? "")).detail, /404\/405/);
37
+ assert.deepEqual(released, [], "a lane still running keeps its lease");
38
+ release(); await done;
39
+ assert.deepEqual(released, [7], "the ended lane's lease is released");
40
+ });
41
+
42
+ it("stopLane records why a lane could not be stopped on its record", async () => {
43
+ const provider = { name: "p", idFor: (n) => `s${n}`, stop: async () => false, stopReason: () => "the pool does not support stop (404/405)" };
44
+ const lanes = providerLanes({ provider, laneArgs: () => [], ledgerFor: () => null });
45
+ const rec = { handle: { id: "s1" } };
46
+ assert.equal(await lanes.stopLane(1, rec), false);
47
+ assert.match(rec.stopNote, /404\/405/);
48
+ });
49
+ });
50
+
51
+ describe("clearLease (#5241)", () => {
52
+ const mk = (lease) => { const st = { lease, phase: "x" }; return { st, projector: { readState: async () => st, writeState: async (_n, s) => { Object.assign(st, s); } } }; };
53
+ it("clears a lease the guard accepts, keeps one it refuses, and no-ops without one", async () => {
54
+ const a = mk({ by: "core_a", until: 9e15 });
55
+ assert.equal(await clearLease({ projector: a.projector, issue: 1 }), true);
56
+ assert.equal(a.st.lease, null);
57
+ const b = mk({ by: "core_b", until: 9e15 });
58
+ assert.equal(await clearLease({ projector: b.projector, issue: 1, shouldClear: () => false }), false);
59
+ assert.equal(b.st.lease.by, "core_b");
60
+ assert.equal(await clearLease({ projector: mk(null).projector, issue: 1 }), false);
61
+ });
62
+ });
63
+
64
+ describe("dead-lease requeue and active-batch lookup (#5241)", () => {
65
+ const seed = (root, id, { repo = "o/r", order = [5], running = {}, pending = [], notBefore = {}, cancelled = false, report = false } = {}) => {
66
+ const b = openBatch(root, id);
67
+ b.writePlan({ v: 1, id, repo });
68
+ b.store.save({ order, running, pending, results: {}, notBefore });
69
+ if (cancelled) b.requestCancel({});
70
+ if (report) b.writeReport({ done: true });
71
+ return b;
72
+ };
73
+ it("requeue accepts a pending issue deferred on a lease whose holder is a cancelled batch, and still refuses an ordinary deferral", () => {
74
+ const root = tmpDir("cancel-requeue-");
75
+ seed(root, "bcancel", { cancelled: true, running: { 5: { remote: true } } });
76
+ const live = seed(root, "blive", { pending: [5, 6], order: [5, 6], notBefore: { 5: Date.now() + 1e6, 6: Date.now() + 1e6 } });
77
+ const r = live.requeue([5, 6]);
78
+ assert.deepEqual(r.requeued, [5]);
79
+ assert.deepEqual(r.refused, [{ issue: 6, reason: "not terminal" }]);
80
+ });
81
+ it("is refused while a live batch runs the issue, or when no cancelled batch owns it", () => {
82
+ const root = tmpDir("cancel-requeue2-");
83
+ seed(root, "bcancel", { cancelled: true });
84
+ seed(root, "bother", { running: { 5: {} } });
85
+ const live = seed(root, "blive", { pending: [5], notBefore: { 5: Date.now() + 1e6 } });
86
+ assert.deepEqual(cancelledOwners(root, "o/r", 5, "blive"), []);
87
+ assert.equal(live.requeue([5]).refused[0].reason, "not terminal");
88
+ });
89
+ it("activeBatchOf names an unfinished, uncancelled batch of the same repo; not a finished, cancelled, stale or other-repo one", () => {
90
+ const root = tmpDir("cancel-active-");
91
+ seed(root, "bpend", { pending: [5] });
92
+ assert.equal(activeBatchOf(root, "o/r", 5), "bpend");
93
+ assert.equal(activeBatchOf(root, "o/other", 5), null);
94
+ assert.equal(activeBatchOf(root, "o/r", 5, { now: Date.now() + 4 * 3600e3 }), null, "stale");
95
+ openBatch(root, "bpend").writeReport({ done: true });
96
+ assert.equal(activeBatchOf(root, "o/r", 5), null, "finished");
97
+ const root2 = tmpDir("cancel-active2-");
98
+ seed(root2, "bc", { pending: [5], cancelled: true });
99
+ assert.equal(activeBatchOf(root2, "o/r", 5), null, "cancelled");
100
+ });
101
+ });
102
+
103
+ describe("orchestrate start skips issues of another active batch (#5241)", () => {
104
+ const mkDeps = (root, batchId, ran) => ({ dir: tmpDir("active-run-"), batchRoot: root, batchId, allowTmpfs: true, emitTelemetry: async () => {}, io: { gh: async () => "o/r\n" }, sched: null,
105
+ leanIo: { gh: async (a) => (a.includes("milestone") ? JSON.stringify({ milestone: null }) : JSON.stringify({ body: "" })), git: async (a) => (a[0] === "ls-remote" ? "abc\trefs/heads/staging\n" : "") },
106
+ decide: () => {}, orchestration: { breaker: null, maxDeferrals: 3, globalParallel: null },
107
+ leanModule: { runCore: async (o) => { ran.push(o.issue); return { terminalReason: "merged", pr: 50 + o.issue }; } } });
108
+ const run = async (argv, deps) => { const lines = []; const l = console.log; console.log = (...a) => lines.push(a.join(" ")); try { return { res: await orchestrateFromCli(argv, deps), lines }; } finally { console.log = l; } };
109
+
110
+ it("skips the issue naming the batch, runs the rest, and --force starts it anyway", async () => {
111
+ const root = tmpDir("active-cli-");
112
+ const other = openBatch(root, "bother");
113
+ other.writePlan({ v: 1, id: "bother", repo: "o/r" });
114
+ other.store.save({ order: [1], running: { 1: { pid: 1 } }, pending: [], results: {} });
115
+ const ran = [];
116
+ const a = await run(["1", "2", "--parallel", "1", "--repo", "o/r", "--no-prefilter"], mkDeps(root, "bnew", ran));
117
+ assert.match(a.lines.join("\n"), /skipped: #1 is already in active batch bother/);
118
+ assert.deepEqual(ran, [2]);
119
+ assert.deepEqual(openBatch(root, "bnew").readPlan().argv, ["2", "--parallel", "1", "--repo", "o/r", "--no-prefilter"]);
120
+ const ran2 = [];
121
+ await run(["1", "--parallel", "1", "--repo", "o/r", "--no-prefilter", "--force", "sibling batch is dead"], mkDeps(root, "bforce", ran2));
122
+ assert.deepEqual(ran2, [1]);
123
+ await assert.rejects(run(["1", "--repo", "o/r", "--no-prefilter"], mkDeps(root, "bnone", [])), /every issue is already in an active batch \(bother\)/);
124
+ });
125
+ });
126
+
127
+ describe("--requeue of a lease-deferred pending issue (#5241)", () => {
128
+ it("releases the deferral wait so the next pass relaunches it at once", async () => {
129
+ let saved = null, entries = [];
130
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: () => {} };
131
+ const runs = [];
132
+ const done = orchestrate({ issues: [9], parallel: 1, pollMs: 5, readBody: async () => "", store, getRequeued: () => entries,
133
+ runOne: async (n) => {
134
+ runs.push(n);
135
+ return runs.length === 1 ? { terminalReason: "deferred", code: "lease-held", detail: `issue 9 leased by core_x until ${new Date(Date.now() + 3600e3).toISOString()}` } : { terminalReason: "merged", pr: 1 };
136
+ } });
137
+ await until(() => Number.isFinite(saved?.notBefore?.[9]));
138
+ entries = [{ issue: 9, reason: "dead lease", by: "operator", at: "2026-01-01T00:00:00Z" }];
139
+ const rows = await done;
140
+ assert.deepEqual(runs, [9, 9]);
141
+ assert.equal(rows.find((r) => r.issue === 9).outcome, "merged");
142
+ });
143
+ });
@@ -21,7 +21,7 @@
21
21
  * before scheduling, so a live lane does not hold up the others.
22
22
  * `deferred` is a scheduling fact, not an end: each typed code is requeued with its retry-at (`deferPolicy`), a usage
23
23
  * limit (and #5168 a claude login failure, `backend.auth`) holds admissions for that account until its reset, and deferrals other than a wait (`host.busy`,
24
- * `sandbox.capacity`, #4528; `sandbox.unreachable`, #4788; `rate_limited`, #4784; `backend.auth`, #5168) stop after `maxDeferrals`.
24
+ * `sandbox.capacity`, #4528; `sandbox.unreachable`, #4788; `rate_limited`, #4784; `backend.auth`, #5168; `quota.exhausted`, #5236) stop after `maxDeferrals`.
25
25
  * #5161: an engine-error whose detail is a transport/gateway failure (`isTransientEngineError`) is requeued with backoff
26
26
  * (`transientRetryDelayMs`) up to `transientRetries` times, not counted against `ENGINE_ERROR_RELAUNCHES`; then it ends engine-error.
27
27
  * #5112: with `remote.offlineFallback` (`execution.fallback_local`), an issue deferred `remote.capacityFallbackAfter` times (default
@@ -30,7 +30,10 @@
30
30
  * host; in memory when absent): admission checks the hold of `identity()`, the account the next lane would use. While held, the
31
31
  * batch re-reads the store every `pollMs` (#4446), so `forgedock limits clear` admits on the next poll, not at the reset.
32
32
  * #5095: `remote.identity()` names the pool's account (execution.mjs `remoteHoldId`); while it is held, a remote-placed lane
33
- * runs local in hybrid (`fallbackLocal`, local account not held) or waits for the reset; admission is not held. An `engine-error` is
33
+ * runs local in hybrid (`fallbackLocal`, local account not held) or waits for the reset; admission is not held. #5203: under a
34
+ * rotator with headroom a pool usage limit reruns at once (`quotaRequeue` `poolId`) and records no pool hold; with no headroom the
35
+ * hold lasts until `rotator.resumeAt()` (the earliest reset). `--requeue` of a quota-paused pending issue clears its notBefore
36
+ * and the pool hold (`drainRequeues`). An `engine-error` is
34
37
  * relaunched once; `breaker` ({errors, window_min}) stops admissions after a burst and lets running lanes finish, the
35
38
  * rest stay pending (outcome `held`) for a resume. `getParallel()` is read on every pass, so K can change live.
36
39
  * #5138: `remote.max`, `remote.fallbackLocal` and `remote.place` are read on every grant too (engine-cli puts live getters on
@@ -118,7 +121,7 @@
118
121
  * the queue order except that decomposed sub-issues go first. A settled row carries `est_minutes` (estimated vs. actual).
119
122
  */
120
123
  import { parseDependsOn } from "../engine/phases.mjs";
121
- import { classifyNeedsHuman, recoveryCodeOf, recoveryClassOf, OUTCOME_CODES } from "../engine/outcome-codes.mjs";
124
+ import { classifyNeedsHuman, recoveryCodeOf, recoveryClassOf, OUTCOME_CODES, ENV_VALIDATE_PLACEMENT, MECHANICAL_CODES } from "../engine/outcome-codes.mjs";
122
125
  import { detectGateDeadlock, formatGateDeadlock } from "./gatewatch.mjs";
123
126
  import { recoveryEvidence } from "./render.mjs";
124
127
  import { renderAlerts } from "../stats/render.mjs";
@@ -130,6 +133,8 @@ import { mapLimit } from "./pmap.mjs";
130
133
  import { quotaRequeue } from "./rotator.mjs";
131
134
  import { joinsDecomposed, addsEpicChildren, selectChildren, edgeText, DEFAULT_POLL_S } from "./autochildren.mjs";
132
135
  import { formatOverload } from "./hostload.mjs";
136
+ import { lackedTools } from "./toolplace.mjs";
137
+ import { openPrerequisites } from "./prereq.mjs";
133
138
 
134
139
  // A dependency that finished like this no longer blocks its dependents.
135
140
  const SATISFIED = new Set(["merged", "invalid"]);
@@ -235,7 +240,7 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
235
240
  const code = r?.code ?? null;
236
241
  if (UNCAPPED_DEFERRALS.has(code)) return { delayMs: (posNum(r?.retryInSeconds) ?? HOST_BUSY_RETRY_S) * 1000, host: true };
237
242
  // #4784: a usage limit is a known-time wait gated by the account hold, never capped.
238
- if (code === "rate_limited") {
243
+ if (code === "rate_limited" || code === "quota.exhausted") { // #5236: no account has capacity: held until the earliest reset
239
244
  const at = posNum(r?.resetAtEpochMs) && r.resetAtEpochMs > now ? r.resetAtEpochMs : now + (posNum(r?.retryInSeconds) ?? RATE_LIMIT_FALLBACK_S) * 1000;
240
245
  return { delayMs: at - now, hold: true };
241
246
  }
@@ -251,6 +256,10 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
251
256
  return { delayMs: Math.min(DEFER_BACKOFF_S * 2 ** (k - 1), DEFER_BACKOFF_MAX_S) * 1000 };
252
257
  }
253
258
 
259
+ // #5241: a cancel re-sends a stop that was not accepted every STOP_RETRY_MS and reports a lane still running after STOP_TIMEOUT_MS.
260
+ const STOP_RETRY_MS = 15 * 1000;
261
+ const STOP_TIMEOUT_MS = 120 * 1000;
262
+
254
263
  const cancellableSleep = (ms, signal) => new Promise((res) => {
255
264
  const t = setTimeout(res, ms);
256
265
  signal?.addEventListener("abort", () => { clearTimeout(t); res(); }, { once: true });
@@ -302,9 +311,9 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
302
311
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), onUpdate = () => {}, onCrossLane = () => {},
303
312
  store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000,
304
313
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
305
- recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, getBlocked = null, trusted = null, getGates = null, stopLane = null,
314
+ recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
306
315
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
307
- getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null }) {
316
+ getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null }) {
308
317
  const saved = store?.load?.() ?? null;
309
318
  const order = saved ? [...saved.order] : [];
310
319
  const set = new Set(order);
@@ -330,10 +339,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
330
339
  let errorTimes = [...(saved?.errorTimes ?? [])];
331
340
  // A legacy batch-local `holdUntil` (pre-#4190) names no account and is ignored: a same-account lane re-sets the hold.
332
341
  const holds = limits ?? memoryLimits(now);
342
+ // #5205: accounts lanes reported limited (account -> until ms), persisted with the batch, excluded from headroom until then.
343
+ const limitedAccounts = toMap(saved?.limitedAccounts);
344
+ const excluded = () => { for (const [k, u] of limitedAccounts) if (!(Number(u) > now())) limitedAccounts.delete(k); return limitedAccounts; };
345
+ const noteLimited = (r) => { for (const l of Array.isArray(r?.limited) ? r.limited : []) { const a = Number(l?.account), u = Number(l?.until); if (Number.isInteger(a) && a > 0 && Number.isFinite(u)) limitedAccounts.set(a, Math.max(u, Number(limitedAccounts.get(a)) || 0)); } };
333
346
  // #5094: with an account rotator, admissions stop only when no account has headroom, and resume when the first one resets.
334
347
  const rotatorHold = () => {
335
348
  if (!rotator) return undefined;
336
- try { if (rotator.headroom()) return null; const u = rotator.resumeAt(); return Number.isFinite(u) && u > now() ? u : undefined; } catch { return undefined; }
349
+ try { if (rotator.headroom(excluded())) return null; const u = rotator.resumeAt(excluded()); return Number.isFinite(u) && u > now() ? u : undefined; } catch { return undefined; }
337
350
  };
338
351
  const heldUntil = () => {
339
352
  const r = rotatorHold();
@@ -374,6 +387,12 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
374
387
  // #4542: a lane recovering from a remote capability block runs on the host, which has the capability.
375
388
  // #4785: a tool-missing recovery too: the sandbox that lacked the tool is not chosen again.
376
389
  if ([OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
390
+ // #5371: a mechanical recovery never repeats the placement of the run that failed (a remote sandbox env defect recurs there), and a remote validate failure is rerun on the host
391
+ if (recovering.get(n)?.code === ENV_VALIDATE_PLACEMENT || (MECHANICAL_CODES.includes(recovering.get(n)?.code) && recovering.get(n)?.where === "remote")) return { where: "local", reason: `different placement: recovering ${recovering.get(n).code} off the remote run` };
392
+ { // #5331: a frozen contract naming a tool the sandbox is known to lack runs on the host (`remote.lacks`, `remote.contractOf(n)`; both optional)
393
+ const lk = lackedTools(remote.contractOf?.(n), remote.lacks);
394
+ if (lk.tools.length) return { where: "local", reason: `host tool: sandbox lacks ${lk.tools.join(", ")}` };
395
+ }
377
396
  if (budgetLocal) return { where: "local", reason: `fallback to local: execution budget: ${budgetHit ?? "cap reached"}` };
378
397
  try {
379
398
  if (typeof remote.place === "function") {
@@ -391,6 +410,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
391
410
  const recoveryMax = Number.isInteger(recovery?.maxAttempts) && recovery.maxAttempts > 0 ? recovery.maxAttempts : 0;
392
411
  // #4725: mechanical/env codes recover on their own budget (>= the conformance one); 0 maxAttempts still turns recovery off.
393
412
  const mechMax = recoveryMax && Number.isInteger(recovery?.mechanicalMaxAttempts) && recovery.mechanicalMaxAttempts > 0 ? Math.max(recovery.mechanicalMaxAttempts, recoveryMax) : recoveryMax;
413
+ const REPEAT_ENV_CODES = [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, OUTCOME_CODES.ENV_TOOL_MISSING]; // #5232: deterministic for a frozen command (a timeout is load, not listed)
414
+ const sigOf = (d) => String(d ?? "").replace(/\s+/g, " ").trim();
394
415
  const maxFor = (cls) => (cls === "mechanical" ? mechMax : recoveryMax);
395
416
  const classUsed = toMap(saved?.recoveryClasses); // `${issue}:${class}` -> recovery lanes launched in that class
396
417
  const recoveries = toMap(saved?.recoveries); // issue -> recovery lanes launched (#4267)
@@ -407,8 +428,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
407
428
  let halted = false; // #4454: stopped by `signal`; the batch's state is no longer this process's to write
408
429
  const save = () => {
409
430
  if (!store || halted) return;
410
- store.save({ v: 1, ...(setup ? { phase: "setup", setup: { ...setup } } : {}), order, deps: toObj(deps), lanes: toObj(lanes), crossSeen: [...crossSeen], results: toObj(results), running: toObj(runRecs),
411
- pending, notBefore: toObj(notBefore), requeues: toObj(requeues), deferrals: toObj(deferrals), engineErrors: toObj(engineErrors), ...(transients.size ? { transientRetries: toObj(transients) } : {}), ...(quota.size ? { quota: toObj(quota) } : {}), ...(capDefers.size ? { capDeferrals: toObj(capDefers) } : {}),
431
+ 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),
432
+ 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) } : {}),
412
433
  prefilter: toObj(checked), errorTimes, breaker: tripped, ...(budget ? { classes: toObj(classes), dispatch: { ...dispatch } } : {}),
413
434
  ...(reg ? { priorities: toObj(priorities) } : {}), ...(sandboxUse.size ? { sandbox: toObj(sandboxUse) } : {}),
414
435
  ...(recoveries.size || recovering.size ? { recoveries: toObj(recoveries), recovering: toObj(recovering), recoveryClasses: toObj(classUsed) } : {}),
@@ -485,6 +506,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
485
506
  };
486
507
  // #4409: `head` (decomposed sub-issues) puts them at the front of the queue in their given order; a sub-issue's
487
508
  // estimate is the parent's ÷ N, floored at the M default.
509
+ // #5340: an open declared prerequisite outside the batch joins it, so edges() orders it first (no run that can only end dependency-open).
510
+ const pullPrerequisites = async (ns) => {
511
+ for (const n of ns) {
512
+ if (results.has(n)) continue;
513
+ const { pull } = await openPrerequisites({ deps: deps.get(n) ?? [], inBatch: (d) => set.has(d), results, issueState, issueLabels });
514
+ if (pull.length) { await addIssues(pull); decided({ issue: n, what: `prerequisite ${pull.map((d) => `#${d}`).join(", ")} is open: pulled into the batch ahead of it`, why: "declared Depends on, outside the batch", alternative: "start the run and end dependency-open" }); }
515
+ }
516
+ };
488
517
  const addIssues = async (ns, { head = false, parent = null } = {}) => {
489
518
  const fresh = ns.filter((d) => !set.has(d));
490
519
  for (const d of fresh) {
@@ -497,6 +526,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
497
526
  if (head) { pending.splice(at++, 0, d); heads.add(d); } else pending.push(d);
498
527
  enqueued.set(d, now());
499
528
  }
529
+ await pullPrerequisites(fresh);
500
530
  noteCrossLane();
501
531
  };
502
532
  // New issues (a fresh batch, or extra issues passed to a resume) join the queue.
@@ -510,6 +540,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
510
540
  await mapLimit(unread, setupConcurrency, async (n) => { await readDeps(n); setup.read++; save(); });
511
541
  setup = null;
512
542
  }
543
+ await pullPrerequisites([...pending]);
513
544
  if (estimate) for (const n of order) { // a resume that enabled the estimator
514
545
  if (estimates.has(n) || results.has(n)) continue;
515
546
  let b = ""; try { b = await readBody(n); } catch { b = ""; }
@@ -705,6 +736,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
705
736
  // Apply one lane's result: requeue it (deferred, dependency-open, engine-error) or record its final row.
706
737
  const settle = async (n, r, rec, pf) => {
707
738
  if (halted) return; // #4454: a resume adopts the lane and settles it
739
+ if (cancelled && releaseLease) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } } // #5241: the lane ended: its lease goes with it
708
740
  // #4304: the pre-filter runs once per issue; a recovery pass's row adds the earlier attempt's cost, which already holds it.
709
741
  const pfCost = recovering.has(n) ? 0 : (pf?.cost_usd ?? 0);
710
742
  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 } : {}),
@@ -717,7 +749,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
717
749
  ...(r?.turns && typeof r.turns === "object" ? { turns: r.turns } : {}), // #4392
718
750
  ...(r?.conformance && typeof r.conformance === "object" ? { conformance: r.conformance } : {}), // #4398
719
751
  ...(rec?.placement ? { placement: rec.placement } : {}), ...(estimates.has(n) ? { est_minutes: Math.round(estimates.get(n) * 10) / 10 } : {}) }; // #4409
720
- const quotaPause = row.outcome === "deferred" && r?.code === "rate_limited" && !cancelled;
752
+ noteLimited(r); // #5205
753
+ const quotaPause = row.outcome === "deferred" && (r?.code === "rate_limited" || r?.code === "quota.exhausted") && !cancelled;
721
754
  if (!quotaPause && quota.has(n)) { // #5094: the paused attempts' cost, added once
722
755
  const q = quota.get(n); quota.delete(n);
723
756
  row.cost_usd = Math.round(((Number(row.cost_usd) || 0) + (Number(q.cost_usd) || 0)) * 1e6) / 1e6;
@@ -797,21 +830,33 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
797
830
  let delayMs = pol.delayMs;
798
831
  if (pol.hold) {
799
832
  // #5094: an account rotator with headroom means another account runs the next call, so no host hold is recorded.
800
- const rq = quotaRequeue({ rotator, r, prior: quota.get(n), delayMs: pol.delayMs });
833
+ // #5203: a usage limit on the pool account rotates like a rotator account (the router hands the next sandbox the
834
+ // lowest-usage login, #5165), so it sets no pool hold and no batch-wide notBefore while any account has headroom.
835
+ const usage = r?.code === "rate_limited" || r?.code === "quota.exhausted";
836
+ let poolId = null;
837
+ if (usage) { try { poolId = remote?.identity?.() ?? null; } catch { poolId = null; } }
838
+ const rq = quotaRequeue({ rotator, r, prior: quota.get(n), delayMs: pol.delayMs, exclude: excluded(), poolId });
839
+ // #5205: no account with room: hold until the rotator's earliest reset (tokenbaton's, over every account), not now+delay
840
+ let rotAt = null;
841
+ if (!rq && rotator && (!r?.backendId || (poolId && r.backendId === poolId) || (() => { try { return rotator.isAccount(r.backendId); } catch { return false; } })())) { // a remote credential keeps its own reset
842
+ try { const p = typeof rotator.pick === "function" ? rotator.pick({ exclude: excluded() }) : null; rotAt = p && p.account === null && Number.isFinite(p.earliestReset) ? p.earliestReset : rotator.resumeAt(excluded()); } catch { rotAt = null; }
843
+ if (!(Number.isFinite(rotAt) && rotAt > now())) rotAt = null;
844
+ }
845
+ // #5203: no account has headroom: the hold lasts until the earliest reset across accounts, not this lane's own reset.
846
+ const holdMs = usage && rotAt !== null ? rotAt - now() : pol.delayMs;
801
847
  if (rq) {
802
848
  delayMs = rq.delayMs;
803
849
  // #5095 + #5094: the pool account's own hold (not the host's) still routes hybrid lanes local until its reset.
804
850
  try { const pool = remote?.identity?.(); if (!rq.rotated && pool && r?.backendId === pool) holds.set(pool, now() + pol.delayMs, `batch ${batchId ?? "?"} #${n}`); } catch { /* fail-open */ }
805
- } else try { holds.set(r?.backendId ?? identity(), now() + pol.delayMs, `batch ${batchId ?? "?"} #${n}`); delayMs = 0; } catch { /* fail-open */ }
851
+ } else try { holds.set(r?.backendId ?? identity(), rotAt ?? now() + holdMs, `batch ${batchId ?? "?"} #${n}`); delayMs = 0; } catch { /* fail-open */ }
806
852
  const q = quota.get(n) ?? { cost_usd: 0, minutes: 0, rotations: 0 };
807
- let rotAt = null;
808
- if (!rq && rotator) { try { rotAt = rotator.resumeAt(); } catch { rotAt = null; } }
809
- const resumeAt = Math.max(now() + (rq ? rq.delayMs : pol.delayMs), Number.isFinite(rotAt) ? rotAt : 0);
853
+ const resumeAt = usage ? now() + (rq ? rq.delayMs : holdMs) : Math.max(now() + (rq ? rq.delayMs : pol.delayMs), rotAt ?? 0);
810
854
  quota.set(n, { cost_usd: Math.round(((Number(q.cost_usd) || 0) + (Number(row.cost_usd) || 0)) * 1e6) / 1e6, minutes: Math.round(((Number(q.minutes) || 0) + (Number(row.minutes) || 0)) * 10) / 10,
811
- resumeAt, rotations: (q.rotations ?? 0) + (rq?.rotated ? 1 : 0) });
855
+ resumeAt, rotations: (q.rotations ?? 0) + (rq?.rotated ? 1 : 0) + (Number(r?.rotations) || 0) }); // #5205: plus the lane's own in-phase rotations
812
856
  requeue(n, delayMs); done(); save();
813
857
  const iso = new Date(resumeAt).toISOString();
814
858
  update({ ...row, outcome: "paused", quota: { resumeAt: iso }, detail: `paused (${r?.code === "backend.auth" ? "backend.auth" : "quota"}) until ${iso}: ${r?.code ?? "deferred"}${r?.detail ? ` ${r.detail}` : ""}` });
859
+ if (r?.code === "quota.exhausted") { const ev = { event: "quota.exhausted", issue: n, batch: batchId ?? null, resumeAt: iso, detail: `quota.exhausted: no account has capacity; resuming ${iso}` }; try { store?.log?.(ev); } catch { /* best effort */ } onUpdate(ev); } // #5236: batch-level event supervisors see
815
860
  return;
816
861
  }
817
862
  requeue(n, capGated ? 0 : delayMs); done(); save();
@@ -875,12 +920,18 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
875
920
  const facts = { ...row, issueEdited: r?.issueEdited === true, quoteMismatch: r?.quoteMismatch === true, conflicting: isConflicting };
876
921
  if (prior) { const pk = `${n}:${recoveryClassOf({ code: prior.code })}`; classUsed.set(pk, Math.max(classUsed.get(pk) ?? 0, prior.attempt)); } // state saved before #4725 has no class counts
877
922
  const cls = recoveryClassOf(facts), max = maxFor(cls), used = classUsed.get(`${n}:${cls}`) ?? 0;
878
- if (classifyNeedsHuman(facts) === "recoverable" && used < max) {
923
+ // #5232: a deterministic env defect of the frozen command that a recovery attempt repeated verbatim is not rebuilt again
924
+ const repeatEnv = prior && REPEAT_ENV_CODES.includes(row.code) && prior.code === row.code && sigOf(prior.detail) === sigOf(row.detail);
925
+ if (repeatEnv) {
926
+ row.detail = `Environment defect: the recovery attempt failed with the same \`${row.code}\` as the run before it, so no further rebuild is spent; run the command below on the host with the project's real dependencies.\n${String(row.detail ?? "")}`;
927
+ decided({ issue: n, what: `no further recovery for ${row.code}: the same failure repeated`, why: firstLine(row.detail), alternative: "requeue another recovery lane that rebuilds against the same frozen command" });
928
+ }
929
+ if (!repeatEnv && classifyNeedsHuman(facts) === "recoverable" && used < max) {
879
930
  const code = recoveryCodeOf(facts), attempt = used + 1;
880
931
  classUsed.set(`${n}:${cls}`, attempt);
881
932
  // #4315: the full lane detail is kept (never firstLine) for the relabel when the batch stops before this attempt
882
933
  recoveries.set(n, (recoveries.get(n) ?? 0) + 1); recovering.set(n, { code, attempt, max, cost_usd: Number(row.cost_usd) || 0, minutes: Number(row.minutes) || 0,
883
- detail: String(row.detail ?? ""), outcome: row.outcome, ...(row.code ? { result_code: row.code } : {}), prev_attempt: prior?.attempt ?? 0 });
934
+ detail: String(row.detail ?? ""), outcome: row.outcome, ...(row.placement?.where ? { where: row.placement.where } : {}), ...(row.code ? { result_code: row.code } : {}), prev_attempt: prior?.attempt ?? 0 });
884
935
  requeue(n, 0); done(); save();
885
936
  decided({ issue: n, what: `recovery lane for ${code} (attempt ${attempt}/${max}); dependents stay queued`, why: firstLine(row.detail) || code,
886
937
  alternative: "leave needs-human for the operator and skip the dependents" });
@@ -977,12 +1028,24 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
977
1028
  // Lanes launched by an earlier dispatcher: re-attach to the live ones, queue the rest again (no result was recorded).
978
1029
  // #4504: every adopt starts at once and races its `onLive` signal, so a live lane never holds up the others: one that
979
1030
  // already ended is settled from its result (or requeued without one) before scheduling; a live one is awaited in the background.
980
- const requeueLost = (n) => { runRecs.delete(n); if (!pending.includes(n) && !results.has(n)) { pending.unshift(n); enqueued.set(n, now()); } };
1031
+ // #5204: a requeue is never silent: one `deferred`/`run.interrupted` row names the cause (an upgrade or a plain restart)
1032
+ // and `onInterrupted` reconciles the issue's labels. It consumes no deferral, engine-error or recovery attempt.
1033
+ const interruptCause = saved?.engineVersion && version && saved.engineVersion !== version ? `upgrade v${saved.engineVersion}→v${version}` : "dispatcher restart";
1034
+ const requeueLost = (n, why) => {
1035
+ runRecs.delete(n);
1036
+ if (pending.includes(n) || results.has(n)) return;
1037
+ pending.unshift(n); enqueued.set(n, now());
1038
+ update({ issue: n, outcome: "deferred", code: "run.interrupted", pr: null, cost_usd: 0, minutes: 0, detail: `interrupted: ${interruptCause}; ${why}; requeued` });
1039
+ decided({ issue: n, what: "requeued (interrupted)", why, alternative: "leave it pending silently" });
1040
+ try { Promise.resolve(onInterrupted?.(n, { cause: interruptCause, why })).catch(() => {}); } catch { /* best effort */ }
1041
+ };
1042
+ const adoptErrors = new Map(); // #5204: issue -> adopt error message, kept for the interrupted row
981
1043
  const adopting = [...runRecs].map(([n, rec]) => {
982
- if (!adopt || !(rec?.pid || rec?.handle)) return { n, rec, live: false, p: Promise.resolve(null) };
1044
+ // #5204: a remote record that lost its handle still adopts: the remote seam finds the sandbox through its ledger.
1045
+ if (!adopt || !(rec?.pid || rec?.handle || rec?.remote)) return { n, rec, live: false, p: Promise.resolve(null) };
983
1046
  let onLive;
984
1047
  const isLive = new Promise((r) => { onLive = () => r(true); });
985
- const p = Promise.resolve().then(() => adopt(n, rec, { onLive })).catch(() => null);
1048
+ const p = Promise.resolve().then(() => adopt(n, rec, { onLive })).catch((e) => { adoptErrors.set(n, `adopt failed: ${firstLine(e?.message ?? e)}`); return null; });
986
1049
  return { n, rec, p, first: Promise.race([p.then(() => false), isLive]) };
987
1050
  });
988
1051
  for (const a of adopting) a.live = a.first ? await a.first : false;
@@ -993,12 +1056,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
993
1056
  track(n, p.then((r) => {
994
1057
  if (r) return settle(n, r, rec, checked.get(n) ?? null);
995
1058
  if (halted) return; // #4454: kept for the next resume
996
- running.delete(n); releaseSlot(n); endRemote(n); requeueLost(n); save(); // ended without a result after all
1059
+ running.delete(n); releaseSlot(n); endRemote(n); requeueLost(n, "the adopted lane ended without a result"); save(); // ended without a result after all
997
1060
  }));
998
1061
  continue;
999
1062
  }
1000
1063
  const r = await p;
1001
- if (!r) { requeueLost(n); continue; }
1064
+ if (!r) {
1065
+ const why = adoptErrors.get(n) ?? (!adopt || !(rec?.pid || rec?.handle || rec?.remote) ? "no adoptable pid or handle" : "the lane ended without a result");
1066
+ requeueLost(n, why); continue;
1067
+ }
1002
1068
  if (rec.remote) { remoteRun.add(n); noteRemote(n, rec.handle); }
1003
1069
  else if (reg) { reg.adoptSlot(keyOf(n), { ...entryOf(n), lanePid: rec.pid }); slotted.add(n); } // released by the settle
1004
1070
  track(n, Promise.resolve(r).then((x) => settle(n, x, rec, checked.get(n) ?? null)));
@@ -1101,6 +1167,17 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1101
1167
  for (const e of fresh) {
1102
1168
  requeueApplied.add(requeueKey(e));
1103
1169
  const row = results.get(e.issue);
1170
+ // #5203: a quota-paused issue (pending, no row) is released: its notBefore and the pool hold go, so the next grant admits it.
1171
+ // #5241: so is an issue waiting out a deferral (e.g. lease-held by a cancelled batch's lane): the next pass admits it.
1172
+ if (!row && pending.includes(e.issue) && (quota.has(e.issue) || notBefore.has(e.issue)) && !running.has(e.issue)) {
1173
+ notBefore.delete(e.issue);
1174
+ if (!quota.has(e.issue)) { deferrals.delete(e.issue); update({ issue: e.issue, outcome: "requeued", detail: `${e.reason || "operator decision"} (deferral released)` }); n++; continue; }
1175
+ try { const pool = remote?.identity?.(); if (pool) holds.clear(pool); } catch { /* fail-open */ }
1176
+ decided({ issue: e.issue, what: `released quota pause of #${e.issue} by ${e.by ?? "operator"} (forgedock orchestrate --requeue)`, why: e.reason || "operator decision", alternative: "wait for the account reset" });
1177
+ update({ issue: e.issue, outcome: "requeued", detail: `${e.reason || "operator decision"} (quota pause released)` });
1178
+ n++;
1179
+ continue;
1180
+ }
1104
1181
  if (!row || !REQUEUABLE(row.outcome) || running.has(e.issue)) continue;
1105
1182
  const moved = [e.issue], priors = new Map([[e.issue, row]]);
1106
1183
  results.delete(e.issue);
@@ -1140,11 +1217,21 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1140
1217
  return n;
1141
1218
  };
1142
1219
  // #4376: one SIGTERM per running local lane (their teardown saves the work); remote lanes run to their result unless the cancel carries `stopRemote` (#4612).
1143
- const stopSent = new Set();
1220
+ // #5241: a stop not accepted is retried and, once the lane outlives the teardown timeout, reported (never silent).
1221
+ const stopSent = new Map(); // issue -> {at, accepted, since, reported}
1144
1222
  function stop(n, rec) {
1145
- if (!stopLane || (rec?.remote && cancelled?.stopRemote !== true) || stopSent.has(n)) return; // #4612: remote lanes only when the cancel asked for it
1146
- stopSent.add(n);
1147
- try { Promise.resolve(stopLane(n, rec)).catch(() => {}); } catch { /* best effort */ }
1223
+ if (!stopLane || (rec?.remote && cancelled?.stopRemote !== true)) return; // #4612: remote lanes only when the cancel asked for it
1224
+ const t = now(), s = stopSent.get(n) ?? { at: null, accepted: false, since: t, reported: false };
1225
+ stopSent.set(n, s);
1226
+ if (!s.reported && t - s.since >= stopTimeoutMs) {
1227
+ s.reported = true;
1228
+ const why = rec?.stopNote ?? (s.accepted ? "stop sent, the lane has not exited" : "stop not accepted");
1229
+ update({ issue: null, outcome: "cancelled", detail: `#${n} not confirmed stopped after ${Math.round(stopTimeoutMs / 1000)}s: ${why}; its lease stays held until it exits` });
1230
+ decided({ issue: n, what: `#${n} not confirmed stopped by the cancel`, why, alternative: "stop the lane by hand" });
1231
+ }
1232
+ if (s.accepted || (s.at !== null && t - s.at < stopRetryMs)) return;
1233
+ s.at = t;
1234
+ try { Promise.resolve(stopLane(n, rec)).then((ok) => { if (ok !== false) s.accepted = true; }, () => {}); } catch { /* best effort */ }
1148
1235
  }
1149
1236
  // #4592: re-read the hold set; one decision and one row when it changes.
1150
1237
  const refreshHeld = () => {
@@ -1462,6 +1549,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1462
1549
  if (offered.size && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // a slot another batch frees
1463
1550
  if (pending.some((n) => remoteCapped.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5138: a live --set-max-remote raise
1464
1551
  if ((getAdded || getRequeued || (getChildren && addsEpicChildren(autoChildren?.mode))) && running.size) wake = Math.min(wake ?? pollMs, pollMs); // #4408/#4550: an add or requeue while only lanes run
1552
+ if (getRequeued && pending.some((n) => quota.has(n) || notBefore.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5203: a --requeue releasing a quota pause
1465
1553
  if ((pfAll || pfRemote) && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #4866
1466
1554
  if (baseWait && pending.length && baseHeld.size) wake = Math.min(wake ?? pollMs, pollMs); // #5031: a landed commit releases on the next tick
1467
1555
  if (getBlocked && pending.length && blockedHit.size) wake = Math.min(wake ?? pollMs, pollMs); // #4773: a removed label releases on the next tick
@@ -1469,7 +1557,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1469
1557
  if (syncParked && running.size && parkedPrs().length) wake = Math.min(wake ?? syncEveryMs, Math.max(0, syncEveryMs - (t - (lastParkedSync ?? t)))); // #4525
1470
1558
  if (running.size && watchable()) wake = Math.min(wake ?? WATCH_EVERY_MS, WATCH_EVERY_MS); // #4595: re-check the blockers of skipped rows
1471
1559
  if (tripped) wake = null;
1472
- if (getCancelled && running.size && !cancelled) wake = Math.min(wake ?? pollMs, pollMs); // #4376: notice a cancel while lanes run
1560
+ 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
1473
1561
  if (running.size) {
1474
1562
  if (wake === null) await race(running.values());
1475
1563
  else { const ac = new AbortController(); await race([...running.values(), sleep(wake, ac.signal)]); ac.abort(); }
@@ -5,11 +5,15 @@
5
5
  * The lane marks the phase it enters; entering one closes the previous, so the lane phases sum to the lane's wall time.
6
6
  * `queue_wait` (and, for a remote lane, the sandbox start the dispatcher saw) happens before the lane clock starts, so the
7
7
  * batch runner adds them to the row; they are not part of the lane-wall sum.
8
- * Row shape: `phases: { <id>: { ms, model_ms?, usd? } }`. FORGE:TELEMETRY values are scalars, so `flattenPhases` gives
9
- * `phase_<id>_ms|_model_ms|_usd` keys for it and `unflattenPhases` reads them back.
8
+ * Row shape: `phases: { <id>: { ms, model_ms?, usd?, wait? } }`. FORGE:TELEMETRY values are scalars, so `flattenPhases` gives
9
+ * `phase_<id>_ms|_model_ms|_usd|_wait_<cause>_ms` keys for it and `unflattenPhases` reads them back.
10
+ * #5349: `wait` is the phase's non-model time by cause (WAIT_CAUSES); what no typed wait explains is `command` (`sandbox` in
11
+ * sandbox_start), so model_ms + the wait causes close to ms.
10
12
  */
11
13
 
12
14
  export const LANE_PHASES = Object.freeze(["queue_wait", "sandbox_start", "deps_install", "validate", "plan", "implement", "precheck", "review", "ci_wait", "base_sync", "merge"]);
15
+ /** Why a lane was not in a model call: queued for a heavy slot, paused for host load, rate-limited, sandbox start, or running a command. */
16
+ export const WAIT_CAUSES = Object.freeze(["heavy_queue", "host_load", "rate_limit", "sandbox", "command"]);
13
17
  const isNum = (x) => typeof x === "number" && Number.isFinite(x);
14
18
 
15
19
  function pct(values, p) {
@@ -19,10 +23,19 @@ function pct(values, p) {
19
23
  return v[Math.max(0, Math.ceil((v.length * p) / 100) - 1)];
20
24
  }
21
25
 
26
+ /** Typed waits rounded, plus the residual (ms - model - typed waits, never negative) as `sandbox` in sandbox_start, else `command`. */
27
+ function waitOf(ms, modelMs, typed = {}, id) {
28
+ const w = {};
29
+ for (const c of WAIT_CAUSES) if (typed[c] > 0) w[c] = Math.round(typed[c]);
30
+ const rest = Math.round(ms - modelMs - Object.values(w).reduce((a, b) => a + b, 0));
31
+ if (rest > 0) { const c = id === "sandbox_start" ? "sandbox" : "command"; w[c] = (w[c] ?? 0) + rest; }
32
+ return w;
33
+ }
34
+
22
35
  /** Sequential ledger starting in `first` at `start`. `now` is the lane clock. */
23
36
  export function createLedger(now, first = "sandbox_start", start = now()) {
24
37
  let cur = LANE_PHASES.includes(first) ? first : null, since = start;
25
- const ms = {}, model = {}, usd = {};
38
+ const ms = {}, model = {}, usd = {}, wait = {};
26
39
  const close = (t) => { if (cur) ms[cur] = (ms[cur] ?? 0) + Math.max(0, t - since); };
27
40
  const enter = (phase) => {
28
41
  if (!LANE_PHASES.includes(phase) || phase === cur) return;
@@ -42,6 +55,12 @@ export function createLedger(now, first = "sandbox_start", start = now()) {
42
55
  if (isNum(modelMs) && modelMs > 0) model[id] = (model[id] ?? 0) + modelMs;
43
56
  if (isNum(cost) && cost > 0) usd[id] = (usd[id] ?? 0) + cost;
44
57
  },
58
+ /** `waitMs` of `cause` (a typed wait) spent in `phase` (the current one when it is not a ledger phase). */
59
+ addWait(phase, cause, waitMs) {
60
+ const id = LANE_PHASES.includes(phase) ? phase : cur;
61
+ if (!id || !WAIT_CAUSES.includes(cause) || !isNum(waitMs) || waitMs <= 0) return;
62
+ (wait[id] ??= {})[cause] = (wait[id][cause] ?? 0) + waitMs;
63
+ },
45
64
  /** The ledger as of now (the open phase counted up to now); does not end the current phase. */
46
65
  snapshot() {
47
66
  const t = now(), total = { ...ms };
@@ -49,7 +68,8 @@ export function createLedger(now, first = "sandbox_start", start = now()) {
49
68
  const out = {};
50
69
  for (const id of LANE_PHASES) {
51
70
  if (!(id in total) && !(id in model) && !(id in usd)) continue;
52
- out[id] = { ms: Math.round(total[id] ?? 0), ...(model[id] ? { model_ms: Math.round(model[id]) } : {}), ...(usd[id] ? { usd: Math.round(usd[id] * 1e6) / 1e6 } : {}) };
71
+ const w = waitOf(total[id] ?? 0, model[id] ?? 0, wait[id], id);
72
+ out[id] = { ms: Math.round(total[id] ?? 0), ...(model[id] ? { model_ms: Math.round(model[id]) } : {}), ...(usd[id] ? { usd: Math.round(usd[id] * 1e6) / 1e6 } : {}), ...(Object.keys(w).length ? { wait: w } : {}) };
53
73
  }
54
74
  return out;
55
75
  },
@@ -69,6 +89,7 @@ export function flattenPhases(phases) {
69
89
  if (isNum(v.ms)) out[`phase_${id}_ms`] = v.ms;
70
90
  if (isNum(v.model_ms)) out[`phase_${id}_model_ms`] = v.model_ms;
71
91
  if (isNum(v.usd)) out[`phase_${id}_usd`] = v.usd;
92
+ for (const c of WAIT_CAUSES) if (isNum(v.wait?.[c])) out[`phase_${id}_wait_${c}_ms`] = v.wait[c];
72
93
  }
73
94
  return out;
74
95
  }
@@ -78,7 +99,9 @@ export function unflattenPhases(rec) {
78
99
  for (const id of LANE_PHASES) {
79
100
  const ms = rec?.[`phase_${id}_ms`], mm = rec?.[`phase_${id}_model_ms`], usd = rec?.[`phase_${id}_usd`];
80
101
  if (!isNum(ms)) continue;
81
- out[id] = { ms, ...(isNum(mm) ? { model_ms: mm } : {}), ...(isNum(usd) ? { usd } : {}) };
102
+ const wait = {};
103
+ for (const c of WAIT_CAUSES) if (isNum(rec?.[`phase_${id}_wait_${c}_ms`])) wait[c] = rec[`phase_${id}_wait_${c}_ms`];
104
+ out[id] = { ms, ...(isNum(mm) ? { model_ms: mm } : {}), ...(isNum(usd) ? { usd } : {}), ...(Object.keys(wait).length ? { wait } : {}) };
82
105
  }
83
106
  return out;
84
107
  }
@@ -103,6 +126,25 @@ export function summarizePhases(list) {
103
126
  return { n: lanes.length, phases, largest: largest ? { phase: largest, share: total > 0 ? phases[largest].sum / total : 0 } : null };
104
127
  }
105
128
 
129
+ /**
130
+ * #5349: non-model time over the given `phases` objects: per phase the summed wall, model and wait-by-cause, and the totals.
131
+ * Only lanes that carry a `wait` breakdown count (older runs have none); `{ n: 0, ... }` when there is none.
132
+ */
133
+ export function summarizeWaits(list) {
134
+ const lanes = (list ?? []).filter((p) => p && typeof p === "object" && Object.values(p).some((v) => v?.wait && typeof v.wait === "object"));
135
+ const phases = {}, total = { ms: 0, model_ms: 0, wait: {} }, per = {}; // per[id][cause]: one value per lane, for p50/p90
136
+ for (const p of lanes) for (const [id, v] of Object.entries(p)) {
137
+ if (!LANE_PHASES.includes(id) || !isNum(v?.ms) || id === "queue_wait") continue;
138
+ const g = (phases[id] ??= { ms: 0, model_ms: 0, wait: {} });
139
+ for (const c of WAIT_CAUSES) if (isNum(v.wait?.[c])) ((per[id] ??= {})[c] ??= []).push(v.wait[c]);
140
+ g.ms += v.ms; total.ms += v.ms;
141
+ if (isNum(v.model_ms)) { g.model_ms += v.model_ms; total.model_ms += v.model_ms; }
142
+ for (const c of WAIT_CAUSES) if (isNum(v.wait?.[c])) { g.wait[c] = (g.wait[c] ?? 0) + v.wait[c]; total.wait[c] = (total.wait[c] ?? 0) + v.wait[c]; }
143
+ }
144
+ for (const [id, byCause] of Object.entries(per)) phases[id].pct = Object.fromEntries(Object.entries(byCause).map(([c, vs]) => [c, { p50: pct(vs, 50), p90: pct(vs, 90) }]));
145
+ return { n: lanes.length, phases, total };
146
+ }
147
+
106
148
  const min = (ms) => `${(ms / 60000).toFixed(1)}m`;
107
149
 
108
150
  /** Report line(s) for p50/p90 per phase and the largest phase; `n/a` when no lane carried a ledger. Never throws. */