@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0fedbc5c9ef7

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 (182) hide show
  1. package/README.md +89 -1
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +19 -12
  17. package/dist/bridge/bridge.service.js +155 -282
  18. package/dist/bridge/bridge.types.d.ts +5 -0
  19. package/dist/bridge/in-flight-registry.d.ts +62 -0
  20. package/dist/bridge/in-flight-registry.js +207 -0
  21. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  22. package/dist/bridge/readiness-result-outbox.js +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +14 -1
  24. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  25. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  26. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  27. package/dist/bridge/windows-bash-resolution.js +153 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +56 -12
  36. package/dist/cli/cli.service.d.ts +3 -10
  37. package/dist/cli/cli.service.js +10 -171
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +2 -0
  41. package/dist/cli/local-config.js +7 -1
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  48. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  49. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  50. package/dist/runtime/attempt-process-supervisor.js +12 -6
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  54. package/dist/runtime/dotnet-build-outputs.js +402 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  56. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  57. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  58. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  59. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  60. package/dist/runtime/host-listener-inspector.js +84 -3
  61. package/dist/runtime/host-load-admission.d.ts +5 -0
  62. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  63. package/dist/runtime/host-load-governor-config.js +4 -1
  64. package/dist/runtime/host-load-governor.d.ts +10 -1
  65. package/dist/runtime/host-load-governor.js +33 -3
  66. package/dist/runtime/host-load-ledger-lock.js +6 -4
  67. package/dist/runtime/host-load-runtime-settings.js +4 -2
  68. package/dist/runtime/host-load-sampler.d.ts +8 -1
  69. package/dist/runtime/host-load-sampler.js +14 -7
  70. package/dist/runtime/host-load-test-slot.js +7 -0
  71. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  72. package/dist/runtime/host-runtime-contract.js +29 -1
  73. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  74. package/dist/runtime/host-runtime-lease.js +140 -296
  75. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  76. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  77. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  78. package/dist/runtime/host-runtime-promotion.js +307 -14
  79. package/dist/runtime/managed-command-teardown.js +5 -16
  80. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  81. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  82. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  83. package/dist/runtime/prepared-runtime-identity.js +130 -9
  84. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  85. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  86. package/dist/runtime/runner-settings.d.ts +4 -0
  87. package/dist/runtime/runner-settings.js +22 -0
  88. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  89. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  90. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  91. package/dist/sandbox/host-capacity-broker.js +4 -2
  92. package/dist/sandbox/managed-branch.d.ts +13 -0
  93. package/dist/sandbox/managed-branch.js +90 -0
  94. package/dist/sandbox/provider-auth/codex.js +11 -11
  95. package/dist/sandbox/runtime.js +3 -7
  96. package/dist/session/managed-attempt-tools.d.ts +0 -7
  97. package/dist/session/managed-attempt-tools.js +50 -82
  98. package/dist/session/managed-build-coordinator.d.ts +16 -0
  99. package/dist/session/managed-build-coordinator.js +10 -0
  100. package/dist/session/managed-build-receipt.d.ts +5 -0
  101. package/dist/session/managed-build-receipt.js +8 -3
  102. package/dist/session/phase-completion.artifacts.js +2 -1
  103. package/dist/session/phase-completion.d.ts +8 -0
  104. package/dist/session/phase-completion.js +1 -0
  105. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  106. package/dist/session/phase-completion.mcp-args.js +156 -0
  107. package/dist/session/phase-completion.runtime.d.ts +0 -8
  108. package/dist/session/phase-completion.runtime.js +43 -197
  109. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  110. package/dist/session/pre-publication-native-postgres.js +111 -0
  111. package/dist/session/pre-publication-process.js +10 -10
  112. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  113. package/dist/session/pre-publication-step-execution.js +6 -5
  114. package/dist/session/pre-publication-validation.d.ts +7 -3
  115. package/dist/session/pre-publication-validation.js +32 -30
  116. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  117. package/dist/session/provider-cli/claude-background-work.js +4 -3
  118. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  119. package/dist/session/provider-cli/host-build-lock.js +30 -0
  120. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  121. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  122. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  123. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  124. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  125. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  126. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  127. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  128. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  129. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  130. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  131. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  132. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  133. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  134. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  135. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  136. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  137. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  138. package/dist/session/qa-sidecar-validation.js +28 -0
  139. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  140. package/dist/session/sandbox-host-capacity-gate.js +35 -16
  141. package/dist/session/session-redaction.js +31 -181
  142. package/dist/session/session.service.d.ts +6 -0
  143. package/dist/session/session.service.js +131 -88
  144. package/dist/session/session.types.d.ts +1 -0
  145. package/dist/session/session.types.js +3 -3
  146. package/dist/session/sidecar-json-shape.d.ts +31 -0
  147. package/dist/session/sidecar-json-shape.js +217 -0
  148. package/dist/shared/fs/file-identity.d.ts +10 -0
  149. package/dist/shared/fs/file-identity.js +15 -0
  150. package/dist/shared/fs/replace-file.d.ts +7 -0
  151. package/dist/shared/fs/replace-file.js +33 -0
  152. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  153. package/dist/shared/process/host-process-recovery.js +23 -3
  154. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  155. package/dist/shared/process/host-process-supervisor.js +66 -14
  156. package/dist/shared/provider-capabilities.js +9 -1
  157. package/dist/version.d.ts +1 -1
  158. package/dist/version.js +1 -1
  159. package/dist/worktree/orphan-relink.d.ts +19 -0
  160. package/dist/worktree/orphan-relink.js +106 -0
  161. package/dist/worktree/wip-git.d.ts +42 -0
  162. package/dist/worktree/wip-git.js +139 -0
  163. package/dist/worktree/wip-refs.d.ts +77 -0
  164. package/dist/worktree/wip-refs.js +146 -0
  165. package/dist/worktree/wip-restore.d.ts +46 -0
  166. package/dist/worktree/wip-restore.js +280 -0
  167. package/dist/worktree/wip-snapshot.d.ts +53 -0
  168. package/dist/worktree/wip-snapshot.js +270 -0
  169. package/dist/worktree/worktree-inputs.d.ts +8 -0
  170. package/dist/worktree/worktree-inputs.js +134 -0
  171. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  172. package/dist/worktree/worktree-origin-sync.js +128 -0
  173. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  174. package/dist/worktree/worktree-wip-events.js +115 -0
  175. package/dist/worktree/worktree-wip.d.ts +51 -0
  176. package/dist/worktree/worktree-wip.js +190 -0
  177. package/dist/worktree/worktree.base.d.ts +7 -1
  178. package/dist/worktree/worktree.service.d.ts +27 -5
  179. package/dist/worktree/worktree.service.js +112 -181
  180. package/dist/worktree/worktree.types.d.ts +35 -0
  181. package/package.json +1 -1
  182. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -10,34 +10,30 @@ import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
