@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0fedbc5c9ef7

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 (182) hide show
  1. package/README.md +89 -1
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +19 -12
  17. package/dist/bridge/bridge.service.js +155 -282
  18. package/dist/bridge/bridge.types.d.ts +5 -0
  19. package/dist/bridge/in-flight-registry.d.ts +62 -0
  20. package/dist/bridge/in-flight-registry.js +207 -0
  21. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  22. package/dist/bridge/readiness-result-outbox.js +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +14 -1
  24. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  25. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  26. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  27. package/dist/bridge/windows-bash-resolution.js +153 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +56 -12
  36. package/dist/cli/cli.service.d.ts +3 -10
  37. package/dist/cli/cli.service.js +10 -171
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +2 -0
  41. package/dist/cli/local-config.js +7 -1
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  48. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  49. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  50. package/dist/runtime/attempt-process-supervisor.js +12 -6
  51. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  52. package/dist/runtime/docker-engine-probe.js +7 -0
  53. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  54. package/dist/runtime/dotnet-build-outputs.js +402 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  56. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  57. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  58. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  59. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  60. package/dist/runtime/host-listener-inspector.js +84 -3
  61. package/dist/runtime/host-load-admission.d.ts +5 -0
  62. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  63. package/dist/runtime/host-load-governor-config.js +4 -1
  64. package/dist/runtime/host-load-governor.d.ts +10 -1
  65. package/dist/runtime/host-load-governor.js +33 -3
  66. package/dist/runtime/host-load-ledger-lock.js +6 -4
  67. package/dist/runtime/host-load-runtime-settings.js +4 -2
  68. package/dist/runtime/host-load-sampler.d.ts +8 -1
  69. package/dist/runtime/host-load-sampler.js +14 -7
  70. package/dist/runtime/host-load-test-slot.js +7 -0
  71. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  72. package/dist/runtime/host-runtime-contract.js +29 -1
  73. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  74. package/dist/runtime/host-runtime-lease.js +140 -296
  75. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  76. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  77. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  78. package/dist/runtime/host-runtime-promotion.js +307 -14
  79. package/dist/runtime/managed-command-teardown.js +5 -16
  80. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  81. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  82. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  83. package/dist/runtime/prepared-runtime-identity.js +130 -9
  84. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  85. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  86. package/dist/runtime/runner-settings.d.ts +4 -0
  87. package/dist/runtime/runner-settings.js +22 -0
  88. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  89. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  90. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  91. package/dist/sandbox/host-capacity-broker.js +4 -2
  92. package/dist/sandbox/managed-branch.d.ts +13 -0
  93. package/dist/sandbox/managed-branch.js +90 -0
  94. package/dist/sandbox/provider-auth/codex.js +11 -11
  95. package/dist/sandbox/runtime.js +3 -7
  96. package/dist/session/managed-attempt-tools.d.ts +0 -7
  97. package/dist/session/managed-attempt-tools.js +50 -82
  98. package/dist/session/managed-build-coordinator.d.ts +16 -0
  99. package/dist/session/managed-build-coordinator.js +10 -0
  100. package/dist/session/managed-build-receipt.d.ts +5 -0
  101. package/dist/session/managed-build-receipt.js +8 -3
  102. package/dist/session/phase-completion.artifacts.js +2 -1
  103. package/dist/session/phase-completion.d.ts +8 -0
  104. package/dist/session/phase-completion.js +1 -0
  105. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  106. package/dist/session/phase-completion.mcp-args.js +156 -0
  107. package/dist/session/phase-completion.runtime.d.ts +0 -8
  108. package/dist/session/phase-completion.runtime.js +43 -197
  109. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  110. package/dist/session/pre-publication-native-postgres.js +111 -0
  111. package/dist/session/pre-publication-process.js +10 -10
  112. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  113. package/dist/session/pre-publication-step-execution.js +6 -5
  114. package/dist/session/pre-publication-validation.d.ts +7 -3
  115. package/dist/session/pre-publication-validation.js +32 -30
  116. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  117. package/dist/session/provider-cli/claude-background-work.js +4 -3
  118. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  119. package/dist/session/provider-cli/host-build-lock.js +30 -0
  120. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  121. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  122. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  123. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  124. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  125. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  126. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  127. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  128. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  129. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  130. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  131. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  132. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  133. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  134. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  135. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  136. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  137. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  138. package/dist/session/qa-sidecar-validation.js +28 -0
  139. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  140. package/dist/session/sandbox-host-capacity-gate.js +35 -16
  141. package/dist/session/session-redaction.js +31 -181
  142. package/dist/session/session.service.d.ts +6 -0
  143. package/dist/session/session.service.js +131 -88
  144. package/dist/session/session.types.d.ts +1 -0
  145. package/dist/session/session.types.js +3 -3
  146. package/dist/session/sidecar-json-shape.d.ts +31 -0
  147. package/dist/session/sidecar-json-shape.js +217 -0
  148. package/dist/shared/fs/file-identity.d.ts +10 -0
  149. package/dist/shared/fs/file-identity.js +15 -0
  150. package/dist/shared/fs/replace-file.d.ts +7 -0
  151. package/dist/shared/fs/replace-file.js +33 -0
  152. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  153. package/dist/shared/process/host-process-recovery.js +23 -3
  154. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  155. package/dist/shared/process/host-process-supervisor.js +66 -14
  156. package/dist/shared/provider-capabilities.js +9 -1
  157. package/dist/version.d.ts +1 -1
  158. package/dist/version.js +1 -1
  159. package/dist/worktree/orphan-relink.d.ts +19 -0
  160. package/dist/worktree/orphan-relink.js +106 -0
  161. package/dist/worktree/wip-git.d.ts +42 -0
  162. package/dist/worktree/wip-git.js +139 -0
  163. package/dist/worktree/wip-refs.d.ts +77 -0
  164. package/dist/worktree/wip-refs.js +146 -0
  165. package/dist/worktree/wip-restore.d.ts +46 -0
  166. package/dist/worktree/wip-restore.js +280 -0
  167. package/dist/worktree/wip-snapshot.d.ts +53 -0
  168. package/dist/worktree/wip-snapshot.js +270 -0
  169. package/dist/worktree/worktree-inputs.d.ts +8 -0
  170. package/dist/worktree/worktree-inputs.js +134 -0
  171. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  172. package/dist/worktree/worktree-origin-sync.js +128 -0
  173. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  174. package/dist/worktree/worktree-wip-events.js +115 -0
  175. package/dist/worktree/worktree-wip.d.ts +51 -0
  176. package/dist/worktree/worktree-wip.js +190 -0
  177. package/dist/worktree/worktree.base.d.ts +7 -1
  178. package/dist/worktree/worktree.service.d.ts +27 -5
  179. package/dist/worktree/worktree.service.js +112 -181
  180. package/dist/worktree/worktree.types.d.ts +35 -0
  181. package/package.json +1 -1
  182. package/runtime/windows-listener-owner.ps1 +12 -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
