@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 0.1.4-dev.028808a841c8

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 (243) hide show
  1. package/README.md +165 -1
  2. package/dist/bridge/bridge-chat.types.d.ts +111 -0
  3. package/dist/bridge/bridge-chat.types.js +401 -0
  4. package/dist/bridge/bridge.base.d.ts +9 -1
  5. package/dist/bridge/bridge.service.d.ts +140 -3
  6. package/dist/bridge/bridge.service.js +2471 -68
  7. package/dist/bridge/bridge.types.d.ts +224 -2
  8. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  9. package/dist/bridge/dispatch-result-outbox.js +87 -0
  10. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  11. package/dist/bridge/dispatch-result-worker.js +122 -0
  12. package/dist/bridge/internals.d.ts +2 -0
  13. package/dist/bridge/internals.js +1 -0
  14. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  15. package/dist/bridge/readiness-result-outbox.js +54 -0
  16. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  17. package/dist/bridge/readiness-result-worker.js +121 -0
  18. package/dist/bridge/runner-host-capabilities.d.ts +15 -0
  19. package/dist/bridge/runner-host-capabilities.js +93 -0
  20. package/dist/cleanup/cleanup.service.d.ts +14 -2
  21. package/dist/cleanup/cleanup.service.js +496 -3
  22. package/dist/cleanup/cleanup.types.d.ts +10 -0
  23. package/dist/cleanup/index.d.ts +1 -1
  24. package/dist/cleanup/index.js +1 -1
  25. package/dist/cleanup/internals.d.ts +2 -2
  26. package/dist/cleanup/internals.js +1 -1
  27. package/dist/cli/cli.help.d.ts +2 -0
  28. package/dist/cli/cli.help.js +217 -0
  29. package/dist/cli/cli.service.d.ts +55 -7
  30. package/dist/cli/cli.service.js +429 -219
  31. package/dist/cli/local-config.d.ts +7 -0
  32. package/dist/cli/local-config.js +51 -3
  33. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  34. package/dist/runtime/aspnet-runtime-prebuild.js +341 -0
  35. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  36. package/dist/runtime/attempt-database-broker.js +390 -0
  37. package/dist/runtime/attempt-node-runtime-launcher.d.ts +18 -0
  38. package/dist/runtime/attempt-node-runtime-launcher.js +140 -0
  39. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  40. package/dist/runtime/attempt-path-operation.js +94 -0
  41. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  42. package/dist/runtime/attempt-private-directory.js +54 -0
  43. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  44. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  45. package/dist/runtime/attempt-process-supervisor.d.ts +121 -0
  46. package/dist/runtime/attempt-process-supervisor.js +471 -0
  47. package/dist/runtime/canonical-source-file.d.ts +3 -0
  48. package/dist/runtime/canonical-source-file.js +54 -0
  49. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  50. package/dist/runtime/docker-engine-probe.js +333 -0
  51. package/dist/runtime/generated-output-reset.d.ts +20 -0
  52. package/dist/runtime/generated-output-reset.js +157 -0
  53. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  54. package/dist/runtime/host-database-capability-boundary.js +63 -0
  55. package/dist/runtime/host-diagnostics.d.ts +11 -0
  56. package/dist/runtime/host-diagnostics.js +192 -0
  57. package/dist/runtime/host-execution-root.d.ts +4 -0
  58. package/dist/runtime/host-execution-root.js +39 -0
  59. package/dist/runtime/host-facts.d.ts +35 -0
  60. package/dist/runtime/host-facts.js +95 -0
  61. package/dist/runtime/host-listener-inspector.d.ts +51 -0
  62. package/dist/runtime/host-listener-inspector.js +385 -0
  63. package/dist/runtime/host-load-sampler.d.ts +83 -0
  64. package/dist/runtime/host-load-sampler.js +164 -0
  65. package/dist/runtime/host-port-broker.d.ts +76 -0
  66. package/dist/runtime/host-port-broker.js +333 -0
  67. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  68. package/dist/runtime/host-pressure-stall.js +121 -0
  69. package/dist/runtime/host-runtime-contract.d.ts +59 -0
  70. package/dist/runtime/host-runtime-contract.js +815 -0
  71. package/dist/runtime/host-runtime-lease.d.ts +217 -0
  72. package/dist/runtime/host-runtime-lease.js +2533 -0
  73. package/dist/runtime/host-runtime-promotion.d.ts +32 -0
  74. package/dist/runtime/host-runtime-promotion.js +206 -0
  75. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  76. package/dist/runtime/managed-command-teardown.js +607 -0
  77. package/dist/runtime/memory-capacity.d.ts +70 -0
  78. package/dist/runtime/memory-capacity.js +123 -0
  79. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  80. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  81. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  82. package/dist/runtime/node-host-runtime-adapter.js +286 -0
  83. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  84. package/dist/runtime/pinned-directory-process.js +61 -0
  85. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  86. package/dist/runtime/pinned-source-directory.js +94 -0
  87. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  88. package/dist/runtime/playwright-browser-cache.js +227 -0
  89. package/dist/runtime/playwright-host-runtime-adapter.d.ts +32 -0
  90. package/dist/runtime/playwright-host-runtime-adapter.js +262 -0
  91. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  92. package/dist/runtime/prepared-runtime-identity.js +218 -0
  93. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  94. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  95. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  96. package/dist/runtime/runtime-isolation-lease.js +161 -0
  97. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  98. package/dist/runtime/workspace-resource-estimator.js +174 -0
  99. package/dist/sandbox/command-runner.d.ts +4 -0
  100. package/dist/sandbox/command-runner.js +47 -0
  101. package/dist/sandbox/contract.d.ts +5 -0
  102. package/dist/sandbox/contract.js +276 -0
  103. package/dist/sandbox/event-budget.d.ts +11 -0
  104. package/dist/sandbox/event-budget.js +27 -0
  105. package/dist/sandbox/image-policy.d.ts +35 -0
  106. package/dist/sandbox/image-policy.js +247 -0
  107. package/dist/sandbox/index.d.ts +5 -0
  108. package/dist/sandbox/index.js +5 -0
  109. package/dist/sandbox/lease-watchdog.d.ts +18 -0
  110. package/dist/sandbox/lease-watchdog.js +67 -0
  111. package/dist/sandbox/preflight.d.ts +84 -0
  112. package/dist/sandbox/preflight.js +521 -0
  113. package/dist/sandbox/process.d.ts +20 -0
  114. package/dist/sandbox/process.js +209 -0
  115. package/dist/sandbox/provider-auth/codex.d.ts +26 -0
  116. package/dist/sandbox/provider-auth/codex.js +212 -0
  117. package/dist/sandbox/repository-lock.d.ts +6 -0
  118. package/dist/sandbox/repository-lock.js +129 -0
  119. package/dist/sandbox/runtime.d.ts +302 -0
  120. package/dist/sandbox/runtime.js +2368 -0
  121. package/dist/sandbox/sandbox.types.d.ts +93 -0
  122. package/dist/sandbox/sandbox.types.js +1 -0
  123. package/dist/sandbox/smoke.d.ts +76 -0
  124. package/dist/sandbox/smoke.js +380 -0
  125. package/dist/sandbox/worker-supervisor.d.ts +13 -0
  126. package/dist/sandbox/worker-supervisor.js +36 -0
  127. package/dist/sandbox/worker.d.ts +1 -0
  128. package/dist/sandbox/worker.js +225 -0
  129. package/dist/sandbox/workspace.service.d.ts +13 -0
  130. package/dist/sandbox/workspace.service.js +74 -0
  131. package/dist/session/managed-attempt-tools.d.ts +53 -0
  132. package/dist/session/managed-attempt-tools.js +1213 -0
  133. package/dist/session/managed-build-coordinator.d.ts +5 -0
  134. package/dist/session/managed-build-coordinator.js +109 -0
  135. package/dist/session/managed-build-receipt.d.ts +21 -0
  136. package/dist/session/managed-build-receipt.js +337 -0
  137. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  138. package/dist/session/managed-verification-timeouts.js +17 -0
  139. package/dist/session/phase-completion.artifacts.d.ts +27 -0
  140. package/dist/session/phase-completion.artifacts.js +833 -0
  141. package/dist/session/phase-completion.d.ts +53 -42
  142. package/dist/session/phase-completion.helpers.d.ts +117 -0
  143. package/dist/session/phase-completion.helpers.js +707 -0
  144. package/dist/session/phase-completion.js +125 -3007
  145. package/dist/session/phase-completion.prompts.d.ts +14 -0
  146. package/dist/session/phase-completion.prompts.js +233 -0
  147. package/dist/session/phase-completion.runtime.d.ts +49 -0
  148. package/dist/session/phase-completion.runtime.js +845 -0
  149. package/dist/session/phase-completion.schemas.d.ts +3 -0
  150. package/dist/session/phase-completion.schemas.js +859 -0
  151. package/dist/session/phase-completion.validation.d.ts +38 -0
  152. package/dist/session/phase-completion.validation.js +918 -0
  153. package/dist/session/pre-publication-process.d.ts +20 -0
  154. package/dist/session/pre-publication-process.js +97 -0
  155. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  156. package/dist/session/pre-publication-skipped-tests.js +109 -0
  157. package/dist/session/pre-publication-validation.d.ts +75 -0
  158. package/dist/session/pre-publication-validation.js +631 -0
  159. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  160. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  161. package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
  162. package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
  163. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +96 -0
  164. package/dist/session/provider-cli/provider-cli.artifacts.js +818 -0
  165. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  166. package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
  167. package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
  168. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
  169. package/dist/session/provider-cli/provider-cli.deterministic.js +407 -0
  170. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  171. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  172. package/dist/session/provider-cli/provider-cli.process.d.ts +128 -0
  173. package/dist/session/provider-cli/provider-cli.process.js +1140 -0
  174. package/dist/session/provider-cli/provider-cli.prompts.d.ts +57 -0
  175. package/dist/session/provider-cli/provider-cli.prompts.js +730 -0
  176. package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
  177. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
  178. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  179. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  180. package/dist/session/provider-cli/provider-cli.runtime.d.ts +22 -0
  181. package/dist/session/provider-cli/provider-cli.runtime.js +92 -0
  182. package/dist/session/provider-cli/provider-cli.service.d.ts +47 -53
  183. package/dist/session/provider-cli/provider-cli.service.js +1344 -2506
  184. package/dist/session/provider-cli/provider-cli.types.d.ts +8 -0
  185. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  186. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  187. package/dist/session/provider-cli/provider-output-state.d.ts +38 -0
  188. package/dist/session/provider-cli/provider-output-state.js +826 -0
  189. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  190. package/dist/session/provider-cli/provider-usage.js +28 -5
  191. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  192. package/dist/session/publishable-worktree-changes.js +193 -0
  193. package/dist/session/session-redaction.d.ts +3 -0
  194. package/dist/session/session-redaction.js +448 -0
  195. package/dist/session/session.base.d.ts +6 -1
  196. package/dist/session/session.service.d.ts +8 -2
  197. package/dist/session/session.service.js +586 -59
  198. package/dist/session/session.types.d.ts +324 -3
  199. package/dist/session/session.types.js +951 -10
  200. package/dist/session/unreferenced-exports.d.ts +12 -0
  201. package/dist/session/unreferenced-exports.js +59 -0
  202. package/dist/shared/format/format-bytes.d.ts +1 -0
  203. package/dist/shared/format/format-bytes.js +9 -0
  204. package/dist/shared/git/git.js +2 -1
  205. package/dist/shared/path/path.d.ts +1 -0
  206. package/dist/shared/path/path.js +21 -1
  207. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  208. package/dist/shared/process/dotnet-toolchain.js +307 -0
  209. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  210. package/dist/shared/process/host-process-recovery.js +79 -0
  211. package/dist/shared/process/host-process-supervisor.d.ts +59 -0
  212. package/dist/shared/process/host-process-supervisor.js +331 -0
  213. package/dist/shared/process/process.d.ts +3 -0
  214. package/dist/shared/process/process.js +13 -7
  215. package/dist/shared/process/windows-launch.d.ts +8 -0
  216. package/dist/shared/process/windows-launch.js +41 -0
  217. package/dist/shared/provider-capabilities.d.ts +4 -0
  218. package/dist/shared/provider-capabilities.js +88 -0
  219. package/dist/shared/redaction/redaction.d.ts +1 -0
  220. package/dist/shared/redaction/redaction.js +47 -4
  221. package/dist/shared/time/monotonic.d.ts +1 -0
  222. package/dist/shared/time/monotonic.js +8 -0
  223. package/dist/version.d.ts +1 -1
  224. package/dist/version.js +1 -1
  225. package/dist/worktree/artifact-injector.d.ts +3 -2
  226. package/dist/worktree/artifact-injector.js +82 -10
  227. package/dist/worktree/dependency-warmer.d.ts +53 -1
  228. package/dist/worktree/dependency-warmer.js +693 -11
  229. package/dist/worktree/index.d.ts +2 -1
  230. package/dist/worktree/index.js +1 -0
  231. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  232. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  233. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  234. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  235. package/dist/worktree/worktree-paths.d.ts +4 -0
  236. package/dist/worktree/worktree-paths.js +30 -0
  237. package/dist/worktree/worktree.base.d.ts +3 -0
  238. package/dist/worktree/worktree.service.d.ts +16 -3
  239. package/dist/worktree/worktree.service.js +334 -54
  240. package/dist/worktree/worktree.types.d.ts +9 -1
  241. package/package.json +12 -7
  242. package/runtime/windows-job-supervisor.ps1 +722 -0
  243. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -0,0 +1,2533 @@
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";
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 { resolveExistingDirectoryPath } from "../shared/path/path.js";
11
+ import { formatBytes } from "../shared/format/format-bytes.js";
12
+ import { redactText } from "../shared/redaction/redaction.js";
13
+ import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
14
+ import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
15
+ import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
16
+ import { HostPortBroker, } from "./host-port-broker.js";
17
+ import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
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";
21
+ import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
22
+ import { HostListenerInspector } from "./host-listener-inspector.js";
23
+ import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
24
+ import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
25
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
26
+ import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
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, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
33
+ const hostCapacityWaiterScanLimit = 64;
34
+ const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
35
+ export class HostRuntimeLeaseManager {
36
+ stateRoot;
37
+ processSupervisors;
38
+ processRunner;
39
+ listenerInspector;
40
+ promotionStore;
41
+ playwrightAdapter;
42
+ processRecovery;
43
+ capacityResourceSample;
44
+ databaseBroker;
45
+ preparedReadiness;
46
+ active = new Map();
47
+ pendingRenewals = new Map();
48
+ acquiringAdmissions = new Set();
49
+ admissions = new Map();
50
+ singletonOwners = new Map();
51
+ singletonWaiters = [];
52
+ parallelProjectOwners = new Map();
53
+ parallelProjectWaiters = [];
54
+ capacityReservations = new Map();
55
+ capacityWaiters = [];
56
+ capacityWaiterScanCursor = 0;
57
+ backgroundAdmissionWaiters = [];
58
+ degraded = new Map();
59
+ knownPromotions = new Map();
60
+ ledgerWriteTail = Promise.resolve();
61
+ workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
62
+ portBroker;
63
+ nodeAdapter;
64
+ capacityConfiguration;
65
+ memoryAvailability;
66
+ executionRoot;
67
+ constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null) {
68
+ this.stateRoot = stateRoot;
69
+ this.processSupervisors = processSupervisors;
70
+ this.processRunner = processRunner;
71
+ this.listenerInspector = listenerInspector;
72
+ this.promotionStore = promotionStore;
73
+ this.playwrightAdapter = playwrightAdapter;
74
+ this.processRecovery = processRecovery;
75
+ this.capacityResourceSample = capacityResourceSample;
76
+ this.databaseBroker = databaseBroker;
77
+ this.executionRoot = path.resolve(executionRoot ?? stateRoot);
78
+ if (executionRoot !== undefined)
79
+ assertHostExecutionRoot(this.executionRoot);
80
+ this.preparedReadiness = new PreparedRuntimeReadiness(this, promotionStore, (id, fence) => this.release(id, fence, true), () => new HostRuntimeAdmissionExpiredError());
81
+ this.portBroker = portBroker;
82
+ this.nodeAdapter = nodeAdapter ?? new NodeHostRuntimeAdapter(portBroker);
83
+ this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
84
+ this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
85
+ }
86
+ async reap(options) {
87
+ await this.refreshKnownPromotions();
88
+ const recoveredAttempts = [];
89
+ const report = {
90
+ examined: 0,
91
+ reaped: 0,
92
+ processesTerminated: 0,
93
+ reusedPidsProtected: 0,
94
+ degraded: 0,
95
+ recoveredAttempts,
96
+ };
97
+ for (const ledger of await this.readLedgers()) {
98
+ const lease = ledger.runtimeLease;
99
+ if (lease.runnerId !== options.runnerId)
100
+ continue;
101
+ // A released ledger with its original attempt root is intentionally retained
102
+ // evidence that exceeded the diagnostics archive budget. It owns no runtime
103
+ // resources, but still requires process-identity recovery below on restart.
104
+ if (lease.state === "released") {
105
+ const attemptRoot = this.attemptRoot(lease.dispatchAttemptId);
106
+ const rootExists = await fs.stat(attemptRoot).then(() => true, error => {
107
+ if (error.code === "ENOENT")
108
+ return false;
109
+ throw error;
110
+ });
111
+ if (!rootExists) {
112
+ await fs.rm(this.ledgerPath(lease.dispatchAttemptId), { force: true });
113
+ continue;
114
+ }
115
+ }
116
+ const active = this.active.get(lease.dispatchAttemptId);
117
+ if (active) {
118
+ if (active.lease.state !== "degraded")
119
+ continue;
120
+ report.examined += 1;
121
+ try {
122
+ const released = await this.release(lease.dispatchAttemptId, lease.fencingToken);
123
+ if (released?.state === "released")
124
+ report.reaped += 1;
125
+ else
126
+ report.degraded += 1;
127
+ }
128
+ catch {
129
+ report.degraded += 1;
130
+ }
131
+ continue;
132
+ }
133
+ const staleInstance = lease.runnerInstanceId !== options.runnerInstanceId;
134
+ const expired = Date.parse(lease.expiresAt) <= (options.nowMs ?? Date.now());
135
+ if (!staleInstance && !expired && lease.state !== "released" && lease.state !== "degraded")
136
+ continue;
137
+ report.examined += 1;
138
+ const attemptRoot = this.attemptRoot(lease.dispatchAttemptId);
139
+ const attemptRootIdentity = deserializeHostAttemptRootIdentity(ledger.attemptRootIdentity);
140
+ let outcomes;
141
+ try {
142
+ if (!attemptRootIdentity) {
143
+ throw new Error("host_runtime_reaper_invalid: original attempt-root identity is unavailable.");
144
+ }
145
+ outcomes = await this.recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity);
146
+ }
147
+ catch {
148
+ await this.markLedgerDegraded(ledger);
149
+ report.degraded += 1;
150
+ continue;
151
+ }
152
+ report.processesTerminated += outcomes.filter(outcome => outcome === "terminated").length;
153
+ report.reusedPidsProtected += outcomes.filter(outcome => outcome === "pid_reused").length;
154
+ if (outcomes.includes("unverifiable")) {
155
+ await this.markLedgerDegraded(ledger);
156
+ report.degraded += 1;
157
+ continue;
158
+ }
159
+ // The runtime has already been released. Keep the over-budget original
160
+ // evidence without re-copying it or reacquiring a capacity claim.
161
+ if (lease.state === "released")
162
+ continue;
163
+ // Every supervised tree of this previous-instance attempt is proved gone,
164
+ // so no provider can still act for it. Diagnostics handling below never
165
+ // revives a process, so the proof stands even if cleanup degrades. An
166
+ // attempt with no ownership record at all may have been mid-launch, so
167
+ // it is not reported and keeps its unknown outcome.
168
+ if (staleInstance && outcomes.length > 0) {
169
+ recoveredAttempts.push({
170
+ dispatchAttemptId: lease.dispatchAttemptId,
171
+ fencingToken: lease.fencingToken,
172
+ runnerInstanceId: lease.runnerInstanceId,
173
+ });
174
+ }
175
+ try {
176
+ const releasing = transitionHostLeaseForCleanup(lease, "releasing");
177
+ await this.writeLedger(releasing, ledger.repoId, attemptRootIdentity);
178
+ let evidenceRetainedAtAttemptRoot = false;
179
+ try {
180
+ await retainHostDiagnostics(this.stateRoot, attemptRoot, lease.dispatchAttemptId, attemptRootIdentity, this.executionRoot);
181
+ }
182
+ catch {
183
+ // Exact process recovery above already proved that the runtime is gone.
184
+ // Diagnostics retention can independently refuse a changed inventory,
185
+ // an unsafe archive path, or an over-budget source. Preserve the
186
+ // original attempt root and a released ledger for reconciliation, but
187
+ // never turn evidence-only work back into a capacity-owning runtime.
188
+ evidenceRetainedAtAttemptRoot = true;
189
+ }
190
+ if (evidenceRetainedAtAttemptRoot) {
191
+ const released = transitionRuntimeIsolationLease(releasing, "released");
192
+ await this.writeLedger(released, ledger.repoId, attemptRootIdentity);
193
+ this.forgetDegraded(lease.dispatchAttemptId, lease.fencingToken);
194
+ report.reaped += 1;
195
+ continue;
196
+ }
197
+ await removeHostAttemptRoot(attemptRoot);
198
+ await fs.rm(this.ledgerPath(lease.dispatchAttemptId), { force: true });
199
+ this.forgetDegraded(lease.dispatchAttemptId, lease.fencingToken);
200
+ report.reaped += 1;
201
+ }
202
+ catch {
203
+ await this.markLedgerDegraded(ledger);
204
+ report.degraded += 1;
205
+ }
206
+ }
207
+ // Databases issued to attempts that ended without a clean release (a Bridge crash, or a
208
+ // drop that met a lingering session) are removed once no live lease holds them.
209
+ // A degraded lease may still own running processes after a restart, so its database is kept.
210
+ await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
211
+ return report;
212
+ }
213
+ snapshot() {
214
+ this.reconcileReservationOwners();
215
+ const projects = new Map();
216
+ for (const promotion of this.knownPromotions.values()) {
217
+ const project = capacityProject(projects, promotion.repoId);
218
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_safe");
219
+ project.runtimeContractFingerprint = promotion.runtimeContractFingerprint;
220
+ project.runtimeContractSource = promotion.runtimeContractSource ?? null;
221
+ project.promotedAt = promotion.observedAt;
222
+ }
223
+ for (const [dispatchAttemptId, admission] of this.admissions) {
224
+ const active = this.active.get(dispatchAttemptId);
225
+ const project = capacityProject(projects, admission.repoId);
226
+ if (active) {
227
+ if (active.lease.state === "degraded") {
228
+ project.degradedAttempts += 1;
229
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
230
+ }
231
+ else {
232
+ project.activeAttempts += 1;
233
+ const effectiveConcurrency = effectiveHostConcurrency(active.lease, active.runtimeContract, active.executionClass);
234
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, effectiveConcurrency === "host_parallel_safe"
235
+ ? effectiveConcurrency
236
+ : admission.executionClass === "analysis_only"
237
+ ? "host_parallel_safe"
238
+ : admission.parallelProjectKey && admission.provisionalPromotionFingerprint
239
+ ? "host_parallel_candidate"
240
+ : "host_serial_only");
241
+ }
242
+ }
243
+ else {
244
+ project.reservedAttempts += 1;
245
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, admission.executionClass === "analysis_only"
246
+ ? "host_parallel_safe"
247
+ : admission.provisionalPromotionFingerprint ? "host_parallel_candidate" : "host_serial_only");
248
+ }
249
+ }
250
+ for (const [dispatchAttemptId, degraded] of this.degraded) {
251
+ if (this.active.has(dispatchAttemptId) || !degraded.repoId)
252
+ continue;
253
+ const project = capacityProject(projects, degraded.repoId);
254
+ project.degradedAttempts += 1;
255
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
256
+ }
257
+ for (const waiter of this.singletonWaiters) {
258
+ const repoId = repoIdFromProjectSingletonKeys(waiter.keys);
259
+ if (!repoId)
260
+ continue;
261
+ const project = capacityProject(projects, repoId);
262
+ project.waitingAttempts += 1;
263
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
264
+ }
265
+ for (const waiter of this.parallelProjectWaiters) {
266
+ const repoId = repoIdFromProjectSingletonKey(waiter.key);
267
+ if (!repoId)
268
+ continue;
269
+ const project = capacityProject(projects, repoId);
270
+ project.waitingAttempts += 1;
271
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_candidate");
272
+ }
273
+ for (const waiter of this.backgroundAdmissionWaiters) {
274
+ const repoId = repoIdFromProjectSingletonKeys(waiter.keys);
275
+ if (!repoId)
276
+ continue;
277
+ const project = capacityProject(projects, repoId);
278
+ project.waitingAttempts += 1;
279
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
280
+ }
281
+ // A prepared-runtime verification remains foreground demand after its
282
+ // preparation admission is released and before the internal probe has
283
+ // acquired a normal admission. Report that barrier as waiting capacity so
284
+ // the server cannot mistake the transient gap for an idle host and dispatch
285
+ // readiness probes in a tight loop.
286
+ const unrepresentedPrepared = this.preparedReadiness.pendingSnapshots()
287
+ .filter(pending => !this.hasAttemptRepresentation(pending.probeDispatchAttemptId ?? pending.dispatchAttemptId, pending.probeFencingToken ?? pending.fencingToken));
288
+ for (const pending of unrepresentedPrepared) {
289
+ const project = capacityProject(projects, pending.repoId);
290
+ project.waitingAttempts += 1;
291
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_candidate");
292
+ }
293
+ const activeAttempts = [...this.active.values()]
294
+ .filter(active => active.lease.state !== "degraded").length;
295
+ const degradedAttempts = new Set([
296
+ ...this.degraded.keys(),
297
+ ...[...this.active.entries()]
298
+ .filter(([, active]) => active.lease.state === "degraded")
299
+ .map(([dispatchAttemptId]) => dispatchAttemptId),
300
+ ]).size;
301
+ const hostResources = this.hostResourceSnapshot();
302
+ return {
303
+ activeAttempts,
304
+ preparedWorktreeReadiness: true,
305
+ reservedAttempts: Math.max(0, this.admissions.size - this.active.size),
306
+ waitingAttempts: this.singletonWaiters.length
307
+ + this.parallelProjectWaiters.length
308
+ + this.capacityWaiters.length
309
+ + this.backgroundAdmissionWaiters.length
310
+ + unrepresentedPrepared.length,
311
+ degradedAttempts,
312
+ exclusiveReservations: this.singletonOwners.size,
313
+ sharedReservations: [...this.parallelProjectOwners.values()]
314
+ .reduce((count, owners) => count + owners.size, 0),
315
+ ...hostResources,
316
+ projects: [...projects.values()]
317
+ .map(project => ({
318
+ ...project,
319
+ safetyClass: project.safetyClass ?? "host_serial_only",
320
+ }))
321
+ .sort((left, right) => left.repoId.localeCompare(right.repoId)),
322
+ };
323
+ }
324
+ hasForegroundDemand() {
325
+ return this.preparedReadiness.hasPending()
326
+ || [...this.admissions.values()].some(admission => admission.priority === "foreground")
327
+ || this.singletonWaiters.some(waiter => waiter.priority === "foreground")
328
+ || this.parallelProjectWaiters.some(waiter => waiter.priority === "foreground")
329
+ || this.capacityWaiters.some(waiter => waiter.priority === "foreground");
330
+ }
331
+ async acquirePreparation(dispatch, signal) {
332
+ // Discovery probes already own their verification lifecycle. Analysis-only
333
+ // work never launches the application and must not wait for a runtime wave.
334
+ if (runtimeExecutionClass(dispatch) === "analysis_only" || runtimeAdmissionPriority(dispatch) === "background") {
335
+ return await this.acquire(dispatch, signal);
336
+ }
337
+ return await this.preparedReadiness.acquire(dispatch, signal);
338
+ }
339
+ async acquire(dispatch, signal) {
340
+ const sandbox = dispatch.sandbox;
341
+ if (!sandbox || sandbox.executionMode !== "host") {
342
+ throw new Error("host_runtime_lease_invalid: managed host sandbox context is required.");
343
+ }
344
+ uuidHex(sandbox.dispatchAttemptId, "dispatch attempt");
345
+ uuidHex(dispatch.lease.fencingToken, "fencing token");
346
+ const owner = {
347
+ dispatchAttemptId: sandbox.dispatchAttemptId,
348
+ fencingToken: dispatch.lease.fencingToken,
349
+ };
350
+ const existing = this.admissions.get(sandbox.dispatchAttemptId);
351
+ if (existing) {
352
+ if (existing.fencingToken !== owner.fencingToken) {
353
+ throw new Error("host_runtime_singleton_conflict: dispatch attempt already holds admission under a different fence.");
354
+ }
355
+ return existing.keys;
356
+ }
357
+ const executionClass = runtimeExecutionClass(dispatch);
358
+ const priority = runtimeAdmissionPriority(dispatch);
359
+ const promotion = executionClass === "managed_runtime"
360
+ ? await this.promotionStore.load(dispatch.repo.id)
361
+ : null;
362
+ if (promotion)
363
+ this.knownPromotions.set(promotion.repoId, promotion);
364
+ const projectKey = executionClass === "analysis_only"
365
+ ? projectHostAnalysisKey(dispatch.repo.id)
366
+ : projectHostRuntimeSingletonKey(dispatch.repo.id);
367
+ const useParallelAdmission = priority === "foreground"
368
+ && dispatch.cycleRun.phase !== "prepared_readiness"
369
+ && (promotion !== null || executionClass === "analysis_only");
370
+ let keys = useParallelAdmission ? [] : [projectKey];
371
+ const resources = normalizedHostResourceRequest(sandbox.requestedResources);
372
+ const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
373
+ ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
374
+ : dispatch.lease.expiresAt;
375
+ const acquisitionKey = hostRuntimeOwnerKey(owner);
376
+ this.acquiringAdmissions.add(acquisitionKey);
377
+ try {
378
+ try {
379
+ if (priority === "background") {
380
+ await this.refreshWorkspaceCapacity();
381
+ keys = await this.reserveBackgroundAdmission(keys, owner, resources, expiresAt, signal);
382
+ }
383
+ else if (useParallelAdmission) {
384
+ await this.reserveParallelProject(projectKey, owner, expiresAt, signal, priority);
385
+ }
386
+ else {
387
+ keys = await this.reserveSingletonKeys(keys, owner, expiresAt, signal, priority);
388
+ }
389
+ if (priority === "foreground") {
390
+ await this.refreshWorkspaceCapacity();
391
+ const capacityExpiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
392
+ ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
393
+ : expiresAt;
394
+ await this.reserveHostCapacity(owner, resources, capacityExpiresAt, signal, priority);
395
+ }
396
+ }
397
+ catch (error) {
398
+ this.releaseHostCapacity(owner.dispatchAttemptId, owner.fencingToken);
399
+ this.releaseSingletonKeys(owner.dispatchAttemptId, owner.fencingToken);
400
+ this.releaseParallelProjects(owner.dispatchAttemptId, owner.fencingToken);
401
+ this.clearPendingRenewal(owner);
402
+ throw error;
403
+ }
404
+ const admittedPromotion = useParallelAdmission
405
+ ? promotion ?? (executionClass === "managed_runtime" && keys.length === 0
406
+ ? this.knownPromotions.get(dispatch.repo.id) ?? null
407
+ : null)
408
+ : null;
409
+ this.admissions.set(sandbox.dispatchAttemptId, {
410
+ repoId: dispatch.repo.id,
411
+ fencingToken: owner.fencingToken,
412
+ executionClass,
413
+ priority,
414
+ provisionalPromotionFingerprint: admittedPromotion?.runtimeContractFingerprint ?? null,
415
+ keys,
416
+ parallelProjectKey: useParallelAdmission ? projectKey : null,
417
+ });
418
+ return keys;
419
+ }
420
+ finally {
421
+ this.acquiringAdmissions.delete(acquisitionKey);
422
+ }
423
+ }
424
+ async reserveHostCapacity(owner, resources, expiresAt, signal, priority = "foreground") {
425
+ const existing = this.capacityReservations.get(owner.dispatchAttemptId);
426
+ if (existing) {
427
+ if (!sameSingletonOwner(existing.owner, owner)) {
428
+ throw new Error("host_runtime_capacity_conflict: dispatch attempt already holds capacity under a different fence.");
429
+ }
430
+ return;
431
+ }
432
+ if (signal?.aborted)
433
+ throw cancellationError(signal);
434
+ throwIfAdmissionExpired(expiresAt);
435
+ const impossibleReason = this.hostCapacityImpossibleReason(resources);
436
+ if (impossibleReason)
437
+ throw new HostRuntimeCapacityRequestImpossibleError(impossibleReason);
438
+ if (this.capacityWaiters.length === 0 && this.hostCapacityAvailable(resources)) {
439
+ this.capacityReservations.set(owner.dispatchAttemptId, { owner, resources, state: "pending" });
440
+ return;
441
+ }
442
+ return new Promise((resolve, reject) => {
443
+ const waiter = {
444
+ owner,
445
+ resources,
446
+ priority,
447
+ resolve,
448
+ reject,
449
+ signal,
450
+ expiresAt,
451
+ deadlineTimer: null,
452
+ capacityRecheckTimer: null,
453
+ abort: () => {
454
+ if (!this.detachCapacityWaiter(waiter))
455
+ return;
456
+ this.clearPendingRenewal(owner);
457
+ reject(cancellationError(signal));
458
+ this.drainAdmissionWaiters();
459
+ },
460
+ expire: () => {
461
+ if (!this.detachCapacityWaiter(waiter))
462
+ return;
463
+ this.clearPendingRenewal(owner);
464
+ reject(new HostRuntimeAdmissionExpiredError());
465
+ this.drainAdmissionWaiters();
466
+ },
467
+ };
468
+ waiter.deadlineTimer = scheduleAdmissionDeadline(expiresAt, waiter.expire);
469
+ // Memory, CPU and filesystem capacity can recover without one of our leases
470
+ // being released (for example when an unrelated host process exits). Recheck
471
+ // ambient capacity while queued so readiness probes and attempts do not remain
472
+ // stranded behind a stale low-resource sample.
473
+ waiter.capacityRecheckTimer = setInterval(() => this.drainCapacityWaiters(), 1_000);
474
+ waiter.capacityRecheckTimer.unref?.();
475
+ signal?.addEventListener("abort", waiter.abort, { once: true });
476
+ enqueueAdmissionWaiter(this.capacityWaiters, waiter);
477
+ this.drainCapacityWaiters();
478
+ });
479
+ }
480
+ async reserveBackgroundAdmission(keys, owner, resources, expiresAt, signal) {
481
+ if (signal?.aborted)
482
+ throw cancellationError(signal);
483
+ throwIfAdmissionExpired(expiresAt);
484
+ return await new Promise((resolve, reject) => {
485
+ const waiter = {
486
+ owner,
487
+ keys,
488
+ resources,
489
+ priority: "background",
490
+ resolve,
491
+ reject,
492
+ signal,
493
+ expiresAt,
494
+ deadlineTimer: null,
495
+ capacityRecheckTimer: null,
496
+ abort: () => {
497
+ removeWaiter(this.backgroundAdmissionWaiters, waiter);
498
+ clearAdmissionDeadline(waiter);
499
+ clearCapacityRecheck(waiter);
500
+ this.clearPendingRenewal(owner);
501
+ reject(cancellationError(signal));
502
+ this.drainAdmissionWaiters();
503
+ },
504
+ expire: () => {
505
+ removeWaiter(this.backgroundAdmissionWaiters, waiter);
506
+ clearCapacityRecheck(waiter);
507
+ signal?.removeEventListener("abort", waiter.abort);
508
+ this.clearPendingRenewal(owner);
509
+ reject(new HostRuntimeAdmissionExpiredError());
510
+ this.drainAdmissionWaiters();
511
+ },
512
+ };
513
+ waiter.deadlineTimer = scheduleAdmissionDeadline(expiresAt, waiter.expire);
514
+ waiter.capacityRecheckTimer = setInterval(() => this.drainAdmissionWaiters(), 1_000);
515
+ waiter.capacityRecheckTimer.unref?.();
516
+ signal?.addEventListener("abort", waiter.abort, { once: true });
517
+ this.backgroundAdmissionWaiters.push(waiter);
518
+ this.drainAdmissionWaiters();
519
+ });
520
+ }
521
+ hostCapacityAvailable(resources) {
522
+ const capacity = this.hostResourceSnapshot();
523
+ return capacity.availableAttempts >= resources.sandboxSlots
524
+ && capacity.availableMemoryBytes >= resources.memoryBytes
525
+ && capacity.availableCpuMillis >= resources.cpuMillis
526
+ && capacity.availableWorkspaceBytes >= resources.workspaceBytes;
527
+ }
528
+ hostCapacityImpossibleReason(resources) {
529
+ const { hardMaxAttempts, idleHostReserveBytes, cpuReserveMillis } = this.capacityConfiguration;
530
+ if (resources.sandboxSlots > hardMaxAttempts) {
531
+ return `requested ${resources.sandboxSlots} sandbox slots exceed the host maximum of ${hardMaxAttempts}.`;
532
+ }
533
+ const totalMemoryBytes = this.capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
534
+ const maximumMemoryBytes = Math.max(0, totalMemoryBytes - idleHostReserveBytes);
535
+ if (resources.memoryBytes > maximumMemoryBytes) {
536
+ return `requested memory ${resources.memoryBytes} exceeds the host maximum of ${maximumMemoryBytes} bytes after reserve.`;
537
+ }
538
+ const totalCpuMillis = this.capacityResourceSample?.totalCpuMillis ?? os.cpus().length * 1_000;
539
+ const maximumCpuMillis = Math.max(0, totalCpuMillis - cpuReserveMillis);
540
+ if (resources.cpuMillis > maximumCpuMillis) {
541
+ return `requested CPU ${resources.cpuMillis} millis exceeds the host maximum of ${maximumCpuMillis} millis after reserve.`;
542
+ }
543
+ return null;
544
+ }
545
+ hostResourceSnapshot() {
546
+ if (!this.capacityResourceSample) {
547
+ try {
548
+ const stats = statfsSync(this.stateRoot);
549
+ this.workspaceAvailableBytes = Math.max(0, stats.bavail * stats.bsize);
550
+ }
551
+ catch {
552
+ // State root may not exist during the first capability heartbeat. The first
553
+ // admission creates it and refreshes the sample before reserving resources.
554
+ }
555
+ }
556
+ const { hardMaxAttempts, cpuReserveMillis, workspaceReserveBytes } = this.capacityConfiguration;
557
+ const hostReserveBytes = this.capacityReservations.size === 0
558
+ ? this.capacityConfiguration.idleHostReserveBytes
559
+ : this.capacityConfiguration.hostReserveBytes;
560
+ const activeReservationMemoryBytes = [...this.capacityReservations.values()]
561
+ .reduce((total, reservation) => total + reservation.resources.memoryBytes, 0);
562
+ const pendingReservationMemoryBytes = [...this.capacityReservations.values()]
563
+ .filter(reservation => reservation.state === "pending")
564
+ .reduce((total, reservation) => total + reservation.resources.memoryBytes, 0);
565
+ const activeReservationCpuMillis = [...this.capacityReservations.values()]
566
+ .reduce((total, reservation) => total + reservation.resources.cpuMillis, 0);
567
+ const activeReservationWorkspaceBytes = [...this.capacityReservations.values()]
568
+ .reduce((total, reservation) => total + reservation.resources.workspaceBytes, 0);
569
+ const sampledAt = new Date().toISOString();
570
+ const totalMemoryBytes = this.capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
571
+ const rawAvailableMemoryBytes = this.capacityResourceSample?.availableMemoryBytes ?? os.freemem();
572
+ const sampledAvailableMemoryBytes = this.memoryAvailability.observe(rawAvailableMemoryBytes);
573
+ // raw/stabilized available memory already includes every resident host and
574
+ // Forge process. Keep the independent total ceiling scoped to Forge's own
575
+ // reservations; adding ambient use here charges it a second time and can
576
+ // strand work even while more than the requested memory is physically free.
577
+ const committedMemoryBytes = Math.min(totalMemoryBytes, activeReservationMemoryBytes);
578
+ const totalCpuMillis = this.capacityResourceSample?.totalCpuMillis ?? os.cpus().length * 1000;
579
+ const sampledWorkspaceBytes = this.capacityResourceSample?.availableWorkspaceBytes ?? this.workspaceAvailableBytes;
580
+ const memoryAdmission = buildMemoryAdmissionDiagnostics({
581
+ sampledAt,
582
+ totalMemoryBytes,
583
+ rawAvailableMemoryBytes,
584
+ stabilizedAvailableMemoryBytes: sampledAvailableMemoryBytes,
585
+ controlPlaneMemoryBytes: process.memoryUsage().rss,
586
+ reserveMemoryBytes: hostReserveBytes,
587
+ committedMemoryBytes,
588
+ pendingCommitmentMemoryBytes: pendingReservationMemoryBytes,
589
+ });
590
+ const availableMemoryBytes = memoryAdmission.availableForAdmissionBytes;
591
+ const availableCpuMillis = Math.max(0, totalCpuMillis - cpuReserveMillis - activeReservationCpuMillis);
592
+ const availableWorkspaceBytes = Math.max(0, sampledWorkspaceBytes - workspaceReserveBytes - activeReservationWorkspaceBytes);
593
+ const slotAvailability = Math.max(0, hardMaxAttempts - this.capacityReservations.size);
594
+ // Capability snapshots advertise whether any supported attempt can fit.
595
+ // The queue/admission path still checks the exact project-derived request.
596
+ const minimumRequest = minimumSupportedHostResourceRequest();
597
+ const resourceAvailability = Math.min(resourceSlots(availableMemoryBytes, minimumRequest.memoryBytes), resourceSlots(availableCpuMillis, minimumRequest.cpuMillis), resourceSlots(availableWorkspaceBytes, minimumRequest.workspaceBytes));
598
+ const availableAttempts = Math.max(0, Math.min(slotAvailability, resourceAvailability));
599
+ const unavailableReason = slotAvailability <= 0
600
+ ? `Host attempt capacity is full (${this.capacityReservations.size}/${hardMaxAttempts}).`
601
+ : availableMemoryBytes < minimumRequest.memoryBytes
602
+ ? "Host memory is below the admission reserve."
603
+ : availableCpuMillis < minimumRequest.cpuMillis
604
+ ? "Host CPU capacity is below the admission reserve."
605
+ : availableWorkspaceBytes < minimumRequest.workspaceBytes
606
+ ? "Host workspace capacity is below the admission reserve."
607
+ : null;
608
+ return {
609
+ hardMaxAttempts,
610
+ effectiveMaxAttempts: this.capacityReservations.size + availableAttempts,
611
+ availableAttempts,
612
+ totalMemoryBytes,
613
+ availableMemoryBytes,
614
+ hostReserveBytes,
615
+ availableCpuMillis,
616
+ availableWorkspaceBytes,
617
+ activeReservationMemoryBytes,
618
+ memoryAdmission,
619
+ unavailableCode: unavailableReason ? "capacity_unavailable" : null,
620
+ unavailableReason,
621
+ };
622
+ }
623
+ async refreshWorkspaceCapacity() {
624
+ if (this.capacityResourceSample)
625
+ return;
626
+ try {
627
+ await fs.mkdir(this.stateRoot, { recursive: true });
628
+ const stats = await fs.statfs(this.stateRoot);
629
+ this.workspaceAvailableBytes = Math.max(0, stats.bavail * stats.bsize);
630
+ }
631
+ catch {
632
+ // Keep the last trustworthy sample. Memory/CPU and the hard ceiling still
633
+ // protect admission when the filesystem cannot be sampled temporarily.
634
+ }
635
+ }
636
+ releaseHostCapacity(dispatchAttemptId, fencingToken) {
637
+ const reservation = this.capacityReservations.get(dispatchAttemptId);
638
+ if (!reservation || reservation.owner.fencingToken !== fencingToken)
639
+ return;
640
+ this.capacityReservations.delete(dispatchAttemptId);
641
+ this.drainAdmissionWaiters();
642
+ }
643
+ drainCapacityWaiters() {
644
+ for (const waiter of this.capacityWaitersForScan()) {
645
+ if (!this.capacityWaiters.includes(waiter))
646
+ continue;
647
+ if (waiter.signal?.aborted) {
648
+ this.detachCapacityWaiter(waiter);
649
+ this.clearPendingRenewal(waiter.owner);
650
+ waiter.reject(cancellationError(waiter.signal));
651
+ continue;
652
+ }
653
+ if (admissionExpired(waiter.expiresAt)) {
654
+ this.detachCapacityWaiter(waiter);
655
+ this.clearPendingRenewal(waiter.owner);
656
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
657
+ continue;
658
+ }
659
+ const impossibleReason = this.hostCapacityImpossibleReason(waiter.resources);
660
+ if (impossibleReason) {
661
+ this.detachCapacityWaiter(waiter);
662
+ this.clearPendingRenewal(waiter.owner);
663
+ waiter.reject(new HostRuntimeCapacityRequestImpossibleError(impossibleReason));
664
+ continue;
665
+ }
666
+ if (!this.hostCapacityAvailable(waiter.resources))
667
+ continue;
668
+ this.detachCapacityWaiter(waiter);
669
+ this.capacityReservations.set(waiter.owner.dispatchAttemptId, {
670
+ owner: waiter.owner,
671
+ resources: waiter.resources,
672
+ state: "pending",
673
+ });
674
+ waiter.resolve();
675
+ }
676
+ }
677
+ capacityWaitersForScan() {
678
+ const head = this.capacityWaiters[0];
679
+ if (!head) {
680
+ this.capacityWaiterScanCursor = 0;
681
+ return [];
682
+ }
683
+ const scanCount = Math.min(hostCapacityWaiterScanLimit, this.capacityWaiters.length);
684
+ if (scanCount === this.capacityWaiters.length) {
685
+ this.capacityWaiterScanCursor = 0;
686
+ return this.capacityWaiters.slice();
687
+ }
688
+ // The head always gets the first opportunity, while a rotating bounded
689
+ // window prevents an unfit renewed head (or a very deep queue) from
690
+ // indefinitely hiding a later request that fits current capacity.
691
+ const laterCount = this.capacityWaiters.length - 1;
692
+ const laterScanCount = scanCount - 1;
693
+ const start = this.capacityWaiterScanCursor % laterCount;
694
+ const result = [head];
695
+ for (let offset = 0; offset < laterScanCount; offset += 1) {
696
+ result.push(this.capacityWaiters[1 + ((start + offset) % laterCount)]);
697
+ }
698
+ this.capacityWaiterScanCursor = (start + laterScanCount) % laterCount;
699
+ return result;
700
+ }
701
+ detachCapacityWaiter(waiter) {
702
+ const index = this.capacityWaiters.indexOf(waiter);
703
+ if (index < 0)
704
+ return false;
705
+ this.capacityWaiters.splice(index, 1);
706
+ clearAdmissionDeadline(waiter);
707
+ clearCapacityRecheck(waiter);
708
+ waiter.signal?.removeEventListener("abort", waiter.abort);
709
+ if (this.capacityWaiters.length === 0)
710
+ this.capacityWaiterScanCursor = 0;
711
+ return true;
712
+ }
713
+ async reserveSingletonKeys(keys, owner, expiresAt, signal, priority = "foreground") {
714
+ const owned = keys.every(key => sameSingletonOwner(this.singletonOwners.get(key), owner));
715
+ if (owned)
716
+ return keys;
717
+ const staleFence = [...this.singletonOwners.values()].find(existing => existing.dispatchAttemptId === owner.dispatchAttemptId
718
+ && existing.fencingToken !== owner.fencingToken);
719
+ if (staleFence) {
720
+ throw new Error("host_runtime_singleton_conflict: dispatch attempt already holds the singleton under a different fence.");
721
+ }
722
+ if (signal?.aborted)
723
+ throw cancellationError(signal);
724
+ throwIfAdmissionExpired(expiresAt);
725
+ if (this.singletonKeysAvailable(keys)) {
726
+ this.assignSingletonKeys(keys, owner);
727
+ return keys;
728
+ }
729
+ return new Promise((resolve, reject) => {
730
+ const waiter = {
731
+ owner,
732
+ keys,
733
+ priority,
734
+ resolve,
735
+ reject,
736
+ signal,
737
+ expiresAt,
738
+ deadlineTimer: null,
739
+ abort: () => {
740
+ const index = this.singletonWaiters.indexOf(waiter);
741
+ if (index >= 0)
742
+ this.singletonWaiters.splice(index, 1);
743
+ clearAdmissionDeadline(waiter);
744
+ this.clearPendingRenewal(owner);
745
+ reject(cancellationError(signal));
746
+ this.drainAdmissionWaiters();
747
+ },
748
+ expire: () => {
749
+ const index = this.singletonWaiters.indexOf(waiter);
750
+ if (index < 0)
751
+ return;
752
+ this.singletonWaiters.splice(index, 1);
753
+ clearAdmissionDeadline(waiter);
754
+ waiter.signal?.removeEventListener("abort", waiter.abort);
755
+ this.clearPendingRenewal(owner);
756
+ reject(new HostRuntimeAdmissionExpiredError());
757
+ this.drainAdmissionWaiters();
758
+ },
759
+ };
760
+ enqueueAdmissionWaiter(this.singletonWaiters, waiter);
761
+ signal?.addEventListener("abort", waiter.abort, { once: true });
762
+ waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
763
+ this.drainAdmissionWaiters();
764
+ });
765
+ }
766
+ async reserveParallelProject(key, owner, expiresAt, signal, priority = "foreground") {
767
+ if (this.parallelProjectOwned(key, owner))
768
+ return;
769
+ const staleFence = [...(this.parallelProjectOwners.get(key)?.values() ?? [])]
770
+ .find(existing => existing.dispatchAttemptId === owner.dispatchAttemptId
771
+ && existing.fencingToken !== owner.fencingToken);
772
+ if (staleFence) {
773
+ throw new Error("host_runtime_parallel_conflict: dispatch attempt already holds shared admission under a different fence.");
774
+ }
775
+ if (signal?.aborted)
776
+ throw cancellationError(signal);
777
+ throwIfAdmissionExpired(expiresAt);
778
+ if (this.parallelProjectAvailable(key, priority)) {
779
+ this.assignParallelProject(key, owner);
780
+ return;
781
+ }
782
+ await new Promise((resolve, reject) => {
783
+ const waiter = {
784
+ owner,
785
+ key,
786
+ priority,
787
+ resolve,
788
+ reject,
789
+ signal,
790
+ expiresAt,
791
+ deadlineTimer: null,
792
+ abort: () => {
793
+ const index = this.parallelProjectWaiters.indexOf(waiter);
794
+ if (index >= 0)
795
+ this.parallelProjectWaiters.splice(index, 1);
796
+ clearAdmissionDeadline(waiter);
797
+ this.clearPendingRenewal(owner);
798
+ reject(cancellationError(signal));
799
+ this.drainAdmissionWaiters();
800
+ },
801
+ expire: () => {
802
+ const index = this.parallelProjectWaiters.indexOf(waiter);
803
+ if (index < 0)
804
+ return;
805
+ this.parallelProjectWaiters.splice(index, 1);
806
+ clearAdmissionDeadline(waiter);
807
+ waiter.signal?.removeEventListener("abort", waiter.abort);
808
+ this.clearPendingRenewal(owner);
809
+ reject(new HostRuntimeAdmissionExpiredError());
810
+ this.drainAdmissionWaiters();
811
+ },
812
+ };
813
+ enqueueAdmissionWaiter(this.parallelProjectWaiters, waiter);
814
+ signal?.addEventListener("abort", waiter.abort, { once: true });
815
+ waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
816
+ this.drainAdmissionWaiters();
817
+ });
818
+ }
819
+ async upgradeParallelProjectToSingleton(keys, parallelProjectKey, owner, expiresAt, signal, priority = "foreground") {
820
+ if (!this.parallelProjectOwned(parallelProjectKey, owner)) {
821
+ throw new Error("host_runtime_parallel_unreserved: matching shared project admission is required before serialization.");
822
+ }
823
+ if (signal?.aborted)
824
+ throw cancellationError(signal);
825
+ throwIfAdmissionExpired(expiresAt);
826
+ return await new Promise((resolve, reject) => {
827
+ const waiter = {
828
+ owner,
829
+ keys,
830
+ priority,
831
+ resolve,
832
+ reject,
833
+ signal,
834
+ expiresAt,
835
+ deadlineTimer: null,
836
+ abort: () => {
837
+ const index = this.singletonWaiters.indexOf(waiter);
838
+ if (index >= 0)
839
+ this.singletonWaiters.splice(index, 1);
840
+ clearAdmissionDeadline(waiter);
841
+ this.clearPendingRenewal(owner);
842
+ reject(cancellationError(signal));
843
+ this.drainAdmissionWaiters();
844
+ },
845
+ expire: () => {
846
+ const index = this.singletonWaiters.indexOf(waiter);
847
+ if (index < 0)
848
+ return;
849
+ this.singletonWaiters.splice(index, 1);
850
+ clearAdmissionDeadline(waiter);
851
+ waiter.signal?.removeEventListener("abort", waiter.abort);
852
+ this.clearPendingRenewal(owner);
853
+ reject(new HostRuntimeAdmissionExpiredError());
854
+ this.drainAdmissionWaiters();
855
+ },
856
+ };
857
+ // Queue the exclusive claim before relinquishing the shared claim. This
858
+ // makes the promotion downgrade atomic from the broker's perspective and
859
+ // prevents a background readiness probe from jumping ahead in between.
860
+ enqueueAdmissionWaiter(this.singletonWaiters, waiter);
861
+ signal?.addEventListener("abort", waiter.abort, { once: true });
862
+ waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
863
+ this.releaseParallelProjectNoDrain(parallelProjectKey, owner);
864
+ this.drainAdmissionWaiters();
865
+ });
866
+ }
867
+ async start(dispatch, worktreePath, signal, onAdmissionCheckpoint) {
868
+ const sandbox = dispatch.sandbox;
869
+ if (!sandbox || sandbox.executionMode !== "host") {
870
+ throw new Error("host_runtime_lease_invalid: managed host sandbox context is required.");
871
+ }
872
+ const wasPrepared = this.preparedReadiness.has(sandbox.dispatchAttemptId);
873
+ const preparedProof = wasPrepared
874
+ ? await this.preparedReadiness.verify(dispatch, worktreePath, onAdmissionCheckpoint)
875
+ : undefined;
876
+ if (wasPrepared) {
877
+ signal?.throwIfAborted();
878
+ const admission = this.hostResourceSnapshot().memoryAdmission;
879
+ const requestedMemoryBytes = normalizedHostResourceRequest(sandbox.requestedResources).memoryBytes;
880
+ await onAdmissionCheckpoint?.({
881
+ code: "host_runtime_prepared_admission_waiting",
882
+ message: `Prepared runtime verification passed. Waiting for host admission before agent startup: ${formatBytes(requestedMemoryBytes)} requested, ${formatBytes(admission.availableForAdmissionBytes)} currently available under the host reserve.`,
883
+ expiresAt: dispatch.lease.expiresAt,
884
+ });
885
+ await this.acquire(dispatch, signal);
886
+ await onAdmissionCheckpoint?.({
887
+ code: "host_runtime_prepared_admission_acquired",
888
+ message: "Prepared runtime acquired host admission; agent startup is continuing.",
889
+ expiresAt: dispatch.lease.expiresAt,
890
+ });
891
+ }
892
+ const existing = this.active.get(sandbox.dispatchAttemptId);
893
+ if (existing) {
894
+ if (existing.lease.fencingToken !== dispatch.lease.fencingToken) {
895
+ throw new Error("host_runtime_lease_conflict: an active host lease has a different fence.");
896
+ }
897
+ return {
898
+ lease: existing.lease,
899
+ environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass, existing.databaseCapability),
900
+ runtimeContract: existing.runtimeContract,
901
+ executionClass: existing.executionClass,
902
+ };
903
+ }
904
+ const admission = this.admissions.get(sandbox.dispatchAttemptId);
905
+ const owner = { dispatchAttemptId: sandbox.dispatchAttemptId, fencingToken: dispatch.lease.fencingToken };
906
+ if (!admission || admission.fencingToken !== owner.fencingToken) {
907
+ throw new Error("host_runtime_singleton_unreserved: managed host admission is required before start.");
908
+ }
909
+ const attemptHex = uuidHex(sandbox.dispatchAttemptId, "dispatch attempt");
910
+ const compactAttemptHex = compactHostAttemptId(sandbox.dispatchAttemptId);
911
+ const normalizedWorktreePath = await resolveExistingDirectoryPath(worktreePath);
912
+ const attemptRoot = path.join(this.executionRoot, "a", compactAttemptHex);
913
+ const temporaryPath = path.join(attemptRoot, "t");
914
+ const logPath = path.join(attemptRoot, "logs");
915
+ const cachePath = path.join(attemptRoot, "c");
916
+ const browserProfilePath = path.join(attemptRoot, "b");
917
+ const testOutputPath = path.join(attemptRoot, "test-output");
918
+ const processSupervisorMetadataPath = path.join(logPath, "attempt-process-supervisor.json");
919
+ const processSupervisorId = `host-${attemptHex}`;
920
+ const renewedExpiry = this.pendingRenewals.get(sandbox.dispatchAttemptId);
921
+ const expiresAt = renewedExpiry?.fencingToken === dispatch.lease.fencingToken
922
+ ? renewedExpiry.expiresAt
923
+ : dispatch.lease.expiresAt;
924
+ let processSupervisor = null;
925
+ let attemptRootIdentity = null;
926
+ try {
927
+ const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
928
+ if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
929
+ throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
930
+ }
931
+ if (wasPrepared && !preparedProof && admission.executionClass === "managed_runtime"
932
+ && hostRuntimeParallelEligible(runtimeContract)) {
933
+ throw new Error("host_runtime_prepared_source_changed: runtime became parallel-eligible after preparation; a new foreground proof is required.");
934
+ }
935
+ const runtimeContractFingerprint = hostRuntimeContractFingerprint(runtimeContract);
936
+ const inputCommitSha = preparedProof?.inputCommitSha
937
+ ?? await resolveWorktreeCommitSha(normalizedWorktreePath, sandbox.inputCommitSha);
938
+ if (preparedProof && (runtimeContractFingerprint !== preparedProof.runtimeContractFingerprint
939
+ || JSON.stringify(preparedProof) !== JSON.stringify(await preparedRuntimeIdentity(normalizedWorktreePath, signal)))) {
940
+ throw new Error("host_runtime_prepared_source_changed: source changed after its foreground proof; agent was not started.");
941
+ }
942
+ const promotion = admission.executionClass === "managed_runtime"
943
+ ? await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha })
944
+ : null;
945
+ const promotionMatches = hostRuntimeParallelEligible(runtimeContract)
946
+ && promotion?.runtimeContractFingerprint === runtimeContractFingerprint
947
+ && promotion.inputCommitSha === inputCommitSha;
948
+ if (admission.executionClass === "managed_runtime" && admission.keys.length === 0 && !promotionMatches) {
949
+ const projectKeys = hostRuntimeSingletonKeys(dispatch);
950
+ const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
951
+ ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
952
+ : dispatch.lease.expiresAt;
953
+ const parallelProjectKey = admission.parallelProjectKey;
954
+ admission.parallelProjectKey = null;
955
+ const capacityReservation = this.capacityReservations.get(owner.dispatchAttemptId);
956
+ if (capacityReservation && !sameSingletonOwner(capacityReservation.owner, owner)) {
957
+ throw new Error("host_runtime_capacity_conflict: dispatch attempt holds capacity under a different fence.");
958
+ }
959
+ const serializedAdmission = parallelProjectKey
960
+ ? this.upgradeParallelProjectToSingleton(projectKeys, parallelProjectKey, owner, expiresAt, signal, admission.priority)
961
+ : this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal, admission.priority);
962
+ // A sibling can already hold the same provisional shared project claim
963
+ // while waiting for this attempt's host-capacity slot. Retaining capacity
964
+ // while waiting for that sibling to release its shared claim creates a
965
+ // cycle: exclusive waits on shared, shared waits on capacity. Relinquish
966
+ // the capacity slot only after the exclusive waiter is queued, then
967
+ // reacquire it after serialization is granted.
968
+ if (capacityReservation) {
969
+ this.releaseHostCapacity(owner.dispatchAttemptId, owner.fencingToken);
970
+ }
971
+ // The checkpoint is allowed to do I/O. Observe an early admission
972
+ // failure now so a slow acknowledgement cannot create an unhandled
973
+ // rejection before the operational promise is awaited below.
974
+ void serializedAdmission.catch(() => undefined);
975
+ // Begin the operational downgrade before publishing telemetry. A lost
976
+ // callback acknowledgement must not leave the attempt holding its old
977
+ // shared admission while every recovery probe waits behind it.
978
+ await onAdmissionCheckpoint?.({
979
+ code: "host_runtime_serial_admission_waiting",
980
+ message: "The prepared runtime contract no longer matches the parallel-readiness proof. Waiting for foreground-priority serialized admission before launch.",
981
+ expiresAt,
982
+ });
983
+ admission.keys = await serializedAdmission;
984
+ while (admission.keys.length === 0) {
985
+ const promoted = this.knownPromotions.get(dispatch.repo.id);
986
+ if (!promoted) {
987
+ throw new Error("host_runtime_parallel_promotion_missing: shared admission requires matching promotion evidence.");
988
+ }
989
+ const matching = await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha });
990
+ if (!matching) {
991
+ // Drop obsolete proof before asking for exclusive admission; otherwise
992
+ // the queue can grant the same stale shared promotion indefinitely.
993
+ this.releaseParallelProjectNoDrain(projectKeys[0], owner);
994
+ admission.keys = await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal, admission.priority);
995
+ continue;
996
+ }
997
+ admission.parallelProjectKey = projectKeys[0] ?? null;
998
+ admission.provisionalPromotionFingerprint = promoted.runtimeContractFingerprint;
999
+ break;
1000
+ }
1001
+ // Do not hold a capacity slot while a stale shared re-grant is still
1002
+ // being converted to exclusive admission.
1003
+ if (capacityReservation) {
1004
+ await this.reserveHostCapacity(owner, capacityReservation.resources, expiresAt, signal, admission.priority);
1005
+ }
1006
+ }
1007
+ const declaredSingletonKeys = runtimeContract.contract.runtime.singletonResources
1008
+ .map(hostRuntimeDeclaredSingletonKey);
1009
+ const missingSingletonKeys = declaredSingletonKeys
1010
+ .filter(key => !admission.keys.includes(key));
1011
+ if (missingSingletonKeys.length > 0) {
1012
+ const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
1013
+ ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
1014
+ : dispatch.lease.expiresAt;
1015
+ const reservedSingletonKeys = await this.reserveSingletonKeys(missingSingletonKeys, owner, expiresAt, signal, admission.priority);
1016
+ admission.keys = [...admission.keys, ...reservedSingletonKeys]
1017
+ .sort((left, right) => left.localeCompare(right));
1018
+ }
1019
+ const singletonKeys = admission.keys;
1020
+ if (!singletonKeys.every(key => sameSingletonOwner(this.singletonOwners.get(key), owner))) {
1021
+ throw new Error("host_runtime_singleton_unreserved: managed host singleton ownership is required before start.");
1022
+ }
1023
+ if (admission.parallelProjectKey && !this.parallelProjectOwned(admission.parallelProjectKey, owner)) {
1024
+ throw new Error("host_runtime_parallel_unreserved: matching shared project admission is required before start.");
1025
+ }
1026
+ await createCanonicalDirectory(attemptRoot);
1027
+ attemptRootIdentity = (await assertCanonicalDirectory(attemptRoot));
1028
+ await Promise.all([
1029
+ createCanonicalDirectory(temporaryPath),
1030
+ createCanonicalDirectory(logPath),
1031
+ createCanonicalDirectory(cachePath),
1032
+ createCanonicalDirectory(browserProfilePath),
1033
+ createCanonicalDirectory(testOutputPath),
1034
+ ]);
1035
+ await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
1036
+ await resetGeneratedOutputs(normalizedWorktreePath, testOutputPath);
1037
+ let lease = createRuntimeIsolationLease({
1038
+ leaseId: sandbox.executionLeaseId,
1039
+ dispatchAttemptId: sandbox.dispatchAttemptId,
1040
+ executionLeaseId: sandbox.executionLeaseId,
1041
+ fencingToken: dispatch.lease.fencingToken,
1042
+ runnerId: dispatch.execution.runnerId ?? "",
1043
+ runnerInstanceId: sandbox.runnerInstanceId,
1044
+ worktreeKey: dispatch.lease.worktreeKey,
1045
+ worktreePath: normalizedWorktreePath,
1046
+ mode: "host",
1047
+ expiresAt,
1048
+ resources: {
1049
+ memoryReservationBytes: 0,
1050
+ cpuMillis: 0,
1051
+ pids: 0,
1052
+ ports: [],
1053
+ paths: [
1054
+ { path: normalizedWorktreePath, role: "worktree" },
1055
+ { path: temporaryPath, role: "temporary" },
1056
+ { path: logPath, role: "logs" },
1057
+ { path: cachePath, role: "cache" },
1058
+ { path: browserProfilePath, role: "browser_profile" },
1059
+ { path: testOutputPath, role: "test_output" },
1060
+ { path: processSupervisorMetadataPath, role: "process_supervisor_metadata" },
1061
+ ],
1062
+ processSupervisorId,
1063
+ dockerResources: [],
1064
+ singletonKeys,
1065
+ },
1066
+ });
1067
+ await this.writeLedger(lease, undefined, attemptRootIdentity);
1068
+ lease = transitionRuntimeIsolationLease(lease, "starting");
1069
+ await this.writeLedger(lease, undefined, attemptRootIdentity);
1070
+ lease = transitionRuntimeIsolationLease(lease, "active");
1071
+ await this.writeLedger(lease, undefined, attemptRootIdentity);
1072
+ processSupervisor = this.processSupervisors.register({
1073
+ processSupervisorId,
1074
+ dispatchAttemptId: lease.dispatchAttemptId,
1075
+ executionLeaseId: lease.executionLeaseId,
1076
+ fencingToken: lease.fencingToken,
1077
+ logDirectory: logPath,
1078
+ }, this.processRunner, { signal });
1079
+ this.active.set(sandbox.dispatchAttemptId, {
1080
+ lease,
1081
+ repoId: dispatch.repo.id,
1082
+ sessionId: dispatch.session.id,
1083
+ attemptRoot,
1084
+ attemptRootIdentity,
1085
+ runtimeContract,
1086
+ runtimeContractFingerprint,
1087
+ inputCommitSha,
1088
+ executionClass: admission.executionClass,
1089
+ parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1090
+ processSupervisor,
1091
+ adapterCleanups: [],
1092
+ pendingAdapterLaunches: new Map(),
1093
+ runtimeResourcesReleased: false,
1094
+ releasing: false,
1095
+ });
1096
+ this.pendingRenewals.delete(sandbox.dispatchAttemptId);
1097
+ return {
1098
+ lease,
1099
+ environment: hostRuntimeEnvironment(dispatch.session.id, lease, runtimeContract, admission.executionClass),
1100
+ runtimeContract,
1101
+ executionClass: admission.executionClass,
1102
+ };
1103
+ }
1104
+ catch (error) {
1105
+ this.pendingRenewals.delete(sandbox.dispatchAttemptId);
1106
+ if (processSupervisor) {
1107
+ await processSupervisor.stopAll(dispatch.lease.fencingToken, "Host runtime start rolled back.").catch(() => undefined);
1108
+ this.processSupervisors.unregister(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
1109
+ }
1110
+ const attemptRemoved = await retainHostDiagnostics(this.stateRoot, attemptRoot, sandbox.dispatchAttemptId, attemptRootIdentity, this.executionRoot).then(async () => {
1111
+ await removeHostAttemptRoot(attemptRoot);
1112
+ return true;
1113
+ }).catch(() => false); // A retention failure preserves the original evidence and ownership ledger.
1114
+ if (attemptRemoved) {
1115
+ await fs.rm(this.ledgerPath(sandbox.dispatchAttemptId), { force: true }).catch(() => undefined);
1116
+ }
1117
+ this.releaseSingletonKeys(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
1118
+ this.releaseParallelProjects(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
1119
+ this.deleteAdmission(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
1120
+ throw error;
1121
+ }
1122
+ }
1123
+ async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
1124
+ try {
1125
+ uuidHex(dispatchAttemptId, "dispatch attempt");
1126
+ uuidHex(fencingToken, "fencing token");
1127
+ }
1128
+ catch {
1129
+ return;
1130
+ }
1131
+ await this.preparedReadiness.renew(dispatchAttemptId, fencingToken, expiresAt);
1132
+ const active = this.active.get(dispatchAttemptId);
1133
+ if (!active) {
1134
+ if (Number.isFinite(Date.parse(expiresAt))) {
1135
+ const pending = this.pendingRenewals.get(dispatchAttemptId);
1136
+ if (!pending
1137
+ || pending.fencingToken !== fencingToken
1138
+ || Date.parse(expiresAt) > Date.parse(pending.expiresAt)) {
1139
+ this.pendingRenewals.set(dispatchAttemptId, { fencingToken, expiresAt });
1140
+ }
1141
+ this.renewAdmissionWaiterDeadline(dispatchAttemptId, fencingToken, expiresAt);
1142
+ }
1143
+ return;
1144
+ }
1145
+ if (active.releasing || active.lease.state === "releasing" || active.lease.state === "released")
1146
+ return;
1147
+ const renewed = renewRuntimeIsolationLease(active.lease, fencingToken, expiresAt);
1148
+ if (!renewed)
1149
+ return;
1150
+ active.lease = renewed;
1151
+ await this.writeLedger(renewed);
1152
+ }
1153
+ async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1154
+ const active = this.active.get(dispatchAttemptId);
1155
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1156
+ throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1157
+ }
1158
+ if (active.executionClass === "analysis_only") {
1159
+ return {
1160
+ lease: active.lease,
1161
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1162
+ runtimeContract: active.runtimeContract,
1163
+ executionClass: active.executionClass,
1164
+ };
1165
+ }
1166
+ const configuredPorts = active.runtimeContract.contract.runtime.ports.filter((port) => port.launch !== null);
1167
+ if (configuredPorts.length === 0) {
1168
+ return {
1169
+ lease: active.lease,
1170
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1171
+ runtimeContract: active.runtimeContract,
1172
+ executionClass: active.executionClass,
1173
+ };
1174
+ }
1175
+ const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
1176
+ // A host without the project's pinned browsers fails here, before any database,
1177
+ // build, launch, or promotion work that the attempt would otherwise waste.
1178
+ if (playwrightConfig)
1179
+ await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
1180
+ const owner = hostPortOwner(active.lease);
1181
+ const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
1182
+ if (!logDirectory)
1183
+ throw new Error("host_runtime_project_invalid: attempt log directory is unavailable.");
1184
+ if (this.databaseBroker && !active.databaseCapability
1185
+ && configuredPorts.some(port => /^dotnet(?:\.exe)?$/iu.test(path.basename(port.launch.command)))) {
1186
+ // An ASP.NET runtime may require an isolated database (Forge.Api refuses to start in a
1187
+ // managed host attempt without one). Issue it before the first launch. Release waits for
1188
+ // an in-flight provision, so a database issued during release is still dropped.
1189
+ const provision = this.databaseBroker.provision(dispatchAttemptId, fencingToken, signal)
1190
+ .then(capability => {
1191
+ active.databaseCapability = capability;
1192
+ return capability;
1193
+ });
1194
+ active.databaseProvision = provision;
1195
+ await provision;
1196
+ if (active.releasing) {
1197
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during database provisioning.");
1198
+ }
1199
+ await onProjectCheckpoint?.({
1200
+ code: "host_runtime_database_provisioned",
1201
+ message: `Provisioned isolated attempt database ${active.databaseCapability.databaseName} on the native test cluster.`,
1202
+ data: { database: active.databaseCapability.databaseName },
1203
+ });
1204
+ }
1205
+ // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1206
+ const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1207
+ const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1208
+ for (const configuredPort of configuredPorts) {
1209
+ const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
1210
+ const buildEnvironment = {
1211
+ ...configuredPort.launch.environment,
1212
+ ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1213
+ };
1214
+ const prebuild = createAspNetRuntimePrebuildPlan({
1215
+ command: configuredPort.launch.command,
1216
+ args: configuredPort.launch.args,
1217
+ cwd: workingDirectory,
1218
+ worktreePath: active.lease.worktreePath,
1219
+ environment: buildEnvironment,
1220
+ inputCommitSha: active.inputCommitSha,
1221
+ runtimeContractFingerprint: active.runtimeContractFingerprint,
1222
+ });
1223
+ if (prebuild) {
1224
+ await onProjectCheckpoint?.({
1225
+ code: "host_runtime_build_started",
1226
+ message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1227
+ data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1228
+ });
1229
+ const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal, capabilitySecrets), signal);
1230
+ await onProjectCheckpoint?.({
1231
+ code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1232
+ message: build.cacheHit
1233
+ ? `Reused the verified ASP.NET build for commit ${active.inputCommitSha.slice(0, 12)}.`
1234
+ : `ASP.NET runtime build completed for commit ${active.inputCommitSha.slice(0, 12)}; launching without another build.`,
1235
+ data: {
1236
+ input_commit_sha: active.inputCommitSha,
1237
+ build_fingerprint: build.fingerprint,
1238
+ receipt_path: build.receiptPath,
1239
+ },
1240
+ });
1241
+ }
1242
+ await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1243
+ command: configuredPort.launch.command,
1244
+ args: configuredPort.launch.args,
1245
+ cwd: workingDirectory,
1246
+ environment: {
1247
+ ...buildEnvironment,
1248
+ },
1249
+ }, launcher, signal);
1250
+ }
1251
+ const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1252
+ const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1253
+ const playwright = active.runtimeContract.contract.runtime.playwright;
1254
+ if (!playwright) {
1255
+ return {
1256
+ lease: promotedLease,
1257
+ environment: runtimeEnvironment,
1258
+ runtimeContract: active.runtimeContract,
1259
+ executionClass: active.executionClass,
1260
+ };
1261
+ }
1262
+ const playwrightPort = promotedLease.resources.ports.find(port => port.name === playwright.baseUrlPort);
1263
+ const playwrightPortConfig = active.runtimeContract.contract.runtime.ports
1264
+ .find(port => port.name === playwright.baseUrlPort);
1265
+ if (!playwrightPort || !playwrightPortConfig?.baseUrlEnv) {
1266
+ throw new Error("host_runtime_playwright_unavailable: the configured verified base URL is unavailable.");
1267
+ }
1268
+ if (playwrightPort.hostIp !== "127.0.0.1") {
1269
+ throw new Error("host_runtime_playwright_unavailable: Playwright requires an IPv4 loopback listener.");
1270
+ }
1271
+ const baseUrl = hostPortEnvironment(playwrightPortConfig, playwrightPort.hostIp, playwrightPort.hostPort)[playwrightPortConfig.baseUrlEnv];
1272
+ if (!baseUrl)
1273
+ throw new Error("host_runtime_playwright_unavailable: the configured base URL could not be rendered.");
1274
+ const pathFor = (role) => promotedLease.resources.paths.find(entry => entry.role === role)?.path ?? "";
1275
+ const preparedPlaywright = await this.playwrightAdapter.prepare(playwright, {
1276
+ worktreePath: promotedLease.worktreePath,
1277
+ temporaryDirectory: pathFor("temporary"),
1278
+ testOutputDirectory: pathFor("test_output"),
1279
+ browserProfileDirectory: pathFor("browser_profile"),
1280
+ baseUrl,
1281
+ ownershipToken: uuidHex(promotedLease.dispatchAttemptId, "dispatch attempt"),
1282
+ });
1283
+ return {
1284
+ lease: promotedLease,
1285
+ environment: { ...runtimeEnvironment, ...preparedPlaywright.environment },
1286
+ runtimeContract: active.runtimeContract,
1287
+ executionClass: active.executionClass,
1288
+ };
1289
+ }
1290
+ providerProcessRunner(dispatchAttemptId, fencingToken) {
1291
+ const active = this.active.get(dispatchAttemptId);
1292
+ if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
1293
+ return null;
1294
+ return new AttemptSupervisedProviderProcessRunner(active.processSupervisor, hostPortOwner(active.lease), this.listenerInspector, active.executionClass === "analysis_only", () => this.markCapacityReservationRunning(dispatchAttemptId, fencingToken));
1295
+ }
1296
+ markCapacityReservationRunning(dispatchAttemptId, fencingToken) {
1297
+ const reservation = this.capacityReservations.get(dispatchAttemptId);
1298
+ if (reservation?.owner.fencingToken === fencingToken)
1299
+ reservation.state = "running";
1300
+ }
1301
+ providerMemoryTelemetry(dispatchAttemptId, fencingToken) {
1302
+ const active = this.active.get(dispatchAttemptId);
1303
+ if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
1304
+ return null;
1305
+ return active.processSupervisor.providerMemoryTelemetry();
1306
+ }
1307
+ async promoteVerifiedRuntime(active, runtimeLease) {
1308
+ if (!active.parallelPromotionEligible)
1309
+ return runtimeLease;
1310
+ const verifiedPortNames = runtimeLease.resources.ports.map(port => port.name).sort((left, right) => left.localeCompare(right));
1311
+ const requiredPortNames = configuredLaunchPortNames(active.runtimeContract);
1312
+ if (requiredPortNames.length !== verifiedPortNames.length
1313
+ || requiredPortNames.some((name, index) => name !== verifiedPortNames[index])) {
1314
+ return runtimeLease;
1315
+ }
1316
+ const projectKey = projectHostRuntimeSingletonKey(active.repoId);
1317
+ const promotedLease = withRuntimeIsolationResources(runtimeLease, {
1318
+ ...runtimeLease.resources,
1319
+ singletonKeys: runtimeLease.resources.singletonKeys.filter(key => key !== projectKey),
1320
+ });
1321
+ await this.writeLedger(promotedLease);
1322
+ active.lease = promotedLease;
1323
+ try {
1324
+ const promotion = await this.promotionStore.observe(active.repoId, active.runtimeContract, runtimeLease.dispatchAttemptId, verifiedPortNames, active.inputCommitSha);
1325
+ this.knownPromotions.set(promotion.repoId, promotion);
1326
+ const owner = {
1327
+ dispatchAttemptId: runtimeLease.dispatchAttemptId,
1328
+ fencingToken: runtimeLease.fencingToken,
1329
+ };
1330
+ if (!this.parallelProjectOwned(projectKey, owner)) {
1331
+ this.convertSingletonToParallelProject(projectKey, owner, promotion);
1332
+ }
1333
+ const admission = this.admissions.get(runtimeLease.dispatchAttemptId);
1334
+ if (admission?.fencingToken === runtimeLease.fencingToken) {
1335
+ this.admissions.set(runtimeLease.dispatchAttemptId, {
1336
+ ...admission,
1337
+ keys: promotedLease.resources.singletonKeys,
1338
+ provisionalPromotionFingerprint: promotion.runtimeContractFingerprint,
1339
+ parallelProjectKey: projectKey,
1340
+ });
1341
+ }
1342
+ return promotedLease;
1343
+ }
1344
+ catch {
1345
+ await this.invalidatePromotion(active.repoId).catch(() => undefined);
1346
+ active.lease = runtimeLease;
1347
+ await this.writeLedger(runtimeLease);
1348
+ return runtimeLease;
1349
+ }
1350
+ }
1351
+ async launchNodeRuntime(dispatchAttemptId, fencingToken, portName, command, launcher, signal) {
1352
+ const active = this.active.get(dispatchAttemptId);
1353
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1354
+ throw new Error("host_runtime_adapter_unavailable: an active matching host runtime lease is required.");
1355
+ }
1356
+ const portConfig = active.runtimeContract.contract.runtime.ports.find(port => port.name === portName);
1357
+ if (!portConfig)
1358
+ throw new Error(`host_runtime_adapter_invalid: configured port '${portName}' was not found.`);
1359
+ if (active.lease.resources.ports.some(port => port.name === portName) || active.pendingAdapterLaunches.has(portName)) {
1360
+ throw new Error(`host_runtime_adapter_conflict: configured port '${portName}' is already active.`);
1361
+ }
1362
+ const controller = linkedAbortController(signal);
1363
+ let retainedByActiveRuntime = false;
1364
+ const operation = (async () => {
1365
+ const owner = hostPortOwner(active.lease);
1366
+ const launched = await this.nodeAdapter.launch(owner, portConfig, command, launcher, controller.signal);
1367
+ let cleaned = false;
1368
+ const cleanup = async () => {
1369
+ if (cleaned)
1370
+ return;
1371
+ await launcher.stop(launched.value);
1372
+ await this.portBroker.release(launched.reservation.reservationId, owner);
1373
+ cleaned = true;
1374
+ unlinkAbortController(controller, signal);
1375
+ };
1376
+ active.adapterCleanups.push(cleanup);
1377
+ try {
1378
+ if (active.releasing)
1379
+ throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
1380
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1381
+ ...active.lease.resources,
1382
+ ports: [...active.lease.resources.ports, {
1383
+ name: launched.reservation.name,
1384
+ protocol: launched.reservation.protocol,
1385
+ hostIp: launched.reservation.hostIp,
1386
+ hostPort: launched.reservation.hostPort,
1387
+ targetPort: launched.reservation.targetPort,
1388
+ }],
1389
+ });
1390
+ await this.writeLedger(runtimeLease);
1391
+ active.lease = runtimeLease;
1392
+ retainedByActiveRuntime = true;
1393
+ return { ...launched, runtimeLease };
1394
+ }
1395
+ catch (error) {
1396
+ try {
1397
+ await cleanup();
1398
+ removeCleanup(active.adapterCleanups, cleanup);
1399
+ }
1400
+ catch {
1401
+ // Preserve the cleanup and broker claim for the fenced release retry.
1402
+ }
1403
+ throw error;
1404
+ }
1405
+ })();
1406
+ active.pendingAdapterLaunches.set(portName, { controller, promise: operation });
1407
+ try {
1408
+ return await operation;
1409
+ }
1410
+ finally {
1411
+ active.pendingAdapterLaunches.delete(portName);
1412
+ if (!retainedByActiveRuntime)
1413
+ unlinkAbortController(controller, signal);
1414
+ }
1415
+ }
1416
+ async release(dispatchAttemptId, fencingToken, preservePreparation = false) {
1417
+ if (!preservePreparation)
1418
+ this.preparedReadiness.cancel(dispatchAttemptId, fencingToken);
1419
+ const active = this.active.get(dispatchAttemptId);
1420
+ if (!preservePreparation)
1421
+ this.pendingRenewals.delete(dispatchAttemptId);
1422
+ if (!active) {
1423
+ this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1424
+ this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1425
+ this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1426
+ this.deleteAdmission(dispatchAttemptId, fencingToken);
1427
+ return null;
1428
+ }
1429
+ if (active.lease.fencingToken !== fencingToken)
1430
+ return null;
1431
+ active.releasing = true;
1432
+ for (const pending of active.pendingAdapterLaunches.values()) {
1433
+ pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1434
+ }
1435
+ await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1436
+ await active.databaseProvision?.catch(() => undefined);
1437
+ let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1438
+ active.lease = releasing;
1439
+ await this.writeLedger(releasing);
1440
+ try {
1441
+ if (!active.runtimeResourcesReleased) {
1442
+ await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1443
+ await releaseAdapterResources(active.adapterCleanups);
1444
+ if (active.databaseCapability && this.databaseBroker) {
1445
+ // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1446
+ await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
1447
+ }
1448
+ active.runtimeResourcesReleased = true;
1449
+ // Runtime admission protects live processes, listeners, ports, and their
1450
+ // memory commitment. Once exact process and adapter cleanup succeeds,
1451
+ // diagnostics retention remains retryable evidence work and must not keep
1452
+ // consuming host capacity or blocking the next project dispatch.
1453
+ this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1454
+ this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1455
+ this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1456
+ this.deleteAdmission(dispatchAttemptId, fencingToken);
1457
+ }
1458
+ let evidenceRetainedAtAttemptRoot = false;
1459
+ try {
1460
+ const diagnosticsPath = await retainHostDiagnostics(this.stateRoot, active.attemptRoot, dispatchAttemptId, active.attemptRootIdentity, this.executionRoot);
1461
+ releasing = withRuntimeIsolationResources(releasing, {
1462
+ ...releasing.resources,
1463
+ paths: [...releasing.resources.paths.filter(entry => entry.role !== "diagnostics_archive"),
1464
+ { role: "diagnostics_archive", path: diagnosticsPath }],
1465
+ });
1466
+ }
1467
+ catch {
1468
+ // Runtime teardown is already proven above. Diagnostics archival is
1469
+ // deliberately non-destructive and may refuse a changed or unsupported
1470
+ // attempt-root inventory. Preserve that root and its released ledger for
1471
+ // operator inspection/reconciliation without converting completed
1472
+ // teardown into a capacity-owning degraded runtime.
1473
+ evidenceRetainedAtAttemptRoot = true;
1474
+ }
1475
+ if (!evidenceRetainedAtAttemptRoot)
1476
+ await removeHostAttemptRoot(active.attemptRoot);
1477
+ const released = transitionRuntimeIsolationLease(releasing, "released");
1478
+ // Publish the terminal in-memory state before its serialized write. Any writer
1479
+ // that already captured this active owner must observe the terminal fence and
1480
+ // cannot recreate a nonterminal ledger after release completes.
1481
+ active.lease = released;
1482
+ await this.writeLedger(released);
1483
+ if (!evidenceRetainedAtAttemptRoot) {
1484
+ await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1485
+ }
1486
+ releasing = released;
1487
+ this.active.delete(dispatchAttemptId);
1488
+ this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1489
+ this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1490
+ this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1491
+ this.deleteAdmission(dispatchAttemptId, fencingToken);
1492
+ return releasing;
1493
+ }
1494
+ catch (error) {
1495
+ const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
1496
+ active.lease = degraded;
1497
+ await this.writeLedger(degraded).catch(() => undefined);
1498
+ throw new HostRuntimeLeaseCleanupError(degraded, error);
1499
+ }
1500
+ }
1501
+ async readLedgers() {
1502
+ const root = path.join(this.stateRoot, "runtime-ledger", "host");
1503
+ const entries = await fs.readdir(root, { withFileTypes: true }).catch(error => {
1504
+ if (error.code === "ENOENT")
1505
+ return [];
1506
+ throw error;
1507
+ });
1508
+ const ledgers = [];
1509
+ for (const entry of entries) {
1510
+ if (!entry.isFile() || !/^[0-9a-f]{32}\.json$/u.test(entry.name))
1511
+ continue;
1512
+ try {
1513
+ const value = JSON.parse(await fs.readFile(path.join(root, entry.name), "utf8"));
1514
+ if (!validHostRuntimeLedger(value))
1515
+ continue;
1516
+ const expectedName = `${uuidHex(value.runtimeLease.dispatchAttemptId, "dispatch attempt")}.json`;
1517
+ if (entry.name !== expectedName)
1518
+ continue;
1519
+ ledgers.push(value);
1520
+ }
1521
+ catch {
1522
+ // An invalid ledger has no trustworthy ownership identity and is never reaped.
1523
+ }
1524
+ }
1525
+ return ledgers;
1526
+ }
1527
+ async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
1528
+ const logsRoot = path.join(attemptRoot, "logs");
1529
+ const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
1530
+ if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
1531
+ throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
1532
+ }
1533
+ await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
1534
+ const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
1535
+ const logsEntry = rootEntries.find(entry => entry.name === "logs");
1536
+ if (!logsEntry)
1537
+ return [];
1538
+ if (logsEntry.kind !== "directory") {
1539
+ throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1540
+ }
1541
+ const outcomes = [];
1542
+ const failures = [];
1543
+ try {
1544
+ const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1545
+ for (const entry of entries) {
1546
+ if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1547
+ continue;
1548
+ const metadataPath = path.join(logsRoot, entry.name);
1549
+ const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1550
+ if (!validHostProcessSupervisorMetadata(value, lease)) {
1551
+ throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1552
+ }
1553
+ outcomes.push(await this.processRecovery.recover(value));
1554
+ }
1555
+ }
1556
+ catch (error) {
1557
+ failures.push(error);
1558
+ }
1559
+ // Managed commands run in their own process groups and record their ownership apart
1560
+ // from the attempt's supervised children. They are recovered even when recovering a
1561
+ // supervised child failed, and both failures are reported together.
1562
+ try {
1563
+ const managed = await terminateAttemptManagedCommands({
1564
+ logDirectory: logsRoot,
1565
+ dispatchAttemptId: lease.dispatchAttemptId,
1566
+ runtimeLeaseId: lease.executionLeaseId,
1567
+ pinnedLogDirectory: logsEntry.identity,
1568
+ }, { reason: "attempt_teardown" });
1569
+ for (const command of managed) {
1570
+ if (command.outcome === "terminated" || command.outcome === "pid_reused")
1571
+ outcomes.push(command.outcome);
1572
+ }
1573
+ }
1574
+ catch (error) {
1575
+ failures.push(error);
1576
+ }
1577
+ if (failures.length === 1)
1578
+ throw failures[0];
1579
+ if (failures.length > 1)
1580
+ throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1581
+ return outcomes;
1582
+ }
1583
+ async markLedgerDegraded(ledger) {
1584
+ const lease = ledger.runtimeLease;
1585
+ if (lease.state === "released")
1586
+ return;
1587
+ const degraded = transitionHostLeaseForCleanup(lease, "degraded");
1588
+ const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
1589
+ this.rememberDegraded(degraded, repoId);
1590
+ await this.writeLedger(degraded, repoId ?? undefined, deserializeHostAttemptRootIdentity(ledger.attemptRootIdentity)).catch(() => undefined);
1591
+ }
1592
+ rememberDegraded(lease, repoId) {
1593
+ this.degraded.set(lease.dispatchAttemptId, { lease, repoId });
1594
+ if (!repoId)
1595
+ return;
1596
+ const owner = { dispatchAttemptId: lease.dispatchAttemptId, fencingToken: lease.fencingToken };
1597
+ const projectKey = projectHostRuntimeSingletonKey(repoId);
1598
+ const existing = this.singletonOwners.get(projectKey);
1599
+ if (!existing || sameSingletonOwner(existing, owner))
1600
+ this.singletonOwners.set(projectKey, owner);
1601
+ }
1602
+ forgetDegraded(dispatchAttemptId, fencingToken) {
1603
+ if (this.degraded.get(dispatchAttemptId)?.lease.fencingToken !== fencingToken)
1604
+ return;
1605
+ this.degraded.delete(dispatchAttemptId);
1606
+ this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1607
+ this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1608
+ }
1609
+ attemptRoot(dispatchAttemptId) {
1610
+ return path.join(this.executionRoot, "a", compactHostAttemptId(dispatchAttemptId));
1611
+ }
1612
+ writeLedger(runtimeLease, explicitRepoId, explicitAttemptRootIdentity) {
1613
+ const activeOwner = this.active.get(runtimeLease.dispatchAttemptId);
1614
+ const write = this.ledgerWriteTail.then(() => {
1615
+ if (activeOwner?.lease.fencingToken === runtimeLease.fencingToken
1616
+ && activeOwner.lease.state === "released"
1617
+ && runtimeLease.state !== "released") {
1618
+ return;
1619
+ }
1620
+ return this.writeLedgerAtomic(runtimeLease, explicitRepoId, explicitAttemptRootIdentity);
1621
+ });
1622
+ this.ledgerWriteTail = write.catch(() => undefined);
1623
+ return write;
1624
+ }
1625
+ async writeLedgerAtomic(runtimeLease, explicitRepoId, explicitAttemptRootIdentity) {
1626
+ const root = path.join(this.stateRoot, "runtime-ledger", "host");
1627
+ await ensurePrivateDirectory(root);
1628
+ const target = this.ledgerPath(runtimeLease.dispatchAttemptId);
1629
+ const temporary = `${target}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
1630
+ try {
1631
+ const handle = await fs.open(temporary, "wx", 0o600);
1632
+ try {
1633
+ const repoId = explicitRepoId
1634
+ ?? this.active.get(runtimeLease.dispatchAttemptId)?.repoId
1635
+ ?? this.admissions.get(runtimeLease.dispatchAttemptId)?.repoId
1636
+ ?? this.degraded.get(runtimeLease.dispatchAttemptId)?.repoId
1637
+ ?? undefined;
1638
+ const attemptRootIdentity = explicitAttemptRootIdentity
1639
+ ?? this.active.get(runtimeLease.dispatchAttemptId)?.attemptRootIdentity
1640
+ ?? undefined;
1641
+ const ledger = {
1642
+ schemaVersion: 1,
1643
+ ...(repoId ? { repoId } : {}),
1644
+ ...(attemptRootIdentity
1645
+ ? { attemptRootIdentity: serializeHostAttemptRootIdentity(attemptRootIdentity) }
1646
+ : {}),
1647
+ runtimeLease,
1648
+ };
1649
+ await handle.writeFile(`${JSON.stringify(ledger)}\n`);
1650
+ await handle.sync();
1651
+ }
1652
+ finally {
1653
+ await handle.close();
1654
+ }
1655
+ await fs.rename(temporary, target);
1656
+ }
1657
+ catch (error) {
1658
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
1659
+ throw new Error(`host_runtime_ledger_write_failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1660
+ }
1661
+ }
1662
+ ledgerPath(dispatchAttemptId) {
1663
+ const attemptHex = uuidHex(dispatchAttemptId, "dispatch attempt");
1664
+ return path.join(this.stateRoot, "runtime-ledger", "host", `${attemptHex}.json`);
1665
+ }
1666
+ singletonKeysAvailable(keys) {
1667
+ return keys.every(key => !this.singletonOwners.has(key) && !this.parallelProjectOwners.has(key));
1668
+ }
1669
+ assignSingletonKeys(keys, owner) {
1670
+ for (const key of keys)
1671
+ this.singletonOwners.set(key, owner);
1672
+ }
1673
+ releaseSingletonKeys(dispatchAttemptId, fencingToken) {
1674
+ for (const [key, owner] of this.singletonOwners) {
1675
+ if (owner.dispatchAttemptId === dispatchAttemptId && owner.fencingToken === fencingToken) {
1676
+ this.singletonOwners.delete(key);
1677
+ }
1678
+ }
1679
+ this.drainAdmissionWaiters();
1680
+ }
1681
+ convertSingletonToParallelProject(key, owner, promotion) {
1682
+ if (!sameSingletonOwner(this.singletonOwners.get(key), owner)) {
1683
+ throw new Error("host_runtime_parallel_promotion_stale: matching exclusive project admission is required.");
1684
+ }
1685
+ this.assignParallelProject(key, owner);
1686
+ this.singletonOwners.delete(key);
1687
+ for (let index = 0; index < this.singletonWaiters.length;) {
1688
+ const waiter = this.singletonWaiters[index];
1689
+ if (waiter.priority !== "foreground" || waiter.keys.length !== 1 || waiter.keys[0] !== key) {
1690
+ index += 1;
1691
+ continue;
1692
+ }
1693
+ this.singletonWaiters.splice(index, 1);
1694
+ clearAdmissionDeadline(waiter);
1695
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1696
+ this.assignParallelProject(key, waiter.owner);
1697
+ this.knownPromotions.set(promotion.repoId, promotion);
1698
+ waiter.resolve([]);
1699
+ }
1700
+ this.drainAdmissionWaiters();
1701
+ }
1702
+ parallelProjectOwned(key, owner) {
1703
+ return sameSingletonOwner(this.parallelProjectOwners.get(key)?.get(owner.dispatchAttemptId), owner);
1704
+ }
1705
+ parallelProjectAvailable(key, priority = "foreground") {
1706
+ return !this.singletonOwners.has(key)
1707
+ && !this.singletonWaiters.some(waiter => waiter.keys.includes(key)
1708
+ && (priority === "background" || waiter.priority === "foreground"));
1709
+ }
1710
+ assignParallelProject(key, owner) {
1711
+ const owners = this.parallelProjectOwners.get(key) ?? new Map();
1712
+ owners.set(owner.dispatchAttemptId, owner);
1713
+ this.parallelProjectOwners.set(key, owners);
1714
+ }
1715
+ releaseParallelProjectNoDrain(key, owner) {
1716
+ const owners = this.parallelProjectOwners.get(key);
1717
+ if (!sameSingletonOwner(owners?.get(owner.dispatchAttemptId), owner))
1718
+ return;
1719
+ owners.delete(owner.dispatchAttemptId);
1720
+ if (owners.size === 0)
1721
+ this.parallelProjectOwners.delete(key);
1722
+ }
1723
+ releaseParallelProjects(dispatchAttemptId, fencingToken) {
1724
+ const owner = { dispatchAttemptId, fencingToken };
1725
+ for (const key of [...this.parallelProjectOwners.keys()]) {
1726
+ this.releaseParallelProjectNoDrain(key, owner);
1727
+ }
1728
+ this.drainAdmissionWaiters();
1729
+ }
1730
+ deleteAdmission(dispatchAttemptId, fencingToken) {
1731
+ if (this.admissions.get(dispatchAttemptId)?.fencingToken === fencingToken) {
1732
+ this.admissions.delete(dispatchAttemptId);
1733
+ }
1734
+ this.releaseHostCapacity(dispatchAttemptId, fencingToken);
1735
+ }
1736
+ renewAdmissionWaiterDeadline(dispatchAttemptId, fencingToken, expiresAt) {
1737
+ for (const waiter of [
1738
+ ...this.singletonWaiters,
1739
+ ...this.parallelProjectWaiters,
1740
+ ...this.capacityWaiters,
1741
+ ...this.backgroundAdmissionWaiters,
1742
+ ]) {
1743
+ if (!sameSingletonOwner(waiter.owner, { dispatchAttemptId, fencingToken })
1744
+ || Date.parse(expiresAt) <= Date.parse(waiter.expiresAt))
1745
+ continue;
1746
+ waiter.expiresAt = expiresAt;
1747
+ clearAdmissionDeadline(waiter);
1748
+ waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
1749
+ }
1750
+ }
1751
+ clearPendingRenewal(owner) {
1752
+ if (this.pendingRenewals.get(owner.dispatchAttemptId)?.fencingToken === owner.fencingToken) {
1753
+ this.pendingRenewals.delete(owner.dispatchAttemptId);
1754
+ }
1755
+ }
1756
+ cancelAdmissionWaiters(dispatchAttemptId, fencingToken, reason) {
1757
+ const owner = { dispatchAttemptId, fencingToken };
1758
+ for (const waiters of [
1759
+ this.singletonWaiters,
1760
+ this.parallelProjectWaiters,
1761
+ this.capacityWaiters,
1762
+ this.backgroundAdmissionWaiters,
1763
+ ]) {
1764
+ for (let index = waiters.length - 1; index >= 0; index -= 1) {
1765
+ const waiter = waiters[index];
1766
+ if (!sameSingletonOwner(waiter.owner, owner))
1767
+ continue;
1768
+ waiters.splice(index, 1);
1769
+ clearAdmissionDeadline(waiter);
1770
+ if ("capacityRecheckTimer" in waiter)
1771
+ clearCapacityRecheck(waiter);
1772
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1773
+ waiter.reject(new Error(`host_runtime_admission_cancelled: ${reason}`));
1774
+ }
1775
+ }
1776
+ this.drainAdmissionWaiters();
1777
+ }
1778
+ drainSingletonWaiters() {
1779
+ for (let index = 0; index < this.singletonWaiters.length;) {
1780
+ const waiter = this.singletonWaiters[index];
1781
+ if (waiter.signal?.aborted) {
1782
+ this.singletonWaiters.splice(index, 1);
1783
+ clearAdmissionDeadline(waiter);
1784
+ waiter.signal.removeEventListener("abort", waiter.abort);
1785
+ this.clearPendingRenewal(waiter.owner);
1786
+ waiter.reject(cancellationError(waiter.signal));
1787
+ continue;
1788
+ }
1789
+ if (admissionExpired(waiter.expiresAt)) {
1790
+ this.singletonWaiters.splice(index, 1);
1791
+ clearAdmissionDeadline(waiter);
1792
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1793
+ this.clearPendingRenewal(waiter.owner);
1794
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
1795
+ continue;
1796
+ }
1797
+ if (!this.singletonKeysAvailable(waiter.keys)) {
1798
+ index += 1;
1799
+ continue;
1800
+ }
1801
+ this.singletonWaiters.splice(index, 1);
1802
+ clearAdmissionDeadline(waiter);
1803
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1804
+ this.assignSingletonKeys(waiter.keys, waiter.owner);
1805
+ waiter.resolve(waiter.keys);
1806
+ }
1807
+ }
1808
+ drainParallelProjectWaiters() {
1809
+ for (let index = 0; index < this.parallelProjectWaiters.length;) {
1810
+ const waiter = this.parallelProjectWaiters[index];
1811
+ if (waiter.signal?.aborted) {
1812
+ this.parallelProjectWaiters.splice(index, 1);
1813
+ clearAdmissionDeadline(waiter);
1814
+ waiter.signal.removeEventListener("abort", waiter.abort);
1815
+ this.clearPendingRenewal(waiter.owner);
1816
+ waiter.reject(cancellationError(waiter.signal));
1817
+ continue;
1818
+ }
1819
+ if (admissionExpired(waiter.expiresAt)) {
1820
+ this.parallelProjectWaiters.splice(index, 1);
1821
+ clearAdmissionDeadline(waiter);
1822
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1823
+ this.clearPendingRenewal(waiter.owner);
1824
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
1825
+ continue;
1826
+ }
1827
+ if (!this.parallelProjectAvailable(waiter.key, waiter.priority)) {
1828
+ index += 1;
1829
+ continue;
1830
+ }
1831
+ this.parallelProjectWaiters.splice(index, 1);
1832
+ clearAdmissionDeadline(waiter);
1833
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1834
+ this.assignParallelProject(waiter.key, waiter.owner);
1835
+ waiter.resolve();
1836
+ }
1837
+ }
1838
+ drainBackgroundAdmissionWaiters() {
1839
+ if (this.hasForegroundDemand())
1840
+ return;
1841
+ for (let index = 0; index < this.backgroundAdmissionWaiters.length;) {
1842
+ const waiter = this.backgroundAdmissionWaiters[index];
1843
+ if (waiter.signal?.aborted) {
1844
+ this.backgroundAdmissionWaiters.splice(index, 1);
1845
+ clearAdmissionDeadline(waiter);
1846
+ clearCapacityRecheck(waiter);
1847
+ waiter.signal.removeEventListener("abort", waiter.abort);
1848
+ this.clearPendingRenewal(waiter.owner);
1849
+ waiter.reject(cancellationError(waiter.signal));
1850
+ continue;
1851
+ }
1852
+ if (admissionExpired(waiter.expiresAt)) {
1853
+ this.backgroundAdmissionWaiters.splice(index, 1);
1854
+ clearAdmissionDeadline(waiter);
1855
+ clearCapacityRecheck(waiter);
1856
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1857
+ this.clearPendingRenewal(waiter.owner);
1858
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
1859
+ continue;
1860
+ }
1861
+ if (!this.singletonKeysAvailable(waiter.keys) || !this.hostCapacityAvailable(waiter.resources)) {
1862
+ index += 1;
1863
+ continue;
1864
+ }
1865
+ this.backgroundAdmissionWaiters.splice(index, 1);
1866
+ clearAdmissionDeadline(waiter);
1867
+ clearCapacityRecheck(waiter);
1868
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1869
+ this.assignSingletonKeys(waiter.keys, waiter.owner);
1870
+ this.capacityReservations.set(waiter.owner.dispatchAttemptId, {
1871
+ owner: waiter.owner,
1872
+ resources: waiter.resources,
1873
+ state: "pending",
1874
+ });
1875
+ waiter.resolve(waiter.keys);
1876
+ }
1877
+ }
1878
+ async refreshKnownPromotions() {
1879
+ const promotions = await this.promotionStore.list();
1880
+ this.knownPromotions.clear();
1881
+ for (const promotion of promotions)
1882
+ this.knownPromotions.set(promotion.repoId, promotion);
1883
+ }
1884
+ async invalidatePromotion(repoId, scope = "all") {
1885
+ await this.promotionStore.invalidate(repoId, scope);
1886
+ this.knownPromotions.delete(repoId.trim().toLowerCase());
1887
+ }
1888
+ drainAdmissionWaiters() {
1889
+ this.reconcileReservationOwners();
1890
+ this.drainSingletonWaiters();
1891
+ this.drainParallelProjectWaiters();
1892
+ this.drainCapacityWaiters();
1893
+ this.drainBackgroundAdmissionWaiters();
1894
+ }
1895
+ reconcileReservationOwners() {
1896
+ for (const [key, owner] of this.singletonOwners) {
1897
+ if (!this.reservationOwnerIsLive(owner))
1898
+ this.singletonOwners.delete(key);
1899
+ }
1900
+ for (const [key, owners] of this.parallelProjectOwners) {
1901
+ for (const [dispatchAttemptId, owner] of owners) {
1902
+ const awaitingExclusiveUpgrade = this.singletonWaiters.some(waiter => waiter.keys.includes(key) && sameSingletonOwner(waiter.owner, owner));
1903
+ // A parallel owner cannot legitimately keep the shared claim after the
1904
+ // same fenced attempt has queued its exclusive downgrade. Reconcile the
1905
+ // half-upgraded state before testing singleton availability so one missed
1906
+ // release cannot make an attempt wait behind itself until lease expiry.
1907
+ if (awaitingExclusiveUpgrade || !this.reservationOwnerIsLive(owner)) {
1908
+ owners.delete(dispatchAttemptId);
1909
+ }
1910
+ }
1911
+ if (owners.size === 0)
1912
+ this.parallelProjectOwners.delete(key);
1913
+ }
1914
+ }
1915
+ reservationOwnerIsLive(owner) {
1916
+ if (this.acquiringAdmissions.has(hostRuntimeOwnerKey(owner)))
1917
+ return true;
1918
+ if (this.admissions.get(owner.dispatchAttemptId)?.fencingToken === owner.fencingToken)
1919
+ return true;
1920
+ if (this.active.get(owner.dispatchAttemptId)?.lease.fencingToken === owner.fencingToken)
1921
+ return true;
1922
+ if (this.degraded.get(owner.dispatchAttemptId)?.lease.fencingToken === owner.fencingToken)
1923
+ return true;
1924
+ if (sameSingletonOwner(this.capacityReservations.get(owner.dispatchAttemptId)?.owner, owner))
1925
+ return true;
1926
+ return [
1927
+ ...this.singletonWaiters,
1928
+ ...this.parallelProjectWaiters,
1929
+ ...this.capacityWaiters,
1930
+ ...this.backgroundAdmissionWaiters,
1931
+ ].some(waiter => sameSingletonOwner(waiter.owner, owner));
1932
+ }
1933
+ hasAttemptRepresentation(dispatchAttemptId, fencingToken) {
1934
+ return this.reservationOwnerIsLive({ dispatchAttemptId, fencingToken });
1935
+ }
1936
+ }
1937
+ class AttemptSupervisedProviderProcessRunner {
1938
+ supervisor;
1939
+ owner;
1940
+ listenerInspector;
1941
+ enforceNoListeners;
1942
+ onProcessTreeStarted;
1943
+ constructor(supervisor, owner, listenerInspector, enforceNoListeners, onProcessTreeStarted) {
1944
+ this.supervisor = supervisor;
1945
+ this.owner = owner;
1946
+ this.listenerInspector = listenerInspector;
1947
+ this.enforceNoListeners = enforceNoListeners;
1948
+ this.onProcessTreeStarted = onProcessTreeStarted;
1949
+ }
1950
+ async run(request, handlers = {}, signal) {
1951
+ const baselineListeners = this.enforceNoListeners
1952
+ ? new Set(await this.listenerInspector.inspectLoopbackListeners())
1953
+ : new Set();
1954
+ const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
1955
+ this.onProcessTreeStarted();
1956
+ try {
1957
+ return await this.awaitProviderResult(child, baselineListeners, signal);
1958
+ }
1959
+ finally {
1960
+ // The provider tree, and the MCP server inside it, is gone. A managed command that
1961
+ // server started now has no supervisor and no receipt writer, so it must not keep
1962
+ // running into the next provider generation. This never rejects; a command it
1963
+ // cannot prove stopped is left to attempt teardown, which fails closed.
1964
+ await this.supervisor.stopOrphanedManagedCommands();
1965
+ }
1966
+ }
1967
+ async awaitProviderResult(child, baselineListeners, signal) {
1968
+ if (!this.enforceNoListeners)
1969
+ return await child.result;
1970
+ let settled = false;
1971
+ let inspectionFailure;
1972
+ const monitor = (async () => {
1973
+ while (!settled) {
1974
+ try {
1975
+ const ports = (await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner))
1976
+ .filter(port => !baselineListeners.has(port));
1977
+ if (ports.length > 0) {
1978
+ inspectionFailure = new Error(`host_analysis_listener_violation: analysis-only provider opened undeclared loopback listener(s): ${ports.join(", ")}.`);
1979
+ await child.stop(this.owner.fencingToken).catch(() => undefined);
1980
+ return;
1981
+ }
1982
+ }
1983
+ catch (error) {
1984
+ inspectionFailure = error;
1985
+ await child.stop(this.owner.fencingToken).catch(() => undefined);
1986
+ return;
1987
+ }
1988
+ await waitForAnalysisInspection(250, signal).catch(error => {
1989
+ if (!settled && !signal?.aborted)
1990
+ inspectionFailure = error;
1991
+ });
1992
+ }
1993
+ })();
1994
+ try {
1995
+ const result = await child.result;
1996
+ settled = true;
1997
+ await monitor;
1998
+ if (inspectionFailure)
1999
+ throw inspectionFailure;
2000
+ return result;
2001
+ }
2002
+ catch (error) {
2003
+ settled = true;
2004
+ await monitor.catch(() => undefined);
2005
+ if (inspectionFailure)
2006
+ throw inspectionFailure;
2007
+ throw error;
2008
+ }
2009
+ }
2010
+ }
2011
+ function waitForAnalysisInspection(milliseconds, signal) {
2012
+ if (signal?.aborted)
2013
+ return Promise.reject(cancellationError(signal));
2014
+ return new Promise((resolve, reject) => {
2015
+ const timer = setTimeout(() => {
2016
+ signal?.removeEventListener("abort", abort);
2017
+ resolve();
2018
+ }, milliseconds);
2019
+ const abort = () => {
2020
+ clearTimeout(timer);
2021
+ reject(cancellationError(signal));
2022
+ };
2023
+ signal?.addEventListener("abort", abort, { once: true });
2024
+ });
2025
+ }
2026
+ export class HostRuntimeLeaseCleanupError extends Error {
2027
+ lease;
2028
+ constructor(lease, cause) {
2029
+ super(`host_runtime_cleanup_degraded: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
2030
+ this.lease = lease;
2031
+ this.name = "HostRuntimeLeaseCleanupError";
2032
+ }
2033
+ }
2034
+ export class HostRuntimeAdmissionExpiredError extends Error {
2035
+ constructor() {
2036
+ super("host_runtime_admission_expired: dispatch lease expired while waiting for managed host admission.");
2037
+ this.name = "HostRuntimeAdmissionExpiredError";
2038
+ }
2039
+ }
2040
+ export class HostRuntimeCapacityRequestImpossibleError extends Error {
2041
+ constructor(reason) {
2042
+ super(`host_runtime_capacity_request_impossible: ${reason}`);
2043
+ this.name = "HostRuntimeCapacityRequestImpossibleError";
2044
+ }
2045
+ }
2046
+ export function hostRuntimeEventResources(lease, runtimeContract, executionClass = "managed_runtime") {
2047
+ const requestedHostConcurrency = runtimeContract?.contract.runtime.hostConcurrency ?? "serial";
2048
+ const configuredLaunches = runtimeContract?.contract.runtime.ports.filter(port => port.launch !== null) ?? [];
2049
+ const verifiedLaunches = configuredLaunches.filter(configured => lease.resources.ports.some(port => port.name === configured.name));
2050
+ const effectiveConcurrency = effectiveHostConcurrency(lease, runtimeContract, executionClass);
2051
+ return {
2052
+ agentContainer: null,
2053
+ sidecarContainers: [],
2054
+ networks: [],
2055
+ volumes: [],
2056
+ publishedPorts: lease.resources.ports,
2057
+ hostConcurrency: effectiveConcurrency,
2058
+ requestedHostConcurrency,
2059
+ hostParallelPromotion: effectiveConcurrency === "host_parallel_safe"
2060
+ ? executionClass === "analysis_only" ? "analysis_profile_enforced" : "observed_probe_passed"
2061
+ : requestedHostConcurrency !== "parallel"
2062
+ ? "not_requested"
2063
+ : configuredLaunches.length > 0 && verifiedLaunches.length === configuredLaunches.length
2064
+ ? "pending_live_parallel_proof"
2065
+ : "pending_adapter_probe",
2066
+ verifiedRuntimePorts: verifiedLaunches.map(port => port.name),
2067
+ runtimeContractSource: runtimeContract?.source ?? "default",
2068
+ executionClass,
2069
+ requestedPorts: runtimeContract?.contract.runtime.ports.map(port => port.name) ?? [],
2070
+ singletonKeys: lease.resources.singletonKeys,
2071
+ processSupervisorId: lease.resources.processSupervisorId,
2072
+ runtimeLease: lease,
2073
+ };
2074
+ }
2075
+ export function hostRuntimeSingletonKeys(dispatch) {
2076
+ return [projectHostRuntimeSingletonKey(dispatch.repo.id)];
2077
+ }
2078
+ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass, databaseCapability) {
2079
+ const pathFor = (role) => lease.resources.paths.find(entry => entry.role === role)?.path ?? "";
2080
+ const environment = {
2081
+ FORGE_SESSION_ID: sessionId,
2082
+ FORGE_RUNTIME_MODE: "host",
2083
+ FORGE_RESOURCE_LEASE_ID: lease.leaseId,
2084
+ FORGE_DISPATCH_ATTEMPT_ID: lease.dispatchAttemptId,
2085
+ FORGE_E2E_OWNERSHIP_MODE: "attempt",
2086
+ FORGE_E2E_OWNERSHIP_TOKEN: uuidHex(lease.dispatchAttemptId, "dispatch attempt"),
2087
+ FORGE_EXECUTION_LEASE_ID: lease.executionLeaseId,
2088
+ FORGE_FENCING_TOKEN: lease.fencingToken,
2089
+ FORGE_WORKSPACE: lease.worktreePath,
2090
+ FORGE_WORKTREE_PATH: lease.worktreePath,
2091
+ FORGE_TMPDIR: pathFor("temporary"),
2092
+ FORGE_LOG_DIR: pathFor("logs"),
2093
+ FORGE_CACHE_DIR: pathFor("cache"),
2094
+ FORGE_BROWSER_PROFILE_DIR: pathFor("browser_profile"),
2095
+ FORGE_TEST_OUTPUT_DIR: pathFor("test_output"),
2096
+ // Project-authored ASP.NET code must not fall back to the durable Forge
2097
+ // database when no brokered attempt database exists. The API policy treats
2098
+ // this marker as a fail-closed isolation requirement.
2099
+ FORGE_ATTEMPT_DATABASE_POLICY: "isolated_only",
2100
+ FORGE_ATTEMPT_DATABASE_SCHEMA: `forge_attempt_${uuidHex(lease.dispatchAttemptId, "dispatch attempt")}`,
2101
+ FORGE_ATTEMPT_DATABASE_READINESS_PATH: path.join(pathFor("logs"), "attempt-database-readiness.json"),
2102
+ FORGE_PROCESS_SUPERVISOR_ID: lease.resources.processSupervisorId ?? "",
2103
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: pathFor("process_supervisor_metadata"),
2104
+ FORGE_HOST_CONCURRENCY: effectiveHostConcurrency(lease, runtimeContract, executionClass),
2105
+ FORGE_HOST_CONCURRENCY_REQUESTED: runtimeContract.contract.runtime.hostConcurrency,
2106
+ FORGE_RUNTIME_EXECUTION_CLASS: executionClass,
2107
+ FORGE_HOST_RUNTIME_CONTRACT_SOURCE: runtimeContract.source,
2108
+ FORGE_SINGLETON_KEYS: lease.resources.singletonKeys.join(","),
2109
+ TMPDIR: pathFor("temporary"),
2110
+ TMP: pathFor("temporary"),
2111
+ TEMP: pathFor("temporary"),
2112
+ XDG_CACHE_HOME: pathFor("cache"),
2113
+ NPM_CONFIG_CACHE: path.join(pathFor("cache"), "npm"),
2114
+ };
2115
+ if (lease.resources.singletonKeys.length === 0)
2116
+ delete environment.FORGE_SINGLETON_KEYS;
2117
+ if (databaseCapability)
2118
+ environment[attemptDatabaseCapabilityEnvironment] = databaseCapability.connectionString;
2119
+ const resolvedBaseUrls = [];
2120
+ for (const assigned of lease.resources.ports) {
2121
+ const configured = runtimeContract.contract.runtime.ports.find(port => port.name === assigned.name);
2122
+ if (!configured || assigned.hostIp !== "127.0.0.1")
2123
+ continue;
2124
+ Object.assign(environment, hostPortEnvironment(configured, assigned.hostIp, assigned.hostPort));
2125
+ const normalizedName = assigned.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
2126
+ environment[`FORGE_${normalizedName}_PORT`] = String(assigned.hostPort);
2127
+ if (configured.baseUrlEnv && configured.format) {
2128
+ const baseUrl = hostPortEnvironment(configured, assigned.hostIp, assigned.hostPort)[configured.baseUrlEnv];
2129
+ if (baseUrl) {
2130
+ environment[`FORGE_${normalizedName}_URL`] = baseUrl;
2131
+ resolvedBaseUrls.push(baseUrl);
2132
+ }
2133
+ }
2134
+ }
2135
+ if (environment.FORGE_API_URL)
2136
+ environment.FORGE_E2E_API_URL = environment.FORGE_API_URL;
2137
+ if (environment.FORGE_WEB_URL)
2138
+ environment.FORGE_E2E_WEB_URL = environment.FORGE_WEB_URL;
2139
+ if (resolvedBaseUrls.length === 1)
2140
+ environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2141
+ return environment;
2142
+ }
2143
+ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = []) {
2144
+ const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2145
+ const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2146
+ const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2147
+ let stdoutTail = "";
2148
+ let stderrTail = "";
2149
+ const append = async (target, line) => {
2150
+ await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2151
+ };
2152
+ const child = await supervisor.startChildReady(childName, {
2153
+ command: plan.command,
2154
+ args: plan.args,
2155
+ cwd: plan.cwd,
2156
+ env: plan.environment,
2157
+ captureOutput: false,
2158
+ }, {
2159
+ onStdoutLine: async (line) => {
2160
+ stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2161
+ await append(stdoutLogPath, line);
2162
+ },
2163
+ onStderrLine: async (line) => {
2164
+ stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2165
+ await append(stderrLogPath, line);
2166
+ },
2167
+ }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2168
+ const result = await child.result;
2169
+ return {
2170
+ exitCode: result.exitCode,
2171
+ stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2172
+ stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2173
+ stdoutLogPath,
2174
+ stderrLogPath,
2175
+ };
2176
+ }
2177
+ function appendRuntimeBuildTail(current, value) {
2178
+ if (!value)
2179
+ return current;
2180
+ return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
2181
+ }
2182
+ function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
2183
+ if (executionClass === "analysis_only") {
2184
+ const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
2185
+ return analysisSingletonHeld ? "host_serial_only" : "host_parallel_safe";
2186
+ }
2187
+ if (!runtimeContract || !hostRuntimeParallelEligible(runtimeContract))
2188
+ return "host_serial_only";
2189
+ const requiredPorts = configuredLaunchPortNames(runtimeContract);
2190
+ const everyPortVerified = requiredPorts.length > 0
2191
+ && requiredPorts.every(name => lease.resources.ports.some(port => port.name === name));
2192
+ const projectSingletonHeld = lease.resources.singletonKeys.some(key => key.endsWith(":host-runtime"));
2193
+ return everyPortVerified && !projectSingletonHeld ? "host_parallel_safe" : "host_serial_only";
2194
+ }
2195
+ function projectHostRuntimeSingletonKey(repoId) {
2196
+ return `project:${repoId.toLowerCase()}:host-runtime`;
2197
+ }
2198
+ function projectHostAnalysisKey(repoId) {
2199
+ return `project:${repoId.toLowerCase()}:host-analysis`;
2200
+ }
2201
+ function hostRuntimeDeclaredSingletonKey(resource) {
2202
+ return `runtime:${resource}`;
2203
+ }
2204
+ function runtimeExecutionClass(dispatch) {
2205
+ return dispatch.runtimeIntent?.executionClass === "analysis_only"
2206
+ && dispatch.runtimeIntent.applicationRuntimeRequired === false
2207
+ ? "analysis_only"
2208
+ : "managed_runtime";
2209
+ }
2210
+ function runtimeAdmissionPriority(dispatch) {
2211
+ return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2212
+ || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2213
+ ? "background"
2214
+ : "foreground";
2215
+ }
2216
+ function enqueueAdmissionWaiter(waiters, waiter) {
2217
+ if (waiter.priority === "background") {
2218
+ waiters.push(waiter);
2219
+ return;
2220
+ }
2221
+ const backgroundIndex = waiters.findIndex(candidate => candidate.priority === "background");
2222
+ if (backgroundIndex < 0)
2223
+ waiters.push(waiter);
2224
+ else
2225
+ waiters.splice(backgroundIndex, 0, waiter);
2226
+ }
2227
+ function defaultHostResourceRequest() {
2228
+ const workerMemoryLimitBytes = configuredInteger("FORGE_HOST_DEFAULT_WORKER_MEMORY_LIMIT_BYTES", 2 * 1024 ** 3, 128 * 1024 ** 2, 512 * 1024 ** 3);
2229
+ const runtimeOverheadBytes = 128 * 1024 ** 2;
2230
+ return {
2231
+ sandboxSlots: 1,
2232
+ cpuMillis: 2000,
2233
+ workerMemoryLimitBytes,
2234
+ serviceMemoryLimitBytes: 0,
2235
+ runtimeOverheadBytes,
2236
+ memoryBytes: workerMemoryLimitBytes + runtimeOverheadBytes,
2237
+ workspaceBytes: 10 * 1024 ** 3,
2238
+ pids: 512,
2239
+ buildSlots: 1,
2240
+ };
2241
+ }
2242
+ function minimumSupportedHostResourceRequest() {
2243
+ return {
2244
+ sandboxSlots: 1,
2245
+ cpuMillis: 1000,
2246
+ workerMemoryLimitBytes: 1024 ** 3,
2247
+ serviceMemoryLimitBytes: 0,
2248
+ runtimeOverheadBytes: 128 * 1024 ** 2,
2249
+ memoryBytes: 1152 * 1024 ** 2,
2250
+ workspaceBytes: architectMinimumWorkspaceEstimateBytes,
2251
+ pids: 256,
2252
+ buildSlots: 0,
2253
+ };
2254
+ }
2255
+ function normalizedHostResourceRequest(resources) {
2256
+ const defaults = defaultHostResourceRequest();
2257
+ const workerMemoryLimitBytes = positiveResourceValue(resources?.workerMemoryLimitBytes, defaults.workerMemoryLimitBytes);
2258
+ const serviceMemoryLimitBytes = nonNegativeResourceValue(resources?.serviceMemoryLimitBytes, defaults.serviceMemoryLimitBytes);
2259
+ const runtimeOverheadBytes = nonNegativeResourceValue(resources?.runtimeOverheadBytes, defaults.runtimeOverheadBytes);
2260
+ return {
2261
+ sandboxSlots: positiveResourceValue(resources?.sandboxSlots, defaults.sandboxSlots),
2262
+ cpuMillis: positiveResourceValue(resources?.cpuMillis, defaults.cpuMillis),
2263
+ workerMemoryLimitBytes,
2264
+ serviceMemoryLimitBytes,
2265
+ runtimeOverheadBytes,
2266
+ memoryBytes: workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
2267
+ workspaceBytes: positiveResourceValue(resources?.workspaceBytes, defaults.workspaceBytes),
2268
+ pids: positiveResourceValue(resources?.pids, defaults.pids),
2269
+ buildSlots: nonNegativeResourceValue(resources?.buildSlots, defaults.buildSlots),
2270
+ };
2271
+ }
2272
+ function positiveResourceValue(value, fallback) {
2273
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
2274
+ }
2275
+ function nonNegativeResourceValue(value, fallback) {
2276
+ return Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
2277
+ }
2278
+ function configuredInteger(name, fallback, minimum, maximum) {
2279
+ const parsed = Number.parseInt(process.env[name] ?? "", 10);
2280
+ return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2281
+ }
2282
+ function loadHostCapacityConfiguration(capacityResourceSample) {
2283
+ const sampledCpuCount = capacityResourceSample
2284
+ ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
2285
+ : os.cpus().length;
2286
+ const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2287
+ const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2288
+ const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
2289
+ const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2290
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2291
+ floorBytes: reserveFloorBytes,
2292
+ ceilingBytes: reserveCeilingBytes,
2293
+ percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
2294
+ });
2295
+ const minimumIdleReserveBytes = Math.min(hostReserveBytes, reserveFloorBytes);
2296
+ return {
2297
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2))), 1, 32),
2298
+ hostReserveBytes,
2299
+ idleHostReserveBytes: configuredInteger("FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES", minimumIdleReserveBytes, 512 * 1024 ** 2, hostReserveBytes),
2300
+ cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2301
+ workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2302
+ memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2303
+ memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2304
+ };
2305
+ }
2306
+ function configuredOptionalInteger(name, minimum, maximum) {
2307
+ const raw = process.env[name];
2308
+ if (raw === undefined || raw.trim().length === 0)
2309
+ return null;
2310
+ const parsed = Number.parseInt(raw, 10);
2311
+ return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : null;
2312
+ }
2313
+ function configuredNumber(name, fallback, minimum, maximum) {
2314
+ const parsed = Number(process.env[name] ?? "");
2315
+ return Number.isFinite(parsed) && parsed > 0
2316
+ ? Math.max(minimum, Math.min(maximum, parsed))
2317
+ : fallback;
2318
+ }
2319
+ function resourceSlots(available, requested) {
2320
+ if (requested <= 0)
2321
+ return Number.MAX_SAFE_INTEGER;
2322
+ return Math.max(0, Math.floor(available / requested));
2323
+ }
2324
+ function removeWaiter(waiters, waiter) {
2325
+ const index = waiters.indexOf(waiter);
2326
+ if (index >= 0)
2327
+ waiters.splice(index, 1);
2328
+ }
2329
+ function capacityProject(projects, repoId) {
2330
+ const normalized = repoId.trim().toLowerCase();
2331
+ const existing = projects.get(normalized);
2332
+ if (existing)
2333
+ return existing;
2334
+ const created = {
2335
+ repoId: normalized,
2336
+ safetyClass: null,
2337
+ activeAttempts: 0,
2338
+ reservedAttempts: 0,
2339
+ waitingAttempts: 0,
2340
+ degradedAttempts: 0,
2341
+ runtimeContractFingerprint: null,
2342
+ runtimeContractSource: null,
2343
+ promotedAt: null,
2344
+ };
2345
+ projects.set(normalized, created);
2346
+ return created;
2347
+ }
2348
+ function conservativeSafetyClass(left, right) {
2349
+ if (!left)
2350
+ return right;
2351
+ const rank = {
2352
+ host_serial_only: 0,
2353
+ host_parallel_candidate: 1,
2354
+ host_parallel_safe: 2,
2355
+ };
2356
+ return rank[right] < rank[left] ? right : left;
2357
+ }
2358
+ function repoIdFromProjectSingletonKeys(keys) {
2359
+ return keys.map(repoIdFromProjectSingletonKey).find((value) => value !== null) ?? null;
2360
+ }
2361
+ function repoIdFromProjectSingletonKey(key) {
2362
+ const prefix = "project:";
2363
+ const suffix = [":host-runtime", ":host-analysis"].find(candidate => key.endsWith(candidate));
2364
+ return key.startsWith(prefix) && suffix
2365
+ ? key.slice(prefix.length, -suffix.length)
2366
+ : null;
2367
+ }
2368
+ function sameSingletonOwner(left, right) {
2369
+ return left?.dispatchAttemptId === right.dispatchAttemptId && left.fencingToken === right.fencingToken;
2370
+ }
2371
+ function hostRuntimeOwnerKey(owner) {
2372
+ return `${owner.dispatchAttemptId}:${owner.fencingToken}`;
2373
+ }
2374
+ function hostPortOwner(lease) {
2375
+ const processSupervisorId = lease.resources.processSupervisorId;
2376
+ if (!processSupervisorId) {
2377
+ throw new Error("host_runtime_adapter_invalid: process supervisor identity is required.");
2378
+ }
2379
+ return {
2380
+ dispatchAttemptId: lease.dispatchAttemptId,
2381
+ executionLeaseId: lease.executionLeaseId,
2382
+ fencingToken: lease.fencingToken,
2383
+ processSupervisorId,
2384
+ };
2385
+ }
2386
+ function linkedAbortController(signal) {
2387
+ const controller = new AbortController();
2388
+ if (signal?.aborted) {
2389
+ controller.abort(signal.reason);
2390
+ }
2391
+ else {
2392
+ signal?.addEventListener("abort", () => controller.abort(signal.reason), { once: true, signal: controller.signal });
2393
+ }
2394
+ return controller;
2395
+ }
2396
+ function unlinkAbortController(controller, _signal) {
2397
+ if (!controller.signal.aborted)
2398
+ controller.abort("Host adapter launch settled.");
2399
+ }
2400
+ function removeCleanup(cleanups, cleanup) {
2401
+ const index = cleanups.indexOf(cleanup);
2402
+ if (index >= 0)
2403
+ cleanups.splice(index, 1);
2404
+ }
2405
+ async function releaseAdapterResources(cleanups) {
2406
+ const pending = cleanups.splice(0);
2407
+ const failed = [];
2408
+ let firstError;
2409
+ for (const cleanup of pending.reverse()) {
2410
+ try {
2411
+ await cleanup();
2412
+ }
2413
+ catch (error) {
2414
+ firstError ??= error;
2415
+ failed.unshift(cleanup);
2416
+ }
2417
+ }
2418
+ cleanups.push(...failed);
2419
+ if (firstError !== undefined)
2420
+ throw firstError;
2421
+ }
2422
+ async function removeHostAttemptRoot(attemptRoot) {
2423
+ await fs.rm(attemptRoot, {
2424
+ recursive: true,
2425
+ force: true,
2426
+ maxRetries: 10,
2427
+ retryDelay: 100,
2428
+ });
2429
+ }
2430
+ function cancellationError(signal) {
2431
+ return new Error(String(signal?.reason ?? "Dispatch cancelled while waiting for host runtime singleton ownership."));
2432
+ }
2433
+ function validHostRuntimeLedger(value) {
2434
+ if (typeof value !== "object" || value === null)
2435
+ return false;
2436
+ const ledger = value;
2437
+ return ledger.schemaVersion === 1
2438
+ && (ledger.repoId === undefined || /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu.test(ledger.repoId))
2439
+ && (ledger.attemptRootIdentity === undefined
2440
+ || validSerializedHostAttemptRootIdentity(ledger.attemptRootIdentity))
2441
+ && validRuntimeIsolationLease(ledger.runtimeLease)
2442
+ && ledger.runtimeLease.mode === "host";
2443
+ }
2444
+ function validSerializedHostAttemptRootIdentity(value) {
2445
+ if (typeof value !== "object" || value === null)
2446
+ return false;
2447
+ const identity = value;
2448
+ return /^-?\d{1,64}$/u.test(identity.dev) && /^-?\d{1,64}$/u.test(identity.ino);
2449
+ }
2450
+ function serializeHostAttemptRootIdentity(identity) {
2451
+ return { dev: identity.dev.toString(), ino: identity.ino.toString() };
2452
+ }
2453
+ function deserializeHostAttemptRootIdentity(identity) {
2454
+ return identity && validSerializedHostAttemptRootIdentity(identity)
2455
+ ? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
2456
+ : null;
2457
+ }
2458
+ function validHostProcessSupervisorMetadata(value, lease) {
2459
+ if (typeof value !== "object" || value === null)
2460
+ return false;
2461
+ const metadata = value;
2462
+ return metadata.schemaVersion === 1
2463
+ && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
2464
+ && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
2465
+ && Number.isSafeInteger(metadata.rootPid)
2466
+ && metadata.rootPid > 0
2467
+ && Number.isFinite(Date.parse(metadata.rootCreatedAt))
2468
+ && (metadata.rootIdentity == null
2469
+ || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
2470
+ && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
2471
+ && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
2472
+ && metadata.runtimeLeaseId === lease.executionLeaseId
2473
+ && metadata.dispatchAttemptId === lease.dispatchAttemptId
2474
+ && metadata.fencingToken === lease.fencingToken
2475
+ && Number.isSafeInteger(metadata.bridgePid)
2476
+ && metadata.bridgePid > 0;
2477
+ }
2478
+ function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
2479
+ const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
2480
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2481
+ }
2482
+ function transitionHostLeaseForCleanup(lease, state) {
2483
+ if (lease.state === state || lease.state === "released")
2484
+ return lease;
2485
+ return transitionRuntimeIsolationLease(lease, state);
2486
+ }
2487
+ function throwIfAdmissionExpired(expiresAt) {
2488
+ if (admissionExpired(expiresAt))
2489
+ throw new HostRuntimeAdmissionExpiredError();
2490
+ }
2491
+ function admissionExpired(expiresAt) {
2492
+ const deadline = Date.parse(expiresAt);
2493
+ return !Number.isFinite(deadline) || deadline <= Date.now();
2494
+ }
2495
+ function scheduleAdmissionDeadline(expiresAt, expire) {
2496
+ const delay = Math.max(0, Date.parse(expiresAt) - Date.now());
2497
+ const timer = setTimeout(expire, Math.min(delay, 2_147_483_647));
2498
+ timer.unref?.();
2499
+ return timer;
2500
+ }
2501
+ function clearAdmissionDeadline(waiter) {
2502
+ if (waiter.deadlineTimer)
2503
+ clearTimeout(waiter.deadlineTimer);
2504
+ waiter.deadlineTimer = null;
2505
+ }
2506
+ function clearCapacityRecheck(waiter) {
2507
+ if (waiter.capacityRecheckTimer)
2508
+ clearInterval(waiter.capacityRecheckTimer);
2509
+ waiter.capacityRecheckTimer = null;
2510
+ }
2511
+ async function ensurePrivateDirectory(directory) {
2512
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
2513
+ if (process.platform !== "win32")
2514
+ await fs.chmod(directory, 0o700);
2515
+ }
2516
+ async function containedWorkingDirectory(worktreePath, configuredDirectory) {
2517
+ const [realWorktree, realDirectory] = await Promise.all([
2518
+ fs.realpath(worktreePath),
2519
+ fs.realpath(path.resolve(worktreePath, configuredDirectory)),
2520
+ ]);
2521
+ const relative = path.relative(realWorktree, realDirectory);
2522
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
2523
+ throw new Error("host_runtime_project_invalid: launch working directory must remain inside the prepared worktree.");
2524
+ }
2525
+ return realDirectory;
2526
+ }
2527
+ function uuidHex(value, label) {
2528
+ const normalized = value.replaceAll("-", "").toLowerCase();
2529
+ if (!/^[0-9a-f]{32}$/u.test(normalized)) {
2530
+ throw new Error(`host_runtime_lease_invalid: ${label} id must be a full UUID.`);
2531
+ }
2532
+ return normalized;
2533
+ }