@loucompanion/forge-bridge 0.1.4-dev.9e8a5b93cbcb → 0.1.4-dev.bbb61d3d6127

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 (89) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +14 -1
  3. package/dist/bridge/bridge.service.js +73 -8
  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/cli/cli.service.js +3 -1
  12. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  13. package/dist/runtime/attempt-process-supervisor.js +50 -0
  14. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  15. package/dist/runtime/host-database-capability-boundary.js +1 -0
  16. package/dist/runtime/host-facts.d.ts +35 -0
  17. package/dist/runtime/host-facts.js +95 -0
  18. package/dist/runtime/host-load-admission.d.ts +52 -0
  19. package/dist/runtime/host-load-admission.js +84 -0
  20. package/dist/runtime/host-load-forge-cgroups.d.ts +8 -0
  21. package/dist/runtime/host-load-forge-cgroups.js +51 -0
  22. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  23. package/dist/runtime/host-load-governor-config.js +46 -0
  24. package/dist/runtime/host-load-governor.d.ts +123 -0
  25. package/dist/runtime/host-load-governor.js +415 -0
  26. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  27. package/dist/runtime/host-load-ledger-lock.js +185 -0
  28. package/dist/runtime/host-load-sampler.d.ts +121 -0
  29. package/dist/runtime/host-load-sampler.js +224 -0
  30. package/dist/runtime/host-load-step-class.d.ts +33 -0
  31. package/dist/runtime/host-load-step-class.js +46 -0
  32. package/dist/runtime/host-load-token-ledger.d.ts +135 -0
  33. package/dist/runtime/host-load-token-ledger.js +345 -0
  34. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  35. package/dist/runtime/host-pressure-stall.js +168 -0
  36. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  37. package/dist/runtime/host-runtime-contract.js +6 -1
  38. package/dist/runtime/host-runtime-lease.d.ts +13 -2
  39. package/dist/runtime/host-runtime-lease.js +82 -11
  40. package/dist/runtime/host-runtime-promotion.js +12 -0
  41. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  42. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  43. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  44. package/dist/runtime/host-runtime-requirements.js +117 -0
  45. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  46. package/dist/runtime/managed-command-teardown.js +607 -0
  47. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  48. package/dist/runtime/playwright-browser-cache.js +227 -0
  49. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  50. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  51. package/dist/session/managed-attempt-tools.d.ts +25 -0
  52. package/dist/session/managed-attempt-tools.js +212 -15
  53. package/dist/session/managed-build-coordinator.d.ts +1 -1
  54. package/dist/session/managed-build-coordinator.js +4 -1
  55. package/dist/session/phase-completion.artifacts.js +4 -0
  56. package/dist/session/phase-completion.runtime.js +22 -17
  57. package/dist/session/pre-publication-host-load.d.ts +27 -0
  58. package/dist/session/pre-publication-host-load.js +96 -0
  59. package/dist/session/pre-publication-process.d.ts +20 -0
  60. package/dist/session/pre-publication-process.js +97 -0
  61. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  62. package/dist/session/pre-publication-skipped-tests.js +109 -0
  63. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  64. package/dist/session/pre-publication-step-execution.js +49 -0
  65. package/dist/session/pre-publication-validation.d.ts +9 -9
  66. package/dist/session/pre-publication-validation.js +44 -112
  67. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  68. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  69. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  70. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  71. package/dist/session/provider-cli/provider-cli.process.d.ts +35 -1
  72. package/dist/session/provider-cli/provider-cli.process.js +187 -17
  73. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  74. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  75. package/dist/session/provider-cli/provider-cli.service.js +126 -26
  76. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  77. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  78. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  79. package/dist/session/provider-cli/provider-output-state.js +9 -0
  80. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  81. package/dist/session/publishable-worktree-changes.js +193 -0
  82. package/dist/session/session.base.d.ts +3 -0
  83. package/dist/session/session.service.d.ts +2 -0
  84. package/dist/session/session.service.js +5 -0
  85. package/dist/session/session.types.d.ts +3 -0
  86. package/dist/session/session.types.js +14 -2
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/package.json +1 -1
@@ -0,0 +1,168 @@
1
+ // Linux Pressure Stall Information (PSI) parsing shared by the host load sampler.
2
+ // Format (system-wide /proc/pressure/<resource> and cgroup v2 <resource>.pressure):
3
+ // some avg10=0.12 avg60=0.34 avg300=0.56 total=123456
4
+ // full avg10=0.00 avg60=0.00 avg300=0.00 total=0
5
+ const pressureLinePattern = /^(some|full)\s+(.*)$/u;
6
+ /**
7
+ * Parses one PSI file. Returns null when the content has no well-formed
8
+ * `some`/`full` line, so callers can report PSI as unavailable instead of
9
+ * publishing zeros for a file they could not interpret.
10
+ */
11
+ export function parsePressureStall(content) {
12
+ let some = null;
13
+ let full = null;
14
+ for (const rawLine of content.split(/\r?\n/u)) {
15
+ const match = pressureLinePattern.exec(rawLine.trim());
16
+ if (!match)
17
+ continue;
18
+ const averages = parseAverages(match[2]);
19
+ if (!averages)
20
+ continue;
21
+ if (match[1] === "some")
22
+ some = averages;
23
+ else
24
+ full = averages;
25
+ }
26
+ return some || full ? { some, full } : null;
27
+ }
28
+ const pressureFieldPattern = /^(avg10|avg60|avg300|total)=(\d+(?:\.\d+)?)$/u;
29
+ /** A PSI line must carry exactly avg10, avg60, avg300 and an integer total; anything else is malformed. */
30
+ function parseAverages(fields) {
31
+ const values = new Map();
32
+ for (const field of fields.trim().split(/\s+/u)) {
33
+ const match = pressureFieldPattern.exec(field);
34
+ if (!match || values.has(match[1]))
35
+ return null;
36
+ values.set(match[1], Number(match[2]));
37
+ }
38
+ const avg10 = values.get("avg10");
39
+ const avg60 = values.get("avg60");
40
+ const avg300 = values.get("avg300");
41
+ const total = values.get("total");
42
+ if (avg10 === undefined || avg60 === undefined || avg300 === undefined
43
+ || total === undefined || !Number.isSafeInteger(total))
44
+ return null;
45
+ return { avg10: clampPercent(avg10), avg60: clampPercent(avg60), avg300: clampPercent(avg300) };
46
+ }
47
+ function clampPercent(value) {
48
+ return Math.min(100, Math.max(0, value));
49
+ }
50
+ /** Reads `usage_usec` from a cgroup v2 `cpu.stat` file. */
51
+ export function parseCgroupCpuUsageUsec(content) {
52
+ const match = /^usage_usec\s+(\d+)\s*$/mu.exec(content);
53
+ if (!match)
54
+ return null;
55
+ const value = Number(match[1]);
56
+ return Number.isSafeInteger(value) ? value : null;
57
+ }
58
+ /** Reads anonymous (RSS-like, excludes page cache) bytes from cgroup v2 `memory.stat`. */
59
+ export function parseCgroupMemoryAnonBytes(content) {
60
+ const match = /^anon\s+(\d+)\s*$/mu.exec(content);
61
+ if (!match)
62
+ return null;
63
+ const value = Number(match[1]);
64
+ return Number.isSafeInteger(value) ? value : null;
65
+ }
66
+ /** Reads a single non-negative integer file such as cgroup v2 `memory.current`. */
67
+ export function parseNonNegativeInteger(content) {
68
+ const trimmed = content.trim();
69
+ if (!/^\d+$/u.test(trimmed))
70
+ return null;
71
+ const value = Number(trimmed);
72
+ return Number.isSafeInteger(value) ? value : null;
73
+ }
74
+ /** Reads `MemAvailable` (bytes) from /proc/meminfo. */
75
+ export function parseMemAvailableBytes(content) {
76
+ const match = /^MemAvailable:\s+(\d+)\s*kB\s*$/mu.exec(content);
77
+ if (!match)
78
+ return null;
79
+ const value = Number(match[1]) * 1024;
80
+ return Number.isSafeInteger(value) ? value : null;
81
+ }
82
+ /**
83
+ * Resolves the unified (cgroup v2) hierarchy path from /proc/self/cgroup.
84
+ * Returns null on pure cgroup v1 hosts (no `0::` entry) and for the root cgroup.
85
+ */
86
+ export function parseUnifiedCgroupPath(content) {
87
+ for (const rawLine of content.split(/\r?\n/u)) {
88
+ const line = rawLine.trim();
89
+ if (!line.startsWith("0::"))
90
+ continue;
91
+ const cgroupPath = line.slice(3).trim();
92
+ if (!cgroupPath.startsWith("/") || cgroupPath === "/")
93
+ return null;
94
+ if (cgroupPath.split("/").some(segment => segment === ".."))
95
+ return null;
96
+ return cgroupPath;
97
+ }
98
+ return null;
99
+ }
100
+ /**
101
+ * This process's cgroup v2 path from `/proc/self/cgroup`, including the root
102
+ * `/` (a container's own cgroup under a cgroup namespace); null for cgroup v1
103
+ * or a malformed entry. `parseUnifiedCgroupPath` excludes the root, because the
104
+ * root is never the bridge's own unit; memory limits apply there all the same.
105
+ */
106
+ export function parseUnifiedCgroupMembership(content) {
107
+ for (const rawLine of content.split(/\r?\n/u)) {
108
+ const line = rawLine.trim();
109
+ if (!line.startsWith("0::"))
110
+ continue;
111
+ const cgroupPath = line.slice(3).trim();
112
+ if (!cgroupPath.startsWith("/"))
113
+ return null;
114
+ if (cgroupPath.split("/").some(segment => segment === ".."))
115
+ return null;
116
+ return cgroupPath;
117
+ }
118
+ return null;
119
+ }
120
+ /** The leaf cgroup name, e.g. `forge-bridge.service`. */
121
+ export function cgroupLeafName(cgroupPath) {
122
+ return cgroupPath.split("/").filter(Boolean).at(-1) ?? null;
123
+ }
124
+ /**
125
+ * Whether the bridge's cgroup is dedicated to it, so its usage can later be
126
+ * subtracted from system pressure as "Forge's own load". Only a systemd
127
+ * `.service` qualifies by default, or exactly the unit an operator names via
128
+ * FORGE_BRIDGE_CGROUP_UNIT. A `.scope` is rejected: a bridge started from a
129
+ * terminal, SSH session or desktop app shares `session-N.scope` /
130
+ * `app-*.scope` with unrelated work (possibly the owner's game).
131
+ * Container cgroups (e.g. `docker-<id>.scope`) are not treated as dedicated yet.
132
+ */
133
+ export function isDedicatedBridgeUnit(unit, configuredUnit) {
134
+ const configured = configuredUnit?.trim();
135
+ if (configured)
136
+ return unit === configured;
137
+ // `app-*` services are desktop-launched apps (XDG naming); `user@N` is the whole user manager.
138
+ return /^[^@\s]+(@[^\s]+)?\.service$/u.test(unit)
139
+ && !/^app-/u.test(unit)
140
+ && !/^user@\d+\.service$/u.test(unit);
141
+ }
142
+ /**
143
+ * Reads the aggregate `cpu` line of /proc/stat. Busy time is user + nice +
144
+ * system + irq + softirq + steal (guest time is already inside user/nice);
145
+ * idle and iowait are not busy. Both counters are additive CPU time, so a
146
+ * cgroup's `cpu.stat` usage over the same window can be subtracted from them.
147
+ */
148
+ export function parseProcStatCpuTotals(content) {
149
+ let aggregate = null;
150
+ let cpuCount = 0;
151
+ for (const rawLine of content.split(/\r?\n/u)) {
152
+ const fields = rawLine.trim().split(/\s+/u);
153
+ if (fields[0] === "cpu") {
154
+ const values = fields.slice(1, 9).map(Number);
155
+ if (values.length < 8 || values.some(value => !Number.isSafeInteger(value) || value < 0))
156
+ return null;
157
+ aggregate = values;
158
+ }
159
+ else if (/^cpu\d+$/u.test(fields[0] ?? "")) {
160
+ cpuCount += 1;
161
+ }
162
+ }
163
+ if (!aggregate || cpuCount === 0)
164
+ return null;
165
+ const [user, nice, system, idle, iowait, irq, softirq, steal] = aggregate;
166
+ const busyTicks = user + nice + system + irq + softirq + steal;
167
+ return { busyTicks, totalTicks: busyTicks + idle + iowait, cpuCount };
168
+ }
@@ -1,6 +1,8 @@
1
+ import { type HostRuntimeRequirements } from "./host-runtime-requirements.js";
1
2
  export declare const hostRuntimeContractPath = ".forge/forge.runtime.yml";
