forgedock 1.54.0 → 1.55.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 (114) hide show
  1. package/bin/auth/app-token.mjs +2 -0
  2. package/bin/auth/app-token.test.mjs +9 -1
  3. package/bin/engine/events.mjs +1 -0
  4. package/bin/engine/events.test.mjs +5 -1
  5. package/bin/engine/outcome-codes.mjs +3 -0
  6. package/bin/engine-cli.mjs +126 -34
  7. package/bin/forgedock.mjs +56 -4
  8. package/bin/gc-schedule.mjs +83 -0
  9. package/bin/gc.mjs +56 -8
  10. package/bin/help-text.mjs +1 -1
  11. package/bin/hooks/pre-tool-use.mjs +1 -0
  12. package/bin/init-detect.mjs +73 -2
  13. package/bin/labels.json +5 -0
  14. package/bin/lean/admission.mjs +21 -1
  15. package/bin/lean/baselines.mjs +43 -0
  16. package/bin/lean/baselines.test.mjs +33 -0
  17. package/bin/lean/batch-health.mjs +43 -6
  18. package/bin/lean/batch-health.test.mjs +41 -1
  19. package/bin/lean/batch.mjs +41 -4
  20. package/bin/lean/batch.test.mjs +106 -3
  21. package/bin/lean/conformance.mjs +131 -12
  22. package/bin/lean/conformance.test.mjs +172 -3
  23. package/bin/lean/depcache.mjs +23 -2
  24. package/bin/lean/depcache.test.mjs +22 -0
  25. package/bin/lean/docsgate.mjs +137 -0
  26. package/bin/lean/docsgate.test.mjs +78 -0
  27. package/bin/lean/effects.mjs +31 -2
  28. package/bin/lean/enumerating.mjs +39 -13
  29. package/bin/lean/enumerating.test.mjs +20 -0
  30. package/bin/lean/execution.test.mjs +3 -3
  31. package/bin/lean/fastforward.mjs +93 -0
  32. package/bin/lean/fastforward.test.mjs +73 -0
  33. package/bin/lean/guardgate.mjs +38 -7
  34. package/bin/lean/guardgate.test.mjs +39 -0
  35. package/bin/lean/issuewatch-install.mjs +92 -0
  36. package/bin/lean/issuewatch-install.test.mjs +31 -0
  37. package/bin/lean/issuewatch-parity.mjs +33 -3
  38. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  39. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  40. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  41. package/bin/lean/issuewatch-verify.mjs +51 -9
  42. package/bin/lean/issuewatch.mjs +153 -33
  43. package/bin/lean/issuewatch.test.mjs +243 -22
  44. package/bin/lean/lean.mjs +381 -75
  45. package/bin/lean/lean.test.mjs +437 -20
  46. package/bin/lean/light.mjs +11 -3
  47. package/bin/lean/light.test.mjs +27 -0
  48. package/bin/lean/lightlane.mjs +8 -3
  49. package/bin/lean/lightlane.test.mjs +20 -0
  50. package/bin/lean/mechfix.mjs +35 -4
  51. package/bin/lean/mechfix.test.mjs +48 -1
  52. package/bin/lean/orchestrate-children.test.mjs +10 -0
  53. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  54. package/bin/lean/orchestrate.mjs +28 -4
  55. package/bin/lean/overlap.mjs +20 -0
  56. package/bin/lean/overlap.test.mjs +49 -0
  57. package/bin/lean/pagegate.mjs +152 -0
  58. package/bin/lean/pagegate.test.mjs +77 -0
  59. package/bin/lean/parked-relabel.mjs +32 -0
  60. package/bin/lean/parked-relabel.test.mjs +45 -0
  61. package/bin/lean/phaseledger.mjs +17 -2
  62. package/bin/lean/postdeploy-check.mjs +27 -0
  63. package/bin/lean/postdeploy-check.test.mjs +13 -1
  64. package/bin/lean/postrun.mjs +32 -0
  65. package/bin/lean/postrun.test.mjs +41 -0
  66. package/bin/lean/preflight.mjs +46 -0
  67. package/bin/lean/preflight.test.mjs +30 -1
  68. package/bin/lean/prompts.mjs +36 -6
  69. package/bin/lean/recovery.test.mjs +16 -0
  70. package/bin/lean/release.mjs +30 -3
  71. package/bin/lean/release.test.mjs +36 -0
  72. package/bin/lean/render.mjs +17 -6
  73. package/bin/lean/reproquality.mjs +116 -0
  74. package/bin/lean/reproquality.test.mjs +85 -0
  75. package/bin/lean/review-trigger.mjs +8 -3
  76. package/bin/lean/sandbox-budget.test.mjs +27 -0
  77. package/bin/lean/schedd.mjs +40 -11
  78. package/bin/lean/schedd.test.mjs +12 -1
  79. package/bin/lean/testadequacy.mjs +97 -0
  80. package/bin/lean/testadequacy.test.mjs +92 -0
  81. package/bin/lean/testsandbox.mjs +202 -0
  82. package/bin/lean/testsandbox.test.mjs +157 -0
  83. package/bin/lean/toolplace.mjs +5 -2
  84. package/bin/lean/toolplace.test.mjs +6 -0
  85. package/bin/lean/verify.mjs +6 -1
  86. package/bin/lean/verify.test.mjs +18 -2
  87. package/bin/lean/warmtree.mjs +77 -0
  88. package/bin/lean/warmtree.test.mjs +81 -0
  89. package/bin/runner.mjs +6 -1
  90. package/bin/stats/conformance-outcomes.mjs +12 -2
  91. package/bin/stats/depth.mjs +24 -1
  92. package/bin/stats/depth.test.mjs +21 -1
  93. package/bin/stats/index.mjs +5 -2
  94. package/bin/stats/query.mjs +2 -1
  95. package/commands/cleanup.md +18 -0
  96. package/commands/fd-introspect.md +19 -0
  97. package/commands/milestone.md +5 -1
  98. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  99. package/commands/recover-orphans.md +31 -1
  100. package/commands/review-pr-staging.md +9 -0
  101. package/commands/review-pr.md +2 -0
  102. package/docs/CI.md +1 -1
  103. package/docs/CONFIG.md +26 -1
  104. package/docs/EVENTS.md +1 -0
  105. package/docs/ISSUE-WATCH.md +12 -3
  106. package/docs/eval/adversarial-bench.md +1 -1
  107. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  108. package/package.json +1 -1
  109. package/scripts/bench-lightlane.mjs +3 -2
  110. package/scripts/hotspots.sh +7 -4
  111. package/scripts/hotspots.test.sh +12 -0
  112. package/scripts/recover-orphans-stateless.test.sh +79 -0
  113. package/scripts/transition-label.sh +2 -0
  114. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
@@ -1,5 +1,6 @@
1
1
  // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { foldRegression } from "./baselines.mjs";
3
4
  import { describe, it } from "node:test";
4
5
  import { laneBackendId } from "./limits.mjs";
5
6
  import { parseExperiment, assignArm } from "../experiment.mjs";
@@ -16,7 +17,7 @@ import { parseVerify } from "./verify.mjs";
16
17
  import { worktreeFingerprint } from "./precheck.mjs";
17
18
  import { renderInvestigation, renderPlan, renderImplementation, renderReview, renderPrBody, renderTrajectory, renderStructure, renderContract, renderAmendments, parseAmendmentsComment, contractJson, parseContractComment, sanitizeMd, capComment, section, cell, NR, MAX_COMMENT_CHARS } from "./render.mjs";
18
19
  import { orchestrate, parseDeps, formatTable, pickNext } from "./orchestrate.mjs";
19
- import { REVIEWER_SYSTEM, REVIEW_RUBRIC, approxTokens as rawTokens, FORGEDOCK_CLI, builderPlanPrompt, builderImplementPrompt, reviewerPrompt, investigationVerdict, decisionNote, hotspotPlanNote, hotspotBuildRule } from "./prompts.mjs";
20
+ import { REVIEWER_SYSTEM, REVIEW_RUBRIC, approxTokens as rawTokens, FORGEDOCK_CLI, builderPlanPrompt, builderImplementPrompt, reviewerPrompt, investigationVerdict, decisionNote, hotspotPlanNote, hotspotBuildRule, reproPlanNote } from "./prompts.mjs";
20
21
  import { parseReview, unnamedEdges, structureNote, applyAmendments, validateContract, scopeText, DECISION_SOURCES } from "./conformance.mjs";
21
22
  import { mapRecord } from "../engine/telemetry-seam.mjs";
22
23
  import { readLog as readRepoLog } from "../engine/runlog.mjs";
@@ -53,6 +54,8 @@ const CONTRACT = {
53
54
  preserve: [{ id: "P1", what: "Existing callers of foo keep working. (src/bar.js)" }],
54
55
  validate: [{ id: "V1", command: "node --test test/foo.test.js" }],
55
56
  };
