@loucompanion/forge-bridge 0.1.4-dev.25308ca4a63d → 0.1.4-dev.297b5afcac9e

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 (126) hide show
  1. package/README.md +55 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -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.base.d.ts +2 -0
  7. package/dist/bridge/bridge.service.d.ts +53 -1
  8. package/dist/bridge/bridge.service.js +234 -113
  9. package/dist/bridge/bridge.types.d.ts +11 -0
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  13. package/dist/bridge/runner-host-capabilities.js +13 -0
  14. package/dist/cli/cli.help.js +18 -0
  15. package/dist/cli/cli.service.d.ts +16 -0
  16. package/dist/cli/cli.service.js +122 -13
  17. package/dist/cli/local-config.d.ts +4 -0
  18. package/dist/cli/local-config.js +26 -4
  19. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  20. package/dist/runtime/aspnet-runtime-prebuild.js +44 -0
  21. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  22. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  23. package/dist/runtime/docker-engine-probe.js +7 -0
  24. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  25. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  26. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  27. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  28. package/dist/runtime/host-facts.d.ts +2 -1
  29. package/dist/runtime/host-load-admission.d.ts +18 -3
  30. package/dist/runtime/host-load-admission.js +19 -4
  31. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  32. package/dist/runtime/host-load-child-environment.js +22 -11
  33. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  34. package/dist/runtime/host-load-governor-config.js +37 -0
  35. package/dist/runtime/host-load-governor.d.ts +12 -0
  36. package/dist/runtime/host-load-governor.js +139 -26
  37. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  38. package/dist/runtime/host-load-runtime-settings.js +78 -0
  39. package/dist/runtime/host-load-sampler.d.ts +34 -4
  40. package/dist/runtime/host-load-sampler.js +73 -7
  41. package/dist/runtime/host-load-step-class.d.ts +3 -1
  42. package/dist/runtime/host-load-step-class.js +60 -5
  43. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  44. package/dist/runtime/host-load-test-slot.js +81 -0
  45. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  46. package/dist/runtime/host-load-token-ledger.js +93 -61
  47. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  48. package/dist/runtime/host-load-windows-cpu.js +85 -0
  49. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  50. package/dist/runtime/host-runtime-contract.js +29 -1
  51. package/dist/runtime/host-runtime-lease.d.ts +29 -3
  52. package/dist/runtime/host-runtime-lease.js +83 -63
  53. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  54. package/dist/runtime/host-runtime-promotion.js +36 -0
  55. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  56. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  57. package/dist/runtime/runner-settings.d.ts +100 -0
  58. package/dist/runtime/runner-settings.js +214 -0
  59. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  60. package/dist/sandbox/host-capacity-broker.js +23 -4
  61. package/dist/session/architect-waits.d.ts +2 -0
  62. package/dist/session/architect-waits.js +138 -0
  63. package/dist/session/managed-attempt-tools.d.ts +0 -7
  64. package/dist/session/managed-attempt-tools.js +51 -62
  65. package/dist/session/managed-command-host-load.d.ts +2 -0
  66. package/dist/session/managed-command-host-load.js +2 -1
  67. package/dist/session/phase-completion.artifacts.js +2 -1
  68. package/dist/session/phase-completion.d.ts +8 -0
  69. package/dist/session/phase-completion.js +1 -0
  70. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  71. package/dist/session/phase-completion.mcp-args.js +156 -0
  72. package/dist/session/phase-completion.runtime.d.ts +0 -8
  73. package/dist/session/phase-completion.runtime.js +38 -168
  74. package/dist/session/phase-completion.schemas.js +25 -23
  75. package/dist/session/phase-completion.validation.js +3 -1
  76. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  77. package/dist/session/pre-publication-native-postgres.js +111 -0
  78. package/dist/session/pre-publication-pass.d.ts +61 -0
  79. package/dist/session/pre-publication-pass.js +148 -0
  80. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  81. package/dist/session/pre-publication-step-execution.js +6 -5
  82. package/dist/session/pre-publication-validation.d.ts +30 -14
  83. package/dist/session/pre-publication-validation.js +207 -134
  84. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  85. package/dist/session/provider-cli/claude-background-work.js +180 -0
  86. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  87. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  88. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  89. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  90. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  91. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  92. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  93. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  94. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  95. package/dist/session/provider-cli/provider-cli.prompts.js +58 -8
  96. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  97. package/dist/session/provider-cli/provider-cli.service.d.ts +5 -5
  98. package/dist/session/provider-cli/provider-cli.service.js +65 -257
  99. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  100. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  101. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  102. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  103. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  104. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  105. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  106. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  107. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  108. package/dist/session/provider-cli/provider-output-state.js +6 -0
  109. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  110. package/dist/session/qa-sidecar-validation.js +28 -0
  111. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  112. package/dist/session/session-redaction.js +31 -181
  113. package/dist/session/session.base.d.ts +6 -1
  114. package/dist/session/session.service.d.ts +4 -1
  115. package/dist/session/session.service.js +6 -0
  116. package/dist/session/session.types.js +3 -3
  117. package/dist/session/sidecar-json-shape.d.ts +31 -0
  118. package/dist/session/sidecar-json-shape.js +217 -0
  119. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  120. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  121. package/dist/shared/process/windows-launch.d.ts +18 -0
  122. package/dist/shared/process/windows-launch.js +68 -0
  123. package/dist/shared/provider-capabilities.js +5 -6
  124. package/dist/version.d.ts +1 -1
  125. package/dist/version.js +1 -1
  126. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import { createHash } from "node:crypto";
