@loucompanion/forge-bridge 0.1.4-dev.a690038a6849 → 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 (59) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +2 -0
  3. package/dist/bridge/bridge.service.js +22 -3
  4. package/dist/bridge/bridge.types.d.ts +5 -0
  5. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  6. package/dist/bridge/runner-host-capabilities.js +4 -0
  7. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  8. package/dist/bridge/test-postgres-capability.js +120 -0
  9. package/dist/cli/cli.service.js +3 -1
  10. package/dist/runtime/host-load-admission.d.ts +52 -0
  11. package/dist/runtime/host-load-admission.js +84 -0
  12. package/dist/runtime/host-load-forge-cgroups.d.ts +8 -0
  13. package/dist/runtime/host-load-forge-cgroups.js +51 -0
  14. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  15. package/dist/runtime/host-load-governor-config.js +46 -0
  16. package/dist/runtime/host-load-governor.d.ts +123 -0
  17. package/dist/runtime/host-load-governor.js +415 -0
  18. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  19. package/dist/runtime/host-load-ledger-lock.js +185 -0
  20. package/dist/runtime/host-load-sampler.d.ts +38 -0
  21. package/dist/runtime/host-load-sampler.js +66 -6
  22. package/dist/runtime/host-load-step-class.d.ts +33 -0
  23. package/dist/runtime/host-load-step-class.js +46 -0
  24. package/dist/runtime/host-load-token-ledger.d.ts +135 -0
  25. package/dist/runtime/host-load-token-ledger.js +345 -0
  26. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  27. package/dist/runtime/host-pressure-stall.js +48 -1
  28. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  29. package/dist/runtime/host-runtime-contract.js +4 -1
  30. package/dist/runtime/host-runtime-lease.d.ts +13 -2
  31. package/dist/runtime/host-runtime-lease.js +27 -2
  32. package/dist/runtime/host-runtime-promotion.js +12 -0
  33. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  34. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  35. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  36. package/dist/runtime/host-runtime-requirements.js +117 -0
  37. package/dist/session/pre-publication-host-load.d.ts +27 -0
  38. package/dist/session/pre-publication-host-load.js +96 -0
  39. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  40. package/dist/session/pre-publication-step-execution.js +49 -0
  41. package/dist/session/pre-publication-validation.d.ts +9 -9
  42. package/dist/session/pre-publication-validation.js +17 -55
  43. package/dist/session/provider-cli/provider-cli.artifacts.js +15 -3
  44. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  45. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  46. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -0
  47. package/dist/session/provider-cli/provider-cli.process.js +13 -5
  48. package/dist/session/provider-cli/provider-cli.prompts.js +2 -0
  49. package/dist/session/provider-cli/provider-cli.service.js +28 -5
  50. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  51. package/dist/session/publishable-worktree-changes.js +21 -5
  52. package/dist/session/session.base.d.ts +3 -0
  53. package/dist/session/session.service.d.ts +2 -0
  54. package/dist/session/session.service.js +5 -0
  55. package/dist/session/session.types.d.ts +3 -0
  56. package/dist/session/session.types.js +5 -2
  57. package/dist/version.d.ts +1 -1
  58. package/dist/version.js +1 -1
  59. package/package.json +1 -1
package/README.md CHANGED
@@ -190,9 +190,9 @@ Production shared runners require a Linux rootless Docker daemon. Docker Desktop
190
190
 
191
191
  Before selecting `sandbox_required`, save the full approved 40- or 64-character Git commit SHA in the project's Sandbox policy dialog. The server persists that SHA on the immutable attempt and the bridge reads `.forge/forge.sandbox.yml`, `.forge/Dockerfile`, and the tracked build context only from that commit. API-key dispatches carry an opaque one-time grant handle; the authenticated current runner instance redeems it after reservation, and plaintext stays out of offers, database payloads, Docker metadata, and host-persisted control files.
192
192
 
193
- Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in Profile Settings. Either missing or expired authorization fails closed. `sandbox_required` never falls back.
193
+ Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in Settings › Runners. Either missing or expired authorization fails closed. `sandbox_required` never falls back.
194
194
 
195
- The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from Profile Settings before upgrades or Docker maintenance, wait for active/starting counts to reach zero, then restart the bridge. Profile Settings also exposes a scoped **Reap** action; the API delivers it only to the currently established protocol-v2 runner instance. Image GC runs only while disk pressure is latched, shares the build lock, preserves active image digests, and prunes only expired images beyond the per-project retention count. Lease renewals are HMAC-bound to the attempt and fence and advance an in-container monotonic deadline; lease, hard-wall, and idle expiry produce distinct failure codes.
195
+ The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from Settings › Runners before upgrades or Docker maintenance, wait for active/starting counts to reach zero, then restart the bridge. Settings › Runners also exposes a scoped **Reap** action; the API delivers it only to the currently established protocol-v2 runner instance. Image GC runs only while disk pressure is latched, shares the build lock, preserves active image digests, and prunes only expired images beyond the per-project retention count. Lease renewals are HMAC-bound to the attempt and fence and advance an in-container monotonic deadline; lease, hard-wall, and idle expiry produce distinct failure codes.
196
196
 
