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