@loucompanion/forge-bridge 0.1.4-dev.6b2148ecc60c → 0.1.4-dev.724427ea7be8

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 (163) hide show
  1. package/README.md +87 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +5 -2
  3. package/dist/bridge/bridge-chat-provider-command.js +29 -22
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.service.d.ts +16 -12
  15. package/dist/bridge/bridge.service.js +131 -243
  16. package/dist/bridge/bridge.types.d.ts +5 -0
  17. package/dist/bridge/in-flight-registry.d.ts +62 -0
  18. package/dist/bridge/in-flight-registry.js +207 -0
  19. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  20. package/dist/bridge/readiness-result-outbox.js +20 -0
  21. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  22. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  23. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  24. package/dist/cleanup/cleanup-wip.js +66 -0
  25. package/dist/cleanup/cleanup.service.d.ts +11 -1
  26. package/dist/cleanup/cleanup.service.js +80 -62
  27. package/dist/cleanup/cleanup.types.d.ts +2 -0
  28. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  29. package/dist/cleanup/host-runtime-ledger.js +30 -9
  30. package/dist/cli/cli.help.js +56 -12
  31. package/dist/cli/cli.service.d.ts +3 -10
  32. package/dist/cli/cli.service.js +10 -171
  33. package/dist/cli/idle-status.d.ts +84 -0
  34. package/dist/cli/idle-status.js +181 -0
  35. package/dist/cli/local-config.d.ts +2 -0
  36. package/dist/cli/local-config.js +7 -1
  37. package/dist/cli/provider-cli-detection.d.ts +10 -0
  38. package/dist/cli/provider-cli-detection.js +160 -0
  39. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  40. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  41. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  42. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  43. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  44. package/dist/runtime/attempt-process-supervisor.js +12 -6
  45. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  46. package/dist/runtime/docker-engine-probe.js +7 -0
  47. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  48. package/dist/runtime/dotnet-build-outputs.js +402 -0
  49. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  50. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  51. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  52. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  53. package/dist/runtime/host-load-governor.d.ts +2 -0
  54. package/dist/runtime/host-load-ledger-lock.js +6 -4
  55. package/dist/runtime/host-load-runtime-settings.js +4 -2
  56. package/dist/runtime/host-load-sampler.d.ts +8 -1
  57. package/dist/runtime/host-load-sampler.js +14 -7
  58. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  59. package/dist/runtime/host-runtime-contract.js +29 -1
  60. package/dist/runtime/host-runtime-lease.d.ts +2 -1
  61. package/dist/runtime/host-runtime-lease.js +30 -153
  62. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  63. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  64. package/dist/runtime/managed-command-teardown.js +5 -16
  65. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  66. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  67. package/dist/runtime/runner-settings.d.ts +4 -0
  68. package/dist/runtime/runner-settings.js +22 -0
  69. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  70. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  71. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  72. package/dist/sandbox/host-capacity-broker.js +4 -2
  73. package/dist/sandbox/managed-branch.d.ts +13 -0
  74. package/dist/sandbox/managed-branch.js +90 -0
  75. package/dist/sandbox/provider-auth/codex.js +11 -11
  76. package/dist/sandbox/runtime.js +2 -6
  77. package/dist/session/architect-waits.d.ts +2 -0
  78. package/dist/session/architect-waits.js +138 -0
  79. package/dist/session/managed-attempt-tools.d.ts +0 -7
  80. package/dist/session/managed-attempt-tools.js +50 -82
  81. package/dist/session/managed-build-coordinator.d.ts +16 -0
  82. package/dist/session/managed-build-coordinator.js +10 -0
  83. package/dist/session/managed-build-receipt.d.ts +5 -0
  84. package/dist/session/managed-build-receipt.js +8 -3
  85. package/dist/session/phase-completion.artifacts.js +2 -1
  86. package/dist/session/phase-completion.d.ts +8 -0
  87. package/dist/session/phase-completion.js +1 -0
  88. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  89. package/dist/session/phase-completion.mcp-args.js +156 -0
  90. package/dist/session/phase-completion.runtime.d.ts +0 -8
  91. package/dist/session/phase-completion.runtime.js +43 -197
  92. package/dist/session/phase-completion.schemas.js +3 -11
  93. package/dist/session/phase-completion.validation.js +3 -1
  94. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  95. package/dist/session/pre-publication-native-postgres.js +111 -0
  96. package/dist/session/pre-publication-process.js +10 -10
  97. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  98. package/dist/session/pre-publication-step-execution.js +6 -5
  99. package/dist/session/pre-publication-validation.d.ts +7 -3
  100. package/dist/session/pre-publication-validation.js +32 -30
  101. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  102. package/dist/session/provider-cli/claude-background-work.js +4 -3
  103. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  104. package/dist/session/provider-cli/host-build-lock.js +30 -0
  105. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  106. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  107. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  108. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  109. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  110. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  111. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  112. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  113. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  115. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  116. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  117. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  118. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  119. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  120. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  121. package/dist/session/qa-sidecar-validation.js +28 -0
  122. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  123. package/dist/session/sandbox-host-capacity-gate.js +34 -15
  124. package/dist/session/session-redaction.js +31 -181
  125. package/dist/session/session.service.d.ts +2 -0
  126. package/dist/session/session.service.js +69 -64
  127. package/dist/session/session.types.js +1 -1
  128. package/dist/session/sidecar-json-shape.d.ts +31 -0
  129. package/dist/session/sidecar-json-shape.js +217 -0
  130. package/dist/shared/fs/file-identity.d.ts +10 -0
  131. package/dist/shared/fs/file-identity.js +15 -0
  132. package/dist/shared/fs/replace-file.d.ts +7 -0
  133. package/dist/shared/fs/replace-file.js +33 -0
  134. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  135. package/dist/shared/process/host-process-recovery.js +23 -3
  136. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  137. package/dist/shared/process/host-process-supervisor.js +66 -14
  138. package/dist/shared/provider-capabilities.js +9 -1
  139. package/dist/version.d.ts +1 -1
  140. package/dist/version.js +1 -1
  141. package/dist/worktree/orphan-relink.d.ts +19 -0
  142. package/dist/worktree/orphan-relink.js +106 -0
  143. package/dist/worktree/wip-git.d.ts +33 -0
  144. package/dist/worktree/wip-git.js +122 -0
  145. package/dist/worktree/wip-refs.d.ts +62 -0
  146. package/dist/worktree/wip-refs.js +119 -0
  147. package/dist/worktree/wip-restore.d.ts +38 -0
  148. package/dist/worktree/wip-restore.js +190 -0
  149. package/dist/worktree/wip-snapshot.d.ts +50 -0
  150. package/dist/worktree/wip-snapshot.js +268 -0
  151. package/dist/worktree/worktree-inputs.d.ts +8 -0
  152. package/dist/worktree/worktree-inputs.js +134 -0
  153. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  154. package/dist/worktree/worktree-origin-sync.js +127 -0
  155. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  156. package/dist/worktree/worktree-wip-events.js +98 -0
  157. package/dist/worktree/worktree-wip.d.ts +50 -0
  158. package/dist/worktree/worktree-wip.js +185 -0
  159. package/dist/worktree/worktree.base.d.ts +7 -1
  160. package/dist/worktree/worktree.service.d.ts +27 -5
  161. package/dist/worktree/worktree.service.js +110 -181
  162. package/dist/worktree/worktree.types.d.ts +31 -0
  163. package/package.json +1 -1