1
+ import { createHash, randomBytes } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { isAlias, parseDocument, visit } from "yaml";
@@ -425,6 +425,34 @@ function safeAspNetLaunchEnvironment(name, value) {
425
425
  "TMPDIR",
426
426
  ]).has(normalized);
427
427
  }
428
+ // The settings an ASP.NET API reads its secret-store master key from (Security:MasterKey wins).
429
+ const aspNetMasterKeySettings = ["security__masterkey", "security__masterkeyfile"];
430
+ /** A managed attempt's own API master key: 32 random bytes, base64-encoded, as Security:MasterKey expects. */
431
+ export function newAttemptApiMasterKey() {
432
+ return randomBytes(32).toString("base64");
433
+ }
434
+ /**
435
+ * The environment a managed attempt's ASP.NET API launches with. When neither the launch profile
436
+ * nor the runtime contract configures Security__MasterKey or Security__MasterKeyFile, the API gets
437
+ * the attempt's own key. Otherwise ASP.NET Development falls back to the host user's dotnet
438
+ * user-secrets: the host's own key where they exist, and a failed secret write wherever they do not.
439
+ * The caller keeps one key for the attempt's whole life, so a restart against the same attempt
440
+ * database can still decrypt what was stored before it. The key is a secret: it is for the API
441
+ * process only, never for the environment handed to checks or providers.
442
+ */
443
+ export function withAttemptApiMasterKey(port, environment, attemptMasterKey) {
444
+ if (port.adapter !== "aspnetcore")
445
+ return environment;
446
+ const masterKeySetting = (name) => aspNetMasterKeySettings.includes(name.toLowerCase());
447
+ if (Object.entries(environment).some(([name, value]) => masterKeySetting(name) && value.trim().length > 0)) {
448
+ return environment;
449
+ }
450
+ // A blank setting configures nothing; drop it so the attempt's key is the only one.
451
+ return {
452
+ ...Object.fromEntries(Object.entries(environment).filter(([name]) => !masterKeySetting(name))),
453
+ Security__MasterKey: attemptMasterKey,
454
+ };
455
+ }
428
456
  async function findFiles(root, accepts, maximumDepth, maximumEntries, snapshot) {
429
457
  const results = [];
430
458
  let examined = 0;
@@ -15,6 +15,7 @@ import { HostParallelPromotionStore } from "./host-runtime-promotion.js";
15
15
  import { type HostProcessRecovery } from "../shared/process/host-process-recovery.js";
16
16
  import { HostLoadGovernor } from "./host-load-governor.js";
17
17
  import { type HostLoadGovernorSource } from "./host-load-sampler.js";
18
+ import type { RunnerHostDefaults } from "./runner-settings.js";
18
19
  export interface HostRuntimeLeaseStart {
19
20
  readonly lease: RuntimeIsolationLease;
20
21
  readonly environment: Readonly<Record<string, string>>;
@@ -28,7 +29,7 @@ export interface HostRuntimeAdmissionCheckpoint {
28
29
  }
29
30
  export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
30
31
  export interface HostRuntimeProjectCheckpoint {
31
- readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
32
+ readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned" | "host_runtime_contract_readmitted";
32
33
  readonly message: string;
33
34
  readonly data?: Readonly<Record<string, unknown>>;
34
35
  }
@@ -96,6 +97,10 @@ export interface HostNodeRuntimeLaunch<T> extends NodeRuntimeAdapterLaunch<T> {
96
97
  }
97
98
  export interface HostRuntimeLeaseRuntime {
98
99
  setRequirementsCheck?(check: HostRequirementsCheck | null): void;
100
+ /** Decision 0014: today's max attempts and memory reserve defaults, before env bounds. */
101
+ capacityLimitDefaults?(): RunnerHostDefaults;
102
+ /** Decision 0014: the effective max attempts and memory reserve, from the next attempt admission. */
103
+ applyCapacityLimits?(limits: HostCapacityLimits): void;
99
104
  acquirePreparation?(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
100
105
  acquire(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
101
106
  start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
@@ -153,15 +158,25 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
153
158
  private workspaceAvailableBytes;
154
159
  private readonly portBroker;
155
160
  private readonly nodeAdapter;
156
- private readonly capacityConfiguration;
161
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
162
+ private capacityConfiguration;
157
163
  private readonly memoryAvailability;
158
164
  private readonly executionRoot;
159
- /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
165
+ /** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
160
166
  readonly hostLoadGovernor: HostLoadGovernor;
161
167
  private requirementsCheck;
162
168
  /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
163
169
  setRequirementsCheck(check: HostRequirementsCheck | null): void;
164
170
  constructor(stateRoot: string, portBroker?: HostPortBroker, nodeAdapter?: NodeHostRuntimeAdapter, processSupervisors?: AttemptProcessSupervisorRegistry, processRunner?: ProviderProcessRunner, listenerInspector?: HostListenerInspector, promotionStore?: HostParallelPromotionStore, playwrightAdapter?: PlaywrightHostRuntimeAdapter, processRecovery?: HostProcessRecovery, capacityResourceSample?: HostCapacityResourceSample | undefined, executionRoot?: string, databaseBroker?: AttemptDatabaseBroker | null, hostLoad?: HostLoadGovernorSource | null);
171
+ /** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
172
+ capacityLimitDefaults(): RunnerHostDefaults;
173
+ /**
174
+ * Decision 0014: the bridge's effective max attempts and memory reserve. They
175
+ * apply from the next attempt admission; admitted attempts keep their
176
+ * reservations and are never preempted, even when the new limit is lower than
177
+ * what already runs. The idle reserve follows the reserve as at startup.
178
+ */
179
+ applyCapacityLimits(limits: HostCapacityLimits): void;
165
180
  hostLoadChildEnvironment(): Readonly<Record<string, string>>;
166
181
  reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
167
182
  snapshot(): HostRuntimeCapacitySnapshot;
@@ -259,3 +274,14 @@ export declare function hostRuntimeSingletonKeys(dispatch: RunOnceDispatchPacket
259
274
  */
260
275
  export declare function hostRuntimeStackEnvironmentKeys(runtimeContract: LoadedHostRuntimeContract): readonly string[];
261
276
  export declare function runtimeAdmissionPriority(dispatch: RunOnceDispatchPacket): HostRuntimeAdmissionPriority;
277
+ /** The pushed attempt limits (decision 0014), already resolved against host env bounds. */
278
+ export interface HostCapacityLimits {
279
+ readonly maxConcurrentAttempts: number;
280
+ readonly memoryReserveBytes: number;
281
+ }
282
+ /**
283
+ * Today's max attempts and adaptive memory reserve for this host, before
284
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
285
+ * (decision 0014 treats those as bounds on the server's values).
286
+ */
287
+ export declare function hostCapacityLimitDefaults(capacityResourceSample?: HostCapacityResourceSample): RunnerHostDefaults;
@@ -10,10 +10,9 @@ 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";
@@ -23,14 +22,14 @@ import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
23
22
  import { HostListenerInspector } from "./host-listener-inspector.js";
24
23
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
25
24
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
26
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
25
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
27
26
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
28
27
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
29
28
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
30
29
  import { readCanonicalSourceFile } from "./canonical-source-file.js";
31
30
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
32
31
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
33
- import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
32
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, executeAspNetRuntimeBuild, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
34
33
  import { HostLoadGovernor } from "./host-load-governor.js";
35
34
  import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
36
35
  import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
@@ -67,10 +66,11 @@ export class HostRuntimeLeaseManager {
67
66
  workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
68
67
  portBroker;
69
68
  nodeAdapter;
69
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
70
70
  capacityConfiguration;
71
71
  memoryAvailability;
72
72
  executionRoot;
73
- /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
73
+ /** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
74
74
  hostLoadGovernor;
75
75
  requirementsCheck = null;
76
76
  /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
@@ -97,6 +97,34 @@ export class HostRuntimeLeaseManager {
97
97
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
98
98
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
99
99
  }
100
+ /** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
101
+ capacityLimitDefaults() {
102
+ return {
103
+ maxConcurrentAttempts: this.capacityConfiguration.defaultHardMaxAttempts,
104
+ memoryReserveBytes: this.capacityConfiguration.adaptiveHostReserveBytes,
105
+ };
106
+ }
107
+ /**
108
+ * Decision 0014: the bridge's effective max attempts and memory reserve. They
109
+ * apply from the next attempt admission; admitted attempts keep their
110
+ * reservations and are never preempted, even when the new limit is lower than
111
+ * what already runs. The idle reserve follows the reserve as at startup.
112
+ */
113
+ applyCapacityLimits(limits) {
114
+ const current = this.capacityConfiguration;
115
+ const hardMaxAttempts = Math.max(1, Math.min(32, Math.floor(limits.maxConcurrentAttempts)));
116
+ const hostReserveBytes = Math.max(512 * 1024 ** 2, Math.floor(limits.memoryReserveBytes));
117
+ if (hardMaxAttempts === current.hardMaxAttempts && hostReserveBytes === current.hostReserveBytes)
118
+ return;
119
+ this.capacityConfiguration = {
120
+ ...current,
121
+ hardMaxAttempts,
122
+ hostReserveBytes,
123
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, current),
124
+ };
125
+ // A raised limit may admit queued attempts now rather than at their next recheck.
126
+ this.drainAdmissionWaiters();
127
+ }
100
128
  hostLoadChildEnvironment() {
101
129
  return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
102
130
  }
@@ -1246,8 +1274,9 @@ export class HostRuntimeLeaseManager {
1246
1274
  data: { database: active.databaseCapability.databaseName },
1247
1275
  });
1248
1276
  }
1249
- // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1250
- const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1277
+ const apiMasterKey = attemptApiMasterKey(active);
1278
+ // Runtime output is persisted to attempt logs; the database login and master key it may print are redacted.
1279
+ const capabilitySecrets = [...attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString), apiMasterKey];
1251
1280
  const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1252
1281
  for (const configuredPort of configuredPorts) {
1253
1282
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
@@ -1310,9 +1339,7 @@ export class HostRuntimeLeaseManager {
1310
1339
  command: configuredPort.launch.command,
1311
1340
  args: configuredPort.launch.args,
1312
1341
  cwd: workingDirectory,
1313
- environment: {
1314
- ...buildEnvironment,
1315
- },
1342
+ environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1316
1343
  }, launcher, signal);
1317
1344
  }
1318
1345
  const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
@@ -1389,12 +1416,13 @@ export class HostRuntimeLeaseManager {
1389
1416
  }
1390
1417
  }
1391
1418
  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.");
1419
+ // The relaunch keeps the admission granted at start. A workspace contract that changed only its
1420
+ // launch environment is adopted; any other change throws host_runtime_contract_changed.
1421
+ const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
1422
+ active.runtimeContract = readmitted.runtimeContract;
1423
+ active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
1424
+ if (readmitted.changed) {
1425
+ 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
1426
  }
1399
1427
  const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1400
1428
  const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
@@ -2344,51 +2372,13 @@ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2344
2372
  }
