forgedock 1.59.2 → 1.60.1

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 (97) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -3
  2. package/bin/engine-cli.mjs +50 -10
  3. package/bin/labels.json +5 -0
  4. package/bin/lean/batch.mjs +21 -2
  5. package/bin/lean/batch.test.mjs +116 -1
  6. package/bin/lean/conformance.mjs +19 -6
  7. package/bin/lean/conformance.test.mjs +37 -3
  8. package/bin/lean/depcache.mjs +34 -15
  9. package/bin/lean/depcache.test.mjs +100 -1
  10. package/bin/lean/design-gate.mjs +15 -10
  11. package/bin/lean/design-gate.test.mjs +21 -0
  12. package/bin/lean/effects.mjs +18 -2
  13. package/bin/lean/execution.mjs +23 -5
  14. package/bin/lean/execution.test.mjs +81 -1
  15. package/bin/lean/gatewatch.test.mjs +5 -5
  16. package/bin/lean/issuewatch-triage.mjs +68 -0
  17. package/bin/lean/issuewatch-triage.test.mjs +98 -0
  18. package/bin/lean/issuewatch.mjs +34 -6
  19. package/bin/lean/issuewatch.test.mjs +11 -0
  20. package/bin/lean/lanelock.mjs +5 -4
  21. package/bin/lean/lean.mjs +144 -21
  22. package/bin/lean/lean.test.mjs +180 -6
  23. package/bin/lean/orchestrate-cancel.test.mjs +33 -0
  24. package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
  25. package/bin/lean/orchestrate-recovering.test.mjs +42 -0
  26. package/bin/lean/orchestrate.mjs +23 -10
  27. package/bin/lean/pagegate.mjs +50 -12
  28. package/bin/lean/pagegate.test.mjs +38 -1
  29. package/bin/lean/phaseledger.mjs +65 -2
  30. package/bin/lean/phaseledger.test.mjs +70 -2
  31. package/bin/lean/preflight.mjs +67 -3
  32. package/bin/lean/preflight.test.mjs +37 -1
  33. package/bin/lean/prompts.mjs +2 -1
  34. package/bin/lean/recovery.test.mjs +11 -6
  35. package/bin/lean/release-classify.mjs +143 -0
  36. package/bin/lean/release-classify.test.mjs +130 -0
  37. package/bin/lean/release-conductor.mjs +163 -0
  38. package/bin/lean/release-conductor.test.mjs +194 -0
  39. package/bin/lean/release-config.mjs +60 -8
  40. package/bin/lean/release-config.test.mjs +43 -1
  41. package/bin/lean/release-control.mjs +22 -5
  42. package/bin/lean/release-control.test.mjs +22 -0
  43. package/bin/lean/release-credentials.mjs +40 -0
  44. package/bin/lean/release-credentials.test.mjs +42 -0
  45. package/bin/lean/release-deploy.mjs +3 -3
  46. package/bin/lean/release-deploy.test.mjs +8 -0
  47. package/bin/lean/release-docs.test.mjs +93 -0
  48. package/bin/lean/release-fence.mjs +2 -0
  49. package/bin/lean/release-gate.mjs +88 -0
  50. package/bin/lean/release-gate.test.mjs +116 -0
  51. package/bin/lean/release-gates.mjs +5 -1
  52. package/bin/lean/release-ledger.mjs +47 -1
  53. package/bin/lean/release-ledger.test.mjs +33 -1
  54. package/bin/lean/release-mergeback.mjs +148 -0
  55. package/bin/lean/release-mergeback.test.mjs +129 -0
  56. package/bin/lean/release-p0.mjs +193 -0
  57. package/bin/lean/release-p0.test.mjs +127 -0
  58. package/bin/lean/release-plan.mjs +267 -0
  59. package/bin/lean/release-plan.test.mjs +202 -0
  60. package/bin/lean/release-preflight.mjs +16 -0
  61. package/bin/lean/release-regate.mjs +141 -0
  62. package/bin/lean/release-regate.test.mjs +149 -0
  63. package/bin/lean/release-review.mjs +5 -3
  64. package/bin/lean/release-rollback.mjs +277 -0
  65. package/bin/lean/release-rollback.test.mjs +245 -0
  66. package/bin/lean/release-snapshot.mjs +48 -9
  67. package/bin/lean/release-snapshot.test.mjs +43 -1
  68. package/bin/lean/release-start.mjs +164 -0
  69. package/bin/lean/release-start.test.mjs +171 -0
  70. package/bin/lean/release-status.mjs +6 -2
  71. package/bin/lean/release-train.mjs +159 -0
  72. package/bin/lean/release-train.test.mjs +139 -0
  73. package/bin/lean/release.mjs +127 -5
  74. package/bin/lean/release.test.mjs +80 -0
  75. package/bin/lean/sandbox-remote.mjs +2 -0
  76. package/bin/lean/schedd-load.test.mjs +82 -0
  77. package/bin/lean/schedd.mjs +67 -31
  78. package/bin/lean/schedd.test.mjs +80 -1
  79. package/bin/lean/validate-catalog.mjs +110 -0
  80. package/bin/lean/validate-catalog.test.mjs +55 -0
  81. package/bin/pool/agent.mjs +12 -1
  82. package/bin/pool/lane-tools.mjs +146 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/router.mjs +3 -1
  85. package/bin/pool/warm.mjs +14 -3
  86. package/docs/CONFIG.md +225 -1
  87. package/docs/ISSUE-WATCH.md +1 -0
  88. package/docs/design/visual-gate.md +10 -0
  89. package/docs/eval/adversarial-bench.md +1 -0
  90. package/package.json +1 -1
  91. package/pool/README.md +2 -0
  92. package/scripts/acceptance-red-green.sh +5 -2
  93. package/scripts/acceptance-red-green.test.sh +11 -0
  94. package/scripts/bench-adversarial.mjs +4 -0
  95. package/scripts/bench-lightlane.mjs +2 -1
  96. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  97. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -11,7 +11,7 @@ import { normaliseDecision, writeDecisionIndex } from "./decisions.mjs"; // #533
11
11
  import { execFileSync } from "node:child_process";
12
12
  import { writeFileSync, existsSync, readFileSync, mkdirSync, symlinkSync, readdirSync, chmodSync } from "node:fs";