+ }
@@ -17,18 +17,29 @@ export declare class HostListenerInspector {
17
17
  private readonly commands;
18
18
  private readonly platform;
19
19
  private readonly retryDelayMs;
20
+ /** How often a live shared-admission run's listeners are re-audited after readiness. */
21
+ ownedListenerAuditIntervalMs: number;
20
22
  constructor(commands?: HostInspectionCommandRunner, platform?: NodeJS.Platform, retryDelayMs?: number);
21
23
  inspect(child: AttemptProcessChildHandle, reservation: HostPortReservation, owner: HostPortLeaseOwner): Promise<HostListenerOwnership>;
22
24
  /** Returns loopback TCP ports opened by one exact supervised child process tree. */
23
25
  inspectOwnedLoopbackListeners(child: AttemptProcessChildHandle, owner: HostPortLeaseOwner): Promise<readonly number[]>;
26
+ /**
27
+ * Returns the TCP ports that one exact supervised child process tree listens on, on any local
28
+ * address: IPv4 or IPv6 loopback, a wildcard (which covers loopback), or a specific interface.
29
+ * The parallel-isolation audit needs all of them, because a sibling could only collide with
30
+ * one it was never brokered.
31
+ */
32
+ inspectOwnedTcpListeners(child: AttemptProcessChildHandle, owner: HostPortLeaseOwner): Promise<readonly number[]>;
24
33
  /** Snapshots loopback TCP ports that predate a supervised child launch. */
25
34
  inspectLoopbackListeners(): Promise<readonly number[]>;
26
35
  private inspectWindows;
27
36
  private inspectAllWindows;
37
+ private ownedWindowsPorts;
28
38
  private runWindowsAncestry;
29
39
  private runWindowsNetstat;
30
40
  private inspectUnix;
31
41
  private inspectAllUnix;
42
+ private ownedUnixPorts;
32
43
  }
