@loucompanion/forge-bridge 0.1.4-dev.138b79c6feb3 → 0.1.4-dev.176dfdaf5020

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 (207) 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 +87 -14
  16. package/dist/bridge/bridge.service.js +393 -337
  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 +104 -26
  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 +32 -4
  83. package/dist/runtime/host-runtime-lease.js +109 -173
  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/runner-settings.d.ts +104 -0
  92. package/dist/runtime/runner-settings.js +236 -0
  93. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  94. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  95. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  96. package/dist/sandbox/host-capacity-broker.js +27 -6
  97. package/dist/sandbox/managed-branch.d.ts +13 -0
  98. package/dist/sandbox/managed-branch.js +90 -0
  99. package/dist/sandbox/provider-auth/codex.js +11 -11
  100. package/dist/sandbox/runtime.js +2 -6
  101. package/dist/session/architect-waits.d.ts +2 -0
  102. package/dist/session/architect-waits.js +138 -0
  103. package/dist/session/managed-attempt-tools.d.ts +0 -7
  104. package/dist/session/managed-attempt-tools.js +58 -91
  105. package/dist/session/managed-build-coordinator.d.ts +16 -0
  106. package/dist/session/managed-build-coordinator.js +10 -0
  107. package/dist/session/managed-build-receipt.d.ts +5 -0
  108. package/dist/session/managed-build-receipt.js +8 -3
  109. package/dist/session/managed-command-host-load.d.ts +2 -0
  110. package/dist/session/managed-command-host-load.js +2 -1
  111. package/dist/session/phase-completion.artifacts.js +2 -1
  112. package/dist/session/phase-completion.d.ts +8 -0
  113. package/dist/session/phase-completion.js +1 -0
  114. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  115. package/dist/session/phase-completion.mcp-args.js +156 -0
  116. package/dist/session/phase-completion.runtime.d.ts +0 -8
  117. package/dist/session/phase-completion.runtime.js +43 -197
  118. package/dist/session/phase-completion.schemas.js +25 -23
  119. package/dist/session/phase-completion.validation.js +3 -1
  120. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  121. package/dist/session/pre-publication-native-postgres.js +111 -0
  122. package/dist/session/pre-publication-pass.d.ts +61 -0
  123. package/dist/session/pre-publication-pass.js +148 -0
  124. package/dist/session/pre-publication-process.js +10 -10
  125. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  126. package/dist/session/pre-publication-step-execution.js +6 -5
  127. package/dist/session/pre-publication-validation.d.ts +30 -14
  128. package/dist/session/pre-publication-validation.js +207 -134
  129. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  130. package/dist/session/provider-cli/claude-background-work.js +181 -0
  131. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  132. package/dist/session/provider-cli/host-build-lock.js +30 -0
  133. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  134. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  135. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  136. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  137. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  138. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  139. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  140. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  141. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  142. package/dist/session/provider-cli/provider-cli.prompts.js +68 -31
  143. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  144. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  145. package/dist/session/provider-cli/provider-cli.service.d.ts +5 -5
  146. package/dist/session/provider-cli/provider-cli.service.js +70 -263
  147. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  148. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  149. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  150. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  151. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  152. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  153. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  154. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  155. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  156. package/dist/session/provider-cli/provider-output-state.js +6 -0
  157. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  158. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  159. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  160. package/dist/session/qa-sidecar-validation.js +28 -0
  161. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  162. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  163. package/dist/session/session-redaction.js +31 -181
  164. package/dist/session/session.base.d.ts +6 -1
  165. package/dist/session/session.service.d.ts +6 -1
  166. package/dist/session/session.service.js +75 -64
  167. package/dist/session/session.types.js +3 -3
  168. package/dist/session/sidecar-json-shape.d.ts +31 -0
  169. package/dist/session/sidecar-json-shape.js +217 -0
  170. package/dist/shared/fs/file-identity.d.ts +10 -0
  171. package/dist/shared/fs/file-identity.js +15 -0
  172. package/dist/shared/fs/replace-file.d.ts +7 -0
  173. package/dist/shared/fs/replace-file.js +33 -0
  174. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  175. package/dist/shared/process/host-process-recovery.js +23 -3
  176. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  177. package/dist/shared/process/host-process-supervisor.js +66 -14
  178. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  179. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  180. package/dist/shared/process/windows-launch.d.ts +18 -0
  181. package/dist/shared/process/windows-launch.js +68 -0
  182. package/dist/shared/provider-capabilities.js +14 -7
  183. package/dist/version.d.ts +1 -1
  184. package/dist/version.js +1 -1
  185. package/dist/worktree/orphan-relink.d.ts +19 -0
  186. package/dist/worktree/orphan-relink.js +106 -0
  187. package/dist/worktree/wip-git.d.ts +33 -0
  188. package/dist/worktree/wip-git.js +122 -0
  189. package/dist/worktree/wip-refs.d.ts +62 -0
  190. package/dist/worktree/wip-refs.js +119 -0
  191. package/dist/worktree/wip-restore.d.ts +38 -0
  192. package/dist/worktree/wip-restore.js +190 -0
  193. package/dist/worktree/wip-snapshot.d.ts +50 -0
  194. package/dist/worktree/wip-snapshot.js +268 -0
  195. package/dist/worktree/worktree-inputs.d.ts +8 -0
  196. package/dist/worktree/worktree-inputs.js +134 -0
  197. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  198. package/dist/worktree/worktree-origin-sync.js +127 -0
  199. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  200. package/dist/worktree/worktree-wip-events.js +98 -0
  201. package/dist/worktree/worktree-wip.d.ts +50 -0
  202. package/dist/worktree/worktree-wip.js +185 -0
  203. package/dist/worktree/worktree.base.d.ts +7 -1
  204. package/dist/worktree/worktree.service.d.ts +27 -5
  205. package/dist/worktree/worktree.service.js +110 -181
  206. package/dist/worktree/worktree.types.d.ts +31 -0
  207. 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
