@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.8901ba056f68

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 (119) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +14 -1
  3. package/dist/bridge/bridge.service.js +80 -9
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  6. package/dist/bridge/dispatch-result-outbox.js +31 -6
  7. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  8. package/dist/bridge/runner-host-capabilities.js +4 -0
  9. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  10. package/dist/bridge/test-postgres-capability.js +120 -0
  11. package/dist/cli/cli.service.js +3 -1
  12. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  13. package/dist/runtime/attempt-process-supervisor.js +50 -0
  14. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  15. package/dist/runtime/host-database-capability-boundary.js +1 -0
  16. package/dist/runtime/host-facts.d.ts +35 -0
  17. package/dist/runtime/host-facts.js +95 -0
  18. package/dist/runtime/host-load-admission.d.ts +52 -0
  19. package/dist/runtime/host-load-admission.js +84 -0
  20. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  21. package/dist/runtime/host-load-child-environment.js +65 -0
  22. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  23. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  24. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  25. package/dist/runtime/host-load-governor-config.js +46 -0
  26. package/dist/runtime/host-load-governor.d.ts +172 -0
  27. package/dist/runtime/host-load-governor.js +519 -0
  28. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  29. package/dist/runtime/host-load-ledger-lock.js +185 -0
  30. package/dist/runtime/host-load-sampler.d.ts +126 -0
  31. package/dist/runtime/host-load-sampler.js +232 -0
  32. package/dist/runtime/host-load-step-class.d.ts +68 -0
  33. package/dist/runtime/host-load-step-class.js +106 -0
  34. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  35. package/dist/runtime/host-load-step-reaper.js +95 -0
  36. package/dist/runtime/host-load-step-run.d.ts +73 -0
  37. package/dist/runtime/host-load-step-run.js +102 -0
  38. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  39. package/dist/runtime/host-load-token-ledger.js +421 -0
  40. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  41. package/dist/runtime/host-pressure-stall.js +168 -0
  42. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  43. package/dist/runtime/host-runtime-contract.js +6 -1
  44. package/dist/runtime/host-runtime-lease.d.ts +17 -3
  45. package/dist/runtime/host-runtime-lease.js +138 -13
  46. package/dist/runtime/host-runtime-promotion.js +12 -0
  47. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  48. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  49. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  50. package/dist/runtime/host-runtime-requirements.js +117 -0
  51. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  52. package/dist/runtime/managed-command-teardown.js +607 -0
  53. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  54. package/dist/runtime/playwright-browser-cache.js +227 -0
  55. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  56. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  57. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  58. package/dist/sandbox/host-capacity-broker.js +315 -0
  59. package/dist/sandbox/runtime.d.ts +10 -1
  60. package/dist/sandbox/runtime.js +45 -2
  61. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  62. package/dist/sandbox/sandbox-cgroups.js +42 -0
  63. package/dist/session/managed-attempt-tools.d.ts +25 -0
  64. package/dist/session/managed-attempt-tools.js +320 -27
  65. package/dist/session/managed-build-coordinator.d.ts +1 -1
  66. package/dist/session/managed-build-coordinator.js +4 -1
  67. package/dist/session/managed-command-host-load.d.ts +45 -0
  68. package/dist/session/managed-command-host-load.js +82 -0
  69. package/dist/session/phase-completion.artifacts.js +4 -0
  70. package/dist/session/phase-completion.d.ts +2 -0
  71. package/dist/session/phase-completion.runtime.d.ts +1 -1
  72. package/dist/session/phase-completion.runtime.js +36 -23
  73. package/dist/session/pre-publication-host-load.d.ts +27 -0
  74. package/dist/session/pre-publication-host-load.js +111 -0
  75. package/dist/session/pre-publication-process.d.ts +23 -0
  76. package/dist/session/pre-publication-process.js +109 -0
  77. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  78. package/dist/session/pre-publication-skipped-tests.js +109 -0
  79. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  80. package/dist/session/pre-publication-step-execution.js +49 -0
  81. package/dist/session/pre-publication-validation.d.ts +9 -9
  82. package/dist/session/pre-publication-validation.js +48 -112
  83. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  84. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  85. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  86. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  87. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  88. package/dist/session/provider-cli/provider-cli.process.js +299 -25
  89. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  90. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  91. package/dist/session/provider-cli/provider-cli.service.js +141 -33
  92. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  93. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  94. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  95. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  96. package/dist/session/provider-cli/provider-output-state.js +9 -0
  97. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  98. package/dist/session/publishable-worktree-changes.js +193 -0
  99. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  100. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  101. package/dist/session/session.base.d.ts +3 -0
  102. package/dist/session/session.service.d.ts +2 -0
  103. package/dist/session/session.service.js +21 -4
  104. package/dist/session/session.types.d.ts +3 -0
  105. package/dist/session/session.types.js +14 -2
  106. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  107. package/dist/shared/process/host-process-supervisor.js +1 -1
  108. package/dist/shared/process/process-tree.d.ts +52 -0
  109. package/dist/shared/process/process-tree.js +144 -0
  110. package/dist/shared/process/process.d.ts +67 -0
  111. package/dist/shared/process/process.js +213 -11
  112. package/dist/version.d.ts +1 -1
  113. package/dist/version.js +1 -1
  114. package/dist/worktree/dependency-warmer.d.ts +25 -0
  115. package/dist/worktree/dependency-warmer.js +46 -10
  116. package/dist/worktree/worktree.service.d.ts +6 -1
  117. package/dist/worktree/worktree.service.js +14 -2
  118. package/dist/worktree/worktree.types.d.ts +7 -0
  119. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
