@loucompanion/forge-bridge 0.1.4-dev.24bdf60b0b53 → 0.1.4-dev.25308ca4a63d

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 (139) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.base.d.ts +7 -0
  3. package/dist/bridge/bridge.service.d.ts +32 -2
  4. package/dist/bridge/bridge.service.js +128 -10
  5. package/dist/bridge/bridge.types.d.ts +11 -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/runner-host-capabilities.d.ts +2 -0
  9. package/dist/bridge/runner-host-capabilities.js +4 -0
  10. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  11. package/dist/bridge/test-postgres-capability.js +120 -0
  12. package/dist/cleanup/cleanup.service.d.ts +9 -0
  13. package/dist/cleanup/cleanup.service.js +72 -109
  14. package/dist/cleanup/cleanup.types.d.ts +4 -0
  15. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  16. package/dist/cleanup/forge-owned-paths.js +53 -0
  17. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  18. package/dist/cleanup/host-runtime-ledger.js +109 -0
  19. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  20. package/dist/cleanup/managed-branch-sweep.js +111 -0
  21. package/dist/cli/cli.service.js +20 -3
  22. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  23. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  24. package/dist/runtime/host-database-capability-boundary.js +1 -0
  25. package/dist/runtime/host-facts.d.ts +35 -0
  26. package/dist/runtime/host-facts.js +95 -0
  27. package/dist/runtime/host-load-admission.d.ts +52 -0
  28. package/dist/runtime/host-load-admission.js +84 -0
  29. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  30. package/dist/runtime/host-load-child-environment.js +65 -0
  31. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  32. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  33. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  34. package/dist/runtime/host-load-governor-config.js +46 -0
  35. package/dist/runtime/host-load-governor.d.ts +172 -0
  36. package/dist/runtime/host-load-governor.js +519 -0
  37. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  38. package/dist/runtime/host-load-ledger-lock.js +185 -0
  39. package/dist/runtime/host-load-sampler.d.ts +126 -0
  40. package/dist/runtime/host-load-sampler.js +232 -0
  41. package/dist/runtime/host-load-step-class.d.ts +68 -0
  42. package/dist/runtime/host-load-step-class.js +106 -0
  43. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  44. package/dist/runtime/host-load-step-reaper.js +95 -0
  45. package/dist/runtime/host-load-step-run.d.ts +73 -0
  46. package/dist/runtime/host-load-step-run.js +102 -0
  47. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  48. package/dist/runtime/host-load-token-ledger.js +421 -0
  49. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  50. package/dist/runtime/host-pressure-stall.js +168 -0
  51. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  52. package/dist/runtime/host-runtime-contract.js +6 -1
  53. package/dist/runtime/host-runtime-lease.d.ts +47 -3
  54. package/dist/runtime/host-runtime-lease.js +215 -5
  55. package/dist/runtime/host-runtime-promotion.js +12 -0
  56. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  57. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  58. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  59. package/dist/runtime/host-runtime-requirements.js +117 -0
  60. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  61. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  62. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  63. package/dist/sandbox/host-capacity-broker.js +315 -0
  64. package/dist/sandbox/runtime.d.ts +10 -1
  65. package/dist/sandbox/runtime.js +45 -2
  66. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  67. package/dist/sandbox/sandbox-cgroups.js +42 -0
  68. package/dist/session/managed-attempt-tools.d.ts +2 -0
  69. package/dist/session/managed-attempt-tools.js +156 -37
  70. package/dist/session/managed-command-host-load.d.ts +45 -0
  71. package/dist/session/managed-command-host-load.js +82 -0
  72. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  73. package/dist/session/mcp-argument-coercion.js +121 -0
  74. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  75. package/dist/session/phase-completion.artifacts.js +98 -25
  76. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  77. package/dist/session/phase-completion.command-validation.js +77 -0
  78. package/dist/session/phase-completion.d.ts +4 -0
  79. package/dist/session/phase-completion.helpers.js +13 -12
  80. package/dist/session/phase-completion.js +4 -0
  81. package/dist/session/phase-completion.prompts.js +6 -1
  82. package/dist/session/phase-completion.runtime.d.ts +5 -3
  83. package/dist/session/phase-completion.runtime.js +49 -19
  84. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  85. package/dist/session/phase-completion.schema-parts.js +188 -0
  86. package/dist/session/phase-completion.schemas.d.ts +3 -3
  87. package/dist/session/phase-completion.schemas.js +184 -209
  88. package/dist/session/phase-completion.validation.d.ts +2 -3
  89. package/dist/session/phase-completion.validation.js +46 -92
  90. package/dist/session/pre-publication-host-load.d.ts +27 -0
  91. package/dist/session/pre-publication-host-load.js +111 -0
  92. package/dist/session/pre-publication-process.d.ts +3 -0
  93. package/dist/session/pre-publication-process.js +25 -12
  94. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  95. package/dist/session/pre-publication-skipped-tests.js +109 -0
  96. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  97. package/dist/session/pre-publication-step-execution.js +49 -0
  98. package/dist/session/pre-publication-validation.d.ts +9 -9
  99. package/dist/session/pre-publication-validation.js +44 -59
  100. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  101. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  102. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  104. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  105. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  107. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  108. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  109. package/dist/session/provider-cli/provider-cli.service.js +237 -33
  110. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  111. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  112. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  113. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  114. package/dist/session/provider-cli/provider-output-state.js +9 -0
  115. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  116. package/dist/session/publishable-worktree-changes.js +193 -0
  117. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  118. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  119. package/dist/session/session.base.d.ts +3 -0
  120. package/dist/session/session.service.d.ts +5 -1
  121. package/dist/session/session.service.js +114 -5
  122. package/dist/session/session.types.d.ts +3 -0
  123. package/dist/session/session.types.js +15 -3
  124. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  125. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  126. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  127. package/dist/shared/process/host-process-supervisor.js +1 -1
  128. package/dist/shared/process/process-tree.d.ts +52 -0
  129. package/dist/shared/process/process-tree.js +144 -0
  130. package/dist/shared/process/process.d.ts +67 -0
  131. package/dist/shared/process/process.js +213 -11
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/dependency-warmer.d.ts +25 -0
  135. package/dist/worktree/dependency-warmer.js +46 -10
  136. package/dist/worktree/worktree.service.d.ts +10 -1
  137. package/dist/worktree/worktree.service.js +42 -2
  138. package/dist/worktree/worktree.types.d.ts +7 -0
  139. 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";
