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

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 (260) hide show
  1. package/README.md +128 -4
  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 +15 -0
  11. package/dist/bridge/bridge-state-io.js +68 -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 +29 -12
  17. package/dist/bridge/bridge.service.js +215 -380
  18. package/dist/bridge/bridge.types.d.ts +21 -0
  19. package/dist/bridge/bridge.types.js +2 -1
  20. package/dist/bridge/default-session-service.d.ts +13 -0
  21. package/dist/bridge/default-session-service.js +22 -0
  22. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  23. package/dist/bridge/dispatch-offer-policy.js +58 -0
  24. package/dist/bridge/in-flight-registry.d.ts +62 -0
  25. package/dist/bridge/in-flight-registry.js +207 -0
  26. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  27. package/dist/bridge/readiness-result-outbox.js +20 -0
  28. package/dist/bridge/runner-host-capabilities.js +14 -1
  29. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  30. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  31. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  32. package/dist/bridge/windows-bash-resolution.js +153 -0
  33. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  34. package/dist/cleanup/cleanup-wip.js +66 -0
  35. package/dist/cleanup/cleanup.service.d.ts +11 -1
  36. package/dist/cleanup/cleanup.service.js +80 -62
  37. package/dist/cleanup/cleanup.types.d.ts +2 -0
  38. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  39. package/dist/cleanup/forge-owned-paths.js +9 -0
  40. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  41. package/dist/cleanup/host-runtime-ledger.js +30 -9
  42. package/dist/cli/cli.help.js +57 -13
  43. package/dist/cli/cli.service.d.ts +3 -10
  44. package/dist/cli/cli.service.js +20 -213
  45. package/dist/cli/idle-status.d.ts +84 -0
  46. package/dist/cli/idle-status.js +181 -0
  47. package/dist/cli/local-config.d.ts +14 -1
  48. package/dist/cli/local-config.js +42 -2
  49. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  50. package/dist/cli/provider-cli-advertising.js +88 -0
  51. package/dist/cli/provider-cli-detection.d.ts +10 -0
  52. package/dist/cli/provider-cli-detection.js +160 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  55. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  56. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  57. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  58. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  59. package/dist/runtime/attempt-process-supervisor.js +12 -6
  60. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  61. package/dist/runtime/docker-engine-probe.js +7 -0
  62. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  63. package/dist/runtime/dotnet-build-outputs.js +402 -0
  64. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  66. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  67. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  68. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  69. package/dist/runtime/host-listener-inspector.js +84 -3
  70. package/dist/runtime/host-load-admission.d.ts +5 -0
  71. package/dist/runtime/host-load-capacity.d.ts +198 -0
  72. package/dist/runtime/host-load-capacity.js +353 -0
  73. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  74. package/dist/runtime/host-load-child-environment.js +35 -1
  75. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  76. package/dist/runtime/host-load-governor-config.js +24 -3
  77. package/dist/runtime/host-load-governor.d.ts +91 -2
  78. package/dist/runtime/host-load-governor.js +217 -18
  79. package/dist/runtime/host-load-ledger-lock.js +6 -4
  80. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  81. package/dist/runtime/host-load-live-test-slots.js +193 -0
  82. package/dist/runtime/host-load-runtime-settings.js +4 -2
  83. package/dist/runtime/host-load-sampler.d.ts +25 -1
  84. package/dist/runtime/host-load-sampler.js +38 -7
  85. package/dist/runtime/host-load-step-run.d.ts +37 -3
  86. package/dist/runtime/host-load-step-run.js +63 -7
  87. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  88. package/dist/runtime/host-load-test-slot.js +26 -7
  89. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  90. package/dist/runtime/host-runtime-contract.js +35 -5
  91. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  92. package/dist/runtime/host-runtime-lease.js +140 -296
  93. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  94. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  95. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  96. package/dist/runtime/host-runtime-promotion.js +307 -14
  97. package/dist/runtime/managed-command-teardown.js +5 -16
  98. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  99. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  100. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  101. package/dist/runtime/prepared-runtime-identity.js +130 -9
  102. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  103. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  104. package/dist/runtime/runner-settings.d.ts +4 -0
  105. package/dist/runtime/runner-settings.js +22 -0
  106. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  107. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  108. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  109. package/dist/sandbox/host-capacity-broker.js +4 -2
  110. package/dist/sandbox/managed-branch.d.ts +13 -0
  111. package/dist/sandbox/managed-branch.js +90 -0
  112. package/dist/sandbox/provider-auth/codex.js +11 -11
  113. package/dist/sandbox/runtime.d.ts +1 -2
  114. package/dist/sandbox/runtime.js +9 -19
  115. package/dist/sandbox/sandbox-input.d.ts +22 -0
  116. package/dist/sandbox/sandbox-input.js +49 -0
  117. package/dist/sandbox/workspace.service.js +15 -2
  118. package/dist/session/managed-attempt-tools.d.ts +0 -7
  119. package/dist/session/managed-attempt-tools.js +54 -109
  120. package/dist/session/managed-build-coordinator.d.ts +16 -0
  121. package/dist/session/managed-build-coordinator.js +10 -0
  122. package/dist/session/managed-build-receipt.d.ts +7 -0
  123. package/dist/session/managed-build-receipt.js +11 -3
  124. package/dist/session/managed-command-environment.d.ts +8 -0
  125. package/dist/session/managed-command-environment.js +28 -0
  126. package/dist/session/managed-command-host-load.d.ts +10 -5
  127. package/dist/session/managed-command-host-load.js +18 -14
  128. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  129. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  130. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  131. package/dist/session/phase-completion.artifacts.js +65 -166
  132. package/dist/session/phase-completion.d.ts +27 -2
  133. package/dist/session/phase-completion.helpers.js +5 -53
  134. package/dist/session/phase-completion.js +15 -32
  135. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  136. package/dist/session/phase-completion.mcp-args.js +195 -0
  137. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  138. package/dist/session/phase-completion.phase-aliases.js +43 -0
  139. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  140. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  141. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  142. package/dist/session/phase-completion.pr-review-validation.js +212 -0
  143. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  144. package/dist/session/phase-completion.pr-review.js +294 -0
  145. package/dist/session/phase-completion.prompts.d.ts +1 -1
  146. package/dist/session/phase-completion.prompts.js +14 -0
  147. package/dist/session/phase-completion.runtime.d.ts +8 -9
  148. package/dist/session/phase-completion.runtime.js +65 -196
  149. package/dist/session/phase-completion.schemas.js +12 -2
  150. package/dist/session/phase-completion.validation.d.ts +1 -0
  151. package/dist/session/phase-completion.validation.js +9 -1
  152. package/dist/session/pr-review-diff-base.d.ts +18 -0
  153. package/dist/session/pr-review-diff-base.js +44 -0
  154. package/dist/session/pr-review-placement.d.ts +50 -0
  155. package/dist/session/pr-review-placement.js +91 -0
  156. package/dist/session/pre-publication-change-set.d.ts +62 -0
  157. package/dist/session/pre-publication-change-set.js +166 -0
  158. package/dist/session/pre-publication-host-load.js +6 -5
  159. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  160. package/dist/session/pre-publication-native-postgres.js +111 -0
  161. package/dist/session/pre-publication-process.js +13 -12
  162. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  163. package/dist/session/pre-publication-step-execution.js +6 -5
  164. package/dist/session/pre-publication-validation.d.ts +9 -4
  165. package/dist/session/pre-publication-validation.js +62 -65
  166. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  167. package/dist/session/provider-cli/claude-background-work.js +4 -3
  168. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  169. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  170. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  171. package/dist/session/provider-cli/host-build-lock.js +30 -0
  172. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  173. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  174. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  175. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  176. package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
  177. package/dist/session/provider-cli/pr-review-prompt.js +119 -0
  178. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  179. package/dist/session/provider-cli/pre-publication-repair.js +41 -3
  180. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  181. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  182. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  183. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  184. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  185. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  186. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  188. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  189. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  190. package/dist/session/provider-cli/provider-cli.prompts.d.ts +13 -3
  191. package/dist/session/provider-cli/provider-cli.prompts.js +137 -84
  192. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  193. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +37 -2
  196. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  197. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  198. package/dist/session/provider-cli/provider-cli.service.d.ts +15 -18
  199. package/dist/session/provider-cli/provider-cli.service.js +59 -190
  200. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  204. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  205. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  206. package/dist/session/qa-sidecar-validation.js +28 -0
  207. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  208. package/dist/session/sandbox-host-capacity-gate.js +63 -22
  209. package/dist/session/session-host-project.d.ts +22 -0
  210. package/dist/session/session-host-project.js +98 -0
  211. package/dist/session/session-redaction.js +31 -181
  212. package/dist/session/session.parse-helpers.d.ts +10 -0
  213. package/dist/session/session.parse-helpers.js +84 -0
  214. package/dist/session/session.runtime-refresh.d.ts +46 -0
  215. package/dist/session/session.runtime-refresh.js +116 -0
  216. package/dist/session/session.service.d.ts +8 -1
  217. package/dist/session/session.service.js +177 -239
  218. package/dist/session/session.types.d.ts +5 -0
  219. package/dist/session/session.types.js +9 -79
  220. package/dist/session/session.types.pr-review.d.ts +48 -0
  221. package/dist/session/session.types.pr-review.js +51 -0
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/shared/fs/file-identity.d.ts +10 -0
  225. package/dist/shared/fs/file-identity.js +15 -0
  226. package/dist/shared/fs/replace-file.d.ts +7 -0
  227. package/dist/shared/fs/replace-file.js +33 -0
  228. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  229. package/dist/shared/process/host-process-recovery.js +23 -3
  230. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  231. package/dist/shared/process/host-process-supervisor.js +66 -14
  232. package/dist/shared/provider-capabilities.d.ts +2 -0
  233. package/dist/shared/provider-capabilities.js +18 -1
  234. package/dist/version.d.ts +1 -1
  235. package/dist/version.js +1 -1
  236. package/dist/worktree/artifact-injector.js +24 -0
  237. package/dist/worktree/orphan-relink.d.ts +19 -0
  238. package/dist/worktree/orphan-relink.js +106 -0
  239. package/dist/worktree/wip-git.d.ts +58 -0
  240. package/dist/worktree/wip-git.js +182 -0
  241. package/dist/worktree/wip-refs.d.ts +85 -0
  242. package/dist/worktree/wip-refs.js +169 -0
  243. package/dist/worktree/wip-restore.d.ts +51 -0
  244. package/dist/worktree/wip-restore.js +324 -0
  245. package/dist/worktree/wip-snapshot.d.ts +53 -0
  246. package/dist/worktree/wip-snapshot.js +270 -0
  247. package/dist/worktree/worktree-inputs.d.ts +8 -0
  248. package/dist/worktree/worktree-inputs.js +134 -0
  249. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  250. package/dist/worktree/worktree-origin-sync.js +128 -0
  251. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  252. package/dist/worktree/worktree-wip-events.js +148 -0
  253. package/dist/worktree/worktree-wip.d.ts +57 -0
  254. package/dist/worktree/worktree-wip.js +200 -0
  255. package/dist/worktree/worktree.base.d.ts +7 -1
  256. package/dist/worktree/worktree.service.d.ts +49 -5
  257. package/dist/worktree/worktree.service.js +223 -187
  258. package/dist/worktree/worktree.types.d.ts +47 -0
  259. package/package.json +1 -1
  260. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -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
  }