57
+ const OUTER_CONTRACT = CONTRACT;
58
+ const TEST_PLAN = [{ requirement: "R1", proof: "foo returns a value for a null argument instead of throwing a TypeError", level: "unit", level_reason: "a pure function, a direct call observes the cause", repro: "foo handles null", regression: ["existing foo callers"], env: [], command: "node --test test/foo.test.js" }]; // #5445: bug lanes freeze a test plan
56
59
  const fence = (o) => "```json\n" + JSON.stringify(o) + "\n```";
57
60
  /** A complete conforming review for `contract` over `files`; `patch` overrides fields. */
58
61
  const conf = (patch = {}, contract = CONTRACT, files = ["src/foo.js", "test/foo.test.js"]) => fence({
@@ -241,7 +244,8 @@ describe("core work-on", () => {
241
244
  assert.equal(w.followups.length, 0);
242
245
  const ev = readLog(dir, 7).map((e) => e.event);
243
246
  assert.ok(ev.includes("CONTRACT_FROZEN") && ev.includes("CONFORMANCE"));
244
- assert.equal(ev[0], "RUN_START"); assert.equal(ev.at(-1), "RUN_TERMINAL");
247
+ assert.equal(ev[0], "RUN_START"); assert.equal(ev.filter((e) => e === "RUN_TERMINAL").length, 1);
248
+ assert.ok(ev.slice(ev.indexOf("RUN_TERMINAL") + 1).every((e) => /^(POSTRUN_|LEDGER_|BRANCH_DELET|TEARDOWN|WORKTREE|GUARD_|STRUCTURE_DELTA)/.test(e)), "#5437: only post-run bookkeeping follows RUN_TERMINAL");
245
249
  });
246
250
 
247
251
  it("investigation and plan comments are posted before the reviewer runs and before the in-review label", async () => {
@@ -269,8 +273,9 @@ describe("core work-on", () => {
269
273
  const mapped = w.telemetry.map((t) => mapRecord(t, 5)).filter(Boolean);
270
274
  assert.deepEqual(mapped.filter((m) => m.event === "phase_attempt").map((m) => m.phase), ["implement", "implement", "review"]);
271
275
  assert.equal(mapped[0].payload.input_tokens, 10);
272
- assert.equal(mapped.at(-1).event, "run_terminal");
273
- assert.equal(mapped.at(-1).payload.reason, "merged");
276
+ const term = mapped.filter((m) => m.event === "run_terminal");
277
+ assert.equal(term.length, 1);
278
+ assert.equal(term[0].payload.reason, "merged");
274
279
  });
275
280
 
276
281
  it("invalid with evidence: the investigation is the evidence comment, closes, trajectory rows", async () => {
@@ -864,6 +869,20 @@ describe("core work-on", () => {
864
869
  assert.notEqual((await run(l, { placement: { where: "local", reason: "x" } })).code, "env.tool_missing");
865
870
  });
866
871
 
872
+ it("#5423 a remote lane provisions the sandbox once before ending env.tool_missing; a first env lane leaves no needs-human label", async () => {
873
+ const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "promtool test rules r.yml" }] };
874
+ const remote = { placement: { where: "remote", reason: "mode remote" } };
875
+ const w = world({ contract }); let fixed = false, prep = 0;
876
+ w.io.deps = { prepare: async () => { prep++; fixed = true; return []; } };
877
+ w.io.probeCommand = async (a) => ({ rc: /promtool/.test(JSON.stringify(a)) && !fixed ? 127 : 0, output: "" });
878
+ assert.notEqual((await run(w, { dir: tmpDir("lean-5423-"), ...remote })).code, "env.tool_missing");
879
+ assert.ok(prep >= 1);
880
+ const l = world({ contract }); l.io.probeCommand = async (a) => ({ rc: /promtool/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
881
+ const r = await run(l, { dir: tmpDir("lean-5423b-"), ...remote });
882
+ assert.equal(r.code, "env.tool_missing");
883
+ assert.ok(!l.edits.some((e) => e.includes("--add-label") && e.includes("needs-human")), JSON.stringify(l.edits));
884
+ });
885
+
867
886
  it("#4778 a relayed host capability does not end the remote lane before building; a failed relay still recovers locally", async () => {
868
887
  const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "promtool test rules r.yml" }] };
869
888
  const remote = { placement: { where: "remote", reason: "mode remote" }, hostCaps: { hostCapabilities: ["promtool"] } };
@@ -952,6 +971,9 @@ describe("core work-on", () => {
952
971
  });
953
972
  });
954
973
 
974
+ import { e2eCheckFor } from "./postdeploy-check.mjs";
975
+ import { autoPostDeployE2e } from "./conformance.mjs";
976
+
955
977
  describe("conformance gate (frozen contract, precheck, structured review)", () => {
956
978
  const Q2 = "Existing callers of foo keep working.";
957
979
  const two = (d2 = "deliver", extra = {}) => ({ ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: Q2, disposition: d2, ...(d2 === "defer" || d2 === "post-deploy" ? { bucket: "post-deploy" } : {}), ...extra }],
@@ -1030,9 +1052,21 @@ describe("conformance gate (frozen contract, precheck, structured review)", () =
1030
1052
  assert.equal(w.closed[0].at(-1), "completed");
1031
1053
  });
1032
1054
 
1055
+ it("#5468 prod-only e2e_unverified is the only finding: the engine converts it to a post-deploy check and the lane merges", async () => {
1056
+ const PQ = "https://store.example.io/{slug}/agent.md returns 200 for every published listing [type:e2e]";
1057
+ const k = two("deliver", { quote: PQ });
1058
+ const kFrozen = autoPostDeployE2e(k).contract; // the engine's freeze rewrite: the reviewer judges the post-deploy row
1059
+ const w = world({ contract: k, body: `${ISSUE_BODY}\n- ${PQ}`, claims: [{ id: "R1", status: "implemented" }, { id: "R2", status: "implemented" }], reviews: [conf({ issue_coverage: [{ quote: "foo must handle a null argument without throwing.", status: "covered" }, { quote: PQ, status: "covered" }] }, kFrozen, files2)], resumeChanged: files2 });
1060
+ const g = e2eCheckFor("R2", PQ); // the fake git cannot show the engine's commit: serve the generated entry as HEAD's checks file
1061
+ w.baseFiles = { "HEAD:.forge/post-deploy-checks.json": JSON.stringify({ [g.id]: g.entry }) };
1062
+ const r = await run(w);
1063
+ assert.equal(r.terminalReason, "merged"); assert.notEqual(r.code, "conformance.e2e_unverified");
1064
+ assert.equal(w.merges.length, 1);
1065
+ });
1066
+
1033
1067
  for (const d of ["defer", "post-deploy"]) {
1034
1068
  it(`a contracted ${d} is filed only after the reviewer accepts it, then linked in the PR and on close`, async () => {
1035
- const k = two(d, { why: d === "defer" ? "separate module" : "only measurable after deploy", ...(d === "post-deploy" ? { check: "login-smoke" } : {}) });
1069
+ const k = two(d, { why: d === "defer" ? "separate module" : "only measurable after deploy", ...(d === "post-deploy" ? { check: "login-smoke", local_infeasible_why: "needs live traffic" } : {}) });
1036
1070
  const w = world({ contract: k, claims: [{ id: "R1", status: "implemented" }], reviews: [conf({}, { ...k, requirements: [k.requirements[0], { ...k.requirements[1], tracked: "#900" }] })] });
1037
1071
  if (d === "post-deploy") w.baseFiles = { "origin/staging:.forge/post-deploy-checks.json": JSON.stringify({ "login-smoke": "true" }) };
1038
1072
  const r = await run(w);
@@ -1476,6 +1510,15 @@ describe("conformance shadow mode (the default)", () => {
1476
1510
  assert.match(traj(w)[0], /\| Review \| shadow: would block \(nonconforming\) \|/);
1477
1511
  });
1478
1512
 
1513
+ it("#5439 a shadow would-BLOCK lane still files its accepted deferral and merges", async () => {
1514
+ const k = { ...CONTRACT, preserve: [], requirements: [CONTRACT.requirements[0], { id: "R2", quote: "Old callers log a warning.", disposition: "defer", why: "w", bucket: "owner:rotate the key" }] };
1515
+ const w = world({ contract: k, body: `${ISSUE_BODY}\n- Old callers log a warning.`, claims: [{ id: "R1", status: "implemented" }], reviews: [conf({ issue_coverage: [{ quote: "foo must handle a null argument without throwing.", status: "covered" }, { quote: "Existing callers of foo keep working.", status: "missing" }] }, k)] });
1516
+ const r = await runShadow(w);
1517
+ assert.equal(r.terminalReason, "merged");
1518
+ assert.match(shadowNote(w), /would BLOCK/);
1519
+ assert.equal(w.followups.length, 1); assert.match(w.followups[0].items[0].key, /^R2: /);
1520
+ });
1521
+
1479
1522
  it("scope creep does not block in shadow (as today) but is recorded", async () => {
1480
1523
  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"])] });
1481
1524
  assert.equal((await runShadow(w)).terminalReason, "merged");
@@ -1533,6 +1576,47 @@ describe("conformance shadow mode (the default)", () => {
1533
1576
  assert.match(nhBody(w), /validate V1 \(`node --test test\/foo\.test\.js`\) failed \(exit 1\)/);
1534
1577
  });
1535
1578
 
1579
+ it("#5447 replay: a missing test module is provisioned once and the lane retries; if it stays missing it ends env.tool_missing, never merged", async () => {
1580
+ const v = [{ id: "V1", command: "node --test test/foo.test.js", exit: 1 }];
1581
+ const w = world({ validation: v }); let provisioned = 0, installed = false;
1582
+ w.io.deps = { prepare: async () => { provisioned++; installed = true; return []; } };
1583
+ w.io.runCommand = async () => (installed ? { rc: 0, output: "" } : { rc: 1, output: "ModuleNotFoundError: No module named 'pytest'" });
1584
+ const ok = await run(w, { conformance: "enforce" });
1585
+ assert.notEqual(ok.code, OUTCOME_CODES.ENV_TOOL_MISSING); assert.equal(provisioned >= 1, true);
1586
+ const w2 = world({ validation: v }); let again = 0;
1587
+ w2.io.deps = { prepare: async () => { again++; return []; } };
1588
+ w2.io.runCommand = async () => ({ rc: 1, output: "ModuleNotFoundError: No module named 'yaml'" });
1589
+ const r = await run(w2, { conformance: "enforce" });
1590
+ 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");
1591
+ });
1592
+
1593
+ it("#5447 a test plan declaring env: a missing runner is provisioned once and the lane builds; if it stays missing the lane ends env.tool_missing before building", async () => {
1594
+ const contract = { ...CONTRACT, test_plan: [{ requirement: "R1", proof: "the pytest case no longer errors at collection", level: "unit", level_reason: "cheapest level that observes it", repro: "no-repro", reason: "env-only", command: "node --test test/foo.test.js", env: ["pytest"] }] };
1595
+ const w = world({ contract }); let installed = false;
1596
+ w.io.deps = { prepare: async () => [] };
1597
+ w.io.runCommand = async ({ command }) => { if (/pip install/.test(command)) installed = true; return /pytest --version/.test(command) && !installed ? { rc: 1, output: "No module named pytest" } : { rc: 0, output: "" }; };
1598
+ const ok = await run(w, { conformance: "enforce" });
1599
+ assert.notEqual(ok.code, OUTCOME_CODES.ENV_TOOL_MISSING); assert.ok(installed);
1600
+ const w2 = world({ contract });
1601
+ w2.io.runCommand = async ({ command }) => (/pytest --version/.test(command) ? { rc: 1, output: "" } : { rc: 0, output: "" });
1602
+ const r = await run(w2, { conformance: "enforce" });
1603
+ assert.equal(r.code, OUTCOME_CODES.ENV_TOOL_MISSING); assert.equal(w2.merges.length, 0);
1604
+ });
1605
+
1606
+ it("#5447 a failed install covering a changed file blocks through the gate (needs-human env.tool_missing, not merged); an unrelated failed install is only logged", async () => {
1607
+ const v = [{ id: "V1", command: "node --test test/foo.test.js", exit: 0 }];
1608
+ const w = world({ validation: v }); let calls = 0;
1609
+ w.io.deps = { prepare: async () => { calls++; return [{ status: "failed", eco: "npm", dir: ".", key: null, ms: 1, reason: "install failed: ERESOLVE" }]; } };
1610
+ const r = await run(w, { conformance: "enforce" });
1611
+ assert.equal(r.code, OUTCOME_CODES.ENV_TOOL_MISSING); assert.equal(w.merges.length, 0);
1612
+ assert.equal(calls, 2, "the toolchain prepare plus exactly one provisioning retry");
1613
+ assert.match(nhBody(w), /dependency install failed \(npm: install failed: ERESOLVE\) for a package the changed file/);
1614
+ const w2 = world({ validation: v });
1615
+ w2.io.deps = { prepare: async () => [{ status: "failed", eco: "poetry", dir: "services/other", key: null, ms: 1, reason: "install failed" }] };
1616
+ const r2 = await run(w2, { conformance: "enforce" });
1617
+ assert.notEqual(r2.code, OUTCOME_CODES.ENV_TOOL_MISSING);
1618
+ });
1619
+
1536
1620
  it("#4323 a validate the host cannot run (missing module) ends env.tool_missing naming it: no builder resume, no reviewer", async () => {
1537
1621
  const v = [{ id: "V1", command: "node --test test/foo.test.js", exit: 1 }];
1538
1622
  for (const conformance of ["shadow", "enforce"]) {
@@ -1800,7 +1884,7 @@ describe("conformance shadow mode (the default)", () => {
1800
1884
  const r = await runShadow(w, { dir, reviewTrigger: { mode: "shadow", riskPaths: ["src/**"] } });
1801
1885
  assert.equal(r.terminalReason, "needs-human"); assert.equal(w.merges.length, 0);
1802
1886
  assert.equal(r.code, "conformance.omission"); assert.equal(builders(w).length, 3, "one builder resume, as in enforce");
1803
- assert.deepEqual(r.conformance, { mode: "enforce", would: null, risk: true });
1887
+ assert.deepEqual(noAdq(r.conformance), { mode: "enforce", would: null, risk: true });
1804
1888
  const log = readLog(dir, 7);
1805
1889
  assert.deepEqual(log.filter((e) => e.event === "CONFORMANCE_RISK_ENFORCED").map((e) => e.paths), [["src/foo.js"]], "logged once (sticky across the resume)");
1806
1890
  assert.equal(log.find((e) => e.event === "RUN_TERMINAL").conformance_mode, "enforce");
@@ -1815,7 +1899,7 @@ describe("conformance shadow mode (the default)", () => {
1815
1899
  const s = world({ contract: { ...CONTRACT, preserve: [] }, changed: ["src/auth/foo.js", "test/foo.test.js"], reviews: [omission()] });
1816
1900
  const rs = await runShadow(s, { reviewTrigger: { mode: "shadow", riskPaths: ["db/**"] } });
1817
1901
  assert.equal(rs.terminalReason, "merged", "an auth path with no declared glob stays shadow");
1818
- assert.deepEqual(rs.conformance, { mode: "shadow", would: "nonconforming", risk: false });
1902
+ assert.deepEqual(noAdq(rs.conformance), { mode: "shadow", would: "nonconforming", risk: false });
1819
1903
  });
1820
1904
 
1821
1905
  it("#5207 shadow: an in-lane engineering deferral (bucket new-issue) resumes the builder once and is never filed", async () => {
@@ -1850,7 +1934,7 @@ describe("conformance shadow mode (the default)", () => {
1850
1934
  const e = world({ contract: k, changed, reviews: [omission(), omission()] });
1851
1935
  const re = await runShadow(e, { reviewTrigger: { mode: "shadow", riskPaths: [], enforceDomains: ["frontend"] } });
1852
1936
  assert.equal(re.terminalReason, "needs-human"); assert.equal(e.merges.length, 0);
1853
- assert.deepEqual(re.conformance, { mode: "enforce", would: null, risk: true });
1937
+ assert.deepEqual(noAdq(re.conformance), { mode: "enforce", would: null, risk: true });
1854
1938
  assert.ok(traj(e)[0].includes("Conformance enforced (review.enforce_domains): frontend"));
1855
1939
  });
1856
1940
 
@@ -2047,7 +2131,7 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2047
2131
  assert.equal(hotspotBuildRule(null), ""); assert.equal(hotspotBuildRule(facts([], { enabled: false })), "");
2048
2132
  const plan = builderPlanPrompt(7) + hotspotPlanNote(facts([HOT, { ...HOT, path: "a/b.py" }, { ...HOT, path: "c/d.py" }]));
2049
2133
  // 1850: #4404 (verify out_of_band) and #4396 (split size rule) grew the plan prompt to ~1803 tokens on CI paths; 1900: #4589 (check timeout is not a block, one block-rule line). 2050: #4724 (deferred-row bucket rule). 1675 (hotspot case): #5284 (rubric prod_parity clause). 2375/1825: #5345 (self-check and pitfall lines).
2050
- assert.ok(approxTokens(plan) <= 2425, `plan prompt with hotspots is ${approxTokens(plan)} tokens`);
2134
+ assert.ok(approxTokens(plan) <= 2600, `plan prompt with hotspots is ${approxTokens(plan)} tokens`);
2051
2135
  assert.ok(approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([]))) <= 1875, `implement prompt with the hotspot rule is ${approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([])))} of 1675 tokens`); // 1600: #4591 (never hand-name migration files) and #4596 (i18n translate rule), one line each; 1650: #4726 (e2e rule)
2052
2136
  });
2053
2137
 
@@ -2117,6 +2201,7 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2117
2201
  });
2118
2202
 
2119
2203
  describe("bug lanes freeze a red-green repro_test (#4271)", () => {
2204
+ const CONTRACT = { ...OUTER_CONTRACT, test_plan: TEST_PLAN };
2120
2205
  const RT = { path: "test/foo.test.js", id: "foo handles null", command: "node --test test/foo.test.js" };
2121
2206
  const BUG = [{ name: "bug" }];
2122
2207
  /** world labelled `labels` whose io.redGreen answers from `rg` in order (the last repeats). */
@@ -2199,6 +2284,16 @@ describe("bug lanes freeze a red-green repro_test (#4271)", () => {
2199
2284
  }
2200
2285
  });
2201
2286
 
2287
+ it("#5487: the sign-off hook env reaches the builder only, never the engine's repro/validate commands", async () => {
2288
+ const w = rworld([RED_GREEN]);
2289
+ w.io.runTmp = { prune: async () => {}, path: (id) => `/rt/${id}`, make: async (_i, id) => `/rt/${id}`, remove: async () => true };
2290
+ w.io.fs.list = async () => ["pre-commit"];
2291
+ const base = w.io.runCommand; w.io.runCommand = async (a) => (/^chmod /.test(a.command) ? { r: { exit: 0 } } : base ? base(a) : { rc: 0, output: "" });
2292
+ assert.equal((await run(w)).terminalReason, "merged");
2293
+ assert.ok(w.envs.some((e) => e?.GIT_CONFIG_KEY_0 === "core.hooksPath"), "builder env carries the hook");
2294
+ assert.ok(w.rgCalls.length > 0);
2295
+ assert.ok(w.rgCalls.every((c) => c.env.GIT_CONFIG_KEY_0 === undefined && c.env.GIT_CONFIG_COUNT === undefined), "engine commands do not");
2296
+ });
2202
2297
  it("the repro harness runs with the lane env: toolchain PATH and the per-run TMPDIR (#4334)", async () => {
2203
2298
  const w = rworld([RED_GREEN]);
2204
2299
  w.io.runTmp = { prune: async () => {}, path: (id) => `/rt/${id}`, make: async (_i, id) => `/rt/${id}`, remove: async () => true };
@@ -2207,6 +2302,15 @@ describe("bug lanes freeze a red-green repro_test (#4271)", () => {
2207
2302
  assert.equal(w.rgCalls[0].env.PATH, "/shim/bin:/host/bin"); assert.match(w.rgCalls[0].env.TMPDIR, /^\/rt\//);
2208
2303
  });
2209
2304
 
2305
+ it("a green-red repro records repro_quality in the trajectory; reproQuality off skips the check (#5446)", async () => {
2306
+ const w = rworld([RED_GREEN]);
2307
+ assert.equal((await run(w)).terminalReason, "merged");
2308
+ assert.ok(traj(w)[0].includes("repro_quality: "), "quality decision recorded");
2309
+ const o = rworld([RED_GREEN]);
2310
+ assert.equal((await run(o, { reproQuality: "off" })).terminalReason, "merged");
2311
+ assert.ok(!traj(o)[0].includes("repro_quality: "));
2312
+ });
2313
+
2210
2314
  it("a non-testable bug records repro_test none with a reason and is not blocked; a missing repro_test gets the one contract correction", async () => {
2211
2315
  const none = { ...CONTRACT, repro_test: "none", repro_test_reason: "spec-only change, nothing executable" };
2212
2316
  const w = rworld([RED_GREEN], { contract: none });
@@ -2222,7 +2326,7 @@ describe("bug lanes freeze a red-green repro_test (#4271)", () => {
2222
2326
  it("lean.repro_test off, or a lane that is not a bug, keeps today's prompts, contract check and precheck unchanged", async () => {
2223
2327
  const plain = world(); await run(plain);
2224
2328
  for (const [o, extra] of [[{}, { reproTest: "off" }], [{ labels: [{ name: "feature" }] }, {}]]) {
2225
- const w = rworld([{ base: "RAN", head: "RAN" }], { contract: CONTRACT, ...o });
2329
+ const w = rworld([{ base: "RAN", head: "RAN" }], { contract: OUTER_CONTRACT, ...o });
2226
2330
  assert.equal((await run(w, extra)).terminalReason, "merged");
2227
2331
  assert.equal(builders(w)[0][4], builders(plain)[0][4], "plan prompt unchanged"); assert.equal(builders(w)[1][4], builders(plain)[1][4]);
2228
2332
  assert.equal(builders(w).length, 2, "no contract correction for a missing repro_test"); assert.equal(w.rgCalls.length, 0);
@@ -2430,6 +2534,7 @@ describe("comment templates", () => {
2430
2534
  const m = renderTrajectory(base);
2431
2535
  assert.match(m, /^## Pipeline Trajectory — #9\n\n\| Phase \| Result \| Notes \|/);
2432
2536
  for (const row of ["| Validate | CONFIRMED | 2 evidence item(s) |", "| Review | PASS | 1 round |", "| PR | #5 | opened |", "| Merge | all | merged at abc |", "| Close | issue closed (completed) | label workflow:merged |", "- d1", "- none", "_cost $1_"]) assert.ok(m.includes(row), row);
2537
+ assert.match(renderTrajectory({ ...base, tests: { declared: 3, ran: 2, redGreen: 1, skipped: [{ id: "V2", reason: "validate_env" }] } }), /\| Tests \| 3 declared, 2 ran, 1 red→green, 1 skipped\(validate_env\) \|/);
2433
2538
  const nh = renderTrajectory({ issue: 9, validate: "CONFIRMED", anomalies: ["needs-human: Review FAIL twice"], close: ["left open", "label needs-human"] });
2434
2539
  assert.match(nh, /\| Implement \| not reached \| - \|/);
2435
2540
  assert.match(nh, /\*\*Anomalies\*\*\n- needs-human: Review FAIL twice/);
@@ -2507,9 +2612,9 @@ describe("comment templates", () => {
2507
2612
 
2508
2613
  it("plan and implement prompts carry the stage templates and the contract schema within budget", () => {
2509
2614
  const plan = builderPlanPrompt(7), impl = builderImplementPrompt();
2510
- assert.ok(approxTokens(plan) <= 2325, `plan prompt is ${approxTokens(plan)} tokens`); // 2075: #5284 (prod_parity plan line); 2050: #4769 (activation-row rule); 2000: #4730 (owner-step remainder); 1950: #4724 (deferred-row bucket rule) // 2325: #5333 (git stash rule + stage stamp line)
2615
+ assert.ok(approxTokens(plan) <= 2500, `plan prompt is ${approxTokens(plan)} tokens`); // 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)
2511
2616
  assert.ok(approxTokens(impl) <= 1850, `implement prompt is ${approxTokens(impl)} of 1700 tokens`); // 1650: #4726 e2e rule; 1550: #4596 i18n translate rule // 1850: #5333 (git stash rule + stage stamp)
2512
- for (const h of ["### What Was Claimed", "### What We Found", "### Root Cause", "### Affected Files", "### Sibling Sweep", "### History", "### Recommendation", "### Related Issues",
2617
+ for (const h of ["### What Was Claimed", "### What We Found", "### Root Cause", "### Affected Files", "### Sibling Sweep", "### History", "### Recommendation", "### Related Issues", "### Test plan",
2513
2618
  "investigation.md", "contract.json", "PLANNING ONLY", '"requirements"', '"deliverables"', '"preserve"', '"validate"', "verbatim", "defer", "post-deploy"]) assert.ok(plan.includes(h), h);
2514
2619
  for (const h of ["### Approach", "### Changes", "### Acceptance Criteria Status", "### Verification", "### Notes", "implementation.md", "result.json",
2515
2620
  "add-deliverable", "add-requirement", '"validation"', "Never report a deliver requirement"]) assert.ok(impl.includes(h), h);
@@ -4756,6 +4861,18 @@ describe("batch robustness (#4112-#4115)", () => {
4756
4861
  assert.match(text, /conformance\.guard_broken.{0,400}?guard\\":\\"#9\\"/, "precheck reports #9 as guard_broken");
4757
4862
  assert.doesNotMatch(text, /conformance\.guard_broken.{0,400}?guard\\":\\"#4785\\"/, "precheck does not report the superseded #4785");
4758
4863
  });
4864
+ it("#5436 the review starts beside guard+precheck: a green gate adopts it once, a red guard resumes the builder and the review is not applied", async () => {
4865
+ const green = world({ prList: [] });
4866
+ assert.equal((await run(green)).terminalReason, "merged");
4867
+ assert.equal(reviewers(green).length, 1, "one reviewer session, started early and adopted");
4868
+ const mkGuard = (issue) => ({ v: 1, issue, pr: issue * 10, merge_sha: "abc1234", tests: [{ path: "src/foo.js", ids: [] }], hunks: [], why: `guard ${issue}` });
4869
+ const dir = tmpDir("guard-overlap-");
4870
+ const w = world({ prList: [], baseFiles: { ":src/foo.js": "old" } });
4871
+ w.io.runCommand = async (a) => ({ rc: String(a?.cwd).includes("guardbase-") ? 0 : 1, output: "guard test failed" });
4872
+ await run(w, { dir, worktreeRoot: dir, loadGuards: async () => [mkGuard(9)] });
4873
+ assert.ok(builders(w).length >= 2, "a failing guard still resumes the builder");
4874
+
4875
+ });
4759
4876
  it("#4899 amendment state round-trips; precheck still enforces a guard that was not superseded", () => {
4760
4877
  const am = [{ kind: "supersedes", guard: "#1", why: "w" }];
4761
4878
  assert.deepEqual(parseAmendmentsComment(renderAmendments([{ kind: "supersedes", target: "#1", why: "w" }], {}, { contract: "abc", amendments: am })), { contract: "abc", amendments: am });
@@ -5162,7 +5279,7 @@ describe("verify-by-CI (#4167): ci mode runs the heavy checks on CI and feeds fa
5162
5279
  assert.equal(readVerify(d), undefined);
5163
5280
  writeFileSync(`${d}/forge.yaml`, "verify:\n mode: ci\n workflow: verify.yml\n skip_paths: \"*.md,docs/**\"\n max_rounds: 3\n precheck_timeout_seconds: 60\n e2e_label: full-ci\n e2e_checks: \"e2e (1),e2e (2)\"\n");
5164
5281
  const e2e = { mode: "auto", label: "full-ci", workflow: null, pathsInput: null, checks: ["e2e (1)", "e2e (2)"], paths: ["e2e/**", "**/e2e/**", "*.e2e.*", "*.e2e-spec.*", "cypress/**", "playwright/**"], blocking: "changed" };
5165
- assert.deepEqual(readVerify(d), { mode: "ci", workflow: "verify.yml", pathsInput: null, skipPaths: ["*.md", "docs/**"], maxRounds: 3, precheckTimeoutSeconds: 60, precheckTotalSeconds: 600, checkRun: false, checks: null, postMerge: null, flaky: [], duplicateExports: true, invariants: [], e2e });
5282
+ assert.deepEqual(readVerify(d), { mode: "ci", workflow: "verify.yml", pathsInput: null, skipPaths: ["*.md", "docs/**"], maxRounds: 3, precheckTimeoutSeconds: 60, precheckTotalSeconds: 600, checkRun: false, checks: null, postMerge: null, flaky: [], duplicateExports: true, enumeratingMechanical: true, invariants: [], e2e });
5166
5283
  });
5167
5284
 
5168
5285
  describe("#4387 a no-commit CI fix round reruns the failed jobs once", () => {
@@ -5535,7 +5652,7 @@ describe("shared dependency cache wiring (#4220)", () => {
5535
5652
  return d;
5536
5653
  };
5537
5654
 
5538
- it("#4220 prepare runs once with the lane worktree after it exists and before the first runner call; DEPS_PREPARED is logged", async () => {
5655
+ it("#4220 prepare runs once with the lane worktree after it exists (#5434: it overlaps the plan session); DEPS_PREPARED is logged", async () => {
5539
5656
  const dir = tmpDir("deps-");
5540
5657
  const w = world(); w.io.runTmp = { prune: async () => {}, make: async (i, id) => `/home/x/.forge/tmp/runs/${id}`, remove: async () => {} };
5541
5658
  const d = depsIo(w);
@@ -5544,7 +5661,6 @@ describe("shared dependency cache wiring (#4220)", () => {
5544
5661
  assert.equal(d.calls[0].wt, "/wt/lean-7");
5545
5662
  assert.match(d.calls[0].repoKey, /^[A-Za-z0-9._-]+-[0-9a-f]{8}$/);
5546
5663
  assert.equal(d.calls[0].worktreeAdded, true);
5547
- assert.equal(d.calls[0].runnerCallsBefore, 0);
5548
5664
  const ev = readLog(dir, 7).filter((e) => e.event === "DEPS_PREPARED");
5549
5665
  assert.deepEqual(ev.map((e) => [e.status, e.eco, e.key]), [["hit", "pnpm", "0123456789abcdef"]]);
5550
5666
  assert.ok(w.envs.length >= 2);
@@ -5556,6 +5672,35 @@ describe("shared dependency cache wiring (#4220)", () => {
5556
5672
  }
5557
5673
  });
5558
5674
 
5675
+
5676
+ it("#5434 the plan session starts while deps install runs; implement waits for the install and logs the setup timings", async () => {
5677
+ const dir = tmpDir("deps-overlap-");
5678
+ const w = world(); depsIo(w);
5679
+ let release, done = false, atPlan = null, atImplement = null, n = 0;
5680
+ const gate = new Promise((r) => { release = r; });
5681
+ w.io.deps.prepare = async () => { await gate; done = true; return [{ status: "hit", eco: "pnpm", key: "k", ms: 5, reason: null }]; };
5682
+ const inner = w.io.runner;
5683
+ w.io.runner = async (c) => { n++; if (n === 1) { atPlan = done; c.onSpawn?.({ pid: 4242 }); release(); } else if (n === 2) atImplement = done; return inner(c); };
5684
+ assert.equal((await run(w, { dir })).terminalReason, "merged");
5685
+ assert.equal(atPlan, false, "the plan session did not wait for the install");
5686
+ assert.equal(atImplement, true, "implement waited for it");
5687
+ const log = readLog(dir, 7);
5688
+ assert.ok(log.some((e) => e.event === "LANE_SETUP_TIMING" && e.step === "deps"));
5689
+ assert.equal(log.filter((e) => e.event === "FIRST_SESSION").length, 1);
5690
+ const steps = log.filter((e) => e.event === "LANE_SETUP_TIMING").map((e) => e.step);
5691
+ for (const st of ["prompt_assembly", "cli_init"]) assert.ok(steps.includes(st), `${st} timed`);
5692
+ });
5693
+
5694
+ it("#5434 a failed env.setup still ends needs-human and no implement session starts", async () => {
5695
+ const dir = tmpDir("deps-setupfail-");
5696
+ const w = world(); depsIo(w);
5697
+ w.io.runSetup = async () => ({ exit: 3, stdout: "", stderr: "nope" });
5698
+ const r = await run(w, { dir, envSetup: "false" });
5699
+ assert.notEqual(r.terminalReason, "merged");
5700
+ assert.ok(w.calls.filter((c) => c[0] === "runner").length <= 1, "only the plan session ran");
5701
+ assert.equal(r.code, OUTCOME_CODES.ENV_SETUP_FAILED);
5702
+ });
5703
+
5559
5704
  it("#4220 a prepare that throws or fails, or an env() that throws, never changes the outcome; no io.deps is the old behaviour", async () => {
5560
5705
  for (const o of [{ prepareThrows: true }, { results: [{ status: "failed", eco: "uv", key: "k", ms: 5, reason: "install failed" }] }, { envThrows: true }]) {
5561
5706
  const dir = tmpDir("deps-f-");
@@ -5715,6 +5860,23 @@ describe("local-mode CI fix rounds at merge and declared pre-PR check commands (
5715
5860
  assert.ok(n >= 2, "the invariant is rerun after the builder fix round");
5716
5861
  });
5717
5862
 
5863
+ it("#5448 a declared baseline runs when a shared path changes and a failing one blocks the merge", async () => {
5864
+ const mk = (rc) => { const w = world({ changed: ["shared/content/a.js", "src/foo.js", "test/foo.test.js"] }); w.ran = []; const f = w.io.runCommand; w.io.runCommand = async (a) => { w.ran.push(a.command); return a.command === "make stealth-baseline" ? { rc, output: "stealth drift" } : f ? f(a) : { rc: 0, output: "" }; }; return w; };
5865
+ const b = [{ when: "shared/content/**", run: "make stealth-baseline" }];
5866
+ const ok = mk(0); await run(ok, { verify: { baselines: b } });
5867
+ assert.ok(ok.ran.includes("make stealth-baseline"), "baseline ran for the shared change");
5868
+ const none = world(); none.ran = []; none.io.runCommand = async (a) => { none.ran.push(a.command); return { rc: 0, output: "" }; };
5869
+ await run(none, { verify: { baselines: b } });
5870
+ assert.ok(!none.ran.includes("make stealth-baseline"), "unrelated change runs no baseline");
5871
+ const bad = mk(1); const r = await run(bad, { verify: { baselines: b } });
5872
+ assert.equal(bad.merges.length, 0); assert.notEqual(r.terminalReason, "merged");
5873
+ });
5874
+
5875
+ it("#5448 contract.regression is folded into validate as G# entries at freeze", () => {
5876
+ const c = foldRegression({ ...CONTRACT, regression: [{ id: "G1", command: "node --test test/bar.test.js", covers: "bar caller" }, { id: "G2", command: "node --test test/foo.test.js" }] });
5877
+ assert.deepEqual(c.validate.map((v) => v.id), ["V1", "G1"], "G2 duplicates an existing validate command");
5878
+ });
5879
+
5718
5880
  it("#5239 a guard failing only on the lane tree blocks the merge (ci.red), never merges", async () => {
5719
5881
  const w = world(); const ran = [];
5720
5882
  w.io.runCommand = async ({ command, cwd }) => { ran.push(cwd); return /basered-/.test(cwd) ? { rc: 0, output: "" } : { rc: 1, output: "bare 429 at app/routers/listing_feeds.py" }; };
@@ -5965,7 +6127,7 @@ describe("toolchain pins and env.setup at lane setup (#4163)", () => {
5965
6127
  assert.equal(r.terminalReason, "needs-human");
5966
6128
  assert.equal(r.code, OUTCOME_CODES.ENV_SETUP_FAILED);
5967
6129
  assert.equal(OUTCOME_CODES.ENV_SETUP_FAILED, "env.setup_failed");
5968
- assert.equal(builders(w).length, 0, "the builder never runs");
6130
+ assert.ok(builders(w).length <= 1, "only the read-only plan session ran, never implement (#5434)");
5969
6131
  assert.equal(w.prs.length, 0);
5970
6132
  const nh = w.comments.find((c) => c.includes("FORGE:NEEDS_HUMAN"));
5971
6133
  assert.match(nh, /Environment error \(not a build failure\)/); assert.match(nh, /role app_user does not exist/);
@@ -6467,6 +6629,14 @@ describe("enumerating tests + sequence numbers at hand-off (#4322)", () => {
6467
6629
  assert.doesNotMatch(fix[0].prompt, /## Diff/);
6468
6630
  });
6469
6631
 
6632
+ it("#5480 enumeratingMechanical false (forge.yaml lean.enumerating.mechanical) skips the engine edit and leaves it to a session", async () => {
6633
+ const w = hworld({ missing: [MISS, []] }); w.mech = [];
6634
+ w.io.mechFix = { applyEnumerating: async ({ missing }) => { w.mech.push("enum"); return { applied: missing, remaining: [] }; }, renameDuplicates: async () => ({ applied: [], remaining: [] }) };
6635
+ assert.equal((await run(w, { verify: { enumeratingMechanical: false } })).terminalReason, "merged");
6636
+ assert.deepEqual(w.mech, []);
6637
+ assert.equal(builders(w).length, 3, "plan, build and one narrow session");
6638
+ });
6639
+
6470
6640
  it("#4596 English copies in a locale catalog resume the builder once to translate; a leftover is an anomaly", async () => {
6471
6641
  const w = hworld(); const c = [[{ path: "messages/ta.json", key: "calendarView.day", value: "Day view", source: "messages/en.json" }], []]; w.cpCalls = 0;
6472
6642
  w.io.englishCopies = async (x) => { w.cpCalls++; w.cpArgs = x; return c.length > 1 ? c.shift() : c[0]; };
@@ -7643,13 +7813,19 @@ describe("#4395 lane profile", () => {
7643
7813
  assert.equal((await makeLeanRunner({ runCli: async () => ({ text: "" }) })({ role: "builder", issue: 7, cwd: dir, resume: null, system: "", prompt: "go" })).tools, null);
7644
7814
  });
7645
7815
 
7816
+ it("#5432 plan and prefilter prompts treat an existing equivalent as a duplicate (INVALID), a deprecation as evidence against an alias", async () => {
7817
+ const { PREFILTER_SYSTEM } = await import("./prompts.mjs");
7818
+ assert.match(builderPlanPrompt(7), /A feature already reachable \(another name, or a stdlib or wrapped dependency function\) is a duplicate: INVALID, naming the equivalent and its path; its deprecation counts against an alias/);
7819
+ assert.match(PREFILTER_SYSTEM, /already reachable under another name, or from the stdlib or a dependency[^\n]*answer INVALID and name the equivalent and its path; a deprecation of it counts against a new alias/);
7820
+ });
7821
+
7646
7822
  it("#4410 both builder prompts ask for same-turn read-only calls and read-once notes (within budget)", () => {
7647
7823
  for (const p of [builderPlanPrompt(7), builderImplementPrompt(), builderImplementPrompt("ci")]) {
7648
7824
  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/);
7649
7825
  assert.match(p, /Read each file's ranges once .* and keep notes; don't re-read it\./);
7650
7826
  }
7651
7827
  assert.ok(approxTokens(builderImplementPrompt()) <= 1850, `implement prompt is ${approxTokens(builderImplementPrompt())} of 1700 tokens`);
7652
- assert.ok(approxTokens(builderPlanPrompt(7)) <= 2325, `plan prompt is ${approxTokens(builderPlanPrompt(7))} of 2125 tokens`);
7828
+ assert.ok(approxTokens(builderPlanPrompt(7)) <= 2500, `plan prompt is ${approxTokens(builderPlanPrompt(7))} of 2125 tokens`);
7653
7829
  });
7654
7830
 
7655
7831
  it("runCliBackendAsync reports the first stream turn's context as baselineTokens; makeLeanRunner drops it on resume", async () => {
@@ -7671,9 +7847,9 @@ describe("#4395 lane profile", () => {
7671
7847
  describe("#4450 light lane: one builder session, derived contract, upgrade to the full lane", () => {
7672
7848
  const RT = { path: "test/foo.test.js", id: "foo handles null", command: "node --test test/foo.test.js" };
7673
7849
  const BODY = "foo crashes on null input in src/foo.js.\n\nExpected behaviour: foo returns null.\n\n- foo must handle a null argument without throwing.\n- Existing callers of foo keep working.";
7674
- const RESULT = { status: "fixed", summary: "fixed foo", requirement: "foo must handle a null argument without throwing.", repro_test: RT, tests: [{ command: RT.command, result: "pass", fails_without_fix: true }] };
7850
+ const RESULT = { status: "fixed", summary: "fixed foo", requirement: "foo must handle a null argument without throwing.", repro_test: RT, test_plan: TEST_PLAN, tests: [{ command: RT.command, result: "pass", fails_without_fix: true }] };
7675
7851
  const lworld = (o = {}) => {
7676
- const w = world({ labels: [{ name: "bug" }], body: BODY, result: RESULT, contract: { ...CONTRACT, repro_test: RT }, ...o });
7852
+ const w = world({ labels: [{ name: "bug" }], body: BODY, result: RESULT, contract: { ...CONTRACT, test_plan: TEST_PLAN, repro_test: RT }, ...o });
7677
7853
  w.numstat = o.numstat ?? "5\t1\tsrc/foo.js\n20\t0\ttest/foo.test.js\n";
7678
7854
  w.rgCalls = []; w.ran = [];
7679
7855
  w.io.redGreen = async (x) => { w.rgCalls.push(x.command); return o.repro ?? { base: "FAILED", head: "RAN" }; };
@@ -7682,7 +7858,7 @@ describe("#4450 light lane: one builder session, derived contract, upgrade to th
7682
7858
  return w;
7683
7859
  };
7684
7860
  const events = (dir, name) => readLog(dir, 7).filter((e) => e.event === name);
7685
- const ON = { light: { mode: "on" } };
7861
+ const ON = { light: { mode: "on", source: "text" } };
7686
7862
 
7687
7863
  it("nothing triggers: exactly one builder session (no plan) plus the review; the derived contract is frozen and posted", async () => {
7688
7864
  const w = lworld(), dir = tmpDir("light-");
@@ -8150,3 +8326,244 @@ describe("#5347 lane: the build opens with its independent reads in one turn", (
8150
8326
  assert.match(buildOpeningNote({ paths: ["src/a.js"], packFiles: pack.files }), /Context pack files \(touched by earlier PRs on these symbols\): src\/b\.js/);
8151
8327
  });
8152
8328
  });
8329
+
8330
+ describe("#5426 investigation decides pipeline depth (lean.light.source: investigation)", () => {
8331
+ const BODY = "foo crashes when it gets a null argument.\n\n- foo must handle a null argument without throwing.\n- Existing callers of foo keep working.";
8332
+ const RT = { path: "test/foo.test.js", id: "foo handles null", command: "node --test test/foo.test.js" };
8333
+ const RESULT = { status: "fixed", summary: "fixed foo", requirement: "foo must handle a null argument without throwing.", repro_test: RT, test_plan: TEST_PLAN, tests: [{ command: RT.command, result: "pass", fails_without_fix: true }] };
8334
+ const FF = { light: { mode: "on", source: "investigation" } };
8335
+ const TRIAGE = { files: ["src/foo.js"], size: "S", risk: false, decision_needed: false };
8336
+ const fworld = (o = {}) => {
8337
+ const w = world({ labels: [{ name: "bug" }], body: BODY, result: RESULT, contract: { ...CONTRACT, test_plan: TEST_PLAN, repro_test: RT }, ...o });
8338
+ w.numstat = o.numstat ?? "5\t1\tsrc/foo.js\n20\t0\ttest/foo.test.js\n";
8339
+ w.io.redGreen = async () => o.repro ?? { base: "FAILED", head: "RAN" };
8340
+ w.io.runCommand = async () => ({ rc: 0, output: "" });
8341
+ w.io.apiShape = async () => ({ status: "none", changes: [], unknown: [] });
8342
+ const orig = w.io.runner; // the investigator writes triage.json beside investigation.md
8343
+ w.io.runner = async (c) => {
8344
+ const r = await orig(c);
8345
+ if (c.role === "builder" && /triage\.json/.test(c.prompt) && o.triage !== null) { const p = `${WT}/.forge-lean/triage.json`; w.files[p] = JSON.stringify(o.triage ?? TRIAGE); w.mtimes[p] = Date.now(); }
8346
+ return r;
8347
+ };
8348
+ return w;
8349
+ };
8350
+ const ev = (dir, name) => readLog(dir, 7).filter((e) => e.event === name);
8351
+
8352
+ it("a trivial issue that names no file fast-forwards: investigate, one resumed implement session, gates, merge; skipped stages are named", async () => {
8353
+ const w = fworld(), dir = tmpDir("ff-");
8354
+ const r = await run(w, { dir, ...FF });
8355
+ assert.equal(r.terminalReason, "merged");
8356
+ const b = builders(w);
8357
+ assert.equal(b.length, 2, "investigation plus one implement session, no contract step");
8358
+ assert.match(b[0][4], /PLANNING ONLY/); assert.match(b[0][4], /triage\.json/); assert.ok(!b[0][4].includes('{"requirements":['));
8359
+ assert.equal(b[1][2], "sess-1", "the implement session resumes the investigation session");
8360
+ assert.match(b[1][4], /fast-forwards this issue/); assert.match(b[1][4], /failing regression test first/);
8361
+ assert.equal(ev(dir, "LIGHT_ELIGIBILITY")[0].verdict, "ambiguous", "the text heuristic is only a shadow signal");
8362
+ const e = ev(dir, "FASTFORWARD_ELIGIBILITY")[0];
8363
+ assert.equal(e.verdict, "eligible"); assert.equal(e.light, true); assert.equal(e.shadow, false);
8364
+ assert.equal(ev(dir, "LIGHT_DONE").length, 1);
8365
+ assert.ok(traj(w)[0].includes("Fast-forward: skipped plan, contract freeze, multi-session review"), traj(w)[0]);
8366
+ const lite = w.comments.find((c) => c.includes("<!-- FORGE:LITE -->"));
8367
+ assert.match(lite, /Fast-forward \(investigation decided the depth\)/);
8368
+ assert.ok(w.comments.some((c) => c.includes("<!-- FORGE:INVESTIGATION -->")));
8369
+ });
8370
+
8371
+ it("an invalid verdict closes with evidence after the investigation alone", async () => {
8372
+ const w = fworld({ changed: [], stages: { investigation: "**Verdict**: INVALID\n\n### What We Found\n- src/foo.js:3 already guards null" },
8373
+ result: { status: "invalid", summary: "not a bug", evidence: ["src/foo.js:3 already guards null"], tests: [] } });
8374
+ const r = await run(w, { dir: tmpDir("ff-invalid-"), ...FF });
8375
+ assert.equal(r.terminalReason, "invalid");
8376
+ assert.equal(builders(w).length, 1);
8377
+ assert.match(w.comments.find((c) => c.includes("FORGE:INVESTIGATION")), /Verdict\*\*: INVALID/);
8378
+ });
8379
+
8380
+ it("a risk path in the predicted files goes to the full lane: the contract step resumes the investigation session", async () => {
8381
+ const w = fworld({ triage: { ...TRIAGE, files: ["src/auth/session.js"] } }), dir = tmpDir("ff-risk-");
8382
+ const r = await run(w, { dir, ...FF });
8383
+ assert.equal(r.terminalReason, "merged");
8384
+ assert.equal(ev(dir, "LIGHT_DONE").length, 0);
8385
+ assert.ok(ev(dir, "FASTFORWARD_ELIGIBILITY")[0].reasons.some((x) => x.code === "risk_path"));
8386
+ const b = builders(w);
8387
+ assert.ok(b.length >= 3, "investigation, contract step, implement");
8388
+ assert.equal(b[1][2], "sess-1"); assert.match(b[1][4], /\{"requirements":\[/); assert.match(b[1][4], /PLANNING ONLY/);
8389
+ assert.equal(w.comments.filter((c) => c.includes("<!-- FORGE:CONTRACT -->")).length, 1);
8390
+ });
8391
+
8392
+ it("a gate failing after the fast-forward upgrades to the full lane (existing #4450 safety net)", async () => {
8393
+ const w = fworld({ repro: { base: "PASSED", head: "RAN" } }), dir = tmpDir("ff-up-");
8394
+ await run(w, { dir, ...FF });
8395
+ const up = ev(dir, "LIGHT_UPGRADE");
8396
+ assert.equal(up.length, 1); assert.ok(up[0].reasons.some((x) => x.code === "repro_not_red"));
8397
+ assert.equal(ev(dir, "LIGHT_DONE").length, 0);
8398
+ assert.ok(builders(w).length >= 4, "investigation, implement, then the full lane's plan and implement");
8399
+ });
8400
+
8401
+ it("source investigation in shadow mode keeps the full lane and logs the investigation verdict beside it", async () => {
8402
+ const w = fworld({ triage: null }), dir = tmpDir("ff-shadow-");
8403
+ const r = await run(w, { dir, light: { mode: "shadow", source: "investigation" } });
8404
+ assert.equal(r.terminalReason, "merged");
8405
+ assert.ok(builders(w).every((x) => !/triage\.json/.test(x[4])), "no investigation-only call");
8406
+ const e = ev(dir, "FASTFORWARD_ELIGIBILITY");
8407
+ assert.equal(e.length, 1); assert.equal(e[0].shadow, true);
8408
+ assert.equal(ev(dir, "LIGHT_DONE").length, 0);
8409
+ });
8410
+
8411
+ it("source: text (the kill-switch) is unchanged: no fast-forward event, no investigation-only call", async () => {
8412
+ const w = fworld(), dir = tmpDir("ff-text-");
8413
+ await run(w, { dir, light: { mode: "on", source: "text" } });
8414
+ assert.equal(ev(dir, "FASTFORWARD_ELIGIBILITY").length, 0);
8415
+ assert.ok(builders(w).every((x) => !/triage\.json/.test(x[4])));
8416
+ });
8417
+ });
8418
+
8419
+ import { diskLow as diskLowAdmission, nearCeiling as nearCeilingDisk } from "./admission.mjs";
8420
+ describe("admission disk ceiling (#5421)", () => {
8421
+ const host = (mb) => ({ memAvailableMb: () => 99999, freeMb: async () => mb, hygienePaths: () => ["/wt", "/forge"] });
8422
+ it("disk below hygiene.min_free_gb is near the ceiling; the injected host probe decides", async () => {
8423
+ assert.equal(await nearCeilingDisk({ host: host(2000), minFreeGb: 5 }), true);
8424
+ assert.equal(await nearCeilingDisk({ host: host(20000), minFreeGb: 5 }), false);
8425
+ assert.equal((await diskLowAdmission({ host: host(2000), minFreeGb: 5 })).reasons.length, 2);
8426
+ });
8427
+ });
8428
+
8429
+ describe("test plan rendered in the FORGE:CONTRACT comment (#5445)", () => {
8430
+ it("renderContract carries a Test plan table; reproPlanNote asks for test_plan", () => {
8431
+ const plan = [{ requirement: "R1", proof: "listing returns 200 not 403", level: "integration", repro: "no-repro", reason: "needs live site", regression: ["a", "b"], env: ["http"], command: "node --test x" }];
8432
+ const body = renderContract({ ...CONTRACT, test_plan: plan }, "abc123abc123");
8433
+ assert.match(body, /### Test plan\n\| Requirement \| Proof/);
8434
+ assert.match(body, /\| R1 \| listing returns 200 not 403 \| integration \| no-repro: needs live site \| a; b \| http \| `node --test x` \|/);
8435
+ assert.ok(!renderContract(CONTRACT, "abc123abc123").includes("### Test plan"));
8436
+ assert.match(reproPlanNote(true), /"test_plan":/);
8437
+ });
8438
+ });
8439
+
8440
+ describe("#5437 post-run bookkeeping", () => {
8441
+ const names = (dir) => readLog(dir, 7).map((x) => x.event);
8442
+ it("a merged lane reports RUN_TERMINAL before its branch delete, ledger clear and post-run jobs, and records each job", async () => {
8443
+ const dir = tmpDir("postrun-merge-");
8444
+ const w = world();
8445
+ const r = await run(w, { dir });
8446
+ assert.equal(r.terminalReason, "merged");
8447
+ const ev = names(dir), term = ev.indexOf("RUN_TERMINAL");
8448
+ assert.ok(term >= 0);
8449
+ for (const e of ["BRANCH_DELETED", "LEDGER_CLEARED"]) if (ev.includes(e)) assert.ok(ev.indexOf(e) > term, `${e} after RUN_TERMINAL`);
8450
+ const ok = readLog(dir, 7).filter((x) => x.event === "POSTRUN_OK").map((x) => x.job);
8451
+ for (const j of ["branch-delete", "trajectory", "teardown"]) assert.ok(ok.includes(j), `${j} recorded`);
8452
+ assert.ok(ev.indexOf("POSTRUN_OK") > term);
8453
+ assert.ok(!ev.includes("POSTRUN_FAILED"));
8454
+ });
8455
+ it("deferPostRun hands the jobs to the caller: nothing ran before postRun(), everything after", async () => {
8456
+ const dir = tmpDir("postrun-defer-");
8457
+ const w = world();
8458
+ const r = await run(w, { dir, deferPostRun: true });
8459
+ assert.equal(r.terminalReason, "merged");
8460
+ assert.equal(typeof r.postRun, "function");
8461
+ assert.ok(!names(dir).includes("POSTRUN_OK"), "no job before the caller runs them");
8462
+ assert.equal(traj(w).length, 0, "trajectory is a post-run job");
8463
+ await r.postRun();
8464
+ assert.ok(names(dir).includes("POSTRUN_OK"));
8465
+ assert.equal(traj(w).length, 1);
8466
+ });
8467
+ it("builder commits are signed when made: a commit-msg hook chains the repo's hooks and rides the lane env (R6)", async () => {
8468
+ const dir = tmpDir("postrun-signoff-");
8469
+ const w = world();
8470
+ w.io.runTmp = { prune: async () => {}, make: async (_i, id) => `/rt/${id}`, remove: async () => true };
8471
+ w.io.fs.list = async () => ["pre-commit", "commit-msg", "applypatch-msg.sample"];
8472
+ const base = w.io.runCommand; w.io.runCommand = async (a) => (/^chmod /.test(a.command) ? { r: { exit: 0 } } : base ? base(a) : { rc: 0, output: "" });
8473
+ await run(w, { dir });
8474
+ const hook = Object.entries(w.files).filter(([p]) => /\/hooks\//.test(p));
8475
+ assert.ok(hook.some(([p, t]) => /commit-msg$/.test(p) && /Signed-off-by/.test(t) && /exec '.*\/commit-msg'/.test(t)), "commit-msg signs and chains the repo's own");
8476
+ assert.ok(hook.some(([p, t]) => /pre-commit$/.test(p) && /exec /.test(t)), "other hooks are forwarded");
8477
+ assert.ok(!hook.some(([p]) => /\.sample$/.test(p)));
8478
+ assert.ok(names(dir).includes("SIGNOFF_HOOK"));
8479
+ });
8480
+ it("an unmerged lane keeps its teardown inline and has no postRun", async () => {
8481
+ const w = world({ changed: [], result: { status: "invalid", summary: "x", evidence: ["a:1"], tests: [] } });
8482
+ const r = await run(w, { deferPostRun: true });
8483
+ assert.equal(r.terminalReason, "invalid");
8484
+ assert.equal(r.postRun, undefined);
8485
+ assert.equal(traj(w).length, 1);
8486
+ });
8487
+ it("an invalid verdict closes the issue and labels it in parallel", async () => {
8488
+ const w = world({ changed: [], result: { status: "invalid", summary: "x", evidence: ["a:1"], tests: [] } });
8489
+ let labelStarted = false, closeSawLabel = null;
8490
+ const gh = w.io.gh, tl = w.io.transitionLabel;
8491
+ w.io.transitionLabel = async (n, st) => { if (st === "invalid") labelStarted = true; return tl(n, st); };
8492
+ w.io.gh = async (a, o) => { if (a[0] === "issue" && a[1] === "close") { for (let i = 0; i < 30 && !labelStarted; i++) await new Promise((x) => setTimeout(x, 5)); closeSawLabel = labelStarted; } return gh(a, o); };
8493
+ const r = await run(w);
8494
+ assert.equal(r.terminalReason, "invalid");
8495
+ assert.equal(closeSawLabel, true, "the label call started before the close finished");
8496
+ assert.equal(w.closed.length, 1);
8497
+ });
8498
+ });
8499
+
8500
+ import { precheck as precheck5440 } from "./conformance.mjs";
8501
+ describe("#5440 precheck scope: directory deliverable and renumbered migration", () => {
8502
+ const mk = (path) => ({ requirements: [{ id: "R1", quote: "q", disposition: "deliver" }], deliverables: [{ id: "D8", path, change: "regenerate", requirements: ["R1"] }], validate: [] });
8503
+ const res = { requirements: [{ id: "R1", status: "implemented" }], validation: [] };
8504
+ const creep = (contract, changedFiles) => precheck5440({ contract, result: res, changedFiles }).failures.filter((f) => f.kind === "scope_creep");
8505
+ it("directory deliverable without a slash: files beneath it are not scope_creep (#40566 shape); a sibling is", () => {
8506
+ const c = mk("listings/official/travel");
8507
+ assert.equal(creep(c, ["listings/official/travel/agent.md", "listings/official/travel/page.md"]).length, 0);
8508
+ assert.equal(creep(c, ["listings/official/travel2/agent.md"]).length, 1);
8509
+ });
8510
+ it("renumbered migration (0637_* -> 0639_*) stays covered; an unrelated file is still scope_creep", () => {
8511
+ const c = mk("db/migrations/0637_*");
8512
+ assert.equal(creep(c, ["db/migrations/0639_add_x.sql"]).length, 0);
8513
+ assert.equal(creep(c, ["db/migrations/0639_add_x.sql", "src/billing.js"]).length, 1);
8514
+ });
8515
+ });
8516
+
8517
+ /** #5449: the conformance record also carries test_adequacy counts; these assertions pin the older fields. */
8518
+ function noAdq({ test_adequacy: _t, ...c } = {}) { return c; }
8519
+
8520
+ describe("test adequacy gate in the lane (#5449)", () => {
8521
+ const RT = { path: "test/foo.test.js", id: "foo handles null", command: "node --test test/foo.test.js" };
8522
+ const bugWorld = (contract) => {
8523
+ const w = world({ labels: [{ name: "bug" }], contract: { ...CONTRACT, repro_test: RT, test_plan: TEST_PLAN, ...contract } });
8524
+ w.io.redGreen = async () => ({ base: "FAILED", head: "RAN" });
8525
+ return w;
8526
+ };
8527
+
8528
+ it("test adequacy: FORGE:REVIEW renders the table and RUN_TERMINAL carries the telemetry fields", async () => {
8529
+ const w = bugWorld({});
8530
+ const r = await run(w);
8531
+ assert.equal(r.terminalReason, "merged");
8532
+ const review = w.comments.find((c) => c.includes("<!-- FORGE:REVIEW -->"));
8533
+ assert.match(review, /Test adequacy/); assert.match(review, /BASE=FAILED HEAD=RAN/); assert.match(review, /adequate/);
8534
+ const term = w.telemetry.find((x) => x.event === "RUN_TERMINAL");
8535
+ assert.equal(typeof term.tests_declared, "number"); assert.equal(typeof term.tests_ran, "number");
8536
+ assert.equal(term.repro_quality, "red_green");
8537
+ assert.equal(term.first_review === undefined || typeof term.first_review === "object", true, "existing fields keep their shape");
8538
+ });
8539
+
8540
+ it("test adequacy: a weak test (patch-echo repro) gets exactly one builder resume, then is recorded in the table and merges", async () => {
8541
+ const w = bugWorld({ repro_quality: "patch-echo" });
8542
+ const r = await run(w);
8543
+ assert.equal(r.terminalReason, "merged");
8544
+ assert.equal(builders(w).length, 3, "plan, build and one resume to strengthen the test");
8545
+ const review = w.comments.find((c) => c.includes("<!-- FORGE:REVIEW -->"));
8546
+ assert.match(review, /weak \(repro quality patch-echo\)/);
8547
+ });
8548
+ });
8549
+
8550
+ describe("#5469: --adopt takes over a hand-built open PR", () => {
8551
+ it("#5469: adopt without a foreign PR referencing the issue parks needs-human and runs no builder", async () => {
8552
+ const w = world();
8553
+ w.prList = [{ number: 9, headRefName: "feat/issue-7-lean", baseRefName: "staging", body: "Fixes #7", closingIssuesReferences: [{ number: 7 }] }, { number: 10, headRefName: "hand/other", baseRefName: "staging", body: "Fixes #70", closingIssuesReferences: [{ number: 70 }] }];
8554
+ const r = await run(w, { adopt: true });
8555
+ assert.notEqual(r.terminalReason, "merged");
8556
+ assert.equal(builders(w).length, 0);
8557
+ assert.ok(w.comments.some((c) => /--adopt: no open PR to `staging` references #7/.test(c)), "the park comment says why");
8558
+ });
8559
+
8560
+ it("#5469: adopt of a hand-made PR reviews it on its own branch and runs no builder", async () => {
8561
+ const w = world();
8562
+ w.prList = [{ number: 55, headRefName: "hand/fix-7", baseRefName: "staging", body: "Fixes #7", closingIssuesReferences: [{ number: 7 }] }];
8563
+ const r = await run(w, { adopt: true });
8564
+ assert.equal(builders(w).length, 0, "no rebuild");
8565
+ assert.ok(reviewers(w).length >= 1, "the PR is reviewed");
8566
+ assert.ok(w.calls.some((c) => c[0] === "git" && JSON.stringify(c).includes("hand/fix-7")), "its head branch is the lane branch");
8567
+ assert.equal(r.terminalReason, "merged");
8568
+ });
8569
+ });