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,110 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { normaliseInvalidation, epicOf, findAmendment, affectedChildren, amendmentBody, holdEdge, releaseEdge, parseDispositions, validateDispositions, renderEpicChecklist, fileAmendment, applyReplan, DISPOSITIONS_TAG } from "./replan.mjs";
6
+
7
+ const kid = (n, body = "**Parent**: #5\n") => ({ number: n, body, labels: [], author: { login: "o" }, authorAssociation: "OWNER" });
8
+ const inv = normaliseInvalidation({ decision: "replay_store is optional", why: "core loop needs it", epic: 5 }, 7);
9
+
10
+ // A fake gh over an in-memory repo: issue list/view/create/edit/close and the REST association list.
11
+ const repoWorld = (issues) => {
12
+ const w = { issues: new Map(issues.map((i) => [i.number, { ...i }])), calls: [], next: 100 };
13
+ w.gh = async (a) => {
14
+ w.calls.push(a);
15
+ if (a[0] === "issue" && a[1] === "list" && a.includes("--help")) return "JSON FIELDS\n author, body, labels, number\n";
16
+ if (a[0] === "issue" && a[1] === "list") return JSON.stringify([...w.issues.values()].filter((i) => i.state !== "closed").map(({ number, body, labels, author }) => ({ number, body, labels: labels ?? [], author: author ?? { login: "o" } })));
17
+ if (a[0] === "api") return [...w.issues.values()].map((i) => `${i.number}\tOWNER`).join("\n");
18
+ if (a[1] === "view") { const i = w.issues.get(Number(a[2])); return JSON.stringify({ body: i.body, comments: i.comments ?? [] }); }
19
+ if (a[1] === "create") { const n = ++w.next; w.issues.set(n, { number: n, body: a[a.indexOf("--body") + 1], title: a[a.indexOf("--title") + 1] }); return `https://github.com/o/r/issues/${n}\n`; }
20
+ if (a[1] === "edit") { w.issues.get(Number(a[2])).body = a[a.indexOf("--body") + 1]; return ""; }
21
+ if (a[1] === "close") { w.issues.get(Number(a[2])).state = "closed"; return ""; }
22
+ throw new Error(`unexpected gh ${a.join(" ")}`);
23
+ };
24
+ return w;
25
+ };
26
+
27
+ describe("re-plan loop (#5342)", () => {
28
+ it("normaliseInvalidation needs a decision and a why; epic never equals the lane issue", () => {
29
+ assert.equal(normaliseInvalidation({ decision: "x" }, 7), null);
30
+ assert.equal(normaliseInvalidation({ why: "y" }, 7), null);
31
+ assert.equal(normaliseInvalidation({ decision: "x", why: "y", epic: 7 }, 7).epic, null);
32
+ assert.equal(epicOf(normaliseInvalidation({ decision: "x", why: "y" }, 7), "**Parent**: #12\n"), 12);
33
+ });
34
+
35
+ it("hold edge is added once and released cleanly", () => {
36
+ const held = holdEdge("body\n", 100);
37
+ assert.equal(holdEdge(held, 100), held);
38
+ assert.match(held, /^\*\*Depends on\*\*: #100$/m);
39
+ assert.doesNotMatch(releaseEdge(held, 100), /Depends on/);
40
+ });
41
+
42
+ it("affectedChildren: open children of the epic, narrowed by declared paths, never the lane itself", () => {
43
+ const list = [kid(7), kid(8, "**Parent**: #5\nedits src/a.ts"), kid(9, "**Parent**: #5\nedits src/b.ts"), kid(10, "**Parent**: #6\n")];
44
+ assert.deepEqual(affectedChildren({ list, epic: 5, self: 7 }), [8, 9]);
45
+ assert.deepEqual(affectedChildren({ list, epic: 5, self: 7, paths: ["src/a.ts"] }), [8]);
46
+ });
47
+
48
+ it("fileAmendment files one amendment, holds siblings and the lane; a second invalidation joins it", async () => {
49
+ const w = repoWorld([{ number: 7, body: "**Parent**: #5\n" }, { number: 8, body: "**Parent**: #5\n" }, { number: 9, body: "**Parent**: #5\n" }]);
50
+ const f = await fileAmendment({ gh: w.gh, create: w.gh, repo: "o/r", issue: 7, inv, epic: 5 });
51
+ assert.deepEqual([f.created, f.held.sort()], [true, [7, 8, 9]]);
52
+ for (const n of [7, 8, 9]) assert.match(w.issues.get(n).body, new RegExp(`^\\*\\*Depends on\\*\\*: #${f.amendment}$`, "m"));
53
+ assert.equal(findAmendment([...w.issues.values()], 5), f.amendment);
54
+ const again = await fileAmendment({ gh: w.gh, create: w.gh, repo: "o/r", issue: 8, inv, epic: 5 });
55
+ assert.deepEqual([again.created, again.amendment], [false, f.amendment]);
56
+ assert.equal([...w.issues.values()].filter((i) => /spike amendment/.test(i.title ?? "")).length, 1);
57
+ });
58
+
59
+ it("parseDispositions takes the last block; validateDispositions fails closed on a missing or bad one", () => {
60
+ const blk = (o) => `\`\`\`${DISPOSITIONS_TAG}\n${JSON.stringify(o)}\n\`\`\``;
61
+ const d = parseDispositions([blk({ children: { 8: { disposition: "dropped" } } }), blk({ children: { 8: { disposition: "unchanged" } } })]);
62
+ assert.equal(d.children[8].disposition, "unchanged");
63
+ assert.equal(validateDispositions(d, [8, 9]).ok, false);
64
+ assert.equal(validateDispositions({ children: { 8: { disposition: "re-scoped" } } }, [8]).ok, false);
65
+ assert.equal(validateDispositions({ children: { 8: { disposition: "bogus" } } }, [8]).ok, false);
66
+ assert.equal(validateDispositions(d, [8]).ok, true);
67
+ });
68
+
69
+ it("renderEpicChecklist strikes dropped children and annotates re-scoped ones once", () => {
70
+ const rows = [{ n: 8, disposition: "dropped" }, { n: 9, disposition: "re-scoped" }, { n: 10, disposition: "unchanged" }];
71
+ const once = renderEpicChecklist("- [ ] #8 a\n- [ ] #9 b\n- [ ] #10 c\n", rows, 100);
72
+ assert.equal(once, "- [x] ~~#8 a~~ (dropped, superseded by #100)\n- [ ] #9 b (re-scoped by #100)\n- [ ] #10 c\n");
73
+ assert.equal(renderEpicChecklist(once, rows, 100), once);
74
+ });
75
+
76
+ it("applyReplan marks each open child unchanged, re-scoped or dropped, releases the hold and updates the epic", async () => {
77
+ const w = repoWorld([{ number: 5, body: "- [ ] #8 a\n- [ ] #9 b\n- [ ] #10 c\n" }, { number: 8, body: "**Parent**: #5\n" }, { number: 9, body: "**Parent**: #5\n" }, { number: 10, body: "**Parent**: #5\n" }, { number: 99, body: "**Parent**: #5\n" }]);
78
+ w.issues.get(5).labels = [{ name: "epic" }];
79
+ // 5 is the epic; the children sit under it. Hold 8, 9, 10 as fileAmendment would.
80
+ const f = await fileAmendment({ gh: w.gh, create: w.gh, repo: "o/r", issue: 99, inv, epic: 5 });
81
+ w.issues.get(f.amendment).comments = [{ body: `\`\`\`${DISPOSITIONS_TAG}\n${JSON.stringify({ children: { 8: { disposition: "dropped" }, 9: { disposition: "re-scoped", body: "new design for 9" }, 10: { disposition: "unchanged" }, 99: { disposition: "unchanged" } } })}\n\`\`\`` }];
82
+ const r = await applyReplan({ gh: w.gh, create: w.gh, repo: "o/r", amendment: f.amendment });
83
+ assert.equal(r.ok, true);
84
+ assert.equal(w.issues.get(8).state, "closed");
85
+ assert.match(w.issues.get(9).body, /^new design for 9/);
86
+ assert.match(w.issues.get(9).body, /^\*\*Parent\*\*: #5$/m);
87
+ for (const n of [9, 10]) assert.doesNotMatch(w.issues.get(n).body, /Depends on/);
88
+ assert.match(w.issues.get(5).body, /~~#8 a~~ \(dropped, superseded by #/);
89
+ });
90
+
91
+ it("applyReplan changes nothing when a held child has no disposition", async () => {
92
+ const w = repoWorld([{ number: 8, body: "**Parent**: #5\n" }, { number: 9, body: "**Parent**: #5\n" }, { number: 99, body: "**Parent**: #5\n" }]);
93
+ const f = await fileAmendment({ gh: w.gh, create: w.gh, repo: "o/r", issue: 99, inv, epic: 5 });
94
+ w.issues.get(f.amendment).comments = [{ body: `\`\`\`${DISPOSITIONS_TAG}\n${JSON.stringify({ children: { 8: { disposition: "dropped" } } })}\n\`\`\`` }];
95
+ const r = await applyReplan({ gh: w.gh, create: w.gh, repo: "o/r", amendment: f.amendment });
96
+ assert.equal(r.ok, false);
97
+ assert.match(r.problem, /#9/);
98
+ assert.notEqual(w.issues.get(8).state, "closed");
99
+ });
100
+
101
+ it("applyReplan refuses an issue that is not an amendment", async () => {
102
+ const w = repoWorld([{ number: 3, body: "plain" }]);
103
+ assert.equal((await applyReplan({ gh: w.gh, create: w.gh, repo: "o/r", amendment: 3 })).ok, false);
104
+ assert.match(amendmentBody({ inv, epic: 5, from: 7, children: [8] }), /FORGE:REPLAN/);
105
+ });
106
+
107
+ it("amendmentBody routes re-scoped user-visible children to /design before build (#5330)", () => {
108
+ assert.match(amendmentBody({ inv, epic: 5, from: 7, children: [8] }), /user-visible[\s\S]*`\/design`[\s\S]*before build/);
109
+ });
110
+ });
@@ -11,6 +11,7 @@
11
11
  import { noComments } from "./render.mjs";
12
12
  import { parseFactsComment } from "./facts.mjs";
13
13
  import { isTrustedIssueComment as trusted } from "./prefilter.mjs";
14
+ import { bestResults, passedOnHead } from "./validatebest.mjs";
14
15
 
15
16
  export const RESUME_DIGEST_BYTES = 2048;
16
17
  const LINE_MAX = 200;
@@ -33,10 +34,9 @@ const recordLine = (body) => one(noComments(String(body ?? "")).split("\n").map(
33
34
  * branch's changed files, `lane` the base branch. The text never exceeds `maxBytes` (UTF-8): whole lines are dropped from
34
35
  * the end, so the end reason and validate results (first) survive longest.
35
36
  */
36
- export function buildResumeDigest({ state = null, comments = [], contract = null, files = [], lane = "", maxBytes = RESUME_DIGEST_BYTES } = {}) {
37
+ export function buildResumeDigest({ state = null, comments = [], contract = null, files = [], lane = "", head: laneHead = "", maxBytes = RESUME_DIGEST_BYTES } = {}) {
37
38
  try {
38
39
  const tc = (Array.isArray(comments) ? comments : []).filter(trusted);
39
- const facts = [...tc].reverse().map((c) => parseFactsComment(c?.body)).find(Boolean) ?? null;
40
40
  const last = [...tc].reverse().find((c) => ["NEEDS_HUMAN", "FIX_CI"].includes(markerOf(c?.body)));
41
41
  const validate = Array.isArray(contract?.validate) ? contract.validate : [];
42
42
  const idOf = (cmd) => validate.find((v) => one(v?.command) === cmd)?.id ?? null;
@@ -46,13 +46,15 @@ export function buildResumeDigest({ state = null, comments = [], contract = null
46
46
  const fails = Array.isArray(state?.failureClasses) ? [...new Set(state.failureClasses.map(code).filter(Boolean))].sort().slice(0, 5) : [];
47
47
  const why = last ? `FORGE:${markerOf(last.body)}: ${recordLine(last.body)}` : "";
48
48
  if (reason || why) sections.push(["How the last run ended:", ...(reason ? [`- ${reason}${tcode && tcode !== "unclassified" ? ` (${tcode})` : ""}${fails.length ? `; failures ${fails.join(", ")}` : ""}`] : []), ...(why ? [`- ${why}`] : [])]);
49
- const base = facts?.baselines ?? [];
50
- if (base.length) sections.push(["Validate results of the last run (command: exit):", ...base.map((b) => { const id = idOf(b.command); return `- ${id ? `${one(id, 20)} ` : ""}\`${b.command.replace(/`/g, "'")}\`: exit ${b.exit}${b.exit === 0 ? "" : " (failing)"}`; })]);
49
+ // #5331: the best result per validate id over every trusted record, not the newest record alone; a tool-missing row never replaces a pass
50
+ const rows = [...tc].map((c) => parseFactsComment(c?.body)).filter(Boolean).flatMap((f) => f.baselines.map((b) => ({ id: idOf(b.command), command: b.command, exit: b.exit, head: b.head })));
51
+ const base = bestResults(rows);
52
+ if (base.length) sections.push(["Validate results of the last run (command: exit):", ...base.map((b) => `- ${b.id ? `${one(b.id, 20)} ` : ""}\`${b.command.replace(/`/g, "'")}\`: exit ${b.exit}${b.exit === 0 ? (passedOnHead(b, laneHead) ? " (already passed: do not re-run unless you changed what it covers)" : "") : " (failing)"}`)]);
51
53
  const reqs = (Array.isArray(contract?.requirements) ? contract.requirements : []).filter((r) => r?.disposition === "deliver");
52
54
  if (reqs.length) sections.push(["Requirements to deliver (frozen contract); verify each against the branch and finish what is missing:", ...reqs.map((r) => `- ${one(r.id, 20)}: ${one(r.quote, 160)}`)]);
53
55
  const changed = (Array.isArray(files) ? files : []).map((f) => one(f)).filter(Boolean);
54
56
  if (changed.length) sections.push([`Files changed on the branch (vs ${one(lane) || "base"}):`, ...changed.slice(0, LIST_MAX).map((f) => `- ${f}`), ...(changed.length > LIST_MAX ? [`- … ${changed.length - LIST_MAX} more`] : [])]);
55
- const none = { text: "", files: 0, validates: 0, reason: null };
57
+ const none = { text: "", files: 0, validates: 0, reason: null, passes: [] };
56
58
  if (!sections.length) return none;
57
59
 
58
60
  const head = "\n\nResume digest of the last run on this branch (engine facts, not issue text):";
@@ -62,6 +64,6 @@ export function buildResumeDigest({ state = null, comments = [], contract = null
62
64
  while (lines.length && size(lines) > maxBytes) lines.pop();
63
65
  while (lines.length && lines[lines.length - 1] === "") lines.pop();
64
66
  if (!lines.length || size(lines) > maxBytes) return none;
65
- return { text: [head, ...lines, tail].join("\n"), files: changed.length, validates: base.length, reason };
66
- } catch { return { text: "", files: 0, validates: 0, reason: null }; }
67
+ return { text: [head, ...lines, tail].join("\n"), files: changed.length, validates: base.length, reason, passes: base.filter((b) => b.id && passedOnHead(b, laneHead)).map((b) => ({ id: b.id, command: b.command, head: b.head })) };
68
+ } catch { return { text: "", files: 0, validates: 0, reason: null, passes: [] }; }
67
69
  }
@@ -81,4 +81,20 @@ describe("#4467: App comments in gh issue view shape", () => {
81
81
  assert.ok(buildResumeDigest({ state, comments: [ghShape("rapiercraft-forgedock")] }).text.includes("- FORGE:NEEDS_HUMAN: CI red on lint"));
82
82
  assert.ok(!buildResumeDigest({ state, comments: [ghShape("someone")] }).text.includes("FORGE:NEEDS_HUMAN"));
83
83
  });
84
+ it("keeps the best result per validate id: a later tool-missing row never replaces a pass (#5331)", () => {
85
+ const hf = (validation) => `<!-- ${FACTS_MARKER} -->\n${renderFactsRecord(normaliseFacts({ validation }, { files: ["src/a.ts"], head: "abc1234" }))}`;
86
+ const comments = [
87
+ { body: hf([{ command: "npm run lint", exit: 0 }]), ...BOT },
88
+ { body: hf([{ command: "npm run lint", exit: 127 }, { command: "npm test -- a.test.ts", exit: 1 }]), ...BOT },
89
+ ];
90
+ const d = buildResumeDigest({ comments, contract: CONTRACT, head: "abc1234" });
91
+ assert.match(d.text, /V2 `npm run lint`: exit 0 \(already passed/);
92
+ assert.doesNotMatch(d.text, /exit 127/);
93
+ assert.match(d.text, /V1 `npm test -- a.test.ts`: exit 1 \(failing\)/);
94
+ assert.deepEqual(d.passes, [{ id: "V2", command: "npm run lint", head: "abc1234" }]);
95
+ // a different head, or a record with no head, is not "the same head": nothing is claimed or carried
96
+ assert.deepEqual(buildResumeDigest({ comments, contract: CONTRACT, head: "fff0000" }).passes, []);
97
+ assert.deepEqual(buildResumeDigest({ comments: COMMENTS, contract: CONTRACT, head: "abc1234" }).passes, []);
98
+ assert.doesNotMatch(buildResumeDigest({ comments: COMMENTS, contract: CONTRACT, head: "abc1234" }).text, /already passed/);
99
+ });
84
100
  });
@@ -6,13 +6,21 @@
6
6
  * exhausted host. This adapter reads tokenbaton's per-account quota state: `~/.tokenbaton/current` (the account number)
7
7
  * and `~/.tokenbaton/live.<n>` (`"<5h used %> <5h reset epoch s> <weekly used %> <weekly reset epoch s> <updated s>"`).
8
8
  * Every method re-reads the files (no cache), never writes, and fails open: unreadable state behaves as no rotator.
9
+ * #5205: detected without config when TOKENBATON_HOME is set or the shim is the first `claude` on PATH; a sample whose
10
+ * reset has passed is stale (unknown, never 0%); callers pass the accounts that just hit a limit as `exclude`; a rotation
11
+ * relaunch pins an account picked here (tokenbaton#3 `--pick --json --exclude` when the CLI has it, else live.N).
9
12
  */
10
- import { readFileSync, readdirSync } from "node:fs";
13
+ import { spawnSync } from "node:child_process";
14
+ import { accessSync, constants, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
11
15
  import { homedir } from "node:os";
12
- import { join } from "node:path";
16
+ import { basename, delimiter, join } from "node:path";
13
17
  import { backendIdentity } from "../engine.mjs";
14
18
 
15
19
  export const ROTATOR_KINDS = ["tokenbaton"];
20
+ /** Env switch: `off` disables auto-detection (bin/tests/_tmp.mjs sets it for test processes, #5205). */
21
+ export const ROTATOR_ENV = "FORGEDOCK_ACCOUNT_ROTATOR";
22
+ /** Bound on every tokenbaton / tokenbaton-ctl call (ms). */
23
+ export const ROTATOR_CALL_TIMEOUT_MS = 5000;
16
24
  /** An account has headroom below this 5-hour use (%), like the computeshare quota-aware picker. */
17
25
  export const HEADROOM_PCT = 95;
18
26
 
@@ -20,16 +28,74 @@ export const HEADROOM_PCT = 95;
20
28
  export function parseLive(text) {
21
29
  const f = String(text ?? "").trim().split(/\s+/).map(Number);
22
30
  if (f.length < 4 || !f.slice(0, 4).every(Number.isFinite)) return null;
23
- return { fiveHourPct: f[0], fiveHourResetMs: f[1] * 1000, weeklyPct: f[2], weeklyResetMs: f[3] * 1000 };
31
+ return { fiveHourPct: f[0], fiveHourResetMs: f[1] * 1000, weeklyPct: f[2], weeklyResetMs: f[3] * 1000, updatedMs: Number.isFinite(f[4]) && f[4] > 0 ? f[4] * 1000 : 0 };
24
32
  }
25
33
 
34
+ /** #5236: a sample older than this is unknown for the 5-hour window, whatever its reset says (0 or absent updated = age unknown). */
35
+ export const ROTATOR_SAMPLE_MAX_AGE_MS = 30 * 60000;
36
+
37
+ const isExec = (p) => { try { accessSync(p, constants.X_OK); return true; } catch { return false; } };
38
+ const real = (p) => { try { return realpathSync(p); } catch { return p; } };
39
+ /** True when `p` (resolved) is tokenbaton's shim: `tokenbaton-exec`, or a `.tokenbaton/shim/claude`. */
40
+ export const isShim = (p) => { const r = real(p); return basename(r) === "tokenbaton-exec" || /[\\/]\.tokenbaton[\\/]shim[\\/]claude$/.test(r); };
41
+ /** Every executable `claude` on env.PATH, in PATH order. */
42
+ const claudesOnPath = (env) => String(env?.PATH ?? "").split(delimiter).filter(Boolean).map((d) => join(d, "claude")).filter(isExec);
43
+ /** First `claude` on PATH, or null. */
44
+ export const firstClaude = (env = process.env) => claudesOnPath(env)[0] ?? null;
45
+ /** The real claude: the first `claude` on PATH that is not the shim (the shim's own rule), or null. */
46
+ export const realClaude = (env = process.env) => claudesOnPath(env).find((c) => !isShim(c)) ?? null;
47
+
48
+ /**
49
+ * The account rotator in use (#5205): explicit `execution.account_rotator: tokenbaton` wins; `off` (or env
50
+ * FORGEDOCK_ACCOUNT_ROTATOR=off) disables; unset auto-detects TOKENBATON_HOME or the shim first on PATH.
51
+ * @returns {"tokenbaton"|null}
52
+ */
53
+ export function rotatorKind({ execution = null, env = process.env, which = firstClaude } = {}) {
54
+ const set = execution?.accountRotator;
55
+ if (ROTATOR_KINDS.includes(set)) return set;
56
+ if (set === "off" || String(env?.[ROTATOR_ENV] ?? "").toLowerCase() === "off") return null;
57
+ if (env?.TOKENBATON_HOME) return "tokenbaton";
58
+ try { const c = which(env); return c && isShim(c) ? "tokenbaton" : null; } catch { return null; }
59
+ }
60
+
61
+ /** The account a running claude uses, from /proc/<pid>/environ: TOKENBATON_ACCOUNT, else CLAUDE_CONFIG_DIR=<home>/.claude-<n>; null when unreadable. */
62
+ export function accountOfPid(pid, { procRoot = "/proc", readFile = (p) => readFileSync(p, "utf8") } = {}) {
63
+ if (!Number.isInteger(pid) || pid <= 0) return null;
64
+ let vars;
65
+ try { vars = String(readFile(join(procRoot, String(pid), "environ"))).split("\0"); } catch { return null; }
66
+ const get = (k) => { const v = vars.find((x) => x.startsWith(`${k}=`)); return v === undefined ? null : v.slice(k.length + 1); };
67
+ const t = Number(get("TOKENBATON_ACCOUNT"));
68
+ if (get("TOKENBATON_ACCOUNT") && Number.isInteger(t) && t > 0) return t;
69
+ const m = /[\\/]\.claude-(\d+)[\\/]?$/.exec(get("CLAUDE_CONFIG_DIR") ?? "");
70
+ return m ? Number(m[1]) : null;
71
+ }
72
+
73
+ /** `exclude` as a Map account -> until ms (null when unknown): accepts a Set/array of numbers, a Map, or a plain object. */
74
+ export function excludeMap(exclude) {
75
+ const out = new Map();
76
+ if (!exclude) return out;
77
+ const add = (n, until) => { const k = Number(n); if (Number.isInteger(k) && k > 0) out.set(k, Number.isFinite(Number(until)) && until !== null ? Number(until) : null); };
78
+ if (exclude instanceof Map) for (const [n, u] of exclude) add(n, u);
79
+ else if (Array.isArray(exclude) || exclude instanceof Set) for (const n of exclude) add(n, null);
80
+ else if (typeof exclude === "object") for (const [n, u] of Object.entries(exclude)) add(n, u);
81
+ return out;
82
+ }
83
+
84
+ const defaultExec = (cmd, args, { env, timeout = ROTATOR_CALL_TIMEOUT_MS } = {}) => {
85
+ const r = spawnSync(cmd, args, { encoding: "utf8", timeout, windowsHide: true, stdio: ["ignore", "pipe", "ignore"], env });
86
+ return { status: r.error ? null : r.status, stdout: String(r.stdout ?? "") };
87
+ };
88
+
26
89
  /**
27
- * Handle on an account rotator, or null (unknown kind, or no readable state).
28
- * @returns {null | {kind, accounts, current(), headroom(), resumeAt(), accountIdentity(n), currentIdentity(), isAccount(id)}}
90
+ * Handle on an account rotator, or null (unknown kind, or no readable state). The state dir is env.TOKENBATON_HOME
91
+ * (as-is) unless `home` is passed, else ~/.tokenbaton.
92
+ * @returns {null | {kind, accounts, current(), headroom(exclude), resumeAt(exclude), pick({exclude}), markLimited(n, untilMs),
93
+ * accountOfPid(pid), realClaude(env), accountIdentity(n), currentIdentity(), isAccount(id)}}
29
94
  */
30
- export function openRotator({ kind, home = homedir(), env = process.env, now = () => Date.now(), readFile = (p) => readFileSync(p, "utf8"), listDir = (d) => readdirSync(d) } = {}) {
95
+ export function openRotator({ kind, home = undefined, env = process.env, now = () => Date.now(), readFile = (p) => readFileSync(p, "utf8"), listDir = (d) => readdirSync(d), exec = defaultExec, stat = (p) => statSync(p).mtimeMs } = {}) {
31
96
  if (!ROTATOR_KINDS.includes(kind)) return null;
32
- const dir = join(home, ".tokenbaton");
97
+ const dir = home === undefined && env?.TOKENBATON_HOME ? String(env.TOKENBATON_HOME) : join(home ?? homedir(), ".tokenbaton");
98
+ const userHome = home ?? homedir();
33
99
  const current = () => { try { const n = Number(String(readFile(join(dir, "current"))).trim()); return Number.isInteger(n) && n > 0 ? n : null; } catch { return null; } };
34
100
  const accounts = () => {
35
101
  let names = [];
@@ -40,32 +106,83 @@ export function openRotator({ kind, home = homedir(), env = process.env, now = (
40
106
  if (!m) continue;
41
107
  let live = null;
42
108
  try { live = parseLive(readFile(join(dir, name))); } catch { live = null; }
43
- if (live) out.push({ n: Number(m[1]), ...live });
109
+ if (!live) continue;
110
+ const aged = live.updatedMs > 0 && now() - live.updatedMs > ROTATOR_SAMPLE_MAX_AGE_MS;
111
+ // #5236: the polled `used.N` percent, when newer than the sample and itself fresh, replaces the 5-hour figure.
112
+ let polled = null;
113
+ try {
114
+ const p = Number(String(readFile(join(dir, `used.${m[1]}`))).trim().split(/\s+/)[0]), at = stat(join(dir, `used.${m[1]}`));
115
+ if (Number.isFinite(p) && p >= 0 && Number.isFinite(at) && at > live.updatedMs && now() - at <= ROTATOR_SAMPLE_MAX_AGE_MS) polled = p;
116
+ } catch { polled = null; }
117
+ out.push({ n: Number(m[1]), ...live, polledPct: polled, aged: aged && polled === null, stale: live.fiveHourResetMs <= now() || live.weeklyResetMs <= now() || (aged && polled === null) });
44
118
  }
45
119
  return out.sort((a, b) => a.n - b.n);
46
120
  };
47
121
  if (current() === null || !accounts().length) return null;
48
- const used = (pct, resetMs) => (resetMs <= now() ? 0 : pct);
49
- const hasRoom = (a) => used(a.fiveHourPct, a.fiveHourResetMs) < HEADROOM_PCT && used(a.weeklyPct, a.weeklyResetMs) < 100;
50
- const accountIdentity = (n) => backendIdentity({ backend: "cli", env: { ...env, CLAUDE_CONFIG_DIR: join(home, `.claude-${n}`) } });
122
+ // #5205: a window whose reset has passed is unknown (null), never 0%.
123
+ const used = (pct, resetMs) => (resetMs <= now() ? null : pct);
124
+ const full = (a) => { const r = []; const f = a.polledPct !== null && a.polledPct !== undefined ? a.polledPct : a.aged ? null : used(a.fiveHourPct, a.fiveHourResetMs), w = used(a.weeklyPct, a.weeklyResetMs);
125
+ if (f !== null && f >= HEADROOM_PCT) r.push(a.fiveHourResetMs); if (w !== null && w >= 100) r.push(a.weeklyResetMs); return r; };
126
+ /** "room" (fresh, under the caps), "stale" (a window unknown, none known full: worth one try), or "full". */
127
+ const state = (a) => (full(a).length ? "full" : a.stale ? "stale" : "room");
128
+ const resumeAt = (exclude) => {
129
+ const ex = excludeMap(exclude), t = now();
130
+ const at = accounts().map((a) => {
131
+ if (ex.has(a.n)) { const r = [ex.get(a.n), ...full(a)].filter((x) => Number.isFinite(x) && x > t); return r.length ? Math.max(...r) : NaN; }
132
+ return state(a) === "full" ? Math.max(...full(a)) : t;
133
+ }).filter((x) => Number.isFinite(x) && x > 0);
134
+ return at.length ? Math.min(...at) : null;
135
+ };
136
+ const localPick = (exclude) => {
137
+ const ex = excludeMap(exclude), list = accounts().filter((a) => !ex.has(a.n));
138
+ const fresh = list.filter((a) => state(a) === "room").sort((a, b) => (a.polledPct ?? a.fiveHourPct) - (b.polledPct ?? b.fiveHourPct) || a.n - b.n);
139
+ if (fresh.length) return { account: fresh[0].n, stale: false };
140
+ const stale = list.filter((a) => state(a) === "stale");
141
+ if (stale.length) return { account: stale[0].n, stale: true };
142
+ return { account: null, earliestReset: resumeAt(ex) };
143
+ };
144
+ const childEnv = () => ({ ...process.env, ...env, TOKENBATON_HOME: dir });
145
+ const accountIdentity = (n) => backendIdentity({ backend: "cli", env: { ...env, CLAUDE_CONFIG_DIR: join(userHome, `.claude-${n}`) } });
51
146
  return {
52
147
  kind,
53
- /** The accounts with readable `live.N` state, re-read on every access. */
148
+ /** The accounts with readable `live.N` state (`stale` when a window's reset has passed), re-read on every access. */
54
149
  get accounts() { return accounts(); },
55
150
  current,
56
- /** True when any account has headroom. */
57
- headroom: () => accounts().some(hasRoom),
58
- /** Epoch ms at which the first account regains headroom (now when one has it), or null when unknown. */
59
- resumeAt: () => {
60
- const t = now(), at = accounts().map((a) => {
61
- if (hasRoom(a)) return t;
62
- const r = [];
63
- if (used(a.fiveHourPct, a.fiveHourResetMs) >= HEADROOM_PCT) r.push(a.fiveHourResetMs);
64
- if (used(a.weeklyPct, a.weeklyResetMs) >= 100) r.push(a.weeklyResetMs);
65
- return Math.max(...r);
66
- }).filter((x) => Number.isFinite(x) && x > 0);
67
- return at.length ? Math.min(...at) : null;
151
+ /** The tokenbaton state dir read. */
152
+ dir,
153
+ /** True when any non-excluded account has headroom (a fresh sample under the caps, or a stale one: worth a try). */
154
+ headroom: (exclude) => { const ex = excludeMap(exclude); return accounts().some((a) => !ex.has(a.n) && state(a) !== "full"); },
155
+ /** Epoch ms at which the first account regains headroom (now when one has it), or null when unknown; excluded ones count from their until. */
156
+ resumeAt,
157
+ /**
158
+ * The account to run on next (#5205): tokenbaton#3 `--pick --json --exclude` when the CLI prints JSON (exit 2 = none),
159
+ * else from live.N (fresh lowest use first, then stale). {account, stale} | {account:null, earliestReset}.
160
+ */
161
+ pick: ({ exclude } = {}) => {
162
+ const ex = excludeMap(exclude);
163
+ try {
164
+ const r = exec("tokenbaton", ["--pick", "--json", ...(ex.size ? ["--exclude", [...ex.keys()].join(",")] : [])], { env: childEnv() });
165
+ let j = null; try { j = JSON.parse(String(r?.stdout ?? "").trim()); } catch { j = null; }
166
+ if (j && typeof j === "object") {
167
+ const n = Number(j.account);
168
+ if (r.status === 0 && Number.isInteger(n) && n > 0 && !ex.has(n)) return { account: n, stale: Boolean(j.stale) };
169
+ if (r.status === 2) { const e = Number(j.earliest_reset); return { account: null, earliestReset: Number.isFinite(e) && e > 0 ? e * 1000 : resumeAt(ex) }; }
170
+ }
171
+ } catch { /* fall back to live.N */ }
172
+ try { return localPick(ex); } catch { return { account: null, earliestReset: null }; }
173
+ },
174
+ /** Best-effort `tokenbaton-ctl mark-limited <n> --until <epoch s>`; false when unsupported. Never writes files itself. */
175
+ markLimited: (n, untilMs) => {
176
+ try {
177
+ if (!Number.isInteger(n) || n <= 0) return false;
178
+ const args = ["mark-limited", String(n), ...(Number.isFinite(untilMs) ? ["--until", String(Math.round(untilMs / 1000))] : [])];
179
+ return exec("tokenbaton-ctl", args, { env: childEnv() })?.status === 0;
180
+ } catch { return false; }
68
181
  },
182
+ accountOfPid: (pid, opts) => { try { return accountOfPid(pid, opts); } catch { return null; } },
183
+ realClaude: (e = env) => { try { return realClaude(e); } catch { return null; } },
184
+ /** CLAUDE_CONFIG_DIR of account n. */
185
+ configDir: (n) => join(userHome, `.claude-${n}`),
69
186
  accountIdentity,
70
187
  /** Identity of the current account; null when `current` is unreadable. */
71
188
  currentIdentity: () => { const n = current(); return n === null ? null : accountIdentity(n); },
@@ -74,23 +191,25 @@ export function openRotator({ kind, home = homedir(), env = process.env, now = (
74
191
  };
75
192
  }
76
193
 
77
- /** True while a usage-limited call should be retried at once on the next account: headroom, and fewer tries than accounts. */
78
- export function rotatorRetry(rotator, tries) {
79
- try { return Boolean(rotator) && tries < rotator.accounts.length && rotator.headroom(); } catch { return false; }
194
+ /** True while a usage-limited call should be retried at once on the next account: headroom (outside `exclude`), and fewer tries than accounts. */
195
+ export function rotatorRetry(rotator, tries, exclude = null) {
196
+ try { return Boolean(rotator) && tries < rotator.accounts.length && rotator.headroom(exclude); } catch { return false; }
80
197
  }
81
198
 
82
199
  /**
83
200
  * How orchestrate requeues a `rate_limited` lane under a rotator (#5094), or null when the host hold applies (no rotator,
84
- * no account with headroom, unreadable state). A lane that ran on one of the rotator's accounts (or reported none) is rerun
201
+ * no account with headroom outside `exclude`, unreadable state). A lane that ran on one of the rotator's accounts (or reported none) is rerun
85
202
  * at once, at most once per account; any other credential (a remote sandbox's) waits for its own reset. Neither sets a host hold.
203
+ * #5203: `poolId` (orchestrate's `remote.identity()`, the pool hold key) rotates like a rotator account: since #5165 the pool
204
+ * router hands each sandbox the lowest-usage tokenbaton login, so a rerun lands on another account.
86
205
  * @returns {null | {delayMs:number, rotated:boolean}}
87
206
  */
88
- export function quotaRequeue({ rotator, r, prior = null, delayMs }) {
207
+ export function quotaRequeue({ rotator, r, prior = null, delayMs, exclude = null, poolId = null }) {
89
208
  if (!rotator) return null;
90
209
  try {
91
- if (!rotator.headroom()) return null;
210
+ if (!rotator.headroom(exclude)) return null;
92
211
  const id = r?.backendId ?? null, rotations = Number(prior?.rotations) || 0;
93
- if ((!id || rotator.isAccount(id)) && rotations < rotator.accounts.length) return { delayMs: 0, rotated: true };
212
+ if ((!id || (poolId && id === poolId) || rotator.isAccount(id)) && rotations < rotator.accounts.length) return { delayMs: 0, rotated: true };
94
213
  return { delayMs, rotated: false };
95
214
  } catch { return null; }
96
215
  }
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
5
5
  import { mkdirSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { tmpDir } from "../tests/_tmp.mjs";
8
- import { parseLive, openRotator, rotatorRetry, quotaRequeue, ROTATOR_KINDS, HEADROOM_PCT } from "./rotator.mjs";
8
+ import { parseLive, openRotator, rotatorRetry, quotaRequeue, rotatorKind, realClaude, accountOfPid, ROTATOR_KINDS, HEADROOM_PCT } from "./rotator.mjs";
9
9
  import { laneBackendId, openLimits } from "./limits.mjs";
10
10
  import { orchestrate, formatTable } from "./orchestrate.mjs";
11
11
  import { parseExecution } from "./execution.mjs";
@@ -25,7 +25,7 @@ const H = 3_600_000;
25
25
 
26
26
  describe("account rotator adapter (#5094)", () => {
27
27
  it("parseLive reads the five fields and rejects malformed lines", () => {
28
- assert.deepEqual(parseLive("42 1800000100 7 1800500000 1800000000"), { fiveHourPct: 42, fiveHourResetMs: 1_800_000_100_000, weeklyPct: 7, weeklyResetMs: 1_800_500_000_000 });
28
+ assert.deepEqual(parseLive("42 1800000100 7 1800500000 1800000000"), { fiveHourPct: 42, fiveHourResetMs: 1_800_000_100_000, weeklyPct: 7, weeklyResetMs: 1_800_500_000_000, updatedMs: 1_800_000_000_000 });
29
29
  assert.equal(parseLive(""), null);
30
30
  assert.equal(parseLive("12 abc 3 4"), null);
31
31
  assert.equal(parseLive("1 2 3"), null);
@@ -83,6 +83,10 @@ describe("account rotator adapter (#5094)", () => {
83
83
  assert.deepEqual(quotaRequeue({ rotator: rot, r: {}, delayMs: 600_000 }), { delayMs: 0, rotated: true });
84
84
  assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "acct-1" }, prior: { rotations: 2 }, delayMs: 600_000 }), { delayMs: 600_000, rotated: false });
85
85
  assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "sandbox-cred" }, delayMs: 600_000 }), { delayMs: 600_000, rotated: false }, "R6: remote credential");
86
+ assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "remote:pool" }, delayMs: 600_000, poolId: "remote:pool" }), { delayMs: 0, rotated: true }, "#5203: the pool rotates");
87
+ assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "remote:pool" }, prior: { rotations: 2 }, delayMs: 600_000, poolId: "remote:pool" }), { delayMs: 600_000, rotated: false }, "#5203: capped at the account count");
88
+ assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "sandbox-cred" }, delayMs: 600_000, poolId: "remote:pool" }), { delayMs: 600_000, rotated: false });
89
+ assert.equal(quotaRequeue({ rotator: { ...rot, headroom: () => false }, r: { backendId: "remote:pool" }, delayMs: 1, poolId: "remote:pool" }), null);
86
90
  assert.equal(quotaRequeue({ rotator: { ...rot, headroom: () => false }, r: {}, delayMs: 1 }), null);
87
91
  assert.equal(quotaRequeue({ rotator: null, r: {}, delayMs: 1 }), null);
88
92
  });
@@ -141,3 +145,102 @@ describe("orchestrate with an account rotator (#5094)", () => {
141
145
  assert.equal(starts[1], T0 + H);
142
146
  });
143
147
  });
