@loucompanion/forge-bridge 0.1.4-dev.9e8a5b93cbcb → 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.
- package/dist/bridge/bridge.service.d.ts +12 -1
- package/dist/bridge/bridge.service.js +51 -5
- package/dist/bridge/bridge.types.d.ts +6 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
- package/dist/runtime/attempt-process-supervisor.js +50 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-load-sampler.d.ts +83 -0
- package/dist/runtime/host-load-sampler.js +164 -0
- package/dist/runtime/host-pressure-stall.d.ts +41 -0
- package/dist/runtime/host-pressure-stall.js +121 -0
- package/dist/runtime/host-runtime-contract.d.ts +1 -0
- package/dist/runtime/host-runtime-contract.js +2 -0
- package/dist/runtime/host-runtime-lease.js +55 -9
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
- package/dist/session/managed-attempt-tools.d.ts +25 -0
- package/dist/session/managed-attempt-tools.js +212 -15
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +4 -1
- package/dist/session/phase-completion.artifacts.js +4 -0
- package/dist/session/phase-completion.runtime.js +22 -17
- package/dist/session/pre-publication-process.d.ts +20 -0
- package/dist/session/pre-publication-process.js +97 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- package/dist/session/pre-publication-validation.js +27 -57
- package/dist/session/provider-cli/provider-cli.artifacts.js +2 -9
- package/dist/session/provider-cli/provider-cli.process.d.ts +4 -1
- package/dist/session/provider-cli/provider-cli.process.js +88 -10
- package/dist/session/provider-cli/provider-cli.service.js +61 -10
- package/dist/session/publishable-worktree-changes.d.ts +45 -0
- package/dist/session/publishable-worktree-changes.js +177 -0
- package/dist/session/session.types.js +3 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- 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
|
-
|
|
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
|
|
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
|
-
|
|
388
|
-
|
|
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: "
|
|
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,
|
|
397
|
-
|
|
528
|
+
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
|
|
529
|
+
return managedCommandPublicResult(receipt);
|
|
530
|
+
}
|
|
398
531
|
}
|
|
399
|
-
async function
|
|
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 =
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
buffer
|
|
563
|
-
|
|
564
|
-
|
|
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
|
-
|
|
570
|
-
|
|
571
|
-
|
|
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,97 @@
|
|
|
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, hostRuntimeTestPostgresProvisionerEnvironment, } 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
|
+
hostRuntimeTestPostgresProvisionerEnvironment.toLowerCase(),
|
|
50
|
+
]);
|
|
51
|
+
for (const [name, value] of Object.entries(process.env)) {
|
|
52
|
+
if (typeof value === "string" && !privilegedNames.has(name.toLowerCase())) {
|
|
53
|
+
child[name] = value;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { ...child, ...environment };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Corepack picks the pnpm version from the nearest package.json `packageManager`
|
|
60
|
+
* pin at or above the process working directory; pnpm's own `--dir` is not
|
|
61
|
+
* consulted. The repository root carries no pin, so `pnpm --dir client ...`
|
|
62
|
+
* launched from the root would run Corepack's host-global default, and pnpm
|
|
63
|
+
* then refuses client's pin (ERR_PNPM_BAD_PM_VERSION). `pnpm --dir X cmd` is
|
|
64
|
+
* `pnpm cmd` run from X, so launch from X and let Corepack walk up from there
|
|
65
|
+
* to the nearest pin. Targets that are absolute, leave the worktree, or do not
|
|
66
|
+
* exist stay unchanged so pnpm reports them itself.
|
|
67
|
+
*/
|
|
68
|
+
export async function pnpmDirectoryLaunch(command, args, cwd) {
|
|
69
|
+
const unchanged = { args, cwd };
|
|
70
|
+
if (command !== "pnpm")
|
|
71
|
+
return unchanged;
|
|
72
|
+
const target = pnpmDirectoryArgument(args);
|
|
73
|
+
if (!target || path.isAbsolute(target.directory))
|
|
74
|
+
return unchanged;
|
|
75
|
+
if (!isSubPath(cwd, path.resolve(cwd, target.directory)))
|
|
76
|
+
return unchanged;
|
|
77
|
+
// The lexical check alone would let a symlink (or junction) inside the worktree
|
|
78
|
+
// move the child's cwd outside it, so compare and launch from real paths.
|
|
79
|
+
const realCwd = await fs.realpath(cwd).catch(() => null);
|
|
80
|
+
const packageDirectory = await fs.realpath(path.resolve(cwd, target.directory)).catch(() => null);
|
|
81
|
+
if (!realCwd || !packageDirectory || !isSubPath(realCwd, packageDirectory))
|
|
82
|
+
return unchanged;
|
|
83
|
+
const stat = await fs.stat(packageDirectory).catch(() => null);
|
|
84
|
+
if (!stat?.isDirectory())
|
|
85
|
+
return unchanged;
|
|
86
|
+
return { args: args.slice(target.consumed), cwd: packageDirectory };
|
|
87
|
+
}
|
|
88
|
+
/** Reads a leading `--dir X`, `--dir=X`, `-C X`, `-CX` or `-C=X`. */
|
|
89
|
+
function pnpmDirectoryArgument(args) {
|
|
90
|
+
const first = args[0] ?? "";
|
|
91
|
+
if (first === "--dir" || first === "-C")
|
|
92
|
+
return args[1] ? { directory: args[1], consumed: 2 } : null;
|
|
93
|
+
const inline = first.startsWith("--dir=") ? first.slice("--dir=".length)
|
|
94
|
+
: first.startsWith("-C") ? first.slice(2).replace(/^=/u, "")
|
|
95
|
+
: "";
|
|
96
|
+
return inline ? { directory: inline, consumed: 1 } : null;
|
|
97
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skipped .NET tests from the TRX files a validation step wrote, so a run that skipped tests reads as
|
|
3
|
+
* "passed with N skipped (reasons)" rather than a plain pass. Only files under the step's declared results
|
|
4
|
+
* directory and written since the step started count, and that directory must resolve (through symlinks) inside
|
|
5
|
+
* the worktree or the attempt's own test-output root; nothing here can fail a passing step.
|
|
6
|
+
*/
|
|
7
|
+
export interface SkippedTestSummary {
|
|
8
|
+
readonly count: number;
|
|
9
|
+
readonly reasons: readonly {
|
|
10
|
+
readonly reason: string;
|
|
11
|
+
readonly count: number;
|
|
12
|
+
}[];
|
|
13
|
+
}
|
|
14
|
+
/** The attempt-owned output root a managed attempt's tests write under, outside the worktree. */
|
|
15
|
+
export declare const attemptTestOutputEnvironment = "FORGE_TEST_OUTPUT_DIR";
|
|
16
|
+
export declare function resultsDirectoryArgument(args: readonly string[]): string | undefined;
|
|
17
|
+
export declare function readSkippedTests(cwd: string, args: readonly string[], sinceMs: number, environment?: Readonly<Record<string, string>>): Promise<SkippedTestSummary>;
|
|
18
|
+
export declare function mergeSkippedTests(left: SkippedTestSummary, right: SkippedTestSummary): SkippedTestSummary;
|
|
19
|
+
export declare function describeSkippedTests(summary: SkippedTestSummary): string;
|
|
20
|
+
/** Each NotExecuted result's skip reason, from its ErrorInfo message (VSTest's TRX shape). */
|
|
21
|
+
export declare function skippedReasons(trx: string): string[];
|