@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.c03d3c89ec4a

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 (174) hide show
  1. package/README.md +45 -3
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +84 -2
  4. package/dist/bridge/bridge.service.js +358 -12
  5. package/dist/bridge/bridge.types.d.ts +22 -0
  6. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  7. package/dist/bridge/dispatch-result-outbox.js +31 -6
  8. package/dist/bridge/local-yield-flag.d.ts +6 -0
  9. package/dist/bridge/local-yield-flag.js +34 -0
  10. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  11. package/dist/bridge/runner-host-capabilities.js +4 -0
  12. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  13. package/dist/bridge/test-postgres-capability.js +120 -0
  14. package/dist/cleanup/cleanup.service.d.ts +9 -0
  15. package/dist/cleanup/cleanup.service.js +72 -109
  16. package/dist/cleanup/cleanup.types.d.ts +4 -0
  17. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  18. package/dist/cleanup/forge-owned-paths.js +53 -0
  19. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  20. package/dist/cleanup/host-runtime-ledger.js +109 -0
  21. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  22. package/dist/cleanup/managed-branch-sweep.js +111 -0
  23. package/dist/cli/cli.help.js +20 -2
  24. package/dist/cli/cli.service.d.ts +16 -0
  25. package/dist/cli/cli.service.js +142 -16
  26. package/dist/cli/local-config.d.ts +4 -0
  27. package/dist/cli/local-config.js +26 -4
  28. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  29. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  30. package/dist/runtime/attempt-database-broker.js +390 -0
  31. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  32. package/dist/runtime/attempt-process-supervisor.js +77 -3
  33. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  34. package/dist/runtime/host-database-capability-boundary.js +1 -0
  35. package/dist/runtime/host-diagnostics.js +4 -3
  36. package/dist/runtime/host-facts.d.ts +35 -0
  37. package/dist/runtime/host-facts.js +95 -0
  38. package/dist/runtime/host-load-admission.d.ts +60 -0
  39. package/dist/runtime/host-load-admission.js +99 -0
  40. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  41. package/dist/runtime/host-load-child-environment.js +67 -0
  42. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  43. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  44. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  45. package/dist/runtime/host-load-governor-config.js +76 -0
  46. package/dist/runtime/host-load-governor.d.ts +174 -0
  47. package/dist/runtime/host-load-governor.js +541 -0
  48. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  49. package/dist/runtime/host-load-ledger-lock.js +185 -0
  50. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  51. package/dist/runtime/host-load-runtime-settings.js +78 -0
  52. package/dist/runtime/host-load-sampler.d.ts +126 -0
  53. package/dist/runtime/host-load-sampler.js +232 -0
  54. package/dist/runtime/host-load-step-class.d.ts +68 -0
  55. package/dist/runtime/host-load-step-class.js +106 -0
  56. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  57. package/dist/runtime/host-load-step-reaper.js +95 -0
  58. package/dist/runtime/host-load-step-run.d.ts +73 -0
  59. package/dist/runtime/host-load-step-run.js +102 -0
  60. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  61. package/dist/runtime/host-load-token-ledger.js +421 -0
  62. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  63. package/dist/runtime/host-pressure-stall.js +168 -0
  64. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  65. package/dist/runtime/host-runtime-contract.js +75 -11
  66. package/dist/runtime/host-runtime-lease.d.ts +76 -4
  67. package/dist/runtime/host-runtime-lease.js +386 -32
  68. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  69. package/dist/runtime/host-runtime-promotion.js +48 -0
  70. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  71. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  72. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  73. package/dist/runtime/host-runtime-requirements.js +117 -0
  74. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  75. package/dist/runtime/managed-command-teardown.js +607 -0
  76. package/dist/runtime/node-host-runtime-adapter.js +5 -4
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  81. package/dist/runtime/runner-settings.d.ts +100 -0
  82. package/dist/runtime/runner-settings.js +214 -0
  83. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  84. package/dist/sandbox/host-capacity-broker.js +315 -0
  85. package/dist/sandbox/repository-lock.js +3 -2
  86. package/dist/sandbox/runtime.d.ts +10 -1
  87. package/dist/sandbox/runtime.js +50 -6
  88. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  89. package/dist/sandbox/sandbox-cgroups.js +42 -0
  90. package/dist/session/managed-attempt-tools.d.ts +27 -0
  91. package/dist/session/managed-attempt-tools.js +366 -45
  92. package/dist/session/managed-build-coordinator.d.ts +1 -1
  93. package/dist/session/managed-build-coordinator.js +8 -4
  94. package/dist/session/managed-command-host-load.d.ts +45 -0
  95. package/dist/session/managed-command-host-load.js +82 -0
  96. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  97. package/dist/session/mcp-argument-coercion.js +121 -0
  98. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  99. package/dist/session/phase-completion.artifacts.js +98 -25
  100. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  101. package/dist/session/phase-completion.command-validation.js +77 -0
  102. package/dist/session/phase-completion.d.ts +4 -0
  103. package/dist/session/phase-completion.helpers.js +13 -12
  104. package/dist/session/phase-completion.js +4 -0
  105. package/dist/session/phase-completion.prompts.js +6 -1
  106. package/dist/session/phase-completion.runtime.d.ts +5 -3
  107. package/dist/session/phase-completion.runtime.js +78 -36
  108. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  109. package/dist/session/phase-completion.schema-parts.js +188 -0
  110. package/dist/session/phase-completion.schemas.d.ts +3 -3
  111. package/dist/session/phase-completion.schemas.js +206 -221
  112. package/dist/session/phase-completion.validation.d.ts +2 -3
  113. package/dist/session/phase-completion.validation.js +46 -92
  114. package/dist/session/pre-publication-host-load.d.ts +27 -0
  115. package/dist/session/pre-publication-host-load.js +111 -0
  116. package/dist/session/pre-publication-pass.d.ts +60 -0
  117. package/dist/session/pre-publication-pass.js +145 -0
  118. package/dist/session/pre-publication-process.d.ts +23 -0
  119. package/dist/session/pre-publication-process.js +109 -0
  120. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  121. package/dist/session/pre-publication-skipped-tests.js +109 -0
  122. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  123. package/dist/session/pre-publication-step-execution.js +49 -0
  124. package/dist/session/pre-publication-validation.d.ts +30 -20
  125. package/dist/session/pre-publication-validation.js +178 -193
  126. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  127. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  128. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  129. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  130. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  131. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  132. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  133. package/dist/session/provider-cli/provider-cli.process.js +299 -25
  134. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  135. package/dist/session/provider-cli/provider-cli.prompts.js +62 -9
  136. package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
  137. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  138. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  139. package/dist/session/provider-cli/provider-cli.service.js +200 -162
  140. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  141. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  143. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  144. package/dist/session/provider-cli/provider-output-state.js +9 -0
  145. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  146. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  147. package/dist/session/publishable-worktree-changes.js +193 -0
  148. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  149. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  150. package/dist/session/session.base.d.ts +9 -1
  151. package/dist/session/session.service.d.ts +9 -2
  152. package/dist/session/session.service.js +120 -5
  153. package/dist/session/session.types.d.ts +3 -0
  154. package/dist/session/session.types.js +15 -3
  155. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  156. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  157. package/dist/shared/process/host-process-recovery.js +3 -2
  158. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  159. package/dist/shared/process/host-process-supervisor.js +6 -5
  160. package/dist/shared/process/process-tree.d.ts +52 -0
  161. package/dist/shared/process/process-tree.js +144 -0
  162. package/dist/shared/process/process.d.ts +67 -0
  163. package/dist/shared/process/process.js +213 -11
  164. package/dist/shared/provider-capabilities.js +5 -6
  165. package/dist/shared/time/monotonic.d.ts +1 -0
  166. package/dist/shared/time/monotonic.js +8 -0
  167. package/dist/version.d.ts +1 -1
  168. package/dist/version.js +1 -1
  169. package/dist/worktree/dependency-warmer.d.ts +25 -0
  170. package/dist/worktree/dependency-warmer.js +120 -10
  171. package/dist/worktree/worktree.service.d.ts +10 -1
  172. package/dist/worktree/worktree.service.js +42 -2
  173. package/dist/worktree/worktree.types.d.ts +7 -0
  174. package/package.json +2 -2
