@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 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 (269) hide show
  1. package/README.md +146 -3
  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 +40 -0
  5. package/dist/bridge/bridge-chat-provider-command.js +230 -0
  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.base.d.ts +9 -0
  17. package/dist/bridge/bridge.service.d.ts +92 -14
  18. package/dist/bridge/bridge.service.js +446 -380
  19. package/dist/bridge/bridge.types.d.ts +21 -0
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +31 -1
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  33. package/dist/bridge/windows-bash-resolution.js +153 -0
  34. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  35. package/dist/cleanup/cleanup-wip.js +66 -0
  36. package/dist/cleanup/cleanup.service.d.ts +20 -1
  37. package/dist/cleanup/cleanup.service.js +150 -169
  38. package/dist/cleanup/cleanup.types.d.ts +6 -0
  39. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  40. package/dist/cleanup/forge-owned-paths.js +53 -0
  41. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  42. package/dist/cleanup/host-runtime-ledger.js +130 -0
  43. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  44. package/dist/cleanup/managed-branch-sweep.js +111 -0
  45. package/dist/cli/cli.help.js +74 -12
  46. package/dist/cli/cli.service.d.ts +19 -10
  47. package/dist/cli/cli.service.js +152 -187
  48. package/dist/cli/idle-status.d.ts +84 -0
  49. package/dist/cli/idle-status.js +181 -0
  50. package/dist/cli/local-config.d.ts +6 -0
  51. package/dist/cli/local-config.js +32 -4
  52. package/dist/cli/provider-cli-detection.d.ts +10 -0
  53. package/dist/cli/provider-cli-detection.js +160 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  55. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  56. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  57. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  58. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  59. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  60. package/dist/runtime/attempt-process-supervisor.js +12 -6
  61. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  62. package/dist/runtime/docker-engine-probe.js +7 -0
  63. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  64. package/dist/runtime/dotnet-build-outputs.js +402 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  66. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  67. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  68. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  69. package/dist/runtime/host-facts.d.ts +2 -1
  70. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  71. package/dist/runtime/host-listener-inspector.js +84 -3
  72. package/dist/runtime/host-load-admission.d.ts +72 -0
  73. package/dist/runtime/host-load-admission.js +99 -0
  74. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  75. package/dist/runtime/host-load-child-environment.js +76 -0
  76. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  77. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  78. package/dist/runtime/host-load-governor-config.d.ts +61 -0
  79. package/dist/runtime/host-load-governor-config.js +86 -0
  80. package/dist/runtime/host-load-governor.d.ts +193 -0
  81. package/dist/runtime/host-load-governor.js +662 -0
  82. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  83. package/dist/runtime/host-load-ledger-lock.js +187 -0
  84. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  85. package/dist/runtime/host-load-runtime-settings.js +80 -0
  86. package/dist/runtime/host-load-sampler.d.ts +75 -2
  87. package/dist/runtime/host-load-sampler.js +142 -8
  88. package/dist/runtime/host-load-step-class.d.ts +70 -0
  89. package/dist/runtime/host-load-step-class.js +161 -0
  90. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  91. package/dist/runtime/host-load-step-reaper.js +95 -0
  92. package/dist/runtime/host-load-step-run.d.ts +73 -0
  93. package/dist/runtime/host-load-step-run.js +102 -0
  94. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  95. package/dist/runtime/host-load-test-slot.js +88 -0
  96. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  97. package/dist/runtime/host-load-token-ledger.js +453 -0
  98. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  99. package/dist/runtime/host-load-windows-cpu.js +85 -0
  100. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  101. package/dist/runtime/host-pressure-stall.js +48 -1
  102. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  103. package/dist/runtime/host-runtime-contract.js +33 -2
  104. package/dist/runtime/host-runtime-lease.d.ts +101 -6
  105. package/dist/runtime/host-runtime-lease.js +408 -294
  106. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  107. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  108. package/dist/runtime/host-runtime-promotion.d.ts +101 -2
  109. package/dist/runtime/host-runtime-promotion.js +355 -14
  110. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  111. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  112. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  113. package/dist/runtime/host-runtime-requirements.js +117 -0
  114. package/dist/runtime/managed-command-teardown.js +5 -16
  115. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  116. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  117. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  119. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  120. package/dist/runtime/prepared-runtime-identity.js +130 -9
  121. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  122. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  123. package/dist/runtime/runner-settings.d.ts +104 -0
  124. package/dist/runtime/runner-settings.js +236 -0
  125. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  126. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  127. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  128. package/dist/sandbox/host-capacity-broker.js +336 -0
  129. package/dist/sandbox/managed-branch.d.ts +13 -0
  130. package/dist/sandbox/managed-branch.js +90 -0
  131. package/dist/sandbox/provider-auth/codex.js +11 -11
  132. package/dist/sandbox/runtime.d.ts +10 -1
  133. package/dist/sandbox/runtime.js +47 -8
  134. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  135. package/dist/sandbox/sandbox-cgroups.js +42 -0
  136. package/dist/session/architect-waits.d.ts +2 -0
  137. package/dist/session/architect-waits.js +138 -0
  138. package/dist/session/managed-attempt-tools.d.ts +2 -7
  139. package/dist/session/managed-attempt-tools.js +207 -121
  140. package/dist/session/managed-build-coordinator.d.ts +16 -0
  141. package/dist/session/managed-build-coordinator.js +10 -0
  142. package/dist/session/managed-build-receipt.d.ts +5 -0
  143. package/dist/session/managed-build-receipt.js +8 -3
  144. package/dist/session/managed-command-host-load.d.ts +47 -0
  145. package/dist/session/managed-command-host-load.js +83 -0
  146. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  147. package/dist/session/mcp-argument-coercion.js +121 -0
  148. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  149. package/dist/session/phase-completion.artifacts.js +96 -26
  150. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  151. package/dist/session/phase-completion.command-validation.js +77 -0
  152. package/dist/session/phase-completion.d.ts +12 -0
  153. package/dist/session/phase-completion.helpers.js +13 -12
  154. package/dist/session/phase-completion.js +5 -0
  155. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  156. package/dist/session/phase-completion.mcp-args.js +156 -0
  157. package/dist/session/phase-completion.prompts.js +6 -1
  158. package/dist/session/phase-completion.runtime.d.ts +5 -11
  159. package/dist/session/phase-completion.runtime.js +91 -215
  160. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  161. package/dist/session/phase-completion.schema-parts.js +188 -0
  162. package/dist/session/phase-completion.schemas.d.ts +3 -3
  163. package/dist/session/phase-completion.schemas.js +208 -231
  164. package/dist/session/phase-completion.validation.d.ts +2 -3
  165. package/dist/session/phase-completion.validation.js +49 -93
  166. package/dist/session/pre-publication-host-load.d.ts +27 -0
  167. package/dist/session/pre-publication-host-load.js +111 -0
  168. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  169. package/dist/session/pre-publication-native-postgres.js +111 -0
  170. package/dist/session/pre-publication-pass.d.ts +61 -0
  171. package/dist/session/pre-publication-pass.js +148 -0
  172. package/dist/session/pre-publication-process.d.ts +3 -0
  173. package/dist/session/pre-publication-process.js +31 -19
  174. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  175. package/dist/session/pre-publication-step-execution.js +50 -0
  176. package/dist/session/pre-publication-validation.d.ts +37 -21
  177. package/dist/session/pre-publication-validation.js +221 -182
  178. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  179. package/dist/session/provider-cli/claude-background-work.js +181 -0
  180. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  181. package/dist/session/provider-cli/host-build-lock.js +30 -0
  182. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  183. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  184. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  185. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  186. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  188. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  190. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  191. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  192. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  193. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  196. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  197. package/dist/session/provider-cli/provider-cli.service.js +98 -173
  198. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  199. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  205. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  206. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  207. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  208. package/dist/session/provider-cli/provider-output-state.js +6 -0
  209. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  210. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  211. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  212. package/dist/session/qa-sidecar-validation.js +28 -0
  213. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  214. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  215. package/dist/session/session-redaction.js +31 -181
  216. package/dist/session/session.base.d.ts +9 -1
  217. package/dist/session/session.service.d.ts +15 -2
  218. package/dist/session/session.service.js +246 -88
  219. package/dist/session/session.types.d.ts +4 -0
  220. package/dist/session/session.types.js +7 -7
  221. package/dist/session/sidecar-json-shape.d.ts +31 -0
  222. package/dist/session/sidecar-json-shape.js +217 -0
  223. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  224. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  225. package/dist/shared/fs/file-identity.d.ts +10 -0
  226. package/dist/shared/fs/file-identity.js +15 -0
  227. package/dist/shared/fs/replace-file.d.ts +7 -0
  228. package/dist/shared/fs/replace-file.js +33 -0
  229. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  230. package/dist/shared/process/host-process-recovery.js +23 -3
  231. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  232. package/dist/shared/process/host-process-supervisor.js +67 -15
  233. package/dist/shared/process/process-tree.d.ts +52 -0
  234. package/dist/shared/process/process-tree.js +144 -0
  235. package/dist/shared/process/process.d.ts +67 -0
  236. package/dist/shared/process/process.js +213 -11
  237. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  238. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  239. package/dist/shared/process/windows-launch.d.ts +18 -0
  240. package/dist/shared/process/windows-launch.js +68 -0
  241. package/dist/shared/provider-capabilities.js +14 -7
  242. package/dist/version.d.ts +1 -1
  243. package/dist/version.js +1 -1
  244. package/dist/worktree/dependency-warmer.d.ts +25 -0
  245. package/dist/worktree/dependency-warmer.js +46 -10
  246. package/dist/worktree/orphan-relink.d.ts +19 -0
  247. package/dist/worktree/orphan-relink.js +106 -0
  248. package/dist/worktree/wip-git.d.ts +42 -0
  249. package/dist/worktree/wip-git.js +139 -0
  250. package/dist/worktree/wip-refs.d.ts +77 -0
  251. package/dist/worktree/wip-refs.js +146 -0
  252. package/dist/worktree/wip-restore.d.ts +46 -0
  253. package/dist/worktree/wip-restore.js +280 -0
  254. package/dist/worktree/wip-snapshot.d.ts +53 -0
  255. package/dist/worktree/wip-snapshot.js +270 -0
  256. package/dist/worktree/worktree-inputs.d.ts +8 -0
  257. package/dist/worktree/worktree-inputs.js +134 -0
  258. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  259. package/dist/worktree/worktree-origin-sync.js +128 -0
  260. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  261. package/dist/worktree/worktree-wip-events.js +115 -0
  262. package/dist/worktree/worktree-wip.d.ts +51 -0
  263. package/dist/worktree/worktree-wip.js +190 -0
  264. package/dist/worktree/worktree.base.d.ts +7 -1
  265. package/dist/worktree/worktree.service.d.ts +36 -5
  266. package/dist/worktree/worktree.service.js +126 -155
  267. package/dist/worktree/worktree.types.d.ts +42 -0
  268. package/package.json +2 -2
  269. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -7,31 +7,33 @@ import { assertHostAttemptRootIdentity, retainHostDiagnostics } from "./host-dia