@@ -2,6 +2,7 @@ import type { BridgeServiceConfig } from "../bridge/bridge.types.js";
2
2
  import type { SessionEventSink } from "../session/session.base.js";
3
3
  import { type RunOnceDispatchPacket, type RunOnceResultPacket } from "../session/session.types.js";
4
4
  import type { SandboxService, ValidatedSandboxContract } from "./sandbox.types.js";
5
+ export { selectSandboxInputRefs } from "./sandbox-input.js";
5
6
  import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
6
7
  import { type RuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
7
8
  export interface SandboxRuntime {
@@ -169,7 +170,6 @@ export declare function selectSandboxConfigRefs(executionPolicy: string, configu
169
170
  readonly refs: readonly string[];
170
171
  readonly approvedSha: string | null;
171
172
  };
172
- export declare function selectSandboxInputRefs(worktreeKey: string, baseBranch: string): readonly string[];
173
173
  export declare function sandboxTimeLimits(environment?: NodeJS.ProcessEnv): {
174
174
  readonly hardWallMs: number;
175
175
  readonly idleMs: number;
@@ -308,4 +308,3 @@ export declare function classifySandboxResourceFailure(value: string): {
308
308
  readonly code: string;
309
309
  readonly message: string;
310
310
  } | null;
311
- export {};
@@ -5,6 +5,8 @@ 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, resolveReviewDiffBase, resolveSandboxInputCommit, reviewOnlySandboxOutput, sandboxPublicationAllowed, withReviewDiffBase } from "./sandbox-input.js";
9
+ export { selectSandboxInputRefs } from "./sandbox-input.js";
8
10
  import { createLeaseUpdate } from "./lease-watchdog.js";
9
11
  import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
10
12
  import { SandboxEventBudget } from "./event-budget.js";
@@ -110,7 +112,7 @@ export class DockerSandboxRuntime {
110
112
  const securityOptions = resolveSandboxSecurityOptions(dispatch.sandbox.executionPolicy);
111
113
  const builtImage = await this.buildImage(prepared.contextRoot, prepared.contextDigest, dispatch.repo.name, validated, upstreamImages, dispatch.sandbox.executionPolicy, sink, runtimeSignal);
112
114
  const imageDigest = builtImage.imageDigest;
113
- const runtimeDispatch = withSandboxMetadata(dispatch, prepared.inputCommitSha, prepared.configCommitSha, validated.digest, imageDigest);
115
+ const runtimeDispatch = withReviewDiffBase(withSandboxMetadata(dispatch, prepared.inputCommitSha, prepared.configCommitSha, validated.digest, imageDigest), prepared.reviewDiffBase);
114
116
  const providerAuthAdapter = sandboxProviderAuthAdapterFor(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
115
117
  const providerAuthUnavailable = sandboxProviderAuthUnavailableMessage(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
116
118
  if (providerAuthUnavailable) {
@@ -169,7 +171,7 @@ export class DockerSandboxRuntime {
169
171
  const brokered = this.hostLoadGate?.enabled === true;
170
172
  const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
171
173
  const createArgs = brokered
172
- ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs)
174
+ ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxTotalWaitMs)
173
175
  : workerArgs;
174
176
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
175
177
  const containerId = dockerObjectId(createdContainer.stdout, "container");
@@ -275,7 +277,7 @@ export class DockerSandboxRuntime {
275
277
  await this.docker(["cp", `${containerId}:/control/output/.`, path.join(attemptRoot, "output")], 60_000);
276
278
  let output;
277
279
  try {
278
- output = await validateOutput(attemptRoot, runtimeDispatch);
280
+ output = reviewOnlySandboxOutput(runtimeDispatch, await validateOutput(attemptRoot, runtimeDispatch));
279
281
  }
280
282
  catch (error) {
281
283
  if (start.exitCode !== 0 && isMissingSandboxManifest(error)) {
@@ -284,7 +286,7 @@ export class DockerSandboxRuntime {
284
286
  throw error;
285
287
  }
286
288
  await git.importResult(runtimeDispatch, output, () => assertSandboxImportCurrent(active, this.active.get(active.dispatchAttemptId), controller.signal));
287
- if (runtimeDispatch.sandbox.publicationMode === "bridge_push") {
289
+ if (sandboxPublicationAllowed(runtimeDispatch)) {
288
290
  const handle = runtimeDispatch.sandbox.publishGrantHandle;
289
291
  if (!handle || !output.manifest.resultCommitSha || !this.publicationGrantRedeemer) {
290
292
  throw trustedSandboxFailure("sandbox_output_publish_forbidden", "bridge publication grant redemption is unavailable.");
@@ -1165,7 +1167,7 @@ class HostGit {
1165
1167
  async prepareLocked(dispatch, attemptRoot) {
1166
1168
  const baseBranch = dispatch.cycleRun.baseBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch;
1167
1169
  await this.git(["fetch", "--prune", "origin"], 5 * 60_000).catch(() => null);
1168
- const inputCommitSha = await this.resolveFirst([...selectSandboxInputRefs(dispatch.lease.worktreeKey, baseBranch)]);
1170
+ const [inputCommitSha, reviewDiffBase] = [await resolveSandboxInputCommit(dispatch, baseBranch, (refs) => this.resolveFirst(refs), (args) => this.git(args, 5 * 60_000)), await resolveReviewDiffBase(dispatch, async (args) => (await this.git(args, 5 * 60_000)).stdout)];
1169
1171
  const configSelection = selectSandboxConfigRefs(dispatch.sandbox.executionPolicy, dispatch.sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
1170
1172
  const configCommitSha = await this.resolveFirst([...configSelection.refs]);
1171
1173
  const approvedConfigSha = configSelection.approvedSha;
@@ -1189,7 +1191,7 @@ class HostGit {
1189
1191
  await fs.mkdir(contextRoot, { recursive: true });
1190
1192
  await requireSandboxProcess({ command: "tar", args: ["-xf", contextArchive, "-C", contextRoot], timeoutMs: 5 * 60_000, maxOutputBytes: 1024 * 1024 });
1191
1193
  const contextDigest = createHash("sha256").update(await fs.readFile(contextArchive)).digest("hex");
1192
- return { inputCommitSha, configCommitSha, contractSource, dockerfile, bundlePath, contextRoot, contextDigest };
1194
+ return { inputCommitSha, reviewDiffBase, configCommitSha, contractSource, dockerfile, bundlePath, contextRoot, contextDigest };
1193
1195
  }
1194
1196
  async importResult(dispatch, output, assertCurrent) {
1195
1197
  await this.coordinator.withLock(this.repoPath, () => this.importResultLocked(dispatch, output, assertCurrent));
@@ -1276,12 +1278,7 @@ class HostGit {
1276
1278
  await this.git(["update-ref", branchRef, imported, managedBranchUpdateExpectedValue(current, expected, imported)], 30_000);
1277
1279
  return;
1278
1280
  }
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 });
1281
+ await advanceCheckedOutBranch({ repoPath: this.repoPath, worktreePath: checkedOut.path, branchRef, expected, imported });
1285
1282
  }
1286
1283
  async resolveFirst(refs) {
1287
1284
  for (const ref of refs) {
@@ -1425,13 +1422,6 @@ export function selectSandboxConfigRefs(executionPolicy, configuredSha, defaultB
1425
1422
  ? { refs: [approvedSha], approvedSha }
1426
1423
  : { refs: [`refs/heads/${defaultBranch}`, `refs/remotes/origin/${defaultBranch}`], approvedSha: null };
1427
1424
  }
1428
- export function selectSandboxInputRefs(worktreeKey, baseBranch) {
1429
- return [
1430
- `refs/heads/${worktreeKey}`,
1431
- `refs/heads/${baseBranch}`,
1432
- `refs/remotes/origin/${baseBranch}`
1433
- ];
1434
- }
1435
1425
  export function sandboxTimeLimits(environment = process.env) {
1436
1426
  const hardWallSeconds = boundedInteger(environment.FORGE_SANDBOX_HARD_WALL_SECONDS, 8 * 60 * 60, 60, 8 * 60 * 60);
1437
1427
  const idleSeconds = boundedInteger(environment.FORGE_SANDBOX_IDLE_SECONDS, 10 * 60, 60, hardWallSeconds);
@@ -0,0 +1,22 @@
1
+ export { advanceCheckedOutBranch } from "./managed-branch.js";
2
+ export { resolveReviewDiffBase, withReviewDiffBase } from "../session/pr-review-diff-base.js";
3
+ import { type RunOnceDispatchPacket } from "../session/session.types.js";
4
+ export declare function selectSandboxInputRefs(worktreeKey: string, baseBranch: string): readonly string[];
5
+ /**
6
+ * The commit a Docker attempt starts from. A Forge PR review reads exactly the dispatched pull request
7
+ * head, fetched from origin by its SHA when the host checkout doesn't have it yet; every other attempt
8
+ * starts from its managed branch or its base. Never a branch name for a review: the head is a full SHA.
9
+ */
10
+ export declare function resolveSandboxInputCommit(dispatch: RunOnceDispatchPacket, baseBranch: string, resolveFirst: (refs: string[]) => Promise<string>, fetchFromOrigin: (args: readonly string[]) => Promise<unknown>): Promise<string>;
11
+ /**
12
+ * A review publishes nothing: whatever the container's HEAD is, the attempt has no result commit, so the
13
+ * host neither imports a bundle into a branch nor pushes one.
14
+ */
15
+ export declare function reviewOnlySandboxOutput<T extends {
16
+ readonly bundlePath: string | null;
17
+ readonly manifest: {
18
+ readonly resultCommitSha: string | null;
19
+ };
20
+ }>(dispatch: RunOnceDispatchPacket, output: T): T;
21
+ /** Whether the host may publish this attempt's result: never for a review, whatever mode it was offered. */
22
+ export declare function sandboxPublicationAllowed(dispatch: RunOnceDispatchPacket): boolean;
@@ -0,0 +1,49 @@
1
+ // The host side of a sandbox attempt's git state: the commit it starts from, whether its result comes back
2
+ // and is published, and how an imported result moves its managed branch (managed-branch.ts).
3
+ export { advanceCheckedOutBranch } from "./managed-branch.js";
4
+ // A review's diff base is in its bundle: the merge base is an ancestor of the head the bundle carries.
5
+ export { resolveReviewDiffBase, withReviewDiffBase } from "../session/pr-review-diff-base.js";
6
+ import { prReviewDispatchHeadSha } from "../session/pr-review-placement.js";
7
+ import { ForgeFailureError } from "../session/session.types.js";
8
+ export function selectSandboxInputRefs(worktreeKey, baseBranch) {
9
+ return [
10
+ `refs/heads/${worktreeKey}`,
11
+ `refs/heads/${baseBranch}`,
12
+ `refs/remotes/origin/${baseBranch}`
13
+ ];
14
+ }
15
+ /**
16
+ * The commit a Docker attempt starts from. A Forge PR review reads exactly the dispatched pull request
17
+ * head, fetched from origin by its SHA when the host checkout doesn't have it yet; every other attempt
18
+ * starts from its managed branch or its base. Never a branch name for a review: the head is a full SHA.
19
+ */
20
+ export async function resolveSandboxInputCommit(dispatch, baseBranch, resolveFirst, fetchFromOrigin) {
21
+ const reviewHead = prReviewDispatchHeadSha(dispatch);
22
+ if (!reviewHead) {
23
+ return await resolveFirst([...selectSandboxInputRefs(dispatch.lease.worktreeKey, baseBranch)]);
24
+ }
25
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(reviewHead)) {
26
+ throw new ForgeFailureError("sandbox_input_failed", "sandbox_input_failed: the pull request review head is not a full Git object id.", "sandbox");
27
+ }
28
+ const resolved = await resolveFirst([reviewHead]).catch(async () => {
29
+ await fetchFromOrigin(["fetch", "--no-tags", "--no-write-fetch-head", "origin", reviewHead]).catch(() => undefined);
30
+ return await resolveFirst([reviewHead]);
31
+ });
32
+ if (resolved.toLowerCase() !== reviewHead) {
33
+ throw new ForgeFailureError("sandbox_input_failed", "sandbox_input_failed: the resolved review input is not the dispatched pull request head.", "sandbox");
34
+ }
35
+ return resolved;
36
+ }
37
+ /**
38
+ * A review publishes nothing: whatever the container's HEAD is, the attempt has no result commit, so the
39
+ * host neither imports a bundle into a branch nor pushes one.
40
+ */
41
+ export function reviewOnlySandboxOutput(dispatch, output) {
42
+ return prReviewDispatchHeadSha(dispatch) === null
43
+ ? output
44
+ : { ...output, bundlePath: null, manifest: { ...output.manifest, resultCommitSha: null } };
45
+ }
46
+ /** Whether the host may publish this attempt's result: never for a review, whatever mode it was offered. */
47
+ export function sandboxPublicationAllowed(dispatch) {
48
+ return dispatch.sandbox?.publicationMode === "bridge_push" && prReviewDispatchHeadSha(dispatch) === null;
49
+ }
@@ -33,7 +33,19 @@ export class SandboxWorkspaceService {
33
33
  if (actualSha.toLowerCase() !== this.inputCommitSha.toLowerCase())
34
34
  throw new Error("Imported bundle does not contain the exact recorded input commit.");
35
35
  const branchName = normalizeBranchName(request.worktreeKey, `forge/${request.workItem.id.replace(/-/g, "")}`);
36
- await this.git.run(this.workspace, ["checkout", "-B", branchName, this.inputCommitSha]);
36
+ const reviewHeadSha = request.detachedHeadSha?.trim().toLowerCase();
37
+ if (reviewHeadSha) {
38
+ // A review reads exactly the dispatched pull request head, detached; the bundle must carry it.
39
+ if (reviewHeadSha !== this.inputCommitSha.toLowerCase())
40
+ throw new Error("Sandbox input commit is not the review head.");
41
+ await this.git.run(this.workspace, ["checkout", "--detach", this.inputCommitSha]);
42
+ const detachedHead = (await this.git.run(this.workspace, ["rev-parse", "HEAD"])).trim().toLowerCase();
43
+ if (detachedHead !== reviewHeadSha)
44
+ throw new Error("Sandbox review worktree is not at the review head.");
45
+ }
46
+ else {
47
+ await this.git.run(this.workspace, ["checkout", "-B", branchName, this.inputCommitSha]);
48
+ }
37
49
  await this.git.run(this.workspace, ["config", "user.email", "forge-agent@forge.local"]);
38
50
  await this.git.run(this.workspace, ["config", "user.name", "Forge Agent"]);
39
51
  await this.git.run(this.workspace, ["config", "core.hooksPath", "/dev/null"]);
@@ -54,7 +66,8 @@ export class SandboxWorkspaceService {
54
66
  branchName,
55
67
  baseBranch: request.baseBranch,
56
68
  cleanupWorktrees: false,
57
- hydratedPriorPhaseArtifactCount
69
+ hydratedPriorPhaseArtifactCount,
70
+ ...(reviewHeadSha ? { detachedHeadSha: reviewHeadSha } : {})
58
71
  };
59
72
  }
60
73
  async release(_handle) {
@@ -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 {};