10
  import { ForgeFailureError } from "../session/session.types.js";
11
11
  import { resolveExistingDirectoryPath } from "../shared/path/path.js";
12
12
  import { formatBytes } from "../shared/format/format-bytes.js";
13
- import { redactText } from "../shared/redaction/redaction.js";
14
13
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
15
14
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
16
- import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
15
+ import { hostPortEnvironment, loadHostRuntimeContract, newAttemptApiMasterKey, withAttemptApiMasterKey, } from "./host-runtime-contract.js";
17
16
  import { HostPortBroker, } from "./host-port-broker.js";
18
17
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
19
18
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
20
- import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
21
19
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
22
- import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
20
+ import { AttemptNodeRuntimeLauncher, AttemptSupervisedProviderProcessRunner, brokeredHostPorts, isolationViolationError } from "./attempt-node-runtime-launcher.js";
23
21
  import { HostListenerInspector } from "./host-listener-inspector.js";
24
22
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
25
23
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
26
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
24
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostParallelPromotionMatches, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
27
25
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
28
26
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
29
27
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
30
- import { readCanonicalSourceFile } from "./canonical-source-file.js";
31
- import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
28
+ import { logHostRuntimeStatus, recoverPersistedHostProcesses, replaceHostRuntimeLedgerFile, retryDegradedHostRelease, } from "./host-runtime-ledger-recovery.js";
32
29
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
33
- import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
30
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, executeAspNetRuntimeBuild, resolveWorktreeCommitSha, supervisedRuntimeLaunchArguments, } from "./aspnet-runtime-prebuild.js";
34
31
  import { HostLoadGovernor } from "./host-load-governor.js";
35
32
  import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
36
33
  import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
37
34
  import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
38
35
  import { HostLoadSampler } from "./host-load-sampler.js";
39
36
  const hostCapacityWaiterScanLimit = 64;