7
7
  import { assertHostExecutionRoot, compactHostAttemptId } from "./host-execution-root.js";
8
8
  import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
9
9
  import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
+ import { ForgeFailureError } from "../session/session.types.js";
10
11
  import { resolveExistingDirectoryPath } from "../shared/path/path.js";
11
12
  import { formatBytes } from "../shared/format/format-bytes.js";
12
- import { redactText } from "../shared/redaction/redaction.js";
13
13
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
14
14
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
15
- import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
15
+ import { hostPortEnvironment, loadHostRuntimeContract, newAttemptApiMasterKey, withAttemptApiMasterKey, } from "./host-runtime-contract.js";
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";
20
19
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
21
- import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
20
+ import { AttemptNodeRuntimeLauncher, AttemptSupervisedProviderProcessRunner, brokeredHostPorts, isolationViolationError } from "./attempt-node-runtime-launcher.js";
22
21
  import { HostListenerInspector } from "./host-listener-inspector.js";
23
22
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
24
23
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
25
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
24
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostParallelPromotionMatches, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
26
25
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
27
26
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
28
27
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
29
- import { readCanonicalSourceFile } from "./canonical-source-file.js";
30
- import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
28
+ import { logHostRuntimeStatus, recoverPersistedHostProcesses, replaceHostRuntimeLedgerFile, retryDegradedHostRelease, } from "./host-runtime-ledger-recovery.js";
31
29
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
32
- import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
30
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, executeAspNetRuntimeBuild, resolveWorktreeCommitSha, supervisedRuntimeLaunchArguments, } from "./aspnet-runtime-prebuild.js";
31
+ import { HostLoadGovernor } from "./host-load-governor.js";
32
+ import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
33
+ import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
34
+ import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
35
+ import { HostLoadSampler } from "./host-load-sampler.js";
33
36
  const hostCapacityWaiterScanLimit = 64;
