@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.deb7f72e7930

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 (253) hide show
  1. package/README.md +144 -3
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +92 -15
  16. package/dist/bridge/bridge.service.js +432 -342
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  25. package/dist/bridge/runner-host-capabilities.js +17 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  29. package/dist/bridge/test-postgres-capability.js +120 -0
  30. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  31. package/dist/cleanup/cleanup-wip.js +66 -0
  32. package/dist/cleanup/cleanup.service.d.ts +20 -1
  33. package/dist/cleanup/cleanup.service.js +150 -169
  34. package/dist/cleanup/cleanup.types.d.ts +6 -0
  35. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  36. package/dist/cleanup/forge-owned-paths.js +53 -0
  37. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  38. package/dist/cleanup/host-runtime-ledger.js +130 -0
  39. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  40. package/dist/cleanup/managed-branch-sweep.js +111 -0
  41. package/dist/cli/cli.help.js +74 -12
  42. package/dist/cli/cli.service.d.ts +19 -10
  43. package/dist/cli/cli.service.js +152 -187
  44. package/dist/cli/idle-status.d.ts +84 -0
  45. package/dist/cli/idle-status.js +181 -0
  46. package/dist/cli/local-config.d.ts +6 -0
  47. package/dist/cli/local-config.js +32 -4
  48. package/dist/cli/provider-cli-detection.d.ts +10 -0
  49. package/dist/cli/provider-cli-detection.js +160 -0
  50. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  51. package/dist/runtime/aspnet-runtime-prebuild.js +140 -7
  52. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  53. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  54. package/dist/runtime/docker-engine-probe.js +7 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  56. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  57. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  58. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  59. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  60. package/dist/runtime/host-database-capability-boundary.js +1 -0
  61. package/dist/runtime/host-facts.d.ts +36 -0
  62. package/dist/runtime/host-facts.js +95 -0
  63. package/dist/runtime/host-load-admission.d.ts +67 -0
  64. package/dist/runtime/host-load-admission.js +99 -0
  65. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  66. package/dist/runtime/host-load-child-environment.js +76 -0
  67. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  68. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  69. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  70. package/dist/runtime/host-load-governor-config.js +83 -0
  71. package/dist/runtime/host-load-governor.d.ts +186 -0
  72. package/dist/runtime/host-load-governor.js +632 -0
  73. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  74. package/dist/runtime/host-load-ledger-lock.js +187 -0
  75. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  76. package/dist/runtime/host-load-runtime-settings.js +80 -0
  77. package/dist/runtime/host-load-sampler.d.ts +156 -0
  78. package/dist/runtime/host-load-sampler.js +298 -0
  79. package/dist/runtime/host-load-step-class.d.ts +70 -0
  80. package/dist/runtime/host-load-step-class.js +161 -0
  81. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  82. package/dist/runtime/host-load-step-reaper.js +95 -0
  83. package/dist/runtime/host-load-step-run.d.ts +73 -0
  84. package/dist/runtime/host-load-step-run.js +102 -0
  85. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  86. package/dist/runtime/host-load-test-slot.js +81 -0
  87. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  88. package/dist/runtime/host-load-token-ledger.js +453 -0
  89. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  90. package/dist/runtime/host-load-windows-cpu.js +85 -0
  91. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  92. package/dist/runtime/host-pressure-stall.js +168 -0
  93. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  94. package/dist/runtime/host-runtime-contract.js +35 -2
  95. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  96. package/dist/runtime/host-runtime-lease.js +285 -55
  97. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  98. package/dist/runtime/host-runtime-promotion.js +48 -0
  99. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  100. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  101. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  102. package/dist/runtime/host-runtime-requirements.js +117 -0
  103. package/dist/runtime/managed-command-teardown.js +5 -16
  104. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  105. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  106. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  107. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  108. package/dist/runtime/runner-settings.d.ts +104 -0
  109. package/dist/runtime/runner-settings.js +236 -0
  110. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  111. package/dist/sandbox/host-capacity-broker.js +336 -0
  112. package/dist/sandbox/managed-branch.d.ts +13 -0
  113. package/dist/sandbox/managed-branch.js +36 -0
  114. package/dist/sandbox/provider-auth/codex.js +11 -11
  115. package/dist/sandbox/runtime.d.ts +10 -1
  116. package/dist/sandbox/runtime.js +47 -8
  117. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  118. package/dist/sandbox/sandbox-cgroups.js +42 -0
  119. package/dist/session/architect-waits.d.ts +2 -0
  120. package/dist/session/architect-waits.js +138 -0
  121. package/dist/session/managed-attempt-tools.d.ts +2 -7
  122. package/dist/session/managed-attempt-tools.js +202 -116
  123. package/dist/session/managed-build-receipt.d.ts +5 -0
  124. package/dist/session/managed-build-receipt.js +8 -3
  125. package/dist/session/managed-command-host-load.d.ts +47 -0
  126. package/dist/session/managed-command-host-load.js +83 -0
  127. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  128. package/dist/session/mcp-argument-coercion.js +121 -0
  129. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  130. package/dist/session/phase-completion.artifacts.js +100 -26
  131. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  132. package/dist/session/phase-completion.command-validation.js +77 -0
  133. package/dist/session/phase-completion.d.ts +12 -0
  134. package/dist/session/phase-completion.helpers.js +13 -12
  135. package/dist/session/phase-completion.js +5 -0
  136. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  137. package/dist/session/phase-completion.mcp-args.js +156 -0
  138. package/dist/session/phase-completion.prompts.js +6 -1
  139. package/dist/session/phase-completion.runtime.d.ts +5 -11
  140. package/dist/session/phase-completion.runtime.js +91 -215
  141. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  142. package/dist/session/phase-completion.schema-parts.js +188 -0
  143. package/dist/session/phase-completion.schemas.d.ts +3 -3
  144. package/dist/session/phase-completion.schemas.js +208 -231
  145. package/dist/session/phase-completion.validation.d.ts +2 -3
  146. package/dist/session/phase-completion.validation.js +49 -93
  147. package/dist/session/pre-publication-host-load.d.ts +27 -0
  148. package/dist/session/pre-publication-host-load.js +111 -0
  149. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  150. package/dist/session/pre-publication-native-postgres.js +111 -0
  151. package/dist/session/pre-publication-pass.d.ts +61 -0
  152. package/dist/session/pre-publication-pass.js +148 -0
  153. package/dist/session/pre-publication-process.d.ts +3 -0
  154. package/dist/session/pre-publication-process.js +33 -20
  155. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  156. package/dist/session/pre-publication-skipped-tests.js +109 -0
  157. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  158. package/dist/session/pre-publication-step-execution.js +50 -0
  159. package/dist/session/pre-publication-validation.d.ts +37 -21
  160. package/dist/session/pre-publication-validation.js +224 -166
  161. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  162. package/dist/session/provider-cli/claude-background-work.js +181 -0
  163. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  164. package/dist/session/provider-cli/host-build-lock.js +30 -0
  165. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  166. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  167. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  168. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  169. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  170. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  171. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  172. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  173. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  174. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  175. package/dist/session/provider-cli/provider-cli.process.d.ts +41 -31
  176. package/dist/session/provider-cli/provider-cli.process.js +139 -438
  177. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  178. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  179. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  180. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  181. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  182. package/dist/session/provider-cli/provider-cli.service.js +200 -189
  183. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  184. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  185. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  186. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  188. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  189. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  190. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  191. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  192. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  193. package/dist/session/provider-cli/provider-output-state.js +15 -0
  194. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  195. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  196. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  197. package/dist/session/publishable-worktree-changes.js +193 -0
  198. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  199. package/dist/session/qa-sidecar-validation.js +28 -0
  200. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  201. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  202. package/dist/session/session-redaction.js +31 -181
  203. package/dist/session/session.base.d.ts +9 -1
  204. package/dist/session/session.service.d.ts +11 -2
  205. package/dist/session/session.service.js +182 -61
  206. package/dist/session/session.types.d.ts +3 -0
  207. package/dist/session/session.types.js +15 -3
  208. package/dist/session/sidecar-json-shape.d.ts +31 -0
  209. package/dist/session/sidecar-json-shape.js +217 -0
  210. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  211. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  212. package/dist/shared/fs/file-identity.d.ts +10 -0
  213. package/dist/shared/fs/file-identity.js +15 -0
  214. package/dist/shared/fs/replace-file.d.ts +7 -0
  215. package/dist/shared/fs/replace-file.js +33 -0
  216. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  217. package/dist/shared/process/host-process-recovery.js +23 -3
  218. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  219. package/dist/shared/process/host-process-supervisor.js +67 -15
  220. package/dist/shared/process/process-tree.d.ts +52 -0
  221. package/dist/shared/process/process-tree.js +144 -0
  222. package/dist/shared/process/process.d.ts +67 -0
  223. package/dist/shared/process/process.js +213 -11
  224. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  225. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  226. package/dist/shared/process/windows-launch.d.ts +18 -0
  227. package/dist/shared/process/windows-launch.js +68 -0
  228. package/dist/shared/provider-capabilities.js +14 -7
  229. package/dist/version.d.ts +1 -1
  230. package/dist/version.js +1 -1
  231. package/dist/worktree/dependency-warmer.d.ts +25 -0
  232. package/dist/worktree/dependency-warmer.js +46 -10
  233. package/dist/worktree/wip-git.d.ts +33 -0
  234. package/dist/worktree/wip-git.js +122 -0
  235. package/dist/worktree/wip-refs.d.ts +62 -0
  236. package/dist/worktree/wip-refs.js +119 -0
  237. package/dist/worktree/wip-restore.d.ts +38 -0
  238. package/dist/worktree/wip-restore.js +190 -0
  239. package/dist/worktree/wip-snapshot.d.ts +50 -0
  240. package/dist/worktree/wip-snapshot.js +268 -0
  241. package/dist/worktree/worktree-inputs.d.ts +8 -0
  242. package/dist/worktree/worktree-inputs.js +134 -0
  243. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  244. package/dist/worktree/worktree-origin-sync.js +127 -0
  245. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  246. package/dist/worktree/worktree-wip-events.js +98 -0
  247. package/dist/worktree/worktree-wip.d.ts +49 -0
  248. package/dist/worktree/worktree-wip.js +182 -0
  249. package/dist/worktree/worktree.base.d.ts +7 -1
  250. package/dist/worktree/worktree.service.d.ts +36 -5
  251. package/dist/worktree/worktree.service.js +120 -155
  252. package/dist/worktree/worktree.types.d.ts +38 -0
  253. package/package.json +2 -2
