@loucompanion/forge-bridge 0.1.4-dev.81e48ecc185d → 0.1.4-dev.866b33be3065

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 (61) hide show
  1. package/README.md +3 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +1 -1
  3. package/dist/bridge/bridge-chat-provider-command.js +16 -4
  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/runner-host-capabilities.d.ts +3 -0
  7. package/dist/bridge/runner-host-capabilities.js +13 -0
  8. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  9. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  10. package/dist/runtime/docker-engine-probe.js +7 -0
  11. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  12. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  13. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  14. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  15. package/dist/runtime/host-facts.d.ts +2 -1
  16. package/dist/runtime/host-load-admission.d.ts +4 -1
  17. package/dist/runtime/host-load-sampler.d.ts +34 -4
  18. package/dist/runtime/host-load-sampler.js +73 -7
  19. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  20. package/dist/runtime/host-load-windows-cpu.js +85 -0
  21. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  22. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  23. package/dist/session/architect-waits.d.ts +2 -0
  24. package/dist/session/architect-waits.js +138 -0
  25. package/dist/session/managed-attempt-tools.d.ts +0 -7
  26. package/dist/session/managed-attempt-tools.js +44 -54
  27. package/dist/session/phase-completion.artifacts.js +2 -1
  28. package/dist/session/phase-completion.runtime.js +1 -1
  29. package/dist/session/phase-completion.schemas.js +3 -11
  30. package/dist/session/phase-completion.validation.js +3 -1
  31. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  32. package/dist/session/pre-publication-native-postgres.js +111 -0
  33. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  34. package/dist/session/pre-publication-step-execution.js +6 -5
  35. package/dist/session/pre-publication-validation.d.ts +7 -3
  36. package/dist/session/pre-publication-validation.js +32 -30
  37. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  38. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  39. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  40. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  41. package/dist/session/provider-cli/provider-cli.process.d.ts +8 -30
  42. package/dist/session/provider-cli/provider-cli.process.js +25 -376
  43. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  44. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  45. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  46. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  47. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  48. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  49. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  50. package/dist/session/qa-sidecar-validation.js +28 -0
  51. package/dist/session/session-redaction.js +31 -181
  52. package/dist/session/session.types.js +1 -1
  53. package/dist/session/sidecar-json-shape.d.ts +31 -0
  54. package/dist/session/sidecar-json-shape.js +217 -0
  55. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  56. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  57. package/dist/shared/process/windows-launch.d.ts +18 -0
  58. package/dist/shared/process/windows-launch.js +68 -0
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. 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;
@@ -18,16 +18,34 @@ export interface HostOwnCgroupLoad {
18
18
  /** All memory charged to the unit (`memory.current`), including page cache. */
19
19
  readonly memoryChargedBytes: number | null;
20
20
  }
21
+ /**
22
+ * Where `systemPressure` comes from: Linux PSI, or (decision 0021) an estimate
23
+ * of CPU `some` pressure from whole-host CPU use on Windows, which has no PSI.
24
+ */
25
+ export type HostLoadPressureSource = "psi" | "windows_estimate";
21
26
  /** Live host load. Reported in every heartbeat but never a material capability signal. */
22
27
  export interface HostLoadSnapshot {
23
28
  readonly sampledAt: string;
29
+ /**
30
+ * True when `systemPressure` carries a CPU pressure signal the governor gates on.
31
+ * The wire name predates decision 0021: on Windows the signal is an estimate
32
+ * (see `pressureSource`), and the static host fact `psiAvailable` stays false.
33
+ */
24
34
  readonly psiAvailable: boolean;
35
+ /** Null exactly when `psiAvailable` is false. */
36
+ readonly pressureSource: HostLoadPressureSource | null;
25
37
  readonly systemPressure: HostSystemPressure | null;
26
38
  /** True only when the bridge runs in a cgroup of its own (see isDedicatedBridgeUnit). */
27
39
  readonly ownCgroupDedicated: boolean;
28
40
  /** Reported only for a dedicated unit; never a shared terminal/session/app scope. */
29
41
  readonly ownCgroup: HostOwnCgroupLoad | null;
30
42
  readonly memoryAvailableBytes: number | null;
43
+ /**
44
+ * Busy share (0-100) of all logical CPUs over the last sampling window: /proc/stat deltas
45
+ * on Linux, os.cpus() deltas on Windows. Null on the first sample, after a break in
46
+ * readings, and on other platforms. For display only; the governor gates on pressure.
47
+ */
48
+ readonly hostCpuPercent: number | null;
31
49
  }
32
50
  /** What the bridge service needs: static facts plus the latest cached load sample. */