@@ -1246,8 +1265,9 @@ export class HostRuntimeLeaseManager {
1246
1265
  data: { database: active.databaseCapability.databaseName },
1247
1266
  });
1248
1267
  }
1249
- // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1250
- 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];
1251
1271
  const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1252
1272
  for (const configuredPort of configuredPorts) {
1253
1273
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
@@ -1257,7 +1277,7 @@ export class HostRuntimeLeaseManager {
1257
1277
  };
1258
1278
  const prebuild = createAspNetRuntimePrebuildPlan({
1259
1279
  command: configuredPort.launch.command,
1260
- args: configuredPort.launch.args,
1280
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1261
1281
  cwd: workingDirectory,
1262
1282
  worktreePath: active.lease.worktreePath,
1263
1283
  environment: buildEnvironment,
@@ -1268,7 +1288,7 @@ export class HostRuntimeLeaseManager {
1268
1288
  await onProjectCheckpoint?.({
1269
1289
  code: "host_runtime_build_started",
1270
1290
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1271
- 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 },
1272
1292
  });
1273
1293
  let hostLoadWaitMs = null;
1274
1294
  const build = await ensureAspNetRuntimePrebuilt(prebuild,
@@ -1308,11 +1328,9 @@ export class HostRuntimeLeaseManager {
1308
1328
  }
1309
1329
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1310
1330
  command: configuredPort.launch.command,
1311
- args: configuredPort.launch.args,
1331
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1312
1332
  cwd: workingDirectory,
1313
- environment: {
1314
- ...buildEnvironment,
1315
- },
1333
+ environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1316
1334
  }, launcher, signal);
1317
1335
  }
1318
1336
  const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
@@ -1389,12 +1407,13 @@ export class HostRuntimeLeaseManager {
1389
1407
  }
1390
1408
  }
1391
1409
  async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1392
- // The relaunch reuses the contract (commands, ports, environment, concurrency) admitted at
1393
- // start. If the workspace now declares a different one, a restart would run stale settings;
1394
- // the attempt fails retryably instead, so a fresh attempt admits the new contract.
1395
- const currentContract = await loadHostRuntimeContract(active.lease.worktreePath);
1396
- if (hostRuntimeContractFingerprint(currentContract) !== active.runtimeContractFingerprint) {
1397
- throw new ForgeFailureError("host_runtime_contract_changed", "host_runtime_contract_changed: the workspace's runtime contract changed after this attempt's runtime was admitted; a fresh attempt is needed to run it.");
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." });
1398
1417
  }
1399
1418
  const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1400
1419
  const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
@@ -1604,10 +1623,14 @@ export class HostRuntimeLeaseManager {
1604
1623
  await restart.promise.catch(() => undefined);
1605
1624
  }
1606
1625
  await active.databaseProvision?.catch(() => undefined);
