@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.03584818ede5

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 (275) hide show
  1. package/README.md +146 -5
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  6. package/dist/bridge/bridge.base.d.ts +13 -1
  7. package/dist/bridge/bridge.service.d.ts +155 -4
  8. package/dist/bridge/bridge.service.js +1805 -155
  9. package/dist/bridge/bridge.types.d.ts +68 -1
  10. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  11. package/dist/bridge/dispatch-result-outbox.js +87 -0
  12. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  13. package/dist/bridge/dispatch-result-worker.js +122 -0
  14. package/dist/bridge/internals.d.ts +2 -0
  15. package/dist/bridge/internals.js +1 -0
  16. package/dist/bridge/local-yield-flag.d.ts +6 -0
  17. package/dist/bridge/local-yield-flag.js +34 -0
  18. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  19. package/dist/bridge/readiness-result-outbox.js +54 -0
  20. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  21. package/dist/bridge/readiness-result-worker.js +121 -0
  22. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +110 -0
  24. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  25. package/dist/bridge/test-postgres-capability.js +120 -0
  26. package/dist/cleanup/cleanup.service.d.ts +10 -0
  27. package/dist/cleanup/cleanup.service.js +128 -104
  28. package/dist/cleanup/cleanup.types.d.ts +4 -0
  29. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  30. package/dist/cleanup/forge-owned-paths.js +53 -0
  31. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  32. package/dist/cleanup/host-runtime-ledger.js +109 -0
  33. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  34. package/dist/cleanup/managed-branch-sweep.js +111 -0
  35. package/dist/cli/cli.help.js +22 -4
  36. package/dist/cli/cli.service.d.ts +30 -6
  37. package/dist/cli/cli.service.js +216 -31
  38. package/dist/cli/local-config.d.ts +5 -0
  39. package/dist/cli/local-config.js +30 -4
  40. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  41. package/dist/runtime/aspnet-runtime-prebuild.js +429 -0
  42. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  43. package/dist/runtime/attempt-database-broker.js +390 -0
  44. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  45. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  46. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  47. package/dist/runtime/attempt-path-operation.js +94 -0
  48. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  49. package/dist/runtime/attempt-private-directory.js +54 -0
  50. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  51. package/dist/runtime/attempt-process-supervisor.js +144 -23
  52. package/dist/runtime/canonical-source-file.d.ts +3 -0
  53. package/dist/runtime/canonical-source-file.js +54 -0
  54. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  55. package/dist/runtime/docker-engine-probe.js +333 -0
  56. package/dist/runtime/generated-output-reset.d.ts +10 -0
  57. package/dist/runtime/generated-output-reset.js +62 -8
  58. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  59. package/dist/runtime/host-database-capability-boundary.js +63 -0
  60. package/dist/runtime/host-diagnostics.d.ts +11 -0
  61. package/dist/runtime/host-diagnostics.js +192 -0
  62. package/dist/runtime/host-execution-root.d.ts +4 -0
  63. package/dist/runtime/host-execution-root.js +39 -0
  64. package/dist/runtime/host-facts.d.ts +36 -0
  65. package/dist/runtime/host-facts.js +95 -0
  66. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  67. package/dist/runtime/host-listener-inspector.js +121 -60
  68. package/dist/runtime/host-load-admission.d.ts +67 -0
  69. package/dist/runtime/host-load-admission.js +99 -0
  70. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  71. package/dist/runtime/host-load-child-environment.js +76 -0
  72. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  73. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  74. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  75. package/dist/runtime/host-load-governor-config.js +83 -0
  76. package/dist/runtime/host-load-governor.d.ts +184 -0
  77. package/dist/runtime/host-load-governor.js +632 -0
  78. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  79. package/dist/runtime/host-load-ledger-lock.js +185 -0
  80. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  81. package/dist/runtime/host-load-runtime-settings.js +78 -0
  82. package/dist/runtime/host-load-sampler.d.ts +149 -0
  83. package/dist/runtime/host-load-sampler.js +291 -0
  84. package/dist/runtime/host-load-step-class.d.ts +70 -0
  85. package/dist/runtime/host-load-step-class.js +161 -0
  86. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  87. package/dist/runtime/host-load-step-reaper.js +95 -0
  88. package/dist/runtime/host-load-step-run.d.ts +73 -0
  89. package/dist/runtime/host-load-step-run.js +102 -0
  90. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  91. package/dist/runtime/host-load-test-slot.js +81 -0
  92. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  93. package/dist/runtime/host-load-token-ledger.js +453 -0
  94. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  95. package/dist/runtime/host-load-windows-cpu.js +85 -0
  96. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  97. package/dist/runtime/host-pressure-stall.js +168 -0
  98. package/dist/runtime/host-runtime-contract.d.ts +16 -1
  99. package/dist/runtime/host-runtime-contract.js +174 -56
  100. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  101. package/dist/runtime/host-runtime-lease.js +1464 -121
  102. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  103. package/dist/runtime/host-runtime-promotion.js +107 -12
  104. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  105. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  106. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  107. package/dist/runtime/host-runtime-requirements.js +117 -0
  108. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  109. package/dist/runtime/managed-command-teardown.js +607 -0
  110. package/dist/runtime/memory-capacity.d.ts +70 -0
  111. package/dist/runtime/memory-capacity.js +123 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  113. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  114. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  115. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  116. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  117. package/dist/runtime/pinned-directory-process.js +61 -0
  118. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  119. package/dist/runtime/pinned-source-directory.js +94 -0
  120. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  121. package/dist/runtime/playwright-browser-cache.js +227 -0
  122. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  123. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  124. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  125. package/dist/runtime/prepared-runtime-identity.js +218 -0
  126. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  127. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  128. package/dist/runtime/runner-settings.d.ts +100 -0
  129. package/dist/runtime/runner-settings.js +214 -0
  130. package/dist/runtime/runtime-isolation-lease.js +4 -1
  131. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  132. package/dist/runtime/workspace-resource-estimator.js +174 -0
  133. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  134. package/dist/sandbox/host-capacity-broker.js +334 -0
  135. package/dist/sandbox/preflight.d.ts +31 -1
  136. package/dist/sandbox/preflight.js +237 -51
  137. package/dist/sandbox/repository-lock.d.ts +2 -1
  138. package/dist/sandbox/repository-lock.js +19 -9
  139. package/dist/sandbox/runtime.d.ts +16 -2
  140. package/dist/sandbox/runtime.js +182 -109
  141. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  142. package/dist/sandbox/sandbox-cgroups.js +42 -0
  143. package/dist/sandbox/sandbox.types.d.ts +7 -0
  144. package/dist/sandbox/workspace.service.js +2 -0
  145. package/dist/session/architect-waits.d.ts +2 -0
  146. package/dist/session/architect-waits.js +138 -0
  147. package/dist/session/managed-attempt-tools.d.ts +44 -1
  148. package/dist/session/managed-attempt-tools.js +816 -46
  149. package/dist/session/managed-build-coordinator.d.ts +5 -0
  150. package/dist/session/managed-build-coordinator.js +109 -0
  151. package/dist/session/managed-build-receipt.d.ts +21 -0
  152. package/dist/session/managed-build-receipt.js +337 -0
  153. package/dist/session/managed-command-host-load.d.ts +47 -0
  154. package/dist/session/managed-command-host-load.js +83 -0
  155. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  156. package/dist/session/managed-verification-timeouts.js +17 -0
  157. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  158. package/dist/session/mcp-argument-coercion.js +121 -0
  159. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  160. package/dist/session/phase-completion.artifacts.js +319 -44
  161. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  162. package/dist/session/phase-completion.command-validation.js +77 -0
  163. package/dist/session/phase-completion.d.ts +15 -1
  164. package/dist/session/phase-completion.helpers.d.ts +5 -0
  165. package/dist/session/phase-completion.helpers.js +43 -19
  166. package/dist/session/phase-completion.js +18 -3
  167. package/dist/session/phase-completion.prompts.js +22 -18
  168. package/dist/session/phase-completion.runtime.d.ts +6 -2
  169. package/dist/session/phase-completion.runtime.js +191 -47
  170. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  171. package/dist/session/phase-completion.schema-parts.js +188 -0
  172. package/dist/session/phase-completion.schemas.d.ts +3 -3
  173. package/dist/session/phase-completion.schemas.js +250 -226
  174. package/dist/session/phase-completion.validation.d.ts +3 -3
  175. package/dist/session/phase-completion.validation.js +135 -89
  176. package/dist/session/pre-publication-host-load.d.ts +27 -0
  177. package/dist/session/pre-publication-host-load.js +111 -0
  178. package/dist/session/pre-publication-pass.d.ts +61 -0
  179. package/dist/session/pre-publication-pass.js +148 -0
  180. package/dist/session/pre-publication-process.d.ts +23 -0
  181. package/dist/session/pre-publication-process.js +109 -0
  182. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  183. package/dist/session/pre-publication-skipped-tests.js +109 -0
  184. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  185. package/dist/session/pre-publication-step-execution.js +49 -0
  186. package/dist/session/pre-publication-validation.d.ts +87 -0
  187. package/dist/session/pre-publication-validation.js +668 -0
  188. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  189. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  190. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  191. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  192. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  193. package/dist/session/provider-cli/claude-background-work.js +180 -0
  194. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  195. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  196. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  197. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  198. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  199. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  200. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  201. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  202. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  203. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  204. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  205. package/dist/session/provider-cli/provider-cli.process.d.ts +92 -14
  206. package/dist/session/provider-cli/provider-cli.process.js +583 -210
  207. package/dist/session/provider-cli/provider-cli.prompts.d.ts +12 -0
  208. package/dist/session/provider-cli/provider-cli.prompts.js +200 -25
  209. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  210. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  211. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  212. package/dist/session/provider-cli/provider-cli.runtime.js +61 -3
  213. package/dist/session/provider-cli/provider-cli.service.d.ts +33 -5
  214. package/dist/session/provider-cli/provider-cli.service.js +819 -84
  215. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  216. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  217. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  218. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  219. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  220. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  221. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  222. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  223. package/dist/session/provider-cli/provider-output-state.js +376 -17
  224. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  225. package/dist/session/provider-cli/provider-usage.js +28 -5
  226. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  227. package/dist/session/publishable-worktree-changes.js +193 -0
  228. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  229. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  230. package/dist/session/session-redaction.js +434 -9
  231. package/dist/session/session.base.d.ts +9 -1
  232. package/dist/session/session.service.d.ts +9 -2
  233. package/dist/session/session.service.js +264 -27
  234. package/dist/session/session.types.d.ts +150 -2
  235. package/dist/session/session.types.js +599 -7
  236. package/dist/session/unreferenced-exports.d.ts +12 -0
  237. package/dist/session/unreferenced-exports.js +59 -0
  238. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  239. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  240. package/dist/shared/format/format-bytes.d.ts +1 -0
  241. package/dist/shared/format/format-bytes.js +9 -0
  242. package/dist/shared/git/git.js +2 -1
  243. package/dist/shared/path/path.d.ts +1 -0
  244. package/dist/shared/path/path.js +18 -0
  245. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  246. package/dist/shared/process/dotnet-toolchain.js +307 -0
  247. package/dist/shared/process/host-process-recovery.js +3 -2
  248. package/dist/shared/process/host-process-supervisor.d.ts +3 -0
  249. package/dist/shared/process/host-process-supervisor.js +61 -12
  250. package/dist/shared/process/process-tree.d.ts +52 -0
  251. package/dist/shared/process/process-tree.js +144 -0
  252. package/dist/shared/process/process.d.ts +69 -0
  253. package/dist/shared/process/process.js +223 -16
  254. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  255. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  256. package/dist/shared/process/windows-launch.d.ts +18 -0
  257. package/dist/shared/process/windows-launch.js +68 -0
  258. package/dist/shared/provider-capabilities.d.ts +3 -0
  259. package/dist/shared/provider-capabilities.js +84 -0
  260. package/dist/shared/redaction/redaction.d.ts +1 -0
  261. package/dist/shared/redaction/redaction.js +39 -3
  262. package/dist/shared/time/monotonic.d.ts +1 -0
  263. package/dist/shared/time/monotonic.js +8 -0
  264. package/dist/version.d.ts +1 -1
  265. package/dist/version.js +1 -1
  266. package/dist/worktree/dependency-warmer.d.ts +66 -9
  267. package/dist/worktree/dependency-warmer.js +609 -24
  268. package/dist/worktree/index.d.ts +1 -1
  269. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  270. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  271. package/dist/worktree/worktree.service.d.ts +17 -1
  272. package/dist/worktree/worktree.service.js +293 -21
  273. package/dist/worktree/worktree.types.d.ts +14 -1
  274. package/package.json +8 -6
  275. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -1,17 +1,40 @@
