@loucompanion/forge-bridge 0.1.4-dev.ccffca94938b → 0.1.4-dev.deb7f72e7930

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 (141) hide show
  1. package/README.md +87 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +4 -1
  3. package/dist/bridge/bridge-chat-provider-command.js +14 -19
  4. package/dist/bridge/bridge-state-file.d.ts +161 -0
  5. package/dist/bridge/bridge-state-file.js +376 -0
  6. package/dist/bridge/bridge-state-io.d.ts +11 -0
  7. package/dist/bridge/bridge-state-io.js +50 -0
  8. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  9. package/dist/bridge/bridge-state-lock.js +102 -0
  10. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  11. package/dist/bridge/bridge-state-unpublished.js +111 -0
  12. package/dist/bridge/bridge.service.d.ts +16 -12
  13. package/dist/bridge/bridge.service.js +131 -243
  14. package/dist/bridge/bridge.types.d.ts +5 -0
  15. package/dist/bridge/in-flight-registry.d.ts +62 -0
  16. package/dist/bridge/in-flight-registry.js +207 -0
  17. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  18. package/dist/bridge/readiness-result-outbox.js +20 -0
  19. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  20. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  21. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  22. package/dist/cleanup/cleanup-wip.js +66 -0
  23. package/dist/cleanup/cleanup.service.d.ts +11 -1
  24. package/dist/cleanup/cleanup.service.js +80 -62
  25. package/dist/cleanup/cleanup.types.d.ts +2 -0
  26. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  27. package/dist/cleanup/host-runtime-ledger.js +30 -9
  28. package/dist/cli/cli.help.js +56 -12
  29. package/dist/cli/cli.service.d.ts +3 -10
  30. package/dist/cli/cli.service.js +10 -171
  31. package/dist/cli/idle-status.d.ts +84 -0
  32. package/dist/cli/idle-status.js +181 -0
  33. package/dist/cli/local-config.d.ts +2 -0
  34. package/dist/cli/local-config.js +7 -1
  35. package/dist/cli/provider-cli-detection.d.ts +10 -0
  36. package/dist/cli/provider-cli-detection.js +160 -0
  37. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  38. package/dist/runtime/aspnet-runtime-prebuild.js +46 -1
  39. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  40. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  41. package/dist/runtime/docker-engine-probe.js +7 -0
  42. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  43. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  44. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  45. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  46. package/dist/runtime/host-load-governor.d.ts +2 -0
  47. package/dist/runtime/host-load-ledger-lock.js +6 -4
  48. package/dist/runtime/host-load-runtime-settings.js +4 -2
  49. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  50. package/dist/runtime/host-runtime-contract.js +29 -1
  51. package/dist/runtime/host-runtime-lease.js +10 -50
  52. package/dist/runtime/managed-command-teardown.js +5 -16
  53. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  54. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  55. package/dist/runtime/runner-settings.d.ts +4 -0
  56. package/dist/runtime/runner-settings.js +22 -0
  57. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  58. package/dist/sandbox/host-capacity-broker.js +4 -2
  59. package/dist/sandbox/managed-branch.d.ts +13 -0
  60. package/dist/sandbox/managed-branch.js +36 -0
  61. package/dist/sandbox/provider-auth/codex.js +11 -11
  62. package/dist/sandbox/runtime.js +2 -6
  63. package/dist/session/managed-attempt-tools.d.ts +0 -7
  64. package/dist/session/managed-attempt-tools.js +45 -77
  65. package/dist/session/managed-build-receipt.d.ts +5 -0
  66. package/dist/session/managed-build-receipt.js +8 -3
  67. package/dist/session/phase-completion.artifacts.js +2 -1
  68. package/dist/session/phase-completion.d.ts +8 -0
  69. package/dist/session/phase-completion.js +1 -0
  70. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  71. package/dist/session/phase-completion.mcp-args.js +156 -0
  72. package/dist/session/phase-completion.runtime.d.ts +0 -8
  73. package/dist/session/phase-completion.runtime.js +43 -197
  74. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  75. package/dist/session/pre-publication-native-postgres.js +111 -0
  76. package/dist/session/pre-publication-process.js +10 -10
  77. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  78. package/dist/session/pre-publication-step-execution.js +6 -5
  79. package/dist/session/pre-publication-validation.d.ts +7 -3
  80. package/dist/session/pre-publication-validation.js +32 -30
  81. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  82. package/dist/session/provider-cli/claude-background-work.js +4 -3
  83. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  84. package/dist/session/provider-cli/host-build-lock.js +30 -0
  85. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  86. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  87. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  88. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  89. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  90. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  91. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  92. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  93. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  94. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  95. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  96. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  97. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  98. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  99. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  100. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  101. package/dist/session/qa-sidecar-validation.js +28 -0
  102. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  103. package/dist/session/sandbox-host-capacity-gate.js +34 -15
  104. package/dist/session/session-redaction.js +31 -181
  105. package/dist/session/session.service.d.ts +2 -0
  106. package/dist/session/session.service.js +62 -56
  107. package/dist/session/session.types.js +1 -1
  108. package/dist/session/sidecar-json-shape.d.ts +31 -0
  109. package/dist/session/sidecar-json-shape.js +217 -0
  110. package/dist/shared/fs/file-identity.d.ts +10 -0
  111. package/dist/shared/fs/file-identity.js +15 -0
  112. package/dist/shared/fs/replace-file.d.ts +7 -0
  113. package/dist/shared/fs/replace-file.js +33 -0
  114. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  115. package/dist/shared/process/host-process-recovery.js +23 -3
  116. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  117. package/dist/shared/process/host-process-supervisor.js +66 -14
  118. package/dist/shared/provider-capabilities.js +9 -1
  119. package/dist/version.d.ts +1 -1
  120. package/dist/version.js +1 -1
  121. package/dist/worktree/wip-git.d.ts +33 -0
  122. package/dist/worktree/wip-git.js +122 -0
  123. package/dist/worktree/wip-refs.d.ts +62 -0
  124. package/dist/worktree/wip-refs.js +119 -0
  125. package/dist/worktree/wip-restore.d.ts +38 -0
  126. package/dist/worktree/wip-restore.js +190 -0
  127. package/dist/worktree/wip-snapshot.d.ts +50 -0
  128. package/dist/worktree/wip-snapshot.js +268 -0
  129. package/dist/worktree/worktree-inputs.d.ts +8 -0
  130. package/dist/worktree/worktree-inputs.js +134 -0
  131. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  132. package/dist/worktree/worktree-origin-sync.js +127 -0
  133. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  134. package/dist/worktree/worktree-wip-events.js +98 -0
  135. package/dist/worktree/worktree-wip.d.ts +49 -0
  136. package/dist/worktree/worktree-wip.js +182 -0
  137. package/dist/worktree/worktree.base.d.ts +7 -1
  138. package/dist/worktree/worktree.service.d.ts +27 -5
  139. package/dist/worktree/worktree.service.js +106 -181
  140. package/dist/worktree/worktree.types.d.ts +31 -0
  141. 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
