@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.028808a841c8

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 (185) hide show
  1. package/README.md +89 -3
  2. package/dist/bridge/bridge-chat.types.d.ts +111 -0
  3. package/dist/bridge/bridge-chat.types.js +401 -0
  4. package/dist/bridge/bridge.base.d.ts +4 -1
  5. package/dist/bridge/bridge.service.d.ts +83 -3
  6. package/dist/bridge/bridge.service.js +1609 -152
  7. package/dist/bridge/bridge.types.d.ts +52 -1
  8. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  9. package/dist/bridge/dispatch-result-outbox.js +87 -0
  10. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  11. package/dist/bridge/dispatch-result-worker.js +122 -0
  12. package/dist/bridge/internals.d.ts +2 -0
  13. package/dist/bridge/internals.js +1 -0
  14. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  15. package/dist/bridge/readiness-result-outbox.js +54 -0
  16. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  17. package/dist/bridge/readiness-result-worker.js +121 -0
  18. package/dist/bridge/runner-host-capabilities.d.ts +15 -0
  19. package/dist/bridge/runner-host-capabilities.js +93 -0
  20. package/dist/cleanup/cleanup.service.d.ts +1 -0
  21. package/dist/cleanup/cleanup.service.js +70 -9
  22. package/dist/cli/cli.help.js +4 -4
  23. package/dist/cli/cli.service.d.ts +14 -6
  24. package/dist/cli/cli.service.js +75 -16
  25. package/dist/cli/local-config.d.ts +1 -0
  26. package/dist/cli/local-config.js +4 -0
  27. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  28. package/dist/runtime/aspnet-runtime-prebuild.js +341 -0
  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-node-runtime-launcher.d.ts +2 -1
  32. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  33. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  34. package/dist/runtime/attempt-path-operation.js +94 -0
  35. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  36. package/dist/runtime/attempt-private-directory.js +54 -0
  37. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  38. package/dist/runtime/attempt-process-supervisor.js +144 -23
  39. package/dist/runtime/canonical-source-file.d.ts +3 -0
  40. package/dist/runtime/canonical-source-file.js +54 -0
  41. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  42. package/dist/runtime/docker-engine-probe.js +333 -0
  43. package/dist/runtime/generated-output-reset.d.ts +10 -0
  44. package/dist/runtime/generated-output-reset.js +62 -8
  45. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  46. package/dist/runtime/host-database-capability-boundary.js +63 -0
  47. package/dist/runtime/host-diagnostics.d.ts +11 -0
  48. package/dist/runtime/host-diagnostics.js +192 -0
  49. package/dist/runtime/host-execution-root.d.ts +4 -0
  50. package/dist/runtime/host-execution-root.js +39 -0
  51. package/dist/runtime/host-facts.d.ts +35 -0
  52. package/dist/runtime/host-facts.js +95 -0
  53. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  54. package/dist/runtime/host-listener-inspector.js +121 -60
  55. package/dist/runtime/host-load-sampler.d.ts +83 -0
  56. package/dist/runtime/host-load-sampler.js +164 -0
  57. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  58. package/dist/runtime/host-pressure-stall.js +121 -0
  59. package/dist/runtime/host-runtime-contract.d.ts +13 -1
  60. package/dist/runtime/host-runtime-contract.js +170 -55
  61. package/dist/runtime/host-runtime-lease.d.ts +92 -8
  62. package/dist/runtime/host-runtime-lease.js +1193 -120
  63. package/dist/runtime/host-runtime-promotion.d.ts +12 -3
  64. package/dist/runtime/host-runtime-promotion.js +59 -12
  65. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  66. package/dist/runtime/managed-command-teardown.js +607 -0
  67. package/dist/runtime/memory-capacity.d.ts +70 -0
  68. package/dist/runtime/memory-capacity.js +123 -0
  69. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  70. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  71. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  72. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  73. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  74. package/dist/runtime/pinned-directory-process.js +61 -0
  75. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  76. package/dist/runtime/pinned-source-directory.js +94 -0
  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 +12 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +100 -58
  81. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  82. package/dist/runtime/prepared-runtime-identity.js +218 -0
  83. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  84. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  85. package/dist/runtime/runtime-isolation-lease.js +4 -1
  86. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  87. package/dist/runtime/workspace-resource-estimator.js +174 -0
  88. package/dist/sandbox/preflight.d.ts +31 -1
  89. package/dist/sandbox/preflight.js +237 -51
  90. package/dist/sandbox/repository-lock.d.ts +2 -1
  91. package/dist/sandbox/repository-lock.js +19 -9
  92. package/dist/sandbox/runtime.d.ts +6 -1
  93. package/dist/sandbox/runtime.js +137 -107
  94. package/dist/sandbox/sandbox.types.d.ts +7 -0
  95. package/dist/sandbox/workspace.service.js +2 -0
  96. package/dist/session/managed-attempt-tools.d.ts +42 -1
  97. package/dist/session/managed-attempt-tools.js +692 -40
  98. package/dist/session/managed-build-coordinator.d.ts +5 -0
  99. package/dist/session/managed-build-coordinator.js +109 -0
  100. package/dist/session/managed-build-receipt.d.ts +21 -0
  101. package/dist/session/managed-build-receipt.js +337 -0
  102. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  103. package/dist/session/managed-verification-timeouts.js +17 -0
  104. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  105. package/dist/session/phase-completion.artifacts.js +228 -22
  106. package/dist/session/phase-completion.d.ts +11 -1
  107. package/dist/session/phase-completion.helpers.d.ts +5 -0
  108. package/dist/session/phase-completion.helpers.js +30 -7
  109. package/dist/session/phase-completion.js +14 -3
  110. package/dist/session/phase-completion.prompts.js +17 -18
  111. package/dist/session/phase-completion.runtime.d.ts +3 -1
  112. package/dist/session/phase-completion.runtime.js +148 -34
  113. package/dist/session/phase-completion.schemas.js +49 -2
  114. package/dist/session/phase-completion.validation.d.ts +1 -0
  115. package/dist/session/phase-completion.validation.js +111 -21
  116. package/dist/session/pre-publication-process.d.ts +20 -0
  117. package/dist/session/pre-publication-process.js +97 -0
  118. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  119. package/dist/session/pre-publication-skipped-tests.js +109 -0
  120. package/dist/session/pre-publication-validation.d.ts +75 -0
  121. package/dist/session/pre-publication-validation.js +631 -0
  122. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  123. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  124. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  125. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  126. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  127. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  128. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  129. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  130. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  131. package/dist/session/provider-cli/provider-cli.process.d.ts +80 -0
  132. package/dist/session/provider-cli/provider-cli.process.js +694 -28
  133. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  134. package/dist/session/provider-cli/provider-cli.prompts.js +151 -16
  135. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  136. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  137. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  138. package/dist/session/provider-cli/provider-cli.runtime.js +54 -3
  139. package/dist/session/provider-cli/provider-cli.service.d.ts +30 -5
  140. package/dist/session/provider-cli/provider-cli.service.js +858 -77
  141. package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  143. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  144. package/dist/session/provider-cli/provider-output-state.d.ts +16 -0
  145. package/dist/session/provider-cli/provider-output-state.js +370 -17
  146. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  147. package/dist/session/provider-cli/provider-usage.js +28 -5
  148. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  149. package/dist/session/publishable-worktree-changes.js +193 -0
  150. package/dist/session/session-redaction.js +434 -9
  151. package/dist/session/session.service.js +145 -23
  152. package/dist/session/session.types.d.ts +147 -2
  153. package/dist/session/session.types.js +599 -7
  154. package/dist/session/unreferenced-exports.d.ts +12 -0
  155. package/dist/session/unreferenced-exports.js +59 -0
  156. package/dist/shared/format/format-bytes.d.ts +1 -0
  157. package/dist/shared/format/format-bytes.js +9 -0
  158. package/dist/shared/git/git.js +2 -1
  159. package/dist/shared/path/path.d.ts +1 -0
  160. package/dist/shared/path/path.js +18 -0
  161. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  162. package/dist/shared/process/dotnet-toolchain.js +307 -0
  163. package/dist/shared/process/host-process-recovery.js +3 -2
  164. package/dist/shared/process/host-process-supervisor.d.ts +2 -0
  165. package/dist/shared/process/host-process-supervisor.js +60 -11
  166. package/dist/shared/process/process.d.ts +2 -0
  167. package/dist/shared/process/process.js +12 -7
  168. package/dist/shared/provider-capabilities.d.ts +3 -0
  169. package/dist/shared/provider-capabilities.js +85 -0
  170. package/dist/shared/redaction/redaction.d.ts +1 -0
  171. package/dist/shared/redaction/redaction.js +39 -3
  172. package/dist/shared/time/monotonic.d.ts +1 -0
  173. package/dist/shared/time/monotonic.js +8 -0
  174. package/dist/version.d.ts +1 -1
  175. package/dist/version.js +1 -1
  176. package/dist/worktree/dependency-warmer.d.ts +41 -9
  177. package/dist/worktree/dependency-warmer.js +571 -22
  178. package/dist/worktree/index.d.ts +1 -1
  179. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  180. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  181. package/dist/worktree/worktree.service.d.ts +7 -0
  182. package/dist/worktree/worktree.service.js +253 -21
  183. package/dist/worktree/worktree.types.d.ts +7 -1
  184. package/package.json +7 -5
  185. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -1,17 +1,34 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
