@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.0098fdb4e213

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