@@ -30,6 +31,11 @@ import { readCanonicalSourceFile } from "./canonical-source-file.js";
30
31
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
31
32
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
32
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";
33
39
  const hostCapacityWaiterScanLimit = 64;
34
40
  const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
35
41
  export class HostRuntimeLeaseManager {
@@ -64,7 +70,14 @@ export class HostRuntimeLeaseManager {
64
70
  capacityConfiguration;
65
71
  memoryAvailability;
66
72
  executionRoot;
67
- 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) {
68
81
  this.stateRoot = stateRoot;
69
82
  this.processSupervisors = processSupervisors;
70
83
  this.processRunner = processRunner;
@@ -74,6 +87,7 @@ export class HostRuntimeLeaseManager {
74
87
  this.processRecovery = processRecovery;
75
88
  this.capacityResourceSample = capacityResourceSample;
76
89
  this.databaseBroker = databaseBroker;
90
+ this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
77
91
  this.executionRoot = path.resolve(executionRoot ?? stateRoot);
78
92
  if (executionRoot !== undefined)
79
93
  assertHostExecutionRoot(this.executionRoot);
@@ -83,7 +97,12 @@ export class HostRuntimeLeaseManager {
83
97
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
84
98
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
85
99
  }
100
+ hostLoadChildEnvironment() {
101
+ return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
102
+ }
86
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);
87
106
  await this.refreshKnownPromotions();
88
107
  const recoveredAttempts = [];
89
108
  const report = {
@@ -208,6 +227,11 @@ export class HostRuntimeLeaseManager {
208
227
  // drop that met a lingering session) are removed once no live lease holds them.
209
228
  // A degraded lease may still own running processes after a restart, so its database is kept.
210
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);
211
235
  return report;
212
236
  }
213
237
  snapshot() {
@@ -925,6 +949,15 @@ export class HostRuntimeLeaseManager {
925
949
  let attemptRootIdentity = null;
926
950
  try {
927
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
+ }
928
961
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
929
962
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
930
963
  }
@@ -1089,6 +1122,8 @@ export class HostRuntimeLeaseManager {
1089
1122
  parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1090
1123
  processSupervisor,
1091
1124
  adapterCleanups: [],
1125
+ adapterCleanupsByPort: new Map(),
1126
+ restartingConfiguredProject: false,
1092
1127
  pendingAdapterLaunches: new Map(),
1093
1128
  runtimeResourcesReleased: false,
1094
1129
  releasing: false,
@@ -1151,6 +1186,15 @@ export class HostRuntimeLeaseManager {
1151
1186
  await this.writeLedger(renewed);
1152
1187
  }
1153
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) {
1154
1198
  const active = this.active.get(dispatchAttemptId);
1155
1199
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1156
1200
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
@@ -1226,7 +1270,29 @@ export class HostRuntimeLeaseManager {
1226
1270
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1227
1271
  data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1228
1272
  });
1229
- 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);
1230
1296
  await onProjectCheckpoint?.({
1231
1297
  code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1232
1298
  message: build.cacheHit
@@ -1236,6 +1302,7 @@ export class HostRuntimeLeaseManager {
1236
1302
  input_commit_sha: active.inputCommitSha,
1237
1303
  build_fingerprint: build.fingerprint,
1238
1304
  receipt_path: build.receiptPath,
1305
+ ...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
1239
1306
  },
1240
1307
  });
1241
1308
  }
@@ -1248,7 +1315,7 @@ export class HostRuntimeLeaseManager {
1248
1315
  },
1249
1316
  }, launcher, signal);
