forgedock 1.61.2 → 1.62.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 (131) hide show
  1. package/bin/config-schema.mjs +10 -1
  2. package/bin/engine/outcome-codes.mjs +4 -0
  3. package/bin/engine-cli.mjs +159 -17
  4. package/bin/env/env.mjs +6 -4
  5. package/bin/forge-home-check.mjs +91 -0
  6. package/bin/forgedock.mjs +50 -7
  7. package/bin/gc.mjs +2 -0
  8. package/bin/hooks/pre-tool-use.mjs +4 -0
  9. package/bin/journey.mjs +55 -5
  10. package/bin/lean/admission.mjs +16 -5
  11. package/bin/lean/batch-health.mjs +55 -16
  12. package/bin/lean/batch-health.test.mjs +67 -1
  13. package/bin/lean/batch.mjs +8 -0
  14. package/bin/lean/batch.test.mjs +5 -0
  15. package/bin/lean/ceiling.mjs +20 -0
  16. package/bin/lean/ceiling.test.mjs +33 -2
  17. package/bin/lean/ci-gate.mjs +240 -0
  18. package/bin/lean/ci-gate.test.mjs +227 -0
  19. package/bin/lean/ci-precheck.mjs +178 -0
  20. package/bin/lean/ci-precheck.test.mjs +149 -0
  21. package/bin/lean/conformance.mjs +85 -9
  22. package/bin/lean/conformance.test.mjs +155 -3
  23. package/bin/lean/context.test.mjs +7 -6
  24. package/bin/lean/dag.mjs +128 -0
  25. package/bin/lean/dag.test.mjs +131 -0
  26. package/bin/lean/decisions.mjs +5 -4
  27. package/bin/lean/decisions.test.mjs +11 -0
  28. package/bin/lean/delguard.mjs +84 -0
  29. package/bin/lean/delguard.test.mjs +104 -0
  30. package/bin/lean/depcache.mjs +125 -17
  31. package/bin/lean/depcache.test.mjs +111 -0
  32. package/bin/lean/design-gate.mjs +5 -5
  33. package/bin/lean/design-gate.test.mjs +14 -0
  34. package/bin/lean/effects.mjs +72 -4
  35. package/bin/lean/execution.mjs +41 -7
  36. package/bin/lean/execution.test.mjs +99 -3
  37. package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
  38. package/bin/lean/guardgate.mjs +30 -7
  39. package/bin/lean/guardgate.test.mjs +44 -1
  40. package/bin/lean/guards.test.mjs +1 -1
  41. package/bin/lean/heavy.test.mjs +87 -0
  42. package/bin/lean/hotarea.mjs +73 -0
  43. package/bin/lean/hotarea.test.mjs +73 -0
  44. package/bin/lean/issuewatch-reconcile.mjs +20 -1
  45. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  46. package/bin/lean/lanecheck.mjs +27 -3
  47. package/bin/lean/lanecheck.test.mjs +47 -5
  48. package/bin/lean/laneconfine.mjs +83 -0
  49. package/bin/lean/laneconfine.test.mjs +113 -0
  50. package/bin/lean/lean.mjs +376 -79
  51. package/bin/lean/lean.test.mjs +710 -22
  52. package/bin/lean/live-reconcile.mjs +169 -0
  53. package/bin/lean/live-reconcile.test.mjs +176 -0
  54. package/bin/lean/orchestrate-envhold.test.mjs +245 -0
  55. package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
  56. package/bin/lean/orchestrate.mjs +207 -17
  57. package/bin/lean/outcomeevidence.mjs +104 -0
  58. package/bin/lean/outcomeevidence.test.mjs +78 -0
  59. package/bin/lean/page-capture.mjs +68 -0
  60. package/bin/lean/page-capture.test.mjs +44 -0
  61. package/bin/lean/pagegate.mjs +46 -7
  62. package/bin/lean/pagegate.test.mjs +66 -1
  63. package/bin/lean/postdeploy-check.mjs +18 -4
  64. package/bin/lean/postdeploy-check.test.mjs +32 -1
  65. package/bin/lean/prefilter.mjs +36 -4
  66. package/bin/lean/prefilter.test.mjs +31 -1
  67. package/bin/lean/preflight.mjs +22 -0
  68. package/bin/lean/preflight.test.mjs +19 -1
  69. package/bin/lean/probe.mjs +18 -0
  70. package/bin/lean/probe.test.mjs +40 -0
  71. package/bin/lean/prompts.mjs +40 -3
  72. package/bin/lean/recovery.test.mjs +20 -0
  73. package/bin/lean/recurrence.mjs +133 -0
  74. package/bin/lean/recurrence.test.mjs +99 -0
  75. package/bin/lean/release-config.mjs +2 -1
  76. package/bin/lean/release-config.test.mjs +18 -0
  77. package/bin/lean/release-control.mjs +4 -2
  78. package/bin/lean/release-control.test.mjs +15 -0
  79. package/bin/lean/release-merge-hold.mjs +65 -0
  80. package/bin/lean/release-merge-hold.test.mjs +69 -0
  81. package/bin/lean/release-review.mjs +26 -9
  82. package/bin/lean/release-review.test.mjs +53 -0
  83. package/bin/lean/release-status.mjs +3 -1
  84. package/bin/lean/release-status.test.mjs +11 -0
  85. package/bin/lean/release.test.mjs +26 -1
  86. package/bin/lean/render.mjs +8 -7
  87. package/bin/lean/routing.mjs +49 -0
  88. package/bin/lean/routing.test.mjs +54 -1
  89. package/bin/lean/run-issue-placement.test.mjs +30 -1
  90. package/bin/lean/sandbox-actions.mjs +121 -0
  91. package/bin/lean/sandbox-actions.test.mjs +94 -0
  92. package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
  93. package/bin/lean/sandbox-remote.mjs +3 -1
  94. package/bin/lean/schedd-health.mjs +14 -2
  95. package/bin/lean/schedd-health.test.mjs +13 -0
  96. package/bin/lean/schedd.mjs +43 -17
  97. package/bin/lean/schedd.test.mjs +61 -1
  98. package/bin/lean/toolchain.mjs +16 -6
  99. package/bin/lean/toolplace.mjs +12 -0
  100. package/bin/lean/weakguard.mjs +105 -0
  101. package/bin/lean/weakguard.test.mjs +59 -0
  102. package/bin/lean/winspawn.mjs +61 -0
  103. package/bin/lean/winspawn.test.mjs +45 -0
  104. package/bin/lean/worktree.mjs +3 -1
  105. package/bin/lean/worktree.test.mjs +11 -0
  106. package/bin/pool/agent.mjs +210 -14
  107. package/bin/pool/cache-sweep.mjs +74 -0
  108. package/bin/pool/cli.mjs +11 -3
  109. package/bin/pool/docker.mjs +33 -2
  110. package/bin/pool/health.mjs +38 -0
  111. package/bin/pool/lane-tools.mjs +23 -4
  112. package/bin/pool/lane-tools.test.mjs +12 -1
  113. package/bin/pool/router.mjs +21 -3
  114. package/bin/runner.mjs +37 -0
  115. package/bin/splash-scene.mjs +356 -0
  116. package/bin/win-hide-children.mjs +114 -0
  117. package/commands/orchestrate.md +18 -27
  118. package/commands/review-pr-agents/infra.md +1 -0
  119. package/commands/review-pr-staging.md +2 -2
  120. package/docs/CONFIG.md +60 -3
  121. package/docs/OUTCOME-CODES.md +3 -0
  122. package/package.json +1 -1
  123. package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
  124. package/plugins/forgedock-splash/README.md +1 -1
  125. package/plugins/forgedock-splash/hooks/scene.ts +142 -8
  126. package/pool/README.md +6 -0
  127. package/pool/image/entrypoint.sh +1 -0
  128. package/scripts/check-spec-size.sh +3 -1
  129. package/scripts/gen-splash-scene.mjs +24 -0
  130. package/scripts/review-staging-pre.sh +8 -3
  131. package/scripts/review-staging-pre.test.sh +2 -0