40
- const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
41
37
  export class HostRuntimeLeaseManager {
42
38
  stateRoot;
43
39
  processSupervisors;
@@ -163,19 +159,16 @@ export class HostRuntimeLeaseManager {
163
159
  }
164
160
  const active = this.active.get(lease.dispatchAttemptId);
165
161
  if (active) {
162
+ // A live lease is never released here, however long past its expiry; a degraded one
163
+ // is retried under its own fence until teardown proves its process tree stopped.
166
164
  if (active.lease.state !== "degraded")
167
165
  continue;
168
166
  report.examined += 1;
169
- try {
170
- const released = await this.release(lease.dispatchAttemptId, lease.fencingToken);
171
- if (released?.state === "released")
172
- report.reaped += 1;
173
- else
174
- report.degraded += 1;
175
- }
176
- catch {
167
+ const released = await retryDegradedHostRelease(active.lease, () => this.release(lease.dispatchAttemptId, lease.fencingToken), options.log ?? logHostRuntimeStatus);
168
+ if (released)
169
+ report.reaped += 1;
170
+ else
177
171
  report.degraded += 1;
178
- }
179
172
  continue;
180
173
  }
181
174
  const staleInstance = lease.runnerInstanceId !== options.runnerInstanceId;
@@ -190,18 +183,16 @@ export class HostRuntimeLeaseManager {
190
183
  if (!attemptRootIdentity) {
191
184
  throw new Error("host_runtime_reaper_invalid: original attempt-root identity is unavailable.");
192
185
  }
193
- outcomes = await this.recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity);
186
+ outcomes = await recoverPersistedHostProcesses(lease, attemptRoot, this.attemptRoot(lease.dispatchAttemptId), attemptRootIdentity, this.processRecovery);
194
187
  }
195
188
  catch {
196
- await this.markLedgerDegraded(ledger);
197
- report.degraded += 1;
189
+ await this.markLedgerDegraded(ledger, report);
198
190
  continue;
199
191
  }
200
192
  report.processesTerminated += outcomes.filter(outcome => outcome === "terminated").length;
201
193
  report.reusedPidsProtected += outcomes.filter(outcome => outcome === "pid_reused").length;
202
194
  if (outcomes.includes("unverifiable")) {
203
- await this.markLedgerDegraded(ledger);
204
- report.degraded += 1;
195
+ await this.markLedgerDegraded(ledger, report);
205
196
  continue;
206
197
  }
207
198
  // The runtime has already been released. Keep the over-budget original
@@ -248,8 +239,7 @@ export class HostRuntimeLeaseManager {
248
239
  report.reaped += 1;
249
240
  }
250
241
  catch {
251
- await this.markLedgerDegraded(ledger);
252
- report.degraded += 1;
242
+ await this.markLedgerDegraded(ledger, report);
253
243
  }
254
244
  }
255
245
  // Databases issued to attempts that ended without a clean release (a Bridge crash, or a
