@loucompanion/forge-bridge 0.1.4-dev.86fc5d1208e6 → 0.1.4-dev.894bcbd53d64

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 (269) hide show
  1. package/README.md +144 -3
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +101 -15
  16. package/dist/bridge/bridge.service.js +472 -345
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  19. package/dist/bridge/dispatch-result-outbox.js +31 -6
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +17 -0
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  33. package/dist/cleanup/cleanup-wip.js +66 -0
  34. package/dist/cleanup/cleanup.service.d.ts +20 -1
  35. package/dist/cleanup/cleanup.service.js +150 -169
  36. package/dist/cleanup/cleanup.types.d.ts +6 -0
  37. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  38. package/dist/cleanup/forge-owned-paths.js +53 -0
  39. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  40. package/dist/cleanup/host-runtime-ledger.js +130 -0
  41. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  42. package/dist/cleanup/managed-branch-sweep.js +111 -0
  43. package/dist/cli/cli.help.js +74 -12
  44. package/dist/cli/cli.service.d.ts +19 -10
  45. package/dist/cli/cli.service.js +152 -187
  46. package/dist/cli/idle-status.d.ts +84 -0
  47. package/dist/cli/idle-status.js +181 -0
  48. package/dist/cli/local-config.d.ts +6 -0
  49. package/dist/cli/local-config.js +32 -4
  50. package/dist/cli/provider-cli-detection.d.ts +10 -0
  51. package/dist/cli/provider-cli-detection.js +160 -0
  52. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  54. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  55. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  56. package/dist/runtime/attempt-process-supervisor.d.ts +21 -0
  57. package/dist/runtime/attempt-process-supervisor.js +62 -6
  58. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  59. package/dist/runtime/docker-engine-probe.js +7 -0
  60. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  61. package/dist/runtime/dotnet-build-outputs.js +402 -0
  62. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  64. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  65. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  66. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  67. package/dist/runtime/host-database-capability-boundary.js +1 -0
  68. package/dist/runtime/host-facts.d.ts +36 -0
  69. package/dist/runtime/host-facts.js +95 -0
  70. package/dist/runtime/host-load-admission.d.ts +67 -0
  71. package/dist/runtime/host-load-admission.js +99 -0
  72. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  73. package/dist/runtime/host-load-child-environment.js +76 -0
  74. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  75. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  76. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  77. package/dist/runtime/host-load-governor-config.js +83 -0
  78. package/dist/runtime/host-load-governor.d.ts +186 -0
  79. package/dist/runtime/host-load-governor.js +632 -0
  80. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  81. package/dist/runtime/host-load-ledger-lock.js +187 -0
  82. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  83. package/dist/runtime/host-load-runtime-settings.js +80 -0
  84. package/dist/runtime/host-load-sampler.d.ts +156 -0
  85. package/dist/runtime/host-load-sampler.js +298 -0
  86. package/dist/runtime/host-load-step-class.d.ts +70 -0
  87. package/dist/runtime/host-load-step-class.js +161 -0
  88. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  89. package/dist/runtime/host-load-step-reaper.js +95 -0
  90. package/dist/runtime/host-load-step-run.d.ts +73 -0
  91. package/dist/runtime/host-load-step-run.js +102 -0
  92. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  93. package/dist/runtime/host-load-test-slot.js +81 -0
  94. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  95. package/dist/runtime/host-load-token-ledger.js +453 -0
  96. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  97. package/dist/runtime/host-load-windows-cpu.js +85 -0
  98. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  99. package/dist/runtime/host-pressure-stall.js +168 -0
  100. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  101. package/dist/runtime/host-runtime-contract.js +35 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  103. package/dist/runtime/host-runtime-lease.js +343 -67
  104. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  105. package/dist/runtime/host-runtime-promotion.js +48 -0
  106. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  107. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  108. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  109. package/dist/runtime/host-runtime-requirements.js +117 -0
  110. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  111. package/dist/runtime/managed-command-teardown.js +596 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  113. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  114. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  115. package/dist/runtime/playwright-browser-cache.js +227 -0
  116. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  117. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  118. package/dist/runtime/runner-settings.d.ts +104 -0
  119. package/dist/runtime/runner-settings.js +236 -0
  120. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  121. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  122. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  123. package/dist/sandbox/host-capacity-broker.js +336 -0
  124. package/dist/sandbox/managed-branch.d.ts +13 -0
  125. package/dist/sandbox/managed-branch.js +90 -0
  126. package/dist/sandbox/provider-auth/codex.js +11 -11
  127. package/dist/sandbox/runtime.d.ts +10 -1
  128. package/dist/sandbox/runtime.js +47 -8
  129. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  130. package/dist/sandbox/sandbox-cgroups.js +42 -0
  131. package/dist/session/architect-waits.d.ts +2 -0
  132. package/dist/session/architect-waits.js +138 -0
  133. package/dist/session/managed-attempt-tools.d.ts +27 -7
  134. package/dist/session/managed-attempt-tools.js +406 -123
  135. package/dist/session/managed-build-coordinator.d.ts +17 -1
  136. package/dist/session/managed-build-coordinator.js +14 -1
  137. package/dist/session/managed-build-receipt.d.ts +5 -0
  138. package/dist/session/managed-build-receipt.js +8 -3
  139. package/dist/session/managed-command-host-load.d.ts +47 -0
  140. package/dist/session/managed-command-host-load.js +83 -0
  141. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  142. package/dist/session/mcp-argument-coercion.js +121 -0
  143. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  144. package/dist/session/phase-completion.artifacts.js +100 -26
  145. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  146. package/dist/session/phase-completion.command-validation.js +77 -0
  147. package/dist/session/phase-completion.d.ts +12 -0
  148. package/dist/session/phase-completion.helpers.js +13 -12
  149. package/dist/session/phase-completion.js +5 -0
  150. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  151. package/dist/session/phase-completion.mcp-args.js +156 -0
  152. package/dist/session/phase-completion.prompts.js +6 -1
  153. package/dist/session/phase-completion.runtime.d.ts +5 -11
  154. package/dist/session/phase-completion.runtime.js +111 -230
  155. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  156. package/dist/session/phase-completion.schema-parts.js +188 -0
  157. package/dist/session/phase-completion.schemas.d.ts +3 -3
  158. package/dist/session/phase-completion.schemas.js +208 -231
  159. package/dist/session/phase-completion.validation.d.ts +2 -3
  160. package/dist/session/phase-completion.validation.js +49 -93
  161. package/dist/session/pre-publication-host-load.d.ts +27 -0
  162. package/dist/session/pre-publication-host-load.js +111 -0
  163. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  164. package/dist/session/pre-publication-native-postgres.js +111 -0
  165. package/dist/session/pre-publication-pass.d.ts +61 -0
  166. package/dist/session/pre-publication-pass.js +148 -0
  167. package/dist/session/pre-publication-process.d.ts +23 -0
  168. package/dist/session/pre-publication-process.js +109 -0
  169. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  170. package/dist/session/pre-publication-skipped-tests.js +109 -0
  171. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  172. package/dist/session/pre-publication-step-execution.js +50 -0
  173. package/dist/session/pre-publication-validation.d.ts +37 -21
  174. package/dist/session/pre-publication-validation.js +228 -219
  175. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  176. package/dist/session/provider-cli/claude-background-work.js +181 -0
  177. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  178. package/dist/session/provider-cli/host-build-lock.js +30 -0
  179. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  180. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  181. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  182. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  183. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  184. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  185. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  186. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  187. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  188. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  189. package/dist/session/provider-cli/provider-cli.process.d.ts +46 -31
  190. package/dist/session/provider-cli/provider-cli.process.js +286 -403
  191. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  192. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  193. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  195. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  196. package/dist/session/provider-cli/provider-cli.service.js +207 -192
  197. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  198. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  199. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  200. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  201. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  202. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  203. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  204. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  205. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  206. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  207. package/dist/session/provider-cli/provider-output-state.js +15 -0
  208. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  209. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  210. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  211. package/dist/session/publishable-worktree-changes.js +193 -0
  212. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  213. package/dist/session/qa-sidecar-validation.js +28 -0
  214. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  215. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  216. package/dist/session/session-redaction.js +31 -181
  217. package/dist/session/session.base.d.ts +9 -1
  218. package/dist/session/session.service.d.ts +11 -2
  219. package/dist/session/session.service.js +189 -69
  220. package/dist/session/session.types.d.ts +3 -0
  221. package/dist/session/session.types.js +15 -3
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  225. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  226. package/dist/shared/fs/file-identity.d.ts +10 -0
  227. package/dist/shared/fs/file-identity.js +15 -0
  228. package/dist/shared/fs/replace-file.d.ts +7 -0
  229. package/dist/shared/fs/replace-file.js +33 -0
  230. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  231. package/dist/shared/process/host-process-recovery.js +23 -3
  232. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  233. package/dist/shared/process/host-process-supervisor.js +67 -15
  234. package/dist/shared/process/process-tree.d.ts +52 -0
  235. package/dist/shared/process/process-tree.js +144 -0
  236. package/dist/shared/process/process.d.ts +67 -0
  237. package/dist/shared/process/process.js +213 -11
  238. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  239. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  240. package/dist/shared/process/windows-launch.d.ts +18 -0
  241. package/dist/shared/process/windows-launch.js +68 -0
  242. package/dist/shared/provider-capabilities.js +14 -7
  243. package/dist/version.d.ts +1 -1
  244. package/dist/version.js +1 -1
  245. package/dist/worktree/dependency-warmer.d.ts +25 -0
  246. package/dist/worktree/dependency-warmer.js +120 -10
  247. package/dist/worktree/orphan-relink.d.ts +19 -0
  248. package/dist/worktree/orphan-relink.js +106 -0
  249. package/dist/worktree/wip-git.d.ts +33 -0
  250. package/dist/worktree/wip-git.js +122 -0
  251. package/dist/worktree/wip-refs.d.ts +62 -0
  252. package/dist/worktree/wip-refs.js +119 -0
  253. package/dist/worktree/wip-restore.d.ts +38 -0
  254. package/dist/worktree/wip-restore.js +190 -0
  255. package/dist/worktree/wip-snapshot.d.ts +50 -0
  256. package/dist/worktree/wip-snapshot.js +268 -0
  257. package/dist/worktree/worktree-inputs.d.ts +8 -0
  258. package/dist/worktree/worktree-inputs.js +134 -0
  259. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  260. package/dist/worktree/worktree-origin-sync.js +127 -0
  261. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  262. package/dist/worktree/worktree-wip-events.js +98 -0
  263. package/dist/worktree/worktree-wip.d.ts +50 -0
  264. package/dist/worktree/worktree-wip.js +185 -0
  265. package/dist/worktree/worktree.base.d.ts +7 -1
  266. package/dist/worktree/worktree.service.d.ts +36 -5
  267. package/dist/worktree/worktree.service.js +124 -155
  268. package/dist/worktree/worktree.types.d.ts +38 -0
  269. package/package.json +2 -2
