@loucompanion/forge-bridge 0.1.4-dev.1ff37038366e → 0.1.4-dev.217a9a59468f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/bridge.service.d.ts +9 -0
  3. package/dist/bridge/bridge.service.js +40 -3
  4. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  5. package/dist/bridge/dispatch-result-outbox.js +31 -6
  6. package/dist/cli/cli.help.js +2 -2
  7. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  8. package/dist/runtime/attempt-process-supervisor.js +77 -3
  9. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  10. package/dist/runtime/host-database-capability-boundary.js +1 -0
  11. package/dist/runtime/host-diagnostics.js +4 -3
  12. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  13. package/dist/runtime/host-runtime-contract.js +2 -0
  14. package/dist/runtime/host-runtime-lease.js +55 -9
  15. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  16. package/dist/runtime/managed-command-teardown.js +607 -0
  17. package/dist/runtime/node-host-runtime-adapter.js +5 -4
  18. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  19. package/dist/runtime/playwright-browser-cache.js +227 -0
  20. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  21. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  22. package/dist/sandbox/repository-lock.js +3 -2
  23. package/dist/sandbox/runtime.js +5 -4
  24. package/dist/session/managed-attempt-tools.d.ts +25 -0
  25. package/dist/session/managed-attempt-tools.js +216 -18
  26. package/dist/session/managed-build-coordinator.d.ts +1 -1
  27. package/dist/session/managed-build-coordinator.js +8 -4
  28. package/dist/session/phase-completion.runtime.js +22 -17
  29. package/dist/session/pre-publication-process.d.ts +20 -0
  30. package/dist/session/pre-publication-process.js +97 -0
  31. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  32. package/dist/session/pre-publication-skipped-tests.js +109 -0
  33. package/dist/session/pre-publication-validation.js +27 -57
  34. package/dist/session/provider-cli/provider-cli.process.d.ts +6 -1
  35. package/dist/session/provider-cli/provider-cli.process.js +198 -16
  36. package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
  37. package/dist/session/provider-cli/provider-cli.runtime.js +11 -0
  38. package/dist/session/provider-cli/provider-cli.service.js +10 -5
  39. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  40. package/dist/shared/process/host-process-recovery.js +3 -2
  41. package/dist/shared/process/host-process-supervisor.js +5 -4
  42. package/dist/shared/time/monotonic.d.ts +1 -0
  43. package/dist/shared/time/monotonic.js +8 -0
  44. package/dist/version.d.ts +1 -1
  45. package/dist/version.js +1 -1
  46. package/dist/worktree/dependency-warmer.js +74 -0
  47. package/package.json +1 -1
package/README.md CHANGED
@@ -65,7 +65,7 @@ Show or change the saved server without editing `bridge.json`:
65
65
  ```bash
66
66
  forge-bridge server show
67
67
  forge-bridge server set http://localhost:5208
68
- forge-bridge server set https://srv1493013.tail66073d.ts.net:8443
68
+ forge-bridge server set https://forge.example.ts.net:8443
69
69
  ```
70
70
 
71
71
  `FORGE_URL` overrides the saved server. Changing the saved URL retains runner credentials so aliases for the same deployment keep working; pair again with `--server` when switching to a different Forge deployment.