@@ -1,15 +1,25 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
5
6
  import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
7
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
6
8
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
7
9
  import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
8
10
  import { redactText } from "../shared/redaction/redaction.js";
11
+ import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
9
12
  import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
13
+ import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
14
+ import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
15
+ import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
16
+ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
17
+ import { hostLoadGovernorEnvironment, hostLoadStateRootEnvironment } from "../runtime/host-load-child-environment.js";
10
18
  import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
11
19
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
12
20
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
21
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
22
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
13
23
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
14
24
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
15
25
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
@@ -39,6 +49,14 @@ const terminalManagedCommandStatuses = new Set([
39
49
  ]);
40
50
  const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
41
51
  const managedCommandTasks = new Map();
52
+ // Every command this MCP server is supervising, synchronous or not. The server is the only
53
+ // writer of their receipts, so it stops them before it exits.
54
+ const activeManagedCommands = new Map();
55
+ const ownerExitStoppedCommands = new Set();
56
+ let ownerProcessIdentity;
57
+ let managedCommandOwnerShuttingDown = false;
58
+ let ownerExitSweep = null;
59
+ const managedCommandOwnerExitMessage = "managed_command_owner_exited: Forge stopped this managed command because the Forge MCP server that supervised it is exiting; its provider process ended before the command finished. Its result is unknown; start it again if it is still needed.";
42
60
  export const managedAttemptToolNames = [
43
61
  "forge.run_managed_command",
44
62
  "run_managed_command",
@@ -53,6 +71,76 @@ export const managedAttemptToolNames = [
53
71
  "forge.reset_generated_outputs",
54
72
  "reset_generated_outputs",
55
73
  ];
74
+ /**
75
+ * Stops every managed command this MCP server started, proves each process tree stopped,
76
+ * and writes their terminal receipts. Called when the provider closes the MCP connection
77
+ * or the server is signalled: once this server exits nothing could supervise them.
78
+ */
79
+ export async function stopManagedCommandsForOwnerExit() {
80
+ // One sweep at a time: a signal that arrives while a sweep runs waits for that sweep.
81
+ ownerExitSweep ??= sweepManagedCommandsForOwnerExit().finally(() => { ownerExitSweep = null; });
82
+ await ownerExitSweep;
83
+ }
84
+ async function sweepManagedCommandsForOwnerExit() {
85
+ // From here on this server refuses new commands, so a request still being handled
86
+ // cannot launch one behind the sweep. Repeat until none is left: a launch that passed
87
+ // its last check just before the flag was set registers synchronously and is caught.
88
+ managedCommandOwnerShuttingDown = true;
89
+ while (activeManagedCommands.size > 0) {
90
+ const active = [...activeManagedCommands.entries()];
91
+ for (const [commandId, command] of active) {
92
+ ownerExitStoppedCommands.add(commandId);
93
+ command.controller.abort(new Error(managedCommandOwnerExitMessage));
94
+ }
95
+ await Promise.allSettled(active.map(([, command]) => command.task));
96
+ }
97
+ }
98
+ /** Test support: lets one test process act as a fresh MCP server after a simulated exit. */
99
+ export function resetManagedCommandOwnerShutdownForTesting() {
100
+ managedCommandOwnerShuttingDown = false;
101
+ }
102
+ function assertManagedCommandsAccepted() {
103
+ if (managedCommandOwnerShuttingDown) {
104
+ throw new Error("managed_command_unavailable: the Forge MCP server is shutting down and accepts no new managed commands.");
105
+ }
106
+ }
107
+ const ownerShutdownSignals = ["SIGTERM", "SIGHUP", "SIGINT"];
108
+ /**
109
+ * Makes a termination signal stop this server's managed commands before it exits, so none
110
+ * outlives its only supervisor. Returns a function that removes the handlers.
111
+ */
112
+ export function installOwnerShutdownHandlers(target = process, exit = code => process.exit(code)) {
113
+ const handlers = ownerShutdownSignals.map(signal => {
114
+ const handler = () => {
115
+ void stopManagedCommandsForOwnerExit().finally(() => exit(128 + os.constants.signals[signal]));
116
+ };
117
+ target.once(signal, handler);
118
+ return { signal, handler };
119
+ });
120
+ return () => {
121
+ for (const { signal, handler } of handlers)
122
+ target.removeListener(signal, handler);
123
+ };
124
+ }
125
+ /**
126
+ * Runs an MCP server body, then stops every managed command it started before returning.
127
+ * The signal handlers stay installed until that stop completes: a signal during the body
128
+ * or the stop exits only after the same stop finishes, never by Node's default exit.
129
+ */
130
+ export async function runWithOwnerShutdown(body, target = process, exit = code => process.exit(code)) {
131
+ const removeShutdownHandlers = installOwnerShutdownHandlers(target, exit);
132
+ try {
133
+ return await body();
134
+ }
135
+ finally {
136
+ try {
137
+ await stopManagedCommandsForOwnerExit();
138
+ }
139
+ finally {
140
+ removeShutdownHandlers();
141
+ }
142
+ }
143
+ }
56
144
  export function isManagedAttemptTool(name) {
57
145
  return managedCommandNames.has(name)
58
146
  || startManagedCommandNames.has(name)
@@ -61,11 +149,17 @@ export function isManagedAttemptTool(name) {
61
149
  || startManagedVerificationNames.has(name)
62
150
  || resetGeneratedOutputNames.has(name);
63
151
  }
152
+ const managedVerificationProfiles = ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"];
153
+ const managedVerificationProfileHint = `Use one of: ${managedVerificationProfiles.join(", ")}. These are .NET test profiles only; run client, bridge, or Playwright e2e checks with forge.start_managed_command.`;
154
+ /** The input schema a managed-attempt tool advertises; also the shape its arguments are coerced to. */
155
+ export function managedAttemptToolInputSchema(name) {
156
+ return managedAttemptToolDefinition(name).inputSchema;
157
+ }
64
158
  export function managedAttemptToolDefinition(name) {
65
159
  if (startManagedVerificationNames.has(name)) {
66
160
  return {
67
161
  name,
68
- 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.",
162
+ description: "Start a canonical Forge .NET verification profile with runner-owned cwd, arguments, attempt output, timeout, and process supervision. Prefer this over reconstructing broad .NET commands. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt. To run every shard of a tier in one call, set run_all_shards: true with shard_count 2 or more and without no_build.",
69
163
  inputSchema: {
70
164
  type: "object",
71
165
  additionalProperties: false,
@@ -73,13 +167,14 @@ export function managedAttemptToolDefinition(name) {
73
167
  properties: {
74
168
  profile: {
75
169
  type: "string",
76
- enum: ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"],
170
+ enum: [...managedVerificationProfiles],
171
+ description: "Required .NET test profile. dotnet_affected selects its own tests and owns its build: it takes no shard or no_build options. dotnet_solution takes no shard options. Client, bridge, and e2e checks are not profiles; use forge.start_managed_command for them.",
77
172
  },
78
- shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1 },
79
- shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0 },
80
- run_all_shards: { type: "boolean", default: false },
173
+ shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1, description: "Number of shards to split the tier into. Must be at least 2 when run_all_shards is true." },
174
+ shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0, description: "Which single shard to run; must be less than shard_count, and 0 when run_all_shards is true." },
175
+ run_all_shards: { type: "boolean", default: false, description: "Run every shard of the tier after one shared build. Requires shard_count of at least 2 and shard_index 0, cannot be combined with no_build, and is not supported for dotnet_solution or dotnet_affected." },
81
176
  max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
82
- no_build: { type: "boolean", default: false },
177
+ no_build: { type: "boolean", default: false, description: "Reuse the verified build from an earlier managed build instead of building. Not allowed with run_all_shards or dotnet_affected." },
83
178
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
84
179
  },
85
180
  },
@@ -96,8 +191,8 @@ export function managedAttemptToolDefinition(name) {
96
191
  additionalProperties: false,
97
192
  required: ["command", "args"],
98
193
  properties: {
99
- command: { type: "string", minLength: 1 },
100
- args: { type: "array", items: { type: "string" } },
194
+ command: { type: "string", minLength: 1, description: "Required executable only, for example pnpm, node, npm, or dotnet. Not a shell command line: shell syntax such as cd, &&, or pipes is not interpreted." },
195
+ args: { type: "array", items: { type: "string" }, description: "Required argument list, each argument its own string, for example [\"--dir\", \"client\", \"lint\"]. Send [] when there are none. Use cwd instead of cd." },
101
196
  cwd: { type: "string", description: "Worktree-relative directory; defaults to the worktree root." },
102
197
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 2700000 },
103
198
  },
@@ -173,6 +268,7 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
173
268
  return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
174
269
  }
175
270
  async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
271
+ assertManagedCommandsAccepted();
176
272
  const command = requiredInputString(record, "command");
177
273
  const args = requiredStringArray(record, "args");
178
274
  const timeoutMs = optionalTimeout(record.timeout_ms);
@@ -197,6 +293,7 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
197
293
  worktreePath,
198
294
  buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
199
295
  buildReceiptReuse,
296
+ controller: new AbortController(),
200
297
  };
