@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,45 @@
1
+ import { type DotnetPathPlatform, type DotnetProjectFiles } from "./dotnet-build-outputs.js";
2
+ /** What a supervised project runtime runs, recorded in the attempt log directory at launch. */
3
+ export interface SupervisedRuntimeDescriptor {
4
+ readonly schemaVersion: 1;
5
+ /** The runtime contract's port name, for example `api`. */
6
+ readonly role: string;
7
+ /** The attempt supervisor child, for example `project-api`. */
8
+ readonly childName: string;
9
+ readonly command: string;
10
+ readonly args: readonly string[];
11
+ readonly cwd: string;
12
+ }
13
+ export interface SupervisedRuntimeCollision {
14
+ readonly childName: string;
15
+ readonly role: string;
16
+ /** The runtime's supervised process (the `dotnet run` the supervisor started), when recorded. */
17
+ readonly pid: number | null;
18
+ readonly project: string;
19
+ readonly outputDirectory: string;
20
+ /** The running file the build would have to replace. */
21
+ readonly lockedPath: string;
22
+ }
23
+ export interface SupervisedRuntimeBuildCheck {
24
+ readonly command: string;
25
+ readonly args: readonly string[];
26
+ readonly cwd: string;
27
+ readonly worktreePath: string;
28
+ /** The attempt's FORGE_LOG_DIR, which holds the supervisor ledger and runtime descriptors. */
29
+ readonly logDirectory: string;
30
+ /** A runner-authored script that builds the worktree's solution (a managed verification tier). */
31
+ readonly buildsWorktreeSolution?: boolean;
32
+ readonly platform?: DotnetPathPlatform;
33
+ readonly files?: DotnetProjectFiles;
34
+ }
35
+ export declare function supervisedRuntimeDescriptorPath(logDirectory: string, childName: string): string;
36
+ export declare function writeSupervisedRuntimeDescriptor(logDirectory: string, descriptor: Omit<SupervisedRuntimeDescriptor, "schemaVersion">): Promise<void>;
37
+ /**
38
+ * Finds the first running supervised runtime of this attempt whose build output the command
39
+ * would write. Only the project graph and output directory decide a collision: a build of an
40
+ * unrelated project, into another output, or a test run without a build never matches.
41
+ */
42
+ export declare function findSupervisedRuntimeCollision(check: SupervisedRuntimeBuildCheck): Promise<SupervisedRuntimeCollision | null>;
43
+ export declare function supervisedRuntimeCollisionMessage(collision: SupervisedRuntimeCollision): string;
44
+ /** Fails fast, naming the runtime, instead of letting the build hit the runtime's locked files. */
45
+ export declare function assertBuildSparesSupervisedRuntimes(check: SupervisedRuntimeBuildCheck): Promise<void>;
@@ -0,0 +1,112 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { replaceFile } from "../shared/fs/replace-file.js";
5
+ import { attemptProcessSupervisorLedgerPath } from "./attempt-process-supervisor.js";
6
+ import { canonicalExistingPath, fileSystemProjectFiles, findDotnetOutputCollisions, hostPathPlatform, isDotnetExecutable, parseDotnetOutputCommand, } from "./dotnet-build-outputs.js";
7
+ const activeChildStatuses = new Set(["starting", "running", "stopping"]);
8
+ export function supervisedRuntimeDescriptorPath(logDirectory, childName) {
9
+ return path.join(logDirectory, `${childName}.runtime.json`);
10
+ }
11
+ export async function writeSupervisedRuntimeDescriptor(logDirectory, descriptor) {
12
+ const target = supervisedRuntimeDescriptorPath(logDirectory, descriptor.childName);
13
+ const temporary = `${target}.${randomUUID()}.tmp`;
14
+ await fs.writeFile(temporary, `${JSON.stringify({ schemaVersion: 1, ...descriptor })}\n`, { encoding: "utf8", mode: 0o600 });
15
+ try {
16
+ await replaceFile(temporary, target);
17
+ }
18
+ finally {
19
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
20
+ }
21
+ }
22
+ /**
23
+ * Finds the first running supervised runtime of this attempt whose build output the command
24
+ * would write. Only the project graph and output directory decide a collision: a build of an
25
+ * unrelated project, into another output, or a test run without a build never matches.
26
+ */
27
+ export async function findSupervisedRuntimeCollision(check) {
28
+ const platform = check.platform ?? hostPathPlatform();
29
+ const files = check.files ?? fileSystemProjectFiles;
30
+ const writer = await buildingCommand(check, platform);
31
+ if (!writer)
32
+ return null;
33
+ const ledger = await readJson(attemptProcessSupervisorLedgerPath(check.logDirectory));
34
+ for (const child of ledger?.children ?? []) {
35
+ if (!child.name.startsWith("project-") || !activeChildStatuses.has(child.status))
36
+ continue;
37
+ const descriptor = await readJson(supervisedRuntimeDescriptorPath(check.logDirectory, child.name));
38
+ if (descriptor?.schemaVersion !== 1 || !Array.isArray(descriptor.args))
39
+ continue;
40
+ const holder = parseDotnetOutputCommand(descriptor.command, descriptor.args, await canonicalPath(descriptor.cwd), { platform, holder: true });
41
+ if (!holder)
42
+ continue;
43
+ const [collision] = await findDotnetOutputCollisions(writer, holder, files, platform);
44
+ if (!collision)
45
+ continue;
46
+ const metadata = await readJson(child.metadataPath);
47
+ const pid = [metadata?.providerPid, metadata?.rootPid].find(value => Number.isSafeInteger(value) && value > 0);
48
+ // A default output's framework folder is the wildcard `*` until the project names it.
49
+ const framework = await projectTargetFramework(collision.project, files);
50
+ const outputDirectory = framework ? collision.outputDirectory.replace(/(?<=[\\/])\*(?=[\\/]|$)/u, framework) : collision.outputDirectory;
51
+ return {
52
+ childName: child.name,
53
+ role: descriptor.role,
54
+ pid: pid ?? null,
55
+ project: collision.project,
56
+ outputDirectory,
57
+ lockedPath: lockedOutputPath(collision.project, outputDirectory, await runtimeProject(holder, files), platform),
58
+ };
59
+ }
60
+ return null;
61
+ }
62
+ /** A single-targeted project's TargetFramework, which names the default output's framework folder. */
63
+ async function projectTargetFramework(project, files) {
64
+ const content = await files.read(project);
65
+ return content?.match(/<TargetFramework>\s*([^<;\s]+)\s*<\/TargetFramework>/u)?.[1]?.toLowerCase() ?? null;
66
+ }
67
+ async function buildingCommand(check, platform) {
68
+ const parsed = parseDotnetOutputCommand(check.command, check.args, await canonicalPath(check.cwd), { platform });
69
+ if (parsed || isDotnetExecutable(check.command, platform) || !check.buildsWorktreeSolution)
70
+ return parsed;
71
+ // The verification scripts build the worktree's solution with its default output.
72
+ return parseDotnetOutputCommand("dotnet", ["build"], await canonicalPath(check.worktreePath), { platform });
73
+ }
74
+ /** Both sides compare canonical paths: a junction, symlink, or 8.3 alias must not hide a collision. */
75
+ async function canonicalPath(directory) {
76
+ return await canonicalExistingPath(directory);
77
+ }
78
+ /** The project the runtime runs, at its real location like the collision's project. */
79
+ async function runtimeProject(holder, files) {
80
+ const target = holder.targets[0];
81
+ return target === undefined || !files.canonical ? target : await files.canonical(target);
82
+ }
83
+ /** The runtime's own executable when the colliding project is the one it runs, otherwise that project's assembly. */
84
+ function lockedOutputPath(project, outputDirectory, runtimeProject, platform) {
85
+ const p = platform === "win32" ? path.win32 : path.posix;
86
+ const name = p.basename(project).replace(/\.(?:cs|fs|vb)proj$/iu, "");
87
+ const isRuntimeProject = runtimeProject !== undefined
88
+ && (platform === "win32" ? runtimeProject.toLowerCase() === project.toLowerCase() : runtimeProject === project);
89
+ const fileName = isRuntimeProject ? `${name}${platform === "win32" ? ".exe" : ""}` : `${name}.dll`;
90
+ return p.join(outputDirectory, fileName);
91
+ }
92
+ export function supervisedRuntimeCollisionMessage(collision) {
93
+ return `managed_command_runtime_output_collision: this command would build ${collision.project} into ${collision.outputDirectory}, `
94
+ + `the output the attempt's running supervised runtime ${collision.childName} (role ${collision.role}, PID ${collision.pid ?? "unknown"}) `
95
+ + `executes from; ${collision.lockedPath} is in use. Forge refused it before launch, because the build would fail on the locked file `
96
+ + "(MSB3027 on Windows) or replace files under the running runtime. Build into a different output directory: the runtime runs from its "
97
+ + "own output, so the project's default output is free. Forge rebuilds and restarts the runtime from the current source when validation needs it.";
98
+ }
99
+ /** Fails fast, naming the runtime, instead of letting the build hit the runtime's locked files. */
100
+ export async function assertBuildSparesSupervisedRuntimes(check) {
101
+ const collision = await findSupervisedRuntimeCollision(check);
102
+ if (collision)
103
+ throw new Error(supervisedRuntimeCollisionMessage(collision));
104
+ }
105
+ async function readJson(file) {
106
+ try {
107
+ return JSON.parse(await fs.readFile(file, "utf8"));
108
+ }
109
+ catch {
110
+ return null;
111
+ }
112
+ }
@@ -108,6 +108,8 @@ export declare function sandboxHostCapacityDeliveryExecArgs(container: string):
108
108
  * newer state. Replies are world-readable but owned by the writer (root, via
109
109
  * `docker exec --user 0`). The directory must already be owned by that same uid
