@loucompanion/forge-bridge 0.1.4-dev.6b2148ecc60c → 0.1.4-dev.724427ea7be8

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 (163) hide show
  1. package/README.md +87 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +5 -2
  3. package/dist/bridge/bridge-chat-provider-command.js +29 -22
  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.service.d.ts +16 -12
  15. package/dist/bridge/bridge.service.js +131 -243
  16. package/dist/bridge/bridge.types.d.ts +5 -0
  17. package/dist/bridge/in-flight-registry.d.ts +62 -0
  18. package/dist/bridge/in-flight-registry.js +207 -0
  19. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  20. package/dist/bridge/readiness-result-outbox.js +20 -0
  21. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  22. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  23. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  24. package/dist/cleanup/cleanup-wip.js +66 -0
  25. package/dist/cleanup/cleanup.service.d.ts +11 -1
  26. package/dist/cleanup/cleanup.service.js +80 -62
  27. package/dist/cleanup/cleanup.types.d.ts +2 -0
  28. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  29. package/dist/cleanup/host-runtime-ledger.js +30 -9
  30. package/dist/cli/cli.help.js +56 -12
  31. package/dist/cli/cli.service.d.ts +3 -10
  32. package/dist/cli/cli.service.js +10 -171
  33. package/dist/cli/idle-status.d.ts +84 -0
  34. package/dist/cli/idle-status.js +181 -0
  35. package/dist/cli/local-config.d.ts +2 -0
  36. package/dist/cli/local-config.js +7 -1
  37. package/dist/cli/provider-cli-detection.d.ts +10 -0
  38. package/dist/cli/provider-cli-detection.js +160 -0
  39. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  40. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  41. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  42. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  43. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  44. package/dist/runtime/attempt-process-supervisor.js +12 -6
  45. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  46. package/dist/runtime/docker-engine-probe.js +7 -0
  47. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  48. package/dist/runtime/dotnet-build-outputs.js +402 -0
  49. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  50. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  51. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  52. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  53. package/dist/runtime/host-load-governor.d.ts +2 -0
  54. package/dist/runtime/host-load-ledger-lock.js +6 -4
  55. package/dist/runtime/host-load-runtime-settings.js +4 -2
  56. package/dist/runtime/host-load-sampler.d.ts +8 -1
  57. package/dist/runtime/host-load-sampler.js +14 -7
  58. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  59. package/dist/runtime/host-runtime-contract.js +29 -1
  60. package/dist/runtime/host-runtime-lease.d.ts +2 -1
  61. package/dist/runtime/host-runtime-lease.js +30 -153
  62. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  63. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  64. package/dist/runtime/managed-command-teardown.js +5 -16
  65. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  66. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  67. package/dist/runtime/runner-settings.d.ts +4 -0
  68. package/dist/runtime/runner-settings.js +22 -0
  69. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  70. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  71. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  72. package/dist/sandbox/host-capacity-broker.js +4 -2
  73. package/dist/sandbox/managed-branch.d.ts +13 -0
  74. package/dist/sandbox/managed-branch.js +90 -0
  75. package/dist/sandbox/provider-auth/codex.js +11 -11
  76. package/dist/sandbox/runtime.js +2 -6
  77. package/dist/session/architect-waits.d.ts +2 -0
  78. package/dist/session/architect-waits.js +138 -0
  79. package/dist/session/managed-attempt-tools.d.ts +0 -7
  80. package/dist/session/managed-attempt-tools.js +50 -82
  81. package/dist/session/managed-build-coordinator.d.ts +16 -0
  82. package/dist/session/managed-build-coordinator.js +10 -0
  83. package/dist/session/managed-build-receipt.d.ts +5 -0
  84. package/dist/session/managed-build-receipt.js +8 -3
  85. package/dist/session/phase-completion.artifacts.js +2 -1
  86. package/dist/session/phase-completion.d.ts +8 -0
  87. package/dist/session/phase-completion.js +1 -0
  88. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  89. package/dist/session/phase-completion.mcp-args.js +156 -0
  90. package/dist/session/phase-completion.runtime.d.ts +0 -8
  91. package/dist/session/phase-completion.runtime.js +43 -197
  92. package/dist/session/phase-completion.schemas.js +3 -11
  93. package/dist/session/phase-completion.validation.js +3 -1
  94. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  95. package/dist/session/pre-publication-native-postgres.js +111 -0
  96. package/dist/session/pre-publication-process.js +10 -10
  97. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  98. package/dist/session/pre-publication-step-execution.js +6 -5
  99. package/dist/session/pre-publication-validation.d.ts +7 -3
  100. package/dist/session/pre-publication-validation.js +32 -30
  101. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  102. package/dist/session/provider-cli/claude-background-work.js +4 -3
  103. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  104. package/dist/session/provider-cli/host-build-lock.js +30 -0
  105. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  106. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  107. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  108. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  109. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  110. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  111. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  112. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  113. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  115. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  116. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  117. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  118. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  119. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  120. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  121. package/dist/session/qa-sidecar-validation.js +28 -0
  122. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  123. package/dist/session/sandbox-host-capacity-gate.js +34 -15
  124. package/dist/session/session-redaction.js +31 -181
  125. package/dist/session/session.service.d.ts +2 -0
  126. package/dist/session/session.service.js +69 -64
  127. package/dist/session/session.types.js +1 -1
  128. package/dist/session/sidecar-json-shape.d.ts +31 -0
  129. package/dist/session/sidecar-json-shape.js +217 -0
  130. package/dist/shared/fs/file-identity.d.ts +10 -0
  131. package/dist/shared/fs/file-identity.js +15 -0
  132. package/dist/shared/fs/replace-file.d.ts +7 -0
  133. package/dist/shared/fs/replace-file.js +33 -0
  134. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  135. package/dist/shared/process/host-process-recovery.js +23 -3
  136. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  137. package/dist/shared/process/host-process-supervisor.js +66 -14
  138. package/dist/shared/provider-capabilities.js +9 -1
  139. package/dist/version.d.ts +1 -1
  140. package/dist/version.js +1 -1
  141. package/dist/worktree/orphan-relink.d.ts +19 -0
  142. package/dist/worktree/orphan-relink.js +106 -0
  143. package/dist/worktree/wip-git.d.ts +33 -0
  144. package/dist/worktree/wip-git.js +122 -0
  145. package/dist/worktree/wip-refs.d.ts +62 -0
  146. package/dist/worktree/wip-refs.js +119 -0
  147. package/dist/worktree/wip-restore.d.ts +38 -0
  148. package/dist/worktree/wip-restore.js +190 -0
  149. package/dist/worktree/wip-snapshot.d.ts +50 -0
  150. package/dist/worktree/wip-snapshot.js +268 -0
  151. package/dist/worktree/worktree-inputs.d.ts +8 -0
  152. package/dist/worktree/worktree-inputs.js +134 -0
  153. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  154. package/dist/worktree/worktree-origin-sync.js +127 -0
  155. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  156. package/dist/worktree/worktree-wip-events.js +98 -0
  157. package/dist/worktree/worktree-wip.d.ts +50 -0
  158. package/dist/worktree/worktree-wip.js +185 -0
  159. package/dist/worktree/worktree.base.d.ts +7 -1
  160. package/dist/worktree/worktree.service.d.ts +27 -5
  161. package/dist/worktree/worktree.service.js +110 -181
  162. package/dist/worktree/worktree.types.d.ts +31 -0
  163. package/package.json +1 -1
