@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.724427ea7be8

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 (271) hide show
  1. package/README.md +144 -3
  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 +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  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 +9 -0
  15. package/dist/bridge/bridge.service.d.ts +101 -15
  16. package/dist/bridge/bridge.service.js +472 -345
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  19. package/dist/bridge/dispatch-result-outbox.js +31 -6
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +17 -0
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  33. package/dist/cleanup/cleanup-wip.js +66 -0
  34. package/dist/cleanup/cleanup.service.d.ts +20 -1
  35. package/dist/cleanup/cleanup.service.js +150 -169
  36. package/dist/cleanup/cleanup.types.d.ts +6 -0
  37. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  38. package/dist/cleanup/forge-owned-paths.js +53 -0
  39. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  40. package/dist/cleanup/host-runtime-ledger.js +130 -0
  41. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  42. package/dist/cleanup/managed-branch-sweep.js +111 -0
  43. package/dist/cli/cli.help.js +74 -12
  44. package/dist/cli/cli.service.d.ts +19 -10
  45. package/dist/cli/cli.service.js +152 -187
  46. package/dist/cli/idle-status.d.ts +84 -0
  47. package/dist/cli/idle-status.js +181 -0
  48. package/dist/cli/local-config.d.ts +6 -0
  49. package/dist/cli/local-config.js +32 -4
  50. package/dist/cli/provider-cli-detection.d.ts +10 -0
  51. package/dist/cli/provider-cli-detection.js +160 -0
  52. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  54. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  55. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  56. package/dist/runtime/attempt-process-supervisor.d.ts +21 -0
  57. package/dist/runtime/attempt-process-supervisor.js +62 -6
  58. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  59. package/dist/runtime/docker-engine-probe.js +7 -0
  60. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  61. package/dist/runtime/dotnet-build-outputs.js +402 -0
  62. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  64. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  65. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  66. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  67. package/dist/runtime/host-database-capability-boundary.js +1 -0
  68. package/dist/runtime/host-facts.d.ts +36 -0
  69. package/dist/runtime/host-facts.js +95 -0
  70. package/dist/runtime/host-load-admission.d.ts +67 -0
  71. package/dist/runtime/host-load-admission.js +99 -0
  72. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  73. package/dist/runtime/host-load-child-environment.js +76 -0
  74. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  75. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  76. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  77. package/dist/runtime/host-load-governor-config.js +83 -0
  78. package/dist/runtime/host-load-governor.d.ts +186 -0
  79. package/dist/runtime/host-load-governor.js +632 -0
  80. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  81. package/dist/runtime/host-load-ledger-lock.js +187 -0
  82. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  83. package/dist/runtime/host-load-runtime-settings.js +80 -0
  84. package/dist/runtime/host-load-sampler.d.ts +156 -0
  85. package/dist/runtime/host-load-sampler.js +298 -0
  86. package/dist/runtime/host-load-step-class.d.ts +70 -0
  87. package/dist/runtime/host-load-step-class.js +161 -0
  88. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  89. package/dist/runtime/host-load-step-reaper.js +95 -0
  90. package/dist/runtime/host-load-step-run.d.ts +73 -0
  91. package/dist/runtime/host-load-step-run.js +102 -0
  92. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  93. package/dist/runtime/host-load-test-slot.js +81 -0
  94. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  95. package/dist/runtime/host-load-token-ledger.js +453 -0
  96. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  97. package/dist/runtime/host-load-windows-cpu.js +85 -0
  98. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  99. package/dist/runtime/host-pressure-stall.js +168 -0
  100. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  101. package/dist/runtime/host-runtime-contract.js +35 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +76 -5
  103. package/dist/runtime/host-runtime-lease.js +322 -129
  104. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  105. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  106. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  107. package/dist/runtime/host-runtime-promotion.js +48 -0
  108. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  109. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  110. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  111. package/dist/runtime/host-runtime-requirements.js +117 -0
  112. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  113. package/dist/runtime/managed-command-teardown.js +596 -0
  114. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  115. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  116. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  117. package/dist/runtime/playwright-browser-cache.js +227 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  119. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  120. package/dist/runtime/runner-settings.d.ts +104 -0
  121. package/dist/runtime/runner-settings.js +236 -0
  122. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  123. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  124. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  125. package/dist/sandbox/host-capacity-broker.js +336 -0
  126. package/dist/sandbox/managed-branch.d.ts +13 -0
  127. package/dist/sandbox/managed-branch.js +90 -0
  128. package/dist/sandbox/provider-auth/codex.js +11 -11
  129. package/dist/sandbox/runtime.d.ts +10 -1
  130. package/dist/sandbox/runtime.js +47 -8
  131. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  132. package/dist/sandbox/sandbox-cgroups.js +42 -0
  133. package/dist/session/architect-waits.d.ts +2 -0
  134. package/dist/session/architect-waits.js +138 -0
  135. package/dist/session/managed-attempt-tools.d.ts +27 -7
  136. package/dist/session/managed-attempt-tools.js +406 -123
  137. package/dist/session/managed-build-coordinator.d.ts +17 -1
  138. package/dist/session/managed-build-coordinator.js +14 -1
  139. package/dist/session/managed-build-receipt.d.ts +5 -0
  140. package/dist/session/managed-build-receipt.js +8 -3
  141. package/dist/session/managed-command-host-load.d.ts +47 -0
  142. package/dist/session/managed-command-host-load.js +83 -0
  143. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  144. package/dist/session/mcp-argument-coercion.js +121 -0
  145. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  146. package/dist/session/phase-completion.artifacts.js +100 -26
  147. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  148. package/dist/session/phase-completion.command-validation.js +77 -0
  149. package/dist/session/phase-completion.d.ts +12 -0
  150. package/dist/session/phase-completion.helpers.js +13 -12
  151. package/dist/session/phase-completion.js +5 -0
  152. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  153. package/dist/session/phase-completion.mcp-args.js +156 -0
  154. package/dist/session/phase-completion.prompts.js +6 -1
  155. package/dist/session/phase-completion.runtime.d.ts +5 -11
  156. package/dist/session/phase-completion.runtime.js +111 -230
  157. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  158. package/dist/session/phase-completion.schema-parts.js +188 -0
  159. package/dist/session/phase-completion.schemas.d.ts +3 -3
  160. package/dist/session/phase-completion.schemas.js +208 -231
  161. package/dist/session/phase-completion.validation.d.ts +2 -3
  162. package/dist/session/phase-completion.validation.js +49 -93
  163. package/dist/session/pre-publication-host-load.d.ts +27 -0
  164. package/dist/session/pre-publication-host-load.js +111 -0
  165. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  166. package/dist/session/pre-publication-native-postgres.js +111 -0
  167. package/dist/session/pre-publication-pass.d.ts +61 -0
  168. package/dist/session/pre-publication-pass.js +148 -0
  169. package/dist/session/pre-publication-process.d.ts +23 -0
  170. package/dist/session/pre-publication-process.js +109 -0
  171. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  172. package/dist/session/pre-publication-skipped-tests.js +109 -0
  173. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  174. package/dist/session/pre-publication-step-execution.js +50 -0
  175. package/dist/session/pre-publication-validation.d.ts +37 -21
  176. package/dist/session/pre-publication-validation.js +228 -219
  177. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  178. package/dist/session/provider-cli/claude-background-work.js +181 -0
  179. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  180. package/dist/session/provider-cli/host-build-lock.js +30 -0
  181. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  182. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  183. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  184. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  185. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  186. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  188. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  190. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  191. package/dist/session/provider-cli/provider-cli.process.d.ts +46 -31
  192. package/dist/session/provider-cli/provider-cli.process.js +286 -403
  193. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  194. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  195. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  196. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  197. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  198. package/dist/session/provider-cli/provider-cli.service.js +207 -192
  199. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  201. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  203. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  205. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  206. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  207. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  208. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  209. package/dist/session/provider-cli/provider-output-state.js +15 -0
  210. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  211. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  212. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  213. package/dist/session/publishable-worktree-changes.js +193 -0
  214. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  215. package/dist/session/qa-sidecar-validation.js +28 -0
  216. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  217. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  218. package/dist/session/session-redaction.js +31 -181
  219. package/dist/session/session.base.d.ts +9 -1
  220. package/dist/session/session.service.d.ts +11 -2
  221. package/dist/session/session.service.js +189 -69
  222. package/dist/session/session.types.d.ts +3 -0
  223. package/dist/session/session.types.js +15 -3
  224. package/dist/session/sidecar-json-shape.d.ts +31 -0
  225. package/dist/session/sidecar-json-shape.js +217 -0
  226. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  227. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  228. package/dist/shared/fs/file-identity.d.ts +10 -0
  229. package/dist/shared/fs/file-identity.js +15 -0
  230. package/dist/shared/fs/replace-file.d.ts +7 -0
  231. package/dist/shared/fs/replace-file.js +33 -0
  232. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  233. package/dist/shared/process/host-process-recovery.js +23 -3
  234. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  235. package/dist/shared/process/host-process-supervisor.js +67 -15
  236. package/dist/shared/process/process-tree.d.ts +52 -0
  237. package/dist/shared/process/process-tree.js +144 -0
  238. package/dist/shared/process/process.d.ts +67 -0
  239. package/dist/shared/process/process.js +213 -11
  240. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  241. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  242. package/dist/shared/process/windows-launch.d.ts +18 -0
  243. package/dist/shared/process/windows-launch.js +68 -0
  244. package/dist/shared/provider-capabilities.js +14 -7
  245. package/dist/version.d.ts +1 -1
  246. package/dist/version.js +1 -1
  247. package/dist/worktree/dependency-warmer.d.ts +25 -0
  248. package/dist/worktree/dependency-warmer.js +46 -10
  249. package/dist/worktree/orphan-relink.d.ts +19 -0
  250. package/dist/worktree/orphan-relink.js +106 -0
  251. package/dist/worktree/wip-git.d.ts +33 -0
  252. package/dist/worktree/wip-git.js +122 -0
  253. package/dist/worktree/wip-refs.d.ts +62 -0
  254. package/dist/worktree/wip-refs.js +119 -0
  255. package/dist/worktree/wip-restore.d.ts +38 -0
  256. package/dist/worktree/wip-restore.js +190 -0
  257. package/dist/worktree/wip-snapshot.d.ts +50 -0
  258. package/dist/worktree/wip-snapshot.js +268 -0
  259. package/dist/worktree/worktree-inputs.d.ts +8 -0
  260. package/dist/worktree/worktree-inputs.js +134 -0
  261. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  262. package/dist/worktree/worktree-origin-sync.js +127 -0
  263. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  264. package/dist/worktree/worktree-wip-events.js +98 -0
  265. package/dist/worktree/worktree-wip.d.ts +50 -0
  266. package/dist/worktree/worktree-wip.js +185 -0
  267. package/dist/worktree/worktree.base.d.ts +7 -1
  268. package/dist/worktree/worktree.service.d.ts +36 -5
  269. package/dist/worktree/worktree.service.js +124 -155
  270. package/dist/worktree/worktree.types.d.ts +38 -0
  271. package/package.json +2 -2
