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

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 (62) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/bridge.service.d.ts +12 -1
  3. package/dist/bridge/bridge.service.js +53 -6
  4. package/dist/bridge/bridge.types.d.ts +6 -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/cli/cli.help.js +2 -2
  8. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  9. package/dist/runtime/attempt-database-broker.js +390 -0
  10. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  11. package/dist/runtime/attempt-process-supervisor.js +77 -3
  12. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  13. package/dist/runtime/host-database-capability-boundary.js +1 -0
  14. package/dist/runtime/host-diagnostics.js +4 -3
  15. package/dist/runtime/host-facts.d.ts +35 -0
  16. package/dist/runtime/host-facts.js +95 -0
  17. package/dist/runtime/host-load-sampler.d.ts +83 -0
  18. package/dist/runtime/host-load-sampler.js +164 -0
  19. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  20. package/dist/runtime/host-pressure-stall.js +121 -0
  21. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  22. package/dist/runtime/host-runtime-contract.js +71 -10
  23. package/dist/runtime/host-runtime-lease.d.ts +4 -2
  24. package/dist/runtime/host-runtime-lease.js +108 -24
  25. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  26. package/dist/runtime/managed-command-teardown.js +607 -0
  27. package/dist/runtime/node-host-runtime-adapter.js +5 -4
  28. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  29. package/dist/runtime/playwright-browser-cache.js +227 -0
  30. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  31. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  32. package/dist/sandbox/repository-lock.js +3 -2
  33. package/dist/sandbox/runtime.js +5 -4
  34. package/dist/session/managed-attempt-tools.d.ts +25 -0
  35. package/dist/session/managed-attempt-tools.js +222 -20
  36. package/dist/session/managed-build-coordinator.d.ts +1 -1
  37. package/dist/session/managed-build-coordinator.js +8 -4
  38. package/dist/session/phase-completion.artifacts.js +4 -0
  39. package/dist/session/phase-completion.runtime.js +30 -18
  40. package/dist/session/pre-publication-process.d.ts +20 -0
  41. package/dist/session/pre-publication-process.js +97 -0
  42. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  43. package/dist/session/pre-publication-skipped-tests.js +109 -0
  44. package/dist/session/pre-publication-validation.js +32 -58
  45. package/dist/session/provider-cli/provider-cli.artifacts.js +2 -9
  46. package/dist/session/provider-cli/provider-cli.process.d.ts +6 -1
  47. package/dist/session/provider-cli/provider-cli.process.js +198 -16
  48. package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
  49. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  50. package/dist/session/provider-cli/provider-cli.service.js +64 -12
  51. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  52. package/dist/session/publishable-worktree-changes.d.ts +45 -0
  53. package/dist/session/publishable-worktree-changes.js +177 -0
  54. package/dist/session/session.types.js +3 -0
  55. package/dist/shared/process/host-process-recovery.js +3 -2
  56. package/dist/shared/process/host-process-supervisor.js +5 -4
  57. package/dist/shared/time/monotonic.d.ts +1 -0
  58. package/dist/shared/time/monotonic.js +8 -0
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/worktree/dependency-warmer.js +74 -0
  62. package/package.json +1 -1
@@ -1,8 +1,10 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
5
6
  import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
7
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
6
8
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
7
9
  import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
8
10
  import { redactText } from "../shared/redaction/redaction.js";
@@ -10,6 +12,8 @@ import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
10
12
  import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
11
13
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
12
14
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
15
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
16
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
13
17
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
14
18
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
15
19
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
@@ -39,6 +43,14 @@ const terminalManagedCommandStatuses = new Set([
39
43
  ]);
40
44
  const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
41
45
  const managedCommandTasks = new Map();
