@loucompanion/forge-bridge 0.2.1-dev.17ad6c965e41 → 0.2.1-dev.4f11ffc822f9

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.
@@ -17,18 +17,29 @@ export declare class HostListenerInspector {
17
17
  private readonly commands;
18
18
  private readonly platform;
19
19
  private readonly retryDelayMs;
20
+ /** How often a live shared-admission run's listeners are re-audited after readiness. */
21
+ ownedListenerAuditIntervalMs: number;
20
22
  constructor(commands?: HostInspectionCommandRunner, platform?: NodeJS.Platform, retryDelayMs?: number);
21
23
  inspect(child: AttemptProcessChildHandle, reservation: HostPortReservation, owner: HostPortLeaseOwner): Promise<HostListenerOwnership>;
22
24
  /** Returns loopback TCP ports opened by one exact supervised child process tree. */
23
25
  inspectOwnedLoopbackListeners(child: AttemptProcessChildHandle, owner: HostPortLeaseOwner): Promise<readonly number[]>;
26
+ /**
27
+ * Returns the TCP ports that one exact supervised child process tree listens on, on any local
28
+ * address: IPv4 or IPv6 loopback, a wildcard (which covers loopback), or a specific interface.
29
+ * The parallel-isolation audit needs all of them, because a sibling could only collide with
30
+ * one it was never brokered.
31
+ */
32
+ inspectOwnedTcpListeners(child: AttemptProcessChildHandle, owner: HostPortLeaseOwner): Promise<readonly number[]>;
24
33
  /** Snapshots loopback TCP ports that predate a supervised child launch. */
25
34
  inspectLoopbackListeners(): Promise<readonly number[]>;
26
35
  private inspectWindows;
27
36
  private inspectAllWindows;
37
+ private ownedWindowsPorts;
28
38
  private runWindowsAncestry;
29
39
  private runWindowsNetstat;
30
40
  private inspectUnix;
31
41
  private inspectAllUnix;
42
+ private ownedUnixPorts;
32
43
  }
