@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.c03d3c89ec4a

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 (174) hide show
  1. package/README.md +45 -3
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +84 -2
  4. package/dist/bridge/bridge.service.js +358 -12
  5. package/dist/bridge/bridge.types.d.ts +22 -0
  6. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  7. package/dist/bridge/dispatch-result-outbox.js +31 -6
  8. package/dist/bridge/local-yield-flag.d.ts +6 -0
  9. package/dist/bridge/local-yield-flag.js +34 -0
  10. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  11. package/dist/bridge/runner-host-capabilities.js +4 -0
  12. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  13. package/dist/bridge/test-postgres-capability.js +120 -0
  14. package/dist/cleanup/cleanup.service.d.ts +9 -0
  15. package/dist/cleanup/cleanup.service.js +72 -109
  16. package/dist/cleanup/cleanup.types.d.ts +4 -0
  17. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  18. package/dist/cleanup/forge-owned-paths.js +53 -0
  19. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  20. package/dist/cleanup/host-runtime-ledger.js +109 -0
  21. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  22. package/dist/cleanup/managed-branch-sweep.js +111 -0
  23. package/dist/cli/cli.help.js +20 -2
  24. package/dist/cli/cli.service.d.ts +16 -0
  25. package/dist/cli/cli.service.js +142 -16
  26. package/dist/cli/local-config.d.ts +4 -0
  27. package/dist/cli/local-config.js +26 -4
  28. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  29. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  30. package/dist/runtime/attempt-database-broker.js +390 -0
  31. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  32. package/dist/runtime/attempt-process-supervisor.js +77 -3
  33. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  34. package/dist/runtime/host-database-capability-boundary.js +1 -0
  35. package/dist/runtime/host-diagnostics.js +4 -3
  36. package/dist/runtime/host-facts.d.ts +35 -0
  37. package/dist/runtime/host-facts.js +95 -0
  38. package/dist/runtime/host-load-admission.d.ts +60 -0
  39. package/dist/runtime/host-load-admission.js +99 -0
  40. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  41. package/dist/runtime/host-load-child-environment.js +67 -0
  42. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  43. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  44. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  45. package/dist/runtime/host-load-governor-config.js +76 -0
  46. package/dist/runtime/host-load-governor.d.ts +174 -0
  47. package/dist/runtime/host-load-governor.js +541 -0
  48. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  49. package/dist/runtime/host-load-ledger-lock.js +185 -0
  50. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  51. package/dist/runtime/host-load-runtime-settings.js +78 -0
  52. package/dist/runtime/host-load-sampler.d.ts +126 -0
  53. package/dist/runtime/host-load-sampler.js +232 -0
  54. package/dist/runtime/host-load-step-class.d.ts +68 -0
  55. package/dist/runtime/host-load-step-class.js +106 -0
  56. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  57. package/dist/runtime/host-load-step-reaper.js +95 -0
  58. package/dist/runtime/host-load-step-run.d.ts +73 -0
  59. package/dist/runtime/host-load-step-run.js +102 -0
  60. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  61. package/dist/runtime/host-load-token-ledger.js +421 -0
  62. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  63. package/dist/runtime/host-pressure-stall.js +168 -0
  64. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  65. package/dist/runtime/host-runtime-contract.js +75 -11
  66. package/dist/runtime/host-runtime-lease.d.ts +76 -4
  67. package/dist/runtime/host-runtime-lease.js +386 -32
  68. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  69. package/dist/runtime/host-runtime-promotion.js +48 -0
  70. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  71. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  72. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  73. package/dist/runtime/host-runtime-requirements.js +117 -0
  74. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  75. package/dist/runtime/managed-command-teardown.js +607 -0
  76. package/dist/runtime/node-host-runtime-adapter.js +5 -4
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  81. package/dist/runtime/runner-settings.d.ts +100 -0
  82. package/dist/runtime/runner-settings.js +214 -0
  83. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  84. package/dist/sandbox/host-capacity-broker.js +315 -0
  85. package/dist/sandbox/repository-lock.js +3 -2
  86. package/dist/sandbox/runtime.d.ts +10 -1
  87. package/dist/sandbox/runtime.js +50 -6
  88. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  89. package/dist/sandbox/sandbox-cgroups.js +42 -0
  90. package/dist/session/managed-attempt-tools.d.ts +27 -0
  91. package/dist/session/managed-attempt-tools.js +366 -45
  92. package/dist/session/managed-build-coordinator.d.ts +1 -1
  93. package/dist/session/managed-build-coordinator.js +8 -4
  94. package/dist/session/managed-command-host-load.d.ts +45 -0
  95. package/dist/session/managed-command-host-load.js +82 -0
  96. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  97. package/dist/session/mcp-argument-coercion.js +121 -0
  98. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  99. package/dist/session/phase-completion.artifacts.js +98 -25
  100. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  101. package/dist/session/phase-completion.command-validation.js +77 -0
  102. package/dist/session/phase-completion.d.ts +4 -0
  103. package/dist/session/phase-completion.helpers.js +13 -12
  104. package/dist/session/phase-completion.js +4 -0
  105. package/dist/session/phase-completion.prompts.js +6 -1
  106. package/dist/session/phase-completion.runtime.d.ts +5 -3
  107. package/dist/session/phase-completion.runtime.js +78 -36
  108. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  109. package/dist/session/phase-completion.schema-parts.js +188 -0
  110. package/dist/session/phase-completion.schemas.d.ts +3 -3
  111. package/dist/session/phase-completion.schemas.js +206 -221
  112. package/dist/session/phase-completion.validation.d.ts +2 -3
  113. package/dist/session/phase-completion.validation.js +46 -92
  114. package/dist/session/pre-publication-host-load.d.ts +27 -0
  115. package/dist/session/pre-publication-host-load.js +111 -0
  116. package/dist/session/pre-publication-pass.d.ts +60 -0
  117. package/dist/session/pre-publication-pass.js +145 -0
  118. package/dist/session/pre-publication-process.d.ts +23 -0
  119. package/dist/session/pre-publication-process.js +109 -0
  120. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  121. package/dist/session/pre-publication-skipped-tests.js +109 -0
  122. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  123. package/dist/session/pre-publication-step-execution.js +49 -0
  124. package/dist/session/pre-publication-validation.d.ts +30 -20
  125. package/dist/session/pre-publication-validation.js +178 -193
  126. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  127. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  128. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  129. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  130. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  131. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  132. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  133. package/dist/session/provider-cli/provider-cli.process.js +299 -25
  134. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  135. package/dist/session/provider-cli/provider-cli.prompts.js +62 -9
  136. package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
  137. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  138. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  139. package/dist/session/provider-cli/provider-cli.service.js +200 -162
  140. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  141. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  143. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  144. package/dist/session/provider-cli/provider-output-state.js +9 -0
  145. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  146. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  147. package/dist/session/publishable-worktree-changes.js +193 -0
  148. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  149. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  150. package/dist/session/session.base.d.ts +9 -1
  151. package/dist/session/session.service.d.ts +9 -2
  152. package/dist/session/session.service.js +120 -5
  153. package/dist/session/session.types.d.ts +3 -0
  154. package/dist/session/session.types.js +15 -3
  155. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  156. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  157. package/dist/shared/process/host-process-recovery.js +3 -2
  158. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  159. package/dist/shared/process/host-process-supervisor.js +6 -5
  160. package/dist/shared/process/process-tree.d.ts +52 -0
  161. package/dist/shared/process/process-tree.js +144 -0
  162. package/dist/shared/process/process.d.ts +67 -0
  163. package/dist/shared/process/process.js +213 -11
  164. package/dist/shared/provider-capabilities.js +5 -6
  165. package/dist/shared/time/monotonic.d.ts +1 -0
  166. package/dist/shared/time/monotonic.js +8 -0
  167. package/dist/version.d.ts +1 -1
  168. package/dist/version.js +1 -1
  169. package/dist/worktree/dependency-warmer.d.ts +25 -0
  170. package/dist/worktree/dependency-warmer.js +120 -10
  171. package/dist/worktree/worktree.service.d.ts +10 -1
  172. package/dist/worktree/worktree.service.js +42 -2
  173. package/dist/worktree/worktree.types.d.ts +7 -0
  174. package/package.json +2 -2