package/bin/forgedock.mjs CHANGED
@@ -2,6 +2,8 @@
2
2
  // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
3
3
  // SPDX-License-Identifier: AGPL-3.0-or-later
4
4
 
5
+ // Must stay the first import: defaults windowsHide for detached/background runs on Windows (see module).
6
+ import "./win-hide-children.mjs";
5
7
  import { fileURLToPath } from "url";
6
8
  import { dirname, join, relative, resolve, sep } from "path";
7
9
  import { mkdir, lstat, readlink, readdir, unlink, readFile, writeFile } from "fs/promises";
@@ -93,6 +95,7 @@ import { checkContext, refreshContextFlow } from "./review-context.mjs";
93
95
  import { runConfigCommand } from "./config-history.mjs";
94
96
  import { validateForgeYaml } from "./config-schema.mjs";
95
97
  import { botTokenStatus } from "./bot-token-status.mjs";
98
+ import { assessForgeHome, isProblem as forgeHomeIsProblem, describe as describeForgeHome, readUserForgeHomeWin, clearUserForgeHomeWin, hookScriptTree } from "./forge-home-check.mjs";
96
99
  import { applyAuthEnv, startAuthRefresh, doctorAppAuth, AUTH_REFRESH_COMMANDS } from "./auth/app-token.mjs";
97
100
  import {
98
101
  parseNameStatusDiff,
@@ -1434,6 +1437,17 @@ async function uninstall() {
1434
1437
  );
1435
1438
  }
1436
1439
  }
1440
+ // Windows keeps FORGE_HOME in the user environment, which the profile cleanup above never sees (#5796).
1441
+ if (process.platform === "win32") {
1442
+ const userValue = readUserForgeHomeWin();
1443
+ if (!userValue) {
1444
+ console.log(` ✔ No FORGE_HOME in the Windows user environment — nothing to remove`);
1445
+ } else if (clearUserForgeHomeWin()) {
1446
+ console.log(` ${GREEN}✔${RESET} Removed FORGE_HOME (${CYAN}${userValue}${RESET}) from the Windows user environment`);
1447
+ } else {
1448
+ console.log(` ${YELLOW}⚠${RESET} Could not remove FORGE_HOME from the Windows user environment — run: [Environment]::SetEnvironmentVariable('FORGE_HOME', $null, 'User')`);
1449
+ }
1450
+ }
1437
1451
  console.log("");
1438
1452
 
1439
1453
  // Remove .forgedock marker file from cwd (created by `npx forgedock enable`)
