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
@@ -2,10 +2,11 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import { laneBackendId } from "./limits.mjs";
5
+ import { parseExperiment, assignArm } from "../experiment.mjs";
5
6
  import assert from "node:assert/strict";
6
7
  import { tmpDir } from "../tests/_tmp.mjs";
7
8
  import { execFileSync } from "node:child_process";
8
- import { writeFileSync, existsSync, readFileSync, mkdirSync, symlinkSync, readdirSync } from "node:fs";
9
+ import { writeFileSync, existsSync, readFileSync, mkdirSync, symlinkSync, readdirSync, chmodSync } from "node:fs";
9
10
  import { join } from "node:path";
10
11
  import { runCore, contractHash, isProtectedLaneBranch, classifyBlock } from "./lean.mjs";
11
12
  import { parseFactsComment, normaliseFacts, renderFactsRecord, FACTS_MARKER } from "./facts.mjs";
@@ -21,10 +22,10 @@ import { mapRecord } from "../engine/telemetry-seam.mjs";
21
22
  import { readLog as readRepoLog } from "../engine/runlog.mjs";
22
23
  // #4432: the run log is keyed by repo + issue; every lane in this file runs in repo o/r.
23
24
  const readLog = (dir, issue, repo = "o/r") => readRepoLog(dir, issue, { repo });
24
- import { makeRunTmp, wrapLaneLimits, laneCapNotice, systemdRunAvailable, makeLeanRunner, requiredChecksFor, procsInDir, makeLeanIo, makeGhCache } from "./effects.mjs";
25
+ import { makeRunTmp, wrapLaneLimits, laneCapNotice, systemdRunAvailable, makeLeanRunner, requiredChecksFor, requiredChecksRead, procsInDir, makeLeanIo, makeGhCache } from "./effects.mjs";
25
26
  import { retrying, ghCacheRetry, refreshAuthOnce, GH_AUTH_RE, PUSH_TRANSIENT_RE } from "./retry.mjs";
26
27
  import { checkAdmission, hostParallelism } from "./admission.mjs";
27
- import { OUTCOME_CODES, ENV_VALIDATE_TIMEOUT, classifyNeedsHuman } from "../engine/outcome-codes.mjs";
28
+ import { OUTCOME_CODES, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, classifyNeedsHuman } from "../engine/outcome-codes.mjs";
28
29
  import * as refactorMod from "./refactor.mjs";
29
30
  import { readAdmission, readConformanceMode, readReviewIncomplete, readEnvConfig, readContextPack } from "../engine-cli.mjs";
30
31
  import { prepareToolchain } from "./toolchain.mjs";
@@ -38,6 +39,8 @@ const approxTokens = (s) => rawTokens(String(s).replaceAll(INSTALL_ROOT, "<root>
38
39
  process.env.FORGEDOCK_SCHED_DIR = tmpDir("lean-sched-");
39
40
 
40
41
  const WT = "/wt/lean-7";
42
+ /** #5333: the engine appends the stage-stamp rule to every builder prompt; strip it to compare against the bare template. */
43
+ const unstamp = (s) => String(s).replace(/\n\nStage notes: make the first line[^\n]*/, "");
41
44
  const STAGE_MD = {
42
45
  investigation: "**Verdict**: CONFIRMED\n**Confidence**: high\n**Severity**: medium\n**Task Type**: bug\n\n### What Was Claimed\nfoo breaks\n\n### What We Found\n- src/foo.js:3 derefs null\n\n### Root Cause\nfoo derefs null at src/foo.js:3\n\n### Affected Files\n- src/foo.js: add guard\n\n### Sibling Sweep\n- src/bar.js:8 same guard\n\n### History\nintroduced in abc123\n\n### Recommendation\nguard null\n\n### Related Issues\nnone",
43
46
  plan: "### Approach\nguard null in foo\n\n### Deliverables\n| File | Change | Why |\n| --- | --- | --- |\n| src/foo.js | add guard | avoid crash |\n\n### Acceptance Criteria\n- [ ] foo handles null\n\n### Implementation Order\n1. guard\n\n### Out of Scope\nrefactor: later\n\n### Risk Assessment\n| Risk | Severity | Mitigation |\n| --- | --- | --- |\n| none | low | test |",
@@ -79,7 +82,8 @@ function world(o = {}) {
79
82
  const writeStages = (keys) => { for (const k of keys) if (w.stages[k] != null) put(`${k}.md`, w.stages[k]); };
80
83
  w.writeStages = writeStages;
81
84
  w.io = {
82
- now: () => w.clock, sleep: async (ms) => { w.clock += ms; },
85
+ credExec: () => ({ status: 1 }), now: () => w.clock, // #5205: never the host's real cs-cred (a sandbox sets CS_CRED_BASE)
86
+ sleep: async (ms) => { w.clock += ms; },
83
87
  gh: async (a, opts) => {
84
88
  const k = a.slice(0, 2).join(" ");
85
89
  if (opts?.env) (w.ghEnvs ??= []).push(opts.env);
@@ -141,7 +145,7 @@ function world(o = {}) {
141
145
  if (a[0] === "diff" && a[1] === "--name-only") return w.changed.join("\n");
142
146
  if (a[0] === "diff" && a[1] === "--numstat") return w.numstat ?? "";
143
147
  if (a[0] === "ls-files") return [...new Set(["src/foo.js", "src/bar.js", "test/foo.test.js", ...w.changed])].join("\n");
144
- if (a[0] === "diff") return "diff --git a/src/foo.js b/src/foo.js\n+fix";
148
+ if (a[0] === "diff") return w.diffText ?? "diff --git a/src/foo.js b/src/foo.js\n+fix";
145
149
  if (a[0] === "merge-base" && a[1] === "--is-ancestor") { if ([...(o.shipped ?? []), ...(o.unusedAncestors ?? [])].includes(String(a[2]).replace(/^origin\//, ""))) return ""; throw new Error("not an ancestor"); } // #4593
146
150
  if (a[0] === "ls-remote" && String(a.at(-1)).startsWith("refs/heads/")) { const b = a.at(-1).slice("refs/heads/".length); return (o.branchesOnOrigin ?? ["staging", "main"]).includes(b) ? `abc\trefs/heads/${b}\n` : ""; }
147
151
  if (a[0] === "ls-remote") return w.remote;
@@ -409,7 +413,7 @@ describe("core work-on", () => {
409
413
  });
410
414
 
411
415
  it("a reviewer that judges a deferral unjustified gets the builder resumed to implement it; nothing is filed for it", async () => {
412
- const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "defer", why: "later", bucket: "new-issue" }] };
416
+ const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "defer", why: "later", bucket: "owner:rotate the key" }] };
413
417
  const rej = conf({ requirements: [{ id: "R1", status: "implemented", evidence: "src/foo.js:3", validated_by: "V1" }, { id: "R2", status: "deferred", deferral_ok: false, note: "one line in bar.js; do it now" }] }, k);
414
418
  const w = world({ contract: k, claims: [{ id: "R1", status: "implemented" }], reviews: [rej, rej] });
415
419
  const r = await run(w);
@@ -643,6 +647,36 @@ describe("core work-on", () => {
643
647
  assert.equal(classifyBlock({ summary: "V1 needs the prod key", block: { kind: "human", why: "credentials" } }, 1).kind, "human");
644
648
  });
645
649
 
650
+ it("#5342 classifyBlock: design-invalidated needs a decision and a why; the other kinds are unchanged", () => {
651
+ const ok = classifyBlock({ block: { kind: "design-invalidated", decision: "replay_store is optional", why: "the core loop needs it", epic: "#5", paths: ["src/a.ts"] } }, 7);
652
+ assert.deepEqual([ok.kind, ok.epic, ok.paths], ["design-invalidated", 5, ["src/a.ts"]]);
653
+ assert.equal(classifyBlock({ block: { kind: "design-invalidated", decision: "x" } }, 7).kind, "untyped");
654
+ assert.equal(classifyBlock({ block: { kind: "dependency", issues: [3] } }, 7).kind, "dependency");
655
+ });
656
+
657
+ it("#5342 a design-invalidated block files one amendment, holds the affected open siblings and the lane behind it, and requeues as dependency-open", async () => {
658
+ const w = depWorld({ changed: [], result: { status: "blocked", summary: "the store design is wrong", block: { kind: "design-invalidated", decision: "replay_store is optional", why: "core loop needs it", epic: 5 } } }, {});
659
+ const gh = w.io.gh;
660
+ const kid = (n) => ({ number: n, body: `**Parent**: #5\n`, labels: [], author: { login: "o" } });
661
+ w.io.gh = async (a) => {
662
+ if (a[0] === "issue" && a[1] === "list" && a.includes("--help")) return "JSON FIELDS\n author, body, labels, number\n";
663
+ if (a[0] === "issue" && a[1] === "list") return JSON.stringify([kid(8), kid(9), kid(7)]);
664
+ if (a[0] === "api" && /issues\?state=open/.test(a[1])) return "7\tOWNER\n8\tOWNER\n9\tOWNER\n";
665
+ if (a[0] === "issue" && a[1] === "view" && /^[789]$/.test(a[2]) && a.includes("body")) return JSON.stringify({ body: `**Parent**: #5\n` });
666
+ return gh(a);
667
+ };
668
+ const r = await run(w);
669
+ assert.equal(r.terminalReason, "dependency-open");
670
+ assert.equal(r.code, "design.invalidated");
671
+ assert.equal(w.created.length, 1);
672
+ assert.match(w.created[0][w.created[0].indexOf("--title") + 1], /^spike amendment: replay_store is optional/);
673
+ const held = w.edits.filter((e) => e[1] === "edit" && e.includes("--body")).map((e) => [e[2], e[e.indexOf("--body") + 1]]);
674
+ assert.deepEqual(held.map(([n]) => n).sort(), ["7", "8", "9"]);
675
+ for (const [, body] of held) assert.match(body, /^\*\*Depends on\*\*: #201$/m);
676
+ assert.ok(w.comments.some((c) => /FORGE:REPLAN/.test(c) && /#201/.test(c)));
677
+ noNeedsHuman(w);
678
+ });
679
+
646
680
  it("#4385 split siblings that declare a shared hub file are serialised (chained, no duplicate transitive edge); disjoint or undeclared files stay parallel", () => {
647
681
  const hub = ["src/domain/index.ts", "./src/domain/events.ts"];
648
682
  const BIG = { files: 40, lines: 2000 }; // #4396: shared or undeclared files are admitted only over the size budget
@@ -820,6 +854,16 @@ describe("core work-on", () => {
820
854
  assert.equal((await run(world({ contract }), { ...remote, hostCaps: { hostCapabilities: ["sops"] } })).terminalReason, "merged");
821
855
  });
822
856
 
857
+ it("#5331 a remote lane whose sandbox lacks a validate tool ends env.tool_missing before building; local placement is unchanged", async () => {
858
+ const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "promtool test rules r.yml" }] };
859
+ const remote = { placement: { where: "remote", reason: "mode remote" } };
860
+ const w = world({ contract }); w.io.probeCommand = async (a) => ({ rc: /promtool/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
861
+ const r = await run(w, { dir: tmpDir("lean-5331-"), ...remote });
862
+ assert.equal(r.code, "env.tool_missing");
863
+ const l = world({ contract }); l.io.probeCommand = async (a) => ({ rc: /promtool/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
864
+ assert.notEqual((await run(l, { placement: { where: "local", reason: "x" } })).code, "env.tool_missing");
865
+ });
866
+
823
867
  it("#4778 a relayed host capability does not end the remote lane before building; a failed relay still recovers locally", async () => {
824
868
  const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "promtool test rules r.yml" }] };
825
869
  const remote = { placement: { where: "remote", reason: "mode remote" }, hostCaps: { hostCapabilities: ["promtool"] } };
@@ -1089,6 +1133,16 @@ describe("conformance gate (frozen contract, precheck, structured review)", () =
1089
1133
  assert.match(traj(w).join("\n"), /left open \(follow-up pending\)/);
1090
1134
  });
1091
1135
 
1136
+ it("#5240 an unticked acceptance box whose requirement the review marks implemented still closes as completed, with no partial note", async () => {
1137
+ const body = "foo crashes on null input.\n\n- [ ] foo must handle a null argument without throwing.\n- Existing callers of foo keep working.";
1138
+ const w = world({ contract: CONTRACT, body, claims: [{ id: "R1", status: "implemented" }], reviews: [conf()] });
1139
+ const r = await run(w);
1140
+ assert.equal(r.terminalReason, "merged");
1141
+ assert.equal(w.closed.length, 1);
1142
+ assert.ok(!w.comments.some((c) => /Left open: partial/.test(c)));
1143
+ assert.doesNotMatch(traj(w).join("\n"), /left open as partial/);
1144
+ });
1145
+
1092
1146
  it("a tracking issue that is not open is not a tracking issue: the item stays pending and is recorded", async () => {
1093
1147
  const k = two("defer", { why: "w" });
1094
1148
  const w = world({ contract: k, claims: [{ id: "R1", status: "implemented" }], reviews: [conf({}, k)], issueStates: { 900: "CLOSED" } });
@@ -1492,6 +1546,22 @@ describe("conformance shadow mode (the default)", () => {
1492
1546
  assert.ok(ran[0].env && typeof ran[0].env === "object", "the rerun gets the lane env");
1493
1547
  }
1494
1548
  });
1549
+ it("#5371 a remote lane whose frozen validate fails ends env.validate_placement (output tail kept); the local recovery lane keeps the real failure terminal", async () => {
1550
+ const v = [{ id: "V1", command: "node --test test/foo.test.js", exit: 1 }];
1551
+ const rerun = async () => ({ rc: 1, output: "1 failed\nTOKEN=abcd1234secretvalue\nassertion x" });
1552
+ const w = world({ validation: v }); w.io.runCommand = rerun;
1553
+ const r = await run(w, { conformance: "enforce", placement: { where: "remote", reason: "mode remote" } });
1554
+ assert.equal(r.code, ENV_VALIDATE_PLACEMENT); assert.equal(classifyNeedsHuman(r), "recoverable"); assert.equal(w.merges.length, 0);
1555
+ assert.equal(builders(w).length, 2, "no builder resume");
1556
+ assert.match(nhBody(w), /assertion x/); assert.doesNotMatch(nhBody(w), /abcd1234secretvalue/);
1557
+ const l = world({ validation: v }); l.io.runCommand = rerun;
1558
+ const lr = await run(l, { conformance: "enforce", placement: { where: "local", reason: "x" } });
1559
+ assert.notEqual(lr.code, ENV_VALIDATE_PLACEMENT);
1560
+ const rec = world({ validation: v }); rec.io.runCommand = rerun;
1561
+ assert.notEqual((await run(rec, { conformance: "enforce", placement: { where: "local", reason: "x" }, recover: { code: ENV_VALIDATE_PLACEMENT, attempt: 1, final: true } })).code, ENV_VALIDATE_PLACEMENT);
1562
+ const ok = world({ validation: v }); ok.io.runCommand = async () => ({ rc: 0, output: "" });
1563
+ assert.equal((await run(ok, { conformance: "enforce", placement: { where: "local", reason: "x" }, recover: { code: ENV_VALIDATE_PLACEMENT, attempt: 1, final: true } })).terminalReason, "merged");
1564
+ });
1495
1565
  it("#4906 a validate rerun that times out (rc 124) ends env.validate_timeout: recoverable, no builder resume, never conformance.unimplemented", async () => {
1496
1566
  const v = [{ id: "V1", command: "node --test test/foo.test.js", exit: 124 }];
1497
1567
  for (const conformance of ["shadow", "enforce"]) {
@@ -1715,7 +1785,7 @@ describe("conformance shadow mode (the default)", () => {
1715
1785
  });
1716
1786
 
1717
1787
  it("#4160 shadow files accepted deferrals with track(), the same as enforce, and the PR links them", async () => {
1718
- const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "defer", why: "w", bucket: "new-issue" }] };
1788
+ const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "defer", why: "w", bucket: "owner:rotate the key" }] };
1719
1789
  const w = world({ contract: k, claims: [{ id: "R1", status: "implemented" }], reviews: [conf({}, k)] });
1720
1790
  assert.equal((await runShadow(w)).terminalReason, "merged");
1721
1791
  assert.equal(w.followups.length, 1); assert.match(w.followups[0].items[0].key, /^R2: /);
@@ -1748,8 +1818,16 @@ describe("conformance shadow mode (the default)", () => {
1748
1818
  assert.deepEqual(rs.conformance, { mode: "shadow", would: "nonconforming", risk: false });
1749
1819
  });
1750
1820
 
1751
- it("#4398 #5152 an investigation whose question is deferred closes partial (completed), carried forward in the tracking issue", async () => {
1821
+ it("#5207 shadow: an in-lane engineering deferral (bucket new-issue) resumes the builder once and is never filed", async () => {
1752
1822
  const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "defer", why: "w", bucket: "new-issue" }] };
1823
+ const w = world({ contract: k, claims: [{ id: "R1", status: "implemented" }], reviews: [conf({}, k), conf({}, k)] });
1824
+ const r = await runShadow(w);
1825
+ assert.equal(r.code, "conformance.unjustified_deferral"); assert.equal(w.followups.length, 0); assert.equal(w.merges.length, 0);
1826
+ assert.match(builders(w)[2][4], /R2 is in-lane engineering work \(bucket new-issue\): deliver it/);
1827
+ });
1828
+
1829
+ it("#4398 #5152 an investigation whose question is deferred closes partial (completed), carried forward in the tracking issue", async () => {
1830
+ const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "defer", why: "w", bucket: "owner:rotate the key" }] };
1753
1831
  const w = world({ title: "investigate(stealth): which signal is rejected", contract: k, claims: [{ id: "R1", status: "implemented" }], reviews: [conf({}, k)] });
1754
1832
  const r = await runShadow(w);
1755
1833
  assert.equal(r.terminalReason, "merged"); assert.equal(r.close, "partial");
@@ -1791,7 +1869,7 @@ describe("conformance shadow mode (the default)", () => {
1791
1869
  const ra = await runShadow(a);
1792
1870
  assert.equal(ra.terminalReason, "merged"); assert.equal(ra.close, undefined);
1793
1871
  assert.deepEqual(a.closed.map((x) => x[x.indexOf("--reason") + 1]), ["completed"]);
1794
- const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "defer", why: "w", bucket: "new-issue" }] };
1872
+ const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "defer", why: "w", bucket: "owner:rotate the key" }] };
1795
1873
  const b = world({ contract: k, claims: [{ id: "R1", status: "implemented" }], reviews: [conf({}, k)] });
1796
1874
  await runShadow(b);
1797
1875
  assert.deepEqual(b.closed.map((x) => x[x.indexOf("--reason") + 1]), ["completed"]);
@@ -1968,9 +2046,9 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
1968
2046
  assert.equal(hotspotBuildRule(facts([], { file_lines: 1000, growth_lines: 50 })).trim(), "Don't grow a file over 1000 lines by more than 50 lines. Put new code next to it.");
1969
2047
  assert.equal(hotspotBuildRule(null), ""); assert.equal(hotspotBuildRule(facts([], { enabled: false })), "");
1970
2048
  const plan = builderPlanPrompt(7) + hotspotPlanNote(facts([HOT, { ...HOT, path: "a/b.py" }, { ...HOT, path: "c/d.py" }]));
1971
- // 1850: #4404 (verify out_of_band) and #4396 (split size rule) grew the plan prompt to ~1803 tokens on CI paths; 1900: #4589 (check timeout is not a block, one block-rule line). 2050: #4724 (deferred-row bucket rule).
1972
- assert.ok(approxTokens(plan) <= 2150, `plan prompt with hotspots is ${approxTokens(plan)} tokens`);
1973
- assert.ok(approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([]))) <= 1650, `implement prompt with the hotspot rule is ${approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([])))} of 1650 tokens`); // 1600: #4591 (never hand-name migration files) and #4596 (i18n translate rule), one line each; 1650: #4726 (e2e rule)
2049
+ // 1850: #4404 (verify out_of_band) and #4396 (split size rule) grew the plan prompt to ~1803 tokens on CI paths; 1900: #4589 (check timeout is not a block, one block-rule line). 2050: #4724 (deferred-row bucket rule). 1675 (hotspot case): #5284 (rubric prod_parity clause). 2375/1825: #5345 (self-check and pitfall lines).
2050
+ assert.ok(approxTokens(plan) <= 2425, `plan prompt with hotspots is ${approxTokens(plan)} tokens`);
2051
+ assert.ok(approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([]))) <= 1875, `implement prompt with the hotspot rule is ${approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([])))} of 1675 tokens`); // 1600: #4591 (never hand-name migration files) and #4596 (i18n translate rule), one line each; 1650: #4726 (e2e rule)
1974
2052
  });
