@loucompanion/forge-bridge 0.1.4-dev.8901ba056f68 → 0.1.4-dev.894bcbd53d64

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 (225) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +87 -14
  16. package/dist/bridge/bridge.service.js +394 -338
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +20 -1
  31. package/dist/cleanup/cleanup.service.js +150 -169
  32. package/dist/cleanup/cleanup.types.d.ts +6 -0
  33. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  34. package/dist/cleanup/forge-owned-paths.js +53 -0
  35. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  36. package/dist/cleanup/host-runtime-ledger.js +130 -0
  37. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  38. package/dist/cleanup/managed-branch-sweep.js +111 -0
  39. package/dist/cli/cli.help.js +74 -12
  40. package/dist/cli/cli.service.d.ts +19 -10
  41. package/dist/cli/cli.service.js +149 -186
  42. package/dist/cli/idle-status.d.ts +84 -0
  43. package/dist/cli/idle-status.js +181 -0
  44. package/dist/cli/local-config.d.ts +6 -0
  45. package/dist/cli/local-config.js +32 -4
  46. package/dist/cli/provider-cli-detection.d.ts +10 -0
  47. package/dist/cli/provider-cli-detection.js +160 -0
  48. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  49. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  50. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  51. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  52. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  53. package/dist/runtime/attempt-process-supervisor.js +12 -6
  54. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  55. package/dist/runtime/docker-engine-probe.js +7 -0
  56. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  57. package/dist/runtime/dotnet-build-outputs.js +402 -0
  58. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  59. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  60. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  61. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  62. package/dist/runtime/host-facts.d.ts +2 -1
  63. package/dist/runtime/host-load-admission.d.ts +18 -3
  64. package/dist/runtime/host-load-admission.js +19 -4
  65. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  66. package/dist/runtime/host-load-child-environment.js +22 -11
  67. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  68. package/dist/runtime/host-load-governor-config.js +37 -0
  69. package/dist/runtime/host-load-governor.d.ts +14 -0
  70. package/dist/runtime/host-load-governor.js +139 -26
  71. package/dist/runtime/host-load-ledger-lock.js +6 -4
  72. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  73. package/dist/runtime/host-load-runtime-settings.js +80 -0
  74. package/dist/runtime/host-load-sampler.d.ts +34 -4
  75. package/dist/runtime/host-load-sampler.js +73 -7
  76. package/dist/runtime/host-load-step-class.d.ts +3 -1
  77. package/dist/runtime/host-load-step-class.js +60 -5
  78. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  79. package/dist/runtime/host-load-test-slot.js +81 -0
  80. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  81. package/dist/runtime/host-load-token-ledger.js +93 -61
  82. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  83. package/dist/runtime/host-load-windows-cpu.js +85 -0
  84. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  85. package/dist/runtime/host-runtime-contract.js +29 -1
  86. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  87. package/dist/runtime/host-runtime-lease.js +212 -61
  88. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  89. package/dist/runtime/host-runtime-promotion.js +36 -0
  90. package/dist/runtime/managed-command-teardown.js +5 -16
  91. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  92. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  93. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  94. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  95. package/dist/runtime/runner-settings.d.ts +104 -0
  96. package/dist/runtime/runner-settings.js +236 -0
  97. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  98. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  99. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  100. package/dist/sandbox/host-capacity-broker.js +27 -6
  101. package/dist/sandbox/managed-branch.d.ts +13 -0
  102. package/dist/sandbox/managed-branch.js +90 -0
  103. package/dist/sandbox/provider-auth/codex.js +11 -11
  104. package/dist/sandbox/runtime.js +2 -6
  105. package/dist/session/architect-waits.d.ts +2 -0
  106. package/dist/session/architect-waits.js +138 -0
  107. package/dist/session/managed-attempt-tools.d.ts +2 -7
  108. package/dist/session/managed-attempt-tools.js +94 -104
  109. package/dist/session/managed-build-coordinator.d.ts +16 -0
  110. package/dist/session/managed-build-coordinator.js +10 -0
  111. package/dist/session/managed-build-receipt.d.ts +5 -0
  112. package/dist/session/managed-build-receipt.js +8 -3
  113. package/dist/session/managed-command-host-load.d.ts +2 -0
  114. package/dist/session/managed-command-host-load.js +2 -1
  115. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  116. package/dist/session/mcp-argument-coercion.js +121 -0
  117. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  118. package/dist/session/phase-completion.artifacts.js +96 -26
  119. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  120. package/dist/session/phase-completion.command-validation.js +77 -0
  121. package/dist/session/phase-completion.d.ts +10 -0
  122. package/dist/session/phase-completion.helpers.js +13 -12
  123. package/dist/session/phase-completion.js +5 -0
  124. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  125. package/dist/session/phase-completion.mcp-args.js +156 -0
  126. package/dist/session/phase-completion.prompts.js +6 -1
  127. package/dist/session/phase-completion.runtime.d.ts +4 -10
  128. package/dist/session/phase-completion.runtime.js +77 -209
  129. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  130. package/dist/session/phase-completion.schema-parts.js +188 -0
  131. package/dist/session/phase-completion.schemas.d.ts +3 -3
  132. package/dist/session/phase-completion.schemas.js +208 -231
  133. package/dist/session/phase-completion.validation.d.ts +2 -3
  134. package/dist/session/phase-completion.validation.js +49 -93
  135. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  136. package/dist/session/pre-publication-native-postgres.js +111 -0
  137. package/dist/session/pre-publication-pass.d.ts +61 -0
  138. package/dist/session/pre-publication-pass.js +148 -0
  139. package/dist/session/pre-publication-process.js +10 -10
  140. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  141. package/dist/session/pre-publication-step-execution.js +6 -5
  142. package/dist/session/pre-publication-validation.d.ts +30 -14
  143. package/dist/session/pre-publication-validation.js +207 -134
  144. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  145. package/dist/session/provider-cli/claude-background-work.js +181 -0
  146. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  147. package/dist/session/provider-cli/host-build-lock.js +30 -0
  148. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  149. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  150. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  151. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  152. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  153. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  154. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  155. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  156. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  157. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  158. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  159. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  160. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  161. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  162. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  163. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  164. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  165. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  166. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  167. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  168. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  169. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  170. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  171. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  172. package/dist/session/provider-cli/provider-output-state.js +6 -0
  173. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  174. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  175. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  176. package/dist/session/qa-sidecar-validation.js +28 -0
  177. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  178. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  179. package/dist/session/session-redaction.js +31 -181
  180. package/dist/session/session.base.d.ts +6 -1
  181. package/dist/session/session.service.d.ts +9 -2
  182. package/dist/session/session.service.js +169 -66
  183. package/dist/session/session.types.js +4 -4
  184. package/dist/session/sidecar-json-shape.d.ts +31 -0
  185. package/dist/session/sidecar-json-shape.js +217 -0
  186. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  187. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  188. package/dist/shared/fs/file-identity.d.ts +10 -0
  189. package/dist/shared/fs/file-identity.js +15 -0
  190. package/dist/shared/fs/replace-file.d.ts +7 -0
  191. package/dist/shared/fs/replace-file.js +33 -0
  192. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  193. package/dist/shared/process/host-process-recovery.js +23 -3
  194. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  195. package/dist/shared/process/host-process-supervisor.js +66 -14
  196. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  197. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  198. package/dist/shared/process/windows-launch.d.ts +18 -0
  199. package/dist/shared/process/windows-launch.js +68 -0
  200. package/dist/shared/provider-capabilities.js +14 -7
  201. package/dist/version.d.ts +1 -1
  202. package/dist/version.js +1 -1
  203. package/dist/worktree/orphan-relink.d.ts +19 -0
  204. package/dist/worktree/orphan-relink.js +106 -0
  205. package/dist/worktree/wip-git.d.ts +33 -0
  206. package/dist/worktree/wip-git.js +122 -0
  207. package/dist/worktree/wip-refs.d.ts +62 -0
  208. package/dist/worktree/wip-refs.js +119 -0
  209. package/dist/worktree/wip-restore.d.ts +38 -0
  210. package/dist/worktree/wip-restore.js +190 -0
  211. package/dist/worktree/wip-snapshot.d.ts +50 -0
  212. package/dist/worktree/wip-snapshot.js +268 -0
  213. package/dist/worktree/worktree-inputs.d.ts +8 -0
  214. package/dist/worktree/worktree-inputs.js +134 -0
  215. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  216. package/dist/worktree/worktree-origin-sync.js +127 -0
  217. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  218. package/dist/worktree/worktree-wip-events.js +98 -0
  219. package/dist/worktree/worktree-wip.d.ts +50 -0
  220. package/dist/worktree/worktree-wip.js +185 -0
  221. package/dist/worktree/worktree.base.d.ts +7 -1
  222. package/dist/worktree/worktree.service.d.ts +31 -5
  223. package/dist/worktree/worktree.service.js +120 -163
  224. package/dist/worktree/worktree.types.d.ts +31 -0
  225. package/package.json +2 -2