33
51
  export interface HostLoadSource {
@@ -48,7 +66,7 @@ export interface HostLoadSource {
48
66
  */
49
67
  export interface HostCpuAttribution {
50
68
  readonly sampledAt: string;
51
- /** Busy cores on the whole host, from /proc/stat deltas. */
69
+ /** Busy cores on the whole host, from /proc/stat deltas (os.cpus() deltas on Windows). */
52
70
  readonly hostCoresInUse: number;
53
71
  /** Cores used by the bridge's dedicated cgroup; null when the cgroup is not dedicated. */
54
72
  readonly ownCoresInUse: number | null;
@@ -80,8 +98,9 @@ export interface HostLoadSamplerOptions {
80
98
  export declare const defaultHostLoadSampleIntervalMs = 5000;
81
99
  /**
82
100
  * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
83
- * latest snapshot. Every read is async and failure-tolerant: a host without PSI
84
- * (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
101
+ * latest snapshot. Every read is async and failure-tolerant: a Linux host without
102
+ * PSI (old kernel, `psi=0`) or another non-Windows host reports `psiAvailable: false`
103
+ * and no pressure. Windows reports a CPU pressure estimate instead (decision 0021).
85
104
  */
86
105
  export declare class HostLoadSampler implements HostLoadSource {
87
106
  private readonly environment;
@@ -100,6 +119,8 @@ export declare class HostLoadSampler implements HostLoadSource {
100
119
  private hostCpuMark;
101
120
  private latestCpuAttribution;
102
121
  private latestMemoryHeadroom;
122
+ private windowsCpuMark;
123
+ private readonly windowsCpuPressure;
103
124
  private readonly forgeCgroups;
104
125
  private readonly sandboxCpu;
105
126
  constructor(options?: HostLoadSamplerOptions);
@@ -115,11 +136,20 @@ export declare class HostLoadSampler implements HostLoadSource {
115
136
  sample(): Promise<HostLoadSnapshot>;
116
137
  private startOnce;
117
138
  private readSnapshot;
139
+ /**
140
+ * Decision 0021: Windows has no PSI or cgroups. CPU pressure is estimated from
141
+ * whole-host CPU use between samples, and memory is available physical memory.
142
+ * The bridge's own share is not attributed, so external load stays unknown and
143
+ * Forge's work counts through reserved cost and the pressure gate (as on a Linux
144
+ * host whose bridge has no dedicated cgroup).
145
+ */
146
+ private readWindowsSnapshot;
118
147
  private readCgroupMemoryHeadroom;
119
148
  private readSystemPressure;
120
149
  private readOwnCgroup;
121
150
  private coresInUse;
122
- private readHostCoresInUse;
151
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
152
+ private readHostCpuUse;
123
153
  private readMemoryAvailable;
124
154
  private fallbackFreeMemory;
125
155
  private readPressure;
@@ -2,13 +2,15 @@ import path from "node:path";
2
2
  import { defaultHostEnvironment, detectHostFacts, readOptional, } from "./host-facts.js";
3
3
  import { cgroupLeafName, isDedicatedBridgeUnit, parseCgroupCpuUsageUsec, parseCgroupMemoryAnonBytes, parseMemAvailableBytes, parseNonNegativeInteger, parsePressureStall, parseProcStatCpuTotals, parseUnifiedCgroupMembership, parseUnifiedCgroupPath, } from "./host-pressure-stall.js";
4
4
  import { ForgeCgroupCpuMeter, readCgroupMemoryHeadroomBytes, } from "./host-load-forge-cgroups.js";
5
+ import { cpuTimeTotals, cpuUtilisation, WindowsCpuPressureEstimator, } from "./host-load-windows-cpu.js";
5
6
  export const defaultHostLoadSampleIntervalMs = 5_000;
6
7
  /** Samples kept for the governor's pressure streak (FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES is at most 60). */
7
8
  const retainedSampleCount = 64;
8
9
  /**
9
10
  * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
10
- * latest snapshot. Every read is async and failure-tolerant: a host without PSI
11
- * (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
11
+ * latest snapshot. Every read is async and failure-tolerant: a Linux host without
12
+ * PSI (old kernel, `psi=0`) or another non-Windows host reports `psiAvailable: false`
13
+ * and no pressure. Windows reports a CPU pressure estimate instead (decision 0021).
12
14
  */
13
15
  export class HostLoadSampler {
14
16
  environment;
@@ -27,6 +29,8 @@ export class HostLoadSampler {
27
29
  hostCpuMark = null;
28
30
  latestCpuAttribution = null;
29
31
  latestMemoryHeadroom = null;
32
+ windowsCpuMark = null;
33
+ windowsCpuPressure = new WindowsCpuPressureEstimator();
30
34
  forgeCgroups;
31
35
  sandboxCpu;
32
36
  constructor(options = {}) {
@@ -77,6 +81,9 @@ export class HostLoadSampler {
77
81
  sample() {
78
82
  this.inFlight ??= this.readSnapshot()
79
83
  .then(snapshot => {
84
+ // A Windows reading that did not advance the CPU window returns the last snapshot.
85
+ if (snapshot === this.latest)
86
+ return snapshot;
80
87
  this.latest = snapshot;
81
88
  this.history.push(snapshot);
82
89
  if (this.history.length > retainedSampleCount)
@@ -104,13 +111,15 @@ export class HostLoadSampler {
104
111
  async readSnapshot() {
105
112
  const sampledAtMs = this.now();
106
113
  const monotonicMs = this.monotonicNow();
114
+ if (this.environment.platform === "win32")
115
+ return this.readWindowsSnapshot(sampledAtMs, monotonicMs);
107
116
  const linux = this.environment.platform === "linux";
108
- const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes, sandboxCores] = linux
117
+ const [systemPressure, ownCgroup, memoryAvailableBytes, hostCpu, cgroupMemoryHeadroomBytes, sandboxCores] = linux
109
118
  ? await Promise.all([
110
119
  this.readSystemPressure(),
111
120
  this.readOwnCgroup(monotonicMs),
112
121
  this.readMemoryAvailable(),
113
- this.readHostCoresInUse(),
122
+ this.readHostCpuUse(),
114
123
  this.readCgroupMemoryHeadroom(),
115
124
  Promise.resolve(this.forgeCgroups?.paths() ?? [])
116
125
  .then(paths => this.sandboxCpu.coresInUse(paths, monotonicMs)).catch(() => 0),
@@ -120,16 +129,54 @@ export class HostLoadSampler {
120
129
  // Docker sandbox CPU is Forge's own work, already counted through reserved cost.
121
130
  const ownCores = ownCgroup?.cpuCoresInUse ?? null;
122
131
  this.latestMemoryHeadroom = cgroupMemoryHeadroomBytes;
123
- this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCores === null ? null : ownCores + sandboxCores);
132
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCpu === null ? null : roundCores(hostCpu.utilisation * hostCpu.cpuCount), ownCores === null ? null : ownCores + sandboxCores);
124
133
  return {
125
134
  sampledAt,
126
135
  psiAvailable: systemPressure !== null,
136
+ pressureSource: systemPressure !== null ? "psi" : null,
127
137
  systemPressure,
128
138
  ownCgroupDedicated: ownCgroup !== null,
129
139
  ownCgroup,
130
140
  memoryAvailableBytes,
141
+ hostCpuPercent: hostCpu === null ? null : hostCpuPercent(hostCpu.utilisation),
131
142
  };
132
143
  }
144
+ /**
145
+ * Decision 0021: Windows has no PSI or cgroups. CPU pressure is estimated from
146
+ * whole-host CPU use between samples, and memory is available physical memory.
147
+ * The bridge's own share is not attributed, so external load stays unknown and
148
+ * Forge's work counts through reserved cost and the pressure gate (as on a Linux
149
+ * host whose bridge has no dedicated cgroup).
150
+ */
151
+ readWindowsSnapshot(sampledAtMs, monotonicMs) {
152
+ let totals;
153
+ try {
154
+ totals = cpuTimeTotals(this.environment.cpus());
155
+ }
156
+ catch {
157
+ totals = null;
158
+ }
159
+ const previous = this.windowsCpuMark;
160
+ const sampledAt = new Date(sampledAtMs).toISOString();
161
+ if (this.latest && totals && previous && previous.totals.cpuCount === totals.cpuCount
162
+ && monotonicMs - previous.atMs < minimumWindowsCpuWindowMs) {
163
+ // Too soon after the last reading (start() right after a sample) for a stable delta:
164
+ // the window stays open and the last snapshot is returned as is. sample() does not
165
+ // record it again, so it never counts as another sample in the pressure streak.
166
+ return this.latest;
167
+ }
168
+ this.windowsCpuMark = totals ? { totals, atMs: monotonicMs } : null;
169
+ const elapsedMs = previous ? monotonicMs - previous.atMs : 0;
170
+ const utilisation = previous && elapsedMs > 0 ? cpuUtilisation(previous.totals, totals) : null;
171
+ // The first sample, or a break in readings (no times, a CPU count change, a counter
172
+ // reset), reports no pressure and restarts the averages from the next window.
173
+ if (utilisation === null)
174
+ this.windowsCpuPressure.reset();
175
+ const cpu = utilisation === null ? null : this.windowsCpuPressure.update(utilisation, elapsedMs);
176
+ this.latestMemoryHeadroom = null;
177
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, utilisation !== null && totals ? roundCores(utilisation * totals.cpuCount) : null, null);
178
+ return windowsSnapshot(sampledAt, cpu, this.fallbackFreeMemory(), utilisation === null ? null : hostCpuPercent(utilisation));
179
+ }
133
180
  async readCgroupMemoryHeadroom() {
134
181
  const membership = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "self", "cgroup"));
135
182
  const cgroupPath = membership ? parseUnifiedCgroupMembership(membership) : null;
@@ -185,7 +232,8 @@ export class HostLoadSampler {
185
232
  return null;
186
233
  return roundCores(usedUsec / elapsedUsec);
187
234
  }
188
- async readHostCoresInUse() {
235
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
236
+ async readHostCpuUse() {
189
237
  const content = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "stat"));
190
238
  const totals = content ? parseProcStatCpuTotals(content) : null;
191
239
  const previous = this.hostCpuMark;
@@ -196,7 +244,7 @@ export class HostLoadSampler {
196
244
  const busyDelta = totals.busyTicks - previous.busyTicks;
197
245
  if (totalDelta <= 0 || busyDelta < 0)
198
246
  return null;
199
- return roundCores((busyDelta / totalDelta) * totals.cpuCount);
247
+ return { utilisation: Math.min(1, busyDelta / totalDelta), cpuCount: totals.cpuCount };
200
248
  }
201
249
  async readMemoryAvailable() {
202
250
  const meminfo = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "meminfo"));
@@ -216,9 +264,27 @@ export class HostLoadSampler {
216
264
  return content ? parsePressureStall(content) : null;
217
265
  }
218
266
  }
267
+ /** Windows CPU deltas shorter than this are too noisy to fold into the pressure estimate. */
268
+ const minimumWindowsCpuWindowMs = 250;
269
+ function windowsSnapshot(sampledAt, cpu, memoryAvailableBytes, cpuPercent) {
270
+ return {
271
+ sampledAt,
272
+ psiAvailable: cpu !== null,
273
+ pressureSource: cpu !== null ? "windows_estimate" : null,
274
+ systemPressure: cpu ? { cpu, memory: null, io: null } : null,
275
+ ownCgroupDedicated: false,
276
+ ownCgroup: null,
277
+ memoryAvailableBytes,
278
+ hostCpuPercent: cpuPercent,
279
+ };
280
+ }
219
281
  function roundCores(value) {
220
282
  return Math.round(value * 100) / 100;
221
283
  }
284
+ /** A 0-1 busy share as a percentage with two decimals. */
285
+ function hostCpuPercent(utilisation) {
286
+ return Math.round(Math.min(1, Math.max(0, utilisation)) * 10_000) / 100;
287
+ }
222
288
  function hostCpuAttribution(sampledAt, hostCoresInUse, ownCoresInUse) {
223
289
  if (hostCoresInUse === null)
224
290
  return null;
@@ -0,0 +1,34 @@
1
+ import type os from "node:os";
2
+ import type { PressureStallResource } from "./host-pressure-stall.js";
3
+ /** Host CPU time summed over every logical CPU, in milliseconds, from os.cpus(). */
4
+ export interface CpuTimeTotals {
5
+ readonly busyMs: number;
6
+ readonly totalMs: number;
7
+ readonly cpuCount: number;
8
+ }
9
+ export type CpuTimesSource = readonly Partial<Pick<os.CpuInfo, "times">>[];
10
+ /**
11
+ * Host CPU use at which the estimate starts to report pressure. Waits for a CPU
12
+ * are rare below it on a many-core host. 0.6 puts the default backpressure
13
+ * threshold (50%) at 80% host CPU use, the default CPU budget.
14
+ */
15
+ export declare const windowsCpuPressureKnee = 0.6;
16
+ /** Busy is user + nice + sys + irq; idle is not busy. Null when any CPU lacks its times. */
17
+ export declare function cpuTimeTotals(cpus: CpuTimesSource): CpuTimeTotals | null;
18
+ /** Busy share of all logical CPUs (0-1) between two readings; null across a CPU count change or a counter reset. */
19
+ export declare function cpuUtilisation(previous: CpuTimeTotals | null, current: CpuTimeTotals | null): number | null;
20
+ /** Estimated share of wall time (percent) some runnable thread waited for a CPU, for one window. */
21
+ export declare function estimatedCpuStallPercent(utilisation: number): number;
22
+ /**
23
+ * Keeps 10/60/300-second exponentially decaying averages of the estimate, the
24
+ * way the kernel keeps PSI averages, so the governor's threshold and pressure
25
+ * streak read it exactly like PSI. The first window seeds every average, so a
26
+ * host already busy when the bridge starts reports pressure at once.
27
+ */
28
+ export declare class WindowsCpuPressureEstimator {
29
+ private averages;
30
+ /** Folds in one window of host CPU use lasting `elapsedMs`. */
31
+ update(utilisation: number, elapsedMs: number): PressureStallResource;
32
+ current(): PressureStallResource | null;
33
+ reset(): void;
34
+ }