1
- import { randomUUID } from "node:crypto";
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 { StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
6
+ import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
7
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
8
+ import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
9
+ import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
10
+ import { redactText } from "../shared/redaction/redaction.js";
11
+ import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
12
+ import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
13
+ import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
14
+ import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
15
+ import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
16
+ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
17
+ import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
18
+ import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
19
+ import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
20
+ import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
21
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
22
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
6
23
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
7
24
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
8
25
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
9
26
  const waitManagedCommandNames = new Set(["forge.wait_managed_command", "wait_managed_command"]);
27
+ const startManagedVerificationNames = new Set(["forge.start_managed_verification", "start_managed_verification"]);
10
28
  const resetGeneratedOutputNames = new Set(["forge.reset_generated_outputs", "reset_generated_outputs"]);
11
29
  const maximumCapturedCharacters = 200_000;
12
- const maximumReturnedOutputCharacters = 12_000;
30
+ const maximumReturnedOutputCharacters = 4_000;
13
31
  const maximumReportedFailedTests = 50;
14
- const maximumSynchronousWaitMs = 240_000;
32
+ // Keep a wait slice comfortably below the MCP transport deadline. The managed
33
+ // process remains supervised and its durable receipt continues to update after
34
+ // this call returns, so a shorter slice avoids converting healthy long-running
35
+ // commands into ambiguous MCP failures.
36
+ const maximumSynchronousWaitMs = 45_000;
37
+ const managedCommandRetryAfterMs = 60_000;
15
38
  const managedCommandLaunchTimeoutMs = 60_000;
16
39
  const managedCommandProgressPersistIntervalMs = 5_000;
17
40
  const managedCommandReceiptPollIntervalMs = 1_000;
@@ -24,7 +47,16 @@ const terminalManagedCommandStatuses = new Set([
24
47
  "timeout_termination_failed",
25
48
  "runner_error",
26
49
  ]);
50
+ const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
27
51
  const managedCommandTasks = new Map();
52
+ // Every command this MCP server is supervising, synchronous or not. The server is the only
53
+ // writer of their receipts, so it stops them before it exits.
54
+ const activeManagedCommands = new Map();
55
+ const ownerExitStoppedCommands = new Set();
56
+ let ownerProcessIdentity;
57
+ let managedCommandOwnerShuttingDown = false;
58
+ let ownerExitSweep = null;
59
+ 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.";
28
60
  export const managedAttemptToolNames = [
29
61
  "forge.run_managed_command",
30
62
  "run_managed_command",
@@ -34,30 +66,133 @@ export const managedAttemptToolNames = [
34
66
  "get_managed_command",
35
67
  "forge.wait_managed_command",
36
68
  "wait_managed_command",
69
+ "forge.start_managed_verification",
70
+ "start_managed_verification",
37
71
  "forge.reset_generated_outputs",
38
72
  "reset_generated_outputs",
39
73
  ];
74
+ /**
75
+ * Stops every managed command this MCP server started, proves each process tree stopped,
76
+ * and writes their terminal receipts. Called when the provider closes the MCP connection
77
+ * or the server is signalled: once this server exits nothing could supervise them.
78
+ */
79
+ export async function stopManagedCommandsForOwnerExit() {
80
+ // One sweep at a time: a signal that arrives while a sweep runs waits for that sweep.
81
+ ownerExitSweep ??= sweepManagedCommandsForOwnerExit().finally(() => { ownerExitSweep = null; });
82
+ await ownerExitSweep;
83
+ }
84
+ async function sweepManagedCommandsForOwnerExit() {
85
+ // From here on this server refuses new commands, so a request still being handled
86
+ // cannot launch one behind the sweep. Repeat until none is left: a launch that passed
87
+ // its last check just before the flag was set registers synchronously and is caught.
88
+ managedCommandOwnerShuttingDown = true;
89
+ while (activeManagedCommands.size > 0) {
90
+ const active = [...activeManagedCommands.entries()];
91
+ for (const [commandId, command] of active) {
92
+ ownerExitStoppedCommands.add(commandId);
93
+ command.controller.abort(new Error(managedCommandOwnerExitMessage));
94
+ }
95
+ await Promise.allSettled(active.map(([, command]) => command.task));
96
+ }
97
+ }
98
+ /** Test support: lets one test process act as a fresh MCP server after a simulated exit. */
99
+ export function resetManagedCommandOwnerShutdownForTesting() {
100
+ managedCommandOwnerShuttingDown = false;
101
+ }
102
+ function assertManagedCommandsAccepted() {
103
+ if (managedCommandOwnerShuttingDown) {
104
+ throw new Error("managed_command_unavailable: the Forge MCP server is shutting down and accepts no new managed commands.");
105
+ }
106
+ }
107
+ const ownerShutdownSignals = ["SIGTERM", "SIGHUP", "SIGINT"];
108
+ /**
109
+ * Makes a termination signal stop this server's managed commands before it exits, so none
110
+ * outlives its only supervisor. Returns a function that removes the handlers.
111
+ */
112
+ export function installOwnerShutdownHandlers(target = process, exit = code => process.exit(code)) {
113
+ const handlers = ownerShutdownSignals.map(signal => {
114
+ const handler = () => {
115
+ void stopManagedCommandsForOwnerExit().finally(() => exit(128 + os.constants.signals[signal]));
116
+ };
117
+ target.once(signal, handler);
118
+ return { signal, handler };
119
+ });
120
+ return () => {
121
+ for (const { signal, handler } of handlers)
122
+ target.removeListener(signal, handler);
123
+ };
124
+ }
125
+ /**
126
+ * Runs an MCP server body, then stops every managed command it started before returning.
127
+ * The signal handlers stay installed until that stop completes: a signal during the body
128
+ * or the stop exits only after the same stop finishes, never by Node's default exit.
129
+ */
130
+ export async function runWithOwnerShutdown(body, target = process, exit = code => process.exit(code)) {
131
+ const removeShutdownHandlers = installOwnerShutdownHandlers(target, exit);
132
+ try {
133
+ return await body();
134
+ }
135
+ finally {
136
+ try {
137
+ await stopManagedCommandsForOwnerExit();
138
+ }
139
+ finally {
140
+ removeShutdownHandlers();
141
+ }
142
+ }
143
+ }
40
144
  export function isManagedAttemptTool(name) {
41
145
  return managedCommandNames.has(name)
42
146
  || startManagedCommandNames.has(name)
43
147
  || getManagedCommandNames.has(name)
44
148
  || waitManagedCommandNames.has(name)
149
+ || startManagedVerificationNames.has(name)
45
150
  || resetGeneratedOutputNames.has(name);
46
151
  }
152
+ const managedVerificationProfiles = ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"];
153
+ 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.`;
154
+ /** The input schema a managed-attempt tool advertises; also the shape its arguments are coerced to. */
155
+ export function managedAttemptToolInputSchema(name) {
156
+ return managedAttemptToolDefinition(name).inputSchema;
157
+ }
47
158
  export function managedAttemptToolDefinition(name) {
159
+ if (startManagedVerificationNames.has(name)) {
160
+ return {
161
+ name,
162
+ 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.",
163
+ inputSchema: {
164
+ type: "object",
165
+ additionalProperties: false,
166
+ required: ["profile"],
167
+ properties: {
168
+ profile: {
169
+ type: "string",
170
+ enum: [...managedVerificationProfiles],
171
+ 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.",
172
+ },
173
+ 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." },
174
+ 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." },
175
+ 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." },
176
+ max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
177
+ 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." },
178
+ timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
179
+ },
180
+ },
181
+ };
182
+ }
48
183
  if (managedCommandNames.has(name) || startManagedCommandNames.has(name)) {
49
184
  return {
50
185
  name,
51
186
  description: startManagedCommandNames.has(name)
52
- ? "Start a long command in an attempt-owned process tree and return a durable command ID immediately. Continue independent work, then call forge.wait_managed_command once for its terminal receipt."
53
- : "Run a short command in an attempt-owned process tree. Commands with a timeout above four minutes automatically start asynchronously; continue independent work, then call forge.wait_managed_command once for the durable result.",
187
+ ? "Start a long command in an attempt-owned process tree and return a durable command ID immediately. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt."
188
+ : "Run a short command in an attempt-owned process tree. Commands with a timeout above four minutes automatically start asynchronously; continue independent work, then use forge.wait_managed_command for the durable result.",
54
189
  inputSchema: {
55
190
  type: "object",
56
191
  additionalProperties: false,
57
192
  required: ["command", "args"],
58
193
  properties: {
59
- command: { type: "string", minLength: 1 },
60
- args: { type: "array", items: { type: "string" } },
194
+ 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." },
195
+ 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." },
61
196
  cwd: { type: "string", description: "Worktree-relative directory; defaults to the worktree root." },
62
197
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 2700000 },
63
198
  },
@@ -81,14 +216,14 @@ export function managedAttemptToolDefinition(name) {
81
216
  if (waitManagedCommandNames.has(name)) {
82
217
  return {
83
218
  name,
84
- description: "Wait for a command started by Forge's managed command runner to reach a terminal state. Use this once after completing work that is independent of the command; Forge streams durable progress while this call waits.",
219
+ description: "Wait up to 45 seconds for a managed command terminal receipt. If it remains active, the call succeeds with command_continues=true and retry_after_ms; continue independent work or wait again later. Live progress remains in the durable receipt/UI; do not poll get_managed_command.",
85
220
  inputSchema: {
86
221
  type: "object",
87
222
  additionalProperties: false,
88
223
  required: ["command_id"],
89
224
  properties: {
90
225
  command_id: { type: "string", minLength: 1 },
91
- wait_timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 7200000 },
226
+ wait_timeout_ms: { type: "integer", minimum: 1000, maximum: 45000, default: 45000 },
92
227
  },
93
228
  },
94
229
  };
@@ -113,6 +248,7 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
113
248
  structuredContent: {
114
249
  status: "pass",
115
250
  quarantined_paths: result.quarantinedPaths,
251
+ retained_paths: result.retainedPaths,
116
252
  quarantine_directory: result.quarantineDirectory,
117
253
  },
118
254
  };
@@ -123,14 +259,21 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
123
259
  if (waitManagedCommandNames.has(name)) {
124
260
  return await waitManagedCommand(input);
125
261
  }
262
+ if (startManagedVerificationNames.has(name)) {
263
+ return await startManagedVerification(input, worktreePath);
264
+ }
126
265
  if (!managedCommandNames.has(name) && !startManagedCommandNames.has(name)) {
127
266
  throw new Error(`Unknown managed attempt tool: ${name}`);
128
267
  }
129
- const record = asRecord(input);
268
+ return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
269
+ }
270
+ async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
271
+ assertManagedCommandsAccepted();
130
272
  const command = requiredInputString(record, "command");
131
273
  const args = requiredStringArray(record, "args");
132
274
  const timeoutMs = optionalTimeout(record.timeout_ms);
133
275
  const cwd = await containedWorkingDirectory(worktreePath, record.cwd);
276
+ await validatePlaywrightCommandProject(command, args, cwd);
134
277
  const logDirectory = requiredAttemptEnvironment("FORGE_LOG_DIR");
135
278
  await fs.mkdir(path.join(logDirectory, "managed-commands"), { recursive: true, mode: 0o700 });
136
279
  const commandId = randomUUID();
@@ -146,8 +289,13 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
146
289
  metadataPath,
147
290
  receiptPath,
148
291
  startedAt: Date.now(),
292
+ verificationProfile,
293
+ worktreePath,
294
+ buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
295
+ buildReceiptReuse,
296
+ controller: new AbortController(),
149
297
  };
150
- if (startManagedCommandNames.has(name) || timeoutMs > maximumSynchronousWaitMs) {
298
+ if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
151
299
  const started = managedCommandResult({
152
300
  ...invocation,
153
301
  timedOut: false,
@@ -155,22 +303,307 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
155
303
  exitCode: null,
156
304
  stdout: "",
157
305
  stderr: "",
306
+ launchRequested: false,
158
307
  });
159
308
  await persistManagedCommandReceipt(receiptPath, started.structuredContent);
160
- 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);
161
325
  managedCommandTasks.set(commandId, task);
162
326
  void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
163
327
  return {
164
- ...started,
328
+ ...managedCommandPublicResult(started),
165
329
  content: [{
166
330
  type: "text",
167
- text: `Forge managed command ${commandId} started asynchronously. Continue independent work, then call forge.wait_managed_command once with this command_id for the terminal receipt.`,
331
+ text: `Forge managed command ${commandId} started asynchronously. Continue independent work, then use forge.wait_managed_command with this command_id for a transport-safe terminal receipt.`,
168
332
  }],
169
333
  };
170
334
  }
171
- 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;
345
+ }
346
+ async function startManagedVerification(input, worktreePath) {
347
+ const record = asRecord(input);
348
+ const profile = requiredInputString(record, "profile");
349
+ const shardCount = optionalBoundedInteger(record.shard_count, "shard_count", 1, 32, 1);
350
+ const shardIndex = optionalBoundedInteger(record.shard_index, "shard_index", 0, 31, 0);
351
+ if (shardIndex >= shardCount) {
352
+ throw new Error("managed_verification_invalid: shard_index must be less than shard_count.");
353
+ }
354
+ const noBuild = optionalBoolean(record.no_build, "no_build", false);
355
+ const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
356
+ const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
357
+ if (runAllShards && shardCount < 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.");
359
+ }
360
+ if (runAllShards && shardIndex !== 0) {
361
+ throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
362
+ }
363
+ if (runAllShards && noBuild) {
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.");
365
+ }
366
+ const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
367
+ const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
368
+ const buildReceiptReuse = noBuild
369
+ ? await verifyManagedBuildReceipt({
370
+ worktreePath,
371
+ configuration: managedBuildConfiguration(profileCommand.command, profileCommand.args),
372
+ requiredCoverage: managedVerificationBuildCoverage,
373
+ })
374
+ : undefined;
375
+ return await launchManagedCommand({
376
+ command: profileCommand.command,
377
+ args: profileCommand.args,
378
+ timeout_ms: record.timeout_ms ?? profileCommand.timeoutMs,
379
+ }, worktreePath, true, profile, !noBuild, buildReceiptReuse);
380
+ }
381
+ export function buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards = false, maxParallelism = 2) {
382
+ if (profile === "dotnet_affected") {
383
+ // The tests an uncommitted change can affect: one build, Unit and Contract whole, then
384
+ // only the affected heavier-tier classes. The script owns its build and its selection.
385
+ if (runAllShards || shardCount !== 1 || shardIndex !== 0 || noBuild) {
386
+ throw new Error("managed_verification_invalid: dotnet_affected selects its own tests and owns its build; it accepts no sharding or no_build.");
387
+ }
388
+ return {
389
+ command: process.execPath,
390
+ args: ["scripts/run-affected-dotnet-tests.mjs", "--results-directory", outputDirectory],
391
+ // A change that reaches tests without naming a type runs the heavier tiers whole.
392
+ timeoutMs: managedMaximumCommandTimeoutMs,
393
+ };
394
+ }
395
+ if (profile === "dotnet_solution") {
396
+ if (runAllShards) {
397
+ throw new Error("managed_verification_invalid: dotnet_solution does not support run_all_shards; select a test tier instead.");
398
+ }
399
+ if (shardCount !== 1 || shardIndex !== 0) {
400
+ throw new Error("managed_verification_invalid: dotnet_solution does not accept sharding; select a test tier instead.");
401
+ }
402
+ const command = preferredPowerShellExecutable();
403
+ const args = [
404
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-suite.ps1",
405
+ "-ResultsDirectory", outputDirectory,
406
+ "-MaxParallelism", String(maxParallelism),
407
+ ];
408
+ if (noBuild)
409
+ args.push("-NoBuild");
410
+ return { command, args, timeoutMs: managedLongTierTimeoutMs };
411
+ }
412
+ const tiers = {
413
+ dotnet_unit: "Unit",
414
+ dotnet_contract: "Contract",
415
+ dotnet_api_component: "ApiComponent",
416
+ dotnet_orchestration: "Orchestration",
417
+ dotnet_infrastructure: "Infrastructure",
418
+ };
419
+ const tier = tiers[profile];
420
+ if (!tier)
421
+ throw new Error(`managed_verification_invalid: unsupported profile ${profile}. ${managedVerificationProfileHint}`);
422
+ const command = preferredPowerShellExecutable();
423
+ if (runAllShards) {
424
+ return {
425
+ command,
426
+ args: [
427
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier-set.ps1",
428
+ "-Tier", tier,
429
+ "-ResultsDirectory", outputDirectory,
430
+ "-ShardCount", String(shardCount),
431
+ "-MaxParallelism", String(maxParallelism),
432
+ ],
433
+ timeoutMs: managedVerificationTierTimeoutMs(tier, { shardCount, maxParallelism }),
434
+ };
435
+ }
436
+ const args = [
437
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier.ps1",
438
+ "-Tier", tier,
439
+ "-ResultsDirectory", outputDirectory,
440
+ "-ShardCount", String(shardCount),
441
+ "-ShardIndex", String(shardIndex),
442
+ ];
443
+ if (noBuild)
444
+ args.push("-NoBuild");
445
+ return { command, args, timeoutMs: managedVerificationTierTimeoutMs(tier) };
446
+ }
447
+ export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
448
+ if (platform !== "win32")
449
+ return "pwsh";
450
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
451
+ }
452
+ export function validatePlaywrightProjectName(project, availableProjects) {
453
+ if (!availableProjects.includes(project)) {
454
+ throw new Error(`managed_command_capability_unavailable: Playwright project '${project}' is not advertised by the selected config. Available projects: ${availableProjects.join(", ") || "none"}.`);
455
+ }
456
+ }
457
+ async function validatePlaywrightCommandProject(command, args, cwd) {
458
+ const invocation = [path.basename(command).toLowerCase(), ...args.map(argument => argument.toLowerCase())];
459
+ if (!invocation.some(argument => argument.includes("playwright")))
460
+ return;
461
+ const project = optionValue(args, "--project");
462
+ if (!project)
463
+ return;
464
+ const configuredPath = optionValue(args, "--config") ?? process.env.FORGE_PLAYWRIGHT_CONFIG;
465
+ const candidates = configuredPath
466
+ ? [path.resolve(cwd, configuredPath)]
467
+ : ["playwright.config.ts", "playwright.config.js", "playwright.config.mjs"].map(file => path.join(cwd, file));
468
+ for (const candidate of candidates) {
469
+ try {
470
+ const source = await fs.readFile(candidate, "utf8");
471
+ const projects = playwrightProjectNamesFromConfigSource(source);
472
+ validatePlaywrightProjectName(project, projects);
473
+ return;
474
+ }
475
+ catch (error) {
476
+ if (error.code !== "ENOENT")
477
+ throw error;
478
+ }
479
+ }
480
+ throw new Error("managed_command_capability_unavailable: Playwright config was not found; project selection cannot be validated.");
481
+ }
482
+ export function playwrightProjectNamesFromConfigSource(source) {
483
+ const marker = source.match(/^\/\/ forge-playwright-projects: (\[[^\r\n]*\])$/mu)?.[1];
484
+ if (!marker) {
485
+ return [...source.matchAll(/\bname\s*:\s*["']([^"']+)["']/gu)].map(match => match[1]);
486
+ }
487
+ try {
488
+ const parsed = JSON.parse(marker);
489
+ return Array.isArray(parsed)
490
+ ? parsed.filter((value) => typeof value === "string" && value.trim().length > 0)
491
+ : [];
492
+ }
493
+ catch {
494
+ return [];
495
+ }
496
+ }
497
+ function optionValue(args, name) {
498
+ const direct = args.find(argument => argument.startsWith(`${name}=`));
499
+ if (direct)
500
+ return direct.slice(name.length + 1).trim() || null;
501
+ const index = args.indexOf(name);
502
+ return index >= 0 ? args[index + 1]?.trim() || null : null;
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;
172
510
  }
173
511
  async function executeManagedCommand(invocation) {
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({
583
+ ...invocation,
584
+ hostLoad: await hostCapacity.unadmittedFields(error),
585
+ timedOut: false,
586
+ status: "runner_error",
587
+ exitCode: null,
588
+ stdout: "",
589
+ stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
590
+ terminationReason: ownerExited ? "owner_exited" : undefined,
591
+ launchRequested: false,
592
+ });
593
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
594
+ return managedCommandPublicResult(receipt);
595
+ }
596
+ }
597
+ async function managedCommandProcessEnvironment(invocation) {
598
+ assertHostDatabaseCapabilityBoundary();
599
+ const databaseEnvironment = invocation.verificationProfile
600
+ ? await managedVerificationDatabaseEnvironment()
601
+ : {};
602
+ const exactSecrets = [
603
+ ...Object.values(databaseEnvironment).filter(value => value !== nativeTestPostgresFallbackDatabaseMode),
604
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
605
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
+ ];
174
607
  const environment = inheritedEnvironment({
175
608
  FORGE_RUNTIME_MODE: "host",
176
609
  FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
@@ -183,30 +616,99 @@ async function executeManagedCommand(invocation) {
183
616
  FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
184
617
  FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
185
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
+ ...databaseEnvironment,
628
+ }
629
+ : {}),
186
630
  });
631
+ return { environment, exactSecrets };
632
+ }
633
+ async function executeManagedCommandProcess(invocation) {
634
+ let prepared;
635
+ try {
636
+ prepared = await managedCommandProcessEnvironment(invocation);
637
+ }
638
+ catch (error) {
639
+ // The call still fails (the database capability boundary or the verification
640
+ // database probe refused it), but its receipt must not stay "starting" forever.
641
+ const receipt = managedCommandResult({
642
+ ...invocation,
643
+ timedOut: false,
644
+ status: "runner_error",
645
+ exitCode: null,
646
+ stdout: "",
647
+ stderr: appendBounded("", redactText(error instanceof Error ? error.message : String(error), [])),
648
+ launchRequested: false,
649
+ });
650
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent).catch(() => undefined);
651
+ throw error;
652
+ }
653
+ const { exactSecrets } = prepared;
187
654
  let stdout = "";
188
655
  let stderr = "";
189
- const controller = new AbortController();
656
+ const controller = invocation.controller;
190
657
  let timedOut = false;
191
658
  let timer = null;
192
659
  let outputRevision = 0;
193
660
  let lastOutputAt = null;
661
+ let lastOutputStream = null;
194
662
  let lastProgressPersistedAt = 0;
195
663
  let progressPersistence = Promise.resolve();
664
+ let progressHeartbeat = null;
665
+ let progressFinished = false;
666
+ const persistProgress = (force = false) => {
667
+ if (progressFinished)
668
+ return progressPersistence;
669
+ const next = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt, lastOutputStream }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; }, force);
670
+ // A heartbeat write is best-effort: one failed write (a locked or full disk) must
671
+ // not poison the chain, freeze later heartbeats, or fail a command that succeeded.
672
+ progressPersistence = force ? next.catch(() => undefined) : next;
673
+ return progressPersistence;
674
+ };
675
+ // Stop progress writes and let any in flight land before a terminal receipt is
676
+ // written, so a late "running" snapshot can never replace it.
677
+ const settleProgress = async () => {
678
+ progressFinished = true;
679
+ if (progressHeartbeat)
680
+ clearInterval(progressHeartbeat);
681
+ progressHeartbeat = null;
682
+ await progressPersistence;
683
+ };
196
684
  const launchTimer = setTimeout(() => {
197
685
  timedOut = true;
198
686
  controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
199
687
  }, managedCommandLaunchTimeoutMs);
200
688
  try {
689
+ if (controller.signal.aborted)
690
+ throw controller.signal.reason;
691
+ // Recorded before the spawn: the process record is written only once the child has
692
+ // spawned, so teardown must know a launch may exist without one.
693
+ await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
694
+ ...invocation,
695
+ timedOut: false,
696
+ status: "starting",
697
+ exitCode: null,
698
+ stdout,
699
+ stderr,
700
+ }).structuredContent);
201
701
  const result = await new StreamingProviderProcessRunner().run({
202
702
  command: invocation.command,
203
703
  args: invocation.args,
204
704
  cwd: invocation.cwd,
205
- env: environment,
705
+ env: prepared.environment,
206
706
  captureOutput: false,
207
707
  }, {
208
708
  onStarted: async () => {
209
709
  clearTimeout(launchTimer);
710
+ // onProcessStarted stops the command itself when its token cannot be held.
711
+ await invocation.onProcessStarted?.();
210
712
  const running = managedCommandResult({
211
713
  ...invocation,
212
714
  timedOut: false,
@@ -216,30 +718,64 @@ async function executeManagedCommand(invocation) {
216
718
  stderr,
217
719
  outputRevision,
218
720
  lastOutputAt,
721
+ lastOutputStream,
219
722
  });
220
723
  await persistManagedCommandReceipt(invocation.receiptPath, running.structuredContent);
221
724
  timer = setTimeout(() => {
222
725
  timedOut = true;
223
726
  controller.abort(new Error(`managed_command_timeout: exceeded ${invocation.timeoutMs}ms.`));
224
727
  }, invocation.timeoutMs);
728
+ // Output alone does not keep the receipt current: a test tier can print a burst
729
+ // and then run quietly for many minutes. Without this heartbeat the elapsed time
730
+ // and the burst's last lines freeze, and a waiting agent sees a hung command.
731
+ // The run can already have failed while the "running" write above was pending.
732
+ if (progressFinished)
733
+ return;
734
+ progressHeartbeat = setInterval(() => {
735
+ void persistProgress(true);
736
+ }, managedCommandProgressPersistIntervalMs);
737
+ progressHeartbeat.unref();
225
738
  },
226
739
  onStdoutLine: (line) => {
227
- stdout = appendBounded(stdout, line);
740
+ stdout = appendBounded(stdout, redactText(line, exactSecrets));
228
741
  outputRevision += 1;
229
742
  lastOutputAt = Date.now();
230
- progressPersistence = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; });
231
- return progressPersistence;
743
+ lastOutputStream = "stdout";
744
+ return persistProgress();
232
745
  },
233
746
  onStderrLine: (line) => {
234
- stderr = appendBounded(stderr, line);
747
+ stderr = appendBounded(stderr, redactText(line, exactSecrets));
235
748
  outputRevision += 1;
236
749
  lastOutputAt = Date.now();
237
- progressPersistence = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; });
238
- return progressPersistence;
750
+ lastOutputStream = "stderr";
751
+ return persistProgress();
239
752
  },
240
753
  }, controller.signal);
241
- await progressPersistence;
242
- const status = timedOut ? "timed_out" : result.exitCode === 0 ? "pass" : "fail";
754
+ await settleProgress();
755
+ // Only a stop that interrupted the process relabels it. A command that exited on its own
756
+ // just before its owner asked for the stop keeps its real result.
757
+ const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
758
+ const hostCapacityLoss = !timedOut && !ownerExited && result.cancelled === true
759
+ ? hostCapacityLossReason(controller.signal.reason)
760
+ : null;
761
+ const fenced = hostCapacityLoss !== null;
762
+ if (ownerExited || fenced) {
763
+ stderr = appendBounded(stderr, ownerExited ? managedCommandOwnerExitMessage : controller.signal.reason.message);
764
+ outputRevision += 1;
765
+ lastOutputAt = Date.now();
766
+ lastOutputStream = "stderr";
767
+ }
768
+ const status = timedOut ? "timed_out" : ownerExited || fenced ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
769
+ const receiptCoverage = managedBuildReceiptCoverage(invocation);
770
+ const buildReceipt = status === "pass" && receiptCoverage
771
+ ? await publishManagedBuildReceipt({
772
+ worktreePath: invocation.worktreePath,
773
+ command: invocation.command,
774
+ args: invocation.args,
775
+ configuration: managedBuildConfiguration(invocation.command, invocation.args),
776
+ coverage: receiptCoverage,
777
+ })
778
+ : invocation.buildReceiptReuse;
243
779
  const receipt = managedCommandResult({
244
780
  ...invocation,
245
781
  timedOut,
@@ -249,13 +785,27 @@ async function executeManagedCommand(invocation) {
249
785
  stderr,
250
786
  outputRevision,
251
787
  lastOutputAt,
788
+ lastOutputStream,
789
+ buildReceipt,
790
+ buildReceiptReused: invocation.buildReceiptReuse !== undefined,
791
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLoss ?? undefined,
792
+ // The runner resolves only after the stopped tree is proven gone.
793
+ processTreeTerminated: ownerExited || fenced ? true : undefined,
252
794
  });
253
795
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
254
- return receipt;
796
+ return managedCommandPublicResult(receipt);
255
797
  }
256
798
  catch (error) {
257
- const message = error instanceof Error ? error.message : String(error);
799
+ // The failure may be a progress write itself; it is reported below.
800
+ await settleProgress().catch(() => undefined);
801
+ const ownerExited = !timedOut && ownerExitStoppedCommands.has(invocation.commandId);
802
+ const message = ownerExited
803
+ ? managedCommandOwnerExitMessage
804
+ : redactText(error instanceof Error ? error.message : String(error), exactSecrets);
258
805
  stderr = appendBounded(stderr, message);
806
+ outputRevision += 1;
807
+ lastOutputAt = Date.now();
808
+ lastOutputStream = "stderr";
259
809
  const receipt = managedCommandResult({
260
810
  ...invocation,
261
811
  timedOut,
@@ -265,14 +815,26 @@ async function executeManagedCommand(invocation) {
265
815
  stderr,
266
816
  outputRevision,
267
817
  lastOutputAt,
818
+ lastOutputStream,
819
+ // A host capacity loss before launch (a fence that landed while it was admitted) is named too.
820
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLossReason(controller.signal.reason) ?? undefined,
821
+ // The runner rejected, so its tree was not proven stopped; teardown still stops it.
822
+ processTreeTerminated: false,
268
823
  });
269
824
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
270
- return receipt;
825
+ // The runner stops the tree before it rejects; only a failed termination proof means
826
+ // part of it may still run. Its token is then kept, never returned with this receipt.
827
+ if (isProcessTreeTerminationUnproven(error)) {
828
+ invocation.holdHostCapacityUntilStopped?.(error instanceof Error ? error : new Error(String(error)));
829
+ }
830
+ return managedCommandPublicResult(receipt);
271
831
  }
272
832
  finally {
273
833
  clearTimeout(launchTimer);
274
834
  if (timer)
275
835
  clearTimeout(timer);
836
+ if (progressHeartbeat)
837
+ clearInterval(progressHeartbeat);
276
838
  }
277
839
  }
278
840
  async function readManagedCommand(input) {
@@ -288,10 +850,15 @@ async function readManagedCommand(input) {
288
850
  }
289
851
  throw error;
290
852
  }
853
+ // A queued receipt is written once; its wait so far is computed when it is read.
854
+ const hostLoadWaitStartedAt = Date.parse(String(receipt.host_load_wait_started_at));
855
+ if (receipt.status === "waiting_for_host_capacity" && Number.isFinite(hostLoadWaitStartedAt)) {
856
+ receipt = { ...receipt, host_load_wait_ms: Math.max(0, Date.now() - hostLoadWaitStartedAt) };
857
+ }
291
858
  const status = typeof receipt.status === "string" ? receipt.status : "unknown";
292
859
  const stdout = typeof receipt.stdout === "string" ? receipt.stdout : "";
293
860
  const stderr = typeof receipt.stderr === "string" ? receipt.stderr : "";
294
- return {
861
+ return managedCommandPublicResult({
295
862
  content: [{
296
863
  type: "text",
297
864
  text: terminalManagedCommandStatuses.has(status)
@@ -307,13 +874,14 @@ async function readManagedCommand(input) {
307
874
  }],
308
875
  structuredContent: receipt,
309
876
  isError: terminalManagedCommandStatuses.has(status) && status !== "pass",
310
- };
877
+ });
311
878
  }
312
879
  async function waitManagedCommand(input) {
313
880
  const record = asRecord(input);
314
881
  const commandId = validatedCommandId(record);
315
- const waitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
316
- const deadline = Date.now() + waitTimeoutMs;
882
+ const requestedWaitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
883
+ const waitTimeoutMs = Math.min(requestedWaitTimeoutMs, maximumSynchronousWaitMs);
884
+ const deadline = monotonicNowMs() + waitTimeoutMs;
317
885
  const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
318
886
  const task = managedCommandTasks.get(commandId);
319
887
  if (task) {
@@ -324,20 +892,46 @@ async function waitManagedCommand(input) {
324
892
  if (result)
325
893
  return result;
326
894
  }
327
- while (Date.now() < deadline) {
895
+ while (monotonicNowMs() < deadline) {
328
896
  const result = await readManagedCommand({ command_id: commandId });
329
897
  if (terminalManagedCommandStatuses.has(String(result.structuredContent.status))) {
330
898
  return result;
331
899
  }
332
- await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - Date.now())));
900
+ await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - monotonicNowMs())));
333
901
  }
334
902
  const receipt = await readManagedCommand({ command_id: commandId });
903
+ // Only a running receipt is refreshed on a heartbeat; queued or starting receipts are
904
+ // written once, so their elapsed time says nothing about progress.
905
+ const elapsedMs = receipt.structuredContent.elapsed_ms;
906
+ const timeoutMs = receipt.structuredContent.timeout_ms;
907
+ const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
908
+ const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
909
+ const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
910
+ ? ` 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.`
911
+ : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
912
+ ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
913
+ + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
914
+ + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
915
+ // Agents otherwise abandon long verification tiers and record a blocker that is not one.
916
+ + (typeof timeoutMs === "number"
917
+ ? ` 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.`
918
+ : "")
919
+ : "";
335
920
  return {
336
921
  ...receipt,
337
922
  content: [{
338
923
  type: "text",
339
- text: `Forge is still supervising managed command ${commandId} after waiting ${waitTimeoutMs}ms. Its durable receipt remains at ${receiptPath}.`,
924
+ 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}.`,
340
925
  }],
