@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.6b2148ecc60c

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 (184) hide show
  1. package/README.md +57 -2
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +125 -0
  4. package/dist/bridge/bridge.base.d.ts +9 -0
  5. package/dist/bridge/bridge.service.d.ts +85 -3
  6. package/dist/bridge/bridge.service.js +361 -122
  7. package/dist/bridge/bridge.types.d.ts +22 -0
  8. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  9. package/dist/bridge/dispatch-result-outbox.js +31 -6
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  13. package/dist/bridge/runner-host-capabilities.js +17 -0
  14. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  15. package/dist/bridge/test-postgres-capability.js +120 -0
  16. package/dist/cleanup/cleanup.service.d.ts +9 -0
  17. package/dist/cleanup/cleanup.service.js +72 -109
  18. package/dist/cleanup/cleanup.types.d.ts +4 -0
  19. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  20. package/dist/cleanup/forge-owned-paths.js +53 -0
  21. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  22. package/dist/cleanup/host-runtime-ledger.js +109 -0
  23. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  24. package/dist/cleanup/managed-branch-sweep.js +111 -0
  25. package/dist/cli/cli.help.js +18 -0
  26. package/dist/cli/cli.service.d.ts +16 -0
  27. package/dist/cli/cli.service.js +142 -16
  28. package/dist/cli/local-config.d.ts +4 -0
  29. package/dist/cli/local-config.js +26 -4
  30. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  31. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  32. package/dist/runtime/attempt-process-supervisor.js +50 -0
  33. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  34. package/dist/runtime/host-database-capability-boundary.js +1 -0
  35. package/dist/runtime/host-facts.d.ts +36 -0
  36. package/dist/runtime/host-facts.js +95 -0
  37. package/dist/runtime/host-load-admission.d.ts +67 -0
  38. package/dist/runtime/host-load-admission.js +99 -0
  39. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  40. package/dist/runtime/host-load-child-environment.js +76 -0
  41. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  42. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  43. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  44. package/dist/runtime/host-load-governor-config.js +83 -0
  45. package/dist/runtime/host-load-governor.d.ts +184 -0
  46. package/dist/runtime/host-load-governor.js +632 -0
  47. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  48. package/dist/runtime/host-load-ledger-lock.js +185 -0
  49. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  50. package/dist/runtime/host-load-runtime-settings.js +78 -0
  51. package/dist/runtime/host-load-sampler.d.ts +149 -0
  52. package/dist/runtime/host-load-sampler.js +291 -0
  53. package/dist/runtime/host-load-step-class.d.ts +70 -0
  54. package/dist/runtime/host-load-step-class.js +161 -0
  55. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  56. package/dist/runtime/host-load-step-reaper.js +95 -0
  57. package/dist/runtime/host-load-step-run.d.ts +73 -0
  58. package/dist/runtime/host-load-step-run.js +102 -0
  59. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  60. package/dist/runtime/host-load-test-slot.js +81 -0
  61. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  62. package/dist/runtime/host-load-token-ledger.js +453 -0
  63. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  64. package/dist/runtime/host-load-windows-cpu.js +85 -0
  65. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  66. package/dist/runtime/host-pressure-stall.js +168 -0
  67. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  68. package/dist/runtime/host-runtime-contract.js +6 -1
  69. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  70. package/dist/runtime/host-runtime-lease.js +336 -20
  71. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  72. package/dist/runtime/host-runtime-promotion.js +48 -0
  73. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  74. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  75. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  76. package/dist/runtime/host-runtime-requirements.js +117 -0
  77. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  78. package/dist/runtime/managed-command-teardown.js +607 -0
  79. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  80. package/dist/runtime/playwright-browser-cache.js +227 -0
  81. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  82. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  83. package/dist/runtime/runner-settings.d.ts +100 -0
  84. package/dist/runtime/runner-settings.js +214 -0
  85. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  86. package/dist/sandbox/host-capacity-broker.js +334 -0
  87. package/dist/sandbox/runtime.d.ts +10 -1
  88. package/dist/sandbox/runtime.js +45 -2
  89. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  90. package/dist/sandbox/sandbox-cgroups.js +42 -0
  91. package/dist/session/managed-attempt-tools.d.ts +27 -0
  92. package/dist/session/managed-attempt-tools.js +357 -42
  93. package/dist/session/managed-build-coordinator.d.ts +1 -1
  94. package/dist/session/managed-build-coordinator.js +4 -1
  95. package/dist/session/managed-command-host-load.d.ts +47 -0
  96. package/dist/session/managed-command-host-load.js +83 -0
  97. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  98. package/dist/session/mcp-argument-coercion.js +121 -0
  99. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  100. package/dist/session/phase-completion.artifacts.js +98 -25
  101. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  102. package/dist/session/phase-completion.command-validation.js +77 -0
  103. package/dist/session/phase-completion.d.ts +4 -0
  104. package/dist/session/phase-completion.helpers.js +13 -12
  105. package/dist/session/phase-completion.js +4 -0
  106. package/dist/session/phase-completion.prompts.js +6 -1
  107. package/dist/session/phase-completion.runtime.d.ts +5 -3
  108. package/dist/session/phase-completion.runtime.js +70 -35
  109. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  110. package/dist/session/phase-completion.schema-parts.js +188 -0
  111. package/dist/session/phase-completion.schemas.d.ts +3 -3
  112. package/dist/session/phase-completion.schemas.js +206 -221
  113. package/dist/session/phase-completion.validation.d.ts +2 -3
  114. package/dist/session/phase-completion.validation.js +46 -92
  115. package/dist/session/pre-publication-host-load.d.ts +27 -0
  116. package/dist/session/pre-publication-host-load.js +111 -0
  117. package/dist/session/pre-publication-pass.d.ts +61 -0
  118. package/dist/session/pre-publication-pass.js +148 -0
  119. package/dist/session/pre-publication-process.d.ts +23 -0
  120. package/dist/session/pre-publication-process.js +109 -0
  121. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  122. package/dist/session/pre-publication-skipped-tests.js +109 -0
  123. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  124. package/dist/session/pre-publication-step-execution.js +49 -0
  125. package/dist/session/pre-publication-validation.d.ts +32 -20
  126. package/dist/session/pre-publication-validation.js +202 -195
  127. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  128. package/dist/session/provider-cli/claude-background-work.js +180 -0
  129. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  130. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  131. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  132. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  133. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  134. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  135. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  136. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  137. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  138. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  139. package/dist/session/provider-cli/provider-cli.process.d.ts +44 -17
  140. package/dist/session/provider-cli/provider-cli.process.js +283 -310
  141. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  142. package/dist/session/provider-cli/provider-cli.prompts.js +65 -10
  143. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  144. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  145. package/dist/session/provider-cli/provider-cli.service.js +203 -172
  146. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  147. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  148. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  149. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  150. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  151. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  152. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  153. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  154. package/dist/session/provider-cli/provider-output-state.js +15 -0
  155. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  156. package/dist/session/publishable-worktree-changes.js +193 -0
  157. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  158. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  159. package/dist/session/session.base.d.ts +9 -1
  160. package/dist/session/session.service.d.ts +9 -2
  161. package/dist/session/session.service.js +120 -5
  162. package/dist/session/session.types.d.ts +3 -0
  163. package/dist/session/session.types.js +15 -3
  164. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  165. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  166. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  167. package/dist/shared/process/host-process-supervisor.js +1 -1
  168. package/dist/shared/process/process-tree.d.ts +52 -0
  169. package/dist/shared/process/process-tree.js +144 -0
  170. package/dist/shared/process/process.d.ts +67 -0
  171. package/dist/shared/process/process.js +213 -11
  172. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  173. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  174. package/dist/shared/process/windows-launch.d.ts +18 -0
  175. package/dist/shared/process/windows-launch.js +68 -0
  176. package/dist/shared/provider-capabilities.js +5 -6
  177. package/dist/version.d.ts +1 -1
  178. package/dist/version.js +1 -1
  179. package/dist/worktree/dependency-warmer.d.ts +25 -0
  180. package/dist/worktree/dependency-warmer.js +46 -10
  181. package/dist/worktree/worktree.service.d.ts +10 -1
  182. package/dist/worktree/worktree.service.js +42 -2
  183. package/dist/worktree/worktree.types.d.ts +7 -0
  184. package/package.json +2 -2
