@loucompanion/forge-bridge 0.1.4-dev.b33004c2b0ea → 0.1.4-dev.bb5355d0d83f

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 (87) hide show
  1. package/README.md +13 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.service.d.ts +1 -1
  7. package/dist/bridge/bridge.service.js +4 -110
  8. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  9. package/dist/bridge/runner-host-capabilities.js +13 -0
  10. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  11. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  12. package/dist/runtime/docker-engine-probe.js +7 -0
  13. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  14. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  15. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  16. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  17. package/dist/runtime/host-facts.d.ts +2 -1
  18. package/dist/runtime/host-load-admission.d.ts +9 -2
  19. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  20. package/dist/runtime/host-load-child-environment.js +19 -10
  21. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  22. package/dist/runtime/host-load-governor-config.js +7 -0
  23. package/dist/runtime/host-load-governor.d.ts +10 -0
  24. package/dist/runtime/host-load-governor.js +125 -34
  25. package/dist/runtime/host-load-sampler.d.ts +34 -4
  26. package/dist/runtime/host-load-sampler.js +73 -7
  27. package/dist/runtime/host-load-step-class.d.ts +3 -1
  28. package/dist/runtime/host-load-step-class.js +60 -5
  29. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  30. package/dist/runtime/host-load-test-slot.js +81 -0
  31. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  32. package/dist/runtime/host-load-token-ledger.js +93 -61
  33. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  34. package/dist/runtime/host-load-windows-cpu.js +85 -0
  35. package/dist/runtime/host-runtime-lease.d.ts +1 -1
  36. package/dist/runtime/host-runtime-lease.js +1 -1
  37. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  38. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  39. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  40. package/dist/sandbox/host-capacity-broker.js +23 -4
  41. package/dist/session/architect-waits.d.ts +2 -0
  42. package/dist/session/architect-waits.js +138 -0
  43. package/dist/session/managed-attempt-tools.d.ts +0 -7
  44. package/dist/session/managed-attempt-tools.js +51 -62
  45. package/dist/session/managed-command-host-load.d.ts +2 -0
  46. package/dist/session/managed-command-host-load.js +2 -1
  47. package/dist/session/phase-completion.runtime.js +1 -1
  48. package/dist/session/phase-completion.schemas.js +25 -23
  49. package/dist/session/phase-completion.validation.js +3 -1
  50. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  51. package/dist/session/pre-publication-native-postgres.js +111 -0
  52. package/dist/session/pre-publication-pass.d.ts +2 -1
  53. package/dist/session/pre-publication-pass.js +8 -5
  54. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  55. package/dist/session/pre-publication-step-execution.js +6 -5
  56. package/dist/session/pre-publication-validation.d.ts +9 -3
  57. package/dist/session/pre-publication-validation.js +62 -34
  58. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  59. package/dist/session/provider-cli/claude-background-work.js +180 -0
  60. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  61. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  62. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  63. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  64. package/dist/session/provider-cli/provider-cli.process.d.ts +13 -22
  65. package/dist/session/provider-cli/provider-cli.process.js +36 -337
  66. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  67. package/dist/session/provider-cli/provider-cli.prompts.js +45 -8
  68. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  69. package/dist/session/provider-cli/provider-cli.service.js +2 -8
  70. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  71. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  72. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  73. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  74. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  75. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  76. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  77. package/dist/session/provider-cli/provider-output-state.js +6 -0
  78. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  79. package/dist/session/session.types.js +1 -1
  80. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  81. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  82. package/dist/shared/process/windows-launch.d.ts +18 -0
  83. package/dist/shared/process/windows-launch.js +68 -0
  84. package/dist/shared/provider-capabilities.js +5 -6
  85. package/dist/version.d.ts +1 -1
  86. package/dist/version.js +1 -1
  87. package/package.json +1 -1