@@ -1,12 +1,37 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { resolveLocalConfigPath } from "../cli/local-config.js";
4
+ import { DockerEngineProbe } from "./docker-engine-probe.js";
5
+ import { ephemeralTestPostgresClusterEnvironment } from "./ephemeral-test-postgres.js";
4
6
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "./host-runtime-contract.js";
5
7
  export const nativeTestPostgresFallbackConfigEnvironment = "FORGE_NATIVE_TEST_POSTGRES_CONFIG";
6
8
  export const nativeTestPostgresFallbackFileName = "native-test-postgres.json";
7
9
  export const nativeTestPostgresFallbackDatabaseMode = "native_fallback";
10
+ /**
11
+ * The cluster serves the shared test server while Docker is up, so tests that need a
12
+ * pinned engine container still start one. Owner policy (2026-11-16): native PostgreSQL
13
+ * first, which keeps test databases out of the Docker VM and saves RAM.
14
+ */
15
+ export const nativeTestPostgresPreferredDatabaseMode = "native_preferred";
16
+ const nativeTestPostgresUses = ["preferred", "docker_unavailable", "ephemeral"];
8
17
  const defaultPostgresPort = 5432;
9
18
  const loopbackHosts = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
19
+ /**
20
+ * The provisioned cluster's grant for a check that can use it, or null to use Docker. A
21
+ * preferred cluster is granted whether or not Docker is up; the mode says which, because
22
+ * only the fallback mode excludes Docker for pinned-engine tests. An `ephemeral` host
23
+ * normally gets its own cluster instead (ephemeral-test-postgres-grant.ts); if that cannot
24
+ * start, the provisioned cluster serves only while Docker is down, as for `docker_unavailable`.
25
+ */
26
+ export function nativeTestPostgresGrant(fallback, dockerAvailable) {
27
+ if (!fallback || (dockerAvailable && fallback.use !== "preferred"))
28
+ return null;
29
+ return {
30
+ connectionString: fallback.connectionString,
31
+ endpoint: fallback.endpoint,
32
+ mode: dockerAvailable ? nativeTestPostgresPreferredDatabaseMode : nativeTestPostgresFallbackDatabaseMode,
33
+ };
34
+ }
10
35
  export class NativeTestPostgresFallbackError extends Error {
11
36
  code = "native_test_postgres_fallback_invalid";
12
37
  constructor(detail) {
@@ -46,9 +71,17 @@ export function readNativeTestPostgresFallback(configPath = resolveNativeTestPos
46
71
  if (document.schemaVersion !== 1 || typeof document.connectionString !== "string") {
47
72
  throw new NativeTestPostgresFallbackError(`${configPath} must contain schemaVersion 1 and a connectionString.`);
48
73
  }
49
- return parseNativeTestPostgresFallback(document.connectionString);
74
+ if (document.use !== undefined && !nativeTestPostgresUses.includes(document.use)) {
75
+ throw new NativeTestPostgresFallbackError(`${configPath} 'use' must be 'preferred', 'docker_unavailable' or 'ephemeral'.`);
76
+ }
77
+ if (document.postgresBin !== undefined
78
+ && (typeof document.postgresBin !== "string" || !path.isAbsolute(document.postgresBin))) {
79
+ throw new NativeTestPostgresFallbackError(`${configPath} 'postgresBin' must be an absolute path.`);
80
+ }
81
+ const fallback = parseNativeTestPostgresFallback(document.connectionString, document.use ?? "preferred");
82
+ return typeof document.postgresBin === "string" ? { ...fallback, postgresBin: document.postgresBin } : fallback;
50
83
  }
51
- export function parseNativeTestPostgresFallback(connectionString) {
84
+ export function parseNativeTestPostgresFallback(connectionString, use = "preferred") {
52
85
  const fields = new Map();
53
86
  for (const segment of connectionString.split(";")) {
54
87
  const separator = segment.indexOf("=");
@@ -79,13 +112,32 @@ export function parseNativeTestPostgresFallback(connectionString) {
79
112
  if (!(fields.get("username") ?? fields.get("userid") ?? fields.get("user"))) {
80
113
  throw new NativeTestPostgresFallbackError("the fallback must name a dedicated test role.");
81
114
  }
82
- return { connectionString: connectionString.trim(), endpoint: `${host}:${port}` };
115
+ return { connectionString: connectionString.trim(), endpoint: `${host}:${port}`, use };
83
116
  }
84
- /** Environment for one runner-authored .NET test process using the fallback. */
85
- export function nativeTestPostgresFallbackEnvironment(fallback) {
117
+ /** Environment for one runner-authored .NET test process using the cluster. */
118
+ export function nativeTestPostgresFallbackEnvironment(grant) {
86
119
  return {
87
- [hostRuntimeTestPostgresAdminEnvironment]: fallback.connectionString,
88
- [hostRuntimeLegacyTestPostgresEnvironment]: fallback.connectionString,
89
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: nativeTestPostgresFallbackDatabaseMode,
120
+ [hostRuntimeTestPostgresAdminEnvironment]: grant.connectionString,
121
+ [hostRuntimeLegacyTestPostgresEnvironment]: grant.connectionString,
122
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: grant.mode,
123
+ // The fixtures accept a superuser login only on the cluster that reports this id.
124
+ ...(grant.ephemeralClusterId ? { [ephemeralTestPostgresClusterEnvironment]: grant.ephemeralClusterId } : {}),
90
125
  };
91
126
  }
127
+ /**
128
+ * Runner-authored verification uses the operator-provisioned native test cluster,
129
+ * which holds no real data, whenever its file prefers it (the default); Docker then
130
+ * only starts pinned-engine containers. A `docker_unavailable` cluster is used only
131
+ * when the Docker engine is unavailable; otherwise the attempt-owned Testcontainers
132
+ * database serves.
133
+ */
134
+ export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().probeWithoutRecovery()).available, readFallback = () => {
135
+ const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
136
+ return configPath ? readNativeTestPostgresFallback(configPath) : null;
137
+ }) {
138
+ const fallback = readFallback();
139
+ if (!fallback)
140
+ return {};
141
+ const grant = nativeTestPostgresGrant(fallback, await dockerAvailable());
142
+ return grant ? nativeTestPostgresFallbackEnvironment(grant) : {};
143
+ }
@@ -98,3 +98,7 @@ export declare function parseRunnerSettingsDocument(raw: unknown): RunnerSetting
98
98
  export declare function runnerSettingsInForce(report: RunnerSettingsReport, previous: RunnerSettingsReport, failures: readonly RunnerSettingRejection[]): RunnerSettingsReport;
99
99
  /** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
100
100
  export declare function sameRunnerSettingsReport(left: RunnerSettingsReport, right: RunnerSettingsReport): boolean;
101
+ /** The offer refusal message while the runner yields to foreground work. */
102
+ export declare function runnerYieldingMessage(report: RunnerSettingsReport): string;
103
+ /** One line describing the effective settings, for the bridge log. */
104
+ export declare function describeRunnerSettings(report: RunnerSettingsReport): string;
@@ -1,3 +1,4 @@
1
+ import { formatBytes } from "../shared/format/format-bytes.js";
1
2
  import { parseHostLoadGovernorMode } from "./host-load-governor-config.js";
2
3
  // Decision 0014 §3 "Precedence" and §6 "Bridge hub": the server pushes a runner
3
4
  // settings document (`ApplySettings`) and is the source of truth. Host env vars
@@ -212,3 +213,24 @@ function numberEnv(environment, envVar, minimum, maximum) {
212
213
  const parsed = Number(raw);
213
214
  return Number.isFinite(parsed) ? { envVar, value: Math.min(maximum, Math.max(minimum, parsed)) } : null;
214
215
  }
216
+ /** The offer refusal message while the runner yields to foreground work. */
217
+ export function runnerYieldingMessage(report) {
218
+ const where = report.sources.yieldToForeground === "host_local" ? "on this host (forge-bridge yield on)" : "in Forge";
219
+ return `runner_yielding: this runner is yielding to foreground work (turned on ${where}); it takes no new attempts until yield is off. Running attempts continue.`;
220
+ }
221
+ /** One line describing the effective settings, for the bridge log. */
222
+ export function describeRunnerSettings(report) {
223
+ const { values } = report;
224
+ const parts = [
225
+ `max attempts ${values.maxConcurrentAttempts}`,
226
+ `CPU budget ${values.cpuBudgetPercent}%`,
227
+ `yield budget ${values.yieldCpuBudgetPercent}%`,
228
+ `memory reserve ${formatBytes(values.memoryReserveBytes)}`,
229
+ `heavy steps ${values.maxHeavySteps ?? "budget only"}`,
230
+ `yield ${values.yieldToForeground ? "on" : "off"}`,
231
+ ];
232
+ const capped = report.bounds
233
+ .filter(bound => report.sources[bound.key] === "host_env")
234
+ .map(bound => `${bound.envVar}=${bound.value}`);
235
+ return `${parts.join(", ")}${capped.length > 0 ? `; host bounds in force: ${[...new Set(capped)].join(", ")}` : ""}`;
236
+ }
@@ -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";
@@ -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) {
@@ -0,0 +1,2 @@
1
+ export declare function architectNonPassProperties(): Record<string, unknown>;
2
+ export declare function validateArchitectWaits(payload: Record<string, unknown>, status: string): void;