@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.ec3460040366

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 (212) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +88 -14
  16. package/dist/bridge/bridge.service.js +406 -345
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +74 -12
  36. package/dist/cli/cli.service.d.ts +19 -10
  37. package/dist/cli/cli.service.js +142 -185
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +6 -0
  41. package/dist/cli/local-config.js +32 -4
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  48. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  49. package/dist/runtime/attempt-process-supervisor.js +12 -6
  50. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  51. package/dist/runtime/docker-engine-probe.js +7 -0
  52. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  53. package/dist/runtime/dotnet-build-outputs.js +402 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  56. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  57. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  58. package/dist/runtime/host-facts.d.ts +2 -1
  59. package/dist/runtime/host-load-admission.d.ts +18 -3
  60. package/dist/runtime/host-load-admission.js +19 -4
  61. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  62. package/dist/runtime/host-load-child-environment.js +22 -11
  63. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  64. package/dist/runtime/host-load-governor-config.js +37 -0
  65. package/dist/runtime/host-load-governor.d.ts +14 -0
  66. package/dist/runtime/host-load-governor.js +139 -26
  67. package/dist/runtime/host-load-ledger-lock.js +6 -4
  68. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  69. package/dist/runtime/host-load-runtime-settings.js +80 -0
  70. package/dist/runtime/host-load-sampler.d.ts +34 -4
  71. package/dist/runtime/host-load-sampler.js +73 -7
  72. package/dist/runtime/host-load-step-class.d.ts +3 -1
  73. package/dist/runtime/host-load-step-class.js +60 -5
  74. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  75. package/dist/runtime/host-load-test-slot.js +81 -0
  76. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  77. package/dist/runtime/host-load-token-ledger.js +93 -61
  78. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  79. package/dist/runtime/host-load-windows-cpu.js +85 -0
  80. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  81. package/dist/runtime/host-runtime-contract.js +29 -1
  82. package/dist/runtime/host-runtime-lease.d.ts +62 -4
  83. package/dist/runtime/host-runtime-lease.js +235 -168
  84. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  85. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  86. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  87. package/dist/runtime/host-runtime-promotion.js +36 -0
  88. package/dist/runtime/managed-command-teardown.js +5 -16
  89. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  90. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  91. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  92. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  93. package/dist/runtime/runner-settings.d.ts +104 -0
  94. package/dist/runtime/runner-settings.js +236 -0
  95. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  96. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  97. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  98. package/dist/sandbox/host-capacity-broker.js +27 -6
  99. package/dist/sandbox/managed-branch.d.ts +13 -0
  100. package/dist/sandbox/managed-branch.js +90 -0
  101. package/dist/sandbox/provider-auth/codex.js +11 -11
  102. package/dist/sandbox/runtime.js +2 -6
  103. package/dist/session/architect-waits.d.ts +2 -0
  104. package/dist/session/architect-waits.js +138 -0
  105. package/dist/session/managed-attempt-tools.d.ts +0 -7
  106. package/dist/session/managed-attempt-tools.js +58 -91
  107. package/dist/session/managed-build-coordinator.d.ts +16 -0
  108. package/dist/session/managed-build-coordinator.js +10 -0
  109. package/dist/session/managed-build-receipt.d.ts +5 -0
  110. package/dist/session/managed-build-receipt.js +8 -3
  111. package/dist/session/managed-command-host-load.d.ts +2 -0
  112. package/dist/session/managed-command-host-load.js +2 -1
  113. package/dist/session/phase-completion.artifacts.js +2 -1
  114. package/dist/session/phase-completion.d.ts +8 -0
  115. package/dist/session/phase-completion.js +1 -0
  116. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  117. package/dist/session/phase-completion.mcp-args.js +156 -0
  118. package/dist/session/phase-completion.runtime.d.ts +0 -8
  119. package/dist/session/phase-completion.runtime.js +43 -197
  120. package/dist/session/phase-completion.schemas.js +25 -23
  121. package/dist/session/phase-completion.validation.js +3 -1
  122. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  123. package/dist/session/pre-publication-native-postgres.js +111 -0
  124. package/dist/session/pre-publication-pass.d.ts +61 -0
  125. package/dist/session/pre-publication-pass.js +148 -0
  126. package/dist/session/pre-publication-process.js +10 -10
  127. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  128. package/dist/session/pre-publication-step-execution.js +6 -5
  129. package/dist/session/pre-publication-validation.d.ts +30 -14
  130. package/dist/session/pre-publication-validation.js +207 -134
  131. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  132. package/dist/session/provider-cli/claude-background-work.js +181 -0
  133. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  134. package/dist/session/provider-cli/host-build-lock.js +30 -0
  135. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  136. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  137. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  138. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  139. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  140. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  141. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  142. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  143. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  144. package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
  145. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  146. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  147. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  148. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  149. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  150. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  151. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  152. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  153. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  154. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  155. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  156. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  157. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  158. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  159. package/dist/session/provider-cli/provider-output-state.js +6 -0
  160. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  161. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  162. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  163. package/dist/session/qa-sidecar-validation.js +28 -0
  164. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  165. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  166. package/dist/session/session-redaction.js +31 -181
  167. package/dist/session/session.base.d.ts +6 -1
  168. package/dist/session/session.service.d.ts +9 -2
  169. package/dist/session/session.service.js +169 -66
  170. package/dist/session/session.types.js +4 -4
  171. package/dist/session/sidecar-json-shape.d.ts +31 -0
  172. package/dist/session/sidecar-json-shape.js +217 -0
  173. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  174. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  175. package/dist/shared/fs/file-identity.d.ts +10 -0
  176. package/dist/shared/fs/file-identity.js +15 -0
  177. package/dist/shared/fs/replace-file.d.ts +7 -0
  178. package/dist/shared/fs/replace-file.js +33 -0
  179. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  180. package/dist/shared/process/host-process-recovery.js +23 -3
  181. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  182. package/dist/shared/process/host-process-supervisor.js +66 -14
  183. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  184. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  185. package/dist/shared/process/windows-launch.d.ts +18 -0
  186. package/dist/shared/process/windows-launch.js +68 -0
  187. package/dist/shared/provider-capabilities.js +14 -7
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/dist/worktree/orphan-relink.d.ts +19 -0
  191. package/dist/worktree/orphan-relink.js +106 -0
  192. package/dist/worktree/wip-git.d.ts +33 -0
  193. package/dist/worktree/wip-git.js +122 -0
  194. package/dist/worktree/wip-refs.d.ts +62 -0
  195. package/dist/worktree/wip-refs.js +119 -0
  196. package/dist/worktree/wip-restore.d.ts +38 -0
  197. package/dist/worktree/wip-restore.js +190 -0
  198. package/dist/worktree/wip-snapshot.d.ts +50 -0
  199. package/dist/worktree/wip-snapshot.js +268 -0
  200. package/dist/worktree/worktree-inputs.d.ts +8 -0
  201. package/dist/worktree/worktree-inputs.js +134 -0
  202. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  203. package/dist/worktree/worktree-origin-sync.js +127 -0
  204. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  205. package/dist/worktree/worktree-wip-events.js +98 -0
  206. package/dist/worktree/worktree-wip.d.ts +50 -0
  207. package/dist/worktree/worktree-wip.js +185 -0
  208. package/dist/worktree/worktree.base.d.ts +7 -1
  209. package/dist/worktree/worktree.service.d.ts +27 -5
  210. package/dist/worktree/worktree.service.js +110 -181
  211. package/dist/worktree/worktree.types.d.ts +31 -0
  212. package/package.json +2 -2
