@loucompanion/forge-bridge 0.1.4-dev.19e5db286f12 → 0.1.4-dev.1ec1b222a073

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 (90) hide show
  1. package/dist/bridge/bridge.service.d.ts +2 -0
  2. package/dist/bridge/bridge.service.js +28 -4
  3. package/dist/bridge/bridge.types.d.ts +5 -0
  4. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  5. package/dist/bridge/runner-host-capabilities.js +4 -0
  6. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  7. package/dist/bridge/test-postgres-capability.js +120 -0
  8. package/dist/cli/cli.service.js +1 -1
  9. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  10. package/dist/runtime/host-load-child-environment.js +65 -0
  11. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  12. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  13. package/dist/runtime/host-load-governor.d.ts +60 -11
  14. package/dist/runtime/host-load-governor.js +145 -41
  15. package/dist/runtime/host-load-sampler.d.ts +5 -0
  16. package/dist/runtime/host-load-sampler.js +12 -4
  17. package/dist/runtime/host-load-step-class.d.ts +35 -0
  18. package/dist/runtime/host-load-step-class.js +60 -0
  19. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  20. package/dist/runtime/host-load-step-reaper.js +95 -0
  21. package/dist/runtime/host-load-step-run.d.ts +73 -0
  22. package/dist/runtime/host-load-step-run.js +102 -0
  23. package/dist/runtime/host-load-token-ledger.d.ts +58 -19
  24. package/dist/runtime/host-load-token-ledger.js +111 -35
  25. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  26. package/dist/runtime/host-runtime-contract.js +4 -1
  27. package/dist/runtime/host-runtime-lease.d.ts +10 -2
  28. package/dist/runtime/host-runtime-lease.js +74 -5
  29. package/dist/runtime/host-runtime-promotion.js +12 -0
  30. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  31. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  32. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  33. package/dist/runtime/host-runtime-requirements.js +117 -0
  34. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  35. package/dist/sandbox/host-capacity-broker.js +315 -0
  36. package/dist/sandbox/runtime.d.ts +10 -1
  37. package/dist/sandbox/runtime.js +45 -2
  38. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  39. package/dist/sandbox/sandbox-cgroups.js +42 -0
  40. package/dist/session/managed-attempt-tools.d.ts +2 -0
  41. package/dist/session/managed-attempt-tools.js +156 -37
  42. package/dist/session/managed-command-host-load.d.ts +45 -0
  43. package/dist/session/managed-command-host-load.js +82 -0
  44. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  45. package/dist/session/mcp-argument-coercion.js +121 -0
  46. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  47. package/dist/session/phase-completion.artifacts.js +94 -25
  48. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  49. package/dist/session/phase-completion.command-validation.js +77 -0
  50. package/dist/session/phase-completion.d.ts +4 -0
  51. package/dist/session/phase-completion.helpers.js +13 -12
  52. package/dist/session/phase-completion.js +4 -0
  53. package/dist/session/phase-completion.prompts.js +6 -1
  54. package/dist/session/phase-completion.runtime.d.ts +5 -3
  55. package/dist/session/phase-completion.runtime.js +49 -19
  56. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  57. package/dist/session/phase-completion.schema-parts.js +188 -0
  58. package/dist/session/phase-completion.schemas.d.ts +3 -3
  59. package/dist/session/phase-completion.schemas.js +184 -209
  60. package/dist/session/phase-completion.validation.d.ts +2 -3
  61. package/dist/session/phase-completion.validation.js +46 -92
  62. package/dist/session/pre-publication-host-load.js +31 -16
  63. package/dist/session/pre-publication-process.d.ts +3 -0
  64. package/dist/session/pre-publication-process.js +23 -11
  65. package/dist/session/pre-publication-validation.js +4 -0
  66. package/dist/session/provider-cli/provider-cli.process.js +2 -2
  67. package/dist/session/provider-cli/provider-cli.prompts.js +1 -1
  68. package/dist/session/provider-cli/provider-cli.service.js +20 -12
  69. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  70. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  71. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  72. package/dist/session/session.base.d.ts +3 -0
  73. package/dist/session/session.service.d.ts +2 -0
  74. package/dist/session/session.service.js +21 -4
  75. package/dist/session/session.types.d.ts +3 -0
  76. package/dist/session/session.types.js +1 -1
  77. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  78. package/dist/shared/process/host-process-supervisor.js +1 -1
  79. package/dist/shared/process/process-tree.d.ts +52 -0
  80. package/dist/shared/process/process-tree.js +144 -0
  81. package/dist/shared/process/process.d.ts +67 -0
  82. package/dist/shared/process/process.js +213 -11
  83. package/dist/version.d.ts +1 -1
  84. package/dist/version.js +1 -1
  85. package/dist/worktree/dependency-warmer.d.ts +25 -0
  86. package/dist/worktree/dependency-warmer.js +46 -10
  87. package/dist/worktree/worktree.service.d.ts +6 -1
  88. package/dist/worktree/worktree.service.js +14 -2
  89. package/dist/worktree/worktree.types.d.ts +7 -0
  90. package/package.json +1 -1