@@ -7,19 +7,23 @@ import { assertHostAttemptRootIdentity, retainHostDiagnostics } from "./host-dia
7
7
  import { assertHostExecutionRoot, compactHostAttemptId } from "./host-execution-root.js";
8
8
  import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
9
9
  import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
+ import { ForgeFailureError } from "../session/session.types.js";
10
11
  import { resolveExistingDirectoryPath } from "../shared/path/path.js";
11
12
  import { formatBytes } from "../shared/format/format-bytes.js";
13
+ import { redactText } from "../shared/redaction/redaction.js";
12
14
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
13
15
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
14
16
  import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
15
17
  import { HostPortBroker, } from "./host-port-broker.js";
16
18
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
17
19
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
20
+ import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
21
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
18
22
  import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
19
23
  import { HostListenerInspector } from "./host-listener-inspector.js";
20
24
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
21
25
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
22
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
26
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
23
27
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
24
28
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
25
29
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
@@ -27,6 +31,11 @@ import { readCanonicalSourceFile } from "./canonical-source-file.js";
27
31
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
28
32
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
29
33
  import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
34
+ import { HostLoadGovernor } from "./host-load-governor.js";
35
+ import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
36
+ import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
37
+ import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
38
+ import { HostLoadSampler } from "./host-load-sampler.js";
30
39
  const hostCapacityWaiterScanLimit = 64;