@@ -10,14 +10,12 @@ 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";
@@ -27,17 +25,15 @@ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContr
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;
@@ -163,19 +159,16 @@ export class HostRuntimeLeaseManager {
163
159
  }
164
160
  const active = this.active.get(lease.dispatchAttemptId);
165
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.
166
164
  if (active.lease.state !== "degraded")
167
165
  continue;
168
166
  report.examined += 1;
169
- try {
170
- const released = await this.release(lease.dispatchAttemptId, lease.fencingToken);
171
- if (released?.state === "released")
172
- report.reaped += 1;
173
- else
174
- report.degraded += 1;
175
- }
176
- 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
177
171
  report.degraded += 1;
178
- }
179
172
  continue;
180
173
  }
181
174
  const staleInstance = lease.runnerInstanceId !== options.runnerInstanceId;
@@ -190,7 +183,7 @@ export class HostRuntimeLeaseManager {
190
183
  if (!attemptRootIdentity) {
191
184
  throw new Error("host_runtime_reaper_invalid: original attempt-root identity is unavailable.");
192
185
  }
193
- outcomes = await this.recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity);
186
+ outcomes = await recoverPersistedHostProcesses(lease, attemptRoot, this.attemptRoot(lease.dispatchAttemptId), attemptRootIdentity, this.processRecovery);
194
187
  }