@@ -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";
@@ -12,6 +13,7 @@ import { codexSandboxModeForPlatform, formatProviderCliCommandForCheckpoint } fr
12
13
  import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
13
14
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
14
15
  import { PrePublicationValidator } from "../session/pre-publication-validation.js";
16
+ import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
15
17
  import { HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
16
18
  import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
17
19
  import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
@@ -84,12 +86,28 @@ export class ForgeBridgeService {
84
86
  sessions;
85
87
  enforceHostDatabaseCapabilityBoundary;
86
88
  hostCapabilities = emptyRunnerHostCapabilitySnapshot();
89
+ dockerAvailable = false;
90
+ hostRequirementFacts() {
91
+ const facts = this.hostLoad.facts();
92
+ return {
93
+ logicalThreads: facts?.logicalThreads ?? os.cpus().length,
94
+ totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
95
+ availableToolchains: Object.entries(this.hostCapabilities.toolchains)
96
+ .filter(([, tool]) => tool?.available === true)
97
+ .map(([name]) => name),
98
+ dockerAvailable: this.dockerAvailable,
99
+ browserLaunch: this.hostCapabilities.browserLaunch,
100
+ testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
101
+ };
102
+ }
87
103
  // Reaping deletes the stale ledger, so its stopped-process proof is held here
88
104
  // until a Hello carrying it is accepted. A bridge restart forgets it, which
89
105
  // leaves those attempts on Forge's conservative unknown-outcome path.
90
106
  recoveredHostAttempts = new Map();
91
107
  hostCapabilitiesDetected = false;
92
- constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox, hostLoad = new HostLoadSampler()) {
108
+ constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
109
+ // Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
110
+ hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
93
111
  this.config = config;
94
112
  this.connections = connections;
95
113
  this.hostCapabilityProbe = hostCapabilityProbe;
@@ -126,8 +144,10 @@ export class ForgeBridgeService {
126
144
  },
127
145
  onStatus: logBridgeStatus,
128
146
  });
129
- this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
130
- this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
147
+ const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
148
+ this.sessions = sessions ?? defaultSessions.sessions;
149
+ // Docker sandboxes ask the same host load governor for their validation tokens.
150
+ this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
131
151
  this.sandboxResourceResolver = sandboxResourceResolver
132
152
  ?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
133
153
  this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
