@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.03584818ede5

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 (275) hide show
  1. package/README.md +146 -5
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  6. package/dist/bridge/bridge.base.d.ts +13 -1
  7. package/dist/bridge/bridge.service.d.ts +155 -4
  8. package/dist/bridge/bridge.service.js +1805 -155
  9. package/dist/bridge/bridge.types.d.ts +68 -1
  10. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  11. package/dist/bridge/dispatch-result-outbox.js +87 -0
  12. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  13. package/dist/bridge/dispatch-result-worker.js +122 -0
  14. package/dist/bridge/internals.d.ts +2 -0
  15. package/dist/bridge/internals.js +1 -0
  16. package/dist/bridge/local-yield-flag.d.ts +6 -0
  17. package/dist/bridge/local-yield-flag.js +34 -0
  18. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  19. package/dist/bridge/readiness-result-outbox.js +54 -0
  20. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  21. package/dist/bridge/readiness-result-worker.js +121 -0
  22. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +110 -0
  24. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  25. package/dist/bridge/test-postgres-capability.js +120 -0
  26. package/dist/cleanup/cleanup.service.d.ts +10 -0
  27. package/dist/cleanup/cleanup.service.js +128 -104
  28. package/dist/cleanup/cleanup.types.d.ts +4 -0
  29. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  30. package/dist/cleanup/forge-owned-paths.js +53 -0
  31. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  32. package/dist/cleanup/host-runtime-ledger.js +109 -0
  33. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  34. package/dist/cleanup/managed-branch-sweep.js +111 -0
  35. package/dist/cli/cli.help.js +22 -4
  36. package/dist/cli/cli.service.d.ts +30 -6
  37. package/dist/cli/cli.service.js +216 -31
  38. package/dist/cli/local-config.d.ts +5 -0
  39. package/dist/cli/local-config.js +30 -4
  40. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  41. package/dist/runtime/aspnet-runtime-prebuild.js +429 -0
  42. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  43. package/dist/runtime/attempt-database-broker.js +390 -0
  44. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  45. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  46. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  47. package/dist/runtime/attempt-path-operation.js +94 -0
  48. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  49. package/dist/runtime/attempt-private-directory.js +54 -0
  50. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  51. package/dist/runtime/attempt-process-supervisor.js +144 -23
  52. package/dist/runtime/canonical-source-file.d.ts +3 -0
  53. package/dist/runtime/canonical-source-file.js +54 -0
  54. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  55. package/dist/runtime/docker-engine-probe.js +333 -0
  56. package/dist/runtime/generated-output-reset.d.ts +10 -0
  57. package/dist/runtime/generated-output-reset.js +62 -8
  58. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  59. package/dist/runtime/host-database-capability-boundary.js +63 -0
  60. package/dist/runtime/host-diagnostics.d.ts +11 -0
  61. package/dist/runtime/host-diagnostics.js +192 -0
  62. package/dist/runtime/host-execution-root.d.ts +4 -0
  63. package/dist/runtime/host-execution-root.js +39 -0
  64. package/dist/runtime/host-facts.d.ts +36 -0
  65. package/dist/runtime/host-facts.js +95 -0
  66. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  67. package/dist/runtime/host-listener-inspector.js +121 -60
  68. package/dist/runtime/host-load-admission.d.ts +67 -0
  69. package/dist/runtime/host-load-admission.js +99 -0
  70. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  71. package/dist/runtime/host-load-child-environment.js +76 -0
  72. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  73. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  74. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  75. package/dist/runtime/host-load-governor-config.js +83 -0
  76. package/dist/runtime/host-load-governor.d.ts +184 -0
  77. package/dist/runtime/host-load-governor.js +632 -0
  78. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  79. package/dist/runtime/host-load-ledger-lock.js +185 -0
  80. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  81. package/dist/runtime/host-load-runtime-settings.js +78 -0
  82. package/dist/runtime/host-load-sampler.d.ts +149 -0
  83. package/dist/runtime/host-load-sampler.js +291 -0
  84. package/dist/runtime/host-load-step-class.d.ts +70 -0
  85. package/dist/runtime/host-load-step-class.js +161 -0
  86. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  87. package/dist/runtime/host-load-step-reaper.js +95 -0
  88. package/dist/runtime/host-load-step-run.d.ts +73 -0
  89. package/dist/runtime/host-load-step-run.js +102 -0
  90. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  91. package/dist/runtime/host-load-test-slot.js +81 -0
  92. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  93. package/dist/runtime/host-load-token-ledger.js +453 -0
  94. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  95. package/dist/runtime/host-load-windows-cpu.js +85 -0
  96. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  97. package/dist/runtime/host-pressure-stall.js +168 -0
  98. package/dist/runtime/host-runtime-contract.d.ts +16 -1
  99. package/dist/runtime/host-runtime-contract.js +174 -56
  100. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  101. package/dist/runtime/host-runtime-lease.js +1464 -121
  102. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  103. package/dist/runtime/host-runtime-promotion.js +107 -12
  104. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  105. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  106. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  107. package/dist/runtime/host-runtime-requirements.js +117 -0
  108. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  109. package/dist/runtime/managed-command-teardown.js +607 -0
  110. package/dist/runtime/memory-capacity.d.ts +70 -0
  111. package/dist/runtime/memory-capacity.js +123 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  113. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  114. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  115. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  116. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  117. package/dist/runtime/pinned-directory-process.js +61 -0
  118. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  119. package/dist/runtime/pinned-source-directory.js +94 -0
  120. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  121. package/dist/runtime/playwright-browser-cache.js +227 -0
  122. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  123. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  124. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  125. package/dist/runtime/prepared-runtime-identity.js +218 -0
  126. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  127. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  128. package/dist/runtime/runner-settings.d.ts +100 -0
  129. package/dist/runtime/runner-settings.js +214 -0
  130. package/dist/runtime/runtime-isolation-lease.js +4 -1
  131. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  132. package/dist/runtime/workspace-resource-estimator.js +174 -0
  133. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  134. package/dist/sandbox/host-capacity-broker.js +334 -0
  135. package/dist/sandbox/preflight.d.ts +31 -1
  136. package/dist/sandbox/preflight.js +237 -51
  137. package/dist/sandbox/repository-lock.d.ts +2 -1
  138. package/dist/sandbox/repository-lock.js +19 -9
  139. package/dist/sandbox/runtime.d.ts +16 -2
  140. package/dist/sandbox/runtime.js +182 -109
  141. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  142. package/dist/sandbox/sandbox-cgroups.js +42 -0
  143. package/dist/sandbox/sandbox.types.d.ts +7 -0
  144. package/dist/sandbox/workspace.service.js +2 -0
  145. package/dist/session/architect-waits.d.ts +2 -0
  146. package/dist/session/architect-waits.js +138 -0
  147. package/dist/session/managed-attempt-tools.d.ts +44 -1
  148. package/dist/session/managed-attempt-tools.js +816 -46
  149. package/dist/session/managed-build-coordinator.d.ts +5 -0
  150. package/dist/session/managed-build-coordinator.js +109 -0
  151. package/dist/session/managed-build-receipt.d.ts +21 -0
  152. package/dist/session/managed-build-receipt.js +337 -0
  153. package/dist/session/managed-command-host-load.d.ts +47 -0
  154. package/dist/session/managed-command-host-load.js +83 -0
  155. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  156. package/dist/session/managed-verification-timeouts.js +17 -0
  157. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  158. package/dist/session/mcp-argument-coercion.js +121 -0
  159. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  160. package/dist/session/phase-completion.artifacts.js +319 -44
  161. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  162. package/dist/session/phase-completion.command-validation.js +77 -0
  163. package/dist/session/phase-completion.d.ts +15 -1
  164. package/dist/session/phase-completion.helpers.d.ts +5 -0
  165. package/dist/session/phase-completion.helpers.js +43 -19
  166. package/dist/session/phase-completion.js +18 -3
  167. package/dist/session/phase-completion.prompts.js +22 -18
  168. package/dist/session/phase-completion.runtime.d.ts +6 -2
  169. package/dist/session/phase-completion.runtime.js +191 -47
  170. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  171. package/dist/session/phase-completion.schema-parts.js +188 -0
  172. package/dist/session/phase-completion.schemas.d.ts +3 -3
  173. package/dist/session/phase-completion.schemas.js +250 -226
  174. package/dist/session/phase-completion.validation.d.ts +3 -3
  175. package/dist/session/phase-completion.validation.js +135 -89
  176. package/dist/session/pre-publication-host-load.d.ts +27 -0
  177. package/dist/session/pre-publication-host-load.js +111 -0
  178. package/dist/session/pre-publication-pass.d.ts +61 -0
  179. package/dist/session/pre-publication-pass.js +148 -0
  180. package/dist/session/pre-publication-process.d.ts +23 -0
  181. package/dist/session/pre-publication-process.js +109 -0
  182. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  183. package/dist/session/pre-publication-skipped-tests.js +109 -0
  184. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  185. package/dist/session/pre-publication-step-execution.js +49 -0
  186. package/dist/session/pre-publication-validation.d.ts +87 -0
  187. package/dist/session/pre-publication-validation.js +668 -0
  188. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  189. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  190. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  191. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  192. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  193. package/dist/session/provider-cli/claude-background-work.js +180 -0
  194. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  195. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  196. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  197. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  198. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  199. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  200. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  201. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  202. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  203. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  204. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  205. package/dist/session/provider-cli/provider-cli.process.d.ts +92 -14
  206. package/dist/session/provider-cli/provider-cli.process.js +583 -210
  207. package/dist/session/provider-cli/provider-cli.prompts.d.ts +12 -0
  208. package/dist/session/provider-cli/provider-cli.prompts.js +200 -25
  209. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  210. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  211. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  212. package/dist/session/provider-cli/provider-cli.runtime.js +61 -3
  213. package/dist/session/provider-cli/provider-cli.service.d.ts +33 -5
  214. package/dist/session/provider-cli/provider-cli.service.js +819 -84
  215. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  216. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  217. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  218. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  219. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  220. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  221. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  222. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  223. package/dist/session/provider-cli/provider-output-state.js +376 -17
  224. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  225. package/dist/session/provider-cli/provider-usage.js +28 -5
  226. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  227. package/dist/session/publishable-worktree-changes.js +193 -0
  228. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  229. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  230. package/dist/session/session-redaction.js +434 -9
  231. package/dist/session/session.base.d.ts +9 -1
  232. package/dist/session/session.service.d.ts +9 -2
  233. package/dist/session/session.service.js +264 -27
  234. package/dist/session/session.types.d.ts +150 -2
  235. package/dist/session/session.types.js +599 -7
  236. package/dist/session/unreferenced-exports.d.ts +12 -0
  237. package/dist/session/unreferenced-exports.js +59 -0
  238. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  239. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  240. package/dist/shared/format/format-bytes.d.ts +1 -0
  241. package/dist/shared/format/format-bytes.js +9 -0
  242. package/dist/shared/git/git.js +2 -1
  243. package/dist/shared/path/path.d.ts +1 -0
  244. package/dist/shared/path/path.js +18 -0
  245. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  246. package/dist/shared/process/dotnet-toolchain.js +307 -0
  247. package/dist/shared/process/host-process-recovery.js +3 -2
  248. package/dist/shared/process/host-process-supervisor.d.ts +3 -0
  249. package/dist/shared/process/host-process-supervisor.js +61 -12
  250. package/dist/shared/process/process-tree.d.ts +52 -0
  251. package/dist/shared/process/process-tree.js +144 -0
  252. package/dist/shared/process/process.d.ts +69 -0
  253. package/dist/shared/process/process.js +223 -16
  254. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  255. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  256. package/dist/shared/process/windows-launch.d.ts +18 -0
  257. package/dist/shared/process/windows-launch.js +68 -0
  258. package/dist/shared/provider-capabilities.d.ts +3 -0
  259. package/dist/shared/provider-capabilities.js +84 -0
  260. package/dist/shared/redaction/redaction.d.ts +1 -0
  261. package/dist/shared/redaction/redaction.js +39 -3
  262. package/dist/shared/time/monotonic.d.ts +1 -0
  263. package/dist/shared/time/monotonic.js +8 -0
  264. package/dist/version.d.ts +1 -1
  265. package/dist/version.js +1 -1
  266. package/dist/worktree/dependency-warmer.d.ts +66 -9
  267. package/dist/worktree/dependency-warmer.js +609 -24
  268. package/dist/worktree/index.d.ts +1 -1
  269. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  270. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  271. package/dist/worktree/worktree.service.d.ts +17 -1
  272. package/dist/worktree/worktree.service.js +293 -21
  273. package/dist/worktree/worktree.types.d.ts +14 -1
  274. package/package.json +8 -6
  275. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -1,17 +1,43 @@
1
1
  import fs from "node:fs/promises";
2
+ import { statfsSync } from "node:fs";
3
+ import { randomUUID } from "node:crypto";
4
+ import os from "node:os";
2
5
  import path from "node:path";
6
+ import { assertHostAttemptRootIdentity, retainHostDiagnostics } from "./host-diagnostics.js";
7
+ import { assertHostExecutionRoot, compactHostAttemptId } from "./host-execution-root.js";
8
+ import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
9
+ import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
+ import { ForgeFailureError } from "../session/session.types.js";
11
+ import { resolveExistingDirectoryPath } from "../shared/path/path.js";
12
+ import { formatBytes } from "../shared/format/format-bytes.js";
13
+ import { redactText } from "../shared/redaction/redaction.js";
3
14
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
4
15
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
5
16
  import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
6
17
  import { HostPortBroker, } from "./host-port-broker.js";
7
18
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
8
19
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
20
+ import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
21
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
9
22
  import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
10
23
  import { HostListenerInspector } from "./host-listener-inspector.js";