201
298
  if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
202
299
  const started = managedCommandResult({
@@ -206,9 +303,25 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
206
303
  exitCode: null,
207
304
  stdout: "",
208
305
  stderr: "",
306
+ launchRequested: false,
209
307
  });
210
308
  await persistManagedCommandReceipt(receiptPath, started.structuredContent);
211
- const task = executeManagedCommand(invocation);
309
+ if (managedCommandOwnerShuttingDown) {
310
+ // Shutdown began while the receipt was written; the command never starts.
311
+ const refused = managedCommandResult({
312
+ ...invocation,
313
+ timedOut: false,
314
+ status: "runner_error",
315
+ exitCode: null,
316
+ stdout: "",
317
+ stderr: appendBounded("", managedCommandOwnerExitMessage),
318
+ launchRequested: false,
319
+ terminationReason: "owner_exited",
320
+ });
321
+ await persistManagedCommandReceipt(receiptPath, refused.structuredContent);
322
+ assertManagedCommandsAccepted();
323
+ }
324
+ const task = trackManagedCommand(invocation);
212
325
  managedCommandTasks.set(commandId, task);
213
326
  void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
214
327
  return {
@@ -219,7 +332,16 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
219
332
  }],
220
333
  };
221
334
  }
222
- return await executeManagedCommand(invocation);
335
+ return await trackManagedCommand(invocation);
336
+ }
337
+ function trackManagedCommand(invocation) {
338
+ const task = executeManagedCommand(invocation);
339
+ activeManagedCommands.set(invocation.commandId, { controller: invocation.controller, task });
340
+ void task.finally(() => {
341
+ activeManagedCommands.delete(invocation.commandId);
342
+ ownerExitStoppedCommands.delete(invocation.commandId);
343
+ }).catch(() => undefined);
344
+ return task;
223
345
  }