@@ -10,34 +10,30 @@ import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
10
  import { ForgeFailureError } from "../session/session.types.js";
11
11
  import { resolveExistingDirectoryPath } from "../shared/path/path.js";
12
12
  import { formatBytes } from "../shared/format/format-bytes.js";
13
- import { redactText } from "../shared/redaction/redaction.js";
14
13
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
15
14
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
16
- import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
15
+ import { hostPortEnvironment, loadHostRuntimeContract, newAttemptApiMasterKey, withAttemptApiMasterKey, } from "./host-runtime-contract.js";
17
16
  import { HostPortBroker, } from "./host-port-broker.js";
18
17
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
19
18
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
20
- import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
21
19
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
22
20
  import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
23
21
  import { HostListenerInspector } from "./host-listener-inspector.js";
24
22
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
25
23
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
26
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
24
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
27
25
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
28
26
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
29
27
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
30
- import { readCanonicalSourceFile } from "./canonical-source-file.js";
31
- import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
28
+ import { logHostRuntimeStatus, recoverPersistedHostProcesses, replaceHostRuntimeLedgerFile, retryDegradedHostRelease, } from "./host-runtime-ledger-recovery.js";
32
29
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
33
- import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
30
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, executeAspNetRuntimeBuild, resolveWorktreeCommitSha, supervisedRuntimeLaunchArguments, } from "./aspnet-runtime-prebuild.js";
34
31
  import { HostLoadGovernor } from "./host-load-governor.js";