@@ -417,9 +407,7 @@ export class HostRuntimeLeaseManager {
417
407
  const projectKey = executionClass === "analysis_only"
418
408
  ? projectHostAnalysisKey(dispatch.repo.id)
419
409
  : projectHostRuntimeSingletonKey(dispatch.repo.id);
420
- const useParallelAdmission = priority === "foreground"
421
- && dispatch.cycleRun.phase !== "prepared_readiness"
422
- && (promotion !== null || executionClass === "analysis_only");
410
+ const useParallelAdmission = this.sharedAdmissionRequested(dispatch, owner, executionClass, priority, promotion);
423
411
  let keys = useParallelAdmission ? [] : [projectKey];
424
412
  const resources = normalizedHostResourceRequest(sandbox.requestedResources);
425
413
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
@@ -474,6 +462,35 @@ export class HostRuntimeLeaseManager {
474
462
  this.acquiringAdmissions.delete(acquisitionKey);
475
463
  }
476
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
+ }
477
494
  async reserveHostCapacity(owner, resources, expiresAt, signal, priority = "foreground") {
478
495
  const existing = this.capacityReservations.get(owner.dispatchAttemptId);
479
496
  if (existing) {
@@ -1001,13 +1018,9 @@ export class HostRuntimeLeaseManager {
1001
1018
  || JSON.stringify(preparedProof) !== JSON.stringify(await preparedRuntimeIdentity(normalizedWorktreePath, signal)))) {
1002
1019
  throw new Error("host_runtime_prepared_source_changed: source changed after its foreground proof; agent was not started.");
1003
1020
  }
1004
- const promotion = admission.executionClass === "managed_runtime"
1005
- ? await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha })
1006
- : null;
1007
- const promotionMatches = hostRuntimeParallelEligible(runtimeContract)
1008
- && promotion?.runtimeContractFingerprint === runtimeContractFingerprint
1009
- && promotion.inputCommitSha === inputCommitSha;
1010
- 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)) {
1011
1024
  const projectKeys = hostRuntimeSingletonKeys(dispatch);
1012
1025
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
1013
1026
  ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
@@ -1145,10 +1158,10 @@ export class HostRuntimeLeaseManager {
1145
1158
  attemptRoot,
1146
1159
  attemptRootIdentity,
1147
1160
  runtimeContract,
1148
- runtimeContractFingerprint,
1161
+ runtimeContractFingerprint, admittedContractFingerprint: runtimeContractFingerprint,
1149
1162
  inputCommitSha,
1150
1163
  executionClass: admission.executionClass,
1151
- parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1164
+ parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness", admittedRevocationGeneration,
1152
1165
  processSupervisor,
1153
1166
  adapterCleanups: [],
1154
1167
  adapterCleanupsByPort: new Map(),
@@ -1215,6 +1228,9 @@ export class HostRuntimeLeaseManager {
1215
1228
  await this.writeLedger(renewed);
1216
1229
  }
1217
1230
  async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1231
+ const violation = this.isolationViolation(dispatchAttemptId, fencingToken);
1232
+ if (violation)
1233
+ throw violation;
1218
1234
  return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
1219
1235
  }
1220
1236
  /**
@@ -1228,16 +1244,8 @@ export class HostRuntimeLeaseManager {
1228
1244
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1229
1245
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1230
1246
  }
1231
- if (active.executionClass === "analysis_only") {
1232
- return {
1233
- lease: active.lease,
1234
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1235
- runtimeContract: active.runtimeContract,
1236
- executionClass: active.executionClass,
1237
- };
1238
- }
1239
1247
  const configuredPorts = active.runtimeContract.contract.runtime.ports.filter((port) => port.launch !== null);
1240
- if (configuredPorts.length === 0) {
1248
+ if (active.executionClass === "analysis_only" || configuredPorts.length === 0) {
1241
1249
  return {
1242
1250
  lease: active.lease,
1243
1251
  environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
@@ -1275,9 +1283,11 @@ export class HostRuntimeLeaseManager {
1275
1283
  data: { database: active.databaseCapability.databaseName },
1276
1284
  });
1277
1285
  }
1278
- // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1279
- const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1286
+ const apiMasterKey = attemptApiMasterKey(active);
1287
+ // Runtime output is persisted to attempt logs; the database login and master key it may print are redacted.
1288
+ const capabilitySecrets = [...attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString), apiMasterKey];
1280
1289
  const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1290
+ active.runtimeLauncher = launcher;
1281
1291
  for (const configuredPort of configuredPorts) {
1282
1292
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
1283
1293
  const buildEnvironment = {
@@ -1286,7 +1296,7 @@ export class HostRuntimeLeaseManager {
1286
1296
  };
1287
1297
  const prebuild = createAspNetRuntimePrebuildPlan({
1288
1298
  command: configuredPort.launch.command,
1289
- args: configuredPort.launch.args,
1299
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1290
1300
  cwd: workingDirectory,
1291
1301
  worktreePath: active.lease.worktreePath,
1292
1302
  environment: buildEnvironment,
@@ -1297,7 +1307,7 @@ export class HostRuntimeLeaseManager {
1297
1307
  await onProjectCheckpoint?.({
1298
1308
  code: "host_runtime_build_started",
1299
1309
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1300
- data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1310
+ data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath, output_directory: prebuild.outputDirectory },
1301
1311
  });
1302
1312
  let hostLoadWaitMs = null;
1303
1313
  const build = await ensureAspNetRuntimePrebuilt(prebuild,
@@ -1337,14 +1347,13 @@ export class HostRuntimeLeaseManager {
1337
1347
  }
1338
1348
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1339
1349
  command: configuredPort.launch.command,
1340
- args: configuredPort.launch.args,
1341
- cwd: workingDirectory,
1342
- environment: {
1343
- ...buildEnvironment,
1344
- },
1350
+ args: supervisedRuntimeLaunchArguments(configuredPort), cwd: workingDirectory,
1351
+ environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1345
1352
  }, launcher, signal);
1353
+ await this.auditRuntimeListeners(active, launcher, onProjectCheckpoint);
1346
1354
  }
1347
- 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);
1348
1357
  const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1349
1358
  const playwright = active.runtimeContract.contract.runtime.playwright;
1350
1359
  if (!playwright) {
@@ -1397,6 +1406,8 @@ export class HostRuntimeLeaseManager {
1397
1406
  }
1398
1407
  if (signal?.aborted)
1399
1408
  throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
1409
+ if (active.isolationViolation)
1410
+ throw active.isolationViolation;
1400
1411
  if (active.restartingConfiguredProject) {
1401
1412
  throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
1402
1413
  }
@@ -1439,7 +1450,13 @@ export class HostRuntimeLeaseManager {
1439
1450
  }
1440
1451
  await this.stopConfiguredProject(active, portNames);
1441
1452
  // Keeps whatever admission the attempt holds; see launchConfiguredProject.
1442
- 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
+ });
1443
1460
  if (active.releasing) {
1444
1461
  throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1445
1462
  }
@@ -1447,10 +1464,8 @@ export class HostRuntimeLeaseManager {
1447
1464
  }
1448
1465
  /** Stops configured project processes in reverse launch order and releases their ports. */
1449
1466
  async stopConfiguredProject(active, portNames) {
1450
- const launched = active.lease.resources.ports
1451
- .map(port => port.name)
1452
- .filter(name => portNames.includes(name))
1453
- .reverse();
1467
+ active.stopListenerMonitor?.();
1468
+ const launched = active.lease.resources.ports.map(port => port.name).filter(name => portNames.includes(name)).reverse();
1454
1469
  for (const name of launched) {
1455
1470
  if (active.releasing) {
1456
1471
  throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
@@ -1477,6 +1492,10 @@ export class HostRuntimeLeaseManager {
1477
1492
  return null;
1478
1493
  return new AttemptSupervisedProviderProcessRunner(active.processSupervisor, hostPortOwner(active.lease), this.listenerInspector, active.executionClass === "analysis_only", () => this.markCapacityReservationRunning(dispatchAttemptId, fencingToken));
1479
1494
  }
1495
+ isolationViolation(dispatchAttemptId, fencingToken) {
1496
+ const active = this.active.get(dispatchAttemptId);
1497
+ return active?.lease.fencingToken === fencingToken ? active.isolationViolation ?? null : null;
1498
+ }
1480
1499
  markCapacityReservationRunning(dispatchAttemptId, fencingToken) {
1481
1500
  const reservation = this.capacityReservations.get(dispatchAttemptId);
1482
1501
  if (reservation?.owner.fencingToken === fencingToken)
@@ -1488,29 +1507,53 @@ export class HostRuntimeLeaseManager {
1488
1507
  return null;
1489
1508
  return active.processSupervisor.providerMemoryTelemetry();
1490
1509
  }
1491
- async promoteVerifiedRuntime(active, runtimeLease) {
1492
- 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)
1493
1542
  return runtimeLease;
1494
1543
  const verifiedPortNames = runtimeLease.resources.ports.map(port => port.name).sort((left, right) => left.localeCompare(right));
1495
1544
  const requiredPortNames = configuredLaunchPortNames(active.runtimeContract);
1496
1545
  if (requiredPortNames.length !== verifiedPortNames.length
1497
- || requiredPortNames.some((name, index) => name !== verifiedPortNames[index])) {
1546
+ || requiredPortNames.some((name, index) => name !== verifiedPortNames[index]))
1498
1547
  return runtimeLease;
1499
- }
1500
1548
  const projectKey = projectHostRuntimeSingletonKey(active.repoId);
1501
- const promotedLease = withRuntimeIsolationResources(runtimeLease, {
1502
- ...runtimeLease.resources,
1503
- singletonKeys: runtimeLease.resources.singletonKeys.filter(key => key !== projectKey),
1504
- });
1549
+ const promotedLease = withRuntimeIsolationResources(runtimeLease, { ...runtimeLease.resources,
1550
+ singletonKeys: runtimeLease.resources.singletonKeys.filter(key => key !== projectKey) });
1505
1551
  await this.writeLedger(promotedLease);
1506
1552
  active.lease = promotedLease;
1507
1553
  try {
1508
- 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);
1509
1555
  this.knownPromotions.set(promotion.repoId, promotion);
1510
- const owner = {
1511
- dispatchAttemptId: runtimeLease.dispatchAttemptId,
1512
- fencingToken: runtimeLease.fencingToken,
1513
- };
1556
+ const owner = { dispatchAttemptId: runtimeLease.dispatchAttemptId, fencingToken: runtimeLease.fencingToken };
1514
1557
  if (!this.parallelProjectOwned(projectKey, owner)) {
1515
1558
  this.convertSingletonToParallelProject(projectKey, owner, promotion);
1516
1559
  }
@@ -1525,8 +1568,9 @@ export class HostRuntimeLeaseManager {
1525
1568
  }
1526
1569
  return promotedLease;
1527
1570
  }
1528
- catch {
1529
- 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);
1530
1574
  active.lease = runtimeLease;
1531
1575
  await this.writeLedger(runtimeLease);
1532
1576
  return runtimeLease;
@@ -1619,6 +1663,7 @@ export class HostRuntimeLeaseManager {
1619
1663
  if (active.lease.fencingToken !== fencingToken)
1620
1664
  return null;
1621
1665
  active.releasing = true;
1666
+ active.stopListenerMonitor?.();
1622
1667
  // Attempt teardown cancels the attempt's queued heavy steps and stops its running
1623
1668
  // ones. Each running step (an ASP.NET prebuild, an install, a validation step)
1624
1669
  // returns its own token only after its processes have exited, so the capacity is
@@ -1634,10 +1679,14 @@ export class HostRuntimeLeaseManager {
1634
1679
  await restart.promise.catch(() => undefined);
1635
1680
  }
1636
1681
  await active.databaseProvision?.catch(() => undefined);
1637
- let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1638
- active.lease = releasing;
1639
- await this.writeLedger(releasing);
1682
+ // The releasing write is part of the fenced teardown: when it fails (Windows can refuse
1683
+ // to replace a ledger another handle is reading), the lease must end degraded so
1684
+ // maintenance retries it, never left nonterminal in memory where nothing retries it.
1685
+ let releasing = active.lease;
1640
1686
  try {
1687
+ releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1688
+ active.lease = releasing;
1689
+ await this.writeLedger(releasing);
1641
1690
  if (!active.runtimeResourcesReleased) {
1642
1691
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1643
1692
  // The attempt's MCP servers and process trees are stopped now; tokens they held
@@ -1693,13 +1742,12 @@ export class HostRuntimeLeaseManager {
1693
1742
  if (!evidenceRetainedAtAttemptRoot) {
1694
1743
  await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1695
1744
  }
1696
- releasing = released;
1697
1745
  this.active.delete(dispatchAttemptId);
1698
1746
  this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1699
1747
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1700
1748
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1701
1749
  this.deleteAdmission(dispatchAttemptId, fencingToken);
1702
- return releasing;
1750
+ return released;
1703
1751
  }
1704
1752
  catch (error) {
1705
1753
  const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
@@ -1734,66 +1782,12 @@ export class HostRuntimeLeaseManager {
1734
1782
  }
1735
1783
  return ledgers;
1736
1784
  }
1737
- async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
1738
- const logsRoot = path.join(attemptRoot, "logs");
1739
- const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
1740
- if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
1741
- throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
1742
- }
1743
- await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
1744
- const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
1745
- const logsEntry = rootEntries.find(entry => entry.name === "logs");
1746
- if (!logsEntry)
1747
- return [];
1748
- if (logsEntry.kind !== "directory") {
1749
- throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1750
- }
1751
- const outcomes = [];
1752
- const failures = [];
1753
- try {
1754
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1755
- for (const entry of entries) {
1756
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1757
- continue;
1758
- const metadataPath = path.join(logsRoot, entry.name);
1759
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1760
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1761
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1762
- }
1763
- outcomes.push(await this.processRecovery.recover(value));
1764
- }
1765
- }
1766
- catch (error) {
1767
- failures.push(error);
1768
- }
1769
- // Managed commands run in their own process groups and record their ownership apart
1770
- // from the attempt's supervised children. They are recovered even when recovering a
1771
- // supervised child failed, and both failures are reported together.
1772
- try {
1773
- const managed = await terminateAttemptManagedCommands({
1774
- logDirectory: logsRoot,
1775
- dispatchAttemptId: lease.dispatchAttemptId,
1776
- runtimeLeaseId: lease.executionLeaseId,
1777
- pinnedLogDirectory: logsEntry.identity,
1778
- }, { reason: "attempt_teardown" });
1779
- for (const command of managed) {
1780
- if (command.outcome === "terminated" || command.outcome === "pid_reused")
1781
- outcomes.push(command.outcome);
1782
- }
1783
- }
1784
- catch (error) {
1785
- failures.push(error);
1786
- }
1787
- if (failures.length === 1)
1788
- throw failures[0];
1789
- if (failures.length > 1)
1790
- throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1791
- return outcomes;
1792
- }
1793
- async markLedgerDegraded(ledger) {
1785
+ /** Degrades and counts a ledger whose runtime may still be live. A retained released ledger owns no slot, so it is neither changed nor counted. */
1786
+ async markLedgerDegraded(ledger, report) {
1794
1787
  const lease = ledger.runtimeLease;
1795
1788
  if (lease.state === "released")
1796
1789
  return;
1790
+ report.degraded += 1;
1797
1791
  const degraded = transitionHostLeaseForCleanup(lease, "degraded");
1798
1792
  const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
1799
1793
  this.rememberDegraded(degraded, repoId);
@@ -1862,7 +1856,7 @@ export class HostRuntimeLeaseManager {
1862
1856
  finally {
1863
1857
  await handle.close();
1864
1858
  }
1865
- await fs.rename(temporary, target);
1859
+ await replaceHostRuntimeLedgerFile(temporary, target);
1866
1860
  }
1867
1861
  catch (error) {
1868
1862
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -2091,10 +2085,11 @@ export class HostRuntimeLeaseManager {
2091
2085
  for (const promotion of promotions)
2092
2086
  this.knownPromotions.set(promotion.repoId, promotion);
2093
2087
  }
2094
- async invalidatePromotion(repoId, scope = "all") {
2095
- await this.promotionStore.invalidate(repoId, scope);
2088
+ async invalidatePromotion(repoId, scope = "all", quarantineFingerprints) {
2096
2089
  this.knownPromotions.delete(repoId.trim().toLowerCase());
2090
+ await this.promotionStore.invalidate(repoId, scope, quarantineFingerprints);
2097
2091
  }
2092
+ promotionQuarantined(repoId, fingerprint) { return this.promotionStore.quarantined(repoId, fingerprint); }
2098
2093
  drainAdmissionWaiters() {
2099
2094
  this.reconcileReservationOwners();
2100
2095
  this.drainSingletonWaiters();
@@ -2144,95 +2139,6 @@ export class HostRuntimeLeaseManager {
2144
2139
  return this.reservationOwnerIsLive({ dispatchAttemptId, fencingToken });
2145
2140
  }
2146
2141
  }
2147
- class AttemptSupervisedProviderProcessRunner {
2148
- supervisor;
2149
- owner;
2150
- listenerInspector;
2151
- enforceNoListeners;
2152
- onProcessTreeStarted;
2153
- constructor(supervisor, owner, listenerInspector, enforceNoListeners, onProcessTreeStarted) {
2154
- this.supervisor = supervisor;
2155
- this.owner = owner;
2156
- this.listenerInspector = listenerInspector;
2157
- this.enforceNoListeners = enforceNoListeners;
2158
- this.onProcessTreeStarted = onProcessTreeStarted;
2159
- }
2160
- async run(request, handlers = {}, signal) {
2161
- const baselineListeners = this.enforceNoListeners
2162
- ? new Set(await this.listenerInspector.inspectLoopbackListeners())
2163
- : new Set();
2164
- const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
2165
- this.onProcessTreeStarted();
2166
- try {
2167
- return await this.awaitProviderResult(child, baselineListeners, signal);
2168
- }
2169
- finally {
2170
- // The provider tree, and the MCP server inside it, is gone. A managed command that
2171
- // server started now has no supervisor and no receipt writer, so it must not keep
2172
- // running into the next provider generation. This never rejects; a command it
2173
- // cannot prove stopped is left to attempt teardown, which fails closed.
2174
- await this.supervisor.stopOrphanedManagedCommands();
2175
- }
2176
- }
2177
- async awaitProviderResult(child, baselineListeners, signal) {
2178
- if (!this.enforceNoListeners)
2179
- return await child.result;
2180
- let settled = false;
2181
- let inspectionFailure;
2182
- const monitor = (async () => {
2183
- while (!settled) {
2184
- try {
2185
- const ports = (await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner))
2186
- .filter(port => !baselineListeners.has(port));
2187
- if (ports.length > 0) {
2188
- inspectionFailure = new Error(`host_analysis_listener_violation: analysis-only provider opened undeclared loopback listener(s): ${ports.join(", ")}.`);
2189
- await child.stop(this.owner.fencingToken).catch(() => undefined);
2190
- return;
2191
- }
2192
- }
2193
- catch (error) {
2194
- inspectionFailure = error;
2195
- await child.stop(this.owner.fencingToken).catch(() => undefined);
2196
- return;
2197
- }
2198
- await waitForAnalysisInspection(250, signal).catch(error => {
2199
- if (!settled && !signal?.aborted)
2200
- inspectionFailure = error;
2201
- });
2202
- }
2203
- })();
2204
- try {
2205
- const result = await child.result;
2206
- settled = true;
2207
- await monitor;
2208
- if (inspectionFailure)
2209
- throw inspectionFailure;
2210
- return result;
2211
- }
2212
- catch (error) {
2213
- settled = true;
2214
- await monitor.catch(() => undefined);
2215
- if (inspectionFailure)
2216
- throw inspectionFailure;
2217
- throw error;
2218
- }
2219
- }
2220
- }
2221
- function waitForAnalysisInspection(milliseconds, signal) {
2222
- if (signal?.aborted)
2223
- return Promise.reject(cancellationError(signal));
2224
- return new Promise((resolve, reject) => {
2225
- const timer = setTimeout(() => {
2226
- signal?.removeEventListener("abort", abort);
2227
- resolve();
2228
- }, milliseconds);
2229
- const abort = () => {
2230
- clearTimeout(timer);
2231
- reject(cancellationError(signal));
2232
- };
2233
- signal?.addEventListener("abort", abort, { once: true });
2234
- });
2235
- }
2236
2142
  export class HostRuntimeLeaseCleanupError extends Error {
2237
2143
  lease;
2238
2144
  constructor(lease, cause) {
@@ -2374,51 +2280,13 @@ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2374
2280
  }
2375
2281
  return [...keys];
2376
2282
  }
2283
+ /** The attempt's API master key: issued on first use, then the same for every relaunch of the attempt. */
2284
+ function attemptApiMasterKey(active) {
2285
+ return active.apiMasterKey ??= newAttemptApiMasterKey();
2286
+ }
2377
2287
  function anySignal(...signals) {
2378
2288
  return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2379
2289
  }
2380
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
2381
- /** Once the build's supervised tree is up: records it on the build's host load token. */
2382
- onStarted) {
2383
- const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2384
- const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2385
- const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2386
- let stdoutTail = "";
2387
- let stderrTail = "";
2388
- const append = async (target, line) => {
2389
- await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2390
- };
2391
- const child = await supervisor.startChildReady(childName, {
2392
- command: plan.command,
2393
- args: plan.args,
2394
- cwd: plan.cwd,
2395
- env: plan.environment,
2396
- captureOutput: false,
2397
- }, {
2398
- onStdoutLine: async (line) => {
2399
- stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2400
- await append(stdoutLogPath, line);
2401
- },
2402
- onStderrLine: async (line) => {
2403
- stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2404
- await append(stderrLogPath, line);
2405
- },
2406
- }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2407
- await onStarted?.(child.metadataPath);
2408
- const result = await child.result;
2409
- return {
2410
- exitCode: result.exitCode,
2411
- stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2412
- stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2413
- stdoutLogPath,
2414
- stderrLogPath,
2415
- };
2416
- }
2417
- function appendRuntimeBuildTail(current, value) {
2418
- if (!value)
2419
- return current;
2420
- return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
2421
- }
2422
2290
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
2423
2291
  if (executionClass === "analysis_only") {
2424
2292
  const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
@@ -2725,30 +2593,6 @@ function deserializeHostAttemptRootIdentity(identity) {
2725
2593
  ? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
2726
2594
  : null;
2727
2595
  }
2728
- function validHostProcessSupervisorMetadata(value, lease) {
2729
- if (typeof value !== "object" || value === null)
2730
- return false;
2731
- const metadata = value;
2732
- return metadata.schemaVersion === 1
2733
- && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
2734
- && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
2735
- && Number.isSafeInteger(metadata.rootPid)
2736
- && metadata.rootPid > 0
2737
- && Number.isFinite(Date.parse(metadata.rootCreatedAt))
2738
- && (metadata.rootIdentity == null
2739
- || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
2740
- && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
2741
- && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
2742
- && metadata.runtimeLeaseId === lease.executionLeaseId
2743
- && metadata.dispatchAttemptId === lease.dispatchAttemptId
2744
- && metadata.fencingToken === lease.fencingToken
2745
- && Number.isSafeInteger(metadata.bridgePid)
2746
- && metadata.bridgePid > 0;
2747
- }
2748
- function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
2749
- const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
2750
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2751
- }
2752
2596
  function transitionHostLeaseForCleanup(lease, state) {
2753
2597
  if (lease.state === state || lease.state === "released")
2754
2598
  return lease;