224
346
  async function startManagedVerification(input, worktreePath) {
225
347
  const record = asRecord(input);
@@ -233,13 +355,13 @@ async function startManagedVerification(input, worktreePath) {
233
355
  const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
234
356
  const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
235
357
  if (runAllShards && shardCount < 2) {
236
- throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 2.");
358
+ throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 2. Set shard_count to 2 or more to run every shard, or omit run_all_shards to run a single shard.");
237
359
  }
238
360
  if (runAllShards && shardIndex !== 0) {
239
361
  throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
240
362
  }
241
363
  if (runAllShards && noBuild) {
242
- throw new Error("managed_verification_invalid: run_all_shards owns the single prerequisite build and cannot be combined with no_build.");
364
+ throw new Error("managed_verification_invalid: run_all_shards owns the single prerequisite build and cannot be combined with no_build. Omit no_build when run_all_shards is true.");
243
365
  }
244
366
  const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
245
367
  const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
@@ -296,7 +418,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
296
418
  };
297
419
  const tier = tiers[profile];
298
420
  if (!tier)
299
- throw new Error(`managed_verification_invalid: unsupported profile ${profile}.`);
421
+ throw new Error(`managed_verification_invalid: unsupported profile ${profile}. ${managedVerificationProfileHint}`);
300
422
  const command = preferredPowerShellExecutable();
301
423
  if (runAllShards) {
302
424
  return {
@@ -379,28 +501,109 @@ function optionValue(args, name) {
379
501
  const index = args.indexOf(name);
380
502
  return index >= 0 ? args[index + 1]?.trim() || null : null;
381
503
  }
504
+ function hostCapacityLossReason(reason) {
505
+ if (reason instanceof HostCapacityTokenFencedError)
506
+ return "host_capacity_token_fenced";
507
+ if (reason instanceof HostCapacityLedgerUnavailableError)
508
+ return "host_capacity_ledger_unavailable";
509
+ return null;
510
+ }
382
511
  async function executeManagedCommand(invocation) {
383
- if (!invocation.buildProducing)
384
- return await executeManagedCommandProcess(invocation);
385
- return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs }), async () => {
386
- const waiting = managedCommandResult({
512
+ let processStarted = false;
513
+ // The per-worktree build slot is taken first: holding a host token while
514
+ // queued behind this worktree's own build would waste host capacity.
515
+ const hostCapacity = new ManagedCommandHostCapacity({ ...invocation, label: invocation.verificationProfile ?? invocation.commandId }, async (hostLoad) => await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
516
+ ...invocation,
517
+ hostLoad,
518
+ timedOut: false,
519
+ status: "waiting_for_host_capacity",
520
+ exitCode: null,
521
+ stdout: "",
522
+ stderr: "",
523
+ launchRequested: false,
524
+ }).structuredContent));
525
+ const launch = async (buildQueueWaitMs) => await hostCapacity.run(invocation.controller.signal, async (hostLoad, control) => {
526
+ processStarted = true;
527
+ // A reclaimed token means this command's capacity is gone: it stops. A fence that
528
+ // landed between admission and here stops it too (a listener added now never fires).
529
+ const stopOnFence = () => invocation.controller.abort(control.fenced.reason);
530
+ if (control.fenced?.aborted)
531
+ stopOnFence();
532
+ else
533
+ control.fenced?.addEventListener("abort", stopOnFence, { once: true });
534
+ try {
535
+ return await executeManagedCommandProcess({
536
+ ...invocation,
537
+ buildQueueWaitMs,
538
+ hostLoad,
539
+ // Recording the tree is part of holding the token: if it fails (the token was
540
+ // fenced meanwhile, or the ledger refused), the command stops instead of
541
+ // running on without a reservation the host can account for.
542
+ // Checked against the tree recorded on the token at launch (null: the governor's own).
543
+ holdHostCapacityUntilStopped: reason => control.holdUntilStopped?.(null, reason),
544
+ onProcessStarted: async () => await attachManagedCommandProcess(control, invocation.metadataPath)
545
+ .catch((error) => {
546
+ invocation.controller.abort(error instanceof HostCapacityTokenFencedError || error instanceof HostCapacityLedgerUnavailableError
547
+ ? error
548
+ : new HostCapacityLedgerUnavailableError(`the managed command's process tree could not be recorded on its host load token: ${error instanceof Error ? error.message : String(error)}`, { cause: error }));
549
+ }),
550
+ });
551
+ }
552
+ finally {
553
+ control.fenced?.removeEventListener("abort", stopOnFence);
554
+ }
555
+ },
556
+ // A fenced release is already the receipt's termination reason; only a ledger fault is noted.
557
+ async (error) => error instanceof HostCapacityTokenFencedError ? undefined : await annotateManagedCommandReceipt(invocation.receiptPath, {
558
+ host_capacity_release_error: redactText(error instanceof Error ? error.message : String(error), []),
559
+ }));
560
+ try {
561
+ if (!invocation.buildProducing)
562
+ return await launch();
563
+ return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, launch, async () => {
564
+ const waiting = managedCommandResult({
565
+ ...invocation,
566
+ timedOut: false,
567
+ status: "waiting_for_build_slot",
568
+ exitCode: null,
569
+ stdout: "",
570
+ stderr: "",
571
+ launchRequested: false,
572
+ });
573
+ await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
574
+ }, invocation.controller.signal);
575
+ }
576
+ catch (error) {
577
+ if (processStarted)
578
+ throw error;
579
+ // The command never started (its build-slot or host-capacity wait failed or was
580
+ // stopped). Its receipt must still become terminal, or a waiting agent sees it queued forever.
581
+ const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
582
+ const receipt = managedCommandResult({
387
583
  ...invocation,
584
+ hostLoad: await hostCapacity.unadmittedFields(error),
388
585
  timedOut: false,
389
- status: "waiting_for_build_slot",
586
+ status: "runner_error",
390
587
  exitCode: null,
391
588
  stdout: "",
392
- stderr: "",
589
+ stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
590
+ terminationReason: ownerExited ? "owner_exited" : undefined,
591
+ launchRequested: false,
393
592
  });
394
- await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
395
- });
593
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
594
+ return managedCommandPublicResult(receipt);
595
+ }
396
596
  }