@@ -162,6 +182,7 @@ export class ForgeBridgeService {
162
182
  // Static host facts and the first load sample ride on Hello; the sampler
163
183
  // keeps refreshing its cached snapshot for later heartbeats.
164
184
  await this.hostLoad.start().catch(() => undefined);
185
+ this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
165
186
  const connection = this.connections.create(this.config);
166
187
  this.connection = connection;
167
188
  this.transportRecovery = null;
@@ -1677,6 +1698,7 @@ export class ForgeBridgeService {
1677
1698
  capabilities() {
1678
1699
  const preflight = this.preflight.current();
1679
1700
  const dockerEngine = this.dockerEngineProbe.current();
1701
+ this.dockerAvailable = dockerEngine?.available === true;
1680
1702
  const runtimeState = this.sandboxRuntime.snapshot();
1681
1703
  const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
1682
1704
  const used = this.usedSandboxResources(runtimeState.degraded);
@@ -1716,6 +1738,7 @@ export class ForgeBridgeService {
1716
1738
  playwrightProjects: this.hostCapabilities.playwrightProjects,
1717
1739
  browserLaunch: this.hostCapabilities.browserLaunch,
1718
1740
  providerConnectivity: this.hostCapabilities.providerConnectivity,
1741
+ testPostgres: this.hostCapabilities.testPostgres,
1719
1742
  host: this.hostLoad.facts(),
1720
1743
  load: this.hostLoad.current(),
1721
1744
  maxConcurrentSandboxes: capacity.sandboxSlots,
@@ -1949,7 +1972,8 @@ function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, doc
1949
1972
  const processSupervisors = new AttemptProcessSupervisorRegistry();
1950
1973
  const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
1951
1974
  const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
1952
- 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);
1975
+ const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
1976
+ return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
1953
1977
  }
1954
1978
  export class SignalRBridgeConnectionFactory {
1955
1979
  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
+ }
@@ -31,7 +31,7 @@ export class ForgeBridgeCliService {
31
31
  cleanupFactory;
32
32
  dotNetToolchainConfigurator;
33
33
  constructor(
34
- // The default session chain validates without the host load governor (Docker-mode gap, decision 0013).
34
+ // In a Docker sandbox the default chain's validator asks the host bridge for host load tokens (decision 0013).
35
35
  sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
36
36
  this.sessions = sessions;
37
37
  this.bridgeFactory = bridgeFactory;
@@ -0,0 +1,22 @@
1
+ import { HostLoadGovernor } from "./host-load-governor.js";
2
+ export declare const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
3
+ export declare const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
4
+ /** True for the variables that carry the governor into a child process. */
5
+ /**
6
+ * A process environment with every host load governor variable removed
7
+ * (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
8
+ * the host ledger, or broker control, that their step's token is held in.
9
+ */
10
+ export declare function withoutHostLoadGovernorVariables<T extends Readonly<Record<string, string | undefined>>>(environment: T): T;
11
+ export declare function isHostLoadChildEnvironmentName(name: string): boolean;
12
+ /**
13
+ * The variables a child needs to share this bridge's ledger: the flag, the
14
+ * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
15
+ * unit. Empty with the governor off, so the child stays ungoverned.
16
+ */
17
+ export declare function hostLoadChildEnvironment(stateRoot: string, environment?: Readonly<Record<string, string | undefined>>): Readonly<Record<string, string>>;
18
+ /**
19
+ * The governor a child process uses, from the variables above. Undefined when
20
+ * the flag is off or no state root was handed over: the child is ungoverned.
21
+ */
22
+ export declare function hostLoadGovernorFromChildEnvironment(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernor | undefined;
@@ -0,0 +1,65 @@
1
+ import path from "node:path";
2
+ import { HostLoadGovernor } from "./host-load-governor.js";
3
+ import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
4
+ import { FileForgeCgroupRegistry } from "./host-load-forge-cgroups.js";
5
+ import { HostLoadSampler } from "./host-load-sampler.js";
6
+ // How a process the bridge starts (the completion MCP server, which runs
7
+ // managed commands) joins the bridge's host load governor (decision 0013).
8
+ // The ledger is file-backed, so the child builds its own governor on the
9
+ // bridge's state root and every token counts against one host budget.
10
+ export const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
11
+ export const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
12
+ const cgroupUnitEnvironment = "FORGE_BRIDGE_CGROUP_UNIT";
13
+ /** True for the variables that carry the governor into a child process. */
14
+ /**
15
+ * A process environment with every host load governor variable removed
16
+ * (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
17
+ * the host ledger, or broker control, that their step's token is held in.
18
+ */
19
+ export function withoutHostLoadGovernorVariables(environment) {
20
+ const kept = {};
21
+ for (const [name, value] of Object.entries(environment)) {
22
+ if (!name.toUpperCase().startsWith("FORGE_HOST_LOAD_"))
23
+ kept[name] = value;
24
+ }
25
+ return kept;
26
+ }
27
+ export function isHostLoadChildEnvironmentName(name) {
28
+ return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment;
29
+ }
30
+ /**
31
+ * The variables a child needs to share this bridge's ledger: the flag, the
32
+ * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
33
+ * unit. Empty with the governor off, so the child stays ungoverned.
34
+ */
35
+ export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
36
+ if (loadHostLoadGovernorConfig(environment).mode !== "on")
37
+ return {};
38
+ const forwarded = {};
39
+ for (const [name, value] of Object.entries(environment)) {
40
+ if (typeof value === "string" && value.trim() && isHostLoadChildEnvironmentName(name))
41
+ forwarded[name] = value;
42
+ }
43
+ forwarded[hostLoadGovernorEnvironment] = "on";
44
+ forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
45
+ return forwarded;
46
+ }
47
+ /**
48
+ * The governor a child process uses, from the variables above. Undefined when
49
+ * the flag is off or no state root was handed over: the child is ungoverned.
50
+ */
51
+ export function hostLoadGovernorFromChildEnvironment(environment = process.env) {
52
+ const config = loadHostLoadGovernorConfig(environment);
53
+ const stateRoot = environment[hostLoadStateRootEnvironment]?.trim();
54
+ if (config.mode !== "on" || !stateRoot || !path.isAbsolute(stateRoot))
55
+ return undefined;
56
+ return new HostLoadGovernor({
57
+ stateRoot,
58
+ config,
59
+ load: new HostLoadSampler({
60
+ cgroupUnit: environment[cgroupUnitEnvironment]?.trim() || null,
61
+ // The bridge registers its Docker sandboxes here: their CPU is Forge's own here too.
62
+ forgeCgroups: new FileForgeCgroupRegistry(stateRoot),
63
+ }),
64
+ });
65
+ }
@@ -1,4 +1,45 @@
1
1
  import { type HostEnvironment } from "./host-facts.js";
2
+ /** Where a sampler learns which cgroups hold Forge's own Docker sandbox work. */
3
+ export interface ForgeCgroupSource {
4
+ paths(): readonly string[] | Promise<readonly string[]>;
5
+ }
6
+ /** Where the sandbox runtime records the cgroups of the containers it launched. */
7
+ export interface ForgeCgroupWriter {
8
+ set(owner: string, cgroupPaths: readonly string[]): void;
9
+ delete(owner: string): void;
10
+ }
11
+ /** Cgroups of Docker sandbox containers this bridge launched (paths below the cgroup root). */
12
+ export declare class ForgeCgroupRegistry implements ForgeCgroupSource, ForgeCgroupWriter {
13
+ private readonly entries;
14
+ set(owner: string, cgroupPaths: readonly string[]): void;
15
+ delete(owner: string): void;
16
+ paths(): readonly string[];
17
+ }
18
+ /**
19
+ * The registry shared by every process on the governor's state root: the
20
+ * bridge's sandbox runtime writes it, and both the bridge's and the MCP
21
+ * servers' samplers read it, so all of them count sandbox CPU as Forge's own.
22
+ */
23
+ export declare class FileForgeCgroupRegistry implements ForgeCgroupSource, ForgeCgroupWriter {
24
+ private readonly filePath;
25
+ private readonly registered;
26
+ private writing;
27
+ constructor(stateRoot: string);
28
+ set(owner: string, cgroupPaths: readonly string[]): void;
29
+ delete(owner: string): void;
30
+ paths(): Promise<readonly string[]>;
31
+ /** Settles once every registration so far is on disk (tests). */
32
+ flushed(): Promise<void>;
33
+ private persist;
34
+ }
35
+ /** CPU cores used by a changing set of cgroups, from `cpu.stat usage_usec` deltas. */
36
+ export declare class ForgeCgroupCpuMeter {
37
+ private readonly environment;
38
+ private marks;
39
+ constructor(environment: HostEnvironment);
40
+ /** Cores used since the previous call; a cgroup seen for the first time contributes from the next window. */
41
+ coresInUse(cgroupPaths: readonly string[], atMs: number): Promise<number>;
42
+ }
2
43
  /**
3
44
  * Free memory under the tightest `memory.max` from the cgroup up to and
4
45
  * including the root (`memory.max − memory.current`), or null when no limit is
@@ -1,9 +1,98 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
1
3
  import path from "node:path";
2
4
  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.
5
+ import { parseCgroupCpuUsageUsec, parseNonNegativeInteger } from "./host-pressure-stall.js";
6
+ /** Cgroups of Docker sandbox containers this bridge launched (paths below the cgroup root). */
7
+ export class ForgeCgroupRegistry {
8
+ entries = new Map();
9
+ set(owner, cgroupPaths) {
10
+ if (cgroupPaths.length === 0)
11
+ this.entries.delete(owner);
12
+ else
13
+ this.entries.set(owner, [...cgroupPaths]);
14
+ }
15
+ delete(owner) {
16
+ this.entries.delete(owner);
17
+ }
18
+ paths() {
19
+ return [...new Set([...this.entries.values()].flat())];
20
+ }
21
+ }
22
+ /**
23
+ * The registry shared by every process on the governor's state root: the
24
+ * bridge's sandbox runtime writes it, and both the bridge's and the MCP
25
+ * servers' samplers read it, so all of them count sandbox CPU as Forge's own.
26
+ */
27
+ export class FileForgeCgroupRegistry {
28
+ filePath;
29
+ registered = new ForgeCgroupRegistry();
30
+ writing = Promise.resolve();
31
+ constructor(stateRoot) {
32
+ this.filePath = path.join(stateRoot, "host-load-governor", "forge-cgroups.v1.json");
33
+ }
34
+ set(owner, cgroupPaths) {
35
+ this.registered.set(owner, cgroupPaths);
36
+ this.persist();
37
+ }
38
+ delete(owner) {
39
+ this.registered.delete(owner);
40
+ this.persist();
41
+ }
42
+ paths() {
43
+ return fs.readFile(this.filePath, "utf8")
44
+ .then(content => {
45
+ const parsed = JSON.parse(content);
46
+ return Array.isArray(parsed.paths)
47
+ ? parsed.paths.filter((entry) => typeof entry === "string").slice(0, 256)
48
+ : [];
49
+ })
50
+ .catch(() => []);
51
+ }
52
+ /** Settles once every registration so far is on disk (tests). */
53
+ async flushed() {
54
+ await this.writing;
55
+ }
56
+ persist() {
57
+ const snapshot = JSON.stringify({ schemaVersion: 1, paths: this.registered.paths() });
58
+ this.writing = this.writing.then(async () => {
59
+ await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 0o700 });
60
+ const temporary = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
61
+ await fs.writeFile(temporary, snapshot, { mode: 0o600 });
62
+ await fs.rename(temporary, this.filePath);
63
+ }).catch(() => undefined);
64
+ }
65
+ }
66
+ /** CPU cores used by a changing set of cgroups, from `cpu.stat usage_usec` deltas. */
67
+ export class ForgeCgroupCpuMeter {
68
+ environment;
69
+ marks = new Map();
70
+ constructor(environment) {
71
+ this.environment = environment;
72
+ }
73
+ /** Cores used since the previous call; a cgroup seen for the first time contributes from the next window. */
74
+ async coresInUse(cgroupPaths, atMs) {
75
+ const next = new Map();
76
+ let cores = 0;
77
+ for (const cgroupPath of cgroupPaths) {
78
+ const directory = cgroupDirectory(this.environment, cgroupPath);
79
+ if (!directory)
80
+ continue;
81
+ const content = await readOptional(this.environment, path.posix.join(directory, "cpu.stat"));
82
+ const usageUsec = content ? parseCgroupCpuUsageUsec(content) : null;
83
+ if (usageUsec === null)
84
+ continue;
85
+ next.set(cgroupPath, { usageUsec, atMs });
86
+ const previous = this.marks.get(cgroupPath);
87
+ const elapsedUsec = previous ? (atMs - previous.atMs) * 1_000 : 0;
88
+ if (previous && elapsedUsec > 0 && usageUsec >= previous.usageUsec) {
89
+ cores += (usageUsec - previous.usageUsec) / elapsedUsec;
90
+ }
91
+ }
92
+ this.marks = next;
93
+ return cores;
94
+ }
95
+ }
7
96
  /**
8
97
  * Free memory under the tightest `memory.max` from the cgroup up to and
9
98
  * including the root (`memory.max − memory.current`), or null when no limit is