@@ -7,12 +7,12 @@ import { assertHostAttemptRootIdentity, retainHostDiagnostics } from "./host-dia
7
7
  import { assertHostExecutionRoot, compactHostAttemptId } from "./host-execution-root.js";
8
8
  import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
9
9
  import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
+ import { ForgeFailureError } from "../session/session.types.js";
10
11
  import { resolveExistingDirectoryPath } from "../shared/path/path.js";
11
12
  import { formatBytes } from "../shared/format/format-bytes.js";
12
- import { redactText } from "../shared/redaction/redaction.js";
13
13
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
14
14
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
15
- import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
15
+ import { hostPortEnvironment, loadHostRuntimeContract, newAttemptApiMasterKey, withAttemptApiMasterKey, } from "./host-runtime-contract.js";
16
16
  import { HostPortBroker, } from "./host-port-broker.js";
17
17
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
18
18
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
@@ -21,16 +21,19 @@ import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
21
21
  import { HostListenerInspector } from "./host-listener-inspector.js";
22
22
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
23
23
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
24
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
24
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
25
25
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
26
26
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
27
27
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
28
- import { readCanonicalSourceFile } from "./canonical-source-file.js";
29
- import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
28
+ import { logHostRuntimeStatus, recoverPersistedHostProcesses, replaceHostRuntimeLedgerFile, retryDegradedHostRelease, } from "./host-runtime-ledger-recovery.js";
30
29
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
31
- import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
30
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, executeAspNetRuntimeBuild, resolveWorktreeCommitSha, supervisedRuntimeLaunchArguments, } from "./aspnet-runtime-prebuild.js";
31
+ import { HostLoadGovernor } from "./host-load-governor.js";
32
+ import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
33
+ import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
34
+ import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
35
+ import { HostLoadSampler } from "./host-load-sampler.js";
32
36
  const hostCapacityWaiterScanLimit = 64;