1607
- let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1608
- active.lease = releasing;
1609
- 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;
1610
1630
  try {
1631
+ releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1632
+ active.lease = releasing;
1633
+ await this.writeLedger(releasing);
1611
1634
  if (!active.runtimeResourcesReleased) {
1612
1635
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1613
1636
  // The attempt's MCP servers and process trees are stopped now; tokens they held
@@ -1663,13 +1686,12 @@ export class HostRuntimeLeaseManager {
1663
1686
  if (!evidenceRetainedAtAttemptRoot) {
1664
1687
  await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1665
1688
  }
1666
- releasing = released;
1667
1689
  this.active.delete(dispatchAttemptId);
1668
1690
  this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1669
1691
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1670
1692
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1671
1693
  this.deleteAdmission(dispatchAttemptId, fencingToken);
1672
- return releasing;
1694
+ return released;
1673
1695
  }
1674
1696
  catch (error) {
1675
1697
  const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
@@ -1704,66 +1726,12 @@ export class HostRuntimeLeaseManager {
1704
1726
  }
1705
1727
  return ledgers;
1706
1728
  }
1707
- async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
1708
- const logsRoot = path.join(attemptRoot, "logs");
1709
- const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
1710
- if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
1711
- throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
1712
- }
1713
- await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
1714
- const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
1715
- const logsEntry = rootEntries.find(entry => entry.name === "logs");
1716
- if (!logsEntry)
1717
- return [];
1718
- if (logsEntry.kind !== "directory") {
1719
- throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1720
- }
1721
- const outcomes = [];
1722
- const failures = [];
1723
- try {
1724
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1725
- for (const entry of entries) {
1726
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1727
- continue;
1728
- const metadataPath = path.join(logsRoot, entry.name);
1729
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1730
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1731
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1732
- }
1733
- outcomes.push(await this.processRecovery.recover(value));
1734
- }
1735
- }
1736
- catch (error) {
1737
- failures.push(error);
1738
- }
1739
- // Managed commands run in their own process groups and record their ownership apart
1740
- // from the attempt's supervised children. They are recovered even when recovering a
1741
- // supervised child failed, and both failures are reported together.
1742
- try {
1743
- const managed = await terminateAttemptManagedCommands({
1744
- logDirectory: logsRoot,
1745
- dispatchAttemptId: lease.dispatchAttemptId,
1746
- runtimeLeaseId: lease.executionLeaseId,
1747
- pinnedLogDirectory: logsEntry.identity,
1748
- }, { reason: "attempt_teardown" });
1749
- for (const command of managed) {
1750
- if (command.outcome === "terminated" || command.outcome === "pid_reused")
1751
- outcomes.push(command.outcome);
1752
- }
1753
- }
1754
- catch (error) {
1755
- failures.push(error);
1756
- }
1757
- if (failures.length === 1)
1758
- throw failures[0];
1759
- if (failures.length > 1)
1760
- throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1761
- return outcomes;
1762
- }
1763
- 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) {
1764
1731
  const lease = ledger.runtimeLease;
1765
1732
  if (lease.state === "released")
1766
1733
  return;
1734
+ report.degraded += 1;
1767
1735
  const degraded = transitionHostLeaseForCleanup(lease, "degraded");
1768
1736
  const repoId = ledger.repoId ?? repoIdFromProjectSingletonKeys(lease.resources.singletonKeys);
1769
1737
  this.rememberDegraded(degraded, repoId);
@@ -1832,7 +1800,7 @@ export class HostRuntimeLeaseManager {
1832
1800
  finally {
1833
1801
  await handle.close();
1834
1802
  }
1835
- await fs.rename(temporary, target);
1803
+ await replaceHostRuntimeLedgerFile(temporary, target);
1836
1804
  }
1837
1805
  catch (error) {
1838
1806
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -2344,51 +2312,13 @@ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2344
2312
  }
2345
2313
  return [...keys];
2346
2314
  }
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();
2318
+ }
2347
2319
  function anySignal(...signals) {
2348
2320
  return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2349
2321
  }