5
- import { StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
6
+ import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
7
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
8
+ import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
9
+ import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
10
+ import { redactText } from "../shared/redaction/redaction.js";
11
+ import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
12
+ import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
13
+ import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
14
+ import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
15
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
16
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
6
17
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
7
18
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
8
19
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
9
20
  const waitManagedCommandNames = new Set(["forge.wait_managed_command", "wait_managed_command"]);
21
+ const startManagedVerificationNames = new Set(["forge.start_managed_verification", "start_managed_verification"]);
10
22
  const resetGeneratedOutputNames = new Set(["forge.reset_generated_outputs", "reset_generated_outputs"]);
11
23
  const maximumCapturedCharacters = 200_000;
12
- const maximumReturnedOutputCharacters = 12_000;
24
+ const maximumReturnedOutputCharacters = 4_000;
13
25
  const maximumReportedFailedTests = 50;
14
- const maximumSynchronousWaitMs = 240_000;
26
+ // Keep a wait slice comfortably below the MCP transport deadline. The managed
27
+ // process remains supervised and its durable receipt continues to update after
28
+ // this call returns, so a shorter slice avoids converting healthy long-running
29
+ // commands into ambiguous MCP failures.
30
+ const maximumSynchronousWaitMs = 45_000;
31
+ const managedCommandRetryAfterMs = 60_000;
15
32
  const managedCommandLaunchTimeoutMs = 60_000;
16
33
  const managedCommandProgressPersistIntervalMs = 5_000;
17
34
  const managedCommandReceiptPollIntervalMs = 1_000;
@@ -24,7 +41,16 @@ const terminalManagedCommandStatuses = new Set([
24
41
  "timeout_termination_failed",
25
42
  "runner_error",
26
43
  ]);
44
+ const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
27
45
  const managedCommandTasks = new Map();
46
+ // Every command this MCP server is supervising, synchronous or not. The server is the only
47
+ // writer of their receipts, so it stops them before it exits.
48
+ const activeManagedCommands = new Map();
49
+ const ownerExitStoppedCommands = new Set();
50
+ let ownerProcessIdentity;
51
+ let managedCommandOwnerShuttingDown = false;
52
+ let ownerExitSweep = null;
53
+ const managedCommandOwnerExitMessage = "managed_command_owner_exited: Forge stopped this managed command because the Forge MCP server that supervised it is exiting; its provider process ended before the command finished. Its result is unknown; start it again if it is still needed.";
28
54
  export const managedAttemptToolNames = [
29
55
  "forge.run_managed_command",
30
56
  "run_managed_command",
@@ -34,23 +60,119 @@ export const managedAttemptToolNames = [
34
60
  "get_managed_command",
35
61
  "forge.wait_managed_command",
36
62
  "wait_managed_command",
63
+ "forge.start_managed_verification",
64
+ "start_managed_verification",
37
65
  "forge.reset_generated_outputs",
38
66
  "reset_generated_outputs",
39
67
  ];
68
+ /**
69
+ * Stops every managed command this MCP server started, proves each process tree stopped,
70
+ * and writes their terminal receipts. Called when the provider closes the MCP connection
71
+ * or the server is signalled: once this server exits nothing could supervise them.
72
+ */
73
+ export async function stopManagedCommandsForOwnerExit() {
74
+ // One sweep at a time: a signal that arrives while a sweep runs waits for that sweep.
75
+ ownerExitSweep ??= sweepManagedCommandsForOwnerExit().finally(() => { ownerExitSweep = null; });
76
+ await ownerExitSweep;
77
+ }
78
+ async function sweepManagedCommandsForOwnerExit() {
79
+ // From here on this server refuses new commands, so a request still being handled
80
+ // cannot launch one behind the sweep. Repeat until none is left: a launch that passed
81
+ // its last check just before the flag was set registers synchronously and is caught.
82
+ managedCommandOwnerShuttingDown = true;
83
+ while (activeManagedCommands.size > 0) {
84
+ const active = [...activeManagedCommands.entries()];
85
+ for (const [commandId, command] of active) {
86
+ ownerExitStoppedCommands.add(commandId);
87
+ command.controller.abort(new Error(managedCommandOwnerExitMessage));
88
+ }
89
+ await Promise.allSettled(active.map(([, command]) => command.task));
90
+ }
91
+ }
92
+ /** Test support: lets one test process act as a fresh MCP server after a simulated exit. */
93
+ export function resetManagedCommandOwnerShutdownForTesting() {
94
+ managedCommandOwnerShuttingDown = false;
95
+ }
96
+ function assertManagedCommandsAccepted() {
97
+ if (managedCommandOwnerShuttingDown) {
98
+ throw new Error("managed_command_unavailable: the Forge MCP server is shutting down and accepts no new managed commands.");
99
+ }
100
+ }
101
+ const ownerShutdownSignals = ["SIGTERM", "SIGHUP", "SIGINT"];
102
+ /**
103
+ * Makes a termination signal stop this server's managed commands before it exits, so none
104
+ * outlives its only supervisor. Returns a function that removes the handlers.
105
+ */
106
+ export function installOwnerShutdownHandlers(target = process, exit = code => process.exit(code)) {
107
+ const handlers = ownerShutdownSignals.map(signal => {
108
+ const handler = () => {
109
+ void stopManagedCommandsForOwnerExit().finally(() => exit(128 + os.constants.signals[signal]));
110
+ };
111
+ target.once(signal, handler);
112
+ return { signal, handler };
113
+ });
114
+ return () => {
115
+ for (const { signal, handler } of handlers)
116
+ target.removeListener(signal, handler);
117
+ };
118
+ }
119
+ /**
120
+ * Runs an MCP server body, then stops every managed command it started before returning.
121
+ * The signal handlers stay installed until that stop completes: a signal during the body
122
+ * or the stop exits only after the same stop finishes, never by Node's default exit.
123
+ */
124
+ export async function runWithOwnerShutdown(body, target = process, exit = code => process.exit(code)) {
125
+ const removeShutdownHandlers = installOwnerShutdownHandlers(target, exit);
126
+ try {
127
+ return await body();
128
+ }
129
+ finally {
130
+ try {
131
+ await stopManagedCommandsForOwnerExit();
132
+ }
133
+ finally {
134
+ removeShutdownHandlers();
135
+ }
136
+ }
137
+ }
40
138
  export function isManagedAttemptTool(name) {
41
139
  return managedCommandNames.has(name)
42
140
  || startManagedCommandNames.has(name)
43
141
  || getManagedCommandNames.has(name)
44
142
  || waitManagedCommandNames.has(name)
143
+ || startManagedVerificationNames.has(name)
45
144
  || resetGeneratedOutputNames.has(name);
46
145
  }
47
146
  export function managedAttemptToolDefinition(name) {
147
+ if (startManagedVerificationNames.has(name)) {
148
+ return {
149
+ 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.",
151
+ inputSchema: {
152
+ type: "object",
153
+ additionalProperties: false,
154
+ required: ["profile"],
155
+ properties: {
156
+ profile: {
157
+ type: "string",
158
+ enum: ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"],
159
+ },
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 },
163
+ max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
164
+ no_build: { type: "boolean", default: false },
165
+ timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
166
+ },
167
+ },
168
+ };
169
+ }
48
170
  if (managedCommandNames.has(name) || startManagedCommandNames.has(name)) {
49
171
  return {
50
172
  name,
51
173
  description: startManagedCommandNames.has(name)
52
- ? "Start a long command in an attempt-owned process tree and return a durable command ID immediately. Continue independent work, then call forge.wait_managed_command once for its terminal receipt."
53
- : "Run a short command in an attempt-owned process tree. Commands with a timeout above four minutes automatically start asynchronously; continue independent work, then call forge.wait_managed_command once for the durable result.",
174
+ ? "Start a long command in an attempt-owned process tree and return a durable command ID immediately. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt."
175
+ : "Run a short command in an attempt-owned process tree. Commands with a timeout above four minutes automatically start asynchronously; continue independent work, then use forge.wait_managed_command for the durable result.",
54
176
  inputSchema: {
55
177
  type: "object",
56
178
  additionalProperties: false,
@@ -81,14 +203,14 @@ export function managedAttemptToolDefinition(name) {
81
203
  if (waitManagedCommandNames.has(name)) {
82
204
  return {
83
205
  name,
84
- description: "Wait for a command started by Forge's managed command runner to reach a terminal state. Use this once after completing work that is independent of the command; Forge streams durable progress while this call waits.",
206
+ description: "Wait up to 45 seconds for a managed command terminal receipt. If it remains active, the call succeeds with command_continues=true and retry_after_ms; continue independent work or wait again later. Live progress remains in the durable receipt/UI; do not poll get_managed_command.",
85
207
  inputSchema: {
86
208
  type: "object",
87
209
  additionalProperties: false,
88
210
  required: ["command_id"],
89
211
  properties: {
90
212
  command_id: { type: "string", minLength: 1 },
91
- wait_timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 7200000 },
213
+ wait_timeout_ms: { type: "integer", minimum: 1000, maximum: 45000, default: 45000 },
92
214
  },
93
215
  },
94
216
  };
@@ -113,6 +235,7 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
113
235
  structuredContent: {
114
236
  status: "pass",
115
237
  quarantined_paths: result.quarantinedPaths,
238
+ retained_paths: result.retainedPaths,
116
239
  quarantine_directory: result.quarantineDirectory,
117
240
  },
118
241
  };
@@ -123,14 +246,21 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
123
246
  if (waitManagedCommandNames.has(name)) {
124
247
  return await waitManagedCommand(input);
125
248
  }
249
+ if (startManagedVerificationNames.has(name)) {
250
+ return await startManagedVerification(input, worktreePath);
251
+ }
126
252
  if (!managedCommandNames.has(name) && !startManagedCommandNames.has(name)) {
127
253
  throw new Error(`Unknown managed attempt tool: ${name}`);
128
254
  }
129
- const record = asRecord(input);
255
+ return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
256
+ }
257
+ async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
258
+ assertManagedCommandsAccepted();
130
259
  const command = requiredInputString(record, "command");
131
260
  const args = requiredStringArray(record, "args");
132
261
  const timeoutMs = optionalTimeout(record.timeout_ms);
133
262
  const cwd = await containedWorkingDirectory(worktreePath, record.cwd);
263
+ await validatePlaywrightCommandProject(command, args, cwd);
134
264
  const logDirectory = requiredAttemptEnvironment("FORGE_LOG_DIR");
135
265
  await fs.mkdir(path.join(logDirectory, "managed-commands"), { recursive: true, mode: 0o700 });
136
266
  const commandId = randomUUID();
@@ -146,8 +276,13 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
146
276
  metadataPath,
147
277
  receiptPath,
148
278
  startedAt: Date.now(),
279
+ verificationProfile,
280
+ worktreePath,
281
+ buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
282
+ buildReceiptReuse,
283
+ controller: new AbortController(),
149
284
  };
150
- if (startManagedCommandNames.has(name) || timeoutMs > maximumSynchronousWaitMs) {
285
+ if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
151
286
  const started = managedCommandResult({
152
287
  ...invocation,
153
288
  timedOut: false,
@@ -155,22 +290,255 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
155
290
  exitCode: null,
156
291
  stdout: "",
157
292
  stderr: "",
293
+ launchRequested: false,
158
294
  });
159
295
  await persistManagedCommandReceipt(receiptPath, started.structuredContent);
160
- const task = executeManagedCommand(invocation);
296
+ if (managedCommandOwnerShuttingDown) {
297
+ // Shutdown began while the receipt was written; the command never starts.
298
+ const refused = managedCommandResult({
299
+ ...invocation,
300
+ timedOut: false,
301
+ status: "runner_error",
302
+ exitCode: null,
303
+ stdout: "",
304
+ stderr: appendBounded("", managedCommandOwnerExitMessage),
305
+ launchRequested: false,
306
+ terminationReason: "owner_exited",
307
+ });
308
+ await persistManagedCommandReceipt(receiptPath, refused.structuredContent);
309
+ assertManagedCommandsAccepted();
310
+ }
311
+ const task = trackManagedCommand(invocation);
161
312
  managedCommandTasks.set(commandId, task);
162
313
  void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
163
314
  return {
164
- ...started,
315
+ ...managedCommandPublicResult(started),
165
316
  content: [{
166
317
  type: "text",
167
- text: `Forge managed command ${commandId} started asynchronously. Continue independent work, then call forge.wait_managed_command once with this command_id for the terminal receipt.`,
318
+ text: `Forge managed command ${commandId} started asynchronously. Continue independent work, then use forge.wait_managed_command with this command_id for a transport-safe terminal receipt.`,
168
319
  }],
169
320
  };
170
321
  }
171
- return await executeManagedCommand(invocation);
322
+ return await trackManagedCommand(invocation);
323
+ }
324
+ function trackManagedCommand(invocation) {
325
+ const task = executeManagedCommand(invocation);
326
+ activeManagedCommands.set(invocation.commandId, { controller: invocation.controller, task });
327
+ void task.finally(() => {
328
+ activeManagedCommands.delete(invocation.commandId);
329
+ ownerExitStoppedCommands.delete(invocation.commandId);
330
+ }).catch(() => undefined);
331
+ return task;
332
+ }
333
+ async function startManagedVerification(input, worktreePath) {
334
+ const record = asRecord(input);
335
+ const profile = requiredInputString(record, "profile");
336
+ const shardCount = optionalBoundedInteger(record.shard_count, "shard_count", 1, 32, 1);
337
+ const shardIndex = optionalBoundedInteger(record.shard_index, "shard_index", 0, 31, 0);
338
+ if (shardIndex >= shardCount) {
339
+ throw new Error("managed_verification_invalid: shard_index must be less than shard_count.");
340
+ }
341
+ const noBuild = optionalBoolean(record.no_build, "no_build", false);
342
+ const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
343
+ const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
344
+ if (runAllShards && shardCount < 2) {
345
+ throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 2.");
346
+ }
347
+ if (runAllShards && shardIndex !== 0) {
348
+ throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
349
+ }
350
+ 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.");
352
+ }
353
+ const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
354
+ const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
355
+ const buildReceiptReuse = noBuild
356
+ ? await verifyManagedBuildReceipt({
357
+ worktreePath,
358
+ configuration: managedBuildConfiguration(profileCommand.command, profileCommand.args),
359
+ requiredCoverage: managedVerificationBuildCoverage,
360
+ })
361
+ : undefined;
362
+ return await launchManagedCommand({
363
+ command: profileCommand.command,
364
+ args: profileCommand.args,
365
+ timeout_ms: record.timeout_ms ?? profileCommand.timeoutMs,
366
+ }, worktreePath, true, profile, !noBuild, buildReceiptReuse);
367
+ }
368
+ export function buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards = false, maxParallelism = 2) {
369
+ if (profile === "dotnet_affected") {
370
+ // The tests an uncommitted change can affect: one build, Unit and Contract whole, then
371
+ // only the affected heavier-tier classes. The script owns its build and its selection.
372
+ if (runAllShards || shardCount !== 1 || shardIndex !== 0 || noBuild) {
373
+ throw new Error("managed_verification_invalid: dotnet_affected selects its own tests and owns its build; it accepts no sharding or no_build.");
374
+ }
375
+ return {
376
+ command: process.execPath,
377
+ args: ["scripts/run-affected-dotnet-tests.mjs", "--results-directory", outputDirectory],
378
+ // A change that reaches tests without naming a type runs the heavier tiers whole.
379
+ timeoutMs: managedMaximumCommandTimeoutMs,
380
+ };
381
+ }
382
+ if (profile === "dotnet_solution") {
383
+ if (runAllShards) {
384
+ throw new Error("managed_verification_invalid: dotnet_solution does not support run_all_shards; select a test tier instead.");
385
+ }
386
+ if (shardCount !== 1 || shardIndex !== 0) {
387
+ throw new Error("managed_verification_invalid: dotnet_solution does not accept sharding; select a test tier instead.");
388
+ }
389
+ const command = preferredPowerShellExecutable();
390
+ const args = [
391
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-suite.ps1",
392
+ "-ResultsDirectory", outputDirectory,
393
+ "-MaxParallelism", String(maxParallelism),
394
+ ];
395
+ if (noBuild)
396
+ args.push("-NoBuild");
397
+ return { command, args, timeoutMs: managedLongTierTimeoutMs };
398
+ }
399
+ const tiers = {
400
+ dotnet_unit: "Unit",
401
+ dotnet_contract: "Contract",
402
+ dotnet_api_component: "ApiComponent",
403
+ dotnet_orchestration: "Orchestration",
404
+ dotnet_infrastructure: "Infrastructure",
405
+ };
406
+ const tier = tiers[profile];
407
+ if (!tier)
408
+ throw new Error(`managed_verification_invalid: unsupported profile ${profile}.`);
409
+ const command = preferredPowerShellExecutable();
410
+ if (runAllShards) {
411
+ return {
412
+ command,
413
+ args: [
414
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier-set.ps1",
415
+ "-Tier", tier,
416
+ "-ResultsDirectory", outputDirectory,
417
+ "-ShardCount", String(shardCount),
418
+ "-MaxParallelism", String(maxParallelism),
419
+ ],
420
+ timeoutMs: managedVerificationTierTimeoutMs(tier, { shardCount, maxParallelism }),
421
+ };
422
+ }
423
+ const args = [
424
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier.ps1",
425
+ "-Tier", tier,
426
+ "-ResultsDirectory", outputDirectory,
427
+ "-ShardCount", String(shardCount),
428
+ "-ShardIndex", String(shardIndex),
429
+ ];
430
+ if (noBuild)
431
+ args.push("-NoBuild");
432
+ return { command, args, timeoutMs: managedVerificationTierTimeoutMs(tier) };
433
+ }
434
+ export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
435
+ if (platform !== "win32")
436
+ return "pwsh";
437
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue) ?? "powershell.exe";
438
+ }
439
+ export function validatePlaywrightProjectName(project, availableProjects) {
440
+ if (!availableProjects.includes(project)) {
441
+ throw new Error(`managed_command_capability_unavailable: Playwright project '${project}' is not advertised by the selected config. Available projects: ${availableProjects.join(", ") || "none"}.`);
442
+ }
443
+ }
444
+ async function validatePlaywrightCommandProject(command, args, cwd) {
445
+ const invocation = [path.basename(command).toLowerCase(), ...args.map(argument => argument.toLowerCase())];
446
+ if (!invocation.some(argument => argument.includes("playwright")))
447
+ return;
448
+ const project = optionValue(args, "--project");
449
+ if (!project)
450
+ return;
451
+ const configuredPath = optionValue(args, "--config") ?? process.env.FORGE_PLAYWRIGHT_CONFIG;
452
+ const candidates = configuredPath
453
+ ? [path.resolve(cwd, configuredPath)]
454
+ : ["playwright.config.ts", "playwright.config.js", "playwright.config.mjs"].map(file => path.join(cwd, file));
455
+ for (const candidate of candidates) {
456
+ try {
457
+ const source = await fs.readFile(candidate, "utf8");
458
+ const projects = playwrightProjectNamesFromConfigSource(source);
459
+ validatePlaywrightProjectName(project, projects);
460
+ return;
461
+ }
462
+ catch (error) {
463
+ if (error.code !== "ENOENT")
464
+ throw error;
465
+ }
466
+ }
467
+ throw new Error("managed_command_capability_unavailable: Playwright config was not found; project selection cannot be validated.");
468
+ }
469
+ export function playwrightProjectNamesFromConfigSource(source) {
470
+ const marker = source.match(/^\/\/ forge-playwright-projects: (\[[^\r\n]*\])$/mu)?.[1];
471
+ if (!marker) {
472
+ return [...source.matchAll(/\bname\s*:\s*["']([^"']+)["']/gu)].map(match => match[1]);
473
+ }
474
+ try {
475
+ const parsed = JSON.parse(marker);
476
+ return Array.isArray(parsed)
477
+ ? parsed.filter((value) => typeof value === "string" && value.trim().length > 0)
478
+ : [];
479
+ }
480
+ catch {
481
+ return [];
482
+ }
483
+ }
484
+ function optionValue(args, name) {
485
+ const direct = args.find(argument => argument.startsWith(`${name}=`));
486
+ if (direct)
487
+ return direct.slice(name.length + 1).trim() || null;
488
+ const index = args.indexOf(name);
489
+ return index >= 0 ? args[index + 1]?.trim() || null : null;
172
490
  }