397
- async function executeManagedCommandProcess(invocation) {
597
+ async function managedCommandProcessEnvironment(invocation) {
398
598
  assertHostDatabaseCapabilityBoundary();
399
599
  const databaseEnvironment = invocation.verificationProfile
400
600
  ? await managedVerificationDatabaseEnvironment()
401
601
  : {};
402
- const exactSecrets = Object.values(databaseEnvironment)
403
- .filter(value => value !== nativeTestPostgresFallbackDatabaseMode);
602
+ const exactSecrets = [
603
+ ...Object.values(databaseEnvironment).filter(value => value !== nativeTestPostgresFallbackDatabaseMode),
604
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
605
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
+ ];
404
607
  const environment = inheritedEnvironment({
405
608
  FORGE_RUNTIME_MODE: "host",
406
609
  FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
@@ -425,9 +628,32 @@ async function executeManagedCommandProcess(invocation) {
425
628
  }
426
629
  : {}),
427
630
  });
631
+ return { environment, exactSecrets };
632
+ }
633
+ async function executeManagedCommandProcess(invocation) {
634
+ let prepared;
635
+ try {
636
+ prepared = await managedCommandProcessEnvironment(invocation);
637
+ }
638
+ catch (error) {
639
+ // The call still fails (the database capability boundary or the verification
640
+ // database probe refused it), but its receipt must not stay "starting" forever.
641
+ const receipt = managedCommandResult({
642
+ ...invocation,
643
+ timedOut: false,
644
+ status: "runner_error",
645
+ exitCode: null,
646
+ stdout: "",
647
+ stderr: appendBounded("", redactText(error instanceof Error ? error.message : String(error), [])),
648
+ launchRequested: false,
649
+ });
650
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent).catch(() => undefined);
651
+ throw error;
652
+ }
653
+ const { exactSecrets } = prepared;
428
654
  let stdout = "";