35
32
  import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
36
33
  import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
37
34
  import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
38
35
  import { HostLoadSampler } from "./host-load-sampler.js";
39
36
  const hostCapacityWaiterScanLimit = 64;
40
- const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
41
37
  export class HostRuntimeLeaseManager {
42
38
  stateRoot;
43
39
  processSupervisors;
@@ -67,10 +63,11 @@ export class HostRuntimeLeaseManager {
67
63
  workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
68
64
  portBroker;
69
65
  nodeAdapter;
66
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
70
67
  capacityConfiguration;
71
68
  memoryAvailability;
72
69
  executionRoot;
73
- /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
70
+ /** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
74
71
  hostLoadGovernor;
75
72
  requirementsCheck = null;
76
73
  /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
@@ -97,6 +94,34 @@ export class HostRuntimeLeaseManager {
97
94
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
98
95
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
99
96
  }
97
+ /** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
98
+ capacityLimitDefaults() {
99
+ return {
100
+ maxConcurrentAttempts: this.capacityConfiguration.defaultHardMaxAttempts,
101
+ memoryReserveBytes: this.capacityConfiguration.adaptiveHostReserveBytes,
102
+ };
103
+ }
104
+ /**
105
+ * Decision 0014: the bridge's effective max attempts and memory reserve. They
106
+ * apply from the next attempt admission; admitted attempts keep their
107
+ * reservations and are never preempted, even when the new limit is lower than
108
+ * what already runs. The idle reserve follows the reserve as at startup.
109
+ */
110
+ applyCapacityLimits(limits) {
111
+ const current = this.capacityConfiguration;
112
+ const hardMaxAttempts = Math.max(1, Math.min(32, Math.floor(limits.maxConcurrentAttempts)));
113
+ const hostReserveBytes = Math.max(512 * 1024 ** 2, Math.floor(limits.memoryReserveBytes));
114
+ if (hardMaxAttempts === current.hardMaxAttempts && hostReserveBytes === current.hostReserveBytes)
115
+ return;
116
+ this.capacityConfiguration = {
117
+ ...current,
118
+ hardMaxAttempts,
119
+ hostReserveBytes,
120
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, current),
121
+ };
122
+ // A raised limit may admit queued attempts now rather than at their next recheck.
123
+ this.drainAdmissionWaiters();
124
+ }
100
125
  hostLoadChildEnvironment() {
101
126
  return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
102
127
  }
@@ -134,19 +159,16 @@ export class HostRuntimeLeaseManager {
134
159
  }
135
160
  const active = this.active.get(lease.dispatchAttemptId);
136
161
  if (active) {
162
+ // A live lease is never released here, however long past its expiry; a degraded one
163
+ // is retried under its own fence until teardown proves its process tree stopped.
137
164
  if (active.lease.state !== "degraded")
138
165
  continue;
139
166
  report.examined += 1;
140
- try {
141
- const released = await this.release(lease.dispatchAttemptId, lease.fencingToken);
142
- if (released?.state === "released")
143
- report.reaped += 1;
144
- else
145
- report.degraded += 1;
146
- }
147
- catch {
167
+ const released = await retryDegradedHostRelease(active.lease, () => this.release(lease.dispatchAttemptId, lease.fencingToken), options.log ?? logHostRuntimeStatus);
168
+ if (released)
169
+ report.reaped += 1;
170
+ else
148
171
  report.degraded += 1;
149
- }
150
172
  continue;
151
173
  }
152
174
  const staleInstance = lease.runnerInstanceId !== options.runnerInstanceId;
@@ -161,18 +183,16 @@ export class HostRuntimeLeaseManager {
161
183
  if (!attemptRootIdentity) {
162
184
  throw new Error("host_runtime_reaper_invalid: original attempt-root identity is unavailable.");
163
185
  }
164
- outcomes = await this.recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity);
186
+ outcomes = await recoverPersistedHostProcesses(lease, attemptRoot, this.attemptRoot(lease.dispatchAttemptId), attemptRootIdentity, this.processRecovery);
165
187
  }
166
188
  catch {
167
- await this.markLedgerDegraded(ledger);
168
- report.degraded += 1;
189
+ await this.markLedgerDegraded(ledger, report);
169
190
  continue;
170
191
  }
171
192
  report.processesTerminated += outcomes.filter(outcome => outcome === "terminated").length;
172
193
  report.reusedPidsProtected += outcomes.filter(outcome => outcome === "pid_reused").length;