173
491
  async function executeManagedCommand(invocation) {
492
+ if (!invocation.buildProducing)
493
+ return await executeManagedCommandProcess(invocation);
494
+ let processStarted = false;
495
+ try {
496
+ return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => {
497
+ processStarted = true;
498
+ return await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs });
499
+ }, async () => {
500
+ const waiting = managedCommandResult({
501
+ ...invocation,
502
+ timedOut: false,
503
+ status: "waiting_for_build_slot",
504
+ exitCode: null,
505
+ stdout: "",
506
+ stderr: "",
507
+ launchRequested: false,
508
+ });
509
+ await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
510
+ }, invocation.controller.signal);
511
+ }
512
+ catch (error) {
513
+ if (processStarted)
514
+ 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.
517
+ const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
518
+ const receipt = managedCommandResult({
519
+ ...invocation,
520
+ timedOut: false,
521
+ status: "runner_error",
522
+ exitCode: null,
523
+ stdout: "",
524
+ stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
525
+ terminationReason: ownerExited ? "owner_exited" : undefined,
526
+ launchRequested: false,
527
+ });
528
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
529
+ return managedCommandPublicResult(receipt);
530
+ }
531
+ }
532
+ async function managedCommandProcessEnvironment(invocation) {
533
+ 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
+ ];
174
542
  const environment = inheritedEnvironment({
175
543
  FORGE_RUNTIME_MODE: "host",
176
544
  FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
@@ -183,26 +551,93 @@ async function executeManagedCommand(invocation) {
183
551
  FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
184
552
  FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
185
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
+ : {}),
186
565
  });