2345
2373
  return [...keys];
2346
2374
  }
2375
+ /** The attempt's API master key: issued on first use, then the same for every relaunch of the attempt. */
2376
+ function attemptApiMasterKey(active) {
2377
+ return active.apiMasterKey ??= newAttemptApiMasterKey();
2378
+ }
2347
2379
  function anySignal(...signals) {
2348
2380
  return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2349
2381
  }
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
2382
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
2393
2383
  if (executionClass === "analysis_only") {
2394
2384
  const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
@@ -2489,6 +2479,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
2489
2479
  const parsed = Number.parseInt(process.env[name] ?? "", 10);
2490
2480
  return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2491
2481
  }
2482
+ /**
2483
+ * Today's max attempts and adaptive memory reserve for this host, before
2484
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
2485
+ * (decision 0014 treats those as bounds on the server's values).
2486
+ */
2487
+ export function hostCapacityLimitDefaults(capacityResourceSample) {
2488
+ const configuration = loadHostCapacityConfiguration(capacityResourceSample);
2489
+ return {
2490
+ maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
2491
+ memoryReserveBytes: configuration.adaptiveHostReserveBytes,
2492
+ };
2493
+ }
2492
2494
  function loadHostCapacityConfiguration(capacityResourceSample) {
2493
2495
  const sampledCpuCount = capacityResourceSample
2494
2496
  ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
@@ -2496,23 +2498,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
2496
2498
  const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2497
2499
  const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2498
2500
  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),
