@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.8f4846c6e7a9

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 (89) 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 +73 -8
  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-forge-cgroups.d.ts +8 -0
  21. package/dist/runtime/host-load-forge-cgroups.js +51 -0
  22. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  23. package/dist/runtime/host-load-governor-config.js +46 -0
  24. package/dist/runtime/host-load-governor.d.ts +123 -0
  25. package/dist/runtime/host-load-governor.js +415 -0
  26. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  27. package/dist/runtime/host-load-ledger-lock.js +185 -0
  28. package/dist/runtime/host-load-sampler.d.ts +121 -0
  29. package/dist/runtime/host-load-sampler.js +224 -0
  30. package/dist/runtime/host-load-step-class.d.ts +33 -0
  31. package/dist/runtime/host-load-step-class.js +46 -0
  32. package/dist/runtime/host-load-token-ledger.d.ts +135 -0
  33. package/dist/runtime/host-load-token-ledger.js +345 -0
  34. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  35. package/dist/runtime/host-pressure-stall.js +168 -0
  36. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  37. package/dist/runtime/host-runtime-contract.js +6 -1
  38. package/dist/runtime/host-runtime-lease.d.ts +13 -2
  39. package/dist/runtime/host-runtime-lease.js +82 -11
  40. package/dist/runtime/host-runtime-promotion.js +12 -0
  41. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  42. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  43. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  44. package/dist/runtime/host-runtime-requirements.js +117 -0
  45. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  46. package/dist/runtime/managed-command-teardown.js +607 -0
  47. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  48. package/dist/runtime/playwright-browser-cache.js +227 -0
  49. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  50. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  51. package/dist/session/managed-attempt-tools.d.ts +25 -0
  52. package/dist/session/managed-attempt-tools.js +212 -15
  53. package/dist/session/managed-build-coordinator.d.ts +1 -1
  54. package/dist/session/managed-build-coordinator.js +4 -1
  55. package/dist/session/phase-completion.artifacts.js +4 -0
  56. package/dist/session/phase-completion.runtime.js +22 -17
  57. package/dist/session/pre-publication-host-load.d.ts +27 -0
  58. package/dist/session/pre-publication-host-load.js +96 -0
  59. package/dist/session/pre-publication-process.d.ts +20 -0
  60. package/dist/session/pre-publication-process.js +97 -0
  61. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  62. package/dist/session/pre-publication-skipped-tests.js +109 -0
  63. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  64. package/dist/session/pre-publication-step-execution.js +49 -0
  65. package/dist/session/pre-publication-validation.d.ts +9 -9
  66. package/dist/session/pre-publication-validation.js +44 -112
  67. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  68. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  69. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  70. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  71. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  72. package/dist/session/provider-cli/provider-cli.process.js +297 -23
  73. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  74. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  75. package/dist/session/provider-cli/provider-cli.service.js +126 -26
  76. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  77. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  78. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  79. package/dist/session/provider-cli/provider-output-state.js +9 -0
  80. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  81. package/dist/session/publishable-worktree-changes.js +193 -0
  82. package/dist/session/session.base.d.ts +3 -0
  83. package/dist/session/session.service.d.ts +2 -0
  84. package/dist/session/session.service.js +5 -0
  85. package/dist/session/session.types.d.ts +3 -0
  86. package/dist/session/session.types.js +14 -2
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. 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";
@@ -12,6 +13,7 @@ import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBui
12
13
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
13
14
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
14
15
  import { monotonicNowMs } from "../shared/time/monotonic.js";
16
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
15
17
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
16
18
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
17
19
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
@@ -41,6 +43,14 @@ const terminalManagedCommandStatuses = new Set([
41
43
  ]);
42
44
  const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
43
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.";
44
54
  export const managedAttemptToolNames = [
45
55
  "forge.run_managed_command",
46
56
  "run_managed_command",
@@ -55,6 +65,76 @@ export const managedAttemptToolNames = [
55
65
  "forge.reset_generated_outputs",
56
66
  "reset_generated_outputs",
57
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
+ }
58
138
  export function isManagedAttemptTool(name) {
59
139
  return managedCommandNames.has(name)
60
140
  || startManagedCommandNames.has(name)
@@ -175,6 +255,7 @@ export async function callManagedAttemptTool(name, input, worktreePath) {
175
255
  return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
176
256
  }
177
257
  async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
258
+ assertManagedCommandsAccepted();
178
259
  const command = requiredInputString(record, "command");
179
260
  const args = requiredStringArray(record, "args");
180
261
  const timeoutMs = optionalTimeout(record.timeout_ms);
@@ -199,6 +280,7 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
199
280
  worktreePath,
200
281
  buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
201
282
  buildReceiptReuse,
283
+ controller: new AbortController(),
202
284
  };
203
285
  if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
204
286
  const started = managedCommandResult({
@@ -208,9 +290,25 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
208
290
  exitCode: null,
209
291
  stdout: "",
210
292
  stderr: "",
293
+ launchRequested: false,
211
294
  });
212
295
  await persistManagedCommandReceipt(receiptPath, started.structuredContent);
213
- 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);
214
312
  managedCommandTasks.set(commandId, task);