566
+ return { environment, exactSecrets };
567
+ }
568
+ async function executeManagedCommandProcess(invocation) {
569
+ let prepared;
570
+ try {
571
+ prepared = await managedCommandProcessEnvironment(invocation);
572
+ }
573
+ catch (error) {
574
+ // The call still fails (the database capability boundary or the verification
575
+ // database probe refused it), but its receipt must not stay "starting" forever.
576
+ const receipt = managedCommandResult({
577
+ ...invocation,
578
+ timedOut: false,
579
+ status: "runner_error",
580
+ exitCode: null,
581
+ stdout: "",
582
+ stderr: appendBounded("", redactText(error instanceof Error ? error.message : String(error), [])),
583
+ launchRequested: false,
584
+ });
585
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent).catch(() => undefined);
586
+ throw error;
587
+ }
588
+ const { exactSecrets } = prepared;
187
589
  let stdout = "";
188
590
  let stderr = "";
189
- const controller = new AbortController();
591
+ const controller = invocation.controller;
190
592
  let timedOut = false;
191
593
  let timer = null;
192
594
  let outputRevision = 0;
193
595
  let lastOutputAt = null;
596
+ let lastOutputStream = null;
194
597
  let lastProgressPersistedAt = 0;
195
598
  let progressPersistence = Promise.resolve();
