forgedock 1.65.0 → 1.67.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 (80) hide show
  1. package/bin/config-schema.mjs +2 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +143 -19
  4. package/bin/forgedock.mjs +7 -0
  5. package/bin/help-text.mjs +3 -3
  6. package/bin/introspect-schedule.mjs +98 -0
  7. package/bin/introspect-schedule.test.mjs +67 -0
  8. package/bin/lean/advisory.test.mjs +49 -0
  9. package/bin/lean/amendment-schema.mjs +31 -0
  10. package/bin/lean/attempts.mjs +159 -0
  11. package/bin/lean/attempts.test.mjs +127 -0
  12. package/bin/lean/basered.mjs +55 -0
  13. package/bin/lean/basered.test.mjs +68 -1
  14. package/bin/lean/batch-health.mjs +13 -5
  15. package/bin/lean/batch-health.test.mjs +16 -0
  16. package/bin/lean/batch.mjs +62 -0
  17. package/bin/lean/batch.test.mjs +119 -3
  18. package/bin/lean/capwait.mjs +14 -3
  19. package/bin/lean/capwait.test.mjs +20 -0
  20. package/bin/lean/clear-breaker.mjs +14 -0
  21. package/bin/lean/commentstate.mjs +41 -0
  22. package/bin/lean/commentstate.test.mjs +32 -0
  23. package/bin/lean/concurrency.mjs +89 -0
  24. package/bin/lean/concurrency.test.mjs +113 -0
  25. package/bin/lean/conformance.e2e.test.mjs +4 -2
  26. package/bin/lean/conformance.mjs +35 -3
  27. package/bin/lean/conformance.test.mjs +52 -0
  28. package/bin/lean/depcache.mjs +9 -0
  29. package/bin/lean/efficiency.mjs +162 -0
  30. package/bin/lean/efficiency.test.mjs +79 -0
  31. package/bin/lean/execution.mjs +31 -13
  32. package/bin/lean/execution.test.mjs +46 -0
  33. package/bin/lean/failure-stop.mjs +46 -0
  34. package/bin/lean/failure-stop.test.mjs +45 -0
  35. package/bin/lean/fixtures/capacity-storm.json +609 -0
  36. package/bin/lean/lean.mjs +130 -30
  37. package/bin/lean/lean.test.mjs +138 -47
  38. package/bin/lean/liveness.mjs +37 -0
  39. package/bin/lean/liveness.test.mjs +33 -0
  40. package/bin/lean/orchestrate-attempts.test.mjs +74 -0
  41. package/bin/lean/orchestrate-envhold.test.mjs +17 -0
  42. package/bin/lean/orchestrate-pause.test.mjs +84 -0
  43. package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
  44. package/bin/lean/orchestrate.mjs +202 -28
  45. package/bin/lean/phaseledger.mjs +6 -0
  46. package/bin/lean/phaseledger.test.mjs +13 -1
  47. package/bin/lean/prompts.mjs +6 -10
  48. package/bin/lean/reconcile.mjs +90 -0
  49. package/bin/lean/recurrence.mjs +38 -2
  50. package/bin/lean/recurrence.test.mjs +56 -1
  51. package/bin/lean/sandbox-remote.mjs +33 -2
  52. package/bin/lean/sched.mjs +19 -0
  53. package/bin/lean/sched.test.mjs +11 -1
  54. package/bin/lean/schedd-health.mjs +8 -1
  55. package/bin/lean/schedd-health.test.mjs +19 -0
  56. package/bin/lean/schedd.mjs +97 -10
  57. package/bin/lean/schedd.test.mjs +138 -1
  58. package/bin/lean/slo.mjs +126 -0
  59. package/bin/lean/slo.test.mjs +112 -0
  60. package/bin/lean/statuscomment.mjs +37 -0
  61. package/bin/lean/statuscomment.test.mjs +48 -1
  62. package/bin/lean/verify.mjs +2 -1
  63. package/bin/pool/agent.mjs +46 -8
  64. package/bin/pool/cache-sweep.mjs +41 -4
  65. package/bin/pool/cli.mjs +28 -1
  66. package/bin/pool/health.mjs +18 -0
  67. package/bin/pool/lane-tools.mjs +21 -0
  68. package/bin/pool/mirror-seed.mjs +21 -2
  69. package/bin/pool/router.mjs +6 -2
  70. package/bin/stats/attempts.mjs +54 -0
  71. package/bin/stats/attempts.test.mjs +30 -0
  72. package/bin/stats/churn.mjs +49 -0
  73. package/bin/stats/churn.test.mjs +31 -0
  74. package/bin/stats/index.mjs +11 -3
  75. package/commands/orchestrate.md +21 -18
  76. package/docs/CONFIG.md +1 -0
  77. package/docs/OUTCOME-CODES.md +1 -0
  78. package/package.json +1 -1
  79. package/pool/image/entrypoint.sh +2 -1
  80. package/scripts/check-devdocs-freshness.sh +1 -1
@@ -398,11 +398,11 @@ describe("core work-on", () => {
398
398
  assert.match(traj(w)[0], /Amendment kinds invalid \(1\); builder asked to correct/);
399
399
  });
400
400
 
