forgedock 1.66.0 → 1.68.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 (173) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +2 -0
  3. package/bin/engine-cli.mjs +193 -27
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +24 -1
  6. package/bin/help-text.mjs +4 -3
  7. package/bin/introspect-schedule.mjs +98 -0
  8. package/bin/introspect-schedule.test.mjs +67 -0
  9. package/bin/lean/admission.mjs +21 -0
  10. package/bin/lean/admission.test.mjs +30 -0
  11. package/bin/lean/advisory.test.mjs +64 -0
  12. package/bin/lean/amendment-schema.mjs +30 -0
  13. package/bin/lean/attempts.mjs +162 -0
  14. package/bin/lean/attempts.test.mjs +141 -0
  15. package/bin/lean/basered.mjs +81 -0
  16. package/bin/lean/basered.test.mjs +68 -1
  17. package/bin/lean/batch-health.mjs +20 -12
  18. package/bin/lean/batch-health.test.mjs +55 -11
  19. package/bin/lean/batch.mjs +45 -0
  20. package/bin/lean/batch.test.mjs +105 -5
  21. package/bin/lean/capwait.mjs +14 -3
  22. package/bin/lean/capwait.test.mjs +20 -0
  23. package/bin/lean/ci-gate.mjs +2 -90
  24. package/bin/lean/ci-gate.test.mjs +1 -127
  25. package/bin/lean/ci-precheck.mjs +25 -8
  26. package/bin/lean/ci-precheck.test.mjs +24 -0
  27. package/bin/lean/clear-breaker.mjs +14 -0
  28. package/bin/lean/clear-breaker.test.mjs +4 -3
  29. package/bin/lean/commentstate.mjs +46 -0
  30. package/bin/lean/commentstate.test.mjs +43 -0
  31. package/bin/lean/concurrency.mjs +89 -0
  32. package/bin/lean/concurrency.test.mjs +113 -0
  33. package/bin/lean/conformance.e2e.test.mjs +13 -8
  34. package/bin/lean/conformance.mjs +73 -181
  35. package/bin/lean/conformance.test.mjs +61 -345
  36. package/bin/lean/depcache.mjs +100 -10
  37. package/bin/lean/depcache.test.mjs +105 -0
  38. package/bin/lean/docsgate.mjs +0 -32
  39. package/bin/lean/docsgate.test.mjs +2 -23
  40. package/bin/lean/effects-cap.test.mjs +9 -1
  41. package/bin/lean/effects-killtree.test.mjs +35 -0
  42. package/bin/lean/effects.mjs +42 -24
  43. package/bin/lean/efficiency.mjs +162 -0
  44. package/bin/lean/efficiency.test.mjs +79 -0
  45. package/bin/lean/engine-readmit.test.mjs +35 -0
  46. package/bin/lean/envgap.mjs +93 -0
  47. package/bin/lean/envgap.test.mjs +53 -0
  48. package/bin/lean/execution.mjs +41 -17
  49. package/bin/lean/execution.test.mjs +58 -0
  50. package/bin/lean/failure-census.mjs +170 -0
  51. package/bin/lean/failure-census.test.mjs +59 -0
  52. package/bin/lean/failure-stop.mjs +46 -0
  53. package/bin/lean/failure-stop.test.mjs +45 -0
  54. package/bin/lean/fixtures/capacity-storm.json +609 -0
  55. package/bin/lean/guardgate.test.mjs +2 -3
  56. package/bin/lean/heavy.mjs +33 -4
  57. package/bin/lean/heavy.test.mjs +38 -6
  58. package/bin/lean/hotarea.mjs +0 -36
  59. package/bin/lean/hotarea.test.mjs +1 -22
  60. package/bin/lean/issuewatch-verify.mjs +19 -4
  61. package/bin/lean/issuewatch.mjs +21 -4
  62. package/bin/lean/issuewatch.test.mjs +48 -1
  63. package/bin/lean/lane-audit-gap.mjs +66 -0
  64. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  65. package/bin/lean/lane-audit-llm.mjs +5 -0
  66. package/bin/lean/lane-audit-query.mjs +47 -0
  67. package/bin/lean/lane-audit-query.test.mjs +44 -0
  68. package/bin/lean/lane-audit-signatures.mjs +33 -0
  69. package/bin/lean/lane-audit.mjs +110 -0
  70. package/bin/lean/lane-audit.test.mjs +97 -0
  71. package/bin/lean/lane-recovery.test.mjs +33 -0
  72. package/bin/lean/lanecheck.mjs +5 -3
  73. package/bin/lean/lanecheck.test.mjs +6 -0
  74. package/bin/lean/lean.mjs +311 -154
  75. package/bin/lean/lean.test.mjs +530 -223
  76. package/bin/lean/limits.mjs +17 -0
  77. package/bin/lean/limits.test.mjs +15 -1
  78. package/bin/lean/live-execution.mjs +21 -2
  79. package/bin/lean/live-execution.test.mjs +39 -0
  80. package/bin/lean/liveness.mjs +37 -0
  81. package/bin/lean/liveness.test.mjs +33 -0
  82. package/bin/lean/orchestrate-attempts.test.mjs +82 -0
  83. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  84. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  85. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  86. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  87. package/bin/lean/orchestrate-pause.test.mjs +76 -1
  88. package/bin/lean/orchestrate-reconcile.test.mjs +164 -0
  89. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  90. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  91. package/bin/lean/orchestrate.mjs +344 -45
  92. package/bin/lean/phaseledger.mjs +6 -0
  93. package/bin/lean/phaseledger.test.mjs +13 -1
  94. package/bin/lean/postdeploy-check.test.mjs +1 -3
  95. package/bin/lean/precheck.mjs +20 -0
  96. package/bin/lean/preflight.mjs +100 -11
  97. package/bin/lean/preflight.test.mjs +44 -4
  98. package/bin/lean/prompts.mjs +13 -28
  99. package/bin/lean/reconcile.mjs +90 -0
  100. package/bin/lean/recurrence.mjs +6 -112
  101. package/bin/lean/recurrence.test.mjs +11 -92
  102. package/bin/lean/release-flakes.mjs +14 -2
  103. package/bin/lean/release-flakes.test.mjs +17 -1
  104. package/bin/lean/release-ledger.mjs +19 -1
  105. package/bin/lean/release-ledger.test.mjs +23 -0
  106. package/bin/lean/release-preflight.mjs +28 -0
  107. package/bin/lean/release-preflight.test.mjs +42 -1
  108. package/bin/lean/release-review.mjs +40 -5
  109. package/bin/lean/release-review.test.mjs +43 -2
  110. package/bin/lean/release.mjs +43 -14
  111. package/bin/lean/release.test.mjs +32 -0
  112. package/bin/lean/retry.mjs +1 -1
  113. package/bin/lean/retry.test.mjs +6 -1
  114. package/bin/lean/rotator.mjs +9 -0
  115. package/bin/lean/rotator.test.mjs +11 -1
  116. package/bin/lean/sandbox-remote.mjs +49 -11
  117. package/bin/lean/sched.mjs +19 -0
  118. package/bin/lean/sched.test.mjs +11 -1
  119. package/bin/lean/schedd-health.mjs +4 -4
  120. package/bin/lean/schedd-health.test.mjs +8 -4
  121. package/bin/lean/schedd.mjs +45 -8
  122. package/bin/lean/schedd.test.mjs +120 -7
  123. package/bin/lean/selfreview.mjs +1 -1
  124. package/bin/lean/slo.mjs +126 -0
  125. package/bin/lean/slo.test.mjs +112 -0
  126. package/bin/lean/statuscomment.mjs +40 -0
  127. package/bin/lean/statuscomment.test.mjs +48 -1
  128. package/bin/lean/validate-catalog.mjs +108 -0
  129. package/bin/lean/validate-catalog.test.mjs +46 -1
  130. package/bin/lean/verify.mjs +3 -2
  131. package/bin/pool/affinity.test.mjs +91 -0
  132. package/bin/pool/agent.mjs +144 -10
  133. package/bin/pool/cache-sweep.mjs +31 -10
  134. package/bin/pool/ci-autoscale.mjs +160 -0
  135. package/bin/pool/cli.mjs +53 -9
  136. package/bin/pool/docker.mjs +3 -0
  137. package/bin/pool/engine-placement.test.mjs +94 -0
  138. package/bin/pool/lane-target.mjs +41 -0
  139. package/bin/pool/lane-tools.mjs +26 -0
  140. package/bin/pool/lane-tools.test.mjs +9 -0
  141. package/bin/pool/mirror-seed.mjs +15 -11
  142. package/bin/pool/router.mjs +88 -32
  143. package/bin/pool/version.mjs +29 -2
  144. package/bin/review-staging.mjs +11 -3
  145. package/bin/runner.mjs +59 -11
  146. package/bin/stats/attempts.mjs +54 -0
  147. package/bin/stats/attempts.test.mjs +30 -0
  148. package/bin/stats/churn.mjs +49 -0
  149. package/bin/stats/churn.test.mjs +31 -0
  150. package/bin/stats/index.mjs +11 -3
  151. package/bin/stats/release.mjs +7 -0
  152. package/bin/stats/release.test.mjs +20 -0
  153. package/bin/stats/scorecard.mjs +187 -0
  154. package/bin/stats/scorecard.test.mjs +89 -0
  155. package/commands/orchestrate.md +21 -18
  156. package/docs/CONFIG.md +41 -0
  157. package/docs/OUTCOME-CODES.md +2 -0
  158. package/docs/STATS.md +17 -0
  159. package/package.json +1 -1
  160. package/pool/image/Dockerfile +14 -2
  161. package/pool/image/manifest.json +25 -0
  162. package/pool/image/mirror.sh +11 -2
  163. package/pool/install/install-agent.ps1 +11 -4
  164. package/scripts/check-devdocs-freshness.sh +1 -1
  165. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  166. package/scripts/ci-local/cli.mjs +1 -1
  167. package/scripts/ci-local/plan.mjs +3 -2
  168. package/scripts/ci-local.test.sh +11 -0
  169. package/scripts/failure-census.mjs +67 -0
  170. package/scripts/review-finalize.sh +5 -5
  171. package/scripts/review-finalize.test.sh +8 -1
  172. package/scripts/verify-phase-trail.sh +11 -0
  173. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { parseStatus } from "./statuscomment.mjs";
4
4
  import { foldRegression } from "./baselines.mjs";
5
- import { describe, it } from "node:test";
5
+ import { describe, it, before, after } from "node:test";
6
6
  import { laneBackendId } from "./limits.mjs";
7
7
  import { parseExperiment, assignArm } from "../experiment.mjs";
8
8
  import assert from "node:assert/strict";
@@ -15,6 +15,7 @@ import * as nodeFs from "node:fs";
15
15
  import { join } from "node:path";
16
16
  import os from "node:os";
17
17
  import { syncBuiltinESMExports } from "node:module";
18
+ import { diffTouchesGuard } from "./basered.mjs";
18
19
  import { runCore, contractHash, isProtectedLaneBranch, classifyBlock, builderFixable } from "./lean.mjs";
19
20
  import { parseFactsComment, normaliseFacts, renderFactsRecord, FACTS_MARKER } from "./facts.mjs";
20
21
  import { makeLedger } from "./ledger.mjs";