599
+ let progressHeartbeat = null;
600
+ let progressFinished = false;
601
+ const persistProgress = (force = false) => {
602
+ if (progressFinished)
603
+ return progressPersistence;
604
+ const next = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt, lastOutputStream }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; }, force);
605
+ // A heartbeat write is best-effort: one failed write (a locked or full disk) must
606
+ // not poison the chain, freeze later heartbeats, or fail a command that succeeded.
607
+ progressPersistence = force ? next.catch(() => undefined) : next;
608
+ return progressPersistence;
609
+ };
610
+ // Stop progress writes and let any in flight land before a terminal receipt is
611
+ // written, so a late "running" snapshot can never replace it.
612
+ const settleProgress = async () => {
613
+ progressFinished = true;
614
+ if (progressHeartbeat)
615
+ clearInterval(progressHeartbeat);
616
+ progressHeartbeat = null;
617
+ await progressPersistence;
618
+ };
196
619
  const launchTimer = setTimeout(() => {
197
620
  timedOut = true;
198
621
  controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
199
622
  }, managedCommandLaunchTimeoutMs);
200
623
  try {
624
+ if (controller.signal.aborted)
625
+ throw controller.signal.reason;
626
+ // Recorded before the spawn: the process record is written only once the child has
627
+ // spawned, so teardown must know a launch may exist without one.
628
+ await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
629
+ ...invocation,
630
+ timedOut: false,
631
+ status: "starting",
632
+ exitCode: null,
633
+ stdout,
634
+ stderr,
635
+ }).structuredContent);
201
636
  const result = await new StreamingProviderProcessRunner().run({
202
637
  command: invocation.command,
203
638
  args: invocation.args,
204
639
  cwd: invocation.cwd,
205
- env: environment,
640
+ env: prepared.environment,
206
641
  captureOutput: false,
207
642
  }, {
208
643
  onStarted: async () => {
@@ -216,30 +651,60 @@ async function executeManagedCommand(invocation) {
216
651
  stderr,
217
652
  outputRevision,
218
653
  lastOutputAt,
654
+ lastOutputStream,
219
655
  });
220
656
  await persistManagedCommandReceipt(invocation.receiptPath, running.structuredContent);
221
657
  timer = setTimeout(() => {
222
658
  timedOut = true;
223
659
  controller.abort(new Error(`managed_command_timeout: exceeded ${invocation.timeoutMs}ms.`));
224
660
  }, invocation.timeoutMs);
661
+ // Output alone does not keep the receipt current: a test tier can print a burst
662
+ // and then run quietly for many minutes. Without this heartbeat the elapsed time
663
+ // and the burst's last lines freeze, and a waiting agent sees a hung command.
664
+ // The run can already have failed while the "running" write above was pending.
665
+ if (progressFinished)
666
+ return;
667
+ progressHeartbeat = setInterval(() => {
668
+ void persistProgress(true);
669
+ }, managedCommandProgressPersistIntervalMs);
670
+ progressHeartbeat.unref();
225
671
  },
226
672
  onStdoutLine: (line) => {
227
- stdout = appendBounded(stdout, line);
673
+ stdout = appendBounded(stdout, redactText(line, exactSecrets));
228
674
  outputRevision += 1;
229
675
  lastOutputAt = Date.now();
230
- progressPersistence = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; });
231
- return progressPersistence;
676
+ lastOutputStream = "stdout";
677
+ return persistProgress();
232
678
  },