@@ -0,0 +1,303 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes, randomUUID } from "node:crypto";
3
+ import fs from "node:fs/promises";
4
+ import net from "node:net";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ // A throwaway PostgreSQL cluster for one test run (owner policy 2026-11-17: native PostgreSQL
8
+ // for every tier, made safe per attempt). The Bridge runs initdb in a fresh directory, starts
9
+ // the server on a free loopback port as its own OS user, and hands the test run the cluster's
10
+ // bootstrap superuser. The run is superuser of that cluster only: the cluster holds nothing but
11
+ // what the run creates, and it is stopped and deleted when the run ends. A Bridge that died
12
+ // before its release leaves a directory whose owner process is gone; the next start reaps it.
13
+ /** Set for a test run on an ephemeral cluster: its id, which the server reports as `forge.ephemeral_cluster`. */
14
+ export const ephemeralTestPostgresClusterEnvironment = "FORGE_TEST_POSTGRES_EPHEMERAL_CLUSTER";
15
+ export const ephemeralTestPostgresMarkerSetting = "forge.ephemeral_cluster";
16
+ const superuserName = "forge_ephemeral";
17
+ const ownerFileName = "owner.json";
18
+ const clusterDirectoryPattern = /^[0-9a-f]{32}$/u;
19
+ // A directory without a readable owner file is a start that is still writing it, or one that
20
+ // died before it could; only the second is old.
21
+ const unownedDirectoryGraceMs = 10 * 60_000;
22
+ const startAttempts = 3;
23
+ export class EphemeralTestPostgresError extends Error {
24
+ code = "ephemeral_test_postgres_unavailable";
25
+ constructor(detail) {
26
+ super(`ephemeral_test_postgres_unavailable: ${detail}`);
27
+ this.name = "EphemeralTestPostgresError";
28
+ }
29
+ }
30
+ export function defaultEphemeralTestPostgresRoot() {
31
+ if (process.platform === "win32") {
32
+ const localAppData = process.env.LOCALAPPDATA?.trim() || path.join(os.homedir(), "AppData", "Local");
33
+ return path.join(localAppData, "forge", "ephemeral-test-postgres");
34
+ }
35
+ const stateHome = process.env.XDG_STATE_HOME?.trim() || path.join(os.homedir(), ".local", "state");
36
+ return path.join(stateHome, "forge", "ephemeral-test-postgres");
37
+ }
38
+ function resolveOptions(options) {
39
+ return {
40
+ binDirectory: options.binDirectory,
41
+ root: options.root ?? defaultEphemeralTestPostgresRoot(),
42
+ ownerPid: options.ownerPid ?? process.pid,
43
+ runTool: options.runTool ?? runPostgresTool,
44
+ isProcessAlive: options.isProcessAlive ?? processIsAlive,
45
+ freePort: options.freePort ?? freeLoopbackPort,
46
+ now: options.now ?? Date.now,
47
+ };
48
+ }
49
+ function program(options, name) {
50
+ return path.join(options.binDirectory, process.platform === "win32" ? `${name}.exe` : name);
51
+ }
52
+ /**
53
+ * A superuser of a cluster run by the `postgres` OS user can read every cluster that user runs,
54
+ * including live ones (Debian and Ubuntu packages run them all as `postgres`). An ephemeral
55
+ * cluster therefore runs only as an ordinary user, the same one that already runs the attempt.
56
+ */
57
+ export function assertEphemeralClusterOsUser(userName = os.userInfo().username, uid = process.getuid?.()) {
58
+ if (uid === 0 || userName.toLowerCase() === "postgres") {
59
+ throw new EphemeralTestPostgresError(`ephemeral test clusters do not run as the '${uid === 0 ? "root" : userName}' OS user; run the Bridge as an ordinary user.`);
60
+ }
61
+ }
62
+ /** Creates, starts and prepares one cluster. On any failure nothing of it is left behind. */
63
+ export async function startEphemeralTestPostgres(options) {
64
+ assertEphemeralClusterOsUser();
65
+ const resolved = resolveOptions(options);
66
+ await reapEphemeralTestPostgres(options);
67
+ await fs.mkdir(resolved.root, { recursive: true });
68
+ const id = randomUUID().replaceAll("-", "");
69
+ const directory = path.join(resolved.root, id);
70
+ await fs.mkdir(directory);
71
+ const release = once(async () => await stopAndRemove(resolved, directory));
72
+ try {
73
+ await fs.writeFile(path.join(directory, ownerFileName), JSON.stringify({
74
+ schemaVersion: 1,
75
+ ownerPid: resolved.ownerPid,
76
+ createdAt: new Date(resolved.now()).toISOString(),
77
+ }));
78
+ const password = randomBytes(24).toString("hex");
79
+ await initializeCluster(resolved, directory, password);
80
+ const port = await startServer(resolved, directory, id);
81
+ await prepareCluster(resolved, port, password, id);
82
+ const endpoint = `127.0.0.1:${port}`;
83
+ return {
84
+ id,
85
+ endpoint,
86
+ password,
87
+ connectionString: `Host=127.0.0.1;Port=${port};Database=postgres;Username=${superuserName};Password=${password}`,
88
+ release,
89
+ };
90
+ }
91
+ catch (error) {
92
+ await release().catch(() => undefined);
93
+ throw error instanceof EphemeralTestPostgresError
94
+ ? error
95
+ : new EphemeralTestPostgresError(error instanceof Error ? error.message : String(error));
96
+ }
97
+ }
98
+ async function initializeCluster(options, directory, password) {
99
+ const passwordFile = path.join(directory, "bootstrap-password");
100
+ await fs.writeFile(passwordFile, password, { mode: 0o600 });
101
+ try {
102
+ const result = await options.runTool(program(options, "initdb"), [
103
+ "-D", path.join(directory, "data"),
104
+ "-U", superuserName,
105
+ "-A", "scram-sha-256",
106
+ `--pwfile=${passwordFile}`,
107
+ "-E", "UTF8",
108
+ "--locale=C",
109
+ // The cluster is deleted with its run, so durability buys nothing.
110
+ "--no-sync",
111
+ "--no-instructions",
112
+ ], { env: toolEnvironment(), timeoutMs: 120_000 });
113
+ if (result.code !== 0)
114
+ throw new EphemeralTestPostgresError(`initdb exited ${result.code}: ${tail(result.output)}`);
115
+ }
116
+ finally {
117
+ await fs.rm(passwordFile, { force: true });
118
+ }
119
+ }
120
+ function serverSettings(port, id) {
121
+ return [
122
+ "",
123
+ "# Forge ephemeral test cluster: loopback only, deleted with its test run.",
124
+ "listen_addresses = '127.0.0.1'",
125
+ `port = ${port}`,
126
+ "unix_socket_directories = ''",
127
+ // Each live test collection holds an API host's pools and a cloned database.
128
+ "max_connections = 300",
129
+ "fsync = off",
130
+ "synchronous_commit = off",
131
+ "full_page_writes = off",
132
+ `${ephemeralTestPostgresMarkerSetting} = '${id}'`,
133
+ "",
134
+ ].join("\n");
135
+ }
136
+ /** Starts the server on a free loopback port, choosing another if a racing process took it. */
137
+ async function startServer(options, directory, id) {
138
+ const data = path.join(directory, "data");
139
+ const configuration = path.join(data, "postgresql.conf");
140
+ const original = await fs.readFile(configuration, "utf8");
141
+ let lastFailure = "";
142
+ for (let attempt = 1; attempt <= startAttempts; attempt += 1) {
143
+ const port = await options.freePort();
144
+ await fs.writeFile(configuration, original + serverSettings(port, id));
145
+ const result = await options.runTool(program(options, "pg_ctl"), [
146
+ "-D", data, "-l", path.join(directory, "postgres.log"), "-w", "-t", "60", "start",
147
+ ], { env: toolEnvironment(), timeoutMs: 90_000, detached: true });
148
+ if (result.code === 0)
149
+ return port;
150
+ lastFailure = `pg_ctl start exited ${result.code}: ${await logTail(directory)}`;
151
+ }
152
+ throw new EphemeralTestPostgresError(lastFailure);
153
+ }
154
+ /** pgvector is not a trusted extension; installing it in template1 gives every test database the type. */
155
+ async function prepareCluster(options, port, password, id) {
156
+ const result = await options.runTool(program(options, "psql"), [
157
+ "-X", "-q", "-A", "-t", "-w", "-v", "ON_ERROR_STOP=1",
158
+ "-h", "127.0.0.1", "-p", String(port), "-U", superuserName, "-d", "template1",
159
+ "-c", "CREATE EXTENSION IF NOT EXISTS vector",
160
+ "-c", `SELECT current_setting('${ephemeralTestPostgresMarkerSetting}')`,
161
+ ], { env: { ...toolEnvironment(), PGPASSWORD: password, PGCONNECT_TIMEOUT: "10" }, timeoutMs: 60_000 });
162
+ if (result.code !== 0) {
163
+ throw new EphemeralTestPostgresError(`preparing the cluster failed: ${tail(result.output.replaceAll(password, "[redacted]"))}`);
164
+ }
165
+ if (result.output.trim() !== id) {
166
+ throw new EphemeralTestPostgresError("the started server did not report this cluster's marker.");
167
+ }
168
+ }
169
+ async function stopAndRemove(options, directory) {
170
+ const data = path.join(directory, "data");
171
+ if (await exists(path.join(data, "postmaster.pid"))) {
172
+ // Immediate: nothing in the cluster is worth a checkpoint.
173
+ const stopped = await options.runTool(program(options, "pg_ctl"), ["-D", data, "-m", "immediate", "-w", "-t", "30", "stop"], {
174
+ env: toolEnvironment(),
175
+ timeoutMs: 60_000,
176
+ });
177
+ if (stopped.code !== 0 && await serverStillRuns(options, data)) {
178
+ // Never delete a live server's directory. Disowning it lets the next start's reap try again.
179
+ await fs.writeFile(path.join(directory, ownerFileName), JSON.stringify({ schemaVersion: 1, ownerPid: null }))
180
+ .catch(() => undefined);
181
+ throw new EphemeralTestPostgresError(`pg_ctl stop exited ${stopped.code}; the cluster is left for the next reap: ${tail(stopped.output)}`);
182
+ }
183
+ }
184
+ await fs.rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
185
+ }
186
+ /** pg_ctl status exits 3 when no server runs in the directory; anything else counts as running. */
187
+ async function serverStillRuns(options, data) {
188
+ const status = await options.runTool(program(options, "pg_ctl"), ["-D", data, "status"], {
189
+ env: toolEnvironment(),
190
+ timeoutMs: 30_000,
191
+ }).catch(() => ({ code: null, output: "" }));
192
+ return status.code !== 3;
193
+ }
194
+ /**
195
+ * Removes clusters whose owning Bridge process is gone. Only directories named like a cluster
196
+ * id inside the root are considered, and a live owner's clusters are never touched.
197
+ */
198
+ export async function reapEphemeralTestPostgres(options) {
199
+ const resolved = resolveOptions(options);
200
+ let entries;
201
+ try {
202
+ entries = await fs.readdir(resolved.root);
203
+ }
204
+ catch (error) {
205
+ if (error.code === "ENOENT")
206
+ return [];
207
+ throw error;
208
+ }
209
+ const reaped = [];
210
+ for (const entry of entries.filter(name => clusterDirectoryPattern.test(name))) {
211
+ const directory = path.join(resolved.root, entry);
212
+ if (!await isAbandoned(resolved, directory))
213
+ continue;
214
+ try {
215
+ await stopAndRemove(resolved, directory);
216
+ reaped.push(entry);
217
+ }
218
+ catch {
219
+ // One stuck directory does not stop the rest; the next start tries again.
220
+ }
221
+ }
222
+ return reaped;
223
+ }
224
+ async function isAbandoned(options, directory) {
225
+ try {
226
+ const owner = JSON.parse(await fs.readFile(path.join(directory, ownerFileName), "utf8"));
227
+ return typeof owner.ownerPid !== "number" || !options.isProcessAlive(owner.ownerPid);
228
+ }
229
+ catch {
230
+ const stat = await fs.stat(directory).catch(() => null);
231
+ return stat !== null && options.now() - stat.mtimeMs > unownedDirectoryGraceMs;
232
+ }
233
+ }
234
+ function processIsAlive(pid) {
235
+ try {
236
+ process.kill(pid, 0);
237
+ return true;
238
+ }
239
+ catch (error) {
240
+ // EPERM: the process exists but belongs to someone else.
241
+ return error.code === "EPERM";
242
+ }
243
+ }
244
+ async function freeLoopbackPort() {
245
+ return await new Promise((resolve, reject) => {
246
+ const server = net.createServer();
247
+ server.once("error", reject);
248
+ server.listen(0, "127.0.0.1", () => {
249
+ const address = server.address();
250
+ server.close(() => typeof address === "object" && address
251
+ ? resolve(address.port)
252
+ : reject(new EphemeralTestPostgresError("no free loopback port")));
253
+ });
254
+ });
255
+ }
256
+ /** Only what the PostgreSQL programs need: never the Bridge's own environment. */
257
+ function toolEnvironment() {
258
+ const names = ["PATH", "SystemRoot", "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "LANG"];
259
+ return Object.fromEntries(names.flatMap(name => process.env[name] ? [[name, process.env[name]]] : []));
260
+ }
261
+ /**
262
+ * On Windows a started postgres inherits pg_ctl's standard handles, so a pipe would stay open for
263
+ * the server's lifetime; a detached program gets no pipes and settles when it exits.
264
+ */
265
+ export const runPostgresTool = (file, args, options) => new Promise((resolve, reject) => {
266
+ const child = spawn(file, [...args], {
267
+ env: { ...options.env },
268
+ stdio: options.detached ? "ignore" : ["ignore", "pipe", "pipe"],
269
+ windowsHide: true,
270
+ });
271
+ let output = "";
272
+ child.stdout?.setEncoding("utf8").on("data", chunk => { output += chunk; });
273
+ child.stderr?.setEncoding("utf8").on("data", chunk => { output += chunk; });
274
+ const timer = setTimeout(() => child.kill(), options.timeoutMs);
275
+ child.once("error", error => {
276
+ clearTimeout(timer);
277
+ reject(error);
278
+ });
279
+ child.once(options.detached ? "exit" : "close", code => {
280
+ clearTimeout(timer);
281
+ resolve({ code, output });
282
+ });
283
+ });
284
+ async function logTail(directory) {
285
+ return tail(await fs.readFile(path.join(directory, "postgres.log"), "utf8").catch(() => ""));
286
+ }
287
+ function tail(text) {
288
+ return text.trim().slice(-1_500);
289
+ }
290
+ async function exists(file) {
291
+ return await fs.access(file).then(() => true, () => false);
292
+ }
293
+ function once(action) {
294
+ let running = null;
295
+ return async () => {
296
+ // A failed release may be retried; a successful one is not repeated.
297
+ running ??= action().catch(error => {
298
+ running = null;
299
+ throw error;
300
+ });
301
+ await running;
302
+ };
303
+ }
@@ -18,7 +18,8 @@ export interface HostEnvironment {
18
18
  readonly etcRoot: string;
19
19
  readonly cgroupRoot: string;
20
20
  readonly readFile: HostFileReader;
21
- readonly cpus: () => readonly Pick<os.CpuInfo, "model">[];
21
+ /** CPU models (host facts) and, where reported, cumulative CPU times (the Windows load sampler). */
22
+ readonly cpus: () => readonly (Pick<os.CpuInfo, "model"> & Partial<Pick<os.CpuInfo, "times">>)[];
22
23
  readonly totalMemoryBytes: () => number;
23
24
  readonly freeMemoryBytes: () => number;
24
25
  readonly architecture: () => string;
@@ -2,7 +2,10 @@ import type { HostLoadGovernorConfig } from "./host-load-governor-config.js";
2
2
  import type { HostLoadStepCost } from "./host-load-step-class.js";
3
3
  /** Measured host load the admission rule reads. Null means PSI is unavailable or stale. */
4
4
  export interface HostLoadSignals {
5
- /** Host-wide CPU PSI `some avg10`, used as is (never split per cgroup). */
5
+ /**
6
+ * Host-wide CPU PSI `some avg10`, used as is (never split per cgroup). On Windows,
7
+ * the estimate from host CPU use in the same shape (decision 0021).
8
+ */
6
9
  readonly cpuSomeAvg10: number;
7
10
  /** Consecutive samples, ending with the latest, at or above the CPU pressure threshold. */
8
11
  readonly cpuPressuredSamples: number;
@@ -20,7 +23,11 @@ export type HostLoadAdmissionReason = "admitted" | "admitted_alone" | "admitted_
20
23
  /** Decision 0014: the host already runs the owner's maximum number of heavy steps. */
21
24
  | "heavy_step_limit"
22
25
  /** A corrupt ledger was quarantined; admissions wait one lease while owners restore their reservations. */
23
- | "ledger_recovering";
26
+ | "ledger_recovering"
27
+ /** Decision 0018: the host test slot is free and this step is next in the host queue. */
28
+ | "admitted_test_slot"
29
+ /** Decision 0018: the host test slot is taken, or steps ahead in the host queue take it first. */
30
+ | "host_test_slot";
24
31
  export interface HostLoadAdmissionInput {
25
32
  readonly request: HostLoadStepCost;
26
33
  /** Reserved cost of every live token on this host (all processes). */
@@ -1,22 +1,27 @@
1
1
  import { HostLoadGovernor } from "./host-load-governor.js";
2
2
  export declare const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
3
3
  export declare const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
4
+ export declare const hostLoadTestSlotsEnvironment = "FORGE_HOST_LOAD_TEST_SLOTS";
4
5
  /** True for the variables that carry the governor into a child process. */
5
6
  /**
6
7
  * 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.
8
+ * (FORGE_HOST_LOAD_*, any case) and the governor turned off explicitly. A governed
9
+ * step's own processes must never join the host ledger, or broker control, that
10
+ * their step's token is held in; since the host test slot is on by default
11
+ * (decision 0018), removing the variables alone would not keep a nested Forge
12
+ * process out.
9
13
  */
10
14
  export declare function withoutHostLoadGovernorVariables<T extends Readonly<Record<string, string | undefined>>>(environment: T): T;
11
15
  export declare function isHostLoadChildEnvironmentName(name: string): boolean;
12
16
  /**
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.
17
+ * The variables a child needs to share this bridge's ledger: the budget flag and
18
+ * the host test slot count as this bridge resolved them, the state root, the
19
+ * operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup unit. Empty with
20
+ * the governor off, so the child stays ungoverned.
16
21
  */
17
22
  export declare function hostLoadChildEnvironment(stateRoot: string, environment?: Readonly<Record<string, string | undefined>>): Readonly<Record<string, string>>;
18
23
  /**
19
24
  * 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.
25
+ * the governor is off or no state root was handed over: the child is ungoverned.
21
26
  */
22
27
  export declare function hostLoadGovernorFromChildEnvironment(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernor | undefined;
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { HostLoadGovernor } from "./host-load-governor.js";
3
- import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
3
+ import { hostLoadGovernorEnabled, loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
4
4
  import { FileForgeCgroupRegistry } from "./host-load-forge-cgroups.js";
5
5
  import { HostLoadSampler } from "./host-load-sampler.js";
6
6
  // How a process the bridge starts (the completion MCP server, which runs
@@ -9,12 +9,16 @@ import { HostLoadSampler } from "./host-load-sampler.js";
9
9
  // bridge's state root and every token counts against one host budget.
10
10
  export const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
11
11
  export const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
12
+ export const hostLoadTestSlotsEnvironment = "FORGE_HOST_LOAD_TEST_SLOTS";
12
13
  const cgroupUnitEnvironment = "FORGE_BRIDGE_CGROUP_UNIT";
13
14
  /** True for the variables that carry the governor into a child process. */
14
15
  /**
15
16
  * 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.
17
+ * (FORGE_HOST_LOAD_*, any case) and the governor turned off explicitly. A governed
18
+ * step's own processes must never join the host ledger, or broker control, that
19
+ * their step's token is held in; since the host test slot is on by default
20
+ * (decision 0018), removing the variables alone would not keep a nested Forge
21
+ * process out.
18
22
  */
19
23
  export function withoutHostLoadGovernorVariables(environment) {
20
24
  const kept = {};
@@ -22,6 +26,8 @@ export function withoutHostLoadGovernorVariables(environment) {
22
26
  if (!name.toUpperCase().startsWith("FORGE_HOST_LOAD_"))
23
27
  kept[name] = value;
24
28
  }
29
+ kept[hostLoadGovernorEnvironment] = "off";
30
+ kept[hostLoadTestSlotsEnvironment] = "0";
25
31
  return kept;
26
32
  }
27
33
  // Decision 0014 operator ceilings the child's governor applies itself (host-load-governor-config.ts).
@@ -30,30 +36,33 @@ export function isHostLoadChildEnvironmentName(name) {
30
36
  return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment || hostCeilingEnvironmentNames.has(name);
31
37
  }
32
38
  /**
33
- * The variables a child needs to share this bridge's ledger: the flag, the
34
- * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
35
- * unit. Empty with the governor off, so the child stays ungoverned.
39
+ * The variables a child needs to share this bridge's ledger: the budget flag and
40
+ * the host test slot count as this bridge resolved them, the state root, the
41
+ * operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup unit. Empty with
42
+ * the governor off, so the child stays ungoverned.
36
43
  */
37
44
  export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
38
- if (loadHostLoadGovernorConfig(environment).mode !== "on")
45
+ const config = loadHostLoadGovernorConfig(environment);
46
+ if (!hostLoadGovernorEnabled(config))
39
47
  return {};
40
48
  const forwarded = {};
41
49
  for (const [name, value] of Object.entries(environment)) {
42
50
  if (typeof value === "string" && value.trim() && isHostLoadChildEnvironmentName(name))
43
51
  forwarded[name] = value;
44
52
  }
45
- forwarded[hostLoadGovernorEnvironment] = "on";
53
+ forwarded[hostLoadGovernorEnvironment] = config.mode;
54
+ forwarded[hostLoadTestSlotsEnvironment] = String(config.testSlots);
46
55
  forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
47
56
  return forwarded;
48
57
  }
49
58
  /**
50
59
  * The governor a child process uses, from the variables above. Undefined when
51
- * the flag is off or no state root was handed over: the child is ungoverned.
60
+ * the governor is off or no state root was handed over: the child is ungoverned.
52
61
  */
53
62
  export function hostLoadGovernorFromChildEnvironment(environment = process.env) {
54
63
  const config = loadHostLoadGovernorConfig(environment);
55
64
  const stateRoot = environment[hostLoadStateRootEnvironment]?.trim();
56
- if (config.mode !== "on" || !stateRoot || !path.isAbsolute(stateRoot))
65
+ if (!hostLoadGovernorEnabled(config) || !stateRoot || !path.isAbsolute(stateRoot))
57
66
  return undefined;
58
67
  return new HostLoadGovernor({
59
68
  stateRoot,
@@ -1,7 +1,13 @@
1
1
  export type HostLoadGovernorMode = "on" | "off";
2
2
  export interface HostLoadGovernorConfig {
3
- /** FORGE_HOST_LOAD_GOVERNOR. Off by default in this step; `off` is the operator override. */
3
+ /** FORGE_HOST_LOAD_GOVERNOR: the CPU and memory budget. Off by default; `off` is the operator override. */
4
4
  readonly mode: HostLoadGovernorMode;
5
+ /**
6
+ * FORGE_HOST_LOAD_TEST_SLOTS (decision 0018): how many heavy steps (builds, test runs,
7
+ * Playwright, the runtime build) run at once on the host, whatever the budget says.
8
+ * 1 by default; 0 turns the slot off, and with the budget off too the governor is off.
9
+ */
10
+ readonly testSlots: number;
5
11
  /** Share of logical CPUs Forge may reserve for heavy steps. */
6
12
  readonly cpuBudgetFraction: number;
7
13
  /** Memory kept free for the rest of the host, taken off MemAvailable. */
@@ -38,6 +44,9 @@ export interface HostLoadGovernorConfig {
38
44
  readonly cpuBudgetCeilingFraction?: number | null;
39
45
  readonly maxHeavyStepsCeiling?: number | null;
40
46
  }
47
+ export declare const defaultHostTestSlots = 1;
41
48
  export declare const defaultHostLoadGovernorConfig: HostLoadGovernorConfig;
42
49
  export declare function parseHostLoadGovernorMode(value: string | undefined): HostLoadGovernorMode;
50
+ /** The governor admits steps when either rule is on: the host test slot or the budget. */
51
+ export declare function hostLoadGovernorEnabled(config: Pick<HostLoadGovernorConfig, "mode" | "testSlots">): boolean;
43
52
  export declare function loadHostLoadGovernorConfig(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernorConfig;
@@ -1,6 +1,8 @@
1
1
  import { defaultHostLoadSampleIntervalMs } from "./host-load-sampler.js";
2
+ export const defaultHostTestSlots = 1;
2
3
  export const defaultHostLoadGovernorConfig = {
3
4
  mode: "off",
5
+ testSlots: defaultHostTestSlots,
4
6
  cpuBudgetFraction: 0.8,
5
7
  memoryReserveBytes: 1024 ** 3,
6
8
  cpuPressureThreshold: 50,
@@ -19,10 +21,15 @@ export function parseHostLoadGovernorMode(value) {
19
21
  const normalized = value?.trim().toLowerCase() ?? "";
20
22
  return normalized === "on" || normalized === "true" || normalized === "1" ? "on" : "off";
21
23
  }
24
+ /** The governor admits steps when either rule is on: the host test slot or the budget. */
25
+ export function hostLoadGovernorEnabled(config) {
26
+ return config.mode === "on" || config.testSlots > 0;
27
+ }
22
28
  export function loadHostLoadGovernorConfig(environment = process.env) {
23
29
  const defaults = defaultHostLoadGovernorConfig;
24
30
  return {
25
31
  mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
32
+ testSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_TEST_SLOTS, defaults.testSlots, 0, 8)),
26
33
  cpuBudgetFraction: bounded(environment.FORGE_HOST_LOAD_CPU_BUDGET_FRACTION, defaults.cpuBudgetFraction, 0.05, 1),
27
34
  memoryReserveBytes: bounded(environment.FORGE_HOST_LOAD_MEMORY_RESERVE_BYTES, defaults.memoryReserveBytes, 0, 1024 ** 4),
28
35
  cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
@@ -79,6 +79,8 @@ export interface HostLoadGovernorOptions {
79
79
  * overtake an unfit head until the head has waited past the anti-starvation
80
80
  * window. Running steps are never preempted. Reserved cost comes from the
81
81
  * shared token ledger, so other processes' steps count against the same budget.
82
+ * The host test slot (decision 0018) comes first: a heavy step waits for it in
83
+ * the host-wide queue the ledger keeps, then for the budget when that is on.
82
84
  */
83
85
  export declare class HostLoadGovernor implements HostLoadStepGate {
84
86
  private readonly options;
@@ -123,6 +125,14 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
123
125
  };
124
126
  private drain;
125
127
  private drainOnce;
128
+ /**
129
+ * Decision 0014: the CPU budget (or yield budget) and the heavy-step limit the
130
+ * bridge has in force apply from the next admission; running steps keep theirs.
131
+ * The operator's env ceilings hold with or without the file, and over whatever it says.
132
+ */
133
+ private budgetPass;
134
+ /** The host test slot first (decision 0018), then the budget when it is on. */
135
+ private decide;
126
136
  private readSignals;
127
137
  /**
128
138
  * Consecutive pressured samples ending with the latest one, read from the