@@ -1,17 +1,24 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
5
- import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
6
6
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
7
7
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
8
- import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
8
+ import { managedVerificationDatabase, noManagedVerificationDatabase, releaseManagedVerificationDatabase, setUpWithManagedVerificationDatabase } from "../runtime/ephemeral-test-postgres-grant.js";
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
- import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
11
- import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
10
+ import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
11
+ import { assertManagedBuildSparesSupervisedRuntimes, ManagedBuildCoordinator } from "./managed-build-coordinator.js";
12
+ import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
13
+ import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
14
+ import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
15
+ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
16
+ import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
17
+ import { managedBuildConfiguration, persistJsonAtomically, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
12
18
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
13
19
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
14
20
  import { monotonicNowMs } from "../shared/time/monotonic.js";
21
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
15
22
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
16
23
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
17
24
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
@@ -30,8 +37,6 @@ const managedCommandRetryAfterMs = 60_000;
30
37
  const managedCommandLaunchTimeoutMs = 60_000;
31
38
  const managedCommandProgressPersistIntervalMs = 5_000;
32
39
  const managedCommandReceiptPollIntervalMs = 1_000;
33
- const managedCommandReceiptReplaceAttempts = 40;
34
- const managedCommandReceiptReplaceRetryMs = 25;
35
40
  const terminalManagedCommandStatuses = new Set([
36
41
  "pass",
37
42
  "fail",
@@ -41,6 +46,14 @@ const terminalManagedCommandStatuses = new Set([
41
46
  ]);
42
47
  const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
43
48
  const managedCommandTasks = new Map();
49
+ // Every command this MCP server is supervising, synchronous or not. The server is the only
50
+ // writer of their receipts, so it stops them before it exits.
51
+ const activeManagedCommands = new Map();
52
+ const ownerExitStoppedCommands = new Set();
53
+ let ownerProcessIdentity;
54
+ let managedCommandOwnerShuttingDown = false;
55
+ let ownerExitSweep = null;
56
+ const managedCommandOwnerExitMessage = "managed_command_owner_exited: Forge stopped this managed command because the Forge MCP server that supervised it is exiting; its provider process ended before the command finished. Its result is unknown; start it again if it is still needed.";
44
57
  export const managedAttemptToolNames = [
45
58
  "forge.run_managed_command",
46
59
  "run_managed_command",
@@ -55,6 +68,76 @@ export const managedAttemptToolNames = [
55
68
  "forge.reset_generated_outputs",
56
69
  "reset_generated_outputs",
57
70
  ];
71
+ /**
72
+ * Stops every managed command this MCP server started, proves each process tree stopped,
73
+ * and writes their terminal receipts. Called when the provider closes the MCP connection
74
+ * or the server is signalled: once this server exits nothing could supervise them.
75
+ */
76
+ export async function stopManagedCommandsForOwnerExit() {
77
+ // One sweep at a time: a signal that arrives while a sweep runs waits for that sweep.
78
+ ownerExitSweep ??= sweepManagedCommandsForOwnerExit().finally(() => { ownerExitSweep = null; });
79
+ await ownerExitSweep;
80
+ }
81
+ async function sweepManagedCommandsForOwnerExit() {
82
+ // From here on this server refuses new commands, so a request still being handled
83
+ // cannot launch one behind the sweep. Repeat until none is left: a launch that passed
84
+ // its last check just before the flag was set registers synchronously and is caught.
85
+ managedCommandOwnerShuttingDown = true;
86
+ while (activeManagedCommands.size > 0) {
87
+ const active = [...activeManagedCommands.entries()];
88
+ for (const [commandId, command] of active) {
89
+ ownerExitStoppedCommands.add(commandId);
90
+ command.controller.abort(new Error(managedCommandOwnerExitMessage));
91
+ }
92
+ await Promise.allSettled(active.map(([, command]) => command.task));
93
+ }
94
+ }
95
+ /** Test support: lets one test process act as a fresh MCP server after a simulated exit. */
96
+ export function resetManagedCommandOwnerShutdownForTesting() {
97
+ managedCommandOwnerShuttingDown = false;
98
+ }
99
+ function assertManagedCommandsAccepted() {
100
+ if (managedCommandOwnerShuttingDown) {
101
+ throw new Error("managed_command_unavailable: the Forge MCP server is shutting down and accepts no new managed commands.");
102
+ }
103
+ }
104
+ const ownerShutdownSignals = ["SIGTERM", "SIGHUP", "SIGINT"];
105
+ /**
106
+ * Makes a termination signal stop this server's managed commands before it exits, so none
107
+ * outlives its only supervisor. Returns a function that removes the handlers.
108
+ */
109
+ export function installOwnerShutdownHandlers(target = process, exit = code => process.exit(code)) {
110
+ const handlers = ownerShutdownSignals.map(signal => {
111
+ const handler = () => {
112
+ void stopManagedCommandsForOwnerExit().finally(() => exit(128 + os.constants.signals[signal]));
113
+ };
114
+ target.once(signal, handler);
115
+ return { signal, handler };
116
+ });
117
+ return () => {
118
+ for (const { signal, handler } of handlers)
119
+ target.removeListener(signal, handler);
120
+ };
121
+ }
122
+ /**
123
+ * Runs an MCP server body, then stops every managed command it started before returning.
124
+ * The signal handlers stay installed until that stop completes: a signal during the body
125
+ * or the stop exits only after the same stop finishes, never by Node's default exit.
126
+ */
127
+ export async function runWithOwnerShutdown(body, target = process, exit = code => process.exit(code)) {
128
+ const removeShutdownHandlers = installOwnerShutdownHandlers(target, exit);
129
+ try {
130
+ return await body();
131
+ }
132
+ finally {
133
+ try {
134
+ await stopManagedCommandsForOwnerExit();
135
+ }
136
+ finally {
137
+ removeShutdownHandlers();
138
+ }
139
+ }
140
+ }
58
141
  export function isManagedAttemptTool(name) {
59
142
  return managedCommandNames.has(name)
60
143
  || startManagedCommandNames.has(name)
@@ -63,11 +146,17 @@ export function isManagedAttemptTool(name) {
63
146
  || startManagedVerificationNames.has(name)
64
147
  || resetGeneratedOutputNames.has(name);
65
148
  }
149
+ const managedVerificationProfiles = ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"];
150
+ const managedVerificationProfileHint = `Use one of: ${managedVerificationProfiles.join(", ")}. These are .NET test profiles only; run client, bridge, or Playwright e2e checks with forge.start_managed_command.`;
151
+ /** The input schema a managed-attempt tool advertises; also the shape its arguments are coerced to. */
152
+ export function managedAttemptToolInputSchema(name) {
153
+ return managedAttemptToolDefinition(name).inputSchema;
154
+ }
66
155
  export function managedAttemptToolDefinition(name) {
67
156
  if (startManagedVerificationNames.has(name)) {
68
157
  return {
69
158
  name,
70
- description: "Start a canonical Forge verification profile with runner-owned cwd, arguments, attempt output, timeout, and process supervision. Prefer this over reconstructing broad .NET commands. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt.",
159
+ description: "Start a canonical Forge .NET verification profile with runner-owned cwd, arguments, attempt output, timeout, and process supervision. Prefer this over reconstructing broad .NET commands. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt. To run every shard of a tier in one call, set run_all_shards: true with shard_count 2 or more and without no_build.",
71
160
  inputSchema: {
72
161
  type: "object",
73
162
  additionalProperties: false,
@@ -75,13 +164,14 @@ export function managedAttemptToolDefinition(name) {
75
164
  properties: {
76
165
  profile: {
77
166
  type: "string",
78
- enum: ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"],
167
+ enum: [...managedVerificationProfiles],
168
+ description: "Required .NET test profile. dotnet_affected selects its own tests and owns its build: it takes no shard or no_build options. dotnet_solution takes no shard options. Client, bridge, and e2e checks are not profiles; use forge.start_managed_command for them.",
79
169
  },
80
- shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1 },
81
- shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0 },
82
- run_all_shards: { type: "boolean", default: false },
170
+ shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1, description: "Number of shards to split the tier into. Must be at least 2 when run_all_shards is true." },
171
+ shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0, description: "Which single shard to run; must be less than shard_count, and 0 when run_all_shards is true." },
172
+ run_all_shards: { type: "boolean", default: false, description: "Run every shard of the tier after one shared build. Requires shard_count of at least 2 and shard_index 0, cannot be combined with no_build, and is not supported for dotnet_solution or dotnet_affected." },
83
173
  max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
84
- no_build: { type: "boolean", default: false },
174
+ no_build: { type: "boolean", default: false, description: "Reuse the verified build from an earlier managed build instead of building. Not allowed with run_all_shards or dotnet_affected." },
85
175
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
86
176
  },
87
177
  },
@@ -98,8 +188,8 @@ export function managedAttemptToolDefinition(name) {
98
188
  additionalProperties: false,
99
189
  required: ["command", "args"],
100
190
  properties: {
101
- command: { type: "string", minLength: 1 },
102
- args: { type: "array", items: { type: "string" } },
191
+ command: { type: "string", minLength: 1, description: "Required executable only, for example pnpm, node, npm, or dotnet. Not a shell command line: shell syntax such as cd, &&, or pipes is not interpreted." },
192
+ args: { type: "array", items: { type: "string" }, description: "Required argument list, each argument its own string, for example [\"--dir\", \"client\", \"lint\"]. Send [] when there are none. Use cwd instead of cd." },
103
193
  cwd: { type: "string", description: "Worktree-relative directory; defaults to the worktree root." },
104
194
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 2700000 },
105
195
  },
@@ -175,6 +265,7 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
175
265
  return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
176
266
  }
177
267
  async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
268
+ assertManagedCommandsAccepted();
178
269
  const command = requiredInputString(record, "command");
179
270
  const args = requiredStringArray(record, "args");
180
271
  const timeoutMs = optionalTimeout(record.timeout_ms);
@@ -199,7 +290,11 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
199
290
  worktreePath,
200
291
  buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
201
292
  buildReceiptReuse,
293
+ controller: new AbortController(),
202
294
  };
295
+ // A build aimed at the output a running supervised runtime executes from fails here, naming
296
+ // that runtime, instead of failing on its locked files after the build-slot and capacity waits.
297
+ await assertManagedBuildSparesSupervisedRuntimes(invocation);
203
298
  if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
204
299
  const started = managedCommandResult({
205
300
  ...invocation,
@@ -208,9 +303,25 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
208
303
  exitCode: null,
209
304
  stdout: "",
210
305
  stderr: "",
306
+ launchRequested: false,
211
307
  });
212
308
  await persistManagedCommandReceipt(receiptPath, started.structuredContent);
213
- const task = executeManagedCommand(invocation);
309
+ if (managedCommandOwnerShuttingDown) {
310
+ // Shutdown began while the receipt was written; the command never starts.
311
+ const refused = managedCommandResult({
312
+ ...invocation,
313
+ timedOut: false,
314
+ status: "runner_error",
315
+ exitCode: null,
316
+ stdout: "",
317
+ stderr: appendBounded("", managedCommandOwnerExitMessage),
318
+ launchRequested: false,
319
+ terminationReason: "owner_exited",
320
+ });
321
+ await persistManagedCommandReceipt(receiptPath, refused.structuredContent);
322
+ assertManagedCommandsAccepted();
323
+ }
324
+ const task = trackManagedCommand(invocation);
214
325
  managedCommandTasks.set(commandId, task);
215
326
  void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
216
327
  return {
@@ -221,7 +332,16 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
221
332
  }],
222
333
  };
223
334
  }