46
+ // Every command this MCP server is supervising, synchronous or not. The server is the only
47
+ // writer of their receipts, so it stops them before it exits.
48
+ const activeManagedCommands = new Map();
49
+ const ownerExitStoppedCommands = new Set();
50
+ let ownerProcessIdentity;
51
+ let managedCommandOwnerShuttingDown = false;
52
+ let ownerExitSweep = null;
53
+ const managedCommandOwnerExitMessage = "managed_command_owner_exited: Forge stopped this managed command because the Forge MCP server that supervised it is exiting; its provider process ended before the command finished. Its result is unknown; start it again if it is still needed.";
42
54
  export const managedAttemptToolNames = [
43
55
  "forge.run_managed_command",
44
56
  "run_managed_command",
@@ -53,6 +65,76 @@ export const managedAttemptToolNames = [
53
65
  "forge.reset_generated_outputs",
54
66
  "reset_generated_outputs",
55
67
  ];
68
+ /**
69
+ * Stops every managed command this MCP server started, proves each process tree stopped,
70
+ * and writes their terminal receipts. Called when the provider closes the MCP connection
71
+ * or the server is signalled: once this server exits nothing could supervise them.
72
+ */
73
+ export async function stopManagedCommandsForOwnerExit() {
74
+ // One sweep at a time: a signal that arrives while a sweep runs waits for that sweep.
75
+ ownerExitSweep ??= sweepManagedCommandsForOwnerExit().finally(() => { ownerExitSweep = null; });
76
+ await ownerExitSweep;
77
+ }
78
+ async function sweepManagedCommandsForOwnerExit() {
79
+ // From here on this server refuses new commands, so a request still being handled
80
+ // cannot launch one behind the sweep. Repeat until none is left: a launch that passed
81
+ // its last check just before the flag was set registers synchronously and is caught.
82
+ managedCommandOwnerShuttingDown = true;
83
+ while (activeManagedCommands.size > 0) {
84
+ const active = [...activeManagedCommands.entries()];
85
+ for (const [commandId, command] of active) {
86
+ ownerExitStoppedCommands.add(commandId);
87
+ command.controller.abort(new Error(managedCommandOwnerExitMessage));
88
+ }
89
+ await Promise.allSettled(active.map(([, command]) => command.task));
90
+ }
91
+ }
92
+ /** Test support: lets one test process act as a fresh MCP server after a simulated exit. */
93
+ export function resetManagedCommandOwnerShutdownForTesting() {
94
+ managedCommandOwnerShuttingDown = false;
95
+ }
96
+ function assertManagedCommandsAccepted() {
97
+ if (managedCommandOwnerShuttingDown) {
98
+ throw new Error("managed_command_unavailable: the Forge MCP server is shutting down and accepts no new managed commands.");
99
+ }
100
+ }
101
+ const ownerShutdownSignals = ["SIGTERM", "SIGHUP", "SIGINT"];
102
+ /**
103
+ * Makes a termination signal stop this server's managed commands before it exits, so none
104
+ * outlives its only supervisor. Returns a function that removes the handlers.
105
+ */
106
+ export function installOwnerShutdownHandlers(target = process, exit = code => process.exit(code)) {
107
+ const handlers = ownerShutdownSignals.map(signal => {
108
+ const handler = () => {
109
+ void stopManagedCommandsForOwnerExit().finally(() => exit(128 + os.constants.signals[signal]));
110
+ };
111
+ target.once(signal, handler);
112
+ return { signal, handler };
113
+ });
114
+ return () => {
115
+ for (const { signal, handler } of handlers)
116
+ target.removeListener(signal, handler);
117
+ };
118
+ }
119
+ /**
120
+ * Runs an MCP server body, then stops every managed command it started before returning.
121
+ * The signal handlers stay installed until that stop completes: a signal during the body
122
+ * or the stop exits only after the same stop finishes, never by Node's default exit.
123
+ */
124
+ export async function runWithOwnerShutdown(body, target = process, exit = code => process.exit(code)) {
125
+ const removeShutdownHandlers = installOwnerShutdownHandlers(target, exit);
126
+ try {
127
+ return await body();
128
+ }
129
+ finally {
130
+ try {
131
+ await stopManagedCommandsForOwnerExit();
132
+ }
133
+ finally {
134
+ removeShutdownHandlers();
135
+ }
136
+ }
137
+ }
56
138
  export function isManagedAttemptTool(name) {
57
139
  return managedCommandNames.has(name)
58
140
  || startManagedCommandNames.has(name)
@@ -173,6 +255,7 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
173
255
  return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
174
256
  }
175
257
  async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
258
+ assertManagedCommandsAccepted();
176
259
  const command = requiredInputString(record, "command");
177
260
  const args = requiredStringArray(record, "args");
178
261
  const timeoutMs = optionalTimeout(record.timeout_ms);
@@ -197,6 +280,7 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
197
280
  worktreePath,
198
281
  buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
199
282
  buildReceiptReuse,
283
+ controller: new AbortController(),
200
284
  };