215
313
  void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
216
314
  return {
@@ -221,7 +319,16 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
221
319
  }],
222
320
  };
223
321
  }
224
- 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;
225
332
  }
226
333
  async function startManagedVerification(input, worktreePath) {
227
334
  const record = asRecord(input);
@@ -384,19 +491,45 @@ function optionValue(args, name) {
384
491
  async function executeManagedCommand(invocation) {
385
492
  if (!invocation.buildProducing)
386
493
  return await executeManagedCommandProcess(invocation);
387
- return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs }), async () => {
388
- 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({
389
519
  ...invocation,
390
520
  timedOut: false,
391
- status: "waiting_for_build_slot",
521
+ status: "runner_error",
392
522
  exitCode: null,
393
523
  stdout: "",
394
- stderr: "",
524
+ stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
525
+ terminationReason: ownerExited ? "owner_exited" : undefined,
526
+ launchRequested: false,
395
527
  });
396
- await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
397
- });
528
+ await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
529
+ return managedCommandPublicResult(receipt);
530
+ }
398
531
  }
399
- async function executeManagedCommandProcess(invocation) {
532
+ async function managedCommandProcessEnvironment(invocation) {
400
533
  assertHostDatabaseCapabilityBoundary();
401
534
  const databaseEnvironment = invocation.verificationProfile
402
535
  ? await managedVerificationDatabaseEnvironment()
@@ -430,9 +563,32 @@ async function executeManagedCommandProcess(invocation) {
430
563
  }
431
564
  : {}),
432
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;
433
589
  let stdout = "";
434
590
  let stderr = "";
435
- const controller = new AbortController();
591
+ const controller = invocation.controller;
436
592
  let timedOut = false;
437
593
  let timer = null;
438
594
  let outputRevision = 0;
@@ -465,11 +621,23 @@ async function executeManagedCommandProcess(invocation) {
465
621
  controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
466
622
  }, managedCommandLaunchTimeoutMs);
467
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);
468
636
  const result = await new StreamingProviderProcessRunner().run({
469
637
  command: invocation.command,
470
638
  args: invocation.args,
471
639
  cwd: invocation.cwd,
472
- env: environment,
640
+ env: prepared.environment,
473
641
  captureOutput: false,
474
642
  }, {
475
643
  onStarted: async () => {
@@ -517,7 +685,16 @@ async function executeManagedCommandProcess(invocation) {
517
685
  },
518
686
  }, controller.signal);
519
687
  await settleProgress();
520
- 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";
521
698
  const receiptCoverage = managedBuildReceiptCoverage(invocation);
522
699
  const buildReceipt = status === "pass" && receiptCoverage
523
700
  ? await publishManagedBuildReceipt({
@@ -540,6 +717,9 @@ async function executeManagedCommandProcess(invocation) {
540
717
  lastOutputStream,
541
718
  buildReceipt,
542
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,
543
723
  });
544
724
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
545
725
  return managedCommandPublicResult(receipt);
@@ -547,7 +727,10 @@ async function executeManagedCommandProcess(invocation) {
547
727
  catch (error) {
548
728
  // The failure may be a progress write itself; it is reported below.
549
729
  await settleProgress().catch(() => undefined);
550
- 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);
551
734
  stderr = appendBounded(stderr, message);
552
735
  outputRevision += 1;
553
736
  lastOutputAt = Date.now();
@@ -562,6 +745,9 @@ async function executeManagedCommandProcess(invocation) {
562
745
  outputRevision,
563
746
  lastOutputAt,
564
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,
565
751
  });
566
752
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
567
753
  return managedCommandPublicResult(receipt);
@@ -650,7 +836,7 @@ async function waitManagedCommand(input) {
650
836
  ...receipt,
651
837
  content: [{
652
838
  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}.`,
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}.`,
654
840
  }],
655
841
  structuredContent: {
656
842
  ...receipt.structuredContent,
@@ -744,11 +930,22 @@ function managedCommandResult(values) {
744
930
  output_count: values.buildReceipt.outputCount,
745
931
  } : null,
746
932
  runtime_configuration: managedRuntimeConfiguration(),
747
- 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 } : {}),
748
939
  },
749
940
  isError: isTerminal && values.status !== "pass",
750
941
  };