@@ -2483,7 +2497,7 @@ async function doctor(fix = false, verbose = false) {
2483
2497
  * "already registered" regardless of whether its script path still
2484
2498
  * resolves, so a dangling entry must be explicitly cleared before forge()
2485
2499
  * will register a fresh one. (forge#1895)
2486
- * @returns {{state: 'ok'|'no-entry'|'unparseable'|'dangling'|'error', path: (string|null), command?: string, ephemeral?: boolean, error: (string|null)}}
2500
+ * @returns {{state: 'ok'|'foreign'|'no-entry'|'unparseable'|'dangling'|'error', path: (string|null), command?: string, ephemeral?: boolean, error: (string|null)}}
2487
2501
  */
2488
2502
  function detectSessionStartHookPath() {
2489
2503
  try {
@@ -2512,7 +2526,9 @@ async function doctor(fix = false, verbose = false) {
2512
2526
  return { state: "unparseable", path: null, command: hookCommand, error: null };
2513
2527
  }
2514
2528
  if (existsSync(hookScriptPath)) {
2515
- return { state: "ok", path: hookScriptPath, error: null };
2529
+ // Exists, but may belong to an old checkout rather than the active install (#5796).
2530
+ const tree = hookScriptTree({ scriptPath: hookScriptPath, sourceDir: FORGE_HOME, persistedHome: join(HOME, ".forge") });
2531
+ return { state: tree === "foreign" ? "foreign" : "ok", path: hookScriptPath, error: null };
2516
2532
  }
2517
2533
  return {
2518
2534
  state: "dangling",
@@ -2552,7 +2568,7 @@ async function doctor(fix = false, verbose = false) {
2552
2568
  console.log(` ${CYAN}↻${RESET} Repairing command links + SessionStart hook...`);
2553
2569
  try {
2554
2570
  const staleHook = detectSessionStartHookPath();
2555
- if (staleHook.state === "dangling") {
2571
+ if (staleHook.state === "dangling" || staleHook.state === "foreign") {
2556
2572
  removeSessionStartHook(settingsPath);
2557
2573
  }
2558
2574
  await forge(ctx());
@@ -2910,7 +2926,7 @@ async function doctor(fix = false, verbose = false) {
2910
2926
  {
2911
2927
  let hookPathResult = detectSessionStartHookPath();
2912
2928
  let hookPathWasBroken = false;
2913
- if (hookPathResult.state === "dangling" && fix) {
2929
+ if ((hookPathResult.state === "dangling" || hookPathResult.state === "foreign") && fix) {
2914
2930
  hookPathWasBroken = true;
2915
2931
  await runInstallRepairOnce();
2916
2932
  hookPathResult = detectSessionStartHookPath();
@@ -2926,6 +2942,11 @@ async function doctor(fix = false, verbose = false) {
2926
2942
  "SessionStart hook script path",
2927
2943
  `Could not parse a script path out of the registered hook command ("${hookPathResult.command}"). Run: npx forgedock install`,
2928
2944
  );
2945
+ } else if (hookPathResult.state === "foreign") {
2946
+ warn(
2947
+ "SessionStart hook script path",
2948
+ `${hookPathResult.path} is outside the active ForgeDock install (${FORGE_HOME}) and ~/.forge — the hook runs a different tree. Run: npx forgedock doctor --fix (or: npx forgedock install)`,
2949
+ );
2929
2950
  } else if (hookPathResult.state === "ok") {
2930
2951
  if (fix && hookPathWasBroken) {
2931
2952
  fixed("SessionStart hook script path", `refreshed to a valid path (${hookPathResult.path})`);
@@ -3179,8 +3200,19 @@ async function doctor(fix = false, verbose = false) {
3179
3200
  // value is a warning, not a failure.
3180
3201
  {
3181
3202
  const envForgeHome = process.env.FORGE_HOME;
3182
- if (envForgeHome) {
3183
- pass("FORGE_HOME env var", `set to "${envForgeHome}"`);
3203
+ const fh = assessForgeHome({ value: envForgeHome, sourceDir: FORGE_HOME, sourceVersion: getVersion(), persistedHome: join(HOME, ".forge") });
3204
+ if (forgeHomeIsProblem(fh)) {
3205
+ // A stale value is never "informational": forge-resolve.sh ranks FORGE_HOME above ~/.forge (#5796).
3206
+ const userValue = process.platform === "win32" ? readUserForgeHomeWin() : null;
3207
+ if (fix && userValue && clearUserForgeHomeWin()) {
3208
+ fixed("Stale FORGE_HOME", `cleared from the Windows user environment (was "${userValue}") — open a new terminal`);
3209
+ } else {
3210
+ warn("Stale FORGE_HOME", `${describeForgeHome(fh, envForgeHome, getVersion())}. ${
3211
+ userValue ? "Fix: npx forgedock doctor --fix (clears it from the Windows user environment)"
3212
+ : "Fix: remove the FORGE_HOME export from your shell profile / environment"}`);
3213
+ }
3214
+ } else if (envForgeHome) {
3215
+ pass("FORGE_HOME env var", fh.state === "current" ? `set to "${envForgeHome}" (this install)` : `set to "${envForgeHome}" (v${fh.version}, matches)`);
3184
3216
  } else {
3185
3217
  warn(
3186
3218
  "FORGE_HOME env var",
@@ -3982,7 +4014,7 @@ async function watch() {
3982
4014
  const SPLASH_COMMANDS = new Set(["run", "bootstrap", "run-issue", "orchestrate", "triage", "probe", "gc", "resume-stalled", "demo", "first-run", "doctor", "watch", "help", "--help", "-h"]);
3983
4015
  const KNOWN_COMMANDS = new Set([
3984
4016
  "install", "init", "enable", "disable", "status", "uninstall", "update",
3985
- "run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "acceptance", "interfaces", "docs", "review-staging", "release", "intake", "gc", "env", "sandbox", "resume-stalled", "demo", "first-run", "doctor", "auth", "watch", "issue-watch", "prod-watch", "selftest", "labels", "config", "stats", "limits", "decisions", "sched", "schedd", "pool", "check", "guide", "help", "--help", "-h",
4017
+ "run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "close", "acceptance", "interfaces", "docs", "review-staging", "release", "intake", "gc", "env", "sandbox", "resume-stalled", "demo", "first-run", "doctor", "auth", "watch", "issue-watch", "prod-watch", "selftest", "labels", "config", "stats", "limits", "decisions", "sched", "schedd", "pool", "check", "guide", "help", "--help", "-h",
3986
4018
  "ci-step", "ci-hook", "tests",
3987
4019
  "version", "--version", "-v",
3988
4020
  ]);
@@ -4499,6 +4531,17 @@ switch (command) {
4499
4531
  }
4500
4532
  break;
4501
4533
  }
4534
+ case "close": { // #5704: `forgedock close reconcile [--repo R] [--dry-run]`
4535
+ const { closeReconcileFromCli } = await import("./engine-cli.mjs");
4536
+ try {
4537
+ await closeReconcileFromCli(restArgs);
4538
+ } catch (err) {
4539
+ process.stderr.write(`${RED}${err.message}${RESET}
4540
+ `);
4541
+ exitCode = 1;
4542
+ }
4543
+ break;
4544
+ }
4502
4545
  case "probe": {
4503
4546
  const { probeFromCli } = await import("./engine-cli.mjs");
4504
4547
  try {
package/bin/gc.mjs CHANGED
@@ -333,6 +333,7 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
333
333
  try {
334
334
  const vols = jsonLines(await P.docker(["volume", "ls", "--format", "{{json .}}"]));
335
335
  const created = new Map();
336
+ const poolCache = (v) => parseLabels(v.Labels)["computeshare.cache"] === "1"; // #5757: pool cache volumes, the agent evicts them
336
337
  const labelled = vols.filter((v) => { const l = parseLabels(v.Labels); return l["forgedock.owner"] === "1" || LANE_COMPOSE_RE.test(String(l["com.docker.compose.project"] ?? "")); }).map((v) => v.Name);
337
338
  if (labelled.length) {
338
339
  try { for (const l of String(await P.docker(["volume", "inspect", "--format", "{{.Name}}\t{{.CreatedAt}}", ...labelled])).split("\n")) { const [n, t] = l.split("\t"); if (n) created.set(n, Date.parse(t)); } }
@@ -340,6 +341,7 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
340
341
  }
341
342
  for (const v of vols) {
342
343
  if (!v.Name || seen.has(`volume:${v.Name}`) || liveIds.has(`volume:${v.Name}`)) continue;
344
+ if (poolCache(v)) { add({ type: "volume", id: v.Name, sizeBytes: null, ageMs: null, owned: false, action: "report", reason: "pool cache volume (computeshare.cache=1); the pool agent evicts it" }); continue; }
343
345
  add({ type: "volume", id: v.Name, sizeBytes: null, ageMs: age(created.get(v.Name)), ...ownedBy(parseLabels(v.Labels), created.get(v.Name), "volume") });
344
346
  }
345
347
  } catch (e) { notes.push(`docker volumes unavailable: ${errText(e)}`); }
@@ -824,6 +824,10 @@ async function checkPrTarget(command) {
824
824
  if (head && /^staging$/.test(head)) {
825
825
  return null; // deploy flow — allowed
826
826
  }
827
+ // #5709: a snapshot release branch (release/<id>, cut by the snapshot-release path) is also a deploy head.
828
+ if (head && /^release\/[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9._-]+)*$/.test(head)) {
829
+ return null;
830
+ }
827
831
 
828
832
  return [
829
833
  `[ForgeDock] BLOCKED: PR targets "${base}" — pipeline rule violation.`,
package/bin/journey.mjs CHANGED
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { existsSync, lstatSync, readFileSync, writeFileSync, renameSync, unlinkSync } from "fs";
14
14
  import { join, basename } from "path";
15
+ import { assessForgeHome, isProblem as forgeHomeIsProblem, describe as describeForgeHome } from "./forge-home-check.mjs";
15
16
  import { backupToHistory } from "./config-history.mjs";
16
17
 
17
18
  // ---------------------------------------------------------------------------
@@ -717,6 +718,42 @@ export function makeCtx(overrides = {}) {
717
718
 
718
719
  const dimLine = (ctx, s) => (ctx.mode === "none" ? s : `\x1b[2m${s}\x1b[22m`);
719
720
 
721
+ /**
722
+ * Play the forgedock-splash scene (Clawd bonks the F; bin/splash-scene.mjs, generated from the plugin's
723
+ * scene.ts) in place, then erase it so the settled banner takes its spot. Interactive truecolor terminals
724
+ * only; skipped by --fast / --no-splash / FORGEDOCK_NO_SPLASH=1. Never throws. Returns true when it played.
725
+ */
726
+ export async function introScene(ctx, { load = () => import("./splash-scene.mjs"), wait = sleep } = {}) {
727
+ const w = ctx.stdout;
728
+ if (!ctx.motion || ctx.mode !== "truecolor") return false;
729
+ if (ctx.env?.FORGEDOCK_NO_SPLASH === "1" || ctx.argv?.includes("--no-splash")) return false;
730
+ let s;
731
+ try { s = await load(); } catch { return false; }
732
+ if ((w.columns ?? 0) < s.MIN_COLUMNS + 2 || (w.rows ?? 0) < s.MIN_ROWS + 2) return false;
733
+ s.setTheme(false);
734
+ const fg = (hex) => `\x1b[38;2;${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}m`;
735
+ const restore = () => w.write("\x1b[?25h");
736
+ process.once("exit", restore);
737
+ let height = 0;
738
+ try {
739
+ w.write("\x1b[?25l");
740
+ for (let f = 0; f <= s.LAST; f++) {
741
+ const rows = s.scene(f).map((runs) => " " + runs.map((r) => `${r.color ? fg(r.color) : ""}${r.bold ? "\x1b[1m" : ""}${r.text}\x1b[0m`).join("") + "\x1b[K");
742
+ if (height) w.write(`\x1b[${height}A\r`);
743
+ w.write(rows.join("\n") + "\n");
744
+ height = rows.length;
745
+ await wait(s.TICK);
746
+ }
747
+ return true;
748
+ } catch {
749
+ return false;
750
+ } finally {
751
+ if (height) w.write(`\x1b[${height}A\r\x1b[J`);
752
+ restore();
753
+ process.removeListener("exit", restore);
754
+ }
755
+ }
756
+
720
757
  /**
721
758
  * Render the hero banner and run preflight checks. Failures render fix cards
722
759
  * and the journey continues — advisory, never fatal. Includes informational
@@ -727,7 +764,9 @@ const dimLine = (ctx, s) => (ctx.mode === "none" ? s : `\x1b[2m${s}\x1b[22m`);
727
764
  export async function preflight(ctx) {
728
765
  const { stdout: w } = ctx;
729
766
  w.write("\n");
730
- await shimmer(HERO_MARK, CHROME_STOPS, { mode: ctx.mode, motion: ctx.motion, writer: w });
767
+ // Open with the startup-splash scene, then settle on the static mark; the shimmer stays the fallback.
768
+ const played = await introScene(ctx);
769
+ await shimmer(HERO_MARK, CHROME_STOPS, { mode: ctx.mode, motion: played ? false : ctx.motion, writer: w });
731
770
  w.write("\n " + ember("F O R G E D O C K", ctx.mode) + "\n");
732
771
  w.write(" " + dimLine(ctx, `──── ${getLogoTagline("install")} ────────────────────`) + "\n\n");
733
772
 
@@ -2194,6 +2233,17 @@ function renderForgeReceipt(ctx, results) {
2194
2233
  w.write(` ${glyph(true)} SessionStart hook ${hookStatus === "already" ? "active" : "registered"} ${dimLine(ctx, settingsPath)}\n`);
2195
2234
  }
2196
2235
 
2236
+ // Stale FORGE_HOME (#5796): a leftover value from an old checkout outranks ~/.forge in forge-resolve.sh.
2237
+ if (process.env.FORGE_HOME) {
2238
+ let ver = ctx.persistHomeResult?.version || "";
2239
+ if (!ver) { try { ver = JSON.parse(readFileSync(join(ctx.forgeHome, "package.json"), "utf8")).version || ""; } catch { /* unknown */ } }
2240
+ const fh = assessForgeHome({ value: process.env.FORGE_HOME, sourceDir: ctx.forgeHome, sourceVersion: ver, persistedHome: join(os.homedir(), ".forge") });
2241
+ if (forgeHomeIsProblem(fh)) {
2242
+ w.write(` ${glyph(false)} stale FORGE_HOME ${dimLine(ctx, `${describeForgeHome(fh, process.env.FORGE_HOME, ver)} — run: npx forgedock doctor --fix`)}
2243
+ `);
2244
+ }
2245
+ }
2246
+
2197
2247
  // Persisted-home / ephemeral-cache advisory (forge#1895, extended #1943):
2198
2248
  // runJourney() calls persistHome(ctx) right before forge() and stashes its
2199
2249
  // result on ctx.persistHomeResult; when persistHome() actually ran (i.e.
@@ -2823,14 +2873,14 @@ export async function connect(ctx) {
2823
2873
  if (yes) {
2824
2874
  ctx.openFn(GITHUB_APP_URL);
2825
2875
  w.write(
2826
- ` \x1b[38;2;255;179;71m✔\x1b[0m Opening ${GITHUB_APP_URL}\n` +
2827
- ` ${ctx.mode === "none" ? "" : "\x1b[2m"}This registers the app only — it does not create a bot token yet.\x1b[22m\n` +
2828
- ` ${ctx.mode === "none" ? "" : "\x1b[2m"}Pipeline commands keep using your personal \`gh\` auth. See docs/CONFIG.md.\x1b[22m\n`,
2876
+ ` ${ctx.mode === "none" ? "✔" : "\x1b[38;2;255;179;71m✔\x1b[0m"} Opening ${GITHUB_APP_URL}\n` +
2877
+ ` ${dimLine(ctx, "This registers the app only — it does not create a bot token yet.")}\n` +
2878
+ ` ${dimLine(ctx, "Pipeline commands keep using your personal `gh` auth. See docs/CONFIG.md.")}\n`,
2829
2879
  );
2830
2880
  return { opened: true };
2831
2881
  }
2832
2882
 
2833
- w.write(` ${ctx.mode === "none" ? "" : "\x1b[2m"}Skipped — install anytime: ${GITHUB_APP_URL}\x1b[22m\n`);
2883
+ w.write(` ${dimLine(ctx, `Skipped — install anytime: ${GITHUB_APP_URL}`)}\n`);
2834
2884
  return { opened: false };
2835
2885
  }
2836
2886
 
@@ -6,7 +6,8 @@
6
6
  */
7
7
  // #4169: load average lags by minutes and is phase-blind, so it is off unless configured; heavy steps are gated by
8
8
  // the host heavy-step semaphore (heavy.mjs) instead. An explicit `max_load_per_core` is still honoured.
9
- export const ADMISSION_DEFAULTS = Object.freeze({ enabled: true, min_free_mem_mb: 2048, min_free_tmp_mb: 1024, max_load_per_core: null, lane_cpu_reservation: 1, lane_mem_mb: 2048 });
9
+ export const ADMISSION_DEFAULTS = Object.freeze({ enabled: true, min_free_mem_mb: 2048, min_free_tmp_mb: 1024, max_load_per_core: null, lane_cpu_reservation: 1, lane_mem_mb: 2048, ramp_s: 60, max_new_per_ramp: 4 });
10
+ // #5845: lanes admitted within `ramp_s` have not grown yet; `host.rampingMb/rampingLanes/laneFootprintMb` (effects.mjs) expose them. null `max_new_per_ramp` = no rate limit.
10
11
  export const ADMISSION_RETRY_SECONDS = 60;
11
12
 
12
13
  /** Workers one verification step may use (#4182): max(1, floor(cores / lanes)); bad inputs count as 1. Heavy shims pass live heavy holders (#4169). */
@@ -21,20 +22,20 @@ export function hostParallelism({ cores, lanes } = {}) {
21
22
  * admission attempt, so it follows the host as lanes come and go; an unknown probe leaves that bound off, and with both
22
23
  * unknown (or admission disabled) it is null (no derived cap).
23
24
  */
24
- export function localLaneCap({ cfg = {}, cores, memAvailableMb } = {}) {
25
+ export function localLaneCap({ cfg = {}, cores, memAvailableMb, rampingMb = 0 } = {}) {
25
26
  const c = { ...ADMISSION_DEFAULTS, ...Object.fromEntries(Object.entries(cfg ?? {}).filter(([, v]) => v !== undefined && v !== null)) };
26
27
  if (c.enabled === false) return null;
27
28
  const pos = (v, d) => (Number.isFinite(v) && v > 0 ? v : d);
28
29
  const bounds = [];
29
30
  if (Number.isFinite(cores) && cores > 0) bounds.push(Math.floor(cores / pos(c.lane_cpu_reservation, 1)));
30
- if (Number.isFinite(memAvailableMb)) bounds.push(Math.floor((memAvailableMb - pos(c.min_free_mem_mb, 0)) / pos(c.lane_mem_mb, 2048)));
31
+ if (Number.isFinite(memAvailableMb)) bounds.push(Math.floor((memAvailableMb - (Number.isFinite(rampingMb) && rampingMb > 0 ? rampingMb : 0) - pos(c.min_free_mem_mb, 0)) / pos(c.lane_mem_mb, 2048)));
31
32
  return bounds.length ? Math.max(1, Math.min(...bounds)) : null;
32
33
  }
33
34
 
34
35
  const gb = (mb) => { const g = mb / 1024; return `${Number.isInteger(g) ? g : g.toFixed(1)}G`; };
35
36
 
36
37
  /**
37
- * @param {{cfg?: object, host: {memAvailableMb?: Function, freeMb?: Function, loadAvg1?: Function, cores?: Function, tmpPaths?: Function}}} p
38
+ * @param {{cfg?: object, host: {memAvailableMb?: Function, rampingMb?: Function, rampingLanes?: Function, laneFootprintMb?: Function, freeMb?: Function, loadAvg1?: Function, cores?: Function, tmpPaths?: Function}}} p
38
39
  * @returns {Promise<{ok: boolean, reasons: string[], detail: string}>}
39
40
  */
40
41
  export async function checkAdmission({ cfg = {}, host }) {
@@ -43,7 +44,16 @@ export async function checkAdmission({ cfg = {}, host }) {
43
44
  const reasons = [];
44
45
  const safe = async (fn, ...a) => { try { const v = await fn?.(...a); return Number.isFinite(v) ? v : null; } catch { return null; } };
45
46
  const mem = await safe(host.memAvailableMb);
47
+ const rampS = Number.isFinite(c.ramp_s) && c.ramp_s > 0 ? c.ramp_s : ADMISSION_DEFAULTS.ramp_s;
48
+ const ramping = mem === null ? null : await safe(host.rampingMb, rampS);
46
49
  if (mem !== null && mem < c.min_free_mem_mb) reasons.push(`mem ${gb(mem)} < ${gb(c.min_free_mem_mb)}`);
50
+ else if (mem !== null && ramping !== null && ramping > 0) {
51
+ const need = ((await safe(host.laneFootprintMb)) ?? c.lane_mem_mb) + c.min_free_mem_mb;
52
+ if (mem - ramping < need) reasons.push(`projected mem ${gb(mem - ramping)} (free ${gb(mem)} − ramping ${gb(ramping)}) < need ${gb(need)}`);
53
+ }
54
+ const maxNew = Number.isFinite(c.max_new_per_ramp) && c.max_new_per_ramp > 0 ? c.max_new_per_ramp : null;
55
+ const rampLanes = maxNew === null ? null : await safe(host.rampingLanes, rampS);
56
+ if (rampLanes !== null && rampLanes >= maxNew) reasons.push(`${rampLanes} lanes admitted in the last ${rampS}s >= ${maxNew}`);
47
57
  let paths = [];
48
58
  try { paths = (await host.tmpPaths?.()) ?? []; } catch { paths = []; }
49
59
  for (const p of paths) {
@@ -71,7 +81,8 @@ export async function nearCeiling({ cfg = {}, host, ratio = 0.8, minFreeGb = nul
71
81
  if (load !== null && cores && load / cores >= r * maxLoad) return true;
72
82
  if ((await diskLow({ host, minFreeGb: Number.isFinite(minFreeGb) && minFreeGb > 0 ? minFreeGb / r : null })).low) return true; // #5421
73
83
  const mem = await safe(host.memAvailableMb);
74
- if (mem !== null && mem <= c.min_free_mem_mb / r) return true;
84
+ const ramping = mem === null ? 0 : (await safe(host.rampingMb, Number.isFinite(c.ramp_s) && c.ramp_s > 0 ? c.ramp_s : ADMISSION_DEFAULTS.ramp_s)) ?? 0;
85
+ if (mem !== null && mem - Math.max(0, ramping) <= c.min_free_mem_mb / r) return true;
75
86
  let paths = [];
76
87
  try { paths = (await host.tmpPaths?.()) ?? []; } catch { paths = []; }
77
88
  for (const p of paths) { const free = await safe(host.freeMb, p); if (free !== null && free <= c.min_free_tmp_mb / r) return true; }
@@ -293,13 +293,25 @@ export async function resolvedOnGithub(cands, gh, repo) {
293
293
  return out;
294
294
  }
295
295
 
296
- export const DEFAULT_STALL_MIN = 10;
296
+ export const FIRST_HOUR_FILE = "first-hour.json";
297
+ export const BATCH_LOG_FILE = "batch.log";
298
+ export const FIRST_HOUR_MIN = 60;
299
+ export const readFirstHour = (dir) => readJson(join(dir, FIRST_HOUR_FILE));
300
+ /** Append one line to the batch's operator-readable log. Best effort. */
301
+ export const appendBatchLog = (dir, text) => { try { appendFileSync(join(dir, BATCH_LOG_FILE), `${text}\n`, { mode: 0o600 }); } catch { /* advisory */ } };
302
+
303
+ /** #5806: minutes without progress (setup reads or dispatch) before a stall is acted on; `FORGEDOCK_SCHEDD_STALL_MIN` overrides (was 10). */
304
+ export const DEFAULT_STALL_MIN = 3;
305
+ /** #5806: auto-recoveries one batch gets in total (one per distinct ready set); past it every stall alerts. */
306
+ export const MAX_STALL_RECOVERIES = 3;
307
+ /** #5745: `; admission held by <code>: <detail>` for each failing preflight gate, "" when none. Pure. */
308
+ export const holdGateDetail = (gates) => (Array.isArray(gates) ? gates : []).filter((g) => g?.code).map((g) => `; admission held by ${g.code}: ${g.detail ?? "failing"}`).join("");
297
309
  /**
298
310
  * #5314: dispatch stall. A batch with ready pending issues, free capacity and no progress for `windowMin` minutes. Ready: pending,
299
311
  * not held, no retry-at in the future, every in-batch dependency ended well. Independent of the runner (it may be dead), so the
300
- * schedd polls it. `hosted`: a runner is alive. @returns null (healthy) or `{code, ready, idleMin, hosted, detail}`. Pure.
312
+ * schedd polls it. `hosted`: a runner is alive. `gates` (#5745): the failing preflight checks `[{code, detail}]` holding admission, named in the detail. @returns null (healthy) or `{code, ready, idleMin, hosted, detail[, gates]}`. Pure.
301
313
  */
302
- export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false } = {}) {
314
+ export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false, gates = [] } = {}) {
303
315
  if (!state || cancelled || reported || lastProgressMs === null) return null;
304
316
  if (state.breaker && !state.breaker.transport) return null; // an operator --resume clears it; a re-host would stop again at once
305
317
  const order = new Set((state.order ?? []).map(Number)), results = state.results ?? {}, heldSet = new Set(held.map(Number));
@@ -309,15 +321,39 @@ export function evaluateDispatchStall(state, { held = [], parallel = null, hoste
309
321
  && (state.deps?.[n] ?? []).every((d) => !order.has(Number(d)) || Number(d) === n || GOOD_END.has(results[d]?.outcome)));
310
322
  const idleMin = Math.floor((now - lastProgressMs) / 60000);
311
323
  if (!ready.length || running >= k || idleMin < windowMin) return null;
312
- return { code: "dispatch-stalled", ready, idleMin, hosted, detail: `${ready.length} ready issue${ready.length === 1 ? "" : "s"} (${list(ready.slice(0, 8))}${ready.length > 8 ? ", …" : ""}) pending with ${k - running} free lane${k - running === 1 ? "" : "s"} and no dispatch for ${idleMin} min; ${hosted ? "the runner is alive but not dispatching" : "no runner hosts the batch"}` };
324
+ const setup = state.phase === "setup" ? ` (stuck in setup, ${Number(state.setup?.read) || 0}/${Number(state.setup?.total) || ready.length} issues read)` : "";
325
+ const gated = (Array.isArray(gates) ? gates : []).filter((g) => g?.code);
326
+ return { code: "dispatch-stalled", ready, idleMin, hosted, setup: !!setup, ...(gated.length ? { gates: gated.map((g) => g.code) } : {}), detail: `${ready.length} ready issue${ready.length === 1 ? "" : "s"} (${list(ready.slice(0, 8))}${ready.length > 8 ? ", …" : ""}) pending with ${k - running} free lane${k - running === 1 ? "" : "s"} and no ${setup ? "progress" : "dispatch"} for ${idleMin} min${setup}; ${hosted ? "the runner is alive but not dispatching" : "no runner hosts the batch"}${holdGateDetail(gated)}` };
313
327
  }
314
328
 
315
- export const FIRST_HOUR_FILE = "first-hour.json";
316
- export const BATCH_LOG_FILE = "batch.log";
317
- export const FIRST_HOUR_MIN = 60;
318
- export const readFirstHour = (dir) => readJson(join(dir, FIRST_HOUR_FILE));
319
- /** Append one line to the batch's operator-readable log. Best effort. */
320
- export const appendBatchLog = (dir, text) => { try { appendFileSync(join(dir, BATCH_LOG_FILE), `${text}\n`, { mode: 0o600 }); } catch { /* advisory */ } };
329
+ /**
330
+ * #5806: what the schedd does about a stall. `recovery` is `health.json` `stallRecovery` ({sig, at, action, count}), kept across
331
+ * daemon restarts so a restart never re-arms it; `probe` is the batch env probe (lanecheck `probeBatchEnv`), null when the
332
+ * batch pins no env. A broken env alerts at once (a resume would stall or fail the same way); the first stall of a ready set
333
+ * is recovered once (`resume` an unhosted batch, `restart-daemon` when its runner is alive but wedged); the same ready set
334
+ * stalling again, or a batch past `maxRecoveries`, alerts with the probed cause. Pure.
335
+ * @returns {{action: "resume"|"restart-daemon"|"alert", sig: string, cause: string|null}}
336
+ */
337
+ export function decideStallAction(stall, { recovery = null, probe = null, hosted = false, maxRecoveries = MAX_STALL_RECOVERIES } = {}) {
338
+ const sig = stall.ready.join(",");
339
+ if (probe && !probe.ok) return { action: "alert", sig, cause: `batch env: ${probe.detail}; fix it with --set-env <id> PATH=<dirs holding the tools>, then --resume` };
340
+ const count = Number(recovery?.count) || 0;
341
+ if (recovery?.sig === sig || count >= maxRecoveries) {
342
+ const why = recovery?.sig === sig ? `stalled again after auto-recovery (${recovery.action} at ${recovery.at})` : `${count} auto-recoveries already spent`;
343
+ return { action: "alert", sig, cause: `${why}${probe ? `; ${probe.detail}` : ""}` };
344
+ }
345
+ return { action: hosted ? "restart-daemon" : "resume", sig, cause: null };
346
+ }
347
+
348
+ /** #5806: persist one auto-recovery (`health.json` `stallRecovery`) and its decision line in `batch.log`. @returns the decision text */
349
+ export function recordStallRecovery(batch, stall, { action, sig = stall.ready.join(","), now = Date.now() } = {}) {
350
+ const prev = readHealth(batch.dir) ?? {}, at = new Date(now).toISOString();
351
+ const what = action === "restart-daemon" ? "restart the hosting schedd (its runner is alive but not progressing)" : "resume the batch (no runner hosts it)";
352
+ const text = `FORGE:DECISION batch ${batch.id} stall-recovery: ${what}; why: ${stall.detail}; alternative: alert only (a repeat of this stall alerts instead)`;
353
+ try { writeHealth(batch.dir, { ...prev, stallRecovery: { sig, at, action, count: (Number(prev.stallRecovery?.count) || 0) + 1, detail: stall.detail } }); } catch { /* advisory */ }
354
+ appendBatchLog(batch.dir, `${at} ${text}`);
355
+ return text;
356
+ }
321
357
 
322
358
  /** The first-hour report of one batch: dispatched / running / merged / stuck, and why. Pure. */
323
359
  export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null, holdInfo = null } = {}) {
@@ -340,14 +376,17 @@ export function writeFirstHour(batch, report) {
340
376
  return true;
341
377
  }
342
378
 
343
- /** The one needs-you item of a stall: recorded in `health.json` (shown by status) per distinct ready set. @returns true when newly raised */
344
- export function recordStallAlert(batch, stall, { now = Date.now() } = {}) {
379
+ /**
380
+ * The one needs-you item of a stall: recorded in `health.json` (shown by status) per distinct ready set. #5806: `cause` is the
381
+ * probed reason (a broken batch env, a repeat after auto-recovery), on its own `probed:` line. @returns true when newly raised
382
+ */
383
+ export function recordStallAlert(batch, stall, { now = Date.now(), cause = null } = {}) {
345
384
  const sig = stall.ready.join(","), prev = readHealth(batch.dir) ?? {};
346
385
  if (prev.stall?.sig === sig) return false;
347
386
  const at = new Date(now).toISOString();
348
- const text = `BATCH UNHEALTHY ${batch.id} (dispatch-stalled)\n cause: dispatch-stalled: ${stall.detail}\n recovery:\n forgedock orchestrate --resume ${batch.id}\n forgedock orchestrate --cancel ${batch.id}`;
349
- try { writeHealth(batch.dir, { ...prev, stall: { at, sig, detail: stall.detail }, ...(prev.alertedAt ? {} : { alertedAt: at, alert: text }) }); } catch { return false; }
350
- appendBatchLog(batch.dir, `${at} ${text.split("\n").slice(0, 2).join(" | ")}`);
387
+ const text = `BATCH UNHEALTHY ${batch.id} (dispatch-stalled)\n cause: dispatch-stalled: ${stall.detail}${cause ? `\n probed: ${cause}` : ""}\n recovery:\n forgedock orchestrate --resume ${batch.id}\n forgedock orchestrate --cancel ${batch.id}`;
388
+ try { writeHealth(batch.dir, { ...prev, stall: { at, sig, detail: stall.detail, ...(cause ? { cause } : {}) }, ...(prev.alertedAt ? {} : { alertedAt: at, alert: text }) }); } catch { return false; }
389
+ appendBatchLog(batch.dir, `${at} ${text.split("\n").slice(0, cause ? 3 : 2).join(" | ")}`);
351
390
  return true;
352
391
  }
353
392
 
@@ -360,7 +399,7 @@ export function summaryLines(root, { now = Date.now() } = {}) {
360
399
  if (b.readReport() || b.readCancel()) continue;
361
400
  const fh = readFirstHour(b.dir), h = readHealth(b.dir);
362
401
  if (fh?.summary) out.push(` batch ${id}: ${fh.summary}`);
363
- if (h?.stall && now - Date.parse(h.stall.at) < 24 * 3600 * 1000) out.push(` batch ${id}: DISPATCH STALLED since ${h.stall.at}: ${h.stall.detail}`);
402
+ if (h?.stall && now - Date.parse(h.stall.at) < 24 * 3600 * 1000) out.push(` batch ${id}: DISPATCH STALLED since ${h.stall.at}: ${h.stall.detail}${h.stall.cause ? ` (${h.stall.cause})` : ""}`);
364
403
  } catch { /* an unreadable batch has no line */ }
365
404
  }
366
405
  return out;
@@ -8,7 +8,8 @@ import { tmpDir } from "../tests/_tmp.mjs";
8
8
  import { openBatch } from "./batch.mjs";
9
9
  import { DEFAULT_HEALTH, parseHealthConfig, rootsOf, evaluateHealth, formatAlert, runCheck, scheduleChecks, scheduleLine, runNotify, deliverAlert,
10
10
  resolvedOnGithub, recordRefusal, readRefusals, statusLines, REFUSAL_KEEP,
11
- evaluateDispatchStall, firstHourReport, writeFirstHour, readFirstHour, recordStallAlert, summaryLines, statelessNeedsHuman, statelessOnGithub } from "./batch-health.mjs";
11
+ evaluateDispatchStall, firstHourReport, writeFirstHour, readFirstHour, recordStallAlert, summaryLines, statelessNeedsHuman, statelessOnGithub,
12
+ DEFAULT_STALL_MIN, MAX_STALL_RECOVERIES, decideStallAction, recordStallRecovery, readHealth } from "./batch-health.mjs";
12
13
 
13
14
  // #1 and #3 are roots; #2 depends on #1, #4 on #3.
14
15
  const base = (results, extra = {}) => ({ order: [1, 2, 3, 4], deps: { 2: [1], 4: [3] }, results, running: {}, pending: [], ...extra });
@@ -194,6 +195,16 @@ describe("#5314 dispatch stall and first-hour report", () => {
194
195
  const st = (extra = {}) => ({ order: [1, 2, 3], deps: { 3: [1] }, results: { 1: { outcome: "merged" } }, running: {}, pending: [2, 3], parallel: 2, ...extra });
195
196
  const stall = (state, o = {}) => evaluateDispatchStall(state, { lastProgressMs: NOW - 12 * MIN, now: NOW, windowMin: 10, ...o });
196
197
 
198
+ it("#5745: gates name the preflight check holding admission; without gates the detail is unchanged", () => {
199
+ const plain = stall(st());
200
+ assert.equal(plain.gates, undefined); assert.ok(!plain.detail.includes("admission held by"));
201
+ const r = stall(st(), { hosted: true, gates: [{ code: "preflight.pool_version", detail: "agent legion runs image version 2.0.0, CLI is 1.61.1" }] });
202
+ assert.deepEqual(r.gates, ["preflight.pool_version"]);
203
+ assert.ok(r.detail.startsWith(plain.detail.replace("no runner hosts the batch", "the runner is alive but not dispatching")));
204
+ assert.match(r.detail, /admission held by preflight\.pool_version: agent legion runs image version 2\.0\.0/);
205
+ assert.equal(stall(st(), { gates: [] }).detail, plain.detail);
206
+ });
207
+
197
208
  it("ready pending issues, a free lane and no progress for the window: stalled, naming the batch's ready issues and who hosts", () => {
198
209
  const r = stall(st());
199
210
  assert.equal(r.code, "dispatch-stalled");
@@ -241,6 +252,61 @@ describe("#5314 dispatch stall and first-hour report", () => {
241
252
  });
242
253
  });
243
254
 
255
+ describe("#5806 setup/dispatch stall: 3-min threshold, one auto-recovery, then an alert with the probed cause", () => {
256
+ const NOW = 10_000_000, MIN = 60000;
257
+ const setupState = { phase: "setup", setup: { read: 0, total: 4 }, order: [1, 2, 3, 4], deps: {}, results: {}, running: {}, pending: [1, 2, 3, 4], parallel: 4 };
258
+ const at = (idle, o = {}) => evaluateDispatchStall(setupState, { lastProgressMs: NOW - idle * MIN, now: NOW, ...o });
259
+
260
+ it("the default window is 3 min: a batch stuck in setup is a stall at 3 min, not at 2, and the detail says so", () => {
261
+ assert.equal(DEFAULT_STALL_MIN, 3);
262
+ assert.equal(at(2), null);
263
+ const s = at(3);
264
+ assert.equal(s.code, "dispatch-stalled");
265
+ assert.equal(s.setup, true);
266
+ assert.match(s.detail, /no progress for 3 min \(stuck in setup, 0\/4 issues read\)/);
267
+ assert.equal(at(3, { windowMin: 10 }), null, "the window stays configurable (FORGEDOCK_SCHEDD_STALL_MIN)");
268
+ });
269
+
270
+ it("first stall of a ready set: resume an unhosted batch, restart the daemon for a wedged hosted one", () => {
271
+ const s = at(4);
272
+ assert.deepEqual(decideStallAction(s, { hosted: false }), { action: "resume", sig: "1,2,3,4", cause: null });
273
+ assert.equal(decideStallAction(s, { hosted: true, probe: { ok: true, detail: "batch env PATH resolves gh, git, node" } }).action, "restart-daemon");
274
+ });
275
+
276
+ it("a broken batch env alerts at once with the probed cause (no futile recovery)", () => {
277
+ const d = decideStallAction(at(4), { probe: { ok: false, missing: ["gh", "git"], detail: "gh, git not resolvable on the batch env PATH (1 entry: /bogus)" } });
278
+ assert.equal(d.action, "alert");
279
+ assert.match(d.cause, /batch env: gh, git not resolvable on the batch env PATH \(1 entry: \/bogus\)/);
280
+ });
281
+
282
+ it("a recovery is recorded once (health.json + FORGE:DECISION in batch.log); the same stall again alerts and never loops", () => {
283
+ const root = tmpDir("stall-recover-"), b = openBatch(root, "b1");
284
+ b.writePlan({ daemon: true, repo: "o/r" });
285
+ const s = at(4);
286
+ const text = recordStallRecovery(b, s, { action: "resume", now: NOW });
287
+ assert.match(text, /^FORGE:DECISION batch b1 stall-recovery: resume the batch/);
288
+ assert.match(readFileSync(join(b.dir, "batch.log"), "utf8"), /FORGE:DECISION batch b1 stall-recovery/);
289
+ const rec = readHealth(b.dir).stallRecovery;
290
+ assert.deepEqual([rec.sig, rec.action, rec.count], ["1,2,3,4", "resume", 1]);
291
+ // the daemon restarted meanwhile: the decision reads health.json, not memory
292
+ const again = decideStallAction(s, { recovery: rec, hosted: true, probe: { ok: true, detail: "batch env PATH resolves gh, git, node" } });
293
+ assert.equal(again.action, "alert");
294
+ assert.match(again.cause, /stalled again after auto-recovery \(resume at .+\); batch env PATH resolves gh, git, node/);
295
+ assert.equal(recordStallAlert(b, s, { now: NOW, cause: again.cause }), true);
296
+ assert.equal(recordStallAlert(b, s, { now: NOW, cause: again.cause }), false, "one alert per ready set");
297
+ const h = readHealth(b.dir);
298
+ assert.match(h.alert, /\n {2}probed: stalled again after auto-recovery/);
299
+ assert.equal(h.stall.cause, again.cause);
300
+ assert.ok(summaryLines(root, { now: NOW }).some((l) => /DISPATCH STALLED .*stalled again after auto-recovery/.test(l)));
301
+ });
302
+
303
+ it("a batch that spent MAX_STALL_RECOVERIES alerts even on a new ready set", () => {
304
+ const d = decideStallAction(at(4), { recovery: { sig: "9", at: "x", action: "resume", count: MAX_STALL_RECOVERIES } });
305
+ assert.equal(d.action, "alert");
306
+ assert.match(d.cause, /auto-recoveries already spent/);
307
+ });
308
+ });
309
+
244
310
  describe("#5466 statelessNeedsHuman", () => {
245
311
  const nh = ["<!-- FORGE:NEEDS_HUMAN -->\nx"];
246
312
  it("flags an open issue with a NEEDS_HUMAN comment and no state label", () => {
@@ -17,6 +17,7 @@
17
17
  */
18
18
  import { appendFileSync, chmodSync, closeSync, existsSync, fchmodSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
19
19
  import { spawn } from "node:child_process";
20
+ import { createHash } from "node:crypto";
20
21
  import { homedir, hostname } from "node:os";
21
22
  import { dirname, join, resolve, sep } from "node:path";
22
23
  import { sanitizeOverride, validateExecutionPatch } from "./live-execution.mjs";
@@ -79,6 +80,13 @@ export function scrubEnv(env) {
79
80
  return { env: names.length ? Object.fromEntries(Object.entries(env).filter(([k]) => !SECRET_ENV.test(k))) : env, names };
80
81
  }
81
82
 
83
+ /** #5805: stable fingerprint of a batch's pinned env (plan.json `env`, set by --set-env); a change re-admits engine/env holds. */
84
+ export function envFingerprint(env) {
85
+ const e = env && typeof env === "object" ? env : {};
86
+ const text = JSON.stringify(Object.keys(e).sort().map((k) => [k, String(e[k])]));
87
+ return createHash("sha256").update(text).digest("hex").slice(0, 16);
88
+ }
89
+
82
90
  const readJson = (file) => { try { return JSON.parse(readFileSync(file, "utf8")); } catch { return null; } };
83
91
  /** #5531: parses done by the cached reader (tests assert a scan parses each batch state once). */
84
92
  export const scanStats = { parses: 0 };
@@ -1828,6 +1828,11 @@ describe("#5168: --requeue accepts engine-error; a claude login failure is held,
1828
1828
  assert.deepEqual(b.readRequeued().map((e) => e.issue), [1]);
1829
1829
  });
1830
1830
 
1831
+ it("#5762 deferPolicy retries backend.cli_failed shortly, capped, with no account hold", () => {
1832
+ assert.deepEqual(deferPolicy({ code: "backend.cli_failed", retryInSeconds: 120 }, { now: 0, deferrals: 0, maxDeferrals: 3 }), { delayMs: 120_000 });
1833
+ assert.deepEqual(deferPolicy({ code: "backend.cli_failed", retryInSeconds: 120 }, { now: 0, deferrals: 3, maxDeferrals: 3 }), { capped: true });
1834
+ });
1835
+
1831
1836
  it("#5168 deferPolicy holds backend.auth like a usage limit: never capped, never counted", () => {
1832
1837
  assert.deepEqual(deferPolicy({ code: "backend.auth", retryInSeconds: 900 }, { now: 0, deferrals: 99, maxDeferrals: 3 }), { delayMs: 900_000, hold: true });
1833
1838
  assert.equal(deferPolicy({ code: "backend.auth" }, { now: 0 }).hold, true);
@@ -70,3 +70,23 @@ export function handoffFacts(toolUses, lastTool = null) {
70
70
 
71
71
  /** Appended to the build prompt of a lane predicted to restart: read the named files, do not survey. */
72
72
  export const NARROW_NOTE = "\n\nContext is tight on this lane (the contract's files and this prompt already fill much of the session window): read only the files the contract names and the code you edit, skip surveys of unrelated code, and make each edit as soon as you know it.";
73
+
74
+ /** #5812: the route digest's byte cap (about 8000 tokens); a smaller hand-off bound lowers it to the bound in bytes, a quarter of it in tokens. */
75
+ export const ROUTE_DIGEST_MAX_BYTES = 32 * 1024;
76
+
77
+ /**
78
+ * #5812: whether the routed build resumes the planning session or starts fresh from a digest. `planTokens` is the planning
79
+ * session's last-turn context (null when unknown: resume, as before), `bound` is `engine.route_handoff_tokens` (0 = always
80
+ * resume), capped at half the lane's ceiling so a build never opens near it. Above the bound: digest.
81
+ */
82
+ export function routeHandoff({ planTokens = null, bound = 0, ceiling = 0 } = {}) {
83
+ const b = bound > 0 ? (ceiling > 0 ? Math.min(bound, Math.floor(ceiling / 2)) : bound) : 0;
84
+ const digest = b > 0 && Number.isFinite(planTokens) && planTokens > b;
85
+ return { digest, planTokens: Number.isFinite(planTokens) ? planTokens : null, bound: b, digestBytes: Math.min(ROUTE_DIGEST_MAX_BYTES, Math.max(2048, b)) };
86
+ }
87
+
88
+ /** #5812: the planning reply's closing "Build reads:" list (the files and searches the build opens with); "" when absent. */
89
+ export function buildReadsOf(text) {
90
+ const s = String(text ?? ""), i = s.lastIndexOf("Build reads:");
91
+ return i < 0 ? "" : s.slice(i + "Build reads:".length).trim().slice(0, 3000);
92
+ }