201
285
  if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
202
286
  const started = managedCommandResult({
@@ -206,9 +290,25 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
206
290
  exitCode: null,
207
291
  stdout: "",
208
292
  stderr: "",
293
+ launchRequested: false,
209
294
  });
210
295
  await persistManagedCommandReceipt(receiptPath, started.structuredContent);
211
- const task = executeManagedCommand(invocation);
296
+ if (managedCommandOwnerShuttingDown) {
297
+ // Shutdown began while the receipt was written; the command never starts.
298
+ const refused = managedCommandResult({
299
+ ...invocation,
300
+ timedOut: false,
301
+ status: "runner_error",
302
+ exitCode: null,
303
+ stdout: "",
304
+ stderr: appendBounded("", managedCommandOwnerExitMessage),
305
+ launchRequested: false,
306
+ terminationReason: "owner_exited",
307
+ });
308
+ await persistManagedCommandReceipt(receiptPath, refused.structuredContent);
309
+ assertManagedCommandsAccepted();
310
+ }
311
+ const task = trackManagedCommand(invocation);
212
312
  managedCommandTasks.set(commandId, task);
213
313
  void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
214
314
  return {
@@ -219,7 +319,16 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
219
319
  }],
220
320
  };
221
321
  }
222
- return await executeManagedCommand(invocation);
322
+ return await trackManagedCommand(invocation);
323
+ }
324
+ function trackManagedCommand(invocation) {
325
+ const task = executeManagedCommand(invocation);
326
+ activeManagedCommands.set(invocation.commandId, { controller: invocation.controller, task });
327
+ void task.finally(() => {
328
+ activeManagedCommands.delete(invocation.commandId);
329
+ ownerExitStoppedCommands.delete(invocation.commandId);
330
+ }).catch(() => undefined);
331
+ return task;
223
332
  }
224
333
  async function startManagedVerification(input, worktreePath) {
225
334
  const record = asRecord(input);
@@ -382,25 +491,54 @@ function optionValue(args, name) {
382
491
  async function executeManagedCommand(invocation) {
383
492
  if (!invocation.buildProducing)
384
493
  return await executeManagedCommandProcess(invocation);
385
- return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs }), async () => {
386
- const waiting = managedCommandResult({
494
+ let processStarted = false;
495
+ try {
496
+ return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => {
497
+ processStarted = true;
498
+ return await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs });
499
+ }, async () => {
500
+ const waiting = managedCommandResult({
501
+ ...invocation,
502
+ timedOut: false,
503
+ status: "waiting_for_build_slot",
504
+ exitCode: null,
505
+ stdout: "",
506
+ stderr: "",
507
+ launchRequested: false,
508
+ });
509
+ await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
510
+ }, invocation.controller.signal);
511
+ }
512
+ catch (error) {
513
+ if (processStarted)
514
+ throw error;
515
+ // The command never started (its build-slot wait failed or was stopped). Its receipt
516
+ // must still become terminal, or a waiting agent sees it queued forever.
517
+ const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
518
+ const receipt = managedCommandResult({
387
519
  ...invocation,
388
520
  timedOut: false,
389
- status: "waiting_for_build_slot",
521
+ status: "runner_error",
390
522
  exitCode: null,
391
523
  stdout: "",
392
- stderr: "",
524
+ stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
525
+ terminationReason: ownerExited ? "owner_exited" : undefined,
526
+ launchRequested: false,
393
527
  });
394
- await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
395
- });
528
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
529
+ return managedCommandPublicResult(receipt);
530
+ }
396
531
  }
