@loucompanion/forge-bridge 0.1.4-dev.04a1e5b9e484 → 0.1.4-dev.138b79c6feb3

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 (148) hide show
  1. package/README.md +3 -3
  2. package/dist/bridge/bridge.service.d.ts +14 -1
  3. package/dist/bridge/bridge.service.js +80 -9
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  6. package/dist/bridge/dispatch-result-outbox.js +31 -6
  7. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  8. package/dist/bridge/runner-host-capabilities.js +4 -0
  9. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  10. package/dist/bridge/test-postgres-capability.js +120 -0
  11. package/dist/cleanup/cleanup.service.d.ts +9 -0
  12. package/dist/cleanup/cleanup.service.js +72 -109
  13. package/dist/cleanup/cleanup.types.d.ts +4 -0
  14. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  15. package/dist/cleanup/forge-owned-paths.js +53 -0
  16. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  17. package/dist/cleanup/host-runtime-ledger.js +109 -0
  18. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  19. package/dist/cleanup/managed-branch-sweep.js +111 -0
  20. package/dist/cli/cli.help.js +2 -2
  21. package/dist/cli/cli.service.js +10 -2
  22. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  23. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  24. package/dist/runtime/attempt-process-supervisor.js +50 -0
  25. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  26. package/dist/runtime/host-database-capability-boundary.js +1 -0
  27. package/dist/runtime/host-facts.d.ts +35 -0
  28. package/dist/runtime/host-facts.js +95 -0
  29. package/dist/runtime/host-load-admission.d.ts +52 -0
  30. package/dist/runtime/host-load-admission.js +84 -0
  31. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  32. package/dist/runtime/host-load-child-environment.js +65 -0
  33. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  34. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  35. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  36. package/dist/runtime/host-load-governor-config.js +46 -0
  37. package/dist/runtime/host-load-governor.d.ts +172 -0
  38. package/dist/runtime/host-load-governor.js +519 -0
  39. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  40. package/dist/runtime/host-load-ledger-lock.js +185 -0
  41. package/dist/runtime/host-load-sampler.d.ts +126 -0
  42. package/dist/runtime/host-load-sampler.js +232 -0
  43. package/dist/runtime/host-load-step-class.d.ts +68 -0
  44. package/dist/runtime/host-load-step-class.js +106 -0
  45. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  46. package/dist/runtime/host-load-step-reaper.js +95 -0
  47. package/dist/runtime/host-load-step-run.d.ts +73 -0
  48. package/dist/runtime/host-load-step-run.js +102 -0
  49. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  50. package/dist/runtime/host-load-token-ledger.js +421 -0
  51. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  52. package/dist/runtime/host-pressure-stall.js +168 -0
  53. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  54. package/dist/runtime/host-runtime-contract.js +6 -1
  55. package/dist/runtime/host-runtime-lease.d.ts +47 -3
  56. package/dist/runtime/host-runtime-lease.js +270 -14
  57. package/dist/runtime/host-runtime-promotion.js +12 -0
  58. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  59. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  60. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  61. package/dist/runtime/host-runtime-requirements.js +117 -0
  62. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  63. package/dist/runtime/managed-command-teardown.js +607 -0
  64. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  65. package/dist/runtime/playwright-browser-cache.js +227 -0
  66. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  67. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  68. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  69. package/dist/sandbox/host-capacity-broker.js +315 -0
  70. package/dist/sandbox/runtime.d.ts +10 -1
  71. package/dist/sandbox/runtime.js +45 -2
  72. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  73. package/dist/sandbox/sandbox-cgroups.js +42 -0
  74. package/dist/session/managed-attempt-tools.d.ts +27 -0
  75. package/dist/session/managed-attempt-tools.js +356 -40
  76. package/dist/session/managed-build-coordinator.d.ts +1 -1
  77. package/dist/session/managed-build-coordinator.js +4 -1
  78. package/dist/session/managed-command-host-load.d.ts +45 -0
  79. package/dist/session/managed-command-host-load.js +82 -0
  80. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  81. package/dist/session/mcp-argument-coercion.js +121 -0
  82. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  83. package/dist/session/phase-completion.artifacts.js +98 -25
  84. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  85. package/dist/session/phase-completion.command-validation.js +77 -0
  86. package/dist/session/phase-completion.d.ts +4 -0
  87. package/dist/session/phase-completion.helpers.js +13 -12
  88. package/dist/session/phase-completion.js +4 -0
  89. package/dist/session/phase-completion.prompts.js +6 -1
  90. package/dist/session/phase-completion.runtime.d.ts +5 -3
  91. package/dist/session/phase-completion.runtime.js +70 -35
  92. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  93. package/dist/session/phase-completion.schema-parts.js +188 -0
  94. package/dist/session/phase-completion.schemas.d.ts +3 -3
  95. package/dist/session/phase-completion.schemas.js +184 -209
  96. package/dist/session/phase-completion.validation.d.ts +2 -3
  97. package/dist/session/phase-completion.validation.js +46 -92
  98. package/dist/session/pre-publication-host-load.d.ts +27 -0
  99. package/dist/session/pre-publication-host-load.js +111 -0
  100. package/dist/session/pre-publication-process.d.ts +23 -0
  101. package/dist/session/pre-publication-process.js +109 -0
  102. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  103. package/dist/session/pre-publication-skipped-tests.js +109 -0
  104. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  105. package/dist/session/pre-publication-step-execution.js +49 -0
  106. package/dist/session/pre-publication-validation.d.ts +9 -9
  107. package/dist/session/pre-publication-validation.js +48 -112
  108. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  109. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  110. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  111. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  112. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  113. package/dist/session/provider-cli/provider-cli.process.js +299 -25
  114. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  115. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  116. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  117. package/dist/session/provider-cli/provider-cli.service.js +244 -36
  118. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  119. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  120. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  121. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  122. package/dist/session/provider-cli/provider-output-state.js +9 -0
  123. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  124. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  125. package/dist/session/publishable-worktree-changes.js +193 -0
  126. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  127. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  128. package/dist/session/session.base.d.ts +3 -0
  129. package/dist/session/session.service.d.ts +5 -1
  130. package/dist/session/session.service.js +114 -5
  131. package/dist/session/session.types.d.ts +3 -0
  132. package/dist/session/session.types.js +15 -3
  133. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  134. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  135. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  136. package/dist/shared/process/host-process-supervisor.js +1 -1
  137. package/dist/shared/process/process-tree.d.ts +52 -0
  138. package/dist/shared/process/process-tree.js +144 -0
  139. package/dist/shared/process/process.d.ts +67 -0
  140. package/dist/shared/process/process.js +213 -11
  141. package/dist/version.d.ts +1 -1
  142. package/dist/version.js +1 -1
  143. package/dist/worktree/dependency-warmer.d.ts +25 -0
  144. package/dist/worktree/dependency-warmer.js +120 -10
  145. package/dist/worktree/worktree.service.d.ts +10 -1
  146. package/dist/worktree/worktree.service.js +42 -2
  147. package/dist/worktree/worktree.types.d.ts +7 -0
  148. package/package.json +1 -1
