@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.0f8fb73715e8

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 (329) hide show
  1. package/README.md +183 -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 +40 -0
  5. package/dist/bridge/bridge-chat-provider-command.js +230 -0
  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.base.d.ts +9 -0
  17. package/dist/bridge/bridge.service.d.ts +102 -14
  18. package/dist/bridge/bridge.service.js +499 -471
  19. package/dist/bridge/bridge.types.d.ts +37 -0
  20. package/dist/bridge/bridge.types.js +2 -1
  21. package/dist/bridge/default-session-service.d.ts +13 -0
  22. package/dist/bridge/default-session-service.js +22 -0
  23. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  24. package/dist/bridge/dispatch-offer-policy.js +58 -0
  25. package/dist/bridge/in-flight-registry.d.ts +62 -0
  26. package/dist/bridge/in-flight-registry.js +207 -0
  27. package/dist/bridge/local-yield-flag.d.ts +6 -0
  28. package/dist/bridge/local-yield-flag.js +34 -0
  29. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  30. package/dist/bridge/readiness-result-outbox.js +20 -0
  31. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  32. package/dist/bridge/runner-host-capabilities.js +31 -1
  33. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  34. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  35. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  36. package/dist/bridge/test-postgres-capability.js +120 -0
  37. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  38. package/dist/bridge/windows-bash-resolution.js +153 -0
  39. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  40. package/dist/cleanup/cleanup-wip.js +66 -0
  41. package/dist/cleanup/cleanup.service.d.ts +20 -1
  42. package/dist/cleanup/cleanup.service.js +150 -169
  43. package/dist/cleanup/cleanup.types.d.ts +6 -0
  44. package/dist/cleanup/forge-owned-paths.d.ts +11 -0
  45. package/dist/cleanup/forge-owned-paths.js +62 -0
  46. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  47. package/dist/cleanup/host-runtime-ledger.js +130 -0
  48. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  49. package/dist/cleanup/managed-branch-sweep.js +111 -0
  50. package/dist/cli/cli.help.js +75 -13
  51. package/dist/cli/cli.service.d.ts +19 -10
  52. package/dist/cli/cli.service.js +161 -228
  53. package/dist/cli/idle-status.d.ts +84 -0
  54. package/dist/cli/idle-status.js +181 -0
  55. package/dist/cli/local-config.d.ts +18 -1
  56. package/dist/cli/local-config.js +67 -5
  57. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  58. package/dist/cli/provider-cli-advertising.js +88 -0
  59. package/dist/cli/provider-cli-detection.d.ts +10 -0
  60. package/dist/cli/provider-cli-detection.js +160 -0
  61. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  62. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  63. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  64. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  65. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  66. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  67. package/dist/runtime/attempt-process-supervisor.js +12 -6
  68. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  69. package/dist/runtime/docker-engine-probe.js +7 -0
  70. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  71. package/dist/runtime/dotnet-build-outputs.js +402 -0
  72. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  73. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  74. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  75. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  76. package/dist/runtime/host-facts.d.ts +2 -1
  77. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  78. package/dist/runtime/host-listener-inspector.js +84 -3
  79. package/dist/runtime/host-load-admission.d.ts +72 -0
  80. package/dist/runtime/host-load-admission.js +99 -0
  81. package/dist/runtime/host-load-capacity.d.ts +198 -0
  82. package/dist/runtime/host-load-capacity.js +353 -0
  83. package/dist/runtime/host-load-child-environment.d.ts +40 -0
  84. package/dist/runtime/host-load-child-environment.js +110 -0
  85. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  86. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  87. package/dist/runtime/host-load-governor-config.d.ts +82 -0
  88. package/dist/runtime/host-load-governor-config.js +104 -0
  89. package/dist/runtime/host-load-governor.d.ts +273 -0
  90. package/dist/runtime/host-load-governor.js +831 -0
  91. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  92. package/dist/runtime/host-load-ledger-lock.js +187 -0
  93. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  94. package/dist/runtime/host-load-live-test-slots.js +193 -0
  95. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  96. package/dist/runtime/host-load-runtime-settings.js +80 -0
  97. package/dist/runtime/host-load-sampler.d.ts +92 -2
  98. package/dist/runtime/host-load-sampler.js +166 -8
  99. package/dist/runtime/host-load-step-class.d.ts +70 -0
  100. package/dist/runtime/host-load-step-class.js +161 -0
  101. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  102. package/dist/runtime/host-load-step-reaper.js +95 -0
  103. package/dist/runtime/host-load-step-run.d.ts +107 -0
  104. package/dist/runtime/host-load-step-run.js +158 -0
  105. package/dist/runtime/host-load-test-slot.d.ts +46 -0
  106. package/dist/runtime/host-load-test-slot.js +100 -0
  107. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  108. package/dist/runtime/host-load-token-ledger.js +453 -0
  109. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  110. package/dist/runtime/host-load-windows-cpu.js +85 -0
  111. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  112. package/dist/runtime/host-pressure-stall.js +48 -1
  113. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  114. package/dist/runtime/host-runtime-contract.js +39 -6
  115. package/dist/runtime/host-runtime-lease.d.ts +101 -6
  116. package/dist/runtime/host-runtime-lease.js +408 -294
  117. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  118. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  119. package/dist/runtime/host-runtime-promotion.d.ts +101 -2
  120. package/dist/runtime/host-runtime-promotion.js +355 -14
  121. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  122. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  123. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  124. package/dist/runtime/host-runtime-requirements.js +117 -0
  125. package/dist/runtime/managed-command-teardown.js +5 -16
  126. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  127. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  128. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  129. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  130. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  131. package/dist/runtime/prepared-runtime-identity.js +130 -9
  132. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  133. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  134. package/dist/runtime/runner-settings.d.ts +104 -0
  135. package/dist/runtime/runner-settings.js +236 -0
  136. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  137. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  138. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  139. package/dist/sandbox/host-capacity-broker.js +336 -0
  140. package/dist/sandbox/managed-branch.d.ts +13 -0
  141. package/dist/sandbox/managed-branch.js +90 -0
  142. package/dist/sandbox/provider-auth/codex.js +11 -11
  143. package/dist/sandbox/runtime.d.ts +11 -3
  144. package/dist/sandbox/runtime.js +53 -20
  145. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  146. package/dist/sandbox/sandbox-cgroups.js +42 -0
  147. package/dist/sandbox/sandbox-input.d.ts +22 -0
  148. package/dist/sandbox/sandbox-input.js +49 -0
  149. package/dist/sandbox/workspace.service.js +15 -2
  150. package/dist/session/architect-waits.d.ts +2 -0
  151. package/dist/session/architect-waits.js +138 -0
  152. package/dist/session/managed-attempt-tools.d.ts +2 -7
  153. package/dist/session/managed-attempt-tools.js +204 -141
  154. package/dist/session/managed-build-coordinator.d.ts +16 -0
  155. package/dist/session/managed-build-coordinator.js +10 -0
  156. package/dist/session/managed-build-receipt.d.ts +7 -0
  157. package/dist/session/managed-build-receipt.js +11 -3
  158. package/dist/session/managed-command-environment.d.ts +8 -0
  159. package/dist/session/managed-command-environment.js +28 -0
  160. package/dist/session/managed-command-host-load.d.ts +52 -0
  161. package/dist/session/managed-command-host-load.js +87 -0
  162. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  163. package/dist/session/mcp-argument-coercion.js +121 -0
  164. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  165. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  166. package/dist/session/phase-completion.artifacts.d.ts +9 -17
  167. package/dist/session/phase-completion.artifacts.js +158 -190
  168. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  169. package/dist/session/phase-completion.command-validation.js +77 -0
  170. package/dist/session/phase-completion.d.ts +31 -2
  171. package/dist/session/phase-completion.helpers.js +18 -65
  172. package/dist/session/phase-completion.js +19 -32
  173. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  174. package/dist/session/phase-completion.mcp-args.js +195 -0
  175. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  176. package/dist/session/phase-completion.phase-aliases.js +43 -0
  177. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  178. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  179. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  180. package/dist/session/phase-completion.pr-review-validation.js +212 -0
  181. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  182. package/dist/session/phase-completion.pr-review.js +294 -0
  183. package/dist/session/phase-completion.prompts.d.ts +1 -1
  184. package/dist/session/phase-completion.prompts.js +20 -1
  185. package/dist/session/phase-completion.runtime.d.ts +13 -12
  186. package/dist/session/phase-completion.runtime.js +113 -214
  187. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  188. package/dist/session/phase-completion.schema-parts.js +188 -0
  189. package/dist/session/phase-completion.schemas.d.ts +3 -3
  190. package/dist/session/phase-completion.schemas.js +219 -232
  191. package/dist/session/phase-completion.validation.d.ts +3 -3
  192. package/dist/session/phase-completion.validation.js +58 -94
  193. package/dist/session/pr-review-diff-base.d.ts +18 -0
  194. package/dist/session/pr-review-diff-base.js +44 -0
  195. package/dist/session/pr-review-placement.d.ts +50 -0
  196. package/dist/session/pr-review-placement.js +91 -0
  197. package/dist/session/pre-publication-change-set.d.ts +62 -0
  198. package/dist/session/pre-publication-change-set.js +166 -0
  199. package/dist/session/pre-publication-host-load.d.ts +27 -0
  200. package/dist/session/pre-publication-host-load.js +112 -0
  201. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  202. package/dist/session/pre-publication-native-postgres.js +111 -0
  203. package/dist/session/pre-publication-pass.d.ts +61 -0
  204. package/dist/session/pre-publication-pass.js +148 -0
  205. package/dist/session/pre-publication-process.d.ts +3 -0
  206. package/dist/session/pre-publication-process.js +32 -19
  207. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  208. package/dist/session/pre-publication-step-execution.js +50 -0
  209. package/dist/session/pre-publication-validation.d.ts +39 -22
  210. package/dist/session/pre-publication-validation.js +241 -207
  211. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  212. package/dist/session/provider-cli/claude-background-work.js +181 -0
  213. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  214. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  215. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  216. package/dist/session/provider-cli/host-build-lock.js +30 -0
  217. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  218. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  219. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  220. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  221. package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
  222. package/dist/session/provider-cli/pr-review-prompt.js +119 -0
  223. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  224. package/dist/session/provider-cli/pre-publication-repair.js +281 -0
  225. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  226. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  227. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  228. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  229. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  230. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  231. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  232. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  233. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  234. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  235. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  236. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  237. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  238. package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -3
  239. package/dist/session/provider-cli/provider-cli.prompts.js +183 -90
  240. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  241. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  242. package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
  243. package/dist/session/provider-cli/provider-cli.runtime.js +43 -1
  244. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  245. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  246. package/dist/session/provider-cli/provider-cli.service.d.ts +18 -18
  247. package/dist/session/provider-cli/provider-cli.service.js +127 -317
  248. package/dist/session/provider-cli/provider-cli.types.d.ts +35 -0
  249. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  250. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  251. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  252. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  253. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  254. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  255. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  256. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  257. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  258. package/dist/session/provider-cli/provider-output-state.js +6 -0
  259. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  260. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  261. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  262. package/dist/session/qa-sidecar-validation.js +28 -0
  263. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  264. package/dist/session/sandbox-host-capacity-gate.js +279 -0
  265. package/dist/session/session-host-project.d.ts +22 -0
  266. package/dist/session/session-host-project.js +98 -0
  267. package/dist/session/session-redaction.js +31 -181
  268. package/dist/session/session.base.d.ts +9 -1
  269. package/dist/session/session.parse-helpers.d.ts +10 -0
  270. package/dist/session/session.parse-helpers.js +84 -0
  271. package/dist/session/session.runtime-refresh.d.ts +46 -0
  272. package/dist/session/session.runtime-refresh.js +116 -0
  273. package/dist/session/session.service.d.ts +16 -2
  274. package/dist/session/session.service.js +208 -155
  275. package/dist/session/session.types.d.ts +8 -0
  276. package/dist/session/session.types.js +13 -83
  277. package/dist/session/session.types.pr-review.d.ts +48 -0
  278. package/dist/session/session.types.pr-review.js +51 -0
  279. package/dist/session/sidecar-json-shape.d.ts +31 -0
  280. package/dist/session/sidecar-json-shape.js +217 -0
  281. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  282. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  283. package/dist/shared/fs/file-identity.d.ts +10 -0
  284. package/dist/shared/fs/file-identity.js +15 -0
  285. package/dist/shared/fs/replace-file.d.ts +7 -0
  286. package/dist/shared/fs/replace-file.js +33 -0
  287. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  288. package/dist/shared/process/host-process-recovery.js +23 -3
  289. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  290. package/dist/shared/process/host-process-supervisor.js +67 -15
  291. package/dist/shared/process/process-tree.d.ts +52 -0
  292. package/dist/shared/process/process-tree.js +144 -0
  293. package/dist/shared/process/process.d.ts +67 -0
  294. package/dist/shared/process/process.js +213 -11
  295. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  296. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  297. package/dist/shared/process/windows-launch.d.ts +18 -0
  298. package/dist/shared/process/windows-launch.js +68 -0
  299. package/dist/shared/provider-capabilities.d.ts +2 -0
  300. package/dist/shared/provider-capabilities.js +23 -7
  301. package/dist/version.d.ts +1 -1
  302. package/dist/version.js +1 -1
  303. package/dist/worktree/artifact-injector.js +24 -0
  304. package/dist/worktree/dependency-warmer.d.ts +25 -0
  305. package/dist/worktree/dependency-warmer.js +46 -10
  306. package/dist/worktree/orphan-relink.d.ts +19 -0
  307. package/dist/worktree/orphan-relink.js +106 -0
  308. package/dist/worktree/wip-git.d.ts +58 -0
  309. package/dist/worktree/wip-git.js +182 -0
  310. package/dist/worktree/wip-refs.d.ts +85 -0
  311. package/dist/worktree/wip-refs.js +169 -0
  312. package/dist/worktree/wip-restore.d.ts +51 -0
  313. package/dist/worktree/wip-restore.js +324 -0
  314. package/dist/worktree/wip-snapshot.d.ts +53 -0
  315. package/dist/worktree/wip-snapshot.js +270 -0
  316. package/dist/worktree/worktree-inputs.d.ts +8 -0
  317. package/dist/worktree/worktree-inputs.js +134 -0
  318. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  319. package/dist/worktree/worktree-origin-sync.js +128 -0
  320. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  321. package/dist/worktree/worktree-wip-events.js +148 -0
  322. package/dist/worktree/worktree-wip.d.ts +57 -0
  323. package/dist/worktree/worktree-wip.js +200 -0
  324. package/dist/worktree/worktree.base.d.ts +7 -1
  325. package/dist/worktree/worktree.service.d.ts +58 -5
  326. package/dist/worktree/worktree.service.js +237 -161
  327. package/dist/worktree/worktree.types.d.ts +54 -0
  328. package/package.json +2 -2
  329. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -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,8 @@ 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";