2501
+ const adaptiveOptions = {
2501
2502
  floorBytes: reserveFloorBytes,
2502
2503
  ceilingBytes: reserveCeilingBytes,
2503
2504
  percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
2505
+ };
2506
+ const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2507
+ ...adaptiveOptions,
2508
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2504
2509
  });
2505
- const minimumIdleReserveBytes = Math.min(hostReserveBytes, reserveFloorBytes);
2510
+ const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
2511
+ const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
2512
+ const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
2506
2513
  return {
2507
- hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2))), 1, 32),
2514
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
2508
2515
  hostReserveBytes,
2509
- idleHostReserveBytes: configuredInteger("FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES", minimumIdleReserveBytes, 512 * 1024 ** 2, hostReserveBytes),
2516
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
2517
+ defaultHardMaxAttempts,
2518
+ adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
2519
+ reserveFloorBytes,
2520
+ idleReserveOverrideBytes,
2510
2521
  cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2511
2522
  workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2512
2523
  memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2513
2524
  memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2514
2525
  };
2515
2526
  }
2527
+ /**
2528
+ * The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
2529
+ * clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
2530
+ */
2531
+ function idleHostReserveBytesFor(hostReserveBytes, configuration) {
2532
+ const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
2533
+ const override = configuration.idleReserveOverrideBytes;
2534
+ return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
2535
+ }
2516
2536
  function configuredOptionalInteger(name, minimum, maximum) {
2517
2537
  const raw = process.env[name];
2518
2538
  if (raw === undefined || raw.trim().length === 0)
@@ -28,5 +28,28 @@ export declare class HostParallelPromotionStore {
28
28
  private recordPath;
29
29
  }
30
30
  export declare function hostRuntimeContractFingerprint(runtimeContract: LoadedHostRuntimeContract): string;
31
+ export interface ReadmittedHostRuntimeContract {
32
+ readonly runtimeContract: LoadedHostRuntimeContract;
33
+ readonly runtimeContractFingerprint: string;
34
+ readonly changed: boolean;
35
+ }
36
+ /**
37
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
38
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
39
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
40
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
41
+ * merging the target branch can rename a variable in a derived launch profile, or change a
42
+ * manifest or project file, without changing anything admission granted. Every other part of the
43
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
44
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
45
+ * profile, singleton resources and declared requirements. Changing any of those throws the
46
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
47
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
48
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
49
+ */
50
+ export declare function readmitHostRuntimeContract(admitted: {
51
+ readonly runtimeContract: LoadedHostRuntimeContract;
52
+ readonly runtimeContractFingerprint: string;
53
+ }, current: LoadedHostRuntimeContract): ReadmittedHostRuntimeContract;
31
54
  export declare function hostRuntimeParallelEligible(runtimeContract: LoadedHostRuntimeContract): boolean;
32
55
  export declare function configuredLaunchPortNames(runtimeContract: LoadedHostRuntimeContract): readonly string[];
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { ForgeFailureError } from "../session/session.types.js";
4
5
  /** Persists only observed, contract-bound host parallel-safety evidence. */
5
6
  export class HostParallelPromotionStore {
6
7
  stateRoot;
@@ -154,6 +155,41 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
154
155
  });