926
+ structuredContent: {
927
+ ...receipt.structuredContent,
928
+ command_continues: true,
929
+ terminal: false,
930
+ wait_timeout_ms: waitTimeoutMs,
931
+ requested_wait_timeout_ms: requestedWaitTimeoutMs,
932
+ retry_after_ms: managedCommandRetryAfterMs,
933
+ },
934
+ isError: false,
341
935
  };
342
936
  }
343
937
  function managedCommandReceiptPath(logDirectory, commandId) {
@@ -367,7 +961,9 @@ async function persistManagedCommandReceipt(receiptPath, receipt) {
367
961
  }
368
962
  }
369
963
  function managedCommandResult(values) {
370
- const elapsedMs = Date.now() - values.startedAt;
964
+ // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
965
+ const hostLoad = values.hostLoad;
966
+ const elapsedMs = Date.now() - (hostLoad ? hostLoad.executionStartedAt ?? Date.now() : values.startedAt);
371
967
  const isTerminal = terminalManagedCommandStatuses.has(values.status);
372
968
  const diagnostics = isTerminal
373
969
  ? managedCommandDiagnostics(values.stdout, values.stderr)
@@ -403,16 +999,94 @@ function managedCommandResult(values) {
403
999
  || values.stderr.length >= maximumCapturedCharacters,
404
1000
  output_revision: values.outputRevision ?? 0,
405
1001
  last_output_at: values.lastOutputAt ? new Date(values.lastOutputAt).toISOString() : null,
1002
+ last_output_stream: values.lastOutputStream ?? null,
406
1003
  supervisor_metadata_path: values.metadataPath,
407
1004
  receipt_path: values.receiptPath,
408
- process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : undefined,
1005
+ verification_profile: values.verificationProfile ?? null,
1006
+ verification_profile_runner_authored: values.verificationProfile !== undefined,
1007
+ build_producing: values.buildProducing,
1008
+ build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
1009
+ build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
1010
+ build_receipt_reused: values.buildReceiptReused ?? false,
1011
+ ...(hostLoad ? managedCommandHostLoadReceipt(hostLoad) : {}),
1012
+ build_receipt: values.buildReceipt ? {
1013
+ fingerprint: values.buildReceipt.fingerprint,
1014
+ receipt_path: values.buildReceipt.receiptPath,
1015
+ producer_command: values.buildReceipt.producerCommand,
1016
+ configuration: values.buildReceipt.configuration,
1017
+ coverage: values.buildReceipt.coverage,
1018
+ output_count: values.buildReceipt.outputCount,
1019
+ } : null,
1020
+ runtime_configuration: managedRuntimeConfiguration(),
1021
+ // The supervising MCP server process. Forge stops a command whose owner has exited.
1022
+ owner_pid: process.pid,
1023
+ owner_identity: managedCommandOwnerIdentity(),
1024
+ launch_requested: values.launchRequested ?? true,
1025
+ process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : values.processTreeTerminated,
1026
+ ...(values.terminationReason ? { termination_reason: values.terminationReason } : {}),
409
1027
  },
410
1028
  isError: isTerminal && values.status !== "pass",
411
1029
  };
