@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 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 (185) hide show
  1. package/README.md +89 -3
  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 +4 -1
  5. package/dist/bridge/bridge.service.d.ts +83 -3
  6. package/dist/bridge/bridge.service.js +1609 -152
  7. package/dist/bridge/bridge.types.d.ts +52 -1
  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 +1 -0
  21. package/dist/cleanup/cleanup.service.js +70 -9
  22. package/dist/cli/cli.help.js +4 -4
  23. package/dist/cli/cli.service.d.ts +14 -6
  24. package/dist/cli/cli.service.js +75 -16
  25. package/dist/cli/local-config.d.ts +1 -0
  26. package/dist/cli/local-config.js +4 -0
  27. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  28. package/dist/runtime/aspnet-runtime-prebuild.js +341 -0
  29. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  30. package/dist/runtime/attempt-database-broker.js +390 -0
  31. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  32. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  33. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  34. package/dist/runtime/attempt-path-operation.js +94 -0
  35. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  36. package/dist/runtime/attempt-private-directory.js +54 -0
  37. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  38. package/dist/runtime/attempt-process-supervisor.js +144 -23
  39. package/dist/runtime/canonical-source-file.d.ts +3 -0
  40. package/dist/runtime/canonical-source-file.js +54 -0
  41. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  42. package/dist/runtime/docker-engine-probe.js +333 -0
  43. package/dist/runtime/generated-output-reset.d.ts +10 -0
  44. package/dist/runtime/generated-output-reset.js +62 -8
  45. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  46. package/dist/runtime/host-database-capability-boundary.js +63 -0
  47. package/dist/runtime/host-diagnostics.d.ts +11 -0
  48. package/dist/runtime/host-diagnostics.js +192 -0
  49. package/dist/runtime/host-execution-root.d.ts +4 -0
  50. package/dist/runtime/host-execution-root.js +39 -0
  51. package/dist/runtime/host-facts.d.ts +35 -0
  52. package/dist/runtime/host-facts.js +95 -0
  53. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  54. package/dist/runtime/host-listener-inspector.js +121 -60
  55. package/dist/runtime/host-load-sampler.d.ts +83 -0
  56. package/dist/runtime/host-load-sampler.js +164 -0
  57. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  58. package/dist/runtime/host-pressure-stall.js +121 -0
  59. package/dist/runtime/host-runtime-contract.d.ts +13 -1
  60. package/dist/runtime/host-runtime-contract.js +170 -55
  61. package/dist/runtime/host-runtime-lease.d.ts +92 -8
  62. package/dist/runtime/host-runtime-lease.js +1193 -120
  63. package/dist/runtime/host-runtime-promotion.d.ts +12 -3
  64. package/dist/runtime/host-runtime-promotion.js +59 -12
  65. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  66. package/dist/runtime/managed-command-teardown.js +607 -0
  67. package/dist/runtime/memory-capacity.d.ts +70 -0
  68. package/dist/runtime/memory-capacity.js +123 -0
  69. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  70. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  71. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  72. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  73. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  74. package/dist/runtime/pinned-directory-process.js +61 -0
  75. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  76. package/dist/runtime/pinned-source-directory.js +94 -0
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +12 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +100 -58
  81. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  82. package/dist/runtime/prepared-runtime-identity.js +218 -0
  83. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  84. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  85. package/dist/runtime/runtime-isolation-lease.js +4 -1
  86. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  87. package/dist/runtime/workspace-resource-estimator.js +174 -0
  88. package/dist/sandbox/preflight.d.ts +31 -1
  89. package/dist/sandbox/preflight.js +237 -51
  90. package/dist/sandbox/repository-lock.d.ts +2 -1
  91. package/dist/sandbox/repository-lock.js +19 -9
  92. package/dist/sandbox/runtime.d.ts +6 -1
  93. package/dist/sandbox/runtime.js +137 -107
  94. package/dist/sandbox/sandbox.types.d.ts +7 -0
  95. package/dist/sandbox/workspace.service.js +2 -0
  96. package/dist/session/managed-attempt-tools.d.ts +42 -1
  97. package/dist/session/managed-attempt-tools.js +692 -40
  98. package/dist/session/managed-build-coordinator.d.ts +5 -0
  99. package/dist/session/managed-build-coordinator.js +109 -0
  100. package/dist/session/managed-build-receipt.d.ts +21 -0
  101. package/dist/session/managed-build-receipt.js +337 -0
  102. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  103. package/dist/session/managed-verification-timeouts.js +17 -0
  104. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  105. package/dist/session/phase-completion.artifacts.js +228 -22
  106. package/dist/session/phase-completion.d.ts +11 -1
  107. package/dist/session/phase-completion.helpers.d.ts +5 -0
  108. package/dist/session/phase-completion.helpers.js +30 -7
  109. package/dist/session/phase-completion.js +14 -3
  110. package/dist/session/phase-completion.prompts.js +17 -18
  111. package/dist/session/phase-completion.runtime.d.ts +3 -1
  112. package/dist/session/phase-completion.runtime.js +148 -34
  113. package/dist/session/phase-completion.schemas.js +49 -2
  114. package/dist/session/phase-completion.validation.d.ts +1 -0
  115. package/dist/session/phase-completion.validation.js +111 -21
  116. package/dist/session/pre-publication-process.d.ts +20 -0
  117. package/dist/session/pre-publication-process.js +97 -0
  118. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  119. package/dist/session/pre-publication-skipped-tests.js +109 -0
  120. package/dist/session/pre-publication-validation.d.ts +75 -0
  121. package/dist/session/pre-publication-validation.js +631 -0
  122. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  123. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  124. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  125. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  126. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  127. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  128. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  129. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  130. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  131. package/dist/session/provider-cli/provider-cli.process.d.ts +80 -0
  132. package/dist/session/provider-cli/provider-cli.process.js +694 -28
  133. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  134. package/dist/session/provider-cli/provider-cli.prompts.js +151 -16
  135. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  136. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  137. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  138. package/dist/session/provider-cli/provider-cli.runtime.js +54 -3
  139. package/dist/session/provider-cli/provider-cli.service.d.ts +30 -5
  140. package/dist/session/provider-cli/provider-cli.service.js +858 -77
  141. package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  143. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  144. package/dist/session/provider-cli/provider-output-state.d.ts +16 -0
  145. package/dist/session/provider-cli/provider-output-state.js +370 -17
  146. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  147. package/dist/session/provider-cli/provider-usage.js +28 -5
  148. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  149. package/dist/session/publishable-worktree-changes.js +193 -0
  150. package/dist/session/session-redaction.js +434 -9
  151. package/dist/session/session.service.js +145 -23
  152. package/dist/session/session.types.d.ts +147 -2
  153. package/dist/session/session.types.js +599 -7
  154. package/dist/session/unreferenced-exports.d.ts +12 -0
  155. package/dist/session/unreferenced-exports.js +59 -0
  156. package/dist/shared/format/format-bytes.d.ts +1 -0
  157. package/dist/shared/format/format-bytes.js +9 -0
  158. package/dist/shared/git/git.js +2 -1
  159. package/dist/shared/path/path.d.ts +1 -0
  160. package/dist/shared/path/path.js +18 -0
  161. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  162. package/dist/shared/process/dotnet-toolchain.js +307 -0
  163. package/dist/shared/process/host-process-recovery.js +3 -2
  164. package/dist/shared/process/host-process-supervisor.d.ts +2 -0
  165. package/dist/shared/process/host-process-supervisor.js +60 -11
  166. package/dist/shared/process/process.d.ts +2 -0
  167. package/dist/shared/process/process.js +12 -7
  168. package/dist/shared/provider-capabilities.d.ts +3 -0
  169. package/dist/shared/provider-capabilities.js +85 -0
  170. package/dist/shared/redaction/redaction.d.ts +1 -0
  171. package/dist/shared/redaction/redaction.js +39 -3
  172. package/dist/shared/time/monotonic.d.ts +1 -0
  173. package/dist/shared/time/monotonic.js +8 -0
  174. package/dist/version.d.ts +1 -1
  175. package/dist/version.js +1 -1
  176. package/dist/worktree/dependency-warmer.d.ts +41 -9
  177. package/dist/worktree/dependency-warmer.js +571 -22
  178. package/dist/worktree/index.d.ts +1 -1
  179. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  180. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  181. package/dist/worktree/worktree.service.d.ts +7 -0
  182. package/dist/worktree/worktree.service.js +253 -21
  183. package/dist/worktree/worktree.types.d.ts +7 -1
  184. package/package.json +7 -5
  185. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -1,17 +1,37 @@