224
- return await executeManagedCommand(invocation);
335
+ return await trackManagedCommand(invocation);
336
+ }
337
+ function trackManagedCommand(invocation) {
338
+ const task = executeManagedCommand(invocation);
339
+ activeManagedCommands.set(invocation.commandId, { controller: invocation.controller, task });
340
+ void task.finally(() => {
341
+ activeManagedCommands.delete(invocation.commandId);
342
+ ownerExitStoppedCommands.delete(invocation.commandId);
343
+ }).catch(() => undefined);
344
+ return task;
225
345
  }
226
346
  async function startManagedVerification(input, worktreePath) {
227
347
  const record = asRecord(input);
@@ -235,13 +355,13 @@ async function startManagedVerification(input, worktreePath) {
235
355
  const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
236
356
  const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
237
357
  if (runAllShards && shardCount < 2) {
238
- throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 2.");
358
+ throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 2. Set shard_count to 2 or more to run every shard, or omit run_all_shards to run a single shard.");
239
359
  }
240
360
  if (runAllShards && shardIndex !== 0) {
241
361
  throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
242
362
  }
243
363
  if (runAllShards && noBuild) {
244
- throw new Error("managed_verification_invalid: run_all_shards owns the single prerequisite build and cannot be combined with no_build.");
364
+ throw new Error("managed_verification_invalid: run_all_shards owns the single prerequisite build and cannot be combined with no_build. Omit no_build when run_all_shards is true.");
245
365
  }
246
366
  const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
247
367
  const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
@@ -298,7 +418,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
298
418
  };
299
419
  const tier = tiers[profile];
300
420
  if (!tier)
301
- throw new Error(`managed_verification_invalid: unsupported profile ${profile}.`);
421
+ throw new Error(`managed_verification_invalid: unsupported profile ${profile}. ${managedVerificationProfileHint}`);
302
422
  const command = preferredPowerShellExecutable();
303
423
  if (runAllShards) {
304
424
  return {
@@ -327,7 +447,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
327
447
  export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
328
448
  if (platform !== "win32")
329
449
  return "pwsh";
330
- return resolveWindowsCommandFromPath("pwsh.exe", pathValue) ?? "powershell.exe";
450
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
331
451
  }
332
452
  export function validatePlaywrightProjectName(project, availableProjects) {
333
453
  if (!availableProjects.includes(project)) {
@@ -381,58 +501,166 @@ function optionValue(args, name) {
381
501
  const index = args.indexOf(name);
382
502
  return index >= 0 ? args[index + 1]?.trim() || null : null;
383
503
  }
504
+ function hostCapacityLossReason(reason) {
505
+ if (reason instanceof HostCapacityTokenFencedError)
506
+ return "host_capacity_token_fenced";
507
+ if (reason instanceof HostCapacityLedgerUnavailableError)
508
+ return "host_capacity_ledger_unavailable";
509
+ return null;
510
+ }
384
511
  async function executeManagedCommand(invocation) {
385
- if (!invocation.buildProducing)
386
- return await executeManagedCommandProcess(invocation);
387
- return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs }), async () => {
388
- const waiting = managedCommandResult({
512
+ let processStarted = false;
513
+ // The per-worktree build slot is taken first: holding a host token while
514
+ // queued behind this worktree's own build would waste host capacity.
515
+ const hostCapacity = new ManagedCommandHostCapacity({ ...invocation, label: invocation.verificationProfile ?? invocation.commandId }, async (hostLoad) => await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
516
+ ...invocation,
517
+ hostLoad,
518
+ timedOut: false,
519
+ status: "waiting_for_host_capacity",
520
+ exitCode: null,
521
+ stdout: "",
522
+ stderr: "",
523
+ launchRequested: false,
524
+ }).structuredContent));
525
+ const launch = async (buildQueueWaitMs) => await hostCapacity.run(invocation.controller.signal, async (hostLoad, control) => {
526
+ processStarted = true;
527
+ // A reclaimed token means this command's capacity is gone: it stops. A fence that
528
+ // landed between admission and here stops it too (a listener added now never fires).
529
+ const stopOnFence = () => invocation.controller.abort(control.fenced.reason);
530
+ if (control.fenced?.aborted)
531
+ stopOnFence();
532
+ else
533
+ control.fenced?.addEventListener("abort", stopOnFence, { once: true });
534
+ try {
535
+ return await executeManagedCommandProcess({
536
+ ...invocation,
537
+ buildQueueWaitMs,
538
+ hostLoad,
539
+ // Recording the tree is part of holding the token: if it fails (the token was
540
+ // fenced meanwhile, or the ledger refused), the command stops instead of
541
+ // running on without a reservation the host can account for.
542
+ // Checked against the tree recorded on the token at launch (null: the governor's own).
543
+ holdHostCapacityUntilStopped: reason => control.holdUntilStopped?.(null, reason),
544
+ onProcessStarted: async () => await attachManagedCommandProcess(control, invocation.metadataPath)
545
+ .catch((error) => {
546
+ invocation.controller.abort(error instanceof HostCapacityTokenFencedError || error instanceof HostCapacityLedgerUnavailableError
547
+ ? error
548
+ : new HostCapacityLedgerUnavailableError(`the managed command's process tree could not be recorded on its host load token: ${error instanceof Error ? error.message : String(error)}`, { cause: error }));
549
+ }),
550
+ });
551
+ }
552
+ finally {
553
+ control.fenced?.removeEventListener("abort", stopOnFence);
554
+ }
555
+ },
556
+ // A fenced release is already the receipt's termination reason; only a ledger fault is noted.
557
+ async (error) => error instanceof HostCapacityTokenFencedError ? undefined : await annotateManagedCommandReceipt(invocation.receiptPath, {
558
+ host_capacity_release_error: redactText(error instanceof Error ? error.message : String(error), []),
559
+ }));
560
+ try {
561
+ if (!invocation.buildProducing)
562
+ return await launch();
563
+ return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, launch, async () => {
564
+ const waiting = managedCommandResult({
565
+ ...invocation,
566
+ timedOut: false,
567
+ status: "waiting_for_build_slot",
568
+ exitCode: null,
569
+ stdout: "",
570
+ stderr: "",
571
+ launchRequested: false,
572
+ });
573
+ await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
574
+ }, invocation.controller.signal);
575
+ }
576
+ catch (error) {
577
+ if (processStarted)
578
+ throw error;
579
+ // The command never started (its build-slot or host-capacity wait failed or was
580
+ // stopped). Its receipt must still become terminal, or a waiting agent sees it queued forever.
581
+ const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
582
+ const receipt = managedCommandResult({
389
583
  ...invocation,
584
+ hostLoad: await hostCapacity.unadmittedFields(error),
390
585
  timedOut: false,
391
- status: "waiting_for_build_slot",
586
+ status: "runner_error",
392
587
  exitCode: null,
393
588
  stdout: "",
394
- stderr: "",
589
+ stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
590
+ terminationReason: ownerExited ? "owner_exited" : undefined,
591
+ launchRequested: false,
395
592
  });
396
- await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
397
- });
593
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
594
+ return managedCommandPublicResult(receipt);
595
+ }
398
596
  }