31
40
  const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
32
41
  export class HostRuntimeLeaseManager {
@@ -38,6 +47,7 @@ export class HostRuntimeLeaseManager {
38
47
  playwrightAdapter;
39
48
  processRecovery;
40
49
  capacityResourceSample;
50
+ databaseBroker;
41
51
  preparedReadiness;
42
52
  active = new Map();
43
53
  pendingRenewals = new Map();
@@ -57,10 +67,18 @@ export class HostRuntimeLeaseManager {
57
67
  workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
58
68
  portBroker;
59
69
  nodeAdapter;
70
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
60
71
  capacityConfiguration;
61
72
  memoryAvailability;
62
73
  executionRoot;
63
- constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot) {
74
+ /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
75
+ hostLoadGovernor;
76
+ requirementsCheck = null;
77
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
78
+ setRequirementsCheck(check) {
79
+ this.requirementsCheck = check;
80
+ }
81
+ constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null, hostLoad = null) {
64
82
  this.stateRoot = stateRoot;
65
83
  this.processSupervisors = processSupervisors;
66
84
  this.processRunner = processRunner;
@@ -69,6 +87,8 @@ export class HostRuntimeLeaseManager {
69
87
  this.playwrightAdapter = playwrightAdapter;
70
88
  this.processRecovery = processRecovery;
71
89
  this.capacityResourceSample = capacityResourceSample;
90
+ this.databaseBroker = databaseBroker;
91
+ this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
72
92
  this.executionRoot = path.resolve(executionRoot ?? stateRoot);
73
93
  if (executionRoot !== undefined)
74
94
  assertHostExecutionRoot(this.executionRoot);
@@ -78,7 +98,40 @@ export class HostRuntimeLeaseManager {
78
98
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
79
99
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
80
100
  }
101
+ /** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
102
+ capacityLimitDefaults() {
103
+ return {
104
+ maxConcurrentAttempts: this.capacityConfiguration.defaultHardMaxAttempts,
105
+ memoryReserveBytes: this.capacityConfiguration.adaptiveHostReserveBytes,
106
+ };
107
+ }
108
+ /**
109
+ * Decision 0014: the bridge's effective max attempts and memory reserve. They
110
+ * apply from the next attempt admission; admitted attempts keep their
111
+ * reservations and are never preempted, even when the new limit is lower than
112
+ * what already runs. The idle reserve follows the reserve as at startup.
113
+ */
114
+ applyCapacityLimits(limits) {
115
+ const current = this.capacityConfiguration;
116
+ const hardMaxAttempts = Math.max(1, Math.min(32, Math.floor(limits.maxConcurrentAttempts)));
117
+ const hostReserveBytes = Math.max(512 * 1024 ** 2, Math.floor(limits.memoryReserveBytes));
118
+ if (hardMaxAttempts === current.hardMaxAttempts && hostReserveBytes === current.hostReserveBytes)
119
+ return;
120
+ this.capacityConfiguration = {
121
+ ...current,
122
+ hardMaxAttempts,
123
+ hostReserveBytes,
124
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, current),
125
+ };
126
+ // A raised limit may admit queued attempts now rather than at their next recheck.
127
+ this.drainAdmissionWaiters();
128
+ }
129
+ hostLoadChildEnvironment() {
130
+ return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
131
+ }
81
132
  async reap(options) {
133
+ // Heavy-step tokens whose owner died or whose lease lapsed are returned first.
134
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
82
135
  await this.refreshKnownPromotions();
83
136
  const recoveredAttempts = [];
84
137
  const report = {
@@ -199,6 +252,15 @@ export class HostRuntimeLeaseManager {
199
252
  report.degraded += 1;
200
253
  }
201
254
  }
255
+ // Databases issued to attempts that ended without a clean release (a Bridge crash, or a
256
+ // drop that met a lingering session) are removed once no live lease holds them.
257
+ // A degraded lease may still own running processes after a restart, so its database is kept.
258
+ await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
259
+ // Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
260
+ // ended with a crashed bridge or MCP server) are returned once no live lease holds
261
+ // their attempt; a degraded lease may still own the running step, so its tokens stay.
262
+ await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
263
+ || (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
202
264
  return report;
203
265
  }
204
266
  snapshot() {
@@ -887,7 +949,7 @@ export class HostRuntimeLeaseManager {
887
949
  }
888
950
  return {
889
951
  lease: existing.lease,
890
- environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass),
952
+ environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass, existing.databaseCapability),
891
953
  runtimeContract: existing.runtimeContract,
892
954
  executionClass: existing.executionClass,
893
955
  };
@@ -916,6 +978,15 @@ export class HostRuntimeLeaseManager {
916
978
  let attemptRootIdentity = null;
917
979
  try {
918
980
  const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
981
+ // Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
982
+ // API learns the requirements in the first place.
983
+ const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
984
+ ? []
985
+ : this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
986
+ if (unmetRequirements.length > 0) {
987
+ // Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
988
+ throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
989
+ }
919
990
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
920
991
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
921
992
  }
@@ -1080,6 +1151,8 @@ export class HostRuntimeLeaseManager {
1080
1151
  parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1081
1152
  processSupervisor,
1082
1153
  adapterCleanups: [],
1154
+ adapterCleanupsByPort: new Map(),
1155
+ restartingConfiguredProject: false,
1083
1156
  pendingAdapterLaunches: new Map(),
1084
1157
  runtimeResourcesReleased: false,
1085
1158
  releasing: false,
@@ -1142,6 +1215,15 @@ export class HostRuntimeLeaseManager {
1142
1215
  await this.writeLedger(renewed);
1143
1216
  }
1144
1217
  async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1218
+ return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
1219
+ }
1220
+ /**
1221
+ * Launches the configured project. Only the first launch, from the admitted commit's clean
1222
+ * source, may record parallel-safety proof: a restart serves the workspace after the provider
1223
+ * edited it, and a proof observed there would be stored under the admitted commit and could
1224
+ * move this or a later attempt at that commit into shared admission for source it never ran.
1225
+ */
1226
+ async launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, promote) {
1145
1227
  const active = this.active.get(dispatchAttemptId);
1146
1228
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1147
1229
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
@@ -1149,7 +1231,7 @@ export class HostRuntimeLeaseManager {
1149
1231
  if (active.executionClass === "analysis_only") {
1150
1232
  return {
1151
1233
  lease: active.lease,
1152
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1234
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1153
1235
  runtimeContract: active.runtimeContract,
1154
1236
  executionClass: active.executionClass,
1155
1237
  };
@@ -1158,21 +1240,49 @@ export class HostRuntimeLeaseManager {
1158
1240
  if (configuredPorts.length === 0) {
1159
1241
  return {
1160
1242
  lease: active.lease,
1161
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1243
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1162
1244
  runtimeContract: active.runtimeContract,
1163
1245
  executionClass: active.executionClass,
1164
1246
  };
1165
1247
  }
1248
+ const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
1249
+ // A host without the project's pinned browsers fails here, before any database,
1250
+ // build, launch, or promotion work that the attempt would otherwise waste.
1251
+ if (playwrightConfig)
1252
+ await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
1166
1253
  const owner = hostPortOwner(active.lease);
1167
1254
  const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
1168
1255
  if (!logDirectory)
1169
1256
  throw new Error("host_runtime_project_invalid: attempt log directory is unavailable.");
1170
- const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector);
1257
+ if (this.databaseBroker && !active.databaseCapability
1258
+ && configuredPorts.some(port => /^dotnet(?:\.exe)?$/iu.test(path.basename(port.launch.command)))) {
1259
+ // An ASP.NET runtime may require an isolated database (Forge.Api refuses to start in a
1260
+ // managed host attempt without one). Issue it before the first launch. Release waits for
1261
+ // an in-flight provision, so a database issued during release is still dropped.
1262
+ const provision = this.databaseBroker.provision(dispatchAttemptId, fencingToken, signal)
1263
+ .then(capability => {
1264
+ active.databaseCapability = capability;
1265
+ return capability;
1266
+ });
1267
+ active.databaseProvision = provision;
1268
+ await provision;
1269
+ if (active.releasing) {
1270
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during database provisioning.");
1271
+ }
1272
+ await onProjectCheckpoint?.({
1273
+ code: "host_runtime_database_provisioned",
1274
+ message: `Provisioned isolated attempt database ${active.databaseCapability.databaseName} on the native test cluster.`,
1275
+ data: { database: active.databaseCapability.databaseName },
1276
+ });
1277
+ }
1278
+ // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1279
+ const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1280
+ const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1171
1281
  for (const configuredPort of configuredPorts) {
1172
1282
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
1173
1283
  const buildEnvironment = {
1174
1284
  ...configuredPort.launch.environment,
1175
- ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1285
+ ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1176
1286
  };
1177
1287
  const prebuild = createAspNetRuntimePrebuildPlan({
1178
1288
  command: configuredPort.launch.command,
@@ -1189,7 +1299,29 @@ export class HostRuntimeLeaseManager {
1189
1299
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1190
1300
  data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1191
1301
  });
1192
- const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal), signal);
1302
+ let hostLoadWaitMs = null;
1303
+ const build = await ensureAspNetRuntimePrebuilt(prebuild,
1304
+ // Only a real build (not a verified cache hit) takes a host load token.
1305
+ async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
1306
+ classification: aspNetPrebuildStepClass,
1307
+ label: prebuild.projectPath,
1308
+ dispatchAttemptId,
1309
+ priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
1310
+ signal: buildSignal,
1311
+ onWaiting: async (decision) => await onProjectCheckpoint?.({
1312
+ code: "host_runtime_build_waiting_for_host_capacity",
1313
+ message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
1314
+ data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
1315
+ }),
1316
+ }, async (waitMs, control) => {
1317
+ hostLoadWaitMs = waitMs;
1318
+ // A reclaimed token stops the build: its capacity is no longer reserved. So does a
1319
+ // build whose process tree cannot be recorded on its token (a reclaim could not stop it).
1320
+ const unrecorded = new AbortController();
1321
+ const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
1322
+ return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
1323
+ .catch((error) => { unrecorded.abort(error); }));
1324
+ }), signal);
1193
1325
  await onProjectCheckpoint?.({
1194
1326
  code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1195
1327
  message: build.cacheHit
@@ -1199,6 +1331,7 @@ export class HostRuntimeLeaseManager {
1199
1331
  input_commit_sha: active.inputCommitSha,
1200
1332
  build_fingerprint: build.fingerprint,
1201
1333
  receipt_path: build.receiptPath,
1334
+ ...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
1202
1335
  },
1203
1336
  });
1204
1337
  }
@@ -1211,8 +1344,8 @@ export class HostRuntimeLeaseManager {
1211
1344
  },
1212
1345
  }, launcher, signal);