5
6
  import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
@@ -8,10 +9,16 @@ import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-c
8
9
  import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
9
10
  import { redactText } from "../shared/redaction/redaction.js";
10
11
  import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
12
+ import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
13
+ import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
14
+ import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
15
+ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
16
+ import { hostLoadGovernorEnvironment, hostLoadStateRootEnvironment } from "../runtime/host-load-child-environment.js";
11
17
  import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
12
18
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
13
19
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
14
20
  import { monotonicNowMs } from "../shared/time/monotonic.js";
21
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
15
22
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
16
23
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
17
24
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
@@ -41,6 +48,14 @@ const terminalManagedCommandStatuses = new Set([
41
48
  ]);
42
49
  const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
43
50
  const managedCommandTasks = new Map();
51
+ // Every command this MCP server is supervising, synchronous or not. The server is the only
52
+ // writer of their receipts, so it stops them before it exits.
53
+ const activeManagedCommands = new Map();
54
+ const ownerExitStoppedCommands = new Set();
55
+ let ownerProcessIdentity;
56
+ let managedCommandOwnerShuttingDown = false;
57
+ let ownerExitSweep = null;
58
+ const managedCommandOwnerExitMessage = "managed_command_owner_exited: Forge stopped this managed command because the Forge MCP server that supervised it is exiting; its provider process ended before the command finished. Its result is unknown; start it again if it is still needed.";
44
59
  export const managedAttemptToolNames = [
45
60
  "forge.run_managed_command",
46
61
  "run_managed_command",
@@ -55,6 +70,76 @@ export const managedAttemptToolNames = [
55
70
  "forge.reset_generated_outputs",
56
71
  "reset_generated_outputs",
57
72
  ];
73
+ /**
74
+ * Stops every managed command this MCP server started, proves each process tree stopped,
75
+ * and writes their terminal receipts. Called when the provider closes the MCP connection
76
+ * or the server is signalled: once this server exits nothing could supervise them.
77
+ */
78
+ export async function stopManagedCommandsForOwnerExit() {
79
+ // One sweep at a time: a signal that arrives while a sweep runs waits for that sweep.
80
+ ownerExitSweep ??= sweepManagedCommandsForOwnerExit().finally(() => { ownerExitSweep = null; });
81
+ await ownerExitSweep;
82
+ }
83
+ async function sweepManagedCommandsForOwnerExit() {
84
+ // From here on this server refuses new commands, so a request still being handled
85
+ // cannot launch one behind the sweep. Repeat until none is left: a launch that passed
86
+ // its last check just before the flag was set registers synchronously and is caught.
87
+ managedCommandOwnerShuttingDown = true;
88
+ while (activeManagedCommands.size > 0) {
89
+ const active = [...activeManagedCommands.entries()];
90
+ for (const [commandId, command] of active) {
91
+ ownerExitStoppedCommands.add(commandId);
92
+ command.controller.abort(new Error(managedCommandOwnerExitMessage));
93
+ }
94
+ await Promise.allSettled(active.map(([, command]) => command.task));
95
+ }
96
+ }
97
+ /** Test support: lets one test process act as a fresh MCP server after a simulated exit. */
98
+ export function resetManagedCommandOwnerShutdownForTesting() {
99
+ managedCommandOwnerShuttingDown = false;
100
+ }
101
+ function assertManagedCommandsAccepted() {
102
+ if (managedCommandOwnerShuttingDown) {
103
+ throw new Error("managed_command_unavailable: the Forge MCP server is shutting down and accepts no new managed commands.");
104
+ }
105
+ }
106
+ const ownerShutdownSignals = ["SIGTERM", "SIGHUP", "SIGINT"];
107
+ /**
108
+ * Makes a termination signal stop this server's managed commands before it exits, so none
109
+ * outlives its only supervisor. Returns a function that removes the handlers.
110
+ */
111
+ export function installOwnerShutdownHandlers(target = process, exit = code => process.exit(code)) {
112
+ const handlers = ownerShutdownSignals.map(signal => {
113
+ const handler = () => {
114
+ void stopManagedCommandsForOwnerExit().finally(() => exit(128 + os.constants.signals[signal]));
115
+ };
116
+ target.once(signal, handler);
117
+ return { signal, handler };
118
+ });
119
+ return () => {
120
+ for (const { signal, handler } of handlers)
121
+ target.removeListener(signal, handler);
122
+ };
123
+ }
124
+ /**
125
+ * Runs an MCP server body, then stops every managed command it started before returning.
126
+ * The signal handlers stay installed until that stop completes: a signal during the body
127
+ * or the stop exits only after the same stop finishes, never by Node's default exit.
128
+ */
129
+ export async function runWithOwnerShutdown(body, target = process, exit = code => process.exit(code)) {
130
+ const removeShutdownHandlers = installOwnerShutdownHandlers(target, exit);
131
+ try {
132
+ return await body();
133
+ }
134
+ finally {
135
+ try {
136
+ await stopManagedCommandsForOwnerExit();
137
+ }
138
+ finally {
139
+ removeShutdownHandlers();
140
+ }
141
+ }
142
+ }
58
143
  export function isManagedAttemptTool(name) {
59
144
  return managedCommandNames.has(name)
60
145
  || startManagedCommandNames.has(name)
@@ -175,6 +260,7 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
175
260
  return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
176
261
  }
177
262
  async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
263
+ assertManagedCommandsAccepted();
178
264
  const command = requiredInputString(record, "command");
179
265
  const args = requiredStringArray(record, "args");
180
266
  const timeoutMs = optionalTimeout(record.timeout_ms);
@@ -199,6 +285,7 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
199
285
  worktreePath,
200
286
  buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
201
287
  buildReceiptReuse,
288
+ controller: new AbortController(),
202
289
  };