@@ -4,9 +4,12 @@ import path from "node:path";
4
4
  import { isAlias, parseDocument, visit } from "yaml";
5
5
  import { readCanonicalSourceFile } from "./canonical-source-file.js";
6
6
  import { isGeneratedOutputDirectoryName } from "./generated-output-reset.js";
7
+ import { parseHostRuntimeRequirements } from "./host-runtime-requirements.js";
7
8
  export const hostRuntimeContractPath = ".forge/forge.runtime.yml";
8
9
  export const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
9
10
  export const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
11
+ // Optional superuser login for operator-run .NET fixtures. Never reaches attempt, validation or provider processes.
12
+ export const hostRuntimeTestPostgresProvisionerEnvironment = "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING";
10
13
  const maximumContractBytes = 64 * 1024;
11
14
  const maximumDepth = 12;
12
15
  // Every discovery scan stops after this many directory entries. A monorepo needs a few
@@ -45,7 +48,7 @@ const ignoredDiscoveryDirectories = new Set([
45
48
  "vendor",
46
49
  "venv",
47
50
  ]);
48
- const topLevelKeys = new Set(["schemaVersion", "runtime"]);
51
+ const topLevelKeys = new Set(["schemaVersion", "runtime", "requires", "costHints"]);
49
52
  const runtimeKeys = new Set(["hostConcurrency", "ports", "playwright", "browserProfile", "singletonResources"]);
50
53
  const portKeys = new Set(["adapter", "launch", "env", "baseUrlEnv", "format"]);
51
54
  const launchKeys = new Set(["command", "args", "workingDirectory", "environment"]);
@@ -547,6 +550,7 @@ export function validateHostRuntimeContract(source) {
547
550
  throw new Error("runtime_contract_invalid: runtime.browserProfile must be isolated.");
548
551
  }
549
552
  const ports = parsePorts(runtime.ports);