+ }
@@ -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;
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import { ForgeFailureError } from "../session/session.types.js";
4
+ import { fileIdentityKey } from "../shared/fs/file-identity.js";
4
5
  export class HostCapacityLedgerUnavailableError extends ForgeFailureError {
5
6
  code = "host_capacity_ledger_unavailable";
6
7
  constructor(detail, options) {
@@ -120,10 +121,11 @@ export class HostLoadLedgerLock {
120
121
  * there is none, or null if it is live or too young to judge.
121
122
  */
122
123
  async judgeStale(lockPath) {
123
- const stat = await fs.lstat(lockPath).catch(() => null);
124
+ // Exact (bigint) stats: a rounded Windows file id could name a different lock file.
125
+ const stat = await fs.lstat(lockPath, { bigint: true }).catch(() => null);
124
126
  if (!stat)
125
127
  return "absent";
126
- const observed = stat.isFile() && stat.size <= 16 * 1024 ? await readLock(lockPath) : null;
128
+ const observed = stat.isFile() && stat.size <= 16n * 1024n ? await readLock(lockPath) : null;
127
129
  if (observed?.holder && validHolder(observed.holder) && typeof observed.token === "string") {
128
130
  // A live holder keeps its lock however old it is.
129
131
  if (this.options.isLive(observed.holder))
@@ -131,9 +133,9 @@ export class HostLoadLedgerLock {
131
133
  return { identity: `t-${observed.token}` };
132
134
  }
133
135
  // Unreadable (claims are atomic, so this is corruption): give it until the stale age.
134
- if (Date.now() - stat.mtimeMs < (this.options.unreadableStaleAfterMs ?? 30_000))
136
+ if (Date.now() - Number(stat.mtimeMs) < (this.options.unreadableStaleAfterMs ?? 30_000))
135
137
  return null;
136
- return { identity: `i-${stat.dev}-${stat.ino}-${Math.trunc(stat.mtimeMs)}-${stat.size}` };
138
+ return { identity: `i-${fileIdentityKey(stat).replace(":", "-")}-${stat.mtimeNs}-${stat.size}` };
137
139
  }
138
140
  /**
139
141
  * Claims the next free link of the stale lock's break chain, held only for the
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
+ import { fileIdentityKey } from "../shared/fs/file-identity.js";
4
5
  export function hostLoadRuntimeSettingsPath(stateRoot) {
5
6
  return path.join(stateRoot, "host-load-governor", "runner-settings.v1.json");
6
7
  }
@@ -45,8 +46,9 @@ export class HostLoadRuntimeSettingsReader {
45
46
  async read() {
46
47
  let key;
47
48
  try {
48
- const stat = await fs.stat(this.filePath);
49
- key = `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`;
49
+ // Exact (bigint) stats: a replaced file whose rounded Windows id matched would read as unchanged.
50
+ const stat = await fs.stat(this.filePath, { bigint: true });
51
+ key = `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}:${fileIdentityKey(stat)}`;
50
52
  }
51
53
  catch {
52
54
  this.cachedKey = null;
@@ -57,6 +57,18 @@ export interface HostRuntimeDirectoryEntry {
57
57
  /** Returns one identity-bound directory inventory for runtime discovery. */
58
58
  export type HostRuntimeDirectorySnapshot = (target: string) => Promise<readonly HostRuntimeDirectoryEntry[]>;
59
59
  export declare function loadHostRuntimeContract(worktreePath: string, snapshot?: HostRuntimeSourceSnapshot, directorySnapshot?: HostRuntimeDirectorySnapshot): Promise<LoadedHostRuntimeContract>;
60
+ /** A managed attempt's own API master key: 32 random bytes, base64-encoded, as Security:MasterKey expects. */
61
+ export declare function newAttemptApiMasterKey(): string;
62
+ /**
63
+ * The environment a managed attempt's ASP.NET API launches with. When neither the launch profile
64
+ * nor the runtime contract configures Security__MasterKey or Security__MasterKeyFile, the API gets
65
+ * the attempt's own key. Otherwise ASP.NET Development falls back to the host user's dotnet
66
+ * user-secrets: the host's own key where they exist, and a failed secret write wherever they do not.
67
+ * The caller keeps one key for the attempt's whole life, so a restart against the same attempt
68
+ * database can still decrypt what was stored before it. The key is a secret: it is for the API
69
+ * process only, never for the environment handed to checks or providers.
70
+ */
71
+ export declare function withAttemptApiMasterKey(port: HostRuntimePortConfig, environment: Readonly<Record<string, string>>, attemptMasterKey: string): Readonly<Record<string, string>>;
60
72
  export declare function defaultHostRuntimeContract(): HostRuntimeContract;
61
73
  export declare function validateHostRuntimeContract(source: string): HostRuntimeContract;
62
74
  export declare function hostPortEnvironment(config: HostRuntimePortConfig, hostIp: "127.0.0.1", hostPort: number): Readonly<Record<string, string>>;
@@ -1,4 +1,4 @@
1
- import { createHash } from "node:crypto";
1
+ import { createHash, randomBytes } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { isAlias, parseDocument, visit } from "yaml";
@@ -425,6 +425,34 @@ function safeAspNetLaunchEnvironment(name, value) {
425
425
  "TMPDIR",
426
426
  ]).has(normalized);
427
427
  }
428
+ // The settings an ASP.NET API reads its secret-store master key from (Security:MasterKey wins).
429
+ const aspNetMasterKeySettings = ["security__masterkey", "security__masterkeyfile"];
430
+ /** A managed attempt's own API master key: 32 random bytes, base64-encoded, as Security:MasterKey expects. */
431
+ export function newAttemptApiMasterKey() {
432
+ return randomBytes(32).toString("base64");
433
+ }
434
+ /**
435
+ * The environment a managed attempt's ASP.NET API launches with. When neither the launch profile
436
+ * nor the runtime contract configures Security__MasterKey or Security__MasterKeyFile, the API gets
437
+ * the attempt's own key. Otherwise ASP.NET Development falls back to the host user's dotnet
438
+ * user-secrets: the host's own key where they exist, and a failed secret write wherever they do not.
439
+ * The caller keeps one key for the attempt's whole life, so a restart against the same attempt
440
+ * database can still decrypt what was stored before it. The key is a secret: it is for the API
441
+ * process only, never for the environment handed to checks or providers.
442
+ */
443
+ export function withAttemptApiMasterKey(port, environment, attemptMasterKey) {
444
+ if (port.adapter !== "aspnetcore")
445
+ return environment;
446
+ const masterKeySetting = (name) => aspNetMasterKeySettings.includes(name.toLowerCase());
447
+ if (Object.entries(environment).some(([name, value]) => masterKeySetting(name) && value.trim().length > 0)) {
448
+ return environment;
449
+ }
450
+ // A blank setting configures nothing; drop it so the attempt's key is the only one.
451
+ return {
452
+ ...Object.fromEntries(Object.entries(environment).filter(([name]) => !masterKeySetting(name))),
453
+ Security__MasterKey: attemptMasterKey,
454
+ };
455
+ }
428
456
  async function findFiles(root, accepts, maximumDepth, maximumEntries, snapshot) {
429
457
  const results = [];
430
458
  let examined = 0;
@@ -10,10 +10,9 @@ import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
10
  import { ForgeFailureError } from "../session/session.types.js";
11
11
  import { resolveExistingDirectoryPath } from "../shared/path/path.js";
12
12
  import { formatBytes } from "../shared/format/format-bytes.js";
13
- import { redactText } from "../shared/redaction/redaction.js";
14
13
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
15
14
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
16
- import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
15
+ import { hostPortEnvironment, loadHostRuntimeContract, newAttemptApiMasterKey, withAttemptApiMasterKey, } from "./host-runtime-contract.js";
17
16
  import { HostPortBroker, } from "./host-port-broker.js";
18
17
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
19
18
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
@@ -30,7 +29,7 @@ import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-pr
30
29
  import { readCanonicalSourceFile } from "./canonical-source-file.js";
31
30
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
32
31
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
33
- import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
32
+ import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, executeAspNetRuntimeBuild, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
34
33
  import { HostLoadGovernor } from "./host-load-governor.js";
35
34
  import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
36
35
  import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
@@ -1275,8 +1274,9 @@ export class HostRuntimeLeaseManager {
1275
1274
  data: { database: active.databaseCapability.databaseName },
1276
1275
  });
1277
1276
  }
1278
- // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1279
- const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1277
+ const apiMasterKey = attemptApiMasterKey(active);
1278
+ // Runtime output is persisted to attempt logs; the database login and master key it may print are redacted.
1279
+ const capabilitySecrets = [...attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString), apiMasterKey];
1280
1280
  const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1281