33
44
  export declare function parseWindowsLoopbackListeners(output: string): readonly {
34
45
  pid: number;
@@ -42,6 +53,21 @@ export declare function parseSsLoopbackListeners(output: string): readonly {
42
53
  pid: number;
43
54
  port: number;
44
55
  }[];
56
+ /** TCP listeners on any local address (IPv4, IPv6 or wildcard) from `netstat -ano`. */
57
+ export declare function parseWindowsTcpListeners(output: string): readonly {
58
+ pid: number;
59
+ port: number;
60
+ }[];
61
+ /** TCP listeners on any local address from `lsof -iTCP -sTCP:LISTEN -Fpn`. */
62
+ export declare function parseLsofTcpListeners(output: string): readonly {
63
+ pid: number;
64
+ port: number;
65
+ }[];
66
+ /** TCP listeners on any local address from `ss -H -ltnp` (local address is the fourth column). */
67
+ export declare function parseSsTcpListeners(output: string): readonly {
68
+ pid: number;
69
+ port: number;
70
+ }[];
45
71
  export declare class ExecFileInspectionCommandRunner implements HostInspectionCommandRunner {
46
72
  run(command: string, args: readonly string[]): Promise<HostInspectionCommandResult>;
47
73
  }
@@ -4,6 +4,8 @@ import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  const windowsListenerOwnerPath = fileURLToPath(new URL("../../runtime/windows-listener-owner.ps1", import.meta.url));
6
6
  const windowsNetstatArgs = ["-ano", "-p", "TCP"];
7
+ // Without "-p", netstat lists TCP over IPv6 as well; "-p TCP" is IPv4 only.
8
+ const windowsAllNetstatArgs = ["-ano"];
7
9
  const windowsNetstatAttempts = 3;
8
10
  const windowsAncestryAttempts = 2;
9
11
  const windowsNetstatRetryDelayMs = 250;
@@ -13,6 +15,8 @@ export class HostListenerInspector {
13
15
  commands;
14
16
  platform;
15
17
  retryDelayMs;
18
+ /** How often a live shared-admission run's listeners are re-audited after readiness. */
19
+ ownedListenerAuditIntervalMs = 10_000;
16
20
  constructor(commands = new ExecFileInspectionCommandRunner(), platform = process.platform, retryDelayMs = windowsNetstatRetryDelayMs) {
17
21
  this.commands = commands;
18
22
  this.platform = platform;
@@ -42,6 +46,32 @@ export class HostListenerInspector {
42
46
  ? await this.inspectAllWindows(metadata.rootPid)
43
47
  : await this.inspectAllUnix(metadata.rootPid);
44
48
  }
49
+ /**
50
+ * Returns the TCP ports that one exact supervised child process tree listens on, on any local
51
+ * address: IPv4 or IPv6 loopback, a wildcard (which covers loopback), or a specific interface.
52
+ * The parallel-isolation audit needs all of them, because a sibling could only collide with
53
+ * one it was never brokered.
54
+ */
55
+ async inspectOwnedTcpListeners(child, owner) {
56
+ const metadata = await loadMetadata(child.metadataPath);
57
+ if (!metadata || !matchesOwner(metadata, child, owner)) {
58
+ throw new Error("host_listener_inspection_invalid: supervised provider ownership metadata is unavailable.");
59
+ }
60
+ if (this.platform === "win32") {
61
+ const netstat = await this.runWindowsNetstat(windowsAllNetstatArgs);
62
+ return await this.ownedWindowsPorts(metadata.rootPid, parseWindowsTcpListeners(netstat.stdout));
63
+ }
64
+ const lsof = await this.commands.run("lsof", ["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-Fpn"]);
65
+ if (lsof.exitCode === 0 || lsof.exitCode === 1) {
66
+ return await this.ownedUnixPorts(metadata.rootPid, parseLsofTcpListeners(lsof.stdout));
67
+ }
68
+ if (lsof.errorCode !== "ENOENT")
69
+ throw commandError("lsof", lsof);
70
+ const ss = await this.commands.run("ss", ["-H", "-ltnp"]);
71
+ if (ss.exitCode !== 0)
72
+ throw commandError("ss", ss);
73
+ return await this.ownedUnixPorts(metadata.rootPid, parseSsTcpListeners(ss.stdout));
74
+ }
45
75
  /** Snapshots loopback TCP ports that predate a supervised child launch. */
46
76
  async inspectLoopbackListeners() {
47
77
  if (this.platform === "win32") {
@@ -75,7 +105,9 @@ export class HostListenerInspector {
75
105
  }
76
106
  async inspectAllWindows(rootPid) {
77
107
  const netstat = await this.runWindowsNetstat();
78
- const listeners = parseWindowsLoopbackListeners(netstat.stdout);
108
+ return await this.ownedWindowsPorts(rootPid, parseWindowsLoopbackListeners(netstat.stdout));
109
+ }
110
+ async ownedWindowsPorts(rootPid, listeners) {
79
111
  if (listeners.length === 0)
80
112
  return [];
81
113
  const pids = [...new Set(listeners.map(listener => listener.pid))];
@@ -130,10 +162,10 @@ export class HostListenerInspector {
130
162
  cause: lastParseError,
131
163
  });
132
164
  }
133
- async runWindowsNetstat() {
165
+ async runWindowsNetstat(args = windowsNetstatArgs) {
134
166
  let lastResult = null;
135
167
  for (let attempt = 1; attempt <= windowsNetstatAttempts; attempt += 1) {
136
- const result = await this.commands.run("netstat.exe", windowsNetstatArgs);
168
+ const result = await this.commands.run("netstat.exe", args);
137
169
  if (result.exitCode === 0)
138
170
  return result;
139
171
  lastResult = result;
@@ -198,6 +230,9 @@ export class HostListenerInspector {
198
230
  else {
199
231
  throw commandError("lsof", lsof);
200
232
  }
233
+ return await this.ownedUnixPorts(rootPid, listeners);
234
+ }
235
+ async ownedUnixPorts(rootPid, listeners) {
201
236
  if (listeners.length === 0)
202
237
  return [];
203
238
  const pids = [...new Set(listeners.map(listener => listener.pid))];
@@ -246,6 +281,44 @@ export function parseSsLoopbackListeners(output) {
246
281
  });
247
282
  }));
248
283
  }
284
+ /** TCP listeners on any local address (IPv4, IPv6 or wildcard) from `netstat -ano`. */
285
+ export function parseWindowsTcpListeners(output) {
286
+ return uniqueListeners(output.split(/\r?\n/u).flatMap(line => {
287
+ const fields = line.trim().split(/\s+/u);
288
+ if (fields.length < 5 || fields[0]?.toUpperCase() !== "TCP" || fields[3]?.toUpperCase() !== "LISTENING")
289
+ return [];
290
+ const port = parseAnyEndpointPort(fields[1]);
291
+ const pids = validPid(fields[4]);
292
+ return port !== null && pids.length === 1 ? [{ pid: pids[0], port }] : [];
293
+ }));
294
+ }
295
+ /** TCP listeners on any local address from `lsof -iTCP -sTCP:LISTEN -Fpn`. */
296
+ export function parseLsofTcpListeners(output) {
297
+ const listeners = [];
298
+ let pid = null;
299
+ for (const line of output.split(/\r?\n/u)) {
300
+ if (line.startsWith("p"))
301
+ pid = validPid(line.slice(1))[0] ?? null;
302
+ if (!line.startsWith("n") || pid === null)
303
+ continue;
304
+ const port = parseAnyEndpointPort(line.slice(1));
305
+ if (port !== null)
306
+ listeners.push({ pid, port });
307
+ }
308
+ return uniqueListeners(listeners);
309
+ }
310
+ /** TCP listeners on any local address from `ss -H -ltnp` (local address is the fourth column). */
311
+ export function parseSsTcpListeners(output) {
312
+ return uniqueListeners(output.split(/\r?\n/u).flatMap(line => {
313
+ const port = parseAnyEndpointPort(line.trim().split(/\s+/u)[3]);
314
+ if (port === null)
315
+ return [];
316
+ return [...line.matchAll(/pid=(\d+)/gu)].flatMap(match => {
317
+ const pid = validPid(match[1])[0];
318
+ return pid ? [{ pid, port }] : [];
319
+ });
320
+ }));
321
+ }
249
322
  export class ExecFileInspectionCommandRunner {
250
323
  run(command, args) {
251
324
  return new Promise(resolve => {
@@ -340,6 +413,14 @@ function parseIpv4LoopbackEndpoint(value) {
340
413
  const port = Number.parseInt(match[1], 10);
341
414
  return Number.isSafeInteger(port) && port >= 1 && port <= 65535 ? port : null;
342
415
  }
416
+ // "127.0.0.1:80", "[::1]:80", "0.0.0.0:80", "[::]:80", "*:80", "127.0.0.53%lo:53".
417
+ function parseAnyEndpointPort(value) {
418
+ const match = value?.match(/^(?:\[[^\]\s]+\]|[^\s:[\]]+)(?:%[^\s:]+)?:(\d+)$/u);
419
+ if (!match)
420
+ return null;
421
+ const port = Number.parseInt(match[1], 10);
422
+ return Number.isSafeInteger(port) && port >= 1 && port <= 65535 ? port : null;
423
+ }
343
424
  function uniqueListeners(values) {
344
425
  const seen = new Set();
345
426
  return values.filter(value => {
@@ -29,7 +29,7 @@ export interface HostRuntimeAdmissionCheckpoint {
29
29
  }
30
30
  export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
31
31
  export interface HostRuntimeProjectCheckpoint {
32
- readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned" | "host_runtime_contract_readmitted";
32
+ readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned" | "host_runtime_contract_readmitted" | "host_runtime_isolation_serialized";
33
33
  readonly message: string;
34
34
  readonly data?: Readonly<Record<string, unknown>>;
35
35
  }
@@ -118,6 +118,9 @@ export interface HostRuntimeLeaseRuntime {
118
118
  providerMemoryTelemetry?(dispatchAttemptId: string, fencingToken: string): AttemptProcessTreeMemoryTelemetry | null;
119
119
  release(dispatchAttemptId: string, fencingToken: string): Promise<RuntimeIsolationLease | null>;
120
120
  invalidatePromotion?(repoId: string, scope?: "all" | "discovery"): Promise<void>;
121
+ promotionQuarantined?(repoId: string, runtimeContractFingerprint: string): Promise<boolean>;
122
+ /** The isolation violation the shared-run listener monitor found after launch, if any; the attempt must fail with it. */
123
+ isolationViolation?(dispatchAttemptId: string, fencingToken: string): Error | null;
121
124
  hasForegroundDemand?(): boolean;
122
125
  reap?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
123
126
  snapshot?(): HostRuntimeCapacitySnapshot;
@@ -185,6 +188,16 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
185
188
  hasForegroundDemand(): boolean;
186
189
  acquirePreparation(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
187
190
  acquire(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
191
+ /**
192
+ * Whether acquire asks for shared project admission. A parallel-eligible probe in a promoted repository
193
+ * runs beside its shared runs (the listener audit fails it closed); otherwise it probes exclusively.
194
+ */
195
+ private sharedAdmissionRequested;
196
+ /**
197
+ * Whether a shared admission may launch without downgrading to exclusive: a stored proof matches the
198
+ * contract by isolation inputs or exact commit, or it is a still-eligible probe of an unrevoked repository.
199
+ */
200
+ private sharedAdmissionStillValid;
188
201
  private reserveHostCapacity;
189
202
  private reserveBackgroundAdmission;
190
203
  private hostCapacityAvailable;
@@ -220,8 +233,17 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
220
233
  /** Stops configured project processes in reverse launch order and releases their ports. */
221
234
  private stopConfiguredProject;
222
235
  providerProcessRunner(dispatchAttemptId: string, fencingToken: string): ProviderProcessRunner | null;
236
+ isolationViolation(dispatchAttemptId: string, fencingToken: string): Error | null;
223
237
  private markCapacityReservationRunning;
224
238
  providerMemoryTelemetry(dispatchAttemptId: string, fencingToken: string): AttemptProcessTreeMemoryTelemetry | null;
239
+ /** Isolation enforcement for parallel-eligible contracts after each launch (restarts included); see monitorListeners. */
240
+ private auditRuntimeListeners;
241
+ /**
242
+ * Quarantines the contract and drops every promotion for the repository. An exclusive run collides with nobody, so it
243
+ * keeps running unpromoted and reports why; a shared one stops its project (a failed stop is left to release) and fails.
244
+ */
245
+ private handleIsolationViolation;
246
+ private monitorSharedRuntimeListeners;
225
247
  private promoteVerifiedRuntime;
226
248
  launchNodeRuntime<T>(dispatchAttemptId: string, fencingToken: string, portName: string, command: NodeRuntimeCommand, launcher: NodeRuntimeCommandLauncher<T>, signal?: AbortSignal): Promise<HostNodeRuntimeLaunch<T>>;
227
249
  release(dispatchAttemptId: string, fencingToken: string, preservePreparation?: boolean): Promise<RuntimeIsolationLease | null>;
@@ -251,7 +273,8 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
251
273
  private drainParallelProjectWaiters;
252
274
  private drainBackgroundAdmissionWaiters;
253
275
  private refreshKnownPromotions;
254
- invalidatePromotion(repoId: string, scope?: "all" | "discovery"): Promise<void>;
276
+ invalidatePromotion(repoId: string, scope?: "all" | "discovery", quarantineFingerprints?: readonly string[]): Promise<void>;
277
+ promotionQuarantined(repoId: string, fingerprint: string): Promise<boolean>;
255
278
  private drainAdmissionWaiters;
256
279
  private reconcileReservationOwners;
257
280
  private reservationOwnerIsLive;
@@ -17,11 +17,11 @@ 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
19
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
20
- import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
20
+ import { AttemptNodeRuntimeLauncher, AttemptSupervisedProviderProcessRunner, brokeredHostPorts, isolationViolationError } from "./attempt-node-runtime-launcher.js";
21
21
  import { HostListenerInspector } from "./host-listener-inspector.js";
22
22
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
23
23
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
24
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
24
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostParallelPromotionMatches, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
25
25
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
26
26
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
27
27
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
@@ -407,9 +407,7 @@ export class HostRuntimeLeaseManager {
407
407
  const projectKey = executionClass === "analysis_only"
408
408
  ? projectHostAnalysisKey(dispatch.repo.id)
409
409
  : projectHostRuntimeSingletonKey(dispatch.repo.id);
410
- const useParallelAdmission = priority === "foreground"
411
- && dispatch.cycleRun.phase !== "prepared_readiness"
412
- && (promotion !== null || executionClass === "analysis_only");
410
+ const useParallelAdmission = this.sharedAdmissionRequested(dispatch, owner, executionClass, priority, promotion);
413
411
  let keys = useParallelAdmission ? [] : [projectKey];
414
412
  const resources = normalizedHostResourceRequest(sandbox.requestedResources);
415
413
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
@@ -464,6 +462,35 @@ export class HostRuntimeLeaseManager {
464
462
  this.acquiringAdmissions.delete(acquisitionKey);
465
463
  }
466
464
  }
465
+ /**
466
+ * Whether acquire asks for shared project admission. A parallel-eligible probe in a promoted repository
467
+ * runs beside its shared runs (the listener audit fails it closed); otherwise it probes exclusively.
468
+ */
469
+ sharedAdmissionRequested(dispatch, owner, executionClass, priority, promotion) {
470
+ if (priority !== "foreground")
471
+ return false;
472
+ if (executionClass === "analysis_only")
473
+ return dispatch.cycleRun.phase !== "prepared_readiness";
474
+ if (promotion === null)
475
+ return false;
476
+ return dispatch.cycleRun.phase !== "prepared_readiness"
477
+ || this.preparedReadiness.isParallelEligibleProbe(owner.dispatchAttemptId, owner.fencingToken);
478
+ }
479
+ /**
480
+ * Whether a shared admission may launch without downgrading to exclusive: a stored proof matches the
481
+ * contract by isolation inputs or exact commit, or it is a still-eligible probe of an unrevoked repository.
482
+ */
483
+ async sharedAdmissionStillValid(dispatch, owner, admission, runtimeContract, proofIdentity) {
484
+ if (!hostRuntimeParallelEligible(runtimeContract))
485
+ return false;
486
+ if (dispatch.cycleRun.phase === "prepared_readiness") {
487
+ return admission.parallelProjectKey !== null && await this.promotionStore.load(dispatch.repo.id) !== null
488
+ && this.preparedReadiness.isParallelEligibleProbe(owner.dispatchAttemptId, owner.fencingToken);
489
+ }
490
+ if (hostRuntimeContractFingerprint(runtimeContract) !== proofIdentity.runtimeContractFingerprint)
491
+ return false;
492
+ return hostParallelPromotionMatches(await this.promotionStore.load(dispatch.repo.id, proofIdentity), proofIdentity);
493
+ }
467
494
  async reserveHostCapacity(owner, resources, expiresAt, signal, priority = "foreground") {
468
495
  const existing = this.capacityReservations.get(owner.dispatchAttemptId);
469
496
  if (existing) {
@@ -991,13 +1018,9 @@ export class HostRuntimeLeaseManager {
991
1018
  || JSON.stringify(preparedProof) !== JSON.stringify(await preparedRuntimeIdentity(normalizedWorktreePath, signal)))) {
992
1019
  throw new Error("host_runtime_prepared_source_changed: source changed after its foreground proof; agent was not started.");
993
1020
  }
994
- const promotion = admission.executionClass === "managed_runtime"
995
- ? await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha })
996
- : null;
997
- const promotionMatches = hostRuntimeParallelEligible(runtimeContract)
998
- && promotion?.runtimeContractFingerprint === runtimeContractFingerprint
999
- && promotion.inputCommitSha === inputCommitSha;
1000
- if (admission.executionClass === "managed_runtime" && admission.keys.length === 0 && !promotionMatches) {
1021
+ const proofIdentity = preparedProof ?? { runtimeContractFingerprint, inputCommitSha }, admittedRevocationGeneration = await this.promotionStore.revocationGeneration(dispatch.repo.id);
1022
+ if (admission.executionClass === "managed_runtime" && admission.keys.length === 0
1023
+ && !await this.sharedAdmissionStillValid(dispatch, owner, admission, runtimeContract, proofIdentity)) {
1001
1024
  const projectKeys = hostRuntimeSingletonKeys(dispatch);
1002
1025
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
1003
1026
  ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
@@ -1135,10 +1158,10 @@ export class HostRuntimeLeaseManager {
1135
1158
  attemptRoot,
1136
1159
  attemptRootIdentity,
1137
1160
  runtimeContract,
1138
- runtimeContractFingerprint,
1161
+ runtimeContractFingerprint, admittedContractFingerprint: runtimeContractFingerprint,
1139
1162
  inputCommitSha,
1140
1163
  executionClass: admission.executionClass,
1141
- parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1164
+ parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness", admittedRevocationGeneration,
1142
1165
  processSupervisor,
1143
1166
  adapterCleanups: [],
1144
1167
  adapterCleanupsByPort: new Map(),
@@ -1205,6 +1228,9 @@ export class HostRuntimeLeaseManager {
1205
1228
  await this.writeLedger(renewed);
1206
1229
  }
1207
1230
  async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1231
+ const violation = this.isolationViolation(dispatchAttemptId, fencingToken);
1232
+ if (violation)
1233
+ throw violation;
1208
1234
  return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
1209
1235
  }
1210
1236
  /**
@@ -1218,16 +1244,8 @@ export class HostRuntimeLeaseManager {
1218
1244
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1219
1245
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1220
1246
  }
1221
- if (active.executionClass === "analysis_only") {
1222
- return {
1223
- lease: active.lease,
1224
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1225
- runtimeContract: active.runtimeContract,
1226
- executionClass: active.executionClass,
1227
- };
1228
- }
1229
1247
  const configuredPorts = active.runtimeContract.contract.runtime.ports.filter((port) => port.launch !== null);
1230
- if (configuredPorts.length === 0) {
1248
+ if (active.executionClass === "analysis_only" || configuredPorts.length === 0) {
1231
1249
  return {
1232
1250
  lease: active.lease,
1233
1251
  environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
@@ -1269,6 +1287,7 @@ export class HostRuntimeLeaseManager {
1269
1287
  // Runtime output is persisted to attempt logs; the database login and master key it may print are redacted.
1270
1288
  const capabilitySecrets = [...attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString), apiMasterKey];
1271
1289
  const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1290
+ active.runtimeLauncher = launcher;
1272
1291
  for (const configuredPort of configuredPorts) {
1273
1292
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
1274
1293
  const buildEnvironment = {
@@ -1328,12 +1347,13 @@ export class HostRuntimeLeaseManager {
1328
1347
  }
1329
1348
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1330
1349
  command: configuredPort.launch.command,
1331
- args: supervisedRuntimeLaunchArguments(configuredPort),
1332
- cwd: workingDirectory,
1350
+ args: supervisedRuntimeLaunchArguments(configuredPort), cwd: workingDirectory,
1333
1351
  environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1334
1352
  }, launcher, signal);
1353
+ await this.auditRuntimeListeners(active, launcher, onProjectCheckpoint);
1335
1354
  }
1336
- const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
1355
+ const promotedLease = await this.promoteVerifiedRuntime(active, active.lease, promote);
1356
+ this.monitorSharedRuntimeListeners(active, launcher);
1337
1357
  const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1338
1358
  const playwright = active.runtimeContract.contract.runtime.playwright;
1339
1359
  if (!playwright) {
@@ -1386,6 +1406,8 @@ export class HostRuntimeLeaseManager {
1386
1406
  }
1387
1407
  if (signal?.aborted)
1388
1408
  throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
1409
+ if (active.isolationViolation)
1410
+ throw active.isolationViolation;
1389
1411
  if (active.restartingConfiguredProject) {
1390
1412
  throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
1391
1413
  }
@@ -1428,7 +1450,13 @@ export class HostRuntimeLeaseManager {
1428
1450
  }
1429
1451
  await this.stopConfiguredProject(active, portNames);
1430
1452
  // Keeps whatever admission the attempt holds; see launchConfiguredProject.
1431
- const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
1453
+ const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false)
1454
+ .catch((error) => {
1455
+ // Ports launched before the failure keep running until release or the next restart: keep auditing them.
1456
+ if (active.runtimeLauncher && !active.isolationViolation)
1457
+ this.monitorSharedRuntimeListeners(active, active.runtimeLauncher);
1458
+ throw error;
1459
+ });
1432
1460
  if (active.releasing) {
1433
1461
  throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1434
1462
  }
@@ -1436,10 +1464,8 @@ export class HostRuntimeLeaseManager {
1436
1464
  }
1437
1465
  /** Stops configured project processes in reverse launch order and releases their ports. */
1438
1466
  async stopConfiguredProject(active, portNames) {
1439
- const launched = active.lease.resources.ports
1440
- .map(port => port.name)
1441
- .filter(name => portNames.includes(name))
1442
- .reverse();
1467
+ active.stopListenerMonitor?.();
1468
+ const launched = active.lease.resources.ports.map(port => port.name).filter(name => portNames.includes(name)).reverse();
1443
1469
  for (const name of launched) {
1444
1470
  if (active.releasing) {
1445
1471
  throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
@@ -1466,6 +1492,10 @@ export class HostRuntimeLeaseManager {
1466
1492
  return null;
1467
1493
  return new AttemptSupervisedProviderProcessRunner(active.processSupervisor, hostPortOwner(active.lease), this.listenerInspector, active.executionClass === "analysis_only", () => this.markCapacityReservationRunning(dispatchAttemptId, fencingToken));
1468
1494
  }
1495
+ isolationViolation(dispatchAttemptId, fencingToken) {
1496
+ const active = this.active.get(dispatchAttemptId);
1497
+ return active?.lease.fencingToken === fencingToken ? active.isolationViolation ?? null : null;
1498
+ }
1469
1499
  markCapacityReservationRunning(dispatchAttemptId, fencingToken) {
1470
1500
  const reservation = this.capacityReservations.get(dispatchAttemptId);
1471
1501
  if (reservation?.owner.fencingToken === fencingToken)
@@ -1477,29 +1507,53 @@ export class HostRuntimeLeaseManager {
1477
1507
  return null;
1478
1508
  return active.processSupervisor.providerMemoryTelemetry();
1479
1509
  }
1480
- async promoteVerifiedRuntime(active, runtimeLease) {
1481
- if (!active.parallelPromotionEligible)
1510
+ /** Isolation enforcement for parallel-eligible contracts after each launch (restarts included); see monitorListeners. */
1511
+ async auditRuntimeListeners(active, launcher, onProjectCheckpoint) {
1512
+ if (!hostRuntimeParallelEligible(active.runtimeContract))
1513
+ return;
1514
+ const violation = await launcher.unbrokeredListenerViolation(brokeredHostPorts(active.lease.resources.ports));
1515
+ if (violation)
1516
+ await this.handleIsolationViolation(active, violation, onProjectCheckpoint);
1517
+ }
1518
+ /**
1519
+ * Quarantines the contract and drops every promotion for the repository. An exclusive run collides with nobody, so it
1520
+ * keeps running unpromoted and reports why; a shared one stops its project (a failed stop is left to release) and fails.
1521
+ */
1522
+ async handleIsolationViolation(active, detail, onProjectCheckpoint) {
1523
+ await this.invalidatePromotion(active.repoId, "all", [active.admittedContractFingerprint, active.runtimeContractFingerprint]).catch(() => undefined);
1524
+ active.parallelPromotionEligible = false;
1525
+ if (active.lease.resources.singletonKeys.includes(projectHostRuntimeSingletonKey(active.repoId))) {
1526
+ return await onProjectCheckpoint?.({ code: "host_runtime_isolation_serialized", data: { detail },
1527
+ message: `The runtime did not prove host isolation (${detail}); the repository's runs are serialized and this one continues unpromoted.` });
1528
+ }
1529
+ active.isolationViolation = isolationViolationError(detail);
1530
+ await this.stopConfiguredProject(active, active.lease.resources.ports.map(port => port.name)).catch(() => undefined);
1531
+ throw active.isolationViolation;
1532
+ }
1533
+ monitorSharedRuntimeListeners(active, launcher) {
1534
+ active.stopListenerMonitor?.();
1535
+ if (!hostRuntimeParallelEligible(active.runtimeContract))
1536
+ return;
1537
+ active.stopListenerMonitor = launcher.monitorListeners(() => active.releasing
1538
+ || active.lease.resources.singletonKeys.includes(projectHostRuntimeSingletonKey(active.repoId)) ? null : brokeredHostPorts(active.lease.resources.ports), detail => this.handleIsolationViolation(active, detail));
1539
+ }
1540
+ async promoteVerifiedRuntime(active, runtimeLease, promote) {
1541
+ if (!promote || !active.parallelPromotionEligible)
1482
1542
  return runtimeLease;
1483
1543
  const verifiedPortNames = runtimeLease.resources.ports.map(port => port.name).sort((left, right) => left.localeCompare(right));
1484
1544
  const requiredPortNames = configuredLaunchPortNames(active.runtimeContract);
1485
1545
  if (requiredPortNames.length !== verifiedPortNames.length
1486
- || requiredPortNames.some((name, index) => name !== verifiedPortNames[index])) {
1546
+ || requiredPortNames.some((name, index) => name !== verifiedPortNames[index]))
1487
1547
  return runtimeLease;
1488
- }
1489
1548
  const projectKey = projectHostRuntimeSingletonKey(active.repoId);
1490
- const promotedLease = withRuntimeIsolationResources(runtimeLease, {
1491
- ...runtimeLease.resources,
1492
- singletonKeys: runtimeLease.resources.singletonKeys.filter(key => key !== projectKey),
1493
- });
1549
+ const promotedLease = withRuntimeIsolationResources(runtimeLease, { ...runtimeLease.resources,
1550
+ singletonKeys: runtimeLease.resources.singletonKeys.filter(key => key !== projectKey) });
1494
1551
  await this.writeLedger(promotedLease);
1495
1552
  active.lease = promotedLease;
1496
1553
  try {
1497
- const promotion = await this.promotionStore.observe(active.repoId, active.runtimeContract, runtimeLease.dispatchAttemptId, verifiedPortNames, active.inputCommitSha);
1554
+ const promotion = await this.promotionStore.observe(active.repoId, active.runtimeContract, runtimeLease.dispatchAttemptId, verifiedPortNames, active.inputCommitSha, undefined, undefined, active.admittedRevocationGeneration);
1498
1555
  this.knownPromotions.set(promotion.repoId, promotion);
1499
- const owner = {
1500
- dispatchAttemptId: runtimeLease.dispatchAttemptId,
1501
- fencingToken: runtimeLease.fencingToken,
1502
- };
1556
+ const owner = { dispatchAttemptId: runtimeLease.dispatchAttemptId, fencingToken: runtimeLease.fencingToken };
1503
1557
  if (!this.parallelProjectOwned(projectKey, owner)) {
1504
1558
  this.convertSingletonToParallelProject(projectKey, owner, promotion);
1505
1559
  }
@@ -1514,8 +1568,9 @@ export class HostRuntimeLeaseManager {
1514
1568
  }
1515
1569
  return promotedLease;
1516
1570
  }
1517
- catch {
1518
- await this.invalidatePromotion(active.repoId).catch(() => undefined);
1571
+ catch (error) { // A fenced observe left no records: revoking again would delete fresh proofs recorded since.
1572
+ if (!(error instanceof Error && error.message.startsWith("host_parallel_promotion_revoked:")))
1573
+ await this.invalidatePromotion(active.repoId).catch(() => undefined);
1519
1574
  active.lease = runtimeLease;
1520
1575
  await this.writeLedger(runtimeLease);
1521
1576
  return runtimeLease;
@@ -1608,6 +1663,7 @@ export class HostRuntimeLeaseManager {
1608
1663
  if (active.lease.fencingToken !== fencingToken)
1609
1664
  return null;
1610
1665
  active.releasing = true;
1666
+ active.stopListenerMonitor?.();
1611
1667
  // Attempt teardown cancels the attempt's queued heavy steps and stops its running
1612
1668
  // ones. Each running step (an ASP.NET prebuild, an install, a validation step)
1613
1669
  // returns its own token only after its processes have exited, so the capacity is
@@ -2029,10 +2085,11 @@ export class HostRuntimeLeaseManager {
2029
2085
  for (const promotion of promotions)
2030
2086
  this.knownPromotions.set(promotion.repoId, promotion);
2031
2087
  }
2032
- async invalidatePromotion(repoId, scope = "all") {
2033
- await this.promotionStore.invalidate(repoId, scope);
2088
+ async invalidatePromotion(repoId, scope = "all", quarantineFingerprints) {
2034
2089
  this.knownPromotions.delete(repoId.trim().toLowerCase());
2090
+ await this.promotionStore.invalidate(repoId, scope, quarantineFingerprints);
2035
2091
  }
2092
+ promotionQuarantined(repoId, fingerprint) { return this.promotionStore.quarantined(repoId, fingerprint); }
2036
2093
  drainAdmissionWaiters() {
2037
2094
  this.reconcileReservationOwners();
2038
2095
  this.drainSingletonWaiters();
@@ -2082,95 +2139,6 @@ export class HostRuntimeLeaseManager {
2082
2139
  return this.reservationOwnerIsLive({ dispatchAttemptId, fencingToken });
2083
2140
  }
2084
2141
  }
2085
- class AttemptSupervisedProviderProcessRunner {
2086
- supervisor;
2087
- owner;
2088
- listenerInspector;
2089
- enforceNoListeners;
2090
- onProcessTreeStarted;
2091
- constructor(supervisor, owner, listenerInspector, enforceNoListeners, onProcessTreeStarted) {
2092
- this.supervisor = supervisor;
2093
- this.owner = owner;
2094
- this.listenerInspector = listenerInspector;
2095
- this.enforceNoListeners = enforceNoListeners;
2096
- this.onProcessTreeStarted = onProcessTreeStarted;
2097
- }
2098
- async run(request, handlers = {}, signal) {
2099
- const baselineListeners = this.enforceNoListeners
2100
- ? new Set(await this.listenerInspector.inspectLoopbackListeners())
2101
- : new Set();
2102
- const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
2103
- this.onProcessTreeStarted();
2104
- try {
2105
- return await this.awaitProviderResult(child, baselineListeners, signal);
2106
- }
2107
- finally {
2108
- // The provider tree, and the MCP server inside it, is gone. A managed command that
2109
- // server started now has no supervisor and no receipt writer, so it must not keep
2110
- // running into the next provider generation. This never rejects; a command it
2111
- // cannot prove stopped is left to attempt teardown, which fails closed.
2112
- await this.supervisor.stopOrphanedManagedCommands();
2113
- }
2114
- }
2115
- async awaitProviderResult(child, baselineListeners, signal) {
2116
- if (!this.enforceNoListeners)
2117
- return await child.result;
2118
- let settled = false;
2119
- let inspectionFailure;
2120
- const monitor = (async () => {
2121
- while (!settled) {
2122
- try {
2123
- const ports = (await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner))
2124
- .filter(port => !baselineListeners.has(port));
2125
- if (ports.length > 0) {
2126
- inspectionFailure = new Error(`host_analysis_listener_violation: analysis-only provider opened undeclared loopback listener(s): ${ports.join(", ")}.`);
2127
- await child.stop(this.owner.fencingToken).catch(() => undefined);
2128
- return;
2129
- }
2130
- }
2131
- catch (error) {
2132
- inspectionFailure = error;
2133
- await child.stop(this.owner.fencingToken).catch(() => undefined);
2134
- return;
2135
- }
2136
- await waitForAnalysisInspection(250, signal).catch(error => {
2137
- if (!settled && !signal?.aborted)
2138
- inspectionFailure = error;
2139
- });
2140
- }
2141
- })();
2142
- try {
2143
- const result = await child.result;
2144
- settled = true;
2145
- await monitor;
2146
- if (inspectionFailure)
2147
- throw inspectionFailure;
2148
- return result;
2149
- }
2150
- catch (error) {
2151
- settled = true;
2152
- await monitor.catch(() => undefined);
2153
- if (inspectionFailure)
2154
- throw inspectionFailure;
2155
- throw error;
2156
- }
2157
- }
2158
- }
2159
- function waitForAnalysisInspection(milliseconds, signal) {
2160
- if (signal?.aborted)
2161
- return Promise.reject(cancellationError(signal));
2162
- return new Promise((resolve, reject) => {
2163
- const timer = setTimeout(() => {
2164
- signal?.removeEventListener("abort", abort);
2165
- resolve();
2166
- }, milliseconds);
2167
- const abort = () => {
2168
- clearTimeout(timer);
2169
- reject(cancellationError(signal));
2170
- };
2171
- signal?.addEventListener("abort", abort, { once: true });
2172
- });
2173
- }
2174
2142
  export class HostRuntimeLeaseCleanupError extends Error {
2175
2143
  lease;
2176
2144
  constructor(lease, cause) {