197
197
  Every attempt-owned container (including short-lived initialization helpers), network, and volume carries `dev.forge.resource-lease-id` equal to the dispatch execution lease. Ledger schema v2 persists the same `resourceLeaseId`; teardown compares the complete expected label set, and orphan reaping fails closed unless the managed, resource-lease, execution-lease, attempt, runner, runner-instance, and fencing identities are all present and consistent.
198
198
 
@@ -60,6 +60,8 @@ export declare class ForgeBridgeService implements BridgeService {
60
60
  private readonly sessions;
61
61
  private readonly enforceHostDatabaseCapabilityBoundary;
62
62
  private hostCapabilities;
63
+ private dockerAvailable;
64
+ private hostRequirementFacts;
63
65
  private readonly recoveredHostAttempts;
64
66
  private hostCapabilitiesDetected;
65
67
  constructor(config: BridgeServiceConfig, sessions?: SessionService | undefined, connections?: BridgeConnectionFactory, preflight?: DockerPreflight, sandboxRuntime?: SandboxRuntime, sandboxResourceResolver?: SandboxResourceResolver, dockerEngineProbe?: DockerEngineProbe, hostCapabilityProbe?: RunnerHostCapabilityProbe, readinessResultOutbox?: ReadinessResultOutbox, chatProcessRunner?: ProviderProcessRunner, dispatchResultOutbox?: DispatchResultOutbox, hostLoad?: HostLoadSource);
@@ -1,3 +1,4 @@
1
+ import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
1
2
  import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
@@ -84,6 +85,20 @@ export class ForgeBridgeService {
84
85
  sessions;
85
86
  enforceHostDatabaseCapabilityBoundary;
86
87
  hostCapabilities = emptyRunnerHostCapabilitySnapshot();
88
+ dockerAvailable = false;
89
+ hostRequirementFacts() {
90
+ const facts = this.hostLoad.facts();
91
+ return {
92
+ logicalThreads: facts?.logicalThreads ?? os.cpus().length,
93
+ totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
94
+ availableToolchains: Object.entries(this.hostCapabilities.toolchains)
95
+ .filter(([, tool]) => tool?.available === true)
96
+ .map(([name]) => name),
97
+ dockerAvailable: this.dockerAvailable,
98
+ browserLaunch: this.hostCapabilities.browserLaunch,
99
+ testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
100
+ };
101
+ }
87
102
  // Reaping deletes the stale ledger, so its stopped-process proof is held here
88
103
  // until a Hello carrying it is accepted. A bridge restart forgets it, which
89
104
  // leaves those attempts on Forge's conservative unknown-outcome path.
@@ -126,7 +141,7 @@ export class ForgeBridgeService {
126
141
  },
127
142
  onStatus: logBridgeStatus,
128
143
  });
129
- this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe);
144
+ this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
130
145
  this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
131
146
  this.sandboxResourceResolver = sandboxResourceResolver
132
147
  ?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
@@ -162,6 +177,7 @@ export class ForgeBridgeService {
162
177
  // Static host facts and the first load sample ride on Hello; the sampler
163
178
  // keeps refreshing its cached snapshot for later heartbeats.
164
179
  await this.hostLoad.start().catch(() => undefined);
180
+ this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
165
181
  const connection = this.connections.create(this.config);
166
182
  this.connection = connection;
167
183
  this.transportRecovery = null;
@@ -1677,6 +1693,7 @@ export class ForgeBridgeService {
1677
1693
  capabilities() {
1678
1694
  const preflight = this.preflight.current();
1679
1695
  const dockerEngine = this.dockerEngineProbe.current();
1696
+ this.dockerAvailable = dockerEngine?.available === true;
1680
1697
  const runtimeState = this.sandboxRuntime.snapshot();
1681
1698
  const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
1682
1699
  const used = this.usedSandboxResources(runtimeState.degraded);
@@ -1716,6 +1733,7 @@ export class ForgeBridgeService {
1716
1733
  playwrightProjects: this.hostCapabilities.playwrightProjects,
1717
1734
  browserLaunch: this.hostCapabilities.browserLaunch,
1718
1735
  providerConnectivity: this.hostCapabilities.providerConnectivity,
1736
+ testPostgres: this.hostCapabilities.testPostgres,
1719
1737
  host: this.hostLoad.facts(),
1720
1738
  load: this.hostLoad.current(),
1721
1739
  maxConcurrentSandboxes: capacity.sandboxSlots,
@@ -1944,11 +1962,12 @@ function isProviderStorageUnavailable(error) {
1944
1962
  function isBridgeCallbackTimeout(error) {
1945
1963
  return errorMessage(error).startsWith("bridge_callback_timeout:");
1946
1964
  }
1947
- function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe) {
1965
+ function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
1948
1966
  const rawProcessRunner = new StreamingProviderProcessRunner();
1949
1967
  const processSupervisors = new AttemptProcessSupervisorRegistry();
1950
1968
  const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
1951
- return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback))), new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot)));
1969
+ const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
1970
+ return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
1952
1971
  }