33
- const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
34
37
  export class HostRuntimeLeaseManager {
35
38
  stateRoot;
36
39
  processSupervisors;
@@ -60,10 +63,18 @@ export class HostRuntimeLeaseManager {
60
63
  workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
61
64
  portBroker;
62
65
  nodeAdapter;
66
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
63
67
  capacityConfiguration;
64
68
  memoryAvailability;
65
69
  executionRoot;
66
- constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null) {
70
+ /** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
71
+ hostLoadGovernor;
72
+ requirementsCheck = null;
73
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
74
+ setRequirementsCheck(check) {
75
+ this.requirementsCheck = check;
76
+ }
77
+ constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null, hostLoad = null) {
67
78
  this.stateRoot = stateRoot;
68
79
  this.processSupervisors = processSupervisors;
69
80
  this.processRunner = processRunner;
@@ -73,6 +84,7 @@ export class HostRuntimeLeaseManager {
73
84
  this.processRecovery = processRecovery;
74
85
  this.capacityResourceSample = capacityResourceSample;
75
86
  this.databaseBroker = databaseBroker;
87
+ this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
76
88
  this.executionRoot = path.resolve(executionRoot ?? stateRoot);
77
89
  if (executionRoot !== undefined)
78
90
  assertHostExecutionRoot(this.executionRoot);
@@ -82,7 +94,40 @@ export class HostRuntimeLeaseManager {
82
94
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
83
95
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
84
96
  }
97
+ /** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
98
+ capacityLimitDefaults() {
99
+ return {
100
+ maxConcurrentAttempts: this.capacityConfiguration.defaultHardMaxAttempts,
101
+ memoryReserveBytes: this.capacityConfiguration.adaptiveHostReserveBytes,
102
+ };
103
+ }
104
+ /**
105
+ * Decision 0014: the bridge's effective max attempts and memory reserve. They
106
+ * apply from the next attempt admission; admitted attempts keep their
107
+ * reservations and are never preempted, even when the new limit is lower than
108
+ * what already runs. The idle reserve follows the reserve as at startup.
109
+ */
110
+ applyCapacityLimits(limits) {
111
+ const current = this.capacityConfiguration;
112
+ const hardMaxAttempts = Math.max(1, Math.min(32, Math.floor(limits.maxConcurrentAttempts)));
113
+ const hostReserveBytes = Math.max(512 * 1024 ** 2, Math.floor(limits.memoryReserveBytes));
114
+ if (hardMaxAttempts === current.hardMaxAttempts && hostReserveBytes === current.hostReserveBytes)
115
+ return;
116
+ this.capacityConfiguration = {
117
+ ...current,
118
+ hardMaxAttempts,
119
+ hostReserveBytes,
120
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, current),
121
+ };
122
+ // A raised limit may admit queued attempts now rather than at their next recheck.
123
+ this.drainAdmissionWaiters();
124
+ }
125
+ hostLoadChildEnvironment() {
126
+ return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
127
+ }
85
128
  async reap(options) {
129
+ // Heavy-step tokens whose owner died or whose lease lapsed are returned first.
130
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
86
131
  await this.refreshKnownPromotions();
87
132
  const recoveredAttempts = [];
88
133
  const report = {
@@ -114,19 +159,16 @@ export class HostRuntimeLeaseManager {
114
159
  }
115
160
  const active = this.active.get(lease.dispatchAttemptId);
116
161
  if (active) {
162
+ // A live lease is never released here, however long past its expiry; a degraded one
163
+ // is retried under its own fence until teardown proves its process tree stopped.
117
164
  if (active.lease.state !== "degraded")
118
165
  continue;
119
166
  report.examined += 1;
120
- try {
121
- const released = await this.release(lease.dispatchAttemptId, lease.fencingToken);
122
- if (released?.state === "released")
123
- report.reaped += 1;
124
- else
125
- report.degraded += 1;
126
- }
127
- catch {
167
+ const released = await retryDegradedHostRelease(active.lease, () => this.release(lease.dispatchAttemptId, lease.fencingToken), options.log ?? logHostRuntimeStatus);
168
+ if (released)
169
+ report.reaped += 1;
170
+ else
128
171
  report.degraded += 1;
129
- }
130
172
  continue;
131
173
  }
132
174
  const staleInstance = lease.runnerInstanceId !== options.runnerInstanceId;
@@ -141,7 +183,7 @@ export class HostRuntimeLeaseManager {
141
183
  if (!attemptRootIdentity) {
142
184
  throw new Error("host_runtime_reaper_invalid: original attempt-root identity is unavailable.");
143
185
  }
144
- outcomes = await this.recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity);
186
+ outcomes = await recoverPersistedHostProcesses(lease, attemptRoot, this.attemptRoot(lease.dispatchAttemptId), attemptRootIdentity, this.processRecovery);
145
187
  }
146
188
  catch {
147
189
  await this.markLedgerDegraded(ledger);
@@ -207,6 +249,11 @@ export class HostRuntimeLeaseManager {
207
249
  // drop that met a lingering session) are removed once no live lease holds them.
208
250
  // A degraded lease may still own running processes after a restart, so its database is kept.
209
251
  await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
252
+ // Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
253
+ // ended with a crashed bridge or MCP server) are returned once no live lease holds
254
+ // their attempt; a degraded lease may still own the running step, so its tokens stay.
255
+ await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
256
+ || (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
210
257
  return report;
211
258
  }
212
259
  snapshot() {
@@ -924,6 +971,15 @@ export class HostRuntimeLeaseManager {
924
971
  let attemptRootIdentity = null;
925
972
  try {
926
973
  const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
974
+ // Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
975
+ // API learns the requirements in the first place.
976
+ const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
977
+ ? []
978
+ : this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
979
+ if (unmetRequirements.length > 0) {
980
+ // Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
981
+ throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
982
+ }
927
983
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
928
984
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
929
985
  }
@@ -1088,6 +1144,8 @@ export class HostRuntimeLeaseManager {
1088
1144
  parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1089
1145
  processSupervisor,
1090
1146
  adapterCleanups: [],
1147
+ adapterCleanupsByPort: new Map(),
1148
+ restartingConfiguredProject: false,
1091
1149
  pendingAdapterLaunches: new Map(),
1092
1150
  runtimeResourcesReleased: false,
1093
1151
  releasing: false,
@@ -1150,6 +1208,15 @@ export class HostRuntimeLeaseManager {
1150
1208
  await this.writeLedger(renewed);
1151
1209
  }
1152
1210
  async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1211
+ return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
1212
+ }
1213
+ /**
1214
+ * Launches the configured project. Only the first launch, from the admitted commit's clean
1215
+ * source, may record parallel-safety proof: a restart serves the workspace after the provider
1216
+ * edited it, and a proof observed there would be stored under the admitted commit and could
1217
+ * move this or a later attempt at that commit into shared admission for source it never ran.
1218
+ */
1219
+ async launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, promote) {
1153
1220
  const active = this.active.get(dispatchAttemptId);
1154
1221
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1155
1222
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
@@ -1171,6 +1238,11 @@ export class HostRuntimeLeaseManager {
1171
1238
  executionClass: active.executionClass,
1172
1239
  };
1173
1240
  }
1241
+ const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
1242
+ // A host without the project's pinned browsers fails here, before any database,
1243
+ // build, launch, or promotion work that the attempt would otherwise waste.
1244
+ if (playwrightConfig)
1245
+ await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
1174
1246
  const owner = hostPortOwner(active.lease);
1175
1247
  const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
1176
1248
  if (!logDirectory)
@@ -1196,8 +1268,9 @@ export class HostRuntimeLeaseManager {
1196
1268
  data: { database: active.databaseCapability.databaseName },
1197
1269
  });
1198
1270
  }
1199
- // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1200
- const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1271
+ const apiMasterKey = attemptApiMasterKey(active);
1272
+ // Runtime output is persisted to attempt logs; the database login and master key it may print are redacted.
1273
+ const capabilitySecrets = [...attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString), apiMasterKey];
1201
1274
  const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1202
1275
  for (const configuredPort of configuredPorts) {
1203
1276
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
@@ -1207,7 +1280,7 @@ export class HostRuntimeLeaseManager {
1207
1280
  };
1208
1281
  const prebuild = createAspNetRuntimePrebuildPlan({
1209
1282
  command: configuredPort.launch.command,
1210
- args: configuredPort.launch.args,
1283
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1211
1284
  cwd: workingDirectory,
1212
1285
  worktreePath: active.lease.worktreePath,
1213
1286
  environment: buildEnvironment,
@@ -1218,9 +1291,31 @@ export class HostRuntimeLeaseManager {
1218
1291
  await onProjectCheckpoint?.({
1219
1292
  code: "host_runtime_build_started",
1220
1293
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1221
- data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1294
+ data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath, output_directory: prebuild.outputDirectory },
1222
1295
  });
1223
- const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal, capabilitySecrets), signal);
1296
+ let hostLoadWaitMs = null;
1297
+ const build = await ensureAspNetRuntimePrebuilt(prebuild,
1298
+ // Only a real build (not a verified cache hit) takes a host load token.
1299
+ async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
1300
+ classification: aspNetPrebuildStepClass,
1301
+ label: prebuild.projectPath,
1302
+ dispatchAttemptId,
1303
+ priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
1304
+ signal: buildSignal,
1305
+ onWaiting: async (decision) => await onProjectCheckpoint?.({
1306
+ code: "host_runtime_build_waiting_for_host_capacity",
1307
+ message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
1308
+ data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
1309
+ }),
1310
+ }, async (waitMs, control) => {
1311
+ hostLoadWaitMs = waitMs;
1312
+ // A reclaimed token stops the build: its capacity is no longer reserved. So does a
1313
+ // build whose process tree cannot be recorded on its token (a reclaim could not stop it).
1314
+ const unrecorded = new AbortController();
1315
+ const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
1316
+ return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
1317
+ .catch((error) => { unrecorded.abort(error); }));
1318
+ }), signal);
1224
1319
  await onProjectCheckpoint?.({
1225
1320
  code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1226
1321
  message: build.cacheHit
@@ -1230,19 +1325,18 @@ export class HostRuntimeLeaseManager {
1230
1325
  input_commit_sha: active.inputCommitSha,
1231
1326
  build_fingerprint: build.fingerprint,
1232
1327
  receipt_path: build.receiptPath,
1328
+ ...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
1233
1329
  },
1234
1330
  });