33
44
  export declare function parseWindowsLoopbackListeners(output: string): readonly {
34
45
  pid: number;
@@ -42,6 +53,21 @@ export declare function parseSsLoopbackListeners(output: string): readonly {
42
53
  pid: number;
43
54
  port: number;
44
55
  }[];
56
+ /** TCP listeners on any local address (IPv4, IPv6 or wildcard) from `netstat -ano`. */
57
+ export declare function parseWindowsTcpListeners(output: string): readonly {
58
+ pid: number;
59
+ port: number;
60
+ }[];
61
+ /** TCP listeners on any local address from `lsof -iTCP -sTCP:LISTEN -Fpn`. */
62
+ export declare function parseLsofTcpListeners(output: string): readonly {
63
+ pid: number;
64
+ port: number;
65
+ }[];
66
+ /** TCP listeners on any local address from `ss -H -ltnp` (local address is the fourth column). */
67
+ export declare function parseSsTcpListeners(output: string): readonly {
68
+ pid: number;
69
+ port: number;
70
+ }[];
45
71
  export declare class ExecFileInspectionCommandRunner implements HostInspectionCommandRunner {
46
72
  run(command: string, args: readonly string[]): Promise<HostInspectionCommandResult>;
47
73
  }
@@ -4,6 +4,8 @@ import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  const windowsListenerOwnerPath = fileURLToPath(new URL("../../runtime/windows-listener-owner.ps1", import.meta.url));
6
6
  const windowsNetstatArgs = ["-ano", "-p", "TCP"];
7
+ // Without "-p", netstat lists TCP over IPv6 as well; "-p TCP" is IPv4 only.
8
+ const windowsAllNetstatArgs = ["-ano"];
7
9
  const windowsNetstatAttempts = 3;
8
10
  const windowsAncestryAttempts = 2;
9
11
  const windowsNetstatRetryDelayMs = 250;
@@ -13,6 +15,8 @@ export class HostListenerInspector {
13
15
  commands;
14
16
  platform;
15
17
  retryDelayMs;
18
+ /** How often a live shared-admission run's listeners are re-audited after readiness. */
19
+ ownedListenerAuditIntervalMs = 10_000;
16
20
  constructor(commands = new ExecFileInspectionCommandRunner(), platform = process.platform, retryDelayMs = windowsNetstatRetryDelayMs) {
17
21
  this.commands = commands;
18
22
  this.platform = platform;
@@ -42,6 +46,32 @@ export class HostListenerInspector {
42
46
  ? await this.inspectAllWindows(metadata.rootPid)
43
47
  : await this.inspectAllUnix(metadata.rootPid);
44
48
  }
49
+ /**
50
+ * Returns the TCP ports that one exact supervised child process tree listens on, on any local
51
+ * address: IPv4 or IPv6 loopback, a wildcard (which covers loopback), or a specific interface.
52
+ * The parallel-isolation audit needs all of them, because a sibling could only collide with
53
+ * one it was never brokered.
54
+ */
55
+ async inspectOwnedTcpListeners(child, owner) {
56
+ const metadata = await loadMetadata(child.metadataPath);
57
+ if (!metadata || !matchesOwner(metadata, child, owner)) {
58
+ throw new Error("host_listener_inspection_invalid: supervised provider ownership metadata is unavailable.");
59
+ }
60
+ if (this.platform === "win32") {
61
+ const netstat = await this.runWindowsNetstat(windowsAllNetstatArgs);
62
+ return await this.ownedWindowsPorts(metadata.rootPid, parseWindowsTcpListeners(netstat.stdout));
63
+ }
64
+ const lsof = await this.commands.run("lsof", ["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-Fpn"]);
65
+ if (lsof.exitCode === 0 || lsof.exitCode === 1) {
66
+ return await this.ownedUnixPorts(metadata.rootPid, parseLsofTcpListeners(lsof.stdout));
67
+ }
68
+ if (lsof.errorCode !== "ENOENT")
69
+ throw commandError("lsof", lsof);
70
+ const ss = await this.commands.run("ss", ["-H", "-ltnp"]);
71
+ if (ss.exitCode !== 0)
72
+ throw commandError("ss", ss);
73
+ return await this.ownedUnixPorts(metadata.rootPid, parseSsTcpListeners(ss.stdout));
74
+ }
45
75
  /** Snapshots loopback TCP ports that predate a supervised child launch. */
46
76
  async inspectLoopbackListeners() {
47
77
  if (this.platform === "win32") {
@@ -75,7 +105,9 @@ export class HostListenerInspector {
75
105
  }
76
106
  async inspectAllWindows(rootPid) {
77
107
  const netstat = await this.runWindowsNetstat();
78
- const listeners = parseWindowsLoopbackListeners(netstat.stdout);
108
+ return await this.ownedWindowsPorts(rootPid, parseWindowsLoopbackListeners(netstat.stdout));
109
+ }
110
+ async ownedWindowsPorts(rootPid, listeners) {
79
111
  if (listeners.length === 0)
80
112
  return [];
81
113
  const pids = [...new Set(listeners.map(listener => listener.pid))];
@@ -130,10 +162,10 @@ export class HostListenerInspector {
130
162
  cause: lastParseError,
131
163
  });
132
164
  }
133
- async runWindowsNetstat() {
165
+ async runWindowsNetstat(args = windowsNetstatArgs) {
134
166
  let lastResult = null;
135
167
  for (let attempt = 1; attempt <= windowsNetstatAttempts; attempt += 1) {
136
- const result = await this.commands.run("netstat.exe", windowsNetstatArgs);
168
+ const result = await this.commands.run("netstat.exe", args);
137
169
  if (result.exitCode === 0)
138
170
  return result;
139
171
  lastResult = result;
@@ -198,6 +230,9 @@ export class HostListenerInspector {
198
230
  else {
199
231
  throw commandError("lsof", lsof);
200
232
  }
233
+ return await this.ownedUnixPorts(rootPid, listeners);
234
+ }
235
+ async ownedUnixPorts(rootPid, listeners) {
201
236
  if (listeners.length === 0)
202
237
  return [];
203
238
  const pids = [...new Set(listeners.map(listener => listener.pid))];
@@ -246,6 +281,44 @@ export function parseSsLoopbackListeners(output) {
246
281
  });
247
282
  }));
248
283
  }
284
+ /** TCP listeners on any local address (IPv4, IPv6 or wildcard) from `netstat -ano`. */
285
+ export function parseWindowsTcpListeners(output) {
286
+ return uniqueListeners(output.split(/\r?\n/u).flatMap(line => {
287
+ const fields = line.trim().split(/\s+/u);
288
+ if (fields.length < 5 || fields[0]?.toUpperCase() !== "TCP" || fields[3]?.toUpperCase() !== "LISTENING")
289
+ return [];
290
+ const port = parseAnyEndpointPort(fields[1]);
291
+ const pids = validPid(fields[4]);
292
+ return port !== null && pids.length === 1 ? [{ pid: pids[0], port }] : [];
293
+ }));
294
+ }
295
+ /** TCP listeners on any local address from `lsof -iTCP -sTCP:LISTEN -Fpn`. */
296
+ export function parseLsofTcpListeners(output) {
297
+ const listeners = [];
298
+ let pid = null;
299
+ for (const line of output.split(/\r?\n/u)) {
300
+ if (line.startsWith("p"))
301
+ pid = validPid(line.slice(1))[0] ?? null;
302
+ if (!line.startsWith("n") || pid === null)
303
+ continue;
304
+ const port = parseAnyEndpointPort(line.slice(1));
305
+ if (port !== null)
306
+ listeners.push({ pid, port });
307
+ }
308
+ return uniqueListeners(listeners);
309
+ }
310
+ /** TCP listeners on any local address from `ss -H -ltnp` (local address is the fourth column). */
311
+ export function parseSsTcpListeners(output) {
312
+ return uniqueListeners(output.split(/\r?\n/u).flatMap(line => {
313
+ const port = parseAnyEndpointPort(line.trim().split(/\s+/u)[3]);
314
+ if (port === null)
315
+ return [];
316
+ return [...line.matchAll(/pid=(\d+)/gu)].flatMap(match => {
317
+ const pid = validPid(match[1])[0];
318
+ return pid ? [{ pid, port }] : [];
319
+ });
320
+ }));
321
+ }
249
322
  export class ExecFileInspectionCommandRunner {
250
323
  run(command, args) {
251
324
  return new Promise(resolve => {
@@ -340,6 +413,14 @@ function parseIpv4LoopbackEndpoint(value) {
340
413
  const port = Number.parseInt(match[1], 10);
341
414
  return Number.isSafeInteger(port) && port >= 1 && port <= 65535 ? port : null;
342
415
  }
416
+ // "127.0.0.1:80", "[::1]:80", "0.0.0.0:80", "[::]:80", "*:80", "127.0.0.53%lo:53".
417
+ function parseAnyEndpointPort(value) {
418
+ const match = value?.match(/^(?:\[[^\]\s]+\]|[^\s:[\]]+)(?:%[^\s:]+)?:(\d+)$/u);
419
+ if (!match)
420
+ return null;
421
+ const port = Number.parseInt(match[1], 10);
422
+ return Number.isSafeInteger(port) && port >= 1 && port <= 65535 ? port : null;
423
+ }
343
424
  function uniqueListeners(values) {
344
425
  const seen = new Set();
345
426
  return values.filter(value => {
@@ -55,6 +55,11 @@ export interface HostLoadAdmissionDecision {
55
55
  readonly reservedCpuCores: number;
56
56
  readonly reservedMemoryBytes: number;
57
57
  readonly detail: string;
58
+ /**
59
+ * Set on a host test slot wait whose holders are all healthy (owner alive, lease renewed, not retained):
60
+ * the queue is moving, so the wait does not count toward the stalled-wait limit.
61
+ */
62
+ readonly progressing?: boolean;
58
63
  }
59
64
  /**
60
65
  * Decision 0013 admission rule. A step is admitted when the reserved cost of
@@ -18,8 +18,17 @@ export interface HostLoadGovernorConfig {
18
18
  readonly backpressureSamples: number;
19
19
  /** Host memory PSI `full avg10` (percent) above which admission is a hard stop. */
20
20
  readonly memoryFullThreshold: number;
21
- /** Maximum queue wait before a retryable host_capacity_timeout. */
21
+ /**
22
+ * FORGE_HOST_LOAD_MAX_WAIT_MS: the longest a step waits while its queue is stalled before a retryable
23
+ * host_capacity_timeout. Time spent behind holders of the host test slot that are all healthy (owner
24
+ * alive, lease renewed, not retained) does not count: their steps are making progress.
25
+ */
22
26
  readonly maxWaitMs: number;
27
+ /**
28
+ * FORGE_HOST_LOAD_MAX_TOTAL_WAIT_MS: the longest a step may queue in all, healthy holders or not; the
29
+ * backstop for a holder that is alive but never finishes. Never below maxWaitMs.
30
+ */
31
+ readonly maxTotalWaitMs: number;
23
32
  /** Steps allowed at once when PSI is unavailable (the per-host semaphore fallback). */
24
33
  readonly fallbackSlots: number;
25
34
  /** After this long at the head of the queue, later waiters may no longer overtake it. */
@@ -9,6 +9,7 @@ export const defaultHostLoadGovernorConfig = {
9
9
  backpressureSamples: 2,
10
10
  memoryFullThreshold: 5,
11
11
  maxWaitMs: 30 * 60_000,
12
+ maxTotalWaitMs: 4 * 60 * 60_000,
12
13
  fallbackSlots: 1,
13
14
  antiStarvationMs: 2 * 60_000,
14
15
  leaseMs: 2 * 60_000,
@@ -27,6 +28,7 @@ export function hostLoadGovernorEnabled(config) {
27
28
  }
28
29
  export function loadHostLoadGovernorConfig(environment = process.env) {
29
30
  const defaults = defaultHostLoadGovernorConfig;
31
+ const maxWaitMs = bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000);
30
32
  return {
31
33
  mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
32
34
  testSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_TEST_SLOTS, defaults.testSlots, 0, 8)),
@@ -35,7 +37,8 @@ export function loadHostLoadGovernorConfig(environment = process.env) {
35
37
  cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
36
38
  backpressureSamples: Math.round(bounded(environment.FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES, defaults.backpressureSamples, 1, 60)),
37
39
  memoryFullThreshold: bounded(environment.FORGE_HOST_LOAD_MEMORY_FULL_THRESHOLD, defaults.memoryFullThreshold, 0, 100),
38
- maxWaitMs: bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000),
40
+ maxWaitMs,
41
+ maxTotalWaitMs: Math.max(maxWaitMs, bounded(environment.FORGE_HOST_LOAD_MAX_TOTAL_WAIT_MS, defaults.maxTotalWaitMs, 1_000, 24 * 60 * 60_000)),
39
42
  fallbackSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_FALLBACK_SLOTS, defaults.fallbackSlots, 1, 64)),
40
43
  antiStarvationMs: defaults.antiStarvationMs,
41
44
  leaseMs: defaults.leaseMs,
@@ -4,6 +4,8 @@ import { type HostLoadGovernorConfig } from "./host-load-governor-config.js";
4
4
  import type { HostLoadGovernorSource } from "./host-load-sampler.js";
5
5
  import type { HostLoadStepCost } from "./host-load-step-class.js";
6
6
  import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
7
+ /** What HostLoadStepGate.attachProcess takes, so a gate's callers need only this module. */
8
+ export type { HostLoadStepProcess } from "./host-load-step-reaper.js";
7
9
  import { type HostLoadOwnerLiveness, type HostLoadToken, type HostLoadTokenOwner, type HostLoadTokenPriority } from "./host-load-token-ledger.js";
8
10
  export interface HostLoadStepRequest {
9
11
  readonly stepClass: string;
@@ -49,7 +51,7 @@ export interface HostLoadAdmission {
49
51
  /** The gate heavy steps call before launching. */
50
52
  export interface HostLoadStepGate {
51
53
  readonly enabled: boolean;
52
- /** The longest a step may queue before host_capacity_timeout, when the gate knows it. */
54
+ /** The longest a step may queue in all before host_capacity_timeout, when the gate knows it. */
53
55
  readonly maxWaitMs?: number;
54
56
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
55
57
  }
@@ -148,6 +150,13 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
148
150
  */
149
151
  private runningStepsMemoryBytes;
150
152
  private logicalCpus;
153
+ /**
154
+ * Waiting behind healthy holders of the host test slot is progress: their steps run, and the slot passes
155
+ * down the queue as they finish. Any other wait (a holder past its lease or whose owner is gone, the
156
+ * budget, a recovering ledger) counts toward maxWaitMs from the last time the queue made progress.
157
+ */
158
+ private checkStalled;
159
+ private timeOut;
151
160
  private settle;
152
161
  /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
153
162
  private applyHeldOutcome;