@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.0098fdb4e213

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 (332) hide show
  1. package/README.md +232 -5
  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 +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  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 +13 -1
  15. package/dist/bridge/bridge.service.d.ts +169 -14
  16. package/dist/bridge/bridge.service.js +1868 -330
  17. package/dist/bridge/bridge.types.d.ts +73 -1
  18. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  19. package/dist/bridge/dispatch-result-outbox.js +87 -0
  20. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  21. package/dist/bridge/dispatch-result-worker.js +122 -0
  22. package/dist/bridge/in-flight-registry.d.ts +62 -0
  23. package/dist/bridge/in-flight-registry.js +207 -0
  24. package/dist/bridge/internals.d.ts +2 -0
  25. package/dist/bridge/internals.js +1 -0
  26. package/dist/bridge/local-yield-flag.d.ts +6 -0
  27. package/dist/bridge/local-yield-flag.js +34 -0
  28. package/dist/bridge/readiness-result-outbox.d.ts +25 -0
  29. package/dist/bridge/readiness-result-outbox.js +74 -0
  30. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  31. package/dist/bridge/readiness-result-worker.js +121 -0
  32. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  33. package/dist/bridge/runner-host-capabilities.js +110 -0
  34. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  35. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  36. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  37. package/dist/bridge/test-postgres-capability.js +120 -0
  38. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  39. package/dist/cleanup/cleanup-wip.js +66 -0
  40. package/dist/cleanup/cleanup.service.d.ts +21 -1
  41. package/dist/cleanup/cleanup.service.js +185 -143
  42. package/dist/cleanup/cleanup.types.d.ts +6 -0
  43. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  44. package/dist/cleanup/forge-owned-paths.js +53 -0
  45. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  46. package/dist/cleanup/host-runtime-ledger.js +130 -0
  47. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  48. package/dist/cleanup/managed-branch-sweep.js +111 -0
  49. package/dist/cli/cli.help.js +78 -16
  50. package/dist/cli/cli.service.d.ts +32 -15
  51. package/dist/cli/cli.service.js +206 -182
  52. package/dist/cli/idle-status.d.ts +84 -0
  53. package/dist/cli/idle-status.js +181 -0
  54. package/dist/cli/local-config.d.ts +7 -0
  55. package/dist/cli/local-config.js +36 -4
  56. package/dist/cli/provider-cli-detection.d.ts +10 -0
  57. package/dist/cli/provider-cli-detection.js +160 -0
  58. package/dist/runtime/aspnet-runtime-prebuild.d.ts +41 -0
  59. package/dist/runtime/aspnet-runtime-prebuild.js +474 -0
  60. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  61. package/dist/runtime/attempt-database-broker.js +390 -0
  62. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  63. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  64. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  65. package/dist/runtime/attempt-path-operation.js +94 -0
  66. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  67. package/dist/runtime/attempt-private-directory.js +54 -0
  68. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  69. package/dist/runtime/attempt-process-supervisor.js +144 -23
  70. package/dist/runtime/canonical-source-file.d.ts +3 -0
  71. package/dist/runtime/canonical-source-file.js +54 -0
  72. package/dist/runtime/docker-engine-probe.d.ts +95 -0
  73. package/dist/runtime/docker-engine-probe.js +340 -0
  74. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  75. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  76. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  77. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  78. package/dist/runtime/generated-output-reset.d.ts +10 -0
  79. package/dist/runtime/generated-output-reset.js +62 -8
  80. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  81. package/dist/runtime/host-database-capability-boundary.js +63 -0
  82. package/dist/runtime/host-diagnostics.d.ts +11 -0
  83. package/dist/runtime/host-diagnostics.js +192 -0
  84. package/dist/runtime/host-execution-root.d.ts +4 -0
  85. package/dist/runtime/host-execution-root.js +39 -0
  86. package/dist/runtime/host-facts.d.ts +36 -0
  87. package/dist/runtime/host-facts.js +95 -0
  88. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  89. package/dist/runtime/host-listener-inspector.js +121 -60
  90. package/dist/runtime/host-load-admission.d.ts +67 -0
  91. package/dist/runtime/host-load-admission.js +99 -0
  92. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  93. package/dist/runtime/host-load-child-environment.js +76 -0
  94. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  95. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  96. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  97. package/dist/runtime/host-load-governor-config.js +83 -0
  98. package/dist/runtime/host-load-governor.d.ts +186 -0
  99. package/dist/runtime/host-load-governor.js +632 -0
  100. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  101. package/dist/runtime/host-load-ledger-lock.js +187 -0
  102. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  103. package/dist/runtime/host-load-runtime-settings.js +80 -0
  104. package/dist/runtime/host-load-sampler.d.ts +156 -0
  105. package/dist/runtime/host-load-sampler.js +298 -0
  106. package/dist/runtime/host-load-step-class.d.ts +70 -0
  107. package/dist/runtime/host-load-step-class.js +161 -0
  108. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  109. package/dist/runtime/host-load-step-reaper.js +95 -0
  110. package/dist/runtime/host-load-step-run.d.ts +73 -0
  111. package/dist/runtime/host-load-step-run.js +102 -0
  112. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  113. package/dist/runtime/host-load-test-slot.js +81 -0
  114. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  115. package/dist/runtime/host-load-token-ledger.js +453 -0
  116. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  117. package/dist/runtime/host-load-windows-cpu.js +85 -0
  118. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  119. package/dist/runtime/host-pressure-stall.js +168 -0
  120. package/dist/runtime/host-runtime-contract.d.ts +28 -1
  121. package/dist/runtime/host-runtime-contract.js +203 -57
  122. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  123. package/dist/runtime/host-runtime-lease.js +1427 -124
  124. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  125. package/dist/runtime/host-runtime-promotion.js +107 -12
  126. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  127. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  128. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  129. package/dist/runtime/host-runtime-requirements.js +117 -0
  130. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  131. package/dist/runtime/managed-command-teardown.js +596 -0
  132. package/dist/runtime/memory-capacity.d.ts +70 -0
  133. package/dist/runtime/memory-capacity.js +123 -0
  134. package/dist/runtime/native-test-postgres-fallback.d.ts +69 -0
  135. package/dist/runtime/native-test-postgres-fallback.js +143 -0
  136. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  137. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  138. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  139. package/dist/runtime/pinned-directory-process.js +61 -0
  140. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  141. package/dist/runtime/pinned-source-directory.js +94 -0
  142. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  143. package/dist/runtime/playwright-browser-cache.js +227 -0
  144. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  145. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  146. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  147. package/dist/runtime/prepared-runtime-identity.js +218 -0
  148. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  149. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  150. package/dist/runtime/runner-settings.d.ts +104 -0
  151. package/dist/runtime/runner-settings.js +236 -0
  152. package/dist/runtime/runtime-isolation-lease.js +4 -1
  153. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  154. package/dist/runtime/workspace-resource-estimator.js +174 -0
  155. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  156. package/dist/sandbox/host-capacity-broker.js +336 -0
  157. package/dist/sandbox/managed-branch.d.ts +13 -0
  158. package/dist/sandbox/managed-branch.js +36 -0
  159. package/dist/sandbox/preflight.d.ts +31 -1
  160. package/dist/sandbox/preflight.js +237 -51
  161. package/dist/sandbox/provider-auth/codex.js +11 -11
  162. package/dist/sandbox/repository-lock.d.ts +2 -1
  163. package/dist/sandbox/repository-lock.js +19 -9
  164. package/dist/sandbox/runtime.d.ts +16 -2
  165. package/dist/sandbox/runtime.js +183 -114
  166. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  167. package/dist/sandbox/sandbox-cgroups.js +42 -0
  168. package/dist/sandbox/sandbox.types.d.ts +7 -0
  169. package/dist/sandbox/workspace.service.js +2 -0
  170. package/dist/session/architect-waits.d.ts +2 -0
  171. package/dist/session/architect-waits.js +138 -0
  172. package/dist/session/managed-attempt-tools.d.ts +37 -1
  173. package/dist/session/managed-attempt-tools.js +822 -84
  174. package/dist/session/managed-build-coordinator.d.ts +5 -0
  175. package/dist/session/managed-build-coordinator.js +109 -0
  176. package/dist/session/managed-build-receipt.d.ts +26 -0
  177. package/dist/session/managed-build-receipt.js +342 -0
  178. package/dist/session/managed-command-host-load.d.ts +47 -0
  179. package/dist/session/managed-command-host-load.js +83 -0
  180. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  181. package/dist/session/managed-verification-timeouts.js +17 -0
  182. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  183. package/dist/session/mcp-argument-coercion.js +121 -0
  184. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  185. package/dist/session/phase-completion.artifacts.js +321 -45
  186. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  187. package/dist/session/phase-completion.command-validation.js +77 -0
  188. package/dist/session/phase-completion.d.ts +23 -1
  189. package/dist/session/phase-completion.helpers.d.ts +5 -0
  190. package/dist/session/phase-completion.helpers.js +43 -19
  191. package/dist/session/phase-completion.js +19 -3
  192. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  193. package/dist/session/phase-completion.mcp-args.js +156 -0
  194. package/dist/session/phase-completion.prompts.js +22 -18
  195. package/dist/session/phase-completion.runtime.d.ts +6 -10
  196. package/dist/session/phase-completion.runtime.js +214 -224
  197. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  198. package/dist/session/phase-completion.schema-parts.js +188 -0
  199. package/dist/session/phase-completion.schemas.d.ts +3 -3
  200. package/dist/session/phase-completion.schemas.js +250 -226
  201. package/dist/session/phase-completion.validation.d.ts +3 -3
  202. package/dist/session/phase-completion.validation.js +135 -89
  203. package/dist/session/pre-publication-host-load.d.ts +27 -0
  204. package/dist/session/pre-publication-host-load.js +111 -0
  205. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  206. package/dist/session/pre-publication-native-postgres.js +111 -0
  207. package/dist/session/pre-publication-pass.d.ts +61 -0
  208. package/dist/session/pre-publication-pass.js +148 -0
  209. package/dist/session/pre-publication-process.d.ts +23 -0
  210. package/dist/session/pre-publication-process.js +109 -0
  211. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  212. package/dist/session/pre-publication-skipped-tests.js +109 -0
  213. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  214. package/dist/session/pre-publication-step-execution.js +50 -0
  215. package/dist/session/pre-publication-validation.d.ts +91 -0
  216. package/dist/session/pre-publication-validation.js +670 -0
  217. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  218. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  219. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  220. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  221. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  222. package/dist/session/provider-cli/claude-background-work.js +181 -0
  223. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  224. package/dist/session/provider-cli/host-build-lock.js +30 -0
  225. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  226. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  227. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  228. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  229. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  230. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  231. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  232. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  233. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  234. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  235. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  236. package/dist/session/provider-cli/provider-cli.process.d.ts +85 -19
  237. package/dist/session/provider-cli/provider-cli.process.js +566 -283
  238. package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -0
  239. package/dist/session/provider-cli/provider-cli.prompts.js +211 -36
  240. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  241. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  242. package/dist/session/provider-cli/provider-cli.runtime.d.ts +22 -1
  243. package/dist/session/provider-cli/provider-cli.runtime.js +83 -4
  244. package/dist/session/provider-cli/provider-cli.service.d.ts +36 -5
  245. package/dist/session/provider-cli/provider-cli.service.js +818 -99
  246. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  247. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  248. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  249. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  250. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  251. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  252. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  253. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  254. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  255. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  256. package/dist/session/provider-cli/provider-output-state.js +376 -17
  257. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  258. package/dist/session/provider-cli/provider-usage.js +28 -5
  259. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  260. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  261. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  262. package/dist/session/publishable-worktree-changes.js +193 -0
  263. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  264. package/dist/session/qa-sidecar-validation.js +28 -0
  265. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  266. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  267. package/dist/session/session-redaction.js +284 -9
  268. package/dist/session/session.base.d.ts +9 -1
  269. package/dist/session/session.service.d.ts +11 -2
  270. package/dist/session/session.service.js +301 -58
  271. package/dist/session/session.types.d.ts +150 -2
  272. package/dist/session/session.types.js +599 -7
  273. package/dist/session/sidecar-json-shape.d.ts +31 -0
  274. package/dist/session/sidecar-json-shape.js +217 -0
  275. package/dist/session/unreferenced-exports.d.ts +12 -0
  276. package/dist/session/unreferenced-exports.js +59 -0
  277. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  278. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  279. package/dist/shared/format/format-bytes.d.ts +1 -0
  280. package/dist/shared/format/format-bytes.js +9 -0
  281. package/dist/shared/fs/file-identity.d.ts +10 -0
  282. package/dist/shared/fs/file-identity.js +15 -0
  283. package/dist/shared/fs/replace-file.d.ts +7 -0
  284. package/dist/shared/fs/replace-file.js +33 -0
  285. package/dist/shared/git/git.js +2 -1
  286. package/dist/shared/path/path.d.ts +1 -0
  287. package/dist/shared/path/path.js +18 -0
  288. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  289. package/dist/shared/process/dotnet-toolchain.js +307 -0
  290. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  291. package/dist/shared/process/host-process-recovery.js +26 -5
  292. package/dist/shared/process/host-process-supervisor.d.ts +16 -1
  293. package/dist/shared/process/host-process-supervisor.js +124 -23
  294. package/dist/shared/process/process-tree.d.ts +52 -0
  295. package/dist/shared/process/process-tree.js +144 -0
  296. package/dist/shared/process/process.d.ts +69 -0
  297. package/dist/shared/process/process.js +223 -16
  298. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  299. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  300. package/dist/shared/process/windows-launch.d.ts +18 -0
  301. package/dist/shared/process/windows-launch.js +68 -0
  302. package/dist/shared/provider-capabilities.d.ts +3 -0
  303. package/dist/shared/provider-capabilities.js +92 -0
  304. package/dist/shared/redaction/redaction.d.ts +1 -0
  305. package/dist/shared/redaction/redaction.js +39 -3
  306. package/dist/shared/time/monotonic.d.ts +1 -0
  307. package/dist/shared/time/monotonic.js +8 -0
  308. package/dist/version.d.ts +1 -1
  309. package/dist/version.js +1 -1
  310. package/dist/worktree/dependency-warmer.d.ts +66 -9
  311. package/dist/worktree/dependency-warmer.js +609 -24
  312. package/dist/worktree/index.d.ts +1 -1
  313. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  314. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  315. package/dist/worktree/wip-git.d.ts +33 -0
  316. package/dist/worktree/wip-git.js +122 -0
  317. package/dist/worktree/wip-refs.d.ts +62 -0
  318. package/dist/worktree/wip-refs.js +119 -0
  319. package/dist/worktree/wip-restore.d.ts +38 -0
  320. package/dist/worktree/wip-restore.js +190 -0
  321. package/dist/worktree/wip-snapshot.d.ts +50 -0
  322. package/dist/worktree/wip-snapshot.js +268 -0
  323. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  324. package/dist/worktree/worktree-wip-events.js +98 -0
  325. package/dist/worktree/worktree-wip.d.ts +49 -0
  326. package/dist/worktree/worktree-wip.js +182 -0
  327. package/dist/worktree/worktree.base.d.ts +7 -1
  328. package/dist/worktree/worktree.service.d.ts +22 -2
  329. package/dist/worktree/worktree.service.js +302 -25
  330. package/dist/worktree/worktree.types.d.ts +36 -1
  331. package/package.json +8 -6
  332. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -1,22 +1,42 @@
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 { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
7
+ import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
8
+ import { managedVerificationDatabase, noManagedVerificationDatabase, releaseManagedVerificationDatabase, setUpWithManagedVerificationDatabase } from "../runtime/ephemeral-test-postgres-grant.js";
9
+ import { redactText } from "../shared/redaction/redaction.js";
10
+ import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
11
+ import { 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";
18
+ import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
19
+ import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
20
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
21
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
6
22
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
7
23
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
8
24
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
9
25
  const waitManagedCommandNames = new Set(["forge.wait_managed_command", "wait_managed_command"]);
26
+ const startManagedVerificationNames = new Set(["forge.start_managed_verification", "start_managed_verification"]);
10
27
  const resetGeneratedOutputNames = new Set(["forge.reset_generated_outputs", "reset_generated_outputs"]);
11
28
  const maximumCapturedCharacters = 200_000;
12
- const maximumReturnedOutputCharacters = 12_000;
29
+ const maximumReturnedOutputCharacters = 4_000;
13
30
  const maximumReportedFailedTests = 50;
14
- const maximumSynchronousWaitMs = 240_000;
31
+ // Keep a wait slice comfortably below the MCP transport deadline. The managed
32
+ // process remains supervised and its durable receipt continues to update after
33
+ // this call returns, so a shorter slice avoids converting healthy long-running
34
+ // commands into ambiguous MCP failures.
35
+ const maximumSynchronousWaitMs = 45_000;
36
+ const managedCommandRetryAfterMs = 60_000;
15
37
  const managedCommandLaunchTimeoutMs = 60_000;
16
38
  const managedCommandProgressPersistIntervalMs = 5_000;
17
39
  const managedCommandReceiptPollIntervalMs = 1_000;
18
- const managedCommandReceiptReplaceAttempts = 40;
19
- const managedCommandReceiptReplaceRetryMs = 25;
20
40
  const terminalManagedCommandStatuses = new Set([
21
41
  "pass",
22
42
  "fail",
@@ -24,7 +44,16 @@ const terminalManagedCommandStatuses = new Set([
24
44
  "timeout_termination_failed",
25
45
  "runner_error",
26
46
  ]);
47
+ const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
27
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.";
28
57
  export const managedAttemptToolNames = [
29
58
  "forge.run_managed_command",
30
59
  "run_managed_command",
@@ -34,30 +63,133 @@ export const managedAttemptToolNames = [
34
63
  "get_managed_command",
35
64
  "forge.wait_managed_command",
36
65
  "wait_managed_command",
66
+ "forge.start_managed_verification",
67
+ "start_managed_verification",
37
68
  "forge.reset_generated_outputs",
38
69
  "reset_generated_outputs",
39
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
+ }
40
141
  export function isManagedAttemptTool(name) {
41
142
  return managedCommandNames.has(name)
42
143
  || startManagedCommandNames.has(name)
43
144
  || getManagedCommandNames.has(name)
44
145
  || waitManagedCommandNames.has(name)
146
+ || startManagedVerificationNames.has(name)
45
147
  || resetGeneratedOutputNames.has(name);
46
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
+ }
47
155
  export function managedAttemptToolDefinition(name) {
156
+ if (startManagedVerificationNames.has(name)) {
157
+ return {
158
+ name,
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.",
160
+ inputSchema: {
161
+ type: "object",
162
+ additionalProperties: false,
163
+ required: ["profile"],
164
+ properties: {
165
+ profile: {
166
+ type: "string",
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.",
169
+ },
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." },
173
+ max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
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." },
175
+ timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
176
+ },
177
+ },
178
+ };
179
+ }
48
180
  if (managedCommandNames.has(name) || startManagedCommandNames.has(name)) {
49
181
  return {
50
182
  name,
51
183
  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.",
184
+ ? "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."
185
+ : "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
186
  inputSchema: {
55
187
  type: "object",
56
188
  additionalProperties: false,
57
189
  required: ["command", "args"],
58
190
  properties: {
59
- command: { type: "string", minLength: 1 },
60
- 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." },
61
193
  cwd: { type: "string", description: "Worktree-relative directory; defaults to the worktree root." },
62
194
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 2700000 },
63
195
  },
@@ -81,14 +213,14 @@ export function managedAttemptToolDefinition(name) {
81
213
  if (waitManagedCommandNames.has(name)) {
82
214
  return {
83
215
  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.",
216
+ 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
217
  inputSchema: {
86
218
  type: "object",
87
219
  additionalProperties: false,
88
220
  required: ["command_id"],
89
221
  properties: {
90
222
  command_id: { type: "string", minLength: 1 },
91
- wait_timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 7200000 },
223
+ wait_timeout_ms: { type: "integer", minimum: 1000, maximum: 45000, default: 45000 },
92
224
  },
93
225
  },
94
226
  };
@@ -113,6 +245,7 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
113
245
  structuredContent: {
114
246
  status: "pass",
115
247
  quarantined_paths: result.quarantinedPaths,
248
+ retained_paths: result.retainedPaths,
116
249
  quarantine_directory: result.quarantineDirectory,
117
250
  },
118
251
  };
@@ -123,14 +256,21 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
123
256
  if (waitManagedCommandNames.has(name)) {
124
257
  return await waitManagedCommand(input);
125
258
  }
259
+ if (startManagedVerificationNames.has(name)) {
260
+ return await startManagedVerification(input, worktreePath);
261
+ }
126
262
  if (!managedCommandNames.has(name) && !startManagedCommandNames.has(name)) {
127
263
  throw new Error(`Unknown managed attempt tool: ${name}`);
128
264
  }
129
- const record = asRecord(input);
265
+ return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
266
+ }
267
+ async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
268
+ assertManagedCommandsAccepted();
130
269
  const command = requiredInputString(record, "command");
131
270
  const args = requiredStringArray(record, "args");
132
271
  const timeoutMs = optionalTimeout(record.timeout_ms);
133
272
  const cwd = await containedWorkingDirectory(worktreePath, record.cwd);
273
+ await validatePlaywrightCommandProject(command, args, cwd);
134
274
  const logDirectory = requiredAttemptEnvironment("FORGE_LOG_DIR");
135
275
  await fs.mkdir(path.join(logDirectory, "managed-commands"), { recursive: true, mode: 0o700 });
136
276
  const commandId = randomUUID();
@@ -146,8 +286,13 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
146
286
  metadataPath,
147
287
  receiptPath,
148
288
  startedAt: Date.now(),
289
+ verificationProfile,
290
+ worktreePath,
291
+ buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
292
+ buildReceiptReuse,
293
+ controller: new AbortController(),
149
294
  };
150
- if (startManagedCommandNames.has(name) || timeoutMs > maximumSynchronousWaitMs) {
295
+ if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
151
296
  const started = managedCommandResult({
152
297
  ...invocation,
153
298
  timedOut: false,
@@ -155,58 +300,419 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
155
300
  exitCode: null,
156
301
  stdout: "",
157
302
  stderr: "",
303
+ launchRequested: false,
158
304
  });
159
305
  await persistManagedCommandReceipt(receiptPath, started.structuredContent);
160
- const task = executeManagedCommand(invocation);
306
+ if (managedCommandOwnerShuttingDown) {
307
+ // Shutdown began while the receipt was written; the command never starts.
308
+ const refused = managedCommandResult({
309
+ ...invocation,
310
+ timedOut: false,
311
+ status: "runner_error",
312
+ exitCode: null,
313
+ stdout: "",
314
+ stderr: appendBounded("", managedCommandOwnerExitMessage),
315
+ launchRequested: false,
316
+ terminationReason: "owner_exited",
317
+ });
318
+ await persistManagedCommandReceipt(receiptPath, refused.structuredContent);
319
+ assertManagedCommandsAccepted();
320
+ }
321
+ const task = trackManagedCommand(invocation);
161
322
  managedCommandTasks.set(commandId, task);
162
323
  void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
163
324
  return {
164
- ...started,
325
+ ...managedCommandPublicResult(started),
165
326
  content: [{
166
327
  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.`,
328
+ 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
329
  }],
169
330
  };
170
331
  }
171
- return await executeManagedCommand(invocation);
332
+ return await trackManagedCommand(invocation);
333
+ }
334
+ function trackManagedCommand(invocation) {
335
+ const task = executeManagedCommand(invocation);
336
+ activeManagedCommands.set(invocation.commandId, { controller: invocation.controller, task });
337
+ void task.finally(() => {
338
+ activeManagedCommands.delete(invocation.commandId);
339
+ ownerExitStoppedCommands.delete(invocation.commandId);
340
+ }).catch(() => undefined);
341
+ return task;
342
+ }
343
+ async function startManagedVerification(input, worktreePath) {
344
+ const record = asRecord(input);
345
+ const profile = requiredInputString(record, "profile");
346
+ const shardCount = optionalBoundedInteger(record.shard_count, "shard_count", 1, 32, 1);
347
+ const shardIndex = optionalBoundedInteger(record.shard_index, "shard_index", 0, 31, 0);
348
+ if (shardIndex >= shardCount) {
349
+ throw new Error("managed_verification_invalid: shard_index must be less than shard_count.");
350
+ }
351
+ const noBuild = optionalBoolean(record.no_build, "no_build", false);
352
+ const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
353
+ const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
354
+ if (runAllShards && shardCount < 2) {
355
+ 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.");
356
+ }
357
+ if (runAllShards && shardIndex !== 0) {
358
+ throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
359
+ }
360
+ if (runAllShards && noBuild) {
361
+ 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.");
362
+ }
363
+ const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
364
+ const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
365
+ const buildReceiptReuse = noBuild
366
+ ? await verifyManagedBuildReceipt({
367
+ worktreePath,
368
+ configuration: managedBuildConfiguration(profileCommand.command, profileCommand.args),
369
+ requiredCoverage: managedVerificationBuildCoverage,
370
+ })
371
+ : undefined;
372
+ return await launchManagedCommand({
373
+ command: profileCommand.command,
374
+ args: profileCommand.args,
375
+ timeout_ms: record.timeout_ms ?? profileCommand.timeoutMs,
376
+ }, worktreePath, true, profile, !noBuild, buildReceiptReuse);
377
+ }
378
+ export function buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards = false, maxParallelism = 2) {
379
+ if (profile === "dotnet_affected") {
380
+ // The tests an uncommitted change can affect: one build, Unit and Contract whole, then
381
+ // only the affected heavier-tier classes. The script owns its build and its selection.
382
+ if (runAllShards || shardCount !== 1 || shardIndex !== 0 || noBuild) {
383
+ throw new Error("managed_verification_invalid: dotnet_affected selects its own tests and owns its build; it accepts no sharding or no_build.");
384
+ }
385
+ return {
386
+ command: process.execPath,
387
+ args: ["scripts/run-affected-dotnet-tests.mjs", "--results-directory", outputDirectory],
388
+ // A change that reaches tests without naming a type runs the heavier tiers whole.
389
+ timeoutMs: managedMaximumCommandTimeoutMs,
390
+ };
391
+ }
392
+ if (profile === "dotnet_solution") {
393
+ if (runAllShards) {
394
+ throw new Error("managed_verification_invalid: dotnet_solution does not support run_all_shards; select a test tier instead.");
395
+ }
396
+ if (shardCount !== 1 || shardIndex !== 0) {
397
+ throw new Error("managed_verification_invalid: dotnet_solution does not accept sharding; select a test tier instead.");
398
+ }
399
+ const command = preferredPowerShellExecutable();
400
+ const args = [
401
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-suite.ps1",
402
+ "-ResultsDirectory", outputDirectory,
403
+ "-MaxParallelism", String(maxParallelism),
404
+ ];
405
+ if (noBuild)
406
+ args.push("-NoBuild");
407
+ return { command, args, timeoutMs: managedLongTierTimeoutMs };
408
+ }
409
+ const tiers = {
410
+ dotnet_unit: "Unit",
411
+ dotnet_contract: "Contract",
412
+ dotnet_api_component: "ApiComponent",
413
+ dotnet_orchestration: "Orchestration",
414
+ dotnet_infrastructure: "Infrastructure",
415
+ };
416
+ const tier = tiers[profile];
417
+ if (!tier)
418
+ throw new Error(`managed_verification_invalid: unsupported profile ${profile}. ${managedVerificationProfileHint}`);
419
+ const command = preferredPowerShellExecutable();
420
+ if (runAllShards) {
421
+ return {
422
+ command,
423
+ args: [
424
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier-set.ps1",
425
+ "-Tier", tier,
426
+ "-ResultsDirectory", outputDirectory,
427
+ "-ShardCount", String(shardCount),
428
+ "-MaxParallelism", String(maxParallelism),
429
+ ],
430
+ timeoutMs: managedVerificationTierTimeoutMs(tier, { shardCount, maxParallelism }),
431
+ };
432
+ }
433
+ const args = [
434
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier.ps1",
435
+ "-Tier", tier,
436
+ "-ResultsDirectory", outputDirectory,
437
+ "-ShardCount", String(shardCount),
438
+ "-ShardIndex", String(shardIndex),
439
+ ];
440
+ if (noBuild)
441
+ args.push("-NoBuild");
442
+ return { command, args, timeoutMs: managedVerificationTierTimeoutMs(tier) };
443
+ }
444
+ export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
445
+ if (platform !== "win32")
446
+ return "pwsh";
447
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
448
+ }
449
+ export function validatePlaywrightProjectName(project, availableProjects) {
450
+ if (!availableProjects.includes(project)) {
451
+ throw new Error(`managed_command_capability_unavailable: Playwright project '${project}' is not advertised by the selected config. Available projects: ${availableProjects.join(", ") || "none"}.`);
452
+ }
453
+ }
454
+ async function validatePlaywrightCommandProject(command, args, cwd) {
455
+ const invocation = [path.basename(command).toLowerCase(), ...args.map(argument => argument.toLowerCase())];
456
+ if (!invocation.some(argument => argument.includes("playwright")))
457
+ return;
458
+ const project = optionValue(args, "--project");
459
+ if (!project)
460
+ return;
461
+ const configuredPath = optionValue(args, "--config") ?? process.env.FORGE_PLAYWRIGHT_CONFIG;
462
+ const candidates = configuredPath
463
+ ? [path.resolve(cwd, configuredPath)]
464
+ : ["playwright.config.ts", "playwright.config.js", "playwright.config.mjs"].map(file => path.join(cwd, file));
465
+ for (const candidate of candidates) {
466
+ try {
467
+ const source = await fs.readFile(candidate, "utf8");
468
+ const projects = playwrightProjectNamesFromConfigSource(source);
469
+ validatePlaywrightProjectName(project, projects);
470
+ return;
471
+ }
472
+ catch (error) {
473
+ if (error.code !== "ENOENT")
474
+ throw error;
475
+ }
476
+ }
477
+ throw new Error("managed_command_capability_unavailable: Playwright config was not found; project selection cannot be validated.");
478
+ }
479
+ export function playwrightProjectNamesFromConfigSource(source) {
480
+ const marker = source.match(/^\/\/ forge-playwright-projects: (\[[^\r\n]*\])$/mu)?.[1];
481
+ if (!marker) {
482
+ return [...source.matchAll(/\bname\s*:\s*["']([^"']+)["']/gu)].map(match => match[1]);
483
+ }
484
+ try {
485
+ const parsed = JSON.parse(marker);
486
+ return Array.isArray(parsed)
487
+ ? parsed.filter((value) => typeof value === "string" && value.trim().length > 0)
488
+ : [];
489
+ }
490
+ catch {
491
+ return [];
492
+ }
493
+ }
494
+ function optionValue(args, name) {
495
+ const direct = args.find(argument => argument.startsWith(`${name}=`));
496
+ if (direct)
497
+ return direct.slice(name.length + 1).trim() || null;
498
+ const index = args.indexOf(name);
499
+ return index >= 0 ? args[index + 1]?.trim() || null : null;
500
+ }
501
+ function hostCapacityLossReason(reason) {
502
+ if (reason instanceof HostCapacityTokenFencedError)
503
+ return "host_capacity_token_fenced";
504
+ if (reason instanceof HostCapacityLedgerUnavailableError)
505
+ return "host_capacity_ledger_unavailable";
506
+ return null;
172
507
  }
173
508
  async function executeManagedCommand(invocation) {
174
- const environment = inheritedEnvironment({
175
- FORGE_RUNTIME_MODE: "host",
176
- FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
177
- FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
178
- // This nested command owns a distinct supervisor identity. A command-local
179
- // fence avoids exposing the parent attempt's fencing capability to Codex's
180
- // MCP subprocess configuration while preserving exact-tree cleanup proof.
181
- FORGE_FENCING_TOKEN: randomUUID(),
182
- FORGE_LOG_DIR: invocation.logDirectory,
183
- FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
184
- FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
185
- FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
509
+ let processStarted = false;
510
+ // The per-worktree build slot is taken first: holding a host token while
511
+ // queued behind this worktree's own build would waste host capacity.
512
+ const hostCapacity = new ManagedCommandHostCapacity({ ...invocation, label: invocation.verificationProfile ?? invocation.commandId }, async (hostLoad) => await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
513
+ ...invocation,
514
+ hostLoad,
515
+ timedOut: false,
516
+ status: "waiting_for_host_capacity",
517
+ exitCode: null,
518
+ stdout: "",
519
+ stderr: "",
520
+ launchRequested: false,
521
+ }).structuredContent));
522
+ const launch = async (buildQueueWaitMs) => await hostCapacity.run(invocation.controller.signal, async (hostLoad, control) => {
523
+ processStarted = true;
524
+ // A reclaimed token means this command's capacity is gone: it stops. A fence that
525
+ // landed between admission and here stops it too (a listener added now never fires).
526
+ const stopOnFence = () => invocation.controller.abort(control.fenced.reason);
527
+ if (control.fenced?.aborted)
528
+ stopOnFence();
529
+ else
530
+ control.fenced?.addEventListener("abort", stopOnFence, { once: true });
531
+ try {
532
+ return await executeManagedCommandProcess({
533
+ ...invocation,
534
+ buildQueueWaitMs,
535
+ hostLoad,
536
+ // Recording the tree is part of holding the token: if it fails (the token was
537
+ // fenced meanwhile, or the ledger refused), the command stops instead of
538
+ // running on without a reservation the host can account for.
539
+ // Checked against the tree recorded on the token at launch (null: the governor's own).
540
+ holdHostCapacityUntilStopped: reason => control.holdUntilStopped?.(null, reason),
541
+ onProcessStarted: async () => await attachManagedCommandProcess(control, invocation.metadataPath)
542
+ .catch((error) => {
543
+ invocation.controller.abort(error instanceof HostCapacityTokenFencedError || error instanceof HostCapacityLedgerUnavailableError
544
+ ? error
545
+ : 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 }));
546
+ }),
547
+ });
548
+ }
549
+ finally {
550
+ control.fenced?.removeEventListener("abort", stopOnFence);
551
+ }
552
+ },
553
+ // A fenced release is already the receipt's termination reason; only a ledger fault is noted.
554
+ async (error) => error instanceof HostCapacityTokenFencedError ? undefined : await annotateManagedCommandReceipt(invocation.receiptPath, {
555
+ host_capacity_release_error: redactText(error instanceof Error ? error.message : String(error), []),
556
+ }));
557
+ try {
558
+ if (!invocation.buildProducing)
559
+ return await launch();
560
+ return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, launch, async () => {
561
+ const waiting = managedCommandResult({
562
+ ...invocation,
563
+ timedOut: false,
564
+ status: "waiting_for_build_slot",
565
+ exitCode: null,
566
+ stdout: "",
567
+ stderr: "",
568
+ launchRequested: false,
569
+ });
570
+ await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
571
+ }, invocation.controller.signal);
572
+ }
573
+ catch (error) {
574
+ if (processStarted)
575
+ throw error;
576
+ // The command never started (its build-slot or host-capacity wait failed or was
577
+ // stopped). Its receipt must still become terminal, or a waiting agent sees it queued forever.
578
+ const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
579
+ const receipt = managedCommandResult({
580
+ ...invocation,
581
+ hostLoad: await hostCapacity.unadmittedFields(error),
582
+ timedOut: false,
583
+ status: "runner_error",
584
+ exitCode: null,
585
+ stdout: "",
586
+ stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
587
+ terminationReason: ownerExited ? "owner_exited" : undefined,
588
+ launchRequested: false,
589
+ });
590
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
591
+ return managedCommandPublicResult(receipt);
592
+ }
593
+ }
594
+ /** A command's environment and redaction list; a setup that throws releases the database it started. */
595
+ async function managedCommandProcessEnvironment(invocation) {
596
+ assertHostDatabaseCapabilityBoundary();
597
+ const database = invocation.verificationProfile ? await managedVerificationDatabase() : noManagedVerificationDatabase;
598
+ return await setUpWithManagedVerificationDatabase(database, () => {
599
+ const exactSecrets = [
600
+ ...database.secrets,
601
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
602
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
603
+ ];
604
+ const environment = inheritedEnvironment({
605
+ FORGE_RUNTIME_MODE: "host",
606
+ FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
607
+ FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
608
+ // This nested command owns a distinct supervisor identity. A command-local
609
+ // fence avoids exposing the parent attempt's fencing capability to Codex's
610
+ // MCP subprocess configuration while preserving exact-tree cleanup proof.
611
+ FORGE_FENCING_TOKEN: randomUUID(),
612
+ FORGE_LOG_DIR: invocation.logDirectory,
613
+ FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
614
+ FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
615
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
616
+ ...(invocation.verificationProfile
617
+ ? {
618
+ FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
619
+ // Managed verification executes mutable worktree scripts, SDK targets,
620
+ // and test assemblies. It uses an attempt-owned container, or the
621
+ // dedicated native test cluster while Docker is unavailable; it never
622
+ // receives a capability for a server that holds real data.
623
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
624
+ ...database.environment,
625
+ }
626
+ : {}),
627
+ });
628
+ return { environment, exactSecrets, release: database.release };
186
629
  });
630
+ }
631
+ function clearManagedCommandTimers(...timers) {
632
+ // clearTimeout and clearInterval share one timer table.
633
+ for (const timer of timers)
634
+ if (timer)
635
+ clearTimeout(timer);
636
+ }
637
+ async function executeManagedCommandProcess(invocation) {
638
+ let prepared;
639
+ try {
640
+ prepared = await managedCommandProcessEnvironment(invocation);
641
+ }
642
+ catch (error) {
643
+ // The call still fails (the database capability boundary or the verification
644
+ // database probe refused it), but its receipt must not stay "starting" forever.
645
+ const receipt = managedCommandResult({
646
+ ...invocation,
647
+ timedOut: false,
648
+ status: "runner_error",
649
+ exitCode: null,
650
+ stdout: "",
651
+ stderr: appendBounded("", redactText(error instanceof Error ? error.message : String(error), [])),
652
+ launchRequested: false,
653
+ });
654
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent).catch(() => undefined);
655
+ throw error;
656
+ }
657
+ const { exactSecrets } = prepared;
187
658
  let stdout = "";
188
659
  let stderr = "";
189
- const controller = new AbortController();
660
+ const controller = invocation.controller;
190
661
  let timedOut = false;
191
662
  let timer = null;
192
663
  let outputRevision = 0;
193
664
  let lastOutputAt = null;
665
+ let lastOutputStream = null;
194
666
  let lastProgressPersistedAt = 0;
195
667
  let progressPersistence = Promise.resolve();
668
+ let progressHeartbeat = null;
669
+ let progressFinished = false;
670
+ const persistProgress = (force = false) => {
671
+ if (progressFinished)
672
+ return progressPersistence;
673
+ const next = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt, lastOutputStream }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; }, force);
674
+ // A heartbeat write is best-effort: one failed write (a locked or full disk) must
675
+ // not poison the chain, freeze later heartbeats, or fail a command that succeeded.
676
+ progressPersistence = force ? next.catch(() => undefined) : next;
677
+ return progressPersistence;
678
+ };
679
+ // Stop progress writes and let any in flight land before a terminal receipt is
680
+ // written, so a late "running" snapshot can never replace it.
681
+ const settleProgress = async () => {
682
+ progressFinished = true;
683
+ if (progressHeartbeat)
684
+ clearInterval(progressHeartbeat);
685
+ progressHeartbeat = null;
686
+ await progressPersistence;
687
+ };
196
688
  const launchTimer = setTimeout(() => {
197
689
  timedOut = true;
198
690
  controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
199
691
  }, managedCommandLaunchTimeoutMs);
200
692
  try {
693
+ if (controller.signal.aborted)
694
+ throw controller.signal.reason;
695
+ // Recorded before the spawn: the process record is written only once the child has
696
+ // spawned, so teardown must know a launch may exist without one.
697
+ await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
698
+ ...invocation,
699
+ timedOut: false,
700
+ status: "starting",
701
+ exitCode: null,
702
+ stdout,
703
+ stderr,
704
+ }).structuredContent);
201
705
  const result = await new StreamingProviderProcessRunner().run({
202
706
  command: invocation.command,
203
707
  args: invocation.args,
204
708
  cwd: invocation.cwd,
205
- env: environment,
709
+ env: prepared.environment,
206
710
  captureOutput: false,
207
711
  }, {
208
712
  onStarted: async () => {
209
713
  clearTimeout(launchTimer);
714
+ // onProcessStarted stops the command itself when its token cannot be held.
715
+ await invocation.onProcessStarted?.();
210
716
  const running = managedCommandResult({
211
717
  ...invocation,
212
718
  timedOut: false,
@@ -216,30 +722,64 @@ async function executeManagedCommand(invocation) {
216
722
  stderr,
217
723
  outputRevision,
218
724
  lastOutputAt,
725
+ lastOutputStream,
219
726
  });
220
727
  await persistManagedCommandReceipt(invocation.receiptPath, running.structuredContent);
221
728
  timer = setTimeout(() => {
222
729
  timedOut = true;
223
730
  controller.abort(new Error(`managed_command_timeout: exceeded ${invocation.timeoutMs}ms.`));
224
731
  }, invocation.timeoutMs);
732
+ // Output alone does not keep the receipt current: a test tier can print a burst
733
+ // and then run quietly for many minutes. Without this heartbeat the elapsed time
734
+ // and the burst's last lines freeze, and a waiting agent sees a hung command.
735
+ // The run can already have failed while the "running" write above was pending.
736
+ if (progressFinished)
737
+ return;
738
+ progressHeartbeat = setInterval(() => {
739
+ void persistProgress(true);
740
+ }, managedCommandProgressPersistIntervalMs);
741
+ progressHeartbeat.unref();
225
742
  },
226
743
  onStdoutLine: (line) => {
227
- stdout = appendBounded(stdout, line);
744
+ stdout = appendBounded(stdout, redactText(line, exactSecrets));
228
745
  outputRevision += 1;
229
746
  lastOutputAt = Date.now();
230
- progressPersistence = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; });
231
- return progressPersistence;
747
+ lastOutputStream = "stdout";
748
+ return persistProgress();
232
749
  },
233
750
  onStderrLine: (line) => {
234
- stderr = appendBounded(stderr, line);
751
+ stderr = appendBounded(stderr, redactText(line, exactSecrets));
235
752
  outputRevision += 1;
236
753
  lastOutputAt = Date.now();
237
- progressPersistence = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; });
238
- return progressPersistence;
754
+ lastOutputStream = "stderr";
755
+ return persistProgress();
239
756
  },
240
757
  }, controller.signal);
241
- await progressPersistence;
242
- const status = timedOut ? "timed_out" : result.exitCode === 0 ? "pass" : "fail";
758
+ await settleProgress();
759
+ // Only a stop that interrupted the process relabels it. A command that exited on its own
760
+ // just before its owner asked for the stop keeps its real result.
761
+ const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
762
+ const hostCapacityLoss = !timedOut && !ownerExited && result.cancelled === true
763
+ ? hostCapacityLossReason(controller.signal.reason)
764
+ : null;
765
+ const fenced = hostCapacityLoss !== null;
766
+ if (ownerExited || fenced) {
767
+ stderr = appendBounded(stderr, ownerExited ? managedCommandOwnerExitMessage : controller.signal.reason.message);
768
+ outputRevision += 1;
769
+ lastOutputAt = Date.now();
770
+ lastOutputStream = "stderr";
771
+ }
772
+ const status = timedOut ? "timed_out" : ownerExited || fenced ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
773
+ const receiptCoverage = managedBuildReceiptCoverage(invocation);
774
+ const buildReceipt = status === "pass" && receiptCoverage
775
+ ? await publishManagedBuildReceipt({
776
+ worktreePath: invocation.worktreePath,
777
+ command: invocation.command,
778
+ args: invocation.args,
779
+ configuration: managedBuildConfiguration(invocation.command, invocation.args),
780
+ coverage: receiptCoverage,
781
+ })
782
+ : invocation.buildReceiptReuse;
243
783
  const receipt = managedCommandResult({
244
784
  ...invocation,
245
785
  timedOut,
@@ -249,13 +789,27 @@ async function executeManagedCommand(invocation) {
249
789
  stderr,
250
790
  outputRevision,
251
791
  lastOutputAt,
792
+ lastOutputStream,
793
+ buildReceipt,
794
+ buildReceiptReused: invocation.buildReceiptReuse !== undefined,
795
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLoss ?? undefined,
796
+ // The runner resolves only after the stopped tree is proven gone.
797
+ processTreeTerminated: ownerExited || fenced ? true : undefined,
252
798
  });
253
799
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
254
- return receipt;
800
+ return managedCommandPublicResult(receipt);
255
801
  }
256
802
  catch (error) {
257
- const message = error instanceof Error ? error.message : String(error);
803
+ // The failure may be a progress write itself; it is reported below.
804
+ await settleProgress().catch(() => undefined);
805
+ const ownerExited = !timedOut && ownerExitStoppedCommands.has(invocation.commandId);
806
+ const message = ownerExited
807
+ ? managedCommandOwnerExitMessage
808
+ : redactText(error instanceof Error ? error.message : String(error), exactSecrets);
258
809
  stderr = appendBounded(stderr, message);
810
+ outputRevision += 1;
811
+ lastOutputAt = Date.now();
812
+ lastOutputStream = "stderr";
259
813
  const receipt = managedCommandResult({
260
814
  ...invocation,
261
815
  timedOut,
@@ -265,14 +819,24 @@ async function executeManagedCommand(invocation) {
265
819
  stderr,
266
820
  outputRevision,
267
821
  lastOutputAt,
822
+ lastOutputStream,
823
+ // A host capacity loss before launch (a fence that landed while it was admitted) is named too.
824
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLossReason(controller.signal.reason) ?? undefined,
825
+ // The runner rejected, so its tree was not proven stopped; teardown still stops it.
826
+ processTreeTerminated: false,
268
827
  });
269
828
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
270
- return receipt;
829
+ // The runner stops the tree before it rejects; only a failed termination proof means
830
+ // part of it may still run. Its token is then kept, never returned with this receipt.
831
+ if (isProcessTreeTerminationUnproven(error)) {
832
+ invocation.holdHostCapacityUntilStopped?.(error instanceof Error ? error : new Error(String(error)));
833
+ }
834
+ return managedCommandPublicResult(receipt);
271
835
  }
272
836
  finally {
273
- clearTimeout(launchTimer);
274
- if (timer)
275
- clearTimeout(timer);
837
+ clearManagedCommandTimers(launchTimer, timer, progressHeartbeat);
838
+ // An ephemeral verification cluster lives exactly as long as its command; one that would not stop is reaped later and named in the receipt.
839
+ await releaseManagedVerificationDatabase(prepared, async (message) => await annotateManagedCommandReceipt(invocation.receiptPath, { ephemeral_cluster_release_error: redactText(message, exactSecrets) }));
276
840
  }
277
841
  }
278
842
  async function readManagedCommand(input) {
@@ -288,10 +852,15 @@ async function readManagedCommand(input) {
288
852
  }
289
853
  throw error;
290
854
  }
855
+ // A queued receipt is written once; its wait so far is computed when it is read.
856
+ const hostLoadWaitStartedAt = Date.parse(String(receipt.host_load_wait_started_at));
857
+ if (receipt.status === "waiting_for_host_capacity" && Number.isFinite(hostLoadWaitStartedAt)) {
858
+ receipt = { ...receipt, host_load_wait_ms: Math.max(0, Date.now() - hostLoadWaitStartedAt) };
859
+ }
291
860
  const status = typeof receipt.status === "string" ? receipt.status : "unknown";
292
861
  const stdout = typeof receipt.stdout === "string" ? receipt.stdout : "";
293
862
  const stderr = typeof receipt.stderr === "string" ? receipt.stderr : "";
294
- return {
863
+ return managedCommandPublicResult({
295
864
  content: [{
296
865
  type: "text",
297
866
  text: terminalManagedCommandStatuses.has(status)
@@ -307,13 +876,14 @@ async function readManagedCommand(input) {
307
876
  }],
308
877
  structuredContent: receipt,
309
878
  isError: terminalManagedCommandStatuses.has(status) && status !== "pass",
310
- };
879
+ });
311
880
  }
312
881
  async function waitManagedCommand(input) {
313
882
  const record = asRecord(input);
314
883
  const commandId = validatedCommandId(record);
315
- const waitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
316
- const deadline = Date.now() + waitTimeoutMs;
884
+ const requestedWaitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
885
+ const waitTimeoutMs = Math.min(requestedWaitTimeoutMs, maximumSynchronousWaitMs);
886
+ const deadline = monotonicNowMs() + waitTimeoutMs;
317
887
  const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
318
888
  const task = managedCommandTasks.get(commandId);
319
889
  if (task) {
@@ -324,50 +894,58 @@ async function waitManagedCommand(input) {
324
894
  if (result)
325
895
  return result;
326
896
  }
327
- while (Date.now() < deadline) {
897
+ while (monotonicNowMs() < deadline) {
328
898
  const result = await readManagedCommand({ command_id: commandId });
329
899
  if (terminalManagedCommandStatuses.has(String(result.structuredContent.status))) {
330
900
  return result;
331
901
  }
332
- await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - Date.now())));
902
+ await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - monotonicNowMs())));
333
903
  }
334
904
  const receipt = await readManagedCommand({ command_id: commandId });
905
+ // Only a running receipt is refreshed on a heartbeat; queued or starting receipts are
906
+ // written once, so their elapsed time says nothing about progress.
907
+ const elapsedMs = receipt.structuredContent.elapsed_ms;
908
+ const timeoutMs = receipt.structuredContent.timeout_ms;
909
+ const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
910
+ const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
911
+ const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
912
+ ? ` 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.`
913
+ : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
914
+ ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
915
+ + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
916
+ + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
917
+ // Agents otherwise abandon long verification tiers and record a blocker that is not one.
918
+ + (typeof timeoutMs === "number"
919
+ ? ` 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.`
920
+ : "")
921
+ : "";
335
922
  return {
336
923
  ...receipt,
337
924
  content: [{
338
925
  type: "text",
339
- text: `Forge is still supervising managed command ${commandId} after waiting ${waitTimeoutMs}ms. Its durable receipt remains at ${receiptPath}.`,
926
+ 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
927
  }],
928
+ structuredContent: {
929
+ ...receipt.structuredContent,
930
+ command_continues: true,
931
+ terminal: false,
932
+ wait_timeout_ms: waitTimeoutMs,
933
+ requested_wait_timeout_ms: requestedWaitTimeoutMs,
934
+ retry_after_ms: managedCommandRetryAfterMs,
935
+ },
936
+ isError: false,
341
937
  };
342
938
  }
343
939
  function managedCommandReceiptPath(logDirectory, commandId) {
344
940
  return path.join(logDirectory, "managed-commands", `${commandId}.receipt.json`);
345
941
  }
346
942
  async function persistManagedCommandReceipt(receiptPath, receipt) {
347
- const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
348
- await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
349
- try {
350
- for (let attempt = 1;; attempt += 1) {
351
- try {
352
- await fs.rename(temporaryPath, receiptPath);
353
- break;
354
- }
355
- catch (error) {
356
- const code = error.code;
357
- if (attempt >= managedCommandReceiptReplaceAttempts
358
- || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES")) {
359
- throw error;
360
- }
361
- await delay(managedCommandReceiptReplaceRetryMs);
362
- }
363
- }
364
- }
365
- finally {
366
- await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
367
- }
943
+ await persistJsonAtomically(receiptPath, receipt);
368
944
  }
369
945
  function managedCommandResult(values) {
370
- const elapsedMs = Date.now() - values.startedAt;
946
+ // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
947
+ const hostLoad = values.hostLoad;
948
+ const elapsedMs = Date.now() - (hostLoad ? hostLoad.executionStartedAt ?? Date.now() : values.startedAt);
371
949
  const isTerminal = terminalManagedCommandStatuses.has(values.status);
372
950
  const diagnostics = isTerminal
373
951
  ? managedCommandDiagnostics(values.stdout, values.stderr)
@@ -403,16 +981,94 @@ function managedCommandResult(values) {
403
981
  || values.stderr.length >= maximumCapturedCharacters,
404
982
  output_revision: values.outputRevision ?? 0,
405
983
  last_output_at: values.lastOutputAt ? new Date(values.lastOutputAt).toISOString() : null,
984
+ last_output_stream: values.lastOutputStream ?? null,
406
985
  supervisor_metadata_path: values.metadataPath,
407
986
  receipt_path: values.receiptPath,
408
- process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : undefined,
987
+ verification_profile: values.verificationProfile ?? null,
988
+ verification_profile_runner_authored: values.verificationProfile !== undefined,
989
+ build_producing: values.buildProducing,
990
+ build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
991
+ build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
992
+ build_receipt_reused: values.buildReceiptReused ?? false,
993
+ ...(hostLoad ? managedCommandHostLoadReceipt(hostLoad) : {}),
994
+ build_receipt: values.buildReceipt ? {
995
+ fingerprint: values.buildReceipt.fingerprint,
996
+ receipt_path: values.buildReceipt.receiptPath,
997
+ producer_command: values.buildReceipt.producerCommand,
998
+ configuration: values.buildReceipt.configuration,
999
+ coverage: values.buildReceipt.coverage,
1000
+ output_count: values.buildReceipt.outputCount,
1001
+ } : null,
1002
+ runtime_configuration: managedRuntimeConfiguration(),
1003
+ // The supervising MCP server process. Forge stops a command whose owner has exited.
1004
+ owner_pid: process.pid,
1005
+ owner_identity: managedCommandOwnerIdentity(),
1006
+ launch_requested: values.launchRequested ?? true,
1007
+ process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : values.processTreeTerminated,
1008
+ ...(values.terminationReason ? { termination_reason: values.terminationReason } : {}),
409
1009
  },
410
1010
  isError: isTerminal && values.status !== "pass",
411
1011
  };
412
1012
  }
413
- function persistManagedCommandProgressIfDue(invocation, snapshot, previousPersistence, lastPersistedAt, setLastPersistedAt) {
1013
+ function managedCommandHostLoadReceipt(hostLoad) {
1014
+ const waiting = hostLoad.waitStartedAt !== undefined;
1015
+ return {
1016
+ host_load_step_class: hostLoad.stepClass,
1017
+ host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
1018
+ ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString(), host_load_wait_detail: hostLoad.waitDetail ?? null } : {}),
1019
+ };
1020
+ }
1021
+ async function annotateManagedCommandReceipt(receiptPath, fields) {
1022
+ const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
1023
+ await persistManagedCommandReceipt(receiptPath, { ...receipt, ...fields });
1024
+ }
1025
+ /** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
1026
+ function managedCommandOwnerIdentity() {
1027
+ // Windows identity capture starts PowerShell; the PID check alone is used there.
1028
+ ownerProcessIdentity ??= process.platform === "linux" ? captureHostProcessIdentity(process.pid) : null;
1029
+ return ownerProcessIdentity;
1030
+ }
1031
+ function managedRuntimeConfiguration() {
1032
+ const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
1033
+ let providerOnlySpecCount = 0;
1034
+ if (providerOnlySpecs) {
1035
+ try {
1036
+ const parsed = JSON.parse(providerOnlySpecs);
1037
+ providerOnlySpecCount = Array.isArray(parsed)
1038
+ ? parsed.filter(value => typeof value === "string" && value.length > 0).length
1039
+ : 0;
1040
+ }
1041
+ catch {
1042
+ providerOnlySpecCount = 0;
1043
+ }
1044
+ }
1045
+ return {
1046
+ attempt_database_schema: process.env.FORGE_ATTEMPT_DATABASE_SCHEMA ?? null,
1047
+ attempt_database_readiness_path: process.env.FORGE_ATTEMPT_DATABASE_READINESS_PATH ?? null,
1048
+ playwright_config: process.env.FORGE_PLAYWRIGHT_CONFIG ?? null,
1049
+ provider_only_spec_count: providerOnlySpecCount,
1050
+ provider_only_spec_fingerprint: providerOnlySpecs
1051
+ ? `sha256:${createHash("sha256").update(providerOnlySpecs).digest("hex")}`
1052
+ : null,
1053
+ };
1054
+ }
1055
+ function managedCommandPublicResult(result) {
1056
+ const stdout = typeof result.structuredContent.stdout === "string" ? result.structuredContent.stdout : "";
1057
+ const stderr = typeof result.structuredContent.stderr === "string" ? result.structuredContent.stderr : "";
1058
+ const { stdout: _stdout, stderr: _stderr, ...receipt } = result.structuredContent;
1059
+ return {
1060
+ ...result,
1061
+ structuredContent: {
1062
+ ...receipt,
1063
+ stdout_tail: tail(stdout, maximumReturnedOutputCharacters),
1064
+ stderr_tail: tail(stderr, maximumReturnedOutputCharacters),
1065
+ full_output_in_receipt: true,
1066
+ },
1067
+ };
1068
+ }
1069
+ function persistManagedCommandProgressIfDue(invocation, snapshot, previousPersistence, lastPersistedAt, setLastPersistedAt, force = false) {
414
1070
  const now = Date.now();
415
- if (now - lastPersistedAt() < managedCommandProgressPersistIntervalMs)
1071
+ if (!force && now - lastPersistedAt() < managedCommandProgressPersistIntervalMs)
416
1072
  return previousPersistence;
417
1073
  setLastPersistedAt(now);
418
1074
  const current = snapshot();
@@ -441,18 +1097,70 @@ async function containedWorkingDirectory(worktreePath, input) {
441
1097
  }
442
1098
  function inheritedEnvironment(overrides) {
443
1099
  const env = {};
444
- for (const [key, value] of Object.entries(process.env)) {
1100
+ // A nested Forge process must not join the host ledger: it would queue behind the
1101
+ // token this command already holds. Every FORGE_HOST_LOAD_* variable is dropped,
1102
+ // the test slot count too (decision 0018).
1103
+ for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(process.env))) {
445
1104
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
446
1105
  env[key] = value;
447
1106
  }
448
1107
  return { ...env, ...overrides };
449
1108
  }
1109
+ export function isBuildProducingManagedCommand(command, args) {
1110
+ const executable = path.basename(command).toLowerCase();
1111
+ if (executable === "dotnet" || executable === "dotnet.exe") {
1112
+ const verb = args.find(argument => !argument.startsWith("-"))?.toLowerCase();
1113
+ if (!verb || !new Set(["build", "test", "restore", "publish", "pack", "msbuild"]).has(verb))
1114
+ return false;
1115
+ return verb === "restore" || !args.some(argument => argument.toLowerCase() === "--no-build");
1116
+ }
1117
+ if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1118
+ const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
1119
+ const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
1120
+ if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
1121
+ return !args.some(argument => argument.toLowerCase() === "-nobuild");
1122
+ }
1123
+ if (script === "run-dotnet-test-tier.ps1") {
1124
+ return !args.some(argument => argument.toLowerCase() === "-nobuild");
1125
+ }
1126
+ }
1127
+ return false;
1128
+ }
1129
+ function managedBuildReceiptCoverage(invocation) {
1130
+ if (!invocation.buildProducing)
1131
+ return null;
1132
+ if (invocation.verificationProfile)
1133
+ return managedVerificationBuildCoverage;
1134
+ const executable = path.basename(invocation.command).toLowerCase();
1135
+ if (executable === "dotnet" || executable === "dotnet.exe") {
1136
+ const verb = invocation.args.find(argument => !argument.startsWith("-"))?.toLowerCase();
1137
+ if (!verb || !new Set(["build", "test"]).has(verb))
1138
+ return null;
1139
+ const target = invocation.args.find(argument => /\.(?:sln|slnx|csproj)$/iu.test(argument));
1140
+ if (target && (/\.(?:sln|slnx)$/iu.test(target) || /(?:^|[\\/])Forge\.Api\.Tests\.csproj$/iu.test(target))) {
1141
+ return managedVerificationBuildCoverage;
1142
+ }
1143
+ return null;
1144
+ }
1145
+ if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1146
+ const fileIndex = invocation.args.findIndex(argument => argument.toLowerCase() === "-file");
1147
+ const script = fileIndex >= 0 ? path.basename(invocation.args[fileIndex + 1] ?? "").toLowerCase() : "";
1148
+ if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)
1149
+ && !invocation.args.some(argument => argument.toLowerCase() === "-nobuild")) {
1150
+ return managedVerificationBuildCoverage;
1151
+ }
1152
+ }
1153
+ return null;
1154
+ }
450
1155
  function looksSensitiveEnvironmentName(name) {
451
1156
  const normalized = name.trim().toUpperCase();
452
1157
  return normalized.includes("SECRET")
453
1158
  || normalized.includes("TOKEN")
454
1159
  || normalized.includes("PASSWORD")
455
1160
  || normalized.includes("CREDENTIAL")
1161
+ || normalized.includes("CONNECTION_STRING")
1162
+ || normalized.startsWith("CONNECTIONSTRINGS__")
1163
+ || normalized.startsWith("CONNECTIONSTRINGS:")
456
1164
  || normalized.endsWith("_API_KEY")
457
1165
  || normalized === "OPENAI_API_KEY";
458
1166
  }
@@ -467,8 +1175,17 @@ function asRecord(value) {
467
1175
  throw new Error("managed_command_invalid: input must be an object.");
468
1176
  return value;
469
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
+ };
470
1183
  function requiredInputString(record, name) {
471
- 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(" ")}` : ""}`);
472
1189
  }
473
1190
  function validatedCommandId(record) {
474
1191
  const commandId = requiredInputString(record, "command_id");
@@ -485,7 +1202,13 @@ function requiredStandaloneString(value, name) {
485
1202
  function requiredStringArray(record, name) {
486
1203
  const value = record[name];
487
1204
  if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) {
488
- 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}`);
489
1212
  }
490
1213
  return value;
491
1214
  }
@@ -499,12 +1222,27 @@ function optionalTimeout(value) {
499
1222
  }
500
1223
  function optionalWaitTimeout(value) {
501
1224
  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.");
1225
+ return maximumSynchronousWaitMs;
1226
+ if (!Number.isSafeInteger(value) || value < 1_000 || value > maximumSynchronousWaitMs) {
1227
+ throw new Error(`managed_command_invalid: wait_timeout_ms must be an integer from 1000 through ${maximumSynchronousWaitMs}.`);
1228
+ }
1229
+ return value;
1230
+ }
1231
+ function optionalBoundedInteger(value, name, minimum, maximum, fallback) {
1232
+ if (value === undefined)
1233
+ return fallback;
1234
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
1235
+ throw new Error(`managed_verification_invalid: ${name} must be an integer from ${minimum} through ${maximum}.`);
505
1236
  }
506
1237
  return value;
507
1238
  }
1239
+ function optionalBoolean(value, name, fallback) {
1240
+ if (value === undefined)
1241
+ return fallback;
1242
+ if (typeof value !== "boolean")
1243
+ throw new Error(`managed_verification_invalid: ${name} must be a boolean.`);
1244
+ return value;
1245
+ }
508
1246
  async function delay(ms) {
509
1247
  await new Promise(resolve => setTimeout(resolve, ms));
510
1248
  }