2
3
  export declare const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
3
4
  export declare const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
5
+ export declare const hostRuntimeTestPostgresProvisionerEnvironment = "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING";
4
6
  export type RequestedHostConcurrency = "serial" | "parallel" | "disabled";
5
7
  export type HostRuntimePortAdapter = "node" | "vite" | "next" | "aspnetcore";
6
8
  export interface HostRuntimeLaunchConfig {
@@ -31,6 +33,8 @@ export interface HostRuntimeContract {
31
33
  readonly browserProfile: "isolated";
32
34
  readonly singletonResources: readonly string[];
33
35
  };
36
+ /** Decision 0013 placement requirements; absent or null when the contract declares none. */
37
+ readonly requires?: HostRuntimeRequirements | null;
34
38
  }
35
39
  export interface LoadedHostRuntimeContract {
36
40
  readonly contract: HostRuntimeContract;
@@ -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>>;
@@ -92,6 +95,7 @@ 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>;
@@ -105,6 +109,7 @@ export interface HostRuntimeLeaseRuntime {
105
109
  reap?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
106
110
  snapshot?(): HostRuntimeCapacitySnapshot;
107
111
  }
112
+ export type HostRuntimeAdmissionPriority = "foreground" | "background";
108
113
  export interface HostCapacityResourceSample {
109
114
  readonly totalMemoryBytes: number;
110
115
  readonly availableMemoryBytes: number;
@@ -143,7 +148,12 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
143
148
  private readonly capacityConfiguration;
144
149
  private readonly memoryAvailability;
145
150
  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);
151
+ /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
152
+ readonly hostLoadGovernor: HostLoadGovernor;
153
+ private requirementsCheck;
154
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
155
+ setRequirementsCheck(check: HostRequirementsCheck | null): void;
156
+ 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);
147
157
  reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