34
- const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
35
37
  export class HostRuntimeLeaseManager {
36
38
  stateRoot;
37
39
  processSupervisors;
@@ -61,10 +63,18 @@ export class HostRuntimeLeaseManager {
61
63
  workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
62
64
  portBroker;
63
65
  nodeAdapter;
66
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
64
67
  capacityConfiguration;
65
68
  memoryAvailability;
66
69
  executionRoot;
67
- constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null) {
70
+ /** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
71
+ hostLoadGovernor;
72
+ requirementsCheck = null;
73
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
74
+ setRequirementsCheck(check) {
75
+ this.requirementsCheck = check;
76
+ }
77
+ constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null, hostLoad = null) {
68
78
  this.stateRoot = stateRoot;
69
79
  this.processSupervisors = processSupervisors;
70
80
  this.processRunner = processRunner;
@@ -74,6 +84,7 @@ export class HostRuntimeLeaseManager {
74
84
  this.processRecovery = processRecovery;
75
85
  this.capacityResourceSample = capacityResourceSample;
76
86
  this.databaseBroker = databaseBroker;
87
+ this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
77
88
  this.executionRoot = path.resolve(executionRoot ?? stateRoot);
78
89
  if (executionRoot !== undefined)
79
90
  assertHostExecutionRoot(this.executionRoot);
@@ -83,7 +94,40 @@ export class HostRuntimeLeaseManager {
83
94
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
84
95
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
85
96
  }
97
+ /** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
98
+ capacityLimitDefaults() {
99
+ return {
100
+ maxConcurrentAttempts: this.capacityConfiguration.defaultHardMaxAttempts,
101
+ memoryReserveBytes: this.capacityConfiguration.adaptiveHostReserveBytes,
102
+ };
103
+ }
104
+ /**
105
+ * Decision 0014: the bridge's effective max attempts and memory reserve. They
106
+ * apply from the next attempt admission; admitted attempts keep their
107
+ * reservations and are never preempted, even when the new limit is lower than
108
+ * what already runs. The idle reserve follows the reserve as at startup.
109
+ */
110
+ applyCapacityLimits(limits) {
111
+ const current = this.capacityConfiguration;
112
+ const hardMaxAttempts = Math.max(1, Math.min(32, Math.floor(limits.maxConcurrentAttempts)));
113
+ const hostReserveBytes = Math.max(512 * 1024 ** 2, Math.floor(limits.memoryReserveBytes));
114
+ if (hardMaxAttempts === current.hardMaxAttempts && hostReserveBytes === current.hostReserveBytes)
115
+ return;
116
+ this.capacityConfiguration = {
117
+ ...current,
118
+ hardMaxAttempts,
119
+ hostReserveBytes,
120
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, current),
121
+ };
122
+ // A raised limit may admit queued attempts now rather than at their next recheck.
123
+ this.drainAdmissionWaiters();
124
+ }
125
+ hostLoadChildEnvironment() {
126
+ return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
127
+ }
86
128
  async reap(options) {
129
+ // Heavy-step tokens whose owner died or whose lease lapsed are returned first.
130
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
87
131
  await this.refreshKnownPromotions();
88
132
  const recoveredAttempts = [];
89
133
  const report = {
@@ -115,19 +159,16 @@ export class HostRuntimeLeaseManager {
115
159
  }
116
160
  const active = this.active.get(lease.dispatchAttemptId);
117
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.
118
164
  if (active.lease.state !== "degraded")
119
165
  continue;
120
166
  report.examined += 1;
121
- try {
122
- const released = await this.release(lease.dispatchAttemptId, lease.fencingToken);
123
- if (released?.state === "released")
124
- report.reaped += 1;
125
- else
126
- report.degraded += 1;
127
- }
128
- 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
129
171
  report.degraded += 1;
130
- }
131
172
  continue;
132
173
  }
133
174
  const staleInstance = lease.runnerInstanceId !== options.runnerInstanceId;
@@ -142,18 +183,16 @@ export class HostRuntimeLeaseManager {
142
183
  if (!attemptRootIdentity) {
143
184
  throw new Error("host_runtime_reaper_invalid: original attempt-root identity is unavailable.");
144
185
  }
145
- outcomes = await this.recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity);
186
+ outcomes = await recoverPersistedHostProcesses(lease, attemptRoot, this.attemptRoot(lease.dispatchAttemptId), attemptRootIdentity, this.processRecovery);
146
187
  }
147
188
  catch {
148
- await this.markLedgerDegraded(ledger);
149
- report.degraded += 1;
189
+ await this.markLedgerDegraded(ledger, report);
150
190
  continue;
151
191
  }
152
192
  report.processesTerminated += outcomes.filter(outcome => outcome === "terminated").length;
153
193
  report.reusedPidsProtected += outcomes.filter(outcome => outcome === "pid_reused").length;
154
194
  if (outcomes.includes("unverifiable")) {
155
- await this.markLedgerDegraded(ledger);
156
- report.degraded += 1;
195
+ await this.markLedgerDegraded(ledger, report);
157
196
  continue;
158
197
  }
159
198
  // The runtime has already been released. Keep the over-budget original
@@ -200,14 +239,18 @@ export class HostRuntimeLeaseManager {
200
239
  report.reaped += 1;
201
240
  }
202
241
  catch {
203
- await this.markLedgerDegraded(ledger);
204
- report.degraded += 1;
242
+ await this.markLedgerDegraded(ledger, report);
205
243
  }
206
244
  }
207
245
  // Databases issued to attempts that ended without a clean release (a Bridge crash, or a
208
246
  // drop that met a lingering session) are removed once no live lease holds them.
209
247
  // A degraded lease may still own running processes after a restart, so its database is kept.
210
248
  await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
249
+ // Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
250
+ // ended with a crashed bridge or MCP server) are returned once no live lease holds
251
+ // their attempt; a degraded lease may still own the running step, so its tokens stay.
252
+ await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
253
+ || (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
211
254
  return report;
212
255
  }