1235
1331
  }
1236
1332
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1237
1333
  command: configuredPort.launch.command,
1238
- args: configuredPort.launch.args,
1334
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1239
1335
  cwd: workingDirectory,
1240
- environment: {
1241
- ...buildEnvironment,
1242
- },
1336
+ environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1243
1337
  }, launcher, signal);
1244
1338
  }
1245
- const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1339
+ const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
1246
1340
  const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1247
1341
  const playwright = active.runtimeContract.contract.runtime.playwright;
1248
1342
  if (!playwright) {
@@ -1281,6 +1375,94 @@ export class HostRuntimeLeaseManager {
1281
1375
  executionClass: active.executionClass,
1282
1376
  };
1283
1377
  }
1378
+ /**
1379
+ * Relaunches the configured project so it serves the current workspace. Every
1380
+ * configured process stops (the API port changes, so the dev server's proxy target
1381
+ * must change with it), its port reservation is released and dropped from the
1382
+ * persisted lease, and the regular start path runs again, including the ASP.NET
1383
+ * prebuild, whose receipt rebuilds only when the sources changed.
1384
+ */
1385
+ async restartConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1386
+ const active = this.active.get(dispatchAttemptId);
1387
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1388
+ throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1389
+ }
1390
+ if (signal?.aborted)
1391
+ throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
1392
+ if (active.restartingConfiguredProject) {
1393
+ throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
1394
+ }
1395
+ active.restartingConfiguredProject = true;
1396
+ // Release cancels the whole restart through this controller and waits for it to settle.
1397
+ const controller = linkedAbortController(signal);
1398
+ const promise = this.runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, controller.signal, onProjectCheckpoint);
1399
+ const restart = { controller, promise };
1400
+ active.configuredProjectRestart = restart;
1401
+ try {
1402
+ return await promise;
1403
+ }
1404
+ finally {
1405
+ // The controller is not aborted on settle: adapters this restart launched keep it as their
1406
+ // parent signal for as long as they run, exactly as they would keep the caller's signal.
1407
+ if (active.configuredProjectRestart === restart)
1408
+ active.configuredProjectRestart = null;
1409
+ active.restartingConfiguredProject = false;
1410
+ }
1411
+ }
1412
+ async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1413
+ // The relaunch keeps the admission granted at start. A workspace contract that changed only its
1414
+ // launch environment is adopted; any other change throws host_runtime_contract_changed.
1415
+ const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
1416
+ active.runtimeContract = readmitted.runtimeContract;
1417
+ active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
1418
+ if (readmitted.changed) {
1419
+ 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." });
1420
+ }
1421
+ const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1422
+ const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
1423
+ if (pendingPort) {
1424
+ throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
1425
+ }
1426
+ const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
1427
+ if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
1428
+ // The generated Playwright config targets the stack being stopped. If the restart fails, no
1429
+ // config may be left pointing at ports another attempt can now be assigned.
1430
+ await this.playwrightAdapter.discardOverlay(temporaryDirectory);
1431
+ }
1432
+ await this.stopConfiguredProject(active, portNames);
1433
+ // Keeps whatever admission the attempt holds; see launchConfiguredProject.
1434
+ const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
1435
+ if (active.releasing) {
1436
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1437
+ }
1438
+ return restarted;
1439
+ }
1440
+ /** Stops configured project processes in reverse launch order and releases their ports. */
1441
+ async stopConfiguredProject(active, portNames) {
1442
+ const launched = active.lease.resources.ports
1443
+ .map(port => port.name)
1444
+ .filter(name => portNames.includes(name))
1445
+ .reverse();
1446
+ for (const name of launched) {
1447
+ if (active.releasing) {
1448
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1449
+ }
1450
+ const cleanup = active.adapterCleanupsByPort.get(name);
1451
+ if (!cleanup) {
1452
+ throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
1453
+ }
1454
+ // A failed stop keeps the cleanup and the port record for the fenced release retry.
1455
+ await cleanup();
1456
+ removeCleanup(active.adapterCleanups, cleanup);
1457
+ active.adapterCleanupsByPort.delete(name);
1458
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1459
+ ...active.lease.resources,
1460
+ ports: active.lease.resources.ports.filter(port => port.name !== name),
1461
+ });
1462
+ await this.writeLedger(runtimeLease);
1463
+ active.lease = runtimeLease;
1464
+ }
1465
+ }
1284
1466
  providerProcessRunner(dispatchAttemptId, fencingToken) {
1285
1467
  const active = this.active.get(dispatchAttemptId);
1286
1468
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
@@ -1368,6 +1550,7 @@ export class HostRuntimeLeaseManager {
1368
1550
  unlinkAbortController(controller, signal);
1369
1551
  };
1370
1552
  active.adapterCleanups.push(cleanup);
1553
+ active.adapterCleanupsByPort.set(portName, cleanup);
1371
1554
  try {
1372
1555
  if (active.releasing)
1373
1556
  throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
@@ -1390,6 +1573,8 @@ export class HostRuntimeLeaseManager {
1390
1573
  try {
1391
1574
  await cleanup();
1392
1575
  removeCleanup(active.adapterCleanups, cleanup);
1576
+ if (active.adapterCleanupsByPort.get(portName) === cleanup)
1577
+ active.adapterCleanupsByPort.delete(portName);
1393
1578
  }
1394
1579
  catch {
1395
1580
  // Preserve the cleanup and broker claim for the fenced release retry.
@@ -1414,6 +1599,9 @@ export class HostRuntimeLeaseManager {
1414
1599
  if (!preservePreparation)
1415
1600
  this.pendingRenewals.delete(dispatchAttemptId);
1416
1601
  if (!active) {
1602
+ // Queued steps are cancelled and running ones stopped; each returns its own
1603
+ // token once its processes are gone (never before, or capacity is reused early).
1604
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1417
1605
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1418
1606
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1419
1607
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
@@ -1423,18 +1611,42 @@ export class HostRuntimeLeaseManager {
1423
1611
  if (active.lease.fencingToken !== fencingToken)
1424
1612
  return null;
1425
1613
  active.releasing = true;
1614
+ // Attempt teardown cancels the attempt's queued heavy steps and stops its running
1615
+ // ones. Each running step (an ASP.NET prebuild, an install, a validation step)
1616
+ // returns its own token only after its processes have exited, so the capacity is
1617
+ // not reused while, say, a build is still being terminated.
1618
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1426
1619
  for (const pending of active.pendingAdapterLaunches.values()) {
1427
1620
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1428
1621
  }
1429
1622
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1623
+ const restart = active.configuredProjectRestart;
1624
+ if (restart) {
1625
+ restart.controller.abort("Host runtime release cancelled the configured project restart.");
1626
+ await restart.promise.catch(() => undefined);
1627
+ }
1430
1628
  await active.databaseProvision?.catch(() => undefined);
1431
- let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1432
- active.lease = releasing;
1433
- await this.writeLedger(releasing);
1629
+ // The releasing write is part of the fenced teardown: when it fails (Windows can refuse
1630
+ // to replace a ledger another handle is reading), the lease must end degraded so
1631
+ // maintenance retries it, never left nonterminal in memory where nothing retries it.
1632
+ let releasing = active.lease;
1434
1633
  try {
1634
+ releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1635
+ active.lease = releasing;
1636
+ await this.writeLedger(releasing);
1435
1637
  if (!active.runtimeResourcesReleased) {
1436
1638
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1639
+ // The attempt's MCP servers and process trees are stopped now; tokens they held
1640
+ // belong to dead owners and go back to the host budget at once, including any
1641
+ // without a recorded process tree (their steps were inside the stopped trees).
1642
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
1643
+ await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
1644
+ .catch(() => undefined);
1645
+ // This bridge's own steps whose trees only stopAll could prove gone (a supervised
1646
+ // validation step whose termination failed earlier) return their tokens now.
1647
+ await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1437
1648
  await releaseAdapterResources(active.adapterCleanups);
1649
+ active.adapterCleanupsByPort.clear();
1438
1650
  if (active.databaseCapability && this.databaseBroker) {
1439
1651
  // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1440
1652
  await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
@@ -1477,13 +1689,12 @@ export class HostRuntimeLeaseManager {
1477
1689
  if (!evidenceRetainedAtAttemptRoot) {
1478
1690
  await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1479
1691
  }
1480
- releasing = released;
1481
1692
  this.active.delete(dispatchAttemptId);
1482
1693
  this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1483
1694
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1484
1695
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1485
1696
  this.deleteAdmission(dispatchAttemptId, fencingToken);
1486
- return releasing;
1697
+ return released;
1487
1698
  }
1488
1699
  catch (error) {
1489
1700
  const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
@@ -1518,34 +1729,6 @@ export class HostRuntimeLeaseManager {
1518
1729
  }
1519
1730
  return ledgers;
1520
1731
  }
1521
- async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
1522
- const logsRoot = path.join(attemptRoot, "logs");
1523
- const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
1524
- if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
1525
- throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
1526
- }
1527
- await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
1528
- const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
1529
- const logsEntry = rootEntries.find(entry => entry.name === "logs");
1530
- if (!logsEntry)
1531
- return [];
1532
- if (logsEntry.kind !== "directory") {
1533
- throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1534
- }
1535
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1536
- const outcomes = [];
1537
- for (const entry of entries) {
1538
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1539
- continue;
1540
- const metadataPath = path.join(logsRoot, entry.name);
1541
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1542
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1543
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1544
- }
1545
- outcomes.push(await this.processRecovery.recover(value));
1546
- }
1547
- return outcomes;
1548
- }
1549
1732
  async markLedgerDegraded(ledger) {
1550
1733
  const lease = ledger.runtimeLease;
1551
1734
  if (lease.state === "released")
@@ -1618,7 +1801,7 @@ export class HostRuntimeLeaseManager {
1618
1801
  finally {
1619
1802
  await handle.close();
1620
1803
  }
1621
- await fs.rename(temporary, target);
1804
+ await replaceHostRuntimeLedgerFile(temporary, target);
1622
1805
  }
1623
1806
  catch (error) {
1624
1807
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -1919,6 +2102,18 @@ class AttemptSupervisedProviderProcessRunner {
1919
2102
  : new Set();
1920
2103
  const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
1921
2104
  this.onProcessTreeStarted();
2105
+ try {
2106
+ return await this.awaitProviderResult(child, baselineListeners, signal);
2107
+ }
2108
+ finally {
2109
+ // The provider tree, and the MCP server inside it, is gone. A managed command that
2110
+ // server started now has no supervisor and no receipt writer, so it must not keep
2111
+ // running into the next provider generation. This never rejects; a command it
2112
+ // cannot prove stopped is left to attempt teardown, which fails closed.
2113
+ await this.supervisor.stopOrphanedManagedCommands();
2114
+ }
2115
+ }
2116
+ async awaitProviderResult(child, baselineListeners, signal) {
1922
2117
  if (!this.enforceNoListeners)
1923
2118
  return await child.result;
1924
2119
  let settled = false;
@@ -2094,44 +2289,36 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2094
2289
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2095
2290
  return environment;
2096
2291
  }
2097
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = []) {
2098
- const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2099
- const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2100
- const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2101
- let stdoutTail = "";
2102
- let stderrTail = "";
2103
- const append = async (target, line) => {
2104
- await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2105
- };
2106
- const child = await supervisor.startChildReady(childName, {
2107
- command: plan.command,
2108
- args: plan.args,
2109
- cwd: plan.cwd,
2110
- env: plan.environment,
2111
- captureOutput: false,
2112
- }, {
2113
- onStdoutLine: async (line) => {
2114
- stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2115
- await append(stdoutLogPath, line);
2116
- },
2117
- onStderrLine: async (line) => {
2118
- stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2119
- await append(stderrLogPath, line);
2120
- },
2121
- }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2122
- const result = await child.result;
2123
- return {
2124
- exitCode: result.exitCode,
2125
- stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2126
- stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2127
- stdoutLogPath,
2128
- stderrLogPath,
2129
- };
2292
+ /**
2293
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
2294
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
2295
+ * stack is down: after its ports are released another attempt may be assigned them.
2296
+ */
2297
+ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2298
+ const keys = new Set([
2299
+ "FORGE_E2E_API_URL",
2300
+ "FORGE_E2E_WEB_URL",
2301
+ "FORGE_BASE_URL",
2302
+ "FORGE_PLAYWRIGHT_BASE_URL",
2303
+ // The generated Playwright config embeds the base URL.
2304
+ "FORGE_PLAYWRIGHT_CONFIG",
2305
+ ]);
2306
+ for (const port of runtimeContract.contract.runtime.ports) {
2307
+ const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
2308
+ keys.add(port.env);
2309
+ if (port.baseUrlEnv)
2310
+ keys.add(port.baseUrlEnv);
2311
+ keys.add(`FORGE_${normalizedName}_PORT`);
2312
+ keys.add(`FORGE_${normalizedName}_URL`);
2313
+ }
2314
+ return [...keys];
2130
2315
  }
2131
- function appendRuntimeBuildTail(current, value) {
2132
- if (!value)
2133
- return current;
2134
- return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
2316
+ /** The attempt's API master key: issued on first use, then the same for every relaunch of the attempt. */
2317
+ function attemptApiMasterKey(active) {
2318
+ return active.apiMasterKey ??= newAttemptApiMasterKey();
2319
+ }
2320
+ function anySignal(...signals) {
2321
+ return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2135
2322
  }
2136
2323
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
2137
2324
  if (executionClass === "analysis_only") {
@@ -2161,7 +2348,7 @@ function runtimeExecutionClass(dispatch) {
2161
2348
  ? "analysis_only"
2162
2349
  : "managed_runtime";
2163
2350
  }
2164
- function runtimeAdmissionPriority(dispatch) {
2351
+ export function runtimeAdmissionPriority(dispatch) {
2165
2352
  return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2166
2353
  || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2167
2354
  ? "background"
@@ -2233,6 +2420,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
2233
2420
  const parsed = Number.parseInt(process.env[name] ?? "", 10);
2234
2421
  return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2235
2422
  }
2423
+ /**
2424
+ * Today's max attempts and adaptive memory reserve for this host, before
2425
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
2426
+ * (decision 0014 treats those as bounds on the server's values).
2427
+ */
2428
+ export function hostCapacityLimitDefaults(capacityResourceSample) {
2429
+ const configuration = loadHostCapacityConfiguration(capacityResourceSample);
2430
+ return {
2431
+ maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
2432
+ memoryReserveBytes: configuration.adaptiveHostReserveBytes,
2433
+ };
2434
+ }
2236
2435
  function loadHostCapacityConfiguration(capacityResourceSample) {
2237
2436
  const sampledCpuCount = capacityResourceSample
2238
2437
  ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
@@ -2240,23 +2439,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
2240
2439
  const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2241
2440
  const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2242
2441
  const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
2243
- const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2244
- explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2442
+ const adaptiveOptions = {
2245
2443
  floorBytes: reserveFloorBytes,
2246
2444
  ceilingBytes: reserveCeilingBytes,
2247
2445
  percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
2446
+ };
2447
+ const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2448
+ ...adaptiveOptions,
2449
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2248
2450
  });
2249
- const minimumIdleReserveBytes = Math.min(hostReserveBytes, reserveFloorBytes);
2451
+ const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
2452
+ const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
2453
+ const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
2250
2454
  return {
2251
- hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2))), 1, 32),
2455
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
2252
2456
  hostReserveBytes,
2253
- idleHostReserveBytes: configuredInteger("FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES", minimumIdleReserveBytes, 512 * 1024 ** 2, hostReserveBytes),
2457
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
2458
+ defaultHardMaxAttempts,
2459
+ adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
2460
+ reserveFloorBytes,
2461
+ idleReserveOverrideBytes,
2254
2462
  cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2255
2463
  workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2256
2464
  memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2257
2465
  memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2258
2466
  };
2259
2467
  }
2468
+ /**
2469
+ * The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
2470
+ * clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
2471
+ */
2472
+ function idleHostReserveBytesFor(hostReserveBytes, configuration) {
2473
+ const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
2474
+ const override = configuration.idleReserveOverrideBytes;
2475
+ return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
2476
+ }
2260
2477
  function configuredOptionalInteger(name, minimum, maximum) {
2261
2478
  const raw = process.env[name];
2262
2479
  if (raw === undefined || raw.trim().length === 0)
@@ -2409,30 +2626,6 @@ function deserializeHostAttemptRootIdentity(identity) {
2409
2626
  ? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
2410
2627
  : null;
2411
2628
  }
2412
- function validHostProcessSupervisorMetadata(value, lease) {
2413
- if (typeof value !== "object" || value === null)
2414
- return false;
2415
- const metadata = value;
2416
- return metadata.schemaVersion === 1
2417
- && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
2418
- && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
2419
- && Number.isSafeInteger(metadata.rootPid)
2420
- && metadata.rootPid > 0
2421
- && Number.isFinite(Date.parse(metadata.rootCreatedAt))
2422
- && (metadata.rootIdentity == null
2423
- || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
2424
- && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
2425
- && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
2426
- && metadata.runtimeLeaseId === lease.executionLeaseId
2427
- && metadata.dispatchAttemptId === lease.dispatchAttemptId
2428
- && metadata.fencingToken === lease.fencingToken
2429
- && Number.isSafeInteger(metadata.bridgePid)
2430
- && metadata.bridgePid > 0;
2431
- }
2432
- function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
2433
- const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
2434
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2435
- }
2436
2629
  function transitionHostLeaseForCleanup(lease, state) {
2437
2630
  if (lease.state === state || lease.state === "released")
2438
2631
  return lease;