412
1030
  }
413
- function persistManagedCommandProgressIfDue(invocation, snapshot, previousPersistence, lastPersistedAt, setLastPersistedAt) {
1031
+ function managedCommandHostLoadReceipt(hostLoad) {
1032
+ const waiting = hostLoad.waitStartedAt !== undefined;
1033
+ return {
1034
+ host_load_step_class: hostLoad.stepClass,
1035
+ host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
1036
+ ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString(), host_load_wait_detail: hostLoad.waitDetail ?? null } : {}),
1037
+ };
1038
+ }
1039
+ async function annotateManagedCommandReceipt(receiptPath, fields) {
1040
+ const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
1041
+ await persistManagedCommandReceipt(receiptPath, { ...receipt, ...fields });
1042
+ }
1043
+ /** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
1044
+ function managedCommandOwnerIdentity() {
1045
+ // Windows identity capture starts PowerShell; the PID check alone is used there.
1046
+ ownerProcessIdentity ??= process.platform === "linux" ? captureHostProcessIdentity(process.pid) : null;
1047
+ return ownerProcessIdentity;
1048
+ }
1049
+ function managedRuntimeConfiguration() {
1050
+ const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
1051
+ let providerOnlySpecCount = 0;
1052
+ if (providerOnlySpecs) {
1053
+ try {
1054
+ const parsed = JSON.parse(providerOnlySpecs);
1055
+ providerOnlySpecCount = Array.isArray(parsed)
1056
+ ? parsed.filter(value => typeof value === "string" && value.length > 0).length
1057
+ : 0;
1058
+ }
1059
+ catch {
1060
+ providerOnlySpecCount = 0;
1061
+ }
1062
+ }
1063
+ return {
1064
+ attempt_database_schema: process.env.FORGE_ATTEMPT_DATABASE_SCHEMA ?? null,
1065
+ attempt_database_readiness_path: process.env.FORGE_ATTEMPT_DATABASE_READINESS_PATH ?? null,
1066
+ playwright_config: process.env.FORGE_PLAYWRIGHT_CONFIG ?? null,
1067
+ provider_only_spec_count: providerOnlySpecCount,
1068
+ provider_only_spec_fingerprint: providerOnlySpecs
1069
+ ? `sha256:${createHash("sha256").update(providerOnlySpecs).digest("hex")}`
1070
+ : null,
1071
+ };
1072
+ }
1073
+ function managedCommandPublicResult(result) {
1074
+ const stdout = typeof result.structuredContent.stdout === "string" ? result.structuredContent.stdout : "";
1075
+ const stderr = typeof result.structuredContent.stderr === "string" ? result.structuredContent.stderr : "";
1076
+ const { stdout: _stdout, stderr: _stderr, ...receipt } = result.structuredContent;
1077
+ return {
1078
+ ...result,
1079
+ structuredContent: {
1080
+ ...receipt,
1081
+ stdout_tail: tail(stdout, maximumReturnedOutputCharacters),
1082
+ stderr_tail: tail(stderr, maximumReturnedOutputCharacters),
1083
+ full_output_in_receipt: true,
1084
+ },
1085
+ };
1086
+ }
1087
+ function persistManagedCommandProgressIfDue(invocation, snapshot, previousPersistence, lastPersistedAt, setLastPersistedAt, force = false) {
414
1088
  const now = Date.now();
415
- if (now - lastPersistedAt() < managedCommandProgressPersistIntervalMs)
1089
+ if (!force && now - lastPersistedAt() < managedCommandProgressPersistIntervalMs)
416
1090
  return previousPersistence;
417
1091
  setLastPersistedAt(now);
418
1092
  const current = snapshot();
@@ -441,18 +1115,84 @@ async function containedWorkingDirectory(worktreePath, input) {
441
1115
  }
442
1116
  function inheritedEnvironment(overrides) {
443
1117
  const env = {};
444
- for (const [key, value] of Object.entries(process.env)) {
1118
+ // A nested Forge process must not join the host ledger: it would queue behind the
1119
+ // token this command already holds. Every FORGE_HOST_LOAD_* variable is dropped,
1120
+ // the test slot count too (decision 0018).
1121
+ for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(process.env))) {
445
1122
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
446
1123
  env[key] = value;
447
1124
  }
448
1125
  return { ...env, ...overrides };
449
1126
  }
1127
+ /**
1128
+ * Runner-authored verification normally uses its attempt-owned Testcontainers
1129
+ * database. Only when the Docker engine is unavailable does it switch to the
1130
+ * operator-provisioned native test cluster, which holds no real data.
1131
+ */
1132
+ export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().refresh(true)).available, readFallback = () => {
1133
+ const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
1134
+ return configPath ? readNativeTestPostgresFallback(configPath) : null;
1135
+ }) {
1136
+ const fallback = readFallback();
1137
+ if (!fallback || await dockerAvailable())
1138
+ return {};
1139
+ return nativeTestPostgresFallbackEnvironment(fallback);
1140
+ }
1141
+ export function isBuildProducingManagedCommand(command, args) {
1142
+ const executable = path.basename(command).toLowerCase();
1143
+ if (executable === "dotnet" || executable === "dotnet.exe") {
1144
+ const verb = args.find(argument => !argument.startsWith("-"))?.toLowerCase();
1145
+ if (!verb || !new Set(["build", "test", "restore", "publish", "pack", "msbuild"]).has(verb))
1146
+ return false;
1147
+ return verb === "restore" || !args.some(argument => argument.toLowerCase() === "--no-build");
1148
+ }
1149
+ if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1150
+ const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
1151
+ const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
1152
+ if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
1153
+ return !args.some(argument => argument.toLowerCase() === "-nobuild");
1154
+ }
1155
+ if (script === "run-dotnet-test-tier.ps1") {
1156
+ return !args.some(argument => argument.toLowerCase() === "-nobuild");
1157
+ }
1158
+ }
1159
+ return false;
1160
+ }
1161
+ function managedBuildReceiptCoverage(invocation) {
1162
+ if (!invocation.buildProducing)
1163
+ return null;
1164
+ if (invocation.verificationProfile)
1165
+ return managedVerificationBuildCoverage;
1166
+ const executable = path.basename(invocation.command).toLowerCase();
1167
+ if (executable === "dotnet" || executable === "dotnet.exe") {
1168
+ const verb = invocation.args.find(argument => !argument.startsWith("-"))?.toLowerCase();
1169
+ if (!verb || !new Set(["build", "test"]).has(verb))
1170
+ return null;
1171
+ const target = invocation.args.find(argument => /\.(?:sln|slnx|csproj)$/iu.test(argument));
1172
+ if (target && (/\.(?:sln|slnx)$/iu.test(target) || /(?:^|[\\/])Forge\.Api\.Tests\.csproj$/iu.test(target))) {
1173
+ return managedVerificationBuildCoverage;
1174
+ }
1175
+ return null;
1176
+ }
1177
+ if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1178
+ const fileIndex = invocation.args.findIndex(argument => argument.toLowerCase() === "-file");
1179
+ const script = fileIndex >= 0 ? path.basename(invocation.args[fileIndex + 1] ?? "").toLowerCase() : "";
1180
+ if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)
1181
+ && !invocation.args.some(argument => argument.toLowerCase() === "-nobuild")) {
1182
+ return managedVerificationBuildCoverage;
1183
+ }
1184
+ }
1185
+ return null;
1186
+ }
450
1187
  function looksSensitiveEnvironmentName(name) {
451
1188
  const normalized = name.trim().toUpperCase();
452
1189
  return normalized.includes("SECRET")
453
1190
  || normalized.includes("TOKEN")
454
1191
  || normalized.includes("PASSWORD")
455
1192
  || normalized.includes("CREDENTIAL")
1193
+ || normalized.includes("CONNECTION_STRING")
1194
+ || normalized.startsWith("CONNECTIONSTRINGS__")
1195
+ || normalized.startsWith("CONNECTIONSTRINGS:")
456
1196
  || normalized.endsWith("_API_KEY")
457
1197
  || normalized === "OPENAI_API_KEY";
458
1198
  }