399
- async function executeManagedCommandProcess(invocation) {
597
+ /** A command's environment and redaction list; a setup that throws releases the database it started. */
598
+ async function managedCommandProcessEnvironment(invocation) {
400
599
  assertHostDatabaseCapabilityBoundary();
401
- const databaseEnvironment = invocation.verificationProfile
402
- ? await managedVerificationDatabaseEnvironment()
403
- : {};
404
- const exactSecrets = [
405
- ...Object.values(databaseEnvironment).filter(value => value !== nativeTestPostgresFallbackDatabaseMode),
406
- // The attempt's brokered database login reaches managed commands; their output never shows it.
407
- ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
408
- ];
409
- const environment = inheritedEnvironment({
410
- FORGE_RUNTIME_MODE: "host",
411
- FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
412
- FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
413
- // This nested command owns a distinct supervisor identity. A command-local
414
- // fence avoids exposing the parent attempt's fencing capability to Codex's
415
- // MCP subprocess configuration while preserving exact-tree cleanup proof.
416
- FORGE_FENCING_TOKEN: randomUUID(),
417
- FORGE_LOG_DIR: invocation.logDirectory,
418
- FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
419
- FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
420
- FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
421
- ...(invocation.verificationProfile
422
- ? {
423
- FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
424
- // Managed verification executes mutable worktree scripts, SDK targets,
425
- // and test assemblies. It uses an attempt-owned container, or the
426
- // dedicated native test cluster while Docker is unavailable; it never
427
- // receives a capability for a server that holds real data.
428
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
429
- ...databaseEnvironment,
430
- }
431
- : {}),
600
+ const database = invocation.verificationProfile ? await managedVerificationDatabase() : noManagedVerificationDatabase;
601
+ return await setUpWithManagedVerificationDatabase(database, () => {
602
+ const exactSecrets = [
603
+ ...database.secrets,
604
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
605
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
+ ];
607
+ const environment = inheritedEnvironment({
608
+ FORGE_RUNTIME_MODE: "host",
609
+ FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
610
+ FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
611
+ // This nested command owns a distinct supervisor identity. A command-local
612
+ // fence avoids exposing the parent attempt's fencing capability to Codex's
613
+ // MCP subprocess configuration while preserving exact-tree cleanup proof.
614
+ FORGE_FENCING_TOKEN: randomUUID(),
615
+ FORGE_LOG_DIR: invocation.logDirectory,
616
+ FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
617
+ FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
618
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
619
+ ...(invocation.verificationProfile
620
+ ? {
621
+ FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
622
+ // Managed verification executes mutable worktree scripts, SDK targets,
623
+ // and test assemblies. It uses an attempt-owned container, or the
624
+ // dedicated native test cluster while Docker is unavailable; it never
625
+ // receives a capability for a server that holds real data.
626
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
627
+ ...database.environment,
628
+ }
629
+ : {}),
630
+ });
631
+ return { environment, exactSecrets, release: database.release };
432
632
  });
633
+ }
634
+ function clearManagedCommandTimers(...timers) {
635
+ // clearTimeout and clearInterval share one timer table.
636
+ for (const timer of timers)
637
+ if (timer)
638
+ clearTimeout(timer);
639
+ }
640
+ async function executeManagedCommandProcess(invocation) {
641
+ let prepared;
642
+ try {
643
+ prepared = await managedCommandProcessEnvironment(invocation);
644
+ }
645
+ catch (error) {
646
+ // The call still fails (the database capability boundary or the verification
647
+ // database probe refused it), but its receipt must not stay "starting" forever.
648
+ const receipt = managedCommandResult({
649
+ ...invocation,
650
+ timedOut: false,
651
+ status: "runner_error",
652
+ exitCode: null,
653
+ stdout: "",
654
+ stderr: appendBounded("", redactText(error instanceof Error ? error.message : String(error), [])),
655
+ launchRequested: false,
656
+ });
657
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent).catch(() => undefined);
658
+ throw error;
659
+ }
660
+ const { exactSecrets } = prepared;
433
661
  let stdout = "";
434
662
  let stderr = "";
435
- const controller = new AbortController();
663
+ const controller = invocation.controller;
436
664
  let timedOut = false;
437
665
  let timer = null;
438
666
  let outputRevision = 0;
@@ -465,15 +693,29 @@ async function executeManagedCommandProcess(invocation) {
465
693
  controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
466
694
  }, managedCommandLaunchTimeoutMs);
467
695
  try {
696
+ if (controller.signal.aborted)
697
+ throw controller.signal.reason;
698
+ // Recorded before the spawn: the process record is written only once the child has
699
+ // spawned, so teardown must know a launch may exist without one.
700
+ await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
701
+ ...invocation,
702
+ timedOut: false,
703
+ status: "starting",
704
+ exitCode: null,
705
+ stdout,
706
+ stderr,
707
+ }).structuredContent);
468
708
  const result = await new StreamingProviderProcessRunner().run({
469
709
  command: invocation.command,
470
710
  args: invocation.args,
471
711
  cwd: invocation.cwd,
472
- env: environment,
712
+ env: prepared.environment,
473
713
  captureOutput: false,
474
714
  }, {
475
715
  onStarted: async () => {
476
716
  clearTimeout(launchTimer);
717
+ // onProcessStarted stops the command itself when its token cannot be held.
718
+ await invocation.onProcessStarted?.();
477
719
  const running = managedCommandResult({
478
720
  ...invocation,
479
721
  timedOut: false,
@@ -517,7 +759,20 @@ async function executeManagedCommandProcess(invocation) {
517
759
  },
518
760
  }, controller.signal);
519
761
  await settleProgress();
520
- const status = timedOut ? "timed_out" : result.exitCode === 0 ? "pass" : "fail";
762
+ // Only a stop that interrupted the process relabels it. A command that exited on its own
763
+ // just before its owner asked for the stop keeps its real result.
764
+ const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
765
+ const hostCapacityLoss = !timedOut && !ownerExited && result.cancelled === true
766
+ ? hostCapacityLossReason(controller.signal.reason)
767
+ : null;
768
+ const fenced = hostCapacityLoss !== null;
769
+ if (ownerExited || fenced) {
770
+ stderr = appendBounded(stderr, ownerExited ? managedCommandOwnerExitMessage : controller.signal.reason.message);
771
+ outputRevision += 1;
772
+ lastOutputAt = Date.now();
773
+ lastOutputStream = "stderr";
774
+ }
775
+ const status = timedOut ? "timed_out" : ownerExited || fenced ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
521
776
  const receiptCoverage = managedBuildReceiptCoverage(invocation);
522
777
  const buildReceipt = status === "pass" && receiptCoverage
523
778
  ? await publishManagedBuildReceipt({
@@ -540,6 +795,9 @@ async function executeManagedCommandProcess(invocation) {
540
795
  lastOutputStream,
541
796
  buildReceipt,
542
797
  buildReceiptReused: invocation.buildReceiptReuse !== undefined,
798
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLoss ?? undefined,
799
+ // The runner resolves only after the stopped tree is proven gone.
800
+ processTreeTerminated: ownerExited || fenced ? true : undefined,
543
801
  });
544
802
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
545
803
  return managedCommandPublicResult(receipt);
@@ -547,7 +805,10 @@ async function executeManagedCommandProcess(invocation) {
547
805
  catch (error) {
548
806
  // The failure may be a progress write itself; it is reported below.
549
807
  await settleProgress().catch(() => undefined);
550
- const message = redactText(error instanceof Error ? error.message : String(error), exactSecrets);
808
+ const ownerExited = !timedOut && ownerExitStoppedCommands.has(invocation.commandId);
809
+ const message = ownerExited
810
+ ? managedCommandOwnerExitMessage
811
+ : redactText(error instanceof Error ? error.message : String(error), exactSecrets);
551
812
  stderr = appendBounded(stderr, message);
552
813
  outputRevision += 1;
553
814
  lastOutputAt = Date.now();
@@ -562,16 +823,23 @@ async function executeManagedCommandProcess(invocation) {
562
823
  outputRevision,
563
824
  lastOutputAt,
564
825
  lastOutputStream,
826
+ // A host capacity loss before launch (a fence that landed while it was admitted) is named too.
827
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLossReason(controller.signal.reason) ?? undefined,
828
+ // The runner rejected, so its tree was not proven stopped; teardown still stops it.
829
+ processTreeTerminated: false,
565
830
  });
566
831
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
832
+ // The runner stops the tree before it rejects; only a failed termination proof means
833
+ // part of it may still run. Its token is then kept, never returned with this receipt.
834
+ if (isProcessTreeTerminationUnproven(error)) {
835
+ invocation.holdHostCapacityUntilStopped?.(error instanceof Error ? error : new Error(String(error)));
836
+ }
567
837
  return managedCommandPublicResult(receipt);
568
838
  }
569
839
  finally {
570
- clearTimeout(launchTimer);
571
- if (timer)
572
- clearTimeout(timer);
573
- if (progressHeartbeat)
574
- clearInterval(progressHeartbeat);
840
+ clearManagedCommandTimers(launchTimer, timer, progressHeartbeat);
841
+ // An ephemeral verification cluster lives exactly as long as its command; one that would not stop is reaped later and named in the receipt.
842
+ await releaseManagedVerificationDatabase(prepared, async (message) => await annotateManagedCommandReceipt(invocation.receiptPath, { ephemeral_cluster_release_error: redactText(message, exactSecrets) }));
575
843
  }
576
844
  }
577
845
  async function readManagedCommand(input) {
@@ -587,6 +855,11 @@ async function readManagedCommand(input) {
587
855
  }
588
856
  throw error;
589
857
  }
858
+ // A queued receipt is written once; its wait so far is computed when it is read.
859
+ const hostLoadWaitStartedAt = Date.parse(String(receipt.host_load_wait_started_at));
860
+ if (receipt.status === "waiting_for_host_capacity" && Number.isFinite(hostLoadWaitStartedAt)) {
861
+ receipt = { ...receipt, host_load_wait_ms: Math.max(0, Date.now() - hostLoadWaitStartedAt) };
862
+ }
590
863
  const status = typeof receipt.status === "string" ? receipt.status : "unknown";
591
864
  const stdout = typeof receipt.stdout === "string" ? receipt.stdout : "";
592
865
  const stderr = typeof receipt.stderr === "string" ? receipt.stderr : "";
@@ -637,20 +910,23 @@ async function waitManagedCommand(input) {
637
910
  const elapsedMs = receipt.structuredContent.elapsed_ms;
638
911
  const timeoutMs = receipt.structuredContent.timeout_ms;
639
912
  const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
640
- const progress = receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
641
- ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
642
- + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
643
- + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
644
- // Agents otherwise abandon long verification tiers and record a blocker that is not one.
645
- + (typeof timeoutMs === "number"
646
- ? ` Forge itself ends it at its ${Math.round(timeoutMs / 60_000)}-minute limit if it hangs, so keep waiting; a running command is not a blocker.`
647
- : "")
648
- : "";
913
+ const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
914
+ const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
915
+ ? ` It has waited ${Math.round(hostLoadWaitMs / 1000)}s for host capacity${typeof receipt.structuredContent.host_load_wait_detail === "string" ? ` (${receipt.structuredContent.host_load_wait_detail})` : ""} and has not started yet; its timeout starts only once it is admitted, so queue time never counts against it. Keep waiting; a queued command is not a blocker.`
916
+ : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
917
+ ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
918
+ + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
919
+ + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
920
+ // Agents otherwise abandon long verification tiers and record a blocker that is not one.
921
+ + (typeof timeoutMs === "number"
922
+ ? ` Forge itself ends it at its ${Math.round(timeoutMs / 60_000)}-minute limit if it hangs, so keep waiting; a running command is not a blocker.`
923
+ : "")
924
+ : "";
649
925
  return {
650
926
  ...receipt,
651
927
  content: [{
652
928
  type: "text",
653
- text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Its durable receipt remains at ${receiptPath}.`,
929
+ text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Do not end your turn to wait for it: Forge ends the provider run shortly after a turn ends, which stops background monitors and this command. Its durable receipt remains at ${receiptPath}.`,
654
930
  }],
655
931
  structuredContent: {
656
932
  ...receipt.structuredContent,
@@ -667,30 +943,12 @@ function managedCommandReceiptPath(logDirectory, commandId) {
667
943
  return path.join(logDirectory, "managed-commands", `${commandId}.receipt.json`);
668
944
  }
669
945
  async function persistManagedCommandReceipt(receiptPath, receipt) {
670
- const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
671
- await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
672
- try {
673
- for (let attempt = 1;; attempt += 1) {
674
- try {
675
- await fs.rename(temporaryPath, receiptPath);
676
- break;
677
- }
678
- catch (error) {
679
- const code = error.code;
680
- if (attempt >= managedCommandReceiptReplaceAttempts
681
- || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES")) {
682
- throw error;
683
- }
684
- await delay(managedCommandReceiptReplaceRetryMs);
685
- }
686
- }
687
- }
688
- finally {
689
- await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
690
- }
946
+ await persistJsonAtomically(receiptPath, receipt);
691
947
  }
692
948
  function managedCommandResult(values) {
693
- const elapsedMs = Date.now() - values.startedAt;
949
+ // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
950
+ const hostLoad = values.hostLoad;
951
+ const elapsedMs = Date.now() - (hostLoad ? hostLoad.executionStartedAt ?? Date.now() : values.startedAt);
694
952
  const isTerminal = terminalManagedCommandStatuses.has(values.status);
695
953
  const diagnostics = isTerminal
696
954
  ? managedCommandDiagnostics(values.stdout, values.stderr)
@@ -735,6 +993,7 @@ function managedCommandResult(values) {
735
993
  build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
736
994
  build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
737
995
  build_receipt_reused: values.buildReceiptReused ?? false,
996
+ ...(hostLoad ? managedCommandHostLoadReceipt(hostLoad) : {}),
738
997
  build_receipt: values.buildReceipt ? {
739
998
  fingerprint: values.buildReceipt.fingerprint,
740
999
  receipt_path: values.buildReceipt.receiptPath,
@@ -744,11 +1003,34 @@ function managedCommandResult(values) {
744
1003
  output_count: values.buildReceipt.outputCount,
745
1004
  } : null,
746
1005
  runtime_configuration: managedRuntimeConfiguration(),
747
- process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : undefined,
1006
+ // The supervising MCP server process. Forge stops a command whose owner has exited.
1007
+ owner_pid: process.pid,
1008
+ owner_identity: managedCommandOwnerIdentity(),
1009
+ launch_requested: values.launchRequested ?? true,
1010
+ process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : values.processTreeTerminated,
1011
+ ...(values.terminationReason ? { termination_reason: values.terminationReason } : {}),
748
1012
  },
749
1013
  isError: isTerminal && values.status !== "pass",
750
1014
  };
751
1015
  }
1016
+ function managedCommandHostLoadReceipt(hostLoad) {
1017
+ const waiting = hostLoad.waitStartedAt !== undefined;
1018
+ return {
1019
+ host_load_step_class: hostLoad.stepClass,
1020
+ host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
1021
+ ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString(), host_load_wait_detail: hostLoad.waitDetail ?? null } : {}),
1022
+ };
1023
+ }
1024
+ async function annotateManagedCommandReceipt(receiptPath, fields) {
1025
+ const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
1026
+ await persistManagedCommandReceipt(receiptPath, { ...receipt, ...fields });
1027
+ }
1028
+ /** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
1029
+ function managedCommandOwnerIdentity() {
1030
+ // Windows identity capture starts PowerShell; the PID check alone is used there.
1031
+ ownerProcessIdentity ??= process.platform === "linux" ? captureHostProcessIdentity(process.pid) : null;
1032
+ return ownerProcessIdentity;
1033
+ }
752
1034
  function managedRuntimeConfiguration() {
753
1035
  const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
754
1036
  let providerOnlySpecCount = 0;
@@ -818,26 +1100,15 @@ async function containedWorkingDirectory(worktreePath, input) {
818
1100
  }
819
1101
  function inheritedEnvironment(overrides) {
820
1102
  const env = {};
821
- for (const [key, value] of Object.entries(process.env)) {
1103
+ // A nested Forge process must not join the host ledger: it would queue behind the
1104
+ // token this command already holds. Every FORGE_HOST_LOAD_* variable is dropped,
1105
+ // the test slot count too (decision 0018).
1106
+ for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(process.env))) {
822
1107
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
823
1108
  env[key] = value;
824
1109
  }
825
1110
  return { ...env, ...overrides };
826
1111
  }
827
- /**
828
- * Runner-authored verification normally uses its attempt-owned Testcontainers
829
- * database. Only when the Docker engine is unavailable does it switch to the
830
- * operator-provisioned native test cluster, which holds no real data.
831
- */
832
- export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().refresh(true)).available, readFallback = () => {
833
- const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
834
- return configPath ? readNativeTestPostgresFallback(configPath) : null;
835
- }) {
836
- const fallback = readFallback();
837
- if (!fallback || await dockerAvailable())
838
- return {};
839
- return nativeTestPostgresFallbackEnvironment(fallback);
840
- }
841
1112
  export function isBuildProducingManagedCommand(command, args) {
842
1113
  const executable = path.basename(command).toLowerCase();
843
1114
  if (executable === "dotnet" || executable === "dotnet.exe") {
@@ -849,10 +1120,7 @@ export function isBuildProducingManagedCommand(command, args) {
849
1120
  if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
850
1121
  const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
851
1122
  const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
852
- if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
853
- return !args.some(argument => argument.toLowerCase() === "-nobuild");
854
- }
855
- if (script === "run-dotnet-test-tier.ps1") {
1123
+ if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)) {
856
1124
  return !args.some(argument => argument.toLowerCase() === "-nobuild");
857
1125
  }
858
1126
  }
@@ -907,8 +1175,17 @@ function asRecord(value) {
907
1175
  throw new Error("managed_command_invalid: input must be an object.");
908
1176
  return value;
909
1177
  }
1178
+ const requiredInputExamples = {
1179
+ command: "Send the executable as command and each argument as its own string in args, for example {\"command\": \"pnpm\", \"args\": [\"--dir\", \"client\", \"lint\"]}.",
1180
+ profile: managedVerificationProfileHint,
1181
+ command_id: "Send the command_id returned by forge.start_managed_command or forge.start_managed_verification.",
1182
+ };
910
1183
  function requiredInputString(record, name) {
911
- return requiredStandaloneString(record[name], name);
1184
+ const value = record[name];
1185
+ if (typeof value === "string" && value.trim())
1186
+ return value.trim();
1187
+ const hints = [requiredInputExamples[name], isEmptyToolInput(record) ? emptyToolInputHint : undefined].filter(Boolean);
1188
+ throw new Error(`managed_command_invalid: ${name} is required.${hints.length > 0 ? ` ${hints.join(" ")}` : ""}`);
912
1189
  }
913
1190
  function validatedCommandId(record) {
914
1191
  const commandId = requiredInputString(record, "command_id");
@@ -925,7 +1202,13 @@ function requiredStandaloneString(value, name) {
925
1202
  function requiredStringArray(record, name) {
926
1203
  const value = record[name];
927
1204
  if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) {
928
- throw new Error(`managed_command_invalid: ${name} must be a string array.`);
1205
+ const shellLine = typeof record.command === "string" && /\s/u.test(record.command.trim());
1206
+ const hint = typeof value === "string"
1207
+ ? " (received a string). Put each argument in its own string, for example [\"--dir\", \"client\", \"test\"]."
1208
+ : value === undefined
1209
+ ? ` (it was omitted). Send [] when there are no arguments.${shellLine ? " command holds only the executable, so move its arguments into args; shell syntax such as cd, &&, or pipes is not interpreted, so set cwd instead of cd." : ""}`
1210
+ : " Every argument must be a string.";
1211
+ throw new Error(`managed_command_invalid: ${name} must be a string array${hint}`);
929
1212
  }
930
1213
  return value;
931
1214
  }