213
256
  snapshot() {
@@ -364,9 +407,7 @@ export class HostRuntimeLeaseManager {
364
407
  const projectKey = executionClass === "analysis_only"
365
408
  ? projectHostAnalysisKey(dispatch.repo.id)
366
409
  : projectHostRuntimeSingletonKey(dispatch.repo.id);
367
- const useParallelAdmission = priority === "foreground"
368
- && dispatch.cycleRun.phase !== "prepared_readiness"
369
- && (promotion !== null || executionClass === "analysis_only");
410
+ const useParallelAdmission = this.sharedAdmissionRequested(dispatch, owner, executionClass, priority, promotion);
370
411
  let keys = useParallelAdmission ? [] : [projectKey];
371
412
  const resources = normalizedHostResourceRequest(sandbox.requestedResources);
372
413
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
@@ -421,6 +462,35 @@ export class HostRuntimeLeaseManager {
421
462
  this.acquiringAdmissions.delete(acquisitionKey);
422
463
  }
423
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
+ }
424
494
  async reserveHostCapacity(owner, resources, expiresAt, signal, priority = "foreground") {
425
495
  const existing = this.capacityReservations.get(owner.dispatchAttemptId);
426
496
  if (existing) {
@@ -925,6 +995,15 @@ export class HostRuntimeLeaseManager {
925
995
  let attemptRootIdentity = null;
926
996
  try {
927
997
  const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
998
+ // Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
999
+ // API learns the requirements in the first place.
1000
+ const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
1001
+ ? []
1002
+ : this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
1003
+ if (unmetRequirements.length > 0) {
1004
+ // Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
1005
+ throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
1006
+ }
928
1007
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
929
1008
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
930
1009
  }
@@ -939,13 +1018,9 @@ export class HostRuntimeLeaseManager {
939
1018
  || JSON.stringify(preparedProof) !== JSON.stringify(await preparedRuntimeIdentity(normalizedWorktreePath, signal)))) {
940
1019
  throw new Error("host_runtime_prepared_source_changed: source changed after its foreground proof; agent was not started.");
941
1020
  }
942
- const promotion = admission.executionClass === "managed_runtime"
943
- ? await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha })
944
- : null;
945
- const promotionMatches = hostRuntimeParallelEligible(runtimeContract)
946
- && promotion?.runtimeContractFingerprint === runtimeContractFingerprint
947
- && promotion.inputCommitSha === inputCommitSha;
948
- 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)) {
949
1024
  const projectKeys = hostRuntimeSingletonKeys(dispatch);
950
1025
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
951
1026
  ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
@@ -1083,12 +1158,14 @@ export class HostRuntimeLeaseManager {
1083
1158
  attemptRoot,
1084
1159
  attemptRootIdentity,
1085
1160
  runtimeContract,
1086
- runtimeContractFingerprint,
1161
+ runtimeContractFingerprint, admittedContractFingerprint: runtimeContractFingerprint,
1087
1162
  inputCommitSha,
1088
1163
  executionClass: admission.executionClass,
1089
- parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1164
+ parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness", admittedRevocationGeneration,
1090
1165
  processSupervisor,
1091
1166
  adapterCleanups: [],
1167
+ adapterCleanupsByPort: new Map(),
1168
+ restartingConfiguredProject: false,
1092
1169
  pendingAdapterLaunches: new Map(),
1093
1170
  runtimeResourcesReleased: false,
1094
1171
  releasing: false,
@@ -1151,20 +1228,24 @@ export class HostRuntimeLeaseManager {
1151
1228
  await this.writeLedger(renewed);
1152
1229
  }
1153
1230
  async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1231
+ const violation = this.isolationViolation(dispatchAttemptId, fencingToken);
1232
+ if (violation)
1233
+ throw violation;
1234
+ return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
1235
+ }
1236
+ /**
1237
+ * Launches the configured project. Only the first launch, from the admitted commit's clean
1238
+ * source, may record parallel-safety proof: a restart serves the workspace after the provider
1239
+ * edited it, and a proof observed there would be stored under the admitted commit and could
1240
+ * move this or a later attempt at that commit into shared admission for source it never ran.
1241
+ */
1242
+ async launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, promote) {
1154
1243
  const active = this.active.get(dispatchAttemptId);
1155
1244
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1156
1245
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1157
1246
  }
1158
- if (active.executionClass === "analysis_only") {
1159
- return {
1160
- lease: active.lease,
1161
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1162
- runtimeContract: active.runtimeContract,
1163
- executionClass: active.executionClass,
1164
- };
1165
- }
1166
1247
  const configuredPorts = active.runtimeContract.contract.runtime.ports.filter((port) => port.launch !== null);
1167
- if (configuredPorts.length === 0) {
1248
+ if (active.executionClass === "analysis_only" || configuredPorts.length === 0) {
1168
1249
  return {
1169
1250
  lease: active.lease,
1170
1251
  environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
@@ -1202,9 +1283,11 @@ export class HostRuntimeLeaseManager {
1202
1283
  data: { database: active.databaseCapability.databaseName },
1203
1284
  });
1204
1285
  }
1205
- // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1206
- 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];
1207
1289
  const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1290
+ active.runtimeLauncher = launcher;
1208
1291
  for (const configuredPort of configuredPorts) {
1209
1292
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
1210
1293
  const buildEnvironment = {
@@ -1213,7 +1296,7 @@ export class HostRuntimeLeaseManager {
1213
1296
  };
1214
1297
  const prebuild = createAspNetRuntimePrebuildPlan({
1215
1298
  command: configuredPort.launch.command,
1216
- args: configuredPort.launch.args,
1299
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1217
1300
  cwd: workingDirectory,
1218
1301
  worktreePath: active.lease.worktreePath,
1219
1302
  environment: buildEnvironment,
@@ -1224,9 +1307,31 @@ export class HostRuntimeLeaseManager {
1224
1307
  await onProjectCheckpoint?.({
1225
1308
  code: "host_runtime_build_started",
1226
1309
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1227
- 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 },
1228
1311
  });
1229
- const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal, capabilitySecrets), signal);
1312
+ let hostLoadWaitMs = null;
1313
+ const build = await ensureAspNetRuntimePrebuilt(prebuild,
1314
+ // Only a real build (not a verified cache hit) takes a host load token.
1315
+ async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
1316
+ classification: aspNetPrebuildStepClass,
1317
+ label: prebuild.projectPath,
1318
+ dispatchAttemptId,
1319
+ priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
1320
+ signal: buildSignal,
1321
+ onWaiting: async (decision) => await onProjectCheckpoint?.({
1322
+ code: "host_runtime_build_waiting_for_host_capacity",
1323
+ message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
1324
+ data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
1325
+ }),
1326
+ }, async (waitMs, control) => {
1327
+ hostLoadWaitMs = waitMs;
1328
+ // A reclaimed token stops the build: its capacity is no longer reserved. So does a
1329
+ // build whose process tree cannot be recorded on its token (a reclaim could not stop it).
1330
+ const unrecorded = new AbortController();
1331
+ const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
1332
+ return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
1333
+ .catch((error) => { unrecorded.abort(error); }));
1334
+ }), signal);
1230
1335
  await onProjectCheckpoint?.({
1231
1336
  code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1232
1337
  message: build.cacheHit
@@ -1236,19 +1341,19 @@ export class HostRuntimeLeaseManager {
1236
1341
  input_commit_sha: active.inputCommitSha,
1237
1342
  build_fingerprint: build.fingerprint,
1238
1343
  receipt_path: build.receiptPath,
1344
+ ...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
1239
1345
  },
1240
1346
  });