148
+
149
+ describe("account rotator: detection, staleness, exclusion, pick (#5205)", () => {
150
+ const exe = (path, body = "#!/bin/sh\nexit 0\n") => { mkdirSync(join(path, ".."), { recursive: true }); writeFileSync(path, body, { mode: 0o755 }); return path; };
151
+
152
+ it("#5205 rotatorKind: explicit wins, off disables, TOKENBATON_HOME or the shim first on PATH detects, absent -> null", () => {
153
+ const root = tmpDir("kind-");
154
+ const shimDir = join(root, ".tokenbaton", "shim"), realDir = join(root, "bin");
155
+ exe(join(shimDir, "claude")); exe(join(realDir, "claude"));
156
+ assert.equal(rotatorKind({ execution: { accountRotator: "tokenbaton" }, env: { FORGEDOCK_ACCOUNT_ROTATOR: "off" } }), "tokenbaton");
157
+ assert.equal(rotatorKind({ execution: { accountRotator: "off" }, env: { TOKENBATON_HOME: root } }), null);
158
+ assert.equal(rotatorKind({ execution: {}, env: { TOKENBATON_HOME: root, FORGEDOCK_ACCOUNT_ROTATOR: "off" } }), null);
159
+ assert.equal(rotatorKind({ execution: null, env: { TOKENBATON_HOME: root } }), "tokenbaton");
160
+ assert.equal(rotatorKind({ env: { PATH: `${shimDir}:${realDir}` } }), "tokenbaton", "shim first on PATH");
161
+ assert.equal(rotatorKind({ env: { PATH: `${realDir}:${shimDir}` } }), null, "real claude first");
162
+ assert.equal(rotatorKind({ env: { PATH: "" } }), null, "absent");
163
+ assert.equal(realClaude({ PATH: `${shimDir}:${realDir}` }), join(realDir, "claude"));
164
+ assert.equal(parseExecution({ account_rotator: "off" }).accountRotator, "off");
165
+ assert.equal(parseExecution({ account_rotator: "none" }).accountRotator, "off");
166
+ assert.equal(parseExecution({}).accountRotator, undefined);
167
+ assert.equal(openRotator({ kind: "off", home: baton(1, { 1: [0, T0 + H, 0, T0 + H] }).home }), null);
168
+ });
169
+
170
+ it("#5205 TOKENBATON_HOME is the state dir as-is", () => {
171
+ const b = baton(2, { 1: [10, T0 + H, 0, T0 + 9 * H], 2: [20, T0 + H, 0, T0 + 9 * H] });
172
+ const rot = openRotator({ kind: "tokenbaton", env: { TOKENBATON_HOME: join(b.home, ".tokenbaton") }, now: () => T0 });
173
+ assert.equal(rot.dir, join(b.home, ".tokenbaton"));
174
+ assert.deepEqual(rot.accounts.map((a) => a.n), [1, 2]);
175
+ assert.equal(rot.current(), 2);
176
+ });
177
+
178
+ it("#5236 --pick fails and the only account is at its weekly limit: no account is picked (never the default profile)", () => {
179
+ const b = baton(1, { 1: [10, T0 + H, 100, T0 + 9 * H] });
180
+ const rot = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec: () => ({ status: 1, stdout: "" }) });
181
+ assert.equal(rot.pick().account, null);
182
+ });
183
+
184
+ it("#5236 a sample older than the max age is unknown even with a future reset; a newer polled used.N replaces the 5h figure", () => {
185
+ const b = baton(1, { 1: [10, T0 + H, 0, T0 + 90 * H], 2: [50, T0 + H, 0, T0 + 90 * H] });
186
+ const dir = join(b.home, ".tokenbaton");
187
+ writeFileSync(join(dir, "live.1"), `10 ${Math.round((T0 + H) / 1000)} 0 ${Math.round((T0 + 90 * H) / 1000)} ${Math.round((T0 - 3 * H) / 1000)}\n`); // updated 3h ago
188
+ const noCli = () => ({ status: 1, stdout: "" });
189
+ const rot = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec: noCli, stat: () => T0 });
190
+ assert.equal(rot.accounts.find((a) => a.n === 1).stale, true);
191
+ assert.deepEqual(rot.pick(), { account: 2, stale: false }, "old 10% ranks after the fresh 50%");
192
+ writeFileSync(join(dir, "used.2"), "97\n"); // polled, newer than live.2's sample age
193
+ const rot2 = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0 + 1000, exec: noCli, stat: () => T0 + 500 });
194
+ assert.deepEqual(rot2.pick(), { account: 1, stale: true }, "polled 97% blocks account 2");
195
+ });
196
+
197
+ it("#5205 a stale sample is unknown, never 0%: ranked after a fresh one, and an excluded account never counts as room", () => {
198
+ // account 1: 99% with a passed reset (stale); account 4: fresh 47%; account 2: fresh 97% (full)
199
+ const b = baton(1, { 1: [99, T0 - H, 50, T0 + 90 * H], 2: [97, T0 + 2 * H, 10, T0 + 90 * H], 4: [47, T0 + H, 10, T0 + 90 * H] });
200
+ const noCli = () => ({ status: 1, stdout: "3\n" }); // installed tokenbaton without tokenbaton#3: a bare number
201
+ const rot = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec: noCli });
202
+ assert.equal(rot.accounts.find((a) => a.n === 1).stale, true);
203
+ assert.deepEqual(rot.pick(), { account: 4, stale: false }, "fresh 47% before stale");
204
+ assert.deepEqual(rot.pick({ exclude: [4] }), { account: 1, stale: true }, "stale is worth one try");
205
+ assert.equal(rot.headroom([4]), true);
206
+ assert.equal(rot.headroom([1, 4]), false, "excluded never counts as room; 2 is full");
207
+ const none = rot.pick({ exclude: new Map([[1, T0 + 3 * H], [4, T0 + 4 * H]]) });
208
+ assert.deepEqual(none, { account: null, earliestReset: T0 + 2 * H });
209
+ assert.equal(rot.resumeAt(new Map([[1, T0 + 3 * H], [4, T0 + 4 * H]])), T0 + 2 * H);
210
+ assert.equal(rotatorRetry(rot, 0, [1, 2, 4]), false);
211
+ assert.equal(quotaRequeue({ rotator: rot, r: {}, delayMs: 5, exclude: [1, 4] }), null);
212
+ });
213
+
214
+ it("#5205 pick uses tokenbaton#3 --pick --json --exclude when it prints JSON (exit 2 = none, earliest_reset)", () => {
215
+ const b = baton(1, { 1: [10, T0 + H, 0, T0 + 9 * H], 2: [20, T0 + H, 0, T0 + 9 * H] });
216
+ const calls = [];
217
+ let reply = { status: 0, stdout: '{"account":2}' };
218
+ const exec = (cmd, args, opts) => { calls.push([cmd, args, opts.env.TOKENBATON_HOME]); return reply; };
219
+ const rot = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec });
220
+ assert.deepEqual(rot.pick({ exclude: [1] }), { account: 2, stale: false });
221
+ assert.deepEqual(calls[0], ["tokenbaton", ["--pick", "--json", "--exclude", "1"], join(b.home, ".tokenbaton")]);
222
+ reply = { status: 2, stdout: JSON.stringify({ account: null, earliest_reset: Math.round((T0 + 5 * H) / 1000) }) };
223
+ assert.deepEqual(rot.pick({ exclude: [1, 2] }), { account: null, earliestReset: T0 + 5 * H });
224
+ reply = { status: 0, stdout: "1\n" }; // pre-#3 CLI: live.N fallback
225
+ assert.deepEqual(rot.pick({ exclude: [1] }), { account: 2, stale: false });
226
+ reply = { status: 0, stdout: "" };
227
+ assert.equal(rot.markLimited(1, T0 + H), true);
228
+ assert.deepEqual(calls.at(-1).slice(0, 2), ["tokenbaton-ctl", ["mark-limited", "1", "--until", String(Math.round((T0 + H) / 1000))]]);
229
+ reply = { status: 2, stdout: "unknown command" };
230
+ assert.equal(rot.markLimited(1, T0 + H), false, "unsupported: ignored");
231
+ assert.equal(openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec: () => { throw new Error("boom"); } }).pick().account, 1, "fails open to live.N");
232
+ });
233
+
234
+ it("#5205 accountOfPid reads TOKENBATON_ACCOUNT, else CLAUDE_CONFIG_DIR, from /proc/<pid>/environ; null when unreadable", () => {
235
+ const proc = tmpDir("proc-");
236
+ const env = (pid, vars) => { mkdirSync(join(proc, String(pid)), { recursive: true }); writeFileSync(join(proc, String(pid), "environ"), `${vars.join("\0")}\0`); };
237
+ env(11, ["PATH=/bin", "TOKENBATON_ACCOUNT=3", "CLAUDE_CONFIG_DIR=/home/x/.claude-1"]);
238
+ env(12, ["PATH=/bin", "CLAUDE_CONFIG_DIR=/home/x/.claude-2"]);
239
+ env(13, ["PATH=/bin", "CLAUDE_CONFIG_DIR=/home/x/.claude"]);
240
+ assert.equal(accountOfPid(11, { procRoot: proc }), 3);
241
+ assert.equal(accountOfPid(12, { procRoot: proc }), 2);
242
+ assert.equal(accountOfPid(13, { procRoot: proc }), null);
243
+ assert.equal(accountOfPid(99, { procRoot: proc }), null);
244
+ assert.equal(accountOfPid(undefined, { procRoot: proc }), null);
245
+ });
246
+ });
@@ -146,6 +146,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
146
146
  if (!transport) throw new Error("remote provider needs a transport");