553
+ const requires = parseHostRuntimeRequirements(root.requires, root.costHints);
550
554
  return {
551
555
  schemaVersion: 1,
552
556
  runtime: {
@@ -556,6 +560,7 @@ export function validateHostRuntimeContract(source) {
556
560
  browserProfile,
557
561
  singletonResources: parseSingletonResources(runtime.singletonResources),
558
562
  },
563
+ ...(requires ? { requires } : {}),
559
564
  };
560
565
  }
561
566
  function parsePlaywright(value, ports) {
@@ -1,4 +1,5 @@
1
- import type { RunOnceDispatchPacket } from "../session/session.types.js";
1
+ import type { HostRequirementsCheck } from "./host-runtime-requirements-check.js";
2
+ import { type RunOnceDispatchPacket } from "../session/session.types.js";
2
3
  import { type ProviderProcessRunner } from "../session/provider-cli/provider-cli.process.js";
3
4
  import { type RuntimeIsolationLease } from "./runtime-isolation-lease.js";
4
5
  import { type LoadedHostRuntimeContract } from "./host-runtime-contract.js";
@@ -12,6 +13,8 @@ import { type MemoryAdmissionDiagnostics } from "./memory-capacity.js";
12
13
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
13
14
  import { HostParallelPromotionStore } from "./host-runtime-promotion.js";
14
15
  import { type HostProcessRecovery } from "../shared/process/host-process-recovery.js";
16
+ import { HostLoadGovernor } from "./host-load-governor.js";
17
+ import { type HostLoadGovernorSource } from "./host-load-sampler.js";
15
18
  export interface HostRuntimeLeaseStart {
16
19
  readonly lease: RuntimeIsolationLease;
17
20
  readonly environment: Readonly<Record<string, string>>;
@@ -25,7 +28,7 @@ export interface HostRuntimeAdmissionCheckpoint {
25
28
  }
26
29
  export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
27
30
  export interface HostRuntimeProjectCheckpoint {
28
- readonly code: "host_runtime_build_started" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
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";
29
32
  readonly message: string;
30
33
  readonly data?: Readonly<Record<string, unknown>>;
31
34
  }
@@ -92,10 +95,17 @@ export interface HostNodeRuntimeLaunch<T> extends NodeRuntimeAdapterLaunch<T> {
92
95
  readonly runtimeLease: RuntimeIsolationLease;
93
96
  }
94
97
  export interface HostRuntimeLeaseRuntime {
98
+ setRequirementsCheck?(check: HostRequirementsCheck | null): void;
95
99
  acquirePreparation?(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
96
100
  acquire(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
97
101
  start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
98
102
  startConfiguredProject(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
103
+ /**
104
+ * Stops the attempt's configured project processes, releases their ports, and
105
+ * starts them again (rebuilding when sources changed) so the stack serves the
106
+ * current workspace. Returns the environment with the newly assigned URLs.
107
+ */
108
+ restartConfiguredProject?(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
99
109
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
100
110
  providerProcessRunner?(dispatchAttemptId: string, fencingToken: string): ProviderProcessRunner | null;
101
111
  providerMemoryTelemetry?(dispatchAttemptId: string, fencingToken: string): AttemptProcessTreeMemoryTelemetry | null;
@@ -104,7 +114,10 @@ export interface HostRuntimeLeaseRuntime {
104
114
  hasForegroundDemand?(): boolean;
105
115
  reap?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
106
116
  snapshot?(): HostRuntimeCapacitySnapshot;
117
+ /** Variables that let the completion MCP server share this host's load governor. */
118
+ hostLoadChildEnvironment?(): Readonly<Record<string, string>>;
107
119
  }
120
+ export type HostRuntimeAdmissionPriority = "foreground" | "background";
108
121
  export interface HostCapacityResourceSample {
109
122
  readonly totalMemoryBytes: number;
110
123
  readonly availableMemoryBytes: number;
@@ -143,7 +156,13 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
143
156
  private readonly capacityConfiguration;
144
157
  private readonly memoryAvailability;
145
158
  private readonly executionRoot;
146
- 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);
159
+ /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
160
+ readonly hostLoadGovernor: HostLoadGovernor;
161
+ private requirementsCheck;
162
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
163
+ setRequirementsCheck(check: HostRequirementsCheck | null): void;
164
+ 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);
165
+ hostLoadChildEnvironment(): Readonly<Record<string, string>>;
147
166
  reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
148
167
  snapshot(): HostRuntimeCapacitySnapshot;
149
168
  hasForegroundDemand(): boolean;
@@ -165,6 +184,24 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
165
184
  start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
166
185
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
167
186
  startConfiguredProject(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
187
+ /**
188
+ * Launches the configured project. Only the first launch, from the admitted commit's clean
189
+ * source, may record parallel-safety proof: a restart serves the workspace after the provider
190
+ * edited it, and a proof observed there would be stored under the admitted commit and could
191
+ * move this or a later attempt at that commit into shared admission for source it never ran.
192
+ */
193
+ private launchConfiguredProject;
194
+ /**
195
+ * Relaunches the configured project so it serves the current workspace. Every
196
+ * configured process stops (the API port changes, so the dev server's proxy target
197
+ * must change with it), its port reservation is released and dropped from the
198
+ * persisted lease, and the regular start path runs again, including the ASP.NET
199
+ * prebuild, whose receipt rebuilds only when the sources changed.
200
+ */
201
+ restartConfiguredProject(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
202
+ private runConfiguredProjectRestart;
203
+ /** Stops configured project processes in reverse launch order and releases their ports. */
204
+ private stopConfiguredProject;
168
205
  providerProcessRunner(dispatchAttemptId: string, fencingToken: string): ProviderProcessRunner | null;
169
206
  private markCapacityReservationRunning;
170
207
  providerMemoryTelemetry(dispatchAttemptId: string, fencingToken: string): AttemptProcessTreeMemoryTelemetry | null;
@@ -215,3 +252,10 @@ export declare class HostRuntimeCapacityRequestImpossibleError extends Error {
215
252
  }
216
253
  export declare function hostRuntimeEventResources(lease: RuntimeIsolationLease, runtimeContract?: LoadedHostRuntimeContract, executionClass?: HostRuntimeExecutionClass): Record<string, unknown>;
217
254
  export declare function hostRuntimeSingletonKeys(dispatch: RunOnceDispatchPacket): readonly string[];
255
+ /**
256
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
257
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
258
+ * stack is down: after its ports are released another attempt may be assigned them.
259
+ */
260
+ export declare function hostRuntimeStackEnvironmentKeys(runtimeContract: LoadedHostRuntimeContract): readonly string[];
261
+ export declare function runtimeAdmissionPriority(dispatch: RunOnceDispatchPacket): HostRuntimeAdmissionPriority;
@@ -7,6 +7,7 @@ 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";
12
13
  import { redactText } from "../shared/redaction/redaction.js";
@@ -16,6 +17,7 @@ import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-co
16
17
  import { HostPortBroker, } from "./host-port-broker.js";
17
18
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
18
19
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
20
+ import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
19
21
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
20
22
  import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
21
23
  import { HostListenerInspector } from "./host-listener-inspector.js";
@@ -29,6 +31,11 @@ import { readCanonicalSourceFile } from "./canonical-source-file.js";
29
31
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
30
32
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
31
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";
32
39
  const hostCapacityWaiterScanLimit = 64;
33
40
  const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
34
41
  export class HostRuntimeLeaseManager {
@@ -63,7 +70,14 @@ export class HostRuntimeLeaseManager {
63
70
  capacityConfiguration;
64
71
  memoryAvailability;
65
72
  executionRoot;
66
- 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) {
73
+ /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
74
+ hostLoadGovernor;
75
+ requirementsCheck = null;
76
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
77
+ setRequirementsCheck(check) {
78
+ this.requirementsCheck = check;
79
+ }
80
+ 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) {
67
81
  this.stateRoot = stateRoot;
68
82
  this.processSupervisors = processSupervisors;
69
83
  this.processRunner = processRunner;
@@ -73,6 +87,7 @@ export class HostRuntimeLeaseManager {
73
87
  this.processRecovery = processRecovery;
74
88
  this.capacityResourceSample = capacityResourceSample;
75
89
  this.databaseBroker = databaseBroker;
90
+ this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
76
91
  this.executionRoot = path.resolve(executionRoot ?? stateRoot);
77
92
  if (executionRoot !== undefined)
78
93
  assertHostExecutionRoot(this.executionRoot);
@@ -82,7 +97,12 @@ export class HostRuntimeLeaseManager {
82
97
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
83
98
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
84
99
  }
100
+ hostLoadChildEnvironment() {
101
+ return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
102
+ }
85
103
  async reap(options) {
104
+ // Heavy-step tokens whose owner died or whose lease lapsed are returned first.
105
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
86
106
  await this.refreshKnownPromotions();
87
107
  const recoveredAttempts = [];
88
108
  const report = {
@@ -207,6 +227,11 @@ export class HostRuntimeLeaseManager {
207
227
  // drop that met a lingering session) are removed once no live lease holds them.
208
228
  // A degraded lease may still own running processes after a restart, so its database is kept.
209
229
  await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
230
+ // Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
231
+ // ended with a crashed bridge or MCP server) are returned once no live lease holds
232
+ // their attempt; a degraded lease may still own the running step, so its tokens stay.
233
+ await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
234
+ || (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
210
235
  return report;
211
236
  }
212
237
  snapshot() {
@@ -924,6 +949,15 @@ export class HostRuntimeLeaseManager {
924
949
  let attemptRootIdentity = null;
925
950
  try {
926
951
  const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
952
+ // Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
953
+ // API learns the requirements in the first place.
954
+ const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
955
+ ? []
956
+ : this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
957
+ if (unmetRequirements.length > 0) {
958
+ // Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
959
+ throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
960
+ }
927
961
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
928
962
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
929
963
  }
@@ -1088,6 +1122,8 @@ export class HostRuntimeLeaseManager {
1088
1122
  parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1089
1123
  processSupervisor,
1090
1124
  adapterCleanups: [],
1125
+ adapterCleanupsByPort: new Map(),
1126
+ restartingConfiguredProject: false,
1091
1127
  pendingAdapterLaunches: new Map(),
1092
1128
  runtimeResourcesReleased: false,
1093
1129
  releasing: false,
@@ -1150,6 +1186,15 @@ export class HostRuntimeLeaseManager {
1150
1186
  await this.writeLedger(renewed);
1151
1187
  }
1152
1188
  async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1189
+ return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
1190
+ }
1191
+ /**
1192
+ * Launches the configured project. Only the first launch, from the admitted commit's clean
1193
+ * source, may record parallel-safety proof: a restart serves the workspace after the provider
1194
+ * edited it, and a proof observed there would be stored under the admitted commit and could
1195
+ * move this or a later attempt at that commit into shared admission for source it never ran.
1196
+ */
1197
+ async launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, promote) {
1153
1198
  const active = this.active.get(dispatchAttemptId);
1154
1199
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1155
1200
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
@@ -1171,6 +1216,11 @@ export class HostRuntimeLeaseManager {
1171
1216
  executionClass: active.executionClass,
1172
1217
  };
1173
1218
  }
1219
+ const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
1220
+ // A host without the project's pinned browsers fails here, before any database,
1221
+ // build, launch, or promotion work that the attempt would otherwise waste.
1222
+ if (playwrightConfig)
1223
+ await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
1174
1224
  const owner = hostPortOwner(active.lease);
1175
1225
  const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
1176
1226
  if (!logDirectory)
@@ -1220,7 +1270,29 @@ export class HostRuntimeLeaseManager {
1220
1270
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1221
1271
  data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1222
1272
  });
1223
- const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal, capabilitySecrets), signal);
1273
+ let hostLoadWaitMs = null;
1274
+ const build = await ensureAspNetRuntimePrebuilt(prebuild,
1275
+ // Only a real build (not a verified cache hit) takes a host load token.
1276
+ async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
1277
+ classification: aspNetPrebuildStepClass,
1278
+ label: prebuild.projectPath,
1279
+ dispatchAttemptId,
1280
+ priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
1281
+ signal: buildSignal,
1282
+ onWaiting: async (decision) => await onProjectCheckpoint?.({
1283
+ code: "host_runtime_build_waiting_for_host_capacity",
1284
+ message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
1285
+ data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
1286
+ }),
1287
+ }, async (waitMs, control) => {
1288
+ hostLoadWaitMs = waitMs;
1289
+ // A reclaimed token stops the build: its capacity is no longer reserved. So does a
1290
+ // build whose process tree cannot be recorded on its token (a reclaim could not stop it).
1291
+ const unrecorded = new AbortController();
1292
+ const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
1293
+ return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
1294
+ .catch((error) => { unrecorded.abort(error); }));
1295
+ }), signal);
1224
1296
  await onProjectCheckpoint?.({
1225
1297
  code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1226
1298
  message: build.cacheHit
@@ -1230,6 +1302,7 @@ export class HostRuntimeLeaseManager {
1230
1302
  input_commit_sha: active.inputCommitSha,
1231
1303
  build_fingerprint: build.fingerprint,
1232
1304
  receipt_path: build.receiptPath,
1305
+ ...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
1233
1306
  },
1234
1307
  });
1235
1308
  }
@@ -1242,7 +1315,7 @@ export class HostRuntimeLeaseManager {
1242
1315
  },
1243
1316
  }, launcher, signal);
1244
1317
  }
1245
- const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1318
+ const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
1246
1319
  const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1247
1320
  const playwright = active.runtimeContract.contract.runtime.playwright;
1248
1321
  if (!playwright) {
@@ -1281,6 +1354,93 @@ export class HostRuntimeLeaseManager {
1281
1354
  executionClass: active.executionClass,
1282
1355
  };
1283
1356
  }
1357
+ /**
1358
+ * Relaunches the configured project so it serves the current workspace. Every
1359
+ * configured process stops (the API port changes, so the dev server's proxy target
1360
+ * must change with it), its port reservation is released and dropped from the
1361
+ * persisted lease, and the regular start path runs again, including the ASP.NET
1362
+ * prebuild, whose receipt rebuilds only when the sources changed.
1363
+ */
1364
+ async restartConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1365
+ const active = this.active.get(dispatchAttemptId);
1366
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1367
+ throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1368
+ }
1369
+ if (signal?.aborted)
1370
+ throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
1371
+ if (active.restartingConfiguredProject) {
1372
+ throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
1373
+ }
1374
+ active.restartingConfiguredProject = true;
1375
+ // Release cancels the whole restart through this controller and waits for it to settle.
1376
+ const controller = linkedAbortController(signal);
1377
+ const promise = this.runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, controller.signal, onProjectCheckpoint);
1378
+ const restart = { controller, promise };
1379
+ active.configuredProjectRestart = restart;
1380
+ try {
1381
+ return await promise;
1382
+ }
1383
+ finally {
1384
+ // The controller is not aborted on settle: adapters this restart launched keep it as their
1385
+ // parent signal for as long as they run, exactly as they would keep the caller's signal.
1386
+ if (active.configuredProjectRestart === restart)
1387
+ active.configuredProjectRestart = null;
1388
+ active.restartingConfiguredProject = false;
1389
+ }
1390
+ }
1391
+ 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.");
1398
+ }
1399
+ const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1400
+ const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
1401
+ if (pendingPort) {
1402
+ throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
1403
+ }
1404
+ const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
1405
+ if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
1406
+ // The generated Playwright config targets the stack being stopped. If the restart fails, no
1407
+ // config may be left pointing at ports another attempt can now be assigned.
1408
+ await this.playwrightAdapter.discardOverlay(temporaryDirectory);
1409
+ }
1410
+ await this.stopConfiguredProject(active, portNames);
1411
+ // Keeps whatever admission the attempt holds; see launchConfiguredProject.
1412
+ const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
1413
+ if (active.releasing) {
1414
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1415
+ }
1416
+ return restarted;
1417
+ }
1418
+ /** Stops configured project processes in reverse launch order and releases their ports. */
1419
+ async stopConfiguredProject(active, portNames) {
1420
+ const launched = active.lease.resources.ports
1421
+ .map(port => port.name)
1422
+ .filter(name => portNames.includes(name))
1423
+ .reverse();
1424
+ for (const name of launched) {
1425
+ if (active.releasing) {
1426
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1427
+ }
1428
+ const cleanup = active.adapterCleanupsByPort.get(name);
1429
+ if (!cleanup) {
1430
+ throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
1431
+ }
1432
+ // A failed stop keeps the cleanup and the port record for the fenced release retry.
1433
+ await cleanup();
1434
+ removeCleanup(active.adapterCleanups, cleanup);
1435
+ active.adapterCleanupsByPort.delete(name);
1436
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1437
+ ...active.lease.resources,
1438
+ ports: active.lease.resources.ports.filter(port => port.name !== name),
1439
+ });
1440
+ await this.writeLedger(runtimeLease);
1441
+ active.lease = runtimeLease;
1442
+ }
1443
+ }
1284
1444
  providerProcessRunner(dispatchAttemptId, fencingToken) {
1285
1445
  const active = this.active.get(dispatchAttemptId);
1286
1446
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
@@ -1368,6 +1528,7 @@ export class HostRuntimeLeaseManager {
1368
1528
  unlinkAbortController(controller, signal);
1369
1529
  };
1370
1530
  active.adapterCleanups.push(cleanup);
1531
+ active.adapterCleanupsByPort.set(portName, cleanup);
1371
1532
  try {
1372
1533
  if (active.releasing)
1373
1534
  throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
@@ -1390,6 +1551,8 @@ export class HostRuntimeLeaseManager {
1390
1551
  try {
1391
1552
  await cleanup();
1392
1553
  removeCleanup(active.adapterCleanups, cleanup);
1554
+ if (active.adapterCleanupsByPort.get(portName) === cleanup)
1555
+ active.adapterCleanupsByPort.delete(portName);
1393
1556
  }
1394
1557
  catch {
1395
1558
  // Preserve the cleanup and broker claim for the fenced release retry.
@@ -1414,6 +1577,9 @@ export class HostRuntimeLeaseManager {
1414
1577
  if (!preservePreparation)
1415
1578
  this.pendingRenewals.delete(dispatchAttemptId);
1416
1579
  if (!active) {
1580
+ // Queued steps are cancelled and running ones stopped; each returns its own
1581
+ // token once its processes are gone (never before, or capacity is reused early).
1582
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1417
1583
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1418
1584
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1419
1585
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
@@ -1423,10 +1589,20 @@ export class HostRuntimeLeaseManager {
1423
1589
  if (active.lease.fencingToken !== fencingToken)
1424
1590
  return null;
1425
1591
  active.releasing = true;
1592
+ // Attempt teardown cancels the attempt's queued heavy steps and stops its running
1593
+ // ones. Each running step (an ASP.NET prebuild, an install, a validation step)
1594
+ // returns its own token only after its processes have exited, so the capacity is
1595
+ // not reused while, say, a build is still being terminated.
1596
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1426
1597
  for (const pending of active.pendingAdapterLaunches.values()) {
1427
1598
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1428
1599
  }
1429
1600
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1601
+ const restart = active.configuredProjectRestart;
1602
+ if (restart) {
1603
+ restart.controller.abort("Host runtime release cancelled the configured project restart.");
1604
+ await restart.promise.catch(() => undefined);
1605
+ }
1430
1606
  await active.databaseProvision?.catch(() => undefined);
1431
1607
  let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1432
1608
  active.lease = releasing;
@@ -1434,7 +1610,17 @@ export class HostRuntimeLeaseManager {
1434
1610
  try {
1435
1611
  if (!active.runtimeResourcesReleased) {
1436
1612
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1613
+ // The attempt's MCP servers and process trees are stopped now; tokens they held
1614
+ // belong to dead owners and go back to the host budget at once, including any
1615
+ // without a recorded process tree (their steps were inside the stopped trees).
1616
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
1617
+ await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
1618
+ .catch(() => undefined);
1619
+ // This bridge's own steps whose trees only stopAll could prove gone (a supervised
1620
+ // validation step whose termination failed earlier) return their tokens now.
1621
+ await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1437
1622
  await releaseAdapterResources(active.adapterCleanups);
1623
+ active.adapterCleanupsByPort.clear();
1438
1624
  if (active.databaseCapability && this.databaseBroker) {
1439
1625
  // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1440
1626
  await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
@@ -1532,18 +1718,46 @@ export class HostRuntimeLeaseManager {
1532
1718
  if (logsEntry.kind !== "directory") {
1533
1719
  throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1534
1720
  }
1535
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1536
1721
  const outcomes = [];
1537
- for (const entry of entries) {
1538
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1539
- continue;
1540
- const metadataPath = path.join(logsRoot, entry.name);
1541
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1542
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1543
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1722
+ const failures = [];
1723
+ try {
1724
+ const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1725
+ for (const entry of entries) {
1726
+ if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1727
+ continue;
1728
+ const metadataPath = path.join(logsRoot, entry.name);
1729
+ const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1730
+ if (!validHostProcessSupervisorMetadata(value, lease)) {
1731
+ throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1732
+ }
1733
+ outcomes.push(await this.processRecovery.recover(value));
1734
+ }
1735
+ }
1736
+ catch (error) {
1737
+ failures.push(error);
1738
+ }
1739
+ // Managed commands run in their own process groups and record their ownership apart
1740
+ // from the attempt's supervised children. They are recovered even when recovering a
1741
+ // supervised child failed, and both failures are reported together.
1742
+ try {
1743
+ const managed = await terminateAttemptManagedCommands({
1744
+ logDirectory: logsRoot,
1745
+ dispatchAttemptId: lease.dispatchAttemptId,
1746
+ runtimeLeaseId: lease.executionLeaseId,
1747
+ pinnedLogDirectory: logsEntry.identity,
1748
+ }, { reason: "attempt_teardown" });
1749
+ for (const command of managed) {
1750
+ if (command.outcome === "terminated" || command.outcome === "pid_reused")
1751
+ outcomes.push(command.outcome);
1544
1752
  }
1545
- outcomes.push(await this.processRecovery.recover(value));
1546
1753
  }
1754
+ catch (error) {
1755
+ failures.push(error);
1756
+ }
1757
+ if (failures.length === 1)
1758
+ throw failures[0];
1759
+ if (failures.length > 1)
1760
+ throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1547
1761
  return outcomes;
1548
1762
  }
1549
1763
  async markLedgerDegraded(ledger) {
@@ -1919,6 +2133,18 @@ class AttemptSupervisedProviderProcessRunner {
1919
2133
  : new Set();
1920
2134
  const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
1921
2135
  this.onProcessTreeStarted();
2136
+ try {
2137
+ return await this.awaitProviderResult(child, baselineListeners, signal);
2138
+ }
2139
+ finally {
2140
+ // The provider tree, and the MCP server inside it, is gone. A managed command that
2141
+ // server started now has no supervisor and no receipt writer, so it must not keep
2142
+ // running into the next provider generation. This never rejects; a command it
2143
+ // cannot prove stopped is left to attempt teardown, which fails closed.
2144
+ await this.supervisor.stopOrphanedManagedCommands();
2145
+ }
2146
+ }
2147
+ async awaitProviderResult(child, baselineListeners, signal) {
1922
2148
  if (!this.enforceNoListeners)
1923
2149
  return await child.result;
1924
2150
  let settled = false;
@@ -2094,7 +2320,36 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2094
2320
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2095
2321
  return environment;
2096
2322
  }
2097
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = []) {
2323
+ /**
2324
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
2325
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
2326
+ * stack is down: after its ports are released another attempt may be assigned them.
2327
+ */
2328
+ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2329
+ const keys = new Set([
2330
+ "FORGE_E2E_API_URL",
2331
+ "FORGE_E2E_WEB_URL",
2332
+ "FORGE_BASE_URL",
2333
+ "FORGE_PLAYWRIGHT_BASE_URL",
2334
+ // The generated Playwright config embeds the base URL.
2335
+ "FORGE_PLAYWRIGHT_CONFIG",
2336
+ ]);
2337
+ for (const port of runtimeContract.contract.runtime.ports) {
2338
+ const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
2339
+ keys.add(port.env);
2340
+ if (port.baseUrlEnv)
2341
+ keys.add(port.baseUrlEnv);
2342
+ keys.add(`FORGE_${normalizedName}_PORT`);
2343
+ keys.add(`FORGE_${normalizedName}_URL`);
2344
+ }
2345
+ return [...keys];
2346
+ }
2347
+ function anySignal(...signals) {
2348
+ return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2349
+ }
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) {
2098
2353
  const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2099
2354
  const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2100
2355
  const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
@@ -2119,6 +2374,7 @@ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal,
2119
2374
  await append(stderrLogPath, line);
2120
2375
  },
2121
2376
  }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2377
+ await onStarted?.(child.metadataPath);
2122
2378
  const result = await child.result;
2123
2379
  return {
2124
2380
  exitCode: result.exitCode,
@@ -2161,7 +2417,7 @@ function runtimeExecutionClass(dispatch) {
2161
2417
  ? "analysis_only"
2162
2418
  : "managed_runtime";
2163
2419
  }
2164
- function runtimeAdmissionPriority(dispatch) {
2420
+ export function runtimeAdmissionPriority(dispatch) {
2165
2421
  return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2166
2422
  || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2167
2423
  ? "background"
@@ -145,12 +145,24 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
145
145
  const canonical = JSON.stringify({
146
146
  schemaVersion: runtimeContract.contract.schemaVersion,
147
147
  runtime: runtimeContract.contract.runtime,
148
+ // Requirements join the fingerprint only when declared, so fingerprints of contracts
149
+ // written before decision 0013 (and their stored promotions) stay unchanged.
150
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
148
151
  derivedCandidateFingerprint: runtimeContract.source === "derived"
149
152
  ? runtimeContract.discovery?.candidateFingerprint ?? null
150
153
  : null,
151
154
  });
152
155
  return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
153
156
  }
157
+ // Cost hints are estimates, not placement constraints: they never change the fingerprint.
158
+ function requirementsFingerprintPart(requires) {
159
+ if (!requires)
160
+ return {};
161
+ const { costHints: _costHints, ...constraints } = requires;
162
+ const declared = constraints.minThreads !== null || constraints.minMemoryGiB !== null || constraints.toolchains.length > 0
163
+ || constraints.docker || constraints.playwright !== null || constraints.testPostgres !== null;
164
+ return declared ? { requires: constraints } : {};
165
+ }
154
166
  export function hostRuntimeParallelEligible(runtimeContract) {
155
167
  const runtime = runtimeContract.contract.runtime;
156
168
  const launchedPorts = runtime.ports.filter(port => port.launch !== null);