195
188
  catch {
196
189
  await this.markLedgerDegraded(ledger);
@@ -1275,8 +1268,9 @@ export class HostRuntimeLeaseManager {
1275
1268
  data: { database: active.databaseCapability.databaseName },
1276
1269
  });
1277
1270
  }
1278
- // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1279
- const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1271
+ const apiMasterKey = attemptApiMasterKey(active);
1272
+ // Runtime output is persisted to attempt logs; the database login and master key it may print are redacted.
1273
+ const capabilitySecrets = [...attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString), apiMasterKey];
1280
1274
  const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1281
1275
  for (const configuredPort of configuredPorts) {
1282
1276
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
@@ -1286,7 +1280,7 @@ export class HostRuntimeLeaseManager {
1286
1280
  };
1287
1281
  const prebuild = createAspNetRuntimePrebuildPlan({
1288
1282
  command: configuredPort.launch.command,
1289
- args: configuredPort.launch.args,
1283
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1290
1284
  cwd: workingDirectory,
1291
1285
  worktreePath: active.lease.worktreePath,
1292
1286
  environment: buildEnvironment,
@@ -1297,7 +1291,7 @@ export class HostRuntimeLeaseManager {
1297
1291
  await onProjectCheckpoint?.({
1298
1292
  code: "host_runtime_build_started",
1299
1293
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1300
- data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1294
+ data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath, output_directory: prebuild.outputDirectory },
1301
1295
  });
1302
1296
  let hostLoadWaitMs = null;
1303
1297
  const build = await ensureAspNetRuntimePrebuilt(prebuild,
@@ -1337,11 +1331,9 @@ export class HostRuntimeLeaseManager {
1337
1331
  }
1338
1332
  await this.launchNodeRuntime(dispatchAttemptId, fencingToken, configuredPort.name, {
1339
1333
  command: configuredPort.launch.command,
1340
- args: configuredPort.launch.args,
1334
+ args: supervisedRuntimeLaunchArguments(configuredPort),
1341
1335
  cwd: workingDirectory,
1342
- environment: {
1343
- ...buildEnvironment,
1344
- },
1336
+ environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1345
1337
  }, launcher, signal);
1346
1338
  }
1347
1339
  const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
@@ -1634,10 +1626,14 @@ export class HostRuntimeLeaseManager {
1634
1626
  await restart.promise.catch(() => undefined);
1635
1627
  }
1636
1628
  await active.databaseProvision?.catch(() => undefined);
1637
- let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1638
- active.lease = releasing;
1639
- await this.writeLedger(releasing);
1629
+ // The releasing write is part of the fenced teardown: when it fails (Windows can refuse
1630
+ // to replace a ledger another handle is reading), the lease must end degraded so
1631
+ // maintenance retries it, never left nonterminal in memory where nothing retries it.
1632
+ let releasing = active.lease;
1640
1633
  try {
1634
+ releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1635
+ active.lease = releasing;
1636
+ await this.writeLedger(releasing);
1641
1637
  if (!active.runtimeResourcesReleased) {
1642
1638
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1643
1639
  // The attempt's MCP servers and process trees are stopped now; tokens they held
@@ -1693,13 +1689,12 @@ export class HostRuntimeLeaseManager {
1693
1689
  if (!evidenceRetainedAtAttemptRoot) {
1694
1690
  await fs.rm(this.ledgerPath(dispatchAttemptId), { force: true });
1695
1691
  }
1696
- releasing = released;
1697
1692
  this.active.delete(dispatchAttemptId);
1698
1693
  this.processSupervisors.unregister(dispatchAttemptId, fencingToken);
1699
1694
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1700
1695
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
1701
1696
  this.deleteAdmission(dispatchAttemptId, fencingToken);
1702
- return releasing;
1697
+ return released;
1703
1698
  }
1704
1699
  catch (error) {
1705
1700
  const degraded = transitionRuntimeIsolationLease(releasing, "degraded");
@@ -1734,62 +1729,6 @@ export class HostRuntimeLeaseManager {
1734
1729
  }
1735
1730
  return ledgers;
1736
1731
  }
1737
- async recoverPersistedProcesses(lease, attemptRoot, attemptRootIdentity) {
1738
- const logsRoot = path.join(attemptRoot, "logs");
1739
- const expectedAttemptRoot = path.resolve(this.attemptRoot(lease.dispatchAttemptId));
1740
- if (path.resolve(attemptRoot) !== expectedAttemptRoot) {
1741
- throw new Error("host_runtime_reaper_invalid: attempt path is outside the fenced attempt root.");
1742
- }
1743
- await assertHostAttemptRootIdentity(attemptRoot, attemptRootIdentity);
1744
- const rootEntries = await readPinnedSourceDirectory(attemptRoot, attemptRootIdentity);
1745
- const logsEntry = rootEntries.find(entry => entry.name === "logs");
1746
- if (!logsEntry)
1747
- return [];
1748
- if (logsEntry.kind !== "directory") {
1749
- throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1750
- }
1751
- const outcomes = [];
1752
- const failures = [];
1753
- try {
1754
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1755
- for (const entry of entries) {
1756
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1757
- continue;
1758
- const metadataPath = path.join(logsRoot, entry.name);
1759
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1760
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1761
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1762
- }
1763
- outcomes.push(await this.processRecovery.recover(value));
1764
- }
1765
- }
1766
- catch (error) {
1767
- failures.push(error);
1768
- }
1769
- // Managed commands run in their own process groups and record their ownership apart
1770
- // from the attempt's supervised children. They are recovered even when recovering a
1771
- // supervised child failed, and both failures are reported together.
1772
- try {
1773
- const managed = await terminateAttemptManagedCommands({
1774
- logDirectory: logsRoot,
1775
- dispatchAttemptId: lease.dispatchAttemptId,
1776
- runtimeLeaseId: lease.executionLeaseId,
1777
- pinnedLogDirectory: logsEntry.identity,
1778
- }, { reason: "attempt_teardown" });
1779
- for (const command of managed) {
1780
- if (command.outcome === "terminated" || command.outcome === "pid_reused")
1781
- outcomes.push(command.outcome);
1782
- }
1783
- }
1784
- catch (error) {
1785
- failures.push(error);
1786
- }
1787
- if (failures.length === 1)
1788
- throw failures[0];
1789
- if (failures.length > 1)
1790
- throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1791
- return outcomes;
1792
- }
1793
1732
  async markLedgerDegraded(ledger) {
1794
1733
  const lease = ledger.runtimeLease;
1795
1734
  if (lease.state === "released")
@@ -1862,7 +1801,7 @@ export class HostRuntimeLeaseManager {
1862
1801
  finally {
1863
1802
  await handle.close();
1864
1803
  }
1865
- await fs.rename(temporary, target);
1804
+ await replaceHostRuntimeLedgerFile(temporary, target);
1866
1805
  }
1867
1806
  catch (error) {
1868
1807
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -2374,51 +2313,13 @@ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2374
2313
  }
2375
2314
  return [...keys];
2376
2315
  }
2316
+ /** The attempt's API master key: issued on first use, then the same for every relaunch of the attempt. */
2317
+ function attemptApiMasterKey(active) {
2318
+ return active.apiMasterKey ??= newAttemptApiMasterKey();
2319
+ }
2377
2320
  function anySignal(...signals) {
2378
2321
  return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2379
2322
  }
2380
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
2381
- /** Once the build's supervised tree is up: records it on the build's host load token. */
2382
- onStarted) {
2383
- const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2384
- const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2385
- const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2386
- let stdoutTail = "";
2387
- let stderrTail = "";
2388
- const append = async (target, line) => {
2389
- await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2390
- };
2391
- const child = await supervisor.startChildReady(childName, {
2392
- command: plan.command,
2393
- args: plan.args,
2394
- cwd: plan.cwd,
2395
- env: plan.environment,
2396
- captureOutput: false,
2397
- }, {
2398
- onStdoutLine: async (line) => {
2399
- stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2400
- await append(stdoutLogPath, line);
2401
- },
2402
- onStderrLine: async (line) => {
2403
- stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2404
- await append(stderrLogPath, line);
2405
- },
2406
- }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2407
- await onStarted?.(child.metadataPath);
2408
- const result = await child.result;
2409
- return {
2410
- exitCode: result.exitCode,
2411
- stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2412
- stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2413
- stdoutLogPath,
2414
- stderrLogPath,
2415
- };
2416
- }
2417
- function appendRuntimeBuildTail(current, value) {
2418
- if (!value)
2419
- return current;
2420
- return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
2421
- }
2422
2323
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
2423
2324
  if (executionClass === "analysis_only") {
2424
2325
  const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
@@ -2725,30 +2626,6 @@ function deserializeHostAttemptRootIdentity(identity) {
2725
2626
  ? { dev: BigInt(identity.dev), ino: BigInt(identity.ino) }
2726
2627
  : null;
2727
2628
  }
2728
- function validHostProcessSupervisorMetadata(value, lease) {
2729
- if (typeof value !== "object" || value === null)
2730
- return false;
2731
- const metadata = value;
2732
- return metadata.schemaVersion === 1
2733
- && /^host-[0-9a-f]{32}$/u.test(metadata.supervisorId)
2734
- && (metadata.strategy === "windows_job_object" || metadata.strategy === "unix_process_group")
2735
- && Number.isSafeInteger(metadata.rootPid)
2736
- && metadata.rootPid > 0
2737
- && Number.isFinite(Date.parse(metadata.rootCreatedAt))
2738
- && (metadata.rootIdentity == null
2739
- || (typeof metadata.rootIdentity === "string" && metadata.rootIdentity.length <= 256))
2740
- && /^[0-9a-f]{64}$/u.test(metadata.commandDigest)
2741
- && containedMetadataWorktreePath(lease.worktreePath, metadata.worktreePath)
2742
- && metadata.runtimeLeaseId === lease.executionLeaseId
2743
- && metadata.dispatchAttemptId === lease.dispatchAttemptId
2744
- && metadata.fencingToken === lease.fencingToken
2745
- && Number.isSafeInteger(metadata.bridgePid)
2746
- && metadata.bridgePid > 0;
2747
- }
2748
- function containedMetadataWorktreePath(worktreePath, metadataWorktreePath) {
2749
- const relative = path.relative(path.resolve(worktreePath), path.resolve(metadataWorktreePath));
2750
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2751
- }
2752
2629
  function transitionHostLeaseForCleanup(lease, state) {
2753
2630
  if (lease.state === state || lease.state === "released")
2754
2631
  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
+ }
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { readCanonicalSourceFile } from "./canonical-source-file.js";
5
5
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
6
+ import { replaceFile } from "../shared/fs/replace-file.js";
6
7
  import { ExactHostProcessRecovery } from "../shared/process/host-process-recovery.js";
7
8
  import { captureHostProcessIdentity, } from "../shared/process/host-process-supervisor.js";
8
9
  import { monotonicNowMs } from "../shared/time/monotonic.js";
@@ -14,8 +15,7 @@ const maximumReceiptBytes = 16 * 1024 * 1024;
14
15
  const maximumCapturedCharacters = 200_000;
15
16
  const defaultGraceMs = 2_000;
16
17
  const receiptReadAttempts = 5;
17
- const receiptReplaceAttempts = 40;
18
- const receiptReplaceRetryMs = 25;
18
+ const receiptReadRetryMs = 25;
19
19
  const invalidMetadata = Symbol("invalid managed-command metadata");
20
20
  let procRoot = "/proc";
21
21
  /** Test support: points the Linux process inventory at another directory (null restores /proc). */
@@ -363,7 +363,7 @@ async function readReceipt(store, name) {
363
363
  }
364
364
  catch {
365
365
  if (attempt < receiptReadAttempts)
366
- await delay(receiptReplaceRetryMs);
366
+ await delay(receiptReadRetryMs);
367
367
  }
368
368
  }
369
369
  return null;
@@ -462,19 +462,8 @@ async function persistReceipt(receiptPath, receipt) {
462
462
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
463
463
  try {
464
464
  await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
465
- for (let attempt = 1;; attempt += 1) {
466
- try {
467
- await fs.rename(temporaryPath, receiptPath);
468
- return;
469
- }
470
- catch (error) {
471
- const code = error.code;
472
- // Windows refuses to replace a file another process briefly holds open.
473
- if (attempt >= receiptReplaceAttempts || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES"))
474
- throw error;
475
- await delay(receiptReplaceRetryMs);
476
- }
477
- }
465
+ // Windows refuses to replace a file another process briefly holds open.
466
+ await replaceFile(temporaryPath, receiptPath);
478
467
  }
479
468
  finally {
480
469
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
@@ -2,15 +2,51 @@ export declare const nativeTestPostgresFallbackConfigEnvironment = "FORGE_NATIVE
2
2
  export declare const nativeTestPostgresFallbackFileName = "native-test-postgres.json";
3
3
  export declare const nativeTestPostgresFallbackDatabaseMode = "native_fallback";
4
4
  /**
5
- * A dedicated, operator-provisioned PostgreSQL cluster that runner-authored .NET
6
- * test tiers may use only while the Docker engine is unavailable. The cluster
7
- * must hold nothing but disposable test databases, so its capability carries no
8
- * more authority than the attempt-private container it replaces.
5
+ * The cluster serves the shared test server while Docker is up, so tests that need a
6
+ * pinned engine container still start one. Owner policy (2026-11-16): native PostgreSQL
7
+ * first, which keeps test databases out of the Docker VM and saves RAM.
8
+ */
9
+ export declare const nativeTestPostgresPreferredDatabaseMode = "native_preferred";
10
+ export type NativeTestPostgresDatabaseMode = typeof nativeTestPostgresFallbackDatabaseMode | typeof nativeTestPostgresPreferredDatabaseMode;
11
+ /**
12
+ * What runner-authored .NET test tiers get: `preferred` (the default) the provisioned
13
+ * cluster whenever it is configured; `docker_unavailable` that cluster only after a
14
+ * Docker probe fails; `ephemeral` a throwaway cluster of their own for each check, whose
15
+ * bootstrap superuser they hold (owner policy 2026-11-17). The provisioned cluster still
16
+ * hosts the attempt database broker in every mode.
17
+ */
18
+ export type NativeTestPostgresUse = "preferred" | "docker_unavailable" | "ephemeral";
19
+ /**
20
+ * A dedicated, operator-provisioned PostgreSQL cluster for runner-authored .NET
21
+ * test tiers, preferred over Docker unless its file says `docker_unavailable`.
22
+ * The cluster must hold nothing but disposable test databases, so its capability
23
+ * carries no more authority than the attempt-private container it replaces.
9
24
  */
10
25
  export interface NativeTestPostgresFallback {
11
26
  readonly connectionString: string;
12
27
  readonly endpoint: string;
28
+ readonly use: NativeTestPostgresUse;
29
+ /** The PostgreSQL bin directory an ephemeral cluster runs from; defaults to the one beside psql. */
30
+ readonly postgresBin?: string;
13
31
  }
32
+ /** The cluster as handed to one test process, with the mode its fixtures run in. */
33
+ export interface NativeTestPostgresGrant {
34
+ readonly connectionString: string;
35
+ readonly endpoint: string;
36
+ readonly mode: NativeTestPostgresDatabaseMode;
37
+ /** Set when the grant is a throwaway cluster of its own; the server reports it as `forge.ephemeral_cluster`. */
38
+ readonly ephemeralClusterId?: string;
39
+ /** Stops and deletes an ephemeral cluster once its check has finished. */
40
+ readonly release?: () => Promise<void>;
41
+ }
42
+ /**
43
+ * The provisioned cluster's grant for a check that can use it, or null to use Docker. A
44
+ * preferred cluster is granted whether or not Docker is up; the mode says which, because
45
+ * only the fallback mode excludes Docker for pinned-engine tests. An `ephemeral` host
46
+ * normally gets its own cluster instead (ephemeral-test-postgres-grant.ts); if that cannot
47
+ * start, the provisioned cluster serves only while Docker is down, as for `docker_unavailable`.
48
+ */
49
+ export declare function nativeTestPostgresGrant(fallback: NativeTestPostgresFallback | null, dockerAvailable: boolean): NativeTestPostgresGrant | null;
14
50
  export declare class NativeTestPostgresFallbackError extends Error {
15
51
  readonly code = "native_test_postgres_fallback_invalid";
16
52
  constructor(detail: string);
@@ -20,6 +56,14 @@ export declare function resolveNativeTestPostgresFallbackPath(): string;
20
56
  export declare function configuredNativeTestPostgresFallbackPath(): string | null;
21
57
  /** Returns null when no fallback is configured; throws when one is configured unsafely. */
22
58
  export declare function readNativeTestPostgresFallback(configPath?: string): NativeTestPostgresFallback | null;
23
- export declare function parseNativeTestPostgresFallback(connectionString: string): NativeTestPostgresFallback;
24
- /** Environment for one runner-authored .NET test process using the fallback. */
25
- export declare function nativeTestPostgresFallbackEnvironment(fallback: NativeTestPostgresFallback): Readonly<Record<string, string>>;
59
+ export declare function parseNativeTestPostgresFallback(connectionString: string, use?: NativeTestPostgresUse): NativeTestPostgresFallback;
60
+ /** Environment for one runner-authored .NET test process using the cluster. */
61
+ export declare function nativeTestPostgresFallbackEnvironment(grant: Pick<NativeTestPostgresGrant, "connectionString" | "mode" | "ephemeralClusterId">): Readonly<Record<string, string>>;
62
+ /**
63
+ * Runner-authored verification uses the operator-provisioned native test cluster,
64
+ * which holds no real data, whenever its file prefers it (the default); Docker then
65
+ * only starts pinned-engine containers. A `docker_unavailable` cluster is used only
66
+ * when the Docker engine is unavailable; otherwise the attempt-owned Testcontainers
67
+ * database serves.
68
+ */
69
+ export declare function managedVerificationDatabaseEnvironment(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null): Promise<Readonly<Record<string, string>>>;