13
13
  import { join } from "node:path";
14
- import { runCore, contractHash, isProtectedLaneBranch, classifyBlock } from "./lean.mjs";
14
+ import { runCore, contractHash, isProtectedLaneBranch, classifyBlock, builderFixable } from "./lean.mjs";
15
15
  import { parseFactsComment, normaliseFacts, renderFactsRecord, FACTS_MARKER } from "./facts.mjs";
16
16
  import { makeLedger } from "./ledger.mjs";
17
17
  import { writeIndex } from "./guards.mjs";
@@ -375,7 +375,7 @@ describe("core work-on", () => {
375
375
  assert.equal(w.prs.length, 1);
376
376
  assert.equal(traj(w).length, 1);
377
377
  assert.match(traj(w)[0], /2 round\(s\)/);
378
- assert.match(traj(w)[0], /Not conforming \(review\): conformance\.unimplemented \(R1 partial: .*\("foo must handle a null argument without throwing\."\)\); builder resumed once/);
378
+ assert.match(traj(w)[0], /Not conforming \(review\): conformance\.unimplemented \(R1 partial: .*\("foo must handle a null argument without throwing\."\)\); builder resumed \(round 1 of 3\)/);
379
379
  assert.equal(w.comments.filter((c) => c.includes("FORGE:IMPLEMENTATION")).length, 1, "one implementation note");
380
380
  assert.equal(w.patches.length, 1, "edited in place after the resume");
381
381
  assert.match(w.patches[0].join(" "), /-X PATCH repos\/o\/r\/issues\/comments\/\d+ -f body=<!-- FORGE:IMPLEMENTATION -->/);
@@ -384,7 +384,7 @@ describe("core work-on", () => {
384
384
 
385
385
  it("nonconforming twice -> needs-human with the specific code, no PR, issue left open", async () => {
386
386
  const w = world({ reviews: [bad(), bad("still bad")] });
387
- const r = await run(w);
387
+ const r = await run(w, { reviewMaxResumes: 1 });
388
388
  assert.equal(r.terminalReason, "needs-human");
389
389
  assert.equal(r.code, "conformance.unimplemented");
390
390
  assert.equal(w.closed.length, 0);
@@ -906,6 +906,45 @@ describe("core work-on", () => {
906
906
  assert.ok(!l.edits.some((e) => e.includes("--add-label") && e.includes("needs-human")), JSON.stringify(l.edits));
907
907
  });
908
908
 
909
+ describe("#5652 in-sandbox recipe install", () => {
910
+ const remote = { placement: { where: "remote", reason: "mode remote" } };
911
+ const withTool = (tool) => ({ ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: `${tool} check x` }] });
912
+ const probing = (w, tool, installed) => { w.io.probeCommand = async (a) => ({ rc: new RegExp(tool).test(JSON.stringify(a)) && !installed() ? 127 : 0, output: "" }); };
913
+ it("a recipe-backed tool is installed in the sandbox and re-probed: the lane continues, no needs-human", async () => {
914
+ const w = world({ contract: withTool("promtool") }); let ok = false; const cmds = [];
915
+ const base = w.io.runCommand;
916
+ w.io.runCommand = async (a) => { if (/promtool/.test(a.command) && /tar -xz/.test(a.command)) { cmds.push(a.command); ok = true; return { rc: 0 }; } return base(a); };
917
+ probing(w, "promtool", () => ok);
918
+ const r = await run(w, { dir: tmpDir("lean-5652a-"), ...remote });
919
+ assert.equal(cmds.length, 1);
920
+ assert.notEqual(r.code, "env.tool_missing");
921
+ assert.notEqual(r.terminalReason, "needs-human");
922
+ });
923
+ it("a tool with no recipe ends the lane naming it, saying no recipe exists and pointing to execution.lane_tools", async () => {
924
+ const w = world({ contract: withTool("zzcheck") }); probing(w, "zzcheck", () => false);
925
+ const r = await run(w, { dir: tmpDir("lean-5652b-"), ...remote });
926
+ assert.equal(r.code, "env.tool_missing");
927
+ const txt = w.comments.map((c) => c.body ?? c).join("\n");
928
+ assert.match(txt, /lacks zzcheck, and no lane_tools recipe exists for it/);
929
+ assert.match(txt, /execution\.lane_tools/);
930
+ });
931
+ it("a failed in-sandbox install ends the lane with the stderr tail", async () => {
932
+ const w = world({ contract: withTool("promtool") }); probing(w, "promtool", () => false);
933
+ const base = w.io.runCommand;
934
+ w.io.runCommand = async (a) => (/tar -xz/.test(a.command) ? { rc: 2, stderr: "curl: (22) 404 not found" } : base(a));
935
+ const r = await run(w, { dir: tmpDir("lean-5652c-"), ...remote });
936
+ assert.equal(r.code, "env.tool_missing");
937
+ assert.match(w.comments.map((c) => c.body ?? c).join("\n"), /Installing promtool in the remote sandbox failed[\s\S]*404 not found/);
938
+ });
939
+ it("regression: a declared host capability still ends env.capability_remote without installing", async () => {
940
+ const w = world({ contract: withTool("promtool") }); let installs = 0; const base = w.io.runCommand;
941
+ w.io.runCommand = async (a) => { if (/tar -xz/.test(a.command)) installs++; return base(a); };
942
+ const r = await run(w, { dir: tmpDir("lean-5652d-"), ...remote, hostCaps: { hostCapabilities: ["promtool"] } });
943
+ assert.equal(r.code, "env.capability_remote");
944
+ assert.equal(installs, 0);
945
+ });
946
+ });
947
+
909
948
  it("#4778 a relayed host capability does not end the remote lane before building; a failed relay still recovers locally", async () => {
910
949
  const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "promtool test rules r.yml" }] };
911
950
  const remote = { placement: { where: "remote", reason: "mode remote" }, hostCaps: { hostCapabilities: ["promtool"] } };
@@ -1275,6 +1314,7 @@ describe("in-batch recovery of mechanical needs-human (#4267)", () => {
1275
1314
  const r = await run(w, { recover: { code: "ci.red", attempt: 1 } });
1276
1315
  assert.equal(r.terminalReason, "merged");
1277
1316
  assert.ok(w.edits.some((e) => e.join(" ") === "issue edit 7 -R o/r --remove-label needs-human"));
1317
+ assert.ok(w.edits.some((e) => e.join(" ") === "issue edit 7 -R o/r --remove-label workflow:recovering"), "#5647: the recovery lane's end clears workflow:recovering");
1278
1318
  const dec = w.comments.find((c) => c.startsWith("<!-- FORGE:DECISION -->"));
1279
1319
  assert.match(dec, /recovery pass for `ci\.red`/); assert.match(dec, /\*\*Why\*\*/); assert.match(dec, /\*\*Alternative\*\*/);
1280
1320
  assert.ok(builders(w).some((b) => /Recovery pass \(ci\.red\): .*--log-failed/.test(b[4])));
@@ -2178,7 +2218,7 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2178
2218
  assert.equal(hotspotBuildRule(facts([], { file_lines: 1000, growth_lines: 50 })).trim(), "Don't grow a file over 1000 lines by more than 50 lines. Put new code next to it.");
2179
2219
  assert.equal(hotspotBuildRule(null), ""); assert.equal(hotspotBuildRule(facts([], { enabled: false })), "");
2180
2220
  const plan = builderPlanPrompt(7) + hotspotPlanNote(facts([HOT, { ...HOT, path: "a/b.py" }, { ...HOT, path: "c/d.py" }]));
2181
- // 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).
2221
+ // 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).
2182
2222
  assert.ok(approxTokens(plan) <= 2650, `plan prompt with hotspots is ${approxTokens(plan)} tokens`);
2183
2223
  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)
2184
2224
  });
@@ -2597,9 +2637,30 @@ describe("comment templates", () => {
2597
2637
  assert.match(renderTrajectory({ issue: 9, validate: ["a|b", "x\ny"] }), /\| Validate \| a\\\|b \| x y \|/);
2598
2638
  });
2599
2639
 
2640
+ it("#5644 review findings get up to 3 builder resume rounds: replay of a fixable finding that clears in round 3 merges", async () => {
2641
+ const w = world({ reviews: [bad("round 1"), bad("round 2"), conf()] });
2642
+ const r = await run(w);
2643
+ assert.equal(r.terminalReason, "merged"); assert.equal(builders(w).length, 4, "build plus two resume rounds");
2644
+ });
2645
+
2646
+ it("#5644 rounds are spent: a changing but never fixed finding ends needs-human after reviewMaxResumes rounds; an unchanged one stops early", async () => {
2647
+ const w = world({ reviews: [bad("a"), bad("b"), bad("c"), bad("d")] });
2648
+ const r = await run(w);
2649
+ assert.equal(r.terminalReason, "needs-human"); assert.equal(builders(w).length, 5);
2650
+ assert.match(traj(w)[0], /after 3 builder resumes/);
2651
+ const w2 = world({ reviews: [bad("a"), bad("b"), bad("c")] });
2652
+ assert.equal((await run(w2, { reviewMaxResumes: 1 })).terminalReason, "needs-human"); assert.equal(builders(w2).length, 3);
2653
+ });
2654
+
2655
+ it("#5644 builderFixable: regression, deferral, scope are fixable; environment and empty sets are not", () => {
2656
+ assert.equal(builderFixable([{ code: "conformance.regression" }, { code: "conformance.unjustified_deferral" }, { code: "conformance.scope_creep" }]), true);
2657
+ assert.equal(builderFixable([{ code: "conformance.regression" }, { code: "env.tool_missing" }]), false);
2658
+ assert.equal(builderFixable([]), false); assert.equal(builderFixable(null), false);
2659
+ });
2660
+
2600
2661
  it("a merged run's trajectory and a needs-human run's trajectory carry the right rows", async () => {
2601
2662
  const w = world({ reviews: [bad(), bad("still bad")] });
2602
- await run(w);
2663
+ await run(w, { reviewMaxResumes: 1 });
2603
2664
  const t = traj(w)[0];
2604
2665
  assert.match(t, /\| Validate \| CONFIRMED \|/);
2605
2666
  assert.match(t, /\| Plan \| contract [0-9a-f]{12} \| 1 requirement\(s\) \|/);
@@ -4729,6 +4790,24 @@ describe("batch robustness (#4112-#4115)", () => {
4729
4790
  assert.ok(w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("node --test --test-reporter=dot test/foo.test.js")));
4730
4791
  });
4731
4792
 
4793
+ it("#5653 a validate command freeze preflight finds unrunnable is rewritten from the CI-derived catalogue before any builder correction", async () => {
4794
+ const d = tmpDir("lean-5653-"); const src = join(d, "ci.yml"); writeFileSync(src, "run: uv run --with-requirements r.txt pytest tests\n");
4795
+ const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "poetry run pytest t.py" }] };
4796
+ const w = world({ contract }); w.io.probeCommand = async (a) => ({ rc: /poetry/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
4797
+ const r = await run(w, { dir: d, validateCatalogSources: [`../..${src}`] });
4798
+ assert.notEqual(r.code, "env.tool_missing");
4799
+ assert.ok(w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("uv run --with-requirements r.txt pytest t.py")));
4800
+ assert.ok(!w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("poetry run pytest")));
4801
+ });
4802
+
4803
+ it("#5653 the plan prompt tells the builder to prefer CI commands, record equivalent substitutes and never narrow time or production criteria", async () => {
4804
+ const { unrunnableValidateNote } = await import("./prompts.mjs");
4805
+ const n = unrunnableValidateNote();
4806
+ assert.match(n, /CI-derived command catalogue/);
4807
+ assert.match(n, /same test ids with the same result is recorded/);
4808
+ assert.match(n, /never narrow it/);
4809
+ });
4810
+
4732
4811
  // ---- #4112 ----