6
+ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
5
7
  import { type RuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
6
8
  export interface SandboxRuntime {
7
9
  runOnce(dispatch: RunOnceDispatchPacket, sink: SessionEventSink, signal?: AbortSignal): Promise<RunOnceResultPacket>;
@@ -87,12 +89,18 @@ export type SandboxPublicationGrantRedeemer = (request: SandboxPublicationGrantR
87
89
  export declare class DockerSandboxRuntime implements SandboxRuntime {
88
90
  private readonly config;
89
91
  private readonly publicationGrantRedeemer?;
92
+ /** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
93
+ private readonly hostLoadGate?;
90
94
  private readonly active;
91
95
  private readonly degraded;
92
96
  private readonly builds;
93
97
  private readonly verifiedCatalogImages;
94
98
  private buildTail;
95
- constructor(config: BridgeServiceConfig, publicationGrantRedeemer?: SandboxPublicationGrantRedeemer | undefined);
99
+ /** Shared with every sampler on the state root, so sandbox CPU is never external load. */
100
+ private readonly forgeCgroups;
101
+ constructor(config: BridgeServiceConfig, publicationGrantRedeemer?: SandboxPublicationGrantRedeemer | undefined,
102
+ /** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
103
+ hostLoadGate?: HostLoadStepGate | undefined);
96
104
  runOnce(dispatch: RunOnceDispatchPacket, sink: SessionEventSink, signal?: AbortSignal): Promise<RunOnceResultPacket>;
97
105
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
98
106
  private pushLeaseUpdate;
@@ -133,6 +141,8 @@ export declare class DockerSandboxRuntime implements SandboxRuntime {
133
141
  private inspectImageMetadata;
134
142
  private startPeakMemorySampler;
135
143
  private docker;
144
+ /** The container's init process: stopping it stops every process in the sandbox. */
145
+ private containerInitProcess;
136
146
  private dockerArgs;
137
147
  }
138
148
  export declare function managedBranchUpdateExpectedValue(current: string, expectedInput: string, imported: string): string;
@@ -160,7 +170,6 @@ export declare function selectSandboxConfigRefs(executionPolicy: string, configu
160
170
  readonly refs: readonly string[];
161
171
  readonly approvedSha: string | null;
162
172
  };
163
- export declare function selectSandboxInputRefs(worktreeKey: string, baseBranch: string): readonly string[];
164
173
  export declare function sandboxTimeLimits(environment?: NodeJS.ProcessEnv): {
165
174
  readonly hardWallMs: number;
166
175
  readonly idleMs: number;
@@ -299,4 +308,3 @@ export declare function classifySandboxResourceFailure(value: string): {
299
308
  readonly code: string;
300
309
  readonly message: string;
301
310
  } | null;
302
- export {};
@@ -5,9 +5,17 @@ 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";
13
+ import { SandboxHostCapacityBroker, sandboxHostCapacityDeliveryExecArgs, withSandboxHostCapacityBroker, } from "./host-capacity-broker.js";
14
+ import { defaultHostLoadGovernorConfig } from "../runtime/host-load-governor-config.js";
15
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
16
+ import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
17
+ import { trackSandboxCgroups } from "./sandbox-cgroups.js";
18
+ import { runtimeAdmissionPriority } from "../runtime/host-runtime-lease.js";
11
19
  import { RepositoryCoordinatorLock } from "./repository-lock.js";
12
20
  import { redactText } from "../shared/redaction/redaction.js";
13
21
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "../runtime/runtime-isolation-lease.js";
@@ -18,14 +26,21 @@ const bridgeRuntimeDigestLabel = "dev.forge.bridge-runtime-digest";
18
26
  export class DockerSandboxRuntime {
19
27
  config;
20
28
  publicationGrantRedeemer;
29
+ hostLoadGate;
21
30
  active = new Map();
22
31
  degraded = new Set();
23
32
  builds = new Map();
24
33
  verifiedCatalogImages = new Set();
25
34
  buildTail = Promise.resolve();
26
- constructor(config, publicationGrantRedeemer) {
35
+ /** Shared with every sampler on the state root, so sandbox CPU is never external load. */
36
+ forgeCgroups;
37
+ constructor(config, publicationGrantRedeemer,
38
+ /** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
39
+ hostLoadGate) {
27
40
  this.config = config;
28
41
  this.publicationGrantRedeemer = publicationGrantRedeemer;
42
+ this.hostLoadGate = hostLoadGate;
43
+ this.forgeCgroups = new FileForgeCgroupRegistry(config.sandboxStateRoot);
29
44
  }
30
45
  async runOnce(dispatch, sink, signal) {
31
46
  if (!dispatch.sandbox || dispatch.sandbox.executionMode !== "docker" || dispatch.sandbox.runtime !== "docker") {
@@ -97,7 +112,7 @@ export class DockerSandboxRuntime {
97
112
  const securityOptions = resolveSandboxSecurityOptions(dispatch.sandbox.executionPolicy);
98
113
  const builtImage = await this.buildImage(prepared.contextRoot, prepared.contextDigest, dispatch.repo.name, validated, upstreamImages, dispatch.sandbox.executionPolicy, sink, runtimeSignal);
99
114
  const imageDigest = builtImage.imageDigest;
100
- 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);
101
116
  const providerAuthAdapter = sandboxProviderAuthAdapterFor(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
102
117
  const providerAuthUnavailable = sandboxProviderAuthUnavailableMessage(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
103
118
  if (providerAuthUnavailable) {
@@ -153,7 +168,11 @@ export class DockerSandboxRuntime {
153
168
  await this.initializeEgressPolicy(builtImage.helperImageDigest, runtimeDispatch, resources, labels, runtimeSignal);
154
169
  const egressProxy = await this.startEgressProxy(runtimeDispatch, resources, labels, securityOptions, sink, runtimeSignal);
155
170
  const serviceContainers = await this.startServices(validated, runtimeDispatch.sandbox.executionPolicy, resources, labels, securityOptions, sink, runtimeSignal);
156
- const createArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
171
+ const brokered = this.hostLoadGate?.enabled === true;
172
+ const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
173
+ const createArgs = brokered
174
+ ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxTotalWaitMs)
175
+ : workerArgs;
157
176
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
158
177
  const containerId = dockerObjectId(createdContainer.stdout, "container");
159
178
  await this.docker(["cp", prepared.bundlePath, `${containerId}:/control/input/repo.bundle`], 60_000, runtimeSignal);
@@ -183,6 +202,16 @@ export class DockerSandboxRuntime {
183
202
  runtimeLease: active.runtimeLease,
184
203
  }));
185
204
  const eventBudget = new SandboxEventBudget();
205
+ const hostCapacity = brokered
206
+ ? new SandboxHostCapacityBroker(this.hostLoadGate, runtimeDispatch.sandbox.dispatchAttemptId, runtimeAdmissionPriority(runtimeDispatch), async (response) => void await requireSandboxProcess({
207
+ command: this.config.dockerExecutable,
208
+ // As root, into the root-owned reply mount the sandbox user cannot write.
209
+ args: this.dockerArgs(sandboxHostCapacityDeliveryExecArgs(containerId)),
210
+ input: `${JSON.stringify(response)}\n`,
211
+ timeoutMs: 10_000,
212
+ maxOutputBytes: 16 * 1024,
213
+ }), { stepProcess: async () => await this.containerInitProcess(containerId) })
214
+ : null;
186
215
  const startPromise = runSandboxProcess({
187
216
  command: this.config.dockerExecutable,
188
217
  args: this.dockerArgs(["start", "--attach", "--interactive", containerId]),
@@ -198,6 +227,8 @@ export class DockerSandboxRuntime {
198
227
  signal: runtimeSignal,
199
228
  onStdoutLine: async (line) => {
200
229
  eventBudget.accept(line);
230
+ if (hostCapacity?.handleLine(line))
231
+ return;
201
232
  const streamedEvent = parseSandboxEventLine(line);
202
233
  if (streamedEvent) {
203
234
  if (streamedEvent.eventType === "provider_cli_started")
@@ -207,7 +238,14 @@ export class DockerSandboxRuntime {
207
238
  }
208
239
  });
209
240
  const memorySampler = this.startPeakMemorySampler(runtimeContainers);
241
+ // The sandbox's CPU is Forge's own work, not external load, for the governor.
242
+ const untrackCgroups = brokered
243
+ ? trackSandboxCgroups(this.forgeCgroups, runtimeDispatch.sandbox.dispatchAttemptId, runtimeContainers.map(container => container.id), async (ids) => (await this.docker(["inspect", "--format", "{{.State.Pid}}", ...ids], 10_000)).stdout)
244
+ : null;
210
245
  const start = await startPromise.finally(async () => {
246
+ // The worker exited: its queued and admitted host load tokens go back to the budget.
247
+ untrackCgroups?.();
248
+ await hostCapacity?.close();
211
249
  const telemetry = await memorySampler.stop();
212
250
  if (!telemetry)
213
251
  return;
@@ -239,7 +277,7 @@ export class DockerSandboxRuntime {
239
277
  await this.docker(["cp", `${containerId}:/control/output/.`, path.join(attemptRoot, "output")], 60_000);
240
278
  let output;
241
279
  try {
242
- output = await validateOutput(attemptRoot, runtimeDispatch);
280
+ output = reviewOnlySandboxOutput(runtimeDispatch, await validateOutput(attemptRoot, runtimeDispatch));
243
281
  }
244
282
  catch (error) {
245
283
  if (start.exitCode !== 0 && isMissingSandboxManifest(error)) {
@@ -248,7 +286,7 @@ export class DockerSandboxRuntime {
248
286
  throw error;
249
287
  }
250
288
  await git.importResult(runtimeDispatch, output, () => assertSandboxImportCurrent(active, this.active.get(active.dispatchAttemptId), controller.signal));
251
- if (runtimeDispatch.sandbox.publicationMode === "bridge_push") {
289
+ if (sandboxPublicationAllowed(runtimeDispatch)) {
252
290
  const handle = runtimeDispatch.sandbox.publishGrantHandle;
253
291
  if (!handle || !output.manifest.resultCommitSha || !this.publicationGrantRedeemer) {
254
292
  throw trustedSandboxFailure("sandbox_output_publish_forbidden", "bridge publication grant redemption is unavailable.");
@@ -1105,6 +1143,13 @@ export class DockerSandboxRuntime {
1105
1143
  docker(args, timeoutMs, signal, maxOutputBytes = 1024 * 1024) {
1106
1144
  return requireSandboxProcess({ command: this.config.dockerExecutable, args: this.dockerArgs(args), timeoutMs, maxOutputBytes, signal });
1107
1145
  }
1146
+ /** The container's init process: stopping it stops every process in the sandbox. */
1147
+ async containerInitProcess(containerId) {
1148
+ const pid = Number((await this.docker(["inspect", "--format", "{{.State.Pid}}", containerId], 10_000)).stdout.trim());
1149
+ return Number.isSafeInteger(pid) && pid > 1
1150
+ ? { rootPid: pid, rootIdentity: captureHostProcessIdentity(pid), processGroup: false }
1151
+ : null;
1152
+ }
1108
1153
  dockerArgs(args) { return this.config.dockerContext ? ["--context", this.config.dockerContext, ...args] : [...args]; }
1109
1154
  }
1110
1155
  class HostGit {
@@ -1122,7 +1167,7 @@ class HostGit {
1122
1167
  async prepareLocked(dispatch, attemptRoot) {
1123
1168
  const baseBranch = dispatch.cycleRun.baseBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch;
1124
1169
  await this.git(["fetch", "--prune", "origin"], 5 * 60_000).catch(() => null);
1125
- 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)];
1126
1171
  const configSelection = selectSandboxConfigRefs(dispatch.sandbox.executionPolicy, dispatch.sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
1127
1172
  const configCommitSha = await this.resolveFirst([...configSelection.refs]);
1128
1173
  const approvedConfigSha = configSelection.approvedSha;
@@ -1146,7 +1191,7 @@ class HostGit {
1146
1191
  await fs.mkdir(contextRoot, { recursive: true });
1147
1192
  await requireSandboxProcess({ command: "tar", args: ["-xf", contextArchive, "-C", contextRoot], timeoutMs: 5 * 60_000, maxOutputBytes: 1024 * 1024 });
1148
1193
  const contextDigest = createHash("sha256").update(await fs.readFile(contextArchive)).digest("hex");
1149
- return { inputCommitSha, configCommitSha, contractSource, dockerfile, bundlePath, contextRoot, contextDigest };
1194
+ return { inputCommitSha, reviewDiffBase, configCommitSha, contractSource, dockerfile, bundlePath, contextRoot, contextDigest };
1150
1195
  }
1151
1196
  async importResult(dispatch, output, assertCurrent) {
1152
1197
  await this.coordinator.withLock(this.repoPath, () => this.importResultLocked(dispatch, output, assertCurrent));
@@ -1233,12 +1278,7 @@ class HostGit {
1233
1278
  await this.git(["update-ref", branchRef, imported, managedBranchUpdateExpectedValue(current, expected, imported)], 30_000);
1234
1279
  return;
1235
1280
  }
1236
- const head = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "rev-parse", "HEAD"], timeoutMs: 30_000 })).stdout.trim();
1237
- const status = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "status", "--porcelain=v1", "--untracked-files=no"], timeoutMs: 30_000, maxOutputBytes: 4 * 1024 * 1024 })).stdout;
1238
- if (head !== expected || status.trim())
1239
- throw trustedSandboxFailure("sandbox_output_conflict", "managed worktree changed after sandbox input was captured.");
1240
- await this.git(["update-ref", branchRef, imported, expected], 30_000);
1241
- 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 });
1242
1282
  }