110
110
  * and writable by no one else, i.e. the root-owned reply mount; it is never
111
- * created here, where it could turn out to be the sandbox's own directory.
111
+ * created here, where it could turn out to be the sandbox's own directory. A
112
+ * runtime without POSIX user ids (Windows) cannot prove that, so the script
113
+ * writes nothing there (exit 3), as for any directory it cannot trust.
112
114
  */
113
115
  export declare const sandboxHostCapacityResponseScript: string;
@@ -327,8 +327,10 @@ export function sandboxHostCapacityDeliveryExecArgs(container) {
327
327
  * newer state. Replies are world-readable but owned by the writer (root, via
328
328
  * `docker exec --user 0`). The directory must already be owned by that same uid
329
329
  * and writable by no one else, i.e. the root-owned reply mount; it is never
330
- * created here, where it could turn out to be the sandbox's own directory.
330
+ * created here, where it could turn out to be the sandbox's own directory. A
331
+ * runtime without POSIX user ids (Windows) cannot prove that, so the script
332
+ * writes nothing there (exit 3), as for any directory it cannot trust.
331
333
  */
332
334
  export const sandboxHostCapacityResponseScript = "let s='';process.stdin.setEncoding('utf8');process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>{const f=require('fs'),r=JSON.parse(s),d='"
333
335
  + sandboxHostCapacityResponseRoot
334
- + "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);const st=f.lstatSync(d);if(!st.isDirectory()||st.uid!==process.getuid()||(st.mode&0o022))process.exit(3);const p=d+'/'+r.requestId+'.json',t=p+'.'+process.pid+'.tmp';let o=-1;try{o=JSON.parse(f.readFileSync(p,'utf8')).sequence}catch{}if(Number.isSafeInteger(o)&&o>=r.sequence)return;f.writeFileSync(t,s,{mode:0o644,flag:'wx'});f.renameSync(t,p)})";
336
+ + "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);if(typeof process.getuid!=='function')process.exit(3);const st=f.lstatSync(d);if(!st.isDirectory()||st.uid!==process.getuid()||(st.mode&0o022))process.exit(3);const p=d+'/'+r.requestId+'.json',t=p+'.'+process.pid+'.tmp';let o=-1;try{o=JSON.parse(f.readFileSync(p,'utf8')).sequence}catch{}if(Number.isSafeInteger(o)&&o>=r.sequence)return;f.writeFileSync(t,s,{mode:0o644,flag:'wx'});f.renameSync(t,p)})";
@@ -0,0 +1,13 @@
1
+ import { type SandboxProcessRequest, type SandboxProcessResult } from "./process.js";
2
+ export type ManagedBranchProcess = (request: SandboxProcessRequest) => Promise<SandboxProcessResult>;
3
+ export interface CheckedOutBranchUpdate {
4
+ readonly repoPath: string;
5
+ readonly worktreePath: string;
6
+ readonly branchRef: string;
7
+ /** The commit the sandbox started from; the branch and worktree must still be exactly there. */
8
+ readonly expected: string;
9
+ readonly imported: string;
10
+ /** Runs git; tests inject one. */
11
+ readonly run?: ManagedBranchProcess;
12
+ }
13
+ export declare function advanceCheckedOutBranch(update: CheckedOutBranchUpdate): Promise<void>;
@@ -0,0 +1,90 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
2
+ import { requireSandboxProcess } from "./process.js";
3
+ export async function advanceCheckedOutBranch(update) {
4
+ const run = update.run ?? requireSandboxProcess;
5
+ const inWorktree = (args, timeoutMs) => run({ command: "git", args: ["-C", update.worktreePath, ...args], timeoutMs, maxOutputBytes: 4 * 1024 * 1024 });
6
+ const head = (await inWorktree(["rev-parse", "HEAD"], 30_000)).stdout.trim();
7
+ const status = (await inWorktree(["status", "--porcelain=v1", "--untracked-files=no"], 30_000)).stdout;
8
+ if (head !== update.expected || status.trim()) {
9
+ throw conflict("managed worktree changed after sandbox input was captured.");
10
+ }
11
+ await inWorktree(["read-tree", "-m", "-u", update.expected, update.imported], 2 * 60_000);
12
+ try {
13
+ await run({
14
+ command: "git",
15
+ args: ["-C", update.repoPath, "update-ref", update.branchRef, update.imported, update.expected],
16
+ timeoutMs: 30_000,
17
+ maxOutputBytes: 4 * 1024 * 1024,
18
+ });
19
+ }
20
+ catch (error) {
21
+ const settled = await followBranch(run, update, inWorktree);
22
+ throw conflict(`managed branch changed while the sandbox result was applied (${messageOf(error)}); its worktree now matches the branch's commit ${settled}.`, { cause: error });
23
+ }
24
+ }
25
+ /** How many times a rollback re-reads a branch that keeps moving before it gives up. */
26
+ const rollbackPasses = 3;
27
+ /** How many times one read of the branch's commit is tried before the rollback gives up on it. */
28
+ const tipReads = 3;
29
+ /**
30
+ * After a lost swap, moves the worktree and index to wherever the branch points (HEAD follows it):
31
+ * the other writer's commit when it won the race, or the input when the swap failed for another
32
+ * reason. The branch can move again while that runs, so the tip is read again after each move and
33
+ * followed; a branch still moving after `rollbackPasses` moves fails closed, naming both commits.
34
+ * A branch whose commit can't be read (after `tipReads` tries) also fails closed, with the worktree
35
+ * left where it is: guessing a commit could leave it on one HEAD doesn't name.
36
+ * Returns the commit the worktree matches.
37
+ */
38
+ async function followBranch(run, update, inWorktree) {
39
+ let restored = update.imported;
40
+ let target = await readTip(run, update);
41
+ for (let pass = 0; pass < rollbackPasses; pass += 1) {
42
+ if (target === null)
43
+ throw unreadableTip(restored);
44
+ if (target === restored)
45
+ return restored;
46
+ try {
47
+ await inWorktree(["read-tree", "-m", "-u", restored, target], 2 * 60_000);
48
+ }
49
+ catch (rollbackError) {
50
+ throw conflict(`managed branch changed while the sandbox result was applied, and its worktree could not be moved to the branch's commit ${target} `
51
+ + `(${messageOf(rollbackError)}); it holds the files of ${restored}.`, { cause: rollbackError });
52
+ }
53
+ restored = target;
54
+ target = await readTip(run, update);
55
+ }
56
+ if (target === null)
57
+ throw unreadableTip(restored);
58
+ if (target === restored)
59
+ return restored;
60
+ throw conflict(`managed branch kept moving while its worktree was rolled back after the sandbox result was applied; the worktree matches ${restored} `
61
+ + `but the branch now points at ${target}.`);
62
+ }
63
+ async function readTip(run, update) {
64
+ for (let read = 0; read < tipReads; read += 1) {
65
+ const tip = await branchTip(run, update).catch(() => null);
66
+ if (tip)
67
+ return tip;
68
+ }
69
+ return null;
70
+ }
71
+ function unreadableTip(restored) {
72
+ return conflict(`managed branch changed while the sandbox result was applied, and its commit could not be read; its worktree holds the files of ${restored}, `
73
+ + "which the branch may no longer point at.");
74
+ }
75
+ async function branchTip(run, update) {
76
+ const result = await run({
77
+ command: "git",
78
+ args: ["-C", update.repoPath, "rev-parse", "-q", "--verify", `${update.branchRef}^{commit}`],
79
+ timeoutMs: 30_000,
80
+ maxOutputBytes: 1024 * 1024,
81
+ });
82
+ const sha = result.stdout.trim();
83
+ return /^[0-9a-f]{40,64}$/iu.test(sha) ? sha : null;
84
+ }
85
+ function conflict(detail, options) {
86
+ return new ForgeFailureError("sandbox_output_conflict", `sandbox_output_conflict: ${detail}`, "sandbox", options);
87
+ }
88
+ function messageOf(error) {
89
+ return error instanceof Error ? error.message : String(error);
90
+ }
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import fsp from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { fileIdentityChanged } from "../../shared/fs/file-identity.js";
5
6
  const maxCredentialFileBytes = 1024 * 1024;
6
7
  // Capability and heartbeat paths call doctor() synchronously; keep validation
7
8
  // fresh enough for auth changes without rereading auth.json for every offer.
@@ -87,7 +88,7 @@ function codexAuthDoctor(environment) {
87
88
  async function readValidatedCodexAuthFile(authPath) {
88
89
  let pathStat;
89
90
  try {
90
- pathStat = await fsp.lstat(authPath);
91
+ pathStat = await fsp.lstat(authPath, { bigint: true });
91
92
  }
92
93
  catch {
93
94
  throw new Error("Codex Local CLI auth is not available on the bridge host.");
@@ -101,11 +102,11 @@ async function readValidatedCodexAuthFile(authPath) {
101
102
  throw codexAuthOpenError(error);
102
103
  }
103
104
  try {
104
- const openedStat = await handle.stat();
105
+ const openedStat = await handle.stat({ bigint: true });
105
106
  validateSameCodexAuthFile(pathStat, openedStat);
106
107
  validateCodexAuthStat(openedStat);
107
108
  const content = await handle.readFile();
108
- const afterStat = await handle.stat();
109
+ const afterStat = await handle.stat({ bigint: true });
109
110
  validateSameCodexAuthFile(openedStat, afterStat);
110
111
  validateCodexAuthStat(afterStat);
111
112
  validateCodexAuthReadSize(content, openedStat, afterStat);
@@ -119,7 +120,7 @@ async function readValidatedCodexAuthFile(authPath) {
119
120
  function readValidatedCodexAuthFileSync(authPath) {
120
121
  let pathStat;
121
122
  try {
122
- pathStat = fs.lstatSync(authPath);
123
+ pathStat = fs.lstatSync(authPath, { bigint: true });
123
124
  }
124
125
  catch {
125
126
  throw new Error("Codex Local CLI auth is not available on the bridge host.");
@@ -133,11 +134,11 @@ function readValidatedCodexAuthFileSync(authPath) {
133
134
  throw codexAuthOpenError(error);
134
135
  }
135
136
  try {
136
- const openedStat = fs.fstatSync(fd);
137
+ const openedStat = fs.fstatSync(fd, { bigint: true });
137
138
  validateSameCodexAuthFile(pathStat, openedStat);
138
139
  validateCodexAuthStat(openedStat);
139
140
  const content = fs.readFileSync(fd);
140
- const afterStat = fs.fstatSync(fd);
141
+ const afterStat = fs.fstatSync(fd, { bigint: true });
141
142
  validateSameCodexAuthFile(openedStat, afterStat);
142
143
  validateCodexAuthStat(afterStat);
143
144
  validateCodexAuthReadSize(content, openedStat, afterStat);
@@ -158,21 +159,20 @@ function validateCodexAuthStat(stat) {
158
159
  if (!stat.isFile()) {
159
160
  throw new Error("Codex Local CLI auth.json is not a regular file.");
160
161
  }
161
- if (stat.size <= 0) {
162
+ if (stat.size <= 0n) {
162
163
  throw new Error("Codex Local CLI auth.json is empty.");
163
164
  }
164
- if (stat.size > maxCredentialFileBytes) {
165
+ if (stat.size > BigInt(maxCredentialFileBytes)) {
165
166
  throw new Error("Codex Local CLI auth.json exceeds the 1 MiB sandbox auth limit.");
166
167
  }
167
168
  }
168
169
  function validateSameCodexAuthFile(before, after) {
169
- if (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
170
- && (before.dev !== after.dev || before.ino !== after.ino)) {
170
+ if (fileIdentityChanged(before, after)) {
171
171
  throw new Error("Codex Local CLI auth.json changed while being copied.");
172
172
  }
173
173
  }
174
174
  function validateCodexAuthReadSize(content, openedStat, afterStat) {
175
- if (openedStat.size !== afterStat.size || content.length !== afterStat.size) {
175
+ if (openedStat.size !== afterStat.size || BigInt(content.length) !== afterStat.size) {
176
176
  throw new Error("Codex Local CLI auth.json changed while being copied.");
177
177
  }
178
178
  }
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { createFailureEnvelope, ForgeFailureError, failureFactsForCode, failurePolicyForCode, failureResult, parseRunOnceResultPacket, } from "../session/session.types.js";
6
6
  import { dockerfileUpstreamImages, validateDockerfilePolicy, validateSandboxContract } from "./contract.js";
7
7
  import { requireSandboxProcess, runSandboxProcess } from "./process.js";
8
+ import { advanceCheckedOutBranch } from "./managed-branch.js";
8
9
  import { createLeaseUpdate } from "./lease-watchdog.js";
9
10
  import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
10
11
  import { SandboxEventBudget } from "./event-budget.js";
@@ -169,7 +170,7 @@ export class DockerSandboxRuntime {
169
170
  const brokered = this.hostLoadGate?.enabled === true;
170
171
  const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
171
172
  const createArgs = brokered
172
- ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs)
173
+ ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxTotalWaitMs)
173
174
  : workerArgs;
174
175
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
175
176
  const containerId = dockerObjectId(createdContainer.stdout, "container");
@@ -1276,12 +1277,7 @@ class HostGit {
1276
1277
  await this.git(["update-ref", branchRef, imported, managedBranchUpdateExpectedValue(current, expected, imported)], 30_000);
1277
1278
  return;
1278
1279
  }
1279
- const head = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "rev-parse", "HEAD"], timeoutMs: 30_000 })).stdout.trim();
1280
- const status = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "status", "--porcelain=v1", "--untracked-files=no"], timeoutMs: 30_000, maxOutputBytes: 4 * 1024 * 1024 })).stdout;
1281
- if (head !== expected || status.trim())
1282
- throw trustedSandboxFailure("sandbox_output_conflict", "managed worktree changed after sandbox input was captured.");
1283
- await this.git(["update-ref", branchRef, imported, expected], 30_000);
1284
- await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "reset", "--hard"], timeoutMs: 2 * 60_000, maxOutputBytes: 4 * 1024 * 1024 });
1280
+ await advanceCheckedOutBranch({ repoPath: this.repoPath, worktreePath: checkedOut.path, branchRef, expected, imported });
1285
1281
  }
