@loucompanion/forge-bridge 0.1.4-dev.9e8a5b93cbcb → 0.1.4-dev.d2d83bc81b6a

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.
@@ -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 {
@@ -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,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 {};
@@ -0,0 +1,96 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "../runtime/host-runtime-contract.js";
6
+ import { isSubPath } from "../shared/path/path.js";
7
+ const execFileAsync = promisify(execFile);
8
+ export class ProcessPrePublicationCommandRunner {
9
+ async run(command, args, cwd, signal, environment) {
10
+ try {
11
+ const launch = await pnpmDirectoryLaunch(command, args, cwd);
12
+ const windowsBatch = process.platform === "win32" && (command === "npm" || command === "pnpm");
13
+ const executable = windowsBatch ? (process.env.ComSpec ?? "cmd.exe") : command;
14
+ const commandArgs = windowsBatch
15
+ ? ["/d", "/s", "/c", [`${command}.cmd`, ...launch.args].map(quoteWindowsCommandArgument).join(" ")]
16
+ : [...launch.args];
17
+ const result = await execFileAsync(executable, commandArgs, {
18
+ cwd: launch.cwd,
19
+ encoding: "utf8",
20
+ maxBuffer: 4 * 1024 * 1024,
21
+ signal,
22
+ env: prePublicationChildEnvironment(environment),
23
+ });
24
+ return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
25
+ }
26
+ catch (error) {
27
+ const failure = error;
28
+ if (failure.name === "AbortError")
29
+ throw error;
30
+ if (failure.code === "ENOENT") {
31
+ return { exitCode: 127, stderr: `executable_not_found: ${command}` };
32
+ }
33
+ return {
34
+ exitCode: typeof failure.code === "number" ? failure.code : 1,
35
+ stdout: failure.stdout,
36
+ stderr: failure.stderr ?? failure.message,
37
+ };
38
+ }
39
+ }
40
+ }
41
+ function quoteWindowsCommandArgument(value) {
42
+ return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
43
+ }
44
+ function prePublicationChildEnvironment(environment) {
45
+ const child = {};
46
+ const privilegedNames = new Set([
47
+ hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
48
+ hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
49
+ ]);
50
+ for (const [name, value] of Object.entries(process.env)) {
51
+ if (typeof value === "string" && !privilegedNames.has(name.toLowerCase())) {
52
+ child[name] = value;
53
+ }
54
+ }
55
+ return { ...child, ...environment };
56
+ }
57
+ /**
58
+ * Corepack picks the pnpm version from the nearest package.json `packageManager`
59
+ * pin at or above the process working directory; pnpm's own `--dir` is not
60
+ * consulted. The repository root carries no pin, so `pnpm --dir client ...`
61
+ * launched from the root would run Corepack's host-global default, and pnpm
62
+ * then refuses client's pin (ERR_PNPM_BAD_PM_VERSION). `pnpm --dir X cmd` is
63
+ * `pnpm cmd` run from X, so launch from X and let Corepack walk up from there
64
+ * to the nearest pin. Targets that are absolute, leave the worktree, or do not
65
+ * exist stay unchanged so pnpm reports them itself.
66
+ */
67
+ export async function pnpmDirectoryLaunch(command, args, cwd) {
68
+ const unchanged = { args, cwd };
69
+ if (command !== "pnpm")
70
+ return unchanged;
71
+ const target = pnpmDirectoryArgument(args);
72
+ if (!target || path.isAbsolute(target.directory))
73
+ return unchanged;
74
+ if (!isSubPath(cwd, path.resolve(cwd, target.directory)))
75
+ return unchanged;
76
+ // The lexical check alone would let a symlink (or junction) inside the worktree
77
+ // move the child's cwd outside it, so compare and launch from real paths.
78
+ const realCwd = await fs.realpath(cwd).catch(() => null);
79
+ const packageDirectory = await fs.realpath(path.resolve(cwd, target.directory)).catch(() => null);
80
+ if (!realCwd || !packageDirectory || !isSubPath(realCwd, packageDirectory))
81
+ return unchanged;
82
+ const stat = await fs.stat(packageDirectory).catch(() => null);
83
+ if (!stat?.isDirectory())
84
+ return unchanged;
85
+ return { args: args.slice(target.consumed), cwd: packageDirectory };
86
+ }
87
+ /** Reads a leading `--dir X`, `--dir=X`, `-C X`, `-CX` or `-C=X`. */
88
+ function pnpmDirectoryArgument(args) {
89
+ const first = args[0] ?? "";
90
+ if (first === "--dir" || first === "-C")
91
+ return args[1] ? { directory: args[1], consumed: 2 } : null;
92
+ const inline = first.startsWith("--dir=") ? first.slice("--dir=".length)
93
+ : first.startsWith("-C") ? first.slice(2).replace(/^=/u, "")
94
+ : "";
95
+ return inline ? { directory: inline, consumed: 1 } : null;
96
+ }
@@ -1,16 +1,14 @@
1
- import { execFile } from "node:child_process";
2
1
  import { createHash, randomUUID } from "node:crypto";
3
2
  import fs from "node:fs/promises";
4
3
  import path from "node:path";
5
- import { promisify } from "node:util";
6
4
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
7
5
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
8
6
  import { nativeTestPostgresFallbackEnvironment, parseNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
9
7
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "../runtime/host-runtime-contract.js";
10
8
  import { redactText } from "../shared/redaction/redaction.js";
9
+ import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
11
10
  import { findUnreferencedNewExports } from "./unreferenced-exports.js";
12
11
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
13
- const execFileAsync = promisify(execFile);
14
12
  const contractRelativePath = ".forge/validation/ci-parity.v1.json";
15
13
  const requiredCheckIds = new Set([
16
14
  "file-size-inventory",
@@ -81,54 +79,6 @@ export class PrePublicationInfrastructureError extends ForgeFailureError {
81
79
  this.name = "PrePublicationInfrastructureError";
82
80
  }
83
81
  }
84
- class ProcessPrePublicationCommandRunner {
85
- async run(command, args, cwd, signal, environment) {
86
- try {
87
- const windowsBatch = process.platform === "win32" && (command === "npm" || command === "pnpm");
88
- const executable = windowsBatch ? (process.env.ComSpec ?? "cmd.exe") : command;
89
- const commandArgs = windowsBatch
90
- ? ["/d", "/s", "/c", [`${command}.cmd`, ...args].map(quoteWindowsCommandArgument).join(" ")]
91
- : [...args];
92
- const result = await execFileAsync(executable, commandArgs, {
93
- cwd,
94
- encoding: "utf8",
95
- maxBuffer: 4 * 1024 * 1024,
96
- signal,
97
- env: prePublicationChildEnvironment(environment),
98
- });
99
- return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
100
- }
101
- catch (error) {
102
- const failure = error;
103
- if (failure.name === "AbortError")
104
- throw error;
105
- if (failure.code === "ENOENT") {
106
- return { exitCode: 127, stderr: `executable_not_found: ${command}` };
107
- }
108
- return {
109
- exitCode: typeof failure.code === "number" ? failure.code : 1,
110
- stdout: failure.stdout,
111
- stderr: failure.stderr ?? failure.message,
112
- };
113
- }
114
- }
115
- }
116
- function quoteWindowsCommandArgument(value) {
117
- return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
118
- }
119
- function prePublicationChildEnvironment(environment) {
120
- const child = {};
121
- const privilegedNames = new Set([
122
- hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
123
- hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
124
- ]);
125
- for (const [name, value] of Object.entries(process.env)) {
126
- if (typeof value === "string" && !privilegedNames.has(name.toLowerCase())) {
127
- child[name] = value;
128
- }
129
- }
130
- return { ...child, ...environment };
131
- }
132
82
  export class PrePublicationValidator {
133
83
  commands;
134
84
  dockerEngineProbe;
@@ -361,10 +311,11 @@ export class PrePublicationValidator {
361
311
  const exactSecrets = validationExactSecrets(execution?.environment);
362
312
  try {
363
313
  if (execution?.processRunner) {
314
+ const launch = await pnpmDirectoryLaunch(command, args, cwd);
364
315
  const result = await execution.processRunner.run({
365
316
  command,
366
- args,
367
- cwd,
317
+ args: launch.args,
318
+ cwd: launch.cwd,
368
319
  env: execution.environment,
369
320
  captureOutput: true,
370
321
  failureRedactionValues: exactSecrets,