155
156
  return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
156
157
  }
158
+ /**
159
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
160
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
161
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
162
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
163
+ * merging the target branch can rename a variable in a derived launch profile, or change a
164
+ * manifest or project file, without changing anything admission granted. Every other part of the
165
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
166
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
167
+ * profile, singleton resources and declared requirements. Changing any of those throws the
168
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
169
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
170
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
171
+ */
172
+ export function readmitHostRuntimeContract(admitted, current) {
173
+ const runtimeContractFingerprint = hostRuntimeContractFingerprint(current);
174
+ // The fingerprint leaves out the source of a project or default contract, but parallel
175
+ // eligibility depends on it, so an unchanged fingerprint alone does not prove the same admission.
176
+ if (runtimeContractFingerprint === admitted.runtimeContractFingerprint && current.source === admitted.runtimeContract.source) {
177
+ return { runtimeContract: admitted.runtimeContract, runtimeContractFingerprint, changed: false };
178
+ }
179
+ if (hostRuntimeAdmissionShape(current) !== hostRuntimeAdmissionShape(admitted.runtimeContract)) {
180
+ 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.");
181
+ }
182
+ return { runtimeContract: current, runtimeContractFingerprint, changed: true };
183
+ }
184
+ function hostRuntimeAdmissionShape(runtimeContract) {
185
+ const runtime = runtimeContract.contract.runtime;
186
+ return JSON.stringify({
187
+ source: runtimeContract.source,
188
+ schemaVersion: runtimeContract.contract.schemaVersion,
189
+ runtime: { ...runtime, ports: runtime.ports.map(port => ({ ...port, launch: port.launch && { ...port.launch, environment: undefined } })) },
190
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
191
+ });
192
+ }
157
193
  // Cost hints are estimates, not placement constraints: they never change the fingerprint.