203
290
  if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
204
291
  const started = managedCommandResult({
@@ -208,9 +295,25 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
208
295
  exitCode: null,
209
296
  stdout: "",
210
297
  stderr: "",
298
+ launchRequested: false,
211
299
  });
212
300
  await persistManagedCommandReceipt(receiptPath, started.structuredContent);
213
- const task = executeManagedCommand(invocation);
301
+ if (managedCommandOwnerShuttingDown) {
302
+ // Shutdown began while the receipt was written; the command never starts.
303
+ const refused = managedCommandResult({
304
+ ...invocation,
305
+ timedOut: false,
306
+ status: "runner_error",
307
+ exitCode: null,
308
+ stdout: "",
309
+ stderr: appendBounded("", managedCommandOwnerExitMessage),
310
+ launchRequested: false,
311
+ terminationReason: "owner_exited",
312
+ });
313
+ await persistManagedCommandReceipt(receiptPath, refused.structuredContent);
314
+ assertManagedCommandsAccepted();
315
+ }
316
+ const task = trackManagedCommand(invocation);
214
317
  managedCommandTasks.set(commandId, task);
215
318
  void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
216
319
  return {
@@ -221,7 +324,16 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
221
324
  }],
222
325
  };
223
326
  }
224
- return await executeManagedCommand(invocation);
327
+ return await trackManagedCommand(invocation);
328
+ }
329
+ function trackManagedCommand(invocation) {
330
+ const task = executeManagedCommand(invocation);
331
+ activeManagedCommands.set(invocation.commandId, { controller: invocation.controller, task });
332
+ void task.finally(() => {
333
+ activeManagedCommands.delete(invocation.commandId);
334
+ ownerExitStoppedCommands.delete(invocation.commandId);
335
+ }).catch(() => undefined);
336
+ return task;
225
337
  }