751
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
+ }
752
949
  function managedRuntimeConfiguration() {
753
950
  const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
754
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
  }
@@ -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 {
@@ -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(() => {
@@ -8,7 +8,7 @@ import { completionPromptForDebugCycle, completionPromptForDecomposeCycle, compl
8
8
  import { configuredNativeTestPostgresFallbackPath, nativeTestPostgresFallbackConfigEnvironment, } from "../runtime/native-test-postgres-fallback.js";
9
9
  import { toolDescription, toolInputSchema } from "./phase-completion.schemas.js";
10
10
  import { writeCompletionArtifact, writeDecomposeGateCompletionArtifact, writeDraftGateCompletionArtifact } from "./phase-completion.artifacts.js";
11
- import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, } from "./managed-attempt-tools.js";
11
+ import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, runWithOwnerShutdown, } from "./managed-attempt-tools.js";
12
12
  export async function prepareCompletionToolRuntime(options) {
13
13
  const phase = options.phase ?? completionPhaseFromDispatch(options.dispatch);
14
14
  const worktreePath = path.resolve(options.worktree.worktreePath);
@@ -552,24 +552,29 @@ function managedAttemptToolsAvailable() {
552
552
  }
553
553
  export async function runCompletionMcpServer(config) {
554
554
  const session = new CompletionToolServerSession(config);
555
- process.stdin.setEncoding("utf8");
556
- let buffer = "";
557
- for await (const chunk of process.stdin) {
558
- buffer += chunk;
559
- let newlineIndex = buffer.indexOf("\n");
560
- while (newlineIndex >= 0) {
561
- const rawLine = buffer.slice(0, newlineIndex).trim();
562
- buffer = buffer.slice(newlineIndex + 1);
563
- if (rawLine.length > 0) {
564
- 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");
565
571
  }
566
- newlineIndex = buffer.indexOf("\n");
567
572
  }
568
- }
569
- const trailing = buffer.trim();
570
- if (trailing.length > 0) {
571
- await handleJsonRpcLine(session, trailing);
572
- }
573
+ const trailing = buffer.trim();
574
+ if (trailing.length > 0) {
575
+ await handleJsonRpcLine(session, trailing);
576
+ }
577
+ });
573
578
  }
574
579
  export function parseCompletionMcpArgs(argv) {
575
580
  let worktreePath = null;
@@ -0,0 +1,27 @@
1
+ import { type HostLoadStepGate } from "../runtime/host-load-governor.js";
2
+ import { type HostLoadTokenPriority } from "../runtime/host-load-token-ledger.js";
3
+ import type { RunnerDispatchEvent } from "./session.types.js";
4
+ /** Which attempt a governed validation step belongs to, and its queue class. */
5
+ export interface PrePublicationHostLoadOwner {
6
+ readonly dispatchAttemptId: string | null;
7
+ readonly priority: HostLoadTokenPriority;
8
+ }
9
+ export interface GovernedValidationStep {
10
+ readonly checkId: string;
11
+ readonly command: string;
12
+ readonly args: readonly string[];
13
+ readonly owner?: PrePublicationHostLoadOwner;
14
+ readonly signal?: AbortSignal;
15
+ readonly emit?: (event: RunnerDispatchEvent) => Promise<void>;
16
+ }
17
+ /**
18
+ * Runs one pre-publication step behind the host load governor (decision 0013).
19
+ * With the governor off this is a direct call, so behavior is unchanged. With
20
+ * it on, the step waits for admission first; queue time is reported as
21
+ * `host_load_wait_ms` with status `waiting_for_host_capacity`, and the step's
22
+ * own clock (`elapsed_ms`) starts only once it is admitted. `run` gets the
23
+ * signal to launch with: it also aborts when the step's reservation is lost
24
+ * (token fenced, or not renewable for a lease), and the step then fails with
25
+ * that error instead of running on unaccounted.
26
+ */
27
+ export declare function runHostGovernedValidationStep<T>(gate: HostLoadStepGate | undefined, step: GovernedValidationStep, run: (signal: AbortSignal | undefined) => Promise<T>): Promise<T>;
@@ -0,0 +1,96 @@
1
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
2
+ import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
3
+ import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
4
+ import { classifyValidationStep } from "../runtime/host-load-step-class.js";
5
+ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
6
+ /**
7
+ * Runs one pre-publication step behind the host load governor (decision 0013).
8
+ * With the governor off this is a direct call, so behavior is unchanged. With
9
+ * it on, the step waits for admission first; queue time is reported as
10
+ * `host_load_wait_ms` with status `waiting_for_host_capacity`, and the step's
11
+ * own clock (`elapsed_ms`) starts only once it is admitted. `run` gets the
12
+ * signal to launch with: it also aborts when the step's reservation is lost
13
+ * (token fenced, or not renewable for a lease), and the step then fails with
14
+ * that error instead of running on unaccounted.
15
+ */
16
+ export async function runHostGovernedValidationStep(gate, step, run) {
17
+ if (!gate?.enabled)
18
+ return await run(step.signal);
19
+ const { stepClass, cost } = classifyValidationStep(step.checkId, step.command, step.args);
20
+ const base = { checkId: step.checkId, contractId: "forge-ci-parity-v1", stepClass };
21
+ const emit = async (eventType, content, data, kind = "checkpoint") => {
22
+ await step.emit?.({ role: "runner", kind, content, eventType, data: JSON.stringify({ ...base, ...data }) })
23
+ .catch(() => undefined);
24
+ };
25
+ let admission;
26
+ try {
27
+ admission = await gate.acquire({
28
+ stepClass,
29
+ label: step.checkId,
30
+ cost,
31
+ dispatchAttemptId: step.owner?.dispatchAttemptId ?? null,
32
+ priority: step.owner?.priority ?? "foreground",
33
+ }, {
34
+ signal: step.signal,
35
+ onWaiting: async (decision) => await emit("prepublication_host_capacity_waiting", `Pre-publication step '${step.checkId}' (${stepClass}) is waiting for host capacity: ${decision.detail}`, { status: "waiting_for_host_capacity", reason: decision.reason, cpuCores: cost.cpuCores, memoryBytes: cost.memoryBytes }),
36
+ });
37
+ }
38
+ catch (error) {
39
+ if (error instanceof HostCapacityTimeoutError) {
40
+ await emit("prepublication_host_capacity_timeout", error.message, { status: "host_capacity_timeout", host_load_wait_ms: Math.round(error.waitMs) }, "error");
41
+ }
42
+ else if (error instanceof HostCapacityLedgerUnavailableError) {
43
+ await emit("prepublication_host_capacity_ledger_unavailable", error.message, { status: "host_capacity_ledger_unavailable" }, "error");
44
+ }
45
+ throw error;
46
+ }
47
+ const waitMs = Math.round(admission.waitMs);
48
+ await emit("prepublication_host_capacity_admitted", `Pre-publication step '${step.checkId}' (${stepClass}) was admitted after ${waitMs}ms waiting for host capacity.`, { status: "running", reason: admission.decision.reason, host_load_wait_ms: waitMs });
49
+ // Step timers start here, after admission: a step can never time out because it waited.
50
+ const startedAtMs = monotonicNowMs();
51
+ const runSignal = step.signal ? AbortSignal.any([step.signal, admission.signal]) : admission.signal;
52
+ const reservationLost = async () => {
53
+ const reason = admission.signal.reason;
54
+ await emit("prepublication_host_capacity_lost", `Pre-publication step '${step.checkId}' (${stepClass}) was stopped because its host capacity reservation was lost: ${reason instanceof Error ? reason.message : String(reason)}`, { status: "host_capacity_lost" }, "error");
55
+ throw reason;
56
+ };
57
+ try {
58
+ let result;
59
+ try {
60
+ result = await run(runSignal);
61
+ }
62
+ catch (error) {
63
+ if (admission.signal.aborted)
64
+ return await reservationLost();
65
+ throw error;
66
+ }
67
+ // A result produced after the reservation was lost is not trusted either.
68
+ if (admission.signal.aborted)
69
+ return await reservationLost();
70
+ return result;
71
+ }
72
+ finally {
73
+ const elapsedMs = Math.round(monotonicNowMs() - startedAtMs);
74
+ let failure = null;
75
+ try {
76
+ await admission.release();
77
+ }
78
+ catch (error) {
79
+ failure = {
80
+ kind: error instanceof HostCapacityTokenFencedError ? "fenced" : "ledger_unavailable",
81
+ message: error instanceof Error ? error.message : String(error),
82
+ };
83
+ }
84
+ await emit("prepublication_host_capacity_released", failure?.kind === "fenced"
85
+ ? `Pre-publication step '${step.checkId}' finished, but its host capacity token had been reclaimed: ${failure.message}`
86
+ : failure
87
+ ? `Pre-publication step '${step.checkId}' finished, but its host capacity token could not be returned yet (the governor keeps retrying): ${failure.message}`
88
+ : `Pre-publication step '${step.checkId}' (${stepClass}) ran ${elapsedMs}ms after waiting ${waitMs}ms for host capacity.`, {
89
+ status: "completed",
90
+ host_load_wait_ms: waitMs,
91
+ elapsed_ms: elapsedMs,
92
+ tokenFenced: failure?.kind === "fenced",
93
+ releaseFailed: failure?.kind === "ledger_unavailable",
94
+ });
95
+ }
96
+ }
@@ -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 {};