@@ -467,8 +1207,17 @@ function asRecord(value) {
467
1207
  throw new Error("managed_command_invalid: input must be an object.");
468
1208
  return value;
469
1209
  }
1210
+ const requiredInputExamples = {
1211
+ command: "Send the executable as command and each argument as its own string in args, for example {\"command\": \"pnpm\", \"args\": [\"--dir\", \"client\", \"lint\"]}.",
1212
+ profile: managedVerificationProfileHint,
1213
+ command_id: "Send the command_id returned by forge.start_managed_command or forge.start_managed_verification.",
1214
+ };
470
1215
  function requiredInputString(record, name) {
471
- return requiredStandaloneString(record[name], name);
1216
+ const value = record[name];
1217
+ if (typeof value === "string" && value.trim())
1218
+ return value.trim();
1219
+ const hints = [requiredInputExamples[name], isEmptyToolInput(record) ? emptyToolInputHint : undefined].filter(Boolean);
1220
+ throw new Error(`managed_command_invalid: ${name} is required.${hints.length > 0 ? ` ${hints.join(" ")}` : ""}`);
472
1221
  }
473
1222
  function validatedCommandId(record) {
474
1223
  const commandId = requiredInputString(record, "command_id");
@@ -485,7 +1234,13 @@ function requiredStandaloneString(value, name) {
485
1234
  function requiredStringArray(record, name) {
486
1235
  const value = record[name];
487
1236
  if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) {
488
- throw new Error(`managed_command_invalid: ${name} must be a string array.`);
1237
+ const shellLine = typeof record.command === "string" && /\s/u.test(record.command.trim());
1238
+ const hint = typeof value === "string"
1239
+ ? " (received a string). Put each argument in its own string, for example [\"--dir\", \"client\", \"test\"]."
1240
+ : value === undefined
1241
+ ? ` (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." : ""}`
1242
+ : " Every argument must be a string.";
1243
+ throw new Error(`managed_command_invalid: ${name} must be a string array${hint}`);
489
1244
  }
490
1245
  return value;
491
1246
  }
@@ -499,12 +1254,27 @@ function optionalTimeout(value) {
499
1254
  }
500
1255
  function optionalWaitTimeout(value) {
501
1256
  if (value === undefined)
502
- return 7_200_000;
503
- if (!Number.isSafeInteger(value) || value < 1_000 || value > 7_200_000) {
504
- throw new Error("managed_command_invalid: wait_timeout_ms must be an integer from 1000 through 7200000.");
1257
+ return maximumSynchronousWaitMs;
1258
+ if (!Number.isSafeInteger(value) || value < 1_000 || value > maximumSynchronousWaitMs) {
1259
+ throw new Error(`managed_command_invalid: wait_timeout_ms must be an integer from 1000 through ${maximumSynchronousWaitMs}.`);
505
1260
  }
506
1261
  return value;
507
1262
  }
1263
+ function optionalBoundedInteger(value, name, minimum, maximum, fallback) {
1264
+ if (value === undefined)
1265
+ return fallback;
1266
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
1267
+ throw new Error(`managed_verification_invalid: ${name} must be an integer from ${minimum} through ${maximum}.`);
1268
+ }
1269
+ return value;
1270
+ }
1271
+ function optionalBoolean(value, name, fallback) {
1272
+ if (value === undefined)
1273
+ return fallback;
1274
+ if (typeof value !== "boolean")
1275
+ throw new Error(`managed_verification_invalid: ${name} must be a boolean.`);
1276
+ return value;
1277
+ }
508
1278
  async function delay(ms) {
509
1279
  await new Promise(resolve => setTimeout(resolve, ms));
510
1280
  }