226
338
  async function startManagedVerification(input, worktreePath) {
227
339
  const record = asRecord(input);
@@ -381,22 +493,100 @@ function optionValue(args, name) {
381
493
  const index = args.indexOf(name);
382
494
  return index >= 0 ? args[index + 1]?.trim() || null : null;
383
495
  }
496
+ function hostCapacityLossReason(reason) {
497
+ if (reason instanceof HostCapacityTokenFencedError)
498
+ return "host_capacity_token_fenced";
499
+ if (reason instanceof HostCapacityLedgerUnavailableError)
500
+ return "host_capacity_ledger_unavailable";
501
+ return null;
502
+ }
384
503
  async function executeManagedCommand(invocation) {
385
- if (!invocation.buildProducing)
386
- return await executeManagedCommandProcess(invocation);
387
- return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs }), async () => {
388
- const waiting = managedCommandResult({
504
+ let processStarted = false;
505
+ // The per-worktree build slot is taken first: holding a host token while
506
+ // queued behind this worktree's own build would waste host capacity.
507
+ const hostCapacity = new ManagedCommandHostCapacity({ ...invocation, label: invocation.verificationProfile ?? invocation.commandId }, async (hostLoad) => await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
508
+ ...invocation,
509
+ hostLoad,
510
+ timedOut: false,
511
+ status: "waiting_for_host_capacity",
512
+ exitCode: null,
513
+ stdout: "",
514
+ stderr: "",
515
+ launchRequested: false,
516
+ }).structuredContent));
517
+ const launch = async (buildQueueWaitMs) => await hostCapacity.run(invocation.controller.signal, async (hostLoad, control) => {
518
+ processStarted = true;
519
+ // A reclaimed token means this command's capacity is gone: it stops. A fence that
520
+ // landed between admission and here stops it too (a listener added now never fires).
521
+ const stopOnFence = () => invocation.controller.abort(control.fenced.reason);
522
+ if (control.fenced?.aborted)
523
+ stopOnFence();
524
+ else
525
+ control.fenced?.addEventListener("abort", stopOnFence, { once: true });
526
+ try {
527
+ return await executeManagedCommandProcess({
528
+ ...invocation,
529
+ buildQueueWaitMs,
530
+ hostLoad,
531
+ // Recording the tree is part of holding the token: if it fails (the token was
532
+ // fenced meanwhile, or the ledger refused), the command stops instead of
533
+ // running on without a reservation the host can account for.
534
+ // Checked against the tree recorded on the token at launch (null: the governor's own).
535
+ holdHostCapacityUntilStopped: reason => control.holdUntilStopped?.(null, reason),
536
+ onProcessStarted: async () => await attachManagedCommandProcess(control, invocation.metadataPath)
537
+ .catch((error) => {
538
+ invocation.controller.abort(error instanceof HostCapacityTokenFencedError || error instanceof HostCapacityLedgerUnavailableError
539
+ ? error
540
+ : new HostCapacityLedgerUnavailableError(`the managed command's process tree could not be recorded on its host load token: ${error instanceof Error ? error.message : String(error)}`, { cause: error }));
541
+ }),
542
+ });
543
+ }
544
+ finally {
545
+ control.fenced?.removeEventListener("abort", stopOnFence);
546
+ }
547
+ },
548
+ // A fenced release is already the receipt's termination reason; only a ledger fault is noted.
549
+ async (error) => error instanceof HostCapacityTokenFencedError ? undefined : await annotateManagedCommandReceipt(invocation.receiptPath, {
550
+ host_capacity_release_error: redactText(error instanceof Error ? error.message : String(error), []),
551
+ }));
552
+ try {
553
+ if (!invocation.buildProducing)
554
+ return await launch();
555
+ return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, launch, async () => {
556
+ const waiting = managedCommandResult({
557
+ ...invocation,
558
+ timedOut: false,
559
+ status: "waiting_for_build_slot",
560
+ exitCode: null,
561
+ stdout: "",
562
+ stderr: "",
563
+ launchRequested: false,
564
+ });
565
+ await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
566
+ }, invocation.controller.signal);
567
+ }
568
+ catch (error) {
569
+ if (processStarted)
570
+ throw error;
571
+ // The command never started (its build-slot or host-capacity wait failed or was
572
+ // stopped). Its receipt must still become terminal, or a waiting agent sees it queued forever.
573
+ const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
574
+ const receipt = managedCommandResult({
389
575
  ...invocation,
576
+ hostLoad: await hostCapacity.unadmittedFields(error),
390
577
  timedOut: false,
391
- status: "waiting_for_build_slot",
578
+ status: "runner_error",
392
579
  exitCode: null,
393
580
  stdout: "",
394
- stderr: "",
581
+ stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
582
+ terminationReason: ownerExited ? "owner_exited" : undefined,
583
+ launchRequested: false,
395
584
  });
396
- await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
397
- });
585
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
586
+ return managedCommandPublicResult(receipt);
587
+ }
398
588
  }
