@loucompanion/forge-bridge 0.1.3-dev.8777774c67bc → 0.1.3-dev.88e93f53db5b

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 (137) hide show
  1. package/README.md +51 -0
  2. package/dist/bridge/bridge.base.d.ts +4 -1
  3. package/dist/bridge/bridge.service.d.ts +50 -3
  4. package/dist/bridge/bridge.service.js +730 -87
  5. package/dist/bridge/bridge.types.d.ts +63 -1
  6. package/dist/cleanup/cleanup.service.d.ts +14 -2
  7. package/dist/cleanup/cleanup.service.js +496 -3
  8. package/dist/cleanup/cleanup.types.d.ts +10 -0
  9. package/dist/cleanup/index.d.ts +1 -1
  10. package/dist/cleanup/index.js +1 -1
  11. package/dist/cleanup/internals.d.ts +2 -2
  12. package/dist/cleanup/internals.js +1 -1
  13. package/dist/cli/cli.help.js +37 -3
  14. package/dist/cli/cli.service.d.ts +30 -2
  15. package/dist/cli/cli.service.js +191 -27
  16. package/dist/cli/local-config.d.ts +4 -0
  17. package/dist/cli/local-config.js +41 -1
  18. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  19. package/dist/runtime/aspnet-runtime-prebuild.js +340 -0
  20. package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
  21. package/dist/runtime/attempt-node-runtime-launcher.js +105 -0
  22. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  23. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  24. package/dist/runtime/attempt-process-supervisor.d.ts +97 -0
  25. package/dist/runtime/attempt-process-supervisor.js +384 -0
  26. package/dist/runtime/generated-output-reset.d.ts +10 -0
  27. package/dist/runtime/generated-output-reset.js +103 -0
  28. package/dist/runtime/host-listener-inspector.d.ts +46 -0
  29. package/dist/runtime/host-listener-inspector.js +349 -0
  30. package/dist/runtime/host-port-broker.d.ts +76 -0
  31. package/dist/runtime/host-port-broker.js +333 -0
  32. package/dist/runtime/host-runtime-contract.d.ts +47 -0
  33. package/dist/runtime/host-runtime-contract.js +700 -0
  34. package/dist/runtime/host-runtime-lease.d.ts +194 -0
  35. package/dist/runtime/host-runtime-lease.js +2138 -0
  36. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  37. package/dist/runtime/host-runtime-promotion.js +159 -0
  38. package/dist/runtime/memory-capacity.d.ts +68 -0
  39. package/dist/runtime/memory-capacity.js +121 -0
  40. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  41. package/dist/runtime/node-host-runtime-adapter.js +284 -0
  42. package/dist/runtime/playwright-host-runtime-adapter.d.ts +21 -0
  43. package/dist/runtime/playwright-host-runtime-adapter.js +225 -0
  44. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  45. package/dist/runtime/runtime-isolation-lease.js +158 -0
  46. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  47. package/dist/runtime/workspace-resource-estimator.js +174 -0
  48. package/dist/sandbox/image-policy.d.ts +3 -1
  49. package/dist/sandbox/image-policy.js +4 -2
  50. package/dist/sandbox/preflight.d.ts +49 -1
  51. package/dist/sandbox/preflight.js +313 -31
  52. package/dist/sandbox/process.js +125 -40
  53. package/dist/sandbox/repository-lock.js +41 -3
  54. package/dist/sandbox/runtime.d.ts +85 -4
  55. package/dist/sandbox/runtime.js +806 -126
  56. package/dist/sandbox/sandbox.types.d.ts +10 -0
  57. package/dist/sandbox/smoke.d.ts +76 -0
  58. package/dist/sandbox/smoke.js +380 -0
  59. package/dist/sandbox/worker-supervisor.js +1 -1
  60. package/dist/sandbox/worker.js +2 -5
  61. package/dist/sandbox/workspace.service.d.ts +1 -0
  62. package/dist/sandbox/workspace.service.js +28 -5
  63. package/dist/session/managed-attempt-tools.d.ts +18 -0
  64. package/dist/session/managed-attempt-tools.js +854 -0
  65. package/dist/session/managed-build-coordinator.d.ts +5 -0
  66. package/dist/session/managed-build-coordinator.js +105 -0
  67. package/dist/session/managed-build-receipt.d.ts +21 -0
  68. package/dist/session/managed-build-receipt.js +335 -0
  69. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  70. package/dist/session/phase-completion.artifacts.js +233 -24
  71. package/dist/session/phase-completion.d.ts +11 -2
  72. package/dist/session/phase-completion.helpers.d.ts +5 -0
  73. package/dist/session/phase-completion.helpers.js +51 -10
  74. package/dist/session/phase-completion.js +12 -3
  75. package/dist/session/phase-completion.prompts.d.ts +3 -3
  76. package/dist/session/phase-completion.prompts.js +21 -6
  77. package/dist/session/phase-completion.runtime.d.ts +13 -1
  78. package/dist/session/phase-completion.runtime.js +189 -8
  79. package/dist/session/phase-completion.schemas.js +108 -3
  80. package/dist/session/phase-completion.validation.d.ts +4 -1
  81. package/dist/session/phase-completion.validation.js +151 -21
  82. package/dist/session/provider-cli/ci-repair-readiness.d.ts +14 -0
  83. package/dist/session/provider-cli/ci-repair-readiness.js +105 -0
  84. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +3 -2
  85. package/dist/session/provider-cli/provider-cli.artifacts.js +65 -7
  86. package/dist/session/provider-cli/provider-cli.deterministic.js +47 -1
  87. package/dist/session/provider-cli/provider-cli.process.d.ts +23 -0
  88. package/dist/session/provider-cli/provider-cli.process.js +420 -32
  89. package/dist/session/provider-cli/provider-cli.prompts.d.ts +4 -1
  90. package/dist/session/provider-cli/provider-cli.prompts.js +99 -19
  91. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +1 -0
  92. package/dist/session/provider-cli/provider-cli.runtime.d.ts +1 -1
  93. package/dist/session/provider-cli/provider-cli.runtime.js +6 -3
  94. package/dist/session/provider-cli/provider-cli.service.d.ts +20 -2
  95. package/dist/session/provider-cli/provider-cli.service.js +464 -102
  96. package/dist/session/provider-cli/provider-cli.types.d.ts +5 -0
  97. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  98. package/dist/session/provider-cli/provider-output-state.js +91 -16
  99. package/dist/session/provider-cli/provider-usage.d.ts +7 -0
  100. package/dist/session/provider-cli/provider-usage.js +28 -5
  101. package/dist/session/session-redaction.d.ts +3 -0
  102. package/dist/session/session-redaction.js +38 -0
  103. package/dist/session/session.base.d.ts +6 -1
  104. package/dist/session/session.service.d.ts +8 -2
  105. package/dist/session/session.service.js +522 -41
  106. package/dist/session/session.types.d.ts +70 -0
  107. package/dist/session/session.types.js +76 -4
  108. package/dist/shared/format/format-bytes.d.ts +1 -0
  109. package/dist/shared/format/format-bytes.js +9 -0
  110. package/dist/shared/path/path.d.ts +1 -0
  111. package/dist/shared/path/path.js +21 -1
  112. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  113. package/dist/shared/process/host-process-recovery.js +78 -0
  114. package/dist/shared/process/host-process-supervisor.d.ts +59 -0
  115. package/dist/shared/process/host-process-supervisor.js +330 -0
  116. package/dist/shared/process/process.d.ts +1 -0
  117. package/dist/shared/process/process.js +1 -0
  118. package/dist/shared/redaction/redaction.js +12 -2
  119. package/dist/version.d.ts +1 -1
  120. package/dist/version.js +1 -1
  121. package/dist/worktree/artifact-injector.d.ts +3 -2
  122. package/dist/worktree/artifact-injector.js +43 -4
  123. package/dist/worktree/dependency-warmer.d.ts +28 -1
  124. package/dist/worktree/dependency-warmer.js +308 -9
  125. package/dist/worktree/index.d.ts +2 -1
  126. package/dist/worktree/index.js +1 -0
  127. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  128. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  129. package/dist/worktree/worktree-paths.d.ts +4 -0
  130. package/dist/worktree/worktree-paths.js +30 -0
  131. package/dist/worktree/worktree.base.d.ts +3 -0
  132. package/dist/worktree/worktree.service.d.ts +9 -2
  133. package/dist/worktree/worktree.service.js +217 -48
  134. package/dist/worktree/worktree.types.d.ts +5 -1
  135. package/package.json +5 -3
  136. package/runtime/windows-job-supervisor.ps1 +444 -0
  137. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -0,0 +1,2138 @@