1241
1347
  }
1242
1348
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1243
1349
  command: configuredPort.launch.command,
1244
- args: configuredPort.launch.args,
1245
- cwd: workingDirectory,
1246
- environment: {
1247
- ...buildEnvironment,
1248
- },
1350
+ args: supervisedRuntimeLaunchArguments(configuredPort), cwd: workingDirectory,
1351
+ environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1249
1352
  }, launcher, signal);
1353
+ await this.auditRuntimeListeners(active, launcher, onProjectCheckpoint);
1250
1354
  }
1251
- const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1355
+ const promotedLease = await this.promoteVerifiedRuntime(active, active.lease, promote);
1356
+ this.monitorSharedRuntimeListeners(active, launcher);
1252
1357
  const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1253
1358
  const playwright = active.runtimeContract.contract.runtime.playwright;
1254
1359
  if (!playwright) {
@@ -1287,12 +1392,110 @@ export class HostRuntimeLeaseManager {
1287
1392
  executionClass: active.executionClass,
1288
1393
  };
1289
1394
  }
1395
+ /**
1396
+ * Relaunches the configured project so it serves the current workspace. Every
1397
+ * configured process stops (the API port changes, so the dev server's proxy target
1398
+ * must change with it), its port reservation is released and dropped from the
1399
+ * persisted lease, and the regular start path runs again, including the ASP.NET
1400
+ * prebuild, whose receipt rebuilds only when the sources changed.
1401
+ */
1402
+ async restartConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1403
+ const active = this.active.get(dispatchAttemptId);
1404
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1405
+ throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1406
+ }
1407
+ if (signal?.aborted)
1408
+ throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
1409
+ if (active.isolationViolation)
1410
+ throw active.isolationViolation;
1411
+ if (active.restartingConfiguredProject) {
1412
+ throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
1413
+ }
1414
+ active.restartingConfiguredProject = true;
1415
+ // Release cancels the whole restart through this controller and waits for it to settle.
1416
+ const controller = linkedAbortController(signal);
1417
+ const promise = this.runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, controller.signal, onProjectCheckpoint);
1418
+ const restart = { controller, promise };
1419
+ active.configuredProjectRestart = restart;
1420
+ try {
1421
+ return await promise;
1422
+ }
1423
+ finally {
1424
+ // The controller is not aborted on settle: adapters this restart launched keep it as their
1425
+ // parent signal for as long as they run, exactly as they would keep the caller's signal.
1426
+ if (active.configuredProjectRestart === restart)
1427
+ active.configuredProjectRestart = null;
1428
+ active.restartingConfiguredProject = false;
1429
+ }
1430
+ }
1431
+ async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1432
+ // The relaunch keeps the admission granted at start. A workspace contract that changed only its
1433
+ // launch environment is adopted; any other change throws host_runtime_contract_changed.
1434
+ const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
1435
+ active.runtimeContract = readmitted.runtimeContract;
1436
+ active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
1437
+ if (readmitted.changed) {
1438
+ await onProjectCheckpoint?.({ code: "host_runtime_contract_readmitted", message: "The workspace's runtime contract changed only its launch environment; the restart runs it under the admission granted at start." });
1439
+ }
1440
+ const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1441
+ const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
1442
+ if (pendingPort) {
1443
+ throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
1444
+ }
1445
+ const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
1446
+ if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
1447
+ // The generated Playwright config targets the stack being stopped. If the restart fails, no
1448
+ // config may be left pointing at ports another attempt can now be assigned.
1449
+ await this.playwrightAdapter.discardOverlay(temporaryDirectory);
1450
+ }
1451
+ await this.stopConfiguredProject(active, portNames);
1452
+ // Keeps whatever admission the attempt holds; see launchConfiguredProject.
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
+ });
1460
+ if (active.releasing) {
1461
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1462
+ }
1463
+ return restarted;
1464
+ }
1465
+ /** Stops configured project processes in reverse launch order and releases their ports. */
1466
+ async stopConfiguredProject(active, portNames) {
1467
+ active.stopListenerMonitor?.();
1468
+ const launched = active.lease.resources.ports.map(port => port.name).filter(name => portNames.includes(name)).reverse();
1469
+ for (const name of launched) {
1470
+ if (active.releasing) {
1471
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1472
+ }
1473
+ const cleanup = active.adapterCleanupsByPort.get(name);
1474
+ if (!cleanup) {
1475
+ throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
1476
+ }
1477
+ // A failed stop keeps the cleanup and the port record for the fenced release retry.
1478
+ await cleanup();
1479
+ removeCleanup(active.adapterCleanups, cleanup);
1480
+ active.adapterCleanupsByPort.delete(name);
1481
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1482
+ ...active.lease.resources,
1483
+ ports: active.lease.resources.ports.filter(port => port.name !== name),
1484
+ });
1485
+ await this.writeLedger(runtimeLease);
1486
+ active.lease = runtimeLease;
1487
+ }
1488
+ }
1290
1489
  providerProcessRunner(dispatchAttemptId, fencingToken) {
1291
1490
  const active = this.active.get(dispatchAttemptId);
1292
1491
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
1293
1492
  return null;
1294
1493
  return new AttemptSupervisedProviderProcessRunner(active.processSupervisor, hostPortOwner(active.lease), this.listenerInspector, active.executionClass === "analysis_only", () => this.markCapacityReservationRunning(dispatchAttemptId, fencingToken));
1295
1494
  }