401
- it("an unknown amendment kind the builder does not fix parks only after the one correction (#5089)", async () => {
401
+ it("an unknown amendment kind the builder does not fix gets the one correction, then is advisory: not applied, never parks (#5089, unclog)", async () => {
402
402
  const bad = [{ kind: "deliverable_change", requirement: "R1", why: "w" }];
403
403
  const w = world({ amendments: bad, resumeAmendments: bad, reviews: [ok()] });
404
404
  const r = await run(w);
405
- assert.equal(r.terminalReason, "needs-human");
405
+ assert.equal(r.terminalReason, "merged");
406
406
  assert.equal(builders(w).filter((c) => /amendments in .*result\.json are not valid/.test(c[4] ?? "")).length, 1);
407
407
  });
408
408
 
@@ -579,6 +579,29 @@ describe("core work-on", () => {
579
579
  };
580
580
  return w;
581
581
  };
582
+ it("#5979 a second identical failure parks with one PARKED summary (failure.repeated), no relaunch; an unchanged DEPENDENCY is not re-posted", async () => {
583
+ const block = { status: "blocked", summary: "need creds", block: { kind: "human", why: "credentials" } };
584
+ const opts = { changed: [] };
585
+ const first = world(opts);
586
+ const r1 = await run(first);
587
+ assert.notEqual(r1.code, "failure.repeated", "the 1st failure is not parked");
588
+ const nh = first.comments.find((c) => c.includes("<!-- FORGE:NEEDS_HUMAN -->"));
589
+ assert.ok(nh && /sig=[0-9a-f]{12}/.test(nh), "every NEEDS_HUMAN carries its signature");
590
+ const again = world({ ...opts, viewComments: [{ author: { login: "rapiercraft-forgedock" }, body: nh }] });
591
+ const r2 = await run(again);
592
+ assert.equal(r2.code, "failure.repeated");
593
+ {
594
+ assert.equal(again.comments.filter((c) => c.includes("<!-- FORGE:PARKED -->")).length, 1);
595
+ assert.ok(again.edits.some((e) => e.includes("parked:failure.repeated")));
596
+ assert.ok(!again.comments.some((c) => c.includes("<!-- FORGE:NEEDS_HUMAN -->")), "the repeat posts the summary instead of another NEEDS_HUMAN");
597
+ }
598
+ const dep = depWorld({ changed: [], result: { status: "blocked", summary: "needs #3", block: { kind: "dependency", issues: [3] } } }, { 3: { state: "OPEN", labels: [] } });
599
+ await run(dep);
600
+ const posted = dep.comments.find((c) => c.includes("<!-- FORGE:DEPENDENCY -->"));
601
+ const dep2 = depWorld({ changed: [], viewComments: [{ author: { login: "rapiercraft-forgedock" }, body: posted }], result: block.block ? { status: "blocked", summary: "needs #3", block: { kind: "dependency", issues: [3] } } : null }, { 3: { state: "OPEN", labels: [] } });
602
+ await run(dep2);
603
+ assert.ok(!dep2.comments.some((c) => c.includes("<!-- FORGE:DEPENDENCY -->")), "same state: skipped");
604
+ });
582
605
  const noNeedsHuman = (w) => {
583
606
  assert.ok(!w.edits.some((e) => e.includes("--add-label") && e.includes("needs-human")), JSON.stringify(w.edits));
584
607
  assert.ok(!w.comments.some((c) => c.includes("FORGE:NEEDS_HUMAN")));
@@ -1340,22 +1363,14 @@ describe("conformance gate (frozen contract, precheck, structured review)", () =
1340
1363
  assert.equal(w.closed[0].at(-1), "completed");
1341
1364
  });
1342
1365
 
1343
- it("scope creep: an unauthorized file is caught by the precheck before any reviewer run; the resume reverts it and it merges", async () => {
1366
+ it("scope creep is advisory (unclog): recorded as an ADVISORY event, no builder resume, the review runs and it merges", async () => {
1344
1367
  const dir = tmpDir("conf-creep-");
1345
- const w = world({ changed: ["src/foo.js", "src/billing.js", "test/foo.test.js"], resumeChanged: ["src/foo.js", "test/foo.test.js"] });
1368
+ const w = world({ changed: ["src/foo.js", "src/billing.js", "test/foo.test.js"] });
1346
1369
  const r = await run(w, { dir });
1347
1370
  assert.equal(r.terminalReason, "merged");
1348
- assert.equal(reviewers(w).length, 1, "the reviewer ran only after the precheck passed");
1349
- assert.match(builders(w)[2][4], /conformance\.scope_creep: changed outside the contract's deliverables: src\/billing\.js/);
1350
- const ev = events(dir);
1351
- assert.ok(ev.indexOf("PRECHECK") < ev.indexOf("CONFORMANCE"));
1352
- });
1353
-
1354
- it("scope creep that persists is needs-human conformance.scope_creep with no reviewer tokens spent", async () => {
1355
- const w = world({ changed: ["src/foo.js", "src/billing.js", "test/foo.test.js"] });
1356
- const r = await run(w);
1357
- assert.equal(r.code, "conformance.scope_creep"); assert.equal(reviewers(w).length, 0);
1358
- blockedNothingMerged(w);
1371
+ assert.equal(reviewers(w).length, 1);
1372
+ assert.ok(!builders(w).some((c) => /conformance\.scope_creep/.test(c[4] ?? "")), "no resume for advisory scope creep");
1373
+ assert.ok(readLog(dir, 7).some((e) => e.event === "ADVISORY" && e.rows.includes("scope_creep")));
1359
1374
  });
1360
1375
 
1361
1376
  it("a claimed 'follow-up' with no typed deferral is needs-human conformance.untracked_deferral; nothing is filed or merged", async () => {
@@ -1698,8 +1713,8 @@ describe("devdocs freshness gate (the repo's own scripts/check-devdocs-freshness
1698
1713
  assert.match(traj(w).at(-1), /Docs freshness check failed; builder resumed once/);
1699
1714
  });
1700
1715
 
1701
- it("a doc the docs round edits outside the deliverables is an implied deliverable (no scope_creep); an unrelated extra file still is", async () => {
1702
- for (const [extra, code] of [[[], null], [["src/billing.js"], "conformance.scope_creep"]]) {
1716
+ it("a doc the docs round edits outside the deliverables is an implied deliverable; an unrelated extra file is advisory scope creep (unclog), both merge", async () => {
1717
+ for (const [extra, code] of [[[], null], [["src/billing.js"], null]]) {
1703
1718
  const w = dworld([STALE, { ok: true, output: "OK" }], { changed: ["src/foo.js", "test/foo.test.js"] });
1704
1719
  const inner = w.io.docsFreshness;
1705
1720
  w.io.docsFreshness = async (x) => { const r = await inner(x); if (r?.ok && !w.changed.includes("devdocs/modules/lean.md")) w.changed = [...w.changed, "devdocs/modules/lean.md", ...extra]; return r; };
@@ -1939,7 +1954,7 @@ describe("conformance shadow mode (the default)", () => {
1939
1954
  it("scope creep does not block in shadow (as today) but is recorded", async () => {
1940
1955
  const w = world({ changed: ["src/foo.js", "src/billing.js", "test/foo.test.js"], reviews: [conf({}, CONTRACT, ["src/foo.js", "src/billing.js", "test/foo.test.js"])] });
1941
1956
  assert.equal((await runShadow(w)).terminalReason, "merged");
1942
- assert.match(shadowNote(w), /would BLOCK[\s\S]*conformance\.scope_creep[\s\S]*src\/billing\.js/);
1957
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\): conformance\.scope_creep/); // unclog: advisory, not a would-block row
1943
1958
  });
1944
1959
 
1945
1960
  it("#4160 an incomplete review gets one targeted re-ask with only the missing ids, then needs-human; never merges in shadow", async () => {
@@ -2308,7 +2323,7 @@ describe("conformance shadow mode (the default)", () => {
2308
2323
  assert.deepEqual(reverts, ["clean -fdq -- .pytest_cache_x/log", "checkout -- src/bar.js"]);
2309
2324
  assert.ok(traj(w).some((x) => /Validate preflight reverted 2 path\(s\) its runs changed/.test(x)));
2310
2325
  });
2311
- it("#4353 the #4348 contract shape: an allowlist validate is dropped at freeze (CONTRACT_SCOPE_VALIDATE_DROPPED), the amended lane merges, and a real out-of-scope edit is still scope_creep", async () => {
2326
+ it("#4353 the #4348 contract shape: an allowlist validate is dropped at freeze (CONTRACT_SCOPE_VALIDATE_DROPPED), the amended lane merges, and a real out-of-scope edit is advisory scope_creep (unclog)", async () => {
2312
2327
  const ALLOW = 'test -z "$(git diff --name-only origin/staging...HEAD | grep -v -x -e src/foo.js -e test/foo.test.js)"';
2313
2328
  const c = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: ALLOW }] }, files = ["src/foo.js", "test/foo.test.js", "docs/foo.md"];
2314
2329
  const shape = (changed) => ({ contract: c, changed, amendments: [{ kind: "add-deliverable", path: "docs/foo.md", why: "the docs-freshness rule needs the module doc" }],
@@ -2326,8 +2341,8 @@ describe("conformance shadow mode (the default)", () => {
2326
2341
  assert.ok(traj(w).some((t) => /Scope-check validate V2 dropped at contract freeze/.test(t)));
2327
2342
  const creep = world(shape([...files, "src/other.js"]));
2328
2343
  creep.io.runCommand = async () => ({ rc: 1, output: "" });
2329
- assert.equal((await run(creep)).code, "conformance.scope_creep");
2330
- assert.ok(builders(creep).some((b) => /changed outside the contract's deliverables: src\/other\.js/.test(b[4])));
2344
+ assert.equal((await run(creep)).terminalReason, "merged", "unclog: an out-of-scope edit is advisory");
2345
+ assert.match(traj(creep).join("\n"), /Advisory \(not blocking\): conformance\.scope_creep[^\n]*src\/other\.js/);
2331
2346
  });
2332
2347
 
2333
2348
  it("#4404 a Lighthouse requirement is tagged out_of_band at freeze; with instrumentation the lane merges and the PR body names the job", async () => {
@@ -2396,7 +2411,7 @@ describe("conformance shadow mode (the default)", () => {
2396
2411
  assert.equal((await runShadow(fixed)).terminalReason, "merged", "recorded by the resume, then merges");
2397
2412
  const a = world({ amendments: [{ kind: "add-deliverable", path: "src/x.js" }] });
2398
2413
  const ra = await runShadow(a);
2399
- assert.equal(ra.code, "conformance.unimplemented"); assert.match(nhBody(a), /amendment without why/);
2414
+ assert.equal(ra.terminalReason, "merged", "unclog: an invalid amendment is advisory, not applied"); assert.match(traj(a).join("\n"), /Advisory \(not blocking\)[^\n]*amendment without why/);
2400
2415
  });
2401
2416
  it("#4737 decision records are persisted after the merge, never at gate time", async () => {
2402
2417
  const dir = tmpDir("dec-"); const prev = process.env.FORGEDOCK_DECISIONS_DIR; process.env.FORGEDOCK_DECISIONS_DIR = dir;
@@ -2553,11 +2568,11 @@ describe("conformance shadow mode (the default)", () => {
2553
2568
 
2554
2569
  describe("conformance gate: base-sync and contract size", () => {
2555
2570
  const CONFLICTING = { mergeable: "CONFLICTING", mergeStateStatus: "DIRTY" }, OKSTATE = { mergeable: "MERGEABLE", mergeStateStatus: "CLEAN" };
2556
- it("the base-sync re-review re-runs the precheck on the current files: creep introduced by conflict resolution is caught", async () => {
2571
+ it("the base-sync re-review re-runs the precheck on the current files: creep introduced by conflict resolution is recorded as advisory (unclog)", async () => {
2557
2572
  const w = world({ prView: [CONFLICTING, OKSTATE], mergeResults: ["conflict"], syncChanged: ["src/foo.js", "src/unrelated.js", "test/foo.test.js"] });
2558
2573
  const r = await run(w);
2559
- assert.equal(r.terminalReason, "needs-human"); assert.equal(w.merges.length, 0);
2560
- assert.ok(builders(w).some((b) => /conformance\.scope_creep: changed outside the contract's deliverables: src\/unrelated\.js/.test(b[4])));
2574
+ assert.equal(r.terminalReason, "merged");
2575
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\): conformance\.scope_creep[^\n]*src\/unrelated\.js/);
2561
2576
  });
2562
2577
  it("a large contract is posted compact so its JSON survives the comment cap and stays recoverable", () => {
2563
2578
  const big = { ...CONTRACT, requirements: Array.from({ length: 160 }, (_, i) => ({ id: `R${i}`, quote: "foo must handle a null argument without throwing.".repeat(4), disposition: "deliver" })) };
@@ -2712,10 +2727,10 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2712
2727
  const plan = builderPlanPrompt(7) + hotspotPlanNote(facts([HOT, { ...HOT, path: "a/b.py" }, { ...HOT, path: "c/d.py" }]));
2713
2728
  // 2750: #5750 (outcome vs guidance rows). 2650: #5557 (classification record line) on top of the base's growth. 1850: #4404 (verify out_of_band) and #4396 (split size rule) grew the plan prompt to ~1803 tokens on CI paths; 1900: #4589 (check timeout is not a block, one block-rule line). 2050: #4724 (deferred-row bucket rule). 1675 (hotspot case): #5284 (rubric prod_parity clause). 2375/1825: #5345 (self-check and pitfall lines).
2714
2729
  assert.ok(approxTokens(plan) <= 2750, `plan prompt with hotspots is ${approxTokens(plan)} tokens`);
2715
- assert.ok(approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([]))) <= 2025, `implement prompt with the hotspot rule is ${approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([])))} of 2025 tokens`); // 2025: #5752 (mechanism supersedes, negative examples, outcome evidence) // 1600: #4591 (never hand-name migration files) and #4596 (i18n translate rule), one line each; 1650: #4726 (e2e rule) // 1925: #5760 (CI budget rule)
2730
+ assert.ok(approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([]))) <= 2075, `implement prompt with the hotspot rule is ${approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([])))} of 2075 tokens`); // 2075: #5979 (substitute-validate and out-of-band from the shared amendment schema); 2025: #5752 (mechanism supersedes, negative examples, outcome evidence) // 1600: #4591 (never hand-name migration files) and #4596 (i18n translate rule), one line each; 1650: #4726 (e2e rule) // 1925: #5760 (CI budget rule)
2716
2731
  });
2717
2732
 
2718
- it("#4519 generated_paths: both prompts name the globs (even with the gate off), and an amendment adding one blocks", async () => {
2733
+ it("#4519 generated_paths: both prompts name the globs (even with the gate off), and an amendment adding one is advisory: not applied (unclog)", async () => {
2719
2734
  const G = ["web/public/openapi*.json"];
2720
2735
  for (const f of [facts([], { generated_paths: G }), facts([HOT], { enabled: false, generated_paths: G })]) {
2721
2736
  assert.match(hotspotPlanNote(f), /Generated paths \(forge\.yaml maintenance\.generated_paths, owned by the repo's generator\): web\/public\/openapi\*\.json\. Never list or amend them in/);
@@ -2724,9 +2739,9 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2724
2739
  assert.equal(hotspotPlanNote(facts([], { generated_paths: [] })), "", "no generated_paths: unchanged");
2725
2740
  const w = hworld(facts([], { generated_paths: G }), [facts([])], { amendments: [{ kind: "add-deliverable", path: "web/public/openapi.json", why: "sync the spec" }] });
2726
2741
  const r = await run(w);
2727
- assert.equal(r.code, "conformance.unimplemented"); assert.equal(w.merges.length, 0);
2742
+ assert.equal(r.terminalReason, "merged");
2728
2743
  assert.match(builders(w)[0][4], /Generated paths .*openapi/);
2729
- assert.match(nh(w), /add-deliverable web\/public\/openapi\.json: generated path/);
2744
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\)[^\n]*add-deliverable web\/public\/openapi\.json: generated path/);
2730
2745
  });
2731
2746
 
2732
2747
  it("the plan prompt carries the facts, the implement prompt the configured rule; growth within the limit merges; no extra runner calls", async () => {
@@ -2742,20 +2757,19 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2742
2757
  assert.equal(plain.calls.filter((c) => c[0] === "runner").length, w.calls.filter((c) => c[0] === "runner").length, "no extra LLM calls");
2743
2758
  });
2744
2759
 
2745
- it("unexempted growth of an over-threshold file blocks in enforce and in shadow: one resume, then needs-human maintenance.hotspot_growth, no reviewer run", async () => {
2760
+ it("unexempted growth of an over-threshold file is advisory (unclog) in enforce and in shadow: recorded, no resume, it merges", async () => {
2746
2761
  for (const conformance of ["enforce", "shadow"]) {
2747
2762
  const w = hworld(facts([HOT]), [facts([GROWN])]);
2748
2763
  const r = await run(w, { conformance });
2749
- assert.equal(r.code, "maintenance.hotspot_growth", conformance); assert.equal(w.merges.length, 0);
2750
- assert.equal(builders(w).length, 3, `${conformance}: plan + implement + one resume`); assert.equal(reviewers(w).length, 0);
2751
- assert.match(builders(w)[2][4], /maintenance\.hotspot_growth: src\/foo\.js grew by 200 lines/);
2752
- assert.match(nh(w), /src\/foo\.js grew by 200 lines/);
2764
+ assert.equal(r.terminalReason, "merged", conformance);
2765
+ assert.equal(builders(w).length, 2, `${conformance}: plan + implement, no resume`);
2766
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\): maintenance\.hotspot_growth[^\n]*src\/foo\.js grew by 200 lines/);
2753
2767
  }
2754
2768
  });
2755
2769
 
2756
2770
  it("growth moved out on the resume merges; an exemption in the contract or a failed/missing script never blocks", async () => {
2757
2771
  const w = hworld(facts([HOT]), [facts([GROWN]), facts([SMALL])]);
2758
- assert.equal((await run(w, { conformance: "shadow" })).terminalReason, "merged"); assert.equal(builders(w).length, 3);
2772
+ assert.equal((await run(w, { conformance: "shadow" })).terminalReason, "merged"); assert.equal(builders(w).length, 2, "unclog: advisory growth costs no resume");
2759
2773
  const k = { ...CONTRACT, deliverables: [{ ...CONTRACT.deliverables[0], change: "guard null; hotspot-exempt: the guard must sit next to the parser it protects" }] };
2760
2774
  const we = hworld(facts([HOT]), [facts([GROWN])], { contract: k, reviews: [conf({}, k)] });
2761
2775
  assert.equal((await run(we)).terminalReason, "merged"); assert.equal(builders(we).length, 2);
@@ -3026,6 +3040,8 @@ describe("structure delta and decision provenance at merge (forge#4165)", () =>
3026
3040
  assert.equal(r.terminalReason, "merged");
3027
3041
  const term = w.telemetry.find((x) => x.event === "RUN_TERMINAL");
3028
3042
  assert.deepEqual([term.pr, term.milestone, term.conformance_mode, term.shadow_would], [r.pr, "Remote MCP Server", "shadow", "conforms"]);
3043
+ assert.equal(term.fixed_overhead_ms, Math.max(0, term.wall_ms - term.model_ms));
3044
+ assert.equal(term.model_share, term.wall_ms > 0 ? Math.round((term.model_ms / term.wall_ms) * 1000) / 1000 : 0);
3029
3045
  const m = mapRecord(term, 5);
3030
3046
  assert.equal(m.pr, r.pr);
3031
3047
  assert.deepEqual([m.payload.milestone, m.payload.conformance_mode, m.payload.shadow_would], ["Remote MCP Server", "shadow", "conforms"]);
@@ -3252,7 +3268,7 @@ describe("comment templates", () => {
3252
3268
  it("plan and implement prompts carry the stage templates and the contract schema within budget", () => {
3253
3269
  const plan = builderPlanPrompt(7), impl = builderImplementPrompt();
3254
3270
  assert.ok(approxTokens(plan) <= 2700, `plan prompt is ${approxTokens(plan)} tokens`); // 2700: #5750 (outcome vs guidance split) on top of 2650; 2550: first-pass check-id + dependency-block rule; 2500: #5445 (Test plan heading); 2475: staging; 2375: #5432 (duplicate rule); 2075: #5284 (prod_parity plan line); 2050: #4769 (activation-row rule); 2000: #4730 (owner-step remainder); 1950: #4724 (deferred-row bucket rule) // 2325: #5333 (git stash rule + stage stamp line)
3255
- assert.ok(approxTokens(impl) <= 2000, `implement prompt is ${approxTokens(impl)} of 2000 tokens`); // 2000: #5752 // 1650: #4726 e2e rule; 1550: #4596 i18n translate rule // 1850: #5333 (git stash rule + stage stamp) // 1900: #5760 (CI budget rule)
3271
+ assert.ok(approxTokens(impl) <= 2050, `implement prompt is ${approxTokens(impl)} of 2050 tokens`); // 2050: #5979; 2000: #5752 // 1650: #4726 e2e rule; 1550: #4596 i18n translate rule // 1850: #5333 (git stash rule + stage stamp) // 1900: #5760 (CI budget rule)
3256
3272
  for (const h of ["### What Was Claimed", "### What We Found", "### Root Cause", "### Affected Files", "### Sibling Sweep", "### History", "### Recommendation", "### Related Issues", "### Test plan",
3257
3273
  "investigation.md", "contract.json", "PLANNING ONLY", '"requirements"', '"deliverables"', '"preserve"', '"validate"', "verbatim", "defer", "post-deploy"]) assert.ok(plan.includes(h), h);
3258
3274
  for (const h of ["### Approach", "### Changes", "### Acceptance Criteria Status", "### Verification", "### Notes", "implementation.md", "result.json",
@@ -4721,6 +4737,17 @@ describe("usage limit, lease takeover, worktree setup, run tmp (#4101-#4104)", (
4721
4737
  assert.equal(cred, 0); assert.equal(r.rotations, undefined); assert.equal(r.limited, undefined);
4722
4738
  });
4723
4739
 
4740
+ it("#5991 a lease of a batch that is no longer live is taken over; a live batch's lease is still held", async () => {
4741
+ const lease = { by: "core_sbx_1_ab", until: 1e12, host: "sandbox-host", pid: 1, batch: "old-batch" };
4742
+ const gone = world(); projector(gone, lease);
4743
+ assert.equal((await run(gone, { hostName: "h1", batchId: "new-batch", liveBatches: () => ["other"] })).terminalReason, "merged");
4744
+ const live = world(); projector(live, lease);
4745
+ const r = await run(live, { hostName: "h1", batchId: "new-batch", liveBatches: () => ["old-batch"] });
4746
+ assert.deepEqual([r.terminalReason, r.code], ["deferred", "lease-held"]);
4747
+ const unknown = world(); projector(unknown, lease);
4748
+ assert.equal((await run(unknown, { hostName: "h1", batchId: "new-batch", liveBatches: () => null })).code, "lease-held");
4749
+ });
4750
+
4724
4751
  it("#4101 a non-limit runner error is still engine-error", async () => {
4725
4752
  const w = world(); failFirstBuilder(w, new Error("boom"));
4726
4753
  assert.equal((await run(w)).terminalReason, "engine-error");
@@ -4923,8 +4950,8 @@ describe("host admission (#4105)", () => {
4923
4950
  it("/orchestrate spec requeues host-busy lanes with a lower K and pauses on rate_limited", async () => {
4924
4951
  const { readFileSync } = await import("node:fs");
4925
4952
  const spec = readFileSync(new URL("../../commands/orchestrate.md", import.meta.url), "utf8");
4926
- assert.match(spec, /host busy[\s\S]*lower the effective K by\s+1 for the next 5 minutes, never below 1/);
4927
- assert.match(spec, /rate_limited[\s\S]*stop launching\s+new lanes until that reset time/);
4953
+ assert.match(spec, /host\.busy[\s\S]*lower K by 1\s+for 5 minutes \(never below 1\)/);
4954
+ assert.match(spec, /rate_limited`: launch nothing until the reset time/);
4928
4955
  });
4929
4956
  });
4930
4957
 
@@ -6715,7 +6742,7 @@ describe("shared dependency cache wiring (#4220)", () => {
6715
6742
  assert.equal((await run(w, { dir })).terminalReason, "merged");
6716
6743
  assert.equal(d.calls.length, 1);
6717
6744
  assert.equal(d.calls[0].wt, "/wt/lean-7");
6718
- assert.match(d.calls[0].repoKey, /^[A-Za-z0-9._-]+-[0-9a-f]{8}$/);
6745
+ assert.equal(d.calls[0].repoKey, "o_r"); // #5901: the repo slug, not the checkout path
6719
6746
  assert.equal(d.calls[0].worktreeAdded, true);
6720
6747
  const ev = readLog(dir, 7).filter((e) => e.event === "DEPS_PREPARED");
6721
6748
  assert.deepEqual(ev.map((e) => [e.status, e.eco, e.key]), [["hit", "pnpm", "0123456789abcdef"]]);
@@ -9055,7 +9082,7 @@ describe("#4395 lane profile", () => {
9055
9082
  assert.match(p, /One turn, many calls: when several reads, greps, git show\/log\/blame or gh calls do not depend on each other, issue them all in the same turn/);
9056
9083
  assert.match(p, /Read each file's ranges once .* and keep notes; don't re-read it\./);
9057
9084
  }
9058
- assert.ok(approxTokens(builderImplementPrompt()) <= 2000, `implement prompt is ${approxTokens(builderImplementPrompt())} of 2000 tokens`); // 1900: #5760; 2000: #5752
9085
+ assert.ok(approxTokens(builderImplementPrompt()) <= 2050, `implement prompt is ${approxTokens(builderImplementPrompt())} of 2050 tokens`); // 2050: #5979; 1900: #5760; 2000: #5752
9059
9086
  assert.ok(approxTokens(builderPlanPrompt(7)) <= 2700, `plan prompt is ${approxTokens(builderPlanPrompt(7))} of 2125 tokens`);
9060
9087
  });
9061
9088
 
@@ -9098,11 +9125,11 @@ describe("#4450 light lane: one builder session, derived contract, upgrade to th
9098
9125
  const DESIGN = { why_failed: "#10 and #11 guarded one caller each", disposition: "replace", outcome: { metric: "null-input crashes in foo tests", target: "0" } };
9099
9126
  const ghApi = (a) => {
9100
9127
  const j = a.join(" ");
9101
- if (j.includes("search/issues")) return [10, 11].map((n) => JSON.stringify({ number: n, title: `fix foo null ${n}`, pr: true, merged: true })).join("\n");
9128
+ if (j.includes("search/issues")) return [10, 11].map((n) => JSON.stringify({ number: n, title: `fix foo null ${n} ERR_NULL_INPUT`, pr: true, merged: true })).join("\n"); // #5979: a symptom match (the issue's backticked signature), not only the path
9102
9129
  if (/pulls\/1[01]\/files/.test(j)) return "src/foo.js\n";
9103
9130
  return null;
9104
9131
  };
9105
- const w = lworld({ ghApi, body: `${BODY}\n\nRecurs #10`, contract: { ...CONTRACT, test_plan: TEST_PLAN, repro_test: RT, design: DESIGN } }), dir = tmpDir("light-");
9132
+ const w = lworld({ ghApi, body: `${BODY}\n\nThrows \`ERR_NULL_INPUT\`. Recurs #10`, contract: { ...CONTRACT, test_plan: TEST_PLAN, repro_test: RT, design: DESIGN } }), dir = tmpDir("light-");
9106
9133
  await run(w, { dir, ...ON });
9107
9134
  const rec = events(dir, "RECURRENCE");
9108
9135
  assert.equal(rec.length, 1);
@@ -9112,7 +9139,7 @@ describe("#4450 light lane: one builder session, derived contract, upgrade to th
9112
9139
  const plan = builders(w).find((c) => /PLANNING ONLY/.test(c[4]));
9113
9140
  assert.ok(plan, "the full lane's plan session ran");
9114
9141
  assert.match(plan[4], /DESIGN LANE \(#5751\)/);
9115
- assert.match(plan[4], /#10 fix foo null 10/);
9142
+ assert.match(plan[4], /#10 fix foo null 10 ERR_NULL_INPUT/);
9116
9143
  assert.ok(w.comments.some((c) => c.includes("<!-- FORGE:RECURRENCE -->") && /Routed to a design lane: recurrence: 2/.test(c)), "the reason is posted on the issue");
9117
9144
  assert.ok(!readLog(dir, 7).some((e) => JSON.stringify(e).includes("design_missing")), "a contract with a design block passes the design check");
9118
9145
  });
@@ -9365,7 +9392,7 @@ describe("per-kind conformance modes (engine.conformance_kinds)", () => {
9365
9392
  const w = world({ changed: CREEP, reviews: [conf({}, CONTRACT, CREEP)] });
9366
9393
  const r = await run(w, { conformance: "enforce", conformanceKinds: { "conformance.scope_creep": "shadow" } });
9367
9394
  assert.equal(r.terminalReason, "merged");
9368
- assert.match(shadowNote(w), /would BLOCK[\s\S]*conformance\.scope_creep[\s\S]*src\/billing\.js/);
9395
+ assert.match(traj(w).join("\n"), /Advisory \(not blocking\): conformance\.scope_creep/); // unclog: scope creep is advisory whatever the kind mode
9369
9396
  });
9370
9397
 
9371
9398
  it("an enforce kind in a shadow lane blocks (scope creep is recorded-only in shadow by default)", async () => {
@@ -9375,9 +9402,9 @@ describe("per-kind conformance modes (engine.conformance_kinds)", () => {
9375
9402
  blockedNothingMerged(w);
9376
9403
  });
9377
9404
 
9378
- it("an enforce lane without kinds still blocks scope creep (unchanged default)", async () => {
9405
+ it("an enforce lane without kinds records scope creep as advisory and merges (unclog default)", async () => {
9379
9406
  const w = world({ changed: CREEP });
9380
- assert.equal((await run(w, { conformance: "enforce", conformanceKinds: {} })).code, "conformance.scope_creep");
9407
+ assert.equal((await run(w, { conformance: "enforce", conformanceKinds: {} })).terminalReason, "merged");
9381
9408
  });
9382
9409
  });
9383
9410
 
@@ -9431,7 +9458,7 @@ describe("prompt budgets (#4969)", () => {
9431
9458
  assert.notEqual(moved, impl);
9432
9459
  assert.equal(approxTokens(moved), approxTokens(impl));
9433
9460
  assert.equal(approxTokens(impl.replaceAll(INSTALL_ROOT, "C:\\fd")), approxTokens(impl));
9434
- assert.ok(approxTokens(moved) <= 2000, `implement prompt from a deep checkout is ${approxTokens(moved)} of 2000 tokens`); // 1900: #5760; 2000: #5752
9461
+ assert.ok(approxTokens(moved) <= 2050, `implement prompt from a deep checkout is ${approxTokens(moved)} of 2050 tokens`); // 1900: #5760; 2000: #5752
9435
9462
  });
9436
9463
  });
9437
9464
 
@@ -10132,3 +10159,67 @@ describe("#5820 required CI checks run in the lane before the PR opens", () => {
10132
10159
  assert.equal(readLog(dir, 7).filter((e) => /^CI_PRECHECK/.test(e.event)).length, 0);
10133
10160
  });
10134
10161
  });
10162
+
10163
+ describe("#5992 verify.guard_bypass: a lane clear of the red guard's files proceeds", () => {
10164
+ it("bypasses only when opted in and the lane diff misses the guarded files", async () => {
10165
+ for (const opt of [false, true]) {
10166
+ const w = world(), git = w.io.git;
10167
+ w.io.runCommand = async () => ({ rc: 1, output: "bare 429 at app/routers/listing_feeds.py" });
10168
+ w.io.git = async (a, o) => a[0] === "log" && a.includes("--format=%H%x1f%s%x1f%b") ? `${"a".repeat(40)}\x1ffeat: feeds (#39805)\x1f` : a[0] === "diff" && a.includes("--name-only") ? "docs/readme.md\n" : git(a, o);
10169
+ const r = await run(w, { verify: { invariants: ["bash scripts/guard.sh"], ...(opt ? { guardBypass: true } : {}) } });
10170
+ if (opt) assert.notEqual(r.code, "base.red", "bypassed");
10171
+ else assert.equal(r.code, "base.red", "default stays deferred (#5239)");
10172
+ }
10173
+ });
10174
+ });
10175
+
10176
+ describe("R2 guard_bypass never discards lane-owned failures", () => {
10177
+ const setup = (rc) => {
10178
+ const w = world(), git = w.io.git;
10179
+ w.io.runCommand = async ({ command, cwd }) => ({ rc: rc(command, String(cwd).includes("basered-")), output: "bare 429 at app/routers/listing_feeds.py" });
10180
+ w.io.git = async (a, o) => a[0] === "log" && a.includes("--format=%H%x1f%s%x1f%b") ? `${"a".repeat(40)}\x1ffeat: feeds (#39805)\x1f` : a[0] === "diff" && a.includes("--name-only") ? "docs/readme.md\n" : git(a, o);
10181
+ return w;
10182
+ };
10183
+ const verify = { invariants: ["bash scripts/guard.sh", "bash scripts/other-guard.sh"], guardBypass: true };
10184
+ it("a guard that is red only in the lane alongside a base-red guard does not bypass", async () => {
10185
+ const w = setup((c, onBase) => (c.includes("other-guard") ? (onBase ? 0 : 1) : 1));
10186
+ const r = await run(w, { verify });
10187
+ assert.notEqual(r.terminalReason, "merged", "lane-broken guard is not discarded");
10188
+ assert.equal(r.events?.some?.((e) => e.event === "BASE_RED_BYPASS") ?? false, false);
10189
+ });
10190
+ it("every failure base-red still bypasses", async () => {
10191
+ const w = setup(() => 1);
10192
+ const r = await run(w, { verify });
10193
+ assert.notEqual(r.code, "base.red", "bypassed");
10194
+ });
10195
+ });
10196
+
10197
+ describe("#6008 lease/hold/pause guard before push and merge (kept sandbox)", () => {
10198
+ // admission reads (first two) see no state; every later read sees `scenario`
10199
+ const guarded = (scenario) => { const w = world(); w.leaseWrites = []; let reads = 0;
10200
+ w.io.projector = { readState: async () => (++reads <= 2 ? null : scenario()), writeState: async (_i, st) => { w.leaseWrites.push(st); } }; return w; };
10201
+ const live = () => ({ v: 1, lease: { by: "x", batch: "b1", until: Date.now() + 600000 } });
10202
+ const refused = async (scenario, extra = {}) => { const w = guarded(scenario); const r = await run(w, { batchId: "b1", ...extra }); return { w, r }; };
10203
+ it("kept: a current lease of the lane's own batch merges", async () => {
10204
+ const { r } = await refused(live);
10205
+ assert.equal(r.terminalReason, "merged");
10206
+ });
10207
+ it("kept: no current lease, an expired lease or another batch's lease refuses push and merge and ends deferred", async () => {
10208
+ for (const sc of [() => ({ v: 1, lease: null }), () => ({ v: 1, lease: { by: "x", batch: "b1", until: 0 } }), () => ({ v: 1, lease: { by: "y", batch: "other", until: Date.now() + 600000 } })]) {
10209
+ const { w, r } = await refused(sc);
10210
+ assert.deepEqual([r.terminalReason, r.code], ["deferred", "lane.suspended"]);
10211
+ assert.ok(!(w.ghCalls ?? []).some?.((c) => /pr.*merge/.test(String(c))));
10212
+ }
10213
+ });
10214
+ it("kept: a held issue or a paused batch (dispatcher suspend marker) refuses push and merge", async () => {
10215
+ for (const reason of ["held", "paused"]) {
10216
+ const { r } = await refused(() => ({ ...live(), suspend: { reason, batch: "b1" } }));
10217
+ assert.deepEqual([r.terminalReason, r.code], ["deferred", "lane.suspended"]);
10218
+ assert.match(r.detail, new RegExp(reason));
10219
+ }
10220
+ });
10221
+ it("a lane without a batch id (interactive run-issue) is not guarded", async () => {
10222
+ const w = guarded(() => ({ v: 1, lease: null }));
10223
+ assert.equal((await run(w)).terminalReason, "merged");
10224
+ });
10225
+ });
@@ -0,0 +1,37 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5991: owner-based liveness under the clock fallbacks (25 min lease TTL, 300 s unreachable window, per-attempt budget key).
5
+ * Pure helpers; the callers supply the facts (live batches, agent online state).
6
+ */
7
+
8
+ /** The transport-failure window once the pool agent answers: the sandbox is gone, not the network. */
9
+ export const AGENT_UP_WINDOW_MS = 90000;
10
+
11
+ /**
12
+ * A lease whose holder batch is provably not live. `liveBatches` is the ids of the batches that still own the issue
13
+ * (array or Set); `null`/`undefined` means unknown, and a lease without a `batch` has no owner to ask: both keep the TTL.
14
+ */
15
+ export function holderGone(lease, { liveBatches = null } = {}) {
16
+ const batch = typeof lease?.batch === "string" && lease.batch ? lease.batch : null;
17
+ if (!batch || liveBatches == null) return false;
18
+ const live = liveBatches instanceof Set ? liveBatches.has(batch) : Array.isArray(liveBatches) ? liveBatches.includes(batch) : null;
19
+ return live === false;
20
+ }
21
+
22
+ /**
23
+ * What a transport failure means after `waitedMs` in a row: "unreachable" ends the wait, "wait" keeps retrying. With the pool
24
+ * agent online (`agentOnline === true`) the window shrinks to 90 s; offline or unknown (`false`/`null`) keeps `windowMs`.
25
+ */
26
+ export function classifyTransportLoss({ agentOnline = null, waitedMs = 0, windowMs = 300000 } = {}) {
27
+ const limit = agentOnline === true ? Math.min(windowMs, AGENT_UP_WINDOW_MS) : windowMs;
28
+ return waitedMs >= limit ? "unreachable" : "wait";
29
+ }
30
+
31
+ /**
32
+ * One budget row per sandbox lifetime. #6023: a pool reuses the sandbox id across an issue's attempts, so the attempt's
33
+ * start time is part of the key; a replay of the same attempt keeps its key (the record keeps the larger usage).
34
+ */
35
+ export function sandboxBudgetKey(batchId, sandboxId, startedAt = null) {
36
+ return `${batchId}#${sandboxId}${startedAt != null && startedAt !== "" ? `#${startedAt}` : ""}`;
37
+ }
@@ -0,0 +1,33 @@
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 { holderGone, classifyTransportLoss, sandboxBudgetKey } from "./liveness.mjs";
6
+
7
+ describe("#5991 liveness helpers", () => {
8
+ it("holderGone: only a lease whose batch is known not live", () => {
9
+ assert.equal(holderGone({ batch: "b1" }, { liveBatches: ["b2"] }), true);
10
+ assert.equal(holderGone({ batch: "b1" }, { liveBatches: new Set(["b1"]) }), false);
11
+ assert.equal(holderGone({ batch: "b1" }, { liveBatches: [] }), true);
12
+ // negative examples: unknown liveness, no batch on the lease, no lease
13
+ assert.equal(holderGone({ batch: "b1" }, { liveBatches: null }), false);
14
+ assert.equal(holderGone({ batch: "b1" }), false);
15
+ assert.equal(holderGone({ by: "x" }, { liveBatches: ["b2"] }), false);
16
+ assert.equal(holderGone(null, { liveBatches: [] }), false);
17
+ });
18
+ it("classifyTransportLoss: 90 s with the agent answering, the window otherwise", () => {
19
+ assert.equal(classifyTransportLoss({ agentOnline: true, waitedMs: 90000, windowMs: 300000 }), "unreachable");
20
+ assert.equal(classifyTransportLoss({ agentOnline: true, waitedMs: 89999, windowMs: 300000 }), "wait");
21
+ assert.equal(classifyTransportLoss({ agentOnline: false, waitedMs: 200000, windowMs: 300000 }), "wait");
22
+ assert.equal(classifyTransportLoss({ agentOnline: null, waitedMs: 299999, windowMs: 300000 }), "wait");
23
+ assert.equal(classifyTransportLoss({ agentOnline: null, waitedMs: 300000, windowMs: 300000 }), "unreachable");
24
+ assert.equal(classifyTransportLoss({ agentOnline: true, waitedMs: 5000, windowMs: 5000 }), "unreachable"); // a shorter window still wins
25
+ });
26
+ it("sandboxBudgetKey is stable per sandbox lifetime", () => {
27
+ assert.equal(sandboxBudgetKey("b1", "fdrsbx-9"), sandboxBudgetKey("b1", "fdrsbx-9"));
28
+ assert.notEqual(sandboxBudgetKey("b1", "fdrsbx-9"), sandboxBudgetKey("b2", "fdrsbx-9"));
29
+ // #6023: a reused sandbox id on a later attempt is a new row; the same attempt replayed is the same row
30
+ assert.notEqual(sandboxBudgetKey("b1", "fdrsbx-9", 1000), sandboxBudgetKey("b1", "fdrsbx-9", 2000));
31
+ assert.equal(sandboxBudgetKey("b1", "fdrsbx-9", 1000), sandboxBudgetKey("b1", "fdrsbx-9", 1000));
32
+ });
33
+ });
@@ -0,0 +1,74 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5986: the attempts ledger in the batch runner: readmission needs a new input hash, a lifetime budget breach escalates once,
4
+ // and the ledger survives a resume (state.json) because releaseHeld never clears it.
5
+ import { describe, it } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { orchestrate } from "./orchestrate.mjs";
8
+
9
+ const memStore = () => { let st = null; return { load: () => (st ? JSON.parse(JSON.stringify(st)) : null), save: (s) => { st = JSON.parse(JSON.stringify(s)); }, log: () => {}, peek: () => st }; };
10
+ const FAIL = { terminalReason: "needs-human", code: "ci.red", detail: "ci red: same failure" };
11
+ const MERGED = { terminalReason: "merged", pr: 1 };
12
+ const seam = (h, extra = {}) => { const notes = [], mirrored = []; return { cfg: { maxAttempts: 4, maxIdentical: 2 }, hash: async () => h.v, notify: async (x) => { notes.push(x); }, mirror: async (n, l) => { mirrored.push([n, l]); }, notes, mirrored, ...extra }; };
13
+ const run = (store, a, runOne, labels = []) => {
14
+ const updates = [];
15
+ return orchestrate({ issues: [1, 2], parallel: 1, pollMs: 5, store, readBody: async (n) => (n === 2 ? "**Depends on**: #1" : ""), // 2 is held behind 1: a root with a held subtree is what the label watch readmits
16
+ attempts: a, issueLabels: async () => labels, runOne: (n, ...x) => (n === 1 ? runOne(n, ...x) : Promise.resolve(MERGED)), onUpdate: (r) => updates.push(r) }).then((rows) => ({ rows, updates }));
17
+ };
18
+
19
+ describe("#5986 attempts ledger in the batch runner", () => {
20
+ it("needs-human label removed with an unchanged input hash: not readmitted, loop.no_new_input, label kept", async () => {
21
+ const store = memStore(), h = { v: "H1" }, a = seam(h);
22
+ await run(store, a, async () => FAIL);
23
+ let ran = 0;
24
+ const r = await run(store, a, async () => { ran++; return MERGED; });
25
+ assert.equal(ran, 0, "no lane ran");
26
+ assert.equal(r.rows[0].outcome, "needs-human");
27
+ assert.ok(r.updates.some((u) => u.code === "loop.no_new_input"), JSON.stringify(r.updates));
28
+ const refused = a.notes.filter((n) => n.code === "loop.no_new_input");
29
+ assert.equal(refused.length, 1);
30
+ assert.equal(refused[0].relabel, true, "the needs-human label is put back");
31
+ });
32
+
33
+ it("a changed input hash readmits the issue", async () => {
34
+ const store = memStore(), h = { v: "H1" }, a = seam(h);
35
+ await run(store, a, async () => FAIL);
36
+ h.v = "H2";
37
+ const r = await run(store, a, async () => MERGED);
38
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["merged", "merged"], "root and its held dependent");
39
+ });
40
+
41
+ it("the 3rd identical-signature failure escalates once and stops; counters survive resumes (state.json)", async () => {
42
+ const store = memStore(), h = { v: "H1" }, a = seam(h);
43
+ await run(store, a, async () => FAIL);
44
+ h.v = "H2"; await run(store, a, async () => FAIL);
45
+ assert.equal(a.notes.filter((n) => n.code === "escalate").length, 0);
46
+ h.v = "H3"; const third = await run(store, a, async () => FAIL);
47
+ assert.equal(third.rows[0].outcome, "needs-human");
48
+ assert.equal(a.notes.filter((n) => n.code === "escalate").length, 1, "one escalation");
49
+ assert.equal(store.peek().attempts[1].attempts, 3);
50
+ assert.equal(store.peek().attempts[1].signatures.length, 3);
51
+ let ran = 0;
52
+ const again = await run(store, a, async () => { ran++; return MERGED; }); // same hash H3, label removed
53
+ assert.equal(ran, 0);
54
+ assert.equal(again.rows[0].outcome, "needs-human");
55
+ assert.equal(a.notes.filter((n) => n.code === "escalate").length, 1, "still one escalation");
56
+ h.v = "H4";
57
+ assert.equal((await run(store, a, async () => MERGED)).rows[0].outcome, "merged", "a new input hash readmits");
58
+ });
59
+
60
+ it("an engine-error that breaches the lifetime attempts cap ends needs-human (escalated)", async () => {
61
+ const store = memStore(), h = { v: "H1" }, a = seam(h, { cfg: { maxAttempts: 1, maxIdentical: 5 } });
62
+ const r = await run(store, a, async () => ({ terminalReason: "engine-error", detail: "boom" }));
63
+ assert.equal(r.rows[0].outcome, "needs-human");
64
+ assert.equal(a.notes.filter((n) => n.code === "escalate").length, 1);
65
+ });
66
+
67
+ it("no seam or no ledger admits (a merged-first-try issue sees nothing)", async () => {
68
+ const a = seam({ v: "H1" });
69
+ const r = await run(memStore(), a, async () => MERGED);
70
+ assert.equal(r.rows[0].outcome, "merged");
71
+ assert.equal(a.notes.length, 0);
72
+ assert.equal((await run(memStore(), null, async () => MERGED)).rows[0].outcome, "merged");
73
+ });
74
+ });
@@ -275,6 +275,23 @@ describe("#5859 agent restart: correlated sandbox loss is sandbox.lost, not engi
275
275
  assert.ok(probes >= 3, "admission waited for the agent's healthy probe");
276
276
  });
277
277
 
278
+ // #5967 R5/R8: a host-memory OOM restart of the agent VM ends N sandboxes together; the VM-restart class is sandbox.lost (not a second pool.vm_restart code).
279
+ it("N sandboxes ending together on an agent VM restart are sandbox.lost deferrals, no breaker trip (#5967)", async () => {
280
+ const issues = [1, 2, 3, 4, 5];
281
+ const script = Object.fromEntries(issues.map((n) => [n, [LOST(n), MERGED]]));
282
+ const store = memStore();
283
+ let probes = 0;
284
+ const r = await harness({ script, issues, parallel: 5, store, envHold: undefined,
285
+ extra: { envHold: null, breaker: BREAKER, remote: { agentHealthy: async () => ++probes > 1 } } });
286
+ assert.ok(!r.updates.some((u) => u.outcome === "breaker"));
287
+ assert.deepEqual([...new Set(r.updates.filter((u) => u.code === "sandbox.lost").map((u) => u.issue))].sort((x, y) => x - y), issues);
288
+ assert.ok(!r.updates.some((u) => u.code === "engine-error"));
289
+ const st = store.load();
290
+ assert.deepEqual(st.errorTimes, []);
291
+ assert.equal(st.breaker, null);
292
+ for (const n of issues) assert.equal(r.byIssue[n].outcome, "merged");
293
+ });
294
+
278
295
  it("agent restart: failure after healthy is an ordinary engine-error", async () => {
279
296
  const store = memStore();
280
297
  const r = await harness({ script: { 1: [LOST(1), LOST(1), MERGED], 2: [LOST(2), MERGED], 3: [LOST(3), MERGED] }, issues: [1, 2, 3], parallel: 3, store,