1
+ import fs from "node:fs/promises";
2
+ import { statfsSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { resolveExistingDirectoryPath } from "../shared/path/path.js";
6
+ import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
7
+ import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
8
+ import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
9
+ import { HostPortBroker, } from "./host-port-broker.js";
10
+ import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
11
+ import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
12
+ import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
13
+ import { HostListenerInspector } from "./host-listener-inspector.js";
14
+ import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
15
+ import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
16
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
17
+ import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
18
+ import { resetGeneratedOutputs } from "./generated-output-reset.js";
19
+ import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
20
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
21
+ const hostCapacityWaiterScanLimit = 64;
22
+ export class HostRuntimeLeaseManager {
23
+ stateRoot;
24
+ processSupervisors;
25
+ processRunner;
26
+ listenerInspector;
27
+ promotionStore;
28
+ playwrightAdapter;
29
+ processRecovery;
30
+ capacityResourceSample;
31
+ active = new Map();
32
+ pendingRenewals = new Map();
33
+ admissions = new Map();
34
+ singletonOwners = new Map();
35
+ singletonWaiters = [];
36
+ parallelProjectOwners = new Map();
37
+ parallelProjectWaiters = [];
38
+ capacityReservations = new Map();
39
+ capacityWaiters = [];
40
+ capacityWaiterScanCursor = 0;
41
+ backgroundAdmissionWaiters = [];
42
+ degraded = new Map();
43
+ knownPromotions = new Map();
44
+ workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
45
+ ambientMemoryCommitmentBytes = null;
46
+ portBroker;
47
+ nodeAdapter;
48
+ capacityConfiguration;
49
+ memoryAvailability;
50
+ 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) {
51
+ this.stateRoot = stateRoot;
52
+ this.processSupervisors = processSupervisors;
53
+ this.processRunner = processRunner;
54
+ this.listenerInspector = listenerInspector;
55
+ this.promotionStore = promotionStore;
56
+ this.playwrightAdapter = playwrightAdapter;
57
+ this.processRecovery = processRecovery;
58
+ this.capacityResourceSample = capacityResourceSample;
59
+ this.portBroker = portBroker;
60
+ this.nodeAdapter = nodeAdapter ?? new NodeHostRuntimeAdapter(portBroker);
61
+ this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
62
+ this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
63
+ }
64
+ async reap(options) {
65
+ await this.refreshKnownPromotions();
66
+ const report = {
67
+ examined: 0,
68
+ reaped: 0,
69
+ processesTerminated: 0,
70
+ reusedPidsProtected: 0,
71
+ degraded: 0,
72
+ };
73
+ for (const ledger of await this.readLedgers()) {
74
+ const lease = ledger.runtimeLease;
75
+ if (lease.runnerId !== options.runnerId)
76
+ continue;
77
+ const active = this.active.get(lease.dispatchAttemptId);
78
+ if (active) {
79
+ if (active.lease.state !== "degraded")
80
+ continue;
81
+ report.examined += 1;
82
+ try {
83
+ const released = await this.release(lease.dispatchAttemptId, lease.fencingToken);
84
+ if (released?.state === "released")
85
+ report.reaped += 1;
86
+ else
87
+ report.degraded += 1;
88
+ }
89
+ catch {
90
+ report.degraded += 1;
91
+ }
92
+ continue;
93
+ }
94
+ const staleInstance = lease.runnerInstanceId !== options.runnerInstanceId;
95
+ const expired = Date.parse(lease.expiresAt) <= (options.nowMs ?? Date.now());
96
+ if (!staleInstance && !expired && lease.state !== "released" && lease.state !== "degraded")
97
+ continue;
98
+ report.examined += 1;
99
+ const attemptRoot = this.attemptRoot(lease.dispatchAttemptId);
100
+ let outcomes;
101
+ try {
102
+ outcomes = await this.recoverPersistedProcesses(lease, attemptRoot);
103
+ }
104
+ catch {
105
+ await this.markLedgerDegraded(ledger);
106
+ report.degraded += 1;
107
+ continue;
108
+ }
109
+ report.processesTerminated += outcomes.filter(outcome => outcome === "terminated").length;
110
+ report.reusedPidsProtected += outcomes.filter(outcome => outcome === "pid_reused").length;
111
+ if (outcomes.includes("unverifiable")) {
112
+ await this.markLedgerDegraded(ledger);
113
+ report.degraded += 1;
114
+ continue;
115
+ }
116
+ try {
117
+ const releasing = transitionHostLeaseForCleanup(lease, "releasing");
118
+ await this.writeLedger(releasing, ledger.repoId);
119
+ await fs.rm(attemptRoot, { recursive: true, force: true });
120
+ await fs.rm(this.ledgerPath(lease.dispatchAttemptId), { force: true });
121
+ this.forgetDegraded(lease.dispatchAttemptId, lease.fencingToken);
122
+ report.reaped += 1;
123
+ }
124
+ catch {
125
+ await this.markLedgerDegraded(ledger);
126
+ report.degraded += 1;
127
+ }
128
+ }
129
+ return report;
130
+ }
131
+ snapshot() {
132
+ const projects = new Map();
133
+ for (const promotion of this.knownPromotions.values()) {
134
+ const project = capacityProject(projects, promotion.repoId);
135
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_safe");
136
+ project.runtimeContractFingerprint = promotion.runtimeContractFingerprint;
137
+ project.runtimeContractSource = promotion.runtimeContractSource ?? null;
138
+ project.promotedAt = promotion.observedAt;
139
+ }
140
+ for (const [dispatchAttemptId, admission] of this.admissions) {
141
+ const active = this.active.get(dispatchAttemptId);
142
+ const project = capacityProject(projects, admission.repoId);
143
+ if (active) {
144
+ if (active.lease.state === "degraded") {
145
+ project.degradedAttempts += 1;
146
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
147
+ }
148
+ else {
149
+ project.activeAttempts += 1;
150
+ const effectiveConcurrency = effectiveHostConcurrency(active.lease, active.runtimeContract, active.executionClass);
151
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, effectiveConcurrency === "host_parallel_safe"
152
+ ? effectiveConcurrency
153
+ : admission.executionClass === "analysis_only"
154
+ ? "host_parallel_safe"
155
+ : admission.parallelProjectKey && admission.provisionalPromotionFingerprint
156
+ ? "host_parallel_candidate"
157
+ : "host_serial_only");
158
+ }
159
+ }
160
+ else {
161
+ project.reservedAttempts += 1;
162
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, admission.executionClass === "analysis_only"
163
+ ? "host_parallel_safe"
164
+ : admission.provisionalPromotionFingerprint ? "host_parallel_candidate" : "host_serial_only");
165
+ }
166
+ }
167
+ for (const [dispatchAttemptId, degraded] of this.degraded) {
168
+ if (this.active.has(dispatchAttemptId) || !degraded.repoId)
169
+ continue;
170
+ const project = capacityProject(projects, degraded.repoId);
171
+ project.degradedAttempts += 1;
172
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
173
+ }
174
+ for (const waiter of this.singletonWaiters) {
175
+ const repoId = repoIdFromProjectSingletonKeys(waiter.keys);
176
+ if (!repoId)
177
+ continue;
178
+ const project = capacityProject(projects, repoId);
179
+ project.waitingAttempts += 1;
180
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
181
+ }
182
+ for (const waiter of this.parallelProjectWaiters) {
183
+ const repoId = repoIdFromProjectSingletonKey(waiter.key);
184
+ if (!repoId)
185
+ continue;
186
+ const project = capacityProject(projects, repoId);
187
+ project.waitingAttempts += 1;
188
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_parallel_candidate");
189
+ }
190
+ for (const waiter of this.backgroundAdmissionWaiters) {
191
+ const repoId = repoIdFromProjectSingletonKeys(waiter.keys);
192
+ if (!repoId)
193
+ continue;
194
+ const project = capacityProject(projects, repoId);
195
+ project.waitingAttempts += 1;
196
+ project.safetyClass = conservativeSafetyClass(project.safetyClass, "host_serial_only");
197
+ }
198
+ const activeAttempts = [...this.active.values()]
199
+ .filter(active => active.lease.state !== "degraded").length;
200
+ const degradedAttempts = new Set([
201
+ ...this.degraded.keys(),
202
+ ...[...this.active.entries()]
203
+ .filter(([, active]) => active.lease.state === "degraded")
204
+ .map(([dispatchAttemptId]) => dispatchAttemptId),
205
+ ]).size;
206
+ const hostResources = this.hostResourceSnapshot();
207
+ return {
208
+ activeAttempts,
209
+ reservedAttempts: Math.max(0, this.admissions.size - this.active.size),
210
+ waitingAttempts: this.singletonWaiters.length
211
+ + this.parallelProjectWaiters.length
212
+ + this.capacityWaiters.length
213
+ + this.backgroundAdmissionWaiters.length,
214
+ degradedAttempts,
215
+ exclusiveReservations: this.singletonOwners.size,
216
+ sharedReservations: [...this.parallelProjectOwners.values()]
217
+ .reduce((count, owners) => count + owners.size, 0),
218
+ ...hostResources,
219
+ projects: [...projects.values()]
220
+ .map(project => ({
221
+ ...project,
222
+ safetyClass: project.safetyClass ?? "host_serial_only",
223
+ }))
224
+ .sort((left, right) => left.repoId.localeCompare(right.repoId)),
225
+ };
226
+ }
227
+ hasForegroundDemand() {
228
+ return [...this.admissions.values()].some(admission => admission.priority === "foreground")
229
+ || this.singletonWaiters.some(waiter => waiter.priority === "foreground")
230
+ || this.parallelProjectWaiters.some(waiter => waiter.priority === "foreground")
231
+ || this.capacityWaiters.some(waiter => waiter.priority === "foreground");
232
+ }
233
+ async acquire(dispatch, signal) {
234
+ const sandbox = dispatch.sandbox;
235
+ if (!sandbox || sandbox.executionMode !== "host") {
236
+ throw new Error("host_runtime_lease_invalid: managed host sandbox context is required.");
237
+ }
238
+ uuidHex(sandbox.dispatchAttemptId, "dispatch attempt");
239
+ uuidHex(dispatch.lease.fencingToken, "fencing token");
240
+ const owner = {
241
+ dispatchAttemptId: sandbox.dispatchAttemptId,
242
+ fencingToken: dispatch.lease.fencingToken,
243
+ };
244
+ const existing = this.admissions.get(sandbox.dispatchAttemptId);
245
+ if (existing) {
246
+ if (existing.fencingToken !== owner.fencingToken) {
247
+ throw new Error("host_runtime_singleton_conflict: dispatch attempt already holds admission under a different fence.");
248
+ }
249
+ return existing.keys;
250
+ }
251
+ const executionClass = runtimeExecutionClass(dispatch);
252
+ const priority = runtimeAdmissionPriority(dispatch);
253
+ const promotion = executionClass === "managed_runtime"
254
+ ? await this.promotionStore.load(dispatch.repo.id)
255
+ : null;
256
+ if (promotion)
257
+ this.knownPromotions.set(promotion.repoId, promotion);
258
+ const projectKey = executionClass === "analysis_only"
259
+ ? projectHostAnalysisKey(dispatch.repo.id)
260
+ : projectHostRuntimeSingletonKey(dispatch.repo.id);
261
+ const useParallelAdmission = priority === "foreground"
262
+ && (promotion !== null || executionClass === "analysis_only");
263
+ let keys = useParallelAdmission ? [] : [projectKey];
264
+ const resources = normalizedHostResourceRequest(sandbox.requestedResources);
265
+ const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
266
+ ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
267
+ : dispatch.lease.expiresAt;
268
+ try {
269
+ if (priority === "background") {
270
+ await this.refreshWorkspaceCapacity();
271
+ keys = await this.reserveBackgroundAdmission(keys, owner, resources, expiresAt, signal);
272
+ }
273
+ else if (useParallelAdmission) {
274
+ await this.reserveParallelProject(projectKey, owner, expiresAt, signal, priority);
275
+ }
276
+ else {
277
+ keys = await this.reserveSingletonKeys(keys, owner, expiresAt, signal, priority);
278
+ }
279
+ if (priority === "foreground") {
280
+ await this.refreshWorkspaceCapacity();
281
+ const capacityExpiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
282
+ ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
283
+ : expiresAt;
284
+ await this.reserveHostCapacity(owner, resources, capacityExpiresAt, signal, priority);
285
+ }
286
+ }
287
+ catch (error) {
288
+ this.releaseHostCapacity(owner.dispatchAttemptId, owner.fencingToken);
289
+ this.releaseSingletonKeys(owner.dispatchAttemptId, owner.fencingToken);
290
+ this.releaseParallelProjects(owner.dispatchAttemptId, owner.fencingToken);
291
+ this.clearPendingRenewal(owner);
292
+ throw error;
293
+ }
294
+ const admittedPromotion = useParallelAdmission
295
+ ? promotion ?? (executionClass === "managed_runtime" && keys.length === 0
296
+ ? this.knownPromotions.get(dispatch.repo.id) ?? null
297
+ : null)
298
+ : null;
299
+ this.admissions.set(sandbox.dispatchAttemptId, {
300
+ repoId: dispatch.repo.id,
301
+ fencingToken: owner.fencingToken,
302
+ executionClass,
303
+ priority,
304
+ provisionalPromotionFingerprint: admittedPromotion?.runtimeContractFingerprint ?? null,
305
+ keys,
306
+ parallelProjectKey: useParallelAdmission ? projectKey : null,
307
+ });
308
+ return keys;
309
+ }
310
+ async reserveHostCapacity(owner, resources, expiresAt, signal, priority = "foreground") {
311
+ const existing = this.capacityReservations.get(owner.dispatchAttemptId);
312
+ if (existing) {
313
+ if (!sameSingletonOwner(existing.owner, owner)) {
314
+ throw new Error("host_runtime_capacity_conflict: dispatch attempt already holds capacity under a different fence.");
315
+ }
316
+ return;
317
+ }
318
+ if (signal?.aborted)
319
+ throw cancellationError(signal);
320
+ throwIfAdmissionExpired(expiresAt);
321
+ const impossibleReason = this.hostCapacityImpossibleReason(resources);
322
+ if (impossibleReason)
323
+ throw new HostRuntimeCapacityRequestImpossibleError(impossibleReason);
324
+ if (this.capacityWaiters.length === 0 && this.hostCapacityAvailable(resources)) {
325
+ this.capacityReservations.set(owner.dispatchAttemptId, { owner, resources, state: "pending" });
326
+ return;
327
+ }
328
+ return new Promise((resolve, reject) => {
329
+ const waiter = {
330
+ owner,
331
+ resources,
332
+ priority,
333
+ resolve,
334
+ reject,
335
+ signal,
336
+ expiresAt,
337
+ deadlineTimer: null,
338
+ capacityRecheckTimer: null,
339
+ abort: () => {
340
+ if (!this.detachCapacityWaiter(waiter))
341
+ return;
342
+ this.clearPendingRenewal(owner);
343
+ reject(cancellationError(signal));
344
+ this.drainAdmissionWaiters();
345
+ },
346
+ expire: () => {
347
+ if (!this.detachCapacityWaiter(waiter))
348
+ return;
349
+ this.clearPendingRenewal(owner);
350
+ reject(new HostRuntimeAdmissionExpiredError());
351
+ this.drainAdmissionWaiters();
352
+ },
353
+ };
354
+ waiter.deadlineTimer = scheduleAdmissionDeadline(expiresAt, waiter.expire);
355
+ // Memory, CPU and filesystem capacity can recover without one of our leases
356
+ // being released (for example when an unrelated host process exits). Recheck
357
+ // ambient capacity while queued so readiness probes and attempts do not remain
358
+ // stranded behind a stale low-resource sample.
359
+ waiter.capacityRecheckTimer = setInterval(() => this.drainCapacityWaiters(), 1_000);
360
+ waiter.capacityRecheckTimer.unref?.();
361
+ signal?.addEventListener("abort", waiter.abort, { once: true });
362
+ enqueueAdmissionWaiter(this.capacityWaiters, waiter);
363
+ this.drainCapacityWaiters();
364
+ });
365
+ }
366
+ async reserveBackgroundAdmission(keys, owner, resources, expiresAt, signal) {
367
+ if (signal?.aborted)
368
+ throw cancellationError(signal);
369
+ throwIfAdmissionExpired(expiresAt);
370
+ return await new Promise((resolve, reject) => {
371
+ const waiter = {
372
+ owner,
373
+ keys,
374
+ resources,
375
+ priority: "background",
376
+ resolve,
377
+ reject,
378
+ signal,
379
+ expiresAt,
380
+ deadlineTimer: null,
381
+ capacityRecheckTimer: null,
382
+ abort: () => {
383
+ removeWaiter(this.backgroundAdmissionWaiters, waiter);
384
+ clearAdmissionDeadline(waiter);
385
+ clearCapacityRecheck(waiter);
386
+ this.clearPendingRenewal(owner);
387
+ reject(cancellationError(signal));
388
+ this.drainAdmissionWaiters();
389
+ },
390
+ expire: () => {
391
+ removeWaiter(this.backgroundAdmissionWaiters, waiter);
392
+ clearCapacityRecheck(waiter);
393
+ signal?.removeEventListener("abort", waiter.abort);
394
+ this.clearPendingRenewal(owner);
395
+ reject(new HostRuntimeAdmissionExpiredError());
396
+ this.drainAdmissionWaiters();
397
+ },
398
+ };
399
+ waiter.deadlineTimer = scheduleAdmissionDeadline(expiresAt, waiter.expire);
400
+ waiter.capacityRecheckTimer = setInterval(() => this.drainAdmissionWaiters(), 1_000);
401
+ waiter.capacityRecheckTimer.unref?.();
402
+ signal?.addEventListener("abort", waiter.abort, { once: true });
403
+ this.backgroundAdmissionWaiters.push(waiter);
404
+ this.drainAdmissionWaiters();
405
+ });
406
+ }
407
+ hostCapacityAvailable(resources) {
408
+ const capacity = this.hostResourceSnapshot();
409
+ return capacity.availableAttempts >= resources.sandboxSlots
410
+ && capacity.availableMemoryBytes >= resources.memoryBytes
411
+ && capacity.availableCpuMillis >= resources.cpuMillis
412
+ && capacity.availableWorkspaceBytes >= resources.workspaceBytes;
413
+ }
414
+ hostCapacityImpossibleReason(resources) {
415
+ const { hardMaxAttempts, hostReserveBytes, cpuReserveMillis } = this.capacityConfiguration;
416
+ if (resources.sandboxSlots > hardMaxAttempts) {
417
+ return `requested ${resources.sandboxSlots} sandbox slots exceed the host maximum of ${hardMaxAttempts}.`;
418
+ }
419
+ const totalMemoryBytes = this.capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
420
+ const maximumMemoryBytes = Math.max(0, totalMemoryBytes - hostReserveBytes);
421
+ if (resources.memoryBytes > maximumMemoryBytes) {
422
+ return `requested memory ${resources.memoryBytes} exceeds the host maximum of ${maximumMemoryBytes} bytes after reserve.`;
423
+ }
424
+ const totalCpuMillis = this.capacityResourceSample?.totalCpuMillis ?? os.cpus().length * 1_000;
425
+ const maximumCpuMillis = Math.max(0, totalCpuMillis - cpuReserveMillis);
426
+ if (resources.cpuMillis > maximumCpuMillis) {
427
+ return `requested CPU ${resources.cpuMillis} millis exceeds the host maximum of ${maximumCpuMillis} millis after reserve.`;
428
+ }
429
+ return null;
430
+ }
431
+ hostResourceSnapshot() {
432
+ if (!this.capacityResourceSample) {
433
+ try {
434
+ const stats = statfsSync(this.stateRoot);
435
+ this.workspaceAvailableBytes = Math.max(0, stats.bavail * stats.bsize);
436
+ }
437
+ catch {
438
+ // State root may not exist during the first capability heartbeat. The first
439
+ // admission creates it and refreshes the sample before reserving resources.
440
+ }
441
+ }
442
+ const { hardMaxAttempts, hostReserveBytes, cpuReserveMillis, workspaceReserveBytes } = this.capacityConfiguration;
443
+ const activeReservationMemoryBytes = [...this.capacityReservations.values()]
444
+ .reduce((total, reservation) => total + reservation.resources.memoryBytes, 0);
445
+ const pendingReservationMemoryBytes = [...this.capacityReservations.values()]
446
+ .filter(reservation => reservation.state === "pending")
447
+ .reduce((total, reservation) => total + reservation.resources.memoryBytes, 0);
448
+ const activeReservationCpuMillis = [...this.capacityReservations.values()]
449
+ .reduce((total, reservation) => total + reservation.resources.cpuMillis, 0);
450
+ const activeReservationWorkspaceBytes = [...this.capacityReservations.values()]
451
+ .reduce((total, reservation) => total + reservation.resources.workspaceBytes, 0);
452
+ const sampledAt = new Date().toISOString();
453
+ const totalMemoryBytes = this.capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
454
+ const rawAvailableMemoryBytes = this.capacityResourceSample?.availableMemoryBytes ?? os.freemem();
455
+ const sampledAvailableMemoryBytes = this.memoryAvailability.observe(rawAvailableMemoryBytes);
456
+ if (this.capacityReservations.size === 0) {
457
+ // Capture non-Forge resident use before the first reservation. Refreshing
458
+ // while idle lets the baseline recover when an unrelated process exits;
459
+ // freezing it while leases exist prevents pending/low-RSS workers from
460
+ // borrowing memory already occupied by the host and control plane.
461
+ this.ambientMemoryCommitmentBytes = Math.max(0, totalMemoryBytes - rawAvailableMemoryBytes);
462
+ }
463
+ const committedMemoryBytes = Math.min(totalMemoryBytes, (this.ambientMemoryCommitmentBytes ?? 0) + activeReservationMemoryBytes);
464
+ const totalCpuMillis = this.capacityResourceSample?.totalCpuMillis ?? os.cpus().length * 1000;
465
+ const sampledWorkspaceBytes = this.capacityResourceSample?.availableWorkspaceBytes ?? this.workspaceAvailableBytes;
466
+ const memoryAdmission = buildMemoryAdmissionDiagnostics({
467
+ sampledAt,
468
+ totalMemoryBytes,
469
+ rawAvailableMemoryBytes,
470
+ stabilizedAvailableMemoryBytes: sampledAvailableMemoryBytes,
471
+ controlPlaneMemoryBytes: process.memoryUsage().rss,
472
+ reserveMemoryBytes: hostReserveBytes,
473
+ committedMemoryBytes,
474
+ pendingCommitmentMemoryBytes: pendingReservationMemoryBytes,
475
+ });
476
+ const availableMemoryBytes = memoryAdmission.availableForAdmissionBytes;
477
+ const availableCpuMillis = Math.max(0, totalCpuMillis - cpuReserveMillis - activeReservationCpuMillis);
478
+ const availableWorkspaceBytes = Math.max(0, sampledWorkspaceBytes - workspaceReserveBytes - activeReservationWorkspaceBytes);
479
+ const slotAvailability = Math.max(0, hardMaxAttempts - this.capacityReservations.size);
480
+ // Capability snapshots advertise whether any supported attempt can fit.
481
+ // The queue/admission path still checks the exact project-derived request.
482
+ const minimumRequest = minimumSupportedHostResourceRequest();
483
+ const resourceAvailability = Math.min(resourceSlots(availableMemoryBytes, minimumRequest.memoryBytes), resourceSlots(availableCpuMillis, minimumRequest.cpuMillis), resourceSlots(availableWorkspaceBytes, minimumRequest.workspaceBytes));
484
+ const availableAttempts = Math.max(0, Math.min(slotAvailability, resourceAvailability));
485
+ const unavailableReason = slotAvailability <= 0
486
+ ? `Host attempt capacity is full (${this.capacityReservations.size}/${hardMaxAttempts}).`
487
+ : availableMemoryBytes < minimumRequest.memoryBytes
488
+ ? "Host memory is below the admission reserve."
489
+ : availableCpuMillis < minimumRequest.cpuMillis
490
+ ? "Host CPU capacity is below the admission reserve."
491
+ : availableWorkspaceBytes < minimumRequest.workspaceBytes
492
+ ? "Host workspace capacity is below the admission reserve."
493
+ : null;
494
+ return {
495
+ hardMaxAttempts,
496
+ effectiveMaxAttempts: this.capacityReservations.size + availableAttempts,
497
+ availableAttempts,
498
+ totalMemoryBytes,
499
+ availableMemoryBytes,
500
+ hostReserveBytes,
501
+ availableCpuMillis,
502
+ availableWorkspaceBytes,
503
+ activeReservationMemoryBytes,
504
+ memoryAdmission,
505
+ unavailableCode: unavailableReason ? "capacity_unavailable" : null,
506
+ unavailableReason,
507
+ };
508
+ }
509
+ async refreshWorkspaceCapacity() {
510
+ if (this.capacityResourceSample)
511
+ return;
512
+ try {
513
+ await fs.mkdir(this.stateRoot, { recursive: true });
514
+ const stats = await fs.statfs(this.stateRoot);
515
+ this.workspaceAvailableBytes = Math.max(0, stats.bavail * stats.bsize);
516
+ }
517
+ catch {
518
+ // Keep the last trustworthy sample. Memory/CPU and the hard ceiling still
519
+ // protect admission when the filesystem cannot be sampled temporarily.
520
+ }
521
+ }
522
+ releaseHostCapacity(dispatchAttemptId, fencingToken) {
523
+ const reservation = this.capacityReservations.get(dispatchAttemptId);
524
+ if (!reservation || reservation.owner.fencingToken !== fencingToken)
525
+ return;
526
+ this.capacityReservations.delete(dispatchAttemptId);
527
+ this.drainAdmissionWaiters();
528
+ }
529
+ drainCapacityWaiters() {
530
+ for (const waiter of this.capacityWaitersForScan()) {
531
+ if (!this.capacityWaiters.includes(waiter))
532
+ continue;
533
+ if (waiter.signal?.aborted) {
534
+ this.detachCapacityWaiter(waiter);
535
+ this.clearPendingRenewal(waiter.owner);
536
+ waiter.reject(cancellationError(waiter.signal));
537
+ continue;
538
+ }
539
+ if (admissionExpired(waiter.expiresAt)) {
540
+ this.detachCapacityWaiter(waiter);
541
+ this.clearPendingRenewal(waiter.owner);
542
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
543
+ continue;
544
+ }
545
+ const impossibleReason = this.hostCapacityImpossibleReason(waiter.resources);
546
+ if (impossibleReason) {
547
+ this.detachCapacityWaiter(waiter);
548
+ this.clearPendingRenewal(waiter.owner);
549
+ waiter.reject(new HostRuntimeCapacityRequestImpossibleError(impossibleReason));
550
+ continue;
551
+ }
552
+ if (!this.hostCapacityAvailable(waiter.resources))
553
+ continue;
554
+ this.detachCapacityWaiter(waiter);
555
+ this.capacityReservations.set(waiter.owner.dispatchAttemptId, {
556
+ owner: waiter.owner,
557
+ resources: waiter.resources,
558
+ state: "pending",
559
+ });
560
+ waiter.resolve();
561
+ }
562
+ }
563
+ capacityWaitersForScan() {
564
+ const head = this.capacityWaiters[0];
565
+ if (!head) {
566
+ this.capacityWaiterScanCursor = 0;
567
+ return [];
568
+ }
569
+ const scanCount = Math.min(hostCapacityWaiterScanLimit, this.capacityWaiters.length);
570
+ if (scanCount === this.capacityWaiters.length) {
571
+ this.capacityWaiterScanCursor = 0;
572
+ return this.capacityWaiters.slice();
573
+ }
574
+ // The head always gets the first opportunity, while a rotating bounded
575
+ // window prevents an unfit renewed head (or a very deep queue) from
576
+ // indefinitely hiding a later request that fits current capacity.
577
+ const laterCount = this.capacityWaiters.length - 1;
578
+ const laterScanCount = scanCount - 1;
579
+ const start = this.capacityWaiterScanCursor % laterCount;
580
+ const result = [head];
581
+ for (let offset = 0; offset < laterScanCount; offset += 1) {
582
+ result.push(this.capacityWaiters[1 + ((start + offset) % laterCount)]);
583
+ }
584
+ this.capacityWaiterScanCursor = (start + laterScanCount) % laterCount;
585
+ return result;
586
+ }
587
+ detachCapacityWaiter(waiter) {
588
+ const index = this.capacityWaiters.indexOf(waiter);
589
+ if (index < 0)
590
+ return false;
591
+ this.capacityWaiters.splice(index, 1);
592
+ clearAdmissionDeadline(waiter);
593
+ clearCapacityRecheck(waiter);
594
+ waiter.signal?.removeEventListener("abort", waiter.abort);
595
+ if (this.capacityWaiters.length === 0)
596
+ this.capacityWaiterScanCursor = 0;
597
+ return true;
598
+ }
599
+ async reserveSingletonKeys(keys, owner, expiresAt, signal, priority = "foreground") {
600
+ const owned = keys.every(key => sameSingletonOwner(this.singletonOwners.get(key), owner));
601
+ if (owned)
602
+ return keys;
603
+ const staleFence = [...this.singletonOwners.values()].find(existing => existing.dispatchAttemptId === owner.dispatchAttemptId
604
+ && existing.fencingToken !== owner.fencingToken);
605
+ if (staleFence) {
606
+ throw new Error("host_runtime_singleton_conflict: dispatch attempt already holds the singleton under a different fence.");
607
+ }
608
+ if (signal?.aborted)
609
+ throw cancellationError(signal);
610
+ throwIfAdmissionExpired(expiresAt);
611
+ if (this.singletonKeysAvailable(keys)) {
612
+ this.assignSingletonKeys(keys, owner);
613
+ return keys;
614
+ }
615
+ return new Promise((resolve, reject) => {
616
+ const waiter = {
617
+ owner,
618
+ keys,
619
+ priority,
620
+ resolve,
621
+ reject,
622
+ signal,
623
+ expiresAt,
624
+ deadlineTimer: null,
625
+ abort: () => {
626
+ const index = this.singletonWaiters.indexOf(waiter);
627
+ if (index >= 0)
628
+ this.singletonWaiters.splice(index, 1);
629
+ clearAdmissionDeadline(waiter);
630
+ this.clearPendingRenewal(owner);
631
+ reject(cancellationError(signal));
632
+ this.drainAdmissionWaiters();
633
+ },
634
+ expire: () => {
635
+ const index = this.singletonWaiters.indexOf(waiter);
636
+ if (index < 0)
637
+ return;
638
+ this.singletonWaiters.splice(index, 1);
639
+ clearAdmissionDeadline(waiter);
640
+ waiter.signal?.removeEventListener("abort", waiter.abort);
641
+ this.clearPendingRenewal(owner);
642
+ reject(new HostRuntimeAdmissionExpiredError());
643
+ this.drainAdmissionWaiters();
644
+ },
645
+ };
646
+ enqueueAdmissionWaiter(this.singletonWaiters, waiter);
647
+ signal?.addEventListener("abort", waiter.abort, { once: true });
648
+ waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
649
+ this.drainAdmissionWaiters();
650
+ });
651
+ }
652
+ async reserveParallelProject(key, owner, expiresAt, signal, priority = "foreground") {
653
+ if (this.parallelProjectOwned(key, owner))
654
+ return;
655
+ const staleFence = [...(this.parallelProjectOwners.get(key)?.values() ?? [])]
656
+ .find(existing => existing.dispatchAttemptId === owner.dispatchAttemptId
657
+ && existing.fencingToken !== owner.fencingToken);
658
+ if (staleFence) {
659
+ throw new Error("host_runtime_parallel_conflict: dispatch attempt already holds shared admission under a different fence.");
660
+ }
661
+ if (signal?.aborted)
662
+ throw cancellationError(signal);
663
+ throwIfAdmissionExpired(expiresAt);
664
+ if (this.parallelProjectAvailable(key, priority)) {
665
+ this.assignParallelProject(key, owner);
666
+ return;
667
+ }
668
+ await new Promise((resolve, reject) => {
669
+ const waiter = {
670
+ owner,
671
+ key,
672
+ priority,
673
+ resolve,
674
+ reject,
675
+ signal,
676
+ expiresAt,
677
+ deadlineTimer: null,
678
+ abort: () => {
679
+ const index = this.parallelProjectWaiters.indexOf(waiter);
680
+ if (index >= 0)
681
+ this.parallelProjectWaiters.splice(index, 1);
682
+ clearAdmissionDeadline(waiter);
683
+ this.clearPendingRenewal(owner);
684
+ reject(cancellationError(signal));
685
+ this.drainAdmissionWaiters();
686
+ },
687
+ expire: () => {
688
+ const index = this.parallelProjectWaiters.indexOf(waiter);
689
+ if (index < 0)
690
+ return;
691
+ this.parallelProjectWaiters.splice(index, 1);
692
+ clearAdmissionDeadline(waiter);
693
+ waiter.signal?.removeEventListener("abort", waiter.abort);
694
+ this.clearPendingRenewal(owner);
695
+ reject(new HostRuntimeAdmissionExpiredError());
696
+ this.drainAdmissionWaiters();
697
+ },
698
+ };
699
+ enqueueAdmissionWaiter(this.parallelProjectWaiters, waiter);
700
+ signal?.addEventListener("abort", waiter.abort, { once: true });
701
+ waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
702
+ this.drainAdmissionWaiters();
703
+ });
704
+ }
705
+ async upgradeParallelProjectToSingleton(keys, parallelProjectKey, owner, expiresAt, signal, priority = "foreground") {
706
+ if (!this.parallelProjectOwned(parallelProjectKey, owner)) {
707
+ throw new Error("host_runtime_parallel_unreserved: matching shared project admission is required before serialization.");
708
+ }
709
+ if (signal?.aborted)
710
+ throw cancellationError(signal);
711
+ throwIfAdmissionExpired(expiresAt);
712
+ return await new Promise((resolve, reject) => {
713
+ const waiter = {
714
+ owner,
715
+ keys,
716
+ priority,
717
+ resolve,
718
+ reject,
719
+ signal,
720
+ expiresAt,
721
+ deadlineTimer: null,
722
+ abort: () => {
723
+ const index = this.singletonWaiters.indexOf(waiter);
724
+ if (index >= 0)
725
+ this.singletonWaiters.splice(index, 1);
726
+ clearAdmissionDeadline(waiter);
727
+ this.clearPendingRenewal(owner);
728
+ reject(cancellationError(signal));
729
+ this.drainAdmissionWaiters();
730
+ },
731
+ expire: () => {
732
+ const index = this.singletonWaiters.indexOf(waiter);
733
+ if (index < 0)
734
+ return;
735
+ this.singletonWaiters.splice(index, 1);
736
+ clearAdmissionDeadline(waiter);
737
+ waiter.signal?.removeEventListener("abort", waiter.abort);
738
+ this.clearPendingRenewal(owner);
739
+ reject(new HostRuntimeAdmissionExpiredError());
740
+ this.drainAdmissionWaiters();
741
+ },
742
+ };
743
+ // Queue the exclusive claim before relinquishing the shared claim. This
744
+ // makes the promotion downgrade atomic from the broker's perspective and
745
+ // prevents a background readiness probe from jumping ahead in between.
746
+ enqueueAdmissionWaiter(this.singletonWaiters, waiter);
747
+ signal?.addEventListener("abort", waiter.abort, { once: true });
748
+ waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
749
+ this.releaseParallelProjectNoDrain(parallelProjectKey, owner);
750
+ this.drainAdmissionWaiters();
751
+ });
752
+ }
753
+ async start(dispatch, worktreePath, signal, onAdmissionCheckpoint) {
754
+ const sandbox = dispatch.sandbox;
755
+ if (!sandbox || sandbox.executionMode !== "host") {
756
+ throw new Error("host_runtime_lease_invalid: managed host sandbox context is required.");
757
+ }
758
+ const existing = this.active.get(sandbox.dispatchAttemptId);
759
+ if (existing) {
760
+ if (existing.lease.fencingToken !== dispatch.lease.fencingToken) {
761
+ throw new Error("host_runtime_lease_conflict: an active host lease has a different fence.");
762
+ }
763
+ return {
764
+ lease: existing.lease,
765
+ environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass),
766
+ runtimeContract: existing.runtimeContract,
767
+ executionClass: existing.executionClass,
768
+ };
769
+ }
770
+ const admission = this.admissions.get(sandbox.dispatchAttemptId);
771
+ const owner = { dispatchAttemptId: sandbox.dispatchAttemptId, fencingToken: dispatch.lease.fencingToken };
772
+ if (!admission || admission.fencingToken !== owner.fencingToken) {
773
+ throw new Error("host_runtime_singleton_unreserved: managed host admission is required before start.");
774
+ }
775
+ const attemptHex = uuidHex(sandbox.dispatchAttemptId, "dispatch attempt");
776
+ const normalizedWorktreePath = await resolveExistingDirectoryPath(worktreePath);
777
+ const attemptRoot = path.join(this.stateRoot, "host-attempts", attemptHex);
778
+ const temporaryPath = path.join(attemptRoot, "tmp");
779
+ const logPath = path.join(attemptRoot, "logs");
780
+ const cachePath = path.join(attemptRoot, "cache");
781
+ const browserProfilePath = path.join(attemptRoot, "browser-profile");
782
+ const testOutputPath = path.join(attemptRoot, "test-output");
783
+ const processSupervisorMetadataPath = path.join(logPath, "attempt-process-supervisor.json");
784
+ const processSupervisorId = `host-${attemptHex}`;
785
+ const renewedExpiry = this.pendingRenewals.get(sandbox.dispatchAttemptId);
786
+ const expiresAt = renewedExpiry?.fencingToken === dispatch.lease.fencingToken
787
+ ? renewedExpiry.expiresAt
788
+ : dispatch.lease.expiresAt;
789
+ let processSupervisor = null;
790
+ try {
791
+ let runtimeContract;
792
+ try {
793
+ runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
794
+ }
795
+ catch (error) {
796
+ if (admission.executionClass === "managed_runtime" && admission.provisionalPromotionFingerprint) {
797
+ await this.invalidatePromotion(dispatch.repo.id).catch(() => undefined);
798
+ }
799
+ throw error;
800
+ }
801
+ if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
802
+ throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
803
+ }
804
+ const runtimeContractFingerprint = hostRuntimeContractFingerprint(runtimeContract);
805
+ const promotion = admission.executionClass === "managed_runtime"
806
+ ? await this.promotionStore.load(dispatch.repo.id)
807
+ : null;
808
+ const promotionMatches = hostRuntimeParallelEligible(runtimeContract)
809
+ && promotion?.runtimeContractFingerprint === runtimeContractFingerprint;
810
+ if (admission.executionClass === "managed_runtime" && admission.keys.length === 0 && !promotionMatches) {
811
+ await this.invalidatePromotion(dispatch.repo.id);
812
+ const projectKeys = hostRuntimeSingletonKeys(dispatch);
813
+ const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
814
+ ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
815
+ : dispatch.lease.expiresAt;
816
+ await onAdmissionCheckpoint?.({
817
+ code: "host_runtime_serial_admission_waiting",
818
+ message: "The prepared runtime contract no longer matches the parallel-readiness proof. Waiting for foreground-priority serialized admission before launch.",
819
+ expiresAt,
820
+ });
821
+ const parallelProjectKey = admission.parallelProjectKey;
822
+ admission.parallelProjectKey = null;
823
+ admission.keys = parallelProjectKey
824
+ ? await this.upgradeParallelProjectToSingleton(projectKeys, parallelProjectKey, owner, expiresAt, signal, admission.priority)
825
+ : await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal, admission.priority);
826
+ while (admission.keys.length === 0) {
827
+ const promoted = this.knownPromotions.get(dispatch.repo.id);
828
+ if (!promoted) {
829
+ throw new Error("host_runtime_parallel_promotion_missing: shared admission requires matching promotion evidence.");
830
+ }
831
+ if (promoted.runtimeContractFingerprint !== runtimeContractFingerprint) {
832
+ this.releaseParallelProjectNoDrain(projectKeys[0], owner);
833
+ await this.invalidatePromotion(dispatch.repo.id);
834
+ admission.keys = await this.reserveSingletonKeys(projectKeys, owner, expiresAt, signal, admission.priority);
835
+ continue;
836
+ }
837
+ admission.parallelProjectKey = projectKeys[0] ?? null;
838
+ admission.provisionalPromotionFingerprint = promoted.runtimeContractFingerprint;
839
+ }
840
+ }
841
+ const declaredSingletonKeys = runtimeContract.contract.runtime.singletonResources
842
+ .map(hostRuntimeDeclaredSingletonKey);
843
+ const missingSingletonKeys = declaredSingletonKeys
844
+ .filter(key => !admission.keys.includes(key));
845
+ if (missingSingletonKeys.length > 0) {
846
+ const expiresAt = this.pendingRenewals.get(sandbox.dispatchAttemptId)?.fencingToken === owner.fencingToken
847
+ ? this.pendingRenewals.get(sandbox.dispatchAttemptId).expiresAt
848
+ : dispatch.lease.expiresAt;
849
+ const reservedSingletonKeys = await this.reserveSingletonKeys(missingSingletonKeys, owner, expiresAt, signal, admission.priority);
850
+ admission.keys = [...admission.keys, ...reservedSingletonKeys]
851
+ .sort((left, right) => left.localeCompare(right));
852
+ }
853
+ const singletonKeys = admission.keys;
854
+ if (!singletonKeys.every(key => sameSingletonOwner(this.singletonOwners.get(key), owner))) {
855
+ throw new Error("host_runtime_singleton_unreserved: managed host singleton ownership is required before start.");
856
+ }
857
+ if (admission.parallelProjectKey && !this.parallelProjectOwned(admission.parallelProjectKey, owner)) {
858
+ throw new Error("host_runtime_parallel_unreserved: matching shared project admission is required before start.");
859
+ }
860
+ await Promise.all([
861
+ ensurePrivateDirectory(temporaryPath),
862
+ ensurePrivateDirectory(logPath),
863
+ ensurePrivateDirectory(cachePath),
864
+ ensurePrivateDirectory(browserProfilePath),
865
+ ensurePrivateDirectory(testOutputPath),
866
+ ]);
867
+ await resetGeneratedOutputs(normalizedWorktreePath, testOutputPath);
868
+ const inputCommitSha = await resolveWorktreeCommitSha(normalizedWorktreePath, sandbox.inputCommitSha);
869
+ let lease = createRuntimeIsolationLease({
870
+ leaseId: sandbox.executionLeaseId,
871
+ dispatchAttemptId: sandbox.dispatchAttemptId,
872
+ executionLeaseId: sandbox.executionLeaseId,
873
+ fencingToken: dispatch.lease.fencingToken,
874
+ runnerId: dispatch.execution.runnerId ?? "",
875
+ runnerInstanceId: sandbox.runnerInstanceId,
876
+ worktreeKey: dispatch.lease.worktreeKey,
877
+ worktreePath: normalizedWorktreePath,
878
+ mode: "host",
879
+ expiresAt,
880
+ resources: {
881
+ memoryReservationBytes: 0,
882
+ cpuMillis: 0,
883
+ pids: 0,
884
+ ports: [],
885
+ paths: [
886
+ { path: normalizedWorktreePath, role: "worktree" },
887
+ { path: temporaryPath, role: "temporary" },
888
+ { path: logPath, role: "logs" },
889
+ { path: cachePath, role: "cache" },
890
+ { path: browserProfilePath, role: "browser_profile" },
891
+ { path: testOutputPath, role: "test_output" },
892
+ { path: processSupervisorMetadataPath, role: "process_supervisor_metadata" },
893
+ ],
894
+ processSupervisorId,
895
+ dockerResources: [],
896
+ singletonKeys,
897
+ },
898
+ });
899
+ await this.writeLedger(lease);
900
+ lease = transitionRuntimeIsolationLease(lease, "starting");
901
+ await this.writeLedger(lease);
902
+ lease = transitionRuntimeIsolationLease(lease, "active");
903
+ await this.writeLedger(lease);
904
+ processSupervisor = this.processSupervisors.register({
905
+ processSupervisorId,
906
+ dispatchAttemptId: lease.dispatchAttemptId,
907
+ executionLeaseId: lease.executionLeaseId,
908
+ fencingToken: lease.fencingToken,
909
+ logDirectory: logPath,
910
+ }, this.processRunner, { signal });
911
+ this.active.set(sandbox.dispatchAttemptId, {
912
+ lease,
913
+ repoId: dispatch.repo.id,
914
+ sessionId: dispatch.session.id,
915
+ attemptRoot,
916
+ runtimeContract,
917
+ runtimeContractFingerprint,
918
+ inputCommitSha,
919
+ executionClass: admission.executionClass,
920
+ parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract),
921
+ processSupervisor,
922
+ adapterCleanups: [],
923
+ pendingAdapterLaunches: new Map(),
924
+ releasing: false,
925
+ });
926
+ this.pendingRenewals.delete(sandbox.dispatchAttemptId);
927
+ return {
928
+ lease,
929
+ environment: hostRuntimeEnvironment(dispatch.session.id, lease, runtimeContract, admission.executionClass),
930
+ runtimeContract,
931
+ executionClass: admission.executionClass,
932
+ };
933
+ }
934
+ catch (error) {
935
+ this.pendingRenewals.delete(sandbox.dispatchAttemptId);
936
+ if (processSupervisor) {
937
+ await processSupervisor.stopAll(dispatch.lease.fencingToken, "Host runtime start rolled back.").catch(() => undefined);
938
+ this.processSupervisors.unregister(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
939
+ }
940
+ await fs.rm(attemptRoot, { recursive: true, force: true }).catch(() => undefined);
941
+ await fs.rm(this.ledgerPath(sandbox.dispatchAttemptId), { force: true }).catch(() => undefined);
942
+ this.releaseSingletonKeys(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
943
+ this.releaseParallelProjects(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
944
+ this.deleteAdmission(sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
945
+ throw error;
946
+ }
947
+ }
948
+ async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
949
+ try {
950
+ uuidHex(dispatchAttemptId, "dispatch attempt");
951
+ uuidHex(fencingToken, "fencing token");
952
+ }
953
+ catch {
954
+ return;
955
+ }
956
+ const active = this.active.get(dispatchAttemptId);
957
+ if (!active) {
958
+ if (Number.isFinite(Date.parse(expiresAt))) {
959
+ const pending = this.pendingRenewals.get(dispatchAttemptId);
960
+ if (!pending
961
+ || pending.fencingToken !== fencingToken
962
+ || Date.parse(expiresAt) > Date.parse(pending.expiresAt)) {
963
+ this.pendingRenewals.set(dispatchAttemptId, { fencingToken, expiresAt });
964
+ }
965
+ this.renewAdmissionWaiterDeadline(dispatchAttemptId, fencingToken, expiresAt);
966
+ }
967
+ return;
968
+ }
969
+ const renewed = renewRuntimeIsolationLease(active.lease, fencingToken, expiresAt);
970
+ if (!renewed)
971
+ return;
972
+ active.lease = renewed;
973
+ await this.writeLedger(renewed);
974
+ }
975
+ async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
976
+ const active = this.active.get(dispatchAttemptId);
977
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
978
+ throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
979
+ }
980
+ if (active.executionClass === "analysis_only") {
981
+ return {
982
+ lease: active.lease,
983
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
984
+ runtimeContract: active.runtimeContract,
985
+ executionClass: active.executionClass,
986
+ };
987
+ }
988
+ const configuredPorts = active.runtimeContract.contract.runtime.ports.filter((port) => port.launch !== null);
989
+ if (configuredPorts.length === 0) {
990
+ return {
991
+ lease: active.lease,
992
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
993
+ runtimeContract: active.runtimeContract,
994
+ executionClass: active.executionClass,
995
+ };
996
+ }
997
+ const owner = hostPortOwner(active.lease);
998
+ const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
999
+ if (!logDirectory)
1000
+ throw new Error("host_runtime_project_invalid: attempt log directory is unavailable.");
1001
+ const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector);
1002
+ for (const configuredPort of configuredPorts) {
1003
+ const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
1004
+ const launchEnvironment = {
1005
+ ...configuredPort.launch.environment,
1006
+ ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1007
+ };
1008
+ const prebuild = createAspNetRuntimePrebuildPlan({
1009
+ command: configuredPort.launch.command,
1010
+ args: configuredPort.launch.args,
1011
+ cwd: workingDirectory,
1012
+ worktreePath: active.lease.worktreePath,
1013
+ environment: launchEnvironment,
1014
+ inputCommitSha: active.inputCommitSha,
1015
+ runtimeContractFingerprint: active.runtimeContractFingerprint,
1016
+ });
1017
+ if (prebuild) {
1018
+ await onProjectCheckpoint?.({
1019
+ code: "host_runtime_build_started",
1020
+ message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1021
+ data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1022
+ });
1023
+ const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal), signal);
1024
+ await onProjectCheckpoint?.({
1025
+ code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1026
+ message: build.cacheHit
1027
+ ? `Reused the verified ASP.NET build for commit ${active.inputCommitSha.slice(0, 12)}.`
1028
+ : `ASP.NET runtime build completed for commit ${active.inputCommitSha.slice(0, 12)}; launching without another build.`,
1029
+ data: {
1030
+ input_commit_sha: active.inputCommitSha,
1031
+ build_fingerprint: build.fingerprint,
1032
+ receipt_path: build.receiptPath,
1033
+ },
1034
+ });
1035
+ }
1036
+ await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1037
+ command: configuredPort.launch.command,
1038
+ args: configuredPort.launch.args,
1039
+ cwd: workingDirectory,
1040
+ environment: launchEnvironment,
1041
+ }, launcher, signal);
1042
+ }
1043
+ const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1044
+ const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass);
1045
+ const playwright = active.runtimeContract.contract.runtime.playwright;
1046
+ if (!playwright) {
1047
+ return {
1048
+ lease: promotedLease,
1049
+ environment: runtimeEnvironment,
1050
+ runtimeContract: active.runtimeContract,
1051
+ executionClass: active.executionClass,
1052
+ };
1053
+ }
1054
+ const playwrightPort = promotedLease.resources.ports.find(port => port.name === playwright.baseUrlPort);
1055
+ const playwrightPortConfig = active.runtimeContract.contract.runtime.ports
1056
+ .find(port => port.name === playwright.baseUrlPort);
1057
+ if (!playwrightPort || !playwrightPortConfig?.baseUrlEnv) {
1058
+ throw new Error("host_runtime_playwright_unavailable: the configured verified base URL is unavailable.");
1059
+ }
1060
+ if (playwrightPort.hostIp !== "127.0.0.1") {
1061
+ throw new Error("host_runtime_playwright_unavailable: Playwright requires an IPv4 loopback listener.");
1062
+ }
1063
+ const baseUrl = hostPortEnvironment(playwrightPortConfig, playwrightPort.hostIp, playwrightPort.hostPort)[playwrightPortConfig.baseUrlEnv];
1064
+ if (!baseUrl)
1065
+ throw new Error("host_runtime_playwright_unavailable: the configured base URL could not be rendered.");
1066
+ const pathFor = (role) => promotedLease.resources.paths.find(entry => entry.role === role)?.path ?? "";
1067
+ const preparedPlaywright = await this.playwrightAdapter.prepare(playwright, {
1068
+ worktreePath: promotedLease.worktreePath,
1069
+ temporaryDirectory: pathFor("temporary"),
1070
+ testOutputDirectory: pathFor("test_output"),
1071
+ browserProfileDirectory: pathFor("browser_profile"),
1072
+ baseUrl,
1073
+ ownershipToken: uuidHex(promotedLease.dispatchAttemptId, "dispatch attempt"),
1074
+ });
1075
+ return {
1076
+ lease: promotedLease,
1077
+ environment: { ...runtimeEnvironment, ...preparedPlaywright.environment },
1078
+ runtimeContract: active.runtimeContract,
1079
+ executionClass: active.executionClass,
1080
+ };
1081
+ }
1082
+ providerProcessRunner(dispatchAttemptId, fencingToken) {
1083
+ const active = this.active.get(dispatchAttemptId);
1084
+ if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
1085
+ return null;
1086
+ return new AttemptSupervisedProviderProcessRunner(active.processSupervisor, hostPortOwner(active.lease), this.listenerInspector, active.executionClass === "analysis_only", () => this.markCapacityReservationRunning(dispatchAttemptId, fencingToken));
1087
+ }
1088
+ markCapacityReservationRunning(dispatchAttemptId, fencingToken) {
1089
+ const reservation = this.capacityReservations.get(dispatchAttemptId);
1090
+ if (reservation?.owner.fencingToken === fencingToken)
1091
+ reservation.state = "running";
1092
+ }
1093
+ providerMemoryTelemetry(dispatchAttemptId, fencingToken) {
1094
+ const active = this.active.get(dispatchAttemptId);
1095
+ if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
1096
+ return null;
1097
+ return active.processSupervisor.providerMemoryTelemetry();
1098
+ }
1099
+ async promoteVerifiedRuntime(active, runtimeLease) {
1100
+ if (!active.parallelPromotionEligible)
1101
+ return runtimeLease;
1102
+ const verifiedPortNames = runtimeLease.resources.ports.map(port => port.name).sort((left, right) => left.localeCompare(right));
1103
+ const requiredPortNames = configuredLaunchPortNames(active.runtimeContract);
1104
+ if (requiredPortNames.length !== verifiedPortNames.length
1105
+ || requiredPortNames.some((name, index) => name !== verifiedPortNames[index])) {
1106
+ return runtimeLease;
1107
+ }
1108
+ const projectKey = projectHostRuntimeSingletonKey(active.repoId);
1109
+ const promotedLease = withRuntimeIsolationResources(runtimeLease, {
1110
+ ...runtimeLease.resources,
1111
+ singletonKeys: runtimeLease.resources.singletonKeys.filter(key => key !== projectKey),
1112
+ });
1113
+ await this.writeLedger(promotedLease);
1114
+ active.lease = promotedLease;
1115
+ try {
1116
+ const promotion = await this.promotionStore.observe(active.repoId, active.runtimeContract, runtimeLease.dispatchAttemptId, verifiedPortNames);
1117
+ this.knownPromotions.set(promotion.repoId, promotion);
1118
+ this.convertSingletonToParallelProject(projectKey, {
1119
+ dispatchAttemptId: runtimeLease.dispatchAttemptId,
1120
+ fencingToken: runtimeLease.fencingToken,
1121
+ }, promotion);
1122
+ const admission = this.admissions.get(runtimeLease.dispatchAttemptId);
1123
+ if (admission?.fencingToken === runtimeLease.fencingToken) {
1124
+ this.admissions.set(runtimeLease.dispatchAttemptId, {
1125
+ ...admission,
1126
+ keys: promotedLease.resources.singletonKeys,
1127
+ provisionalPromotionFingerprint: promotion.runtimeContractFingerprint,
1128
+ parallelProjectKey: projectKey,
1129
+ });
1130
+ }
1131
+ return promotedLease;
1132
+ }
1133
+ catch {
1134
+ await this.invalidatePromotion(active.repoId).catch(() => undefined);
1135
+ active.lease = runtimeLease;
1136
+ await this.writeLedger(runtimeLease);
1137
+ return runtimeLease;
1138
+ }
1139
+ }
1140
+ async launchNodeRuntime(dispatchAttemptId, fencingToken, portName, command, launcher, signal) {
1141
+ const active = this.active.get(dispatchAttemptId);
1142
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1143
+ throw new Error("host_runtime_adapter_unavailable: an active matching host runtime lease is required.");
1144
+ }
1145
+ const portConfig = active.runtimeContract.contract.runtime.ports.find(port => port.name === portName);
1146
+ if (!portConfig)
1147
+ throw new Error(`host_runtime_adapter_invalid: configured port '${portName}' was not found.`);
1148
+ if (active.lease.resources.ports.some(port => port.name === portName) || active.pendingAdapterLaunches.has(portName)) {
1149
+ throw new Error(`host_runtime_adapter_conflict: configured port '${portName}' is already active.`);
1150
+ }
1151
+ const controller = linkedAbortController(signal);
1152
+ let retainedByActiveRuntime = false;
1153
+ const operation = (async () => {
1154
+ const owner = hostPortOwner(active.lease);
1155
+ const launched = await this.nodeAdapter.launch(owner, portConfig, command, launcher, controller.signal);
1156
+ let cleaned = false;
1157
+ const cleanup = async () => {
1158
+ if (cleaned)
1159
+ return;
1160
+ await launcher.stop(launched.value);
1161
+ await this.portBroker.release(launched.reservation.reservationId, owner);
1162
+ cleaned = true;
1163
+ unlinkAbortController(controller, signal);
1164
+ };
1165
+ active.adapterCleanups.push(cleanup);
1166
+ try {
1167
+ if (active.releasing)
1168
+ throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
1169
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1170
+ ...active.lease.resources,
1171
+ ports: [...active.lease.resources.ports, {
1172
+ name: launched.reservation.name,
1173
+ protocol: launched.reservation.protocol,
1174
+ hostIp: launched.reservation.hostIp,
1175
+ hostPort: launched.reservation.hostPort,
1176
+ targetPort: launched.reservation.targetPort,
1177
+ }],
1178
+ });
1179
+ await this.writeLedger(runtimeLease);
1180
+ active.lease = runtimeLease;
1181
+ retainedByActiveRuntime = true;
1182
+ return { ...launched, runtimeLease };
1183
+ }
1184
+ catch (error) {
1185
+ try {
1186
+ await cleanup();
1187
+ removeCleanup(active.adapterCleanups, cleanup);
1188
+ }
1189
+ catch {
1190
+ // Preserve the cleanup and broker claim for the fenced release retry.
1191
+ }
1192
+ throw error;
1193
+ }
1194
+ })();
1195
+ active.pendingAdapterLaunches.set(portName, { controller, promise: operation });
1196
+ try {
1197
+ return await operation;
1198
+ }
1199
+ finally {
1200
+ active.pendingAdapterLaunches.delete(portName);
1201
+ if (!retainedByActiveRuntime)
1202
+ unlinkAbortController(controller, signal);
1203
+ }
1204
+ }
1205
+ async release(dispatchAttemptId, fencingToken) {
1206
+ const active = this.active.get(dispatchAttemptId);
1207
+ this.pendingRenewals.delete(dispatchAttemptId);
1208
+ if (!active) {
1209
+ this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1210
+ this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1211
+ this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1212
+ this.deleteAdmission(dispatchAttemptId, fencingToken);
1213
+ return null;
1214
+ }
1215
+ if (active.lease.fencingToken !== fencingToken)
1216
+ return null;
1217
+ active.releasing = true;
1218
+ for (const pending of active.pendingAdapterLaunches.values()) {
1219
+ pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1220
+ }
1221
+ await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1222
+ let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1223
+ active.lease = releasing;
1224
+ await this.writeLedger(releasing);
1225
+ try {
1226
+ await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1227
+ await releaseAdapterResources(active.adapterCleanups);
1228
+ await fs.rm(active.attemptRoot, { recursive: true, force: true });
1229
+ releasing = transitionRuntimeIsolationLease(releasing, "released");
1230
+ active.lease = releasing;
1231
+ await this.writeLedger(releasing);
1232
+ await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1233
+ this.active.delete(dispatchAttemptId);
1234
+ this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1235
+ this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1236
+ this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1237
+ this.deleteAdmission(dispatchAttemptId, fencingToken);
1238
+ return releasing;
1239
+ }
1240
+ catch (error) {
1241
+ const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
1242
+ active.lease = degraded;
1243
+ await this.writeLedger(degraded).catch(() => undefined);
1244
+ throw new HostRuntimeLeaseCleanupError(degraded, error);
1245
+ }
1246
+ }
1247
+ async readLedgers() {
1248
+ const root = path.join(this.stateRoot, "runtime-ledger", "host");
1249
+ const entries = await fs.readdir(root, { withFileTypes: true }).catch(error => {
1250
+ if (error.code === "ENOENT")
1251
+ return [];
1252
+ throw error;
1253
+ });
1254
+ const ledgers = [];
1255
+ for (const entry of entries) {
1256
+ if (!entry.isFile() || !/^[0-9a-f]{32}\.json$/u.test(entry.name))
1257
+ continue;
1258
+ try {
1259
+ const value = JSON.parse(await fs.readFile(path.join(root, entry.name), "utf8"));
1260
+ if (!validHostRuntimeLedger(value))
1261
+ continue;
1262
+ const expectedName = `${uuidHex(value.runtimeLease.dispatchAttemptId, "dispatch attempt")}.json`;
1263
+ if (entry.name !== expectedName)
1264
+ continue;
1265
+ ledgers.push(value);
1266
+ }
1267
+ catch {
1268
+ // An invalid ledger has no trustworthy ownership identity and is never reaped.
1269
+ }
1270
+ }
1271
+ return ledgers;
1272
+ }
1273
+ async recoverPersistedProcesses(lease, attemptRoot) {
1274
+ const logsRoot = path.join(attemptRoot, "logs");
1275
+ const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
1276
+ if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
1277
+ throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
1278
+ }
1279
+ const entries = await fs.readdir(logsRoot, { withFileTypes: true }).catch(error => {
1280
+ if (error.code === "ENOENT")
1281
+ return [];
1282
+ throw error;
1283
+ });
1284
+ const outcomes = [];
1285
+ for (const entry of entries) {
1286
+ if (!entry.isFile() || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1287
+ continue;
1288
+ const metadataPath = path.join(logsRoot, entry.name);
1289
+ const value = JSON.parse(await fs.readFile(metadataPath, "utf8"));
1290
+ if (!validHostProcessSupervisorMetadata(value, lease)) {
1291
+ throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1292
+ }
1293
+ outcomes.push(await this.processRecovery.recover(value));
1294
+ }
1295
+ return outcomes;
1296
+ }
1297
+ async markLedgerDegraded(ledger) {
1298
+ const lease = ledger.runtimeLease;
1299
+ if (lease.state === "released")
1300
+ return;
1301
+ const degraded = transitionHostLeaseForCleanup(lease, "degraded");
1302
+ const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
1303
+ this.rememberDegraded(degraded, repoId);
1304
+ await this.writeLedger(degraded, repoId ?? undefined).catch(() => undefined);
1305
+ }
1306
+ rememberDegraded(lease, repoId) {
1307
+ this.degraded.set(lease.dispatchAttemptId, { lease, repoId });
1308
+ if (!repoId)
1309
+ return;
1310
+ const owner = { dispatchAttemptId: lease.dispatchAttemptId, fencingToken: lease.fencingToken };
1311
+ const projectKey = projectHostRuntimeSingletonKey(repoId);
1312
+ const existing = this.singletonOwners.get(projectKey);
1313
+ if (!existing || sameSingletonOwner(existing, owner))
1314
+ this.singletonOwners.set(projectKey, owner);
1315
+ }
1316
+ forgetDegraded(dispatchAttemptId, fencingToken) {
1317
+ if (this.degraded.get(dispatchAttemptId)?.lease.fencingToken !== fencingToken)
1318
+ return;
1319
+ this.degraded.delete(dispatchAttemptId);
1320
+ this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1321
+ this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1322
+ }
1323
+ attemptRoot(dispatchAttemptId) {
1324
+ return path.join(this.stateRoot, "host-attempts", uuidHex(dispatchAttemptId, "dispatch attempt"));
1325
+ }
1326
+ async writeLedger(runtimeLease, explicitRepoId) {
1327
+ const root = path.join(this.stateRoot, "runtime-ledger", "host");
1328
+ await ensurePrivateDirectory(root);
1329
+ const target = this.ledgerPath(runtimeLease.dispatchAttemptId);
1330
+ const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
1331
+ try {
1332
+ const handle = await fs.open(temporary, "wx", 0o600);
1333
+ try {
1334
+ const repoId = explicitRepoId
1335
+ ?? this.active.get(runtimeLease.dispatchAttemptId)?.repoId
1336
+ ?? this.admissions.get(runtimeLease.dispatchAttemptId)?.repoId
1337
+ ?? this.degraded.get(runtimeLease.dispatchAttemptId)?.repoId
1338
+ ?? undefined;
1339
+ const ledger = {
1340
+ schemaVersion: 1,
1341
+ ...(repoId ? { repoId } : {}),
1342
+ runtimeLease,
1343
+ };
1344
+ await handle.writeFile(`${JSON.stringify(ledger)}\n`);
1345
+ await handle.sync();
1346
+ }
1347
+ finally {
1348
+ await handle.close();
1349
+ }
1350
+ await fs.rename(temporary, target);
1351
+ }
1352
+ catch (error) {
1353
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
1354
+ throw error;
1355
+ }
1356
+ }
1357
+ ledgerPath(dispatchAttemptId) {
1358
+ const attemptHex = uuidHex(dispatchAttemptId, "dispatch attempt");
1359
+ return path.join(this.stateRoot, "runtime-ledger", "host", `${attemptHex}.json`);
1360
+ }
1361
+ singletonKeysAvailable(keys) {
1362
+ return keys.every(key => !this.singletonOwners.has(key) && !this.parallelProjectOwners.has(key));
1363
+ }
1364
+ assignSingletonKeys(keys, owner) {
1365
+ for (const key of keys)
1366
+ this.singletonOwners.set(key, owner);
1367
+ }
1368
+ releaseSingletonKeys(dispatchAttemptId, fencingToken) {
1369
+ for (const [key, owner] of this.singletonOwners) {
1370
+ if (owner.dispatchAttemptId === dispatchAttemptId && owner.fencingToken === fencingToken) {
1371
+ this.singletonOwners.delete(key);
1372
+ }
1373
+ }
1374
+ this.drainAdmissionWaiters();
1375
+ }
1376
+ convertSingletonToParallelProject(key, owner, promotion) {
1377
+ if (!sameSingletonOwner(this.singletonOwners.get(key), owner)) {
1378
+ throw new Error("host_runtime_parallel_promotion_stale: matching exclusive project admission is required.");
1379
+ }
1380
+ this.assignParallelProject(key, owner);
1381
+ this.singletonOwners.delete(key);
1382
+ for (let index = 0; index < this.singletonWaiters.length;) {
1383
+ const waiter = this.singletonWaiters[index];
1384
+ if (waiter.priority !== "foreground" || waiter.keys.length !== 1 || waiter.keys[0] !== key) {
1385
+ index += 1;
1386
+ continue;
1387
+ }
1388
+ this.singletonWaiters.splice(index, 1);
1389
+ clearAdmissionDeadline(waiter);
1390
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1391
+ this.assignParallelProject(key, waiter.owner);
1392
+ this.knownPromotions.set(promotion.repoId, promotion);
1393
+ waiter.resolve([]);
1394
+ }
1395
+ this.drainAdmissionWaiters();
1396
+ }
1397
+ parallelProjectOwned(key, owner) {
1398
+ return sameSingletonOwner(this.parallelProjectOwners.get(key)?.get(owner.dispatchAttemptId), owner);
1399
+ }
1400
+ parallelProjectAvailable(key, priority = "foreground") {
1401
+ return !this.singletonOwners.has(key)
1402
+ && !this.singletonWaiters.some(waiter => waiter.keys.includes(key)
1403
+ && (priority === "background" || waiter.priority === "foreground"));
1404
+ }
1405
+ assignParallelProject(key, owner) {
1406
+ const owners = this.parallelProjectOwners.get(key) ?? new Map();
1407
+ owners.set(owner.dispatchAttemptId, owner);
1408
+ this.parallelProjectOwners.set(key, owners);
1409
+ }
1410
+ releaseParallelProjectNoDrain(key, owner) {
1411
+ const owners = this.parallelProjectOwners.get(key);
1412
+ if (!sameSingletonOwner(owners?.get(owner.dispatchAttemptId), owner))
1413
+ return;
1414
+ owners.delete(owner.dispatchAttemptId);
1415
+ if (owners.size === 0)
1416
+ this.parallelProjectOwners.delete(key);
1417
+ }
1418
+ releaseParallelProjects(dispatchAttemptId, fencingToken) {
1419
+ const owner = { dispatchAttemptId, fencingToken };
1420
+ for (const key of [...this.parallelProjectOwners.keys()]) {
1421
+ this.releaseParallelProjectNoDrain(key, owner);
1422
+ }
1423
+ this.drainAdmissionWaiters();
1424
+ }
1425
+ deleteAdmission(dispatchAttemptId, fencingToken) {
1426
+ if (this.admissions.get(dispatchAttemptId)?.fencingToken === fencingToken) {
1427
+ this.admissions.delete(dispatchAttemptId);
1428
+ }
1429
+ this.releaseHostCapacity(dispatchAttemptId, fencingToken);
1430
+ }
1431
+ renewAdmissionWaiterDeadline(dispatchAttemptId, fencingToken, expiresAt) {
1432
+ for (const waiter of [
1433
+ ...this.singletonWaiters,
1434
+ ...this.parallelProjectWaiters,
1435
+ ...this.capacityWaiters,
1436
+ ...this.backgroundAdmissionWaiters,
1437
+ ]) {
1438
+ if (!sameSingletonOwner(waiter.owner, { dispatchAttemptId, fencingToken })
1439
+ || Date.parse(expiresAt) <= Date.parse(waiter.expiresAt))
1440
+ continue;
1441
+ waiter.expiresAt = expiresAt;
1442
+ clearAdmissionDeadline(waiter);
1443
+ waiter.deadlineTimer = scheduleAdmissionDeadline(waiter.expiresAt, waiter.expire);
1444
+ }
1445
+ }
1446
+ clearPendingRenewal(owner) {
1447
+ if (this.pendingRenewals.get(owner.dispatchAttemptId)?.fencingToken === owner.fencingToken) {
1448
+ this.pendingRenewals.delete(owner.dispatchAttemptId);
1449
+ }
1450
+ }
1451
+ cancelAdmissionWaiters(dispatchAttemptId, fencingToken, reason) {
1452
+ const owner = { dispatchAttemptId, fencingToken };
1453
+ for (const waiters of [
1454
+ this.singletonWaiters,
1455
+ this.parallelProjectWaiters,
1456
+ this.capacityWaiters,
1457
+ this.backgroundAdmissionWaiters,
1458
+ ]) {
1459
+ for (let index = waiters.length - 1; index >= 0; index -= 1) {
1460
+ const waiter = waiters[index];
1461
+ if (!sameSingletonOwner(waiter.owner, owner))
1462
+ continue;
1463
+ waiters.splice(index, 1);
1464
+ clearAdmissionDeadline(waiter);
1465
+ if ("capacityRecheckTimer" in waiter)
1466
+ clearCapacityRecheck(waiter);
1467
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1468
+ waiter.reject(new Error(`host_runtime_admission_cancelled: ${reason}`));
1469
+ }
1470
+ }
1471
+ this.drainAdmissionWaiters();
1472
+ }
1473
+ drainSingletonWaiters() {
1474
+ for (let index = 0; index < this.singletonWaiters.length;) {
1475
+ const waiter = this.singletonWaiters[index];
1476
+ if (waiter.signal?.aborted) {
1477
+ this.singletonWaiters.splice(index, 1);
1478
+ clearAdmissionDeadline(waiter);
1479
+ waiter.signal.removeEventListener("abort", waiter.abort);
1480
+ this.clearPendingRenewal(waiter.owner);
1481
+ waiter.reject(cancellationError(waiter.signal));
1482
+ continue;
1483
+ }
1484
+ if (admissionExpired(waiter.expiresAt)) {
1485
+ this.singletonWaiters.splice(index, 1);
1486
+ clearAdmissionDeadline(waiter);
1487
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1488
+ this.clearPendingRenewal(waiter.owner);
1489
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
1490
+ continue;
1491
+ }
1492
+ if (!this.singletonKeysAvailable(waiter.keys)) {
1493
+ index += 1;
1494
+ continue;
1495
+ }
1496
+ this.singletonWaiters.splice(index, 1);
1497
+ clearAdmissionDeadline(waiter);
1498
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1499
+ this.assignSingletonKeys(waiter.keys, waiter.owner);
1500
+ waiter.resolve(waiter.keys);
1501
+ }
1502
+ }
1503
+ drainParallelProjectWaiters() {
1504
+ for (let index = 0; index < this.parallelProjectWaiters.length;) {
1505
+ const waiter = this.parallelProjectWaiters[index];
1506
+ if (waiter.signal?.aborted) {
1507
+ this.parallelProjectWaiters.splice(index, 1);
1508
+ clearAdmissionDeadline(waiter);
1509
+ waiter.signal.removeEventListener("abort", waiter.abort);
1510
+ this.clearPendingRenewal(waiter.owner);
1511
+ waiter.reject(cancellationError(waiter.signal));
1512
+ continue;
1513
+ }
1514
+ if (admissionExpired(waiter.expiresAt)) {
1515
+ this.parallelProjectWaiters.splice(index, 1);
1516
+ clearAdmissionDeadline(waiter);
1517
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1518
+ this.clearPendingRenewal(waiter.owner);
1519
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
1520
+ continue;
1521
+ }
1522
+ if (!this.parallelProjectAvailable(waiter.key, waiter.priority)) {
1523
+ index += 1;
1524
+ continue;
1525
+ }
1526
+ this.parallelProjectWaiters.splice(index, 1);
1527
+ clearAdmissionDeadline(waiter);
1528
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1529
+ this.assignParallelProject(waiter.key, waiter.owner);
1530
+ waiter.resolve();
1531
+ }
1532
+ }
1533
+ drainBackgroundAdmissionWaiters() {
1534
+ if (this.hasForegroundDemand())
1535
+ return;
1536
+ for (let index = 0; index < this.backgroundAdmissionWaiters.length;) {
1537
+ const waiter = this.backgroundAdmissionWaiters[index];
1538
+ if (waiter.signal?.aborted) {
1539
+ this.backgroundAdmissionWaiters.splice(index, 1);
1540
+ clearAdmissionDeadline(waiter);
1541
+ clearCapacityRecheck(waiter);
1542
+ waiter.signal.removeEventListener("abort", waiter.abort);
1543
+ this.clearPendingRenewal(waiter.owner);
1544
+ waiter.reject(cancellationError(waiter.signal));
1545
+ continue;
1546
+ }
1547
+ if (admissionExpired(waiter.expiresAt)) {
1548
+ this.backgroundAdmissionWaiters.splice(index, 1);
1549
+ clearAdmissionDeadline(waiter);
1550
+ clearCapacityRecheck(waiter);
1551
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1552
+ this.clearPendingRenewal(waiter.owner);
1553
+ waiter.reject(new HostRuntimeAdmissionExpiredError());
1554
+ continue;
1555
+ }
1556
+ if (!this.singletonKeysAvailable(waiter.keys) || !this.hostCapacityAvailable(waiter.resources)) {
1557
+ index += 1;
1558
+ continue;
1559
+ }
1560
+ this.backgroundAdmissionWaiters.splice(index, 1);
1561
+ clearAdmissionDeadline(waiter);
1562
+ clearCapacityRecheck(waiter);
1563
+ waiter.signal?.removeEventListener("abort", waiter.abort);
1564
+ this.assignSingletonKeys(waiter.keys, waiter.owner);
1565
+ this.capacityReservations.set(waiter.owner.dispatchAttemptId, {
1566
+ owner: waiter.owner,
1567
+ resources: waiter.resources,
1568
+ state: "pending",
1569
+ });
1570
+ waiter.resolve(waiter.keys);
1571
+ }
1572
+ }
1573
+ async refreshKnownPromotions() {
1574
+ const promotions = await this.promotionStore.list();
1575
+ this.knownPromotions.clear();
1576
+ for (const promotion of promotions)
1577
+ this.knownPromotions.set(promotion.repoId, promotion);
1578
+ }
1579
+ async invalidatePromotion(repoId) {
1580
+ await this.promotionStore.invalidate(repoId);
1581
+ this.knownPromotions.delete(repoId.trim().toLowerCase());
1582
+ }
1583
+ drainAdmissionWaiters() {
1584
+ this.drainSingletonWaiters();
1585
+ this.drainParallelProjectWaiters();
1586
+ this.drainCapacityWaiters();
1587
+ this.drainBackgroundAdmissionWaiters();
1588
+ }
1589
+ }
1590
+ class AttemptSupervisedProviderProcessRunner {
1591
+ supervisor;
1592
+ owner;
1593
+ listenerInspector;
1594
+ enforceNoListeners;
1595
+ onProcessTreeStarted;
1596
+ constructor(supervisor, owner, listenerInspector, enforceNoListeners, onProcessTreeStarted) {
1597
+ this.supervisor = supervisor;
1598
+ this.owner = owner;
1599
+ this.listenerInspector = listenerInspector;
1600
+ this.enforceNoListeners = enforceNoListeners;
1601
+ this.onProcessTreeStarted = onProcessTreeStarted;
1602
+ }
1603
+ async run(request, handlers = {}, signal) {
1604
+ const baselineListeners = this.enforceNoListeners
1605
+ ? new Set(await this.listenerInspector.inspectLoopbackListeners())
1606
+ : new Set();
1607
+ const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
1608
+ this.onProcessTreeStarted();
1609
+ if (!this.enforceNoListeners)
1610
+ return await child.result;
1611
+ let settled = false;
1612
+ let inspectionFailure;
1613
+ const monitor = (async () => {
1614
+ while (!settled) {
1615
+ try {
1616
+ const ports = (await this.listenerInspector.inspectOwnedLoopbackListeners(child, this.owner))
1617
+ .filter(port => !baselineListeners.has(port));
1618
+ if (ports.length > 0) {
1619
+ inspectionFailure = new Error(`host_analysis_listener_violation: analysis-only provider opened undeclared loopback listener(s): ${ports.join(", ")}.`);
1620
+ await child.stop(this.owner.fencingToken).catch(() => undefined);
1621
+ return;
1622
+ }
1623
+ }
1624
+ catch (error) {
1625
+ inspectionFailure = error;
1626
+ await child.stop(this.owner.fencingToken).catch(() => undefined);
1627
+ return;
1628
+ }
1629
+ await waitForAnalysisInspection(250, signal).catch(error => {
1630
+ if (!settled && !signal?.aborted)
1631
+ inspectionFailure = error;
1632
+ });
1633
+ }
1634
+ })();
1635
+ try {
1636
+ const result = await child.result;
1637
+ settled = true;
1638
+ await monitor;
1639
+ if (inspectionFailure)
1640
+ throw inspectionFailure;
1641
+ return result;
1642
+ }
1643
+ catch (error) {
1644
+ settled = true;
1645
+ await monitor.catch(() => undefined);
1646
+ if (inspectionFailure)
1647
+ throw inspectionFailure;
1648
+ throw error;
1649
+ }
1650
+ }
1651
+ }
1652
+ function waitForAnalysisInspection(milliseconds, signal) {
1653
+ if (signal?.aborted)
1654
+ return Promise.reject(cancellationError(signal));
1655
+ return new Promise((resolve, reject) => {
1656
+ const timer = setTimeout(() => {
1657
+ signal?.removeEventListener("abort", abort);
1658
+ resolve();
1659
+ }, milliseconds);
1660
+ const abort = () => {
1661
+ clearTimeout(timer);
1662
+ reject(cancellationError(signal));
1663
+ };
1664
+ signal?.addEventListener("abort", abort, { once: true });
1665
+ });
1666
+ }
1667
+ export class HostRuntimeLeaseCleanupError extends Error {
1668
+ lease;
1669
+ constructor(lease, cause) {
1670
+ super(`host_runtime_cleanup_degraded: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
1671
+ this.lease = lease;
1672
+ this.name = "HostRuntimeLeaseCleanupError";
1673
+ }
1674
+ }
1675
+ export class HostRuntimeAdmissionExpiredError extends Error {
1676
+ constructor() {
1677
+ super("host_runtime_admission_expired: dispatch lease expired while waiting for managed host admission.");
1678
+ this.name = "HostRuntimeAdmissionExpiredError";
1679
+ }
1680
+ }
1681
+ export class HostRuntimeCapacityRequestImpossibleError extends Error {
1682
+ constructor(reason) {
1683
+ super(`host_runtime_capacity_request_impossible: ${reason}`);
1684
+ this.name = "HostRuntimeCapacityRequestImpossibleError";
1685
+ }
1686
+ }
1687
+ export function hostRuntimeEventResources(lease, runtimeContract, executionClass = "managed_runtime") {
1688
+ const requestedHostConcurrency = runtimeContract?.contract.runtime.hostConcurrency ?? "serial";
1689
+ const configuredLaunches = runtimeContract?.contract.runtime.ports.filter(port => port.launch !== null) ?? [];
1690
+ const verifiedLaunches = configuredLaunches.filter(configured => lease.resources.ports.some(port => port.name === configured.name));
1691
+ const effectiveConcurrency = effectiveHostConcurrency(lease, runtimeContract, executionClass);
1692
+ return {
1693
+ agentContainer: null,
1694
+ sidecarContainers: [],
1695
+ networks: [],
1696
+ volumes: [],
1697
+ publishedPorts: lease.resources.ports,
1698
+ hostConcurrency: effectiveConcurrency,
1699
+ requestedHostConcurrency,
1700
+ hostParallelPromotion: effectiveConcurrency === "host_parallel_safe"
1701
+ ? executionClass === "analysis_only" ? "analysis_profile_enforced" : "observed_probe_passed"
1702
+ : requestedHostConcurrency !== "parallel"
1703
+ ? "not_requested"
1704
+ : configuredLaunches.length > 0 && verifiedLaunches.length === configuredLaunches.length
1705
+ ? "pending_live_parallel_proof"
1706
+ : "pending_adapter_probe",
1707
+ verifiedRuntimePorts: verifiedLaunches.map(port => port.name),
1708
+ runtimeContractSource: runtimeContract?.source ?? "default",
1709
+ executionClass,
1710
+ requestedPorts: runtimeContract?.contract.runtime.ports.map(port => port.name) ?? [],
1711
+ singletonKeys: lease.resources.singletonKeys,
1712
+ processSupervisorId: lease.resources.processSupervisorId,
1713
+ runtimeLease: lease,
1714
+ };
1715
+ }
1716
+ export function hostRuntimeSingletonKeys(dispatch) {
1717
+ return [projectHostRuntimeSingletonKey(dispatch.repo.id)];
1718
+ }
1719
+ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass) {
1720
+ const pathFor = (role) => lease.resources.paths.find(entry => entry.role === role)?.path ?? "";
1721
+ const environment = {
1722
+ FORGE_SESSION_ID: sessionId,
1723
+ FORGE_RUNTIME_MODE: "host",
1724
+ FORGE_RESOURCE_LEASE_ID: lease.leaseId,
1725
+ FORGE_DISPATCH_ATTEMPT_ID: lease.dispatchAttemptId,
1726
+ FORGE_E2E_OWNERSHIP_MODE: "attempt",
1727
+ FORGE_E2E_OWNERSHIP_TOKEN: uuidHex(lease.dispatchAttemptId, "dispatch attempt"),
1728
+ FORGE_EXECUTION_LEASE_ID: lease.executionLeaseId,
1729
+ FORGE_FENCING_TOKEN: lease.fencingToken,
1730
+ FORGE_WORKSPACE: lease.worktreePath,
1731
+ FORGE_WORKTREE_PATH: lease.worktreePath,
1732
+ FORGE_TMPDIR: pathFor("temporary"),
1733
+ FORGE_LOG_DIR: pathFor("logs"),
1734
+ FORGE_CACHE_DIR: pathFor("cache"),
1735
+ FORGE_BROWSER_PROFILE_DIR: pathFor("browser_profile"),
1736
+ FORGE_TEST_OUTPUT_DIR: pathFor("test_output"),
1737
+ FORGE_ATTEMPT_DATABASE_SCHEMA: `forge_attempt_${uuidHex(lease.dispatchAttemptId, "dispatch attempt")}`,
1738
+ FORGE_ATTEMPT_DATABASE_READINESS_PATH: path.join(pathFor("logs"), "attempt-database-readiness.json"),
1739
+ FORGE_PROCESS_SUPERVISOR_ID: lease.resources.processSupervisorId ?? "",
1740
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: pathFor("process_supervisor_metadata"),
1741
+ FORGE_HOST_CONCURRENCY: effectiveHostConcurrency(lease, runtimeContract, executionClass),
1742
+ FORGE_HOST_CONCURRENCY_REQUESTED: runtimeContract.contract.runtime.hostConcurrency,
1743
+ FORGE_RUNTIME_EXECUTION_CLASS: executionClass,
1744
+ FORGE_HOST_RUNTIME_CONTRACT_SOURCE: runtimeContract.source,
1745
+ FORGE_SINGLETON_KEYS: lease.resources.singletonKeys.join(","),
1746
+ TMPDIR: pathFor("temporary"),
1747
+ TMP: pathFor("temporary"),
1748
+ TEMP: pathFor("temporary"),
1749
+ XDG_CACHE_HOME: pathFor("cache"),
1750
+ NPM_CONFIG_CACHE: path.join(pathFor("cache"), "npm"),
1751
+ };
1752
+ if (lease.resources.singletonKeys.length === 0)
1753
+ delete environment.FORGE_SINGLETON_KEYS;
1754
+ const resolvedBaseUrls = [];
1755
+ for (const assigned of lease.resources.ports) {
1756
+ const configured = runtimeContract.contract.runtime.ports.find(port => port.name === assigned.name);
1757
+ if (!configured || assigned.hostIp !== "127.0.0.1")
1758
+ continue;
1759
+ Object.assign(environment, hostPortEnvironment(configured, assigned.hostIp, assigned.hostPort));
1760
+ const normalizedName = assigned.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
1761
+ environment[`FORGE_${normalizedName}_PORT`] = String(assigned.hostPort);
1762
+ if (configured.baseUrlEnv && configured.format) {
1763
+ const baseUrl = hostPortEnvironment(configured, assigned.hostIp, assigned.hostPort)[configured.baseUrlEnv];
1764
+ if (baseUrl) {
1765
+ environment[`FORGE_${normalizedName}_URL`] = baseUrl;
1766
+ resolvedBaseUrls.push(baseUrl);
1767
+ }
1768
+ }
1769
+ }
1770
+ if (environment.FORGE_API_URL)
1771
+ environment.FORGE_E2E_API_URL = environment.FORGE_API_URL;
1772
+ if (environment.FORGE_WEB_URL)
1773
+ environment.FORGE_E2E_WEB_URL = environment.FORGE_WEB_URL;
1774
+ if (resolvedBaseUrls.length === 1)
1775
+ environment.FORGE_BASE_URL = resolvedBaseUrls[0];
1776
+ return environment;
1777
+ }
1778
+ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal) {
1779
+ const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
1780
+ const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
1781
+ const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
1782
+ let stdoutTail = "";
1783
+ let stderrTail = "";
1784
+ const append = async (target, line) => {
1785
+ await fs.appendFile(target, `${line}\n`, { encoding: "utf8", mode: 0o600 });
1786
+ };
1787
+ const child = await supervisor.startChildReady(childName, {
1788
+ command: plan.command,
1789
+ args: plan.args,
1790
+ cwd: plan.cwd,
1791
+ env: plan.environment,
1792
+ captureOutput: false,
1793
+ }, {
1794
+ onStdoutLine: async (line) => {
1795
+ stdoutTail = appendRuntimeBuildTail(stdoutTail, line);
1796
+ await append(stdoutLogPath, line);
1797
+ },
1798
+ onStderrLine: async (line) => {
1799
+ stderrTail = appendRuntimeBuildTail(stderrTail, line);
1800
+ await append(stderrLogPath, line);
1801
+ },
1802
+ }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
1803
+ const result = await child.result;
1804
+ return {
1805
+ exitCode: result.exitCode,
1806
+ stdoutTail: appendRuntimeBuildTail(stdoutTail, result.stdout),
1807
+ stderrTail: appendRuntimeBuildTail(stderrTail, result.stderr),
1808
+ stdoutLogPath,
1809
+ stderrLogPath,
1810
+ };
1811
+ }
1812
+ function appendRuntimeBuildTail(current, value) {
1813
+ if (!value)
1814
+ return current;
1815
+ return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
1816
+ }
1817
+ function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
1818
+ if (executionClass === "analysis_only") {
1819
+ const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
1820
+ return analysisSingletonHeld ? "host_serial_only" : "host_parallel_safe";
1821
+ }
1822
+ if (!runtimeContract || !hostRuntimeParallelEligible(runtimeContract))
1823
+ return "host_serial_only";
1824
+ const requiredPorts = configuredLaunchPortNames(runtimeContract);
1825
+ const everyPortVerified = requiredPorts.length > 0
1826
+ && requiredPorts.every(name => lease.resources.ports.some(port => port.name === name));
1827
+ const projectSingletonHeld = lease.resources.singletonKeys.some(key => key.endsWith(":host-runtime"));
1828
+ return everyPortVerified && !projectSingletonHeld ? "host_parallel_safe" : "host_serial_only";
1829
+ }
1830
+ function projectHostRuntimeSingletonKey(repoId) {
1831
+ return `project:${repoId.toLowerCase()}:host-runtime`;
1832
+ }
1833
+ function projectHostAnalysisKey(repoId) {
1834
+ return `project:${repoId.toLowerCase()}:host-analysis`;
1835
+ }
1836
+ function hostRuntimeDeclaredSingletonKey(resource) {
1837
+ return `runtime:${resource}`;
1838
+ }
1839
+ function runtimeExecutionClass(dispatch) {
1840
+ return dispatch.runtimeIntent?.executionClass === "analysis_only"
1841
+ && dispatch.runtimeIntent.applicationRuntimeRequired === false
1842
+ ? "analysis_only"
1843
+ : "managed_runtime";
1844
+ }
1845
+ function runtimeAdmissionPriority(dispatch) {
1846
+ return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
1847
+ || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
1848
+ ? "background"
1849
+ : "foreground";
1850
+ }
1851
+ function enqueueAdmissionWaiter(waiters, waiter) {
1852
+ if (waiter.priority === "background") {
1853
+ waiters.push(waiter);
1854
+ return;
1855
+ }
1856
+ const backgroundIndex = waiters.findIndex(candidate => candidate.priority === "background");
1857
+ if (backgroundIndex < 0)
1858
+ waiters.push(waiter);
1859
+ else
1860
+ waiters.splice(backgroundIndex, 0, waiter);
1861
+ }
1862
+ function defaultHostResourceRequest() {
1863
+ const workerMemoryLimitBytes = configuredInteger("FORGE_HOST_DEFAULT_WORKER_MEMORY_LIMIT_BYTES", 2 * 1024 ** 3, 128 * 1024 ** 2, 512 * 1024 ** 3);
1864
+ const runtimeOverheadBytes = 128 * 1024 ** 2;
1865
+ return {
1866
+ sandboxSlots: 1,
1867
+ cpuMillis: 2000,
1868
+ workerMemoryLimitBytes,
1869
+ serviceMemoryLimitBytes: 0,
1870
+ runtimeOverheadBytes,
1871
+ memoryBytes: workerMemoryLimitBytes + runtimeOverheadBytes,
1872
+ workspaceBytes: 10 * 1024 ** 3,
1873
+ pids: 512,
1874
+ buildSlots: 1,
1875
+ };
1876
+ }
1877
+ function minimumSupportedHostResourceRequest() {
1878
+ return {
1879
+ sandboxSlots: 1,
1880
+ cpuMillis: 1000,
1881
+ workerMemoryLimitBytes: 1024 ** 3,
1882
+ serviceMemoryLimitBytes: 0,
1883
+ runtimeOverheadBytes: 128 * 1024 ** 2,
1884
+ memoryBytes: 1152 * 1024 ** 2,
1885
+ workspaceBytes: architectMinimumWorkspaceEstimateBytes,
1886
+ pids: 256,
1887
+ buildSlots: 0,
1888
+ };
1889
+ }
1890
+ function normalizedHostResourceRequest(resources) {
1891
+ const defaults = defaultHostResourceRequest();
1892
+ const workerMemoryLimitBytes = positiveResourceValue(resources?.workerMemoryLimitBytes, defaults.workerMemoryLimitBytes);
1893
+ const serviceMemoryLimitBytes = nonNegativeResourceValue(resources?.serviceMemoryLimitBytes, defaults.serviceMemoryLimitBytes);
1894
+ const runtimeOverheadBytes = nonNegativeResourceValue(resources?.runtimeOverheadBytes, defaults.runtimeOverheadBytes);
1895
+ return {
1896
+ sandboxSlots: positiveResourceValue(resources?.sandboxSlots, defaults.sandboxSlots),
1897
+ cpuMillis: positiveResourceValue(resources?.cpuMillis, defaults.cpuMillis),
1898
+ workerMemoryLimitBytes,
1899
+ serviceMemoryLimitBytes,
1900
+ runtimeOverheadBytes,
1901
+ memoryBytes: workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
1902
+ workspaceBytes: positiveResourceValue(resources?.workspaceBytes, defaults.workspaceBytes),
1903
+ pids: positiveResourceValue(resources?.pids, defaults.pids),
1904
+ buildSlots: nonNegativeResourceValue(resources?.buildSlots, defaults.buildSlots),
1905
+ };
1906
+ }
1907
+ function positiveResourceValue(value, fallback) {
1908
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
1909
+ }
1910
+ function nonNegativeResourceValue(value, fallback) {
1911
+ return Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
1912
+ }
1913
+ function configuredInteger(name, fallback, minimum, maximum) {
1914
+ const parsed = Number.parseInt(process.env[name] ?? "", 10);
1915
+ return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
1916
+ }
1917
+ function loadHostCapacityConfiguration(capacityResourceSample) {
1918
+ const sampledCpuCount = capacityResourceSample
1919
+ ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
1920
+ : os.cpus().length;
1921
+ const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
1922
+ const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
1923
+ const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
1924
+ return {
1925
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2))), 1, 32),
1926
+ hostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
1927
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
1928
+ floorBytes: reserveFloorBytes,
1929
+ ceilingBytes: reserveCeilingBytes,
1930
+ percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
1931
+ }),
1932
+ cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
1933
+ workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
1934
+ memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
1935
+ memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
1936
+ };
1937
+ }
1938
+ function configuredOptionalInteger(name, minimum, maximum) {
1939
+ const raw = process.env[name];
1940
+ if (raw === undefined || raw.trim().length === 0)
1941
+ return null;
1942
+ const parsed = Number.parseInt(raw, 10);
1943
+ return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : null;
1944
+ }
1945
+ function configuredNumber(name, fallback, minimum, maximum) {
1946
+ const parsed = Number(process.env[name] ?? "");
1947
+ return Number.isFinite(parsed) && parsed > 0
1948
+ ? Math.max(minimum, Math.min(maximum, parsed))
1949
+ : fallback;
1950
+ }
1951
+ function resourceSlots(available, requested) {
1952
+ if (requested <= 0)
1953
+ return Number.MAX_SAFE_INTEGER;
1954
+ return Math.max(0, Math.floor(available / requested));
1955
+ }
1956
+ function removeWaiter(waiters, waiter) {
1957
+ const index = waiters.indexOf(waiter);
1958
+ if (index >= 0)
1959
+ waiters.splice(index, 1);
1960
+ }
1961
+ function capacityProject(projects, repoId) {
1962
+ const normalized = repoId.trim().toLowerCase();
1963
+ const existing = projects.get(normalized);
1964
+ if (existing)
1965
+ return existing;
1966
+ const created = {
1967
+ repoId: normalized,
1968
+ safetyClass: null,
1969
+ activeAttempts: 0,
1970
+ reservedAttempts: 0,
1971
+ waitingAttempts: 0,
1972
+ degradedAttempts: 0,
1973
+ runtimeContractFingerprint: null,
1974
+ runtimeContractSource: null,
1975
+ promotedAt: null,
1976
+ };
1977
+ projects.set(normalized, created);
1978
+ return created;
1979
+ }
1980
+ function conservativeSafetyClass(left, right) {
1981
+ if (!left)
1982
+ return right;
1983
+ const rank = {
1984
+ host_serial_only: 0,
1985
+ host_parallel_candidate: 1,
1986
+ host_parallel_safe: 2,
1987
+ };
1988
+ return rank[right] < rank[left] ? right : left;
1989
+ }
1990
+ function repoIdFromProjectSingletonKeys(keys) {
1991
+ return keys.map(repoIdFromProjectSingletonKey).find((value) => value !== null) ?? null;
1992
+ }
1993
+ function repoIdFromProjectSingletonKey(key) {
1994
+ const prefix = "project:";
1995
+ const suffix = [":host-runtime", ":host-analysis"].find(candidate => key.endsWith(candidate));
1996
+ return key.startsWith(prefix) && suffix
1997
+ ? key.slice(prefix.length, -suffix.length)
1998
+ : null;
1999
+ }
2000
+ function sameSingletonOwner(left, right) {
2001
+ return left?.dispatchAttemptId === right.dispatchAttemptId && left.fencingToken === right.fencingToken;
2002
+ }
2003
+ function hostPortOwner(lease) {
2004
+ const processSupervisorId = lease.resources.processSupervisorId;
2005
+ if (!processSupervisorId) {
2006
+ throw new Error("host_runtime_adapter_invalid: process supervisor identity is required.");
2007
+ }
2008
+ return {
2009
+ dispatchAttemptId: lease.dispatchAttemptId,
2010
+ executionLeaseId: lease.executionLeaseId,
2011
+ fencingToken: lease.fencingToken,
2012
+ processSupervisorId,
2013
+ };
2014
+ }
2015
+ function linkedAbortController(signal) {
2016
+ const controller = new AbortController();
2017
+ if (signal?.aborted) {
2018
+ controller.abort(signal.reason);
2019
+ }
2020
+ else {
2021
+ signal?.addEventListener("abort", () => controller.abort(signal.reason), { once: true, signal: controller.signal });
2022
+ }
2023
+ return controller;
2024
+ }
2025
+ function unlinkAbortController(controller, _signal) {
2026
+ if (!controller.signal.aborted)
2027
+ controller.abort("Host adapter launch settled.");
2028
+ }
2029
+ function removeCleanup(cleanups, cleanup) {
2030
+ const index = cleanups.indexOf(cleanup);
2031
+ if (index >= 0)
2032
+ cleanups.splice(index, 1);
2033
+ }
2034
+ async function releaseAdapterResources(cleanups) {
2035
+ const pending = cleanups.splice(0);
2036
+ const failed = [];
2037
+ let firstError;
2038
+ for (const cleanup of pending.reverse()) {
2039
+ try {
2040
+ await cleanup();
2041
+ }
2042
+ catch (error) {
2043
+ firstError ??= error;
2044
+ failed.unshift(cleanup);
2045
+ }
2046
+ }
2047
+ cleanups.push(...failed);
2048
+ if (firstError !== undefined)
2049
+ throw firstError;
2050
+ }
2051
+ function cancellationError(signal) {
2052
+ return new Error(String(signal?.reason ?? "Dispatch cancelled while waiting for host runtime singleton ownership."));
2053
+ }
2054
+ function validHostRuntimeLedger(value) {
2055
+ if (typeof value !== "object" || value === null)
2056
+ return false;
2057
+ const ledger = value;
2058
+ return ledger.schemaVersion === 1
2059
+ && (ledger.repoId === undefined || /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu.test(ledger.repoId))
2060
+ && validRuntimeIsolationLease(ledger.runtimeLease)
2061
+ && ledger.runtimeLease.mode === "host";
2062
+ }
2063
+ function validHostProcessSupervisorMetadata(value, lease) {
2064
+ if (typeof value !== "object" || value === null)
2065
+ return false;
2066
+ const metadata = value;
2067
+ return metadata.schemaVersion === 1
2068
+ && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
2069
+ && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
2070
+ && Number.isSafeInteger(metadata.rootPid)
2071
+ && metadata.rootPid > 0
2072
+ && Number.isFinite(Date.parse(metadata.rootCreatedAt))
2073
+ && (metadata.rootIdentity == null
2074
+ || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
2075
+ && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
2076
+ && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
2077
+ && metadata.runtimeLeaseId === lease.executionLeaseId
2078
+ && metadata.dispatchAttemptId === lease.dispatchAttemptId
2079
+ && metadata.fencingToken === lease.fencingToken
2080
+ && Number.isSafeInteger(metadata.bridgePid)
2081
+ && metadata.bridgePid > 0;
2082
+ }
2083
+ function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
2084
+ const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
2085
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2086
+ }
2087
+ function transitionHostLeaseForCleanup(lease, state) {
2088
+ if (lease.state === state || lease.state === "released")
2089
+ return lease;
2090
+ return transitionRuntimeIsolationLease(lease, state);
2091
+ }
2092
+ function throwIfAdmissionExpired(expiresAt) {
2093
+ if (admissionExpired(expiresAt))
2094
+ throw new HostRuntimeAdmissionExpiredError();
2095
+ }
2096
+ function admissionExpired(expiresAt) {
2097
+ const deadline = Date.parse(expiresAt);
2098
+ return !Number.isFinite(deadline) || deadline <= Date.now();
2099
+ }
2100
+ function scheduleAdmissionDeadline(expiresAt, expire) {
2101
+ const delay = Math.max(0, Date.parse(expiresAt) - Date.now());
2102
+ const timer = setTimeout(expire, Math.min(delay, 2_147_483_647));
2103
+ timer.unref?.();
2104
+ return timer;
2105
+ }
2106
+ function clearAdmissionDeadline(waiter) {
2107
+ if (waiter.deadlineTimer)
2108
+ clearTimeout(waiter.deadlineTimer);
2109
+ waiter.deadlineTimer = null;
2110
+ }
2111
+ function clearCapacityRecheck(waiter) {
2112
+ if (waiter.capacityRecheckTimer)
2113
+ clearInterval(waiter.capacityRecheckTimer);
2114
+ waiter.capacityRecheckTimer = null;
2115
+ }
2116
+ async function ensurePrivateDirectory(directory) {
2117
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
2118
+ if (process.platform !== "win32")
2119
+ await fs.chmod(directory, 0o700);
2120
+ }
2121
+ async function containedWorkingDirectory(worktreePath, configuredDirectory) {
2122
+ const [realWorktree, realDirectory] = await Promise.all([
2123
+ fs.realpath(worktreePath),
2124
+ fs.realpath(path.resolve(worktreePath, configuredDirectory)),
2125
+ ]);
2126
+ const relative = path.relative(realWorktree, realDirectory);
2127
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
2128
+ throw new Error("host_runtime_project_invalid: launch working directory must remain inside the prepared worktree.");
2129
+ }
2130
+ return realDirectory;
2131
+ }
2132
+ function uuidHex(value, label) {
2133
+ const normalized = value.replaceAll("-", "").toLowerCase();
2134
+ if (!/^[0-9a-f]{32}$/u.test(normalized)) {
2135
+ throw new Error(`host_runtime_lease_invalid: ${label} id must be a full UUID.`);
2136
+ }
2137
+ return normalized;
2138
+ }