158
194
  function requirementsFingerprintPart(requires) {
159
195
  if (!requires)
@@ -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>>>;
@@ -1,12 +1,37 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { resolveLocalConfigPath } from "../cli/local-config.js";
4
+ import { DockerEngineProbe } from "./docker-engine-probe.js";
5
+ import { ephemeralTestPostgresClusterEnvironment } from "./ephemeral-test-postgres.js";
4
6
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "./host-runtime-contract.js";
5
7
  export const nativeTestPostgresFallbackConfigEnvironment = "FORGE_NATIVE_TEST_POSTGRES_CONFIG";
6
8
  export const nativeTestPostgresFallbackFileName = "native-test-postgres.json";
7
9
  export const nativeTestPostgresFallbackDatabaseMode = "native_fallback";
10
+ /**
11
+ * The cluster serves the shared test server while Docker is up, so tests that need a
12
+ * pinned engine container still start one. Owner policy (2026-11-16): native PostgreSQL
13
+ * first, which keeps test databases out of the Docker VM and saves RAM.
14
+ */
15
+ export const nativeTestPostgresPreferredDatabaseMode = "native_preferred";
16
+ const nativeTestPostgresUses = ["preferred", "docker_unavailable", "ephemeral"];
8
17
  const defaultPostgresPort = 5432;
9
18
  const loopbackHosts = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
19
+ /**
20
+ * The provisioned cluster's grant for a check that can use it, or null to use Docker. A
21
+ * preferred cluster is granted whether or not Docker is up; the mode says which, because
22
+ * only the fallback mode excludes Docker for pinned-engine tests. An `ephemeral` host
23
+ * normally gets its own cluster instead (ephemeral-test-postgres-grant.ts); if that cannot
24
+ * start, the provisioned cluster serves only while Docker is down, as for `docker_unavailable`.
25
+ */
26
+ export function nativeTestPostgresGrant(fallback, dockerAvailable) {
27
+ if (!fallback || (dockerAvailable && fallback.use !== "preferred"))
28
+ return null;
29
+ return {
30
+ connectionString: fallback.connectionString,
31
+ endpoint: fallback.endpoint,
32
+ mode: dockerAvailable ? nativeTestPostgresPreferredDatabaseMode : nativeTestPostgresFallbackDatabaseMode,
33
+ };
34
+ }
10
35
  export class NativeTestPostgresFallbackError extends Error {
11
36
  code = "native_test_postgres_fallback_invalid";
12
37
  constructor(detail) {
@@ -46,9 +71,17 @@ export function readNativeTestPostgresFallback(configPath = resolveNativeTestPos
46
71
  if (document.schemaVersion !== 1 || typeof document.connectionString !== "string") {
47
72
  throw new NativeTestPostgresFallbackError(`${configPath} must contain schemaVersion 1 and a connectionString.`);
48
73
  }
49
- return parseNativeTestPostgresFallback(document.connectionString);
74
+ if (document.use !== undefined && !nativeTestPostgresUses.includes(document.use)) {
75
+ throw new NativeTestPostgresFallbackError(`${configPath} 'use' must be 'preferred', 'docker_unavailable' or 'ephemeral'.`);
76
+ }
77
+ if (document.postgresBin !== undefined
78
+ && (typeof document.postgresBin !== "string" || !path.isAbsolute(document.postgresBin))) {
79
+ throw new NativeTestPostgresFallbackError(`${configPath} 'postgresBin' must be an absolute path.`);
80
+ }
81
+ const fallback = parseNativeTestPostgresFallback(document.connectionString, document.use ?? "preferred");
82
+ return typeof document.postgresBin === "string" ? { ...fallback, postgresBin: document.postgresBin } : fallback;
50
83
  }
51
- export function parseNativeTestPostgresFallback(connectionString) {
84
+ export function parseNativeTestPostgresFallback(connectionString, use = "preferred") {
52
85
  const fields = new Map();
53
86
  for (const segment of connectionString.split(";")) {
54
87
  const separator = segment.indexOf("=");
@@ -79,13 +112,32 @@ export function parseNativeTestPostgresFallback(connectionString) {
79
112
  if (!(fields.get("username") ?? fields.get("userid") ?? fields.get("user"))) {
80
113
  throw new NativeTestPostgresFallbackError("the fallback must name a dedicated test role.");
81
114
  }
82
- return { connectionString: connectionString.trim(), endpoint: `${host}:${port}` };
115
+ return { connectionString: connectionString.trim(), endpoint: `${host}:${port}`, use };
83
116
  }
84
- /** Environment for one runner-authored .NET test process using the fallback. */
85
- export function nativeTestPostgresFallbackEnvironment(fallback) {
117
+ /** Environment for one runner-authored .NET test process using the cluster. */
118
+ export function nativeTestPostgresFallbackEnvironment(grant) {
86
119
  return {
87
- [hostRuntimeTestPostgresAdminEnvironment]: fallback.connectionString,
88
- [hostRuntimeLegacyTestPostgresEnvironment]: fallback.connectionString,
89
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: nativeTestPostgresFallbackDatabaseMode,
120
+ [hostRuntimeTestPostgresAdminEnvironment]: grant.connectionString,
121
+ [hostRuntimeLegacyTestPostgresEnvironment]: grant.connectionString,
122
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: grant.mode,
123
+ // The fixtures accept a superuser login only on the cluster that reports this id.
124
+ ...(grant.ephemeralClusterId ? { [ephemeralTestPostgresClusterEnvironment]: grant.ephemeralClusterId } : {}),
90
125
  };
91
126
  }
127
+ /**
128
+ * Runner-authored verification uses the operator-provisioned native test cluster,
129
+ * which holds no real data, whenever its file prefers it (the default); Docker then
130
+ * only starts pinned-engine containers. A `docker_unavailable` cluster is used only
131
+ * when the Docker engine is unavailable; otherwise the attempt-owned Testcontainers
132
+ * database serves.
133
+ */
134
+ export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().probeWithoutRecovery()).available, readFallback = () => {
135
+ const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
136
+ return configPath ? readNativeTestPostgresFallback(configPath) : null;
137
+ }) {
138
+ const fallback = readFallback();
139
+ if (!fallback)
140
+ return {};
141
+ const grant = nativeTestPostgresGrant(fallback, await dockerAvailable());
142
+ return grant ? nativeTestPostgresFallbackEnvironment(grant) : {};
143
+ }