@@ -3,18 +3,18 @@ import fs from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
6
- import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
7
6
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
8
7
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
9
- import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
8
+ import { managedVerificationDatabase, noManagedVerificationDatabase, releaseManagedVerificationDatabase, setUpWithManagedVerificationDatabase } from "../runtime/ephemeral-test-postgres-grant.js";
10
9
  import { redactText } from "../shared/redaction/redaction.js";
11
- import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
10
+ import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
11
+ import { assertManagedBuildSparesSupervisedRuntimes, ManagedBuildCoordinator } from "./managed-build-coordinator.js";
12
12
  import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
13
13
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
14
14
  import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
15
15
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
16
- import { hostLoadGovernorEnvironment, hostLoadStateRootEnvironment } from "../runtime/host-load-child-environment.js";
17
- import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
16
+ import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
17
+ import { managedBuildConfiguration, persistJsonAtomically, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
18
18
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
19
19
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
20
20
  import { monotonicNowMs } from "../shared/time/monotonic.js";
@@ -37,8 +37,6 @@ const managedCommandRetryAfterMs = 60_000;
37
37
  const managedCommandLaunchTimeoutMs = 60_000;
38
38
  const managedCommandProgressPersistIntervalMs = 5_000;
39
39
  const managedCommandReceiptPollIntervalMs = 1_000;
40
- const managedCommandReceiptReplaceAttempts = 40;
41
- const managedCommandReceiptReplaceRetryMs = 25;
42
40
  const terminalManagedCommandStatuses = new Set([
43
41
  "pass",
44
42
  "fail",
@@ -148,11 +146,17 @@ export function isManagedAttemptTool(name) {
148
146
  || startManagedVerificationNames.has(name)
149
147
  || resetGeneratedOutputNames.has(name);
150
148
  }
149
+ const managedVerificationProfiles = ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"];
150
+ const managedVerificationProfileHint = `Use one of: ${managedVerificationProfiles.join(", ")}. These are .NET test profiles only; run client, bridge, or Playwright e2e checks with forge.start_managed_command.`;
151
+ /** The input schema a managed-attempt tool advertises; also the shape its arguments are coerced to. */
152
+ export function managedAttemptToolInputSchema(name) {
153
+ return managedAttemptToolDefinition(name).inputSchema;
154
+ }
151
155
  export function managedAttemptToolDefinition(name) {
152
156
  if (startManagedVerificationNames.has(name)) {
153
157
  return {
154
158
  name,
155
- description: "Start a canonical Forge verification profile with runner-owned cwd, arguments, attempt output, timeout, and process supervision. Prefer this over reconstructing broad .NET commands. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt.",
159
+ description: "Start a canonical Forge .NET verification profile with runner-owned cwd, arguments, attempt output, timeout, and process supervision. Prefer this over reconstructing broad .NET commands. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt. To run every shard of a tier in one call, set run_all_shards: true with shard_count 2 or more and without no_build.",
156
160
  inputSchema: {
157
161
  type: "object",
158
162
  additionalProperties: false,
@@ -160,13 +164,14 @@ export function managedAttemptToolDefinition(name) {
160
164
  properties: {
161
165
  profile: {
162
166
  type: "string",
163
- enum: ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"],
167
+ enum: [...managedVerificationProfiles],
168
+ description: "Required .NET test profile. dotnet_affected selects its own tests and owns its build: it takes no shard or no_build options. dotnet_solution takes no shard options. Client, bridge, and e2e checks are not profiles; use forge.start_managed_command for them.",
164
169
  },
165
- shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1 },
166
- shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0 },
167
- run_all_shards: { type: "boolean", default: false },
170
+ shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1, description: "Number of shards to split the tier into. Must be at least 2 when run_all_shards is true." },
171
+ shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0, description: "Which single shard to run; must be less than shard_count, and 0 when run_all_shards is true." },
172
+ run_all_shards: { type: "boolean", default: false, description: "Run every shard of the tier after one shared build. Requires shard_count of at least 2 and shard_index 0, cannot be combined with no_build, and is not supported for dotnet_solution or dotnet_affected." },
168
173
  max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
169
- no_build: { type: "boolean", default: false },
174
+ no_build: { type: "boolean", default: false, description: "Reuse the verified build from an earlier managed build instead of building. Not allowed with run_all_shards or dotnet_affected." },
170
175
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
171
176
  },
172
177
  },
@@ -183,8 +188,8 @@ export function managedAttemptToolDefinition(name) {
183
188
  additionalProperties: false,
184
189
  required: ["command", "args"],
185
190
  properties: {
186
- command: { type: "string", minLength: 1 },
187
- args: { type: "array", items: { type: "string" } },
191
+ command: { type: "string", minLength: 1, description: "Required executable only, for example pnpm, node, npm, or dotnet. Not a shell command line: shell syntax such as cd, &&, or pipes is not interpreted." },
192
+ args: { type: "array", items: { type: "string" }, description: "Required argument list, each argument its own string, for example [\"--dir\", \"client\", \"lint\"]. Send [] when there are none. Use cwd instead of cd." },
188
193
  cwd: { type: "string", description: "Worktree-relative directory; defaults to the worktree root." },
189
194
  timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 2700000 },
190
195
  },
@@ -287,6 +292,9 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
287
292
  buildReceiptReuse,
288
293
  controller: new AbortController(),
289
294
  };
295
+ // A build aimed at the output a running supervised runtime executes from fails here, naming
296
+ // that runtime, instead of failing on its locked files after the build-slot and capacity waits.
297
+ await assertManagedBuildSparesSupervisedRuntimes(invocation);
290
298
  if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
291
299
  const started = managedCommandResult({
292
300
  ...invocation,
@@ -347,13 +355,13 @@ async function startManagedVerification(input, worktreePath) {
347
355
  const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
348
356
  const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
349
357
  if (runAllShards && shardCount < 2) {
350
- 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.");
351
359
  }
352
360
  if (runAllShards && shardIndex !== 0) {
353
361
  throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
354
362
  }
355
363
  if (runAllShards && noBuild) {
356
- 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.");
357
365
  }
358
366
  const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
359
367
  const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
@@ -410,7 +418,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
410
418
  };
411
419
  const tier = tiers[profile];
412
420
  if (!tier)
413
- throw new Error(`managed_verification_invalid: unsupported profile ${profile}.`);
421
+ throw new Error(`managed_verification_invalid: unsupported profile ${profile}. ${managedVerificationProfileHint}`);
414
422
  const command = preferredPowerShellExecutable();
415
423
  if (runAllShards) {
416
424
  return {
@@ -439,7 +447,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
439
447
  export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
440
448
  if (platform !== "win32")
441
449
  return "pwsh";
442
- return resolveWindowsCommandFromPath("pwsh.exe", pathValue) ?? "powershell.exe";
450
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
443
451
  }
444
452
  export function validatePlaywrightProjectName(project, availableProjects) {
445
453
  if (!availableProjects.includes(project)) {
@@ -586,41 +594,48 @@ async function executeManagedCommand(invocation) {
586
594
  return managedCommandPublicResult(receipt);
587
595
  }
588
596
  }
597
+ /** A command's environment and redaction list; a setup that throws releases the database it started. */
589
598
  async function managedCommandProcessEnvironment(invocation) {
590
599
  assertHostDatabaseCapabilityBoundary();
591
- const databaseEnvironment = invocation.verificationProfile
592
- ? await managedVerificationDatabaseEnvironment()
593
- : {};
594
- const exactSecrets = [
595
- ...Object.values(databaseEnvironment).filter(value => value !== nativeTestPostgresFallbackDatabaseMode),
596
- // The attempt's brokered database login reaches managed commands; their output never shows it.
597
- ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
598
- ];
599
- const environment = inheritedEnvironment({
600
- FORGE_RUNTIME_MODE: "host",
601
- FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
602
- FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
603
- // This nested command owns a distinct supervisor identity. A command-local
604
- // fence avoids exposing the parent attempt's fencing capability to Codex's
605
- // MCP subprocess configuration while preserving exact-tree cleanup proof.
606
- FORGE_FENCING_TOKEN: randomUUID(),
607
- FORGE_LOG_DIR: invocation.logDirectory,
608
- FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
609
- FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
610
- FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
611
- ...(invocation.verificationProfile
612
- ? {
613
- FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
614
- // Managed verification executes mutable worktree scripts, SDK targets,
615
- // and test assemblies. It uses an attempt-owned container, or the
616
- // dedicated native test cluster while Docker is unavailable; it never
617
- // receives a capability for a server that holds real data.
618
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
619
- ...databaseEnvironment,
620
- }
621
- : {}),
600
+ const database = invocation.verificationProfile ? await managedVerificationDatabase() : noManagedVerificationDatabase;
601
+ return await setUpWithManagedVerificationDatabase(database, () => {
602
+ const exactSecrets = [
603
+ ...database.secrets,
604
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
605
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
+ ];
607
+ const environment = inheritedEnvironment({
608
+ FORGE_RUNTIME_MODE: "host",
609
+ FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
610
+ FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
611
+ // This nested command owns a distinct supervisor identity. A command-local
612
+ // fence avoids exposing the parent attempt's fencing capability to Codex's
613
+ // MCP subprocess configuration while preserving exact-tree cleanup proof.
614
+ FORGE_FENCING_TOKEN: randomUUID(),
615
+ FORGE_LOG_DIR: invocation.logDirectory,
616
+ FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
617
+ FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
618
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
619
+ ...(invocation.verificationProfile
620
+ ? {
621
+ FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
622
+ // Managed verification executes mutable worktree scripts, SDK targets,
623
+ // and test assemblies. It uses an attempt-owned container, or the
624
+ // dedicated native test cluster while Docker is unavailable; it never
625
+ // receives a capability for a server that holds real data.
626
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
627
+ ...database.environment,
628
+ }
629
+ : {}),
630
+ });
631
+ return { environment, exactSecrets, release: database.release };
622
632
  });
623
- return { environment, exactSecrets };
633
+ }
634
+ function clearManagedCommandTimers(...timers) {
635
+ // clearTimeout and clearInterval share one timer table.
636
+ for (const timer of timers)
637
+ if (timer)
638
+ clearTimeout(timer);
624
639
  }
625
640
  async function executeManagedCommandProcess(invocation) {
626
641
  let prepared;
@@ -822,11 +837,9 @@ async function executeManagedCommandProcess(invocation) {
822
837
  return managedCommandPublicResult(receipt);
823
838
  }
824
839
  finally {
825
- clearTimeout(launchTimer);
826
- if (timer)
827
- clearTimeout(timer);
828
- if (progressHeartbeat)
829
- clearInterval(progressHeartbeat);
840
+ clearManagedCommandTimers(launchTimer, timer, progressHeartbeat);
841
+ // An ephemeral verification cluster lives exactly as long as its command; one that would not stop is reaped later and named in the receipt.
842
+ await releaseManagedVerificationDatabase(prepared, async (message) => await annotateManagedCommandReceipt(invocation.receiptPath, { ephemeral_cluster_release_error: redactText(message, exactSecrets) }));
830
843
  }
831
844
  }
832
845
  async function readManagedCommand(input) {
@@ -899,7 +912,7 @@ async function waitManagedCommand(input) {
899
912
  const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
900
913
  const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
901
914
  const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
902
- ? ` 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.`
915
+ ? ` It has waited ${Math.round(hostLoadWaitMs / 1000)}s for host capacity${typeof receipt.structuredContent.host_load_wait_detail === "string" ? ` (${receipt.structuredContent.host_load_wait_detail})` : ""} and has not started yet; its timeout starts only once it is admitted, so queue time never counts against it. Keep waiting; a queued command is not a blocker.`
903
916
  : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
904
917
  ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
905
918
  + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
@@ -930,27 +943,7 @@ function managedCommandReceiptPath(logDirectory, commandId) {
930
943
  return path.join(logDirectory, "managed-commands", `${commandId}.receipt.json`);
931
944
  }
932
945
  async function persistManagedCommandReceipt(receiptPath, receipt) {
933
- const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
934
- await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
935
- try {
936
- for (let attempt = 1;; attempt += 1) {
937
- try {
938
- await fs.rename(temporaryPath, receiptPath);
939
- break;
940
- }
941
- catch (error) {
942
- const code = error.code;
943
- if (attempt >= managedCommandReceiptReplaceAttempts
944
- || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES")) {
945
- throw error;
946
- }
947
- await delay(managedCommandReceiptReplaceRetryMs);
948
- }
949
- }
950
- }
951
- finally {
952
- await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
953
- }
946
+ await persistJsonAtomically(receiptPath, receipt);
954
947
  }
955
948
  function managedCommandResult(values) {
956
949
  // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
@@ -1025,7 +1018,7 @@ function managedCommandHostLoadReceipt(hostLoad) {
1025
1018
  return {
1026
1019
  host_load_step_class: hostLoad.stepClass,
1027
1020
  host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
1028
- ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString() } : {}),
1021
+ ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString(), host_load_wait_detail: hostLoad.waitDetail ?? null } : {}),
1029
1022
  };
1030
1023
  }
1031
1024
  async function annotateManagedCommandReceipt(receiptPath, fields) {
@@ -1107,30 +1100,15 @@ async function containedWorkingDirectory(worktreePath, input) {
1107
1100
  }
1108
1101
  function inheritedEnvironment(overrides) {
1109
1102
  const env = {};
1110
- for (const [key, value] of Object.entries(process.env)) {
1111
- // A nested Forge process must not join the host ledger: it would queue behind the
1112
- // token this command already holds.
1113
- if (key === hostLoadGovernorEnvironment || key === hostLoadStateRootEnvironment)
1114
- continue;
1103
+ // A nested Forge process must not join the host ledger: it would queue behind the
1104
+ // token this command already holds. Every FORGE_HOST_LOAD_* variable is dropped,
1105
+ // the test slot count too (decision 0018).
1106
+ for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(process.env))) {
1115
1107
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
1116
1108
  env[key] = value;
1117
1109
  }
1118
1110
  return { ...env, ...overrides };
1119
1111
  }
1120
- /**
1121
- * Runner-authored verification normally uses its attempt-owned Testcontainers
1122
- * database. Only when the Docker engine is unavailable does it switch to the
1123
- * operator-provisioned native test cluster, which holds no real data.
1124
- */
1125
- export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().refresh(true)).available, readFallback = () => {
1126
- const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
1127
- return configPath ? readNativeTestPostgresFallback(configPath) : null;
1128
- }) {
1129
- const fallback = readFallback();
1130
- if (!fallback || await dockerAvailable())
1131
- return {};
1132
- return nativeTestPostgresFallbackEnvironment(fallback);
1133
- }
1134
1112
  export function isBuildProducingManagedCommand(command, args) {
1135
1113
  const executable = path.basename(command).toLowerCase();
1136
1114
  if (executable === "dotnet" || executable === "dotnet.exe") {
@@ -1142,10 +1120,7 @@ export function isBuildProducingManagedCommand(command, args) {
1142
1120
  if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1143
1121
  const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
1144
1122
  const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
1145
- if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
1146
- return !args.some(argument => argument.toLowerCase() === "-nobuild");
1147
- }
1148
- if (script === "run-dotnet-test-tier.ps1") {
1123
+ if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)) {
1149
1124
  return !args.some(argument => argument.toLowerCase() === "-nobuild");
1150
1125
  }
1151
1126
  }
@@ -1200,8 +1175,17 @@ function asRecord(value) {
1200
1175
  throw new Error("managed_command_invalid: input must be an object.");
1201
1176
  return value;
1202
1177
  }
1178
+ const requiredInputExamples = {
1179
+ command: "Send the executable as command and each argument as its own string in args, for example {\"command\": \"pnpm\", \"args\": [\"--dir\", \"client\", \"lint\"]}.",
1180
+ profile: managedVerificationProfileHint,
1181
+ command_id: "Send the command_id returned by forge.start_managed_command or forge.start_managed_verification.",
1182
+ };
1203
1183
  function requiredInputString(record, name) {
1204
- return requiredStandaloneString(record[name], name);
1184
+ const value = record[name];
1185
+ if (typeof value === "string" && value.trim())
1186
+ return value.trim();
1187
+ const hints = [requiredInputExamples[name], isEmptyToolInput(record) ? emptyToolInputHint : undefined].filter(Boolean);
1188
+ throw new Error(`managed_command_invalid: ${name} is required.${hints.length > 0 ? ` ${hints.join(" ")}` : ""}`);
1205
1189
  }
1206
1190
  function validatedCommandId(record) {
1207
1191
  const commandId = requiredInputString(record, "command_id");
@@ -1218,7 +1202,13 @@ function requiredStandaloneString(value, name) {
1218
1202
  function requiredStringArray(record, name) {
1219
1203
  const value = record[name];
1220
1204
  if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) {
1221
- throw new Error(`managed_command_invalid: ${name} must be a string array.`);
1205
+ const shellLine = typeof record.command === "string" && /\s/u.test(record.command.trim());
1206
+ const hint = typeof value === "string"
1207
+ ? " (received a string). Put each argument in its own string, for example [\"--dir\", \"client\", \"test\"]."
1208
+ : value === undefined
1209
+ ? ` (it was omitted). Send [] when there are no arguments.${shellLine ? " command holds only the executable, so move its arguments into args; shell syntax such as cd, &&, or pipes is not interpreted, so set cwd instead of cd." : ""}`
1210
+ : " Every argument must be a string.";
1211
+ throw new Error(`managed_command_invalid: ${name} must be a string array${hint}`);
1222
1212
  }
1223
1213
  return value;
1224
1214
  }
@@ -1,3 +1,19 @@
1
+ /** The managed command a build check needs: what it runs, where, and for which attempt. */
2
+ export interface ManagedBuildCandidate {
3
+ readonly command: string;
4
+ readonly args: readonly string[];
5
+ readonly cwd: string;
6
+ readonly worktreePath: string;
7
+ readonly logDirectory: string;
8
+ readonly buildProducing: boolean;
9
+ }
10
+ /**
11
+ * Refuses, before launch, a managed command that would build into the output one of the
12
+ * attempt's running supervised runtimes executes from. The build slot below orders builds
13
+ * against each other; a running runtime cannot wait its turn, so the collision fails fast
14
+ * with an error naming the runtime instead of a build stuck on its locked files.
15
+ */
16
+ export declare function assertManagedBuildSparesSupervisedRuntimes(candidate: ManagedBuildCandidate): Promise<void>;
1
17
  export declare class ManagedBuildCoordinator {
2
18
  private readonly stateRoot;
3
19
  constructor(stateRoot?: string);
@@ -3,10 +3,20 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
5
5
  import { monotonicNowMs } from "../shared/time/monotonic.js";
6
+ import { assertBuildSparesSupervisedRuntimes } from "../runtime/supervised-runtime-build-guard.js";
6
7
  const heartbeatIntervalMs = 30_000;
7
8
  const staleAfterMs = 2 * 60_000;
8
9
  const acquisitionTimeoutMs = 2 * 60 * 60_000;
9
10
  const pollIntervalMs = 100;
11
+ /**
12
+ * Refuses, before launch, a managed command that would build into the output one of the
13
+ * attempt's running supervised runtimes executes from. The build slot below orders builds
14
+ * against each other; a running runtime cannot wait its turn, so the collision fails fast
15
+ * with an error naming the runtime instead of a build stuck on its locked files.
16
+ */
17
+ export async function assertManagedBuildSparesSupervisedRuntimes(candidate) {
18
+ await assertBuildSparesSupervisedRuntimes({ ...candidate, buildsWorktreeSolution: candidate.buildProducing });
19
+ }
10
20
  export class ManagedBuildCoordinator {
11
21
  stateRoot;
12
22
  constructor(stateRoot = defaultWorktreeCoordinatorStateRoot()) {
@@ -19,3 +19,8 @@ export declare function verifyManagedBuildReceipt(options: {
19
19
  readonly requiredCoverage: string;
20
20
  }): Promise<ManagedBuildReceiptEvidence>;
21
21
  export declare function managedBuildConfiguration(command: string, args: readonly string[]): string;
22
+ /**
23
+ * Writes a JSON receipt by replacing the whole file. Agents and Forge poll receipts, and on
24
+ * Windows a poll that has one open refuses the replace: that delays a write, never fails it.
25
+ */
26
+ export declare function persistJsonAtomically(receiptPath: string, value: unknown): Promise<void>;
@@ -3,6 +3,7 @@ import { spawn } from "node:child_process";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
6
+ import { replaceFile } from "../shared/fs/replace-file.js";
6
7
  const schemaVersion = 1;
7
8
  const maximumRetainedReceipts = 8;
8
9
  const maximumOutputManifestEntries = 20_000;
@@ -262,7 +263,7 @@ async function persistImmutableReceipt(receiptPath, receipt) {
262
263
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
263
264
  await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
264
265
  try {
265
- await fs.rename(temporaryPath, receiptPath).catch(async (error) => {
266
+ await replaceFile(temporaryPath, receiptPath).catch(async (error) => {
266
267
  if (error.code !== "EEXIST")
267
268
  throw error;
268
269
  });
@@ -271,11 +272,15 @@ async function persistImmutableReceipt(receiptPath, receipt) {
271
272
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
272
273
  }
273
274
  }
274
- async function persistJsonAtomically(receiptPath, value) {
275
+ /**
276
+ * Writes a JSON receipt by replacing the whole file. Agents and Forge poll receipts, and on
277
+ * Windows a poll that has one open refuses the replace: that delays a write, never fails it.
278
+ */
279
+ export async function persistJsonAtomically(receiptPath, value) {
275
280
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
276
281
  await fs.writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
277
282
  try {
278
- await fs.rename(temporaryPath, receiptPath);
283
+ await replaceFile(temporaryPath, receiptPath);
279
284
  }
280
285
  finally {
281
286
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
@@ -8,6 +8,8 @@ export interface ManagedCommandHostLoadFields {
8
8
  readonly waitMs: number;
9
9
  /** Set while the command is still queued: the receipt reports the wait so far. */
10
10
  readonly waitStartedAt?: number;
11
+ /** Why it waits, for example for the host test slot and who holds it (decision 0018). */
12
+ readonly waitDetail?: string;
11
13
  /** When the command was admitted; elapsed_ms counts from here. */
12
14
  readonly executionStartedAt?: number;
13
15
  }
@@ -45,11 +45,12 @@ export class ManagedCommandHostCapacity {
45
45
  signal,
46
46
  // The receipt says host_capacity_token_fenced itself (termination_reason).
47
47
  reportsOwnFence: true,
48
- onWaiting: () => {
48
+ onWaiting: decision => {
49
49
  this.waitingWrite = this.persistWaiting({
50
50
  stepClass: this.classification.stepClass,
51
51
  waitMs: 0,
52
52
  waitStartedAt: this.requestedAtMs ?? Date.now(),
53
+ waitDetail: decision.detail,
53
54
  }).catch(() => undefined);
54
55
  },
55
56
  onReleaseFailed,
@@ -0,0 +1,23 @@
1
+ /**
2
+ * MCP clients sometimes send a structured tool argument as its JSON text, for
3
+ * example `sidecars: "[{...}]"` instead of `sidecars: [{...}]`. At the tool-call
4
+ * boundary, before any validation, this replaces such a string with its parsed
5
+ * value, but only where the tool's declared input schema says the value is an
6
+ * array or an object and the string parses to exactly that kind of value.
7
+ *
8
+ * Nothing else is coerced: a string field that happens to contain JSON stays a
9
+ * string, an undeclared field is left alone, and a malformed string is passed
10
+ * through unchanged so the validator reports it.
11
+ */
12
+ export declare function coerceJsonStringArguments(value: unknown, schema: unknown): unknown;
13
+ type StructuredKind = "array" | "object";
14
+ /**
15
+ * Explains why a value is not the expected array or object, for validator
16
+ * messages. A string gets an explicit instruction because that is the usual
17
+ * client mistake; the hint never echoes the value itself.
18
+ */
19
+ export declare function structuredTypeHint(value: unknown, expected: StructuredKind): string;
20
+ /** True when a tool call arrived with no usable arguments at all. */
21
+ export declare function isEmptyToolInput(input: unknown): boolean;
22
+ export declare const emptyToolInputHint: string;
23
+ export {};
@@ -0,0 +1,121 @@
1
+ /**
2
+ * MCP clients sometimes send a structured tool argument as its JSON text, for
3
+ * example `sidecars: "[{...}]"` instead of `sidecars: [{...}]`. At the tool-call
4
+ * boundary, before any validation, this replaces such a string with its parsed
5
+ * value, but only where the tool's declared input schema says the value is an
6
+ * array or an object and the string parses to exactly that kind of value.
7
+ *
8
+ * Nothing else is coerced: a string field that happens to contain JSON stays a
9
+ * string, an undeclared field is left alone, and a malformed string is passed
10
+ * through unchanged so the validator reports it.
11
+ */
12
+ export function coerceJsonStringArguments(value, schema) {
13
+ const node = schemaNode(schema);
14
+ if (!node)
15
+ return value;
16
+ const expected = structuredKind(node);
17
+ let current = value;
18
+ if (typeof current === "string" && expected) {
19
+ const parsed = parseStructured(current, expected);
20
+ if (parsed !== undefined)
21
+ current = parsed;
22
+ }
23
+ if (Array.isArray(current)) {
24
+ const items = schemaNode(node.items);
25
+ if (!items || !acceptsKind(node, "array"))
26
+ return current;
27
+ let changed = current !== value;
28
+ const next = current.map((entry) => {
29
+ const coerced = coerceJsonStringArguments(entry, items);
30
+ if (coerced !== entry)
31
+ changed = true;
32
+ return coerced;
33
+ });
34
+ return changed ? next : current;
35
+ }
36
+ if (isPlainRecord(current)) {
37
+ const properties = schemaNode(node.properties);
38
+ if (!properties || !acceptsKind(node, "object"))
39
+ return current;
40
+ let next = current !== value ? { ...current } : null;
41
+ for (const [key, propertySchema] of Object.entries(properties)) {
42
+ if (!Object.prototype.hasOwnProperty.call(current, key))
43
+ continue;
44
+ const original = current[key];
45
+ const coerced = coerceJsonStringArguments(original, propertySchema);
46
+ if (coerced !== original) {
47
+ next ??= { ...current };
48
+ next[key] = coerced;
49
+ }
50
+ }
51
+ return next ?? current;
52
+ }
53
+ return current;
54
+ }
55
+ function structuredKind(node) {
56
+ const type = node.type;
57
+ if (type === "array" || type === "object")
58
+ return type;
59
+ if (Array.isArray(type)) {
60
+ // A schema that also admits a string must keep the string as sent.
61
+ if (type.includes("string"))
62
+ return null;
63
+ if (type.includes("array") && !type.includes("object"))
64
+ return "array";
65
+ if (type.includes("object") && !type.includes("array"))
66
+ return "object";
67
+ }
68
+ return null;
69
+ }
70
+ function acceptsKind(node, kind) {
71
+ const type = node.type;
72
+ if (type === undefined)
73
+ return true;
74
+ return type === kind || (Array.isArray(type) && type.includes(kind));
75
+ }
76
+ function parseStructured(text, expected) {
77
+ const trimmed = text.trim();
78
+ if (!trimmed.startsWith(expected === "array" ? "[" : "{"))
79
+ return undefined;
80
+ try {
81
+ const parsed = JSON.parse(trimmed);
82
+ if (expected === "array" ? Array.isArray(parsed) : isPlainRecord(parsed))
83
+ return parsed;
84
+ }
85
+ catch {
86
+ // Leave malformed JSON text in place; the validator reports it with a hint.
87
+ }
88
+ return undefined;
89
+ }
90
+ function schemaNode(value) {
91
+ return isPlainRecord(value) ? value : null;
92
+ }
93
+ function isPlainRecord(value) {
94
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
95
+ }
96
+ /**
97
+ * Explains why a value is not the expected array or object, for validator
98
+ * messages. A string gets an explicit instruction because that is the usual
99
+ * client mistake; the hint never echoes the value itself.
100
+ */
101
+ export function structuredTypeHint(value, expected) {
102
+ if (value === undefined || value === null) {
103
+ return " (it was omitted)";
104
+ }
105
+ if (typeof value === "string") {
106
+ return expected === "array"
107
+ ? " (received a string; pass a JSON array value, not a quoted string)"
108
+ : " (received a string; pass a JSON object value, not a quoted string)";
109
+ }
110
+ if (Array.isArray(value))
111
+ return " (received an array)";
112
+ return typeof value === "object" ? " (received an object)" : ` (received a ${typeof value})`;
113
+ }
114
+ /** True when a tool call arrived with no usable arguments at all. */
115
+ export function isEmptyToolInput(input) {
116
+ return input === undefined
117
+ || input === null
118
+ || (isPlainRecord(input) && Object.keys(input).length === 0);
119
+ }
120
+ export const emptyToolInputHint = "No arguments were received: the call arrived as an empty object. "
121
+ + "If the call was large it was probably cut off before it was sent; resend it with every required field.";
@@ -2,6 +2,13 @@ import { type CompletionArtifactReference, type CompletionPhase, type Completion
2
2
  import type { RunnerDispatchArtifact } from "./session.types.js";
3
3
  export declare function writeDecomposeGateCompletionArtifact(config: CompletionToolServerConfig, gate: DecomposeCompletionGate, toolName: string, input: unknown): Promise<CompletionArtifactReference>;
4
4
  export declare function writeDraftGateCompletionArtifact(config: CompletionToolServerConfig, gate: DraftCompletionGate, toolName: string, input: unknown): Promise<CompletionArtifactReference>;
5
+ /**
6
+ * Judges a Decompose gate call before anything is written and returns its status. The gate's
7
+ * input schema advertises exactly these rules (see the completion tool schema contract test).
8
+ */
9
+ export declare function validateDecomposeGatePayload(gate: DecomposeCompletionGate, payload: Record<string, unknown>): string;
10
+ /** Judges a Draft gate call before anything is written and returns its status. */
11
+ export declare function validateDraftGatePayload(gate: DraftCompletionGate, payload: Record<string, unknown>): string;
5
12
  export declare function writeCompletionArtifact(config: CompletionToolServerConfig, toolName: string, input: unknown): Promise<CompletionArtifactReference>;
6
13
  export declare function writeArchitectCompletionArtifact(config: CompletionToolServerConfig, payload: Record<string, unknown>, status: string, producedBy: string): Promise<CompletionArtifactReference>;
7
14
  export declare function writeQaGateCompletionArtifact(config: CompletionToolServerConfig, gate: QaCompletionGate, input: unknown): Promise<CompletionArtifactReference>;