233
679
  onStderrLine: (line) => {
234
- stderr = appendBounded(stderr, line);
680
+ stderr = appendBounded(stderr, redactText(line, exactSecrets));
235
681
  outputRevision += 1;
236
682
  lastOutputAt = Date.now();
237
- progressPersistence = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; });
238
- return progressPersistence;
683
+ lastOutputStream = "stderr";
684
+ return persistProgress();
239
685
  },
240
686
  }, controller.signal);
241
- await progressPersistence;
242
- const status = timedOut ? "timed_out" : result.exitCode === 0 ? "pass" : "fail";
687
+ await settleProgress();
688
+ // Only a stop that interrupted the process relabels it. A command that exited on its own
689
+ // just before its owner asked for the stop keeps its real result.
690
+ const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
691
+ if (ownerExited) {
692
+ stderr = appendBounded(stderr, managedCommandOwnerExitMessage);
693
+ outputRevision += 1;
694
+ lastOutputAt = Date.now();
695
+ lastOutputStream = "stderr";
696
+ }
697
+ const status = timedOut ? "timed_out" : ownerExited ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
698
+ const receiptCoverage = managedBuildReceiptCoverage(invocation);
699
+ const buildReceipt = status === "pass" && receiptCoverage
700
+ ? await publishManagedBuildReceipt({
701
+ worktreePath: invocation.worktreePath,
702
+ command: invocation.command,
703
+ args: invocation.args,
704
+ configuration: managedBuildConfiguration(invocation.command, invocation.args),
705
+ coverage: receiptCoverage,
706
+ })
707
+ : invocation.buildReceiptReuse;
243
708
  const receipt = managedCommandResult({
244
709
  ...invocation,
245
710
  timedOut,
@@ -249,13 +714,27 @@ async function executeManagedCommand(invocation) {
249
714
  stderr,
250
715
  outputRevision,
251
716
  lastOutputAt,
717
+ lastOutputStream,
718
+ buildReceipt,
719
+ buildReceiptReused: invocation.buildReceiptReuse !== undefined,
720
+ terminationReason: ownerExited ? "owner_exited" : undefined,
721
+ // The runner resolves only after the stopped tree is proven gone.
722
+ processTreeTerminated: ownerExited ? true : undefined,
252
723
  });
253
724
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
254
- return receipt;
725
+ return managedCommandPublicResult(receipt);
255
726
  }
256
727
  catch (error) {
257
- const message = error instanceof Error ? error.message : String(error);
728
+ // The failure may be a progress write itself; it is reported below.
729
+ await settleProgress().catch(() => undefined);
730
+ const ownerExited = !timedOut && ownerExitStoppedCommands.has(invocation.commandId);
731
+ const message = ownerExited
732
+ ? managedCommandOwnerExitMessage
733
+ : redactText(error instanceof Error ? error.message : String(error), exactSecrets);
258
734
  stderr = appendBounded(stderr, message);
735
+ outputRevision += 1;
736
+ lastOutputAt = Date.now();
737
+ lastOutputStream = "stderr";
259
738
  const receipt = managedCommandResult({
260
739
  ...invocation,
261
740
  timedOut,
@@ -265,14 +744,20 @@ async function executeManagedCommand(invocation) {
265
744
  stderr,
266
745
  outputRevision,
267
746
  lastOutputAt,
747
+ lastOutputStream,
748
+ terminationReason: ownerExited ? "owner_exited" : undefined,
749
+ // The runner rejected, so its tree was not proven stopped; teardown still stops it.
750
+ processTreeTerminated: false,
268
751
  });
269
752
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
270
- return receipt;
753
+ return managedCommandPublicResult(receipt);
271
754
  }
272
755
  finally {
273
756
  clearTimeout(launchTimer);
274
757
  if (timer)
275
758
  clearTimeout(timer);
759
+ if (progressHeartbeat)
760
+ clearInterval(progressHeartbeat);
276
761
  }
277
762
  }