148
158
  snapshot(): HostRuntimeCapacitySnapshot;
149
159
  hasForegroundDemand(): boolean;
@@ -215,3 +225,4 @@ export declare class HostRuntimeCapacityRequestImpossibleError extends Error {
215
225
  }
216
226
  export declare function hostRuntimeEventResources(lease: RuntimeIsolationLease, runtimeContract?: LoadedHostRuntimeContract, executionClass?: HostRuntimeExecutionClass): Record<string, unknown>;
217
227
  export declare function hostRuntimeSingletonKeys(dispatch: RunOnceDispatchPacket): readonly string[];
228
+ 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,8 @@ 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 { HostLoadSampler } from "./host-load-sampler.js";
32
36
  const hostCapacityWaiterScanLimit = 64;
33
37
  const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
34
38
  export class HostRuntimeLeaseManager {
@@ -63,7 +67,14 @@ export class HostRuntimeLeaseManager {
63
67
  capacityConfiguration;
64
68
  memoryAvailability;
65
69
  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) {
70
+ /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
71
+ hostLoadGovernor;
72
+ requirementsCheck = null;
73
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
74
+ setRequirementsCheck(check) {
75
+ this.requirementsCheck = check;
76
+ }
77
+ 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
78
  this.stateRoot = stateRoot;
68
79
  this.processSupervisors = processSupervisors;
69
80
  this.processRunner = processRunner;
@@ -73,6 +84,7 @@ export class HostRuntimeLeaseManager {
73
84
  this.processRecovery = processRecovery;
74
85
  this.capacityResourceSample = capacityResourceSample;
75
86
  this.databaseBroker = databaseBroker;
87
+ this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
76
88
  this.executionRoot = path.resolve(executionRoot ?? stateRoot);
77
89
  if (executionRoot !== undefined)
78
90
  assertHostExecutionRoot(this.executionRoot);
@@ -83,6 +95,8 @@ export class HostRuntimeLeaseManager {
83
95
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
84
96
  }
85
97
  async reap(options) {
98
+ // Heavy-step tokens whose owner died or whose lease lapsed are returned first.
99
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
86
100
  await this.refreshKnownPromotions();
87
101
  const recoveredAttempts = [];
88
102
  const report = {
@@ -924,6 +938,15 @@ export class HostRuntimeLeaseManager {
924
938
  let attemptRootIdentity = null;
925
939
  try {
926
940
  const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
941
+ // Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
942
+ // API learns the requirements in the first place.
943
+ const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
944
+ ? []
945
+ : this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
946
+ if (unmetRequirements.length > 0) {
947
+ // Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
948
+ throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
949
+ }
927
950
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
928
951
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
929
952
  }
@@ -1171,6 +1194,11 @@ export class HostRuntimeLeaseManager {
1171
1194
  executionClass: active.executionClass,
1172
1195
  };
1173
1196
  }
1197
+ const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
1198
+ // A host without the project's pinned browsers fails here, before any database,
1199
+ // build, launch, or promotion work that the attempt would otherwise waste.
1200
+ if (playwrightConfig)
1201
+ await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
1174
1202
  const owner = hostPortOwner(active.lease);
1175
1203
  const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
1176
1204
  if (!logDirectory)
@@ -1414,6 +1442,7 @@ export class HostRuntimeLeaseManager {
1414
1442
  if (!preservePreparation)
1415
1443
  this.pendingRenewals.delete(dispatchAttemptId);
1416
1444
  if (!active) {
1445
+ await this.hostLoadGovernor.releaseAttempt(dispatchAttemptId).catch(() => undefined);
1417
1446
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1418
1447
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1419
1448
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
@@ -1423,6 +1452,8 @@ export class HostRuntimeLeaseManager {
1423
1452
  if (active.lease.fencingToken !== fencingToken)
1424
1453
  return null;
1425
1454
  active.releasing = true;
1455
+ // Attempt teardown returns the attempt's heavy-step tokens and cancels its queued steps.
1456
+ await this.hostLoadGovernor.releaseAttempt(dispatchAttemptId).catch(() => undefined);
1426
1457
  for (const pending of active.pendingAdapterLaunches.values()) {
1427
1458
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1428
1459
  }
@@ -1532,18 +1563,46 @@ export class HostRuntimeLeaseManager {
1532
1563
  if (logsEntry.kind !== "directory") {
1533
1564
  throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1534
1565
  }
1535
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1536
1566
  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.");
1567
+ const failures = [];
1568
+ try {
1569
+ const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1570
+ for (const entry of entries) {
1571
+ if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1572
+ continue;
1573
+ const metadataPath = path.join(logsRoot, entry.name);
1574
+ const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1575
+ if (!validHostProcessSupervisorMetadata(value, lease)) {
1576
+ throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1577
+ }
1578
+ outcomes.push(await this.processRecovery.recover(value));
1544
1579
  }
1545
- outcomes.push(await this.processRecovery.recover(value));
1546
1580
  }
1581
+ catch (error) {
1582
+ failures.push(error);
1583
+ }
1584
+ // Managed commands run in their own process groups and record their ownership apart
1585
+ // from the attempt's supervised children. They are recovered even when recovering a
1586
+ // supervised child failed, and both failures are reported together.
1587
+ try {
1588
+ const managed = await terminateAttemptManagedCommands({
1589
+ logDirectory: logsRoot,
1590
+ dispatchAttemptId: lease.dispatchAttemptId,
1591
+ runtimeLeaseId: lease.executionLeaseId,
1592
+ pinnedLogDirectory: logsEntry.identity,
1593
+ }, { reason: "attempt_teardown" });
1594
+ for (const command of managed) {
1595
+ if (command.outcome === "terminated" || command.outcome === "pid_reused")
1596
+ outcomes.push(command.outcome);
1597
+ }
1598
+ }
1599
+ catch (error) {
1600
+ failures.push(error);
1601
+ }
1602
+ if (failures.length === 1)
1603
+ throw failures[0];
1604
+ if (failures.length > 1)
1605
+ throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1547
1606
  return outcomes;
1548
1607
  }
1549
1608
  async markLedgerDegraded(ledger) {
@@ -1919,6 +1978,18 @@ class AttemptSupervisedProviderProcessRunner {
1919
1978
  : new Set();
1920
1979
  const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
1921
1980
  this.onProcessTreeStarted();
1981
+ try {
1982
+ return await this.awaitProviderResult(child, baselineListeners, signal);
1983
+ }
1984
+ finally {
1985
+ // The provider tree, and the MCP server inside it, is gone. A managed command that
1986
+ // server started now has no supervisor and no receipt writer, so it must not keep
1987
+ // running into the next provider generation. This never rejects; a command it
1988
+ // cannot prove stopped is left to attempt teardown, which fails closed.
1989
+ await this.supervisor.stopOrphanedManagedCommands();
1990
+ }
1991
+ }
1992
+ async awaitProviderResult(child, baselineListeners, signal) {
1922
1993
  if (!this.enforceNoListeners)
1923
1994
  return await child.result;
1924
1995
  let settled = false;
@@ -2161,7 +2232,7 @@ function runtimeExecutionClass(dispatch) {
2161
2232
  ? "analysis_only"
2162
2233
  : "managed_runtime";
2163
2234
  }
2164
- function runtimeAdmissionPriority(dispatch) {
2235
+ export function runtimeAdmissionPriority(dispatch) {
2165
2236
  return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2166
2237
  || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2167
2238
  ? "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;