@@ -3,13 +3,18 @@ import fs from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
6
- import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
7
6
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
8
7
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
9
- import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
8
+ import { managedVerificationDatabase, noManagedVerificationDatabase, releaseManagedVerificationDatabase, setUpWithManagedVerificationDatabase } from "../runtime/ephemeral-test-postgres-grant.js";
10
9
  import { redactText } from "../shared/redaction/redaction.js";
10
+ import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
11
11
  import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
12
- import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.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";
13
18
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
14
19
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
15
20
  import { monotonicNowMs } from "../shared/time/monotonic.js";
@@ -32,8 +37,6 @@ const managedCommandRetryAfterMs = 60_000;
32
37
  const managedCommandLaunchTimeoutMs = 60_000;
33
38
  const managedCommandProgressPersistIntervalMs = 5_000;
34
39
  const managedCommandReceiptPollIntervalMs = 1_000;
35
- const managedCommandReceiptReplaceAttempts = 40;
36
- const managedCommandReceiptReplaceRetryMs = 25;
37
40
  const terminalManagedCommandStatuses = new Set([
38
41
  "pass",
39
42
  "fail",
@@ -143,11 +146,17 @@ export function isManagedAttemptTool(name) {
143
146
  || startManagedVerificationNames.has(name)
144
147
  || resetGeneratedOutputNames.has(name);
145
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
+ }
146
155
  export function managedAttemptToolDefinition(name) {
147
156
  if (startManagedVerificationNames.has(name)) {
148
157
  return {
149
158
  name,
150
- description: "Start a canonical Forge verification profile with runner-owned cwd, arguments, attempt output, timeout, and process supervision. Prefer this over reconstructing broad .NET commands. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt.",
159
+ description: "Start a canonical Forge .NET verification profile with runner-owned cwd, arguments, attempt output, timeout, and process supervision. Prefer this over reconstructing broad .NET commands. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt. To run every shard of a tier in one call, set run_all_shards: true with shard_count 2 or more and without no_build.",
151
160
  inputSchema: {
152
161
  type: "object",
153
162
  additionalProperties: false,
@@ -155,13 +164,14 @@ export function managedAttemptToolDefinition(name) {
155
164
  properties: {
156
165
  profile: {
157
166
  type: "string",
158
- enum: ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"],
167
+ enum: [...managedVerificationProfiles],
168
+ description: "Required .NET test profile. dotnet_affected selects its own tests and owns its build: it takes no shard or no_build options. dotnet_solution takes no shard options. Client, bridge, and e2e checks are not profiles; use forge.start_managed_command for them.",
159
169
  },
160
- shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1 },
161
- shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0 },
162
- run_all_shards: { type: "boolean", default: false },
170
+ shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1, description: "Number of shards to split the tier into. Must be at least 2 when run_all_shards is true." },
171
+ shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0, description: "Which single shard to run; must be less than shard_count, and 0 when run_all_shards is true." },
172
+ run_all_shards: { type: "boolean", default: false, description: "Run every shard of the tier after one shared build. Requires shard_count of at least 2 and shard_index 0, cannot be combined with no_build, and is not supported for dotnet_solution or dotnet_affected." },
163
173
  max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
164
- no_build: { type: "boolean", default: false },
174
+ no_build: { type: "boolean", default: false, description: "Reuse the verified build from an earlier managed build instead of building. Not allowed with run_all_shards or dotnet_affected." },
165
175
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
166
176
  },
167
177
  },
@@ -178,8 +188,8 @@ export function managedAttemptToolDefinition(name) {
178
188
  additionalProperties: false,
179
189
  required: ["command", "args"],
180
190
  properties: {
181
- command: { type: "string", minLength: 1 },
182
- 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." },
183
193
  cwd: { type: "string", description: "Worktree-relative directory; defaults to the worktree root." },
184
194
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 2700000 },
185
195
  },
@@ -342,13 +352,13 @@ async function startManagedVerification(input, worktreePath) {
342
352
  const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
343
353
  const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
344
354
  if (runAllShards && shardCount < 2) {
345
- throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 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.");
346
356
  }
347
357
  if (runAllShards && shardIndex !== 0) {
348
358
  throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
349
359
  }
350
360
  if (runAllShards && noBuild) {
351
- throw new Error("managed_verification_invalid: run_all_shards owns the single prerequisite build and cannot be combined with no_build.");
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.");
352
362
  }
353
363
  const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
354
364
  const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
@@ -405,7 +415,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
405
415
  };
406
416
  const tier = tiers[profile];
407
417
  if (!tier)
408
- throw new Error(`managed_verification_invalid: unsupported profile ${profile}.`);
418
+ throw new Error(`managed_verification_invalid: unsupported profile ${profile}. ${managedVerificationProfileHint}`);
409
419
  const command = preferredPowerShellExecutable();
410
420
  if (runAllShards) {
411
421
  return {
@@ -434,7 +444,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
434
444
  export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
435
445
  if (platform !== "win32")
436
446
  return "pwsh";
437
- return resolveWindowsCommandFromPath("pwsh.exe", pathValue) ?? "powershell.exe";
447
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
438
448
  }
439
449
  export function validatePlaywrightProjectName(project, availableProjects) {
440
450
  if (!availableProjects.includes(project)) {
@@ -488,15 +498,66 @@ function optionValue(args, name) {
488
498
  const index = args.indexOf(name);
489
499
  return index >= 0 ? args[index + 1]?.trim() || null : null;
490
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;
507
+ }
491
508
  async function executeManagedCommand(invocation) {
492
- if (!invocation.buildProducing)
493
- return await executeManagedCommandProcess(invocation);
494
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
+ }));
495
557
  try {
496
- return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => {
497
- processStarted = true;
498
- return await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs });
499
- }, async () => {
558
+ if (!invocation.buildProducing)
559
+ return await launch();
560
+ return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, launch, async () => {
500
561
  const waiting = managedCommandResult({
501
562
  ...invocation,
502
563
  timedOut: false,
@@ -512,11 +573,12 @@ async function executeManagedCommand(invocation) {
512
573
  catch (error) {
513
574
  if (processStarted)
514
575
  throw error;
515
- // The command never started (its build-slot wait failed or was stopped). Its receipt
516
- // must still become terminal, or a waiting agent sees it queued forever.
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.
517
578
  const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
518
579
  const receipt = managedCommandResult({
519
580
  ...invocation,
581
+ hostLoad: await hostCapacity.unadmittedFields(error),
520
582
  timedOut: false,
521
583
  status: "runner_error",
522
584
  exitCode: null,
@@ -529,41 +591,48 @@ async function executeManagedCommand(invocation) {
529
591
  return managedCommandPublicResult(receipt);
530
592
  }
531
593
  }
594
+ /** A command's environment and redaction list; a setup that throws releases the database it started. */
532
595
  async function managedCommandProcessEnvironment(invocation) {
533
596
  assertHostDatabaseCapabilityBoundary();
534
- const databaseEnvironment = invocation.verificationProfile
535
- ? await managedVerificationDatabaseEnvironment()
536
- : {};
537
- const exactSecrets = [
538
- ...Object.values(databaseEnvironment).filter(value => value !== nativeTestPostgresFallbackDatabaseMode),
539
- // The attempt's brokered database login reaches managed commands; their output never shows it.
540
- ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
541
- ];
542
- const environment = inheritedEnvironment({
543
- FORGE_RUNTIME_MODE: "host",
544
- FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
545
- FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
546
- // This nested command owns a distinct supervisor identity. A command-local
547
- // fence avoids exposing the parent attempt's fencing capability to Codex's
548
- // MCP subprocess configuration while preserving exact-tree cleanup proof.
549
- FORGE_FENCING_TOKEN: randomUUID(),
550
- FORGE_LOG_DIR: invocation.logDirectory,
551
- FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
552
- FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
553
- FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
554
- ...(invocation.verificationProfile
555
- ? {
556
- FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
557
- // Managed verification executes mutable worktree scripts, SDK targets,
558
- // and test assemblies. It uses an attempt-owned container, or the
559
- // dedicated native test cluster while Docker is unavailable; it never
560
- // receives a capability for a server that holds real data.
561
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
562
- ...databaseEnvironment,
563
- }
564
- : {}),
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 };
565
629
  });
566
- return { environment, exactSecrets };
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);
567
636
  }
568
637
  async function executeManagedCommandProcess(invocation) {
569
638
  let prepared;
@@ -642,6 +711,8 @@ async function executeManagedCommandProcess(invocation) {
642
711
  }, {
643
712
  onStarted: async () => {
644
713
  clearTimeout(launchTimer);
714
+ // onProcessStarted stops the command itself when its token cannot be held.
715
+ await invocation.onProcessStarted?.();
645
716
  const running = managedCommandResult({
646
717
  ...invocation,
647
718
  timedOut: false,
@@ -688,13 +759,17 @@ async function executeManagedCommandProcess(invocation) {
688
759
  // Only a stop that interrupted the process relabels it. A command that exited on its own
689
760
  // just before its owner asked for the stop keeps its real result.
690
761
  const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
691
- if (ownerExited) {
692
- stderr = appendBounded(stderr, managedCommandOwnerExitMessage);
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);
693
768
  outputRevision += 1;
694
769
  lastOutputAt = Date.now();
695
770
  lastOutputStream = "stderr";
696
771
  }
697
- const status = timedOut ? "timed_out" : ownerExited ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
772
+ const status = timedOut ? "timed_out" : ownerExited || fenced ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
698
773
  const receiptCoverage = managedBuildReceiptCoverage(invocation);
699
774
  const buildReceipt = status === "pass" && receiptCoverage
700
775
  ? await publishManagedBuildReceipt({
@@ -717,9 +792,9 @@ async function executeManagedCommandProcess(invocation) {
717
792
  lastOutputStream,
718
793
  buildReceipt,
719
794
  buildReceiptReused: invocation.buildReceiptReuse !== undefined,
720
- terminationReason: ownerExited ? "owner_exited" : undefined,
795
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLoss ?? undefined,
721
796
  // The runner resolves only after the stopped tree is proven gone.
722
- processTreeTerminated: ownerExited ? true : undefined,
797
+ processTreeTerminated: ownerExited || fenced ? true : undefined,
723
798
  });
724
799
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
725
800
  return managedCommandPublicResult(receipt);
@@ -745,19 +820,23 @@ async function executeManagedCommandProcess(invocation) {
745
820
  outputRevision,
746
821
  lastOutputAt,
747
822
  lastOutputStream,
748
- terminationReason: ownerExited ? "owner_exited" : undefined,
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,
749
825
  // The runner rejected, so its tree was not proven stopped; teardown still stops it.
750
826
  processTreeTerminated: false,
751
827
  });
752
828
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
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
+ }
753
834
  return managedCommandPublicResult(receipt);
754
835
  }
755
836
  finally {
756
- clearTimeout(launchTimer);
757
- if (timer)
758
- clearTimeout(timer);
759
- if (progressHeartbeat)
760
- clearInterval(progressHeartbeat);
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) }));
761
840
  }
762
841
  }
763
842
  async function readManagedCommand(input) {
@@ -773,6 +852,11 @@ async function readManagedCommand(input) {
773
852
  }
774
853
  throw error;
775
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
+ }
776
860
  const status = typeof receipt.status === "string" ? receipt.status : "unknown";
777
861
  const stdout = typeof receipt.stdout === "string" ? receipt.stdout : "";
778
862
  const stderr = typeof receipt.stderr === "string" ? receipt.stderr : "";
@@ -823,15 +907,18 @@ async function waitManagedCommand(input) {
823
907
  const elapsedMs = receipt.structuredContent.elapsed_ms;
824
908
  const timeoutMs = receipt.structuredContent.timeout_ms;
825
909
  const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
826
- const progress = receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
827
- ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
828
- + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
829
- + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
830
- // Agents otherwise abandon long verification tiers and record a blocker that is not one.
831
- + (typeof timeoutMs === "number"
832
- ? ` 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.`
833
- : "")
834
- : "";
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
+ : "";
835
922
  return {
836
923
  ...receipt,
837
924
  content: [{
@@ -853,30 +940,12 @@ function managedCommandReceiptPath(logDirectory, commandId) {
853
940
  return path.join(logDirectory, "managed-commands", `${commandId}.receipt.json`);
854
941
  }
855
942
  async function persistManagedCommandReceipt(receiptPath, receipt) {
856
- const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
857
- await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
858
- try {
859
- for (let attempt = 1;; attempt += 1) {
860
- try {
861
- await fs.rename(temporaryPath, receiptPath);
862
- break;
863
- }
864
- catch (error) {
865
- const code = error.code;
866
- if (attempt >= managedCommandReceiptReplaceAttempts
867
- || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES")) {
868
- throw error;
869
- }
870
- await delay(managedCommandReceiptReplaceRetryMs);
871
- }
872
- }
873
- }
874
- finally {
875
- await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
876
- }
943
+ await persistJsonAtomically(receiptPath, receipt);
877
944
  }
878
945
  function managedCommandResult(values) {
879
- 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);
880
949
  const isTerminal = terminalManagedCommandStatuses.has(values.status);
881
950
  const diagnostics = isTerminal
882
951
  ? managedCommandDiagnostics(values.stdout, values.stderr)
@@ -921,6 +990,7 @@ function managedCommandResult(values) {
921
990
  build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
922
991
  build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
923
992
  build_receipt_reused: values.buildReceiptReused ?? false,
993
+ ...(hostLoad ? managedCommandHostLoadReceipt(hostLoad) : {}),
924
994
  build_receipt: values.buildReceipt ? {
925
995
  fingerprint: values.buildReceipt.fingerprint,
926
996
  receipt_path: values.buildReceipt.receiptPath,
@@ -940,6 +1010,18 @@ function managedCommandResult(values) {
940
1010
  isError: isTerminal && values.status !== "pass",
941
1011
  };
942
1012
  }
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
+ }
943
1025
  /** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
944
1026
  function managedCommandOwnerIdentity() {
945
1027
  // Windows identity capture starts PowerShell; the PID check alone is used there.
@@ -1015,26 +1097,15 @@ async function containedWorkingDirectory(worktreePath, input) {
1015
1097
  }
1016
1098
  function inheritedEnvironment(overrides) {
1017
1099
  const env = {};
1018
- 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))) {
1019
1104
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
1020
1105
  env[key] = value;
1021
1106
  }
1022
1107
  return { ...env, ...overrides };
1023
1108
  }
1024
- /**
1025
- * Runner-authored verification normally uses its attempt-owned Testcontainers
1026
- * database. Only when the Docker engine is unavailable does it switch to the
1027
- * operator-provisioned native test cluster, which holds no real data.
1028
- */
1029
- export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().refresh(true)).available, readFallback = () => {
1030
- const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
1031
- return configPath ? readNativeTestPostgresFallback(configPath) : null;
1032
- }) {
1033
- const fallback = readFallback();
1034
- if (!fallback || await dockerAvailable())
1035
- return {};
1036
- return nativeTestPostgresFallbackEnvironment(fallback);
1037
- }
1038
1109
  export function isBuildProducingManagedCommand(command, args) {
1039
1110
  const executable = path.basename(command).toLowerCase();
1040
1111
  if (executable === "dotnet" || executable === "dotnet.exe") {
@@ -1104,8 +1175,17 @@ function asRecord(value) {
1104
1175
  throw new Error("managed_command_invalid: input must be an object.");
1105
1176
  return value;
1106
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
+ };
1107
1183
  function requiredInputString(record, name) {
1108
- 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(" ")}` : ""}`);
1109
1189
  }
1110
1190
  function validatedCommandId(record) {
1111
1191
  const commandId = requiredInputString(record, "command_id");
@@ -1122,7 +1202,13 @@ function requiredStandaloneString(value, name) {
1122
1202
  function requiredStringArray(record, name) {
1123
1203
  const value = record[name];
1124
1204
  if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) {
1125
- 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}`);
1126
1212
  }
1127
1213
  return value;
1128
1214
  }
@@ -19,3 +19,8 @@ export declare function verifyManagedBuildReceipt(options: {
19
19
  readonly requiredCoverage: string;
20
20
  }): Promise<ManagedBuildReceiptEvidence>;
21
21
  export declare function managedBuildConfiguration(command: string, args: readonly string[]): string;
22
+ /**
23
+ * Writes a JSON receipt by replacing the whole file. Agents and Forge poll receipts, and on
24
+ * Windows a poll that has one open refuses the replace: that delays a write, never fails it.
25
+ */
26
+ export declare function persistJsonAtomically(receiptPath: string, value: unknown): Promise<void>;
@@ -3,6 +3,7 @@ import { spawn } from "node:child_process";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
6
+ import { replaceFile } from "../shared/fs/replace-file.js";
6
7
  const schemaVersion = 1;
7
8
  const maximumRetainedReceipts = 8;
8
9
  const maximumOutputManifestEntries = 20_000;
@@ -262,7 +263,7 @@ async function persistImmutableReceipt(receiptPath, receipt) {
262
263
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
263
264
  await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
264
265
  try {
265
- await fs.rename(temporaryPath, receiptPath).catch(async (error) => {
266
+ await replaceFile(temporaryPath, receiptPath).catch(async (error) => {
266
267
  if (error.code !== "EEXIST")
267
268
  throw error;
268
269
  });
@@ -271,11 +272,15 @@ async function persistImmutableReceipt(receiptPath, receipt) {
271
272
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
272
273
  }
273
274
  }
274
- async function persistJsonAtomically(receiptPath, value) {
275
+ /**
276
+ * Writes a JSON receipt by replacing the whole file. Agents and Forge poll receipts, and on
277
+ * Windows a poll that has one open refuses the replace: that delays a write, never fails it.
278
+ */
279
+ export async function persistJsonAtomically(receiptPath, value) {
275
280
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
276
281
  await fs.writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
277
282
  try {
278
- await fs.rename(temporaryPath, receiptPath);
283
+ await replaceFile(temporaryPath, receiptPath);
279
284
  }
280
285
  finally {
281
286
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
@@ -0,0 +1,47 @@
1
+ import { type HostLoadStepGate } from "../runtime/host-load-governor.js";
2
+ import { type HostLoadStepClassification, type ManagedCommandStepInput } from "../runtime/host-load-step-class.js";
3
+ import { type HostLoadStepControl } from "../runtime/host-load-step-run.js";
4
+ /** Host-load facts a managed command receipt carries; absent while the governor is off. */
5
+ export interface ManagedCommandHostLoadFields {
6
+ readonly stepClass: string;
7
+ /** Queue time before admission; never part of elapsed_ms. */
8
+ readonly waitMs: number;
9
+ /** Set while the command is still queued: the receipt reports the wait so far. */
10
+ readonly waitStartedAt?: number;
11
+ /** Why it waits, for example for the host test slot and who holds it (decision 0018). */
12
+ readonly waitDetail?: string;
13
+ /** When the command was admitted; elapsed_ms counts from here. */
14
+ readonly executionStartedAt?: number;
15
+ }
16
+ /** This MCP server's governor, built once from the environment the bridge handed it. */
17
+ export declare function managedCommandHostLoadGate(): HostLoadStepGate | undefined;
18
+ /** Test support: installs a gate (undefined disables it; null rebuilds from the environment). */
19
+ export declare function setManagedCommandHostLoadGateForTesting(value: HostLoadStepGate | undefined | null): void;
20
+ /**
21
+ * Admits one managed command. The waiting receipt is written while the command
22
+ * is queued and always lands before the launch receipts, so a stale "waiting"
23
+ * write can never replace a later status.
24
+ */
25
+ export declare class ManagedCommandHostCapacity {
26
+ private readonly persistWaiting;
27
+ private readonly gateFor;
28
+ readonly classification: HostLoadStepClassification;
29
+ private readonly label;
30
+ private requestedAtMs;
31
+ private waitingWrite;
32
+ constructor(input: ManagedCommandStepInput & {
33
+ readonly label: string;
34
+ }, persistWaiting: (fields: ManagedCommandHostLoadFields) => Promise<void>, gateFor?: () => HostLoadStepGate | undefined);
35
+ /** Runs `launch` once admitted; `fields` is undefined with the governor off. */
36
+ run<T>(signal: AbortSignal, launch: (fields: ManagedCommandHostLoadFields | undefined, control: HostLoadStepControl) => Promise<T>, onReleaseFailed?: (error: unknown) => Promise<void>): Promise<T>;
37
+ /**
38
+ * Host-load facts for a command that was never admitted (it timed out in
39
+ * the queue or was stopped while waiting), once its waiting receipt landed.
40
+ */
41
+ unadmittedFields(error: unknown): Promise<ManagedCommandHostLoadFields | undefined>;
42
+ }
43
+ /**
44
+ * The managed command's process tree as its supervisor recorded it, for its
45
+ * host load token: a reclaim then stops exactly this tree before reuse.
46
+ */
47
+ export declare function attachManagedCommandProcess(control: HostLoadStepControl, metadataPath: string): Promise<void>;