147
147
  const idFor = (issue) => `fdrsbx-${safeSegment(batch.id)}-${issue}`;
148
148
  const known = new Set(); // secret values seen this process, for redaction
149
+ const stopWhy = new Map(); // #5241: sandbox id -> why its last stop was not accepted
149
150
  const remember = (v) => { if (typeof v === "string" && v.length >= 4) known.add(v); };
150
151
  for (const k of settings.secrets ?? []) remember(credentials(k));
151
152
  if (settings.tokenEnv) remember(credentials(settings.tokenEnv));
@@ -240,9 +241,15 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
240
241
  },
241
242
  /** #4612: a graceful stop at the lane's checkpoint; false when unsupported or failed. Never destroys the sandbox. */
242
243
  async stop(h) {
243
- if (typeof transport.stop !== "function") return false;
244
- try { return (await transport.stop(h.id)) === true; } catch { return false; }
244
+ if (typeof transport.stop !== "function") { stopWhy.set(h.id, "the transport has no stop"); return false; }
245
+ try {
246
+ const ok = (await transport.stop(h.id)) === true;
247
+ if (ok) stopWhy.delete(h.id); else stopWhy.set(h.id, "the pool does not support stop (404/405)");
248
+ return ok;
249
+ } catch (e) { stopWhy.set(h.id, `stop failed: ${e?.message ?? e}`); return false; }
245
250
  },
251
+ /** #5241: why the last `stop(h)` returned false (null when it succeeded or never ran), so a cancel can report it. */
252
+ stopReason: (h) => stopWhy.get(h?.id) ?? null,
246
253
  async teardown(h) {
247
254
  await minutesOf(h);
248
255
  try { return (await transport.destroy(h.id)) !== false; } catch { return false; }