@@ -61,6 +62,7 @@ if (process.platform === "win32") {
61
62
  const WT = "/wt/lean-7";
62
63
  /** Windows: `path.join` yields backslashes; the fake fs keys are POSIX paths. */
63
64
  const posix = (p) => String(p).replace(/\\/g, "/");
65
+ const fp = posix; // #5753 alias
64
66
  /** #5333: the engine appends the stage-stamp rule to every builder prompt; strip it to compare against the bare template. */
65
67
  const unstamp = (s) => String(s).replace(/\n\nStage notes: make the first line[^\n]*/, "");
66
68
  const STAGE_MD = {
@@ -107,7 +109,7 @@ function world(o = {}) {
107
109
  contract: o.contract ?? CONTRACT, issueComments: o.issueComments, issueStates: o.issueStates,
108
110
  changed: o.changed ?? ["src/foo.js", "test/foo.test.js"], reviews: [...(o.reviews ?? [])], waits: [...(o.waits ?? [])], clock: 0,
109
111
  result: o.result ?? { status: "fixed", summary: "fixed foo", evidence: [], tests: ["test/foo.test.js"] },
110
- prList: o.prList ?? [], remote: o.remote ?? "", resumeResult: o.resumeResult, seq: [], mtimes: {}, envs: [], pushes: 0, pushErrors: [...(o.pushErrors ?? [])], commentErrors: [...(o.commentErrors ?? [])], dirty: o.dirty ?? false, lastSubject: o.lastSubject ?? "", prView: [...(o.prView ?? [])], mergeResults: [...(o.mergeResults ?? [])], mergeErrors: [...(o.mergeErrors ?? [])], conflictFiles: [], baseHeads: [...(o.baseHeads ?? ["ba5e000000000000"])], mergeInProgress: false, markers: false, mergeAttempts: 0, branchDeletes: [],
112
+ prList: o.prList ?? [], remote: o.remote ?? "", resumeResult: o.resumeResult, seq: [], mtimes: {}, envs: [], pushes: 0, pushErrors: [...(o.pushErrors ?? [])], commentErrors: [...(o.commentErrors ?? [])], dirty: o.dirty ?? false, lastSubject: o.lastSubject ?? "", prView: [...(o.prView ?? [])], mergeResults: [...(o.mergeResults ?? [])], behind: o.behind ?? 0, mergeErrors: [...(o.mergeErrors ?? [])], conflictFiles: [], baseHeads: [...(o.baseHeads ?? ["ba5e000000000000"])], mergeInProgress: false, markers: false, mergeAttempts: 0, branchDeletes: [],
111
113
  stages: { ...STAGE_MD, ...(o.stages ?? {}) }, builderN: 0,
112
114
  salvageTrees: [...(o.salvageTrees ?? [])], alive: new Set((o.procs ?? []).map((p) => p.pid)), kills: [],
113
115
  };
@@ -174,6 +176,7 @@ function world(o = {}) {
174
176
  if (a[0] === "ls-tree" && w.stagedDeletions) return a.slice(a.indexOf("--") + 1).filter((p) => !(w.laneAdded ?? []).includes(p)).join("\0"); // #5819: on the base unless the lane added it
175
177
  if (a[0] === "checkout" && a.includes("HEAD") && w.stagedDeletions) { w.restoredPaths = [...(w.restoredPaths ?? []), ...a.slice(a.indexOf("--") + 1)]; return ""; }
176
178
  if (a[0] === "rm" && a[1] === "--cached" && w.added) w.added = w.added.filter((f) => !a.includes(f));
179
+ if (a[0] === "rev-list" && a.includes("--count")) return String(w.behind ?? 0); // #6107: commits the branch is behind its base
177
180
  if (a[0] === "diff" && a.includes("--diff-filter=U")) return w.conflictFiles.join("\n");
178
181
  if (a[0] === "diff" && a[1] === "--check") return "";
179
182
  if (a[0] === "grep") return w.markers ? "src/foo.js:3:<<<<<<< HEAD" : "";
@@ -219,7 +222,7 @@ function world(o = {}) {
219
222
  if (fix && n > 2 && /does not conform/.test(c.prompt) && o.resumeChanged) w.changed = o.resumeChanged;
220
223
  if (/Merging origin\//.test(c.prompt) && o.syncChanged) w.changed = o.syncChanged;
221
224
  if (r?.status === "blocked" || ["invalid", "already-fixed"].includes(r?.status)) put("result.json", JSON.stringify(r));
222
- else if (r) put("result.json", JSON.stringify({ ...r, requirements: o.claims ?? w.contract.requirements.filter((x) => x.disposition === "deliver").map((x) => ({ id: x.id, status: "implemented", evidence: "src/foo.js:3" })),
225
+ else if (r) put("result.json", JSON.stringify({ ...r, requirements: (fix && n > 2 ? o.resumeClaims : null) ?? o.claims ?? w.contract.requirements.filter((x) => x.disposition === "deliver").map((x) => ({ id: x.id, status: "implemented", evidence: "src/foo.js:3" })),
223
226
  validation: (fix && n > 2 ? o.resumeValidation : null) ?? o.validation ?? (w.contract.validate ?? []).map((v) => ({ id: v.id, command: v.command, exit: 0 })), amendments: (fix && n > 2 ? o.resumeAmendments : null) ?? o.amendments ?? [] }));
224
227
  }
225
228
  if ((fix && !o.freshNoCommit) || /Merging origin\//.test(c.prompt)) { w.head = `bbbb${w.calls.length}`.padEnd(16, "0"); if (!o.leaveConflicts) { w.conflictFiles = []; w.mergeInProgress = false; } }
@@ -237,6 +240,10 @@ function world(o = {}) {
237
240
  };
238
241
  return w;
239
242
  }
243
+ // #6083: the codes the gate cut made advisory. Tests of the resume and needs-human mechanics exercise a blocking code, so they
244
+ // re-promote these with engine.conformance_kinds enforce (ENF); the advisory default itself is pinned by the "gate cut (#6083)" tests.
245
+ const LEGACY_ENFORCE = Object.fromEntries(["conformance.unimplemented", "conformance.e2e_unverified", "conformance.untracked_deferral", "conformance.unjustified_deferral", "conformance.guard_broken", "conformance.preserve_violated", "env.tool_missing", "env.repro_unrunnable", "env.validate_timeout", "contract.invalid_command"].map((c) => [c, "enforce"]));
246
+ const ENF = { conformanceKinds: LEGACY_ENFORCE };
240
247
  const run = (w, extra = {}) => runCore({ issue: 7, repo: "o/r", lane: "staging", cwd: "/repo", worktreeRoot: "/wt", dir: tmpDir("core-"), conformance: "enforce",
241
248
  io: w.io, emitTelemetry: async (r) => w.telemetry.push(r), random: () => 0.5, ...extra });
242
249
  /** #5728: run `fn` with a fixed, idle load average: precheck.mjs sizes its timeout retry from the real host load, so a loaded host defers the check to CI. */
@@ -390,25 +397,11 @@ describe("core work-on", () => {
390
397
  assert.match(t, /\| Plan \| not reached \|/);
391
398
  });
392
399
 
393
- it("an unknown amendment kind gets one in-lane correction before the gate and does not use the conformance resume (#5089)", async () => {
394
- const w = world({ amendments: [{ kind: "deliverable_change", requirement: "R1", why: "no Linux build" }], resumeAmendments: [], reviews: [ok()] });
395
- const r = await run(w);
396
- assert.equal(r.terminalReason, "merged");
397
- assert.ok(builders(w).some((c) => /amendments in .*result\.json are not valid/.test(c[4] ?? "")), "the correction prompt ran");
398
- assert.match(traj(w)[0], /Amendment kinds invalid \(1\); builder asked to correct/);
399
- });
400
400
 
401
- it("an unknown amendment kind the builder does not fix parks only after the one correction (#5089)", async () => {
402
- const bad = [{ kind: "deliverable_change", requirement: "R1", why: "w" }];
403
- const w = world({ amendments: bad, resumeAmendments: bad, reviews: [ok()] });
404
- const r = await run(w);
405
- assert.equal(r.terminalReason, "needs-human");
406
- assert.equal(builders(w).filter((c) => /amendments in .*result\.json are not valid/.test(c[4] ?? "")).length, 1);
407
- });
408
401
 
409
402
  it("nonconforming review -> builder resumed in its session with the failed rows -> re-review conforms -> merge; the note is re-posted", async () => {
410
403
  const w = world({ reviews: [bad("src/foo.js:9 still wrong"), ok()] });
411
- const r = await run(w);
404
+ const r = await run(w, ENF);
412
405
  assert.equal(r.terminalReason, "merged");
413
406
  const b = builders(w);
414
407
  assert.equal(b.length, 3);
@@ -427,7 +420,7 @@ describe("core work-on", () => {
427
420
 
428
421
  it("nonconforming twice -> needs-human with the specific code, no PR, issue left open", async () => {
429
422
  const w = world({ reviews: [bad(), bad("still bad")] });
430
- const r = await run(w, { reviewMaxResumes: 1 });
423
+ const r = await run(w, { ...ENF, reviewMaxResumes: 1 });
431
424
  assert.equal(r.terminalReason, "needs-human");
432
425
  assert.equal(r.code, "conformance.unimplemented");
433
426
  assert.equal(w.closed.length, 0);
@@ -478,16 +471,15 @@ describe("core work-on", () => {
478
471
 
479
472
  it("a CONFORMS verdict whose rows fail is not conforming (the engine computes the verdict)", async () => {
480
473
  const w = world({ reviews: [bad("half done", "CONFORMS"), ok()] });
481
- assert.equal((await run(w)).terminalReason, "merged");
474
+ assert.equal((await run(w, ENF)).terminalReason, "merged");
482
475
  assert.equal(builders(w).length, 3);
483
- assert.match(traj(w)[0], /reviewer verdict contradicted its rows/);
484
476
  });
485
477
 
486
478
  it("a reviewer that judges a deferral unjustified gets the builder resumed to implement it; nothing is filed for it", async () => {
487
479
  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" }] };
488
480
  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);
489
481
  const w = world({ contract: k, claims: [{ id: "R1", status: "implemented" }], reviews: [rej, rej] });
490
- const r = await run(w);
482
+ const r = await run(w, ENF);
491
483
  assert.equal(r.code, "conformance.unjustified_deferral"); assert.equal(w.followups.length, 0); assert.equal(w.merges.length, 0);
492
484
  assert.match(builders(w)[2][4], /conformance\.unjustified_deferral: R2 defer is not justified: one line in bar\.js; do it now; implement it/);
493
485
  });
@@ -567,6 +559,23 @@ describe("core work-on", () => {
567
559
  assert.equal(real.code, "builder.blocked");
568
560
  });
569
561
 
562
+ it("#6076 an unhappy terminal posts one FORGE:LANE_AUDIT; a failing audit post leaves the terminal reason unchanged", async () => {
563
+ const block = { status: "blocked", summary: "need creds", block: { kind: "human", why: "credentials" } };
564
+ const w = world({ changed: [], result: block });
565
+ const r = await run(w);
566
+ assert.equal(r.terminalReason, "needs-human");
567
+ const audits = w.comments.filter((c) => c.includes("<!-- FORGE:LANE_AUDIT -->"));
568
+ assert.equal(audits.length, 1);
569
+ assert.match(audits[0], /"status": "proposed"/);
570
+ assert.match(audits[0], /"engine_version"/);
571
+ const bad = world({ changed: [], result: block });
572
+ const gh = bad.io.gh;
573
+ bad.io.gh = async (a) => { if (a[0] === "issue" && a[1] === "comment" && String(a[a.indexOf("--body") + 1]).includes("FORGE:LANE_AUDIT")) throw new Error("gh down"); return gh(a); };
574
+ const r2 = await run(bad);
575
+ assert.equal(r2.terminalReason, "needs-human");
576
+ assert.equal(r2.code, r.code);
577
+ });
578
+
570
579
  // #4124: a builder block is typed; only kind "human" with an allowed reason may reach needs-human.
571
580
  const depWorld = (o, deps) => {
572
581
  const w = world(o);
@@ -579,6 +588,29 @@ describe("core work-on", () => {
579
588
  };
580
589
  return w;
581
590
  };
591
+ it("#5979 a second identical failure parks with one PARKED summary (failure.repeated), no relaunch; an unchanged DEPENDENCY is not re-posted", async () => {
592
+ const block = { status: "blocked", summary: "need creds", block: { kind: "human", why: "credentials" } };
593
+ const opts = { changed: [] };
594
+ const first = world(opts);
595
+ const r1 = await run(first);
596
+ assert.notEqual(r1.code, "failure.repeated", "the 1st failure is not parked");
597
+ const nh = first.comments.find((c) => c.includes("<!-- FORGE:NEEDS_HUMAN -->"));
598
+ assert.ok(nh && /sig=[0-9a-f]{12}/.test(nh), "every NEEDS_HUMAN carries its signature");
599
+ const again = world({ ...opts, viewComments: [{ author: { login: "rapiercraft-forgedock" }, body: nh }] });
600
+ const r2 = await run(again);
601
+ assert.equal(r2.code, "failure.repeated");
602
+ {
603
+ assert.equal(again.comments.filter((c) => c.includes("<!-- FORGE:PARKED -->")).length, 1);
604
+ assert.ok(again.edits.some((e) => e.includes("parked:failure.repeated")));
605
+ assert.ok(!again.comments.some((c) => c.includes("<!-- FORGE:NEEDS_HUMAN -->")), "the repeat posts the summary instead of another NEEDS_HUMAN");
606
+ }
607
+ const dep = depWorld({ changed: [], result: { status: "blocked", summary: "needs #3", block: { kind: "dependency", issues: [3] } } }, { 3: { state: "OPEN", labels: [] } });
608
+ await run(dep);
609
+ const posted = dep.comments.find((c) => c.includes("<!-- FORGE:DEPENDENCY -->"));
610
+ const dep2 = depWorld({ changed: [], viewComments: [{ author: { login: "rapiercraft-forgedock" }, body: posted }], result: block.block ? { status: "blocked", summary: "needs #3", block: { kind: "dependency", issues: [3] } } : null }, { 3: { state: "OPEN", labels: [] } });
611
+ await run(dep2);
612
+ assert.ok(!dep2.comments.some((c) => c.includes("<!-- FORGE:DEPENDENCY -->")), "same state: skipped");
613
+ });
582
614
  const noNeedsHuman = (w) => {
583
615
  assert.ok(!w.edits.some((e) => e.includes("--add-label") && e.includes("needs-human")), JSON.stringify(w.edits));
584
616
  assert.ok(!w.comments.some((c) => c.includes("FORGE:NEEDS_HUMAN")));
@@ -710,14 +742,6 @@ describe("core work-on", () => {
710
742
  assert.ok(w.comments.some((c) => /FORGE:DECOMPOSED/.test(c) && /size: 40 files, 4000 lines .* oversize yes/.test(c)));
711
743
  });
712
744
 
713
- it("#4857 a product-decision block over an unrunnable validate is untyped (one correction resume), a real one stays human", () => {
714
- const u = classifyBlock({ summary: "V2 cannot run: poetry found no pyproject at the repo root", block: { kind: "human", why: "product-decision" } }, 1);
715
- assert.equal(u.kind, "untyped");
716
- assert.match(u.problem, /substitute-validate/);
717
- assert.equal(classifyBlock({ summary: "needs a pricing decision", block: { kind: "human", why: "product-decision" } }, 1).kind, "human");
718
- assert.equal(classifyBlock({ summary: "V1 needs the prod key", block: { kind: "human", why: "credentials" } }, 1).kind, "human");
719
- });
720
-
721
745
  it("#5342 classifyBlock: design-invalidated needs a decision and a why; the other kinds are unchanged", () => {
722
746
  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);
723
747
  assert.deepEqual([ok.kind, ok.epic, ok.paths], ["design-invalidated", 5, ["src/a.ts"]]);
@@ -1064,7 +1088,13 @@ describe("core work-on", () => {
1064
1088
  // #4685: a missing tool is never a credential block on a remote lane; local lanes and real credential needs stay human.
1065
1089
  assert.equal(await rb("validate V1 needs promtool via docker; no docker daemon in this sandbox", remote), "env.tool_missing");
1066
1090
  assert.equal(await rb("ModuleNotFoundError: No module named 'yaml'", remote), "env.tool_missing");
1067
- assert.equal(await rb("promtool: command not found", { ...remote, placement: { where: "local", reason: "x" } }), "builder.blocked");
1091
+ assert.equal(await rb("promtool: command not found", { ...remote, placement: { where: "local", reason: "x" } }), "env.tool_missing"); // #6106: a missing tool is env on any placement
1092
+ // #6106: the two real block texts are env gaps whatever reason the builder typed; a genuine human reason stays human
1093
+ const pd = (summary) => code(world({ result: { status: "blocked", summary, block: { kind: "human", why: "product-decision" } } }));
1094
+ assert.equal(await pd("the yaml lane-tools recipe lives in the engine, so the lane cannot install it"), "env.tool_missing");
1095
+ assert.equal(await rb("no Python 3.11 interpreter in the sandbox (only 3.12.3)"), "env.tool_missing");
1096
+ assert.equal(await pd("needs Stripe approval before the pricing change ships"), "builder.blocked");
1097
+ assert.equal(await rb("needs the production API key and credentials from the owner"), "builder.blocked");
1068
1098
  assert.equal(await rb("this lane has no sops/age key", { ...remote, hostCaps: undefined }), "builder.blocked");
1069
1099
  assert.equal(await rb("this lane has no sops/age key", { ...remote, placement: { where: "local", reason: "x" } }), "builder.blocked");
1070
1100
  assert.equal(await code(world({ changed: [] })), "builder.no_commit");
@@ -1340,27 +1370,19 @@ describe("conformance gate (frozen contract, precheck, structured review)", () =
1340
1370
  assert.equal(w.closed[0].at(-1), "completed");
1341
1371
  });
1342
1372
 
1343
- it("scope creep: an unauthorized file is caught by the precheck before any reviewer run; the resume reverts it and it merges", async () => {
1373
+ it("scope creep is advisory (unclog): recorded as an ADVISORY event, no builder resume, the review runs and it merges", async () => {
1344
1374
  const dir = tmpDir("conf-creep-");
1345
- const w = world({ changed: ["src/foo.js", "src/billing.js", "test/foo.test.js"], resumeChanged: ["src/foo.js", "test/foo.test.js"] });
1375
+ const w = world({ changed: ["src/foo.js", "src/billing.js", "test/foo.test.js"] });
1346
1376
  const r = await run(w, { dir });
1347
1377
  assert.equal(r.terminalReason, "merged");
1348
- assert.equal(reviewers(w).length, 1, "the reviewer ran only after the precheck passed");
1349
- assert.match(builders(w)[2][4], /conformance\.scope_creep: changed outside the contract's deliverables: src\/billing\.js/);
1350
- const ev = events(dir);
1351
- assert.ok(ev.indexOf("PRECHECK") < ev.indexOf("CONFORMANCE"));
1352
- });
1353
-
1354
- it("scope creep that persists is needs-human conformance.scope_creep with no reviewer tokens spent", async () => {
1355
- const w = world({ changed: ["src/foo.js", "src/billing.js", "test/foo.test.js"] });
1356
- const r = await run(w);
1357
- assert.equal(r.code, "conformance.scope_creep"); assert.equal(reviewers(w).length, 0);
1358
- blockedNothingMerged(w);
1378
+ assert.equal(reviewers(w).length, 1);
1379
+ assert.ok(!builders(w).some((c) => /conformance\.scope_creep/.test(c[4] ?? "")), "no resume for advisory scope creep");
1380
+ assert.ok(readLog(dir, 7).some((e) => e.event === "ADVISORY" && e.rows.includes("scope_creep")));
1359
1381
  });
1360
1382
 
1361
1383
  it("a claimed 'follow-up' with no typed deferral is needs-human conformance.untracked_deferral; nothing is filed or merged", async () => {
1362
1384
  const w = world({ contract: two(), changed: files2, claims: [{ id: "R1", status: "implemented" }, { id: "R2", status: "deferred", note: "follow-up" }] });
1363
- const r = await run(w);
1385
+ const r = await run(w, ENF);
1364
1386
  assert.equal(r.code, "conformance.untracked_deferral"); assert.equal(reviewers(w).length, 0); assert.equal(w.followups.length, 0);
1365
1387
  assert.match(nhBody(w), /R2 was contracted as deliver but reported "deferred" without a typed amendment/);
1366
1388
  blockedNothingMerged(w);
@@ -1370,7 +1392,7 @@ describe("conformance gate (frozen contract, precheck, structured review)", () =
1370
1392
  const w = world({ contract: two(), changed: files2, claims: [{ id: "R1", status: "implemented" }, { id: "R2", status: "deferred" }],
1371
1393
  resumeAmendments: [{ kind: "defer", requirement: "R2", why: "callers live in another module's release train" }],
1372
1394
  reviews: [conf({}, two("defer", { tracked: "#900" }), files2)] });
1373
- const r = await run(w);
1395
+ const r = await run(w, ENF);
1374
1396
  assert.equal(r.terminalReason, "merged");
1375
1397
  assert.equal(w.followups.length, 1);
1376
1398
  assert.deepEqual(w.followups[0].items.map((i) => i.key), ["R2: Existing callers of foo keep working."]);
@@ -1689,17 +1711,9 @@ describe("devdocs freshness gate (the repo's own scripts/check-devdocs-freshness
1689
1711
  };
1690
1712
  const STALE = { ok: false, output: "STALE: bin/lean/lean.mjs changed but no dossier matching it was touched (devdocs/modules/lean.md)" };
1691
1713
 
1692
- it("a stale dossier gets one builder resume with the script's output, then merges once it passes", async () => {
1693
- const w = dworld([STALE, { ok: true, output: "OK" }]);
1694
- assert.equal((await run(w)).terminalReason, "merged");
1695
- assert.equal(builders(w).length, 3, "plan + implement + one docs resume");
1696
- assert.match(builders(w)[2][4], /docs freshness check[\s\S]*devdocs\/modules\/lean\.md/);
1697
- assert.equal(w.docsCalls[0].base, "origin/staging");
1698
- assert.match(traj(w).at(-1), /Docs freshness check failed; builder resumed once/);
1699
- });
1700
1714
 
1701
- it("a doc the docs round edits outside the deliverables is an implied deliverable (no scope_creep); an unrelated extra file still is", async () => {
1702
- for (const [extra, code] of [[[], null], [["src/billing.js"], "conformance.scope_creep"]]) {
1715
+ it("a doc the docs round edits outside the deliverables is an implied deliverable; an unrelated extra file is advisory scope creep (unclog), both merge", async () => {
1716
+ for (const [extra, code] of [[[], null], [["src/billing.js"], null]]) {
1703
1717
  const w = dworld([STALE, { ok: true, output: "OK" }], { changed: ["src/foo.js", "test/foo.test.js"] });
1704
1718
  const inner = w.io.docsFreshness;
1705
1719
  w.io.docsFreshness = async (x) => { const r = await inner(x); if (r?.ok && !w.changed.includes("devdocs/modules/lean.md")) w.changed = [...w.changed, "devdocs/modules/lean.md", ...extra]; return r; };
@@ -1708,12 +1722,6 @@ describe("devdocs freshness gate (the repo's own scripts/check-devdocs-freshness
1708
1722
  }
1709
1723
  });
1710
1724
 
1711
- it("still stale after the resume: needs-human docs.stale, before any PR or reviewer run", async () => {
1712
- const w = dworld([STALE]);
1713
- const r = await run(w);
1714
- assert.equal(r.code, "docs.stale"); assert.equal(w.prs.length, 0); assert.equal(reviewers(w).length, 0);
1715
- assert.equal(builders(w).length, 3);
1716
- });
1717
1725
 
1718
1726
  it("no script in the repo, or it cannot run (null): no resume, the run is unchanged", async () => {
1719
1727
  const w = dworld([null]);
@@ -1721,22 +1729,6 @@ describe("devdocs freshness gate (the repo's own scripts/check-devdocs-freshness
1721
1729
  assert.equal(builders(w).length, 2);
1722
1730
  });
1723
1731
 
1724
- it("the effect: absent script -> null; exit 0 -> ok; exit 1 -> stale with output; exit 2 -> null", async () => {
1725
- const io = makeLeanIo({ repo: "o/r" });
1726
- const dir = tmpDir("docs-fresh-");
1727
- assert.equal(await io.docsFreshness({ cwd: dir, base: "origin/x" }), null);
1728
- mkdirSync(join(dir, "scripts"), { recursive: true });
1729
- const put = (body) => writeFileSync(join(dir, "scripts", "check-devdocs-freshness.sh"), `#!/usr/bin/env bash\n${body}\n`);
1730
- put('echo "OK: $1"; exit 0');
1731
- assert.deepEqual(await io.docsFreshness({ cwd: dir, base: "origin/x" }), { ok: true, output: "OK: origin/x\n" });
1732
- put('echo "STALE: lean.md"; exit 1');
1733
- const st = await io.docsFreshness({ cwd: dir, base: "origin/x" });
1734
- assert.equal(st.ok, false); assert.match(st.output, /STALE: lean\.md/);
1735
- put("echo usage >&2; exit 2");
1736
- assert.equal(await io.docsFreshness({ cwd: dir, base: "origin/x" }), null);
1737
- put('[ -z "$PR_BODY" ] && exit 0 || exit 1');
1738
- assert.equal((await io.docsFreshness({ cwd: dir, base: "origin/x" })).ok, true, "PR_BODY is empty: no exemption is read from the environment");
1739
- });
1740
1732
  });
1741
1733
 
1742
1734
  describe("review row skeleton and targeted retry (#4160)", () => {
@@ -1939,7 +1931,7 @@ describe("conformance shadow mode (the default)", () => {
1939
1931
  it("scope creep does not block in shadow (as today) but is recorded", async () => {
1940
1932
  const w = world({ changed: ["src/foo.js", "src/billing.js", "test/foo.test.js"], reviews: [conf({}, CONTRACT, ["src/foo.js", "src/billing.js", "test/foo.test.js"])] });
1941
1933
  assert.equal((await runShadow(w)).terminalReason, "merged");
1942
- assert.match(shadowNote(w), /would BLOCK[\s\S]*conformance\.scope_creep[\s\S]*src\/billing\.js/);
1934
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\): conformance\.scope_creep/); // unclog: advisory, not a would-block row
1943
1935
  });
1944
1936
 
1945
1937
  it("#4160 an incomplete review gets one targeted re-ask with only the missing ids, then needs-human; never merges in shadow", async () => {
@@ -1977,10 +1969,10 @@ describe("conformance shadow mode (the default)", () => {
1977
1969
 
1978
1970
  it("shadow still blocks what the previous reviewer blocked on: a requirement not implemented gets one resume, then needs-human", async () => {
1979
1971
  const w = world({ reviews: [bad("still null-derefs"), bad("still null-derefs")] });
1980
- const r = await runShadow(w);
1972
+ const r = await runShadow(w, ENF);
1981
1973
  assert.equal(r.code, "conformance.unimplemented"); assert.equal(builders(w).length, 3); assert.equal(w.merges.length, 0);
1982
1974
  const w2 = world({ reviews: [conf({ regressions: [{ at: "src/bar.js:4", failure: "caller passes undefined" }] }), ok()] });
1983
- assert.equal((await runShadow(w2)).terminalReason, "merged"); assert.equal(builders(w2).length, 3, "a regression is resumed in shadow too");
1975
+ assert.equal((await runShadow(w2, ENF)).terminalReason, "merged"); assert.equal(builders(w2).length, 3, "a regression is resumed in shadow too");
1984
1976
  });
1985
1977
 
1986
1978
  it("shadow blocks a failed validate command (#4160): one resume, then needs-human, and no reviewer tokens are spent", async () => {
@@ -1998,12 +1990,12 @@ describe("conformance shadow mode (the default)", () => {
1998
1990
  const w = world({ validation: v }); let provisioned = 0, installed = false;
1999
1991
  w.io.deps = { prepare: async () => { provisioned++; installed = true; return []; } };
2000
1992
  w.io.runCommand = async () => (installed ? { rc: 0, output: "" } : { rc: 1, output: "ModuleNotFoundError: No module named 'pytest'" });
2001
- const ok = await run(w, { conformance: "enforce" });
1993
+ const ok = await run(w, { ...ENF, conformance: "enforce" });
2002
1994
  assert.notEqual(ok.code, OUTCOME_CODES.ENV_TOOL_MISSING); assert.equal(provisioned >= 1, true);
2003
1995
  const w2 = world({ validation: v }); let again = 0;
2004
1996
  w2.io.deps = { prepare: async () => { again++; return []; } };
2005
1997
  w2.io.runCommand = async () => ({ rc: 1, output: "ModuleNotFoundError: No module named 'yaml'" });
2006
- const r = await run(w2, { conformance: "enforce" });
1998
+ const r = await run(w2, { ...ENF, conformance: "enforce" });
2007
1999
  assert.equal(r.code, OUTCOME_CODES.ENV_TOOL_MISSING); assert.equal(w2.merges.length, 0); assert.equal(again, 2, "the toolchain prepare plus exactly one provisioning retry");
2008
2000
  });
2009
2001
 
@@ -2024,13 +2016,13 @@ describe("conformance shadow mode (the default)", () => {
2024
2016
  const v = [{ id: "V1", command: "node --test test/foo.test.js", exit: 0 }];
2025
2017
  const w = world({ validation: v }); let calls = 0;
2026
2018
  w.io.deps = { prepare: async () => { calls++; return [{ status: "failed", eco: "npm", dir: ".", key: null, ms: 1, reason: "install failed: ERESOLVE" }]; } };
2027
- const r = await run(w, { conformance: "enforce" });
2019
+ const r = await run(w, { ...ENF, conformance: "enforce" });
2028
2020
  assert.equal(r.code, OUTCOME_CODES.ENV_TOOL_MISSING); assert.equal(w.merges.length, 0);
2029
2021
  assert.equal(calls, 2, "the toolchain prepare plus exactly one provisioning retry");
2030
2022
  assert.match(nhBody(w), /dependency install failed \(npm: install failed: ERESOLVE\) for a package the changed file/);
2031
2023
  const w2 = world({ validation: v });
2032
2024
  w2.io.deps = { prepare: async () => [{ status: "failed", eco: "poetry", dir: "services/other", key: null, ms: 1, reason: "install failed" }] };
2033
- const r2 = await run(w2, { conformance: "enforce" });
2025
+ const r2 = await run(w2, { ...ENF, conformance: "enforce" });
2034
2026
  assert.notEqual(r2.code, OUTCOME_CODES.ENV_TOOL_MISSING);
2035
2027
  });
2036
2028
 
@@ -2039,7 +2031,7 @@ describe("conformance shadow mode (the default)", () => {
2039
2031
  for (const conformance of ["shadow", "enforce"]) {
2040
2032
  const w = world({ validation: v }), ran = [];
2041
2033
  w.io.runCommand = async (a) => { ran.push(a); return { rc: 1, output: "ModuleNotFoundError: No module named 'yaml'" }; };
2042
- const r = await run(w, { conformance });
2034
+ const r = await run(w, { ...ENF, conformance });
2043
2035
  assert.equal(r.code, OUTCOME_CODES.ENV_TOOL_MISSING, conformance); assert.equal(w.merges.length, 0);
2044
2036
  assert.equal(builders(w).length, 2, "plan + implement only"); assert.equal(reviewers(w).length, 0);
2045
2037
  assert.match(nhBody(w), /Environment error \(not a conformance failure\): the host is missing yaml/);
@@ -2063,11 +2055,10 @@ describe("conformance shadow mode (the default)", () => {
2063
2055
  const ok = world({ validation: v }); ok.io.runCommand = async () => ({ rc: 0, output: "" });
2064
2056
  assert.equal((await run(ok, { conformance: "enforce", placement: { where: "local", reason: "x" }, recover: { code: ENV_VALIDATE_PLACEMENT, attempt: 1, final: true } })).terminalReason, "merged");
2065
2057
  });
2066
- const remoteV = { conformance: "enforce", placement: { where: "remote", reason: "mode remote" } };
2058
+ const remoteV = { ...ENF, conformance: "enforce", placement: { where: "remote", reason: "mode remote" } };
2067
2059
  const v5730 = [{ id: "V1", command: "node --test test/foo.test.js", exit: 1 }];
2068
2060
  it("5730: remote validate_failed with stale-artifact output resumes the builder", async () => {
2069
- const stale = "listings/official/maps/maps-places/agent.md: missing or out of date (run --render-agent-md --render-page)";
2070
- for (const output of [stale, "not ok 1 - foo\n AssertionError: expected 3, got 4"]) {
2061
+ for (const output of ["not ok 1 - foo\n AssertionError: expected 3, got 4"]) { // #6083: a stale generated artifact (validate_drift) is advisory
2071
2062
  const w = world({ validation: v5730 }); w.io.runCommand = async () => ({ rc: 1, output });
2072
2063
  const r = await run(w, remoteV);
2073
2064
  assert.notEqual(r.code, ENV_VALIDATE_PLACEMENT, output); assert.ok(builders(w).length >= 3, "the builder resumes");
@@ -2091,31 +2082,13 @@ describe("conformance shadow mode (the default)", () => {
2091
2082
  for (const conformance of ["shadow", "enforce"]) {
2092
2083
  const w = world({ validation: v });
2093
2084
  w.io.runCommand = async () => ({ rc: 124, output: "(timed out after 1s)" });
2094
- const r = await run(w, { conformance });
2085
+ const r = await run(w, { ...ENF, conformance });
2095
2086
  assert.equal(r.code, ENV_VALIDATE_TIMEOUT, conformance); assert.equal(r.terminalReason, "needs-human");
2096
2087
  assert.equal(classifyNeedsHuman(r), "recoverable"); assert.equal(w.merges.length, 0);
2097
2088
  assert.equal(builders(w).length, 2, "plan + implement only"); assert.equal(reviewers(w).length, 0);
2098
2089
  assert.match(nhBody(w), /timed out \(exit 124\) even after one longer retry/);
2099
2090
  }
2100
2091
  });
2101
- it("#4979 the engine reruns a substituted validate's frozen command: a runnable failing one blocks, an unrunnable one lets the substitute stand", async () => {
2102
- const amendments = [{ kind: "substitute-validate", validate: "V1", command: "node --test test/foo2.test.js", why: "the frozen path does not exist" }];
2103
- const validation = [{ id: "V1", command: "node --test test/foo2.test.js", exit: 0 }];
2104
- const lane = (frozenOut) => {
2105
- const w = world({ validation, amendments, resumeValidation: validation, resumeAmendments: amendments }), ran = [];
2106
- w.io.runCommand = async (a) => { ran.push(a); return a.command === "node --test test/foo.test.js" ? frozenOut : { rc: 0, output: "" }; };
2107
- return { w, ran };
2108
- };
2109
- const dir = tmpDir("subst-");
2110
- const bad = lane({ rc: 1, output: "not ok 1 - foo handles null\nAssertionError: expected 1" });
2111
- const rb = await run(bad.w, { conformance: "enforce", dir });
2112
- assert.equal(rb.terminalReason, "needs-human"); assert.equal(bad.w.merges.length, 0);
2113
- assert.match(nhBody(bad.w), /frozen command runs and fails \(exit 1\)/);
2114
- assert.ok(bad.ran.some((a) => a.command === "node --test test/foo.test.js" && posix(a.cwd) === WT && a.env), "the frozen command is rerun in the worktree with the lane env");
2115
- assert.deepEqual(readLog(dir, 7).filter((e) => e.event === "SUBSTITUTE_RERUN").map((e) => e.runs), [[{ id: "V1", rc: 1 }], [{ id: "V1", rc: 1 }]]);
2116
- const good = lane({ rc: 1, output: "no tests ran: no test files matched test/foo.test.js" });
2117
- assert.equal((await run(good.w, { conformance: "enforce" })).terminalReason, "merged");
2118
- });
2119
2092
  it("#4323 a rerun that fails for a repo reason stays conformance.unimplemented; one that passes merges", async () => {
2120
2093
  const v = [{ id: "V1", command: "node --test test/foo.test.js", exit: 1 }];
2121
2094
  const w = world({ validation: v, resumeValidation: v });
@@ -2147,7 +2120,7 @@ describe("conformance shadow mode (the default)", () => {
2147
2120
  const GC = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "G1", command: "node --test test/bar.test.js", regression: true }] };
2148
2121
  const w = world({ contract: GC, validation: [{ id: "V1", command: CONTRACT.validate[0].command, exit: 0 }] });
2149
2122
  delete w.io.runCommand;
2150
- const r = await runShadow(w);
2123
+ const r = await runShadow(w, ENF);
2151
2124
  assert.notEqual(r.terminalReason, "merged"); assert.ok(builders(w).length >= 3, "validate_missing resumes the builder");
2152
2125
  });
2153
2126
  it("#5728 a fix resume that hits the context ceiling restarts with the failure list, not the full build prompt", async () => {
@@ -2308,7 +2281,7 @@ describe("conformance shadow mode (the default)", () => {
2308
2281
  assert.deepEqual(reverts, ["clean -fdq -- .pytest_cache_x/log", "checkout -- src/bar.js"]);
2309
2282
  assert.ok(traj(w).some((x) => /Validate preflight reverted 2 path\(s\) its runs changed/.test(x)));
2310
2283
  });
2311
- it("#4353 the #4348 contract shape: an allowlist validate is dropped at freeze (CONTRACT_SCOPE_VALIDATE_DROPPED), the amended lane merges, and a real out-of-scope edit is still scope_creep", async () => {
2284
+ it("#4353 the #4348 contract shape: an allowlist validate is dropped at freeze (CONTRACT_SCOPE_VALIDATE_DROPPED), the amended lane merges, and a real out-of-scope edit is advisory scope_creep (unclog)", async () => {
2312
2285
  const ALLOW = 'test -z "$(git diff --name-only origin/staging...HEAD | grep -v -x -e src/foo.js -e test/foo.test.js)"';
2313
2286
  const c = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: ALLOW }] }, files = ["src/foo.js", "test/foo.test.js", "docs/foo.md"];
2314
2287
  const shape = (changed) => ({ contract: c, changed, amendments: [{ kind: "add-deliverable", path: "docs/foo.md", why: "the docs-freshness rule needs the module doc" }],
@@ -2326,8 +2299,8 @@ describe("conformance shadow mode (the default)", () => {
2326
2299
  assert.ok(traj(w).some((t) => /Scope-check validate V2 dropped at contract freeze/.test(t)));
2327
2300
  const creep = world(shape([...files, "src/other.js"]));
2328
2301
  creep.io.runCommand = async () => ({ rc: 1, output: "" });
2329
- assert.equal((await run(creep)).code, "conformance.scope_creep");
2330
- assert.ok(builders(creep).some((b) => /changed outside the contract's deliverables: src\/other\.js/.test(b[4])));
2302
+ assert.equal((await run(creep)).terminalReason, "merged", "unclog: an out-of-scope edit is advisory");
2303
+ assert.match(traj(creep).join("\n"), /Advisory \(not blocking\): conformance\.scope_creep[^\n]*src\/other\.js/);
2331
2304
  });
2332
2305
 
2333
2306
  it("#4404 a Lighthouse requirement is tagged out_of_band at freeze; with instrumentation the lane merges and the PR body names the job", async () => {
@@ -2388,26 +2361,26 @@ describe("conformance shadow mode (the default)", () => {
2388
2361
 
2389
2362
  it("#4160 shadow blocks a validate step with no recorded result and an invalid amendment like a reviewer-found unimplemented requirement", async () => {
2390
2363
  const w = world({ validation: [] });
2391
- const r = await runShadow(w);
2364
+ const r = await runShadow(w, ENF);
2392
2365
  assert.equal(r.code, "conformance.unimplemented"); assert.equal(w.merges.length, 0);
2393
2366
  assert.equal(builders(w).length, 3, "one builder resume"); assert.equal(reviewers(w).length, 0, "no reviewer tokens on a precheck block");
2394
2367
  assert.match(builders(w)[2][4], /validate V1 .*has no recorded result/);
2395
2368
  const fixed = world({ validation: [], resumeValidation: [{ id: "V1", command: "node --test test/foo.test.js", exit: 0 }] });
2396
- assert.equal((await runShadow(fixed)).terminalReason, "merged", "recorded by the resume, then merges");
2369
+ assert.equal((await runShadow(fixed, ENF)).terminalReason, "merged", "recorded by the resume, then merges");
2397
2370
  const a = world({ amendments: [{ kind: "add-deliverable", path: "src/x.js" }] });
2398
2371
  const ra = await runShadow(a);
2399
- assert.equal(ra.code, "conformance.unimplemented"); assert.match(nhBody(a), /amendment without why/);
2372
+ assert.equal(ra.terminalReason, "merged", "#6083: an invalid amendment is simply not applied, no gate"); assert.doesNotMatch(traj(a).join("\n"), /amendment without why/);
2400
2373
  });
2401
2374
  it("#4737 decision records are persisted after the merge, never at gate time", async () => {
2402
2375
  const dir = tmpDir("dec-"); const prev = process.env.FORGEDOCK_DECISIONS_DIR; process.env.FORGEDOCK_DECISIONS_DIR = dir;
2403
2376
  try {
2404
2377
  const amendments = [{ kind: "decision", why: "w", decision: { choice: "use X", anchors: ["src/db.ts"], why: "w" } }];
2405
2378
  const bad = world({ validation: [], amendments });
2406
- assert.equal((await runShadow(bad)).code, "conformance.unimplemented");
2379
+ assert.equal((await runShadow(bad, ENF)).code, "conformance.unimplemented");
2407
2380
  assert.ok(!bad.comments.some((c) => c.includes("FORGE:DECISION")), "a lane that never merges records nothing");
2408
2381
  assert.equal(readdirSync(dir).length, 0, "no index written");
2409
2382
  const ok = world({ amendments });
2410
- assert.equal((await runShadow(ok)).terminalReason, "merged");
2383
+ assert.equal((await runShadow(ok, ENF)).terminalReason, "merged");
2411
2384
  assert.ok(ok.comments.some((c) => c.includes("FORGE:DECISION")), "recorded after the merge");
2412
2385
  assert.equal(readdirSync(dir).length, 1);
2413
2386
  } finally { if (prev === undefined) delete process.env.FORGEDOCK_DECISIONS_DIR; else process.env.FORGEDOCK_DECISIONS_DIR = prev; }
@@ -2485,7 +2458,7 @@ describe("conformance shadow mode (the default)", () => {
2485
2458
  it("#5207 shadow: an in-lane engineering deferral (bucket new-issue) resumes the builder once and is never filed", async () => {
2486
2459
  const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "defer", why: "w", bucket: "new-issue" }] };
2487
2460
  const w = world({ contract: k, claims: [{ id: "R1", status: "implemented" }], reviews: [conf({}, k), conf({}, k)] });
2488
- const r = await runShadow(w);
2461
+ const r = await runShadow(w, ENF);
2489
2462
  assert.equal(r.code, "conformance.unjustified_deferral"); assert.equal(w.followups.length, 0); assert.equal(w.merges.length, 0);
2490
2463
  assert.match(builders(w)[2][4], /R2 is in-lane engineering work \(bucket new-issue\): deliver it/);
2491
2464
  });
@@ -2553,11 +2526,11 @@ describe("conformance shadow mode (the default)", () => {
2553
2526
 
2554
2527
  describe("conformance gate: base-sync and contract size", () => {
2555
2528
  const CONFLICTING = { mergeable: "CONFLICTING", mergeStateStatus: "DIRTY" }, OKSTATE = { mergeable: "MERGEABLE", mergeStateStatus: "CLEAN" };
2556
- it("the base-sync re-review re-runs the precheck on the current files: creep introduced by conflict resolution is caught", async () => {
2529
+ it("the base-sync re-review re-runs the precheck on the current files: creep introduced by conflict resolution is recorded as advisory (unclog)", async () => {
2557
2530
  const w = world({ prView: [CONFLICTING, OKSTATE], mergeResults: ["conflict"], syncChanged: ["src/foo.js", "src/unrelated.js", "test/foo.test.js"] });
2558
2531
  const r = await run(w);
2559
- assert.equal(r.terminalReason, "needs-human"); assert.equal(w.merges.length, 0);
2560
- assert.ok(builders(w).some((b) => /conformance\.scope_creep: changed outside the contract's deliverables: src\/unrelated\.js/.test(b[4])));
2532
+ assert.equal(r.terminalReason, "merged");
2533
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\): conformance\.scope_creep[^\n]*src\/unrelated\.js/);
2561
2534
  });
2562
2535
  it("a large contract is posted compact so its JSON survives the comment cap and stays recoverable", () => {
2563
2536
  const big = { ...CONTRACT, requirements: Array.from({ length: 160 }, (_, i) => ({ id: `R${i}`, quote: "foo must handle a null argument without throwing.".repeat(4), disposition: "deliver" })) };
@@ -2712,22 +2685,9 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2712
2685
  const plan = builderPlanPrompt(7) + hotspotPlanNote(facts([HOT, { ...HOT, path: "a/b.py" }, { ...HOT, path: "c/d.py" }]));
2713
2686
  // 2750: #5750 (outcome vs guidance rows). 2650: #5557 (classification record line) on top of the base's growth. 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).
2714
2687
  assert.ok(approxTokens(plan) <= 2750, `plan prompt with hotspots is ${approxTokens(plan)} tokens`);
2715
- assert.ok(approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([]))) <= 2025, `implement prompt with the hotspot rule is ${approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([])))} of 2025 tokens`); // 2025: #5752 (mechanism supersedes, negative examples, outcome evidence) // 1600: #4591 (never hand-name migration files) and #4596 (i18n translate rule), one line each; 1650: #4726 (e2e rule) // 1925: #5760 (CI budget rule)
2688
+ assert.ok(approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([]))) <= 2075, `implement prompt with the hotspot rule is ${approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([])))} of 2075 tokens`); // 2075: #5979 (substitute-validate and out-of-band from the shared amendment schema); 2025: #5752 (mechanism supersedes, negative examples, outcome evidence) // 1600: #4591 (never hand-name migration files) and #4596 (i18n translate rule), one line each; 1650: #4726 (e2e rule) // 1925: #5760 (CI budget rule)
2716
2689
  });
2717
2690
 
2718
- it("#4519 generated_paths: both prompts name the globs (even with the gate off), and an amendment adding one blocks", async () => {
2719
- const G = ["web/public/openapi*.json"];
2720
- for (const f of [facts([], { generated_paths: G }), facts([HOT], { enabled: false, generated_paths: G })]) {
2721
- assert.match(hotspotPlanNote(f), /Generated paths \(forge\.yaml maintenance\.generated_paths, owned by the repo's generator\): web\/public\/openapi\*\.json\. Never list or amend them in/);
2722
- assert.match(hotspotBuildRule(f), /Generated paths .*web\/public\/openapi\*\.json/);
2723
- }
2724
- assert.equal(hotspotPlanNote(facts([], { generated_paths: [] })), "", "no generated_paths: unchanged");
2725
- const w = hworld(facts([], { generated_paths: G }), [facts([])], { amendments: [{ kind: "add-deliverable", path: "web/public/openapi.json", why: "sync the spec" }] });
2726
- const r = await run(w);
2727
- assert.equal(r.code, "conformance.unimplemented"); assert.equal(w.merges.length, 0);
2728
- assert.match(builders(w)[0][4], /Generated paths .*openapi/);
2729
- assert.match(nh(w), /add-deliverable web\/public\/openapi\.json: generated path/);
2730
- });
2731
2691
 
2732
2692
  it("the plan prompt carries the facts, the implement prompt the configured rule; growth within the limit merges; no extra runner calls", async () => {
2733
2693
  const w = hworld(facts([HOT, COLD], { file_lines: 2000, growth_lines: 150 }), [facts([SMALL])]);
@@ -2742,20 +2702,10 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2742
2702
  assert.equal(plain.calls.filter((c) => c[0] === "runner").length, w.calls.filter((c) => c[0] === "runner").length, "no extra LLM calls");
2743
2703
  });
2744
2704
 
2745
- it("unexempted growth of an over-threshold file blocks in enforce and in shadow: one resume, then needs-human maintenance.hotspot_growth, no reviewer run", async () => {
2746
- for (const conformance of ["enforce", "shadow"]) {
2747
- const w = hworld(facts([HOT]), [facts([GROWN])]);
2748
- const r = await run(w, { conformance });
2749
- assert.equal(r.code, "maintenance.hotspot_growth", conformance); assert.equal(w.merges.length, 0);
2750
- assert.equal(builders(w).length, 3, `${conformance}: plan + implement + one resume`); assert.equal(reviewers(w).length, 0);
2751
- assert.match(builders(w)[2][4], /maintenance\.hotspot_growth: src\/foo\.js grew by 200 lines/);
2752
- assert.match(nh(w), /src\/foo\.js grew by 200 lines/);
2753
- }
2754
- });
2755
2705
 
2756
2706
  it("growth moved out on the resume merges; an exemption in the contract or a failed/missing script never blocks", async () => {
2757
2707
  const w = hworld(facts([HOT]), [facts([GROWN]), facts([SMALL])]);
2758
- assert.equal((await run(w, { conformance: "shadow" })).terminalReason, "merged"); assert.equal(builders(w).length, 3);
2708
+ assert.equal((await run(w, { conformance: "shadow" })).terminalReason, "merged"); assert.equal(builders(w).length, 2, "unclog: advisory growth costs no resume");
2759
2709
  const k = { ...CONTRACT, deliverables: [{ ...CONTRACT.deliverables[0], change: "guard null; hotspot-exempt: the guard must sit next to the parser it protects" }] };
2760
2710
  const we = hworld(facts([HOT]), [facts([GROWN])], { contract: k, reviews: [conf({}, k)] });
2761
2711
  assert.equal((await run(we)).terminalReason, "merged"); assert.equal(builders(we).length, 2);
@@ -2841,10 +2791,39 @@ describe("bug lanes freeze a red-green repro_test (#4271)", () => {
2841
2791
  assert.equal((await run(fixed, { conformance: "shadow" })).terminalReason, "merged"); assert.equal(fixed.rgCalls.length, 2);
2842
2792
  });
2843
2793
 
2794
+ describe("#6058 a requirement with no status row is skipped, not failed", () => {
2795
+ const two2 = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Existing callers of foo keep working.", disposition: "deliver" }],
2796
+ deliverables: [...CONTRACT.deliverables, { id: "D2", path: "src/bar.js", change: "keep callers", requirements: ["R2"] }] };
2797
+ const row = (id) => ({ id, status: "implemented", evidence: "src/foo.js:3" }), runShadow = (w) => run(w, { conformance: "shadow" });
2798
+ it("the one resume names R2 and its quote; a resume that adds the row merges", async () => {
2799
+ const w = world({ contract: two2, claims: [row("R1")], resumeClaims: [row("R1"), row("R2")], reviews: [conf({}, two2)] });
2800
+ const r = await runShadow(w);
2801
+ assert.equal(r.terminalReason, "merged");
2802
+ const resume = builders(w)[2][4];
2803
+ assert.match(resume, /no status row for R2/); assert.match(resume, /R2: "Existing callers of foo keep working\."/);
2804
+ assert.doesNotMatch(resume, /R1:/);
2805
+ });
2806
+ it("still skipped after the targeted resume: a distinct park kind and a detail that says the builder did not address it", async () => {
2807
+ const w = world({ contract: two2, claims: [row("R1")], reviews: [conf({}, two2)] });
2808
+ const r = await runShadow(w);
2809
+ assert.equal(r.terminalReason, "needs-human"); assert.equal(r.kind, "requirement_no_status"); assert.deepEqual(r.requirements, ["R2"]);
2810
+ assert.equal(builders(w).length, 3, "plan + implement + one targeted resume");
2811
+ assert.match(r.detail, /The builder did not address R2: no status row/);
2812
+ assert.match(r.detail, /reported "no status"/, "the census still buckets it");
2813
+ });
2814
+ it("a failing row (not a missing one) keeps the generic resume and park", async () => {
2815
+ const w = world({ contract: two2, claims: [row("R1"), { id: "R2", status: "partial" }], reviews: [conf({}, two2)] });
2816
+ const r = await runShadow(w);
2817
+ assert.equal(r.code, "conformance.unimplemented"); assert.equal(r.kind, undefined);
2818
+ assert.doesNotMatch(builders(w)[2][4], /no status row/);
2819
+ assert.match(builders(w)[2][4], /does not conform/);
2820
+ });
2821
+ });
2822
+
2844
2823
  it("#5732 a head that failed on an absent interpreter is env.repro_unrunnable with its output, no builder resume", async () => {
2845
2824
  const w = rworld([{ base: "SKIPPED", head: "FAILED" }]);
2846
2825
  w.io.runCommand = async () => ({ rc: 1, output: "Creating virtualenv\npoetry env use: python3.11 not found" });
2847
- const r = await run(w, { conformance: "enforce" });
2826
+ const r = await run(w, { ...ENF, conformance: "enforce" });
2848
2827
  assert.equal(r.code, "env.repro_unrunnable"); assert.equal(w.merges.length, 0);
2849
2828
  assert.equal(builders(w).length, 2, "plan + implement only");
2850
2829
  assert.match(nh(w), /output tail/); assert.match(nh(w), /python3\.11 not found/);
@@ -2893,7 +2872,7 @@ describe("bug lanes freeze a red-green repro_test (#4271)", () => {
2893
2872
  for (const conformance of ["enforce", "shadow"]) {
2894
2873
  for (const rg of [{ base: "SKIPPED", head: "UNRUNNABLE" }, null]) {
2895
2874
  const w = rworld([rg]);
2896
- const r = await run(w, { conformance });
2875
+ const r = await run(w, { ...ENF, conformance });
2897
2876
  assert.equal(r.code, "env.repro_unrunnable", `${conformance} ${JSON.stringify(rg)}`); assert.equal(r.terminalReason, "needs-human");
2898
2877
  assert.equal(classifyNeedsHuman(r), "recoverable");
2899
2878
  assert.equal(w.merges.length, 0); assert.equal(builders(w).length, 2, "plan + implement, no resume"); assert.equal(reviewers(w).length, 0);
@@ -3026,6 +3005,8 @@ describe("structure delta and decision provenance at merge (forge#4165)", () =>
3026
3005
  assert.equal(r.terminalReason, "merged");
3027
3006
  const term = w.telemetry.find((x) => x.event === "RUN_TERMINAL");
3028
3007
  assert.deepEqual([term.pr, term.milestone, term.conformance_mode, term.shadow_would], [r.pr, "Remote MCP Server", "shadow", "conforms"]);
3008
+ assert.equal(term.fixed_overhead_ms, Math.max(0, term.wall_ms - term.model_ms));
3009
+ assert.equal(term.model_share, term.wall_ms > 0 ? Math.round((term.model_ms / term.wall_ms) * 1000) / 1000 : 0);
3029
3010
  const m = mapRecord(term, 5);
3030
3011
  assert.equal(m.pr, r.pr);
3031
3012
  assert.deepEqual([m.payload.milestone, m.payload.conformance_mode, m.payload.shadow_would], ["Remote MCP Server", "shadow", "conforms"]);
@@ -3161,17 +3142,17 @@ describe("comment templates", () => {
3161
3142
 
3162
3143
  it("#5644 review findings get up to 3 builder resume rounds: replay of a fixable finding that clears in round 3 merges", async () => {
3163
3144
  const w = world({ reviews: [bad("round 1"), bad("round 2"), conf()] });
3164
- const r = await run(w);
3145
+ const r = await run(w, ENF);
3165
3146
  assert.equal(r.terminalReason, "merged"); assert.equal(builders(w).length, 4, "build plus two resume rounds");
3166
3147
  });
3167
3148
 
3168
3149
  it("#5644 rounds are spent: a changing but never fixed finding ends needs-human after reviewMaxResumes rounds; an unchanged one stops early", async () => {
3169
3150
  const w = world({ reviews: [bad("a"), bad("b"), bad("c"), bad("d")] });
3170
- const r = await run(w);
3151
+ const r = await run(w, ENF);
3171
3152
  assert.equal(r.terminalReason, "needs-human"); assert.equal(builders(w).length, 5);
3172
3153
  assert.match(traj(w)[0], /after 3 builder resumes/);
3173
3154
  const w2 = world({ reviews: [bad("a"), bad("b"), bad("c")] });
3174
- assert.equal((await run(w2, { reviewMaxResumes: 1 })).terminalReason, "needs-human"); assert.equal(builders(w2).length, 3);
3155
+ assert.equal((await run(w2, { ...ENF, reviewMaxResumes: 1 })).terminalReason, "needs-human"); assert.equal(builders(w2).length, 3);
3175
3156
  });
3176
3157
 
3177
3158
  it("#5644 builderFixable: regression, deferral, scope are fixable; environment and empty sets are not", () => {
@@ -3182,7 +3163,7 @@ describe("comment templates", () => {
3182
3163
 
3183
3164
  it("a merged run's trajectory and a needs-human run's trajectory carry the right rows", async () => {
3184
3165
  const w = world({ reviews: [bad(), bad("still bad")] });
3185
- await run(w, { reviewMaxResumes: 1 });
3166
+ await run(w, { ...ENF, reviewMaxResumes: 1 });
3186
3167
  const t = traj(w)[0];
3187
3168
  assert.match(t, /\| Validate \| CONFIRMED \|/);
3188
3169
  assert.match(t, /\| Plan \| contract [0-9a-f]{12} \| 1 requirement\(s\) \|/);
@@ -3252,7 +3233,7 @@ describe("comment templates", () => {
3252
3233
  it("plan and implement prompts carry the stage templates and the contract schema within budget", () => {
3253
3234
  const plan = builderPlanPrompt(7), impl = builderImplementPrompt();
3254
3235
  assert.ok(approxTokens(plan) <= 2700, `plan prompt is ${approxTokens(plan)} tokens`); // 2700: #5750 (outcome vs guidance split) on top of 2650; 2550: first-pass check-id + dependency-block rule; 2500: #5445 (Test plan heading); 2475: staging; 2375: #5432 (duplicate rule); 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)
3255
- assert.ok(approxTokens(impl) <= 2000, `implement prompt is ${approxTokens(impl)} of 2000 tokens`); // 2000: #5752 // 1650: #4726 e2e rule; 1550: #4596 i18n translate rule // 1850: #5333 (git stash rule + stage stamp) // 1900: #5760 (CI budget rule)
3236
+ assert.ok(approxTokens(impl) <= 2050, `implement prompt is ${approxTokens(impl)} of 2050 tokens`); // 2050: #5979; 2000: #5752 // 1650: #4726 e2e rule; 1550: #4596 i18n translate rule // 1850: #5333 (git stash rule + stage stamp) // 1900: #5760 (CI budget rule)
3256
3237
  for (const h of ["### What Was Claimed", "### What We Found", "### Root Cause", "### Affected Files", "### Sibling Sweep", "### History", "### Recommendation", "### Related Issues", "### Test plan",
3257
3238
  "investigation.md", "contract.json", "PLANNING ONLY", '"requirements"', '"deliverables"', '"preserve"', '"validate"', "verbatim", "defer", "post-deploy"]) assert.ok(plan.includes(h), h);
3258
3239
  for (const h of ["### Approach", "### Changes", "### Acceptance Criteria Status", "### Verification", "### Notes", "implementation.md", "result.json",
@@ -4221,6 +4202,16 @@ describe("base-sync (#4100)", () => {
4221
4202
  noRebaseNoForce(w);
4222
4203
  });
4223
4204
 
4205
+ it("#5898 a failed FORGE:BASE_SYNC comment after a resolved base-sync is an anomaly, not an engine-error: the lane merges", async () => {
4206
+ const w = world({ prView: [CONFLICTING, OKSTATE], mergeResults: ["conflict"], reviews: [ok(), ok()] });
4207
+ const post = w.io.gh;
4208
+ w.io.gh = async (a) => (a[0] === "issue" && a[1] === "comment" && a[a.indexOf("--body") + 1].includes("FORGE:BASE_SYNC") ? Promise.reject(new Error("HTTP 502: unexpected EOF")) : post(a));
4209
+ const r = await run(w);
4210
+ assert.equal(r.terminalReason, "merged");
4211
+ assert.equal(w.merges.length, 1);
4212
+ assert.match(traj(w).join("\n"), /FORGE:BASE_SYNC comment not posted: HTTP 502/);
4213
+ });
4214
+
4224
4215
  it("#5583 follow-up: a builder-resolved base-sync with only documentation conflicts and an unchanged code diff skips the re-review", async () => {
4225
4216
  const w = world({ prView: [CONFLICTING, OKSTATE], mergeResults: ["conflict"], conflictFiles: ["devdocs/modules/lean.md"], reviews: [ok(), ok()] });
4226
4217
  const git = w.io.git;
@@ -4249,7 +4240,7 @@ describe("base-sync (#4100)", () => {
4249
4240
 
4250
4241
  it("conflict resolution that the re-review FAILs gets one retry then merges on PASS", async () => {
4251
4242
  const w = world({ prView: [CONFLICTING, OKSTATE], mergeResults: ["conflict"], reviews: [ok(), bad("src/foo.js:4 lost base change"), ok()] });
4252
- assert.equal((await run(w)).terminalReason, "merged");
4243
+ assert.equal((await run(w, ENF)).terminalReason, "merged");
4253
4244
  assert.equal(reviewers(w).length, 3);
4254
4245
  assert.equal(builders(w).length, 4);
4255
4246
  });
@@ -4543,6 +4534,33 @@ describe("usage limit, lease takeover, worktree setup, run tmp (#4101-#4104)", (
4543
4534
  assert.equal(r.account, "3");
4544
4535
  });
4545
4536
 
4537
+ it("#6105 a builder session ended api_error is resumed by id with backoff; the lane continues and nothing is relaunched", async () => {
4538
+ const w = world(); const sleeps = []; const dir = tmpDir("core-"); const s0 = w.io.sleep; w.io.sleep = async (ms) => { sleeps.push(ms); return s0(ms); };
4539
+ const apiErr = Object.assign(new Error("claude CLI exited with status 1"), { code: "CLI_BACKEND_FAILED", apiError: true, cliIsError: true, cliTerminalReason: "api_error", cliSessionId: "sess-api" });
4540
+ const orig = w.io.runner; let n = 0; const sent = [];
4541
+ w.io.runner = async (c) => { if (c.role === "builder") { sent.push({ resume: c.resume ?? null, prompt: c.prompt }); if (++n === 2) throw apiErr; } return orig(c); };
4542
+ const r = await run(w, { dir });
4543
+ assert.equal(r.terminalReason, "merged");
4544
+ const resumed = sent.filter((x) => x.resume === "sess-api");
4545
+ assert.equal(resumed.length, 1, "the failed session is resumed by id");
4546
+ assert.match(resumed[0].prompt, /transient API error/);
4547
+ assert.ok(sleeps.includes(20_000), "backoff before the resume");
4548
+ const log = readLog(dir, 7);
4549
+ assert.equal(log.filter((e) => e.event === "API_ERROR_RESUME").length, 1);
4550
+ assert.equal(log.find((e) => e.event === "RUN_TERMINAL").api_resumes, 1, "resumes are counted apart from relaunches");
4551
+ });
4552
+
4553
+ it("#6105 an api_error that keeps recurring defers backend.cli_failed after the capped resumes (never engine-error)", async () => {
4554
+ const w = world(); projector(w, null);
4555
+ const apiErr = () => Object.assign(new Error("claude CLI exited with status 1"), { code: "CLI_BACKEND_FAILED", apiError: true, cliIsError: true, cliTerminalReason: "api_error", cliSessionId: "sess-api" });
4556
+ const orig = w.io.runner; let resumes = 0;
4557
+ w.io.runner = async (c) => { if (c.role === "builder") { if (c.resume === "sess-api") resumes++; throw apiErr(); } return orig(c); };
4558
+ const r = await run(w);
4559
+ assert.equal(r.terminalReason, "deferred"); assert.equal(r.code, "backend.cli_failed");
4560
+ assert.equal(resumes, 3, "three resumes, then the deferral");
4561
+ assert.match(r.detail, /transient API error/);
4562
+ });
4563
+
4546
4564
  it("#5168 an error that is both a usage limit and auth-like stays rate_limited", async () => {
4547
4565
  const w = world();
4548
4566
  failFirstBuilder(w, limitErr({ authFailure: true, resetAtEpochMs: 3 * 3600 * 1000, resetAt: "8:30pm" }));
@@ -4721,6 +4739,17 @@ describe("usage limit, lease takeover, worktree setup, run tmp (#4101-#4104)", (
4721
4739
  assert.equal(cred, 0); assert.equal(r.rotations, undefined); assert.equal(r.limited, undefined);
4722
4740
  });
4723
4741
 
4742
+ it("#5991 a lease of a batch that is no longer live is taken over; a live batch's lease is still held", async () => {
4743
+ const lease = { by: "core_sbx_1_ab", until: 1e12, host: "sandbox-host", pid: 1, batch: "old-batch" };
4744
+ const gone = world(); projector(gone, lease);
4745
+ assert.equal((await run(gone, { hostName: "h1", batchId: "new-batch", liveBatches: () => ["other"] })).terminalReason, "merged");
4746
+ const live = world(); projector(live, lease);
4747
+ const r = await run(live, { hostName: "h1", batchId: "new-batch", liveBatches: () => ["old-batch"] });
4748
+ assert.deepEqual([r.terminalReason, r.code], ["deferred", "lease-held"]);
4749
+ const unknown = world(); projector(unknown, lease);
4750
+ assert.equal((await run(unknown, { hostName: "h1", batchId: "new-batch", liveBatches: () => null })).code, "lease-held");
4751
+ });
4752
+
4724
4753
  it("#4101 a non-limit runner error is still engine-error", async () => {
4725
4754
  const w = world(); failFirstBuilder(w, new Error("boom"));
4726
4755
  assert.equal((await run(w)).terminalReason, "engine-error");
@@ -4780,7 +4809,7 @@ describe("usage limit, lease takeover, worktree setup, run tmp (#4101-#4104)", (
4780
4809
  };
4781
4810
  for (const [reason, prep] of Object.entries(cases)) {
4782
4811
  const w = world(); mk(w); prep(w);
4783
- const r = await run(w);
4812
+ const r = await run(w, ENF);
4784
4813
  assert.equal(r.terminalReason, reason);
4785
4814
  assert.equal(w.pruned, true);
4786
4815
  assert.equal(w.tmpMade.length, 1);
@@ -4923,8 +4952,8 @@ describe("host admission (#4105)", () => {
4923
4952
  it("/orchestrate spec requeues host-busy lanes with a lower K and pauses on rate_limited", async () => {
4924
4953
  const { readFileSync } = await import("node:fs");
4925
4954
  const spec = readFileSync(new URL("../../commands/orchestrate.md", import.meta.url), "utf8");
4926
- assert.match(spec, /host busy[\s\S]*lower the effective K by\s+1 for the next 5 minutes, never below 1/);
4927
- assert.match(spec, /rate_limited[\s\S]*stop launching\s+new lanes until that reset time/);
4955
+ assert.match(spec, /host\.busy[\s\S]*lower K by 1\s+for 5 minutes \(never below 1\)/);
4956
+ assert.match(spec, /rate_limited`: launch nothing until the reset time/);
4928
4957
  });
4929
4958
  });
4930
4959
 
@@ -5541,20 +5570,12 @@ describe("batch robustness (#4112-#4115)", () => {
5541
5570
  const d = tmpDir("lean-5653-"); const src = join(d, "ci.yml"); writeFileSync(src, "run: uv run --with-requirements r.txt pytest tests\n");
5542
5571
  const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "poetry run pytest t.py" }] };
5543
5572
  const w = world({ contract }); w.io.probeCommand = async (a) => ({ rc: /poetry/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
5544
- const r = await run(w, { dir: d, validateCatalogSources: [`../..${src}`] });
5573
+ const r = await run(w, { dir: d, validateCatalogSources: [`../..${src.replace(/^[A-Za-z]:/, "").split("\\").join("/")}`] }); // #5753: drive-less posix path on Windows
5545
5574
  assert.notEqual(r.code, "env.tool_missing");
5546
5575
  assert.ok(w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("uv run --with-requirements r.txt pytest t.py")));
5547
5576
  assert.ok(!w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("poetry run pytest")));
5548
5577
  });
5549
5578
 
5550
- it("#5653 the plan prompt tells the builder to prefer CI commands, record equivalent substitutes and never narrow time or production criteria", async () => {
5551
- const { unrunnableValidateNote } = await import("./prompts.mjs");
5552
- const n = unrunnableValidateNote();
5553
- assert.match(n, /CI-derived command catalogue/);
5554
- assert.match(n, /same test ids with the same result is recorded/);
5555
- assert.match(n, /never narrow it/);
5556
- });
5557
-
5558
5579
  // ---- #4112 ----
5559
5580
  const fakeCli = async (name, body) => {
5560
5581
  const { writeFileSync, chmodSync } = await import("node:fs");
@@ -5743,6 +5764,23 @@ describe("batch robustness (#4112-#4115)", () => {
5743
5764
  assert.ok(!w.comments.some((c) => c.includes("FORGE:CONTRACT")), "not re-posted");
5744
5765
  assert.match(traj(w)[0], /frozen contract [0-9a-f]{12} recovered from the issue/);
5745
5766
  });
5767
+ it("#5920 a reused frozen contract gets the validate.recipes rewrite and an audit amendment, once", async () => {
5768
+ const recipes = [{ match: "^node --test ", replace: "node --test --test-reporter=dot " }];
5769
+ const w = world({ prList: [], remote: "abc\trefs/heads/feat/issue-7-lean", lastSubject: "wip(forge): checkpoint after idle timeout", issueComments: [frozenComment()] });
5770
+ const r = await run(w, { validateRecipes: recipes });
5771
+ assert.equal(r.terminalReason, "merged");
5772
+ assert.match(w.files[`${WT}/.forge-lean/contract.json`], /node --test --test-reporter=dot test\/foo\.test\.js/, "the rewritten command is the one the lane runs");
5773
+ const am = w.comments.filter((c) => c.includes("FORGE:AMENDMENT") && c.includes("rewrite-validate"));
5774
+ assert.equal(am.length, 1);
5775
+ assert.match(am[0], new RegExp(`frozen contract ${contractHash(contractJson(CONTRACT))}`));
5776
+ assert.ok(!am[0].includes("AMENDMENT-STATE"), "audit only: never replayed as an amendment");
5777
+ const w2 = world({ prList: [], remote: "abc\trefs/heads/feat/issue-7-lean", lastSubject: "wip(forge): checkpoint after idle timeout", issueComments: [frozenComment(), { body: am[0], author_association: "OWNER", user: { type: "User", login: "op" } }] });
5778
+ await run(w2, { validateRecipes: recipes });
5779
+ assert.equal(w2.comments.filter((c) => c.includes("rewrite-validate")).length, 0, "a second reuse posts nothing new");
5780
+ const w3 = world({ prList: [], remote: "abc\trefs/heads/feat/issue-7-lean", lastSubject: "wip(forge): checkpoint after idle timeout", issueComments: [frozenComment()] });
5781
+ await run(w3);
5782
+ assert.ok(!w3.comments.some((c) => c.includes("rewrite-validate")), "no recipe, no amendment");
5783
+ });
5746
5784
  it("recovery lane replays accepted supersedes amendment (#4899)", async () => {
5747
5785
  const sup = { kind: "supersedes", guard: "#4785", why: "behaviour changed on purpose" };
5748
5786
  const state = { contract: contractHash(contractJson(CONTRACT)), amendments: [sup] };
@@ -5820,11 +5858,11 @@ describe("batch robustness (#4112-#4115)", () => {
5820
5858
  });
5821
5859
  it("#5752 a declared outcome-evidence area touched without a before/after result row blocks with a clear reason", async () => {
5822
5860
  const w = world({ prList: [] });
5823
- await run(w, { outcomeEvidenceConfig: { paths: { core: ["src/**"] }, corpus: { core: ["corpus/**"] } } });
5861
+ await run(w, { ...ENF, outcomeEvidenceConfig: { paths: { core: ["src/**"] }, corpus: { core: ["corpus/**"] } } });
5824
5862
  assert.ok(builders(w).length >= 2, "the missing evidence resumes the builder");
5825
5863
  assert.match(JSON.stringify(w.calls.filter((c) => c[0] === "runner")), /outcome-evidence area 'core'.{0,200}src\/foo\.js.{0,200}no before\/after measurement/);
5826
5864
  const off = world({ prList: [] });
5827
- await run(off);
5865
+ await run(off, ENF);
5828
5866
  assert.doesNotMatch(JSON.stringify([off.comments, off.calls.filter((c) => c[0] === "runner")]), /outcome_evidence_missing|outcome-evidence area/, "no outcome_evidence config: no new check");
5829
5867
  });
5830
5868
  it("#5752 the builder prompt carries the negative-examples rule and the mechanism supersedes amendment", async () => {
@@ -6238,14 +6276,14 @@ describe("verify-by-CI (#4167): ci mode runs the heavy checks on CI and feeds fa
6238
6276
 
6239
6277
  it("without the fix, a validate id left to CI is missing under enforce (the regression this guards)", async () => {
6240
6278
  const w = world({ validation: ciValidation });
6241
- const r = await run(w);
6279
+ const r = await run(w, ENF);
6242
6280
  assert.equal(r.terminalReason, "needs-human"); assert.equal(w.merges.length, 0);
6243
6281
  });
6244
6282
 
6245
6283
  it("#4527 base-sync re-review FAIL: the fix round's head is CI-verified before the retry review, which accepts validates left to CI and notes them", async () => {
6246
6284
  const CONFLICTING = { mergeable: "CONFLICTING", mergeStateStatus: "DIRTY" }, OKSTATE = { mergeable: "MERGEABLE", mergeStateStatus: "CLEAN" };
6247
6285
  const w = withCi(world({ validation: ciValidation, prView: [CONFLICTING, OKSTATE], mergeResults: ["conflict"], reviews: [ok(), bad("src/foo.js:4 lost base change"), ok()] }));
6248
- const r = await run(w, { verify: CI });
6286
+ const r = await run(w, { ...ENF, verify: CI });
6249
6287
  assert.equal(r.terminalReason, "merged", r.reason);
6250
6288
  assert.equal(reviewers(w).length, 3);
6251
6289
  assert.equal(new Set(w.ci.runs.map((x) => x.headSha)).size, w.ci.runs.length, "every reviewed head was verified once");
@@ -6934,7 +6972,7 @@ describe("local-mode CI fix rounds at merge and declared pre-PR check commands (
6934
6972
  it("pre-PR: declared commands run in the lane worktree; a failing one goes back to the builder before PR_OPENED", async () => {
6935
6973
  const w = world(); const ran = [];
6936
6974
  let rc = 1;
6937
- w.io.runCommand = async ({ command, cwd, timeoutMs }) => { ran.push([command, cwd, timeoutMs]); w.seq.push(`check:${rc}`); const r = { rc, output: "check-test-tmp-cleanup: mkdtempSync in x.test.mjs" }; return r; };
6975
+ w.io.runCommand = async ({ command, cwd, timeoutMs }) => { ran.push([command, cwd, timeoutMs]); w.seq.push(`check:${rc}`); const r = { rc, output: "check-test-tmp-cleanup: mkdtempSync in test/foo.test.js" }; return r; };
6938
6976
  const inner = w.io.runner;
6939
6977
  w.io.runner = async (c) => { if (/declared check commands failed/.test(c.prompt)) rc = 0; return inner(c); };
6940
6978
  const dir = tmpDir("core-");
@@ -6943,7 +6981,7 @@ describe("local-mode CI fix rounds at merge and declared pre-PR check commands (
6943
6981
  assert.deepEqual(ran.map((x) => x.slice(0, 2)), [["bash scripts/check-test-tmp-cleanup.sh", WT], ["bash scripts/check-test-tmp-cleanup.sh", WT]]);
6944
6982
  assert.equal(ran[0][2], 300000);
6945
6983
  const fix = builders(w).filter((b) => /declared check commands failed/.test(b[4]));
6946
- assert.equal(fix.length, 1); assert.equal(fix[0][2], null); assert.match(fix[0][4], /mkdtempSync in x\.test\.mjs/); assert.match(fix[0][4], /exit 1/);
6984
+ assert.equal(fix.length, 1); assert.equal(fix[0][2], null); assert.match(fix[0][4], /mkdtempSync in test\/foo\.test\.js/); assert.match(fix[0][4], /exit 1/);
6947
6985
  assert.ok(w.seq.indexOf("builder", w.seq.indexOf("check:1")) < w.seq.indexOf("pr"), "the fix runs before the PR is opened");
6948
6986
  const log = readLog(dir, 7);
6949
6987
  const pre = log.filter((e) => e.event === "PRECHECK_COMMANDS");
@@ -7031,6 +7069,28 @@ describe("local-mode CI fix rounds at merge and declared pre-PR check commands (
7031
7069
  assert.equal(builders(w).length, 2, "no builder fix round spent on a base failure");
7032
7070
  });
7033
7071
 
7072
+ it("#5913 a lane whose diff touches the failing guard's files and makes it pass on the lane tree is not deferred on base.red", async () => {
7073
+ const w = world({ changed: ["app/routers/listing_feeds.py", "test/foo.test.js"] }); let laneRuns = 0;
7074
+ w.io.runCommand = async ({ cwd }) => (/basered-/.test(cwd) ? { rc: 1, output: "bare 429 at app/routers/listing_feeds.py" } : ++laneRuns === 1 ? { rc: 1, output: "bare 429 at app/routers/listing_feeds.py" } : { rc: 0, output: "" });
7075
+ const r = await run(w, { verify: { invariants: ["bash scripts/guard.sh"] } });
7076
+ assert.notEqual(r.code, "base.red"); assert.ok(laneRuns >= 2, "the guard was re-run on the lane tree");
7077
+ });
7078
+
7079
+ it("#5913 a lane that touches the guard's files but still fails it is deferred on base.red and names the owner escape", async () => {
7080
+ const w = world({ changed: ["app/routers/listing_feeds.py"] });
7081
+ w.io.runCommand = async () => ({ rc: 1, output: "bare 429 at app/routers/listing_feeds.py" });
7082
+ const r = await run(w, { verify: { invariants: ["bash scripts/guard.sh"] } });
7083
+ assert.equal(r.code, "base.red"); assert.equal(w.merges.length, 0);
7084
+ assert.match(JSON.stringify(r), /--owner-requested/);
7085
+ });
7086
+
7087
+ it("#5913 diffTouchesGuard is true only when a changed file is named by the failing guard", () => {
7088
+ const failed = [{ command: "bash scripts/guard.sh", output: "bare 429 at app/routers/listing_feeds.py" }];
7089
+ assert.equal(diffTouchesGuard({ changed: ["./app/routers/listing_feeds.py"], failed }), true);
7090
+ assert.equal(diffTouchesGuard({ changed: ["src/foo.js"], failed }), false);
7091
+ assert.equal(diffTouchesGuard({ changed: [], failed }), false);
7092
+ });
7093
+
7034
7094
  it("#5945 an env-signature base failure is not base.red and files nothing; a host verify pass skips filing", async () => {
7035
7095
  for (const hook of [false, true]) {
7036
7096
  const w = world(); const filed = [], gh = w.io.gh;
@@ -7613,12 +7673,12 @@ describe("context pack modes (forge#4275)", () => {
7613
7673
  it("write-back: the terminal FORGE:STATE carries the typed outcome code and failure classes the compiler reads", async () => {
7614
7674
  const w = world({ reviews: [bad(), bad()] });
7615
7675
  w.leaseWrites = []; w.io.projector = { readState: async () => null, writeState: async (_i, st) => { w.leaseWrites.push(st); } };
7616
- const r = await run(w);
7676
+ const r = await run(w, ENF);
7617
7677
  assert.equal(r.terminalReason, "needs-human");
7618
7678
  const last = w.leaseWrites.at(-1);
7619
7679
  assert.deepEqual([last.terminal, last.terminalReason, last.terminalCode, last.failureClasses], [true, "needs-human", OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED]]);
7620
7680
  const m = world(); m.leaseWrites = []; m.io.projector = { readState: async () => null, writeState: async (_i, st) => { m.leaseWrites.push(st); } };
7621
- await run(m);
7681
+ await run(m, ENF);
7622
7682
  assert.deepEqual([m.leaseWrites.at(-1).terminalCode, m.leaseWrites.at(-1).failureClasses], [OUTCOME_CODES.COMPLETED, []]);
7623
7683
  });
7624
7684
 
@@ -8094,15 +8154,15 @@ describe("#4363 fresh fix sessions", () => {
8094
8154
 
8095
8155
  it("a conformance FAIL citing file:line is fresh; one without a file:line resumes; the one review retry is unchanged", async () => {
8096
8156
  const w1 = world({ reviews: [bad("src/foo.js:9 still wrong"), ok()] }); const d1 = tmpDir("core-");
8097
- assert.equal((await run(w1, { dir: d1 })).terminalReason, "merged");
8157
+ assert.equal((await run(w1, { ...ENF, dir: d1 })).terminalReason, "merged");
8098
8158
  assert.deepEqual(usage(d1).map((e) => e.mode ?? null), [null, null, "fresh"]);
8099
8159
  const vague = conf({ verdict: "NONCONFORMING", requirements: [{ id: "R1", status: "partial", evidence: "the foo module", validated_by: "V1", note: "null still throws" }] });
8100
8160
  const w2 = world({ reviews: [vague, ok()] }); const d2 = tmpDir("core-");
8101
- assert.equal((await run(w2, { dir: d2 })).terminalReason, "merged");
8161
+ assert.equal((await run(w2, { ...ENF, dir: d2 })).terminalReason, "merged");
8102
8162
  assert.equal(builders(w2)[2][2], "sess-1");
8103
8163
  assert.deepEqual(usage(d2).map((e) => e.mode ?? null), [null, null, "resume"]);
8104
8164
  const w3 = world({ reviews: [bad(), bad(), bad()] });
8105
- const r3 = await run(w3);
8165
+ const r3 = await run(w3, ENF);
8106
8166
  assert.equal(r3.terminalReason, "needs-human"); assert.equal(reviewers(w3).length, 2, "still one review retry");
8107
8167
  });
8108
8168
  });
@@ -8841,14 +8901,14 @@ describe("#4394 builder model routing", () => {
8841
8901
 
8842
8902
  it("a conformance fix round on the mid tier does not escalate and keeps the fix model", async () => {
8843
8903
  const w = world({ reviews: [bad("src/foo.js:9 still wrong"), ok()] }); const dir = tmpDir("core-");
8844
- assert.equal((await run(w, { dir, builderModel: "opus-b", fixModel: "haiku-fix" })).terminalReason, "merged");
8904
+ assert.equal((await run(w, { ...ENF, dir, builderModel: "opus-b", fixModel: "haiku-fix" })).terminalReason, "merged");
8845
8905
  assert.equal(builders(w)[2][3], "haiku-fix");
8846
8906
  assert.deepEqual(events(dir, "BUILDER_ESCALATED"), []);
8847
8907
  });
8848
8908
 
8849
8909
  it("builder_routing off: plan, build and the resume keep builderModel; the class is still recorded on the top tier", async () => { // #5810: the pre-route is top too
8850
8910
  const w = world({ reviews: [conf({ verdict: "NONCONFORMING", requirements: [{ id: "R1", status: "partial", evidence: "the foo module", validated_by: "V1", note: "x" }] }), ok()] }); const dir = tmpDir("core-");
8851
- await run(w, { dir, builderModel: "opus-b", builderRouting: { mode: "off" } });
8911
+ await run(w, { ...ENF, dir, builderModel: "opus-b", builderRouting: { mode: "off" } });
8852
8912
  assert.ok(builders(w).length >= 3);
8853
8913
  assert.ok(builders(w).every((b) => b[3] === "opus-b"));
8854
8914
  const term = events(dir, "RUN_TERMINAL").at(-1);
@@ -9055,7 +9115,7 @@ describe("#4395 lane profile", () => {
9055
9115
  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/);
9056
9116
  assert.match(p, /Read each file's ranges once .* and keep notes; don't re-read it\./);
9057
9117
  }
9058
- assert.ok(approxTokens(builderImplementPrompt()) <= 2000, `implement prompt is ${approxTokens(builderImplementPrompt())} of 2000 tokens`); // 1900: #5760; 2000: #5752
9118
+ assert.ok(approxTokens(builderImplementPrompt()) <= 2050, `implement prompt is ${approxTokens(builderImplementPrompt())} of 2050 tokens`); // 2050: #5979; 1900: #5760; 2000: #5752
9059
9119
  assert.ok(approxTokens(builderPlanPrompt(7)) <= 2700, `plan prompt is ${approxTokens(builderPlanPrompt(7))} of 2125 tokens`);
9060
9120
  });
9061
9121
 
@@ -9094,28 +9154,6 @@ describe("#4450 light lane: one builder session, derived contract, upgrade to th
9094
9154
  const events = (dir, name) => readLog(dir, 7).filter((e) => e.event === name);
9095
9155
  const ON = { light: { mode: "on", source: "text" } };
9096
9156
 
9097
- it("#5751 recurrence: an issue matching two earlier merged fixes on its path skips the light lane, gets the design note and records the reason", async () => {
9098
- const DESIGN = { why_failed: "#10 and #11 guarded one caller each", disposition: "replace", outcome: { metric: "null-input crashes in foo tests", target: "0" } };
9099
- const ghApi = (a) => {
9100
- const j = a.join(" ");
9101
- if (j.includes("search/issues")) return [10, 11].map((n) => JSON.stringify({ number: n, title: `fix foo null ${n}`, pr: true, merged: true })).join("\n");
9102
- if (/pulls\/1[01]\/files/.test(j)) return "src/foo.js\n";
9103
- return null;
9104
- };
9105
- const w = lworld({ ghApi, body: `${BODY}\n\nRecurs #10`, contract: { ...CONTRACT, test_plan: TEST_PLAN, repro_test: RT, design: DESIGN } }), dir = tmpDir("light-");
9106
- await run(w, { dir, ...ON });
9107
- const rec = events(dir, "RECURRENCE");
9108
- assert.equal(rec.length, 1);
9109
- assert.deepEqual(rec[0].fixes.sort(), [10, 11]);
9110
- assert.match(rec[0].reason, /^recurrence: 2 earlier merged fix\(es\) on the same symptom and area/);
9111
- assert.equal(events(dir, "LIGHT_DONE").length, 0, "a recurrence never takes the light lane");
9112
- const plan = builders(w).find((c) => /PLANNING ONLY/.test(c[4]));
9113
- assert.ok(plan, "the full lane's plan session ran");
9114
- assert.match(plan[4], /DESIGN LANE \(#5751\)/);
9115
- assert.match(plan[4], /#10 fix foo null 10/);
9116
- assert.ok(w.comments.some((c) => c.includes("<!-- FORGE:RECURRENCE -->") && /Routed to a design lane: recurrence: 2/.test(c)), "the reason is posted on the issue");
9117
- assert.ok(!readLog(dir, 7).some((e) => JSON.stringify(e).includes("design_missing")), "a contract with a design block passes the design check");
9118
- });
9119
9157
 
9120
9158
  it("#5751 recurrence: no matching history keeps the light lane and the plan prompt unchanged", async () => {
9121
9159
  const w = lworld(), dir = tmpDir("light-");
@@ -9365,7 +9403,7 @@ describe("per-kind conformance modes (engine.conformance_kinds)", () => {
9365
9403
  const w = world({ changed: CREEP, reviews: [conf({}, CONTRACT, CREEP)] });
9366
9404
  const r = await run(w, { conformance: "enforce", conformanceKinds: { "conformance.scope_creep": "shadow" } });
9367
9405
  assert.equal(r.terminalReason, "merged");
9368
- assert.match(shadowNote(w), /would BLOCK[\s\S]*conformance\.scope_creep[\s\S]*src\/billing\.js/);
9406
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\): conformance\.scope_creep/); // unclog: scope creep is advisory whatever the kind mode
9369
9407
  });
9370
9408
 
9371
9409
  it("an enforce kind in a shadow lane blocks (scope creep is recorded-only in shadow by default)", async () => {
@@ -9375,9 +9413,9 @@ describe("per-kind conformance modes (engine.conformance_kinds)", () => {
9375
9413
  blockedNothingMerged(w);
9376
9414
  });
9377
9415
 
9378
- it("an enforce lane without kinds still blocks scope creep (unchanged default)", async () => {
9416
+ it("an enforce lane without kinds records scope creep as advisory and merges (unclog default)", async () => {
9379
9417
  const w = world({ changed: CREEP });
9380
- assert.equal((await run(w, { conformance: "enforce", conformanceKinds: {} })).code, "conformance.scope_creep");
9418
+ assert.equal((await run(w, { conformance: "enforce", conformanceKinds: {} })).terminalReason, "merged");
9381
9419
  });
9382
9420
  });
9383
9421
 
@@ -9431,7 +9469,7 @@ describe("prompt budgets (#4969)", () => {
9431
9469
  assert.notEqual(moved, impl);
9432
9470
  assert.equal(approxTokens(moved), approxTokens(impl));
9433
9471
  assert.equal(approxTokens(impl.replaceAll(INSTALL_ROOT, "C:\\fd")), approxTokens(impl));
9434
- assert.ok(approxTokens(moved) <= 2000, `implement prompt from a deep checkout is ${approxTokens(moved)} of 2000 tokens`); // 1900: #5760; 2000: #5752
9472
+ assert.ok(approxTokens(moved) <= 2050, `implement prompt from a deep checkout is ${approxTokens(moved)} of 2050 tokens`); // 1900: #5760; 2000: #5752
9435
9473
  });
9436
9474
  });
9437
9475
 
@@ -9465,7 +9503,7 @@ describe("#5237 relaxation gate", () => {
9465
9503
  };
9466
9504
  it("relaxation without a negative test blocks (relaxation_untested) in a risk path", async () => {
9467
9505
  const w = withV(world({ contract: { ...CONTRACT, preserve: [] }, reviews: [conf(), conf(), conf()] })); w.diffText = rescue;
9468
- const r = await run(w, { dir: tmpDir("relax-"), reviewTrigger: { mode: "shadow", riskPaths: ["src/**"] } });
9506
+ const r = await run(w, { ...ENF, dir: tmpDir("relax-"), reviewTrigger: { mode: "shadow", riskPaths: ["src/**"] } });
9469
9507
  assert.equal(w.merges.length, 0); assert.equal(r.code, "conformance.unimplemented");
9470
9508
  });
9471
9509
  it("a negative test lets it through, and the verifier runs even with review.verifier off, fed the hunk", async () => {
@@ -9876,22 +9914,6 @@ describe("spec-only page gate failures end design.spec_required (#5729)", () =>
9876
9914
  const pagesConfig = { ...parsePagesConfig(undefined, { hasAppPages: true }), require: ["design"] };
9877
9915
  const link = (h, x = "") => `<Link href="${h}"${x}>Book a demo</Link>`;
9878
9916
  const mk = (diff) => { const w = world({ contract: pc, changed: [PAGE, "test/foo.test.js"], reviews: [conf({}, pc, [PAGE, "test/foo.test.js"])] }); w.diffText = `+++ b/${PAGE}\n${diff}`; return w; };
9879
- it("spec-only precheck failures end design.spec_required with no resume for 5729", async () => {
9880
- const w = mk(`-${link("/contact")}\n+${link("/contact")}<Badge />\n`), r = await run(w, { pagesConfig });
9881
- assert.equal(r.terminalReason, "needs-human");
9882
- assert.equal(r.code, OUTCOME_CODES.DESIGN_SPEC_REQUIRED);
9883
- assert.ok(w.comments.some((c) => c.includes("FORGE:NEEDS_HUMAN") && /recovery lane was spent/.test(c)));
9884
- assert.ok(!builders(w).some((c) => /resume|conformance\.unimplemented/i.test(c[4] ?? "")), "no builder resume");
9885
- assert.equal(classifyNeedsHuman({ outcome: "needs-human", code: r.code }), "terminal", "no recovery lane");
9886
- });
9887
- it("replay of #40917 spends no resume or recovery for 5729", async () => {
9888
- const w = mk(`-${link("https://calendly.com/x", ' target="_self"')}\n+${link("/contact", ' target="_blank"')}\n`), r = await run(w, { pagesConfig });
9889
- assert.equal(r.code, OUTCOME_CODES.DESIGN_SPEC_REQUIRED); // only the screenshot row is left, and it is terminal too
9890
- const note = w.comments.find((c) => c.includes("FORGE:NEEDS_HUMAN")) ?? "";
9891
- assert.ok(!/is a public page but the issue has no approved/.test(note), "no spec row for a copy edit");
9892
- assert.match(note, /visual check/);
9893
- assert.ok(!builders(w).some((c) => /conformance\.unimplemented/i.test(c[4] ?? "")), "no builder resume");
9894
- });
9895
9917
  });
9896
9918
 
9897
9919
  describe("classification record in the plan prompt (#5557)", () => {
@@ -10125,6 +10147,30 @@ describe("#5820 required CI checks run in the lane before the PR opens", () => {
10125
10147
  assert.match(p2.unrunnable[0].reason, /CI check plan unavailable: yq not found/);
10126
10148
  });
10127
10149
 
10150
+ it("#6049 a release-only required formatter fails the precheck before the PR; a required context with no job is a parity gap filed once", async () => {
10151
+ const fmt = ciJob("fmt", "Format check", "black --check .");
10152
+ const plan = { version: 1, repo: WT, jobs: [ciJob("lint", "Lint", "pnpm lint"), fmt] };
10153
+ let broken = true; const asked = [];
10154
+ const w = ciWorld({ plan: async (a) => { asked.push(a.releaseBranch ?? ""); return plan; }, ciRun: (c) => (broken ? { rc: 1, output: "would reformat a.py\nCI_LOCAL_FAIL: gha:ci:fmt | step: black --check . | exit 1" } : { rc: 0, output: "CI_LOCAL_RESULT: PASS" }) });
10155
+ const byBranch = []; w.io.requiredChecks = async (b) => { byBranch.push(b); return b === "main" ? ["Format check", "Wiring audit"] : ["Lint"]; };
10156
+ const inner = w.io.runner;
10157
+ w.io.runner = async (c) => { if (/declared check commands failed/.test(c.prompt)) broken = false; return inner(c); };
10158
+ const issues = []; const gh = w.io.gh;
10159
+ w.io.gh = async (args, ...x) => { if (args[0] === "issue" && args[1] === "list") return JSON.stringify(issues.map((i) => ({ ...i, number: 77, state: "OPEN", body: i.body }))); if (args[0] === "issue" && args[1] === "create") { issues.push({ body: args[args.indexOf("--body") + 1] }); return "https://github.com/o/r/issues/77"; } return gh(args, ...x); };
10160
+ const dir = tmpDir("core-");
10161
+ await run(w, { dir });
10162
+ assert.ok(byBranch.includes("main"), `the release branch's required checks are read (read: ${byBranch})`);
10163
+ const log = readLog(dir, 7);
10164
+ const p = log.find((e) => e.event === "CI_PRECHECK_PLAN");
10165
+ assert.ok(p.commands.some((c) => c.job === "gha:ci:fmt" && /on release branch/.test(c.why)));
10166
+ assert.ok(log.filter((e) => e.event === "CI_PRECHECK_RESULT")[0].results.some((x) => x.status === "fail"));
10167
+ assert.ok(w.seq.indexOf("ci-precheck") < w.seq.indexOf("pr"));
10168
+ const par = log.filter((e) => e.event === "CI_PRECHECK_PARITY");
10169
+ assert.deepEqual(par[0].gaps.map((g) => g.context), ["Wiring audit"]);
10170
+ assert.equal(issues.length, 1, "one issue per gap, not re-filed on the fix round");
10171
+ assert.match(issues[0].body, /FORGE:PARITY_GAP Wiring audit/);
10172
+ });
10173
+
10128
10174
  it("lean.ci_precheck off runs nothing and logs no plan", async () => {
10129
10175
  const w = ciWorld(); const dir = tmpDir("core-");
10130
10176
  await run(w, { dir, precheck: { ci: { mode: "off", include: [], exclude: [], maxJobs: 8 } } });
@@ -10132,3 +10178,264 @@ describe("#5820 required CI checks run in the lane before the PR opens", () => {
10132
10178
  assert.equal(readLog(dir, 7).filter((e) => /^CI_PRECHECK/.test(e.event)).length, 0);
10133
10179
  });
10134
10180
  });
10181
+
10182
+ describe("#5749 freeze-time runnability: host-only commands, recipes, check tails", () => {
10183
+ const remote = { placement: { where: "remote", reason: "mode remote" } };
10184
+ const V2 = (command) => ({ ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command }] });
10185
+ it("#5749 host-only validate is rejected at freeze", async () => {
10186
+ const w = world({ contract: V2(`legion-run bash -lc 'for i in $(seq $(nproc)); do (timeout 300 sh -c "while :; do :; done") & done; npx vitest run'`) });
10187
+ const r = await run(w, { dir: tmpDir("lean-5749a-"), ...remote });
10188
+ assert.equal(r.code, "contract.invalid"); assert.equal(w.merges.length, 0);
10189
+ assert.ok(builders(w).some((b) => /legion-run/.test(b[4])), "the correction prompt names the host-only wrapper");
10190
+ assert.equal((await run(world({ contract: V2("npx vitest run a.test.ts") }), { dir: tmpDir("lean-5749a2-"), ...remote })).terminalReason, "merged");
10191
+ });
10192
+ it("#5749 remote probe installs a recipe tool or re-places before the builder", async () => {
10193
+ const installed = []; let ok = false;
10194
+ const w = world({ contract: V2("shellcheck scripts/x.sh") });
10195
+ w.io.runCommand = async ({ command }) => { if (/apt-get/.test(command)) { installed.push(command); ok = true; } return { rc: 0, output: "" }; };
10196
+ w.io.probeCommand = async (a) => ({ rc: /shellcheck/.test(JSON.stringify(a)) && !ok ? 127 : 0, output: "" });
10197
+ assert.notEqual((await run(w, { dir: tmpDir("lean-5749b-"), ...remote })).code, "env.tool_missing");
10198
+ assert.equal(installed.length, 1);
10199
+ const n = world({ contract: V2("nopetool-5749 x") }); n.io.probeCommand = async (a) => ({ rc: /nopetool-5749/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
10200
+ const r = await run(n, { dir: tmpDir("lean-5749b2-"), ...remote });
10201
+ assert.equal(r.code, "env.tool_missing");
10202
+ });
10203
+ it("#5749 remote lane with every tool keeps remote placement", async () => {
10204
+ const w = world({ contract: V2("shellcheck scripts/x.sh") }); w.io.probeCommand = async () => ({ rc: 0, output: "" });
10205
+ const installs = []; w.io.runCommand = async ({ command }) => { installs.push(command); return { rc: 0, output: "" }; };
10206
+ const r = await run(w, { dir: tmpDir("lean-5749c-"), ...remote });
10207
+ assert.equal(r.terminalReason, "merged"); assert.ok(!installs.some((c) => /apt-get/.test(c)));
10208
+ });
10209
+ it("#6106 a check that fails on a pass-through wrapper with no real binary is env.tool_missing after one dependency preparation, not ci.red", async () => {
10210
+ const w = world(); const prepared = [];
10211
+ w.io.deps = { prepare: async () => { prepared.push(1); return []; } };
10212
+ w.io.runCommand = async () => ({ rc: 127, output: "forgedock heavy: eslint at /w/web/node_modules/.bin/eslint is a PATH pass-through wrapper with no real binary behind it" });
10213
+ const r = await atIdleLoad(() => run(w, { precheck: { commands: ["make lint"] }, verify: { ...parseVerify({}), precheckBlock: true } }));
10214
+ assert.equal(r.code, "env.tool_missing"); assert.equal(r.terminalReason, "needs-human");
10215
+ assert.ok(prepared.length >= 2, "deps prepared at setup and once more after the missing tool");
10216
+ assert.equal(builders(w).filter((b) => /declared check commands failed/.test(b[4])).length, 0, "no builder resume");
10217
+ });
10218
+ it("#6094 a check that fails in a test file the diff does not touch is rerun once: green on rerun is no fix round; red twice stays ci.red", async () => {
10219
+ const out = "not ok 3 - ten concurrent\n location: '/w/bin/tests/mirror-script.test.mjs:48:3'";
10220
+ const w = world(); let n = 0;
10221
+ w.io.runCommand = async () => (++n === 1 ? { rc: 1, output: out } : { rc: 0, output: "" });
10222
+ const r = await atIdleLoad(() => run(w, { precheck: { commands: ["make test"] }, verify: { ...parseVerify({}), precheckBlock: true } }));
10223
+ assert.equal(r.terminalReason, "merged"); assert.equal(n, 2);
10224
+ assert.equal(builders(w).filter((b) => /declared check commands failed/.test(b[4])).length, 0);
10225
+ const w2 = world(), dir2 = tmpDir("lean-6094-");
10226
+ w2.io.runCommand = async () => ({ rc: 1, output: out });
10227
+ const r2 = await atIdleLoad(() => run(w2, { dir: dir2, precheck: { commands: ["make test"] }, verify: { ...parseVerify({}), precheckBlock: true } }));
10228
+ assert.equal(r2.code, "ci.red"); assert.equal(readLog(dir2, 7).filter((e) => e.event === "PRECHECK_FLAKE_RERUN").length, 1, "exactly one rerun");
10229
+ const w3 = world(), dir3 = tmpDir("lean-6094b-"); // a failure in a test the diff touches is the lane's: no rerun
10230
+ w3.io.runCommand = async () => ({ rc: 1, output: "not ok 1 - x\n location: 'test/foo.test.js:4:1'" });
10231
+ await atIdleLoad(() => run(w3, { dir: dir3, precheck: { commands: ["make test"] }, verify: { ...parseVerify({}), precheckBlock: true } }));
10232
+ assert.equal(readLog(dir3, 7).filter((e) => e.event === "PRECHECK_FLAKE_RERUN").length, 0);
10233
+ });
10234
+ it("#5749 precheck_block detail carries the failing check tail", async () => {
10235
+ const w = world();
10236
+ w.io.runCommand = async () => ({ rc: 1, output: `${"noise\n".repeat(60)}FAILED lane-check shellcheck scripts/x.sh` });
10237
+ const r = await atIdleLoad(() => run(w, { precheck: { commands: ["make lanecheck"] }, verify: { ...parseVerify({}), precheckBlock: true } }));
10238
+ assert.equal(r.code, "ci.red");
10239
+ assert.match((w.comments.find((c) => c.includes("FORGE:NEEDS_HUMAN")) ?? ""), /`make lanecheck`[\s\S]*FAILED lane-check shellcheck scripts\/x\.sh/);
10240
+ });
10241
+ });
10242
+
10243
+ describe("#6107 precheck parks carry the failing check; a ci.red recovery runs the checks on a synced tree", () => {
10244
+ const block = { precheck: { commands: ["make lanecheck"] }, verify: { ...parseVerify({}), precheckBlock: true } };
10245
+ const nhOf = (w) => w.comments.find((c) => c.includes("FORGE:NEEDS_HUMAN")) ?? "";
10246
+ it("the park names the failing check and carries only its last 40 lines, secrets redacted, and the run log has them too", async () => {
10247
+ const w = world(); const dir = tmpDir("lean-6107-");
10248
+ w.io.runCommand = async () => ({ rc: 1, output: `EARLY-NOISE-MARKER\n${"noise\n".repeat(60)}API_TOKEN=hunter2hunter2\nAuthorization: Bearer abcdefghijklmnop\nFAILED lane-check shellcheck scripts/x.sh` });
10249
+ const r = await atIdleLoad(() => run(w, { dir, ...block }));
10250
+ assert.equal(r.code, "ci.red");
10251
+ const nh = nhOf(w);
10252
+ assert.match(nh, /Failing check `make lanecheck`, exit 1, last 40 lines/);
10253
+ assert.match(nh, /FAILED lane-check shellcheck scripts\/x\.sh/);
10254
+ assert.doesNotMatch(nh, /EARLY-NOISE-MARKER/); assert.doesNotMatch(nh, /hunter2hunter2|abcdefghijklmnop/);
10255
+ const rec = readLog(dir, 7).find((e) => e.event === "PRECHECK_FAILED");
10256
+ assert.equal(rec.checks[0].command, "make lanecheck"); assert.match(rec.checks[0].tail, /FAILED lane-check/); assert.doesNotMatch(rec.checks[0].tail, /hunter2hunter2/);
10257
+ });
10258
+ it("a ci.red recovery that is behind its base merges the base before any check runs", async () => {
10259
+ const w = world({ behind: 2 }); const order = [];
10260
+ w.io.runCommand = async () => { order.push("check"); return { rc: 0, output: "" }; };
10261
+ const orig = w.io.git; w.io.git = async (a, ...rest) => { if (a[0] === "merge" && a[1] === "--no-edit") order.push("merge"); return orig(a, ...rest); };
10262
+ const r = await atIdleLoad(() => run(w, { recover: { code: "ci.red", attempt: 1 }, precheck: { commands: ["make lanecheck"] } }));
10263
+ assert.equal(r.terminalReason, "merged");
10264
+ assert.ok(order.indexOf("merge") >= 0 && order.indexOf("merge") < order.indexOf("check"), `merge before check: ${order}`);
10265
+ });
10266
+ it("a ci.red recovery whose branch conflicts with the base ends base.conflict and never runs the checks on the stale tree", async () => {
10267
+ const w = world({ behind: 3, mergeResults: ["conflict"], conflictFiles: [".github/workflows/ci.yml"] }); let checks = 0;
10268
+ w.io.runCommand = async () => { checks++; return { rc: 1, output: "stale tree failure" }; };
10269
+ const r = await atIdleLoad(() => run(w, { recover: { code: "ci.red", attempt: 1 }, ...block }));
10270
+ assert.equal(r.code, "base.conflict"); assert.equal(checks, 0); assert.equal(w.merges.length, 0);
10271
+ assert.ok(w.calls.some((c) => c[0] === "git" && c[1] === "merge" && c[2] === "--abort"));
10272
+ });
10273
+ it("a first lane (no recovery) does not base-sync before the checks", async () => {
10274
+ const w = world({ behind: 2 });
10275
+ w.io.runCommand = async () => ({ rc: 0, output: "" });
10276
+ await atIdleLoad(() => run(w, { precheck: { commands: ["make lanecheck"] } }));
10277
+ assert.equal(w.calls.filter((c) => c[0] === "git" && c[1] === "merge" && c[2] === "--no-edit").length, 0);
10278
+ });
10279
+ });
10280
+
10281
+ describe("#5844 a busy host is not an absent CLI", () => {
10282
+ const base = { role: "builder", issue: 5844, cwd: "/tmp/x", model: "m", prompt: "p", system: "s" };
10283
+ it("probe timeout does not spawn a bare name", async () => {
10284
+ const { makeLeanRunner } = await import("./effects.mjs");
10285
+ let spawned = 0;
10286
+ const runner = makeLeanRunner({ runCli: async () => { spawned++; return {}; }, probe: () => false, resolveBin: () => null, probeTimedOut: () => true });
10287
+ await assert.rejects(runner(base), (e) => e.deferCode === OUTCOME_CODES.HOST_BUSY && e.retryInSeconds > 0 && e.spawnDeterministic !== true);
10288
+ assert.equal(spawned, 0);
10289
+ });
10290
+ it("a probe that answered absent still spawns, so the deterministic path stays reachable", async () => {
10291
+ const { makeLeanRunner } = await import("./effects.mjs");
10292
+ let spawned = 0;
10293
+ const runner = makeLeanRunner({ runCli: async () => { spawned++; return {}; }, probe: () => false, resolveBin: () => null, probeTimedOut: () => false });
10294
+ await runner(base);
10295
+ assert.equal(spawned, 1);
10296
+ });
10297
+ it("win32 bare name unresolved while the CLI is present defers host.busy, nothing spawned", async () => {
10298
+ const { makeLeanRunner } = await import("./effects.mjs");
10299
+ let spawned = 0;
10300
+ const runner = makeLeanRunner({ runCli: async () => { spawned++; return {}; }, probe: () => false, resolveBin: () => null, probeTimedOut: () => false, platform: "win32", binMissing: () => false });
10301
+ await assert.rejects(runner(base), (e) => e.deferCode === OUTCOME_CODES.HOST_BUSY && e.spawnDeterministic !== true);
10302
+ assert.equal(spawned, 0);
10303
+ const absent = makeLeanRunner({ runCli: async () => { spawned++; return {}; }, probe: () => false, resolveBin: () => null, probeTimedOut: () => false, platform: "win32", binMissing: () => true });
10304
+ await absent(base);
10305
+ assert.equal(spawned, 1, "proven absence still spawns so cli.spawn_failed stays reachable");
10306
+ });
10307
+ it("ENOENT with the CLI present is not cli.spawn_failed", async () => {
10308
+ const { runCliBackend } = await import("../runner.mjs");
10309
+ const dir = tmpDir("core-5844-");
10310
+ writeFileSync(join(dir, "claude"), "");
10311
+ const prev = process.env.PATH; process.env.PATH = dir;
10312
+ let err;
10313
+ try { runCliBackend({ spec: { name: "t" }, userMessage: "go", args: ["1"], cwd: tmpDir("core-5844-"), bin: "claude", logger: { log() {} }, spawnFn: () => ({ status: null, error: Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" }) }) }); } catch (e) { err = e; } finally { process.env.PATH = prev; }
10314
+ assert.equal(err.spawnDeterministic, undefined);
10315
+ assert.notEqual(err.code, "CLI_SPAWN_FAILED");
10316
+ const w = world(); w.io.runner = async () => { throw err; };
10317
+ const res = await run(w);
10318
+ assert.notEqual(res.code, OUTCOME_CODES.CLI_SPAWN_FAILED);
10319
+ });
10320
+ });
10321
+
10322
+ describe("#5753 frozen pytest commands run in the env CI runs them in", () => {
10323
+ const saved = {}; // #5753: a host ~/.forge/guards/o_r.json (another run's leftovers) must not add H-rows to these runs
10324
+ before(() => { for (const k of ["HOME", "USERPROFILE"]) saved[k] = process.env[k]; process.env.HOME = process.env.USERPROFILE = tmpDir("lean-5753-home-"); });
10325
+ after(() => { for (const [k, v] of Object.entries(saved)) if (v === undefined) delete process.env[k]; else process.env[k] = v; });
10326
+ it("#5753 a shared/ pytest validate is rewritten at freeze to the services/worker CI env and the freeze records it", async () => {
10327
+ const d = tmpDir("lean-5753a-"); const src = join(d, "ci.yml");
10328
+ writeFileSync(src, "jobs:\n worker:\n steps:\n - name: Test worker\n working-directory: services/worker\n run: poetry run pytest tests/ ../../shared -q\n");
10329
+ const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "python -m pytest shared/detection/test_x.py" }] };
10330
+ const w = world({ contract }); w.io.probeCommand = async () => ({ rc: 0, output: "" });
10331
+ await run(w, { dir: d, validateCatalogSources: [`../..${src.replace(/^[A-Za-z]:/, "").replace(/\\/g, "/")}`] });
10332
+ assert.ok(w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("cd services/worker && poetry run pytest ../../shared/detection/test_x.py")));
10333
+ assert.ok(!w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("python -m pytest shared/detection/test_x.py")));
10334
+ });
10335
+ it("#5753 a collect-only ImportError is a preflight miss corrected before the implement builder", async () => {
10336
+ const V2 = "python3 -m pytest -q tests/test_corpus.py";
10337
+ const c = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: V2 }] };
10338
+ const fixed = { ...c, validate: [c.validate[0], { id: "V2", command: "uv run pytest -q tests/test_corpus.py" }] };
10339
+ const dir = tmpDir("lean-5753b-");
10340
+ const w = world({ contract: c, fixedContract: fixed, validation: fixed.validate.map((v) => ({ id: v.id, command: v.command, exit: 0 })) });
10341
+ const collected = [];
10342
+ w.io.probeCommand = async () => ({ rc: 0, output: "" });
10343
+ w.io.preflightRun = async (a) => {
10344
+ if (/--collect-only/.test(a.command)) collected.push([a.command, w.seq.length]);
10345
+ return /--collect-only/.test(a.command) && !/uv run/.test(a.command) ? { rc: 2, output: "E ModuleNotFoundError: No module named 'html2text'\n" } : { rc: 1, output: "AssertionError: expected RED on base" };
10346
+ };
10347
+ assert.equal((await run(w, { dir })).terminalReason, "merged");
10348
+ const b = builders(w);
10349
+ assert.equal(b.length, 3, "plan + one contract correction + implement");
10350
+ assert.match(b[1][4], /V2: importing its test modules on the base worktree \(pytest --collect-only\) failed: needs Python module 'html2text'/);
10351
+ assert.ok(collected.some(([cmd]) => cmd === "python3 -m pytest --collect-only -q -q tests/test_corpus.py"));
10352
+ const firstImpl = w.seq.indexOf("builder-resume", w.seq.indexOf("builder-resume") + 1);
10353
+ assert.ok(collected.every(([, at]) => at < firstImpl), "every collect-only run happens before the implement session");
10354
+ const pf = readLog(dir, 7).filter((e) => e.event === "VALIDATE_PREFLIGHT");
10355
+ assert.deepEqual(pf.map((e) => [e.corrected, e.found.map((m) => [m.ids, m.tool, m.kind, m.source])]), [[true, [[["V2"], "html2text", "python-module", "collect"]]]]);
10356
+ });
10357
+ });
10358
+ describe("#5992 verify.guard_bypass: a lane clear of the red guard's files proceeds", () => {
10359
+ it("bypasses only when opted in and the lane diff misses the guarded files", async () => {
10360
+ for (const opt of [false, true]) {
10361
+ const w = world(), git = w.io.git;
10362
+ w.io.runCommand = async () => ({ rc: 1, output: "bare 429 at app/routers/listing_feeds.py" });
10363
+ w.io.git = async (a, o) => a[0] === "log" && a.includes("--format=%H%x1f%s%x1f%b") ? `${"a".repeat(40)}\x1ffeat: feeds (#39805)\x1f` : a[0] === "diff" && a.includes("--name-only") ? "docs/readme.md\n" : git(a, o);
10364
+ const r = await run(w, { verify: { invariants: ["bash scripts/guard.sh"], ...(opt ? { guardBypass: true } : {}) } });
10365
+ if (opt) assert.notEqual(r.code, "base.red", "bypassed");
10366
+ else assert.equal(r.code, "base.red", "default stays deferred (#5239)");
10367
+ }
10368
+ });
10369
+ });
10370
+
10371
+ describe("R2 guard_bypass never discards lane-owned failures", () => {
10372
+ const setup = (rc) => {
10373
+ const w = world(), git = w.io.git;
10374
+ w.io.runCommand = async ({ command, cwd }) => ({ rc: rc(command, String(cwd).includes("basered-")), output: "bare 429 at app/routers/listing_feeds.py" });
10375
+ w.io.git = async (a, o) => a[0] === "log" && a.includes("--format=%H%x1f%s%x1f%b") ? `${"a".repeat(40)}\x1ffeat: feeds (#39805)\x1f` : a[0] === "diff" && a.includes("--name-only") ? "docs/readme.md\n" : git(a, o);
10376
+ return w;
10377
+ };
10378
+ const verify = { invariants: ["bash scripts/guard.sh", "bash scripts/other-guard.sh"], guardBypass: true };
10379
+ it("a guard that is red only in the lane alongside a base-red guard does not bypass", async () => {
10380
+ const w = setup((c, onBase) => (c.includes("other-guard") ? (onBase ? 0 : 1) : 1));
10381
+ const r = await run(w, { verify });
10382
+ assert.notEqual(r.terminalReason, "merged", "lane-broken guard is not discarded");
10383
+ assert.equal(r.events?.some?.((e) => e.event === "BASE_RED_BYPASS") ?? false, false);
10384
+ });
10385
+ it("every failure base-red still bypasses", async () => {
10386
+ const w = setup(() => 1);
10387
+ const r = await run(w, { verify });
10388
+ assert.notEqual(r.code, "base.red", "bypassed");
10389
+ });
10390
+ });
10391
+
10392
+ describe("#6008 lease/hold/pause guard before push and merge (kept sandbox)", () => {
10393
+ // admission reads (first two) see no state; every later read sees `scenario`
10394
+ const guarded = (scenario) => { const w = world(); w.leaseWrites = []; let reads = 0;
10395
+ w.io.projector = { readState: async () => (++reads <= 2 ? null : scenario()), writeState: async (_i, st) => { w.leaseWrites.push(st); } }; return w; };
10396
+ const live = () => ({ v: 1, lease: { by: "x", batch: "b1", until: Date.now() + 600000 } });
10397
+ const refused = async (scenario, extra = {}) => { const w = guarded(scenario); const r = await run(w, { batchId: "b1", ...extra }); return { w, r }; };
10398
+ it("kept: a current lease of the lane's own batch merges", async () => {
10399
+ const { r } = await refused(live);
10400
+ assert.equal(r.terminalReason, "merged");
10401
+ });
10402
+ it("kept: no current lease, an expired lease or another batch's lease refuses push and merge and ends deferred", async () => {
10403
+ for (const sc of [() => ({ v: 1, lease: null }), () => ({ v: 1, lease: { by: "x", batch: "b1", until: 0 } }), () => ({ v: 1, lease: { by: "y", batch: "other", until: Date.now() + 600000 } })]) {
10404
+ const { w, r } = await refused(sc);
10405
+ assert.deepEqual([r.terminalReason, r.code], ["deferred", "lane.suspended"]);
10406
+ assert.ok(!(w.ghCalls ?? []).some?.((c) => /pr.*merge/.test(String(c))));
10407
+ }
10408
+ });
10409
+ it("kept: a held issue or a paused batch (dispatcher suspend marker) refuses push and merge", async () => {
10410
+ for (const reason of ["held", "paused"]) {
10411
+ const { r } = await refused(() => ({ ...live(), suspend: { reason, batch: "b1" } }));
10412
+ assert.deepEqual([r.terminalReason, r.code], ["deferred", "lane.suspended"]);
10413
+ assert.match(r.detail, new RegExp(reason));
10414
+ }
10415
+ });
10416
+ it("a lane without a batch id (interactive run-issue) is not guarded", async () => {
10417
+ const w = guarded(() => ({ v: 1, lease: null }));
10418
+ assert.equal((await run(w)).terminalReason, "merged");
10419
+ });
10420
+ });
10421
+
10422
+ describe("gate cut (#6083): advisory by default, enforce re-promotes", () => {
10423
+ it("a reviewer unimplemented row without a failing assertion is recorded and the lane merges; enforce makes it block", async () => {
10424
+ const w = world({ reviews: [bad("still null-derefs")] });
10425
+ const r = await run(w);
10426
+ assert.equal(r.terminalReason, "merged"); assert.equal(builders(w).length, 2, "no resume spent");
10427
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\)[^\n]*conformance\.unimplemented/);
10428
+ const w2 = world({ reviews: [bad("still null-derefs"), bad("still null-derefs")] });
10429
+ assert.equal((await run(w2, ENF)).terminalReason, "needs-human");
10430
+ });
10431
+ it("a validate step with no recorded result is advisory: the lane merges without a resume", async () => {
10432
+ const w = world({ validation: [] });
10433
+ const r = await run(w);
10434
+ assert.equal(r.terminalReason, "merged"); assert.equal(builders(w).length, 2);
10435
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\)[^\n]*validate_missing/);
10436
+ });
10437
+ it("a reviewer regression row still blocks", async () => {
10438
+ const w = world({ reviews: [conf({ regressions: [{ at: "src/bar.js:4", failure: "caller passes undefined" }] }), ok()] });
10439
+ assert.equal((await run(w)).terminalReason, "merged"); assert.equal(builders(w).length, 3, "the regression is resumed");
10440
+ });
10441
+ });