2350
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
2351
- /** Once the build's supervised tree is up: records it on the build's host load token. */
2352
- onStarted) {
2353
- const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2354
- const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2355
- const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2356
- let stdoutTail = "";
2357
- let stderrTail = "";
2358
- const append = async (target, line) => {
2359
- await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2360
- };
2361
- const child = await supervisor.startChildReady(childName, {
2362
- command: plan.command,
2363
- args: plan.args,
2364
- cwd: plan.cwd,
2365
- env: plan.environment,
2366
- captureOutput: false,
2367
- }, {
2368
- onStdoutLine: async (line) => {
2369
- stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2370
- await append(stdoutLogPath, line);
2371
- },
2372
- onStderrLine: async (line) => {
2373
- stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2374
- await append(stderrLogPath, line);
2375
- },
2376
- }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2377
- await onStarted?.(child.metadataPath);
2378
- const result = await child.result;
2379
- return {
2380
- exitCode: result.exitCode,
2381
- stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2382
- stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2383
- stdoutLogPath,
2384
- stderrLogPath,
2385
- };
2386
- }
2387
- function appendRuntimeBuildTail(current, value) {
2388
- if (!value)
2389
- return current;
2390
- return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
2391
- }
2392
2322
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
2393
2323
  if (executionClass === "analysis_only") {
2394
2324
  const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
@@ -2489,6 +2419,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
2489
2419
  const parsed = Number.parseInt(process.env[name] ?? "", 10);
2490
2420
  return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2491
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
+ }
2492
2434
  function loadHostCapacityConfiguration(capacityResourceSample) {
2493
2435
  const sampledCpuCount = capacityResourceSample
2494
2436
  ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
@@ -2496,23 +2438,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
2496
2438
  const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2497
2439
  const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2498
2440
  const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
2499
- const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2500
- explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2441
+ const adaptiveOptions = {
2501
2442
  floorBytes: reserveFloorBytes,
2502
2443
  ceilingBytes: reserveCeilingBytes,
2503
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),
2504
2449
  });
2505
- 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;
2506
2453
  return {
2507
- 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),
2508
2455
  hostReserveBytes,
2509
- 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,
2510
2461
  cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2511
2462
  workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2512
2463
  memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2513
2464
  memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2514
2465
  };