1286
1282
  async resolveFirst(refs) {
1287
1283
  for (const ref of refs) {
@@ -1,4 +1,3 @@
1
- import { type NativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
2
1
  export declare const managedAttemptToolNames: readonly ["forge.run_managed_command", "run_managed_command", "forge.start_managed_command", "start_managed_command", "forge.get_managed_command", "get_managed_command", "forge.wait_managed_command", "wait_managed_command", "forge.start_managed_verification", "start_managed_verification", "forge.reset_generated_outputs", "reset_generated_outputs"];
3
2
  /**
4
3
  * Stops every managed command this MCP server started, proves each process tree stopped,
@@ -45,11 +44,5 @@ export declare function buildManagedVerificationCommand(profile: string, outputD
45
44
  export declare function preferredPowerShellExecutable(platform?: NodeJS.Platform, pathValue?: string): string;
46
45
  export declare function validatePlaywrightProjectName(project: string, availableProjects: readonly string[]): void;
47
46
  export declare function playwrightProjectNamesFromConfigSource(source: string): readonly string[];
48
- /**
49
- * Runner-authored verification normally uses its attempt-owned Testcontainers
50
- * database. Only when the Docker engine is unavailable does it switch to the
51
- * operator-provisioned native test cluster, which holds no real data.
52
- */
53
- export declare function managedVerificationDatabaseEnvironment(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null): Promise<Readonly<Record<string, string>>>;
54
47
  export declare function isBuildProducingManagedCommand(command: string, args: readonly string[]): boolean;
55
48
  export {};
@@ -3,19 +3,18 @@ import fs from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
6
- import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
7
6
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
8
7
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
9
- import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
8
+ import { managedVerificationDatabase, noManagedVerificationDatabase, releaseManagedVerificationDatabase, setUpWithManagedVerificationDatabase } from "../runtime/ephemeral-test-postgres-grant.js";
10
9
  import { redactText } from "../shared/redaction/redaction.js";
11
10
  import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
12
- import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
11
+ import { assertManagedBuildSparesSupervisedRuntimes, ManagedBuildCoordinator } from "./managed-build-coordinator.js";
13
12
  import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
14
13
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
15
14
  import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
16
15
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
17
16
  import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
18
- import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
17
+ import { managedBuildConfiguration, persistJsonAtomically, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
19
18
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
20
19
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
21
20
  import { monotonicNowMs } from "../shared/time/monotonic.js";
@@ -38,8 +37,6 @@ const managedCommandRetryAfterMs = 60_000;
38
37
  const managedCommandLaunchTimeoutMs = 60_000;
39
38
  const managedCommandProgressPersistIntervalMs = 5_000;
40
39
  const managedCommandReceiptPollIntervalMs = 1_000;
41
- const managedCommandReceiptReplaceAttempts = 40;
42
- const managedCommandReceiptReplaceRetryMs = 25;
43
40
  const terminalManagedCommandStatuses = new Set([
44
41
  "pass",
45
42
  "fail",
@@ -295,6 +292,9 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
295
292
  buildReceiptReuse,
296
293
  controller: new AbortController(),
297
294
  };
295
+ // A build aimed at the output a running supervised runtime executes from fails here, naming
296
+ // that runtime, instead of failing on its locked files after the build-slot and capacity waits.
297
+ await assertManagedBuildSparesSupervisedRuntimes(invocation);
298
298
  if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
299
299
  const started = managedCommandResult({
300
300
  ...invocation,
@@ -594,41 +594,48 @@ async function executeManagedCommand(invocation) {
594
594
  return managedCommandPublicResult(receipt);
595
595
  }
596
596
  }
597
+ /** A command's environment and redaction list; a setup that throws releases the database it started. */
597
598
  async function managedCommandProcessEnvironment(invocation) {
598
599
  assertHostDatabaseCapabilityBoundary();
599
- const databaseEnvironment = invocation.verificationProfile
600
- ? await managedVerificationDatabaseEnvironment()
601
- : {};
602
- const exactSecrets = [
603
- ...Object.values(databaseEnvironment).filter(value => value !== nativeTestPostgresFallbackDatabaseMode),
604
- // The attempt's brokered database login reaches managed commands; their output never shows it.
605
- ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
- ];
607
- const environment = inheritedEnvironment({
608
- FORGE_RUNTIME_MODE: "host",
609
- FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
610
- FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
611
- // This nested command owns a distinct supervisor identity. A command-local
612
- // fence avoids exposing the parent attempt's fencing capability to Codex's
613
- // MCP subprocess configuration while preserving exact-tree cleanup proof.
614
- FORGE_FENCING_TOKEN: randomUUID(),
615
- FORGE_LOG_DIR: invocation.logDirectory,
616
- FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
617
- FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
618
- FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
619
- ...(invocation.verificationProfile
620
- ? {
621
- FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
622
- // Managed verification executes mutable worktree scripts, SDK targets,
623
- // and test assemblies. It uses an attempt-owned container, or the
624
- // dedicated native test cluster while Docker is unavailable; it never
625
- // receives a capability for a server that holds real data.
626
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
627
- ...databaseEnvironment,
628
- }
629
- : {}),
600
+ const database = invocation.verificationProfile ? await managedVerificationDatabase() : noManagedVerificationDatabase;
601
+ return await setUpWithManagedVerificationDatabase(database, () => {
602
+ const exactSecrets = [
603
+ ...database.secrets,
604
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
605
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
+ ];
607
+ const environment = inheritedEnvironment({
608
+ FORGE_RUNTIME_MODE: "host",
609
+ FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
610
+ FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
611
+ // This nested command owns a distinct supervisor identity. A command-local
612
+ // fence avoids exposing the parent attempt's fencing capability to Codex's
613
+ // MCP subprocess configuration while preserving exact-tree cleanup proof.
614
+ FORGE_FENCING_TOKEN: randomUUID(),
615
+ FORGE_LOG_DIR: invocation.logDirectory,
616
+ FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
617
+ FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
618
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
619
+ ...(invocation.verificationProfile
620
+ ? {
621
+ FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
622
+ // Managed verification executes mutable worktree scripts, SDK targets,
623
+ // and test assemblies. It uses an attempt-owned container, or the
624
+ // dedicated native test cluster while Docker is unavailable; it never
625
+ // receives a capability for a server that holds real data.
626
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
627
+ ...database.environment,
628
+ }
629
+ : {}),
630
+ });
631
+ return { environment, exactSecrets, release: database.release };
630
632
  });
631
- return { environment, exactSecrets };
633
+ }
634
+ function clearManagedCommandTimers(...timers) {
635
+ // clearTimeout and clearInterval share one timer table.
636
+ for (const timer of timers)
637
+ if (timer)
638
+ clearTimeout(timer);
632
639
  }
633
640
  async function executeManagedCommandProcess(invocation) {
634
641
  let prepared;
@@ -830,11 +837,9 @@ async function executeManagedCommandProcess(invocation) {
830
837
  return managedCommandPublicResult(receipt);
831
838
  }
832
839
  finally {
833
- clearTimeout(launchTimer);
834
- if (timer)
835
- clearTimeout(timer);
836
- if (progressHeartbeat)
837
- clearInterval(progressHeartbeat);
840
+ clearManagedCommandTimers(launchTimer, timer, progressHeartbeat);
841
+ // An ephemeral verification cluster lives exactly as long as its command; one that would not stop is reaped later and named in the receipt.
842
+ await releaseManagedVerificationDatabase(prepared, async (message) => await annotateManagedCommandReceipt(invocation.receiptPath, { ephemeral_cluster_release_error: redactText(message, exactSecrets) }));
838
843
  }
839
844
  }
840
845
  async function readManagedCommand(input) {
@@ -938,27 +943,7 @@ function managedCommandReceiptPath(logDirectory, commandId) {
938
943
  return path.join(logDirectory, "managed-commands", `${commandId}.receipt.json`);
939
944
  }
940
945
  async function persistManagedCommandReceipt(receiptPath, receipt) {
941
- const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
942
- await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
943
- try {
944
- for (let attempt = 1;; attempt += 1) {
945
- try {
946
- await fs.rename(temporaryPath, receiptPath);
947
- break;
948
- }
949
- catch (error) {
950
- const code = error.code;
951
- if (attempt >= managedCommandReceiptReplaceAttempts
952
- || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES")) {
953
- throw error;
954
- }
955
- await delay(managedCommandReceiptReplaceRetryMs);
956
- }
957
- }
958
- }
959
- finally {
960
- await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
961
- }
946
+ await persistJsonAtomically(receiptPath, receipt);
962
947
  }
963
948
  function managedCommandResult(values) {
964
949
  // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
@@ -1124,20 +1109,6 @@ function inheritedEnvironment(overrides) {
1124
1109
  }
1125
1110
  return { ...env, ...overrides };
1126
1111
  }
1127
- /**
1128
- * Runner-authored verification normally uses its attempt-owned Testcontainers
1129
- * database. Only when the Docker engine is unavailable does it switch to the
1130
- * operator-provisioned native test cluster, which holds no real data.
1131
- */
1132
- export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().refresh(true)).available, readFallback = () => {
1133
- const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
1134
- return configPath ? readNativeTestPostgresFallback(configPath) : null;
1135
- }) {
1136
- const fallback = readFallback();
1137
- if (!fallback || await dockerAvailable())
1138
- return {};
1139
- return nativeTestPostgresFallbackEnvironment(fallback);
1140
- }
1141
1112
  export function isBuildProducingManagedCommand(command, args) {
1142
1113
  const executable = path.basename(command).toLowerCase();
1143
1114
  if (executable === "dotnet" || executable === "dotnet.exe") {
@@ -1149,10 +1120,7 @@ export function isBuildProducingManagedCommand(command, args) {
1149
1120
  if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1150
1121
  const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
1151
1122
  const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
1152
- if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
1153
- return !args.some(argument => argument.toLowerCase() === "-nobuild");
1154
- }
1155
- if (script === "run-dotnet-test-tier.ps1") {
1123
+ if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)) {
1156
1124
  return !args.some(argument => argument.toLowerCase() === "-nobuild");
1157
1125
  }
1158
1126
  }
@@ -1,3 +1,19 @@
1
+ /** The managed command a build check needs: what it runs, where, and for which attempt. */
2
+ export interface ManagedBuildCandidate {
3
+ readonly command: string;
4
+ readonly args: readonly string[];
5
+ readonly cwd: string;
6
+ readonly worktreePath: string;
7
+ readonly logDirectory: string;
8
+ readonly buildProducing: boolean;
9
+ }
10
+ /**
11
+ * Refuses, before launch, a managed command that would build into the output one of the
12
+ * attempt's running supervised runtimes executes from. The build slot below orders builds
13
+ * against each other; a running runtime cannot wait its turn, so the collision fails fast
14
+ * with an error naming the runtime instead of a build stuck on its locked files.
15
+ */
16
+ export declare function assertManagedBuildSparesSupervisedRuntimes(candidate: ManagedBuildCandidate): Promise<void>;
1
17
  export declare class ManagedBuildCoordinator {
2
18
  private readonly stateRoot;
3
19
  constructor(stateRoot?: string);