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
@@ -446,6 +446,9 @@ describe("#4402: the batch report prints the efficiency lines, fail-soft", () =>
446
446
  });
447
447
  });
448
448
 
449
+ // #5314: with no daemon the CLI queues the issues, then fails loudly (nothing is scheduled); the queued result rides on the error.
450
+ const queued = (p) => p.catch((e) => { if (e?.code === "batch.not-hosted") return e.result; throw e; });
451
+
449
452
  describe("#4408: issues added to a running batch (forgedock orchestrate --add)", () => {
450
453
  const gate = () => { let open; const p = new Promise((r) => { open = r; }); return { p, open }; };
451
454
  it("one lane running: an added independent issue starts on the next pass, an added one that Depends on the running issue waits for its merge", async () => {
@@ -545,7 +548,7 @@ describe("#4408: issues added to a running batch (forgedock orchestrate --add)",
545
548
  assert.deepEqual(b.unrunAdds(), [2, 3, 5]);
546
549
  const views = [];
547
550
  const io = { gh: async (a) => { if (a[0] === "api") return "OWNER\n"; views.push(a); if (a[2] === "8") throw new Error("gh down"); return JSON.stringify({ state: a[2] === "7" ? "CLOSED" : "OPEN" }); } };
548
- const res = await quiet(() => orchestrateFromCli(["--add", "b1", "6", "7", "8", "3", "x"], { batchRoot: root, io }));
551
+ const res = await queued(quiet(() => orchestrateFromCli(["--add", "b1", "6", "7", "8", "3", "x"], { batchRoot: root, io })));
549
552
  assert.deepEqual(res.added, [6]);
550
553
  assert.deepEqual(res.skipped.map((x) => [x.issue, x.reason]).sort(), [[3, "already in batch"], [7, "closed"], [8, "unreadable"], ["x", "not an integer"]]);
551
554
  assert.ok(views.every((a) => a.includes("-R") && a.includes("o/r")), "state read against the batch's repo");
@@ -566,7 +569,7 @@ describe("#4408: issues added to a running batch (forgedock orchestrate --add)",
566
569
  await assert.rejects(quiet(() => orchestrateFromCli(["--resume", "b1", "--parallel", "5", "6", "--lane", "staging"], { batchRoot: root, io })), /usage/);
567
570
  assert.deepEqual(views, ["6"]);
568
571
  assert.deepEqual(b.readAdded(), [6]);
569
- const res = await quiet(() => orchestrateFromCli(["--add", "b1", "7", "--parallel", "5"], { batchRoot: root, io }));
572
+ const res = await queued(quiet(() => orchestrateFromCli(["--add", "b1", "7", "--parallel", "5"], { batchRoot: root, io })));
570
573
  assert.deepEqual(res.added, [7]);
571
574
  assert.deepEqual(res.skipped, []);
572
575
  assert.deepEqual(b.readAdded(), [6, 7]);
@@ -881,6 +884,54 @@ describe("#4504: a resume settles lanes that ended while no dispatcher ran", ()
881
884
  });
882
885
  });
883
886
 
887
+ describe("#5204: lanes interrupted by an upgrade are logged and requeued, never dropped", () => {
888
+ const stateOf = (running, extra = {}) => ({ v: 1, order: Object.keys(running).map(Number), deps: Object.fromEntries(Object.keys(running).map((k) => [k, []])), lanes: {}, crossSeen: [], results: {},
889
+ running, pending: [], notBefore: {}, requeues: {}, deferrals: {}, engineErrors: {}, prefilter: {}, errorTimes: [], breaker: null, ...extra });
890
+ it("#5204: a resume after an upgrade logs an interrupted row and requeues a lane that ended without a result", async () => {
891
+ let saved = stateOf({ 3: { startedAt: 1, pid: 33 }, 5: { startedAt: 1, remote: true }, 6: { startedAt: 1, pid: 66 }, 7: { startedAt: 1 } }, { engineVersion: "1.51.0" });
892
+ const logged = [], updates = [], decisions = [], interrupted = [], adopted = [];
893
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: (r) => logged.push(r) };
894
+ const adopt = async (n, rec) => { adopted.push(n); if (n === 6) throw new Error("ledger unreadable"); return null; };
895
+ const launched = [];
896
+ const rows = await orchestrate({ issues: [], parallel: 3, pollMs: 5, readBody: async () => "", store, adopt, version: "1.52.0",
897
+ onUpdate: (r) => updates.push(r), decide: (d) => decisions.push(d),
898
+ onInterrupted: async (n, detail) => { interrupted.push([n, detail.cause]); if (n === 3) throw new Error("gh down"); }, // errors are swallowed
899
+ runOne: async (n) => { launched.push(n); return { terminalReason: "merged", pr: 100 + n }; } });
900
+ assert.deepEqual(adopted.sort(), [3, 5, 6], "a handle-less remote record is still adopted (the ledger seam); a record with nothing to adopt is not");
901
+ const ir = logged.filter((r) => r.code === "run.interrupted");
902
+ assert.deepEqual(ir.map((r) => r.issue).sort(), [3, 5, 6, 7], "one interrupted row per requeued lane");
903
+ for (const r of ir) {
904
+ assert.equal(r.outcome, "deferred");
905
+ assert.equal(r.pr, null); assert.equal(r.cost_usd, 0); assert.equal(r.minutes, 0);
906
+ assert.match(r.detail, /^interrupted: upgrade v1\.51\.0→v1\.52\.0; .+; requeued$/);
907
+ }
908
+ assert.match(ir.find((r) => r.issue === 6).detail, /adopt failed: ledger unreadable/, "the adopt error is kept");
909
+ assert.match(ir.find((r) => r.issue === 7).detail, /no adoptable pid or handle/);
910
+ assert.match(ir.find((r) => r.issue === 3).detail, /ended without a result/);
911
+ assert.deepEqual(updates.filter((r) => r.code === "run.interrupted").length, 4, "onUpdate sees the same rows");
912
+ assert.deepEqual(decisions.filter((d) => d.what === "requeued (interrupted)").map((d) => d.issue).sort(), [3, 5, 6, 7]);
913
+ assert.deepEqual(interrupted.map(([n]) => n).sort(), [3, 5, 6, 7]);
914
+ assert.ok(interrupted.every(([, c]) => c === "upgrade v1.51.0→v1.52.0"));
915
+ assert.deepEqual(launched.sort(), [3, 5, 6, 7], "each requeued lane runs once");
916
+ assert.deepEqual(rows.map((r) => [r.issue, r.outcome]).sort((a, b) => a[0] - b[0]), [[3, "merged"], [5, "merged"], [6, "merged"], [7, "merged"]], "the interrupted row is not a result");
917
+ assert.deepEqual(saved.deferrals, {}, "no deferral consumed");
918
+ assert.deepEqual(saved.engineErrors, {}, "no engine-error consumed");
919
+ assert.equal(saved.engineVersion, "1.52.0", "the running engine version is saved");
920
+ });
921
+ it("#5204: without a version change the cause is a dispatcher restart; a lane with a result is settled, not interrupted", async () => {
922
+ let saved = stateOf({ 1: { startedAt: 1, pid: 11 }, 2: { startedAt: 1, pid: 22 } }, { engineVersion: "1.52.0" });
923
+ const logged = [];
924
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: (r) => logged.push(r) };
925
+ const adopt = async (n) => (n === 1 ? { terminalReason: "merged", pr: 101 } : null);
926
+ const rows = await orchestrate({ issues: [], parallel: 2, pollMs: 5, readBody: async () => "", store, adopt, version: "1.52.0",
927
+ runOne: async (n) => ({ terminalReason: "merged", pr: 100 + n }) });
928
+ const ir = logged.filter((r) => r.code === "run.interrupted");
929
+ assert.deepEqual(ir.map((r) => r.issue), [2]);
930
+ assert.match(ir[0].detail, /^interrupted: dispatcher restart; the lane ended without a result; requeued$/);
931
+ assert.deepEqual(rows.map((r) => [r.issue, r.outcome, r.pr]), [[1, "merged", 101], [2, "merged", 102]]);
932
+ });
933
+ });
934
+
884
935
  describe("#4528: a full sandbox pool (sandbox.capacity) is never capped", () => {
885
936
  it("sandbox.capacity is uncapped and honours retryInSeconds; other codes still cap at maxDeferrals", () => {
886
937
  assert.deepEqual(deferPolicy({ code: "sandbox.capacity" }, { now: 0, deferrals: 99 }), { delayMs: 60000, host: true });
@@ -1017,13 +1068,13 @@ describe("#4550: forgedock orchestrate --requeue", () => {
1017
1068
  assert.match(bad.refused[1].reason, /needs-human/);
1018
1069
  assert.deepEqual(b.readRequeued(), []);
1019
1070
  assert.ok(b.readReport(), "nothing changed");
1020
- const ok = await quiet(() => orchestrateFromCli(["--requeue", "b1", "5", "--reason", "decided"], { batchRoot: root, io }));
1071
+ const ok = await queued(quiet(() => orchestrateFromCli(["--requeue", "b1", "5", "--reason", "decided"], { batchRoot: root, io })));
1021
1072
  assert.deepEqual(ok.requeued, [5]);
1022
1073
  assert.equal(b.readRequeued()[0].reason, "decided");
1023
1074
  assert.equal(b.readReport(), null, "the finished batch is reopened for --resume");
1024
1075
  });
1025
1076
 
1026
- it("#5000: --add/--requeue on a finished batch without a daemon clear the report and say it is not hosted", async () => {
1077
+ it("#5000/#5314: --add/--requeue on a finished batch without a daemon queue the issue and fail loudly (nothing is scheduled)", async () => {
1027
1078
  const root = tmpDir("batch-add-finished-");
1028
1079
  const b = openBatch(root, "b1");
1029
1080
  b.writePlan({ argv: ["1"], repo: "o/r" });
@@ -1032,14 +1083,13 @@ describe("#4550: forgedock orchestrate --requeue", () => {
1032
1083
  const io = { gh: async () => JSON.stringify({ state: "OPEN", labels: [], body: "", author: { login: "a" } }) };
1033
1084
  const lines = [];
1034
1085
  const run = async (argv) => { const l = console.log; console.log = (x) => lines.push(String(x)); try { return await orchestrateFromCli(argv, { batchRoot: root, io }); } finally { console.log = l; } };
1035
- const add = await run(["--add", "b1", "7"]);
1036
- assert.deepEqual(add.added, [7]);
1086
+ await assert.rejects(run(["--add", "b1", "7"]), /NOTHING is scheduled.*--resume b1/);
1087
+ assert.deepEqual(b.readAdded(), [7], "the add itself is kept");
1037
1088
  assert.equal(b.readReport(), null, "a plain add reopens the finished batch for --resume");
1038
- assert.ok(lines.some((l) => /NOT hosted.*--resume b1/.test(l)), "the CLI says nothing is scheduled yet");
1089
+ assert.ok(lines.some((l) => /NOT hosted.*--resume b1/.test(l)));
1039
1090
  b.writeReport({ rows: [], report: "x" });
1040
1091
  lines.length = 0;
1041
- const rq = await run(["--requeue", "b1", "5"]);
1042
- assert.deepEqual(rq.requeued, [5]);
1092
+ await assert.rejects(run(["--requeue", "b1", "5"]), /NOTHING is scheduled/);
1043
1093
  assert.equal(b.readReport(), null);
1044
1094
  assert.ok(lines.some((l) => /NOT hosted.*--resume b1/.test(l)));
1045
1095
  });
@@ -1520,14 +1570,35 @@ describe("#5161 transient engine-error retries", () => {
1520
1570
  });
1521
1571
  });
1522
1572
 
1573
+ describe("#5242 an add that lands after the last dispatch pass keeps the batch open", () => {
1574
+ it("a run that receives an add in its post-loop tail writes no report.json, so the add is not stranded", async () => {
1575
+ const batchRoot = tmpDir("tail-add-batch-");
1576
+ const leanIo = { gh: async (a) => (a[0] === "issue" && a[1] === "view" ? JSON.stringify({ body: "", milestone: null, comments: [], author: { login: "x" } }) : a[0] === "repo" ? "main\n" : "[]"), git: async (a) => (a[0] === "ls-remote" ? "abc\tref\n" : "") };
1577
+ const deps = { dir: tmpDir("tail-add-run-"), batchRoot, allowTmpfs: true, emitTelemetry: async () => {}, leanIo, pollMs: 5, preflight: null,
1578
+ io: { gh: async (a) => (a[0] === "issue" ? JSON.stringify({ body: "", state: "OPEN" }) : "o/r\n"), git: async () => "" },
1579
+ alertConfig: { get tailAdd() { openBatch(batchRoot, readdirSync(batchRoot)[0]).addIssues([9]); return null; } }, // read by the post-loop alerts step
1580
+ leanModule: { runCore: async (o) => ({ terminalReason: "merged", pr: o.issue, cost_usd: 0, wall_ms: 1 }) } };
1581
+ const adm = tmpDir("tail-add-adm-"), prevCwd = process.cwd();
1582
+ writeFileSync(join(adm, "forge.yaml"), "engine:\n admission_enabled: false\n");
1583
+ process.chdir(adm);
1584
+ const l = console.log; console.log = () => {};
1585
+ try { await orchestrateFromCli(["1", "--repo", "o/r", "--no-prefilter"], deps); } finally { console.log = l; process.chdir(prevCwd); }
1586
+ const b = openBatch(batchRoot, readdirSync(batchRoot)[0]);
1587
+ assert.deepEqual(b.unrunAdds(), [9], "the add was never drained");
1588
+ assert.equal(b.readReport(), null, "the batch stays open for a re-host or --resume");
1589
+ });
1590
+ });
1591
+
1523
1592
  describe("#5167 early batch health in runBatch", () => {
1524
1593
  // #1 and #3 are roots, #2 depends on #1. #3 runs until `release`; the captured T+15 timer fires while it runs.
1525
- const mk = ({ fail }) => {
1594
+ const mk = ({ fail, merged = false }) => {
1526
1595
  const timers = [], comments = [], notes = [], gate = { open: null };
1527
1596
  const released = new Promise((r) => { gate.open = r; });
1528
1597
  const bodies = { 1: "", 2: "Depends on #1", 3: "" };
1529
1598
  const leanIo = { gh: async (a) => {
1530
1599
  if (a[0] === "issue" && a[1] === "comment") { if (/FORGE:BATCH-HEALTH/.test(a.at(-1))) comments.push(a); return ""; }
1600
+ if (merged && a[0] === "issue" && a[1] === "view" && a.some((x) => /closedByPullRequestsReferences/.test(x))) return JSON.stringify({ state: "CLOSED", labels: [], comments: [], closedByPullRequestsReferences: [{ number: 99 }] });
1601
+ if (merged && a[0] === "pr" && a[1] === "view") return JSON.stringify({ state: "MERGED" });
1531
1602
  if (a[0] === "issue" && a[1] === "view") return JSON.stringify({ body: bodies[a[2]] ?? "", milestone: { title: "M Two" }, comments: [], author: { login: "x" } });
1532
1603
  return a[0] === "repo" ? "main\n" : "[]";
1533
1604
  }, git: async (a) => (a[0] === "ls-remote" ? "abc\tref\n" : "") };
@@ -1544,9 +1615,32 @@ describe("#5167 early batch health in runBatch", () => {
1544
1615
  };
1545
1616
  const capture = async (fn) => { const lines = [], l = console.log; console.log = (...a) => lines.push(a.join(" ")); try { await fn(); } finally { console.log = l; } return lines; };
1546
1617
 
1618
+ it("#5243 roots whose issues were merged by hand raise no BATCH UNHEALTHY and no requeue suggestion", async () => {
1619
+ const { deps, timers, comments, gate } = mk({ fail: true, merged: true });
1620
+ let id = null;
1621
+ const adm = tmpDir("bh-adm-"), prevCwd = process.cwd();
1622
+ writeFileSync(join(adm, "forge.yaml"), "engine:\n admission_enabled: false\n");
1623
+ process.chdir(adm);
1624
+ const lines = await capture(async () => {
1625
+ const run = orchestrateFromCli(["1", "2", "3", "--repo", "o/r", "--no-prefilter", "--parallel", "3"], deps);
1626
+ try {
1627
+ await until(() => { id = readdirSyncSafe(deps.batchRoot)[0]; return id && JSON.parse(readFileSync(join(deps.batchRoot, id, "state.json"), "utf8")).results?.[1]; });
1628
+ await timers[0].fn();
1629
+ await until(() => existsSync(join(deps.batchRoot, id, "health.json")), 5000);
1630
+ } finally { gate.open(); await run; process.chdir(prevCwd); }
1631
+ });
1632
+ assert.ok(!lines.some((l) => /BATCH UNHEALTHY|--requeue/.test(l)), lines.join("\n"));
1633
+ assert.equal(comments.length, 0);
1634
+ assert.equal(JSON.parse(readFileSync(join(deps.batchRoot, id, "health.json"), "utf8")).alertedAt, undefined);
1635
+ });
1636
+
1547
1637
  it("#5167 roots ending engine-error raise one BATCH UNHEALTHY at T+15 with recovery commands, on every channel", async () => {
1548
1638
  const { deps, timers, comments, notes, gate } = mk({ fail: true });
1549
1639
  let id = null;
1640
+ // Three concurrent roots must not depend on host memory: the live local lane cap (#4777) reads forge.yaml from the cwd.
1641
+ const adm = tmpDir("bh-adm-"), prevCwd = process.cwd();
1642
+ writeFileSync(join(adm, "forge.yaml"), "engine:\n admission_enabled: false\n");
1643
+ process.chdir(adm);
1550
1644
  const lines = await capture(async () => {
1551
1645
  const run = orchestrateFromCli(["1", "2", "3", "--repo", "o/r", "--no-prefilter", "--parallel", "3"], deps);
1552
1646
  try {
@@ -1555,7 +1649,7 @@ describe("#5167 early batch health in runBatch", () => {
1555
1649
  await timers[0].fn();
1556
1650
  await until(() => existsSync(join(deps.batchRoot, id, "health.json")) && JSON.parse(readFileSync(join(deps.batchRoot, id, "health.json"), "utf8")).alertedAt, 5000);
1557
1651
  await until(() => notes.length === 1, 5000);
1558
- } finally { gate.open(); await run; }
1652
+ } finally { gate.open(); await run; process.chdir(prevCwd); }
1559
1653
  });
1560
1654
  assert.ok(lines.some((l) => /^health checks: T\+15 \d\d:\d\dZ, T\+60 \d\d:\d\dZ, and at batch end; forgedock status --batch /.test(l)), lines.join("\n"));
1561
1655
  const alerts = lines.filter((l) => /^BATCH UNHEALTHY /.test(l));
@@ -1616,6 +1710,16 @@ describe("#5168: --requeue accepts engine-error; a claude login failure is held,
1616
1710
  assert.equal(rows.find((x) => x.issue === 1).requeued.prior[0].outcome, "engine-error");
1617
1711
  });
1618
1712
 
1713
+ it("#5203 --requeue accepts a quota-paused pending issue; other pending issues stay refused not terminal", () => {
1714
+ const b = openBatch(tmpDir("batch-requeue-5203-"), "b1");
1715
+ b.writePlan({ argv: ["1"], repo: "o/r" });
1716
+ b.store.save({ order: [1, 2, 3], pending: [1, 2], results: { 3: { outcome: "merged" } }, notBefore: { 1: 9e12, 2: 9e12 }, quota: { 1: { cost_usd: 0, minutes: 1, resumeAt: 9e12, rotations: 0 } } });
1717
+ const r = b.requeue([1, 2, 3], { reason: "accounts usable", by: "operator" });
1718
+ assert.deepEqual(r.requeued, [1]);
1719
+ assert.deepEqual(r.refused, [{ issue: 2, reason: "not terminal" }, { issue: 3, reason: "not terminal" }]);
1720
+ assert.deepEqual(b.readRequeued().map((e) => e.issue), [1]);
1721
+ });
1722
+
1619
1723
  it("#5168 deferPolicy holds backend.auth like a usage limit: never capped, never counted", () => {
1620
1724
  assert.deepEqual(deferPolicy({ code: "backend.auth", retryInSeconds: 900 }, { now: 0, deferrals: 99, maxDeferrals: 3 }), { delayMs: 900_000, hold: true });
1621
1725
  assert.equal(deferPolicy({ code: "backend.auth" }, { now: 0 }).hold, true);
@@ -0,0 +1,54 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * One writer per lane branch (#5333): a lock file in the repo's shared git dir, so every worktree and every engine
5
+ * process on the host sees it. A builder session (implement, recovery, fix-up) holds it while it may commit.
6
+ * Also the lane's teardown ordering helper: a worktree is removed only after its builder processes have exited.
7
+ */
8
+ import { closeSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { pidAlive } from "./sched.mjs";
11
+
12
+ export const LOCK_DIR = "forge-branch-locks";
13
+
14
+ const lockPath = (gitCommonDir, branch) => join(gitCommonDir, LOCK_DIR, encodeURIComponent(String(branch)));
15
+ const readHolder = (p) => { try { const j = JSON.parse(readFileSync(p, "utf8")); return j && typeof j === "object" ? j : null; } catch { return null; } };
16
+
17
+ /**
18
+ * Take the writer lock of `branch`. The same `owner` re-enters. A holder whose pid is dead is taken over. Otherwise wait up to
19
+ * `waitMs` (0: do not wait), then report the holder.
20
+ * @returns {Promise<{ok: true, release: () => void} | {ok: false, holder: object|null}>}
21
+ */
22
+ export async function acquireBranchLock({ gitCommonDir, branch, owner, pid = process.pid, alive = pidAlive, waitMs = 0, pollMs = 500, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now }) {
23
+ const p = lockPath(gitCommonDir, branch);
24
+ mkdirSync(join(gitCommonDir, LOCK_DIR), { recursive: true });
25
+ const deadline = now() + waitMs;
26
+ for (;;) {
27
+ try {
28
+ const fd = openSync(p, "wx");
29
+ try { writeSync(fd, JSON.stringify({ owner, pid, branch, at: now() })); } finally { closeSync(fd); }
30
+ return { ok: true, release: () => { if (readHolder(p)?.owner === owner) { try { unlinkSync(p); } catch { /* already gone */ } } } };
31
+ } catch (e) {
32
+ if (e?.code !== "EEXIST") throw e;
33
+ }
34
+ const holder = readHolder(p);
35
+ if (holder?.owner === owner) return { ok: true, release: () => {} }; // re-entrant: the outer holder releases
36
+ if (!holder || !alive(holder.pid)) { try { unlinkSync(p); } catch { /* raced: retry */ } continue; } // stale or unreadable: take over
37
+ if (now() >= deadline) return { ok: false, holder };
38
+ await sleep(pollMs);
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Wait until none of `pids` is alive: SIGTERM was already sent; after `graceMs` escalate to SIGKILL, then wait `killMs` more.
44
+ * @returns {Promise<number[]>} the pids still alive (empty: all exited)
45
+ */
46
+ export async function waitPidsExit(pids, { alive, kill, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = 5000, killMs = 3000, stepMs = 250 }) {
47
+ const live = () => pids.filter((x) => alive(x));
48
+ let left = live();
49
+ for (let t = 0; left.length && t < graceMs; t += stepMs) { await sleep(stepMs); left = live(); }
50
+ if (!left.length) return [];
51
+ for (const x of left) { try { kill(x, "SIGKILL"); } catch { /* gone */ } }
52
+ for (let t = 0; left.length && t < killMs; t += stepMs) { await sleep(stepMs); left = live(); }
53
+ return left;
54
+ }
@@ -0,0 +1,49 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { existsSync, writeFileSync, mkdirSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { acquireBranchLock, waitPidsExit, LOCK_DIR } from "./branchlock.mjs";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+
8
+ const common = () => tmpDir("branchlock-");
9
+
10
+ describe("branch writer lock (#5333)", () => {
11
+ it("two sessions cannot hold the same lane branch at once; the second reports the holder", async () => {
12
+ const dir = common();
13
+ const a = await acquireBranchLock({ gitCommonDir: dir, branch: "feat/issue-7-lean", owner: "A", alive: () => true });
14
+ assert.equal(a.ok, true);
15
+ const b = await acquireBranchLock({ gitCommonDir: dir, branch: "feat/issue-7-lean", owner: "B", alive: () => true });
16
+ assert.equal(b.ok, false);
17
+ assert.equal(b.holder.owner, "A");
18
+ });
19
+ it("another branch is independent; release lets the waiter in", async () => {
20
+ const dir = common();
21
+ const a = await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "A", alive: () => true });
22
+ assert.equal((await acquireBranchLock({ gitCommonDir: dir, branch: "y", owner: "B", alive: () => true })).ok, true);
23
+ let waited = 0;
24
+ const b = await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "B", alive: () => true, waitMs: 1000, pollMs: 10, sleep: async () => { if (++waited === 2) a.release(); } });
25
+ assert.equal(b.ok, true);
26
+ assert.ok(waited >= 2);
27
+ });
28
+ it("the same owner re-enters without releasing the outer hold", async () => {
29
+ const dir = common();
30
+ const a = await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "A", alive: () => true });
31
+ const again = await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "A", alive: () => true });
32
+ again.release();
33
+ assert.equal(existsSync(join(dir, LOCK_DIR, "x")), true);
34
+ a.release();
35
+ assert.equal(existsSync(join(dir, LOCK_DIR, "x")), false);
36
+ });
37
+ it("a lock whose holder died is taken over", async () => {
38
+ const dir = common();
39
+ mkdirSync(join(dir, LOCK_DIR));
40
+ writeFileSync(join(dir, LOCK_DIR, "x"), JSON.stringify({ owner: "dead", pid: 999999 }));
41
+ assert.equal((await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "B", alive: () => false })).ok, true);
42
+ });
43
+ it("waitPidsExit escalates to SIGKILL and reports survivors", async () => {
44
+ const alive = new Set([1, 2]), kills = [];
45
+ const left = await waitPidsExit([1, 2], { alive: (p) => alive.has(p), kill: (p, s) => { kills.push([p, s]); if (p === 1) alive.delete(p); }, sleep: async () => {}, graceMs: 500, killMs: 500 });
46
+ assert.deepEqual(left, [2]);
47
+ assert.deepEqual(kills, [[1, "SIGKILL"], [2, "SIGKILL"]]);
48
+ });
49
+ });
@@ -0,0 +1,72 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Context-ceiling helpers (#5346): the per-size ceiling, the pre-build restart prediction and the restart hand-off facts.
5
+ * Pure: no I/O. The ceiling itself (#4390) is applied in lean.mjs `builder()`; the mid-edit deferral lives in runner.mjs.
6
+ */
7
+
8
+ import { SIZES } from "./budget.mjs";
9
+
10
+ /** A session that starts above this share of the ceiling restarts whatever the builder does. */
11
+ export const PREDICT_SHARE = 0.6;
12
+ /** Rough bytes per token for source and prose. */
13
+ export const BYTES_PER_TOKEN = 4;
14
+ export const HANDOFF_FILES_MAX = 30;
15
+ const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
16
+
17
+ /** `engine.context_ceiling_by_size`: "S=80000,M=120000,L=160000" or `{S, M, L}`; a null when absent or without a valid entry. 0 = no ceiling for that size. */
18
+ export function parseCeilingBySize(engine) {
19
+ const raw = engine?.context_ceiling_by_size ?? engine?.contextCeilingBySize;
20
+ if (raw == null || raw === "") return null;
21
+ const out = {};
22
+ const put = (k, v) => { const key = String(k).trim().toUpperCase(); if (SIZES.includes(key) && /^\d+$/.test(String(v).trim())) out[key] = Number(String(v).trim()); };
23
+ if (typeof raw === "object" && !Array.isArray(raw)) for (const [k, v] of Object.entries(raw)) put(k, v);
24
+ else for (const part of String(raw).split(/[,;]/)) { const [k, v] = part.split(/[=:]/); if (v !== undefined) put(k, v); }
25
+ return Object.keys(out).length ? out : null;
26
+ }
27
+
28
+ /** The ceiling for a lane of `size`: its per-size entry, else the global one. */
29
+ export function ceilingFor(size, { tokens = 0, bySize = null } = {}) {
30
+ const v = bySize && SIZES.includes(size) ? bySize[size] : undefined;
31
+ return Number.isFinite(v) && v >= 0 ? v : tokens;
32
+ }
33
+
34
+ /**
35
+ * Whether a build session is predicted to restart. `promptBytes` is the build prompt, `fileBytes` the named files' size.
36
+ * `certain`: the named files alone exceed the ceiling, so any session that reads them restarts.
37
+ * `predicted`: the start (prompt + files) is at or above PREDICT_SHARE of the ceiling.
38
+ */
39
+ export function predictRestart({ ceiling = 0, promptBytes = 0, fileBytes = 0 } = {}) {
40
+ const files = Math.ceil(Math.max(0, fileBytes) / BYTES_PER_TOKEN);
41
+ const estimate = Math.ceil(Math.max(0, promptBytes) / BYTES_PER_TOKEN) + files;
42
+ if (!(ceiling > 0)) return { predicted: false, certain: false, estimate, ceiling };
43
+ const certain = files > ceiling;
44
+ return { predicted: certain || estimate >= ceiling * PREDICT_SHARE, certain, estimate, ceiling };
45
+ }
46
+
47
+ /** The tool uses' first edit: the 1-based turn (distinct assistant message) of the first Edit/Write, null when none. */
48
+ export function firstEditTurn(toolUses) {
49
+ const msgs = new Map();
50
+ for (const u of Array.isArray(toolUses) ? toolUses : []) {
51
+ if (!u || typeof u !== "object") continue;
52
+ const k = u.msg ?? `#${msgs.size}`;
53
+ if (!msgs.has(k)) msgs.set(k, msgs.size + 1);
54
+ if (EDIT_TOOLS.has(u.name)) return msgs.get(k);
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** What the stopped session had established: files read, files edited (deduped, capped) and the last tool call. */
60
+ export function handoffFacts(toolUses, lastTool = null) {
61
+ const read = new Set(), edited = new Set();
62
+ for (const u of Array.isArray(toolUses) ? toolUses : []) {
63
+ if (!u || typeof u.path !== "string" || !u.path) continue;
64
+ if (EDIT_TOOLS.has(u.name)) edited.add(u.path); else if (u.name === "Read") read.add(u.path);
65
+ }
66
+ const readOnly = [...read].filter((p) => !edited.has(p));
67
+ return { read: readOnly.slice(0, HANDOFF_FILES_MAX), edited: [...edited].slice(0, HANDOFF_FILES_MAX), readMore: Math.max(0, readOnly.length - HANDOFF_FILES_MAX),
68
+ last: lastTool && typeof lastTool.name === "string" ? { name: lastTool.name, input: String(lastTool.input ?? "").slice(0, 200) } : null };
69
+ }
70
+
71
+ /** Appended to the build prompt of a lane predicted to restart: read the named files, do not survey. */
72
+ export const NARROW_NOTE = "\n\nContext is tight on this lane (the contract's files and this prompt already fill much of the session window): read only the files the contract names and the code you edit, skip surveys of unrelated code, and make each edit as soon as you know it.";
@@ -0,0 +1,54 @@
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 { parseCeilingBySize, ceilingFor, predictRestart, handoffFacts, firstEditTurn, HANDOFF_FILES_MAX } from "./ceiling.mjs";
6
+ import { contextRestartPrompt } from "./prompts.mjs";
7
+ import { toolStats } from "./toolstats.mjs";
8
+
9
+ describe("context ceiling helpers (#5346)", () => {
10
+ it("parseCeilingBySize reads a string or object, ignores junk, null when empty", () => {
11
+ assert.deepEqual(parseCeilingBySize({ context_ceiling_by_size: "S=80000, m=120000;L:0" }), { S: 80000, M: 120000, L: 0 });
12
+ assert.deepEqual(parseCeilingBySize({ context_ceiling_by_size: { L: "160000", X: "5" } }), { L: 160000 });
13
+ assert.equal(parseCeilingBySize({ context_ceiling_by_size: "big" }), null);
14
+ assert.equal(parseCeilingBySize({}), null);
15
+ });
16
+ it("ceilingFor uses the size entry (0 included), else the global ceiling", () => {
17
+ assert.equal(ceilingFor("L", { tokens: 120000, bySize: { L: 160000 } }), 160000);
18
+ assert.equal(ceilingFor("L", { tokens: 120000, bySize: { L: 0 } }), 0);
19
+ assert.equal(ceilingFor("M", { tokens: 120000, bySize: { L: 160000 } }), 120000);
20
+ assert.equal(ceilingFor(null, { tokens: 120000, bySize: { L: 1 } }), 120000);
21
+ });
22
+ it("predictRestart: 60% of the ceiling predicts, named files over the ceiling are certain, off never predicts", () => {
23
+ assert.equal(predictRestart({ ceiling: 100000, promptBytes: 4000, fileBytes: 0 }).predicted, false);
24
+ const near = predictRestart({ ceiling: 100000, promptBytes: 4000, fileBytes: 4 * 59000 });
25
+ assert.deepEqual([near.predicted, near.certain, near.estimate], [true, false, 60000]);
26
+ assert.deepEqual([predictRestart({ ceiling: 100000, fileBytes: 4 * 100001 }).predicted, predictRestart({ ceiling: 100000, fileBytes: 4 * 100001 }).certain], [true, true]);
27
+ assert.equal(predictRestart({ ceiling: 0, fileBytes: 1e9 }).predicted, false);
28
+ });
29
+ it("handoffFacts dedupes, drops read files that were edited, caps the list and keeps the last tool", () => {
30
+ const uses = [{ name: "Read", path: "a" }, { name: "Read", path: "a" }, { name: "Read", path: "b" }, { name: "Edit", path: "b" }, { name: "Bash", cmd: "ls" },
31
+ ...Array.from({ length: 40 }, (_, i) => ({ name: "Read", path: `f${i}` }))];
32
+ const h = handoffFacts(uses, { name: "Edit", input: "x" });
33
+ assert.deepEqual(h.edited, ["b"]);
34
+ assert.equal(h.read.length, HANDOFF_FILES_MAX);
35
+ assert.equal(h.readMore, 11);
36
+ assert.deepEqual(h.last, { name: "Edit", input: "x" });
37
+ assert.deepEqual(handoffFacts(null, null), { read: [], edited: [], readMore: 0, last: null });
38
+ });
39
+ it("firstEditTurn counts distinct assistant messages; toolStats exposes it", () => {
40
+ const uses = [{ msg: "m1", name: "Read", path: "a" }, { msg: "m1", name: "Read", path: "b" }, { msg: "m2", name: "Bash" }, { msg: "m3", name: "Write", path: "c" }];
41
+ assert.equal(firstEditTurn(uses), 3);
42
+ assert.equal(firstEditTurn([{ msg: "m1", name: "Read" }]), null);
43
+ assert.equal(toolStats(uses).first_edit_turn, 3);
44
+ assert.equal("first_edit_turn" in toolStats([{ msg: "m1", name: "Read", path: "a" }]), false);
45
+ });
46
+ it("the restart prompt carries the established block only when there are facts, and keeps its other sections", () => {
47
+ const base = contextRestartPrompt({ stat: "1 file", diff: "d", base: "origin/x", check: "", ceiling: 5 });
48
+ assert.doesNotMatch(base, /<established>/);
49
+ const p = contextRestartPrompt({ stat: "1 file", diff: "d", base: "origin/x", check: "ok", ceiling: 5, established: handoffFacts([{ name: "Read", path: "src/a.js" }], { name: "Read", input: "i" }) });
50
+ assert.match(p, /<established>\nFiles it read[^\n]*\n- src\/a\.js\nIts last tool call: Read i/);
51
+ assert.match(p, /<diff_stat base="origin\/x">/);
52
+ assert.match(p, /Last validate result/);
53
+ });
54
+ });
@@ -0,0 +1,43 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5202: the engine pushes a `wip(forge): checkpoint` commit mid-run (context ceiling, timeout, turn budget). A fresh builder
5
+ * session may then amend or squash it locally, so origin/<branch> is no longer an ancestor of HEAD and the next plain push is
6
+ * rejected non-fast-forward. Before a push, when every remote-only commit is such a checkpoint that this worktree produced or
7
+ * held (it is in the local reflog), it is merged in with `-s ours`: HEAD keeps the lane's own newer tree, the checkpoint stays in
8
+ * history (never lost) and the push stays a plain fast-forward (never force). Deterministic, 0 LLM calls; never throws.
9
+ */
10
+ const CHECKPOINT_PREFIX = "wip(forge): checkpoint";
11
+ const SEP = "\x1f";
12
+
13
+ /**
14
+ * @param {object} o
15
+ * @param {(args: string[]) => Promise<string>} o.git runs git in the lane worktree
16
+ * @param {string} o.branch the lane's own branch
17
+ * @returns {Promise<{state: "none"|"ok"|"reconciled"|"foreign"|"error", commits?: {sha: string, subject: string}[], sha?: string, error?: string}>}
18
+ */
19
+ export async function reconcileCheckpoints({ git, branch }) {
20
+ const out = async (args) => String(await git(args) ?? "").trim();
21
+ const ok = async (args) => { try { await git(args); return true; } catch { return false; } };
22
+ try {
23
+ try { await git(["fetch", "origin", branch]); } catch { /* offline or not pushed yet: the tracking ref we have decides */ }
24
+ const remote = `refs/remotes/origin/${branch}`;
25
+ if (!(await ok(["rev-parse", "--verify", "-q", remote]))) return { state: "none" };
26
+ if (await ok(["merge-base", "--is-ancestor", remote, "HEAD"])) return { state: "ok" };
27
+ const commits = (await out(["log", `--format=%H${SEP}%s`, `HEAD..${remote}`])).split("\n").filter(Boolean).map((l) => {
28
+ const [sha, subject = ""] = l.split(SEP);
29
+ return { sha: sha.trim(), subject };
30
+ });
31
+ if (!commits.length) return { state: "ok" };
32
+ const known = new Set();
33
+ for (const ref of [`refs/heads/${branch}`, "HEAD"]) {
34
+ try { for (const s of (await out(["log", "-g", "--format=%H", ref])).split("\n")) if (s.trim()) known.add(s.trim()); } catch { /* no reflog */ }
35
+ }
36
+ if (commits.some((c) => !c.subject.startsWith(CHECKPOINT_PREFIX) || !known.has(c.sha))) return { state: "foreign", commits };
37
+ const tip = await out(["rev-parse", remote]);
38
+ await git(["merge", "-s", "ours", "--no-edit", "-m", `merge(forge): keep pushed checkpoint ${tip.slice(0, 10)} in history`, remote]);
39
+ return { state: "reconciled", commits, sha: tip };
40
+ } catch (e) {
41
+ return { state: "error", error: String(e?.stderr ?? e?.message ?? e).slice(0, 300) };
42
+ }
43
+ }
@@ -0,0 +1,95 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5202: a pushed checkpoint the lane amended locally is merged back in before the push, on a real temp git repo (bare origin + clone).
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { execFileSync } from "node:child_process";
7
+ import { writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { tmpDir } from "../tests/_tmp.mjs";
10
+ import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
11
+
12
+ const CLEAN = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^GIT_(AUTHOR|COMMITTER)_/.test(k)));
13
+ const ENV = { ...CLEAN, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null" };
14
+ const sh = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8", env: ENV, stdio: ["ignore", "pipe", "pipe"] }).trim();
15
+ const CKPT = "wip(forge): checkpoint after context ceiling";
16
+
17
+ function fixture() {
18
+ const root = tmpDir("reconcile-"), origin = join(root, "origin.git"), wt = join(root, "wt");
19
+ sh(root, "init", "--bare", "-b", "staging", origin);
20
+ sh(root, "clone", "-q", origin, wt);
21
+ sh(wt, "config", "user.name", "Lane Bot"); sh(wt, "config", "user.email", "lane@example.com");
22
+ const commit = (file, msg, dir = wt) => { writeFileSync(join(dir, file), `${file}\n`); sh(dir, "add", file); sh(dir, "commit", "-q", "-m", msg); return sh(dir, "rev-parse", "HEAD"); };
23
+ commit("base.txt", "base");
24
+ sh(wt, "push", "-q", "origin", "HEAD:staging");
25
+ sh(wt, "checkout", "-q", "-b", "feat/x");
26
+ const git = async (a) => execFileSync("git", a, { cwd: wt, encoding: "utf8", env: ENV, stdio: ["ignore", "pipe", "pipe"] }).trim();
27
+ return { root, origin, wt, commit, git, sh: (...a) => sh(wt, ...a) };
28
+ }
29
+ const isAncestor = (f, a, b) => { try { f.sh("merge-base", "--is-ancestor", a, b); return true; } catch { return false; } };
30
+
31
+ describe("reconcileCheckpoints (#5202)", () => {
32
+ it("#5202 a pushed checkpoint the lane amended is merged in: HEAD descends from it, the tree is kept, a plain push succeeds", async () => {
33
+ const f = fixture();
34
+ const ckpt = f.commit("a.txt", CKPT);
35
+ f.sh("push", "-q", "-u", "origin", "feat/x");
36
+ f.sh("commit", "-q", "--amend", "-m", "fix: a proper message");
37
+ f.commit("b.txt", "feat: more");
38
+ const tree = f.sh("rev-parse", "HEAD^{tree}");
39
+ assert.equal(isAncestor(f, ckpt, "HEAD"), false);
40
+ const r = await reconcileCheckpoints({ git: f.git, branch: "feat/x" });
41
+ assert.equal(r.state, "reconciled");
42
+ assert.equal(r.sha, ckpt);
43
+ assert.equal(r.commits.length, 1);
44
+ assert.equal(isAncestor(f, ckpt, "HEAD"), true);
45
+ assert.equal(f.sh("rev-parse", "HEAD^{tree}"), tree);
46
+ f.sh("push", "-q", "origin", "feat/x"); // plain push, no force
47
+ assert.equal(sh(f.origin, "rev-parse", "feat/x"), f.sh("rev-parse", "HEAD"));
48
+ });
49
+
50
+ it("#5202 a branch already ahead of origin is left alone", async () => {
51
+ const f = fixture();
52
+ f.commit("a.txt", CKPT);
53
+ f.sh("push", "-q", "-u", "origin", "feat/x");
54
+ const head = f.commit("b.txt", "feat: more");
55
+ assert.equal((await reconcileCheckpoints({ git: f.git, branch: "feat/x" })).state, "ok");
56
+ assert.equal(f.sh("rev-parse", "HEAD"), head);
57
+ });
58
+
59
+ it("#5202 an unpushed branch is 'none'", async () => {
60
+ const f = fixture();
61
+ f.commit("a.txt", "feat: a");
62
+ assert.equal((await reconcileCheckpoints({ git: f.git, branch: "feat/x" })).state, "none");
63
+ });
64
+
65
+ it("#5202 a remote-only commit that is not a checkpoint is 'foreign' and HEAD is unchanged", async () => {
66
+ const f = fixture();
67
+ f.commit("a.txt", "feat: a");
68
+ f.sh("push", "-q", "-u", "origin", "feat/x");
69
+ f.sh("commit", "-q", "--amend", "-m", "feat: a reworded");
70
+ const head = f.sh("rev-parse", "HEAD");
71
+ const r = await reconcileCheckpoints({ git: f.git, branch: "feat/x" });
72
+ assert.equal(r.state, "foreign");
73
+ assert.equal(f.sh("rev-parse", "HEAD"), head);
74
+ });
75
+
76
+ it("#5202 a checkpoint pushed from another clone (not in this reflog) is 'foreign'", async () => {
77
+ const f = fixture();
78
+ f.commit("a.txt", "feat: a");
79
+ f.sh("push", "-q", "-u", "origin", "feat/x");
80
+ const other = join(f.root, "other");
81
+ sh(f.root, "clone", "-q", "-b", "feat/x", f.origin, other);
82
+ sh(other, "config", "user.name", "Other"); sh(other, "config", "user.email", "other@example.com");
83
+ f.commit("c.txt", CKPT, other);
84
+ sh(other, "push", "-q", "origin", "feat/x");
85
+ const head = f.commit("b.txt", "feat: b");
86
+ const r = await reconcileCheckpoints({ git: f.git, branch: "feat/x" });
87
+ assert.equal(r.state, "foreign");
88
+ assert.equal(f.sh("rev-parse", "HEAD"), head);
89
+ });
90
+
91
+ it("#5202 git failures never throw", async () => {
92
+ const r = await reconcileCheckpoints({ git: async (a) => { if (a[0] === "fetch") throw new Error("offline"); if (a[0] === "rev-parse") return "x"; if (a[0] === "merge-base") throw new Error("no"); throw new Error("boom"); }, branch: "feat/x" });
93
+ assert.equal(r.state, "error");
94
+ });
95
+ });