397
- async function executeManagedCommandProcess(invocation) {
532
+ async function managedCommandProcessEnvironment(invocation) {
398
533
  assertHostDatabaseCapabilityBoundary();
399
534
  const databaseEnvironment = invocation.verificationProfile
400
535
  ? await managedVerificationDatabaseEnvironment()
401
536
  : {};
402
- const exactSecrets = Object.values(databaseEnvironment)
403
- .filter(value => value !== nativeTestPostgresFallbackDatabaseMode);
537
+ const exactSecrets = [
538
+ ...Object.values(databaseEnvironment).filter(value => value !== nativeTestPostgresFallbackDatabaseMode),
539
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
540
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
541
+ ];
404
542
  const environment = inheritedEnvironment({
405
543
  FORGE_RUNTIME_MODE: "host",
406
544
  FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
@@ -425,9 +563,32 @@ async function executeManagedCommandProcess(invocation) {
425
563
  }
426
564
  : {}),
427
565
  });
566
+ return { environment, exactSecrets };
567
+ }
568
+ async function executeManagedCommandProcess(invocation) {
569
+ let prepared;
570
+ try {
571
+ prepared = await managedCommandProcessEnvironment(invocation);
572
+ }
573
+ catch (error) {
574
+ // The call still fails (the database capability boundary or the verification
575
+ // database probe refused it), but its receipt must not stay "starting" forever.
576
+ const receipt = managedCommandResult({
577
+ ...invocation,
578
+ timedOut: false,
579
+ status: "runner_error",
580
+ exitCode: null,
581
+ stdout: "",
582
+ stderr: appendBounded("", redactText(error instanceof Error ? error.message : String(error), [])),
583
+ launchRequested: false,
584
+ });
585
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent).catch(() => undefined);
586
+ throw error;
587
+ }
588
+ const { exactSecrets } = prepared;
428
589
  let stdout = "";
429
590
  let stderr = "";
430
- const controller = new AbortController();
591
+ const controller = invocation.controller;
431
592
  let timedOut = false;
432
593
  let timer = null;
433
594
  let outputRevision = 0;
@@ -460,11 +621,23 @@ async function executeManagedCommandProcess(invocation) {
460
621
  controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
461
622
  }, managedCommandLaunchTimeoutMs);