1243
1283
  async resolveFirst(refs) {
1244
1284
  for (const ref of refs) {
@@ -1382,13 +1422,6 @@ export function selectSandboxConfigRefs(executionPolicy, configuredSha, defaultB
1382
1422
  ? { refs: [approvedSha], approvedSha }
1383
1423
  : { refs: [`refs/heads/${defaultBranch}`, `refs/remotes/origin/${defaultBranch}`], approvedSha: null };
1384
1424
  }
1385
- export function selectSandboxInputRefs(worktreeKey, baseBranch) {
1386
- return [
1387
- `refs/heads/${worktreeKey}`,
1388
- `refs/heads/${baseBranch}`,
1389
- `refs/remotes/origin/${baseBranch}`
1390
- ];
1391
- }
1392
1425
  export function sandboxTimeLimits(environment = process.env) {
1393
1426
  const hardWallSeconds = boundedInteger(environment.FORGE_SANDBOX_HARD_WALL_SECONDS, 8 * 60 * 60, 60, 8 * 60 * 60);
1394
1427
  const idleSeconds = boundedInteger(environment.FORGE_SANDBOX_IDLE_SECONDS, 10 * 60, 60, hardWallSeconds);
@@ -0,0 +1,14 @@
1
+ import type { ForgeCgroupWriter } from "../runtime/host-load-forge-cgroups.js";
2
+ export type DockerInspectPids = (containerIds: readonly string[]) => Promise<string>;
3
+ /** Cgroup paths of the given containers' init processes; containers not yet running are skipped. */
4
+ export declare function sandboxContainerCgroupPaths(inspectPids: DockerInspectPids, containerIds: readonly string[], procRoot?: string): Promise<readonly string[]>;
5
+ /**
6
+ * Registers a sandbox's container cgroups once its containers are running,
7
+ * retrying briefly while the agent container starts. Returns a function that
8
+ * stops the retries and removes the registration.
9
+ */
10
+ export declare function trackSandboxCgroups(registry: ForgeCgroupWriter, owner: string, containerIds: readonly string[], inspectPids: DockerInspectPids, options?: {
11
+ readonly attempts?: number;
12
+ readonly intervalMs?: number;
13
+ readonly procRoot?: string;
14
+ }): () => void;
@@ -0,0 +1,42 @@
1
+ import fs from "node:fs/promises";
2
+ import { parseUnifiedCgroupPath } from "../runtime/host-pressure-stall.js";
3
+ /** Cgroup paths of the given containers' init processes; containers not yet running are skipped. */
4
+ export async function sandboxContainerCgroupPaths(inspectPids, containerIds, procRoot = "/proc") {
5
+ const output = await inspectPids(containerIds);
6
+ const paths = [];
7
+ for (const line of output.split(/\r?\n/u)) {
8
+ const pid = Number(line.trim());
9
+ if (!Number.isSafeInteger(pid) || pid <= 1)
10
+ continue;
11
+ const membership = await fs.readFile(`${procRoot}/${pid}/cgroup`, "utf8").catch(() => null);
12
+ const cgroupPath = membership ? parseUnifiedCgroupPath(membership) : null;
13
+ if (cgroupPath)
14
+ paths.push(cgroupPath);
15
+ }
16
+ return paths;
17
+ }
18
+ /**
19
+ * Registers a sandbox's container cgroups once its containers are running,
20
+ * retrying briefly while the agent container starts. Returns a function that
21
+ * stops the retries and removes the registration.
22
+ */
23
+ export function trackSandboxCgroups(registry, owner, containerIds, inspectPids, options = {}) {
24
+ let stopped = false;
25
+ void (async () => {
26
+ for (let attempt = 0; attempt < (options.attempts ?? 10) && !stopped; attempt += 1) {
27
+ await new Promise(resolve => setTimeout(resolve, options.intervalMs ?? 1_000));
28
+ if (stopped)
29
+ return;
30
+ const paths = await sandboxContainerCgroupPaths(inspectPids, containerIds, options.procRoot).catch(() => []);
31
+ if (stopped)
32
+ return;
33
+ registry.set(owner, paths);
34
+ if (paths.length >= containerIds.length)
35
+ return;
36
+ }
37
+ })();
38
+ return () => {
39
+ stopped = true;
40
+ registry.delete(owner);
41
+ };
42
+ }
@@ -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) {
@@ -0,0 +1,2 @@
1
+ export declare function architectNonPassProperties(): Record<string, unknown>;
2
+ export declare function validateArchitectWaits(payload: Record<string, unknown>, status: string): void;
@@ -0,0 +1,138 @@
1
+ // Decision 0022: a blocked Architect verdict may say what it waits on (a sibling Story, a pull
2
+ // request, or something outside Forge) and which choice it needs from the owner. Forge records
3
+ // Story and pull request waits as dependency edges and re-plans the Story when they merge.
4
+ const architectWaitKinds = ["story", "pull_request", "external"];
5
+ const architectWaitUntil = ["merged"];
6
+ const storyIdPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,32})$/i;
7
+ // Architect tool properties for non-pass verdicts: revision prose plus the structured waits.
8
+ export function architectNonPassProperties() {
9
+ return {
10
+ revision_questions: {
11
+ type: "array",
12
+ description: "Required for needs_revision when blockers are not used.",
13
+ items: { type: "string" }
14
+ },
15
+ revision_reasons: {
16
+ type: "array",
17
+ description: "Concrete reasons that prevent pass status.",
18
+ items: { type: "string" }
19
+ },
20
+ waits_on: {
21
+ type: "array",
22
+ description: "Only with status blocked. What must merge before this Story can be planned: a sibling Story (kind story, story_id as the full id or its first 8+ hex digits), a pull request (kind pull_request, pr_number), or something outside Forge (kind external). Forge records Story and sibling pull request waits and plans the Story again when they merge; external waits hold for the owner.",
23
+ items: {
24
+ type: "object",
25
+ additionalProperties: false,
26
+ required: ["kind", "until", "reason"],
27
+ properties: {
28
+ kind: { type: "string", enum: [...architectWaitKinds] },
29
+ story_id: { type: "string", description: "Required for kind story." },
30
+ pr_number: { type: "integer", minimum: 1, description: "Required for kind pull_request." },
31
+ until: { type: "string", enum: [...architectWaitUntil] },
32
+ reason: { type: "string", description: "What this Story needs from the blocker." }
33
+ }
34
+ }
35
+ },
36
+ owner_decision: {
37
+ type: "object",
38
+ description: "Only with status blocked. A choice only the owner can make before the Story can be planned. Forge holds the Story for the owner and never picks an option.",
39
+ additionalProperties: false,
40
+ required: ["question", "options"],
41
+ properties: {
42
+ question: { type: "string" },
43
+ options: {
44
+ type: "array",
45
+ minItems: 2,
46
+ items: {
47
+ type: "object",
48
+ additionalProperties: false,
49
+ required: ["label", "summary"],
50
+ properties: {
51
+ label: { type: "string" },
52
+ summary: { type: "string" }
53
+ }
54
+ }
55
+ },
56
+ recommended: { type: "string", description: "Label of the recommended option." }
57
+ }
58
+ }
59
+ };
60
+ }
61
+ // An explicit null is absent, as the API reads it.
62
+ function isPresent(value) {
63
+ return value !== undefined && value !== null;
64
+ }
65
+ function hasArchitectWaitDeclarations(payload) {
66
+ return isPresent(payload.waits_on) || isPresent(payload.owner_decision);
67
+ }
68
+ // Throws an actionable error for a malformed waits_on or owner_decision. Absent (or null) fields are valid.
69
+ export function validateArchitectWaits(payload, status) {
70
+ if (!hasArchitectWaitDeclarations(payload)) {
71
+ return;
72
+ }
73
+ if (status !== "blocked") {
74
+ throw new Error("waits_on/owner_decision: allowed only with status blocked; correction: remove them, or return status blocked when the plan cannot pass until they are resolved.");
75
+ }
76
+ if (isPresent(payload.waits_on)) {
77
+ validateWaitsOn(payload.waits_on);
78
+ }
79
+ if (isPresent(payload.owner_decision)) {
80
+ validateOwnerDecision(payload.owner_decision);
81
+ }
82
+ }
83
+ function validateWaitsOn(value) {
84
+ if (!Array.isArray(value) || value.length === 0) {
85
+ throw new Error("waits_on: expected a non-empty array; correction: list each Story, pull request or external dependency, or omit waits_on.");
86
+ }
87
+ value.forEach((entry, index) => validateWait(entry, `waits_on[${index}]`));
88
+ }
89
+ function validateWait(entry, label) {
90
+ const wait = requireRecord(entry, label);
91
+ const kind = wait.kind;
92
+ if (typeof kind !== "string" || !architectWaitKinds.includes(kind)) {
93
+ throw new Error(`${label}.kind: expected one of story, pull_request, external.`);
94
+ }
95
+ if (wait.until !== "merged") {
96
+ throw new Error(`${label}.until: expected "merged".`);
97
+ }
98
+ requireText(wait.reason, `${label}.reason`);
99
+ if (kind === "story") {
100
+ const storyId = requireText(wait.story_id, `${label}.story_id`);
101
+ if (!storyIdPattern.test(storyId)) {
102
+ throw new Error(`${label}.story_id: expected the Story's full id or its first 8+ hex digits; got '${storyId}'.`);
103
+ }
104
+ }
105
+ if (kind === "pull_request" && !(typeof wait.pr_number === "number" && Number.isInteger(wait.pr_number) && wait.pr_number > 0)) {
106
+ throw new Error(`${label}.pr_number: expected a positive integer pull request number.`);
107
+ }
108
+ }
109
+ function validateOwnerDecision(value) {
110
+ const decision = requireRecord(value, "owner_decision");
111
+ requireText(decision.question, "owner_decision.question");
112
+ if (!Array.isArray(decision.options) || decision.options.length < 2) {
113
+ throw new Error("owner_decision.options: expected at least two options, each with a distinct label and a summary.");
114
+ }
115
+ const labels = decision.options.map((option, index) => {
116
+ const record = requireRecord(option, `owner_decision.options[${index}]`);
117
+ requireText(record.summary, `owner_decision.options[${index}].summary`);
118
+ return requireText(record.label, `owner_decision.options[${index}].label`);
119
+ });
120
+ if (new Set(labels).size !== labels.length) {
121
+ throw new Error("owner_decision.options: expected at least two options, each with a distinct label and a summary.");
122
+ }
123
+ if (isPresent(decision.recommended) && !labels.includes(requireText(decision.recommended, "owner_decision.recommended"))) {
124
+ throw new Error("owner_decision.recommended: expected the label of one of the options.");
125
+ }
126
+ }
127
+ function requireRecord(value, label) {
128
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
129
+ throw new Error(`${label}: expected an object.`);
130
+ }
131
+ return value;
132
+ }
133
+ function requireText(value, label) {
134
+ if (typeof value !== "string" || value.trim().length === 0) {
135
+ throw new Error(`${label}: expected a non-empty string.`);
136
+ }
137
+ return value.trim();
138
+ }
@@ -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,
@@ -25,6 +24,8 @@ export declare function installOwnerShutdownHandlers(target?: OwnerShutdownSigna
25
24
  */
26
25
  export declare function runWithOwnerShutdown<T>(body: () => Promise<T>, target?: OwnerShutdownSignalTarget, exit?: (code: number) => void): Promise<T>;
27
26
  export declare function isManagedAttemptTool(name: string): boolean;
27
+ /** The input schema a managed-attempt tool advertises; also the shape its arguments are coerced to. */
28
+ export declare function managedAttemptToolInputSchema(name: string): unknown;
28
29
  export declare function managedAttemptToolDefinition(name: string): unknown;
29
30
  export interface ManagedAttemptToolResult {
30
31
  readonly content: readonly {
@@ -43,11 +44,5 @@ export declare function buildManagedVerificationCommand(profile: string, outputD
43
44
  export declare function preferredPowerShellExecutable(platform?: NodeJS.Platform, pathValue?: string): string;
44
45
  export declare function validatePlaywrightProjectName(project: string, availableProjects: readonly string[]): void;
45
46
  export declare function playwrightProjectNamesFromConfigSource(source: string): readonly string[];
46
- /**
47
- * Runner-authored verification normally uses its attempt-owned Testcontainers
48
- * database. Only when the Docker engine is unavailable does it switch to the
49
- * operator-provisioned native test cluster, which holds no real data.
50
- */
51
- export declare function managedVerificationDatabaseEnvironment(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null): Promise<Readonly<Record<string, string>>>;
52
47
  export declare function isBuildProducingManagedCommand(command: string, args: readonly string[]): boolean;
53
48
  export {};