278
763
  async function readManagedCommand(input) {
@@ -291,7 +776,7 @@ async function readManagedCommand(input) {
291
776
  const status = typeof receipt.status === "string" ? receipt.status : "unknown";
292
777
  const stdout = typeof receipt.stdout === "string" ? receipt.stdout : "";
293
778
  const stderr = typeof receipt.stderr === "string" ? receipt.stderr : "";
294
- return {
779
+ return managedCommandPublicResult({
295
780
  content: [{
296
781
  type: "text",
297
782
  text: terminalManagedCommandStatuses.has(status)
@@ -307,13 +792,14 @@ async function readManagedCommand(input) {
307
792
  }],
308
793
  structuredContent: receipt,
309
794
  isError: terminalManagedCommandStatuses.has(status) && status !== "pass",
310
- };
795
+ });
311
796
  }
312
797
  async function waitManagedCommand(input) {
313
798
  const record = asRecord(input);
314
799
  const commandId = validatedCommandId(record);
315
- const waitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
316
- const deadline = Date.now() + waitTimeoutMs;
800
+ const requestedWaitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
801
+ const waitTimeoutMs = Math.min(requestedWaitTimeoutMs, maximumSynchronousWaitMs);
802
+ const deadline = monotonicNowMs() + waitTimeoutMs;
317
803
  const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
318
804
  const task = managedCommandTasks.get(commandId);
319
805
  if (task) {
@@ -324,20 +810,43 @@ async function waitManagedCommand(input) {
324
810
  if (result)
325
811
  return result;
326
812
  }
327
- while (Date.now() < deadline) {
813
+ while (monotonicNowMs() < deadline) {
328
814
  const result = await readManagedCommand({ command_id: commandId });
329
815
  if (terminalManagedCommandStatuses.has(String(result.structuredContent.status))) {
330
816
  return result;
331
817
  }
332
- await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - Date.now())));
818
+ await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - monotonicNowMs())));
333
819
  }
334
820
  const receipt = await readManagedCommand({ command_id: commandId });