@@ -107,6 +107,15 @@ export declare class ForgeBridgeService implements BridgeService {
107
107
  private sendResultPayloadDirect;
108
108
  private flushDispatchResults;
109
109
  private flushDispatchResultsCore;
110
+ /**
111
+ * Forge binds each result to the runner instance that ran the attempt. On an
112
+ * authoritative connection it rejects another instance's result with
113
+ * bridge.stale_result_instance; Forge's own recovery handles that attempt,
114
+ * so the record can never be delivered and must not block the replay queue.
115
+ * bridge.stale_runner_instance means this connection is not authoritative
116
+ * and says nothing about the record, so it never quarantines.
117
+ */
118
+ private isReplacedRunnerInstanceResult;
110
119
  private startHeartbeat;
111
120
  private heartbeatTick;
112
121
  private startLeaseWatchdog;
@@ -34,7 +34,7 @@ import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, br
34
34
  import { formatBytes } from "../shared/format/format-bytes.js";
35
35
  import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
36
36
  import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
37
- import { FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
37
+ import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
38
38
  /**
39
39
  * Protocol-v2 events are acknowledged one at a time before runOnce returns.
40
40
  * Sending the complete transcript again in DispatchResult made long QA and CI
@@ -1468,6 +1468,19 @@ export class ForgeBridgeService {
1468
1468
  await this.dispatchResultOutbox.acknowledge(pending.payload.leaseId);
1469
1469
  continue;
1470
1470
  }
1471
+ if (this.isReplacedRunnerInstanceResult(pending.payload, error)) {
1472
+ try {
1473
+ await this.dispatchResultOutbox.quarantine(pending);
1474
+ }
1475
+ catch (quarantineError) {
1476
+ // Keep the record and surface Forge's rejection: replay stays
1477
+ // deferred and a heartbeat tick does not count it as a failure.
1478
+ logBridgeStatus(`Dispatch result ${pending.payload.leaseId} from replaced runner instance ${pending.payload.runnerInstanceId} could not be quarantined: ${errorMessage(quarantineError)}`);
1479
+ throw error;
1480
+ }
1481
+ logBridgeStatus(`Quarantined dispatch result ${pending.payload.leaseId}: Forge rejected it because it belongs to replaced runner instance ${pending.payload.runnerInstanceId}. Forge's own recovery handles that instance's attempt; the redacted result is kept in ${dispatchResultQuarantineDirectory} for reconciliation.`);
1482
+ continue;
1483
+ }
1471
1484
  throw error;
1472
1485
  }
1473
1486
  }
@@ -1478,6 +1491,20 @@ export class ForgeBridgeService {
1478
1491
  this.dispatchResultFlushedGeneration = startedGeneration;
1479
1492
  }
1480
1493
  }
1494
+ /**
1495
+ * Forge binds each result to the runner instance that ran the attempt. On an
1496
+ * authoritative connection it rejects another instance's result with
1497
+ * bridge.stale_result_instance; Forge's own recovery handles that attempt,
1498
+ * so the record can never be delivered and must not block the replay queue.
1499
+ * bridge.stale_runner_instance means this connection is not authoritative
1500
+ * and says nothing about the record, so it never quarantines.
1501
+ */
1502
+ isReplacedRunnerInstanceResult(payload, error) {
1503
+ return error instanceof BridgeCallbackRejectedError
1504
+ && error.code === "bridge.stale_result_instance"
1505
+ && typeof payload.runnerInstanceId === "string"
1506
+ && payload.runnerInstanceId.toLowerCase() !== this.config.runnerInstanceId.toLowerCase();
1507
+ }
1481
1508
  startHeartbeat() {
1482
1509
  this.stopHeartbeat();
1483
1510
  this.consecutiveHeartbeatFailures = 0;
@@ -1496,8 +1523,11 @@ export class ForgeBridgeService {
1496
1523
  return;
1497
1524
  this.heartbeatInFlight = true;
1498
1525
  try {
1499
- await this.flushDispatchResults();
1500
- await this.flushReadinessResults();
1526
+ // A rejected replay is an answer from Forge, so the connection is alive:
1527
+ // an undeliverable record must not count as a heartbeat failure and
1528
+ // force reconnects. Transport failures still do.
1529
+ await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
1530
+ await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
1501
1531
  await this.sendHeartbeat();
1502
1532
  this.consecutiveHeartbeatFailures = 0;
1503
1533
  }
@@ -1880,6 +1910,13 @@ class BridgeCallbackRejectedError extends Error {
1880
1910
  this.name = "BridgeCallbackRejectedError";
1881
1911
  }
1882
1912
  }
1913
+ function deferRejectedReplay(kind) {
1914
+ return error => {
1915
+ if (!(error instanceof BridgeCallbackRejectedError))
1916
+ throw error;
1917
+ logBridgeStatus(`${kind} result replay deferred: ${errorMessage(error)}`);
1918
+ };
1919
+ }
1883
1920
  function isDispatchNoLongerPending(error) {
1884
1921
  if (error instanceof BridgeCallbackRejectedError) {
1885
1922
  return error.code === "bridge.dispatch_not_pending" || error.code === "bridge.stale_dispatch";
@@ -8,7 +8,14 @@ export interface DispatchResultOutbox {
8
8
  persist(payload: BridgeDispatchResultCallback): Promise<void>;
9
9
  pending(): Promise<readonly DurableDispatchResult[]>;
10
10
  acknowledge(leaseId: string): Promise<void>;
11
+ /**
12
+ * Moves an undeliverable record out of the replay set. The redacted result
13
+ * is kept, with its original persistedAt, so preserved work can be reconciled.
14
+ */
15
+ quarantine(record: DurableDispatchResult): Promise<void>;
11
16
  }
17
+ export declare const dispatchResultOutboxDirectory = "dispatch-results";
18
+ export declare const dispatchResultQuarantineDirectory = "dispatch-results-quarantine";
12
19
  /**
13
20
  * Persists the already-redacted terminal result before the Bridge attempts its
14
21
  * SignalR callback. A transport or API restart can therefore delay delivery,
@@ -16,10 +23,13 @@ export interface DispatchResultOutbox {
16
23
  */
17
24
  export declare class FileDispatchResultOutbox implements DispatchResultOutbox {
18
25
  private readonly stateRoot;
26
+ private readonly directory;
19
27
  private readonly writes;
20
- constructor(stateRoot: string);
28
+ constructor(stateRoot: string, directory?: string);
21
29
  persist(payload: BridgeDispatchResultCallback): Promise<void>;
30
+ private persistRecord;
22
31
  pending(): Promise<readonly DurableDispatchResult[]>;
23
32
  acknowledge(leaseId: string): Promise<void>;
33
+ quarantine(record: DurableDispatchResult): Promise<void>;
24
34
  private operate;
25
35
  }
@@ -3,6 +3,8 @@ import { isDeepStrictEqual } from "node:util";
3
3
  import { assertCanonicalDirectory, createCanonicalDirectory } from "../runtime/attempt-private-directory.js";
4
4
  import { runPinnedDirectoryProcess } from "../runtime/pinned-directory-process.js";
5
5
  import { dispatchResultReceiptWorker } from "./dispatch-result-worker.js";
6
+ export const dispatchResultOutboxDirectory = "dispatch-results";
7
+ export const dispatchResultQuarantineDirectory = "dispatch-results-quarantine";
6
8
  /**
7
9
  * Persists the already-redacted terminal result before the Bridge attempts its
8
10
  * SignalR callback. A transport or API restart can therefore delay delivery,
@@ -10,11 +12,16 @@ import { dispatchResultReceiptWorker } from "./dispatch-result-worker.js";
10
12
  */
11
13
  export class FileDispatchResultOutbox {
12
14
  stateRoot;
15
+ directory;
13
16
  writes = new Map();
14
- constructor(stateRoot) {
17
+ constructor(stateRoot, directory = dispatchResultOutboxDirectory) {
15
18
  this.stateRoot = stateRoot;
19
+ this.directory = directory;
16
20
  }
17
21
  async persist(payload) {
22
+ await this.persistRecord(payload, new Date().toISOString());
23
+ }
24
+ async persistRecord(payload, persistedAt) {
18
25
  const name = recordName(payload.leaseId);
19
26
  const value = JSON.parse(JSON.stringify({ payload }));
20
27
  const pending = this.writes.get(name);
@@ -27,7 +34,7 @@ export class FileDispatchResultOutbox {
27
34
  const write = this.operate({
28
35
  kind: "persist",
29
36
  name,
30
- record: { schemaVersion: 1, persistedAt: new Date().toISOString(), ...value },
37
+ record: { schemaVersion: 1, persistedAt, ...value },
31
38
  }).then(() => undefined);
32
39
  this.writes.set(name, { value, write });
33
40
  try {
@@ -44,8 +51,23 @@ export class FileDispatchResultOutbox {
44
51
  async acknowledge(leaseId) {
45
52
  await this.operate({ kind: "acknowledge", name: recordName(leaseId) });
46
53
  }
54
+ async quarantine(record) {
55
+ // One execution lease can carry several dispatch attempts, so quarantine
56
+ // files are grouped per attempt: <quarantine>/<attempt>/<lease>.json.
57
+ // Copy before removal: a crash in between leaves an identical record in
58
+ // both places, and the next replay quarantines it again idempotently.
59
+ // A record without an attempt id has no per-attempt bucket; the caller
60
+ // keeps it deferred rather than grouping unrelated attempts together.
61
+ const { payload } = record;
62
+ if (!payload.dispatchAttemptId) {
63
+ throw new Error("dispatch_result_invalid: only attempt-bound results can be quarantined.");
64
+ }
65
+ const bucket = path.join(dispatchResultQuarantineDirectory, compactUuid(payload.dispatchAttemptId));
66
+ await new FileDispatchResultOutbox(this.stateRoot, bucket).persistRecord(payload, record.persistedAt);
67
+ await this.acknowledge(payload.leaseId);
68
+ }
47
69
  async operate(operation) {
48
- const root = path.resolve(this.stateRoot, "dispatch-results");
70
+ const root = path.resolve(this.stateRoot, this.directory);
49
71
  await createCanonicalDirectory(root);
50
72
  const identity = await assertCanonicalDirectory(root);
51
73
  if (!identity)
@@ -54,9 +76,12 @@ export class FileDispatchResultOutbox {
54
76
  }
55
77
  }
56
78
  function recordName(leaseId) {
57
- const value = leaseId.replaceAll("-", "").toLowerCase();
79
+ return `${compactUuid(leaseId)}.json`;
80
+ }
81
+ function compactUuid(id) {
82
+ const value = id.replaceAll("-", "").toLowerCase();
58
83
  if (!/^[0-9a-f]{32}$/u.test(value)) {
59
- throw new Error("dispatch_result_invalid: lease id must be a UUID.");
84
+ throw new Error("dispatch_result_invalid: identifiers must be UUIDs.");
60
85
  }
61
- return `${value}.json`;
86
+ return value;
62
87
  }
@@ -28,7 +28,7 @@ export function helpText() {
28
28
  "",
29
29
  "Examples:",
30
30
  " npm install -g @loucompanion/forge-bridge@next",
31
- " forge-bridge pair 1234-5678 --server https://srv1493013.tail66073d.ts.net:8443 --repo-root \"%USERPROFILE%\\ForgeRepos\"",
31
+ " forge-bridge pair 1234-5678 --server https://forge.example.ts.net:8443 --repo-root \"%USERPROFILE%\\ForgeRepos\"",
32
32
  " forge-bridge connect",
33
33
  " forge-bridge status --check-updates",
34
34
  " forge-bridge server set http://localhost:5208",
@@ -116,7 +116,7 @@ export function commandHelpText(command) {
116
116
  "",
117
117
  "Examples:",
118
118
  " forge-bridge server set http://localhost:5208",
119
- " forge-bridge server set https://srv1493013.tail66073d.ts.net:8443",
119
+ " forge-bridge server set https://forge.example.ts.net:8443",
120
120
  "",
121
121
  ].join("\n");
122
122
  case "add-repo":
@@ -1,4 +1,5 @@
1
1
  import type { ProviderProcessHandlers, ProviderProcessRunRequest, ProviderProcessRunner, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ import { type ManagedCommandTeardownOptions, type ManagedCommandTeardownOutcome } from "./managed-command-teardown.js";
2
3
  export type AttemptProcessChildStatus = "starting" | "running" | "stopping" | "exited" | "failed";
3
4
  export type AttemptProcessSupervisorStatus = "active" | "stopping" | "stopped" | "degraded";
4
5
  export interface AttemptProcessSupervisorIdentity {
@@ -32,6 +33,8 @@ export interface AttemptProcessSupervisorLedger {
32
33
  readonly status: AttemptProcessSupervisorStatus;
33
34
  readonly updatedAt: string;
34
35
  readonly children: readonly AttemptProcessChildLedgerEntry[];
36
+ /** A provider-exit managed-command cleanup that failed and was left to attempt teardown. */
37
+ readonly deferredManagedCommandTeardownFailure?: string;
35
38
  }
36
39
  export interface AttemptProcessChildHandle {
37
40
  readonly name: string;
@@ -46,6 +49,9 @@ export interface AttemptProcessChildHandle {
46
49
  export interface AttemptProcessSupervisorOptions {
47
50
  readonly metadataReadyTimeoutMs?: number;
48
51
  readonly signal?: AbortSignal;
52
+ readonly replaceLedgerFile?: (temporaryPath: string, ledgerPath: string) => Promise<void>;
53
+ readonly ledgerReplaceRetryMs?: number;
54
+ readonly managedCommandTeardownGraceMs?: number;
49
55
  }
50
56
  export interface AttemptProcessChildReadyOptions {
51
57
  readonly maxStartAttempts?: number;
@@ -62,6 +68,9 @@ export declare class AttemptProcessSupervisor {
62
68
  readonly ledgerPath: string;
63
69
  private readonly identity;
64
70
  private readonly metadataReadyTimeoutMs;
71
+ private readonly replaceLedgerFile;
72
+ private readonly ledgerReplaceRetryMs;
73
+ private readonly managedCommandTeardownGraceMs;
65
74
  private readonly records;
66
75
  private readonly currentByName;
67
76
  private readonly attemptController;
@@ -69,6 +78,8 @@ export declare class AttemptProcessSupervisor {
69
78
  private persistTail;
70
79
  private persistenceFailure;
71
80
  private stopOperation;
81
+ private managedCommandTeardownTail;
82
+ private deferredManagedCommandTeardownFailure;
72
83
  constructor(identity: AttemptProcessSupervisorIdentity, runner: ProviderProcessRunner, options?: AttemptProcessSupervisorOptions);
73
84
  startChild(name: string, request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<AttemptProcessChildHandle>;
74
85
  /**
@@ -82,10 +93,23 @@ export declare class AttemptProcessSupervisor {
82
93
  stopChild(name: string, generation: number, fencingToken: string, reason?: unknown): Promise<ProviderProcessRunResult>;
83
94
  stopAll(fencingToken: string, reason?: unknown): Promise<void>;
84
95
  private performStopAll;
96
+ /**
97
+ * Stops the managed commands this attempt's MCP servers started and finalizes their
98
+ * receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
99
+ * left running: it survives wait slices and MCP call boundaries within a live provider.
100
+ */
101
+ terminateManagedCommands(options: Omit<ManagedCommandTeardownOptions, "graceMs">): Promise<readonly ManagedCommandTeardownOutcome[]>;
102
+ /**
103
+ * After a provider exits, stops the managed commands its MCP server left behind. It never
104
+ * fails the provider's result: a command it cannot prove stopped is recorded in the ledger
105
+ * and left to attempt teardown, which fails closed.
106
+ */
107
+ stopOrphanedManagedCommands(): Promise<void>;
85
108
  snapshot(): AttemptProcessSupervisorLedger;
86
109
  providerMemoryTelemetry(): AttemptProcessTreeMemoryTelemetry | null;
87
110
  private observeChildReady;
88
111
  private settleChild;
112
+ private replaceLedger;
89
113
  private assertFence;
90
114
  private persist;
91
115
  }
@@ -2,8 +2,15 @@ import { createHash } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { ForgeFailureError, sanitizeFailureError } from "../session/session.types.js";
5
+ import { terminateAttemptManagedCommands, } from "./managed-command-teardown.js";
6
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
5
7
  const terminalChildStatuses = new Set(["exited", "failed"]);
6
8
  const defaultMetadataReadyTimeoutMs = process.platform === "win32" ? 60_000 : 10_000;
9
+ // Windows refuses to replace a file another process (a scanner or indexer) briefly holds
10
+ // open. One such refusal must not degrade the attempt, so the ledger replace is retried.
11
+ const ledgerReplaceAttempts = 40;
12
+ const defaultLedgerReplaceRetryMs = 25;
13
+ const transientLedgerReplaceCodes = new Set(["EPERM", "EACCES", "EBUSY"]);
7
14
  /**
8
15
  * Owns the independently supervised process trees that belong to one host
9
16
  * dispatch attempt. Each named child gets a distinct Windows Job Object or
@@ -15,6 +22,9 @@ export class AttemptProcessSupervisor {
15
22
  ledgerPath;
16
23
  identity;
17
24
  metadataReadyTimeoutMs;
25
+ replaceLedgerFile;
26
+ ledgerReplaceRetryMs;
27
+ managedCommandTeardownGraceMs;
18
28
  records = [];
19
29
  currentByName = new Map();
20
30
  attemptController = new AbortController();
@@ -22,10 +32,15 @@ export class AttemptProcessSupervisor {
22
32
  persistTail = Promise.resolve();
23
33
  persistenceFailure;
24
34
  stopOperation = null;
35
+ managedCommandTeardownTail = Promise.resolve();
36
+ deferredManagedCommandTeardownFailure;
25
37
  constructor(identity, runner, options = {}) {
26
38
  this.runner = runner;
27
39
  this.identity = validateIdentity(identity);
28
40
  this.metadataReadyTimeoutMs = boundedInteger(options.metadataReadyTimeoutMs ?? defaultMetadataReadyTimeoutMs, 100, 120_000, "metadataReadyTimeoutMs");
41
+ this.replaceLedgerFile = options.replaceLedgerFile ?? ((temporaryPath, ledgerPath) => fs.rename(temporaryPath, ledgerPath));
42
+ this.ledgerReplaceRetryMs = options.ledgerReplaceRetryMs ?? defaultLedgerReplaceRetryMs;
43
+ this.managedCommandTeardownGraceMs = options.managedCommandTeardownGraceMs;
29
44
  this.ledgerPath = path.join(this.identity.logDirectory, "attempt-process-supervisor.json");
30
45
  if (options.signal?.aborted) {
31
46
  this.status = "stopping";
@@ -189,6 +204,14 @@ export class AttemptProcessSupervisor {
189
204
  const rejected = results.flatMap((result, index) => result.status === "rejected"
190
205
  ? [sanitizeFailureError(result.reason, active[index].failureRedactionValues)]
191
206
  : []);
207
+ // Managed commands run in their own process groups, outside every child tree stopped
208
+ // above. The attempt is not stopped until each of them is proven stopped too.
209
+ try {
210
+ await this.terminateManagedCommands({ reason: "attempt_teardown" });
211
+ }
212
+ catch (error) {
213
+ rejected.push(error instanceof Error ? error : new Error(String(error)));
214
+ }
192
215
  const terminalStatus = rejected.length > 0 || this.persistenceFailure !== undefined ? "degraded" : "stopped";
193
216
  await this.persist({
194
217
  ...this.snapshot(),
@@ -202,6 +225,40 @@ export class AttemptProcessSupervisor {
202
225
  if (this.persistenceFailure !== undefined)
203
226
  throw this.persistenceFailure;
204
227
  }
228
+ /**
229
+ * Stops the managed commands this attempt's MCP servers started and finalizes their
230
+ * receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
231
+ * left running: it survives wait slices and MCP call boundaries within a live provider.
232
+ */
233
+ async terminateManagedCommands(options) {
234
+ // One sweep at a time: a provider-exit sweep and attempt teardown would otherwise
235
+ // signal the same groups and write the same receipts concurrently, and stopAll must
236
+ // not report the attempt stopped while an earlier sweep is still writing.
237
+ const sweep = this.managedCommandTeardownTail.then(async () => await terminateAttemptManagedCommands({
238
+ logDirectory: this.identity.logDirectory,
239
+ dispatchAttemptId: this.identity.dispatchAttemptId,
240
+ runtimeLeaseId: this.identity.executionLeaseId,
241
+ }, {
242
+ ...options,
243
+ ...(this.managedCommandTeardownGraceMs === undefined ? {} : { graceMs: this.managedCommandTeardownGraceMs }),
244
+ }));
245
+ this.managedCommandTeardownTail = sweep.catch(() => undefined);
246
+ return await sweep;
247
+ }
248
+ /**
249
+ * After a provider exits, stops the managed commands its MCP server left behind. It never
250
+ * fails the provider's result: a command it cannot prove stopped is recorded in the ledger
251
+ * and left to attempt teardown, which fails closed.
252
+ */
253
+ async stopOrphanedManagedCommands() {
254
+ try {
255
+ await this.terminateManagedCommands({ reason: "owner_exited", onlyOrphaned: true });
256
+ }
257
+ catch (error) {
258
+ this.deferredManagedCommandTeardownFailure = boundedFailure(error, []);
259
+ await this.persist().catch(() => undefined);
260
+ }
261
+ }
205
262
  snapshot() {
206
263
  return {
207
264
  schemaVersion: 1,
@@ -210,6 +267,9 @@ export class AttemptProcessSupervisor {
210
267
  executionLeaseId: this.identity.executionLeaseId,
211
268
  status: this.status,
212
269
  updatedAt: new Date().toISOString(),
270
+ ...(this.deferredManagedCommandTeardownFailure
271
+ ? { deferredManagedCommandTeardownFailure: this.deferredManagedCommandTeardownFailure }
272
+ : {}),
213
273
  children: this.records.map(record => ({
214
274
  name: record.name,
215
275
  generation: record.generation,
@@ -248,8 +308,8 @@ export class AttemptProcessSupervisor {
248
308
  };
249
309
  }
250
310
  async observeChildReady(record) {
251
- const deadline = Date.now() + this.metadataReadyTimeoutMs;
252
- while (Date.now() <= deadline) {
311
+ const deadline = monotonicNowMs() + this.metadataReadyTimeoutMs;
312
+ while (monotonicNowMs() <= deadline) {
253
313
  if (await fileExists(record.metadataPath)) {
254
314
  if (record.status === "starting") {
255
315
  record.status = "running";
@@ -290,6 +350,20 @@ export class AttemptProcessSupervisor {
290
350
  this.status = "degraded";
291
351
  });
292
352
  }
353
+ async replaceLedger(temporary) {
354
+ for (let attempt = 1;; attempt += 1) {
355
+ try {
356
+ await this.replaceLedgerFile(temporary, this.ledgerPath);
357
+ return;
358
+ }
359
+ catch (error) {
360
+ const code = error.code;
361
+ if (attempt >= ledgerReplaceAttempts || !code || !transientLedgerReplaceCodes.has(code))
362
+ throw error;
363
+ await wait(this.ledgerReplaceRetryMs);
364
+ }
365
+ }
366
+ }
293
367
  assertFence(fencingToken) {
294
368
  if (fencingToken !== this.identity.fencingToken) {
295
369
  throw new Error("attempt_process_supervisor_fenced: fencing token does not own this attempt.");
@@ -308,7 +382,7 @@ export class AttemptProcessSupervisor {
308
382
  finally {
309
383
  await handle.close();
310
384
  }
311
- await fs.rename(temporary, this.ledgerPath);
385
+ await this.replaceLedger(temporary);
312
386
  }
313
387
  catch (error) {
314
388
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -1,4 +1,4 @@
1
- export declare const hostDatabaseCapabilityEnvironmentNames: readonly ["FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING", "FORGE_TEST_POSTGRES_CONNECTION_STRING"];
1
+ export declare const hostDatabaseCapabilityEnvironmentNames: readonly ["FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING", "FORGE_TEST_POSTGRES_CONNECTION_STRING", "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING"];
2
2
  export interface HostDatabaseCapabilityBoundaryOptions {
3
3
  readonly platform?: NodeJS.Platform;
4
4
  readonly processEnvironment?: NodeJS.ProcessEnv;
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  export const hostDatabaseCapabilityEnvironmentNames = [
4
4
  "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING",
5
5
  "FORGE_TEST_POSTGRES_CONNECTION_STRING",
6
+ "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING",
6
7
  ];
7
8
  const boundaryAttestationEnvironment = "FORGE_HOST_DATABASE_CAPABILITY_BOUNDARY";
8
9
  const boundaryAttestationValue = "user_store_clear";
@@ -6,6 +6,7 @@ import { assertCanonicalDirectory } from "./attempt-private-directory.js";
6
6
  import { runAttemptArchiveOperation, runAttemptPathOperation } from "./attempt-path-operation.js";
7
7
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
8
8
  import { compactHostAttemptId } from "./host-execution-root.js";
9
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
9
10
  const maximumEvidenceBytes = 200 * 1024 * 1024;
10
11
  const diagnosticsRetentionDeadlineMs = 30_000;
11
12
  const diagnosticsHelperTerminationConfirmationMs = 2_000;
@@ -21,7 +22,7 @@ export async function retainHostDiagnostics(stateRoot, attemptRoot, attemptId, e
21
22
  const configuredDeadlineMs = Math.max(1, Math.min(diagnosticsRetentionDeadlineMs, Number.isFinite(requestedDeadlineMs) && (requestedDeadlineMs ?? 0) > 0
22
23
  ? Math.floor(requestedDeadlineMs)
23
24
  : diagnosticsRetentionDeadlineMs));
24
- const retentionDeadline = Date.now() + configuredDeadlineMs;
25
+ const retentionDeadline = monotonicNowMs() + configuredDeadlineMs;
25
26
  const identity = attemptId.replaceAll("-", "").toLowerCase();
26
27
  const compactAttemptRoot = path.resolve(attemptOwnerRoot, "a", compactHostAttemptId(attemptId));
27
28
  const legacyAttemptRoot = path.resolve(stateRoot, "host-attempts", identity);
@@ -155,7 +156,7 @@ function remainingHelperTiming(retentionDeadline, configuredDeadlineMs) {
155
156
  return { operationTimeoutMs, terminationConfirmationMs };
156
157
  }
157
158
  function remainingRetentionMs(retentionDeadline, configuredDeadlineMs) {
158
- const remainingMs = retentionDeadline - Date.now();
159
+ const remainingMs = retentionDeadline - monotonicNowMs();
159
160
  if (remainingMs <= 0)
160
161
  throw diagnosticsDeadlineError(configuredDeadlineMs);
161
162
  return remainingMs;
@@ -181,7 +182,7 @@ async function runWithinRetentionHelperDeadline(operation, retentionDeadline, co
181
182
  return await operation();
182
183
  }
183
184
  catch (error) {
184
- if (Date.now() >= retentionDeadline)
185
+ if (monotonicNowMs() >= retentionDeadline)
185
186
  throw diagnosticsDeadlineError(configuredDeadlineMs);
186
187
  throw error;
187
188
  }
@@ -1,6 +1,7 @@
1
1
  export declare const hostRuntimeContractPath = ".forge/forge.runtime.yml";
2
2
  export declare const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
3
3
  export declare const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
4
+ export declare const hostRuntimeTestPostgresProvisionerEnvironment = "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING";
4
5
  export type RequestedHostConcurrency = "serial" | "parallel" | "disabled";
5
6
  export type HostRuntimePortAdapter = "node" | "vite" | "next" | "aspnetcore";
6
7
  export interface HostRuntimeLaunchConfig {
@@ -7,6 +7,8 @@ import { isGeneratedOutputDirectoryName } from "./generated-output-reset.js";
7
7
  export const hostRuntimeContractPath = ".forge/forge.runtime.yml";
8
8
  export const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
9
9
  export const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
10
+ // Optional superuser login for operator-run .NET fixtures. Never reaches attempt, validation or provider processes.
11
+ export const hostRuntimeTestPostgresProvisionerEnvironment = "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING";
10
12
  const maximumContractBytes = 64 * 1024;
11
13
  const maximumDepth = 12;
12
14
  // Every discovery scan stops after this many directory entries. A monorepo needs a few
@@ -16,6 +16,7 @@ import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-co
16
16
  import { HostPortBroker, } from "./host-port-broker.js";
17
17
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
18
18
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
19
+ import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
19
20
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
20
21
  import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
21
22
  import { HostListenerInspector } from "./host-listener-inspector.js";
@@ -1171,6 +1172,11 @@ export class HostRuntimeLeaseManager {
1171
1172
  executionClass: active.executionClass,
1172
1173
  };
1173
1174
  }
1175
+ const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
1176
+ // A host without the project's pinned browsers fails here, before any database,
1177
+ // build, launch, or promotion work that the attempt would otherwise waste.
1178
+ if (playwrightConfig)
1179
+ await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
1174
1180
  const owner = hostPortOwner(active.lease);
1175
1181
  const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
1176
1182
  if (!logDirectory)
@@ -1532,18 +1538,46 @@ export class HostRuntimeLeaseManager {
1532
1538
  if (logsEntry.kind !== "directory") {
1533
1539
  throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1534
1540
  }
1535
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1536
1541
  const outcomes = [];
1537
- for (const entry of entries) {
1538
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1539
- continue;
1540
- const metadataPath = path.join(logsRoot, entry.name);
1541
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1542
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1543
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1542
+ const failures = [];
1543
+ try {
1544
+ const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1545
+ for (const entry of entries) {
1546
+ if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1547
+ continue;
1548
+ const metadataPath = path.join(logsRoot, entry.name);
1549
+ const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1550
+ if (!validHostProcessSupervisorMetadata(value, lease)) {
1551
+ throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1552
+ }
1553
+ outcomes.push(await this.processRecovery.recover(value));
1554
+ }
1555
+ }
1556
+ catch (error) {
1557
+ failures.push(error);
1558
+ }
1559
+ // Managed commands run in their own process groups and record their ownership apart
1560
+ // from the attempt's supervised children. They are recovered even when recovering a
1561
+ // supervised child failed, and both failures are reported together.
1562
+ try {
1563
+ const managed = await terminateAttemptManagedCommands({
1564
+ logDirectory: logsRoot,
1565
+ dispatchAttemptId: lease.dispatchAttemptId,
1566
+ runtimeLeaseId: lease.executionLeaseId,
1567
+ pinnedLogDirectory: logsEntry.identity,
1568
+ }, { reason: "attempt_teardown" });
1569
+ for (const command of managed) {
1570
+ if (command.outcome === "terminated" || command.outcome === "pid_reused")
1571
+ outcomes.push(command.outcome);
1544
1572
  }
1545
- outcomes.push(await this.processRecovery.recover(value));
1546
1573
  }
1574
+ catch (error) {
1575
+ failures.push(error);
1576
+ }
1577
+ if (failures.length === 1)
1578
+ throw failures[0];
1579
+ if (failures.length > 1)
1580
+ throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1547
1581
  return outcomes;
1548
1582
  }
1549
1583
  async markLedgerDegraded(ledger) {
@@ -1919,6 +1953,18 @@ class AttemptSupervisedProviderProcessRunner {
1919
1953
  : new Set();
1920
1954
  const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
1921
1955
  this.onProcessTreeStarted();
1956
+ try {
1957
+ return await this.awaitProviderResult(child, baselineListeners, signal);
1958
+ }
1959
+ finally {
1960
+ // The provider tree, and the MCP server inside it, is gone. A managed command that
1961
+ // server started now has no supervisor and no receipt writer, so it must not keep
1962
+ // running into the next provider generation. This never rejects; a command it
1963
+ // cannot prove stopped is left to attempt teardown, which fails closed.
1964
+ await this.supervisor.stopOrphanedManagedCommands();
1965
+ }
1966
+ }
1967
+ async awaitProviderResult(child, baselineListeners, signal) {
1922
1968
  if (!this.enforceNoListeners)
1923
1969
  return await child.result;
1924
1970
  let settled = false;