399
- async function executeManagedCommandProcess(invocation) {
589
+ async function managedCommandProcessEnvironment(invocation) {
400
590
  assertHostDatabaseCapabilityBoundary();
401
591
  const databaseEnvironment = invocation.verificationProfile
402
592
  ? await managedVerificationDatabaseEnvironment()
@@ -430,9 +620,32 @@ async function executeManagedCommandProcess(invocation) {
430
620
  }
431
621
  : {}),
432
622
  });
623
+ return { environment, exactSecrets };
624
+ }
625
+ async function executeManagedCommandProcess(invocation) {
626
+ let prepared;
627
+ try {
628
+ prepared = await managedCommandProcessEnvironment(invocation);
629
+ }
630
+ catch (error) {
631
+ // The call still fails (the database capability boundary or the verification
632
+ // database probe refused it), but its receipt must not stay "starting" forever.
633
+ const receipt = managedCommandResult({
634
+ ...invocation,
635
+ timedOut: false,
636
+ status: "runner_error",
637
+ exitCode: null,
638
+ stdout: "",
639
+ stderr: appendBounded("", redactText(error instanceof Error ? error.message : String(error), [])),
640
+ launchRequested: false,
641
+ });
642
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent).catch(() => undefined);
643
+ throw error;
644
+ }
645
+ const { exactSecrets } = prepared;
433
646
  let stdout = "";
434
647
  let stderr = "";
435
- const controller = new AbortController();
648
+ const controller = invocation.controller;
436
649
  let timedOut = false;
437
650
  let timer = null;
438
651
  let outputRevision = 0;
@@ -465,15 +678,29 @@ async function executeManagedCommandProcess(invocation) {
465
678
  controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
466
679
  }, managedCommandLaunchTimeoutMs);