1
1
  import fs from "node:fs/promises";
2
+ import { statfsSync } from "node:fs";
3
+ import { randomUUID } from "node:crypto";
4
+ import os from "node:os";
2
5
  import path from "node:path";
6
+ import { assertHostAttemptRootIdentity, retainHostDiagnostics } from "./host-diagnostics.js";
7
+ import { assertHostExecutionRoot, compactHostAttemptId } from "./host-execution-root.js";
8
+ import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
9
+ import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
+ import { resolveExistingDirectoryPath } from "../shared/path/path.js";
11
+ import { formatBytes } from "../shared/format/format-bytes.js";
12
+ import { redactText } from "../shared/redaction/redaction.js";
3
13
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
4
14
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
5
15
  import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
6
16
  import { HostPortBroker, } from "./host-port-broker.js";
7
17
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
8
18
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
19
+ import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
20
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
9
21
  import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
10
22
  import { HostListenerInspector } from "./host-listener-inspector.js";
23
+ import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
11
24
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
12
25
  import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
13
26
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
14
27
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
28
+ import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
29
+ import { readCanonicalSourceFile } from "./canonical-source-file.js";
30
+ import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
31
+ import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
32
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
33
+ const hostCapacityWaiterScanLimit = 64;
34
+ const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
15
35
  export class HostRuntimeLeaseManager {
16
36
  stateRoot;
17
37
  processSupervisors;
@@ -20,18 +40,31 @@ export class HostRuntimeLeaseManager {
20
40
  promotionStore;
21
41
  playwrightAdapter;
22
42
  processRecovery;
43
+ capacityResourceSample;
44
+ databaseBroker;
45
+ preparedReadiness;
23
46
  active = new Map();
24
47
  pendingRenewals = new Map();
48
+ acquiringAdmissions = new Set();
25
49
  admissions = new Map();
26
50
  singletonOwners = new Map();
27
51
  singletonWaiters = [];
28
52
  parallelProjectOwners = new Map();
29
53
  parallelProjectWaiters = [];
54
+ capacityReservations = new Map();
55
+ capacityWaiters = [];
56
+ capacityWaiterScanCursor = 0;
57
+ backgroundAdmissionWaiters = [];
30
58
  degraded = new Map();
31
59
  knownPromotions = new Map();
60
+ ledgerWriteTail = Promise.resolve();
61
+ workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
32
62
  portBroker;
33
63
  nodeAdapter;
34
- constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery()) {
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) {
35
68
  this.stateRoot = stateRoot;
36
69
  this.processSupervisors = processSupervisors;
37
70
  this.processRunner = processRunner;
@@ -39,22 +72,47 @@ export class HostRuntimeLeaseManager {
39
72
  this.promotionStore = promotionStore;
40
73
  this.playwrightAdapter = playwrightAdapter;
41
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());
42
81
  this.portBroker = portBroker;
43
82
  this.nodeAdapter = nodeAdapter ?? new NodeHostRuntimeAdapter(portBroker);
83
+ this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
84
+ this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
44
85
  }
45
86
  async reap(options) {
46
87
  await this.refreshKnownPromotions();
88
+ const recoveredAttempts = [];
47
89
  const report = {
48
90
  examined: 0,
49
91
  reaped: 0,
50
92
  processesTerminated: 0,
51
93
  reusedPidsProtected: 0,
52
94
  degraded: 0,
95
+ recoveredAttempts,
53
96
  };
54
97
  for (const ledger of await this.readLedgers()) {
55
98
  const lease = ledger.runtimeLease;
56
99
  if (lease.runnerId !== options.runnerId)
57
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
+ }
58
116
  const active = this.active.get(lease.dispatchAttemptId);
59
117
  if (active) {
60
118
  if (active.lease.state !== "degraded")
@@ -78,9 +136,13 @@ export class HostRuntimeLeaseManager {
78
136
  continue;
79
137
  report.examined += 1;
80
138
  const attemptRoot = this.attemptRoot(lease.dispatchAttemptId);
139
+ const attemptRootIdentity = deserializeHostAttemptRootIdentity(ledger.attemptRootIdentity);
81
140
  let outcomes;
82
141
  try {
83
- outcomes = await this.recoverPersistedProcesses(lease, attemptRoot);
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);
84
146
  }
85
147
  catch {
86
148
  await this.markLedgerDegraded(ledger);
@@ -94,10 +156,45 @@ export class HostRuntimeLeaseManager {
94
156
  report.degraded += 1;
95
157
  continue;
96
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
+ }
97
175
  try {
98
176
  const releasing = transitionHostLeaseForCleanup(lease, "releasing");
99
- await this.writeLedger(releasing, ledger.repoId);
100
- await fs.rm(attemptRoot, { recursive: true, force: true });
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);
101
198
  await fs.rm(this.ledgerPath(lease.dispatchAttemptId), { force: true });
102
199
  this.forgetDegraded(lease.dispatchAttemptId, lease.fencingToken);
103
200
  report.reaped += 1;
@@ -107,9 +204,14 @@ export class HostRuntimeLeaseManager {
107
204
  report.degraded += 1;
108
205
  }
109
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);
110
211
  return report;
111
212
  }
112
213
  snapshot() {
214
+ this.reconcileReservationOwners();
113
215
  const projects = new Map();
114
216
  for (const promotion of this.knownPromotions.values()) {
115
217
  const project = capacityProject(projects, promotion.repoId);
@@ -168,6 +270,26 @@ export class HostRuntimeLeaseManager {
168
270
  project.waitingAttempts += 1;
169
271
  project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_candidate");
170
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
+ }
171
293
  const activeAttempts = [...this.active.values()]
172
294
  .filter(active => active.lease.state !== "degraded").length;
173
295
  const degradedAttempts = new Set([
@@ -176,14 +298,21 @@ export class HostRuntimeLeaseManager {
176
298
  .filter(([, active]) => active.lease.state === "degraded")
177
299
  .map(([dispatchAttemptId]) => dispatchAttemptId),
178
300
  ]).size;
301
+ const hostResources = this.hostResourceSnapshot();
179
302
  return {
180
303
  activeAttempts,
304
+ preparedWorktreeReadiness: true,
181
305
  reservedAttempts: Math.max(0, this.admissions.size - this.active.size),
182
- waitingAttempts: this.singletonWaiters.length + this.parallelProjectWaiters.length,
306
+ waitingAttempts: this.singletonWaiters.length
307
+ + this.parallelProjectWaiters.length
308
+ + this.capacityWaiters.length
309
+ + this.backgroundAdmissionWaiters.length
310
+ + unrepresentedPrepared.length,
183
311
  degradedAttempts,
184
312
  exclusiveReservations: this.singletonOwners.size,
185
313
  sharedReservations: [...this.parallelProjectOwners.values()]
186
314
  .reduce((count, owners) => count + owners.size, 0),
315
+ ...hostResources,
187
316
  projects: [...projects.values()]
188
317
  .map(project => ({
189
318
  ...project,
@@ -192,6 +321,21 @@ export class HostRuntimeLeaseManager {
192
321
  .sort((left, right) => left.repoId.localeCompare(right.repoId)),
193
322
  };
194
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
+ }
195
339
  async acquire(dispatch, signal) {
196
340
  const sandbox = dispatch.sandbox;
197
341
  if (!sandbox || sandbox.executionMode !== "host") {
@@ -211,6 +355,7 @@ export class HostRuntimeLeaseManager {
211
355
  return existing.keys;
212
356
  }
213
357
  const executionClass = runtimeExecutionClass(dispatch);
358
+ const priority = runtimeAdmissionPriority(dispatch);
214
359
  const promotion = executionClass === "managed_runtime"
215
360
  ? await this.promotionStore.load(dispatch.repo.id)
216
361
  : null;
@@ -219,37 +364,353 @@ export class HostRuntimeLeaseManager {
219
364
  const projectKey = executionClass === "analysis_only"
220
365
  ? projectHostAnalysisKey(dispatch.repo.id)
221
366
  : projectHostRuntimeSingletonKey(dispatch.repo.id);
222
- let keys = promotion || executionClass === "analysis_only" ? [] : [projectKey];
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);
223
372
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
224
373
  ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
225
374
  : dispatch.lease.expiresAt;
375
+ const acquisitionKey = hostRuntimeOwnerKey(owner);
376
+ this.acquiringAdmissions.add(acquisitionKey);
226
377
  try {
227
- if (promotion || executionClass === "analysis_only") {
228
- await this.reserveParallelProject(projectKey, owner, expiresAt, signal);
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
+ }
229
396
  }
230
- else {
231
- keys = await this.reserveSingletonKeys(keys, owner, expiresAt, signal);
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;
232
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;
233
419
  }
234
- catch (error) {
235
- this.clearPendingRenewal(owner);
236
- throw error;
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.`;
237
537
  }
238
- const admittedPromotion = promotion
239
- ?? (executionClass === "managed_runtime" && keys.length === 0
240
- ? this.knownPromotions.get(dispatch.repo.id) ?? null
241
- : null);
242
- this.admissions.set(sandbox.dispatchAttemptId, {
243
- repoId: dispatch.repo.id,
244
- fencingToken: owner.fencingToken,
245
- executionClass,
246
- provisionalPromotionFingerprint: admittedPromotion?.runtimeContractFingerprint ?? null,
247
- keys,
248
- parallelProjectKey: admittedPromotion || executionClass === "analysis_only" ? projectKey : null,
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,
249
589
  });
250
- return keys;
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();
251
642
  }
252
- async reserveSingletonKeys(keys, owner, expiresAt, signal) {
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") {
253
714
  const owned = keys.every(key => sameSingletonOwner(this.singletonOwners.get(key), owner));
254
715
  if (owned)
255
716
  return keys;
@@ -269,6 +730,7 @@ export class HostRuntimeLeaseManager {
269
730
  const waiter = {
270
731
  owner,
271
732
  keys,
733
+ priority,
272
734
  resolve,
273
735
  reject,
274
736
  signal,
@@ -295,13 +757,13 @@ export class HostRuntimeLeaseManager {
295
757
  this.drainAdmissionWaiters();
296
758
  },
297
759
  };
298
- this.singletonWaiters.push(waiter);
760
+ enqueueAdmissionWaiter(this.singletonWaiters, waiter);
299
761
  signal?.addEventListener("abort", waiter.abort, { once: true });
300
762
  waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
301
763
  this.drainAdmissionWaiters();
302
764
  });
303
765
  }
304
- async reserveParallelProject(key, owner, expiresAt, signal) {
766
+ async reserveParallelProject(key, owner, expiresAt, signal, priority = "foreground") {
305
767
  if (this.parallelProjectOwned(key, owner))
306
768
  return;
307
769
  const staleFence = [...(this.parallelProjectOwners.get(key)?.values() ?? [])]
@@ -313,7 +775,7 @@ export class HostRuntimeLeaseManager {
313
775
  if (signal?.aborted)
314
776
  throw cancellationError(signal);
315
777
  throwIfAdmissionExpired(expiresAt);
316
- if (this.parallelProjectAvailable(key)) {
778
+ if (this.parallelProjectAvailable(key, priority)) {
317
779
  this.assignParallelProject(key, owner);
318
780
  return;
319
781
  }
@@ -321,6 +783,7 @@ export class HostRuntimeLeaseManager {
321
783
  const waiter = {
322
784
  owner,
323
785
  key,
786
+ priority,
324
787
  resolve,
325
788
  reject,
326
789
  signal,
@@ -347,17 +810,85 @@ export class HostRuntimeLeaseManager {
347
810
  this.drainAdmissionWaiters();
348
811
  },
349
812
  };
350
- this.parallelProjectWaiters.push(waiter);
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);
351
861
  signal?.addEventListener("abort", waiter.abort, { once: true });
352
862
  waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
863
+ this.releaseParallelProjectNoDrain(parallelProjectKey, owner);
353
864
  this.drainAdmissionWaiters();
354
865
  });
355
866
  }
356
- async start(dispatch, worktreePath, signal) {
867
+ async start(dispatch, worktreePath, signal, onAdmissionCheckpoint) {
357
868
  const sandbox = dispatch.sandbox;
358
869
  if (!sandbox || sandbox.executionMode !== "host") {
359
870
  throw new Error("host_runtime_lease_invalid: managed host sandbox context is required.");
360
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
+ }
361
892
  const existing = this.active.get(sandbox.dispatchAttemptId);
362
893
  if (existing) {
363
894
  if (existing.lease.fencingToken !== dispatch.lease.fencingToken) {
@@ -365,7 +896,7 @@ export class HostRuntimeLeaseManager {
365
896
  }
366
897
  return {
367
898
  lease: existing.lease,
368
- environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass),
899
+ environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass, existing.databaseCapability),
369
900
  runtimeContract: existing.runtimeContract,
370
901
  executionClass: existing.executionClass,
371
902
  };
@@ -376,12 +907,13 @@ export class HostRuntimeLeaseManager {
376
907
  throw new Error("host_runtime_singleton_unreserved: managed host admission is required before start.");
377
908
  }
378
909
  const attemptHex = uuidHex(sandbox.dispatchAttemptId, "dispatch attempt");
379
- const normalizedWorktreePath = path.resolve(worktreePath);
380
- const attemptRoot = path.join(this.stateRoot, "host-attempts", attemptHex);
381
- const temporaryPath = path.join(attemptRoot, "tmp");
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");
382
914
  const logPath = path.join(attemptRoot, "logs");
383
- const cachePath = path.join(attemptRoot, "cache");
384
- const browserProfilePath = path.join(attemptRoot, "browser-profile");
915
+ const cachePath = path.join(attemptRoot, "c");
916
+ const browserProfilePath = path.join(attemptRoot, "b");
385
917
  const testOutputPath = path.join(attemptRoot, "test-output");
386
918
  const processSupervisorMetadataPath = path.join(logPath, "attempt-process-supervisor.json");
387
919
  const processSupervisorId = `host-${attemptHex}`;
@@ -390,50 +922,86 @@ export class HostRuntimeLeaseManager {
390
922
  ? renewedExpiry.expiresAt
391
923
  : dispatch.lease.expiresAt;
392
924
  let processSupervisor = null;
925
+ let attemptRootIdentity = null;
393
926
  try {
394
- let runtimeContract;
395
- try {
396
- runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
397
- }
398
- catch (error) {
399
- if (admission.executionClass === "managed_runtime" && admission.provisionalPromotionFingerprint) {
400
- await this.invalidatePromotion(dispatch.repo.id).catch(() => undefined);
401
- }
402
- throw error;
403
- }
927
+ const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
404
928
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
405
929
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
406
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
+ }
407
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
+ }
408
942
  const promotion = admission.executionClass === "managed_runtime"
409
- ? await this.promotionStore.load(dispatch.repo.id)
943
+ ? await this.promotionStore.load(dispatch.repo.id, preparedProof ?? { runtimeContractFingerprint, inputCommitSha })
410
944
  : null;
411
945
  const promotionMatches = hostRuntimeParallelEligible(runtimeContract)
412
- && promotion?.runtimeContractFingerprint === runtimeContractFingerprint;
946
+ && promotion?.runtimeContractFingerprint === runtimeContractFingerprint
947
+ && promotion.inputCommitSha === inputCommitSha;
413
948
  if (admission.executionClass === "managed_runtime" && admission.keys.length === 0 && !promotionMatches) {
414
- await this.invalidatePromotion(dispatch.repo.id);
415
949
  const projectKeys = hostRuntimeSingletonKeys(dispatch);
416
- if (admission.parallelProjectKey) {
417
- this.releaseParallelProjectNoDrain(admission.parallelProjectKey, owner);
418
- admission.parallelProjectKey = null;
419
- }
420
950
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
421
951
  ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
422
952
  : dispatch.lease.expiresAt;
423
- admission.keys = await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal);
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;
424
984
  while (admission.keys.length === 0) {
425
985
  const promoted = this.knownPromotions.get(dispatch.repo.id);
426
986
  if (!promoted) {
427
987
  throw new Error("host_runtime_parallel_promotion_missing: shared admission requires matching promotion evidence.");
428
988
  }
429
- if (promoted.runtimeContractFingerprint !== runtimeContractFingerprint) {
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.
430
993
  this.releaseParallelProjectNoDrain(projectKeys[0], owner);
431
- await this.invalidatePromotion(dispatch.repo.id);
432
- admission.keys = await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal);
994
+ admission.keys = await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal, admission.priority);
433
995
  continue;
434
996
  }
435
997
  admission.parallelProjectKey = projectKeys[0] ?? null;
436
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);
437
1005
  }
438
1006
  }
439
1007
  const declaredSingletonKeys = runtimeContract.contract.runtime.singletonResources
@@ -444,7 +1012,7 @@ export class HostRuntimeLeaseManager {
444
1012
  const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
445
1013
  ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
446
1014
  : dispatch.lease.expiresAt;
447
- const reservedSingletonKeys = await this.reserveSingletonKeys(missingSingletonKeys, owner, expiresAt, signal);
1015
+ const reservedSingletonKeys = await this.reserveSingletonKeys(missingSingletonKeys, owner, expiresAt, signal, admission.priority);
448
1016
  admission.keys = [...admission.keys, ...reservedSingletonKeys]
449
1017
  .sort((left, right) => left.localeCompare(right));
450
1018
  }
@@ -455,13 +1023,16 @@ export class HostRuntimeLeaseManager {
455
1023
  if (admission.parallelProjectKey && !this.parallelProjectOwned(admission.parallelProjectKey, owner)) {
456
1024
  throw new Error("host_runtime_parallel_unreserved: matching shared project admission is required before start.");
457
1025
  }
1026
+ await createCanonicalDirectory(attemptRoot);
1027
+ attemptRootIdentity = (await assertCanonicalDirectory(attemptRoot));
458
1028
  await Promise.all([
459
- ensurePrivateDirectory(temporaryPath),
460
- ensurePrivateDirectory(logPath),
461
- ensurePrivateDirectory(cachePath),
462
- ensurePrivateDirectory(browserProfilePath),
463
- ensurePrivateDirectory(testOutputPath),
1029
+ createCanonicalDirectory(temporaryPath),
1030
+ createCanonicalDirectory(logPath),
1031
+ createCanonicalDirectory(cachePath),
1032
+ createCanonicalDirectory(browserProfilePath),
1033
+ createCanonicalDirectory(testOutputPath),
464
1034
  ]);
1035
+ await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
465
1036
  await resetGeneratedOutputs(normalizedWorktreePath, testOutputPath);
466
1037
  let lease = createRuntimeIsolationLease({
467
1038
  leaseId: sandbox.executionLeaseId,
@@ -493,11 +1064,11 @@ export class HostRuntimeLeaseManager {
493
1064
  singletonKeys,
494
1065
  },
495
1066
  });
496
- await this.writeLedger(lease);
1067
+ await this.writeLedger(lease, undefined, attemptRootIdentity);
497
1068
  lease = transitionRuntimeIsolationLease(lease, "starting");
498
- await this.writeLedger(lease);
1069
+ await this.writeLedger(lease, undefined, attemptRootIdentity);
499
1070
  lease = transitionRuntimeIsolationLease(lease, "active");
500
- await this.writeLedger(lease);
1071
+ await this.writeLedger(lease, undefined, attemptRootIdentity);
501
1072
  processSupervisor = this.processSupervisors.register({
502
1073
  processSupervisorId,
503
1074
  dispatchAttemptId: lease.dispatchAttemptId,
@@ -510,13 +1081,16 @@ export class HostRuntimeLeaseManager {
510
1081
  repoId: dispatch.repo.id,
511
1082
  sessionId: dispatch.session.id,
512
1083
  attemptRoot,
1084
+ attemptRootIdentity,
513
1085
  runtimeContract,
514
1086
  runtimeContractFingerprint,
1087
+ inputCommitSha,
515
1088
  executionClass: admission.executionClass,
516
- parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract),
1089
+ parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
517
1090
  processSupervisor,
518
1091
  adapterCleanups: [],
519
1092
  pendingAdapterLaunches: new Map(),
1093
+ runtimeResourcesReleased: false,
520
1094
  releasing: false,
521
1095
  });
522
1096
  this.pendingRenewals.delete(sandbox.dispatchAttemptId);
@@ -533,8 +1107,13 @@ export class HostRuntimeLeaseManager {
533
1107
  await processSupervisor.stopAll(dispatch.lease.fencingToken, "Host runtime start rolled back.").catch(() => undefined);
534
1108
  this.processSupervisors.unregister(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
535
1109
  }
536
- await fs.rm(attemptRoot, { recursive: true, force: true }).catch(() => undefined);
537
- await fs.rm(this.ledgerPath(sandbox.dispatchAttemptId), { force: true }).catch(() => undefined);
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
+ }
538
1117
  this.releaseSingletonKeys(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
539
1118
  this.releaseParallelProjects(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
540
1119
  this.deleteAdmission(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
@@ -549,6 +1128,7 @@ export class HostRuntimeLeaseManager {
549
1128
  catch {
550
1129
  return;
551
1130
  }
1131
+ await this.preparedReadiness.renew(dispatchAttemptId, fencingToken, expiresAt);
552
1132
  const active = this.active.get(dispatchAttemptId);
553
1133
  if (!active) {
554
1134
  if (Number.isFinite(Date.parse(expiresAt))) {
@@ -562,13 +1142,15 @@ export class HostRuntimeLeaseManager {
562
1142
  }
563
1143
  return;
564
1144
  }
1145
+ if (active.releasing || active.lease.state === "releasing" || active.lease.state === "released")
1146
+ return;
565
1147
  const renewed = renewRuntimeIsolationLease(active.lease, fencingToken, expiresAt);
566
1148
  if (!renewed)
567
1149
  return;
568
1150
  active.lease = renewed;
569
1151
  await this.writeLedger(renewed);
570
1152
  }
571
- async startConfiguredProject(dispatchAttemptId, fencingToken, signal) {
1153
+ async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
572
1154
  const active = this.active.get(dispatchAttemptId);
573
1155
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
574
1156
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
@@ -576,7 +1158,7 @@ export class HostRuntimeLeaseManager {
576
1158
  if (active.executionClass === "analysis_only") {
577
1159
  return {
578
1160
  lease: active.lease,
579
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1161
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
580
1162
  runtimeContract: active.runtimeContract,
581
1163
  executionClass: active.executionClass,
582
1164
  };
@@ -585,30 +1167,89 @@ export class HostRuntimeLeaseManager {
585
1167
  if (configuredPorts.length === 0) {
586
1168
  return {
587
1169
  lease: active.lease,
588
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1170
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
589
1171
  runtimeContract: active.runtimeContract,
590
1172
  executionClass: active.executionClass,
591
1173
  };
592
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);
593
1180
  const owner = hostPortOwner(active.lease);
594
1181
  const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
595
1182
  if (!logDirectory)
596
1183
  throw new Error("host_runtime_project_invalid: attempt log directory is unavailable.");
597
- const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector);
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);
598
1208
  for (const configuredPort of configuredPorts) {
599
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
+ }
600
1242
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
601
1243
  command: configuredPort.launch.command,
602
1244
  args: configuredPort.launch.args,
603
1245
  cwd: workingDirectory,
604
1246
  environment: {
605
- ...configuredPort.launch.environment,
606
- ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1247
+ ...buildEnvironment,
607
1248
  },
608
1249
  }, launcher, signal);
609
1250
  }
610
1251
  const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
611
- const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass);
1252
+ const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
612
1253
  const playwright = active.runtimeContract.contract.runtime.playwright;
613
1254
  if (!playwright) {
614
1255
  return {
@@ -637,6 +1278,7 @@ export class HostRuntimeLeaseManager {
637
1278
  testOutputDirectory: pathFor("test_output"),
638
1279
  browserProfileDirectory: pathFor("browser_profile"),
639
1280
  baseUrl,
1281
+ ownershipToken: uuidHex(promotedLease.dispatchAttemptId, "dispatch attempt"),
640
1282
  });
641
1283
  return {
642
1284
  lease: promotedLease,
@@ -649,7 +1291,18 @@ export class HostRuntimeLeaseManager {
649
1291
  const active = this.active.get(dispatchAttemptId);
650
1292
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
651
1293
  return null;
652
- return new AttemptSupervisedProviderProcessRunner(active.processSupervisor, hostPortOwner(active.lease), this.listenerInspector, active.executionClass === "analysis_only");
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();
653
1306
  }
654
1307
  async promoteVerifiedRuntime(active, runtimeLease) {
655
1308
  if (!active.parallelPromotionEligible)
@@ -668,12 +1321,15 @@ export class HostRuntimeLeaseManager {
668
1321
  await this.writeLedger(promotedLease);
669
1322
  active.lease = promotedLease;
670
1323
  try {
671
- const promotion = await this.promotionStore.observe(active.repoId, active.runtimeContract, runtimeLease.dispatchAttemptId, verifiedPortNames);
1324
+ const promotion = await this.promotionStore.observe(active.repoId, active.runtimeContract, runtimeLease.dispatchAttemptId, verifiedPortNames, active.inputCommitSha);
672
1325
  this.knownPromotions.set(promotion.repoId, promotion);
673
- this.convertSingletonToParallelProject(projectKey, {
1326
+ const owner = {
674
1327
  dispatchAttemptId: runtimeLease.dispatchAttemptId,
675
1328
  fencingToken: runtimeLease.fencingToken,
676
- }, promotion);
1329
+ };
1330
+ if (!this.parallelProjectOwned(projectKey, owner)) {
1331
+ this.convertSingletonToParallelProject(projectKey, owner, promotion);
1332
+ }
677
1333
  const admission = this.admissions.get(runtimeLease.dispatchAttemptId);
678
1334
  if (admission?.fencingToken === runtimeLease.fencingToken) {
679
1335
  this.admissions.set(runtimeLease.dispatchAttemptId, {
@@ -757,9 +1413,12 @@ export class HostRuntimeLeaseManager {
757
1413
  unlinkAbortController(controller, signal);
758
1414
  }
759
1415
  }
760
- async release(dispatchAttemptId, fencingToken) {
1416
+ async release(dispatchAttemptId, fencingToken, preservePreparation = false) {
1417
+ if (!preservePreparation)
1418
+ this.preparedReadiness.cancel(dispatchAttemptId, fencingToken);
761
1419
  const active = this.active.get(dispatchAttemptId);
762
- this.pendingRenewals.delete(dispatchAttemptId);
1420
+ if (!preservePreparation)
1421
+ this.pendingRenewals.delete(dispatchAttemptId);
763
1422
  if (!active) {
764
1423
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
765
1424
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
@@ -774,17 +1433,57 @@ export class HostRuntimeLeaseManager {
774
1433
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
775
1434
  }
776
1435
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1436
+ await active.databaseProvision?.catch(() => undefined);
777
1437
  let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
778
1438
  active.lease = releasing;
779
1439
  await this.writeLedger(releasing);
780
1440
  try {
781
- await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
782
- await releaseAdapterResources(active.adapterCleanups);
783
- await fs.rm(active.attemptRoot, { recursive: true, force: true });
784
- releasing = transitionRuntimeIsolationLease(releasing, "released");
785
- active.lease = releasing;
786
- await this.writeLedger(releasing);
787
- await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
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;
788
1487
  this.active.delete(dispatchAttemptId);
789
1488
  this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
790
1489
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
@@ -825,28 +1524,60 @@ export class HostRuntimeLeaseManager {
825
1524
  }
826
1525
  return ledgers;
827
1526
  }
828
- async recoverPersistedProcesses(lease, attemptRoot) {
1527
+ async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
829
1528
  const logsRoot = path.join(attemptRoot, "logs");
830
1529
  const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
831
1530
  if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
832
1531
  throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
833
1532
  }
834
- const entries = await fs.readdir(logsRoot, { withFileTypes: true }).catch(error => {
835
- if (error.code === "ENOENT")
836
- return [];
837
- throw error;
838
- });
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
+ }
839
1541
  const outcomes = [];
840
- for (const entry of entries) {
841
- if (!entry.isFile() || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
842
- continue;
843
- const metadataPath = path.join(logsRoot, entry.name);
844
- const value = JSON.parse(await fs.readFile(metadataPath, "utf8"));
845
- if (!validHostProcessSupervisorMetadata(value, lease)) {
846
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
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);
847
1572
  }
848
- outcomes.push(await this.processRecovery.recover(value));
849
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");
850
1581
  return outcomes;
851
1582
  }
852
1583
  async markLedgerDegraded(ledger) {
@@ -856,7 +1587,7 @@ export class HostRuntimeLeaseManager {
856
1587
  const degraded = transitionHostLeaseForCleanup(lease, "degraded");
857
1588
  const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
858
1589
  this.rememberDegraded(degraded, repoId);
859
- await this.writeLedger(degraded, repoId ?? undefined).catch(() => undefined);
1590
+ await this.writeLedger(degraded, repoId ?? undefined, deserializeHostAttemptRootIdentity(ledger.attemptRootIdentity)).catch(() => undefined);
860
1591
  }
861
1592
  rememberDegraded(lease, repoId) {
862
1593
  this.degraded.set(lease.dispatchAttemptId, { lease, repoId });
@@ -876,13 +1607,26 @@ export class HostRuntimeLeaseManager {
876
1607
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
877
1608
  }
878
1609
  attemptRoot(dispatchAttemptId) {
879
- return path.join(this.stateRoot, "host-attempts", uuidHex(dispatchAttemptId, "dispatch attempt"));
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;
880
1624
  }
881
- async writeLedger(runtimeLease, explicitRepoId) {
1625
+ async writeLedgerAtomic(runtimeLease, explicitRepoId, explicitAttemptRootIdentity) {
882
1626
  const root = path.join(this.stateRoot, "runtime-ledger", "host");
883
1627
  await ensurePrivateDirectory(root);
884
1628
  const target = this.ledgerPath(runtimeLease.dispatchAttemptId);
885
- const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
1629
+ const temporary = `${target}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
886
1630
  try {
887
1631
  const handle = await fs.open(temporary, "wx", 0o600);
888
1632
  try {
@@ -891,9 +1635,15 @@ export class HostRuntimeLeaseManager {
891
1635
  ?? this.admissions.get(runtimeLease.dispatchAttemptId)?.repoId
892
1636
  ?? this.degraded.get(runtimeLease.dispatchAttemptId)?.repoId
893
1637
  ?? undefined;
1638
+ const attemptRootIdentity = explicitAttemptRootIdentity
1639
+ ?? this.active.get(runtimeLease.dispatchAttemptId)?.attemptRootIdentity
1640
+ ?? undefined;
894
1641
  const ledger = {
895
1642
  schemaVersion: 1,
896
1643
  ...(repoId ? { repoId } : {}),
1644
+ ...(attemptRootIdentity
1645
+ ? { attemptRootIdentity: serializeHostAttemptRootIdentity(attemptRootIdentity) }
1646
+ : {}),
897
1647
  runtimeLease,
898
1648
  };
899
1649
  await handle.writeFile(`${JSON.stringify(ledger)}\n`);
@@ -906,7 +1656,7 @@ export class HostRuntimeLeaseManager {
906
1656
  }
907
1657
  catch (error) {
908
1658
  await fs.rm(temporary, { force: true }).catch(() => undefined);
909
- throw error;
1659
+ throw new Error(`host_runtime_ledger_write_failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
910
1660
  }
911
1661
  }
912
1662
  ledgerPath(dispatchAttemptId) {
@@ -936,7 +1686,7 @@ export class HostRuntimeLeaseManager {
936
1686
  this.singletonOwners.delete(key);
937
1687
  for (let index = 0; index < this.singletonWaiters.length;) {
938
1688
  const waiter = this.singletonWaiters[index];
939
- if (waiter.keys.length !== 1 || waiter.keys[0] !== key) {
1689
+ if (waiter.priority !== "foreground" || waiter.keys.length !== 1 || waiter.keys[0] !== key) {
940
1690
  index += 1;
941
1691
  continue;
942
1692
  }
@@ -952,9 +1702,10 @@ export class HostRuntimeLeaseManager {
952
1702
  parallelProjectOwned(key, owner) {
953
1703
  return sameSingletonOwner(this.parallelProjectOwners.get(key)?.get(owner.dispatchAttemptId), owner);
954
1704
  }
955
- parallelProjectAvailable(key) {
1705
+ parallelProjectAvailable(key, priority = "foreground") {
956
1706
  return !this.singletonOwners.has(key)
957
- && !this.singletonWaiters.some(waiter => waiter.keys.includes(key));
1707
+ && !this.singletonWaiters.some(waiter => waiter.keys.includes(key)
1708
+ && (priority === "background" || waiter.priority === "foreground"));
958
1709
  }
959
1710
  assignParallelProject(key, owner) {
960
1711
  const owners = this.parallelProjectOwners.get(key) ?? new Map();
@@ -980,9 +1731,15 @@ export class HostRuntimeLeaseManager {
980
1731
  if (this.admissions.get(dispatchAttemptId)?.fencingToken === fencingToken) {
981
1732
  this.admissions.delete(dispatchAttemptId);
982
1733
  }
1734
+ this.releaseHostCapacity(dispatchAttemptId, fencingToken);
983
1735
  }
984
1736
  renewAdmissionWaiterDeadline(dispatchAttemptId, fencingToken, expiresAt) {
985
- for (const waiter of [...this.singletonWaiters, ...this.parallelProjectWaiters]) {
1737
+ for (const waiter of [
1738
+ ...this.singletonWaiters,
1739
+ ...this.parallelProjectWaiters,
1740
+ ...this.capacityWaiters,
1741
+ ...this.backgroundAdmissionWaiters,
1742
+ ]) {
986
1743
  if (!sameSingletonOwner(waiter.owner, { dispatchAttemptId, fencingToken })
987
1744
  || Date.parse(expiresAt) <= Date.parse(waiter.expiresAt))
988
1745
  continue;
@@ -998,13 +1755,20 @@ export class HostRuntimeLeaseManager {
998
1755
  }
999
1756
  cancelAdmissionWaiters(dispatchAttemptId, fencingToken, reason) {
1000
1757
  const owner = { dispatchAttemptId, fencingToken };
1001
- for (const waiters of [this.singletonWaiters, this.parallelProjectWaiters]) {
1758
+ for (const waiters of [
1759
+ this.singletonWaiters,
1760
+ this.parallelProjectWaiters,
1761
+ this.capacityWaiters,
1762
+ this.backgroundAdmissionWaiters,
1763
+ ]) {
1002
1764
  for (let index = waiters.length - 1; index >= 0; index -= 1) {
1003
1765
  const waiter = waiters[index];
1004
1766
  if (!sameSingletonOwner(waiter.owner, owner))
1005
1767
  continue;
1006
1768
  waiters.splice(index, 1);
1007
1769
  clearAdmissionDeadline(waiter);
1770
+ if ("capacityRecheckTimer" in waiter)
1771
+ clearCapacityRecheck(waiter);
1008
1772
  waiter.signal?.removeEventListener("abort", waiter.abort);
1009
1773
  waiter.reject(new Error(`host_runtime_admission_cancelled: ${reason}`));
1010
1774
  }
@@ -1060,7 +1824,7 @@ export class HostRuntimeLeaseManager {
1060
1824
  waiter.reject(new HostRuntimeAdmissionExpiredError());
1061
1825
  continue;
1062
1826
  }
1063
- if (!this.parallelProjectAvailable(waiter.key)) {
1827
+ if (!this.parallelProjectAvailable(waiter.key, waiter.priority)) {
1064
1828
  index += 1;
1065
1829
  continue;
1066
1830
  }
@@ -1071,19 +1835,103 @@ export class HostRuntimeLeaseManager {
1071
1835
  waiter.resolve();
1072
1836
  }
1073
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
+ }
1074
1878
  async refreshKnownPromotions() {
1075
1879
  const promotions = await this.promotionStore.list();
1076
1880
  this.knownPromotions.clear();
1077
1881
  for (const promotion of promotions)
1078
1882
  this.knownPromotions.set(promotion.repoId, promotion);
1079
1883
  }
1080
- async invalidatePromotion(repoId) {
1081
- await this.promotionStore.invalidate(repoId);
1884
+ async invalidatePromotion(repoId, scope = "all") {
1885
+ await this.promotionStore.invalidate(repoId, scope);
1082
1886
  this.knownPromotions.delete(repoId.trim().toLowerCase());
1083
1887
  }
1084
1888
  drainAdmissionWaiters() {
1889
+ this.reconcileReservationOwners();
1085
1890
  this.drainSingletonWaiters();
1086
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 });
1087
1935
  }
1088
1936
  }
1089
1937
  class AttemptSupervisedProviderProcessRunner {
@@ -1091,14 +1939,32 @@ class AttemptSupervisedProviderProcessRunner {
1091
1939
  owner;
1092
1940
  listenerInspector;
1093
1941
  enforceNoListeners;
1094
- constructor(supervisor, owner, listenerInspector, enforceNoListeners) {
1942
+ onProcessTreeStarted;
1943
+ constructor(supervisor, owner, listenerInspector, enforceNoListeners, onProcessTreeStarted) {
1095
1944
  this.supervisor = supervisor;
1096
1945
  this.owner = owner;
1097
1946
  this.listenerInspector = listenerInspector;
1098
1947
  this.enforceNoListeners = enforceNoListeners;
1948
+ this.onProcessTreeStarted = onProcessTreeStarted;
1099
1949
  }
1100
1950
  async run(request, handlers = {}, signal) {
1951
+ const baselineListeners = this.enforceNoListeners
1952
+ ? new Set(await this.listenerInspector.inspectLoopbackListeners())
1953
+ : new Set();
1101
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) {
1102
1968
  if (!this.enforceNoListeners)
1103
1969
  return await child.result;
1104
1970
  let settled = false;
@@ -1106,7 +1972,8 @@ class AttemptSupervisedProviderProcessRunner {
1106
1972
  const monitor = (async () => {
1107
1973
  while (!settled) {
1108
1974
  try {
1109
- const ports = await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner);
1975
+ const ports = (await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner))
1976
+ .filter(port => !baselineListeners.has(port));
1110
1977
  if (ports.length > 0) {
1111
1978
  inspectionFailure = new Error(`host_analysis_listener_violation: analysis-only provider opened undeclared loopback listener(s): ${ports.join(", ")}.`);
1112
1979
  await child.stop(this.owner.fencingToken).catch(() => undefined);
@@ -1170,6 +2037,12 @@ export class HostRuntimeAdmissionExpiredError extends Error {
1170
2037
  this.name = "HostRuntimeAdmissionExpiredError";
1171
2038
  }
1172
2039
  }
2040
+ export class HostRuntimeCapacityRequestImpossibleError extends Error {
2041
+ constructor(reason) {
2042
+ super(`host_runtime_capacity_request_impossible: ${reason}`);
2043
+ this.name = "HostRuntimeCapacityRequestImpossibleError";
2044
+ }
2045
+ }
1173
2046
  export function hostRuntimeEventResources(lease, runtimeContract, executionClass = "managed_runtime") {
1174
2047
  const requestedHostConcurrency = runtimeContract?.contract.runtime.hostConcurrency ?? "serial";
1175
2048
  const configuredLaunches = runtimeContract?.contract.runtime.ports.filter(port => port.launch !== null) ?? [];
@@ -1202,13 +2075,15 @@ export function hostRuntimeEventResources(lease, runtimeContract, executionClass
1202
2075
  export function hostRuntimeSingletonKeys(dispatch) {
1203
2076
  return [projectHostRuntimeSingletonKey(dispatch.repo.id)];
1204
2077
  }
1205
- function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass) {
2078
+ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass, databaseCapability) {
1206
2079
  const pathFor = (role) => lease.resources.paths.find(entry => entry.role === role)?.path ?? "";
1207
2080
  const environment = {
1208
2081
  FORGE_SESSION_ID: sessionId,
1209
2082
  FORGE_RUNTIME_MODE: "host",
1210
2083
  FORGE_RESOURCE_LEASE_ID: lease.leaseId,
1211
2084
  FORGE_DISPATCH_ATTEMPT_ID: lease.dispatchAttemptId,
2085
+ FORGE_E2E_OWNERSHIP_MODE: "attempt",
2086
+ FORGE_E2E_OWNERSHIP_TOKEN: uuidHex(lease.dispatchAttemptId, "dispatch attempt"),
1212
2087
  FORGE_EXECUTION_LEASE_ID: lease.executionLeaseId,
1213
2088
  FORGE_FENCING_TOKEN: lease.fencingToken,
1214
2089
  FORGE_WORKSPACE: lease.worktreePath,
@@ -1218,6 +2093,12 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
1218
2093
  FORGE_CACHE_DIR: pathFor("cache"),
1219
2094
  FORGE_BROWSER_PROFILE_DIR: pathFor("browser_profile"),
1220
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"),
1221
2102
  FORGE_PROCESS_SUPERVISOR_ID: lease.resources.processSupervisorId ?? "",
1222
2103
  FORGE_PROCESS_SUPERVISOR_METADATA_PATH: pathFor("process_supervisor_metadata"),
1223
2104
  FORGE_HOST_CONCURRENCY: effectiveHostConcurrency(lease, runtimeContract, executionClass),
@@ -1233,6 +2114,8 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
1233
2114
  };
1234
2115
  if (lease.resources.singletonKeys.length === 0)
1235
2116
  delete environment.FORGE_SINGLETON_KEYS;
2117
+ if (databaseCapability)
2118
+ environment[attemptDatabaseCapabilityEnvironment] = databaseCapability.connectionString;
1236
2119
  const resolvedBaseUrls = [];
1237
2120
  for (const assigned of lease.resources.ports) {
1238
2121
  const configured = runtimeContract.contract.runtime.ports.find(port => port.name === assigned.name);
@@ -1257,6 +2140,45 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
1257
2140
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
1258
2141
  return environment;
1259
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
+ }
1260
2182
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
1261
2183
  if (executionClass === "analysis_only") {
1262
2184
  const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
@@ -1285,6 +2207,125 @@ function runtimeExecutionClass(dispatch) {
1285
2207
  ? "analysis_only"
1286
2208
  : "managed_runtime";
1287
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
+ }
1288
2329
  function capacityProject(projects, repoId) {
1289
2330
  const normalized = repoId.trim().toLowerCase();
1290
2331
  const existing = projects.get(normalized);
@@ -1327,6 +2368,9 @@ function repoIdFromProjectSingletonKey(key) {
1327
2368
  function sameSingletonOwner(left, right) {
1328
2369
  return left?.dispatchAttemptId === right.dispatchAttemptId && left.fencingToken === right.fencingToken;
1329
2370
  }
2371
+ function hostRuntimeOwnerKey(owner) {
2372
+ return `${owner.dispatchAttemptId}:${owner.fencingToken}`;
2373
+ }
1330
2374
  function hostPortOwner(lease) {
1331
2375
  const processSupervisorId = lease.resources.processSupervisorId;
1332
2376
  if (!processSupervisorId) {
@@ -1375,6 +2419,14 @@ async function releaseAdapterResources(cleanups) {
1375
2419
  if (firstError !== undefined)
1376
2420
  throw firstError;
1377
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
+ }
1378
2430
  function cancellationError(signal) {
1379
2431
  return new Error(String(signal?.reason ?? "Dispatch cancelled while waiting for host runtime singleton ownership."));
1380
2432
  }
@@ -1384,9 +2436,25 @@ function validHostRuntimeLedger(value) {
1384
2436
  const ledger = value;
1385
2437
  return ledger.schemaVersion === 1
1386
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))
1387
2441
  && validRuntimeIsolationLease(ledger.runtimeLease)
1388
2442
  && ledger.runtimeLease.mode === "host";
1389
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
+ }
1390
2458
  function validHostProcessSupervisorMetadata(value, lease) {
1391
2459
  if (typeof value !== "object" || value === null)
1392
2460
  return false;
@@ -1435,6 +2503,11 @@ function clearAdmissionDeadline(waiter) {
1435
2503
  clearTimeout(waiter.deadlineTimer);
1436
2504
  waiter.deadlineTimer = null;
1437
2505
  }
2506
+ function clearCapacityRecheck(waiter) {
2507
+ if (waiter.capacityRecheckTimer)
2508
+ clearInterval(waiter.capacityRecheckTimer);
2509
+ waiter.capacityRecheckTimer = null;
2510
+ }
1438
2511
  async function ensurePrivateDirectory(directory) {
1439
2512
  await fs.mkdir(directory, { recursive: true, mode: 0o700 });
1440
2513
  if (process.platform !== "win32")