1975
2053
 
1976
2054
  it("#4519 generated_paths: both prompts name the globs (even with the gate off), and an amendment adding one blocks", async () => {
@@ -2073,7 +2151,7 @@ describe("bug lanes freeze a red-green repro_test (#4271)", () => {
2073
2151
  const prev = process.env.FORGE_HOST_PARALLELISM; process.env.FORGE_HOST_PARALLELISM = "3";
2074
2152
  try { assert.equal((await run(w, { envSetup: "make setup", precheck: { commands: ["npm run lint"] } })).terminalReason, "merged"); }
2075
2153
  finally { if (prev === undefined) delete process.env.FORGE_HOST_PARALLELISM; else process.env.FORGE_HOST_PARALLELISM = prev; }
2076
- const lane = { UV_CACHE_DIR: "/c/uv", TMPDIR: w.envs[0].TMPDIR, FORGE_HOST_PARALLELISM: "3", PATH: "/rt/toolchain/bin:/usr/bin" };
2154
+ const lane = { UV_CACHE_DIR: "/c/uv", TMPDIR: w.envs[0].TMPDIR, FORGE_HOST_PARALLELISM: "3", FORGE_LANE_WORKTREE: "1", PATH: "/rt/toolchain/bin:/usr/bin" };
2077
2155
  assert.match(lane.TMPDIR, /\/runs\/7-/, "the builder ran with the run TMPDIR");
2078
2156
  assert.deepEqual(w.rgCalls.map((x) => x.env), [lane], "red-green gets the lane env, not the daemon's");
2079
2157
  assert.deepEqual(ran.map((a) => [a.command, a.env]), [["npm run lint", lane], ["node --test test/foo.test.js", lane]]);
@@ -2375,7 +2453,8 @@ describe("comment templates", () => {
2375
2453
  assert.equal((await run(w)).terminalReason, "merged");
2376
2454
  const f = parseFactsComment(w.comments.find((c) => markerOf(c) === "FORGE:FACTS"));
2377
2455
  assert.deepEqual(f.rejected, [{ approach: "detection-only guard", why: "hides the cause" }]);
2378
- assert.deepEqual(f.baselines, [{ command: "node --test test/foo.test.js", exit: 0 }]);
2456
+ assert.equal(f.baselines.length, 1); assert.deepEqual({ ...f.baselines[0], head: undefined }, { command: "node --test test/foo.test.js", exit: 0, head: undefined }); // #5331: the baseline also records the head it ran on
2457
+ assert.match(f.baselines[0].head, /^[0-9a-f]{7,40}$/);
2379
2458
  assert.ok(f.files.length > 0 && !f.files.some((x) => x.startsWith(".forge-lean/")), JSON.stringify(f.files));
2380
2459
  assert.ok(!scopeText({ title: "t", body: "b" }, [{ body: w.comments.find((c) => markerOf(c) === "FORGE:FACTS") }]).includes("detection-only"));
2381
2460
  });
@@ -2392,7 +2471,7 @@ describe("comment templates", () => {
2392
2471
  });
2393
2472
 
2394
2473
  it("live posting: stage notes appear while the builder session is still running", async () => {
2395
- const until = async (wd, marker) => { for (let i = 0; i < 300 && !wd.comments.some((c) => c.includes(`<!-- ${marker} -->`)); i++) await new Promise((r) => setTimeout(r, 10)); return wd.comments.map(markerOf); };
2474
+ const until = async (wd, marker) => { for (let i = 0; i < 1000 && !wd.comments.some((c) => c.includes(`<!-- ${marker} -->`)); i++) await new Promise((r) => setTimeout(r, 10)); return wd.comments.map(markerOf); };
2396
2475
  const w = world({ builder: async (wd, put, kind) => {
2397
2476
  wd.liveSeen ??= {};
2398
2477
  if (kind === "plan") {
@@ -2428,8 +2507,8 @@ describe("comment templates", () => {
2428
2507
 
2429
2508
  it("plan and implement prompts carry the stage templates and the contract schema within budget", () => {
2430
2509
  const plan = builderPlanPrompt(7), impl = builderImplementPrompt();
2431
- assert.ok(approxTokens(plan) <= 2050, `plan prompt is ${approxTokens(plan)} tokens`); // 2050: #4769 (activation-row rule); 2000: #4730 (owner-step remainder); 1950: #4724 (deferred-row bucket rule)
2432
- assert.ok(approxTokens(impl) <= 1650, `implement prompt is ${approxTokens(impl)} of 1650 tokens`); // 1650: #4726 e2e rule; 1550: #4596 i18n translate rule
2510
+ assert.ok(approxTokens(plan) <= 2325, `plan prompt is ${approxTokens(plan)} tokens`); // 2075: #5284 (prod_parity plan line); 2050: #4769 (activation-row rule); 2000: #4730 (owner-step remainder); 1950: #4724 (deferred-row bucket rule) // 2325: #5333 (git stash rule + stage stamp line)
2511
+ assert.ok(approxTokens(impl) <= 1850, `implement prompt is ${approxTokens(impl)} of 1700 tokens`); // 1650: #4726 e2e rule; 1550: #4596 i18n translate rule // 1850: #5333 (git stash rule + stage stamp)
2433
2512
  for (const h of ["### What Was Claimed", "### What We Found", "### Root Cause", "### Affected Files", "### Sibling Sweep", "### History", "### Recommendation", "### Related Issues",
2434
2513
  "investigation.md", "contract.json", "PLANNING ONLY", '"requirements"', '"deliverables"', '"preserve"', '"validate"', "verbatim", "defer", "post-deploy"]) assert.ok(plan.includes(h), h);
2435
2514
  for (const h of ["### Approach", "### Changes", "### Acceptance Criteria Status", "### Verification", "### Notes", "implementation.md", "result.json",
@@ -2637,7 +2716,7 @@ describe("run-issue routing", () => {
2637
2716
 
2638
2717
  it("bad --path errors; --retry is rejected on the core path", async () => {
2639
2718
  await assert.rejects(runFromCli(["7", "--lane", "staging", "--path", "bogus"], mk()), /--path must be/);
2640
- await assert.rejects(runFromCli(["7", "--lane", "staging", "--repo", "o/r", "--retry"], mk()), /not supported with the core path/);
2719
+ await assert.rejects(runFromCli(["7", "--lane", "staging", "--repo", "o/r", "--retry"], mk()), /only works with the legacy pipeline/);
2641
2720
  assert.deepEqual(ENGINE_PATHS, ["core", "full", "lean", "auto"]);
2642
2721
  });
2643
2722
  });
@@ -3184,6 +3263,12 @@ describe("requiredChecksFor: classic protection + rulesets (#4158)", () => {
3184
3263
  const { gh } = stub({ classic: new Error("HTTP 404"), rules: new Error("HTTP 404") });
3185
3264
  assert.deepEqual(await requiredChecksFor({ gh, repo: "o/r", lane: "staging" }), []);
3186
3265
  });
3266
+ it("requiredChecksRead flags a non-404 failure as unreadable and a 404 as an answer (#5382)", async () => {
3267
+ const e403 = stub({ classic: new Error("gh: Resource not accessible (HTTP 403)"), rules: [] });
3268
+ assert.deepEqual(await requiredChecksRead({ gh: e403.gh, repo: "o/r", lane: "staging" }), { checks: [], unreadable: true });
3269
+ const e404 = stub({ classic: new Error("HTTP 404: Branch not protected"), rules: new Error("HTTP 404") });
3270
+ assert.deepEqual(await requiredChecksRead({ gh: e404.gh, repo: "o/r", lane: "staging" }), { checks: [], unreadable: false });
3271
+ });
3187
3272
  it("a ruleset-derived required check is polled before the merge", async () => {
3188
3273
  const w = world();
3189
3274
  const { gh } = stub({ classic: new Error("HTTP 404"), rules: [{ type: "required_status_checks", parameters: { required_status_checks: [{ context: "build" }] } }] });
@@ -3532,6 +3617,127 @@ describe("usage limit, lease takeover, worktree setup, run tmp (#4101-#4104)", (
3532
3617
  assert.equal(sent.length, 1);
3533
3618
  });
3534
3619
 
3620
+ // #5205: a rotator with pick() relaunches the limited phase pinned to another account (real claude + CLAUDE_CONFIG_DIR), no pause.
3621
+ const smartRotator = (o = {}) => { const marked = [], picks = [];
3622
+ return { ...fakeRotator({ accounts: [{ n: 1 }, { n: 2 }, { n: 3 }] }), marked, picks, accountOfPid: (pid) => pid - 100, realClaude: () => "/real/claude", configDir: (n) => `/h/.claude-${n}`,
3623
+ markLimited: (n, until) => { marked.push([n, until]); return true; },
3624
+ pick: ({ exclude }) => { picks.push([...exclude.keys()]); return o.none ? { account: null, earliestReset: o.none } : { account: [1, 2, 3].find((n) => !exclude.has(n)) ?? null, earliestReset: 7e6 }; } }; };
3625
+ const spawnAs = (w, err, times) => { const orig = w.io.runner; const sent = []; let n = 0;
3626
+ w.io.runner = async (c) => { if (c.role === "builder") { const acct = c.env?.CLAUDE_CONFIG_DIR ? Number(c.env.CLAUDE_CONFIG_DIR.split("-").at(-1)) : 1;
3627
+ c.onSpawn?.({ pid: 100 + acct }); sent.push({ prompt: c.prompt, resume: c.resume ?? null, bin: c.bin ?? null, dir: c.env?.CLAUDE_CONFIG_DIR ?? null }); if (n++ < times) throw err; } return orig(c); }; return sent; };
3628
+
3629
+ it("#5205 3 accounts, the first limited: the phase relaunches pinned to another account with no pause, rotations = 1", async () => {
3630
+ const w = world(); const sleeps = []; const progress = []; const dir = tmpDir("core-");
3631
+ const s0 = w.io.sleep; w.io.sleep = async (ms) => { sleeps.push(ms); return s0(ms); };
3632
+ const sent = spawnAs(w, limitErr({ resetAtEpochMs: 3 * 3600 * 1000, resetAt: "8:30pm" }), 1);
3633
+ const rot = smartRotator(); w.io.rotator = rot;
3634
+ const r = await run(w, { dir, onProgress: (p) => progress.push(p) });
3635
+ assert.equal(r.terminalReason, "merged");
3636
+ assert.equal(r.rotations, 1);
3637
+ assert.deepEqual(r.limited, [{ account: 1, until: 3 * 3600 * 1000 }]);
3638
+ assert.deepEqual(rot.marked, [[1, 3 * 3600 * 1000]], "the limited account is marked");
3639
+ assert.deepEqual(rot.picks[0], [], "#5236: the preflight pick before the first spawn");
3640
+ assert.deepEqual(rot.picks[1], [1], "the limited account is excluded");
3641
+ assert.deepEqual({ ...sent[1], bin: null, dir: null }, { ...sent[0], bin: null, dir: null }, "same prompt and resume");
3642
+ assert.equal(sent[1].bin, "/real/claude"); assert.equal(sent[1].dir, "/h/.claude-2");
3643
+ assert.equal(sleeps.includes(3 * 3600 * 1000), false);
3644
+ assert.equal(progress.some((p) => p.event === "phase_paused"), false);
3645
+ const log = readLog(dir, 7);
3646
+ assert.equal(log.some((e) => e.event === "PHASE_RATE_LIMITED"), false);
3647
+ assert.ok(log.some((e) => e.event === "PHASE_ACCOUNT_ROTATED" && e.from === 1 && e.to === 2));
3648
+ });
3649
+
3650
+ it("#5268 the shim sets the account after exec: the first read at spawn is null, the limit-time re-read excludes the limited account", async () => {
3651
+ const w = world(); const sent = spawnAs(w, limitErr({ resetAtEpochMs: 3 * 3600 * 1000, resetAt: "8:30pm" }), 1);
3652
+ const rot = smartRotator(); let reads = 0; const real = rot.accountOfPid; rot.accountOfPid = (pid) => (++reads === 1 ? null : real(pid)); w.io.rotator = rot;
3653
+ const r = await run(w);
3654
+ assert.equal(r.terminalReason, "merged");
3655
+ assert.deepEqual(rot.marked, [[1, 3 * 3600 * 1000]], "the account read late is marked limited");
3656
+ assert.deepEqual(rot.picks[1], [1], "and excluded from the next pick");
3657
+ assert.equal(sent[1].dir, "/h/.claude-2");
3658
+ });
3659
+
3660
+ it("#5205 every account limited: rotations stop at the account count; pick none defers with tokenbaton's earliest reset", async () => {
3661
+ const w = world();
3662
+ const sent = spawnAs(w, limitErr({ resetAtEpochMs: 3 * 3600 * 1000, resetAt: "8:30pm" }), 99);
3663
+ w.io.rotator = smartRotator();
3664
+ const r = await run(w);
3665
+ assert.equal(r.terminalReason, "deferred"); assert.equal(r.code, "quota.exhausted"); // #5236
3666
+ assert.equal(sent.length, 3, "one call per account, never the limited one again");
3667
+ assert.equal(r.resetAtEpochMs, 7e6, "held until the earliest reset pick() reports");
3668
+ assert.equal(r.rotations, 2);
3669
+ const w2 = world(); spawnAs(w2, limitErr({ resetAtEpochMs: 3600 * 1000 }), 99); w2.io.rotator = smartRotator({ none: 5 * 3600 * 1000 });
3670
+ const r2 = await run(w2);
3671
+ assert.equal(r2.code, "quota.exhausted"); assert.equal(r2.resetAtEpochMs, 5 * 3600 * 1000, "not the limited account's own reset");
3672
+ });
3673
+
3674
+ it("#5236 weekly limit with a reset >1h away re-picks and continues on an account with room, no pause", async () => {
3675
+ const w = world(); const sleeps = []; const s0 = w.io.sleep; w.io.sleep = async (ms) => { sleeps.push(ms); return s0(ms); };
3676
+ const sent = spawnAs(w, limitErr({ resetAtEpochMs: 30 * 3600 * 1000, resetAt: "Nov 9, 2pm" }), 1);
3677
+ w.io.rotator = smartRotator();
3678
+ const r = await run(w);
3679
+ assert.equal(r.terminalReason, "merged");
3680
+ assert.equal(sent[1].dir, "/h/.claude-2");
3681
+ assert.equal(sleeps.includes(30 * 3600 * 1000), false);
3682
+ });
3683
+
3684
+ it("#5236 no account has room: the lane never spawns, ends quota.exhausted (not backend.auth) with the earliest reset and a QUOTA_EXHAUSTED event", async () => {
3685
+ const w = world(); const dir = tmpDir("core-");
3686
+ const sent = spawnAs(w, new Error("unused"), 0);
3687
+ w.io.rotator = smartRotator({ none: 5 * 3600 * 1000 });
3688
+ const r = await run(w, { dir });
3689
+ assert.equal(r.terminalReason, "deferred");
3690
+ assert.equal(r.code, "quota.exhausted");
3691
+ assert.equal(r.resetAtEpochMs, 5 * 3600 * 1000);
3692
+ assert.equal(sent.length, 0, "no spawn through the shim (it would fall back to the default profile)");
3693
+ assert.ok(readLog(dir, 7).some((e) => e.event === "QUOTA_EXHAUSTED" && e.earliestReset === 5 * 3600 * 1000));
3694
+ });
3695
+
3696
+ it("#5236 --pick fails (the rotator throws): the lane never falls back to the default profile, ends quota.exhausted", async () => {
3697
+ const w = world(); const dir = tmpDir("core-");
3698
+ const sent = spawnAs(w, new Error("unused"), 0);
3699
+ w.io.rotator = { ...smartRotator({ none: 0 }), pick: () => { throw new Error("pick failed"); } };
3700
+ const r = await run(w, { dir });
3701
+ assert.equal(r.terminalReason, "deferred"); assert.equal(r.code, "quota.exhausted");
3702
+ assert.equal(sent.length, 0, "no spawn under the default profile");
3703
+ });
3704
+
3705
+ it("#5236 a login failure while the pool is exhausted is quota.exhausted, not backend.auth; with room it stays backend.auth", async () => {
3706
+ const mk = () => Object.assign(new Error("Failed to authenticate. API Error: 401"), { code: "CLI_BACKEND_FAILED", authFailure: true }); // fresh: the lane marks the error it defers
3707
+ const w = world(); spawnAs(w, mk(), 99);
3708
+ const rot = smartRotator(); let calls = 0; const pick = rot.pick;
3709
+ rot.pick = (a) => (calls++ === 0 ? pick(a) : { account: null, earliestReset: 4 * 3600 * 1000 }); // room at the preflight, none after the failure
3710
+ w.io.rotator = rot;
3711
+ const r = await run(w);
3712
+ assert.equal(r.code, "quota.exhausted");
3713
+ const w2 = world(); spawnAs(w2, mk(), 99); w2.io.rotator = smartRotator();
3714
+ assert.equal((await run(w2)).code, "backend.auth");
3715
+ });
3716
+
3717
+ it("#5205 sandbox (CS_CRED_BASE, no rotator): cs-cred claude --limited reports the limit and re-sends at once; its failure defers as before", async () => {
3718
+ const w = world(); const calls = [];
3719
+ const sent = captureBuilders(w, limitErr({ resetAtEpochMs: 3 * 3600 * 1000, resetAt: "8:30pm" }), 1);
3720
+ w.io.rotator = null; w.io.env = { CS_CRED_BASE: "http://agent/sandboxes/x/creds" }; w.io.credExec = (a) => { calls.push(a); return { status: 0 }; };
3721
+ const r = await run(w);
3722
+ assert.equal(r.terminalReason, "merged"); assert.equal(r.rotations, 1);
3723
+ assert.deepEqual(calls, [["claude", "--limited", String(3 * 3600)]]);
3724
+ assert.deepEqual(sent[1], sent[0]);
3725
+ const w2 = world(); captureBuilders(w2, limitErr({ resetAtEpochMs: 3 * 3600 * 1000, resetAt: "8:30pm" }), 99);
3726
+ w2.io.rotator = null; w2.io.env = { CS_CRED_BASE: "x" }; let n = 0; w2.io.credExec = () => { n++; return { status: 1 }; };
3727
+ const r2 = await run(w2);
3728
+ assert.equal(r2.code, "rate_limited"); assert.equal(n, 1, "a 429 from the router falls through to the existing defer");
3729
+ });
3730
+
3731
+ it("#5205 no rotator and no sandbox: the pause path is unchanged (no cs-cred, no rotation facts)", async () => {
3732
+ const w = world(); const sleeps = []; let cred = 0;
3733
+ const s0 = w.io.sleep; w.io.sleep = async (ms) => { sleeps.push(ms); return s0(ms); };
3734
+ failFirstBuilder(w, limitErr({ resetAtEpochMs: 90000, resetAt: "8:30pm" }));
3735
+ w.io.rotator = null; w.io.env = {}; w.io.credExec = () => { cred++; return { status: 0 }; };
3736
+ const r = await run(w);
3737
+ assert.equal(r.terminalReason, "merged"); assert.ok(sleeps.includes(90000));
3738
+ assert.equal(cred, 0); assert.equal(r.rotations, undefined); assert.equal(r.limited, undefined);
3739
+ });
3740
+
3535
3741
  it("#4101 a non-limit runner error is still engine-error", async () => {
3536
3742
  const w = world(); failFirstBuilder(w, new Error("boom"));
3537
3743
  assert.equal((await run(w)).terminalReason, "engine-error");
@@ -4224,8 +4430,12 @@ describe("batch robustness (#4112-#4115)", () => {
4224
4430
  const r = await run(w);
4225
4431
  assert.equal([r.terminalReason, r.code].join("/"), "deferred/lease.held");
4226
4432
  });
4227
- it("#4920 a non-ff push nobody else owns, and any other permanent rejection, stay needs-human", async () => {
4228
- assert.equal((await run(ownerProbe(world({ pushErrors: [NONFF] })))).terminalReason, "needs-human");
4433
+ it("#5202 a non-ff push no other lane owns ends engine-error engine.push_diverged, never needs-human", async () => {
4434
+ const r = await run(ownerProbe(world({ pushErrors: [NONFF] })));
4435
+ assert.equal([r.terminalReason, r.code].join("/"), "engine-error/engine.push_diverged");
4436
+ assert.match(r.detail, /non-fast-forward.*no other lane owns feat\/issue-7-lean/s);
4437
+ });
4438
+ it("#4920 any other permanent push rejection (protected branch) stays needs-human", async () => {
4229
4439
  assert.equal((await run(ownerProbe(world({ pushErrors: ["remote: error: GH006: Protected branch update failed"] }), { open: [{ number: 4919 }] }))).terminalReason, "needs-human");
4230
4440
  });
4231
4441
  it("#4920 two sandbox lanes (pid 1) get distinct lease holders, and a lease another lane wrote meanwhile defers this lane", async () => {
@@ -4941,7 +5151,7 @@ describe("verify-by-CI (#4167): ci mode runs the heavy checks on CI and feeds fa
4941
5151
  const w = withCi(world());
4942
5152
  const r = await run(w);
4943
5153
  assert.equal(r.terminalReason, "merged"); assert.equal(w.ci.dispatched.length, 0);
4944
- assert.equal(builders(w)[1][4], builderImplementPrompt());
5154
+ assert.ok(unstamp(builders(w)[1][4]).startsWith(builderImplementPrompt()), "#5347: only the opening-batch note follows the base prompt");
4945
5155
  assert.doesNotMatch(traj(w)[0], /\| Verify \|/);
4946
5156
  });
4947
5157
 
@@ -5055,6 +5265,28 @@ describe("lane resource ledger + teardown on every exit path (#4179)", () => {
5055
5265
  assert.equal(existsSync(w.ledgerFile), false, `${label}: ledger cleared`);
5056
5266
  };
5057
5267
 
5268
+ /** #5333: SIGTERM while the builder runs; `proc` decides which pids stay alive after SIGTERM / SIGKILL. */
5269
+ const interruptedWith = async (stubborn) => {
5270
+ let td = null, out = null;
5271
+ const w = ledgered({ dirty: true, during: async (w2, c) => { if (!/PLANNING ONLY/.test(c.prompt) && !out) out = await td("SIGTERM"); } });
5272
+ w.alive = new Set([4242]); w.kills = [];
5273
+ w.io.sleep = async () => {};
5274
+ w.io.proc = { inDir: async () => [], alive: (pid) => w.alive.has(pid), kill: (pid, sig) => { w.kills.push([pid, sig]); w.seq.push(`kill-${sig}`); if (sig === "SIGKILL" && !stubborn) w.alive.delete(pid); } };
5275
+ await run(w, { onTeardown: (fn) => { td = fn; } });
5276
+ return w;
5277
+ };
5278
+ it("#5333 teardown removes the worktree only after the builder process exited (SIGKILL after the grace period)", async () => {
5279
+ const w = await interruptedWith(false);
5280
+ assert.deepEqual(w.kills, [[4242, "SIGKILL"]]);
5281
+ assert.ok(w.seq.indexOf("kill-SIGKILL") < w.seq.lastIndexOf("worktree-remove"), "worktree removed after the builder was gone");
5282
+ tornDown(w, "builder gone");
5283
+ });
5284
+
5285
+ it("#5333 a builder process that survives SIGKILL keeps the worktree (nothing is removed under a running builder)", async () => {
5286
+ const w = await interruptedWith(true);
5287
+ assert.equal(w.calls.filter((c) => c[1] === "worktree" && c[2] === "remove").length, 1, "only the setup remove ran");
5288
+ });
5289
+
5058
5290
  it("while the lane runs, the ledger on disk lists worktree, branch, run tmp and builder pid with owner/batch/lane/issue/created/expires (survives a crash)", async () => {
5059
5291
  const w = ledgered({ batch: "b1" });
5060
5292
  await run(w, { batchId: "b1" });
@@ -5161,6 +5393,46 @@ describe("lane resource ledger + teardown on every exit path (#4179)", () => {
5161
5393
  tornDown(w, sig);
5162
5394
  }
5163
5395
  });
5396
+
5397
+ // ---- #5334: a killed session still records the usage it streamed ----
5398
+ const KILLED = { input_tokens: 1000, output_tokens: 2000, cache_read_input_tokens: 100000, cache_creation_input_tokens: 10000 }; // sonnet tier: $0.1005
5399
+ const attemptsOf = (dir) => readLog(dir, 7).filter((e) => e.event === "PHASE_ATTEMPT_USAGE");
5400
+ it("#5334 SIGTERM mid-attempt: PHASE_ATTEMPT_USAGE with the session's turns and an estimated cost lands before RUN_TERMINAL; no turns 0 / model_ms 0", async () => {
5401
+ let td = null; const dir = tmpDir("core-sig-usage-");
5402
+ const w = ledgered({ dirty: true, during: async (w2, c) => { if (!/PLANNING ONLY/.test(c.prompt) && td) { c.session.snapshot = () => ({ usage: KILLED, turns: 7, toolUses: [] }); await new Promise((r) => setTimeout(r, 5)); await td("SIGTERM"); } } });
5403
+ const r = await run(w, { dir, onTeardown: (fn) => { td = fn; } });
5404
+ assert.equal(r.code, "run.interrupted");
5405
+ const log = readLog(dir, 7), a = attemptsOf(dir).filter((e) => e.turns === 7);
5406
+ assert.equal(a.length, 1, "one attempt for the interrupted session, not double counted by the builder's own catch");
5407
+ assert.equal(a[0].turns, 7); assert.deepEqual(a[0].usage, KILLED);
5408
+ assert.ok(Math.abs(a[0].cost_usd - 0.1005) / 0.1005 < 0.05, String(a[0].cost_usd)); assert.equal(a[0].cost_estimated, true);
5409
+ const term = log.find((e) => e.event === "RUN_TERMINAL");
5410
+ assert.ok(log.indexOf(a[0]) < log.indexOf(term));
5411
+ assert.ok(term.model_ms > 0, "model_ms is the session's time, not 0");
5412
+ });
5413
+
5414
+ it("#5334 a host kill and an idle kill each record the killed session's usage (turns, cost) before the retry", async () => {
5415
+ for (const kill of [{ code: "CLI_BACKEND_FAILED", signal: "SIGTERM", status: null }, { code: "CLI_IDLE", lastTool: null, children: [] }]) {
5416
+ const w = world({ dirty: true }); const dir = tmpDir("core-kill-usage-");
5417
+ const orig = w.io.runner; let n = 0;
5418
+ w.io.runner = async (c) => { if (c.role === "builder" && n++ === 1) throw Object.assign(new Error("killed"), kill, { usage: KILLED, turns: 5 }); return orig(c); };
5419
+ assert.equal((await run(w, { dir })).terminalReason, "merged");
5420
+ const k = attemptsOf(dir).find((e) => e.turns === 5);
5421
+ assert.ok(k, kill.code); assert.deepEqual(k.usage, KILLED);
5422
+ assert.ok(Math.abs(k.cost_usd - 0.1005) / 0.1005 < 0.05, String(k.cost_usd));
5423
+ assert.equal(k.cost_usd_delta, k.cost_usd);
5424
+ }
5425
+ });
5426
+
5427
+ it("#5334 a kill that streamed nothing is marked usage_unknown, never recorded as 0 turns", async () => {
5428
+ const w = world({ dirty: true }); const dir = tmpDir("core-kill-unknown-");
5429
+ const orig = w.io.runner; let n = 0;
5430
+ w.io.runner = async (c) => { if (c.role === "builder" && n++ === 1) throw Object.assign(new Error("idle"), { code: "CLI_IDLE", lastTool: null, children: [] }); return orig(c); };
5431
+ await run(w, { dir });
5432
+ const u = attemptsOf(dir).find((e) => e.usage_unknown === true);
5433
+ assert.ok(u); assert.equal(u.turns, null);
5434
+ assert.equal(readLog(dir, 7).find((e) => e.event === "RUN_TERMINAL").usage_unknown, true);
5435
+ });
5164
5436
  });
5165
5437
 
5166
5438
  describe("two repos with the same issue number on one host (#4432)", () => {
@@ -5405,6 +5677,25 @@ describe("local-mode CI fix rounds at merge and declared pre-PR check commands (
5405
5677
  assert.ok(log.findIndex((e) => e.event === "PRECHECK_COMMANDS") < log.findIndex((e) => e.event === "PR_OPENED"));
5406
5678
  });
5407
5679
 
5680
+ it("#5332 a precheck round whose only non-zero result is rc 124 does not resume the builder or end ci.red, and is never self_check green", async () => {
5681
+ const w = world(); const dir = tmpDir("core-");
5682
+ w.io.runCommand = async () => ({ rc: 124, output: "(timed out after 1s)" });
5683
+ const r = await run(w, { dir, precheck: { commands: ["make slow"] } });
5684
+ assert.equal(r.terminalReason, "merged");
5685
+ assert.equal(builders(w).filter((b) => /declared check commands failed/.test(b[4])).length, 0, "no builder resume");
5686
+ const pre = readLog(dir, 7).filter((e) => e.event === "PRECHECK_COMMANDS");
5687
+ assert.deepEqual(pre.map((e) => e.results[0].rc), [124]); assert.equal(pre.length, 1);
5688
+ assert.equal(pre[0].self_check, "timed_out");
5689
+ });
5690
+ it("#5332 with verify.precheck_block a timed-out check ends env.validate_timeout (not ci.red) naming the command and limit", async () => {
5691
+ const w = world();
5692
+ w.io.runCommand = async () => ({ rc: 124, output: "(timed out after 1s)" });
5693
+ const r = await run(w, { precheck: { commands: ["make slow"] }, verify: { ...parseVerify({}), precheckBlock: true } });
5694
+ assert.equal(r.code, ENV_VALIDATE_TIMEOUT); assert.equal(r.terminalReason, "needs-human"); assert.equal(w.merges.length, 0);
5695
+ assert.equal(builders(w).filter((b) => /declared check commands failed/.test(b[4])).length, 0);
5696
+ assert.match((w.comments.find((c) => c.includes("FORGE:NEEDS_HUMAN")) ?? ""), /`make slow` \(timed out after 1 s, exit 124\)/);
5697
+ });
5698
+
5408
5699
  it("#4585 verify.invariants run in the pre-PR round even with no learned commands, and the prompts carry the checklist", async () => {
5409
5700
  const w = world(); const ran = [];
5410
5701
  w.io.runCommand = async ({ command }) => { ran.push(command); return { rc: 0, output: "" }; };
@@ -5424,6 +5715,37 @@ describe("local-mode CI fix rounds at merge and declared pre-PR check commands (
5424
5715
  assert.ok(n >= 2, "the invariant is rerun after the builder fix round");
5425
5716
  });
5426
5717
 
5718
+ it("#5239 a guard failing only on the lane tree blocks the merge (ci.red), never merges", async () => {
5719
+ const w = world(); const ran = [];
5720
+ w.io.runCommand = async ({ command, cwd }) => { ran.push(cwd); return /basered-/.test(cwd) ? { rc: 0, output: "" } : { rc: 1, output: "bare 429 at app/routers/listing_feeds.py" }; };
5721
+ const r = await run(w, { verify: { invariants: ["bash scripts/guard.sh"] } });
5722
+ assert.equal(r.terminalReason, "needs-human"); assert.equal(r.code, "ci.red");
5723
+ assert.equal(w.merges.length, 0);
5724
+ assert.ok(ran.some((c) => /basered-/.test(c)), "the guard was also run on the base");
5725
+ });
5726
+
5727
+ it("#5239 a guard that also fails on the base defers the lane (base.red), comments on the introducing issue, no needs-human", async () => {
5728
+ const w = world(); const comments = [], gh = w.io.gh, git = w.io.git;
5729
+ w.io.runCommand = async () => ({ rc: 1, output: "bare 429 at app/routers/listing_feeds.py" });
5730
+ w.io.git = async (a, o) => (a[0] === "log" && a.includes("--format=%H%x1f%s%x1f%b") ? `${"a".repeat(40)}\x1ffeat: feeds (#39805)\x1f` : git(a, o));
5731
+ w.io.gh = async (a, o) => {
5732
+ if (a[0] === "issue" && a[1] === "view" && a[2] === "39805") return "OPEN";
5733
+ if (a[0] === "issue" && a[1] === "comment" && a[2] === "39805") { comments.push(a.at(-1)); return ""; }
5734
+ return gh(a, o);
5735
+ };
5736
+ const r = await run(w, { verify: { invariants: ["bash scripts/guard.sh"] } });
5737
+ assert.equal(r.terminalReason, "deferred"); assert.equal(r.code, "base.red");
5738
+ assert.equal(w.merges.length, 0);
5739
+ assert.equal(comments.length, 1); assert.match(comments[0], /FORGE:BASE_RED/);
5740
+ assert.equal(builders(w).length, 2, "no builder fix round spent on a base failure");
5741
+ });
5742
+
5743
+ it("#5239 verify.guard_block false keeps a failing invariant advisory", async () => {
5744
+ const w = world(); w.io.runCommand = async () => ({ rc: 1, output: "x" });
5745
+ const r = await run(w, { verify: { invariants: ["bash scripts/guard.sh"], guardBlock: false } });
5746
+ assert.notEqual(r.code, "base.red"); assert.notEqual(r.code, "ci.red");
5747
+ });
5748
+
5427
5749
  it("pre-PR: a passing set adds no builder turn; no commands configured runs nothing", async () => {
5428
5750
  const w = world(); let n = 0;
5429
5751
  w.io.runCommand = async () => { n++; return { rc: 0, output: "" }; };
@@ -5547,14 +5869,14 @@ describe("test map and repo facts caches (#4272)", () => {
5547
5869
  });
5548
5870
 
5549
5871
  it("neither file present: the same commands, events and prompts as without the feature", async () => {
5550
- const w = world(); const ran = recorder(w); w.io.fs.exists = async () => false;
5872
+ const w = world(); const ran = recorder(w); w.io.fs.exists = async (p) => p === WT;
5551
5873
  const dir = tmpDir("core-");
5552
5874
  assert.equal((await run(w, { dir, precheck: { commands: ["true", "make lint"] } })).terminalReason, "merged");
5553
5875
  assert.deepEqual(ran, ["true", "make lint"]);
5554
5876
  assert.deepEqual(readLog(dir, 7).filter((e) => e.event === "PRECHECK_COMMANDS").map(({ round, results, ...rest }) => [round, results, Object.keys(rest).filter((k) => k === "source")]),
5555
5877
  [[0, [{ command: "true", rc: 0, ms: 0 }, { command: "make lint", rc: 0, ms: 0 }], []]]);
5556
5878
  const [plan, impl] = builders(w);
5557
- assert.equal(plan[4].startsWith(builderPlanPrompt(7)), true); assert.equal(impl[4].startsWith(builderImplementPrompt("local")), true);
5879
+ assert.equal(unstamp(plan[4]).startsWith(builderPlanPrompt(7)), true); assert.equal(unstamp(impl[4]).startsWith(builderImplementPrompt("local")), true);
5558
5880
  for (const b of builders(w)) assert.doesNotMatch(b[4], /Repo facts/);
5559
5881
  assert.doesNotMatch(traj(w)[0], /test-map/);
5560
5882
  });
@@ -5562,11 +5884,11 @@ describe("test map and repo facts caches (#4272)", () => {
5562
5884
  it("repo-facts.json present: the builder prompts cite its path, never its content", async () => {
5563
5885
  const w = world(); recorder(w);
5564
5886
  w.files[FACTSF] = JSON.stringify({ version: 1, toolchain: { pm: { name: "pnpm", version: "9.9.9-SECRET" } } });
5565
- w.io.fs.exists = async (p) => p in w.files;
5887
+ w.io.fs.exists = async (p) => p === WT || p in w.files;
5566
5888
  assert.equal((await run(w)).terminalReason, "merged");
5567
5889
  const [plan, impl] = builders(w);
5568
5890
  for (const b of [plan, impl]) { assert.ok(b[4].includes(`are cached in ${FACTSF}`)); assert.doesNotMatch(b[4], /9\.9\.9-SECRET/); }
5569
- const w2 = world(); recorder(w2); w2.files["/repo/.forge/repo-facts.json"] = "{}"; w2.io.fs.exists = async (p) => p in w2.files;
5891
+ const w2 = world(); recorder(w2); w2.files["/repo/.forge/repo-facts.json"] = "{}"; w2.io.fs.exists = async (p) => p === WT || p in w2.files;
5570
5892
  assert.equal((await run(w2)).terminalReason, "merged");
5571
5893
  assert.ok(builders(w2)[0][4].includes("are cached in /repo/.forge/repo-facts.json"));
5572
5894
  });
@@ -5913,7 +6235,7 @@ describe("context pack modes (forge#4275)", () => {
5913
6235
  const r = await run(w, { dir, contextPack: { mode: "on" } });
5914
6236
  assert.equal(r.terminalReason, "merged");
5915
6237
  const plan = builders(w)[0][4];
5916
- assert.ok(plan.startsWith(builderPlanPrompt(7)));
6238
+ assert.ok(unstamp(plan).startsWith(builderPlanPrompt(7)));
5917
6239
  assert.match(plan, /Context pack \(hints, not proof[\s\S]*- #3 \[parent\] OPEN "Epic"[\s\S]*zebra protocol/);
5918
6240
  assert.equal(w.packCalls.length, 1);
5919
6241
  assert.equal(w.packCalls[0].base, "origin/staging");
@@ -6119,6 +6441,32 @@ describe("enumerating tests + sequence numbers at hand-off (#4322)", () => {
6119
6441
  assert.equal(w.dupArgs.cwd, WT);
6120
6442
  });
6121
6443
 
6444
+ it("#5348 an enumerating-test omission and a duplicate export the detectors name are fixed without a model session", async () => {
6445
+ const w = hworld({ missing: [MISS, []] }); const d = [DUP, []]; w.mech = [];
6446
+ w.io.duplicateExports = async () => (d.length > 1 ? d.shift() : d[0]);
6447
+ w.io.mechFix = {
6448
+ applyEnumerating: async ({ missing }) => { w.mech.push(["enum", missing.length]); return { applied: missing, remaining: [] }; },
6449
+ renameDuplicates: async ({ dups }) => { w.mech.push(["dup", dups.length]); return { applied: dups.map((x) => ({ ...x, renamedTo: "FeedUndo" })), remaining: [] }; },
6450
+ };
6451
+ assert.equal((await run(w)).terminalReason, "merged");
6452
+ assert.deepEqual(w.mech, [["enum", 1], ["dup", 1]]);
6453
+ assert.equal(builders(w).length, 2, "plan and build only: no fix session");
6454
+ assert.ok(w.calls.some((c) => c[0] === "git" && c[1] === "commit" && /enumerating fix applied by the engine/.test(c.join(" "))), "the mechanical edit is committed");
6455
+ assert.ok(w.calls.some((c) => c[0] === "git" && c[1] === "commit" && /duplicate fix applied by the engine/.test(c.join(" "))));
6456
+ });
6457
+
6458
+ it("#5348 what the engine cannot place goes to one narrow session that also carries the other pending narrow fix", async () => {
6459
+ const w = hworld({ missing: [MISS, []] }); const d = [DUP, []]; const seen = [];
6460
+ w.io.duplicateExports = async () => (d.length > 1 ? d.shift() : d[0]);
6461
+ w.io.mechFix = { applyEnumerating: async ({ missing }) => ({ applied: [], remaining: missing }), renameDuplicates: async ({ dups }) => ({ applied: [], remaining: dups }) };
6462
+ const inner = w.io.runner; w.io.runner = async (c) => { if (c.role === "builder") seen.push({ profile: c.profile ?? null, prompt: c.prompt }); return inner(c); };
6463
+ assert.equal((await run(w)).terminalReason, "merged");
6464
+ const fix = seen.filter((x) => x.profile === "narrow");
6465
+ assert.equal(fix.length, 1, "one narrow session for both findings");
6466
+ assert.match(fix[0].prompt, /fooNew[\s\S]*undoActivityAction/);
6467
+ assert.doesNotMatch(fix[0].prompt, /## Diff/);
6468
+ });
6469
+
6122
6470
  it("#4596 English copies in a locale catalog resume the builder once to translate; a leftover is an anomaly", async () => {
6123
6471
  const w = hworld(); const c = [[{ path: "messages/ta.json", key: "calendarView.day", value: "Day view", source: "messages/en.json" }], []]; w.cpCalls = 0;
6124
6472
  w.io.englishCopies = async (x) => { w.cpCalls++; w.cpArgs = x; return c.length > 1 ? c.shift() : c[0]; };
@@ -6251,6 +6599,24 @@ describe("enumerating tests + sequence numbers at hand-off (#4322)", () => {
6251
6599
  assert.equal(w.resolveArgs.partial, true);
6252
6600
  });
6253
6601
 
6602
+ it("#5340: a full-path lane whose contract touches a declared shared surface takes a reserved slot, released at finish", async () => {
6603
+ const w = dworld({ seq: [[]] }), declared = [];
6604
+ w.io.sequenceLease.declare = async (x) => { declared.push(x); };
6605
+ w.io.sequenceLease.undeclare = async () => {};
6606
+ const r = await run(w, { sharedSurfaces: ["src/foo.js", "src/gen.js => npm run gen"] });
6607
+ assert.equal(r.terminalReason, "merged");
6608
+ const slot = w.leases.acquired.find((a) => a.lane === "*");
6609
+ assert.deepEqual(slot.dirs, ["surface:src/foo.js"]);
6610
+ assert.deepEqual(declared[0].surfaces, ["src/foo.js"]);
6611
+ assert.ok(w.leases.released >= 1, "slot released at teardown");
6612
+ });
6613
+
6614
+ it("#5340: no declared shared surface takes no surface lease", async () => {
6615
+ const w = dworld({ seq: [[]] });
6616
+ await run(w);
6617
+ assert.ok(!w.leases.acquired.some((a) => a.lane === "*"));
6618
+ });
6619
+
6254
6620
  it("#4526: the renumber gets a reserve hook bound to (repo, lane, issue), and the run's reservations are dropped at finish", async () => {
6255
6621
  const w = dworld({ seq: [COLL, []] }), reserved = [], unreserved = [];
6256
6622
  w.io.sequenceLease.reserve = async (x) => { reserved.push(x); return { numbers: [9] }; };
@@ -6287,6 +6653,31 @@ describe("enumerating tests + sequence numbers at hand-off (#4322)", () => {
6287
6653
  assert.match(w.comments.find((c) => c.includes("<!-- FORGE:BASE_SYNC -->")), /deterministic: 2 union \/ JSON-map \/ generated file/);
6288
6654
  });
6289
6655
 
6656
+ it("#5235 a hand-off renumber reruns the frozen validates without a spurious failure (no fix round, no anomaly)", async () => {
6657
+ const w = dworld({ seq: [COLL, []] }), ran = [];
6658
+ w.io.runCommand = async (a) => { ran.push(a.command); return { rc: 0, output: "" }; };
6659
+ const r = await run(w);
6660
+ assert.equal(r.terminalReason, "merged");
6661
+ assert.equal(w.renumbers.length, 1);
6662
+ assert.ok(ran.includes("node --test test/foo.test.js"), `validate rerun after hand-off renumber: ${JSON.stringify(ran)}`);
6663
+ assert.equal(builders(w).length, 2, "no fix round");
6664
+ assert.ok(!(r.anomalies ?? []).some((x) => /after the hand-off renumber/.test(x)), JSON.stringify(r.anomalies));
6665
+ });
6666
+
6667
+ it("#5235 a renumber after a base-sync reruns the frozen validates before the merge; no renumber, no extra run", async () => {
6668
+ const w = dworld({ seq: [[], COLL, []], prView: [CONFLICTING, OKSTATE], mergeResults: ["clean"], mine: [] }), ran = [];
6669
+ w.io.runCommand = async (a) => { ran.push(a.command); return { rc: 0, output: "" }; };
6670
+ assert.equal((await run(w)).terminalReason, "merged");
6671
+ assert.ok(w.renumbers.length >= 1, "renumbered at the base-sync");
6672
+ assert.ok(ran.includes("node --test test/foo.test.js"), `frozen validate rerun: ${JSON.stringify(ran)}`);
6673
+ assert.ok(w.merges.length === 1);
6674
+ const n = dworld({ seq: [[], [], []], prView: [CONFLICTING, OKSTATE], mergeResults: ["clean"], mine: [] }), nran = [];
6675
+ n.io.runCommand = async (a) => { nran.push(a.command); return { rc: 0, output: "" }; };
6676
+ await run(n);
6677
+ assert.equal(n.renumbers.length, 0);
6678
+ assert.ok(!nran.includes("node --test test/foo.test.js"), "P2: nothing extra without a renumber");
6679
+ });
6680
+
6290
6681
  it("#4588: files the engine cannot resolve go to the sequence resolver, and the builder when that fails; without config nothing changes", async () => {
6291
6682
  const w = dworld({ prView: [CONFLICTING, OKSTATE], mergeResults: ["conflict"], conflictFiles: ["src/index.ts", "db/meta/_journal.json"], resolve: { unsupported: "x" } });
6292
6683
  w.io.conflictResolve = async () => ({ resolved: ["src/index.ts"], remaining: ["db/meta/_journal.json"] });
@@ -6482,7 +6873,7 @@ describe("#4362 attempt triggers", () => {
6482
6873
  w.io.runner = async (c) => { if (c.role === "builder" && n++ === 1) throw Object.assign(new Error("idle"), { code: "CLI_IDLE" }); return orig(c); };
6483
6874
  const r = await run(w, { dir });
6484
6875
  assert.equal(r.terminalReason, "merged");
6485
- assert.deepEqual(usage(dir).filter((e) => e.phase === "implement").map((e) => [e.attempt, e.trigger, e.restart_of ?? null]), [[1, "plan", null], [2, "timeout_restart", "build"]]);
6876
+ assert.deepEqual(usage(dir).filter((e) => e.phase === "implement").map((e) => [e.attempt, e.trigger, e.restart_of ?? null]), [[1, "plan", null], [2, "build", null], [2, "timeout_restart", "build"]]); // #5334: the killed session is its own attempt row
6486
6877
  assert.equal(r.firstPass, true);
6487
6878
  });
6488
6879
 
@@ -6533,6 +6924,55 @@ describe("#4362 attempt triggers", () => {
6533
6924
  assert.equal((await run(off, { dir: tmpDir("core-ctx-"), contextCeilingTokens: 0 })).terminalReason, "merged");
6534
6925
  assert.ok(offCaps.every((x) => x === 0));
6535
6926
  });
6927
+
6928
+ it("#5346: a lane whose start is at 60% of the ceiling is narrowed before the build; named files alone over the ceiling run uncapped", async () => {
6929
+ const big = (bytes, ceil) => {
6930
+ const w = world({ dirty: true }); const seen = []; const orig = w.io.runner;
6931
+ w.files[`${WT}/src/foo.js`] = "x".repeat(bytes);
6932
+ w.io.runner = async (c) => { if (c.role === "builder") seen.push({ contextMax: c.contextMax ?? 0, prompt: c.prompt }); return orig(c); };
6933
+ return { w, seen, go: () => run(w, { dir: tmpDir("core-pred-"), contextCeilingTokens: ceil }) };
6934
+ };
6935
+ const near = big(500_000, 200000); // about 125000 tokens of named files: over 60% of 200000, under the ceiling
6936
+ assert.equal((await near.go()).terminalReason, "merged");
6937
+ assert.equal(near.seen[1].contextMax, 200000, "predicted, not certain: the ceiling stays");
6938
+ assert.match(near.seen[1].prompt, /Context is tight on this lane/);
6939
+ const certain = big(2_000_000, 120000); // 500000 tokens of named files: a restart is certain
6940
+ const rc = await certain.go();
6941
+ assert.equal(rc.terminalReason, "merged");
6942
+ assert.equal(certain.seen[1].contextMax, 0, "certain restart: the build runs without the ceiling");
6943
+ assert.match(certain.seen[1].prompt, /Context is tight on this lane/);
6944
+ const small = big(400, 120000);
6945
+ await small.go();
6946
+ assert.doesNotMatch(small.seen[1].prompt, /Context is tight on this lane/, "a small lane is untouched");
6947
+ assert.equal(small.seen[1].contextMax, 120000);
6948
+ });
6949
+
6950
+ it("#5346: the restart prompt carries the files the stopped session read and edited, and its last tool", async () => {
6951
+ const w = world({ dirty: true }); const orig = w.io.runner, seen = []; let n = 0;
6952
+ w.io.runner = async (c) => {
6953
+ if (c.role === "builder") seen.push(c.prompt);
6954
+ if (c.role === "builder" && n++ === 1) throw Object.assign(new Error("ctx"), { code: "CLI_CONTEXT", context: 130000, turns: 9, usage: null,
6955
+ toolUses: [{ msg: "m1", name: "Read", path: "src/read-me.js" }, { msg: "m2", name: "Edit", path: "src/foo.js" }], lastTool: { name: "Edit", input: "{\"file_path\":\"src/foo.js\"}" } });
6956
+ return orig(c);
6957
+ };
6958
+ assert.equal((await run(w, { dir: tmpDir("core-hand-"), contextCeilingTokens: 120000 })).terminalReason, "merged");
6959
+ const restart = seen[2];
6960
+ assert.match(restart, /<established>/);
6961
+ assert.match(restart, /Files the previous session edited:\n- src\/foo\.js/);
6962
+ assert.match(restart, /do not re-read them unless you must edit them\):\n- src\/read-me\.js/);
6963
+ assert.match(restart, /Its last tool call: Edit /);
6964
+ });
6965
+
6966
+ it("#5346: engine.context_ceiling_by_size sets the ceiling per lane size (size S here), the global one otherwise", async () => {
6967
+ const w = world({ dirty: true }); const caps = []; const orig = w.io.runner;
6968
+ w.io.runner = async (c) => { if (c.role === "builder") caps.push(c.contextMax ?? 0); return orig(c); };
6969
+ await run(w, { dir: tmpDir("core-size-"), contextCeilingTokens: 120000, contextCeilingBySize: { S: 90000 } });
6970
+ assert.equal(caps[1], 90000);
6971
+ const m = world({ dirty: true }); const mcaps = []; const o2 = m.io.runner;
6972
+ m.io.runner = async (c) => { if (c.role === "builder") mcaps.push(c.contextMax ?? 0); return o2(c); };
6973
+ await run(m, { dir: tmpDir("core-size-"), contextCeilingTokens: 120000, contextCeilingBySize: { L: 90000 } });
6974
+ assert.equal(mcaps[1], 120000, "no entry for the lane's size: the global ceiling");
6975
+ });
6536
6976
  });
6537
6977
 
6538
6978
  describe("#4407 per-attempt cost deltas", () => {
@@ -6723,7 +7163,7 @@ describe("explorer subagent (#4391)", () => {
6723
7163
  assert.ok(b.length >= 2 && b.every((s) => s.agents?.explorer?.model === "claude-haiku-5-5"));
6724
7164
  assert.ok(seen.filter((s) => s.role !== "builder").every((s) => s.agents === null));
6725
7165
  const [plan, impl] = builders(w).map((c) => c[4]);
6726
- assert.ok(plan.startsWith(builderPlanPrompt(7)));
7166
+ assert.ok(unstamp(plan).startsWith(builderPlanPrompt(7)));
6727
7167
  assert.match(plan, /subagent_type "explorer"[\s\S]*Open a file yourself only to edit it or to verify a digest claim/);
6728
7168
  assert.match(impl, /subagent_type "explorer"/);
6729
7169
  assert.equal(readLog(dir, 7).find((e) => e.event === "RUN_TERMINAL").explore, "on");
@@ -6741,6 +7181,36 @@ describe("explorer subagent (#4391)", () => {
6741
7181
  });
6742
7182
  });
6743
7183
 
7184
+ describe("experiment arm overrides (#5206)", () => {
7185
+ const capture = (w) => { const seen = []; const inner = w.io.runner; w.io.runner = async (c) => { seen.push({ role: c.role, agents: c.agents ?? null }); return inner(c); }; return seen; };
7186
+ // issue 7 hashes to arm "on" under id x0 and to "off" under id x2 (assignArm, sha1 of id:issue)
7187
+ const exp = (id) => parseExperiment({ id, arms: "on,off", "on.lean.explore": "on", "off.lean.explore": "off" });
7188
+
7189
+ it("R1/R3: the explorer runs only in the on arm; RUN_TERMINAL carries arm and the applied overrides", async () => {
7190
+ assert.equal(assignArm(exp("x0"), 7), "on"); assert.equal(assignArm(exp("x2"), 7), "off");
7191
+ const on = world(), seenOn = capture(on), dOn = tmpDir("core-");
7192
+ assert.equal((await run(on, { dir: dOn, experiment: exp("x0"), explore: { model: "claude-haiku-5-5" } })).terminalReason, "merged");
7193
+ assert.ok(seenOn.filter((s) => s.role === "builder").every((s) => s.agents?.explorer?.model === "claude-haiku-5-5"));
7194
+ const tOn = readLog(dOn, 7).find((e) => e.event === "RUN_TERMINAL");
7195
+ assert.deepEqual([tOn.experiment, tOn.arm, tOn.arm_overrides, tOn.explore], ["x0", "on", "lean.explore=on", "on"]);
7196
+ const off = world(), seenOff = capture(off), dOff = tmpDir("core-");
7197
+ assert.equal((await run(off, { dir: dOff, experiment: exp("x2"), explore: { mode: "on" } })).terminalReason, "merged");
7198
+ assert.ok(seenOff.every((s) => s.agents === null));
7199
+ const tOff = readLog(dOff, 7).find((e) => e.event === "RUN_TERMINAL");
7200
+ assert.deepEqual([tOff.arm, tOff.arm_overrides, tOff.explore], ["off", "lean.explore=off", "off"]);
7201
+ assert.ok(readLog(dOff, 7).filter((e) => e.event === "PHASE_ATTEMPT_USAGE").every((e) => e.arm === "off" && e.arm_overrides === "lean.explore=off"));
7202
+ });
7203
+
7204
+ it("R4: no experiment: prompts and RUN_TERMINAL carry no arm fields", async () => {
7205
+ const w = world(), d = tmpDir("core-");
7206
+ await run(w, { dir: d, explore: { mode: "off" } });
7207
+ const t = readLog(d, 7).find((e) => e.event === "RUN_TERMINAL");
7208
+ assert.ok(!("arm" in t) && !("arm_overrides" in t) && !("experiment" in t));
7209
+ const x = world(); await run(x, { explore: { mode: "off" } });
7210
+ assert.deepEqual(builders(w).map((c) => c[4]), builders(x).map((c) => c[4]));
7211
+ });
7212
+ });
7213
+
6744
7214
  describe("e2e merge gate (#4403)", () => {
6745
7215
  const SPECS = ["src/foo.js", "test/foo.test.js", "e2e/foo.spec.ts"];
6746
7216
  const RUN = "https://github.com/o/r/actions/runs/777/job/1";
@@ -7175,11 +7645,11 @@ describe("#4395 lane profile", () => {
7175
7645
 
7176
7646
  it("#4410 both builder prompts ask for same-turn read-only calls and read-once notes (within budget)", () => {
7177
7647
  for (const p of [builderPlanPrompt(7), builderImplementPrompt(), builderImplementPrompt("ci")]) {
7178
- assert.match(p, /Issue independent read-only calls \(reads, greps, git log\/blame, gh\) in the same turn or one shell call\./);
7648
+ assert.match(p, /One turn, many calls: when several reads, greps, git show\/log\/blame or gh calls do not depend on each other, issue them all in the same turn/);
7179
7649
  assert.match(p, /Read each file's ranges once .* and keep notes; don't re-read it\./);
7180
7650
  }
7181
- assert.ok(approxTokens(builderImplementPrompt()) <= 1650, `implement prompt is ${approxTokens(builderImplementPrompt())} of 1650 tokens`);
7182
- assert.ok(approxTokens(builderPlanPrompt(7)) <= 2050, `plan prompt is ${approxTokens(builderPlanPrompt(7))} of 2050 tokens`);
7651
+ assert.ok(approxTokens(builderImplementPrompt()) <= 1850, `implement prompt is ${approxTokens(builderImplementPrompt())} of 1700 tokens`);
7652
+ assert.ok(approxTokens(builderPlanPrompt(7)) <= 2325, `plan prompt is ${approxTokens(builderPlanPrompt(7))} of 2125 tokens`);
7183
7653
  });
7184
7654
 
7185
7655
  it("runCliBackendAsync reports the first stream turn's context as baselineTokens; makeLeanRunner drops it on resume", async () => {
@@ -7347,10 +7817,35 @@ describe("#4450 light lane: one builder session, derived contract, upgrade to th
7347
7817
  const plan = w.calls.indexOf(builders(w)[1]);
7348
7818
  // each fake notes w.calls.length when called, i.e. the index the next call takes: <= plan means before the plan call
7349
7819
  assert.ok(w.over.hot.some((i) => i <= plan) && w.over.pack.some((i) => i <= plan), JSON.stringify({ plan, ...w.over }));
7350
- assert.ok(w.over.hot.every((i) => i > w.calls.indexOf(builders(w)[0])), "not before the light session");
7820
+ const light = w.calls.indexOf(builders(w)[0]);
7821
+ assert.equal(w.over.hot.filter((i) => i <= light).length, 1, "#5209: only the eligibility-signal call precedes the light session");
7822
+ assert.ok(w.over.hot.some((i) => i > light && i <= plan), "the upgrade recomputes the plan facts after the light session");
7351
7823
  assert.ok(w.over.structure.length >= 1);
7352
7824
  assert.equal(events(dir, "RUN_TERMINAL")[0].light, false);
7353
7825
  });
7826
+ it("#5209 shadow mode: LIGHT_ELIGIBILITY carries signals and the hotspot reason; the lane keeps the full shape", async () => {
7827
+ const w = lworld(), dir = tmpDir("light-5209-shadow-");
7828
+ w.io.hotspots = async () => ({ enabled: true, file_lines: 2000, growth_lines: 150, files: [{ path: "src/foo.js", lines: 2400, commits_90d: 25, over: true, excluded: false, growth: 0 }] });
7829
+ const r = await run(w, { dir });
7830
+ assert.equal(r.terminalReason, "merged");
7831
+ const e = events(dir, "LIGHT_ELIGIBILITY")[0];
7832
+ assert.equal(e.mode, "shadow");
7833
+ assert.equal(e.verdict, "ineligible");
7834
+ assert.equal(e.light, false);
7835
+ assert.ok(e.reasons.some((x) => x.code === "hotspot" && /src\/foo\.js \(2400 lines\)/.test(x.detail)), JSON.stringify(e.reasons));
7836
+ const sig = e.signals.map((x) => x.code);
7837
+ for (const c of ["repro", "files_named", "churn_high", "hotspot", "size_none"]) assert.ok(sig.includes(c), `${c} in ${sig}`);
7838
+ assert.match(builders(w)[0][4], /PLANNING ONLY/, "plan call present");
7839
+ assert.equal(events(dir, "LIGHT_DONE").length + events(dir, "LIGHT_UPGRADE").length, 0);
7840
+ });
7841
+ it("#5209 mode on: an eligible light try still gets no hotspot build rule in its builder prompt", async () => {
7842
+ const w = lworld(), dir = tmpDir("light-5209-on-");
7843
+ w.io.hotspots = async () => ({ enabled: true, file_lines: 2000, growth_lines: 150, files: [{ path: "src/foo.js", lines: 120, commits_90d: 3, over: false, excluded: false, growth: 0 }] });
7844
+ await run(w, { dir, ...ON });
7845
+ assert.equal(events(dir, "LIGHT_ELIGIBILITY")[0].verdict, "eligible");
7846
+ assert.equal(events(dir, "LIGHT_DONE").length, 1);
7847
+ assert.ok(!/Don't grow a file over/.test(builders(w)[0][4]), "no hotspotBuildRule in the light prompt");
7848
+ });
7354
7849
  it("#4451 a full lane (light off) keeps its context-pack, structure and hotspot calls", async () => {
7355
7850
  const w = overhead(), dir = tmpDir("light-over-off-");
7356
7851
  await run(w, { dir, light: { mode: "off" }, contextPack: { mode: "on" } });
@@ -7494,6 +7989,164 @@ describe("prompt budgets (#4969)", () => {
7494
7989
  assert.notEqual(moved, impl);
7495
7990
  assert.equal(approxTokens(moved), approxTokens(impl));
7496
7991
  assert.equal(approxTokens(impl.replaceAll(INSTALL_ROOT, "C:\\fd")), approxTokens(impl));
7497
- assert.ok(approxTokens(moved) <= 1650, `implement prompt from a deep checkout is ${approxTokens(moved)} of 1650 tokens`);
7992
+ assert.ok(approxTokens(moved) <= 1850, `implement prompt from a deep checkout is ${approxTokens(moved)} of 1700 tokens`);
7993
+ });
7994
+ });
7995
+
7996
+ describe("#5250 intake host triage", () => {
7997
+ const hostBody = "## Acceptance Criteria\n\n- [ ] Measured clear rate on live production traffic is above 50%\n- [ ] Root-cause capture from a real browser is attached\n";
7998
+ it("an issue whose criteria are all live-production or real-browser work ends host-task with no builder run", async () => {
7999
+ const w = world({ body: hostBody });
8000
+ const r = await run(w);
8001
+ assert.equal(r.terminalReason, "host-task");
8002
+ assert.ok(w.edits.some((e) => e.includes("--add-label") && e.includes("host-task")), JSON.stringify(w.edits));
8003
+ assert.ok(w.comments.some((c) => String(c.body ?? c).includes("FORGE:HOST_TASK")), "FORGE:HOST_TASK comment");
8004
+ assert.equal(w.builderN, 0);
8005
+ });
8006
+ it("a code issue is unaffected", async () => {
8007
+ const w = world({ body: "## Acceptance Criteria\n\n- [ ] foo no longer breaks\n" });
8008
+ assert.notEqual((await run(w)).terminalReason, "host-task");
8009
+ });
8010
+ });
8011
+
8012
+ describe("#5237 relaxation gate", () => {
8013
+ const rescue = "diff --git a/src/foo.js b/src/foo.js\n@@ -1,0 +5,1 @@\n+ if (looksThin(page)) return true; // rescue\n";
8014
+ const negTest = "diff --git a/test/foo.test.js b/test/foo.test.js\n@@ -1,0 +1,1 @@\n+ assert.equal(isBenign(cookieChallenge), false);\n";
8015
+ const withV = (w) => {
8016
+ const orig = w.io.runner; w.vcalls = [];
8017
+ w.io.runner = async (c) => {
8018
+ if (c.role !== "verifier") return orig(c);
8019
+ w.vcalls.push(c);
8020
+ return { text: "```json\n{\"findings\":[]}\n```", sessionId: "ver", usage: { input_tokens: 3, output_tokens: 1 }, costUsd: 0.01, durationMs: 300, turns: 2, model: c.model };
8021
+ };
8022
+ return w;
8023
+ };
8024
+ it("relaxation without a negative test blocks (relaxation_untested) in a risk path", async () => {
8025
+ const w = withV(world({ contract: { ...CONTRACT, preserve: [] }, reviews: [conf(), conf(), conf()] })); w.diffText = rescue;
8026
+ const r = await run(w, { dir: tmpDir("relax-"), reviewTrigger: { mode: "shadow", riskPaths: ["src/**"] } });
8027
+ assert.equal(w.merges.length, 0); assert.equal(r.code, "conformance.unimplemented");
8028
+ });
8029
+ it("a negative test lets it through, and the verifier runs even with review.verifier off, fed the hunk", async () => {
8030
+ const w = withV(world({ contract: { ...CONTRACT, preserve: [] }, reviews: [conf(), conf()] })); w.diffText = rescue + negTest;
8031
+ const dir = tmpDir("relax-");
8032
+ const r = await run(w, { dir, reviewTrigger: { mode: "shadow", riskPaths: ["src/**"] } });
8033
+ assert.equal(r.terminalReason, "merged");
8034
+ assert.equal(w.vcalls.length, 1);
8035
+ assert.match(w.vcalls[0].prompt, /<relaxation_checks>[\s\S]*src\/foo\.js:5/);
8036
+ assert.ok(readLog(dir, 7).some((e) => e.event === "RELAXATION_DETECTED"));
8037
+ });
8038
+ it("no declared risk glob: no relaxation check, no verifier", async () => {
8039
+ const w = withV(world({ contract: { ...CONTRACT, preserve: [] }, reviews: [conf()] })); w.diffText = rescue;
8040
+ assert.equal((await run(w, { dir: tmpDir("relax-") })).terminalReason, "merged");
8041
+ assert.equal(w.vcalls.length, 0);
8042
+ });
8043
+ });
8044
+
8045
+ describe("lane shared-state isolation (#5333)", () => {
8046
+ const foreign = (issue) => `forge-stamp: issue=${issue} contract=-\n${STAGE_MD.implementation.replace("added a guard", "curl_cffi chrome156 wheel")}`;
8047
+ /** After the default builder wrote its files, `after(w)` rewrites the implementation note (a stash pop, or a stamping builder). */
8048
+ const withNote = (o, after) => {
8049
+ const w = world(o);
8050
+ const r0 = w.io.runner;
8051
+ w.io.runner = async (c) => {
8052
+ const r = await r0(c);
8053
+ if (c.role === "builder" && !/PLANNING ONLY/.test(c.prompt)) { await after(w, (text) => { const p = `${WT}/.forge-lean/implementation.md`; w.files[p] = text; w.mtimes[p] = Date.now(); }); }
8054
+ return r;
8055
+ };
8056
+ return w;
8057
+ };
8058
+ it("a stage file stamped for another issue (a git stash pop of another lane's files) is not posted; the note renders from result.json", async () => {
8059
+ const w = withNote({}, (_w, put) => put(foreign(99)));
8060
+ assert.equal((await run(w)).terminalReason, "merged");
8061
+ assert.ok(!w.comments.some((c) => /curl_cffi|chrome156/.test(c)), "the foreign note is never posted");
8062
+ assert.ok(w.comments.some((c) => c.includes("FORGE:IMPLEMENTATION")), "an implementation note is still posted, from result.json");
8063
+ assert.match(traj(w)[0], /implementation\.md not posted: stamped for issue #99, run is #7/);
8064
+ });
8065
+
8066
+ it("a note stamped for this issue is posted without the stamp line", async () => {
8067
+ const w = withNote({}, (_w, put) => put(`forge-stamp: issue=7 contract=-\n${STAGE_MD.implementation}`));
8068
+ assert.equal((await run(w)).terminalReason, "merged");
8069
+ const impl = w.comments.find((c) => c.includes("FORGE:IMPLEMENTATION"));
8070
+ assert.match(impl, /added a guard/);
8071
+ assert.doesNotMatch(impl, /forge-stamp/);
8072
+ });
8073
+
8074
+ it("a note posted live that a later stash pop replaces with another lane's file is re-rendered after the builder's final turn", async () => {
8075
+ const w = withNote({}, async (wd, put) => {
8076
+ put(`forge-stamp: issue=7 contract=-\n${STAGE_MD.implementation}`);
8077
+ for (let i = 0; i < 1000 && !wd.comments.some((c) => c.includes("<!-- FORGE:IMPLEMENTATION -->")); i++) await new Promise((r) => setTimeout(r, 10));
8078
+ put(foreign(99));
8079
+ });
8080
+ await run(w, { livePollMs: 10, stableMs: 30 });
8081
+ assert.ok(w.patches.length >= 1, "the posted comment was edited");
8082
+ assert.doesNotMatch(w.patches.at(-1).join(" "), /curl_cffi|chrome156/);
8083
+ assert.ok(!w.comments.some((c) => /curl_cffi|chrome156/.test(c)));
8084
+ });
8085
+
8086
+ it("no builder session starts in a worktree that no longer exists: the lane defers run.interrupted", async () => {
8087
+ const w = world({ wtExists: true });
8088
+ const git0 = w.io.git, fs0 = w.io.fs.exists;
8089
+ let gone = false, builders = 0;
8090
+ w.io.git = async (a, ...r) => { if (a[0] === "worktree" && a[1] === "add") gone = true; return git0(a, ...r); };
8091
+ w.io.fs.exists = async (p) => (gone ? false : fs0(p));
8092
+ const r0 = w.io.runner; w.io.runner = async (c) => { if (c.role === "builder") builders++; return r0(c); };
8093
+ const r = await run(w);
8094
+ assert.equal(r.terminalReason, "deferred");
8095
+ assert.equal(builders, 0);
8096
+ });
8097
+ });
8098
+
8099
+ describe("#5347 builders open with one batch of independent reads", () => {
8100
+ it("the batching rule is its own rule in plan, implement and fix prompts, and the plan asks for the build's reads", async () => {
8101
+ const { fixSessionPrompt, buildOpeningNote } = await import("./prompts.mjs");
8102
+ for (const p of [builderPlanPrompt(7), builderImplementPrompt(), fixSessionPrompt({ task: "t" })]) assert.match(p, /One turn, many calls/);
8103
+ assert.match(builderPlanPrompt(7), /Build reads/);
8104
+ assert.match(buildOpeningNote({ paths: ["a.mjs", "a.mjs", "b.mjs"], tests: ["node --test a.test.mjs"] }), /Deliverables: a\.mjs, b\.mjs\nMapped tests \(test map\): node --test a\.test\.mjs/);
8105
+ assert.equal(buildOpeningNote({}), "");
8106
+ });
8107
+ it("the implement session prompt carries the contract's deliverable paths and the test map's commands", async () => {
8108
+ const { buildOpeningNote } = await import("./prompts.mjs");
8109
+ const { selectCommands, parseTestMap } = await import("./testmap.mjs");
8110
+ const map = parseTestMap(JSON.stringify({ version: 1, entries: [{ globs: ["src/**"], command: "node --test src/x.test.mjs" }] }));
8111
+ const note = buildOpeningNote({ paths: ["src/x.mjs", "docs/y.md"], tests: selectCommands(map, ["src/x.mjs", "docs/y.md"]) });
8112
+ assert.match(note, /src\/x\.mjs, docs\/y\.md/);
8113
+ assert.match(note, /node --test src\/x\.test\.mjs/);
8114
+ });
8115
+ });
8116
+
8117
+ describe("#5347 lane: the build opens with its independent reads in one turn", () => {
8118
+ it("a lane whose contract names two deliverables hands the builder the opening batch; the builder's one-turn reads through the real stream parser record calls/turn >= 2", async () => {
8119
+ const { runCliBackendAsync } = await import("../runner.mjs");
8120
+ const { toolStats } = await import("./toolstats.mjs");
8121
+ const two = { ...CONTRACT, deliverables: [...CONTRACT.deliverables, { id: "D2", path: "src/bar.js", change: "keep callers", requirements: ["R1"] }] };
8122
+ const w = world({ contract: two, changed: ["src/foo.js", "src/bar.js", "test/foo.test.js"] }), dir = tmpDir("core-onebatch-"), orig = w.io.runner;
8123
+ const prompts = [];
8124
+ w.io.runner = async (c) => {
8125
+ const out = await orig(c);
8126
+ if (c.role !== "builder" || /PLANNING ONLY/.test(c.prompt)) return out;
8127
+ prompts.push(c.prompt);
8128
+ // the model's side, stood in by a fake CLI: one assistant message (one id) with a Read per opening-batch path
8129
+ const paths = (/Deliverables: (.*)/.exec(c.prompt)?.[1] ?? "").split(", ").filter(Boolean);
8130
+ const blocks = paths.map((p, i) => ({ type: "tool_use", id: `t${i}`, name: "Read", input: { file_path: p } }));
8131
+ const ev = (o) => JSON.stringify(o).replaceAll("'", "");
8132
+ const script = `#!/bin/sh\necho '${ev({ type: "assistant", message: { id: "m1", content: blocks, usage: { input_tokens: 1, output_tokens: 1 } } })}'\necho '${ev({ type: "result", subtype: "success", is_error: false, result: "ok", session_id: "s", usage: { input_tokens: 2, output_tokens: 2 } })}'\n`;
8133
+ writeFileSync(`${dir}/fake`, script); chmodSync(`${dir}/fake`, 0o755);
8134
+ const r = await runCliBackendAsync({ spec: { name: "t" }, userMessage: "go", args: ["1"], cwd: dir, bin: `${dir}/fake`, logger: { log() {} }, stream: true });
8135
+ return { ...out, tools: toolStats(r.toolUses) };
8136
+ };
8137
+ await run(w, { dir });
8138
+ assert.ok(prompts.length && /Opening batch: .*\nDeliverables: src\/foo\.js, src\/bar\.js/.test(prompts[0]), "the implement prompt carries the opening batch");
8139
+ const u = readLog(dir, 7).find((e) => e.event === "PHASE_ATTEMPT_USAGE" && e.phase === "implement" && e.trigger === "build");
8140
+ assert.equal(u.tools.turns, 1);
8141
+ assert.equal(u.tools.calls, 2);
8142
+ assert.ok(u.tools.per_turn >= 2, `calls/turn ${u.tools.per_turn}`);
8143
+ });
8144
+ it("the context pack's file list joins the opening batch (compileContextPack files from the ledger)", async () => {
8145
+ const { compileContextPack } = await import("./context.mjs");
8146
+ const { buildOpeningNote } = await import("./prompts.mjs");
8147
+ const pack = compileContextPack({ issue: 9, links: [], attempts: [], ledger: [{ pr: 4, sha: "abc", title: "t", revert: false, reverted: null, files: ["src/a.js", "src/b.js"], notes: [] }], facts: [] });
8148
+ assert.deepEqual(pack.files, ["src/a.js", "src/b.js"]);
8149
+ assert.deepEqual(compileContextPack({ issue: 9, links: [], attempts: [], ledger: [], facts: [] }).files, []);
8150
+ assert.match(buildOpeningNote({ paths: ["src/a.js"], packFiles: pack.files }), /Context pack files \(touched by earlier PRs on these symbols\): src\/b\.js/);
7498
8151
  });
7499
8152
  });