467
680
  try {
681
+ if (controller.signal.aborted)
682
+ throw controller.signal.reason;
683
+ // Recorded before the spawn: the process record is written only once the child has
684
+ // spawned, so teardown must know a launch may exist without one.
685
+ await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
686
+ ...invocation,
687
+ timedOut: false,
688
+ status: "starting",
689
+ exitCode: null,
690
+ stdout,
691
+ stderr,
692
+ }).structuredContent);
468
693
  const result = await new StreamingProviderProcessRunner().run({
469
694
  command: invocation.command,
470
695
  args: invocation.args,
471
696
  cwd: invocation.cwd,
472
- env: environment,
697
+ env: prepared.environment,
473
698
  captureOutput: false,
474
699
  }, {
475
700
  onStarted: async () => {
476
701
  clearTimeout(launchTimer);
702
+ // onProcessStarted stops the command itself when its token cannot be held.
703
+ await invocation.onProcessStarted?.();
477
704
  const running = managedCommandResult({
478
705
  ...invocation,
479
706
  timedOut: false,
@@ -517,7 +744,20 @@ async function executeManagedCommandProcess(invocation) {
517
744
  },
518
745
  }, controller.signal);
519
746
  await settleProgress();
520
- const status = timedOut ? "timed_out" : result.exitCode === 0 ? "pass" : "fail";
747
+ // Only a stop that interrupted the process relabels it. A command that exited on its own
748
+ // just before its owner asked for the stop keeps its real result.
749
+ const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
750
+ const hostCapacityLoss = !timedOut && !ownerExited && result.cancelled === true
751
+ ? hostCapacityLossReason(controller.signal.reason)
752
+ : null;
753
+ const fenced = hostCapacityLoss !== null;
754
+ if (ownerExited || fenced) {
755
+ stderr = appendBounded(stderr, ownerExited ? managedCommandOwnerExitMessage : controller.signal.reason.message);
756
+ outputRevision += 1;
757
+ lastOutputAt = Date.now();
758
+ lastOutputStream = "stderr";
759
+ }
760
+ const status = timedOut ? "timed_out" : ownerExited || fenced ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
521
761
  const receiptCoverage = managedBuildReceiptCoverage(invocation);
522
762
  const buildReceipt = status === "pass" && receiptCoverage
523
763
  ? await publishManagedBuildReceipt({
@@ -540,6 +780,9 @@ async function executeManagedCommandProcess(invocation) {
540
780
  lastOutputStream,
541
781
  buildReceipt,
542
782
  buildReceiptReused: invocation.buildReceiptReuse !== undefined,
783
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLoss ?? undefined,
784
+ // The runner resolves only after the stopped tree is proven gone.
785
+ processTreeTerminated: ownerExited || fenced ? true : undefined,
543
786
  });
544
787
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
545
788
  return managedCommandPublicResult(receipt);
@@ -547,7 +790,10 @@ async function executeManagedCommandProcess(invocation) {
547
790
  catch (error) {
548
791
  // The failure may be a progress write itself; it is reported below.
549
792
  await settleProgress().catch(() => undefined);
550
- const message = redactText(error instanceof Error ? error.message : String(error), exactSecrets);
793
+ const ownerExited = !timedOut && ownerExitStoppedCommands.has(invocation.commandId);
794
+ const message = ownerExited
795
+ ? managedCommandOwnerExitMessage
796
+ : redactText(error instanceof Error ? error.message : String(error), exactSecrets);
551
797
  stderr = appendBounded(stderr, message);
552
798
  outputRevision += 1;
553
799
  lastOutputAt = Date.now();
@@ -562,8 +808,17 @@ async function executeManagedCommandProcess(invocation) {
562
808
  outputRevision,
563
809
  lastOutputAt,
564
810
  lastOutputStream,
811
+ // A host capacity loss before launch (a fence that landed while it was admitted) is named too.
812
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLossReason(controller.signal.reason) ?? undefined,
813
+ // The runner rejected, so its tree was not proven stopped; teardown still stops it.
814
+ processTreeTerminated: false,
565
815
  });
566
816
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
817
+ // The runner stops the tree before it rejects; only a failed termination proof means
818
+ // part of it may still run. Its token is then kept, never returned with this receipt.
819
+ if (isProcessTreeTerminationUnproven(error)) {
820
+ invocation.holdHostCapacityUntilStopped?.(error instanceof Error ? error : new Error(String(error)));
821
+ }
567
822
  return managedCommandPublicResult(receipt);
568
823
  }
569
824
  finally {
@@ -587,6 +842,11 @@ async function readManagedCommand(input) {
587
842
  }
588
843
  throw error;
589
844
  }
845
+ // A queued receipt is written once; its wait so far is computed when it is read.
846
+ const hostLoadWaitStartedAt = Date.parse(String(receipt.host_load_wait_started_at));
847
+ if (receipt.status === "waiting_for_host_capacity" && Number.isFinite(hostLoadWaitStartedAt)) {
848
+ receipt = { ...receipt, host_load_wait_ms: Math.max(0, Date.now() - hostLoadWaitStartedAt) };
849
+ }
590
850
  const status = typeof receipt.status === "string" ? receipt.status : "unknown";
591
851
  const stdout = typeof receipt.stdout === "string" ? receipt.stdout : "";
592
852
  const stderr = typeof receipt.stderr === "string" ? receipt.stderr : "";
@@ -637,20 +897,23 @@ async function waitManagedCommand(input) {
637
897
  const elapsedMs = receipt.structuredContent.elapsed_ms;
638
898
  const timeoutMs = receipt.structuredContent.timeout_ms;
639
899
  const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
640
- const progress = receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
641
- ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
642
- + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
643
- + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
644
- // Agents otherwise abandon long verification tiers and record a blocker that is not one.
645
- + (typeof timeoutMs === "number"
646
- ? ` Forge itself ends it at its ${Math.round(timeoutMs / 60_000)}-minute limit if it hangs, so keep waiting; a running command is not a blocker.`
647
- : "")
648
- : "";
900
+ const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
901
+ 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.`
903
+ : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
904
+ ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
905
+ + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
906
+ + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
907
+ // Agents otherwise abandon long verification tiers and record a blocker that is not one.
908
+ + (typeof timeoutMs === "number"
909
+ ? ` Forge itself ends it at its ${Math.round(timeoutMs / 60_000)}-minute limit if it hangs, so keep waiting; a running command is not a blocker.`
910
+ : "")
911
+ : "";
649
912
  return {
650
913
  ...receipt,
651
914
  content: [{
652
915
  type: "text",
653
- text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Its durable receipt remains at ${receiptPath}.`,
916
+ text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Do not end your turn to wait for it: Forge ends the provider run shortly after a turn ends, which stops background monitors and this command. Its durable receipt remains at ${receiptPath}.`,
654
917
  }],
655
918
  structuredContent: {
656
919
  ...receipt.structuredContent,
@@ -690,7 +953,9 @@ async function persistManagedCommandReceipt(receiptPath, receipt) {
690
953
  }
691
954
  }
692
955
  function managedCommandResult(values) {
693
- const elapsedMs = Date.now() - values.startedAt;
956
+ // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
957
+ const hostLoad = values.hostLoad;
958
+ const elapsedMs = Date.now() - (hostLoad ? hostLoad.executionStartedAt ?? Date.now() : values.startedAt);
694
959
  const isTerminal = terminalManagedCommandStatuses.has(values.status);
695
960
  const diagnostics = isTerminal
696
961
  ? managedCommandDiagnostics(values.stdout, values.stderr)
@@ -735,6 +1000,7 @@ function managedCommandResult(values) {
735
1000
  build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
736
1001
  build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
737
1002
  build_receipt_reused: values.buildReceiptReused ?? false,
1003
+ ...(hostLoad ? managedCommandHostLoadReceipt(hostLoad) : {}),
738
1004
  build_receipt: values.buildReceipt ? {
739
1005
  fingerprint: values.buildReceipt.fingerprint,
740
1006
  receipt_path: values.buildReceipt.receiptPath,
@@ -744,11 +1010,34 @@ function managedCommandResult(values) {
744
1010
  output_count: values.buildReceipt.outputCount,
745
1011
  } : null,
746
1012
  runtime_configuration: managedRuntimeConfiguration(),
747
- process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : undefined,
1013
+ // The supervising MCP server process. Forge stops a command whose owner has exited.
1014
+ owner_pid: process.pid,
1015
+ owner_identity: managedCommandOwnerIdentity(),
1016
+ launch_requested: values.launchRequested ?? true,
1017
+ process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : values.processTreeTerminated,
1018
+ ...(values.terminationReason ? { termination_reason: values.terminationReason } : {}),
748
1019
  },
749
1020
  isError: isTerminal && values.status !== "pass",
750
1021
  };
751
1022
  }
1023
+ function managedCommandHostLoadReceipt(hostLoad) {
1024
+ const waiting = hostLoad.waitStartedAt !== undefined;
1025
+ return {
1026
+ host_load_step_class: hostLoad.stepClass,
1027
+ 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() } : {}),
1029
+ };
1030
+ }
1031
+ async function annotateManagedCommandReceipt(receiptPath, fields) {
1032
+ const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
1033
+ await persistManagedCommandReceipt(receiptPath, { ...receipt, ...fields });
1034
+ }
1035
+ /** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
1036
+ function managedCommandOwnerIdentity() {
1037
+ // Windows identity capture starts PowerShell; the PID check alone is used there.
1038
+ ownerProcessIdentity ??= process.platform === "linux" ? captureHostProcessIdentity(process.pid) : null;
1039
+ return ownerProcessIdentity;
1040
+ }
752
1041
  function managedRuntimeConfiguration() {
753
1042
  const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
754
1043
  let providerOnlySpecCount = 0;
@@ -819,6 +1108,10 @@ async function containedWorkingDirectory(worktreePath, input) {
819
1108
  function inheritedEnvironment(overrides) {
820
1109
  const env = {};
821
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;
822
1115
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
823
1116
  env[key] = value;
824
1117
  }
@@ -1,5 +1,5 @@
1
1
  export declare class ManagedBuildCoordinator {
2
2
  private readonly stateRoot;
3
3
  constructor(stateRoot?: string);
4
- withBuildSlot<T>(worktreePath: string, action: (queueWaitMs: number) => Promise<T>, onWaiting?: () => Promise<void>): Promise<T>;
4
+ withBuildSlot<T>(worktreePath: string, action: (queueWaitMs: number) => Promise<T>, onWaiting?: () => Promise<void>, signal?: AbortSignal): Promise<T>;
5
5
  }
@@ -12,7 +12,7 @@ export class ManagedBuildCoordinator {
12
12
  constructor(stateRoot = defaultWorktreeCoordinatorStateRoot()) {
13
13
  this.stateRoot = stateRoot;
14
14
  }
15
- async withBuildSlot(worktreePath, action, onWaiting) {
15
+ async withBuildSlot(worktreePath, action, onWaiting, signal) {
16
16
  const resolved = path.resolve(worktreePath);
17
17
  const key = createHash("sha256").update(resolved.toLowerCase()).digest("hex");
18
18
  const root = path.join(this.stateRoot, "managed-build-locks");
@@ -22,6 +22,9 @@ export class ManagedBuildCoordinator {
22
22
  let waitingReported = false;
23
23
  await fs.mkdir(root, { recursive: true, mode: 0o700 });
24
24
  while (true) {
25
+ if (signal?.aborted) {
26
+ throw signal.reason instanceof Error ? signal.reason : new Error("managed_build_slot_cancelled: the build-slot wait was cancelled.");
27
+ }
25
28
  try {
26
29
  const handle = await fs.open(target, "wx", 0o600);
27
30
  try {
@@ -0,0 +1,45 @@
1
+ import { type HostLoadStepGate } from "../runtime/host-load-governor.js";
2
+ import { type HostLoadStepClassification, type ManagedCommandStepInput } from "../runtime/host-load-step-class.js";
3
+ import { type HostLoadStepControl } from "../runtime/host-load-step-run.js";
4
+ /** Host-load facts a managed command receipt carries; absent while the governor is off. */
5
+ export interface ManagedCommandHostLoadFields {
6
+ readonly stepClass: string;
7
+ /** Queue time before admission; never part of elapsed_ms. */
8
+ readonly waitMs: number;
9
+ /** Set while the command is still queued: the receipt reports the wait so far. */
10
+ readonly waitStartedAt?: number;
11
+ /** When the command was admitted; elapsed_ms counts from here. */
12
+ readonly executionStartedAt?: number;
13
+ }
14
+ /** This MCP server's governor, built once from the environment the bridge handed it. */
15
+ export declare function managedCommandHostLoadGate(): HostLoadStepGate | undefined;
16
+ /** Test support: installs a gate (undefined disables it; null rebuilds from the environment). */
17
+ export declare function setManagedCommandHostLoadGateForTesting(value: HostLoadStepGate | undefined | null): void;
18
+ /**
19
+ * Admits one managed command. The waiting receipt is written while the command
20
+ * is queued and always lands before the launch receipts, so a stale "waiting"
21
+ * write can never replace a later status.
22
+ */
23
+ export declare class ManagedCommandHostCapacity {
24
+ private readonly persistWaiting;
25
+ private readonly gateFor;
26
+ readonly classification: HostLoadStepClassification;
27
+ private readonly label;
28
+ private requestedAtMs;
29
+ private waitingWrite;
30
+ constructor(input: ManagedCommandStepInput & {
31
+ readonly label: string;
32
+ }, persistWaiting: (fields: ManagedCommandHostLoadFields) => Promise<void>, gateFor?: () => HostLoadStepGate | undefined);
33
+ /** Runs `launch` once admitted; `fields` is undefined with the governor off. */
34
+ run<T>(signal: AbortSignal, launch: (fields: ManagedCommandHostLoadFields | undefined, control: HostLoadStepControl) => Promise<T>, onReleaseFailed?: (error: unknown) => Promise<void>): Promise<T>;
35
+ /**
36
+ * Host-load facts for a command that was never admitted (it timed out in
37
+ * the queue or was stopped while waiting), once its waiting receipt landed.
38
+ */
39
+ unadmittedFields(error: unknown): Promise<ManagedCommandHostLoadFields | undefined>;
40
+ }
41
+ /**
42
+ * The managed command's process tree as its supervisor recorded it, for its
43
+ * host load token: a reclaim then stops exactly this tree before reuse.
44
+ */
45
+ export declare function attachManagedCommandProcess(control: HostLoadStepControl, metadataPath: string): Promise<void>;