821
+ // Only a running receipt is refreshed on a heartbeat; queued or starting receipts are
822
+ // written once, so their elapsed time says nothing about progress.
823
+ const elapsedMs = receipt.structuredContent.elapsed_ms;
824
+ const timeoutMs = receipt.structuredContent.timeout_ms;
825
+ 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
+ : "";
335
835
  return {
336
836
  ...receipt,
337
837
  content: [{
338
838
  type: "text",
339
- text: `Forge is still supervising managed command ${commandId} after waiting ${waitTimeoutMs}ms. Its durable receipt remains at ${receiptPath}.`,
839
+ text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Do not end your turn to wait for it: Forge ends the provider run shortly after a turn ends, which stops background monitors and this command. Its durable receipt remains at ${receiptPath}.`,
340
840
  }],
841
+ structuredContent: {
842
+ ...receipt.structuredContent,
843
+ command_continues: true,
844
+ terminal: false,
845
+ wait_timeout_ms: waitTimeoutMs,
846
+ requested_wait_timeout_ms: requestedWaitTimeoutMs,
847
+ retry_after_ms: managedCommandRetryAfterMs,
848
+ },
849
+ isError: false,
341
850
  };
342
851
  }
343
852
  function managedCommandReceiptPath(logDirectory, commandId) {
@@ -403,16 +912,81 @@ function managedCommandResult(values) {
403
912
  || values.stderr.length >= maximumCapturedCharacters,
404
913
  output_revision: values.outputRevision ?? 0,
405
914
  last_output_at: values.lastOutputAt ? new Date(values.lastOutputAt).toISOString() : null,
915
+ last_output_stream: values.lastOutputStream ?? null,
406
916
  supervisor_metadata_path: values.metadataPath,
407
917
  receipt_path: values.receiptPath,
408
- process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : undefined,
918
+ verification_profile: values.verificationProfile ?? null,
919
+ verification_profile_runner_authored: values.verificationProfile !== undefined,
920
+ build_producing: values.buildProducing,
921
+ build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
922
+ build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
923
+ build_receipt_reused: values.buildReceiptReused ?? false,
924
+ build_receipt: values.buildReceipt ? {
925
+ fingerprint: values.buildReceipt.fingerprint,
926
+ receipt_path: values.buildReceipt.receiptPath,
927
+ producer_command: values.buildReceipt.producerCommand,
928
+ configuration: values.buildReceipt.configuration,
929
+ coverage: values.buildReceipt.coverage,
930
+ output_count: values.buildReceipt.outputCount,
931
+ } : null,
932
+ runtime_configuration: managedRuntimeConfiguration(),
933
+ // The supervising MCP server process. Forge stops a command whose owner has exited.
934
+ owner_pid: process.pid,
935
+ owner_identity: managedCommandOwnerIdentity(),
936
+ launch_requested: values.launchRequested ?? true,
937
+ process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : values.processTreeTerminated,
938
+ ...(values.terminationReason ? { termination_reason: values.terminationReason } : {}),
409
939
  },
410
940
  isError: isTerminal && values.status !== "pass",
411
941
  };
412
942
  }
413
- function persistManagedCommandProgressIfDue(invocation, snapshot, previousPersistence, lastPersistedAt, setLastPersistedAt) {
943
+ /** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
944
+ function managedCommandOwnerIdentity() {
945
+ // Windows identity capture starts PowerShell; the PID check alone is used there.
946
+ ownerProcessIdentity ??= process.platform === "linux" ? captureHostProcessIdentity(process.pid) : null;
947
+ return ownerProcessIdentity;
948
+ }
949
+ function managedRuntimeConfiguration() {
950
+ const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
951
+ let providerOnlySpecCount = 0;
952
+ if (providerOnlySpecs) {
953
+ try {
954
+ const parsed = JSON.parse(providerOnlySpecs);
955
+ providerOnlySpecCount = Array.isArray(parsed)
956
+ ? parsed.filter(value => typeof value === "string" && value.length > 0).length
957
+ : 0;
958
+ }
959
+ catch {
960
+ providerOnlySpecCount = 0;
961
+ }
962
+ }
963
+ return {
964
+ attempt_database_schema: process.env.FORGE_ATTEMPT_DATABASE_SCHEMA ?? null,
965
+ attempt_database_readiness_path: process.env.FORGE_ATTEMPT_DATABASE_READINESS_PATH ?? null,
966
+ playwright_config: process.env.FORGE_PLAYWRIGHT_CONFIG ?? null,
967
+ provider_only_spec_count: providerOnlySpecCount,
968
+ provider_only_spec_fingerprint: providerOnlySpecs
969
+ ? `sha256:${createHash("sha256").update(providerOnlySpecs).digest("hex")}`
970
+ : null,
971
+ };
972
+ }
973
+ function managedCommandPublicResult(result) {
974
+ const stdout = typeof result.structuredContent.stdout === "string" ? result.structuredContent.stdout : "";
975
+ const stderr = typeof result.structuredContent.stderr === "string" ? result.structuredContent.stderr : "";
976
+ const { stdout: _stdout, stderr: _stderr, ...receipt } = result.structuredContent;
977
+ return {
978
+ ...result,
979
+ structuredContent: {
980
+ ...receipt,
981
+ stdout_tail: tail(stdout, maximumReturnedOutputCharacters),
982
+ stderr_tail: tail(stderr, maximumReturnedOutputCharacters),
983
+ full_output_in_receipt: true,
984
+ },
985
+ };
986
+ }
987
+ function persistManagedCommandProgressIfDue(invocation, snapshot, previousPersistence, lastPersistedAt, setLastPersistedAt, force = false) {
414
988
  const now = Date.now();
415
- if (now - lastPersistedAt() < managedCommandProgressPersistIntervalMs)
989
+ if (!force && now - lastPersistedAt() < managedCommandProgressPersistIntervalMs)
416
990
  return previousPersistence;
417
991
  setLastPersistedAt(now);
418
992
  const current = snapshot();
@@ -447,12 +1021,75 @@ function inheritedEnvironment(overrides) {
447
1021
  }
448
1022
  return { ...env, ...overrides };
449
1023
  }
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
+ export function isBuildProducingManagedCommand(command, args) {
1039
+ const executable = path.basename(command).toLowerCase();
1040
+ if (executable === "dotnet" || executable === "dotnet.exe") {
1041
+ const verb = args.find(argument => !argument.startsWith("-"))?.toLowerCase();
1042
+ if (!verb || !new Set(["build", "test", "restore", "publish", "pack", "msbuild"]).has(verb))
1043
+ return false;
1044
+ return verb === "restore" || !args.some(argument => argument.toLowerCase() === "--no-build");
1045
+ }
1046
+ if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1047
+ const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
1048
+ const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
1049
+ if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
1050
+ return !args.some(argument => argument.toLowerCase() === "-nobuild");
1051
+ }
1052
+ if (script === "run-dotnet-test-tier.ps1") {
1053
+ return !args.some(argument => argument.toLowerCase() === "-nobuild");
1054
+ }
1055
+ }
1056
+ return false;
1057
+ }
1058
+ function managedBuildReceiptCoverage(invocation) {
1059
+ if (!invocation.buildProducing)
1060
+ return null;
1061
+ if (invocation.verificationProfile)
1062
+ return managedVerificationBuildCoverage;
1063
+ const executable = path.basename(invocation.command).toLowerCase();
1064
+ if (executable === "dotnet" || executable === "dotnet.exe") {
1065
+ const verb = invocation.args.find(argument => !argument.startsWith("-"))?.toLowerCase();
1066
+ if (!verb || !new Set(["build", "test"]).has(verb))
1067
+ return null;
1068
+ const target = invocation.args.find(argument => /\.(?:sln|slnx|csproj)$/iu.test(argument));
1069
+ if (target && (/\.(?:sln|slnx)$/iu.test(target) || /(?:^|[\\/])Forge\.Api\.Tests\.csproj$/iu.test(target))) {
1070
+ return managedVerificationBuildCoverage;
1071
+ }
1072
+ return null;
1073
+ }
1074
+ if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1075
+ const fileIndex = invocation.args.findIndex(argument => argument.toLowerCase() === "-file");
1076
+ const script = fileIndex >= 0 ? path.basename(invocation.args[fileIndex + 1] ?? "").toLowerCase() : "";
1077
+ if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)
1078
+ && !invocation.args.some(argument => argument.toLowerCase() === "-nobuild")) {
1079
+ return managedVerificationBuildCoverage;
1080
+ }
1081
+ }
1082
+ return null;
1083
+ }
450
1084
  function looksSensitiveEnvironmentName(name) {
451
1085
  const normalized = name.trim().toUpperCase();
452
1086
  return normalized.includes("SECRET")
453
1087
  || normalized.includes("TOKEN")
454
1088
  || normalized.includes("PASSWORD")
455
1089
  || normalized.includes("CREDENTIAL")
1090
+ || normalized.includes("CONNECTION_STRING")
1091
+ || normalized.startsWith("CONNECTIONSTRINGS__")
1092
+ || normalized.startsWith("CONNECTIONSTRINGS:")
456
1093
  || normalized.endsWith("_API_KEY")
457
1094
  || normalized === "OPENAI_API_KEY";
458
1095
  }
@@ -499,12 +1136,27 @@ function optionalTimeout(value) {
499
1136
  }
500
1137
  function optionalWaitTimeout(value) {
501
1138
  if (value === undefined)
502
- return 7_200_000;
503
- if (!Number.isSafeInteger(value) || value < 1_000 || value > 7_200_000) {
504
- throw new Error("managed_command_invalid: wait_timeout_ms must be an integer from 1000 through 7200000.");
1139
+ return maximumSynchronousWaitMs;
1140
+ if (!Number.isSafeInteger(value) || value < 1_000 || value > maximumSynchronousWaitMs) {
1141
+ throw new Error(`managed_command_invalid: wait_timeout_ms must be an integer from 1000 through ${maximumSynchronousWaitMs}.`);
1142
+ }
1143
+ return value;
1144
+ }
1145
+ function optionalBoundedInteger(value, name, minimum, maximum, fallback) {
1146
+ if (value === undefined)
1147
+ return fallback;
1148
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
1149
+ throw new Error(`managed_verification_invalid: ${name} must be an integer from ${minimum} through ${maximum}.`);
505
1150
  }
506
1151
  return value;
507
1152
  }
1153
+ function optionalBoolean(value, name, fallback) {
1154
+ if (value === undefined)
1155
+ return fallback;
1156
+ if (typeof value !== "boolean")
1157
+ throw new Error(`managed_verification_invalid: ${name} must be a boolean.`);
1158
+ return value;
1159
+ }
508
1160
  async function delay(ms) {
509
1161
  await new Promise(resolve => setTimeout(resolve, ms));
510
1162
  }