173
194
  if (outcomes.includes("unverifiable")) {
174
- await this.markLedgerDegraded(ledger);
175
- report.degraded += 1;
195
+ await this.markLedgerDegraded(ledger, report);
176
196
  continue;
177
197
  }
178
198
  // The runtime has already been released. Keep the over-budget original
@@ -219,8 +239,7 @@ export class HostRuntimeLeaseManager {
219
239
  report.reaped += 1;
220
240
  }
221
241
  catch {
222
- await this.markLedgerDegraded(ledger);
223
- report.degraded += 1;
242
+ await this.markLedgerDegraded(ledger, report);
224
243
  }
225
244
  }
226
245
  // Databases issued to attempts that ended without a clean release (a Bridge crash, or a
@@ -1122,6 +1141,8 @@ export class HostRuntimeLeaseManager {
1122
1141
  parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1123
1142
  processSupervisor,
1124
1143
  adapterCleanups: [],
1144
+ adapterCleanupsByPort: new Map(),
1145
+ restartingConfiguredProject: false,
1125
1146
  pendingAdapterLaunches: new Map(),
1126
1147
  runtimeResourcesReleased: false,
1127
1148
  releasing: false,
@@ -1184,6 +1205,15 @@ export class HostRuntimeLeaseManager {
1184
1205
  await this.writeLedger(renewed);
1185
1206
  }
1186
1207
  async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1208
+ return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
1209
+ }
1210
+ /**
1211
+ * Launches the configured project. Only the first launch, from the admitted commit's clean
1212
+ * source, may record parallel-safety proof: a restart serves the workspace after the provider
1213
+ * edited it, and a proof observed there would be stored under the admitted commit and could
1214
+ * move this or a later attempt at that commit into shared admission for source it never ran.
1215
+ */
1216
+ async launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, promote) {
1187
1217
  const active = this.active.get(dispatchAttemptId);
1188
1218
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1189
1219
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
@@ -1235,8 +1265,9 @@ export class HostRuntimeLeaseManager {
1235
1265
  data: { database: active.databaseCapability.databaseName },
1236
1266
  });
1237
1267
  }
1238
- // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1239
- const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1268
+ const apiMasterKey = attemptApiMasterKey(active);
1269
+ // Runtime output is persisted to attempt logs; the database login and master key it may print are redacted.
1270
+ const capabilitySecrets = [...attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString), apiMasterKey];
1240
1271
  const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1241