1953
1972
  export class SignalRBridgeConnectionFactory {
1954
1973
  create(config) {
@@ -1,3 +1,5 @@
1
+ import type { HostRuntimeRequirements } from "../runtime/host-runtime-requirements.js";
2
+ import type { BridgeTestPostgresCapability } from "./test-postgres-capability.js";
1
3
  import type { ApiKeySecretGrant, DispatchSandboxResourceRequest, RunOnceResultPacket, RunnerDispatchEvent } from "../session/session.types.js";
2
4
  import type { SandboxFeatureMatrix } from "../sandbox/sandbox.types.js";
3
5
  import type { HostRuntimeCapacitySnapshot } from "../runtime/host-runtime-lease.js";
@@ -144,6 +146,8 @@ export interface BridgeCapabilities {
144
146
  readonly playwrightProjects?: readonly string[] | null;
145
147
  readonly browserLaunch?: boolean | null;
146
148
  readonly providerConnectivity?: Readonly<Record<string, boolean>> | null;
149
+ /** Native test PostgreSQL and whether its role is a superuser (decision 0013 placement). */
150
+ readonly testPostgres?: BridgeTestPostgresCapability | null;
147
151
  /** Static host hardware facts (schema 7). Material: changes are persisted immediately. */
148
152
  readonly host?: HostFacts | null;
149
153
  /** Live host load sample (schema 7). Never material: heartbeats with only load changes are not persisted. */
@@ -298,6 +302,7 @@ export interface BridgeRuntimeReadinessResult {
298
302
  readonly status: "parallel_ready" | "serialized" | "failed";
299
303
  readonly runtimeContractFingerprint?: string | null;
300
304
  readonly runtimeContractSource?: string | null;
305
+ readonly runtimeRequirements?: HostRuntimeRequirements | null;
301
306
  readonly reasonCode?: string | null;
302
307
  readonly reasonMessage?: string | null;
303
308
  readonly qaAppLaunchTarget?: BridgeRuntimeReadinessQaLaunchTarget | null;
@@ -1,9 +1,11 @@
1
1
  import type { BridgeServiceConfig, BridgeToolchainCapabilities } from "./bridge.types.js";
2
+ import { type BridgeTestPostgresCapability } from "./test-postgres-capability.js";
2
3
  export interface RunnerHostCapabilitySnapshot {
3
4
  readonly toolchains: BridgeToolchainCapabilities;
4
5
  readonly playwrightProjects: readonly string[];
5
6
  readonly browserLaunch: boolean;
6
7
  readonly providerConnectivity: Readonly<Record<string, boolean>>;
8
+ readonly testPostgres: BridgeTestPostgresCapability;
7
9
  }
8
10
  export interface RunnerHostCapabilityProbe {
9
11
  detect(config: BridgeServiceConfig): Promise<RunnerHostCapabilitySnapshot>;
@@ -2,6 +2,7 @@ import { execFile } from "node:child_process";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { promisify } from "node:util";
5
+ import { probeTestPostgresCapability } from "./test-postgres-capability.js";
5
6
  const execFileAsync = promisify(execFile);
6
7
  export class ProcessRunnerHostCapabilityProbe {
7
8
  async detect(config) {
@@ -16,6 +17,7 @@ export class ProcessRunnerHostCapabilityProbe {
16
17
  : Promise.resolve(unavailable("powershell.exe")),
17
18
  ]);
18
19
  const playwrightProjects = await detectPlaywrightProjects(config.repoMappings);
20
+ const testPostgres = await probeTestPostgresCapability();
19
21
  const browserLaunch = playwrightProjects.length > 0
20
22
  || config.repoMappings.some(mapping => Boolean(mapping.qaAppLaunchTarget?.url
21
23
  || mapping.qaAppLaunchTarget?.command
@@ -33,6 +35,7 @@ export class ProcessRunnerHostCapabilityProbe {
33
35
  browserLaunch,
34
36
  providerConnectivity: Object.fromEntries(Object.entries(config.providerStatuses)
35
37
  .map(([provider, status]) => [provider, status.signedIn === true])),
38
+ testPostgres,
36
39
  };
37
40
  }
38
41
  }
@@ -89,5 +92,6 @@ export function emptyRunnerHostCapabilitySnapshot() {
89
92
  playwrightProjects: [],
90
93
  browserLaunch: false,
91
94
  providerConnectivity: {},
95
+ testPostgres: { available: false, superuser: null },
92
96
  };
93
97
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Whether this host offers a native test PostgreSQL and whether its role is a superuser
3
+ * (decision 0013 placement). Suites that need `session_replication_role`, `CREATE ROLE` or
4
+ * similar can only run on a superuser test database or on Docker-backed Testcontainers.
5
+ */
6
+ export interface BridgeTestPostgresCapability {
7
+ readonly available: boolean;
8
+ /** Null when the cluster is configured but the role could not be checked. */
9
+ readonly superuser: boolean | null;
10
+ }
11
+ export type PsqlRunner = (args: readonly string[], env: NodeJS.ProcessEnv) => Promise<string>;
12
+ export declare function probeTestPostgresCapability(environment?: NodeJS.ProcessEnv, runPsql?: PsqlRunner, readFallback?: () => string | null): Promise<BridgeTestPostgresCapability>;
13
+ /** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
14
+ export declare function psqlTarget(connection: string): Record<string, string> | null;
@@ -0,0 +1,120 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { hostRuntimeTestPostgresAdminEnvironment } from "../runtime/host-runtime-contract.js";
4
+ import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
5
+ const execFileAsync = promisify(execFile);
6
+ const superuserQuery = "select rolsuper from pg_roles where rolname = current_user";
7
+ export async function probeTestPostgresCapability(environment = process.env, runPsql = defaultPsql, readFallback = configuredFallbackConnection) {
8
+ // Same sources pre-publication validation uses: the environment, else the operator's
9
+ // native test cluster file.
10
+ const connection = environment[hostRuntimeTestPostgresAdminEnvironment]?.trim() || readFallback()?.trim();
11
+ if (!connection)
12
+ return { available: false, superuser: null };
13
+ const target = psqlTarget(connection);
14
+ if (!target)
15
+ return { available: true, superuser: null };
16
+ try {
17
+ // The secret travels only in the child's environment, never in argv or logs.
18
+ const output = await runPsql(["-X", "-A", "-t", "-w", "-c", superuserQuery], { ...process.env, ...target, PGCONNECT_TIMEOUT: "5" });
19
+ const value = output.trim().toLowerCase();
20
+ return { available: true, superuser: value === "t" ? true : value === "f" ? false : null };
21
+ }
22
+ catch {
23
+ return { available: true, superuser: null };
24
+ }
25
+ }
26
+ /** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
27
+ export function psqlTarget(connection) {
28
+ // libpq reads PGDATABASE as a database name only, so a URI is split into PG* variables
29
+ // rather than passed whole (and not as psql's argument, which would put the secret in argv).
30
+ if (/^postgres(?:ql)?:\/\//iu.test(connection))
31
+ return uriTarget(connection);
32
+ const keys = {
33
+ host: "PGHOST", server: "PGHOST", port: "PGPORT", database: "PGDATABASE",
34
+ username: "PGUSER", "user id": "PGUSER", userid: "PGUSER", user: "PGUSER", password: "PGPASSWORD",
35
+ };
36
+ const target = {};
37
+ for (const part of connection.split(";")) {
38
+ const separator = part.indexOf("=");
39
+ if (separator <= 0)
40
+ continue;
41
+ const name = keys[part.slice(0, separator).trim().toLowerCase()];
42
+ const value = part.slice(separator + 1).trim();
43
+ if (name && value)
44
+ target[name] = value;
45
+ }
46
+ return target.PGHOST || target.PGUSER ? target : null;
47
+ }
48
+ /** libpq URI query parameters that have a PG* environment equivalent. */
49
+ const uriParameterEnvironment = {
50
+ host: "PGHOST", hostaddr: "PGHOSTADDR", port: "PGPORT", dbname: "PGDATABASE", user: "PGUSER",
51
+ password: "PGPASSWORD", passfile: "PGPASSFILE", options: "PGOPTIONS", application_name: "PGAPPNAME",
52
+ sslmode: "PGSSLMODE", sslrootcert: "PGSSLROOTCERT", sslcert: "PGSSLCERT", sslkey: "PGSSLKEY",
53
+ sslcrl: "PGSSLCRL", gssencmode: "PGGSSENCMODE", target_session_attrs: "PGTARGETSESSIONATTRS",
54
+ };
55
+ /**
56
+ * Parses `postgres[ql]://[user[:password]@][host[:port][,...]][/dbname][?param=value&...]`
57
+ * (libpq's URI form, including comma-separated hosts, bracketed IPv6 and percent-encoding).
58
+ */
59
+ function uriTarget(connection) {
60
+ const match = /^postgres(?:ql)?:\/\/([^/?#]*)(?:\/([^?#]*))?(?:\?([^#]*))?/iu.exec(connection);
61
+ if (!match)
62
+ return null;
63
+ try {
64
+ const [, authority = "", path, query] = match;
65
+ const target = {};
66
+ const at = authority.lastIndexOf("@");
67
+ if (at >= 0) {
68
+ const userInfo = authority.slice(0, at);
69
+ const colon = userInfo.indexOf(":");
70
+ const user = decodeURIComponent(colon >= 0 ? userInfo.slice(0, colon) : userInfo);
71
+ if (user)
72
+ target.PGUSER = user;
73
+ if (colon >= 0)
74
+ target.PGPASSWORD = decodeURIComponent(userInfo.slice(colon + 1));
75
+ }
76
+ const hosts = [];
77
+ const ports = [];
78
+ for (const entry of authority.slice(at + 1).split(",")) {
79
+ const ipv6 = /^\[([^\]]*)\](?::(.*))?$/u.exec(entry);
80
+ const colon = entry.lastIndexOf(":");
81
+ const host = ipv6 ? ipv6[1] ?? "" : colon >= 0 ? entry.slice(0, colon) : entry;
82
+ const port = ipv6 ? ipv6[2] ?? "" : colon >= 0 ? entry.slice(colon + 1) : "";
83
+ hosts.push(decodeURIComponent(host));
84
+ ports.push(port);
85
+ }
86
+ if (hosts.some(Boolean))
87
+ target.PGHOST = hosts.join(",");
88
+ if (ports.some(Boolean))
89
+ target.PGPORT = ports.join(",");
90
+ const database = path ? decodeURIComponent(path) : "";
91
+ if (database)
92
+ target.PGDATABASE = database;
93
+ for (const parameter of (query ?? "").split("&")) {
94
+ const separator = parameter.indexOf("=");
95
+ if (separator <= 0)
96
+ continue;
97
+ const name = uriParameterEnvironment[decodeURIComponent(parameter.slice(0, separator))];
98
+ const value = decodeURIComponent(parameter.slice(separator + 1));
99
+ if (name && value)
100
+ target[name] = value;
101
+ }
102
+ return target;
103
+ }
104
+ catch {
105
+ // Malformed percent-encoding: the role cannot be checked.
106
+ return null;
107
+ }
108
+ }
109
+ function configuredFallbackConnection() {
110
+ try {
111
+ return readNativeTestPostgresFallback()?.connectionString ?? null;
112
+ }
113
+ catch {
114
+ return null;
115
+ }
116
+ }
117
+ async function defaultPsql(args, env) {
118
+ const result = await execFileAsync("psql", [...args], { encoding: "utf8", timeout: 10_000, env });
119
+ return result.stdout;
120
+ }
@@ -30,7 +30,9 @@ export class ForgeBridgeCliService {
30
30
  pairRunner;
31
31
  cleanupFactory;
32
32
  dotNetToolchainConfigurator;
33
- constructor(sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
33
+ constructor(
34
+ // The default session chain validates without the host load governor (Docker-mode gap, decision 0013).
35
+ sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
34
36
  this.sessions = sessions;
35
37
  this.bridgeFactory = bridgeFactory;
36
38
  this.pairRunner = pairRunner;
@@ -0,0 +1,52 @@
1
+ import type { HostLoadGovernorConfig } from "./host-load-governor-config.js";
2
+ import type { HostLoadStepCost } from "./host-load-step-class.js";
3
+ /** Measured host load the admission rule reads. Null means PSI is unavailable or stale. */
4
+ export interface HostLoadSignals {
5
+ /** Host-wide CPU PSI `some avg10`, used as is (never split per cgroup). */
6
+ readonly cpuSomeAvg10: number;
7
+ /** Consecutive samples, ending with the latest, at or above the CPU pressure threshold. */
8
+ readonly cpuPressuredSamples: number;
9
+ /** Host-wide memory PSI `full avg10`; a hard stop above its threshold. */
10
+ readonly memoryFullAvg10: number | null;
11
+ readonly memoryAvailableBytes: number | null;
12
+ /**
13
+ * Host CPU from /proc/stat minus the bridge's dedicated cgroup over the same
14
+ * window. Null when the bridge's cgroup is not dedicated: Forge's own work is
15
+ * then counted only through reserved cost and the host PSI gate.
16
+ */
17
+ readonly externalCpuCores: number | null;
18
+ }
19
+ export type HostLoadAdmissionReason = "admitted" | "admitted_alone" | "admitted_fallback" | "cpu_budget" | "memory_budget" | "cpu_pressure" | "memory_pressure" | "fallback_slots"
20
+ /** A corrupt ledger was quarantined; admissions wait one lease while owners restore their reservations. */
21
+ | "ledger_recovering";
22
+ export interface HostLoadAdmissionInput {
23
+ readonly request: HostLoadStepCost;
24
+ /** Reserved cost of every live token on this host (all processes). */
25
+ readonly running: readonly HostLoadStepCost[];
26
+ /**
27
+ * Memory the running steps already use. MemAvailable already excludes it, so
28
+ * it is added back to the budget (capped at their reservations) instead of
29
+ * being counted twice.
30
+ */
31
+ readonly runningMemoryBytes?: number;
32
+ readonly logicalCpus: number;
33
+ readonly signals: HostLoadSignals | null;
34
+ readonly config: Pick<HostLoadGovernorConfig, "cpuBudgetFraction" | "memoryReserveBytes" | "cpuPressureThreshold" | "backpressureSamples" | "memoryFullThreshold" | "fallbackSlots">;
35
+ }
36
+ export interface HostLoadAdmissionDecision {
37
+ readonly admitted: boolean;
38
+ readonly reason: HostLoadAdmissionReason;
39
+ readonly cpuBudgetCores: number | null;
40
+ readonly memoryBudgetBytes: number | null;
41
+ readonly reservedCpuCores: number;
42
+ readonly reservedMemoryBytes: number;
43
+ readonly detail: string;
44
+ }
45
+ /**
46
+ * Decision 0013 admission rule. A step is admitted when the reserved cost of
47
+ * running steps plus its own cost fits the budget and host pressure is under
48
+ * the backpressure threshold. Memory `full` pressure is a hard stop. A step
49
+ * too large for the budget on its own runs only when nothing else does.
50
+ * Without PSI, a simple per-host semaphore applies instead.
51
+ */
52
+ export declare function decideHostLoadAdmission(input: HostLoadAdmissionInput): HostLoadAdmissionDecision;
@@ -0,0 +1,84 @@
1
+ const epsilon = 1e-9;
2
+ /**
3
+ * Decision 0013 admission rule. A step is admitted when the reserved cost of
4
+ * running steps plus its own cost fits the budget and host pressure is under
5
+ * the backpressure threshold. Memory `full` pressure is a hard stop. A step
6
+ * too large for the budget on its own runs only when nothing else does.
7
+ * Without PSI, a simple per-host semaphore applies instead.
8
+ */
9
+ export function decideHostLoadAdmission(input) {
10
+ const { request, running, signals, config } = input;
11
+ const reservedCpuCores = running.reduce((sum, cost) => sum + cost.cpuCores, 0);
12
+ const reservedMemoryBytes = running.reduce((sum, cost) => sum + cost.memoryBytes, 0);
13
+ const base = { reservedCpuCores, reservedMemoryBytes };
14
+ if (!signals) {
15
+ const admitted = running.length < config.fallbackSlots;
16
+ return {
17
+ ...base,
18
+ admitted,
19
+ reason: admitted ? "admitted_fallback" : "fallback_slots",
20
+ cpuBudgetCores: null,
21
+ memoryBudgetBytes: null,
22
+ detail: admitted
23
+ ? "Host pressure data is unavailable; admitted under the per-host step semaphore."
24
+ : `Host pressure data is unavailable; ${running.length} of ${config.fallbackSlots} heavy step slot(s) are in use.`,
25
+ };
26
+ }
27
+ const cpuBudgetCores = Math.max(0, input.logicalCpus * config.cpuBudgetFraction - (signals.externalCpuCores ?? 0));
28
+ const usedByRunning = Math.min(reservedMemoryBytes, Math.max(0, input.runningMemoryBytes ?? 0));
29
+ const memoryBudgetBytes = signals.memoryAvailableBytes === null
30
+ ? null
31
+ : Math.max(0, signals.memoryAvailableBytes + usedByRunning - config.memoryReserveBytes);
32
+ const budget = { ...base, cpuBudgetCores, memoryBudgetBytes };
33
+ if (signals.memoryFullAvg10 !== null && signals.memoryFullAvg10 > config.memoryFullThreshold) {
34
+ return {
35
+ ...budget,
36
+ admitted: false,
37
+ reason: "memory_pressure",
38
+ detail: `Host memory pressure (full avg10 ${signals.memoryFullAvg10}%) is above ${config.memoryFullThreshold}%; no heavy step may start.`,
39
+ };
40
+ }
41
+ if (signals.cpuPressuredSamples >= config.backpressureSamples) {
42
+ return {
43
+ ...budget,
44
+ admitted: false,
45
+ reason: "cpu_pressure",
46
+ detail: `Host CPU pressure (some avg10 ${signals.cpuSomeAvg10}%) has been at or above ${config.cpuPressureThreshold}% for ${signals.cpuPressuredSamples} sample(s).`,
47
+ };
48
+ }
49
+ if (running.length === 0) {
50
+ const oversize = request.cpuCores > cpuBudgetCores + epsilon
51
+ || (memoryBudgetBytes !== null && request.memoryBytes > memoryBudgetBytes + epsilon);
52
+ return {
53
+ ...budget,
54
+ admitted: true,
55
+ reason: oversize ? "admitted_alone" : "admitted",
56
+ detail: oversize
57
+ ? "The step exceeds the host budget on its own and runs alone because nothing else is running."
58
+ : "The step fits the host budget.",
59
+ };
60
+ }
61
+ if (reservedCpuCores + request.cpuCores > cpuBudgetCores + epsilon) {
62
+ return {
63
+ ...budget,
64
+ admitted: false,
65
+ reason: "cpu_budget",
66
+ detail: `Reserved ${round(reservedCpuCores)} + requested ${round(request.cpuCores)} cores exceed the ${round(cpuBudgetCores)}-core budget${signals.externalCpuCores ? ` (${round(signals.externalCpuCores)} cores of external load)` : ""}.`,
67
+ };
68
+ }
69
+ if (memoryBudgetBytes !== null && reservedMemoryBytes + request.memoryBytes > memoryBudgetBytes + epsilon) {
70
+ return {
71
+ ...budget,
72
+ admitted: false,
73
+ reason: "memory_budget",
74
+ detail: `Reserved ${gib(reservedMemoryBytes)} + requested ${gib(request.memoryBytes)} GiB exceed the ${gib(memoryBudgetBytes)} GiB memory budget.`,
75
+ };
76
+ }
77
+ return { ...budget, admitted: true, reason: "admitted", detail: "The step fits the host budget." };
78
+ }
79
+ function round(value) {
80
+ return Math.round(value * 100) / 100;
81
+ }
82
+ function gib(bytes) {
83
+ return round(bytes / 1024 ** 3);
84
+ }
@@ -0,0 +1,8 @@
1
+ import { type HostEnvironment } from "./host-facts.js";
2
+ /**
3
+ * Free memory under the tightest `memory.max` from the cgroup up to and
4
+ * including the root (`memory.max − memory.current`), or null when no limit is
5
+ * set on the path. Inside a container the root is the container's own cgroup,
6
+ * whose `memory.max` is the container limit.
7
+ */
8
+ export declare function readCgroupMemoryHeadroomBytes(environment: HostEnvironment, cgroupPath: string): Promise<number | null>;
@@ -0,0 +1,51 @@
1
+ import path from "node:path";
2
+ import { readOptional } from "./host-facts.js";
3
+ import { parseNonNegativeInteger } from "./host-pressure-stall.js";
4
+ // Decision 0013 cgroup accounting: the memory budget follows the tightest
5
+ // `memory.max` on the bridge's cgroup path, so a step is never admitted past
6
+ // the limit that would OOM-kill it.
7
+ /**
8
+ * Free memory under the tightest `memory.max` from the cgroup up to and
9
+ * including the root (`memory.max − memory.current`), or null when no limit is
10
+ * set on the path. Inside a container the root is the container's own cgroup,
11
+ * whose `memory.max` is the container limit.
12
+ */
13
+ export async function readCgroupMemoryHeadroomBytes(environment, cgroupPath) {
14
+ let tightest = null;
15
+ for (const current of cgroupPathAndAncestors(cgroupPath)) {
16
+ const directory = cgroupDirectory(environment, current);
17
+ if (!directory)
18
+ return null;
19
+ const [maximum, used] = await Promise.all([
20
+ readOptional(environment, path.posix.join(directory, "memory.max")),
21
+ readOptional(environment, path.posix.join(directory, "memory.current")),
22
+ ]);
23
+ const limit = maximum ? parseNonNegativeInteger(maximum) : null;
24
+ const usage = used ? parseNonNegativeInteger(used) : null;
25
+ if (limit === null || usage === null)
26
+ continue;
27
+ const headroom = Math.max(0, limit - usage);
28
+ tightest = tightest === null ? headroom : Math.min(tightest, headroom);
29
+ }
30
+ return tightest;
31
+ }
32
+ /** `/a/b/c`, `/a/b`, `/a`, `/`; nothing for a relative or traversing path. */
33
+ function cgroupPathAndAncestors(cgroupPath) {
34
+ if (!cgroupPath.startsWith("/") || cgroupPath.split("/").includes(".."))
35
+ return [];
36
+ const paths = [];
37
+ for (let current = path.posix.normalize(cgroupPath);; current = path.posix.dirname(current)) {
38
+ paths.push(current);
39
+ if (current === "/")
40
+ return paths;
41
+ }
42
+ }
43
+ function cgroupDirectory(environment, cgroupPath) {
44
+ if (!cgroupPath.startsWith("/") || cgroupPath.split("/").includes(".."))
45
+ return null;
46
+ const root = environment.cgroupRoot.replace(/\/+$/u, "");
47
+ if (cgroupPath === "/")
48
+ return root;
49
+ const directory = path.posix.join(root, cgroupPath);
50
+ return directory.startsWith(`${root}/`) ? directory : null;
51
+ }
@@ -0,0 +1,34 @@
1
+ export type HostLoadGovernorMode = "on" | "off";
2
+ export interface HostLoadGovernorConfig {
3
+ /** FORGE_HOST_LOAD_GOVERNOR. Off by default in this step; `off` is the operator override. */
4
+ readonly mode: HostLoadGovernorMode;
5
+ /** Share of logical CPUs Forge may reserve for heavy steps. */
6
+ readonly cpuBudgetFraction: number;
7
+ /** Memory kept free for the rest of the host, taken off MemAvailable. */
8
+ readonly memoryReserveBytes: number;
9
+ /** Host CPU PSI `some avg10` (percent) at or above which a sample counts as pressured. */
10
+ readonly cpuPressureThreshold: number;
11
+ /** Consecutive pressured samples that stop new admissions (backpressure). */
12
+ readonly backpressureSamples: number;
13
+ /** Host memory PSI `full avg10` (percent) above which admission is a hard stop. */
14
+ readonly memoryFullThreshold: number;
15
+ /** Maximum queue wait before a retryable host_capacity_timeout. */
16
+ readonly maxWaitMs: number;
17
+ /** Steps allowed at once when PSI is unavailable (the per-host semaphore fallback). */
18
+ readonly fallbackSlots: number;
19
+ /** After this long at the head of the queue, later waiters may no longer overtake it. */
20
+ readonly antiStarvationMs: number;
21
+ /** Token lease; the owner renews well before it expires. */
22
+ readonly leaseMs: number;
23
+ /** How often waiters are re-evaluated against fresh samples and the shared ledger. */
24
+ readonly recheckIntervalMs: number;
25
+ /** A load sample older than this is treated as missing PSI. */
26
+ readonly sampleStaleMs: number;
27
+ /** The sampler's interval; a longer gap between samples resets the pressure streak. */
28
+ readonly sampleIntervalMs: number;
29
+ /** Without a dedicated cgroup, a step this old is assumed to use its reserved memory. */
30
+ readonly memoryRampMs: number;
31
+ }
32
+ export declare const defaultHostLoadGovernorConfig: HostLoadGovernorConfig;
33
+ export declare function parseHostLoadGovernorMode(value: string | undefined): HostLoadGovernorMode;
34
+ export declare function loadHostLoadGovernorConfig(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernorConfig;
@@ -0,0 +1,46 @@
1
+ import { defaultHostLoadSampleIntervalMs } from "./host-load-sampler.js";
2
+ export const defaultHostLoadGovernorConfig = {
3
+ mode: "off",
4
+ cpuBudgetFraction: 0.8,
5
+ memoryReserveBytes: 1024 ** 3,
6
+ cpuPressureThreshold: 50,
7
+ backpressureSamples: 2,
8
+ memoryFullThreshold: 5,
9
+ maxWaitMs: 30 * 60_000,
10
+ fallbackSlots: 1,
11
+ antiStarvationMs: 2 * 60_000,
12
+ leaseMs: 2 * 60_000,
13
+ recheckIntervalMs: 1_000,
14
+ sampleStaleMs: 30_000,
15
+ sampleIntervalMs: defaultHostLoadSampleIntervalMs,
16
+ memoryRampMs: 60_000,
17
+ };
18
+ export function parseHostLoadGovernorMode(value) {
19
+ const normalized = value?.trim().toLowerCase() ?? "";
20
+ return normalized === "on" || normalized === "true" || normalized === "1" ? "on" : "off";
21
+ }
22
+ export function loadHostLoadGovernorConfig(environment = process.env) {
23
+ const defaults = defaultHostLoadGovernorConfig;
24
+ return {
25
+ mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
26
+ cpuBudgetFraction: bounded(environment.FORGE_HOST_LOAD_CPU_BUDGET_FRACTION, defaults.cpuBudgetFraction, 0.05, 1),
27
+ memoryReserveBytes: bounded(environment.FORGE_HOST_LOAD_MEMORY_RESERVE_BYTES, defaults.memoryReserveBytes, 0, 1024 ** 4),
28
+ cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
29
+ backpressureSamples: Math.round(bounded(environment.FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES, defaults.backpressureSamples, 1, 60)),
30
+ memoryFullThreshold: bounded(environment.FORGE_HOST_LOAD_MEMORY_FULL_THRESHOLD, defaults.memoryFullThreshold, 0, 100),
31
+ maxWaitMs: bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000),
32
+ fallbackSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_FALLBACK_SLOTS, defaults.fallbackSlots, 1, 64)),
33
+ antiStarvationMs: defaults.antiStarvationMs,
34
+ leaseMs: defaults.leaseMs,
35
+ recheckIntervalMs: defaults.recheckIntervalMs,
36
+ sampleStaleMs: defaults.sampleStaleMs,
37
+ sampleIntervalMs: defaults.sampleIntervalMs,
38
+ memoryRampMs: defaults.memoryRampMs,
39
+ };
40
+ }
41
+ function bounded(raw, fallback, minimum, maximum) {
42
+ if (raw === undefined || raw.trim() === "")
43
+ return fallback;
44
+ const value = Number(raw);
45
+ return Number.isFinite(value) ? Math.min(maximum, Math.max(minimum, value)) : fallback;
46
+ }