@@ -17,6 +17,7 @@ export declare class ForgeBridgeCliService implements CliService {
17
17
  constructor(sessions?: SessionService, bridgeFactory?: (config: BridgeServiceConfig) => BridgeService, pairRunner?: PairRunnerClient, cleanupFactory?: CleanupServiceFactory, dotNetToolchainConfigurator?: DotNetToolchainConfigurator);
18
18
  run(argv: readonly string[], io?: CliIo): Promise<number>;
19
19
  }
20
+ type YieldAction = "on" | "off" | "status";
20
21
  export declare function parseArgs(argv: readonly string[]): {
21
22
  readonly ok: true;
22
23
  readonly command: "run-once";
@@ -86,6 +87,10 @@ export declare function parseArgs(argv: readonly string[]): {
86
87
  } | {
87
88
  readonly ok: true;
88
89
  readonly command: "sandbox-status";
90
+ } | {
91
+ readonly ok: true;
92
+ readonly command: "yield";
93
+ readonly action: YieldAction;
89
94
  } | {
90
95
  readonly ok: false;
91
96
  readonly error: string;
@@ -104,13 +109,24 @@ interface PairArgs {
104
109
  readonly repoRoot?: string;
105
110
  readonly cleanupWorktrees: boolean;
106
111
  readonly cliProviders: readonly string[];
112
+ /** True when `--cli-provider` named the providers, which then win over the Connect dialog's choice. */
113
+ readonly cliProvidersFromFlag?: boolean;
107
114
  readonly projectLabels: readonly string[];
108
115
  }
116
+ /** Decision 0014 §5: what the Connect dialog's pairing intent set for this host, echoed by the claim. */
117
+ export interface PairRunnerHost {
118
+ readonly name?: string;
119
+ readonly repoRoot?: string;
120
+ readonly cliProviders?: readonly string[];
121
+ }
109
122
  interface PairRunnerClaim {
110
123
  readonly runnerId: string;
111
124
  readonly deviceToken: string;
125
+ readonly host?: PairRunnerHost;
112
126
  }
113
127
  type PairRunnerClient = (args: PairArgs) => Promise<PairRunnerClaim>;
128
+ /** Expands `~` in a repo folder chosen in Forge and rejects one shaped for another OS. */
129
+ export declare function resolveHostRepoRoot(value: string, platform?: NodeJS.Platform, home?: string): string | undefined;
114
130
  export declare const claudeDefaultModels: readonly string[];
115
131
  export declare function parseCodexModelCatalog(raw: string): string[];
116
132
  export declare function parseCursorModelList(raw: string): string[];
@@ -9,10 +9,10 @@ import { buildWindowsCmdLaunch } from "../shared/process/windows-launch.js";
9
9
  import { configureDotNetToolchain } from "../shared/process/dotnet-toolchain.js";
10
10
  import { supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
11
11
  import { redactText } from "../shared/redaction/redaction.js";
12
- import { defaultBridgeServiceConfig, ForgeBridgeService } from "../bridge/bridge.service.js";
12
+ import { BridgeRevokedError, bridgeRevokedExitCode, defaultBridgeServiceConfig, ForgeBridgeService, } from "../bridge/bridge.service.js";
13
13
  import { forgeBridgeVersion } from "../version.js";
14
14
  import { ManagedWorktreeCleanupService } from "../cleanup/cleanup.service.js";
15
- import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
15
+ import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, resolveLocalYieldFlagPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
16
16
  import { BridgeSessionService } from "../session/session.service.js";
17
17
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
18
18
  import { validateDockerfilePolicy, validateSandboxContract } from "../sandbox/contract.js";
@@ -22,6 +22,7 @@ import { DockerSandboxSmoke } from "../sandbox/smoke.js";
22
22
  import { parseCompletionMcpArgs, runCompletionMcpServer } from "../session/phase-completion.js";
23
23
  import { failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
24
24
  import { commandHelpText, helpText } from "./cli.help.js";
25
+ import { readLocalYieldFlag, writeLocalYieldFlag } from "../bridge/local-yield-flag.js";
25
26
  const apiKeySecretGrantEnv = "FORGE_API_KEY_SECRET_GRANT";
26
27
  const execFileAsync = promisify(execFile);
27
28
  export class ForgeBridgeCliService {
@@ -30,7 +31,9 @@ export class ForgeBridgeCliService {
30
31
  pairRunner;
31
32
  cleanupFactory;
32
33
  dotNetToolchainConfigurator;
33
- constructor(sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
34
+ constructor(
35
+ // In a Docker sandbox the default chain's validator asks the host bridge for host load tokens (decision 0013).
36
+ sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
34
37
  this.sessions = sessions;
35
38
  this.bridgeFactory = bridgeFactory;
36
39
  this.pairRunner = pairRunner;
@@ -89,11 +92,22 @@ export class ForgeBridgeCliService {
89
92
  if (config.cleanupWorktrees && config.repoMappings.some(mapping => mapping.localPath?.trim())) {
90
93
  io.stdout.write("Cleaning stale managed worktrees before accepting dispatches.\n");
91
94
  await cleanupRepos(config, "stale", true, this.cleanupFactory(config.sandboxStateRoot), io);
95
+ // Forge branches on this device whose work has merged since the bridge last ran.
96
+ await cleanupRepos(config, "merged", true, this.cleanupFactory(config.sandboxStateRoot), io);
92
97
  }
93
98
  io.stdout.write(connectStartupText(config));
94
99
  await this.bridgeFactory(config).run(controller.signal);
95
100
  return 0;
96
101
  }
102
+ catch (error) {
103
+ if (error instanceof BridgeRevokedError) {
104
+ // Decision 0014: removed from Forge. Exit with a distinct code so a supervisor can
105
+ // tell "pair again" apart from a crash.
106
+ io.stderr.write(`${error.message}\n`);
107
+ return bridgeRevokedExitCode;
108
+ }
109
+ throw error;
110
+ }
97
111
  finally {
98
112
  process.off("SIGINT", stop);
99
113
  process.off("SIGTERM", stop);
@@ -117,13 +131,22 @@ export class ForgeBridgeCliService {
117
131
  const current = readLocalConfigSync();
118
132
  io.stdout.write(`Pairing with server: ${args.serverUrl}\n`);
119
133
  const code = await resolvePairingCode(args.code);
120
- const repoRoot = await resolvePairRepoRoot(args.repoRoot, current.defaultRepoRoot);
121
- await fs.mkdir(repoRoot, { recursive: true });
122
- const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot });
134
+ const provisionalRoot = path.resolve(args.repoRoot ?? current.defaultRepoRoot ?? path.join(os.homedir(), "ForgeRepos"));
135
+ const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot: provisionalRoot });
123
136
  const claim = await this.pairRunner(pairArgs);
124
- const next = pairedConfig(current, pairArgs, claim);
125
- await writeLocalConfig(next);
126
- io.stdout.write(`Paired runner ${claim.runnerId}.\n`);
137
+ // The code is spent now: save the credentials before anything else can fail or prompt.
138
+ const applied = applyPairHost(pairArgs, claim.host, args.repoRoot !== undefined, io);
139
+ await writeLocalConfig(pairedConfig(current, applied.args, claim));
140
+ let repoRoot = applied.args.repoRoot;
141
+ if (!args.repoRoot && !applied.repoRootFromHost) {
142
+ const answered = await promptPairRepoRoot(repoRoot);
143
+ if (answered !== repoRoot) {
144
+ repoRoot = answered;
145
+ await writeLocalConfig(pairedConfig(current, { ...applied.args, repoRoot }, claim));
146
+ }
147
+ }
148
+ await fs.mkdir(repoRoot, { recursive: true });
149
+ io.stdout.write(`Paired runner ${claim.runnerId}${applied.args.name ? ` (${applied.args.name})` : ""}.\n`);
127
150
  io.stdout.write(`Repo folder: ${repoRoot}\n`);
128
151
  io.stdout.write(`Config: ${resolveLocalConfigPath()}\n`);
129
152
  io.stdout.write("Start the bridge with: forge-bridge connect\n");
@@ -206,6 +229,9 @@ export class ForgeBridgeCliService {
206
229
  writeSandboxPolicyStatus(readLocalConfigSync(), io);
207
230
  return 0;
208
231
  }
232
+ if (args.command === "yield") {
233
+ return await runYieldCommand(args.action, io);
234
+ }
209
235
  if (args.command === "mcp") {
210
236
  const parsed = parseCompletionMcpArgs(args.argv);
211
237
  if (!parsed.ok) {
@@ -243,6 +269,36 @@ export class ForgeBridgeCliService {
243
269
  }
244
270
  }
245
271
  }
272
+ /**
273
+ * Decision 0014 `forge-bridge yield`: the host's own yield switch. It writes a
274
+ * flag file next to the bridge config (never bridge.json); a running bridge
275
+ * polls it and stops taking new attempts without a restart.
276
+ */
277
+ async function runYieldCommand(action, io) {
278
+ const flagPath = resolveLocalYieldFlagPath();
279
+ try {
280
+ if (action !== "status") {
281
+ await writeLocalYieldFlag(flagPath, action === "on");
282
+ }
283
+ const on = await readLocalYieldFlag(flagPath);
284
+ if (action === "on") {
285
+ io.stdout.write("Local yield to foreground is on. A running bridge takes no new attempts within one heartbeat; running attempts finish.\n");
286
+ }
287
+ else if (action === "off") {
288
+ io.stdout.write("Local yield to foreground is off. The bridge takes new attempts again unless yield is on in Forge.\n");
289
+ }
290
+ else {
291
+ io.stdout.write(`Local yield to foreground: ${on ? "on" : "off"}\n`);
292
+ }
293
+ io.stdout.write(`Flag file: ${flagPath}\n`);
294
+ io.stdout.write("The effective state also depends on Forge: the runner yields when this flag or its Yield toggle in Forge is on.\n");
295
+ return 0;
296
+ }
297
+ catch (error) {
298
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
299
+ return 1;
300
+ }
301
+ }
246
302
  function attachEnvSecretGrant(dispatch) {
247
303
  if (!dispatch.execution.requiresApiKeySecretGrant) {
248
304
  delete process.env[apiKeySecretGrantEnv];
@@ -346,6 +402,13 @@ export function parseArgs(argv) {
346
402
  if (argv[0] === "sandbox") {
347
403
  return parseSandboxArgs(argv);
348
404
  }
405
+ if (argv[0] === "yield") {
406
+ const action = argv[1] ?? "status";
407
+ if (argv.length > 2 || (action !== "on" && action !== "off" && action !== "status")) {
408
+ return { ok: false, error: "Usage: forge-bridge yield [on|off|status]" };
409
+ }
410
+ return { ok: true, command: "yield", action };
411
+ }
349
412
  if (argv[0] !== "run-once") {
350
413
  return {
351
414
  ok: false,
@@ -759,6 +822,7 @@ function parsePairArgs(argv) {
759
822
  repoRoot: repoRoot?.trim() ? path.resolve(repoRoot) : undefined,
760
823
  cleanupWorktrees: cleanupWorktrees ?? defaultConfig.cleanupWorktrees,
761
824
  cliProviders: cliProviders.length > 0 ? cliProviders : localConfig.cliProviders && localConfig.cliProviders.length > 0 ? [...localConfig.cliProviders] : ["codex"],
825
+ cliProvidersFromFlag: cliProviders.length > 0,
762
826
  projectLabels: projectLabels.length > 0 ? projectLabels : localConfig.projectLabels ? [...localConfig.projectLabels] : []
763
827
  };
764
828
  }
@@ -821,9 +885,71 @@ async function claimBridgeRunner(args) {
821
885
  }
822
886
  return {
823
887
  runnerId: value.runnerId,
824
- deviceToken: value.deviceToken
888
+ deviceToken: value.deviceToken,
889
+ host: parsePairRunnerHost(value.host)
890
+ };
891
+ }
892
+ function parsePairRunnerHost(value) {
893
+ if (!value || typeof value !== "object") {
894
+ return undefined;
895
+ }
896
+ const host = value;
897
+ const name = typeof host.name === "string" && host.name.trim() ? host.name.trim() : undefined;
898
+ const repoRoot = typeof host.repoRoot === "string" && host.repoRoot.trim() ? host.repoRoot.trim() : undefined;
899
+ const cliProviders = Array.isArray(host.cliProviders)
900
+ ? host.cliProviders.filter((provider) => typeof provider === "string" && provider.trim().length > 0)
901
+ : [];
902
+ return { name, repoRoot, cliProviders: cliProviders.length > 0 ? cliProviders : undefined };
903
+ }
904
+ /**
905
+ * Decision 0014 §5: the claim's host block carries what the Connect dialog chose. The runner name
906
+ * is the server's; providers and the repo folder apply unless a flag named them on this command line.
907
+ */
908
+ function applyPairHost(args, host, repoRootFromFlag, io) {
909
+ if (!host) {
910
+ return { args, repoRootFromHost: false };
911
+ }
912
+ let repoRoot = args.repoRoot;
913
+ let repoRootFromHost = false;
914
+ if (host.repoRoot && !repoRootFromFlag) {
915
+ const resolved = resolveHostRepoRoot(host.repoRoot);
916
+ if (!resolved) {
917
+ io.stderr.write(`Ignoring the repo folder chosen in Forge (${host.repoRoot}): it is not a path on this machine.\n`);
918
+ }
919
+ else {
920
+ repoRootFromHost = true;
921
+ repoRoot = resolved;
922
+ }
923
+ }
924
+ return {
925
+ args: {
926
+ ...args,
927
+ name: host.name ?? args.name,
928
+ cliProviders: host.cliProviders && !args.cliProvidersFromFlag ? [...host.cliProviders] : args.cliProviders,
929
+ repoRoot
930
+ },
931
+ repoRootFromHost
825
932
  };
826
933
  }
934
+ /** Expands `~` in a repo folder chosen in Forge and rejects one shaped for another OS. */
935
+ export function resolveHostRepoRoot(value, platform = process.platform, home = os.homedir()) {
936
+ const trimmed = value.trim();
937
+ if (!trimmed) {
938
+ return undefined;
939
+ }
940
+ const pathApi = platform === "win32" ? path.win32 : path.posix;
941
+ if (trimmed === "~") {
942
+ return home;
943
+ }
944
+ if (/^~[\\/]/.test(trimmed)) {
945
+ return pathApi.resolve(home, trimmed.slice(2));
946
+ }
947
+ const windowsShaped = /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.startsWith("\\\\");
948
+ if (platform === "win32") {
949
+ return windowsShaped || trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
950
+ }
951
+ return !windowsShaped && trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
952
+ }
827
953
  function pairedConfig(current, args, claim) {
828
954
  return {
829
955
  ...current,
@@ -868,11 +994,7 @@ async function resolvePairingCode(code) {
868
994
  prompt.close();
869
995
  }
870
996
  }
871
- async function resolvePairRepoRoot(repoRoot, configuredRoot) {
872
- const fallback = path.resolve(repoRoot ?? configuredRoot ?? path.join(os.homedir(), "ForgeRepos"));
873
- if (repoRoot?.trim()) {
874
- return fallback;
875
- }
997
+ async function promptPairRepoRoot(fallback) {
876
998
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
877
999
  return fallback;
878
1000
  }
@@ -1001,7 +1123,11 @@ async function cleanupRepos(config, mode, force, cleanup, io) {
1001
1123
  io.stdout.write(`Removed ${result.removedWorktrees} stale managed ${result.removedWorktrees === 1 ? "worktree" : "worktrees"} from ${result.worktreeRoot}\n`);
1002
1124
  }
1003
1125
  else {
1004
- io.stdout.write(`Pruned stale worktree metadata for ${repoPath}\n`);
1126
+ const deleted = result.deletedBranches ?? 0;
1127
+ io.stdout.write(`Pruned stale worktree metadata and deleted ${deleted} Forge ${deleted === 1 ? "branch" : "branches"} (merged work and leftover readiness probes) in ${repoPath}\n`);
1128
+ if (result.mergedBaseUnresolved) {
1129
+ io.stderr.write(`${repoPath}: merged work branches were kept because the base branch couldn't be determined: origin/HEAD is unset or names a branch that no longer exists, and origin has none or more than one of develop, main and master. Run \`git fetch origin && git remote set-head origin --auto\`.\n`);
1130
+ }
1005
1131
  }
1006
1132
  }
1007
1133
  catch (error) {
@@ -30,8 +30,12 @@ export interface LocalRepoMapping extends BridgeRepoMapping {
30
30
  export declare function resolveLocalConfigPath(): string;
31
31
  export declare function readLocalConfig(): Promise<BridgeLocalConfig>;
32
32
  export declare function readLocalConfigSync(): BridgeLocalConfig;
33
+ /** Decision 0014 §5: `bridge.json` holds the device token, so only its owner may read it. */
34
+ export declare const localConfigFileMode = 384;
33
35
  export declare function writeLocalConfig(config: BridgeLocalConfig): Promise<void>;
34
36
  export declare function applyLocalConfigDefaults(config: BridgeServiceConfig, local: BridgeLocalConfig): BridgeServiceConfig;
37
+ /** Decision 0014: the `forge-bridge yield` flag, beside the bridge config and never inside it. */
38
+ export declare function resolveLocalYieldFlagPath(): string;
35
39
  export declare function addRepoMapping(label: string, repoPath: string): Promise<BridgeLocalConfig>;
36
40
  export declare function removeRepoMapping(label: string): Promise<{
37
41
  readonly config: BridgeLocalConfig;
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
2
2
  import fsSync from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { localYieldFlagPathFor } from "../bridge/local-yield-flag.js";
5
6
  export function resolveLocalConfigPath() {
6
7
  if (process.env.FORGE_BRIDGE_CONFIG?.trim()) {
7
8
  return path.resolve(process.env.FORGE_BRIDGE_CONFIG);
@@ -28,12 +29,28 @@ export function readLocalConfigSync() {
28
29
  }
29
30
  return parseLocalConfig(fsSync.readFileSync(configPath, "utf8"));
30
31
  }
32
+ /** Decision 0014 §5: `bridge.json` holds the device token, so only its owner may read it. */
33
+ export const localConfigFileMode = 0o600;
34
+ const localConfigDirectoryMode = 0o700;
31
35
  export async function writeLocalConfig(config) {
32
36
  const configPath = resolveLocalConfigPath();
33
- await fs.mkdir(path.dirname(configPath), { recursive: true });
37
+ await fs.mkdir(path.dirname(configPath), { recursive: true, mode: localConfigDirectoryMode });
34
38
  const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
35
- await fs.writeFile(tempPath, `${JSON.stringify(normalizeLocalConfig(config), null, 2)}\n`, "utf8");
36
- await fs.rename(tempPath, configPath);
39
+ try {
40
+ await fs.writeFile(tempPath, `${JSON.stringify(normalizeLocalConfig(config), null, 2)}\n`, {
41
+ encoding: "utf8",
42
+ mode: localConfigFileMode
43
+ });
44
+ if (process.platform !== "win32") {
45
+ // The create mode is masked by the umask; set it exactly before the file becomes visible.
46
+ await fs.chmod(tempPath, localConfigFileMode);
47
+ }
48
+ await fs.rename(tempPath, configPath);
49
+ }
50
+ catch (error) {
51
+ await fs.rm(tempPath, { force: true }).catch(() => undefined);
52
+ throw error;
53
+ }
37
54
  }
38
55
  export function applyLocalConfigDefaults(config, local) {
39
56
  const cliProviders = local.cliProviders && local.cliProviders.length > 0 ? [...local.cliProviders] : config.cliProviders;
@@ -65,9 +82,14 @@ export function applyLocalConfigDefaults(config, local) {
65
82
  supportsRunnerAuthoredPhaseArtifacts: local.supportsRunnerAuthoredPhaseArtifacts ?? config.supportsRunnerAuthoredPhaseArtifacts,
66
83
  supportsDraftRunOnce: local.supportsDraftRunOnce ?? config.supportsDraftRunOnce,
67
84
  supportsDraftAttachments: local.supportsDraftAttachments ?? config.supportsDraftAttachments,
68
- supportsDraftImageAttachments: local.supportsDraftImageAttachments ?? config.supportsDraftImageAttachments
85
+ supportsDraftImageAttachments: local.supportsDraftImageAttachments ?? config.supportsDraftImageAttachments,
86
+ localYieldFlagPath: resolveLocalYieldFlagPath()
69
87
  };
70
88
  }
89
+ /** Decision 0014: the `forge-bridge yield` flag, beside the bridge config and never inside it. */
90
+ export function resolveLocalYieldFlagPath() {
91
+ return localYieldFlagPathFor(resolveLocalConfigPath());
92
+ }
71
93
  export async function addRepoMapping(label, repoPath) {
72
94
  const normalizedLabel = normalizeLabel(label);
73
95
  const localPath = path.resolve(repoPath);
@@ -211,7 +211,7 @@ async function aspNetBuildInputs(plan) {
211
211
  const projectDirectory = path.extname(plan.projectPath).toLowerCase() === ".csproj"
212
212
  ? path.dirname(plan.projectPath)
213
213
  : plan.projectPath;
214
- const sourceDigest = await directoryContentDigest(projectDirectory);
214
+ const sourceDigest = await projectSourceDigest(plan, projectDirectory);
215
215
  const dependencyReceipt = path.join(projectDirectory, "obj", ".forge-dependency-preparation.json");
216
216
  const dependencyContent = await fs.readFile(dependencyReceipt).catch(() => null);
217
217
  const globalJson = await findAncestorFile(projectDirectory, plan.worktreePath, "global.json");
@@ -225,18 +225,106 @@ async function aspNetBuildInputs(plan) {
225
225
  sdkVersion: await dotnetSdkVersion(plan.cwd),
226
226
  };
227
227
  }
228
- async function directoryContentDigest(directory) {
229
- const files = [];
230
- await collectInputFiles(directory, directory, files);
228
+ /**
229
+ * Digest of everything the project build compiles from inside the worktree: the
230
+ * project directory, every project it references (transitively, through
231
+ * ProjectReference), and the Directory.Build/Directory.Packages files above them.
232
+ * A change in a referenced project must invalidate the receipt, or the launch
233
+ * reuses a binary built from the previous source.
234
+ */
235
+ async function projectSourceDigest(plan, projectDirectory) {
236
+ const worktree = path.resolve(plan.worktreePath);
237
+ const directories = await projectSourceDirectories(plan, projectDirectory);
238
+ const files = new Set();
239
+ for (const directory of directories) {
240
+ const collected = [];
241
+ await collectInputFiles(directory, directory, collected);
242
+ for (const file of collected)
243
+ files.add(file);
244
+ for (const buildFile of await ancestorBuildFiles(directory, worktree))
245
+ files.add(buildFile);
246
+ }
231
247
  const hash = createHash("sha256");
232
- for (const file of files.sort((left, right) => left.localeCompare(right))) {
233
- hash.update(path.relative(directory, file).replaceAll("\\", "/"));
248
+ for (const file of [...files].sort((left, right) => left.localeCompare(right))) {
249
+ hash.update(path.relative(worktree, file).replaceAll("\\", "/"));
234
250
  hash.update("\0");
235
251
  hash.update(await fs.readFile(file));
236
252
  hash.update("\0");
237
253
  }
238
254
  return `sha256:${hash.digest("hex")}`;
239
255
  }
256
+ const msbuildProjectExtensions = new Set([".csproj", ".fsproj", ".vbproj"]);
257
+ const msbuildDirectoryFiles = ["Directory.Build.props", "Directory.Build.targets", "Directory.Packages.props"];
258
+ /** The project directory and the directories of the projects it references inside the worktree. */
259
+ async function projectSourceDirectories(plan, projectDirectory) {
260
+ const worktree = path.resolve(plan.worktreePath);
261
+ const directories = new Set([path.resolve(projectDirectory)]);
262
+ const queue = msbuildProjectExtensions.has(path.extname(plan.projectPath).toLowerCase())
263
+ ? [path.resolve(plan.projectPath)]
264
+ : await projectFilesIn(projectDirectory);
265
+ const visited = new Set();
266
+ while (queue.length > 0) {
267
+ const projectFile = queue.shift();
268
+ if (visited.has(projectFile))
269
+ continue;
270
+ visited.add(projectFile);
271
+ const content = await fs.readFile(projectFile, "utf8").catch(() => null);
272
+ if (content === null)
273
+ continue;
274
+ for (const include of projectReferenceIncludes(content)) {
275
+ // An MSBuild property cannot be resolved here; the referenced source stays outside the digest.
276
+ if (include.includes("$("))
277
+ continue;
278
+ const referenced = path.resolve(path.dirname(projectFile), include.replaceAll("\\", "/"));
279
+ if (!containedIn(worktree, referenced))
280
+ continue;
281
+ directories.add(path.dirname(referenced));
282
+ queue.push(referenced);
283
+ }
284
+ }
285
+ return [...directories];
286
+ }
287
+ async function projectFilesIn(directory) {
288
+ const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => []);
289
+ return entries
290
+ .filter(entry => entry.isFile() && msbuildProjectExtensions.has(path.extname(entry.name).toLowerCase()))
291
+ .map(entry => path.join(directory, entry.name));
292
+ }
293
+ function projectReferenceIncludes(projectXml) {
294
+ const withoutComments = projectXml.replaceAll(/<!--[\s\S]*?-->/gu, "");
295
+ const includes = [];
296
+ for (const match of withoutComments.matchAll(/<ProjectReference\b[^>]*?\bInclude\s*=\s*(?:"([^"]*)"|'([^']*)')/giu)) {
297
+ const value = match[1] ?? match[2] ?? "";
298
+ for (const part of value.split(";")) {
299
+ const trimmed = part.trim();
300
+ if (trimmed)
301
+ includes.push(trimmed);
302
+ }
303
+ }
304
+ return includes;
305
+ }
306
+ async function ancestorBuildFiles(directory, worktree) {
307
+ const found = [];
308
+ let current = path.resolve(directory);
309
+ while (containedIn(worktree, current)) {
310
+ for (const name of msbuildDirectoryFiles) {
311
+ const candidate = path.join(current, name);
312
+ if (await fs.stat(candidate).then(stat => stat.isFile()).catch(() => false))
313
+ found.push(candidate);
314
+ }
315
+ if (current === worktree)
316
+ break;
317
+ const parent = path.dirname(current);
318
+ if (parent === current)
319
+ break;
320
+ current = parent;
321
+ }
322
+ return found;
323
+ }
324
+ function containedIn(root, candidate) {
325
+ const relative = path.relative(root, candidate);
326
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
327
+ }
240
328
  async function collectInputFiles(root, directory, files) {
241
329
  const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => []);
242
330
  for (const entry of entries) {
@@ -1,4 +1,5 @@
1
1
  import type { ProviderProcessHandlers, ProviderProcessRunRequest, ProviderProcessRunner, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ import { type ManagedCommandTeardownOptions, type ManagedCommandTeardownOutcome } from "./managed-command-teardown.js";
2
3
  export type AttemptProcessChildStatus = "starting" | "running" | "stopping" | "exited" | "failed";
3
4
  export type AttemptProcessSupervisorStatus = "active" | "stopping" | "stopped" | "degraded";
4
5
  export interface AttemptProcessSupervisorIdentity {
@@ -32,6 +33,8 @@ export interface AttemptProcessSupervisorLedger {
32
33
  readonly status: AttemptProcessSupervisorStatus;
33
34
  readonly updatedAt: string;
34
35
  readonly children: readonly AttemptProcessChildLedgerEntry[];
36
+ /** A provider-exit managed-command cleanup that failed and was left to attempt teardown. */
37
+ readonly deferredManagedCommandTeardownFailure?: string;
35
38
  }
36
39
  export interface AttemptProcessChildHandle {
37
40
  readonly name: string;
@@ -48,6 +51,7 @@ export interface AttemptProcessSupervisorOptions {
48
51
  readonly signal?: AbortSignal;
49
52
  readonly replaceLedgerFile?: (temporaryPath: string, ledgerPath: string) => Promise<void>;
50
53
  readonly ledgerReplaceRetryMs?: number;
54
+ readonly managedCommandTeardownGraceMs?: number;
51
55
  }
52
56
  export interface AttemptProcessChildReadyOptions {
53
57
  readonly maxStartAttempts?: number;
@@ -66,6 +70,7 @@ export declare class AttemptProcessSupervisor {
66
70
  private readonly metadataReadyTimeoutMs;
67
71
  private readonly replaceLedgerFile;
68
72
  private readonly ledgerReplaceRetryMs;
73
+ private readonly managedCommandTeardownGraceMs;
69
74
  private readonly records;
70
75
  private readonly currentByName;
71
76
  private readonly attemptController;
@@ -73,6 +78,8 @@ export declare class AttemptProcessSupervisor {
73
78
  private persistTail;
74
79
  private persistenceFailure;
75
80
  private stopOperation;
81
+ private managedCommandTeardownTail;
82
+ private deferredManagedCommandTeardownFailure;
76
83
  constructor(identity: AttemptProcessSupervisorIdentity, runner: ProviderProcessRunner, options?: AttemptProcessSupervisorOptions);
77
84
  startChild(name: string, request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<AttemptProcessChildHandle>;
78
85
  /**
@@ -86,6 +93,18 @@ export declare class AttemptProcessSupervisor {
86
93
  stopChild(name: string, generation: number, fencingToken: string, reason?: unknown): Promise<ProviderProcessRunResult>;
87
94
  stopAll(fencingToken: string, reason?: unknown): Promise<void>;
88
95
  private performStopAll;
96
+ /**
97
+ * Stops the managed commands this attempt's MCP servers started and finalizes their
98
+ * receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
99
+ * left running: it survives wait slices and MCP call boundaries within a live provider.
100
+ */
101
+ terminateManagedCommands(options: Omit<ManagedCommandTeardownOptions, "graceMs">): Promise<readonly ManagedCommandTeardownOutcome[]>;
102
+ /**
103
+ * After a provider exits, stops the managed commands its MCP server left behind. It never
104
+ * fails the provider's result: a command it cannot prove stopped is recorded in the ledger
105
+ * and left to attempt teardown, which fails closed.
106
+ */
107
+ stopOrphanedManagedCommands(): Promise<void>;
89
108
  snapshot(): AttemptProcessSupervisorLedger;
90
109
  providerMemoryTelemetry(): AttemptProcessTreeMemoryTelemetry | null;
91
110
  private observeChildReady;
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { ForgeFailureError, sanitizeFailureError } from "../session/session.types.js";
5
+ import { terminateAttemptManagedCommands, } from "./managed-command-teardown.js";
5
6
  import { monotonicNowMs } from "../shared/time/monotonic.js";
6
7
  const terminalChildStatuses = new Set(["exited", "failed"]);
7
8
  const defaultMetadataReadyTimeoutMs = process.platform === "win32" ? 60_000 : 10_000;
@@ -23,6 +24,7 @@ export class AttemptProcessSupervisor {
23
24
  metadataReadyTimeoutMs;
24
25
  replaceLedgerFile;
25
26
  ledgerReplaceRetryMs;
27
+ managedCommandTeardownGraceMs;
26
28
  records = [];
27
29
  currentByName = new Map();
28
30
  attemptController = new AbortController();
@@ -30,12 +32,15 @@ export class AttemptProcessSupervisor {
30
32
  persistTail = Promise.resolve();
31
33
  persistenceFailure;
32
34
  stopOperation = null;
35
+ managedCommandTeardownTail = Promise.resolve();
36
+ deferredManagedCommandTeardownFailure;
33
37
  constructor(identity, runner, options = {}) {
34
38
  this.runner = runner;
35
39
  this.identity = validateIdentity(identity);
36
40
  this.metadataReadyTimeoutMs = boundedInteger(options.metadataReadyTimeoutMs ?? defaultMetadataReadyTimeoutMs, 100, 120_000, "metadataReadyTimeoutMs");
37
41
  this.replaceLedgerFile = options.replaceLedgerFile ?? ((temporaryPath, ledgerPath) => fs.rename(temporaryPath, ledgerPath));
38
42
  this.ledgerReplaceRetryMs = options.ledgerReplaceRetryMs ?? defaultLedgerReplaceRetryMs;
43
+ this.managedCommandTeardownGraceMs = options.managedCommandTeardownGraceMs;
39
44
  this.ledgerPath = path.join(this.identity.logDirectory, "attempt-process-supervisor.json");
40
45
  if (options.signal?.aborted) {
41
46
  this.status = "stopping";
@@ -199,6 +204,14 @@ export class AttemptProcessSupervisor {
199
204
  const rejected = results.flatMap((result, index) => result.status === "rejected"
200
205
  ? [sanitizeFailureError(result.reason, active[index].failureRedactionValues)]
201
206
  : []);
207
+ // Managed commands run in their own process groups, outside every child tree stopped
208
+ // above. The attempt is not stopped until each of them is proven stopped too.
209
+ try {
210
+ await this.terminateManagedCommands({ reason: "attempt_teardown" });
211
+ }
212
+ catch (error) {
213
+ rejected.push(error instanceof Error ? error : new Error(String(error)));
214
+ }
202
215
  const terminalStatus = rejected.length > 0 || this.persistenceFailure !== undefined ? "degraded" : "stopped";
203
216
  await this.persist({
204
217
  ...this.snapshot(),
@@ -212,6 +225,40 @@ export class AttemptProcessSupervisor {
212
225
  if (this.persistenceFailure !== undefined)
213
226
  throw this.persistenceFailure;
214
227
  }
228
+ /**
229
+ * Stops the managed commands this attempt's MCP servers started and finalizes their
230
+ * receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
231
+ * left running: it survives wait slices and MCP call boundaries within a live provider.
232
+ */
233
+ async terminateManagedCommands(options) {
234
+ // One sweep at a time: a provider-exit sweep and attempt teardown would otherwise
235
+ // signal the same groups and write the same receipts concurrently, and stopAll must
236
+ // not report the attempt stopped while an earlier sweep is still writing.
237
+ const sweep = this.managedCommandTeardownTail.then(async () => await terminateAttemptManagedCommands({
238
+ logDirectory: this.identity.logDirectory,
239
+ dispatchAttemptId: this.identity.dispatchAttemptId,
240
+ runtimeLeaseId: this.identity.executionLeaseId,
241
+ }, {
242
+ ...options,
243
+ ...(this.managedCommandTeardownGraceMs === undefined ? {} : { graceMs: this.managedCommandTeardownGraceMs }),
244
+ }));
245
+ this.managedCommandTeardownTail = sweep.catch(() => undefined);
246
+ return await sweep;
247
+ }
248
+ /**
249
+ * After a provider exits, stops the managed commands its MCP server left behind. It never
250
+ * fails the provider's result: a command it cannot prove stopped is recorded in the ledger
251
+ * and left to attempt teardown, which fails closed.
252
+ */
253
+ async stopOrphanedManagedCommands() {
254
+ try {
255
+ await this.terminateManagedCommands({ reason: "owner_exited", onlyOrphaned: true });
256
+ }
257
+ catch (error) {
258
+ this.deferredManagedCommandTeardownFailure = boundedFailure(error, []);
259
+ await this.persist().catch(() => undefined);
260
+ }
261
+ }
215
262
  snapshot() {
216
263
  return {
217
264
  schemaVersion: 1,
@@ -220,6 +267,9 @@ export class AttemptProcessSupervisor {
220
267
  executionLeaseId: this.identity.executionLeaseId,
221
268
  status: this.status,
222
269
  updatedAt: new Date().toISOString(),
270
+ ...(this.deferredManagedCommandTeardownFailure
271
+ ? { deferredManagedCommandTeardownFailure: this.deferredManagedCommandTeardownFailure }
272
+ : {}),
223
273
  children: this.records.map(record => ({
224
274
  name: record.name,
225
275
  generation: record.generation,
@@ -1,4 +1,4 @@
1
- export declare const hostDatabaseCapabilityEnvironmentNames: readonly ["FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING", "FORGE_TEST_POSTGRES_CONNECTION_STRING"];
1
+ export declare const hostDatabaseCapabilityEnvironmentNames: readonly ["FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING", "FORGE_TEST_POSTGRES_CONNECTION_STRING", "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING"];
2
2
  export interface HostDatabaseCapabilityBoundaryOptions {
3
3
  readonly platform?: NodeJS.Platform;
4
4
  readonly processEnvironment?: NodeJS.ProcessEnv;
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  export const hostDatabaseCapabilityEnvironmentNames = [
4
4
  "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING",
5
5
  "FORGE_TEST_POSTGRES_CONNECTION_STRING",
6
+ "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING",
6
7
  ];
7
8
  const boundaryAttestationEnvironment = "FORGE_HOST_DATABASE_CAPABILITY_BOUNDARY";
8
9
  const boundaryAttestationValue = "user_store_clear";