1272
  for (const configuredPort of configuredPorts) {
1242
1273
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
@@ -1246,7 +1277,7 @@ export class HostRuntimeLeaseManager {
1246
1277
  };
1247
1278
  const prebuild = createAspNetRuntimePrebuildPlan({
1248
1279
  command: configuredPort.launch.command,
1249
- args: configuredPort.launch.args,
1280
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1250
1281
  cwd: workingDirectory,
1251
1282
  worktreePath: active.lease.worktreePath,
1252
1283
  environment: buildEnvironment,
@@ -1257,7 +1288,7 @@ export class HostRuntimeLeaseManager {
1257
1288
  await onProjectCheckpoint?.({
1258
1289
  code: "host_runtime_build_started",
1259
1290
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1260
- data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1291
+ data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath, output_directory: prebuild.outputDirectory },
1261
1292
  });
1262
1293
  let hostLoadWaitMs = null;
1263
1294
  const build = await ensureAspNetRuntimePrebuilt(prebuild,
@@ -1297,14 +1328,12 @@ export class HostRuntimeLeaseManager {
1297
1328
  }
1298
1329
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1299
1330
  command: configuredPort.launch.command,
1300
- args: configuredPort.launch.args,
1331
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1301
1332
  cwd: workingDirectory,
1302
- environment: {
1303
- ...buildEnvironment,
1304
- },
1333
+ environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1305
1334
  }, launcher, signal);
1306
1335
  }
1307
- const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1336
+ const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
1308
1337
  const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1309
1338
  const playwright = active.runtimeContract.contract.runtime.playwright;
1310
1339
  if (!playwright) {
@@ -1343,6 +1372,94 @@ export class HostRuntimeLeaseManager {
1343
1372
  executionClass: active.executionClass,
1344
1373
  };
1345
1374
  }
1375
+ /**
1376
+ * Relaunches the configured project so it serves the current workspace. Every
1377
+ * configured process stops (the API port changes, so the dev server's proxy target
1378
+ * must change with it), its port reservation is released and dropped from the
1379
+ * persisted lease, and the regular start path runs again, including the ASP.NET
1380
+ * prebuild, whose receipt rebuilds only when the sources changed.
1381
+ */
1382
+ async restartConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1383
+ const active = this.active.get(dispatchAttemptId);
1384
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1385
+ throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1386
+ }
1387
+ if (signal?.aborted)
1388
+ throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
1389
+ if (active.restartingConfiguredProject) {
1390
+ throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
1391
+ }
1392
+ active.restartingConfiguredProject = true;
1393
+ // Release cancels the whole restart through this controller and waits for it to settle.
1394
+ const controller = linkedAbortController(signal);
1395
+ const promise = this.runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, controller.signal, onProjectCheckpoint);
1396
+ const restart = { controller, promise };
1397
+ active.configuredProjectRestart = restart;
1398
+ try {
1399
+ return await promise;
1400
+ }
1401
+ finally {
1402
+ // The controller is not aborted on settle: adapters this restart launched keep it as their
1403
+ // parent signal for as long as they run, exactly as they would keep the caller's signal.
1404
+ if (active.configuredProjectRestart === restart)
1405
+ active.configuredProjectRestart = null;
1406
+ active.restartingConfiguredProject = false;
1407
+ }
1408
+ }
1409
+ async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1410
+ // The relaunch keeps the admission granted at start. A workspace contract that changed only its
1411
+ // launch environment is adopted; any other change throws host_runtime_contract_changed.
1412
+ const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
1413
+ active.runtimeContract = readmitted.runtimeContract;
1414
+ active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
1415
+ if (readmitted.changed) {
1416
+ await onProjectCheckpoint?.({ code: "host_runtime_contract_readmitted", message: "The workspace's runtime contract changed only its launch environment; the restart runs it under the admission granted at start." });
1417
+ }
1418
+ const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1419
+ const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
1420
+ if (pendingPort) {
1421
+ throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
1422
+ }
1423
+ const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
1424
+ if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
1425
+ // The generated Playwright config targets the stack being stopped. If the restart fails, no
1426
+ // config may be left pointing at ports another attempt can now be assigned.
1427
+ await this.playwrightAdapter.discardOverlay(temporaryDirectory);
1428
+ }
1429
+ await this.stopConfiguredProject(active, portNames);
1430
+ // Keeps whatever admission the attempt holds; see launchConfiguredProject.
1431
+ const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
1432
+ if (active.releasing) {
1433
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1434
+ }
1435
+ return restarted;
1436
+ }
1437
+ /** Stops configured project processes in reverse launch order and releases their ports. */
1438
+ async stopConfiguredProject(active, portNames) {
1439
+ const launched = active.lease.resources.ports
1440
+ .map(port => port.name)
1441
+ .filter(name => portNames.includes(name))
1442
+ .reverse();
1443
+ for (const name of launched) {
1444
+ if (active.releasing) {
1445
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1446
+ }
1447
+ const cleanup = active.adapterCleanupsByPort.get(name);
1448
+ if (!cleanup) {
1449
+ throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
1450
+ }
1451
+ // A failed stop keeps the cleanup and the port record for the fenced release retry.
1452
+ await cleanup();
1453
+ removeCleanup(active.adapterCleanups, cleanup);
1454
+ active.adapterCleanupsByPort.delete(name);
1455
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1456
+ ...active.lease.resources,
1457
+ ports: active.lease.resources.ports.filter(port => port.name !== name),
1458
+ });
1459
+ await this.writeLedger(runtimeLease);
1460
+ active.lease = runtimeLease;
1461
+ }
1462
+ }
1346
1463
  providerProcessRunner(dispatchAttemptId, fencingToken) {
1347
1464
  const active = this.active.get(dispatchAttemptId);
1348
1465
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
@@ -1430,6 +1547,7 @@ export class HostRuntimeLeaseManager {
1430
1547
  unlinkAbortController(controller, signal);
1431
1548
  };
1432
1549
  active.adapterCleanups.push(cleanup);
1550
+ active.adapterCleanupsByPort.set(portName, cleanup);
1433
1551
  try {
1434
1552
  if (active.releasing)
1435
1553
  throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
@@ -1452,6 +1570,8 @@ export class HostRuntimeLeaseManager {
1452
1570
  try {
1453
1571
  await cleanup();
1454
1572
  removeCleanup(active.adapterCleanups, cleanup);
1573
+ if (active.adapterCleanupsByPort.get(portName) === cleanup)
1574
+ active.adapterCleanupsByPort.delete(portName);
1455
1575
  }
1456
1576
  catch {
1457
1577
  // Preserve the cleanup and broker claim for the fenced release retry.
@@ -1497,11 +1617,20 @@ export class HostRuntimeLeaseManager {
1497
1617
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1498
1618
  }
1499
1619
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1620
+ const restart = active.configuredProjectRestart;
1621
+ if (restart) {
1622
+ restart.controller.abort("Host runtime release cancelled the configured project restart.");
1623
+ await restart.promise.catch(() => undefined);
1624
+ }
1500
1625
  await active.databaseProvision?.catch(() => undefined);
1501
- let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1502
- active.lease = releasing;
1503
- await this.writeLedger(releasing);
1626
+ // The releasing write is part of the fenced teardown: when it fails (Windows can refuse
1627
+ // to replace a ledger another handle is reading), the lease must end degraded so
1628
+ // maintenance retries it, never left nonterminal in memory where nothing retries it.
1629
+ let releasing = active.lease;
1504
1630
  try {
1631
+ releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1632
+ active.lease = releasing;
1633
+ await this.writeLedger(releasing);
1505
1634
  if (!active.runtimeResourcesReleased) {
1506
1635
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1507
1636
  // The attempt's MCP servers and process trees are stopped now; tokens they held
@@ -1514,6 +1643,7 @@ export class HostRuntimeLeaseManager {
1514
1643
  // validation step whose termination failed earlier) return their tokens now.
1515
1644
  await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1516
1645
  await releaseAdapterResources(active.adapterCleanups);
1646
+ active.adapterCleanupsByPort.clear();
1517
1647
  if (active.databaseCapability && this.databaseBroker) {
1518
1648
  // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1519
1649
  await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
@@ -1556,13 +1686,12 @@ export class HostRuntimeLeaseManager {
1556
1686
  if (!evidenceRetainedAtAttemptRoot) {
1557
1687
  await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1558
1688
  }
1559
- releasing = released;
1560
1689
  this.active.delete(dispatchAttemptId);
1561
1690
  this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1562
1691
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1563
1692
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1564
1693
  this.deleteAdmission(dispatchAttemptId, fencingToken);
1565
- return releasing;
1694
+ return released;
1566
1695
  }
1567
1696
  catch (error) {
1568
1697
  const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
@@ -1597,66 +1726,12 @@ export class HostRuntimeLeaseManager {
1597
1726
  }
1598
1727
  return ledgers;
1599
1728
  }
1600
- async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
1601
- const logsRoot = path.join(attemptRoot, "logs");
1602
- const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
1603
- if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
1604
- throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
1605
- }
1606
- await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
1607
- const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
1608
- const logsEntry = rootEntries.find(entry => entry.name === "logs");
1609
- if (!logsEntry)
1610
- return [];
1611
- if (logsEntry.kind !== "directory") {
1612
- throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1613
- }
1614
- const outcomes = [];
1615
- const failures = [];
1616
- try {
1617
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1618
- for (const entry of entries) {
1619
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1620
- continue;
1621
- const metadataPath = path.join(logsRoot, entry.name);
1622
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1623
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1624
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1625
- }
1626
- outcomes.push(await this.processRecovery.recover(value));
1627
- }
1628
- }
1629
- catch (error) {
1630
- failures.push(error);
1631
- }
1632
- // Managed commands run in their own process groups and record their ownership apart
1633
- // from the attempt's supervised children. They are recovered even when recovering a
1634
- // supervised child failed, and both failures are reported together.
1635
- try {
1636
- const managed = await terminateAttemptManagedCommands({
1637
- logDirectory: logsRoot,
1638
- dispatchAttemptId: lease.dispatchAttemptId,
1639
- runtimeLeaseId: lease.executionLeaseId,
1640
- pinnedLogDirectory: logsEntry.identity,
1641
- }, { reason: "attempt_teardown" });
1642
- for (const command of managed) {
1643
- if (command.outcome === "terminated" || command.outcome === "pid_reused")
1644
- outcomes.push(command.outcome);
1645
- }
1646
- }
1647
- catch (error) {
1648
- failures.push(error);
1649
- }
1650
- if (failures.length === 1)
1651
- throw failures[0];
1652
- if (failures.length > 1)
1653
- throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1654
- return outcomes;
1655
- }
1656
- async markLedgerDegraded(ledger) {
1729
+ /** Degrades and counts a ledger whose runtime may still be live. A retained released ledger owns no slot, so it is neither changed nor counted. */
1730
+ async markLedgerDegraded(ledger, report) {
1657
1731
  const lease = ledger.runtimeLease;
1658
1732
  if (lease.state === "released")
1659
1733
  return;
1734
+ report.degraded += 1;
1660
1735
  const degraded = transitionHostLeaseForCleanup(lease, "degraded");
1661
1736
  const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
1662
1737
  this.rememberDegraded(degraded, repoId);
@@ -1725,7 +1800,7 @@ export class HostRuntimeLeaseManager {
1725
1800
  finally {
1726
1801
  await handle.close();
1727
1802
  }
1728
- await fs.rename(temporary, target);
1803
+ await replaceHostRuntimeLedgerFile(temporary, target);
1729
1804
  }
1730
1805
  catch (error) {
1731
1806
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -2213,50 +2288,36 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2213
2288
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2214
2289
  return environment;
2215
2290
  }
2216
- function anySignal(...signals) {
2217
- return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2291
+ /**
2292
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
2293
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
2294
+ * stack is down: after its ports are released another attempt may be assigned them.
2295
+ */
2296
+ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2297
+ const keys = new Set([
2298
+ "FORGE_E2E_API_URL",
2299
+ "FORGE_E2E_WEB_URL",
2300
+ "FORGE_BASE_URL",
2301
+ "FORGE_PLAYWRIGHT_BASE_URL",
2302
+ // The generated Playwright config embeds the base URL.
2303
+ "FORGE_PLAYWRIGHT_CONFIG",
2304
+ ]);
2305
+ for (const port of runtimeContract.contract.runtime.ports) {
2306
+ const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
2307
+ keys.add(port.env);
2308
+ if (port.baseUrlEnv)
2309
+ keys.add(port.baseUrlEnv);
2310
+ keys.add(`FORGE_${normalizedName}_PORT`);
2311
+ keys.add(`FORGE_${normalizedName}_URL`);
2312
+ }
2313
+ return [...keys];
2218
2314
  }
2219
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
2220
- /** Once the build's supervised tree is up: records it on the build's host load token. */
2221
- onStarted) {
2222
- const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2223
- const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2224
- const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2225
- let stdoutTail = "";
2226
- let stderrTail = "";
2227
- const append = async (target, line) => {
2228
- await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2229
- };
2230
- const child = await supervisor.startChildReady(childName, {
2231
- command: plan.command,
2232
- args: plan.args,
2233
- cwd: plan.cwd,
2234
- env: plan.environment,
2235
- captureOutput: false,
2236
- }, {
2237
- onStdoutLine: async (line) => {
2238
- stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2239
- await append(stdoutLogPath, line);
2240
- },
2241
- onStderrLine: async (line) => {
2242
- stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2243
- await append(stderrLogPath, line);
2244
- },
2245
- }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2246
- await onStarted?.(child.metadataPath);
2247
- const result = await child.result;
2248
- return {
2249
- exitCode: result.exitCode,
2250
- stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2251
- stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2252
- stdoutLogPath,
2253
- stderrLogPath,
2254
- };
2315
+ /** The attempt's API master key: issued on first use, then the same for every relaunch of the attempt. */
2316
+ function attemptApiMasterKey(active) {
2317
+ return active.apiMasterKey ??= newAttemptApiMasterKey();
2255
2318
  }
2256
- function appendRuntimeBuildTail(current, value) {
2257
- if (!value)
2258
- return current;
2259
- return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
2319
+ function anySignal(...signals) {
2320
+ return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2260
2321
  }
2261
2322
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
2262
2323
  if (executionClass === "analysis_only") {
@@ -2358,6 +2419,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
2358
2419
  const parsed = Number.parseInt(process.env[name] ?? "", 10);
2359
2420
  return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2360
2421
  }
2422
+ /**
2423
+ * Today's max attempts and adaptive memory reserve for this host, before
2424
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
2425
+ * (decision 0014 treats those as bounds on the server's values).
2426
+ */
2427
+ export function hostCapacityLimitDefaults(capacityResourceSample) {
2428
+ const configuration = loadHostCapacityConfiguration(capacityResourceSample);
2429
+ return {
2430
+ maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
2431
+ memoryReserveBytes: configuration.adaptiveHostReserveBytes,
2432
+ };
2433
+ }
2361
2434
  function loadHostCapacityConfiguration(capacityResourceSample) {
2362
2435
  const sampledCpuCount = capacityResourceSample
2363
2436
  ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
@@ -2365,23 +2438,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
2365
2438
  const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2366
2439
  const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2367
2440
  const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
2368
- const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2369
- explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2441
+ const adaptiveOptions = {
2370
2442
  floorBytes: reserveFloorBytes,
2371
2443
  ceilingBytes: reserveCeilingBytes,
2372
2444
  percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
2445
+ };
2446
+ const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2447
+ ...adaptiveOptions,
2448
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2373
2449
  });
2374
- const minimumIdleReserveBytes = Math.min(hostReserveBytes, reserveFloorBytes);
2450
+ const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
2451
+ const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
2452
+ const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
2375
2453
  return {
2376
- hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2))), 1, 32),
2454
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
2377
2455
  hostReserveBytes,
2378
- idleHostReserveBytes: configuredInteger("FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES", minimumIdleReserveBytes, 512 * 1024 ** 2, hostReserveBytes),
2456
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
2457
+ defaultHardMaxAttempts,
2458
+ adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
2459
+ reserveFloorBytes,
2460
+ idleReserveOverrideBytes,
2379
2461
  cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2380
2462
  workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2381
2463
  memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2382
2464
  memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2383
2465
  };
2384
2466
  }
2467
+ /**
2468
+ * The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
2469
+ * clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
2470
+ */
2471
+ function idleHostReserveBytesFor(hostReserveBytes, configuration) {
2472
+ const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
2473
+ const override = configuration.idleReserveOverrideBytes;
2474
+ return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
2475
+ }
2385
2476
  function configuredOptionalInteger(name, minimum, maximum) {
2386
2477
  const raw = process.env[name];
2387
2478
  if (raw === undefined || raw.trim().length === 0)
@@ -2534,30 +2625,6 @@ function deserializeHostAttemptRootIdentity(identity) {
2534
2625
  ? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
2535
2626
  : null;
2536
2627
  }
2537
- function validHostProcessSupervisorMetadata(value, lease) {
2538
- if (typeof value !== "object" || value === null)
2539
- return false;
2540
- const metadata = value;
2541
- return metadata.schemaVersion === 1
2542
- && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
2543
- && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
2544
- && Number.isSafeInteger(metadata.rootPid)
2545
- && metadata.rootPid > 0
2546
- && Number.isFinite(Date.parse(metadata.rootCreatedAt))
2547
- && (metadata.rootIdentity == null
2548
- || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
2549
- && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
2550
- && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
2551
- && metadata.runtimeLeaseId === lease.executionLeaseId
2552
- && metadata.dispatchAttemptId === lease.dispatchAttemptId
2553
- && metadata.fencingToken === lease.fencingToken
2554
- && Number.isSafeInteger(metadata.bridgePid)
2555
- && metadata.bridgePid > 0;
2556
- }
2557
- function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
2558
- const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
2559
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2560
- }
2561
2628
  function transitionHostLeaseForCleanup(lease, state) {
2562
2629
  if (lease.state === state || lease.state === "released")
2563
2630
  return lease;
@@ -0,0 +1,20 @@
1
+ import type { HostProcessRecovery, HostProcessRecoveryOutcome } from "../shared/process/host-process-recovery.js";
2
+ import type { PinnedDirectoryIdentity } from "./pinned-directory-process.js";
3
+ import type { RuntimeIsolationLease } from "./runtime-isolation-lease.js";
4
+ /**
5
+ * Replaces a host runtime ledger with its fully written temporary file. Windows refuses
6
+ * to replace a file another handle has open (EPERM), for example while a recovery pass
7
+ * reads the same ledger, so a transient refusal is retried for about a second, as the
8
+ * attempt supervisor does for its own ledger.
9
+ */
10
+ export declare function replaceHostRuntimeLedgerFile(temporary: string, target: string, retryMs?: number): Promise<void>;
11
+ /**
12
+ * Maintenance retry of a degraded lease's fenced release. The release frees the slot only
13
+ * after its teardown proves the attempt's supervised process tree stopped (the supervisor
14
+ * is stopped with no live child or managed command); otherwise the lease stays degraded
15
+ * and the log says why. Returns whether the lease was released.
16
+ */
17
+ export declare function retryDegradedHostRelease(lease: RuntimeIsolationLease, release: () => Promise<RuntimeIsolationLease | null>, log: (message: string) => void): Promise<boolean>;
18
+ export declare function logHostRuntimeStatus(message: string): void;
19
+ /** Exact, fenced recovery of the process trees a lease's attempt recorded under its attempt root. */
20
+ export declare function recoverPersistedHostProcesses(lease: RuntimeIsolationLease, attemptRoot: string, expectedAttemptRoot: string, attemptRootIdentity: PinnedDirectoryIdentity, processRecovery: HostProcessRecovery): Promise<readonly HostProcessRecoveryOutcome[]>;