24
+ import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
11
25
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
12
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
26
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
13
27
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
14
28
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
29
+ import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
30
+ import { readCanonicalSourceFile } from "./canonical-source-file.js";
31
+ import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
32
+ import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
33
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
34
+ import { HostLoadGovernor } from "./host-load-governor.js";
35
+ import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
36
+ import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
37
+ import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
38
+ import { HostLoadSampler } from "./host-load-sampler.js";
39
+ const hostCapacityWaiterScanLimit = 64;
40
+ const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
15
41
  export class HostRuntimeLeaseManager {
16
42
  stateRoot;
17
43
  processSupervisors;
@@ -20,18 +46,39 @@ export class HostRuntimeLeaseManager {
20
46
  promotionStore;
21
47
  playwrightAdapter;
22
48
  processRecovery;
49
+ capacityResourceSample;
50
+ databaseBroker;
51
+ preparedReadiness;
23
52
  active = new Map();
24
53
  pendingRenewals = new Map();
54
+ acquiringAdmissions = new Set();
25
55
  admissions = new Map();
26
56
  singletonOwners = new Map();
27
57
  singletonWaiters = [];
28
58
  parallelProjectOwners = new Map();
29
59
  parallelProjectWaiters = [];
60
+ capacityReservations = new Map();
61
+ capacityWaiters = [];
62
+ capacityWaiterScanCursor = 0;
63
+ backgroundAdmissionWaiters = [];
30
64
  degraded = new Map();
31
65
  knownPromotions = new Map();
66
+ ledgerWriteTail = Promise.resolve();
67
+ workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
32
68
  portBroker;
33
69
  nodeAdapter;
34
- 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()) {
70
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
71
+ capacityConfiguration;
72
+ memoryAvailability;
73
+ executionRoot;
74
+ /** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
75
+ hostLoadGovernor;
76
+ requirementsCheck = null;
77
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
78
+ setRequirementsCheck(check) {
79
+ this.requirementsCheck = check;
80
+ }
81
+ 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) {
35
82
  this.stateRoot = stateRoot;
36
83
  this.processSupervisors = processSupervisors;
37
84
  this.processRunner = processRunner;
@@ -39,22 +86,81 @@ export class HostRuntimeLeaseManager {
39
86
  this.promotionStore = promotionStore;
40
87
  this.playwrightAdapter = playwrightAdapter;
41
88
  this.processRecovery = processRecovery;
89
+ this.capacityResourceSample = capacityResourceSample;
90
+ this.databaseBroker = databaseBroker;
91
+ this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
92
+ this.executionRoot = path.resolve(executionRoot ?? stateRoot);
93
+ if (executionRoot !== undefined)
94
+ assertHostExecutionRoot(this.executionRoot);
95
+ this.preparedReadiness = new PreparedRuntimeReadiness(this, promotionStore, (id, fence) => this.release(id, fence, true), () => new HostRuntimeAdmissionExpiredError());
42
96
  this.portBroker = portBroker;
43
97
  this.nodeAdapter = nodeAdapter ?? new NodeHostRuntimeAdapter(portBroker);
98
+ this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
99
+ this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
100
+ }
101
+ /** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
102
+ capacityLimitDefaults() {
103
+ return {
104
+ maxConcurrentAttempts: this.capacityConfiguration.defaultHardMaxAttempts,
105
+ memoryReserveBytes: this.capacityConfiguration.adaptiveHostReserveBytes,
106
+ };
107
+ }
108
+ /**
109
+ * Decision 0014: the bridge's effective max attempts and memory reserve. They
110
+ * apply from the next attempt admission; admitted attempts keep their
111
+ * reservations and are never preempted, even when the new limit is lower than
112
+ * what already runs. The idle reserve follows the reserve as at startup.
113
+ */
114
+ applyCapacityLimits(limits) {
115
+ const current = this.capacityConfiguration;
116
+ const hardMaxAttempts = Math.max(1, Math.min(32, Math.floor(limits.maxConcurrentAttempts)));
117
+ const hostReserveBytes = Math.max(512 * 1024 ** 2, Math.floor(limits.memoryReserveBytes));
118
+ if (hardMaxAttempts === current.hardMaxAttempts && hostReserveBytes === current.hostReserveBytes)
119
+ return;
120
+ this.capacityConfiguration = {
121
+ ...current,
122
+ hardMaxAttempts,
123
+ hostReserveBytes,
124
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, current),
125
+ };
126
+ // A raised limit may admit queued attempts now rather than at their next recheck.
127
+ this.drainAdmissionWaiters();
128
+ }
129
+ hostLoadChildEnvironment() {
130
+ return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
44
131
  }
45
132
  async reap(options) {
133
+ // Heavy-step tokens whose owner died or whose lease lapsed are returned first.
134
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
46
135
  await this.refreshKnownPromotions();
136
+ const recoveredAttempts = [];
47
137
  const report = {
48
138
  examined: 0,
49
139
  reaped: 0,
50
140
  processesTerminated: 0,
51
141
  reusedPidsProtected: 0,
52
142
  degraded: 0,
143
+ recoveredAttempts,
53
144
  };
54
145
  for (const ledger of await this.readLedgers()) {
55
146
  const lease = ledger.runtimeLease;
56
147
  if (lease.runnerId !== options.runnerId)
57
148
  continue;
149
+ // A released ledger with its original attempt root is intentionally retained
150
+ // evidence that exceeded the diagnostics archive budget. It owns no runtime
151
+ // resources, but still requires process-identity recovery below on restart.
152
+ if (lease.state === "released") {
153
+ const attemptRoot = this.attemptRoot(lease.dispatchAttemptId);
154
+ const rootExists = await fs.stat(attemptRoot).then(() => true, error => {
155
+ if (error.code === "ENOENT")
156
+ return false;
157
+ throw error;
158
+ });
159
+ if (!rootExists) {
160
+ await fs.rm(this.ledgerPath(lease.dispatchAttemptId), { force: true });
161
+ continue;
162
+ }
163
+ }
58
164
  const active = this.active.get(lease.dispatchAttemptId);
59
165
  if (active) {
60
166
  if (active.lease.state !== "degraded")
@@ -78,9 +184,13 @@ export class HostRuntimeLeaseManager {
78
184
  continue;
79
185
  report.examined += 1;
80
186
  const attemptRoot = this.attemptRoot(lease.dispatchAttemptId);
187
+ const attemptRootIdentity = deserializeHostAttemptRootIdentity(ledger.attemptRootIdentity);
81
188
  let outcomes;
82
189
  try {
83
- outcomes = await this.recoverPersistedProcesses(lease, attemptRoot);
190
+ if (!attemptRootIdentity) {
191
+ throw new Error("host_runtime_reaper_invalid: original attempt-root identity is unavailable.");
192
+ }
193
+ outcomes = await this.recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity);
84
194
  }
85
195
  catch {
86
196
  await this.markLedgerDegraded(ledger);
@@ -94,10 +204,45 @@ export class HostRuntimeLeaseManager {
94
204
  report.degraded += 1;
95
205
  continue;
96
206
  }
207
+ // The runtime has already been released. Keep the over-budget original
208
+ // evidence without re-copying it or reacquiring a capacity claim.
209
+ if (lease.state === "released")
210
+ continue;
211
+ // Every supervised tree of this previous-instance attempt is proved gone,
212
+ // so no provider can still act for it. Diagnostics handling below never
213
+ // revives a process, so the proof stands even if cleanup degrades. An
214
+ // attempt with no ownership record at all may have been mid-launch, so
215
+ // it is not reported and keeps its unknown outcome.
216
+ if (staleInstance && outcomes.length > 0) {
217
+ recoveredAttempts.push({
218
+ dispatchAttemptId: lease.dispatchAttemptId,
219
+ fencingToken: lease.fencingToken,
220
+ runnerInstanceId: lease.runnerInstanceId,
221
+ });
222
+ }
97
223
  try {
98
224
  const releasing = transitionHostLeaseForCleanup(lease, "releasing");
99
- await this.writeLedger(releasing, ledger.repoId);
100
- await fs.rm(attemptRoot, { recursive: true, force: true });
225
+ await this.writeLedger(releasing, ledger.repoId, attemptRootIdentity);
226
+ let evidenceRetainedAtAttemptRoot = false;
227
+ try {
228
+ await retainHostDiagnostics(this.stateRoot, attemptRoot, lease.dispatchAttemptId, attemptRootIdentity, this.executionRoot);
229
+ }
230
+ catch {
231
+ // Exact process recovery above already proved that the runtime is gone.
232
+ // Diagnostics retention can independently refuse a changed inventory,
233
+ // an unsafe archive path, or an over-budget source. Preserve the
234
+ // original attempt root and a released ledger for reconciliation, but
235
+ // never turn evidence-only work back into a capacity-owning runtime.
236
+ evidenceRetainedAtAttemptRoot = true;
237
+ }
238
+ if (evidenceRetainedAtAttemptRoot) {
239
+ const released = transitionRuntimeIsolationLease(releasing, "released");
240
+ await this.writeLedger(released, ledger.repoId, attemptRootIdentity);
241
+ this.forgetDegraded(lease.dispatchAttemptId, lease.fencingToken);
242
+ report.reaped += 1;
243
+ continue;
244
+ }
245
+ await removeHostAttemptRoot(attemptRoot);
101
246
  await fs.rm(this.ledgerPath(lease.dispatchAttemptId), { force: true });
102
247
  this.forgetDegraded(lease.dispatchAttemptId, lease.fencingToken);
103
248
  report.reaped += 1;
@@ -107,9 +252,19 @@ export class HostRuntimeLeaseManager {
107
252
  report.degraded += 1;
108
253
  }
109
254
  }
255
+ // Databases issued to attempts that ended without a clean release (a Bridge crash, or a
256
+ // drop that met a lingering session) are removed once no live lease holds them.
257
+ // A degraded lease may still own running processes after a restart, so its database is kept.
258
+ await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
259
+ // Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
260
+ // ended with a crashed bridge or MCP server) are returned once no live lease holds
261
+ // their attempt; a degraded lease may still own the running step, so its tokens stay.
262
+ await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
263
+ || (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
110
264
  return report;
111
265
  }
112
266
  snapshot() {
267
+ this.reconcileReservationOwners();
113
268
  const projects = new Map();
114
269
  for (const promotion of this.knownPromotions.values()) {
115
270
  const project = capacityProject(projects, promotion.repoId);
@@ -168,6 +323,26 @@ export class HostRuntimeLeaseManager {
168
323
  project.waitingAttempts += 1;
169
324
  project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_candidate");
170
325
  }
326
+ for (const waiter of this.backgroundAdmissionWaiters) {
327
+ const repoId = repoIdFromProjectSingletonKeys(waiter.keys);
328
+ if (!repoId)
329
+ continue;
330
+ const project = capacityProject(projects, repoId);
331
+ project.waitingAttempts += 1;
332
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
333
+ }
334
+ // A prepared-runtime verification remains foreground demand after its
335
+ // preparation admission is released and before the internal probe has
336
+ // acquired a normal admission. Report that barrier as waiting capacity so
337
+ // the server cannot mistake the transient gap for an idle host and dispatch
338
+ // readiness probes in a tight loop.
339
+ const unrepresentedPrepared = this.preparedReadiness.pendingSnapshots()
340
+ .filter(pending => !this.hasAttemptRepresentation(pending.probeDispatchAttemptId ?? pending.dispatchAttemptId, pending.probeFencingToken ?? pending.fencingToken));
341
+ for (const pending of unrepresentedPrepared) {
342
+ const project = capacityProject(projects, pending.repoId);
343
+ project.waitingAttempts += 1;
344
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_candidate");
345
+ }
171
346
  const activeAttempts = [...this.active.values()]
172
347
  .filter(active => active.lease.state !== "degraded").length;
173
348
  const degradedAttempts = new Set([
@@ -176,14 +351,21 @@ export class HostRuntimeLeaseManager {
176
351
  .filter(([, active]) => active.lease.state === "degraded")
177
352
  .map(([dispatchAttemptId]) => dispatchAttemptId),
178
353
  ]).size;
354
+ const hostResources = this.hostResourceSnapshot();
179
355
  return {
180
356
  activeAttempts,
357
+ preparedWorktreeReadiness: true,
181
358
  reservedAttempts: Math.max(0, this.admissions.size - this.active.size),
182
- waitingAttempts: this.singletonWaiters.length + this.parallelProjectWaiters.length,
359
+ waitingAttempts: this.singletonWaiters.length
360
+ + this.parallelProjectWaiters.length
361
+ + this.capacityWaiters.length
362
+ + this.backgroundAdmissionWaiters.length
363
+ + unrepresentedPrepared.length,
183
364
  degradedAttempts,
184
365
  exclusiveReservations: this.singletonOwners.size,
185
366
  sharedReservations: [...this.parallelProjectOwners.values()]
186
367
  .reduce((count, owners) => count + owners.size, 0),
368
+ ...hostResources,
187
369
  projects: [...projects.values()]
188
370
  .map(project => ({
189
371
  ...project,
@@ -192,6 +374,21 @@ export class HostRuntimeLeaseManager {
192
374
  .sort((left, right) => left.repoId.localeCompare(right.repoId)),
193
375
  };
194
376
  }
377
+ hasForegroundDemand() {
378
+ return this.preparedReadiness.hasPending()
379
+ || [...this.admissions.values()].some(admission => admission.priority === "foreground")
380
+ || this.singletonWaiters.some(waiter => waiter.priority === "foreground")
381
+ || this.parallelProjectWaiters.some(waiter => waiter.priority === "foreground")
382
+ || this.capacityWaiters.some(waiter => waiter.priority === "foreground");
383
+ }
384
+ async acquirePreparation(dispatch, signal) {
385
+ // Discovery probes already own their verification lifecycle. Analysis-only
386
+ // work never launches the application and must not wait for a runtime wave.
387
+ if (runtimeExecutionClass(dispatch) === "analysis_only" || runtimeAdmissionPriority(dispatch) === "background") {
388
+ return await this.acquire(dispatch, signal);
389
+ }
390
+ return await this.preparedReadiness.acquire(dispatch, signal);
391
+ }
195
392
  async acquire(dispatch, signal) {
196
393
  const sandbox = dispatch.sandbox;
197
394
  if (!sandbox || sandbox.executionMode !== "host") {
@@ -211,6 +408,7 @@ export class HostRuntimeLeaseManager {
211
408
  return existing.keys;
212
409
  }
213
410
  const executionClass = runtimeExecutionClass(dispatch);
411
+ const priority = runtimeAdmissionPriority(dispatch);
214
412
  const promotion = executionClass === "managed_runtime"
215
413
  ? await this.promotionStore.load(dispatch.repo.id)
216
414
  : null;
@@ -219,37 +417,353 @@ export class HostRuntimeLeaseManager {
219
417
  const projectKey = executionClass === "analysis_only"
220
418
  ? projectHostAnalysisKey(dispatch.repo.id)
221
419
  : projectHostRuntimeSingletonKey(dispatch.repo.id);
222
- let keys = promotion || executionClass === "analysis_only" ? [] : [projectKey];
420
+ const useParallelAdmission = priority === "foreground"
421
+ && dispatch.cycleRun.phase !== "prepared_readiness"
422
+ && (promotion !== null || executionClass === "analysis_only");
423
+ let keys = useParallelAdmission ? [] : [projectKey];
424
+ const resources = normalizedHostResourceRequest(sandbox.requestedResources);
223
425
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
224
426
  ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
225
427
  : dispatch.lease.expiresAt;
428
+ const acquisitionKey = hostRuntimeOwnerKey(owner);
429
+ this.acquiringAdmissions.add(acquisitionKey);
226
430
  try {
227
- if (promotion || executionClass === "analysis_only") {
228
- await this.reserveParallelProject(projectKey, owner, expiresAt, signal);
431
+ try {
432
+ if (priority === "background") {
433
+ await this.refreshWorkspaceCapacity();
434
+ keys = await this.reserveBackgroundAdmission(keys, owner, resources, expiresAt, signal);
435
+ }
436
+ else if (useParallelAdmission) {
437
+ await this.reserveParallelProject(projectKey, owner, expiresAt, signal, priority);
438
+ }
439
+ else {
440
+ keys = await this.reserveSingletonKeys(keys, owner, expiresAt, signal, priority);
441
+ }
442
+ if (priority === "foreground") {
443
+ await this.refreshWorkspaceCapacity();
444
+ const capacityExpiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
445
+ ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
446
+ : expiresAt;
447
+ await this.reserveHostCapacity(owner, resources, capacityExpiresAt, signal, priority);
448
+ }
229
449
  }
230
- else {
231
- keys = await this.reserveSingletonKeys(keys, owner, expiresAt, signal);
450
+ catch (error) {
451
+ this.releaseHostCapacity(owner.dispatchAttemptId, owner.fencingToken);
452
+ this.releaseSingletonKeys(owner.dispatchAttemptId, owner.fencingToken);
453
+ this.releaseParallelProjects(owner.dispatchAttemptId, owner.fencingToken);
454
+ this.clearPendingRenewal(owner);
455
+ throw error;
232
456
  }
457
+ const admittedPromotion = useParallelAdmission
458
+ ? promotion ?? (executionClass === "managed_runtime" && keys.length === 0
459
+ ? this.knownPromotions.get(dispatch.repo.id) ?? null
460
+ : null)
461
+ : null;
462
+ this.admissions.set(sandbox.dispatchAttemptId, {
463
+ repoId: dispatch.repo.id,
464
+ fencingToken: owner.fencingToken,
465
+ executionClass,
466
+ priority,
467
+ provisionalPromotionFingerprint: admittedPromotion?.runtimeContractFingerprint ?? null,
468
+ keys,
469
+ parallelProjectKey: useParallelAdmission ? projectKey : null,
470
+ });
471
+ return keys;
233
472
  }
234
- catch (error) {
235
- this.clearPendingRenewal(owner);
236
- throw error;
473
+ finally {
474
+ this.acquiringAdmissions.delete(acquisitionKey);
475
+ }
476
+ }
477
+ async reserveHostCapacity(owner, resources, expiresAt, signal, priority = "foreground") {
478
+ const existing = this.capacityReservations.get(owner.dispatchAttemptId);
479
+ if (existing) {
480
+ if (!sameSingletonOwner(existing.owner, owner)) {
481
+ throw new Error("host_runtime_capacity_conflict: dispatch attempt already holds capacity under a different fence.");
482
+ }
483
+ return;
484
+ }
485
+ if (signal?.aborted)
486
+ throw cancellationError(signal);
487
+ throwIfAdmissionExpired(expiresAt);
488
+ const impossibleReason = this.hostCapacityImpossibleReason(resources);
489
+ if (impossibleReason)
490
+ throw new HostRuntimeCapacityRequestImpossibleError(impossibleReason);
491
+ if (this.capacityWaiters.length === 0 && this.hostCapacityAvailable(resources)) {
492
+ this.capacityReservations.set(owner.dispatchAttemptId, { owner, resources, state: "pending" });
493
+ return;
494
+ }
495
+ return new Promise((resolve, reject) => {
496
+ const waiter = {
497
+ owner,
498
+ resources,
499
+ priority,
500
+ resolve,
501
+ reject,
502
+ signal,
503
+ expiresAt,
504
+ deadlineTimer: null,
505
+ capacityRecheckTimer: null,
506
+ abort: () => {
507
+ if (!this.detachCapacityWaiter(waiter))
508
+ return;
509
+ this.clearPendingRenewal(owner);
510
+ reject(cancellationError(signal));
511
+ this.drainAdmissionWaiters();
512
+ },
513
+ expire: () => {
514
+ if (!this.detachCapacityWaiter(waiter))
515
+ return;
516
+ this.clearPendingRenewal(owner);
517
+ reject(new HostRuntimeAdmissionExpiredError());
518
+ this.drainAdmissionWaiters();
519
+ },
520
+ };
521
+ waiter.deadlineTimer = scheduleAdmissionDeadline(expiresAt, waiter.expire);
522
+ // Memory, CPU and filesystem capacity can recover without one of our leases
523
+ // being released (for example when an unrelated host process exits). Recheck
524
+ // ambient capacity while queued so readiness probes and attempts do not remain
525
+ // stranded behind a stale low-resource sample.
526
+ waiter.capacityRecheckTimer = setInterval(() => this.drainCapacityWaiters(), 1_000);
527
+ waiter.capacityRecheckTimer.unref?.();
528
+ signal?.addEventListener("abort", waiter.abort, { once: true });
529
+ enqueueAdmissionWaiter(this.capacityWaiters, waiter);
530
+ this.drainCapacityWaiters();
531
+ });
532
+ }
533
+ async reserveBackgroundAdmission(keys, owner, resources, expiresAt, signal) {
534
+ if (signal?.aborted)
535
+ throw cancellationError(signal);
536
+ throwIfAdmissionExpired(expiresAt);
537
+ return await new Promise((resolve, reject) => {
538
+ const waiter = {
539
+ owner,
540
+ keys,
541
+ resources,
542
+ priority: "background",
543
+ resolve,
544
+ reject,
545
+ signal,
546
+ expiresAt,
547
+ deadlineTimer: null,
548
+ capacityRecheckTimer: null,
549
+ abort: () => {
550
+ removeWaiter(this.backgroundAdmissionWaiters, waiter);
551
+ clearAdmissionDeadline(waiter);
552
+ clearCapacityRecheck(waiter);
553
+ this.clearPendingRenewal(owner);
554
+ reject(cancellationError(signal));
555
+ this.drainAdmissionWaiters();
556
+ },
557
+ expire: () => {
558
+ removeWaiter(this.backgroundAdmissionWaiters, waiter);
559
+ clearCapacityRecheck(waiter);
560
+ signal?.removeEventListener("abort", waiter.abort);
561
+ this.clearPendingRenewal(owner);
562
+ reject(new HostRuntimeAdmissionExpiredError());
563
+ this.drainAdmissionWaiters();
564
+ },
565
+ };
566
+ waiter.deadlineTimer = scheduleAdmissionDeadline(expiresAt, waiter.expire);
567
+ waiter.capacityRecheckTimer = setInterval(() => this.drainAdmissionWaiters(), 1_000);
568
+ waiter.capacityRecheckTimer.unref?.();
569
+ signal?.addEventListener("abort", waiter.abort, { once: true });
570
+ this.backgroundAdmissionWaiters.push(waiter);
571
+ this.drainAdmissionWaiters();
572
+ });
573
+ }
574
+ hostCapacityAvailable(resources) {
575
+ const capacity = this.hostResourceSnapshot();
576
+ return capacity.availableAttempts >= resources.sandboxSlots
577
+ && capacity.availableMemoryBytes >= resources.memoryBytes
578
+ && capacity.availableCpuMillis >= resources.cpuMillis
579
+ && capacity.availableWorkspaceBytes >= resources.workspaceBytes;
580
+ }
581
+ hostCapacityImpossibleReason(resources) {
582
+ const { hardMaxAttempts, idleHostReserveBytes, cpuReserveMillis } = this.capacityConfiguration;
583
+ if (resources.sandboxSlots > hardMaxAttempts) {
584
+ return `requested ${resources.sandboxSlots} sandbox slots exceed the host maximum of ${hardMaxAttempts}.`;
585
+ }
586
+ const totalMemoryBytes = this.capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
587
+ const maximumMemoryBytes = Math.max(0, totalMemoryBytes - idleHostReserveBytes);
588
+ if (resources.memoryBytes > maximumMemoryBytes) {
589
+ return `requested memory ${resources.memoryBytes} exceeds the host maximum of ${maximumMemoryBytes} bytes after reserve.`;
590
+ }
591
+ const totalCpuMillis = this.capacityResourceSample?.totalCpuMillis ?? os.cpus().length * 1_000;
592
+ const maximumCpuMillis = Math.max(0, totalCpuMillis - cpuReserveMillis);
593
+ if (resources.cpuMillis > maximumCpuMillis) {
594
+ return `requested CPU ${resources.cpuMillis} millis exceeds the host maximum of ${maximumCpuMillis} millis after reserve.`;
595
+ }
596
+ return null;
597
+ }
598
+ hostResourceSnapshot() {
599
+ if (!this.capacityResourceSample) {
600
+ try {
601
+ const stats = statfsSync(this.stateRoot);
602
+ this.workspaceAvailableBytes = Math.max(0, stats.bavail * stats.bsize);
603
+ }
604
+ catch {
605
+ // State root may not exist during the first capability heartbeat. The first
606
+ // admission creates it and refreshes the sample before reserving resources.
607
+ }
237
608
  }
238
- const admittedPromotion = promotion
239
- ?? (executionClass === "managed_runtime" && keys.length === 0
240
- ? this.knownPromotions.get(dispatch.repo.id) ?? null
241
- : null);
242
- this.admissions.set(sandbox.dispatchAttemptId, {
243
- repoId: dispatch.repo.id,
244
- fencingToken: owner.fencingToken,
245
- executionClass,
246
- provisionalPromotionFingerprint: admittedPromotion?.runtimeContractFingerprint ?? null,
247
- keys,
248
- parallelProjectKey: admittedPromotion || executionClass === "analysis_only" ? projectKey : null,
609
+ const { hardMaxAttempts, cpuReserveMillis, workspaceReserveBytes } = this.capacityConfiguration;
610
+ const hostReserveBytes = this.capacityReservations.size === 0
611
+ ? this.capacityConfiguration.idleHostReserveBytes
612
+ : this.capacityConfiguration.hostReserveBytes;
613
+ const activeReservationMemoryBytes = [...this.capacityReservations.values()]
614
+ .reduce((total, reservation) => total + reservation.resources.memoryBytes, 0);
615
+ const pendingReservationMemoryBytes = [...this.capacityReservations.values()]
616
+ .filter(reservation => reservation.state === "pending")
617
+ .reduce((total, reservation) => total + reservation.resources.memoryBytes, 0);
618
+ const activeReservationCpuMillis = [...this.capacityReservations.values()]
619
+ .reduce((total, reservation) => total + reservation.resources.cpuMillis, 0);
620
+ const activeReservationWorkspaceBytes = [...this.capacityReservations.values()]
621
+ .reduce((total, reservation) => total + reservation.resources.workspaceBytes, 0);
622
+ const sampledAt = new Date().toISOString();
623
+ const totalMemoryBytes = this.capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
624
+ const rawAvailableMemoryBytes = this.capacityResourceSample?.availableMemoryBytes ?? os.freemem();
625
+ const sampledAvailableMemoryBytes = this.memoryAvailability.observe(rawAvailableMemoryBytes);
626
+ // raw/stabilized available memory already includes every resident host and
627
+ // Forge process. Keep the independent total ceiling scoped to Forge's own
628
+ // reservations; adding ambient use here charges it a second time and can
629
+ // strand work even while more than the requested memory is physically free.
630
+ const committedMemoryBytes = Math.min(totalMemoryBytes, activeReservationMemoryBytes);
631
+ const totalCpuMillis = this.capacityResourceSample?.totalCpuMillis ?? os.cpus().length * 1000;
632
+ const sampledWorkspaceBytes = this.capacityResourceSample?.availableWorkspaceBytes ?? this.workspaceAvailableBytes;
633
+ const memoryAdmission = buildMemoryAdmissionDiagnostics({
634
+ sampledAt,
635
+ totalMemoryBytes,
636
+ rawAvailableMemoryBytes,
637
+ stabilizedAvailableMemoryBytes: sampledAvailableMemoryBytes,
638
+ controlPlaneMemoryBytes: process.memoryUsage().rss,
639
+ reserveMemoryBytes: hostReserveBytes,
640
+ committedMemoryBytes,
641
+ pendingCommitmentMemoryBytes: pendingReservationMemoryBytes,
249
642
  });
250
- return keys;
643
+ const availableMemoryBytes = memoryAdmission.availableForAdmissionBytes;
644
+ const availableCpuMillis = Math.max(0, totalCpuMillis - cpuReserveMillis - activeReservationCpuMillis);
645
+ const availableWorkspaceBytes = Math.max(0, sampledWorkspaceBytes - workspaceReserveBytes - activeReservationWorkspaceBytes);
646
+ const slotAvailability = Math.max(0, hardMaxAttempts - this.capacityReservations.size);
647
+ // Capability snapshots advertise whether any supported attempt can fit.
648
+ // The queue/admission path still checks the exact project-derived request.
649
+ const minimumRequest = minimumSupportedHostResourceRequest();
650
+ const resourceAvailability = Math.min(resourceSlots(availableMemoryBytes, minimumRequest.memoryBytes), resourceSlots(availableCpuMillis, minimumRequest.cpuMillis), resourceSlots(availableWorkspaceBytes, minimumRequest.workspaceBytes));
651
+ const availableAttempts = Math.max(0, Math.min(slotAvailability, resourceAvailability));
652
+ const unavailableReason = slotAvailability <= 0
653
+ ? `Host attempt capacity is full (${this.capacityReservations.size}/${hardMaxAttempts}).`
654
+ : availableMemoryBytes < minimumRequest.memoryBytes
655
+ ? "Host memory is below the admission reserve."
656
+ : availableCpuMillis < minimumRequest.cpuMillis
657
+ ? "Host CPU capacity is below the admission reserve."
658
+ : availableWorkspaceBytes < minimumRequest.workspaceBytes
659
+ ? "Host workspace capacity is below the admission reserve."
660
+ : null;
661
+ return {
662
+ hardMaxAttempts,
663
+ effectiveMaxAttempts: this.capacityReservations.size + availableAttempts,
664
+ availableAttempts,
665
+ totalMemoryBytes,
666
+ availableMemoryBytes,
667
+ hostReserveBytes,
668
+ availableCpuMillis,
669
+ availableWorkspaceBytes,
670
+ activeReservationMemoryBytes,
671
+ memoryAdmission,
672
+ unavailableCode: unavailableReason ? "capacity_unavailable" : null,
673
+ unavailableReason,
674
+ };
675
+ }
676
+ async refreshWorkspaceCapacity() {
677
+ if (this.capacityResourceSample)
678
+ return;
679
+ try {
680
+ await fs.mkdir(this.stateRoot, { recursive: true });
681
+ const stats = await fs.statfs(this.stateRoot);
682
+ this.workspaceAvailableBytes = Math.max(0, stats.bavail * stats.bsize);
683
+ }
684
+ catch {
685
+ // Keep the last trustworthy sample. Memory/CPU and the hard ceiling still
686
+ // protect admission when the filesystem cannot be sampled temporarily.
687
+ }
688
+ }
689
+ releaseHostCapacity(dispatchAttemptId, fencingToken) {
690
+ const reservation = this.capacityReservations.get(dispatchAttemptId);
691
+ if (!reservation || reservation.owner.fencingToken !== fencingToken)
692
+ return;
693
+ this.capacityReservations.delete(dispatchAttemptId);
694
+ this.drainAdmissionWaiters();
251
695
  }
252
- async reserveSingletonKeys(keys, owner, expiresAt, signal) {
696
+ drainCapacityWaiters() {
697
+ for (const waiter of this.capacityWaitersForScan()) {
698
+ if (!this.capacityWaiters.includes(waiter))
699
+ continue;
700
+ if (waiter.signal?.aborted) {
701
+ this.detachCapacityWaiter(waiter);
702
+ this.clearPendingRenewal(waiter.owner);
703
+ waiter.reject(cancellationError(waiter.signal));
704
+ continue;
705
+ }
706
+ if (admissionExpired(waiter.expiresAt)) {
707
+ this.detachCapacityWaiter(waiter);
708
+ this.clearPendingRenewal(waiter.owner);
709
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
710
+ continue;
711
+ }
712
+ const impossibleReason = this.hostCapacityImpossibleReason(waiter.resources);
713
+ if (impossibleReason) {
714
+ this.detachCapacityWaiter(waiter);
715
+ this.clearPendingRenewal(waiter.owner);
716
+ waiter.reject(new HostRuntimeCapacityRequestImpossibleError(impossibleReason));
717
+ continue;
718
+ }
719
+ if (!this.hostCapacityAvailable(waiter.resources))
720
+ continue;
721
+ this.detachCapacityWaiter(waiter);
722
+ this.capacityReservations.set(waiter.owner.dispatchAttemptId, {
723
+ owner: waiter.owner,
724
+ resources: waiter.resources,
725
+ state: "pending",
726
+ });
727
+ waiter.resolve();
728
+ }
729
+ }
730
+ capacityWaitersForScan() {
731
+ const head = this.capacityWaiters[0];
732
+ if (!head) {
733
+ this.capacityWaiterScanCursor = 0;
734
+ return [];
735
+ }
736
+ const scanCount = Math.min(hostCapacityWaiterScanLimit, this.capacityWaiters.length);
737
+ if (scanCount === this.capacityWaiters.length) {
738
+ this.capacityWaiterScanCursor = 0;
739
+ return this.capacityWaiters.slice();
740
+ }
741
+ // The head always gets the first opportunity, while a rotating bounded
742
+ // window prevents an unfit renewed head (or a very deep queue) from
743
+ // indefinitely hiding a later request that fits current capacity.
744
+ const laterCount = this.capacityWaiters.length - 1;
745
+ const laterScanCount = scanCount - 1;
746
+ const start = this.capacityWaiterScanCursor % laterCount;
747
+ const result = [head];
748
+ for (let offset = 0; offset < laterScanCount; offset += 1) {
749
+ result.push(this.capacityWaiters[1 + ((start + offset) % laterCount)]);
750
+ }
751
+ this.capacityWaiterScanCursor = (start + laterScanCount) % laterCount;
752
+ return result;
753
+ }
754
+ detachCapacityWaiter(waiter) {
755
+ const index = this.capacityWaiters.indexOf(waiter);
756
+ if (index < 0)
757
+ return false;
758
+ this.capacityWaiters.splice(index, 1);
759
+ clearAdmissionDeadline(waiter);
760
+ clearCapacityRecheck(waiter);
761
+ waiter.signal?.removeEventListener("abort", waiter.abort);
762
+ if (this.capacityWaiters.length === 0)
763
+ this.capacityWaiterScanCursor = 0;
764
+ return true;
765
+ }
766
+ async reserveSingletonKeys(keys, owner, expiresAt, signal, priority = "foreground") {
253
767
  const owned = keys.every(key => sameSingletonOwner(this.singletonOwners.get(key), owner));
254
768
  if (owned)
255
769
  return keys;
@@ -269,6 +783,7 @@ export class HostRuntimeLeaseManager {
269
783
  const waiter = {
270
784
  owner,
271
785
  keys,
786
+ priority,
272
787
  resolve,
273
788
  reject,
274
789
  signal,
@@ -295,13 +810,13 @@ export class HostRuntimeLeaseManager {
295
810
  this.drainAdmissionWaiters();
296
811
  },
297
812
  };
298
- this.singletonWaiters.push(waiter);
813
+ enqueueAdmissionWaiter(this.singletonWaiters, waiter);
299
814
  signal?.addEventListener("abort", waiter.abort, { once: true });
300
815
  waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
301
816
  this.drainAdmissionWaiters();
302
817
  });
303
818
  }
304
- async reserveParallelProject(key, owner, expiresAt, signal) {
819
+ async reserveParallelProject(key, owner, expiresAt, signal, priority = "foreground") {
305
820
  if (this.parallelProjectOwned(key, owner))
306
821
  return;
307
822
  const staleFence = [...(this.parallelProjectOwners.get(key)?.values() ?? [])]
@@ -313,7 +828,7 @@ export class HostRuntimeLeaseManager {
313
828
  if (signal?.aborted)
314
829
  throw cancellationError(signal);
315
830
  throwIfAdmissionExpired(expiresAt);
316
- if (this.parallelProjectAvailable(key)) {
831
+ if (this.parallelProjectAvailable(key, priority)) {
317
832
  this.assignParallelProject(key, owner);
318
833
  return;
319
834
  }
@@ -321,6 +836,7 @@ export class HostRuntimeLeaseManager {
321
836
  const waiter = {
322
837
  owner,
323
838
  key,
839
+ priority,
324
840
  resolve,
325
841
  reject,
326
842
  signal,
@@ -347,17 +863,85 @@ export class HostRuntimeLeaseManager {
347
863
  this.drainAdmissionWaiters();
348
864
  },
349
865
  };
350
- this.parallelProjectWaiters.push(waiter);
866
+ enqueueAdmissionWaiter(this.parallelProjectWaiters, waiter);
867
+ signal?.addEventListener("abort", waiter.abort, { once: true });
868
+ waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
869
+ this.drainAdmissionWaiters();
870
+ });
871
+ }
872
+ async upgradeParallelProjectToSingleton(keys, parallelProjectKey, owner, expiresAt, signal, priority = "foreground") {
873
+ if (!this.parallelProjectOwned(parallelProjectKey, owner)) {
874
+ throw new Error("host_runtime_parallel_unreserved: matching shared project admission is required before serialization.");
875
+ }
876
+ if (signal?.aborted)
877
+ throw cancellationError(signal);
878
+ throwIfAdmissionExpired(expiresAt);
879
+ return await new Promise((resolve, reject) => {
880
+ const waiter = {
881
+ owner,
882
+ keys,
883
+ priority,
884
+ resolve,
885
+ reject,
886
+ signal,
887
+ expiresAt,
888
+ deadlineTimer: null,
889
+ abort: () => {
890
+ const index = this.singletonWaiters.indexOf(waiter);
891
+ if (index >= 0)
892
+ this.singletonWaiters.splice(index, 1);
893
+ clearAdmissionDeadline(waiter);
894
+ this.clearPendingRenewal(owner);
895
+ reject(cancellationError(signal));
896
+ this.drainAdmissionWaiters();
897
+ },
898
+ expire: () => {
899
+ const index = this.singletonWaiters.indexOf(waiter);
900
+ if (index < 0)
901
+ return;
902
+ this.singletonWaiters.splice(index, 1);
903
+ clearAdmissionDeadline(waiter);
904
+ waiter.signal?.removeEventListener("abort", waiter.abort);
905
+ this.clearPendingRenewal(owner);
906
+ reject(new HostRuntimeAdmissionExpiredError());
907
+ this.drainAdmissionWaiters();
908
+ },
909
+ };
910
+ // Queue the exclusive claim before relinquishing the shared claim. This
911
+ // makes the promotion downgrade atomic from the broker's perspective and
912
+ // prevents a background readiness probe from jumping ahead in between.
913
+ enqueueAdmissionWaiter(this.singletonWaiters, waiter);
351
914
  signal?.addEventListener("abort", waiter.abort, { once: true });
352
915
  waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
916
+ this.releaseParallelProjectNoDrain(parallelProjectKey, owner);
353
917
  this.drainAdmissionWaiters();
354
918
  });
355
919
  }
356
- async start(dispatch, worktreePath, signal) {
920
+ async start(dispatch, worktreePath, signal, onAdmissionCheckpoint) {
357
921
  const sandbox = dispatch.sandbox;
358
922
  if (!sandbox || sandbox.executionMode !== "host") {
359
923
  throw new Error("host_runtime_lease_invalid: managed host sandbox context is required.");
360
924
  }
925
+ const wasPrepared = this.preparedReadiness.has(sandbox.dispatchAttemptId);
926
+ const preparedProof = wasPrepared
927
+ ? await this.preparedReadiness.verify(dispatch, worktreePath, onAdmissionCheckpoint)
928
+ : undefined;
929
+ if (wasPrepared) {
930
+ signal?.throwIfAborted();
931
+ const admission = this.hostResourceSnapshot().memoryAdmission;
932
+ const requestedMemoryBytes = normalizedHostResourceRequest(sandbox.requestedResources).memoryBytes;
933
+ await onAdmissionCheckpoint?.({
934
+ code: "host_runtime_prepared_admission_waiting",
935
+ message: `Prepared runtime verification passed. Waiting for host admission before agent startup: ${formatBytes(requestedMemoryBytes)} requested, ${formatBytes(admission.availableForAdmissionBytes)} currently available under the host reserve.`,
936
+ expiresAt: dispatch.lease.expiresAt,
937
+ });
938
+ await this.acquire(dispatch, signal);
939
+ await onAdmissionCheckpoint?.({
940
+ code: "host_runtime_prepared_admission_acquired",
941
+ message: "Prepared runtime acquired host admission; agent startup is continuing.",
942
+ expiresAt: dispatch.lease.expiresAt,
943
+ });
944
+ }
361
945
  const existing = this.active.get(sandbox.dispatchAttemptId);
362
946
  if (existing) {
363
947
  if (existing.lease.fencingToken !== dispatch.lease.fencingToken) {
@@ -365,7 +949,7 @@ export class HostRuntimeLeaseManager {
365
949
  }
366
950
  return {
367
951
  lease: existing.lease,
368
- environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass),
952
+ environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass, existing.databaseCapability),
369
953
  runtimeContract: existing.runtimeContract,
370
954
  executionClass: existing.executionClass,
371
955
  };
@@ -376,12 +960,13 @@ export class HostRuntimeLeaseManager {
376
960
  throw new Error("host_runtime_singleton_unreserved: managed host admission is required before start.");
377
961
  }
378
962
  const attemptHex = uuidHex(sandbox.dispatchAttemptId, "dispatch attempt");
379
- const normalizedWorktreePath = path.resolve(worktreePath);
380
- const attemptRoot = path.join(this.stateRoot, "host-attempts", attemptHex);
381
- const temporaryPath = path.join(attemptRoot, "tmp");
963
+ const compactAttemptHex = compactHostAttemptId(sandbox.dispatchAttemptId);
964
+ const normalizedWorktreePath = await resolveExistingDirectoryPath(worktreePath);
965
+ const attemptRoot = path.join(this.executionRoot, "a", compactAttemptHex);
966
+ const temporaryPath = path.join(attemptRoot, "t");
382
967
  const logPath = path.join(attemptRoot, "logs");
383
- const cachePath = path.join(attemptRoot, "cache");
384
- const browserProfilePath = path.join(attemptRoot, "browser-profile");
968
+ const cachePath = path.join(attemptRoot, "c");
969
+ const browserProfilePath = path.join(attemptRoot, "b");
385
970
  const testOutputPath = path.join(attemptRoot, "test-output");
386
971
  const processSupervisorMetadataPath = path.join(logPath, "attempt-process-supervisor.json");
387
972
  const processSupervisorId = `host-${attemptHex}`;
@@ -390,50 +975,95 @@ export class HostRuntimeLeaseManager {
390
975
  ? renewedExpiry.expiresAt
391
976
  : dispatch.lease.expiresAt;
392
977
  let processSupervisor = null;
978
+ let attemptRootIdentity = null;
393
979
  try {
394
- let runtimeContract;
395
- try {
396
- runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
397
- }
398
- catch (error) {
399
- if (admission.executionClass === "managed_runtime" && admission.provisionalPromotionFingerprint) {
400
- await this.invalidatePromotion(dispatch.repo.id).catch(() => undefined);
401
- }
402
- throw error;
980
+ const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
981
+ // Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
982
+ // API learns the requirements in the first place.
983
+ const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
984
+ ? []
985
+ : this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
986
+ if (unmetRequirements.length > 0) {
987
+ // Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
988
+ throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
403
989
  }
404
990
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
405
991
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
406
992
  }
993
+ if (wasPrepared && !preparedProof && admission.executionClass === "managed_runtime"
994
+ && hostRuntimeParallelEligible(runtimeContract)) {
995
+ throw new Error("host_runtime_prepared_source_changed: runtime became parallel-eligible after preparation; a new foreground proof is required.");
996
+ }
407
997
  const runtimeContractFingerprint = hostRuntimeContractFingerprint(runtimeContract);
998
+ const inputCommitSha = preparedProof?.inputCommitSha
999
+ ?? await resolveWorktreeCommitSha(normalizedWorktreePath, sandbox.inputCommitSha);
1000
+ if (preparedProof && (runtimeContractFingerprint !== preparedProof.runtimeContractFingerprint
1001
+ || JSON.stringify(preparedProof) !== JSON.stringify(await preparedRuntimeIdentity(normalizedWorktreePath, signal)))) {
1002
+ throw new Error("host_runtime_prepared_source_changed: source changed after its foreground proof; agent was not started.");
1003
+ }
408
1004
  const promotion = admission.executionClass === "managed_runtime"
409
- ? await this.promotionStore.load(dispatch.repo.id)
1005
+ ? await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha })
410
1006
  : null;
411
1007
  const promotionMatches = hostRuntimeParallelEligible(runtimeContract)
412
- && promotion?.runtimeContractFingerprint === runtimeContractFingerprint;
1008
+ && promotion?.runtimeContractFingerprint === runtimeContractFingerprint
1009
+ && promotion.inputCommitSha === inputCommitSha;
413
1010
  if (admission.executionClass === "managed_runtime" && admission.keys.length === 0 && !promotionMatches) {
414
- await this.invalidatePromotion(dispatch.repo.id);
415
1011
  const projectKeys = hostRuntimeSingletonKeys(dispatch);
416
- if (admission.parallelProjectKey) {
417
- this.releaseParallelProjectNoDrain(admission.parallelProjectKey, owner);
418
- admission.parallelProjectKey = null;
419
- }
420
1012
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
421
1013
  ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
422
1014
  : dispatch.lease.expiresAt;
423
- admission.keys = await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal);
1015
+ const parallelProjectKey = admission.parallelProjectKey;
1016
+ admission.parallelProjectKey = null;
1017
+ const capacityReservation = this.capacityReservations.get(owner.dispatchAttemptId);
1018
+ if (capacityReservation && !sameSingletonOwner(capacityReservation.owner, owner)) {
1019
+ throw new Error("host_runtime_capacity_conflict: dispatch attempt holds capacity under a different fence.");
1020
+ }
1021
+ const serializedAdmission = parallelProjectKey
1022
+ ? this.upgradeParallelProjectToSingleton(projectKeys, parallelProjectKey, owner, expiresAt, signal, admission.priority)
1023
+ : this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal, admission.priority);
1024
+ // A sibling can already hold the same provisional shared project claim
1025
+ // while waiting for this attempt's host-capacity slot. Retaining capacity
1026
+ // while waiting for that sibling to release its shared claim creates a
1027
+ // cycle: exclusive waits on shared, shared waits on capacity. Relinquish
1028
+ // the capacity slot only after the exclusive waiter is queued, then
1029
+ // reacquire it after serialization is granted.
1030
+ if (capacityReservation) {
1031
+ this.releaseHostCapacity(owner.dispatchAttemptId, owner.fencingToken);
1032
+ }
1033
+ // The checkpoint is allowed to do I/O. Observe an early admission
1034
+ // failure now so a slow acknowledgement cannot create an unhandled
1035
+ // rejection before the operational promise is awaited below.
1036
+ void serializedAdmission.catch(() => undefined);
1037
+ // Begin the operational downgrade before publishing telemetry. A lost
1038
+ // callback acknowledgement must not leave the attempt holding its old
1039
+ // shared admission while every recovery probe waits behind it.
1040
+ await onAdmissionCheckpoint?.({
1041
+ code: "host_runtime_serial_admission_waiting",
1042
+ message: "The prepared runtime contract no longer matches the parallel-readiness proof. Waiting for foreground-priority serialized admission before launch.",
1043
+ expiresAt,
1044
+ });
1045
+ admission.keys = await serializedAdmission;
424
1046
  while (admission.keys.length === 0) {
425
1047
  const promoted = this.knownPromotions.get(dispatch.repo.id);
426
1048
  if (!promoted) {
427
1049
  throw new Error("host_runtime_parallel_promotion_missing: shared admission requires matching promotion evidence.");
428
1050
  }
429
- if (promoted.runtimeContractFingerprint !== runtimeContractFingerprint) {
1051
+ const matching = await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha });
1052
+ if (!matching) {
1053
+ // Drop obsolete proof before asking for exclusive admission; otherwise
1054
+ // the queue can grant the same stale shared promotion indefinitely.
430
1055
  this.releaseParallelProjectNoDrain(projectKeys[0], owner);
431
- await this.invalidatePromotion(dispatch.repo.id);
432
- admission.keys = await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal);
1056
+ admission.keys = await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal, admission.priority);
433
1057
  continue;
434
1058
  }
435
1059
  admission.parallelProjectKey = projectKeys[0] ?? null;
436
1060
  admission.provisionalPromotionFingerprint = promoted.runtimeContractFingerprint;
1061
+ break;
1062
+ }
1063
+ // Do not hold a capacity slot while a stale shared re-grant is still
1064
+ // being converted to exclusive admission.
1065
+ if (capacityReservation) {
1066
+ await this.reserveHostCapacity(owner, capacityReservation.resources, expiresAt, signal, admission.priority);
437
1067
  }
438
1068
  }
439
1069
  const declaredSingletonKeys = runtimeContract.contract.runtime.singletonResources
@@ -444,7 +1074,7 @@ export class HostRuntimeLeaseManager {
444
1074
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
445
1075
  ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
446
1076
  : dispatch.lease.expiresAt;
447
- const reservedSingletonKeys = await this.reserveSingletonKeys(missingSingletonKeys, owner, expiresAt, signal);
1077
+ const reservedSingletonKeys = await this.reserveSingletonKeys(missingSingletonKeys, owner, expiresAt, signal, admission.priority);
448
1078
  admission.keys = [...admission.keys, ...reservedSingletonKeys]
449
1079
  .sort((left, right) => left.localeCompare(right));
450
1080
  }
@@ -455,13 +1085,16 @@ export class HostRuntimeLeaseManager {
455
1085
  if (admission.parallelProjectKey && !this.parallelProjectOwned(admission.parallelProjectKey, owner)) {
456
1086
  throw new Error("host_runtime_parallel_unreserved: matching shared project admission is required before start.");
457
1087
  }
1088
+ await createCanonicalDirectory(attemptRoot);
1089
+ attemptRootIdentity = (await assertCanonicalDirectory(attemptRoot));
458
1090
  await Promise.all([
459
- ensurePrivateDirectory(temporaryPath),
460
- ensurePrivateDirectory(logPath),
461
- ensurePrivateDirectory(cachePath),
462
- ensurePrivateDirectory(browserProfilePath),
463
- ensurePrivateDirectory(testOutputPath),
1091
+ createCanonicalDirectory(temporaryPath),
1092
+ createCanonicalDirectory(logPath),
1093
+ createCanonicalDirectory(cachePath),
1094
+ createCanonicalDirectory(browserProfilePath),
1095
+ createCanonicalDirectory(testOutputPath),
464
1096
  ]);
1097
+ await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
465
1098
  await resetGeneratedOutputs(normalizedWorktreePath, testOutputPath);
466
1099
  let lease = createRuntimeIsolationLease({
467
1100
  leaseId: sandbox.executionLeaseId,
@@ -493,11 +1126,11 @@ export class HostRuntimeLeaseManager {
493
1126
  singletonKeys,
494
1127
  },
495
1128
  });
496
- await this.writeLedger(lease);
1129
+ await this.writeLedger(lease, undefined, attemptRootIdentity);
497
1130
  lease = transitionRuntimeIsolationLease(lease, "starting");
498
- await this.writeLedger(lease);
1131
+ await this.writeLedger(lease, undefined, attemptRootIdentity);
499
1132
  lease = transitionRuntimeIsolationLease(lease, "active");
500
- await this.writeLedger(lease);
1133
+ await this.writeLedger(lease, undefined, attemptRootIdentity);
501
1134
  processSupervisor = this.processSupervisors.register({
502
1135
  processSupervisorId,
503
1136
  dispatchAttemptId: lease.dispatchAttemptId,
@@ -510,13 +1143,18 @@ export class HostRuntimeLeaseManager {
510
1143
  repoId: dispatch.repo.id,
511
1144
  sessionId: dispatch.session.id,
512
1145
  attemptRoot,
1146
+ attemptRootIdentity,
513
1147
  runtimeContract,
514
1148
  runtimeContractFingerprint,
1149
+ inputCommitSha,
515
1150
  executionClass: admission.executionClass,
516
- parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract),
1151
+ parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
517
1152
  processSupervisor,
518
1153
  adapterCleanups: [],
1154
+ adapterCleanupsByPort: new Map(),
1155
+ restartingConfiguredProject: false,
519
1156
  pendingAdapterLaunches: new Map(),
1157
+ runtimeResourcesReleased: false,
520
1158
  releasing: false,
521
1159
  });
522
1160
  this.pendingRenewals.delete(sandbox.dispatchAttemptId);
@@ -533,8 +1171,13 @@ export class HostRuntimeLeaseManager {
533
1171
  await processSupervisor.stopAll(dispatch.lease.fencingToken, "Host runtime start rolled back.").catch(() => undefined);
534
1172
  this.processSupervisors.unregister(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
535
1173
  }
536
- await fs.rm(attemptRoot, { recursive: true, force: true }).catch(() => undefined);
537
- await fs.rm(this.ledgerPath(sandbox.dispatchAttemptId), { force: true }).catch(() => undefined);
1174
+ const attemptRemoved = await retainHostDiagnostics(this.stateRoot, attemptRoot, sandbox.dispatchAttemptId, attemptRootIdentity, this.executionRoot).then(async () => {
1175
+ await removeHostAttemptRoot(attemptRoot);
1176
+ return true;
1177
+ }).catch(() => false); // A retention failure preserves the original evidence and ownership ledger.
1178
+ if (attemptRemoved) {
1179
+ await fs.rm(this.ledgerPath(sandbox.dispatchAttemptId), { force: true }).catch(() => undefined);
1180
+ }
538
1181
  this.releaseSingletonKeys(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
539
1182
  this.releaseParallelProjects(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
540
1183
  this.deleteAdmission(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
@@ -549,6 +1192,7 @@ export class HostRuntimeLeaseManager {
549
1192
  catch {
550
1193
  return;
551
1194
  }
1195
+ await this.preparedReadiness.renew(dispatchAttemptId, fencingToken, expiresAt);
552
1196
  const active = this.active.get(dispatchAttemptId);
553
1197
  if (!active) {
554
1198
  if (Number.isFinite(Date.parse(expiresAt))) {
@@ -562,13 +1206,24 @@ export class HostRuntimeLeaseManager {
562
1206
  }
563
1207
  return;
564
1208
  }
1209
+ if (active.releasing || active.lease.state === "releasing" || active.lease.state === "released")
1210
+ return;
565
1211
  const renewed = renewRuntimeIsolationLease(active.lease, fencingToken, expiresAt);
566
1212
  if (!renewed)
567
1213
  return;
568
1214
  active.lease = renewed;
569
1215
  await this.writeLedger(renewed);
570
1216
  }
571
- async startConfiguredProject(dispatchAttemptId, fencingToken, signal) {
1217
+ async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1218
+ return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
1219
+ }
1220
+ /**
1221
+ * Launches the configured project. Only the first launch, from the admitted commit's clean
1222
+ * source, may record parallel-safety proof: a restart serves the workspace after the provider
1223
+ * edited it, and a proof observed there would be stored under the admitted commit and could
1224
+ * move this or a later attempt at that commit into shared admission for source it never ran.
1225
+ */
1226
+ async launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, promote) {
572
1227
  const active = this.active.get(dispatchAttemptId);
573
1228
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
574
1229
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
@@ -576,7 +1231,7 @@ export class HostRuntimeLeaseManager {
576
1231
  if (active.executionClass === "analysis_only") {
577
1232
  return {
578
1233
  lease: active.lease,
579
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1234
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
580
1235
  runtimeContract: active.runtimeContract,
581
1236
  executionClass: active.executionClass,
582
1237
  };
@@ -585,30 +1240,112 @@ export class HostRuntimeLeaseManager {
585
1240
  if (configuredPorts.length === 0) {
586
1241
  return {
587
1242
  lease: active.lease,
588
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1243
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
589
1244
  runtimeContract: active.runtimeContract,
590
1245
  executionClass: active.executionClass,
591
1246
  };
592
1247
  }
1248
+ const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
1249
+ // A host without the project's pinned browsers fails here, before any database,
1250
+ // build, launch, or promotion work that the attempt would otherwise waste.
1251
+ if (playwrightConfig)
1252
+ await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
593
1253
  const owner = hostPortOwner(active.lease);
594
1254
  const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
595
1255
  if (!logDirectory)
596
1256
  throw new Error("host_runtime_project_invalid: attempt log directory is unavailable.");
597
- const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector);
1257
+ if (this.databaseBroker && !active.databaseCapability
1258
+ && configuredPorts.some(port => /^dotnet(?:\.exe)?$/iu.test(path.basename(port.launch.command)))) {
1259
+ // An ASP.NET runtime may require an isolated database (Forge.Api refuses to start in a
1260
+ // managed host attempt without one). Issue it before the first launch. Release waits for
1261
+ // an in-flight provision, so a database issued during release is still dropped.
1262
+ const provision = this.databaseBroker.provision(dispatchAttemptId, fencingToken, signal)
1263
+ .then(capability => {
1264
+ active.databaseCapability = capability;
1265
+ return capability;
1266
+ });
1267
+ active.databaseProvision = provision;
1268
+ await provision;
1269
+ if (active.releasing) {
1270
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during database provisioning.");
1271
+ }
1272
+ await onProjectCheckpoint?.({
1273
+ code: "host_runtime_database_provisioned",
1274
+ message: `Provisioned isolated attempt database ${active.databaseCapability.databaseName} on the native test cluster.`,
1275
+ data: { database: active.databaseCapability.databaseName },
1276
+ });
1277
+ }
1278
+ // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1279
+ const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1280
+ const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
598
1281
  for (const configuredPort of configuredPorts) {
599
1282
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
1283
+ const buildEnvironment = {
1284
+ ...configuredPort.launch.environment,
1285
+ ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1286
+ };
1287
+ const prebuild = createAspNetRuntimePrebuildPlan({
1288
+ command: configuredPort.launch.command,
1289
+ args: configuredPort.launch.args,
1290
+ cwd: workingDirectory,
1291
+ worktreePath: active.lease.worktreePath,
1292
+ environment: buildEnvironment,
1293
+ inputCommitSha: active.inputCommitSha,
1294
+ runtimeContractFingerprint: active.runtimeContractFingerprint,
1295
+ });
1296
+ if (prebuild) {
1297
+ await onProjectCheckpoint?.({
1298
+ code: "host_runtime_build_started",
1299
+ 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 },
1301
+ });
1302
+ let hostLoadWaitMs = null;
1303
+ const build = await ensureAspNetRuntimePrebuilt(prebuild,
1304
+ // Only a real build (not a verified cache hit) takes a host load token.
1305
+ async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
1306
+ classification: aspNetPrebuildStepClass,
1307
+ label: prebuild.projectPath,
1308
+ dispatchAttemptId,
1309
+ priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
1310
+ signal: buildSignal,
1311
+ onWaiting: async (decision) => await onProjectCheckpoint?.({
1312
+ code: "host_runtime_build_waiting_for_host_capacity",
1313
+ message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
1314
+ data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
1315
+ }),
1316
+ }, async (waitMs, control) => {
1317
+ hostLoadWaitMs = waitMs;
1318
+ // A reclaimed token stops the build: its capacity is no longer reserved. So does a
1319
+ // build whose process tree cannot be recorded on its token (a reclaim could not stop it).
1320
+ const unrecorded = new AbortController();
1321
+ const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
1322
+ return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
1323
+ .catch((error) => { unrecorded.abort(error); }));
1324
+ }), signal);
1325
+ await onProjectCheckpoint?.({
1326
+ code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1327
+ message: build.cacheHit
1328
+ ? `Reused the verified ASP.NET build for commit ${active.inputCommitSha.slice(0, 12)}.`
1329
+ : `ASP.NET runtime build completed for commit ${active.inputCommitSha.slice(0, 12)}; launching without another build.`,
1330
+ data: {
1331
+ input_commit_sha: active.inputCommitSha,
1332
+ build_fingerprint: build.fingerprint,
1333
+ receipt_path: build.receiptPath,
1334
+ ...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
1335
+ },
1336
+ });
1337
+ }
600
1338
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
601
1339
  command: configuredPort.launch.command,
602
1340
  args: configuredPort.launch.args,
603
1341
  cwd: workingDirectory,
604
1342
  environment: {
605
- ...configuredPort.launch.environment,
606
- ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1343
+ ...buildEnvironment,
607
1344
  },
608
1345
  }, launcher, signal);
609
1346
  }
610
- const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
611
- const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass);
1347
+ const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
1348
+ const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
612
1349
  const playwright = active.runtimeContract.contract.runtime.playwright;
613
1350
  if (!playwright) {
614
1351
  return {
@@ -637,6 +1374,7 @@ export class HostRuntimeLeaseManager {
637
1374
  testOutputDirectory: pathFor("test_output"),
638
1375
  browserProfileDirectory: pathFor("browser_profile"),
639
1376
  baseUrl,
1377
+ ownershipToken: uuidHex(promotedLease.dispatchAttemptId, "dispatch attempt"),
640
1378
  });
641
1379
  return {
642
1380
  lease: promotedLease,
@@ -645,11 +1383,110 @@ export class HostRuntimeLeaseManager {
645
1383
  executionClass: active.executionClass,
646
1384
  };
647
1385
  }
1386
+ /**
1387
+ * Relaunches the configured project so it serves the current workspace. Every
1388
+ * configured process stops (the API port changes, so the dev server's proxy target
1389
+ * must change with it), its port reservation is released and dropped from the
1390
+ * persisted lease, and the regular start path runs again, including the ASP.NET
1391
+ * prebuild, whose receipt rebuilds only when the sources changed.
1392
+ */
1393
+ async restartConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1394
+ const active = this.active.get(dispatchAttemptId);
1395
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1396
+ throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1397
+ }
1398
+ if (signal?.aborted)
1399
+ throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
1400
+ if (active.restartingConfiguredProject) {
1401
+ throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
1402
+ }
1403
+ active.restartingConfiguredProject = true;
1404
+ // Release cancels the whole restart through this controller and waits for it to settle.
1405
+ const controller = linkedAbortController(signal);
1406
+ const promise = this.runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, controller.signal, onProjectCheckpoint);
1407
+ const restart = { controller, promise };
1408
+ active.configuredProjectRestart = restart;
1409
+ try {
1410
+ return await promise;
1411
+ }
1412
+ finally {
1413
+ // The controller is not aborted on settle: adapters this restart launched keep it as their
1414
+ // parent signal for as long as they run, exactly as they would keep the caller's signal.
1415
+ if (active.configuredProjectRestart === restart)
1416
+ active.configuredProjectRestart = null;
1417
+ active.restartingConfiguredProject = false;
1418
+ }
1419
+ }
1420
+ async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1421
+ // The relaunch keeps the admission granted at start. A workspace contract that changed only its
1422
+ // launch environment is adopted; any other change throws host_runtime_contract_changed.
1423
+ const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
1424
+ active.runtimeContract = readmitted.runtimeContract;
1425
+ active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
1426
+ if (readmitted.changed) {
1427
+ 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." });
1428
+ }
1429
+ const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1430
+ const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
1431
+ if (pendingPort) {
1432
+ throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
1433
+ }
1434
+ const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
1435
+ if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
1436
+ // The generated Playwright config targets the stack being stopped. If the restart fails, no
1437
+ // config may be left pointing at ports another attempt can now be assigned.
1438
+ await this.playwrightAdapter.discardOverlay(temporaryDirectory);
1439
+ }
1440
+ await this.stopConfiguredProject(active, portNames);
1441
+ // Keeps whatever admission the attempt holds; see launchConfiguredProject.
1442
+ const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
1443
+ if (active.releasing) {
1444
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1445
+ }
1446
+ return restarted;
1447
+ }
1448
+ /** Stops configured project processes in reverse launch order and releases their ports. */
1449
+ async stopConfiguredProject(active, portNames) {
1450
+ const launched = active.lease.resources.ports
1451
+ .map(port => port.name)
1452
+ .filter(name => portNames.includes(name))
1453
+ .reverse();
1454
+ for (const name of launched) {
1455
+ if (active.releasing) {
1456
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1457
+ }
1458
+ const cleanup = active.adapterCleanupsByPort.get(name);
1459
+ if (!cleanup) {
1460
+ throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
1461
+ }
1462
+ // A failed stop keeps the cleanup and the port record for the fenced release retry.
1463
+ await cleanup();
1464
+ removeCleanup(active.adapterCleanups, cleanup);
1465
+ active.adapterCleanupsByPort.delete(name);
1466
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1467
+ ...active.lease.resources,
1468
+ ports: active.lease.resources.ports.filter(port => port.name !== name),
1469
+ });
1470
+ await this.writeLedger(runtimeLease);
1471
+ active.lease = runtimeLease;
1472
+ }
1473
+ }
648
1474
  providerProcessRunner(dispatchAttemptId, fencingToken) {
649
1475
  const active = this.active.get(dispatchAttemptId);
650
1476
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
651
1477
  return null;
652
- return new AttemptSupervisedProviderProcessRunner(active.processSupervisor, hostPortOwner(active.lease), this.listenerInspector, active.executionClass === "analysis_only");
1478
+ return new AttemptSupervisedProviderProcessRunner(active.processSupervisor, hostPortOwner(active.lease), this.listenerInspector, active.executionClass === "analysis_only", () => this.markCapacityReservationRunning(dispatchAttemptId, fencingToken));
1479
+ }
1480
+ markCapacityReservationRunning(dispatchAttemptId, fencingToken) {
1481
+ const reservation = this.capacityReservations.get(dispatchAttemptId);
1482
+ if (reservation?.owner.fencingToken === fencingToken)
1483
+ reservation.state = "running";
1484
+ }
1485
+ providerMemoryTelemetry(dispatchAttemptId, fencingToken) {
1486
+ const active = this.active.get(dispatchAttemptId);
1487
+ if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
1488
+ return null;
1489
+ return active.processSupervisor.providerMemoryTelemetry();
653
1490
  }
654
1491
  async promoteVerifiedRuntime(active, runtimeLease) {
655
1492
  if (!active.parallelPromotionEligible)
@@ -668,12 +1505,15 @@ export class HostRuntimeLeaseManager {
668
1505
  await this.writeLedger(promotedLease);
669
1506
  active.lease = promotedLease;
670
1507
  try {
671
- const promotion = await this.promotionStore.observe(active.repoId, active.runtimeContract, runtimeLease.dispatchAttemptId, verifiedPortNames);
1508
+ const promotion = await this.promotionStore.observe(active.repoId, active.runtimeContract, runtimeLease.dispatchAttemptId, verifiedPortNames, active.inputCommitSha);
672
1509
  this.knownPromotions.set(promotion.repoId, promotion);
673
- this.convertSingletonToParallelProject(projectKey, {
1510
+ const owner = {
674
1511
  dispatchAttemptId: runtimeLease.dispatchAttemptId,
675
1512
  fencingToken: runtimeLease.fencingToken,
676
- }, promotion);
1513
+ };
1514
+ if (!this.parallelProjectOwned(projectKey, owner)) {
1515
+ this.convertSingletonToParallelProject(projectKey, owner, promotion);
1516
+ }
677
1517
  const admission = this.admissions.get(runtimeLease.dispatchAttemptId);
678
1518
  if (admission?.fencingToken === runtimeLease.fencingToken) {
679
1519
  this.admissions.set(runtimeLease.dispatchAttemptId, {
@@ -718,6 +1558,7 @@ export class HostRuntimeLeaseManager {
718
1558
  unlinkAbortController(controller, signal);
719
1559
  };
720
1560
  active.adapterCleanups.push(cleanup);
1561
+ active.adapterCleanupsByPort.set(portName, cleanup);
721
1562
  try {
722
1563
  if (active.releasing)
723
1564
  throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
@@ -740,6 +1581,8 @@ export class HostRuntimeLeaseManager {
740
1581
  try {
741
1582
  await cleanup();
742
1583
  removeCleanup(active.adapterCleanups, cleanup);
1584
+ if (active.adapterCleanupsByPort.get(portName) === cleanup)
1585
+ active.adapterCleanupsByPort.delete(portName);
743
1586
  }
744
1587
  catch {
745
1588
  // Preserve the cleanup and broker claim for the fenced release retry.
@@ -757,10 +1600,16 @@ export class HostRuntimeLeaseManager {
757
1600
  unlinkAbortController(controller, signal);
758
1601
  }
759
1602
  }
760
- async release(dispatchAttemptId, fencingToken) {
1603
+ async release(dispatchAttemptId, fencingToken, preservePreparation = false) {
1604
+ if (!preservePreparation)
1605
+ this.preparedReadiness.cancel(dispatchAttemptId, fencingToken);
761
1606
  const active = this.active.get(dispatchAttemptId);
762
- this.pendingRenewals.delete(dispatchAttemptId);
1607
+ if (!preservePreparation)
1608
+ this.pendingRenewals.delete(dispatchAttemptId);
763
1609
  if (!active) {
1610
+ // Queued steps are cancelled and running ones stopped; each returns its own
1611
+ // token once its processes are gone (never before, or capacity is reused early).
1612
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
764
1613
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
765
1614
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
766
1615
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
@@ -770,21 +1619,81 @@ export class HostRuntimeLeaseManager {
770
1619
  if (active.lease.fencingToken !== fencingToken)
771
1620
  return null;
772
1621
  active.releasing = true;
1622
+ // Attempt teardown cancels the attempt's queued heavy steps and stops its running
1623
+ // ones. Each running step (an ASP.NET prebuild, an install, a validation step)
1624
+ // returns its own token only after its processes have exited, so the capacity is
1625
+ // not reused while, say, a build is still being terminated.
1626
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
773
1627
  for (const pending of active.pendingAdapterLaunches.values()) {
774
1628
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
775
1629
  }
776
1630
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1631
+ const restart = active.configuredProjectRestart;
1632
+ if (restart) {
1633
+ restart.controller.abort("Host runtime release cancelled the configured project restart.");
1634
+ await restart.promise.catch(() => undefined);
1635
+ }
1636
+ await active.databaseProvision?.catch(() => undefined);
777
1637
  let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
778
1638
  active.lease = releasing;
779
1639
  await this.writeLedger(releasing);
780
1640
  try {
781
- await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
782
- await releaseAdapterResources(active.adapterCleanups);
783
- await fs.rm(active.attemptRoot, { recursive: true, force: true });
784
- releasing = transitionRuntimeIsolationLease(releasing, "released");
785
- active.lease = releasing;
786
- await this.writeLedger(releasing);
787
- await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1641
+ if (!active.runtimeResourcesReleased) {
1642
+ await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1643
+ // The attempt's MCP servers and process trees are stopped now; tokens they held
1644
+ // belong to dead owners and go back to the host budget at once, including any
1645
+ // without a recorded process tree (their steps were inside the stopped trees).
1646
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
1647
+ await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
1648
+ .catch(() => undefined);
1649
+ // This bridge's own steps whose trees only stopAll could prove gone (a supervised
1650
+ // validation step whose termination failed earlier) return their tokens now.
1651
+ await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1652
+ await releaseAdapterResources(active.adapterCleanups);
1653
+ active.adapterCleanupsByPort.clear();
1654
+ if (active.databaseCapability && this.databaseBroker) {
1655
+ // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1656
+ await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
1657
+ }
1658
+ active.runtimeResourcesReleased = true;
1659
+ // Runtime admission protects live processes, listeners, ports, and their
1660
+ // memory commitment. Once exact process and adapter cleanup succeeds,
1661
+ // diagnostics retention remains retryable evidence work and must not keep
1662
+ // consuming host capacity or blocking the next project dispatch.
1663
+ this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1664
+ this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1665
+ this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1666
+ this.deleteAdmission(dispatchAttemptId, fencingToken);
1667
+ }
1668
+ let evidenceRetainedAtAttemptRoot = false;
1669
+ try {
1670
+ const diagnosticsPath = await retainHostDiagnostics(this.stateRoot, active.attemptRoot, dispatchAttemptId, active.attemptRootIdentity, this.executionRoot);
1671
+ releasing = withRuntimeIsolationResources(releasing, {
1672
+ ...releasing.resources,
1673
+ paths: [...releasing.resources.paths.filter(entry => entry.role !== "diagnostics_archive"),
1674
+ { role: "diagnostics_archive", path: diagnosticsPath }],
1675
+ });
1676
+ }
1677
+ catch {
1678
+ // Runtime teardown is already proven above. Diagnostics archival is
1679
+ // deliberately non-destructive and may refuse a changed or unsupported
1680
+ // attempt-root inventory. Preserve that root and its released ledger for
1681
+ // operator inspection/reconciliation without converting completed
1682
+ // teardown into a capacity-owning degraded runtime.
1683
+ evidenceRetainedAtAttemptRoot = true;
1684
+ }
1685
+ if (!evidenceRetainedAtAttemptRoot)
1686
+ await removeHostAttemptRoot(active.attemptRoot);
1687
+ const released = transitionRuntimeIsolationLease(releasing, "released");
1688
+ // Publish the terminal in-memory state before its serialized write. Any writer
1689
+ // that already captured this active owner must observe the terminal fence and
1690
+ // cannot recreate a nonterminal ledger after release completes.
1691
+ active.lease = released;
1692
+ await this.writeLedger(released);
1693
+ if (!evidenceRetainedAtAttemptRoot) {
1694
+ await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1695
+ }
1696
+ releasing = released;
788
1697
  this.active.delete(dispatchAttemptId);
789
1698
  this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
790
1699
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
@@ -825,28 +1734,60 @@ export class HostRuntimeLeaseManager {
825
1734
  }
826
1735
  return ledgers;
827
1736
  }
828
- async recoverPersistedProcesses(lease, attemptRoot) {
1737
+ async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
829
1738
  const logsRoot = path.join(attemptRoot, "logs");
830
1739
  const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
831
1740
  if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
832
1741
  throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
833
1742
  }
834
- const entries = await fs.readdir(logsRoot, { withFileTypes: true }).catch(error => {
835
- if (error.code === "ENOENT")
836
- return [];
837
- throw error;
838
- });
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
+ }
839
1751
  const outcomes = [];
840
- for (const entry of entries) {
841
- if (!entry.isFile() || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
842
- continue;
843
- const metadataPath = path.join(logsRoot, entry.name);
844
- const value = JSON.parse(await fs.readFile(metadataPath, "utf8"));
845
- if (!validHostProcessSupervisorMetadata(value, lease)) {
846
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
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));
847
1764
  }
848
- outcomes.push(await this.processRecovery.recover(value));
849
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");
850
1791
  return outcomes;
851
1792
  }
852
1793
  async markLedgerDegraded(ledger) {
@@ -856,7 +1797,7 @@ export class HostRuntimeLeaseManager {
856
1797
  const degraded = transitionHostLeaseForCleanup(lease, "degraded");
857
1798
  const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
858
1799
  this.rememberDegraded(degraded, repoId);
859
- await this.writeLedger(degraded, repoId ?? undefined).catch(() => undefined);
1800
+ await this.writeLedger(degraded, repoId ?? undefined, deserializeHostAttemptRootIdentity(ledger.attemptRootIdentity)).catch(() => undefined);
860
1801
  }
861
1802
  rememberDegraded(lease, repoId) {
862
1803
  this.degraded.set(lease.dispatchAttemptId, { lease, repoId });
@@ -876,13 +1817,26 @@ export class HostRuntimeLeaseManager {
876
1817
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
877
1818
  }
878
1819
  attemptRoot(dispatchAttemptId) {
879
- return path.join(this.stateRoot, "host-attempts", uuidHex(dispatchAttemptId, "dispatch attempt"));
1820
+ return path.join(this.executionRoot, "a", compactHostAttemptId(dispatchAttemptId));
1821
+ }
1822
+ writeLedger(runtimeLease, explicitRepoId, explicitAttemptRootIdentity) {
1823
+ const activeOwner = this.active.get(runtimeLease.dispatchAttemptId);
1824
+ const write = this.ledgerWriteTail.then(() => {
1825
+ if (activeOwner?.lease.fencingToken === runtimeLease.fencingToken
1826
+ && activeOwner.lease.state === "released"
1827
+ && runtimeLease.state !== "released") {
1828
+ return;
1829
+ }
1830
+ return this.writeLedgerAtomic(runtimeLease, explicitRepoId, explicitAttemptRootIdentity);
1831
+ });
1832
+ this.ledgerWriteTail = write.catch(() => undefined);
1833
+ return write;
880
1834
  }
881
- async writeLedger(runtimeLease, explicitRepoId) {
1835
+ async writeLedgerAtomic(runtimeLease, explicitRepoId, explicitAttemptRootIdentity) {
882
1836
  const root = path.join(this.stateRoot, "runtime-ledger", "host");
883
1837
  await ensurePrivateDirectory(root);
884
1838
  const target = this.ledgerPath(runtimeLease.dispatchAttemptId);
885
- const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
1839
+ const temporary = `${target}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
886
1840
  try {
887
1841
  const handle = await fs.open(temporary, "wx", 0o600);
888
1842
  try {
@@ -891,9 +1845,15 @@ export class HostRuntimeLeaseManager {
891
1845
  ?? this.admissions.get(runtimeLease.dispatchAttemptId)?.repoId
892
1846
  ?? this.degraded.get(runtimeLease.dispatchAttemptId)?.repoId
893
1847
  ?? undefined;
1848
+ const attemptRootIdentity = explicitAttemptRootIdentity
1849
+ ?? this.active.get(runtimeLease.dispatchAttemptId)?.attemptRootIdentity
1850
+ ?? undefined;
894
1851
  const ledger = {
895
1852
  schemaVersion: 1,
896
1853
  ...(repoId ? { repoId } : {}),
1854
+ ...(attemptRootIdentity
1855
+ ? { attemptRootIdentity: serializeHostAttemptRootIdentity(attemptRootIdentity) }
1856
+ : {}),
897
1857
  runtimeLease,
898
1858
  };
899
1859
  await handle.writeFile(`${JSON.stringify(ledger)}\n`);
@@ -906,7 +1866,7 @@ export class HostRuntimeLeaseManager {
906
1866
  }
907
1867
  catch (error) {
908
1868
  await fs.rm(temporary, { force: true }).catch(() => undefined);
909
- throw error;
1869
+ throw new Error(`host_runtime_ledger_write_failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
910
1870
  }
911
1871
  }
912
1872
  ledgerPath(dispatchAttemptId) {
@@ -936,7 +1896,7 @@ export class HostRuntimeLeaseManager {
936
1896
  this.singletonOwners.delete(key);
937
1897
  for (let index = 0; index < this.singletonWaiters.length;) {
938
1898
  const waiter = this.singletonWaiters[index];
939
- if (waiter.keys.length !== 1 || waiter.keys[0] !== key) {
1899
+ if (waiter.priority !== "foreground" || waiter.keys.length !== 1 || waiter.keys[0] !== key) {
940
1900
  index += 1;
941
1901
  continue;
942
1902
  }
@@ -952,9 +1912,10 @@ export class HostRuntimeLeaseManager {
952
1912
  parallelProjectOwned(key, owner) {
953
1913
  return sameSingletonOwner(this.parallelProjectOwners.get(key)?.get(owner.dispatchAttemptId), owner);
954
1914
  }
955
- parallelProjectAvailable(key) {
1915
+ parallelProjectAvailable(key, priority = "foreground") {
956
1916
  return !this.singletonOwners.has(key)
957
- && !this.singletonWaiters.some(waiter => waiter.keys.includes(key));
1917
+ && !this.singletonWaiters.some(waiter => waiter.keys.includes(key)
1918
+ && (priority === "background" || waiter.priority === "foreground"));
958
1919
  }
959
1920
  assignParallelProject(key, owner) {
960
1921
  const owners = this.parallelProjectOwners.get(key) ?? new Map();
@@ -980,9 +1941,15 @@ export class HostRuntimeLeaseManager {
980
1941
  if (this.admissions.get(dispatchAttemptId)?.fencingToken === fencingToken) {
981
1942
  this.admissions.delete(dispatchAttemptId);
982
1943
  }
1944
+ this.releaseHostCapacity(dispatchAttemptId, fencingToken);
983
1945
  }
984
1946
  renewAdmissionWaiterDeadline(dispatchAttemptId, fencingToken, expiresAt) {
985
- for (const waiter of [...this.singletonWaiters, ...this.parallelProjectWaiters]) {
1947
+ for (const waiter of [
1948
+ ...this.singletonWaiters,
1949
+ ...this.parallelProjectWaiters,
1950
+ ...this.capacityWaiters,
1951
+ ...this.backgroundAdmissionWaiters,
1952
+ ]) {
986
1953
  if (!sameSingletonOwner(waiter.owner, { dispatchAttemptId, fencingToken })
987
1954
  || Date.parse(expiresAt) <= Date.parse(waiter.expiresAt))
988
1955
  continue;
@@ -998,13 +1965,20 @@ export class HostRuntimeLeaseManager {
998
1965
  }
999
1966
  cancelAdmissionWaiters(dispatchAttemptId, fencingToken, reason) {
1000
1967
  const owner = { dispatchAttemptId, fencingToken };
1001
- for (const waiters of [this.singletonWaiters, this.parallelProjectWaiters]) {
1968
+ for (const waiters of [
1969
+ this.singletonWaiters,
1970
+ this.parallelProjectWaiters,
1971
+ this.capacityWaiters,
1972
+ this.backgroundAdmissionWaiters,
1973
+ ]) {
1002
1974
  for (let index = waiters.length - 1; index >= 0; index -= 1) {
1003
1975
  const waiter = waiters[index];
1004
1976
  if (!sameSingletonOwner(waiter.owner, owner))
1005
1977
  continue;
1006
1978
  waiters.splice(index, 1);
1007
1979
  clearAdmissionDeadline(waiter);
1980
+ if ("capacityRecheckTimer" in waiter)
1981
+ clearCapacityRecheck(waiter);
1008
1982
  waiter.signal?.removeEventListener("abort", waiter.abort);
1009
1983
  waiter.reject(new Error(`host_runtime_admission_cancelled: ${reason}`));
1010
1984
  }
@@ -1060,7 +2034,7 @@ export class HostRuntimeLeaseManager {
1060
2034
  waiter.reject(new HostRuntimeAdmissionExpiredError());
1061
2035
  continue;
1062
2036
  }
1063
- if (!this.parallelProjectAvailable(waiter.key)) {
2037
+ if (!this.parallelProjectAvailable(waiter.key, waiter.priority)) {
1064
2038
  index += 1;
1065
2039
  continue;
1066
2040
  }
@@ -1071,19 +2045,103 @@ export class HostRuntimeLeaseManager {
1071
2045
  waiter.resolve();
1072
2046
  }
1073
2047
  }
2048
+ drainBackgroundAdmissionWaiters() {
2049
+ if (this.hasForegroundDemand())
2050
+ return;
2051
+ for (let index = 0; index < this.backgroundAdmissionWaiters.length;) {
2052
+ const waiter = this.backgroundAdmissionWaiters[index];
2053
+ if (waiter.signal?.aborted) {
2054
+ this.backgroundAdmissionWaiters.splice(index, 1);
2055
+ clearAdmissionDeadline(waiter);
2056
+ clearCapacityRecheck(waiter);
2057
+ waiter.signal.removeEventListener("abort", waiter.abort);
2058
+ this.clearPendingRenewal(waiter.owner);
2059
+ waiter.reject(cancellationError(waiter.signal));
2060
+ continue;
2061
+ }
2062
+ if (admissionExpired(waiter.expiresAt)) {
2063
+ this.backgroundAdmissionWaiters.splice(index, 1);
2064
+ clearAdmissionDeadline(waiter);
2065
+ clearCapacityRecheck(waiter);
2066
+ waiter.signal?.removeEventListener("abort", waiter.abort);
2067
+ this.clearPendingRenewal(waiter.owner);
2068
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
2069
+ continue;
2070
+ }
2071
+ if (!this.singletonKeysAvailable(waiter.keys) || !this.hostCapacityAvailable(waiter.resources)) {
2072
+ index += 1;
2073
+ continue;
2074
+ }
2075
+ this.backgroundAdmissionWaiters.splice(index, 1);
2076
+ clearAdmissionDeadline(waiter);
2077
+ clearCapacityRecheck(waiter);
2078
+ waiter.signal?.removeEventListener("abort", waiter.abort);
2079
+ this.assignSingletonKeys(waiter.keys, waiter.owner);
2080
+ this.capacityReservations.set(waiter.owner.dispatchAttemptId, {
2081
+ owner: waiter.owner,
2082
+ resources: waiter.resources,
2083
+ state: "pending",
2084
+ });
2085
+ waiter.resolve(waiter.keys);
2086
+ }
2087
+ }
1074
2088
  async refreshKnownPromotions() {
1075
2089
  const promotions = await this.promotionStore.list();
1076
2090
  this.knownPromotions.clear();
1077
2091
  for (const promotion of promotions)
1078
2092
  this.knownPromotions.set(promotion.repoId, promotion);
1079
2093
  }
1080
- async invalidatePromotion(repoId) {
1081
- await this.promotionStore.invalidate(repoId);
2094
+ async invalidatePromotion(repoId, scope = "all") {
2095
+ await this.promotionStore.invalidate(repoId, scope);
1082
2096
  this.knownPromotions.delete(repoId.trim().toLowerCase());
1083
2097
  }
1084
2098
  drainAdmissionWaiters() {
2099
+ this.reconcileReservationOwners();
1085
2100
  this.drainSingletonWaiters();
1086
2101
  this.drainParallelProjectWaiters();
2102
+ this.drainCapacityWaiters();
2103
+ this.drainBackgroundAdmissionWaiters();
2104
+ }
2105
+ reconcileReservationOwners() {
2106
+ for (const [key, owner] of this.singletonOwners) {
2107
+ if (!this.reservationOwnerIsLive(owner))
2108
+ this.singletonOwners.delete(key);
2109
+ }
2110
+ for (const [key, owners] of this.parallelProjectOwners) {
2111
+ for (const [dispatchAttemptId, owner] of owners) {
2112
+ const awaitingExclusiveUpgrade = this.singletonWaiters.some(waiter => waiter.keys.includes(key) && sameSingletonOwner(waiter.owner, owner));
2113
+ // A parallel owner cannot legitimately keep the shared claim after the
2114
+ // same fenced attempt has queued its exclusive downgrade. Reconcile the
2115
+ // half-upgraded state before testing singleton availability so one missed
2116
+ // release cannot make an attempt wait behind itself until lease expiry.
2117
+ if (awaitingExclusiveUpgrade || !this.reservationOwnerIsLive(owner)) {
2118
+ owners.delete(dispatchAttemptId);
2119
+ }
2120
+ }
2121
+ if (owners.size === 0)
2122
+ this.parallelProjectOwners.delete(key);
2123
+ }
2124
+ }
2125
+ reservationOwnerIsLive(owner) {
2126
+ if (this.acquiringAdmissions.has(hostRuntimeOwnerKey(owner)))
2127
+ return true;
2128
+ if (this.admissions.get(owner.dispatchAttemptId)?.fencingToken === owner.fencingToken)
2129
+ return true;
2130
+ if (this.active.get(owner.dispatchAttemptId)?.lease.fencingToken === owner.fencingToken)
2131
+ return true;
2132
+ if (this.degraded.get(owner.dispatchAttemptId)?.lease.fencingToken === owner.fencingToken)
2133
+ return true;
2134
+ if (sameSingletonOwner(this.capacityReservations.get(owner.dispatchAttemptId)?.owner, owner))
2135
+ return true;
2136
+ return [
2137
+ ...this.singletonWaiters,
2138
+ ...this.parallelProjectWaiters,
2139
+ ...this.capacityWaiters,
2140
+ ...this.backgroundAdmissionWaiters,
2141
+ ].some(waiter => sameSingletonOwner(waiter.owner, owner));
2142
+ }
2143
+ hasAttemptRepresentation(dispatchAttemptId, fencingToken) {
2144
+ return this.reservationOwnerIsLive({ dispatchAttemptId, fencingToken });
1087
2145
  }
1088
2146
  }
1089
2147
  class AttemptSupervisedProviderProcessRunner {
@@ -1091,14 +2149,32 @@ class AttemptSupervisedProviderProcessRunner {
1091
2149
  owner;
1092
2150
  listenerInspector;
1093
2151
  enforceNoListeners;
1094
- constructor(supervisor, owner, listenerInspector, enforceNoListeners) {
2152
+ onProcessTreeStarted;
2153
+ constructor(supervisor, owner, listenerInspector, enforceNoListeners, onProcessTreeStarted) {
1095
2154
  this.supervisor = supervisor;
1096
2155
  this.owner = owner;
1097
2156
  this.listenerInspector = listenerInspector;
1098
2157
  this.enforceNoListeners = enforceNoListeners;
2158
+ this.onProcessTreeStarted = onProcessTreeStarted;
1099
2159
  }
1100
2160
  async run(request, handlers = {}, signal) {
2161
+ const baselineListeners = this.enforceNoListeners
2162
+ ? new Set(await this.listenerInspector.inspectLoopbackListeners())
2163
+ : new Set();
1101
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) {
1102
2178
  if (!this.enforceNoListeners)
1103
2179
  return await child.result;
1104
2180
  let settled = false;
@@ -1106,7 +2182,8 @@ class AttemptSupervisedProviderProcessRunner {
1106
2182
  const monitor = (async () => {
1107
2183
  while (!settled) {
1108
2184
  try {
1109
- const ports = await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner);
2185
+ const ports = (await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner))
2186
+ .filter(port => !baselineListeners.has(port));
1110
2187
  if (ports.length > 0) {
1111
2188
  inspectionFailure = new Error(`host_analysis_listener_violation: analysis-only provider opened undeclared loopback listener(s): ${ports.join(", ")}.`);
1112
2189
  await child.stop(this.owner.fencingToken).catch(() => undefined);
@@ -1170,6 +2247,12 @@ export class HostRuntimeAdmissionExpiredError extends Error {
1170
2247
  this.name = "HostRuntimeAdmissionExpiredError";
1171
2248
  }
1172
2249
  }
2250
+ export class HostRuntimeCapacityRequestImpossibleError extends Error {
2251
+ constructor(reason) {
2252
+ super(`host_runtime_capacity_request_impossible: ${reason}`);
2253
+ this.name = "HostRuntimeCapacityRequestImpossibleError";
2254
+ }
2255
+ }
1173
2256
  export function hostRuntimeEventResources(lease, runtimeContract, executionClass = "managed_runtime") {
1174
2257
  const requestedHostConcurrency = runtimeContract?.contract.runtime.hostConcurrency ?? "serial";
1175
2258
  const configuredLaunches = runtimeContract?.contract.runtime.ports.filter(port => port.launch !== null) ?? [];
@@ -1202,13 +2285,15 @@ export function hostRuntimeEventResources(lease, runtimeContract, executionClass
1202
2285
  export function hostRuntimeSingletonKeys(dispatch) {
1203
2286
  return [projectHostRuntimeSingletonKey(dispatch.repo.id)];
1204
2287
  }
1205
- function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass) {
2288
+ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass, databaseCapability) {
1206
2289
  const pathFor = (role) => lease.resources.paths.find(entry => entry.role === role)?.path ?? "";
1207
2290
  const environment = {
1208
2291
  FORGE_SESSION_ID: sessionId,
1209
2292
  FORGE_RUNTIME_MODE: "host",
1210
2293
  FORGE_RESOURCE_LEASE_ID: lease.leaseId,
1211
2294
  FORGE_DISPATCH_ATTEMPT_ID: lease.dispatchAttemptId,
2295
+ FORGE_E2E_OWNERSHIP_MODE: "attempt",
2296
+ FORGE_E2E_OWNERSHIP_TOKEN: uuidHex(lease.dispatchAttemptId, "dispatch attempt"),
1212
2297
  FORGE_EXECUTION_LEASE_ID: lease.executionLeaseId,
1213
2298
  FORGE_FENCING_TOKEN: lease.fencingToken,
1214
2299
  FORGE_WORKSPACE: lease.worktreePath,
@@ -1218,6 +2303,12 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
1218
2303
  FORGE_CACHE_DIR: pathFor("cache"),
1219
2304
  FORGE_BROWSER_PROFILE_DIR: pathFor("browser_profile"),
1220
2305
  FORGE_TEST_OUTPUT_DIR: pathFor("test_output"),
2306
+ // Project-authored ASP.NET code must not fall back to the durable Forge
2307
+ // database when no brokered attempt database exists. The API policy treats
2308
+ // this marker as a fail-closed isolation requirement.
2309
+ FORGE_ATTEMPT_DATABASE_POLICY: "isolated_only",
2310
+ FORGE_ATTEMPT_DATABASE_SCHEMA: `forge_attempt_${uuidHex(lease.dispatchAttemptId, "dispatch attempt")}`,
2311
+ FORGE_ATTEMPT_DATABASE_READINESS_PATH: path.join(pathFor("logs"), "attempt-database-readiness.json"),
1221
2312
  FORGE_PROCESS_SUPERVISOR_ID: lease.resources.processSupervisorId ?? "",
1222
2313
  FORGE_PROCESS_SUPERVISOR_METADATA_PATH: pathFor("process_supervisor_metadata"),
1223
2314
  FORGE_HOST_CONCURRENCY: effectiveHostConcurrency(lease, runtimeContract, executionClass),
@@ -1233,6 +2324,8 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
1233
2324
  };
1234
2325
  if (lease.resources.singletonKeys.length === 0)
1235
2326
  delete environment.FORGE_SINGLETON_KEYS;
2327
+ if (databaseCapability)
2328
+ environment[attemptDatabaseCapabilityEnvironment] = databaseCapability.connectionString;
1236
2329
  const resolvedBaseUrls = [];
1237
2330
  for (const assigned of lease.resources.ports) {
1238
2331
  const configured = runtimeContract.contract.runtime.ports.find(port => port.name === assigned.name);
@@ -1257,6 +2350,75 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
1257
2350
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
1258
2351
  return environment;
1259
2352
  }
2353
+ /**
2354
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
2355
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
2356
+ * stack is down: after its ports are released another attempt may be assigned them.
2357
+ */
2358
+ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2359
+ const keys = new Set([
2360
+ "FORGE_E2E_API_URL",
2361
+ "FORGE_E2E_WEB_URL",
2362
+ "FORGE_BASE_URL",
2363
+ "FORGE_PLAYWRIGHT_BASE_URL",
2364
+ // The generated Playwright config embeds the base URL.
2365
+ "FORGE_PLAYWRIGHT_CONFIG",
2366
+ ]);
2367
+ for (const port of runtimeContract.contract.runtime.ports) {
2368
+ const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
2369
+ keys.add(port.env);
2370
+ if (port.baseUrlEnv)
2371
+ keys.add(port.baseUrlEnv);
2372
+ keys.add(`FORGE_${normalizedName}_PORT`);
2373
+ keys.add(`FORGE_${normalizedName}_URL`);
2374
+ }
2375
+ return [...keys];
2376
+ }
2377
+ function anySignal(...signals) {
2378
+ return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2379
+ }
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
+ }
1260
2422
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
1261
2423
  if (executionClass === "analysis_only") {
1262
2424
  const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
@@ -1285,6 +2447,155 @@ function runtimeExecutionClass(dispatch) {
1285
2447
  ? "analysis_only"
1286
2448
  : "managed_runtime";
1287
2449
  }
2450
+ export function runtimeAdmissionPriority(dispatch) {
2451
+ return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2452
+ || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2453
+ ? "background"
2454
+ : "foreground";
2455
+ }
2456
+ function enqueueAdmissionWaiter(waiters, waiter) {
2457
+ if (waiter.priority === "background") {
2458
+ waiters.push(waiter);
2459
+ return;
2460
+ }
2461
+ const backgroundIndex = waiters.findIndex(candidate => candidate.priority === "background");
2462
+ if (backgroundIndex < 0)
2463
+ waiters.push(waiter);
2464
+ else
2465
+ waiters.splice(backgroundIndex, 0, waiter);
2466
+ }
2467
+ function defaultHostResourceRequest() {
2468
+ const workerMemoryLimitBytes = configuredInteger("FORGE_HOST_DEFAULT_WORKER_MEMORY_LIMIT_BYTES", 2 * 1024 ** 3, 128 * 1024 ** 2, 512 * 1024 ** 3);
2469
+ const runtimeOverheadBytes = 128 * 1024 ** 2;
2470
+ return {
2471
+ sandboxSlots: 1,
2472
+ cpuMillis: 2000,
2473
+ workerMemoryLimitBytes,
2474
+ serviceMemoryLimitBytes: 0,
2475
+ runtimeOverheadBytes,
2476
+ memoryBytes: workerMemoryLimitBytes + runtimeOverheadBytes,
2477
+ workspaceBytes: 10 * 1024 ** 3,
2478
+ pids: 512,
2479
+ buildSlots: 1,
2480
+ };
2481
+ }
2482
+ function minimumSupportedHostResourceRequest() {
2483
+ return {
2484
+ sandboxSlots: 1,
2485
+ cpuMillis: 1000,
2486
+ workerMemoryLimitBytes: 1024 ** 3,
2487
+ serviceMemoryLimitBytes: 0,
2488
+ runtimeOverheadBytes: 128 * 1024 ** 2,
2489
+ memoryBytes: 1152 * 1024 ** 2,
2490
+ workspaceBytes: architectMinimumWorkspaceEstimateBytes,
2491
+ pids: 256,
2492
+ buildSlots: 0,
2493
+ };
2494
+ }
2495
+ function normalizedHostResourceRequest(resources) {
2496
+ const defaults = defaultHostResourceRequest();
2497
+ const workerMemoryLimitBytes = positiveResourceValue(resources?.workerMemoryLimitBytes, defaults.workerMemoryLimitBytes);
2498
+ const serviceMemoryLimitBytes = nonNegativeResourceValue(resources?.serviceMemoryLimitBytes, defaults.serviceMemoryLimitBytes);
2499
+ const runtimeOverheadBytes = nonNegativeResourceValue(resources?.runtimeOverheadBytes, defaults.runtimeOverheadBytes);
2500
+ return {
2501
+ sandboxSlots: positiveResourceValue(resources?.sandboxSlots, defaults.sandboxSlots),
2502
+ cpuMillis: positiveResourceValue(resources?.cpuMillis, defaults.cpuMillis),
2503
+ workerMemoryLimitBytes,
2504
+ serviceMemoryLimitBytes,
2505
+ runtimeOverheadBytes,
2506
+ memoryBytes: workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
2507
+ workspaceBytes: positiveResourceValue(resources?.workspaceBytes, defaults.workspaceBytes),
2508
+ pids: positiveResourceValue(resources?.pids, defaults.pids),
2509
+ buildSlots: nonNegativeResourceValue(resources?.buildSlots, defaults.buildSlots),
2510
+ };
2511
+ }
2512
+ function positiveResourceValue(value, fallback) {
2513
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
2514
+ }
2515
+ function nonNegativeResourceValue(value, fallback) {
2516
+ return Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
2517
+ }
2518
+ function configuredInteger(name, fallback, minimum, maximum) {
2519
+ const parsed = Number.parseInt(process.env[name] ?? "", 10);
2520
+ return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2521
+ }
2522
+ /**
2523
+ * Today's max attempts and adaptive memory reserve for this host, before
2524
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
2525
+ * (decision 0014 treats those as bounds on the server's values).
2526
+ */
2527
+ export function hostCapacityLimitDefaults(capacityResourceSample) {
2528
+ const configuration = loadHostCapacityConfiguration(capacityResourceSample);
2529
+ return {
2530
+ maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
2531
+ memoryReserveBytes: configuration.adaptiveHostReserveBytes,
2532
+ };
2533
+ }
2534
+ function loadHostCapacityConfiguration(capacityResourceSample) {
2535
+ const sampledCpuCount = capacityResourceSample
2536
+ ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
2537
+ : os.cpus().length;
2538
+ const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2539
+ const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2540
+ const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
2541
+ const adaptiveOptions = {
2542
+ floorBytes: reserveFloorBytes,
2543
+ ceilingBytes: reserveCeilingBytes,
2544
+ percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
2545
+ };
2546
+ const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2547
+ ...adaptiveOptions,
2548
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2549
+ });
2550
+ const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
2551
+ const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
2552
+ const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
2553
+ return {
2554
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
2555
+ hostReserveBytes,
2556
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
2557
+ defaultHardMaxAttempts,
2558
+ adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
2559
+ reserveFloorBytes,
2560
+ idleReserveOverrideBytes,
2561
+ cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2562
+ workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2563
+ memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2564
+ memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2565
+ };
2566
+ }
2567
+ /**
2568
+ * The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
2569
+ * clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
2570
+ */
2571
+ function idleHostReserveBytesFor(hostReserveBytes, configuration) {
2572
+ const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
2573
+ const override = configuration.idleReserveOverrideBytes;
2574
+ return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
2575
+ }
2576
+ function configuredOptionalInteger(name, minimum, maximum) {
2577
+ const raw = process.env[name];
2578
+ if (raw === undefined || raw.trim().length === 0)
2579
+ return null;
2580
+ const parsed = Number.parseInt(raw, 10);
2581
+ return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : null;
2582
+ }
2583
+ function configuredNumber(name, fallback, minimum, maximum) {
2584
+ const parsed = Number(process.env[name] ?? "");
2585
+ return Number.isFinite(parsed) && parsed > 0
2586
+ ? Math.max(minimum, Math.min(maximum, parsed))
2587
+ : fallback;
2588
+ }
2589
+ function resourceSlots(available, requested) {
2590
+ if (requested <= 0)
2591
+ return Number.MAX_SAFE_INTEGER;
2592
+ return Math.max(0, Math.floor(available / requested));
2593
+ }
2594
+ function removeWaiter(waiters, waiter) {
2595
+ const index = waiters.indexOf(waiter);
2596
+ if (index >= 0)
2597
+ waiters.splice(index, 1);
2598
+ }
1288
2599
  function capacityProject(projects, repoId) {
1289
2600
  const normalized = repoId.trim().toLowerCase();
1290
2601
  const existing = projects.get(normalized);
@@ -1327,6 +2638,9 @@ function repoIdFromProjectSingletonKey(key) {
1327
2638
  function sameSingletonOwner(left, right) {
1328
2639
  return left?.dispatchAttemptId === right.dispatchAttemptId && left.fencingToken === right.fencingToken;
1329
2640
  }
2641
+ function hostRuntimeOwnerKey(owner) {
2642
+ return `${owner.dispatchAttemptId}:${owner.fencingToken}`;
2643
+ }
1330
2644
  function hostPortOwner(lease) {
1331
2645
  const processSupervisorId = lease.resources.processSupervisorId;
1332
2646
  if (!processSupervisorId) {
@@ -1375,6 +2689,14 @@ async function releaseAdapterResources(cleanups) {
1375
2689
  if (firstError !== undefined)
1376
2690
  throw firstError;
1377
2691
  }
2692
+ async function removeHostAttemptRoot(attemptRoot) {
2693
+ await fs.rm(attemptRoot, {
2694
+ recursive: true,
2695
+ force: true,
2696
+ maxRetries: 10,
2697
+ retryDelay: 100,
2698
+ });
2699
+ }
1378
2700
  function cancellationError(signal) {
1379
2701
  return new Error(String(signal?.reason ?? "Dispatch cancelled while waiting for host runtime singleton ownership."));
1380
2702
  }
@@ -1384,9 +2706,25 @@ function validHostRuntimeLedger(value) {
1384
2706
  const ledger = value;
1385
2707
  return ledger.schemaVersion === 1
1386
2708
  && (ledger.repoId === undefined || /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu.test(ledger.repoId))
2709
+ && (ledger.attemptRootIdentity === undefined
2710
+ || validSerializedHostAttemptRootIdentity(ledger.attemptRootIdentity))
1387
2711
  && validRuntimeIsolationLease(ledger.runtimeLease)
1388
2712
  && ledger.runtimeLease.mode === "host";
1389
2713
  }
2714
+ function validSerializedHostAttemptRootIdentity(value) {
2715
+ if (typeof value !== "object" || value === null)
2716
+ return false;
2717
+ const identity = value;
2718
+ return /^-?\d{1,64}$/u.test(identity.dev) && /^-?\d{1,64}$/u.test(identity.ino);
2719
+ }
2720
+ function serializeHostAttemptRootIdentity(identity) {
2721
+ return { dev: identity.dev.toString(), ino: identity.ino.toString() };
2722
+ }
2723
+ function deserializeHostAttemptRootIdentity(identity) {
2724
+ return identity && validSerializedHostAttemptRootIdentity(identity)
2725
+ ? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
2726
+ : null;
2727
+ }
1390
2728
  function validHostProcessSupervisorMetadata(value, lease) {
1391
2729
  if (typeof value !== "object" || value === null)
1392
2730
  return false;
@@ -1435,6 +2773,11 @@ function clearAdmissionDeadline(waiter) {
1435
2773
  clearTimeout(waiter.deadlineTimer);
1436
2774
  waiter.deadlineTimer = null;
1437
2775
  }
2776
+ function clearCapacityRecheck(waiter) {
2777
+ if (waiter.capacityRecheckTimer)
2778
+ clearInterval(waiter.capacityRecheckTimer);
2779
+ waiter.capacityRecheckTimer = null;
2780
+ }
1438
2781
  async function ensurePrivateDirectory(directory) {
1439
2782
  await fs.mkdir(directory, { recursive: true, mode: 0o700 });
1440
2783
  if (process.platform !== "win32")