462
623
  try {
624
+ if (controller.signal.aborted)
625
+ throw controller.signal.reason;
626
+ // Recorded before the spawn: the process record is written only once the child has
627
+ // spawned, so teardown must know a launch may exist without one.
628
+ await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
629
+ ...invocation,
630
+ timedOut: false,
631
+ status: "starting",
632
+ exitCode: null,
633
+ stdout,
634
+ stderr,
635
+ }).structuredContent);
463
636
  const result = await new StreamingProviderProcessRunner().run({
464
637
  command: invocation.command,
465
638
  args: invocation.args,
466
639
  cwd: invocation.cwd,
467
- env: environment,
640
+ env: prepared.environment,
468
641
  captureOutput: false,
469
642
  }, {
470
643
  onStarted: async () => {
@@ -512,7 +685,16 @@ async function executeManagedCommandProcess(invocation) {
512
685
  },
513
686
  }, controller.signal);
514
687
  await settleProgress();
515
- const status = timedOut ? "timed_out" : result.exitCode === 0 ? "pass" : "fail";
688
+ // Only a stop that interrupted the process relabels it. A command that exited on its own
689
+ // just before its owner asked for the stop keeps its real result.
690
+ const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
691
+ if (ownerExited) {
692
+ stderr = appendBounded(stderr, managedCommandOwnerExitMessage);
693
+ outputRevision += 1;
694
+ lastOutputAt = Date.now();
695
+ lastOutputStream = "stderr";
696
+ }
697
+ const status = timedOut ? "timed_out" : ownerExited ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
516
698
  const receiptCoverage = managedBuildReceiptCoverage(invocation);
517
699
  const buildReceipt = status === "pass" && receiptCoverage
518
700
  ? await publishManagedBuildReceipt({
@@ -535,6 +717,9 @@ async function executeManagedCommandProcess(invocation) {
535
717
  lastOutputStream,
536
718
  buildReceipt,
537
719
  buildReceiptReused: invocation.buildReceiptReuse !== undefined,
720
+ terminationReason: ownerExited ? "owner_exited" : undefined,
721
+ // The runner resolves only after the stopped tree is proven gone.
722
+ processTreeTerminated: ownerExited ? true : undefined,
538
723
  });
539
724
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
540
725
  return managedCommandPublicResult(receipt);
@@ -542,7 +727,10 @@ async function executeManagedCommandProcess(invocation) {
542
727
  catch (error) {
543
728
  // The failure may be a progress write itself; it is reported below.
544
729
  await settleProgress().catch(() => undefined);
545
- const message = redactText(error instanceof Error ? error.message : String(error), exactSecrets);
730
+ const ownerExited = !timedOut && ownerExitStoppedCommands.has(invocation.commandId);
731
+ const message = ownerExited
732
+ ? managedCommandOwnerExitMessage
733
+ : redactText(error instanceof Error ? error.message : String(error), exactSecrets);
546
734
  stderr = appendBounded(stderr, message);
547
735
  outputRevision += 1;
548
736
  lastOutputAt = Date.now();
@@ -557,6 +745,9 @@ async function executeManagedCommandProcess(invocation) {
557
745
  outputRevision,
558
746
  lastOutputAt,
559
747
  lastOutputStream,
748
+ terminationReason: ownerExited ? "owner_exited" : undefined,
749
+ // The runner rejected, so its tree was not proven stopped; teardown still stops it.
750
+ processTreeTerminated: false,
560
751
  });
561
752
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
562
753
  return managedCommandPublicResult(receipt);
@@ -608,7 +799,7 @@ async function waitManagedCommand(input) {
608
799
  const commandId = validatedCommandId(record);
609
800
  const requestedWaitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
610
801
  const waitTimeoutMs = Math.min(requestedWaitTimeoutMs, maximumSynchronousWaitMs);
611
- const deadline = Date.now() + waitTimeoutMs;
802
+ const deadline = monotonicNowMs() + waitTimeoutMs;
612
803
  const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
613
804
  const task = managedCommandTasks.get(commandId);
614
805
  if (task) {
@@ -619,12 +810,12 @@ async function waitManagedCommand(input) {
619
810
  if (result)
620
811
  return result;
621
812
  }
622
- while (Date.now() < deadline) {
813
+ while (monotonicNowMs() < deadline) {
623
814
  const result = await readManagedCommand({ command_id: commandId });
624
815
  if (terminalManagedCommandStatuses.has(String(result.structuredContent.status))) {
625
816
  return result;
626
817
  }
627
- await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - Date.now())));
818
+ await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - monotonicNowMs())));
628
819
  }
629
820
  const receipt = await readManagedCommand({ command_id: commandId });
630
821
  // Only a running receipt is refreshed on a heartbeat; queued or starting receipts are
@@ -645,7 +836,7 @@ async function waitManagedCommand(input) {
645
836
  ...receipt,
646
837
  content: [{
647
838
  type: "text",
648
- text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Its durable receipt remains at ${receiptPath}.`,
839
+ text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Do not end your turn to wait for it: Forge ends the provider run shortly after a turn ends, which stops background monitors and this command. Its durable receipt remains at ${receiptPath}.`,
649
840
  }],
650
841
  structuredContent: {
651
842
  ...receipt.structuredContent,
@@ -739,11 +930,22 @@ function managedCommandResult(values) {
739
930
  output_count: values.buildReceipt.outputCount,
740
931
  } : null,
741
932
  runtime_configuration: managedRuntimeConfiguration(),
742
- process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : undefined,
933
+ // The supervising MCP server process. Forge stops a command whose owner has exited.
934
+ owner_pid: process.pid,
935
+ owner_identity: managedCommandOwnerIdentity(),
936
+ launch_requested: values.launchRequested ?? true,
937
+ process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : values.processTreeTerminated,
938
+ ...(values.terminationReason ? { termination_reason: values.terminationReason } : {}),
743
939
  },
744
940
  isError: isTerminal && values.status !== "pass",
745
941
  };
746
942
  }