1213
1346
  }
1214
- const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1215
- const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass);
1347
+ const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
1348
+ const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1216
1349
  const playwright = active.runtimeContract.contract.runtime.playwright;
1217
1350
  if (!playwright) {
1218
1351
  return {
@@ -1250,6 +1383,94 @@ export class HostRuntimeLeaseManager {
1250
1383
  executionClass: active.executionClass,
1251
1384
  };
1252
1385
  }
1386
+ /**
1387
+ * Relaunches the configured project so it serves the current workspace. Every
1388
+ * configured process stops (the API port changes, so the dev server's proxy target
1389
+ * must change with it), its port reservation is released and dropped from the
1390
+ * persisted lease, and the regular start path runs again, including the ASP.NET
1391
+ * prebuild, whose receipt rebuilds only when the sources changed.
1392
+ */
1393
+ async restartConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1394
+ const active = this.active.get(dispatchAttemptId);
1395
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1396
+ throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1397
+ }
1398
+ if (signal?.aborted)
1399
+ throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
1400
+ if (active.restartingConfiguredProject) {
1401
+ throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
1402
+ }
1403
+ active.restartingConfiguredProject = true;
1404
+ // Release cancels the whole restart through this controller and waits for it to settle.
1405
+ const controller = linkedAbortController(signal);
1406
+ const promise = this.runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, controller.signal, onProjectCheckpoint);
1407
+ const restart = { controller, promise };
1408
+ active.configuredProjectRestart = restart;
1409
+ try {
1410
+ return await promise;
1411
+ }
1412
+ finally {
1413
+ // The controller is not aborted on settle: adapters this restart launched keep it as their
1414
+ // parent signal for as long as they run, exactly as they would keep the caller's signal.
1415
+ if (active.configuredProjectRestart === restart)
1416
+ active.configuredProjectRestart = null;
1417
+ active.restartingConfiguredProject = false;
1418
+ }
1419
+ }
1420
+ async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1421
+ // The relaunch keeps the admission granted at start. A workspace contract that changed only its
1422
+ // launch environment is adopted; any other change throws host_runtime_contract_changed.
1423
+ const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
1424
+ active.runtimeContract = readmitted.runtimeContract;
1425
+ active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
1426
+ if (readmitted.changed) {
1427
+ 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." });
1428
+ }
1429
+ const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1430
+ const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
1431
+ if (pendingPort) {
1432
+ throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
1433
+ }
1434
+ const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
1435
+ if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
1436
+ // The generated Playwright config targets the stack being stopped. If the restart fails, no
1437
+ // config may be left pointing at ports another attempt can now be assigned.
1438
+ await this.playwrightAdapter.discardOverlay(temporaryDirectory);
1439
+ }
1440
+ await this.stopConfiguredProject(active, portNames);
1441
+ // Keeps whatever admission the attempt holds; see launchConfiguredProject.
1442
+ const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
1443
+ if (active.releasing) {
1444
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1445
+ }
1446
+ return restarted;
1447
+ }
1448
+ /** Stops configured project processes in reverse launch order and releases their ports. */
1449
+ async stopConfiguredProject(active, portNames) {
1450
+ const launched = active.lease.resources.ports
1451
+ .map(port => port.name)
1452
+ .filter(name => portNames.includes(name))
1453
+ .reverse();
1454
+ for (const name of launched) {
1455
+ if (active.releasing) {
1456
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1457
+ }
1458
+ const cleanup = active.adapterCleanupsByPort.get(name);
1459
+ if (!cleanup) {
1460
+ throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
1461
+ }
1462
+ // A failed stop keeps the cleanup and the port record for the fenced release retry.
1463
+ await cleanup();
1464
+ removeCleanup(active.adapterCleanups, cleanup);
1465
+ active.adapterCleanupsByPort.delete(name);
1466
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1467
+ ...active.lease.resources,
1468
+ ports: active.lease.resources.ports.filter(port => port.name !== name),
1469
+ });
1470
+ await this.writeLedger(runtimeLease);
1471
+ active.lease = runtimeLease;
1472
+ }
1473
+ }
1253
1474
  providerProcessRunner(dispatchAttemptId, fencingToken) {
1254
1475
  const active = this.active.get(dispatchAttemptId);
1255
1476
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
@@ -1337,6 +1558,7 @@ export class HostRuntimeLeaseManager {
1337
1558
  unlinkAbortController(controller, signal);
1338
1559
  };
1339
1560
  active.adapterCleanups.push(cleanup);
1561
+ active.adapterCleanupsByPort.set(portName, cleanup);
1340
1562
  try {
1341
1563
  if (active.releasing)
1342
1564
  throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
@@ -1359,6 +1581,8 @@ export class HostRuntimeLeaseManager {
1359
1581
  try {
1360
1582
  await cleanup();
1361
1583
  removeCleanup(active.adapterCleanups, cleanup);
1584
+ if (active.adapterCleanupsByPort.get(portName) === cleanup)
1585
+ active.adapterCleanupsByPort.delete(portName);
1362
1586
  }
1363
1587
  catch {
1364
1588
  // Preserve the cleanup and broker claim for the fenced release retry.
@@ -1383,6 +1607,9 @@ export class HostRuntimeLeaseManager {
1383
1607
  if (!preservePreparation)
1384
1608
  this.pendingRenewals.delete(dispatchAttemptId);
1385
1609
  if (!active) {
1610
+ // Queued steps are cancelled and running ones stopped; each returns its own
1611
+ // token once its processes are gone (never before, or capacity is reused early).
1612
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1386
1613
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1387
1614
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1388
1615
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
@@ -1392,17 +1619,42 @@ export class HostRuntimeLeaseManager {
1392
1619
  if (active.lease.fencingToken !== fencingToken)
1393
1620
  return null;
1394
1621
  active.releasing = true;
1622
+ // Attempt teardown cancels the attempt's queued heavy steps and stops its running
1623
+ // ones. Each running step (an ASP.NET prebuild, an install, a validation step)
1624
+ // returns its own token only after its processes have exited, so the capacity is
1625
+ // not reused while, say, a build is still being terminated.
1626
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1395
1627
  for (const pending of active.pendingAdapterLaunches.values()) {
1396
1628
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1397
1629
  }
1398
1630
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1631
+ const restart = active.configuredProjectRestart;
1632
+ if (restart) {
1633
+ restart.controller.abort("Host runtime release cancelled the configured project restart.");
1634
+ await restart.promise.catch(() => undefined);
1635
+ }
1636
+ await active.databaseProvision?.catch(() => undefined);
1399
1637
  let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1400
1638
  active.lease = releasing;
1401
1639
  await this.writeLedger(releasing);
1402
1640
  try {
1403
1641
  if (!active.runtimeResourcesReleased) {
1404
1642
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1643
+ // The attempt's MCP servers and process trees are stopped now; tokens they held
1644
+ // belong to dead owners and go back to the host budget at once, including any
1645
+ // without a recorded process tree (their steps were inside the stopped trees).
1646
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
1647
+ await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
1648
+ .catch(() => undefined);
1649
+ // This bridge's own steps whose trees only stopAll could prove gone (a supervised
1650
+ // validation step whose termination failed earlier) return their tokens now.
1651
+ await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1405
1652
  await releaseAdapterResources(active.adapterCleanups);
1653
+ active.adapterCleanupsByPort.clear();
1654
+ if (active.databaseCapability && this.databaseBroker) {
1655
+ // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1656
+ await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
1657
+ }
1406
1658
  active.runtimeResourcesReleased = true;
1407
1659
  // Runtime admission protects live processes, listeners, ports, and their
1408
1660
  // memory commitment. Once exact process and adapter cleanup succeeds,
@@ -1496,18 +1748,46 @@ export class HostRuntimeLeaseManager {
1496
1748
  if (logsEntry.kind !== "directory") {
1497
1749
  throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1498
1750
  }
1499
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1500
1751
  const outcomes = [];
1501
- for (const entry of entries) {
1502
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1503
- continue;
1504
- const metadataPath = path.join(logsRoot, entry.name);
1505
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1506
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1507
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
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);
1508
1782
  }
1509
- outcomes.push(await this.processRecovery.recover(value));
1510
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");
1511
1791
  return outcomes;
1512
1792
  }
1513
1793
  async markLedgerDegraded(ledger) {
@@ -1883,6 +2163,18 @@ class AttemptSupervisedProviderProcessRunner {
1883
2163
  : new Set();
1884
2164
  const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
1885
2165
  this.onProcessTreeStarted();
2166
+ try {
2167
+ return await this.awaitProviderResult(child, baselineListeners, signal);
2168
+ }
2169
+ finally {
2170
+ // The provider tree, and the MCP server inside it, is gone. A managed command that
2171
+ // server started now has no supervisor and no receipt writer, so it must not keep
2172
+ // running into the next provider generation. This never rejects; a command it
2173
+ // cannot prove stopped is left to attempt teardown, which fails closed.
2174
+ await this.supervisor.stopOrphanedManagedCommands();
2175
+ }
2176
+ }
2177
+ async awaitProviderResult(child, baselineListeners, signal) {
1886
2178
  if (!this.enforceNoListeners)
1887
2179
  return await child.result;
1888
2180
  let settled = false;
@@ -1993,7 +2285,7 @@ export function hostRuntimeEventResources(lease, runtimeContract, executionClass
1993
2285
  export function hostRuntimeSingletonKeys(dispatch) {
1994
2286
  return [projectHostRuntimeSingletonKey(dispatch.repo.id)];
1995
2287
  }
1996
- function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass) {
2288
+ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass, databaseCapability) {
1997
2289
  const pathFor = (role) => lease.resources.paths.find(entry => entry.role === role)?.path ?? "";
1998
2290
  const environment = {
1999
2291
  FORGE_SESSION_ID: sessionId,
@@ -2032,6 +2324,8 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2032
2324
  };
2033
2325
  if (lease.resources.singletonKeys.length === 0)
2034
2326
  delete environment.FORGE_SINGLETON_KEYS;
2327
+ if (databaseCapability)
2328
+ environment[attemptDatabaseCapabilityEnvironment] = databaseCapability.connectionString;
2035
2329
  const resolvedBaseUrls = [];
2036
2330
  for (const assigned of lease.resources.ports) {
2037
2331
  const configured = runtimeContract.contract.runtime.ports.find(port => port.name === assigned.name);
@@ -2056,14 +2350,43 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2056
2350
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2057
2351
  return environment;
2058
2352
  }
2059
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal) {
2353
+ /**
2354
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
2355
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
2356
+ * stack is down: after its ports are released another attempt may be assigned them.
2357
+ */
2358
+ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2359
+ const keys = new Set([
2360
+ "FORGE_E2E_API_URL",
2361
+ "FORGE_E2E_WEB_URL",
2362
+ "FORGE_BASE_URL",
2363
+ "FORGE_PLAYWRIGHT_BASE_URL",
2364
+ // The generated Playwright config embeds the base URL.
2365
+ "FORGE_PLAYWRIGHT_CONFIG",
2366
+ ]);
2367
+ for (const port of runtimeContract.contract.runtime.ports) {
2368
+ const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
2369
+ keys.add(port.env);
2370
+ if (port.baseUrlEnv)
2371
+ keys.add(port.baseUrlEnv);
2372
+ keys.add(`FORGE_${normalizedName}_PORT`);
2373
+ keys.add(`FORGE_${normalizedName}_URL`);
2374
+ }
2375
+ return [...keys];
2376
+ }
2377
+ function anySignal(...signals) {
2378
+ return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2379
+ }
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) {
2060
2383
  const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2061
2384
  const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2062
2385
  const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2063
2386
  let stdoutTail = "";
2064
2387
  let stderrTail = "";
2065
2388
  const append = async (target, line) => {
2066
- await fs.appendFile(target, `${line}\n`, { encoding: "utf8", mode: 0o600 });
2389
+ await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2067
2390
  };
2068
2391
  const child = await supervisor.startChildReady(childName, {
2069
2392
  command: plan.command,
@@ -2073,19 +2396,20 @@ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal)
2073
2396
  captureOutput: false,
2074
2397
  }, {
2075
2398
  onStdoutLine: async (line) => {
2076
- stdoutTail = appendRuntimeBuildTail(stdoutTail, line);
2399
+ stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2077
2400
  await append(stdoutLogPath, line);
2078
2401
  },
2079
2402
  onStderrLine: async (line) => {
2080
- stderrTail = appendRuntimeBuildTail(stderrTail, line);
2403
+ stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2081
2404
  await append(stderrLogPath, line);
2082
2405
  },
2083
2406
  }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2407
+ await onStarted?.(child.metadataPath);
2084
2408
  const result = await child.result;
2085
2409
  return {
2086
2410
  exitCode: result.exitCode,
2087
- stdoutTail: appendRuntimeBuildTail(stdoutTail, result.stdout),
2088
- stderrTail: appendRuntimeBuildTail(stderrTail, result.stderr),
2411
+ stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2412
+ stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2089
2413
  stdoutLogPath,
2090
2414
  stderrLogPath,
2091
2415
  };
@@ -2123,7 +2447,7 @@ function runtimeExecutionClass(dispatch) {
2123
2447
  ? "analysis_only"
2124
2448
  : "managed_runtime";
2125
2449
  }
2126
- function runtimeAdmissionPriority(dispatch) {
2450
+ export function runtimeAdmissionPriority(dispatch) {
2127
2451
  return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2128
2452
  || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2129
2453
  ? "background"
@@ -2195,6 +2519,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
2195
2519
  const parsed = Number.parseInt(process.env[name] ?? "", 10);
2196
2520
  return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2197
2521
  }
2522
+ /**
2523
+ * Today's max attempts and adaptive memory reserve for this host, before
2524
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
2525
+ * (decision 0014 treats those as bounds on the server's values).
2526
+ */
2527
+ export function hostCapacityLimitDefaults(capacityResourceSample) {
2528
+ const configuration = loadHostCapacityConfiguration(capacityResourceSample);
2529
+ return {
2530
+ maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
2531
+ memoryReserveBytes: configuration.adaptiveHostReserveBytes,
2532
+ };
2533
+ }
2198
2534
  function loadHostCapacityConfiguration(capacityResourceSample) {
2199
2535
  const sampledCpuCount = capacityResourceSample
2200
2536
  ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
@@ -2202,23 +2538,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
2202
2538
  const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2203
2539
  const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2204
2540
  const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
2205
- const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2206
- explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2541
+ const adaptiveOptions = {
2207
2542
  floorBytes: reserveFloorBytes,
2208
2543
  ceilingBytes: reserveCeilingBytes,
2209
2544
  percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
2545
+ };
2546
+ const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2547
+ ...adaptiveOptions,
2548
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2210
2549
  });
2211
- const minimumIdleReserveBytes = Math.min(hostReserveBytes, reserveFloorBytes);
2550
+ const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
2551
+ const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
2552
+ const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
2212
2553
  return {
2213
- hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2))), 1, 32),
2554
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
2214
2555
  hostReserveBytes,
2215
- idleHostReserveBytes: configuredInteger("FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES", minimumIdleReserveBytes, 512 * 1024 ** 2, hostReserveBytes),
2556
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
2557
+ defaultHardMaxAttempts,
2558
+ adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
2559
+ reserveFloorBytes,
2560
+ idleReserveOverrideBytes,
2216
2561
  cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2217
2562
  workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2218
2563
  memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2219
2564
  memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2220
2565
  };
2221
2566
  }
2567
+ /**
2568
+ * The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
2569
+ * clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
2570
+ */
2571
+ function idleHostReserveBytesFor(hostReserveBytes, configuration) {
2572
+ const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
2573
+ const override = configuration.idleReserveOverrideBytes;
2574
+ return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
2575
+ }
2222
2576
  function configuredOptionalInteger(name, minimum, maximum) {
2223
2577
  const raw = process.env[name];
2224
2578
  if (raw === undefined || raw.trim().length === 0)