1250
1317
  }
1251
- const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1318
+ const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
1252
1319
  const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1253
1320
  const playwright = active.runtimeContract.contract.runtime.playwright;
1254
1321
  if (!playwright) {
@@ -1287,6 +1354,93 @@ export class HostRuntimeLeaseManager {
1287
1354
  executionClass: active.executionClass,
1288
1355
  };
1289
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
+ }
1290
1444
  providerProcessRunner(dispatchAttemptId, fencingToken) {
1291
1445
  const active = this.active.get(dispatchAttemptId);
1292
1446
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
@@ -1374,6 +1528,7 @@ export class HostRuntimeLeaseManager {
1374
1528
  unlinkAbortController(controller, signal);
1375
1529
  };
1376
1530
  active.adapterCleanups.push(cleanup);
1531
+ active.adapterCleanupsByPort.set(portName, cleanup);
1377
1532
  try {
1378
1533
  if (active.releasing)
1379
1534
  throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
@@ -1396,6 +1551,8 @@ export class HostRuntimeLeaseManager {
1396
1551
  try {
1397
1552
  await cleanup();
1398
1553
  removeCleanup(active.adapterCleanups, cleanup);
1554
+ if (active.adapterCleanupsByPort.get(portName) === cleanup)
1555
+ active.adapterCleanupsByPort.delete(portName);
1399
1556
  }
1400
1557
  catch {
1401
1558
  // Preserve the cleanup and broker claim for the fenced release retry.
@@ -1420,6 +1577,9 @@ export class HostRuntimeLeaseManager {
1420
1577
  if (!preservePreparation)
1421
1578
  this.pendingRenewals.delete(dispatchAttemptId);
1422
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);
1423
1583
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1424
1584
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1425
1585
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
@@ -1429,10 +1589,20 @@ export class HostRuntimeLeaseManager {
1429
1589
  if (active.lease.fencingToken !== fencingToken)
1430
1590
  return null;
1431
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);
1432
1597
  for (const pending of active.pendingAdapterLaunches.values()) {
1433
1598
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1434
1599
  }
1435
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
+ }
1436
1606
  await active.databaseProvision?.catch(() => undefined);
1437
1607
  let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1438
1608
  active.lease = releasing;
@@ -1440,7 +1610,17 @@ export class HostRuntimeLeaseManager {
1440
1610
  try {
1441
1611
  if (!active.runtimeResourcesReleased) {
1442
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);
1443
1622
  await releaseAdapterResources(active.adapterCleanups);
1623
+ active.adapterCleanupsByPort.clear();
1444
1624
  if (active.databaseCapability && this.databaseBroker) {
1445
1625
  // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1446
1626
  await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
@@ -2140,7 +2320,36 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2140
2320
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2141
2321
  return environment;
2142
2322
  }
2143
- 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) {
2144
2353
  const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2145
2354
  const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2146
2355
  const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
@@ -2165,6 +2374,7 @@ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal,
2165
2374
  await append(stderrLogPath, line);
2166
2375
  },
2167
2376
  }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2377
+ await onStarted?.(child.metadataPath);
2168
2378
  const result = await child.result;
2169
2379
  return {
2170
2380
  exitCode: result.exitCode,
@@ -2207,7 +2417,7 @@ function runtimeExecutionClass(dispatch) {
2207
2417
  ? "analysis_only"
2208
2418
  : "managed_runtime";
2209
2419
  }
2210
- function runtimeAdmissionPriority(dispatch) {
2420
+ export function runtimeAdmissionPriority(dispatch) {
2211
2421
  return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2212
2422
  || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2213
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);
@@ -0,0 +1,17 @@
1
+ import type { HostRuntimeRequirements } from "./host-runtime-requirements.js";
2
+ /** What this bridge host offers, for the accept-time requirements recheck (decision 0013). */
3
+ export interface HostRequirementFacts {
4
+ readonly logicalThreads: number;
5
+ readonly totalMemoryBytes: number;
6
+ readonly availableToolchains: readonly string[];
7
+ readonly dockerAvailable: boolean;
8
+ readonly browserLaunch: boolean;
9
+ readonly testPostgresSuperuser: boolean | null;
10
+ }
11
+ export type HostRequirementsCheck = (requires: HostRuntimeRequirements | null | undefined) => readonly string[];
12
+ /**
13
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
14
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
15
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
16
+ */
17
+ export declare function unmetHostRuntimeRequirements(requires: HostRuntimeRequirements | null | undefined, facts: HostRequirementFacts): readonly string[];
@@ -0,0 +1,29 @@
1
+ const gib = 1024 * 1024 * 1024;
2
+ /**
3
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
4
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
5
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
6
+ */
7
+ export function unmetHostRuntimeRequirements(requires, facts) {
8
+ if (!requires)
9
+ return [];
10
+ const unmet = [];
11
+ if (requires.minThreads !== null && facts.logicalThreads < requires.minThreads) {
12
+ unmet.push(`needs ≥ ${requires.minThreads} threads; this host has ${facts.logicalThreads}`);
13
+ }
14
+ if (requires.minMemoryGiB !== null && facts.totalMemoryBytes / gib < requires.minMemoryGiB) {
15
+ unmet.push(`needs ≥ ${requires.minMemoryGiB} GiB; this host has ${(Math.floor(facts.totalMemoryBytes / gib * 100) / 100)}`);
16
+ }
17
+ const available = new Set(facts.availableToolchains.map(name => name.toLowerCase()));
18
+ const missing = requires.toolchains.filter(name => !available.has(name));
19
+ if (missing.length > 0)
20
+ unmet.push(`needs ${missing.join(", ")}; this host does not have ${missing.length === 1 ? "it" : "them"}`);
21
+ if (requires.docker && !facts.dockerAvailable)
22
+ unmet.push("needs Docker; this host does not have it");
23
+ if (requires.testPostgres?.superuser && !facts.dockerAvailable && facts.testPostgresSuperuser !== true) {
24
+ unmet.push("needs Docker or a superuser test database; this host has neither");
25
+ }
26
+ if (requires.playwright && !facts.browserLaunch)
27
+ unmet.push("needs Playwright browsers; this host cannot launch them");
28
+ return unmet;
29
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Project host requirements declared in `.forge/forge.runtime.yml` (decision 0013 §3).
3
+ *
4
+ * The bridge parses them with the runtime contract and reports them, with the contract
5
+ * fingerprint, in its readiness payload. The API stores them per fingerprint and uses them
6
+ * as hard placement filters. A contract without a `requires` section has no requirements.
7
+ */
8
+ export interface HostRuntimePlaywrightRequirement {
9
+ /** Pinned Playwright revision. Recorded; enforced once bridges probe browser revisions. */
10
+ readonly revision: string | null;
11
+ }
12
+ export interface HostRuntimeTestPostgresRequirement {
13
+ readonly extensions: readonly string[];
14
+ /** Suites need a superuser role (or Docker-backed Testcontainers). */
15
+ readonly superuser: boolean;
16
+ }
17
+ export interface HostRuntimeCostHint {
18
+ readonly cores: number | null;
19
+ readonly memoryGiB: number | null;
20
+ }
21
+ export interface HostRuntimeRequirements {
22
+ readonly minThreads: number | null;
23
+ readonly minMemoryGiB: number | null;
24
+ readonly toolchains: readonly string[];
25
+ /** Suites need a Docker engine (for example Testcontainers). */
26
+ readonly docker: boolean;
27
+ readonly playwright: HostRuntimePlaywrightRequirement | null;
28
+ readonly testPostgres: HostRuntimeTestPostgresRequirement | null;
29
+ /** Accepted and reported, not yet used for placement. */
30
+ readonly costHints: Readonly<Record<string, HostRuntimeCostHint>>;
31
+ }
32
+ /**
33
+ * Validates the optional top-level `requires` and `costHints` sections. Returns null when
34
+ * neither section is present, so contracts written before decision 0013 keep their meaning.
35
+ */
36
+ export declare function parseHostRuntimeRequirements(requires: unknown, costHints: unknown): HostRuntimeRequirements | null;