1495
+ isolationViolation(dispatchAttemptId, fencingToken) {
1496
+ const active = this.active.get(dispatchAttemptId);
1497
+ return active?.lease.fencingToken === fencingToken ? active.isolationViolation ?? null : null;
1498
+ }
1296
1499
  markCapacityReservationRunning(dispatchAttemptId, fencingToken) {
1297
1500
  const reservation = this.capacityReservations.get(dispatchAttemptId);
1298
1501
  if (reservation?.owner.fencingToken === fencingToken)
@@ -1304,29 +1507,53 @@ export class HostRuntimeLeaseManager {
1304
1507
  return null;
1305
1508
  return active.processSupervisor.providerMemoryTelemetry();
1306
1509
  }
1307
- async promoteVerifiedRuntime(active, runtimeLease) {
1308
- 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)
1309
1542
  return runtimeLease;
1310
1543
  const verifiedPortNames = runtimeLease.resources.ports.map(port => port.name).sort((left, right) => left.localeCompare(right));
1311
1544
  const requiredPortNames = configuredLaunchPortNames(active.runtimeContract);
1312
1545
  if (requiredPortNames.length !== verifiedPortNames.length
1313
- || requiredPortNames.some((name, index) => name !== verifiedPortNames[index])) {
1546
+ || requiredPortNames.some((name, index) => name !== verifiedPortNames[index]))
1314
1547
  return runtimeLease;
1315
- }
1316
1548
  const projectKey = projectHostRuntimeSingletonKey(active.repoId);
1317
- const promotedLease = withRuntimeIsolationResources(runtimeLease, {
1318
- ...runtimeLease.resources,
1319
- singletonKeys: runtimeLease.resources.singletonKeys.filter(key => key !== projectKey),
1320
- });
1549
+ const promotedLease = withRuntimeIsolationResources(runtimeLease, { ...runtimeLease.resources,
1550
+ singletonKeys: runtimeLease.resources.singletonKeys.filter(key => key !== projectKey) });
1321
1551
  await this.writeLedger(promotedLease);
1322
1552
  active.lease = promotedLease;
1323
1553
  try {
1324
- 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);
1325
1555
  this.knownPromotions.set(promotion.repoId, promotion);
1326
- const owner = {
1327
- dispatchAttemptId: runtimeLease.dispatchAttemptId,
1328
- fencingToken: runtimeLease.fencingToken,
1329
- };
1556
+ const owner = { dispatchAttemptId: runtimeLease.dispatchAttemptId, fencingToken: runtimeLease.fencingToken };
1330
1557
  if (!this.parallelProjectOwned(projectKey, owner)) {
1331
1558
  this.convertSingletonToParallelProject(projectKey, owner, promotion);
1332
1559
  }
@@ -1341,8 +1568,9 @@ export class HostRuntimeLeaseManager {
1341
1568
  }
1342
1569
  return promotedLease;
1343
1570
  }
1344
- catch {
1345
- 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);
1346
1574
  active.lease = runtimeLease;
1347
1575
  await this.writeLedger(runtimeLease);
1348
1576
  return runtimeLease;
@@ -1374,6 +1602,7 @@ export class HostRuntimeLeaseManager {
1374
1602
  unlinkAbortController(controller, signal);
1375
1603
  };
1376
1604
  active.adapterCleanups.push(cleanup);