429
655
  let stderr = "";
430
- const controller = new AbortController();
656
+ const controller = invocation.controller;
431
657
  let timedOut = false;
432
658
  let timer = null;
433
659
  let outputRevision = 0;
@@ -460,15 +686,29 @@ async function executeManagedCommandProcess(invocation) {
460
686
  controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
461
687
  }, managedCommandLaunchTimeoutMs);
462
688
  try {
689
+ if (controller.signal.aborted)
690
+ throw controller.signal.reason;
691
+ // Recorded before the spawn: the process record is written only once the child has
692
+ // spawned, so teardown must know a launch may exist without one.
693
+ await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
694
+ ...invocation,
695
+ timedOut: false,
696
+ status: "starting",
697
+ exitCode: null,
698
+ stdout,
699
+ stderr,
700
+ }).structuredContent);
463
701
  const result = await new StreamingProviderProcessRunner().run({
464
702
  command: invocation.command,
465
703
  args: invocation.args,
466
704
  cwd: invocation.cwd,
467
- env: environment,
705
+ env: prepared.environment,
468
706
  captureOutput: false,
469
707
  }, {
470
708
  onStarted: async () => {
471
709
  clearTimeout(launchTimer);
710
+ // onProcessStarted stops the command itself when its token cannot be held.
711
+ await invocation.onProcessStarted?.();
472
712
  const running = managedCommandResult({
473
713
  ...invocation,
474
714
  timedOut: false,
@@ -512,7 +752,20 @@ async function executeManagedCommandProcess(invocation) {
512
752
  },
513
753
  }, controller.signal);
514
754
  await settleProgress();
515
- const status = timedOut ? "timed_out" : result.exitCode === 0 ? "pass" : "fail";
755
+ // Only a stop that interrupted the process relabels it. A command that exited on its own
756
+ // just before its owner asked for the stop keeps its real result.
757
+ const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
758
+ const hostCapacityLoss = !timedOut && !ownerExited && result.cancelled === true
759
+ ? hostCapacityLossReason(controller.signal.reason)
760
+ : null;
761
+ const fenced = hostCapacityLoss !== null;
762
+ if (ownerExited || fenced) {
763
+ stderr = appendBounded(stderr, ownerExited ? managedCommandOwnerExitMessage : controller.signal.reason.message);
764
+ outputRevision += 1;
765
+ lastOutputAt = Date.now();
766
+ lastOutputStream = "stderr";
767
+ }
768
+ const status = timedOut ? "timed_out" : ownerExited || fenced ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
516
769
  const receiptCoverage = managedBuildReceiptCoverage(invocation);
517
770
  const buildReceipt = status === "pass" && receiptCoverage
518
771
  ? await publishManagedBuildReceipt({
@@ -535,6 +788,9 @@ async function executeManagedCommandProcess(invocation) {
535
788
  lastOutputStream,
536
789
  buildReceipt,
537
790
  buildReceiptReused: invocation.buildReceiptReuse !== undefined,
791
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLoss ?? undefined,
792
+ // The runner resolves only after the stopped tree is proven gone.
793
+ processTreeTerminated: ownerExited || fenced ? true : undefined,
538
794
  });
539
795
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
540
796
  return managedCommandPublicResult(receipt);
@@ -542,7 +798,10 @@ async function executeManagedCommandProcess(invocation) {
542
798
  catch (error) {
543
799
  // The failure may be a progress write itself; it is reported below.
544
800
  await settleProgress().catch(() => undefined);
545
- const message = redactText(error instanceof Error ? error.message : String(error), exactSecrets);
801
+ const ownerExited = !timedOut && ownerExitStoppedCommands.has(invocation.commandId);
802
+ const message = ownerExited
803
+ ? managedCommandOwnerExitMessage
804
+ : redactText(error instanceof Error ? error.message : String(error), exactSecrets);
546
805
  stderr = appendBounded(stderr, message);
547
806
  outputRevision += 1;
548
807
  lastOutputAt = Date.now();
@@ -557,8 +816,17 @@ async function executeManagedCommandProcess(invocation) {
557
816
  outputRevision,
558
817
  lastOutputAt,
559
818
  lastOutputStream,
819
+ // A host capacity loss before launch (a fence that landed while it was admitted) is named too.
820
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLossReason(controller.signal.reason) ?? undefined,
821
+ // The runner rejected, so its tree was not proven stopped; teardown still stops it.
822
+ processTreeTerminated: false,
560
823
  });
561
824
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
825
+ // The runner stops the tree before it rejects; only a failed termination proof means
826
+ // part of it may still run. Its token is then kept, never returned with this receipt.
827
+ if (isProcessTreeTerminationUnproven(error)) {
828
+ invocation.holdHostCapacityUntilStopped?.(error instanceof Error ? error : new Error(String(error)));
829
+ }
562
830
  return managedCommandPublicResult(receipt);
563
831
  }
564
832
  finally {
@@ -582,6 +850,11 @@ async function readManagedCommand(input) {
582
850
  }
583
851
  throw error;
584
852
  }
853
+ // A queued receipt is written once; its wait so far is computed when it is read.
854
+ const hostLoadWaitStartedAt = Date.parse(String(receipt.host_load_wait_started_at));
855
+ if (receipt.status === "waiting_for_host_capacity" && Number.isFinite(hostLoadWaitStartedAt)) {
856
+ receipt = { ...receipt, host_load_wait_ms: Math.max(0, Date.now() - hostLoadWaitStartedAt) };
857
+ }
585
858
  const status = typeof receipt.status === "string" ? receipt.status : "unknown";
586
859
  const stdout = typeof receipt.stdout === "string" ? receipt.stdout : "";
587
860
  const stderr = typeof receipt.stderr === "string" ? receipt.stderr : "";
@@ -608,7 +881,7 @@ async function waitManagedCommand(input) {
608
881
  const commandId = validatedCommandId(record);
609
882
  const requestedWaitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
610
883
  const waitTimeoutMs = Math.min(requestedWaitTimeoutMs, maximumSynchronousWaitMs);
611
- const deadline = Date.now() + waitTimeoutMs;
884
+ const deadline = monotonicNowMs() + waitTimeoutMs;
612
885
  const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
613
886
  const task = managedCommandTasks.get(commandId);
614
887
  if (task) {
@@ -619,12 +892,12 @@ async function waitManagedCommand(input) {
619
892
  if (result)
620
893
  return result;
621
894
  }
622
- while (Date.now() < deadline) {
895
+ while (monotonicNowMs() < deadline) {
623
896
  const result = await readManagedCommand({ command_id: commandId });
624
897
  if (terminalManagedCommandStatuses.has(String(result.structuredContent.status))) {
625
898
  return result;
626
899
  }
627
- await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - Date.now())));
900
+ await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - monotonicNowMs())));
628
901
  }
629
902
  const receipt = await readManagedCommand({ command_id: commandId });
630
903
  // Only a running receipt is refreshed on a heartbeat; queued or starting receipts are
@@ -632,20 +905,23 @@ async function waitManagedCommand(input) {
632
905
  const elapsedMs = receipt.structuredContent.elapsed_ms;
633
906
  const timeoutMs = receipt.structuredContent.timeout_ms;
634
907
  const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
635
- const progress = receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
636
- ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
637
- + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
638
- + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
639
- // Agents otherwise abandon long verification tiers and record a blocker that is not one.
640
- + (typeof timeoutMs === "number"
641
- ? ` 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.`
642
- : "")
643
- : "";
908
+ const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
909
+ const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
910
+ ? ` It has waited ${Math.round(hostLoadWaitMs / 1000)}s for host capacity and has not started yet; its timeout starts only once it is admitted, so queue time never counts against it. Keep waiting; a queued command is not a blocker.`
911
+ : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
912
+ ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
913
+ + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
914
+ + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
915
+ // Agents otherwise abandon long verification tiers and record a blocker that is not one.
916
+ + (typeof timeoutMs === "number"
917
+ ? ` Forge itself ends it at its ${Math.round(timeoutMs / 60_000)}-minute limit if it hangs, so keep waiting; a running command is not a blocker.`
918
+ : "")
919
+ : "";
644
920
  return {
645
921
  ...receipt,
646
922
  content: [{
647
923
  type: "text",
648
- text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Its durable receipt remains at ${receiptPath}.`,
924
+ text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Do not end your turn to wait for it: Forge ends the provider run shortly after a turn ends, which stops background monitors and this command. Its durable receipt remains at ${receiptPath}.`,
649
925
  }],
650
926
  structuredContent: {
651
927
  ...receipt.structuredContent,
@@ -685,7 +961,9 @@ async function persistManagedCommandReceipt(receiptPath, receipt) {
685
961
  }
686
962
  }
687
963
  function managedCommandResult(values) {
688
- const elapsedMs = Date.now() - values.startedAt;
964
+ // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
965
+ const hostLoad = values.hostLoad;
966
+ const elapsedMs = Date.now() - (hostLoad ? hostLoad.executionStartedAt ?? Date.now() : values.startedAt);
689
967
  const isTerminal = terminalManagedCommandStatuses.has(values.status);
690
968
  const diagnostics = isTerminal
691
969
  ? managedCommandDiagnostics(values.stdout, values.stderr)
@@ -730,6 +1008,7 @@ function managedCommandResult(values) {
730
1008
  build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
731
1009
  build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
732
1010
  build_receipt_reused: values.buildReceiptReused ?? false,
1011
+ ...(hostLoad ? managedCommandHostLoadReceipt(hostLoad) : {}),
733
1012
  build_receipt: values.buildReceipt ? {
734
1013
  fingerprint: values.buildReceipt.fingerprint,
735
1014
  receipt_path: values.buildReceipt.receiptPath,
@@ -739,11 +1018,34 @@ function managedCommandResult(values) {
739
1018
  output_count: values.buildReceipt.outputCount,
740
1019
  } : null,
741
1020
  runtime_configuration: managedRuntimeConfiguration(),
742
- process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : undefined,
1021
+ // The supervising MCP server process. Forge stops a command whose owner has exited.
1022
+ owner_pid: process.pid,
1023
+ owner_identity: managedCommandOwnerIdentity(),
1024
+ launch_requested: values.launchRequested ?? true,
1025
+ process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : values.processTreeTerminated,
1026
+ ...(values.terminationReason ? { termination_reason: values.terminationReason } : {}),
743
1027
  },
744
1028
  isError: isTerminal && values.status !== "pass",
745
1029
  };
746
1030
  }
1031
+ function managedCommandHostLoadReceipt(hostLoad) {
1032
+ const waiting = hostLoad.waitStartedAt !== undefined;
1033
+ return {
1034
+ host_load_step_class: hostLoad.stepClass,
1035
+ host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
1036
+ ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString() } : {}),
1037
+ };
1038
+ }
1039
+ async function annotateManagedCommandReceipt(receiptPath, fields) {
1040
+ const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
1041
+ await persistManagedCommandReceipt(receiptPath, { ...receipt, ...fields });
1042
+ }
1043
+ /** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
1044
+ function managedCommandOwnerIdentity() {
1045
+ // Windows identity capture starts PowerShell; the PID check alone is used there.
1046
+ ownerProcessIdentity ??= process.platform === "linux" ? captureHostProcessIdentity(process.pid) : null;
1047
+ return ownerProcessIdentity;
1048
+ }
747
1049
  function managedRuntimeConfiguration() {
748
1050
  const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
749
1051
  let providerOnlySpecCount = 0;
@@ -814,6 +1116,10 @@ async function containedWorkingDirectory(worktreePath, input) {
814
1116
  function inheritedEnvironment(overrides) {
815
1117
  const env = {};
816
1118
  for (const [key, value] of Object.entries(process.env)) {
1119
+ // A nested Forge process must not join the host ledger: it would queue behind the
1120
+ // token this command already holds.
1121
+ if (key === hostLoadGovernorEnvironment || key === hostLoadStateRootEnvironment)
1122
+ continue;
817
1123
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
818
1124
  env[key] = value;
819
1125
  }
@@ -902,8 +1208,17 @@ function asRecord(value) {
902
1208
  throw new Error("managed_command_invalid: input must be an object.");
903
1209
  return value;
904
1210
  }
1211
+ const requiredInputExamples = {
1212
+ command: "Send the executable as command and each argument as its own string in args, for example {\"command\": \"pnpm\", \"args\": [\"--dir\", \"client\", \"lint\"]}.",
1213
+ profile: managedVerificationProfileHint,
1214
+ command_id: "Send the command_id returned by forge.start_managed_command or forge.start_managed_verification.",
1215
+ };
905
1216
  function requiredInputString(record, name) {
906
- return requiredStandaloneString(record[name], name);
1217
+ const value = record[name];
1218
+ if (typeof value === "string" && value.trim())
1219
+ return value.trim();
1220
+ const hints = [requiredInputExamples[name], isEmptyToolInput(record) ? emptyToolInputHint : undefined].filter(Boolean);
1221
+ throw new Error(`managed_command_invalid: ${name} is required.${hints.length > 0 ? ` ${hints.join(" ")}` : ""}`);
907
1222
  }
908
1223
  function validatedCommandId(record) {
909
1224
  const commandId = requiredInputString(record, "command_id");
@@ -920,7 +1235,13 @@ function requiredStandaloneString(value, name) {
920
1235
  function requiredStringArray(record, name) {
921
1236
  const value = record[name];
922
1237
  if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) {
923
- throw new Error(`managed_command_invalid: ${name} must be a string array.`);
1238
+ const shellLine = typeof record.command === "string" && /\s/u.test(record.command.trim());
1239
+ const hint = typeof value === "string"
1240
+ ? " (received a string). Put each argument in its own string, for example [\"--dir\", \"client\", \"test\"]."
1241
+ : value === undefined
1242
+ ? ` (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." : ""}`
1243
+ : " Every argument must be a string.";
1244
+ throw new Error(`managed_command_invalid: ${name} must be a string array${hint}`);
924
1245
  }
925
1246
  return value;
926
1247
  }