2515
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
+ }
2516
2476
  function configuredOptionalInteger(name, minimum, maximum) {
2517
2477
  const raw = process.env[name];
2518
2478
  if (raw === undefined || raw.trim().length === 0)
@@ -2665,30 +2625,6 @@ function deserializeHostAttemptRootIdentity(identity) {
2665
2625
  ? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
2666
2626
  : null;
2667
2627
  }
2668
- function validHostProcessSupervisorMetadata(value, lease) {
2669
- if (typeof value !== "object" || value === null)
2670
- return false;
2671
- const metadata = value;
2672
- return metadata.schemaVersion === 1
2673
- && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
2674
- && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
2675
- && Number.isSafeInteger(metadata.rootPid)
2676
- && metadata.rootPid > 0
2677
- && Number.isFinite(Date.parse(metadata.rootCreatedAt))
2678
- && (metadata.rootIdentity == null
2679
- || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
2680
- && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
2681
- && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
2682
- && metadata.runtimeLeaseId === lease.executionLeaseId
2683
- && metadata.dispatchAttemptId === lease.dispatchAttemptId
2684
- && metadata.fencingToken === lease.fencingToken
2685
- && Number.isSafeInteger(metadata.bridgePid)
2686
- && metadata.bridgePid > 0;
2687
- }
2688
- function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
2689
- const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
2690
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2691
- }
2692
2628
  function transitionHostLeaseForCleanup(lease, state) {
2693
2629
  if (lease.state === state || lease.state === "released")
2694
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[]>;
@@ -0,0 +1,134 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { readCanonicalSourceFile } from "./canonical-source-file.js";
4
+ import { assertHostAttemptRootIdentity } from "./host-diagnostics.js";
5
+ import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
6
+ import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
7
+ // Host runtime ledger persistence and recovery helpers shared by HostRuntimeLeaseManager.
8
+ const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
9
+ const ledgerReplaceAttempts = 40;
10
+ const transientLedgerReplaceCodes = new Set(["EPERM", "EACCES", "EBUSY"]);
11
+ /**
12
+ * Replaces a host runtime ledger with its fully written temporary file. Windows refuses
13
+ * to replace a file another handle has open (EPERM), for example while a recovery pass
14
+ * reads the same ledger, so a transient refusal is retried for about a second, as the
15
+ * attempt supervisor does for its own ledger.
16
+ */
17
+ export async function replaceHostRuntimeLedgerFile(temporary, target, retryMs = 25) {
18
+ for (let attempt = 1;; attempt += 1) {
19
+ try {
20
+ await fs.rename(temporary, target);
21
+ return;
22
+ }
23
+ catch (error) {
24
+ const code = error.code;
25
+ if (attempt >= ledgerReplaceAttempts || !code || !transientLedgerReplaceCodes.has(code))
26
+ throw error;
27
+ await new Promise(resolve => setTimeout(resolve, retryMs));
28
+ }
29
+ }
30
+ }
31
+ /**
32
+ * Maintenance retry of a degraded lease's fenced release. The release frees the slot only
33
+ * after its teardown proves the attempt's supervised process tree stopped (the supervisor
34
+ * is stopped with no live child or managed command); otherwise the lease stays degraded
35
+ * and the log says why. Returns whether the lease was released.
36
+ */
37
+ export async function retryDegradedHostRelease(lease, release, log) {
38
+ const subject = `host runtime lease ${lease.leaseId} of attempt ${lease.dispatchAttemptId}`;
39
+ try {
40
+ const released = await release();
41
+ if (released?.state === "released") {
42
+ log(`Released degraded ${subject}: teardown proved its supervised process tree stopped, so its project runtime slot is free.`);
43
+ return true;
44
+ }
45
+ log(`Degraded ${subject} stays degraded: its fencing token no longer owns the attempt.`);
46
+ }
47
+ catch (error) {
48
+ log(`Degraded ${subject} stays degraded: ${error instanceof Error ? error.message : String(error)}`);
49
+ }
50
+ return false;
51
+ }
52
+ export function logHostRuntimeStatus(message) {
53
+ process.stderr.write(`[${new Date().toISOString()}] ${message}\n`);
54
+ }
55
+ /** Exact, fenced recovery of the process trees a lease's attempt recorded under its attempt root. */
56
+ export async function recoverPersistedHostProcesses(lease, attemptRoot, expectedAttemptRoot, attemptRootIdentity, processRecovery) {
57
+ const logsRoot = path.join(attemptRoot, "logs");
58
+ if (path.resolve(attemptRoot) !== path.resolve(expectedAttemptRoot)) {
59
+ throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
60
+ }
61
+ await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
62
+ const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
63
+ const logsEntry = rootEntries.find(entry => entry.name === "logs");
64
+ if (!logsEntry)
65
+ return [];
66
+ if (logsEntry.kind !== "directory") {
67
+ throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
68
+ }
69
+ const outcomes = [];
70
+ const failures = [];
71
+ try {
72
+ const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
73
+ for (const entry of entries) {
74
+ if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
75
+ continue;
76
+ const metadataPath = path.join(logsRoot, entry.name);
77
+ const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
78
+ if (!validHostProcessSupervisorMetadata(value, lease)) {
79
+ throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
80
+ }
81
+ outcomes.push(await processRecovery.recover(value));
82
+ }
83
+ }
84
+ catch (error) {
85
+ failures.push(error);
86
+ }
87
+ // Managed commands run in their own process groups and record their ownership apart
88
+ // from the attempt's supervised children. They are recovered even when recovering a
89
+ // supervised child failed, and both failures are reported together.
90
+ try {
91
+ const managed = await terminateAttemptManagedCommands({
92
+ logDirectory: logsRoot,
93
+ dispatchAttemptId: lease.dispatchAttemptId,
94
+ runtimeLeaseId: lease.executionLeaseId,
95
+ pinnedLogDirectory: logsEntry.identity,
96
+ }, { reason: "attempt_teardown" });
97
+ for (const command of managed) {
98
+ if (command.outcome === "terminated" || command.outcome === "pid_reused")
99
+ outcomes.push(command.outcome);
100
+ }
101
+ }
102
+ catch (error) {
103
+ failures.push(error);
104
+ }
105
+ if (failures.length === 1)
106
+ throw failures[0];
107
+ if (failures.length > 1)
108
+ throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
109
+ return outcomes;
110
+ }
111
+ function validHostProcessSupervisorMetadata(value, lease) {
112
+ if (typeof value !== "object" || value === null)
113
+ return false;
114
+ const metadata = value;
115
+ return metadata.schemaVersion === 1
116
+ && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
117
+ && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
118
+ && Number.isSafeInteger(metadata.rootPid)
119
+ && metadata.rootPid > 0
120
+ && Number.isFinite(Date.parse(metadata.rootCreatedAt))
121
+ && (metadata.rootIdentity == null
122
+ || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
123
+ && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
124
+ && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
125
+ && metadata.runtimeLeaseId === lease.executionLeaseId
126
+ && metadata.dispatchAttemptId === lease.dispatchAttemptId
127
+ && metadata.fencingToken === lease.fencingToken
128
+ && Number.isSafeInteger(metadata.bridgePid)
129
+ && metadata.bridgePid > 0;
130
+ }
131
+ function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
132
+ const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
133
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
134
+ }