1605
+ active.adapterCleanupsByPort.set(portName, cleanup);
1377
1606
  try {
1378
1607
  if (active.releasing)
1379
1608
  throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
@@ -1396,6 +1625,8 @@ export class HostRuntimeLeaseManager {
1396
1625
  try {
1397
1626
  await cleanup();
1398
1627
  removeCleanup(active.adapterCleanups, cleanup);
1628
+ if (active.adapterCleanupsByPort.get(portName) === cleanup)
1629
+ active.adapterCleanupsByPort.delete(portName);
1399
1630
  }
1400
1631
  catch {
1401
1632
  // Preserve the cleanup and broker claim for the fenced release retry.
@@ -1420,6 +1651,9 @@ export class HostRuntimeLeaseManager {
1420
1651
  if (!preservePreparation)
1421
1652
  this.pendingRenewals.delete(dispatchAttemptId);
1422
1653
  if (!active) {
1654
+ // Queued steps are cancelled and running ones stopped; each returns its own
1655
+ // token once its processes are gone (never before, or capacity is reused early).
1656
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1423
1657
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1424
1658
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1425
1659
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
@@ -1429,18 +1663,43 @@ export class HostRuntimeLeaseManager {
1429
1663
  if (active.lease.fencingToken !== fencingToken)
1430
1664
  return null;
1431
1665
  active.releasing = true;
1666
+ active.stopListenerMonitor?.();
1667
+ // Attempt teardown cancels the attempt's queued heavy steps and stops its running
1668
+ // ones. Each running step (an ASP.NET prebuild, an install, a validation step)
1669
+ // returns its own token only after its processes have exited, so the capacity is
1670
+ // not reused while, say, a build is still being terminated.
1671
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1432
1672
  for (const pending of active.pendingAdapterLaunches.values()) {
1433
1673
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1434
1674
  }
1435
1675
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1676
+ const restart = active.configuredProjectRestart;
1677
+ if (restart) {
1678
+ restart.controller.abort("Host runtime release cancelled the configured project restart.");
1679
+ await restart.promise.catch(() => undefined);
1680
+ }
1436
1681
  await active.databaseProvision?.catch(() => undefined);
1437
- let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1438
- active.lease = releasing;
1439
- 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;
1440
1686
  try {
1687
+ releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1688
+ active.lease = releasing;
1689
+ await this.writeLedger(releasing);
1441
1690
  if (!active.runtimeResourcesReleased) {
1442
1691
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1692
+ // The attempt's MCP servers and process trees are stopped now; tokens they held
1693
+ // belong to dead owners and go back to the host budget at once, including any
1694
+ // without a recorded process tree (their steps were inside the stopped trees).
1695
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
1696
+ await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
1697
+ .catch(() => undefined);
1698
+ // This bridge's own steps whose trees only stopAll could prove gone (a supervised
1699
+ // validation step whose termination failed earlier) return their tokens now.
1700
+ await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1443
1701
  await releaseAdapterResources(active.adapterCleanups);
1702
+ active.adapterCleanupsByPort.clear();
1444
1703
  if (active.databaseCapability && this.databaseBroker) {
1445
1704
  // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1446
1705
  await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
@@ -1483,13 +1742,12 @@ export class HostRuntimeLeaseManager {
1483
1742
  if (!evidenceRetainedAtAttemptRoot) {
1484
1743
  await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1485
1744
  }
1486
- releasing = released;
1487
1745
  this.active.delete(dispatchAttemptId);
1488
1746
  this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1489
1747
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1490
1748
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1491
1749
  this.deleteAdmission(dispatchAttemptId, fencingToken);
1492
- return releasing;
1750
+ return released;
1493
1751
  }
1494
1752
  catch (error) {
1495
1753
  const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
@@ -1524,66 +1782,12 @@ export class HostRuntimeLeaseManager {
1524
1782
  }
1525
1783
  return ledgers;
1526
1784
  }
1527
- async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
1528
- const logsRoot = path.join(attemptRoot, "logs");
1529
- const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
1530
- if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
1531
- throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
1532
- }
1533
- await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
1534
- const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
1535
- const logsEntry = rootEntries.find(entry => entry.name === "logs");
1536
- if (!logsEntry)
1537
- return [];
1538
- if (logsEntry.kind !== "directory") {
1539
- throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1540
- }
1541
- const outcomes = [];
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);
1572
- }
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");
1581
- return outcomes;
1582
- }
1583
- 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) {
1584
1787
  const lease = ledger.runtimeLease;
1585
1788
  if (lease.state === "released")
1586
1789
  return;
1790
+ report.degraded += 1;
1587
1791
  const degraded = transitionHostLeaseForCleanup(lease, "degraded");
1588
1792
  const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
1589
1793
  this.rememberDegraded(degraded, repoId);
@@ -1652,7 +1856,7 @@ export class HostRuntimeLeaseManager {
1652
1856
  finally {
1653
1857
  await handle.close();
1654
1858
  }
1655
- await fs.rename(temporary, target);
1859
+ await replaceHostRuntimeLedgerFile(temporary, target);
1656
1860
  }
1657
1861
  catch (error) {
1658
1862
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -1881,10 +2085,11 @@ export class HostRuntimeLeaseManager {
1881
2085
  for (const promotion of promotions)
1882
2086
  this.knownPromotions.set(promotion.repoId, promotion);
1883
2087
  }
1884
- async invalidatePromotion(repoId, scope = "all") {
1885
- await this.promotionStore.invalidate(repoId, scope);
2088
+ async invalidatePromotion(repoId, scope = "all", quarantineFingerprints) {
1886
2089
  this.knownPromotions.delete(repoId.trim().toLowerCase());
2090
+ await this.promotionStore.invalidate(repoId, scope, quarantineFingerprints);
1887
2091
  }
2092
+ promotionQuarantined(repoId, fingerprint) { return this.promotionStore.quarantined(repoId, fingerprint); }
1888
2093
  drainAdmissionWaiters() {
1889
2094
  this.reconcileReservationOwners();
1890
2095
  this.drainSingletonWaiters();
@@ -1934,95 +2139,6 @@ export class HostRuntimeLeaseManager {
1934
2139
  return this.reservationOwnerIsLive({ dispatchAttemptId, fencingToken });
1935
2140
  }
1936
2141
  }
1937
- class AttemptSupervisedProviderProcessRunner {
1938
- supervisor;
1939
- owner;
1940
- listenerInspector;
1941
- enforceNoListeners;
1942
- onProcessTreeStarted;
1943
- constructor(supervisor, owner, listenerInspector, enforceNoListeners, onProcessTreeStarted) {
1944
- this.supervisor = supervisor;
1945
- this.owner = owner;
1946
- this.listenerInspector = listenerInspector;
1947
- this.enforceNoListeners = enforceNoListeners;
1948
- this.onProcessTreeStarted = onProcessTreeStarted;
1949
- }
1950
- async run(request, handlers = {}, signal) {
1951
- const baselineListeners = this.enforceNoListeners
1952
- ? new Set(await this.listenerInspector.inspectLoopbackListeners())
1953
- : new Set();
1954
- const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
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) {
1968
- if (!this.enforceNoListeners)
1969
- return await child.result;
1970
- let settled = false;
1971
- let inspectionFailure;
1972
- const monitor = (async () => {
1973
- while (!settled) {
1974
- try {
1975
- const ports = (await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner))
1976
- .filter(port => !baselineListeners.has(port));
1977
- if (ports.length > 0) {
1978
- inspectionFailure = new Error(`host_analysis_listener_violation: analysis-only provider opened undeclared loopback listener(s): ${ports.join(", ")}.`);
1979
- await child.stop(this.owner.fencingToken).catch(() => undefined);
1980
- return;
1981
- }
1982
- }
1983
- catch (error) {
1984
- inspectionFailure = error;
1985
- await child.stop(this.owner.fencingToken).catch(() => undefined);
1986
- return;
1987
- }
1988
- await waitForAnalysisInspection(250, signal).catch(error => {
1989
- if (!settled && !signal?.aborted)
1990
- inspectionFailure = error;
1991
- });
1992
- }
1993
- })();
1994
- try {
1995
- const result = await child.result;
1996
- settled = true;
1997
- await monitor;
1998
- if (inspectionFailure)
1999
- throw inspectionFailure;
2000
- return result;
2001
- }
2002
- catch (error) {
2003
- settled = true;
2004
- await monitor.catch(() => undefined);
2005
- if (inspectionFailure)
2006
- throw inspectionFailure;
2007
- throw error;
2008
- }
2009
- }
2010
- }
2011
- function waitForAnalysisInspection(milliseconds, signal) {
2012
- if (signal?.aborted)
2013
- return Promise.reject(cancellationError(signal));
2014
- return new Promise((resolve, reject) => {
2015
- const timer = setTimeout(() => {
2016
- signal?.removeEventListener("abort", abort);
2017
- resolve();
2018
- }, milliseconds);
2019
- const abort = () => {
2020
- clearTimeout(timer);
2021
- reject(cancellationError(signal));
2022
- };
2023
- signal?.addEventListener("abort", abort, { once: true });
2024
- });
2025
- }
2026
2142
  export class HostRuntimeLeaseCleanupError extends Error {
2027
2143
  lease;
2028
2144
  constructor(lease, cause) {
@@ -2140,44 +2256,36 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2140
2256
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2141
2257
  return environment;
2142
2258
  }
2143
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = []) {
2144
- const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2145
- const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2146
- const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2147
- let stdoutTail = "";
2148
- let stderrTail = "";
2149
- const append = async (target, line) => {
2150
- await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2151
- };
2152
- const child = await supervisor.startChildReady(childName, {
2153
- command: plan.command,
2154
- args: plan.args,
2155
- cwd: plan.cwd,
2156
- env: plan.environment,
2157
- captureOutput: false,
2158
- }, {
2159
- onStdoutLine: async (line) => {
2160
- stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2161
- await append(stdoutLogPath, line);
2162
- },
2163
- onStderrLine: async (line) => {
2164
- stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2165
- await append(stderrLogPath, line);
2166
- },
2167
- }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2168
- const result = await child.result;
2169
- return {
2170
- exitCode: result.exitCode,
2171
- stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2172
- stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2173
- stdoutLogPath,
2174
- stderrLogPath,
2175
- };
2259
+ /**
2260
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
2261
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
2262
+ * stack is down: after its ports are released another attempt may be assigned them.
2263
+ */
2264
+ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2265
+ const keys = new Set([
2266
+ "FORGE_E2E_API_URL",
2267
+ "FORGE_E2E_WEB_URL",
2268
+ "FORGE_BASE_URL",
2269
+ "FORGE_PLAYWRIGHT_BASE_URL",
2270
+ // The generated Playwright config embeds the base URL.
2271
+ "FORGE_PLAYWRIGHT_CONFIG",
2272
+ ]);
2273
+ for (const port of runtimeContract.contract.runtime.ports) {
2274
+ const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
2275
+ keys.add(port.env);
2276
+ if (port.baseUrlEnv)
2277
+ keys.add(port.baseUrlEnv);
2278
+ keys.add(`FORGE_${normalizedName}_PORT`);
2279
+ keys.add(`FORGE_${normalizedName}_URL`);
2280
+ }
2281
+ return [...keys];
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();
2176
2286
  }
2177
- function appendRuntimeBuildTail(current, value) {
2178
- if (!value)
2179
- return current;
2180
- return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
2287
+ function anySignal(...signals) {
2288
+ return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2181
2289
  }
2182
2290
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
2183
2291
  if (executionClass === "analysis_only") {
@@ -2207,7 +2315,7 @@ function runtimeExecutionClass(dispatch) {
2207
2315
  ? "analysis_only"
2208
2316
  : "managed_runtime";
2209
2317
  }
2210
- function runtimeAdmissionPriority(dispatch) {
2318
+ export function runtimeAdmissionPriority(dispatch) {
2211
2319
  return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2212
2320
  || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2213
2321
  ? "background"
@@ -2279,6 +2387,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
2279
2387
  const parsed = Number.parseInt(process.env[name] ?? "", 10);
2280
2388
  return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2281
2389
  }
2390
+ /**
2391
+ * Today's max attempts and adaptive memory reserve for this host, before
2392
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
2393
+ * (decision 0014 treats those as bounds on the server's values).
2394
+ */
2395
+ export function hostCapacityLimitDefaults(capacityResourceSample) {
2396
+ const configuration = loadHostCapacityConfiguration(capacityResourceSample);
2397
+ return {
2398
+ maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
2399
+ memoryReserveBytes: configuration.adaptiveHostReserveBytes,
2400
+ };
2401
+ }
2282
2402
  function loadHostCapacityConfiguration(capacityResourceSample) {
2283
2403
  const sampledCpuCount = capacityResourceSample
2284
2404
  ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
@@ -2286,23 +2406,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
2286
2406
  const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2287
2407
  const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2288
2408
  const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
2289
- const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2290
- explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2409
+ const adaptiveOptions = {
2291
2410
  floorBytes: reserveFloorBytes,
2292
2411
  ceilingBytes: reserveCeilingBytes,
2293
2412
  percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
2413
+ };
2414
+ const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2415
+ ...adaptiveOptions,
2416
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2294
2417
  });
2295
- const minimumIdleReserveBytes = Math.min(hostReserveBytes, reserveFloorBytes);
2418
+ const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
2419
+ const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
2420
+ const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
2296
2421
  return {
2297
- hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2))), 1, 32),
2422
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
2298
2423
  hostReserveBytes,
2299
- idleHostReserveBytes: configuredInteger("FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES", minimumIdleReserveBytes, 512 * 1024 ** 2, hostReserveBytes),
2424
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
2425
+ defaultHardMaxAttempts,
2426
+ adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
2427
+ reserveFloorBytes,
2428
+ idleReserveOverrideBytes,
2300
2429
  cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2301
2430
  workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2302
2431
  memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2303
2432
  memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2304
2433
  };
2305
2434
  }
2435
+ /**
2436
+ * The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
2437
+ * clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
2438
+ */
2439
+ function idleHostReserveBytesFor(hostReserveBytes, configuration) {
2440
+ const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
2441
+ const override = configuration.idleReserveOverrideBytes;
2442
+ return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
2443
+ }
2306
2444
  function configuredOptionalInteger(name, minimum, maximum) {
2307
2445
  const raw = process.env[name];
2308
2446
  if (raw === undefined || raw.trim().length === 0)
@@ -2455,30 +2593,6 @@ function deserializeHostAttemptRootIdentity(identity) {
2455
2593
  ? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
2456
2594
  : null;
2457
2595
  }
2458
- function validHostProcessSupervisorMetadata(value, lease) {
2459
- if (typeof value !== "object" || value === null)
2460
- return false;
2461
- const metadata = value;
2462
- return metadata.schemaVersion === 1
2463
- && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
2464
- && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
2465
- && Number.isSafeInteger(metadata.rootPid)
2466
- && metadata.rootPid > 0
2467
- && Number.isFinite(Date.parse(metadata.rootCreatedAt))
2468
- && (metadata.rootIdentity == null
2469
- || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
2470
- && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
2471
- && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
2472
- && metadata.runtimeLeaseId === lease.executionLeaseId
2473
- && metadata.dispatchAttemptId === lease.dispatchAttemptId
2474
- && metadata.fencingToken === lease.fencingToken
2475
- && Number.isSafeInteger(metadata.bridgePid)
2476
- && metadata.bridgePid > 0;
2477
- }
2478
- function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
2479
- const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
2480
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2481
- }
2482
2596
  function transitionHostLeaseForCleanup(lease, state) {
2483
2597
  if (lease.state === state || lease.state === "released")
2484
2598
  return lease;