4733
4812
  const fakeCli = async (name, body) => {
4734
4813
  const { writeFileSync, chmodSync } = await import("node:fs");
@@ -5773,6 +5852,12 @@ describe("shared dependency cache wiring (#4220)", () => {
5773
5852
  for (const st of ["prompt_assembly", "cli_init"]) assert.ok(steps.includes(st), `${st} timed`);
5774
5853
  });
5775
5854
 
5855
+ it("#5651 launch, re-place, recovery and gate entries all install through io.deps.prepare (and so depcache's pythonFor)", () => {
5856
+ const src = readFileSync(new URL("./lean.mjs", import.meta.url), "utf8");
5857
+ assert.ok((src.match(/io\.deps\.prepare\(/g) ?? []).length >= 4);
5858
+ assert.ok(!/pythonFor/.test(src), "lean.mjs has no second interpreter-selection path");
5859
+ });
5860
+
5776
5861
  it("#5434 a failed env.setup still ends needs-human and no implement session starts", async () => {
5777
5862
  const dir = tmpDir("deps-setupfail-");
5778
5863
  const w = world(); depsIo(w);
@@ -7090,7 +7175,7 @@ describe("#4362 attempt triggers", () => {
7090
7175
  const builderSites = at(/builder\(\+\+attemptN,/), fixSites = at(/fixRound\("/), attemptSites = at(/attempt\("(?!implement)/);
7091
7176
  assert.ok(builderSites.length >= 9 && fixSites.length >= 9 && attemptSites.length >= 2, "the call sites were found");
7092
7177
  const known = (lit, l, n) => assert.ok(lit && TRIGGERS.includes(lit), `lean.mjs:${n} passes no known trigger: ${l.trim().slice(0, 120)}`);
7093
- const fixLines = at(/async function fixRound\(/)[0][1];
7178
+ const fixLines = at(/async function fixRoundRaw\(/)[0][1];
7094
7179
  for (const [l, n] of builderSites) {
7095
7180
  if (n > fixLines && n < fixLines + 10 && /trigger \}\)/.test(l)) continue; // fixRound forwards its own trigger, checked below
7096
7181
  known(/trigger: "([a-z_]+)"/.exec(l)?.[1], l, n);
@@ -8692,6 +8777,69 @@ describe("design gate routing in the lane (#5330 R11, R13, R15)", () => {
8692
8777
  });
8693
8778
  });
8694
8779
 
8780
+ describe("classification record in the plan prompt (#5557)", () => {
8781
+ it("asks only for the judgment fields and never for units or migrations", () => {
8782
+ const p = builderPlanPrompt(7);
8783
+ assert.match(p, /classification\.json/);
8784
+ assert.doesNotMatch(p.split("classification.json")[1].split("\n")[0], /units|migrations|risk/);
8785
+ });
8786
+ });
8787
+
8788
+ describe("FORGE:CLASSIFY wiring (#5557)", () => {
8789
+ const POLICY = "schema: 1\nbranches: {default: main}\nunits:\n foo: {paths: [\"src/**\"]}\n";
8790
+ const CLS = JSON.stringify({ type: "bug", severity: "P2", exists_in: "unknown", flag: "none", confidence: 0.8, units: ["LLM-LIED"] });
8791
+ const withPolicy = (w) => { const g = w.io.git; w.io.git = async (a, o) => (a[0] === "show" && /\.forge\/release\.yaml$/.test(a.at(-1)) ? POLICY : g(a, o)); };
8792
+ it("posts FORGE:CLASSIFY with code-derived units and namespaced labels when a release policy exists", async () => {
8793
+ const w = world(); withPolicy(w); const rd = w.io.fs.read; w.io.fs.read = async (p) => (p.endsWith("/classification.json") ? CLS : rd(p));
8794
+ await run(w);
8795
+ const c = w.comments.find((x) => x.includes("FORGE:CLASSIFY"));
8796
+ assert.ok(c, "FORGE:CLASSIFY posted");
8797
+ assert.match(c, /"units": \[\s*"foo"\s*\]/); assert.doesNotMatch(c, /LLM-LIED/);
8798
+ assert.ok(w.edits.some((e) => e.includes("unit:foo")) && w.edits.some((e) => e.includes("type:bug")), "namespaced labels added");
8799
+ });
8800
+ it("a live claim without verifiable evidence is downgraded and gets the lane:release label", async () => {
8801
+ const w = world(); withPolicy(w); const rd = w.io.fs.read;
8802
+ w.io.fs.read = async (p) => (p.endsWith("/classification.json") ? JSON.stringify({ type: "bug", severity: "P2", exists_in: "live", flag: "none", confidence: 0.8 }) : rd(p));
8803
+ await run(w);
8804
+ const flat = w.edits.flat().map(String).join(" ");
8805
+ assert.ok(flat.includes("lane:release"), "lane:release label issued");
8806
+ assert.ok(flat.includes("where:unknown") && !flat.includes("where:live"), "downgraded to unknown");
8807
+ });
8808
+ it("issues every label namespace incl. priority:, and an invalid record triggers the correction loop", async () => {
8809
+ const w = world(); withPolicy(w); const rd = w.io.fs.read;
8810
+ w.io.fs.read = async (p) => (p.endsWith("/classification.json") ? JSON.stringify({ type: "bug", severity: "P2", exists_in: "unknown" }) : rd(p));
8811
+ await run(w);
8812
+ const flat = w.edits.flat().map(String).join(" ");
8813
+ for (const ns of ["type:", "priority:P2", "where:", "unit:foo", "mig:", "risk:"]) assert.ok(flat.includes(ns), ns);
8814
+ const bad = world(); withPolicy(bad); const rb = bad.io.fs.read;
8815
+ bad.io.fs.read = async (p) => (p.endsWith("/classification.json") ? JSON.stringify({ type: "nope", severity: "P2", exists_in: "unknown" }) : rb(p));
8816
+ await run(bad);
8817
+ assert.ok(builders(bad).some((c) => String(c[4]).includes("concerns .forge-lean/classification.json")), "the correction resume was issued for the invalid record");
8818
+ assert.ok(!builders(w).some((c) => String(c[4]).includes("concerns .forge-lean/classification.json")), "a valid record needs no correction");
8819
+ const c = bad.comments.find((x) => x.includes("FORGE:CLASSIFY"));
8820
+ assert.ok(c && /text-only/.test(c), "a second invalid record falls back to text-only after the one correction");
8821
+ });
8822
+ it("a repro that passes (runCommand rc 0) on the live sha downgrades exists_in: live; a failing one (rc 1) keeps it", async () => {
8823
+ const LIVE = JSON.stringify({ type: "bug", severity: "P2", exists_in: "live", flag: "none", confidence: 0.8, exists_in_evidence: { cite: "src/a.js:1", repro: { command: "node r.js", red_on_live: true, green_after: null } } });
8824
+ const go = async (rc) => {
8825
+ const w = world(); const g = w.io.git, rd = w.io.fs.read;
8826
+ w.io.git = async (a, o) => (a[0] === "show" && /\.forge\/release\.yaml$/.test(a.at(-1)) ? POLICY.replace("default: main", "default: main, release: rel") : a[0] === "rev-parse" && /origin\/rel$/.test(a.at(-1)) ? "abc123\n" : a[0] === "cat-file" ? "" : a[0] === "show" && /^abc123:/.test(a.at(-1)) ? "line1\n" : a[0] === "worktree" ? "" : g(a, o));
8827
+ w.io.fs.read = async (p) => (p.endsWith("/classification.json") ? LIVE : rd(p));
8828
+ w.io.runCommand = async () => ({ rc, output: "" });
8829
+ await run(w);
8830
+ return w.comments.find((x) => x.includes("FORGE:CLASSIFY")) ?? "";
8831
+ };
8832
+ assert.match(await go(0), /"exists_in": "unknown"/);
8833
+ assert.match(await go(1), /"exists_in": "live"/);
8834
+ });
8835
+ it("is a no-op without .forge/release.yaml", async () => {
8836
+ const w = world();
8837
+ await run(w);
8838
+ assert.ok(!w.comments.some((x) => x.includes("FORGE:CLASSIFY")));
8839
+ assert.ok(!w.edits.some((e) => e.some((x) => /^(type|unit|where|mig|risk):/.test(String(x)))));
8840
+ });
8841
+ });
8842
+
8695
8843
  describe("#5592 (8) comment and label spam", () => {
8696
8844
  const BOTC = { author: { login: "rapiercraft-forgedock" }, authorAssociation: "CONTRIBUTOR" };
8697
8845
  const SEP = "<!-- FORGE:STATUS:SEP -->";
@@ -8746,3 +8894,29 @@ describe("#5592 (8) comment and label spam", () => {
8746
8894
  assert.ok(w.edits.some((e) => e.join(" ") === "issue edit 7 -R o/r --remove-label parked:ci.red"));
8747
8895
  });
8748
8896
  });
8897
+
8898
+ describe("#5683 monorepo sub-project dependencies are not host tools", () => {
8899
+ const pkg = JSON.stringify({ devDependencies: { vitest: "^1", vite: "^5" } });
8900
+ const withWeb = (w) => { const g = w.io.git; w.io.git = async (a, ...r) => (a[0] === "ls-files" && !a.includes(".forge-lean/") ? `${await g(a, ...r)}\nweb/package.json` : g(a, ...r)); w.files[`${WT}/web/package.json`] = pkg; return w; };
8901
+ const planEnv = (env) => ({ ...CONTRACT, test_plan: [{ requirement: "R1", proof: "the runner resolves", level: "unit", level_reason: "cheapest level that observes it", repro: "no-repro", reason: "env-only", command: "node --test test/foo.test.js", env }] });
8902
+ const hostMiss = (w) => { w.io.runCommand = async ({ command }) => (/command -v/.test(command) ? { rc: 1, output: "" } : { rc: 0, output: "" }); };
8903
+ it("monorepo sub-project env name is not a host tool: prepared, never env.tool_missing; a real host tool still is", async () => {
8904
+ const w = withWeb(world({ contract: planEnv(["vitest"]) })); let prepared = 0;
8905
+ w.io.deps = { prepare: async () => { prepared++; return []; } }; hostMiss(w);
8906
+ const ok = await run(w, { conformance: "enforce" });
8907
+ assert.notEqual(ok.code, OUTCOME_CODES.ENV_TOOL_MISSING); assert.ok(prepared >= 1);
8908
+ const h = withWeb(world({ contract: planEnv(["psql"]) })); h.io.deps = { prepare: async () => [] }; hostMiss(h);
8909
+ assert.equal((await run(h, { conformance: "enforce" })).code, OUTCOME_CODES.ENV_TOOL_MISSING);
8910
+ });
8911
+ it("monorepo sub-project remote name skips recipe branch; a manifest-less tool still hits it", async () => {
8912
+ const remote = { placement: { where: "remote", reason: "mode remote" } };
8913
+ const withTool = (tool) => ({ ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: `${tool} check x` }] });
8914
+ const probing = (w, tool) => { w.io.probeCommand = async (a) => ({ rc: new RegExp(tool).test(JSON.stringify(a)) ? 127 : 0, output: "" }); };
8915
+ const w = withWeb(world({ contract: withTool("vite") })); probing(w, "vite"); let prepared = 0; w.io.deps = { prepare: async () => { prepared++; return []; } };
8916
+ const r = await run(w, { dir: tmpDir("lean-5683a-"), ...remote });
8917
+ assert.notEqual(r.code, "env.tool_missing"); assert.ok(prepared >= 1);
8918
+ assert.doesNotMatch(w.comments.map((c) => c.body ?? c).join("\n"), /no lane_tools recipe/);
8919
+ const h = withWeb(world({ contract: withTool("zzcheck") })); probing(h, "zzcheck");
8920
+ assert.equal((await run(h, { dir: tmpDir("lean-5683b-"), ...remote })).code, "env.tool_missing");
8921
+ });
8922
+ });
@@ -140,4 +140,37 @@ describe("--requeue of a lease-deferred pending issue (#5241)", () => {
140
140
  assert.deepEqual(runs, [9, 9]);
141
141
  assert.equal(rows.find((r) => r.issue === 9).outcome, "merged");
142
142
  });
143
+
144
+ // #5654: an interrupted or engine-error lane releases its own lease so the requeue is not deferred as lease.held
145
+ it("releases the lease of a resumed run whose lane is gone, and re-dispatches it", async () => {
146
+ let saved = { v: 1, order: [9], running: { 9: { startedAt: 1, pid: 4242 } }, results: {}, pending: [] };
147
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: () => {} };
148
+ const released = [], ran = [], order = [];
149
+ await orchestrate({ issues: [9], parallel: 1, pollMs: 5, readBody: async () => "", store, adopt: async () => null,
150
+ releaseLease: async (n) => { released.push(n); order.push("release"); },
151
+ runOne: async (n) => { ran.push(n); order.push("run"); return { terminalReason: "merged", pr: 1 }; } });
152
+ assert.deepEqual(released, [9]);
153
+ assert.deepEqual(ran, [9]);
154
+ assert.equal(order[0], "release", "the lease goes before the issue is dispatched again");
155
+ });
156
+
157
+ it("releases the lease of a lane that ends in engine-error", async () => {
158
+ const released = [];
159
+ const store = { load: () => null, save: () => {}, log: () => {} };
160
+ let calls = 0;
161
+ await orchestrate({ issues: [2], parallel: 1, pollMs: 5, readBody: async () => "", store, releaseLease: async (n) => { released.push(n); },
162
+ runOne: async () => (++calls === 1 ? { terminalReason: "engine-error", detail: "boom" } : { terminalReason: "merged", pr: 2 }) });
163
+ assert.deepEqual(released, [2]);
164
+ });
165
+
166
+ it("requeues an interrupted lane at once (no backoff) after releasing its lease", async () => {
167
+ const released = [], store = { load: () => null, save: () => {}, log: () => {} };
168
+ let calls = 0;
169
+ const t0 = Date.now();
170
+ await orchestrate({ issues: [3], parallel: 1, pollMs: 5, readBody: async () => "", store, releaseLease: async (n) => { released.push(n); },
171
+ runOne: async () => (++calls === 1 ? { terminalReason: "deferred", code: "run.interrupted", detail: "SIGTERM" } : { terminalReason: "merged", pr: 3 }) });
172
+ assert.deepEqual(released, [3]);
173
+ assert.equal(calls, 2);
174
+ assert.ok(Date.now() - t0 < 10000, "re-dispatched without the 120s deferral backoff");
175
+ });
143
176
  });
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { orchestrate } from "./orchestrate.mjs";
6
+ import { hostFallbackAllowed } from "./execution.mjs";
7
+
8
+ // #5652: host re-placement of a remote lane's env.tool_missing / env.capability_remote end follows host.role / execution.host_fallback.
9
+ const go = async (code, cfg) => {
10
+ const calls = [];
11
+ const rows = await orchestrate({ issues: [5], parallel: 2, recovery: { maxAttempts: 1 }, readBody: async () => "",
12
+ remote: { max: 2, isRemote: () => true, hostFallback: hostFallbackAllowed(cfg), place: () => ({ where: "remote", reason: "mode remote" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 },
13
+ runOne: async (n, _l, ctx = {}) => {
14
+ calls.push({ placement: ctx.placement?.where, recover: ctx.recover?.code ?? null });
15
+ return ctx.recover ? { terminalReason: "merged", pr: 9 } : { terminalReason: "needs-human", code, detail: "no tool", placement: { where: "remote" } };
16
+ } });
17
+ return { rows, calls };
18
+ };
19
+
20
+ describe("#5652 host fallback placement", () => {
21
+ for (const code of ["env.capability_remote", "env.tool_missing"]) {
22
+ it(`${code}: host.role unset keeps the host re-placement`, async () => {
23
+ const r = await go(code, {});
24
+ assert.equal(r.calls.length, 2);
25
+ });
26
+ it(`${code}: host.role orchestrator ends the lane without a host re-placement`, async () => {
27
+ const r = await go(code, { hostRole: "orchestrator" });
28
+ assert.equal(r.calls.length, 1);
29
+ assert.equal(r.rows.find((x) => x.issue === 5).outcome, "needs-human");
30
+ });
31
+ it(`${code}: explicit host_fallback: true overrides host.role orchestrator`, async () => {
32
+ const r = await go(code, { hostRole: "orchestrator", hostFallback: true });
33
+ assert.equal(r.calls.length, 2);
34
+ assert.equal(r.calls[1].placement === "local" || r.calls[1].placement === "remote", true);
35
+ });
36
+ }
37
+ it("regression: a non-host code (ci.red-like) recovery is unaffected by host.role", async () => {
38
+ const r = await go("env.repro_unrunnable", { hostRole: "orchestrator" });
39
+ assert.ok(r.calls.length >= 1);
40
+ });
41
+ });
@@ -0,0 +1,42 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5647: while a recovery lane is queued or running the issue shows workflow:recovering, not needs-human.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { orchestrate } from "./orchestrate.mjs";
8
+
9
+ process.env.FORGEDOCK_SCHED_DIR = tmpDir("recovering-sched-");
10
+ const NH = (code) => ({ terminalReason: "needs-human", code, detail: `ended ${code}` });
11
+ const run = (script, extra = {}) => {
12
+ const marks = [], relabels = [], rows = [];
13
+ let k = 0;
14
+ return orchestrate({ issues: [1], parallel: 1, recovery: { maxAttempts: 1 }, readBody: async () => "", onUpdate: (r) => rows.push(r.outcome),
15
+ runOne: async () => script[Math.min(k++, script.length - 1)],
16
+ markRecovering: async (x) => { marks.push(x); }, relabelNeedsHuman: async (x) => { relabels.push(x); }, ...extra })
17
+ .then((res) => ({ res, marks, relabels, rows }));
18
+ };
19
+
20
+ describe("workflow:recovering during recovery (#5647)", () => {
21
+ it("a recoverable needs-human row calls markRecovering once with attempt/max and the row goes recovering", async () => {
22
+ const r = await run([NH("base.conflict"), { terminalReason: "merged" }]);
23
+ assert.deepEqual(r.marks, [{ issue: 1, code: "base.conflict", attempt: 1, max: 1 }]);
24
+ assert.ok(r.rows.includes("recovering"));
25
+ assert.equal(r.res[0].outcome, "merged");
26
+ assert.deepEqual(r.relabels, []);
27
+ });
28
+ it("a throwing markRecovering does not block the recovery lane", async () => {
29
+ const r = await run([NH("base.conflict"), { terminalReason: "merged" }], { markRecovering: async () => { throw new Error("gh down"); } });
30
+ assert.equal(r.res[0].outcome, "merged");
31
+ });
32
+ it("an exhausted recovery ends needs-human through relabelNeedsHuman, after the single mark", async () => {
33
+ const r = await run([NH("base.conflict"), NH("base.conflict")]);
34
+ assert.equal(r.marks.length, 1);
35
+ assert.equal(r.res[0].outcome, "needs-human");
36
+ assert.equal(r.relabels.length, 1);
37
+ });
38
+ it("a human-owned code is never marked recovering", async () => {
39
+ const r = await run([NH("builder.blocked")]);
40
+ assert.deepEqual(r.marks, []);
41
+ });
42
+ });
@@ -249,6 +249,7 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
249
249
  const k = deferrals + 1;
250
250
  if (k > maxDeferrals) return { capped: true };
251
251
  if (posNum(r?.retryInSeconds)) return { delayMs: r.retryInSeconds * 1000 };
252
+ if (code === "run.interrupted") return { delayMs: 0 }; // #5654: its lease was released, so there is nothing to wait out
252
253
  // lease-held: "leased by X until <ISO>"
253
254
  const until = /\buntil (\d{4}-\d\d-\d\dT[\d:.]+Z)/.exec(String(r?.detail ?? ""))?.[1];
254
255
  const at = until ? Date.parse(until) : NaN;
@@ -311,7 +312,7 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
311
312
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
312
313
  store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000,
313
314
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
314
- recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
315
+ recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
315
316
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
316
317
  getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null }) {
317
318
  const saved = store?.load?.() ?? null;
@@ -382,6 +383,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
382
383
  const remoteRun = new Set(); // remote lanes running now (#4253): admitted against remoteMax, never the host cap
383
384
  let budgetLocal = false; // the execution budget refused a remote lane under on_budget local: the rest run on the host
384
385
  // #4256: where a lane goes before capacity: `remote.place` (hybrid) or `remote.isRemote` (remote mode).
386
+ const hostFallbackOn = () => remote?.hostFallback !== false; // #5652: unset keeps the host re-placement
385
387
  const placeOf = (n) => {
386
388
  if (!remote) return null;
387
389
  // #4542: a lane recovering from a remote capability block runs on the host, which has the capability.
@@ -389,7 +391,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
389
391
  // #5423: the lane now provisions the sandbox before ending tool_missing, so the first tool-missing recovery of a remote run retries remotely (not parked behind host load); a repeat goes to the host
390
392
  const rec = recovering.get(n);
391
393
  if (rec?.code === OUTCOME_CODES.ENV_TOOL_MISSING && rec.where === "remote" && (rec.attempt ?? 1) <= 1 && !budgetLocal) return { where: "remote", reason: "retry remotely after sandbox provisioning" };
392
- if ([OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
394
+ // #5652: with host fallback off (execution.host_fallback / host.role: orchestrator) the host is orchestrator-only: no re-placement here
395
+ if (hostFallbackOn() && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
393
396
  // #5371: a mechanical recovery never repeats the placement of the run that failed (a remote sandbox env defect recurs there), and a remote validate failure is rerun on the host
394
397
  if (recovering.get(n)?.code === ENV_VALIDATE_PLACEMENT || (MECHANICAL_CODES.includes(recovering.get(n)?.code) && recovering.get(n)?.where === "remote")) return { where: "local", reason: `different placement: recovering ${recovering.get(n).code} off the remote run` };
395
398
  { // #5331: a frozen contract naming a tool the sandbox is known to lack runs on the host (`remote.lacks`, `remote.contractOf(n)`; both optional)
@@ -744,7 +747,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
744
747
  // Apply one lane's result: requeue it (deferred, dependency-open, engine-error) or record its final row.
745
748
  const settleLane = async (n, r, rec, pf) => {
746
749
  if (halted) return; // #4454: a resume adopts the lane and settles it
747
- if (cancelled && releaseLease) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } } // #5241: the lane ended: its lease goes with it
750
+ // #5241: the lane ended: its lease goes with it. #5654: also an interrupted or engine-error end, which is requeued at once
751
+ if (releaseLease && (cancelled || (r?.terminalReason ?? "engine-error") === "engine-error" || (r?.terminalReason === "deferred" && r?.code === "run.interrupted"))) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } }
748
752
  // #4304: the pre-filter runs once per issue; a recovery pass's row adds the earlier attempt's cost, which already holds it.
749
753
  const pfCost = recovering.has(n) ? 0 : (pf?.cost_usd ?? 0);
750
754
  const row = { issue: n, outcome: r?.terminalReason ?? "engine-error", pr: r?.pr ?? null, cost_usd: (r?.cost_usd ?? 0) + pfCost, minutes: Math.round((now() - rec.startedAt) / 6000) / 10, detail: r?.detail, ...(r?.code ? { code: r.code } : {}), ...(pf ? { prefilter: pf } : {}),
@@ -943,13 +947,18 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
943
947
  row.detail = `Environment defect: the recovery attempt failed with the same \`${row.code}\` as the run before it, so no further rebuild is spent; run the command below on the host with the project's real dependencies.\n${String(row.detail ?? "")}`;
944
948
  decided({ issue: n, what: `no further recovery for ${row.code}: the same failure repeated`, why: firstLine(row.detail), alternative: "requeue another recovery lane that rebuilds against the same frozen command" });
945
949
  }
946
- if (!repeatEnv && !sameHostReplay && classifyNeedsHuman(facts) === "recoverable" && used < max) {
950
+ // #5652: a remote lane's tool/capability end is not recovered on the host when host fallback is off; the lane message names the fix
951
+ const noHostRecovery = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
952
+ if (noHostRecovery) decided({ issue: n, what: `no host re-placement for ${row.code}: host fallback is off (execution.host_fallback / host.role: orchestrator)`, why: firstLine(row.detail), alternative: "re-place the lane on the host" });
953
+ if (!repeatEnv && !noHostRecovery && !sameHostReplay && classifyNeedsHuman(facts) === "recoverable" && used < max) {
947
954
  const code = recoveryCodeOf(facts), attempt = used + 1;
948
955
  classUsed.set(`${n}:${cls}`, attempt);
949
956
  // #4315: the full lane detail is kept (never firstLine) for the relabel when the batch stops before this attempt
950
957
  recoveries.set(n, (recoveries.get(n) ?? 0) + 1); recovering.set(n, { code, attempt, max, cost_usd: Number(row.cost_usd) || 0, minutes: Number(row.minutes) || 0,
951
958
  detail: String(row.detail ?? ""), outcome: row.outcome, ...(row.placement?.where ? { where: row.placement.where } : {}), ...(row.code ? { result_code: row.code } : {}), prev_attempt: prior?.attempt ?? 0 });
952
959
  requeue(n, 0); done(); save();
960
+ // #5647: the first lane labelled needs-human before the batch chose to recover; swap it for workflow:recovering while the recovery runs
961
+ if (typeof markRecovering === "function") { try { await markRecovering({ issue: n, code, attempt, max }); } catch { /* best effort: needs-human stays */ } }
953
962
  decided({ issue: n, what: `recovery lane for ${code} (attempt ${attempt}/${max}); dependents stay queued`, why: firstLine(row.detail) || code,
954
963
  alternative: "leave needs-human for the operator and skip the dependents" });
955
964
  update({ ...row, outcome: "recovering", detail: `recovering (${code}), attempt ${attempt}/${max}: ${firstLine(row.detail)}` });
@@ -1039,7 +1048,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1039
1048
  else if (pf?.parked) r = { terminalReason: pf.kind, cost_usd: 0, detail: `pre-filter: ${pf.detail}` };
1040
1049
  else {
1041
1050
  try {
1042
- r = await runOne(n, lane, { remote: !!rec.remote, ...(rec.placement ? { placement: rec.placement } : {}), ...(recovering.has(n) ? { recover: { code: recovering.get(n).code, attempt: recovering.get(n).attempt, final: recovering.get(n).attempt >= (recovering.get(n).max ?? recoveryMax) } } : {}), onStart: (info) => {
1051
+ r = await runOne(n, lane, { ...(signal ? { signal } : {}), remote: !!rec.remote, ...(rec.placement ? { placement: rec.placement } : {}), ...(recovering.has(n) ? { recover: { code: recovering.get(n).code, attempt: recovering.get(n).attempt, final: recovering.get(n).attempt >= (recovering.get(n).max ?? recoveryMax) } } : {}), onStart: (info) => {
1043
1052
  Object.assign(rec, info ?? {}); save();
1044
1053
  if (rec.remote && remoteRun.has(n)) noteRemote(n, rec.handle);
1045
1054
  if (cancelled) stop(n, rec); // #4376: launched while the cancel arrived
@@ -1058,9 +1067,13 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1058
1067
  // #5204: a requeue is never silent: one `deferred`/`run.interrupted` row names the cause (an upgrade or a plain restart)
1059
1068
  // and `onInterrupted` reconciles the issue's labels. It consumes no deferral, engine-error or recovery attempt.
1060
1069
  const interruptCause = saved?.engineVersion && version && saved.engineVersion !== version ? `upgrade v${saved.engineVersion}→v${version}` : "dispatcher restart";
1061
- const requeueLost = (n, why) => {
1070
+ const requeueLost = async (n, why) => {
1071
+ const rec = runRecs.get(n);
1062
1072
  runRecs.delete(n);
1063
1073
  if (pending.includes(n) || results.has(n)) return;
1074
+ // #5654: the lost lane's own lease would defer the requeue as lease.held for its whole TTL
1075
+ if (releaseLease) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } }
1076
+ if (pending.includes(n) || results.has(n)) return;
1064
1077
  pending.unshift(n); enqueued.set(n, now());
1065
1078
  update({ issue: n, outcome: "deferred", code: "run.interrupted", pr: null, cost_usd: 0, minutes: 0, detail: `interrupted: ${interruptCause}; ${why}; requeued` });
1066
1079
  decided({ issue: n, what: "requeued (interrupted)", why, alternative: "leave it pending silently" });
@@ -1072,7 +1085,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1072
1085
  if (!adopt || !(rec?.pid || rec?.handle || rec?.remote)) return { n, rec, live: false, p: Promise.resolve(null) };
1073
1086
  let onLive;
1074
1087
  const isLive = new Promise((r) => { onLive = () => r(true); });
1075
- const p = Promise.resolve().then(() => adopt(n, rec, { onLive })).catch((e) => { adoptErrors.set(n, `adopt failed: ${firstLine(e?.message ?? e)}`); return null; });
1088
+ const p = Promise.resolve().then(() => adopt(n, rec, { onLive, ...(signal ? { signal } : {}) })).catch((e) => { adoptErrors.set(n, `adopt failed: ${firstLine(e?.message ?? e)}`); return null; });
1076
1089
  return { n, rec, p, first: Promise.race([p.then(() => false), isLive]) };
1077
1090
  });
1078
1091
  for (const a of adopting) a.live = a.first ? await a.first : false;
@@ -1080,17 +1093,17 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1080
1093
  if (live) {
1081
1094
  if (rec.remote) { remoteRun.add(n); noteRemote(n, rec.handle); }
1082
1095
  else if (reg) { reg.adoptSlot(keyOf(n), { ...entryOf(n), lanePid: rec.pid }); slotted.add(n); }
1083
- track(n, p.then((r) => {
1096
+ track(n, p.then(async (r) => {
1084
1097
  if (r) return settle(n, r, rec, checked.get(n) ?? null);
1085
1098
  if (halted) return; // #4454: kept for the next resume
1086
- running.delete(n); releaseSlot(n); endRemote(n); requeueLost(n, "the adopted lane ended without a result"); save(); // ended without a result after all
1099
+ running.delete(n); releaseSlot(n); endRemote(n); await requeueLost(n, "the adopted lane ended without a result"); save(); // ended without a result after all
1087
1100
  }));
1088
1101
  continue;
1089
1102
  }
1090
1103
  const r = await p;
1091
1104
  if (!r) {
1092
1105
  const why = adoptErrors.get(n) ?? (!adopt || !(rec?.pid || rec?.handle || rec?.remote) ? "no adoptable pid or handle" : "the lane ended without a result");
1093
- requeueLost(n, why); continue;
1106
+ await requeueLost(n, why); continue;
1094
1107
  }
1095
1108
  if (rec.remote) { remoteRun.add(n); noteRemote(n, rec.handle); }
1096
1109
  else if (reg) { reg.adoptSlot(keyOf(n), { ...entryOf(n), lanePid: rec.pid }); slotted.add(n); } // released by the settle