943
+ /** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
944
+ function managedCommandOwnerIdentity() {
945
+ // Windows identity capture starts PowerShell; the PID check alone is used there.
946
+ ownerProcessIdentity ??= process.platform === "linux" ? captureHostProcessIdentity(process.pid) : null;
947
+ return ownerProcessIdentity;
948
+ }
747
949
  function managedRuntimeConfiguration() {
748
950
  const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
749
951
  let providerOnlySpecCount = 0;
@@ -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
  }
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
5
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
5
6
  const heartbeatIntervalMs = 30_000;
6
7
  const staleAfterMs = 2 * 60_000;
7
8
  const acquisitionTimeoutMs = 2 * 60 * 60_000;
@@ -11,16 +12,19 @@ export class ManagedBuildCoordinator {
11
12
  constructor(stateRoot = defaultWorktreeCoordinatorStateRoot()) {
12
13
  this.stateRoot = stateRoot;
13
14
  }
14
- async withBuildSlot(worktreePath, action, onWaiting) {
15
+ async withBuildSlot(worktreePath, action, onWaiting, signal) {
15
16
  const resolved = path.resolve(worktreePath);
16
17
  const key = createHash("sha256").update(resolved.toLowerCase()).digest("hex");
17
18
  const root = path.join(this.stateRoot, "managed-build-locks");
18
19
  const target = path.join(root, `${key}.lock`);
19
20
  const token = randomUUID();
20
- const startedAt = Date.now();
21
+ const startedAt = monotonicNowMs();
21
22
  let waitingReported = false;
22
23
  await fs.mkdir(root, { recursive: true, mode: 0o700 });
23
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
+ }
24
28
  try {
25
29
  const handle = await fs.open(target, "wx", 0o600);
26
30
  try {
@@ -49,7 +53,7 @@ export class ManagedBuildCoordinator {
49
53
  waitingReported = true;
50
54
  await onWaiting?.();
51
55
  }
52
- if (Date.now() - startedAt >= acquisitionTimeoutMs) {
56
+ if (monotonicNowMs() - startedAt >= acquisitionTimeoutMs) {
53
57
  throw new Error("managed_build_slot_timeout: another build held this worktree for more than two hours.", { cause: error });
54
58
  }
55
59
  await delay(pollIntervalMs);
@@ -58,7 +62,7 @@ export class ManagedBuildCoordinator {
58
62
  const heartbeat = setInterval(() => void refreshHeartbeat(target, token), heartbeatIntervalMs);
59
63
  heartbeat.unref?.();
60
64
  try {
61
- return await action(Date.now() - startedAt);
65
+ return await action(Math.round(monotonicNowMs() - startedAt));
62
66
  }
63
67
  finally {
64
68
  clearInterval(heartbeat);
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { redactSecrets } from "../shared/redaction/redaction.js";
5
5
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
6
+ import { assertClaimedChangedFilesMatchPublishableDiff } from "./publishable-worktree-changes.js";
6
7
  import { artifactRootFor, artifactRootForOwner, completionArtifactJsonPath, completionArtifactReportPath, decomposeGateFileNames, draftGateFileNames, phaseFiles, qaGateFileNames } from "./phase-completion.js";
7
8
  import { artifactOwnerFields, artifactReferenceOwnerFields, artifactOwnerRelativeRoot, defaultQaChecklist, fallbackReport, isNodeError, jsonText, normalizeArtifactPayload, normalizeCompletionStatus, normalizeQaGateArtifactPayload, normalizeQaGateStatus, normalizedString, optionalString, numberOrDefault, parseJsonObject, parseOptionalJsonObject, phaseFromToolName, qaArray, qaArtifactRelativePath, qaArtifactRelativePathForOwner, qaEvidenceSource, qaObjectArray, qaPolicyWarnings, qaStringArray, readOptionalFile, reportMarkdown, requiredRecord, requiredString, qaGateFromToolName, sha256, stableStringify, validateOptionalWorkItemId, validatePayloadShape, validateQaGatePayloadShape, validateQaScopeRecord, writeFileAtomic, asRecord } from "./phase-completion.validation.js";
8
9
  export async function writeDecomposeGateCompletionArtifact(config, gate, toolName, input) {
@@ -158,6 +159,9 @@ export async function writeCompletionArtifact(config, toolName, input) {
158
159
  }
159
160
  validatePayloadShape(phase, validationPayload);
160
161
  validateOptionalWorkItemId(validationPayload, config.workItemId);
162
+ if (phase === "comment_repair" && status === "pass") {
163
+ await assertClaimedChangedFilesMatchPublishableDiff(config.worktreePath, validationPayload, toolName);
164
+ }
161
165
  const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
162
166
  assertStructuralFieldsUnchanged(validationPayload, redactedPayload);
163
167
  validatePostRedaction(() => {
@@ -1,13 +1,14 @@
1
1
  import fs from "node:fs/promises";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
4
5
  import { completionPhaseFromDispatch, completionPhaseOrder, completionRedactionSecretsEnv, completionToolNamesForDebugGate, completionToolNamesForDecomposeGate, completionToolNamesForDraftGate, completionToolNamesForPhase, completionToolNamesForQaGate, debugCompletionPhaseOrder, decomposeCompletionGateOrder, draftCompletionGateOrder, qaCompletionGateOrder, toolServerName, usesArchitectCycleCompletion, usesDebugCycleCompletion, usesDevelopCycleCompletion, usesQaCycleCompletion } from "./phase-completion.js";
5
6
  import { CompletionPayloadValidationError, asDebugCompletionPhase, asJsonRpcMessage, asMutableRecord, asRecord, artifactOwnerRelativeRoot, decomposeGateFromToolName, draftGateFromToolName, errorMessage, forgeBridgeCliBinPath, isDebugCompletionPhase, isDecomposeDispatch, isDevelopCompletionPhase, normalizedOwnerType, parseCompletionRedactionSecrets, parseOptionalJsonObject, parseStrictCompletionPhase, phaseFromToolName, qaGateFromToolName, requiredString, rpcError, tomlString, tomlStringArray, writeFileAtomic, writeJsonRpc } from "./phase-completion.validation.js";
6
7
  import { completionPromptForDebugCycle, completionPromptForDecomposeCycle, completionPromptForDevelopCycle, completionPromptForDraftCycle, completionPromptForPhase, completionPromptForQaCycle, completionToolNextInstruction, completionToolNextInstructionForDebugGate, completionToolNextInstructionForDecomposeGate, completionToolNextInstructionForDraftGate, completionToolNextInstructionForQaGate, nextDebugPhaseAfter, nextPhaseAfter } from "./phase-completion.prompts.js";
7
8
  import { configuredNativeTestPostgresFallbackPath, nativeTestPostgresFallbackConfigEnvironment, } from "../runtime/native-test-postgres-fallback.js";
8
9
  import { toolDescription, toolInputSchema } from "./phase-completion.schemas.js";
9
10
  import { writeCompletionArtifact, writeDecomposeGateCompletionArtifact, writeDraftGateCompletionArtifact } from "./phase-completion.artifacts.js";
10
- import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, } from "./managed-attempt-tools.js";
11
+ import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, runWithOwnerShutdown, } from "./managed-attempt-tools.js";
11
12
  export async function prepareCompletionToolRuntime(options) {
12
13
  const phase = options.phase ?? completionPhaseFromDispatch(options.dispatch);
13
14
  const worktreePath = path.resolve(options.worktree.worktreePath);
@@ -441,10 +442,13 @@ const completionToolRuntimeEnvironmentNames = [
441
442
  "FORGE_TEST_OUTPUT_DIR",
442
443
  "FORGE_ATTEMPT_DATABASE_SCHEMA",
443
444
  "FORGE_ATTEMPT_DATABASE_READINESS_PATH",
445
+ "FORGE_ATTEMPT_DATABASE_CAPABILITY",
444
446
  "FORGE_CI_REPAIR_READINESS_PATH",
445
447
  "FORGE_CI_REPAIR_HANDOFF_PATH",
446
448
  "FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS",
447
449
  "FORGE_PLAYWRIGHT_CONFIG",
450
+ "FORGE_API_URL",
451
+ "FORGE_WEB_URL",
448
452
  "FORGE_E2E_API_URL",
449
453
  "FORGE_E2E_WEB_URL",
450
454
  "PLAYWRIGHT_BROWSERS_PATH",
@@ -548,24 +552,29 @@ function managedAttemptToolsAvailable() {
548
552
  }
549
553
  export async function runCompletionMcpServer(config) {
550
554
  const session = new CompletionToolServerSession(config);
551
- process.stdin.setEncoding("utf8");
552
- let buffer = "";
553
- for await (const chunk of process.stdin) {
554
- buffer += chunk;
555
- let newlineIndex = buffer.indexOf("\n");
556
- while (newlineIndex >= 0) {
557
- const rawLine = buffer.slice(0, newlineIndex).trim();
558
- buffer = buffer.slice(newlineIndex + 1);
559
- if (rawLine.length > 0) {
560
- await handleJsonRpcLine(session, rawLine);
555
+ // This server is the only supervisor of the managed commands it starts, and they run in
556
+ // their own process groups. When the provider closes the connection or stops this server,
557
+ // stop them first so none outlives its supervisor and receipt writer.
558
+ await runWithOwnerShutdown(async () => {
559
+ process.stdin.setEncoding("utf8");
560
+ let buffer = "";
561
+ for await (const chunk of process.stdin) {
562
+ buffer += chunk;
563
+ let newlineIndex = buffer.indexOf("\n");
564
+ while (newlineIndex >= 0) {
565
+ const rawLine = buffer.slice(0, newlineIndex).trim();
566
+ buffer = buffer.slice(newlineIndex + 1);
567
+ if (rawLine.length > 0) {
568
+ await handleJsonRpcLine(session, rawLine);
569
+ }
570
+ newlineIndex = buffer.indexOf("\n");
561
571
  }
562
- newlineIndex = buffer.indexOf("\n");
563
572
  }
564
- }
565
- const trailing = buffer.trim();
566
- if (trailing.length > 0) {
567
- await handleJsonRpcLine(session, trailing);
568
- }
573
+ const trailing = buffer.trim();
574
+ if (trailing.length > 0) {
575
+ await handleJsonRpcLine(session, trailing);
576
+ }
577
+ });
569
578
  }
570
579
  export function parseCompletionMcpArgs(argv) {
571
580
  let worktreePath = null;
@@ -663,7 +672,10 @@ export function parseCompletionMcpArgs(argv) {
663
672
  ownerId,
664
673
  phase,
665
674
  producedBy,
666
- redactionSecrets: parseCompletionRedactionSecrets(process.env[completionRedactionSecretsEnv]),
675
+ redactionSecrets: [
676
+ ...parseCompletionRedactionSecrets(process.env[completionRedactionSecretsEnv]),
677
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
678
+ ],
667
679
  developCycle,
668
680
  qaCycle,
669
681
  debugCycle,
@@ -0,0 +1,20 @@
1
+ import type { PrePublicationCommandResult, PrePublicationCommandRunner } from "./pre-publication-validation.js";
2
+ export declare class ProcessPrePublicationCommandRunner implements PrePublicationCommandRunner {
3
+ run(command: string, args: readonly string[], cwd: string, signal?: AbortSignal, environment?: Readonly<Record<string, string>>): Promise<PrePublicationCommandResult>;
4
+ }
5
+ interface PackageManagerLaunchLocation {
6
+ readonly args: readonly string[];
7
+ readonly cwd: string;
8
+ }
9
+ /**
10
+ * Corepack picks the pnpm version from the nearest package.json `packageManager`
11
+ * pin at or above the process working directory; pnpm's own `--dir` is not
12
+ * consulted. The repository root carries no pin, so `pnpm --dir client ...`
13
+ * launched from the root would run Corepack's host-global default, and pnpm
14
+ * then refuses client's pin (ERR_PNPM_BAD_PM_VERSION). `pnpm --dir X cmd` is
15
+ * `pnpm cmd` run from X, so launch from X and let Corepack walk up from there
16
+ * to the nearest pin. Targets that are absolute, leave the worktree, or do not
17
+ * exist stay unchanged so pnpm reports them itself.
18
+ */
19
+ export declare function pnpmDirectoryLaunch(command: string, args: readonly string[], cwd: string): Promise<PackageManagerLaunchLocation>;
20
+ export {};