1281
  for (const configuredPort of configuredPorts) {
1282
1282
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
@@ -1339,9 +1339,7 @@ export class HostRuntimeLeaseManager {
1339
1339
  command: configuredPort.launch.command,
1340
1340
  args: configuredPort.launch.args,
1341
1341
  cwd: workingDirectory,
1342
- environment: {
1343
- ...buildEnvironment,
1344
- },
1342
+ environment: withAttemptApiMasterKey(configuredPort, buildEnvironment, apiMasterKey),
1345
1343
  }, launcher, signal);
1346
1344
  }
1347
1345
  const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
@@ -2374,51 +2372,13 @@ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2374
2372
  }
2375
2373
  return [...keys];
2376
2374
  }
2375
+ /** The attempt's API master key: issued on first use, then the same for every relaunch of the attempt. */
2376
+ function attemptApiMasterKey(active) {
2377
+ return active.apiMasterKey ??= newAttemptApiMasterKey();
2378
+ }
2377
2379
  function anySignal(...signals) {
2378
2380
  return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2379
2381
  }
2380
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
2381
- /** Once the build's supervised tree is up: records it on the build's host load token. */
2382
- onStarted) {
2383
- const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2384
- const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2385
- const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2386
- let stdoutTail = "";
2387
- let stderrTail = "";
2388
- const append = async (target, line) => {
2389
- await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2390
- };
2391
- const child = await supervisor.startChildReady(childName, {
2392
- command: plan.command,
2393
- args: plan.args,
2394
- cwd: plan.cwd,
2395
- env: plan.environment,
2396
- captureOutput: false,
2397
- }, {
2398
- onStdoutLine: async (line) => {
2399
- stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2400
- await append(stdoutLogPath, line);
2401
- },
2402
- onStderrLine: async (line) => {
2403
- stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2404
- await append(stderrLogPath, line);
2405
- },
2406
- }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2407
- await onStarted?.(child.metadataPath);
2408
- const result = await child.result;
2409
- return {
2410
- exitCode: result.exitCode,
2411
- stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2412
- stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2413
- stdoutLogPath,
2414
- stderrLogPath,
2415
- };
2416
- }
2417
- function appendRuntimeBuildTail(current, value) {
2418
- if (!value)
2419
- return current;
2420
- return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
2421
- }
2422
2382
  function effectiveHostConcurrency(lease, runtimeContract, executionClass = "managed_runtime") {
2423
2383
  if (executionClass === "analysis_only") {
2424
2384
  const analysisSingletonHeld = lease.resources.singletonKeys.length > 0;
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { readCanonicalSourceFile } from "./canonical-source-file.js";
5
5
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
6
+ import { replaceFile } from "../shared/fs/replace-file.js";
6
7
  import { ExactHostProcessRecovery } from "../shared/process/host-process-recovery.js";
7
8
  import { captureHostProcessIdentity, } from "../shared/process/host-process-supervisor.js";
8
9
  import { monotonicNowMs } from "../shared/time/monotonic.js";
@@ -14,8 +15,7 @@ const maximumReceiptBytes = 16 * 1024 * 1024;
14
15
  const maximumCapturedCharacters = 200_000;
15
16
  const defaultGraceMs = 2_000;
16
17
  const receiptReadAttempts = 5;
17
- const receiptReplaceAttempts = 40;
18
- const receiptReplaceRetryMs = 25;
18
+ const receiptReadRetryMs = 25;
19
19
  const invalidMetadata = Symbol("invalid managed-command metadata");
20
20
  let procRoot = "/proc";
21
21
  /** Test support: points the Linux process inventory at another directory (null restores /proc). */
@@ -363,7 +363,7 @@ async function readReceipt(store, name) {
363
363
  }
364
364
  catch {
365
365
  if (attempt < receiptReadAttempts)
366
- await delay(receiptReplaceRetryMs);
366
+ await delay(receiptReadRetryMs);
367
367
  }
368
368
  }
369
369
  return null;
@@ -462,19 +462,8 @@ async function persistReceipt(receiptPath, receipt) {
462
462
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
463
463
  try {
464
464
  await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
465
- for (let attempt = 1;; attempt += 1) {
466
- try {
467
- await fs.rename(temporaryPath, receiptPath);
468
- return;
469
- }
470
- catch (error) {
471
- const code = error.code;
472
- // Windows refuses to replace a file another process briefly holds open.
473
- if (attempt >= receiptReplaceAttempts || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES"))
474
- throw error;
475
- await delay(receiptReplaceRetryMs);
476
- }
477
- }
465
+ // Windows refuses to replace a file another process briefly holds open.
466
+ await replaceFile(temporaryPath, receiptPath);
478
467
  }
479
468
  finally {
480
469
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
@@ -2,15 +2,51 @@ export declare const nativeTestPostgresFallbackConfigEnvironment = "FORGE_NATIVE
2
2
  export declare const nativeTestPostgresFallbackFileName = "native-test-postgres.json";
3
3
  export declare const nativeTestPostgresFallbackDatabaseMode = "native_fallback";
4
4
  /**
5
- * A dedicated, operator-provisioned PostgreSQL cluster that runner-authored .NET
6
- * test tiers may use only while the Docker engine is unavailable. The cluster
7
- * must hold nothing but disposable test databases, so its capability carries no
8
- * more authority than the attempt-private container it replaces.
5
+ * The cluster serves the shared test server while Docker is up, so tests that need a
6
+ * pinned engine container still start one. Owner policy (2026-11-16): native PostgreSQL
7
+ * first, which keeps test databases out of the Docker VM and saves RAM.
8
+ */
9
+ export declare const nativeTestPostgresPreferredDatabaseMode = "native_preferred";
10
+ export type NativeTestPostgresDatabaseMode = typeof nativeTestPostgresFallbackDatabaseMode | typeof nativeTestPostgresPreferredDatabaseMode;
11
+ /**
12
+ * What runner-authored .NET test tiers get: `preferred` (the default) the provisioned
13
+ * cluster whenever it is configured; `docker_unavailable` that cluster only after a
14
+ * Docker probe fails; `ephemeral` a throwaway cluster of their own for each check, whose
15
+ * bootstrap superuser they hold (owner policy 2026-11-17). The provisioned cluster still
16
+ * hosts the attempt database broker in every mode.
17
+ */
18
+ export type NativeTestPostgresUse = "preferred" | "docker_unavailable" | "ephemeral";
19
+ /**
20
+ * A dedicated, operator-provisioned PostgreSQL cluster for runner-authored .NET
21
+ * test tiers, preferred over Docker unless its file says `docker_unavailable`.
22
+ * The cluster must hold nothing but disposable test databases, so its capability
23
+ * carries no more authority than the attempt-private container it replaces.
9
24
  */
10
25
  export interface NativeTestPostgresFallback {
11
26
  readonly connectionString: string;
12
27
  readonly endpoint: string;
28
+ readonly use: NativeTestPostgresUse;
29
+ /** The PostgreSQL bin directory an ephemeral cluster runs from; defaults to the one beside psql. */
30
+ readonly postgresBin?: string;
13
31
  }
32
+ /** The cluster as handed to one test process, with the mode its fixtures run in. */
33
+ export interface NativeTestPostgresGrant {
34
+ readonly connectionString: string;
35
+ readonly endpoint: string;
36
+ readonly mode: NativeTestPostgresDatabaseMode;
37
+ /** Set when the grant is a throwaway cluster of its own; the server reports it as `forge.ephemeral_cluster`. */
38
+ readonly ephemeralClusterId?: string;
39
+ /** Stops and deletes an ephemeral cluster once its check has finished. */
40
+ readonly release?: () => Promise<void>;
41
+ }
42
+ /**
43
+ * The provisioned cluster's grant for a check that can use it, or null to use Docker. A
44
+ * preferred cluster is granted whether or not Docker is up; the mode says which, because
45
+ * only the fallback mode excludes Docker for pinned-engine tests. An `ephemeral` host
46
+ * normally gets its own cluster instead (ephemeral-test-postgres-grant.ts); if that cannot
47
+ * start, the provisioned cluster serves only while Docker is down, as for `docker_unavailable`.
48
+ */
49
+ export declare function nativeTestPostgresGrant(fallback: NativeTestPostgresFallback | null, dockerAvailable: boolean): NativeTestPostgresGrant | null;
14
50
  export declare class NativeTestPostgresFallbackError extends Error {
15
51
  readonly code = "native_test_postgres_fallback_invalid";
16
52
  constructor(detail: string);
@@ -20,6 +56,14 @@ export declare function resolveNativeTestPostgresFallbackPath(): string;
20
56
  export declare function configuredNativeTestPostgresFallbackPath(): string | null;
21
57
  /** Returns null when no fallback is configured; throws when one is configured unsafely. */
22
58
  export declare function readNativeTestPostgresFallback(configPath?: string): NativeTestPostgresFallback | null;
23
- export declare function parseNativeTestPostgresFallback(connectionString: string): NativeTestPostgresFallback;
24
- /** Environment for one runner-authored .NET test process using the fallback. */
25
- export declare function nativeTestPostgresFallbackEnvironment(fallback: NativeTestPostgresFallback): Readonly<Record<string, string>>;
59
+ export declare function parseNativeTestPostgresFallback(connectionString: string, use?: NativeTestPostgresUse): NativeTestPostgresFallback;
60
+ /** Environment for one runner-authored .NET test process using the cluster. */
61
+ export declare function nativeTestPostgresFallbackEnvironment(grant: Pick<NativeTestPostgresGrant, "connectionString" | "mode" | "ephemeralClusterId">): Readonly<Record<string, string>>;
62
+ /**
63
+ * Runner-authored verification uses the operator-provisioned native test cluster,
64
+ * which holds no real data, whenever its file prefers it (the default); Docker then
65
+ * only starts pinned-engine containers. A `docker_unavailable` cluster is used only
66
+ * when the Docker engine is unavailable; otherwise the attempt-owned Testcontainers
67
+ * database serves.
68
+ */
69
+ export declare function managedVerificationDatabaseEnvironment(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null): Promise<Readonly<Record<string, string>>>;