@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.0098fdb4e213

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 (332) hide show
  1. package/README.md +232 -5
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +13 -1
  15. package/dist/bridge/bridge.service.d.ts +169 -14
  16. package/dist/bridge/bridge.service.js +1868 -330
  17. package/dist/bridge/bridge.types.d.ts +73 -1
  18. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  19. package/dist/bridge/dispatch-result-outbox.js +87 -0
  20. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  21. package/dist/bridge/dispatch-result-worker.js +122 -0
  22. package/dist/bridge/in-flight-registry.d.ts +62 -0
  23. package/dist/bridge/in-flight-registry.js +207 -0
  24. package/dist/bridge/internals.d.ts +2 -0
  25. package/dist/bridge/internals.js +1 -0
  26. package/dist/bridge/local-yield-flag.d.ts +6 -0
  27. package/dist/bridge/local-yield-flag.js +34 -0
  28. package/dist/bridge/readiness-result-outbox.d.ts +25 -0
  29. package/dist/bridge/readiness-result-outbox.js +74 -0
  30. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  31. package/dist/bridge/readiness-result-worker.js +121 -0
  32. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  33. package/dist/bridge/runner-host-capabilities.js +110 -0
  34. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  35. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  36. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  37. package/dist/bridge/test-postgres-capability.js +120 -0
  38. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  39. package/dist/cleanup/cleanup-wip.js +66 -0
  40. package/dist/cleanup/cleanup.service.d.ts +21 -1
  41. package/dist/cleanup/cleanup.service.js +185 -143
  42. package/dist/cleanup/cleanup.types.d.ts +6 -0
  43. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  44. package/dist/cleanup/forge-owned-paths.js +53 -0
  45. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  46. package/dist/cleanup/host-runtime-ledger.js +130 -0
  47. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  48. package/dist/cleanup/managed-branch-sweep.js +111 -0
  49. package/dist/cli/cli.help.js +78 -16
  50. package/dist/cli/cli.service.d.ts +32 -15
  51. package/dist/cli/cli.service.js +206 -182
  52. package/dist/cli/idle-status.d.ts +84 -0
  53. package/dist/cli/idle-status.js +181 -0
  54. package/dist/cli/local-config.d.ts +7 -0
  55. package/dist/cli/local-config.js +36 -4
  56. package/dist/cli/provider-cli-detection.d.ts +10 -0
  57. package/dist/cli/provider-cli-detection.js +160 -0
  58. package/dist/runtime/aspnet-runtime-prebuild.d.ts +41 -0
  59. package/dist/runtime/aspnet-runtime-prebuild.js +474 -0
  60. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  61. package/dist/runtime/attempt-database-broker.js +390 -0
  62. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  63. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  64. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  65. package/dist/runtime/attempt-path-operation.js +94 -0
  66. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  67. package/dist/runtime/attempt-private-directory.js +54 -0
  68. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  69. package/dist/runtime/attempt-process-supervisor.js +144 -23
  70. package/dist/runtime/canonical-source-file.d.ts +3 -0
  71. package/dist/runtime/canonical-source-file.js +54 -0
  72. package/dist/runtime/docker-engine-probe.d.ts +95 -0
  73. package/dist/runtime/docker-engine-probe.js +340 -0
  74. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  75. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  76. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  77. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  78. package/dist/runtime/generated-output-reset.d.ts +10 -0
  79. package/dist/runtime/generated-output-reset.js +62 -8
  80. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  81. package/dist/runtime/host-database-capability-boundary.js +63 -0
  82. package/dist/runtime/host-diagnostics.d.ts +11 -0
  83. package/dist/runtime/host-diagnostics.js +192 -0
  84. package/dist/runtime/host-execution-root.d.ts +4 -0
  85. package/dist/runtime/host-execution-root.js +39 -0
  86. package/dist/runtime/host-facts.d.ts +36 -0
  87. package/dist/runtime/host-facts.js +95 -0
  88. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  89. package/dist/runtime/host-listener-inspector.js +121 -60
  90. package/dist/runtime/host-load-admission.d.ts +67 -0
  91. package/dist/runtime/host-load-admission.js +99 -0
  92. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  93. package/dist/runtime/host-load-child-environment.js +76 -0
  94. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  95. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  96. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  97. package/dist/runtime/host-load-governor-config.js +83 -0
  98. package/dist/runtime/host-load-governor.d.ts +186 -0
  99. package/dist/runtime/host-load-governor.js +632 -0
  100. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  101. package/dist/runtime/host-load-ledger-lock.js +187 -0
  102. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  103. package/dist/runtime/host-load-runtime-settings.js +80 -0
  104. package/dist/runtime/host-load-sampler.d.ts +156 -0
  105. package/dist/runtime/host-load-sampler.js +298 -0
  106. package/dist/runtime/host-load-step-class.d.ts +70 -0
  107. package/dist/runtime/host-load-step-class.js +161 -0
  108. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  109. package/dist/runtime/host-load-step-reaper.js +95 -0
  110. package/dist/runtime/host-load-step-run.d.ts +73 -0
  111. package/dist/runtime/host-load-step-run.js +102 -0
  112. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  113. package/dist/runtime/host-load-test-slot.js +81 -0
  114. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  115. package/dist/runtime/host-load-token-ledger.js +453 -0
  116. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  117. package/dist/runtime/host-load-windows-cpu.js +85 -0
  118. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  119. package/dist/runtime/host-pressure-stall.js +168 -0
  120. package/dist/runtime/host-runtime-contract.d.ts +28 -1
  121. package/dist/runtime/host-runtime-contract.js +203 -57
  122. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  123. package/dist/runtime/host-runtime-lease.js +1427 -124
  124. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  125. package/dist/runtime/host-runtime-promotion.js +107 -12
  126. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  127. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  128. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  129. package/dist/runtime/host-runtime-requirements.js +117 -0
  130. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  131. package/dist/runtime/managed-command-teardown.js +596 -0
  132. package/dist/runtime/memory-capacity.d.ts +70 -0
  133. package/dist/runtime/memory-capacity.js +123 -0
  134. package/dist/runtime/native-test-postgres-fallback.d.ts +69 -0
  135. package/dist/runtime/native-test-postgres-fallback.js +143 -0
  136. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  137. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  138. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  139. package/dist/runtime/pinned-directory-process.js +61 -0
  140. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  141. package/dist/runtime/pinned-source-directory.js +94 -0
  142. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  143. package/dist/runtime/playwright-browser-cache.js +227 -0
  144. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  145. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  146. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  147. package/dist/runtime/prepared-runtime-identity.js +218 -0
  148. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  149. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  150. package/dist/runtime/runner-settings.d.ts +104 -0
  151. package/dist/runtime/runner-settings.js +236 -0
  152. package/dist/runtime/runtime-isolation-lease.js +4 -1
  153. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  154. package/dist/runtime/workspace-resource-estimator.js +174 -0
  155. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  156. package/dist/sandbox/host-capacity-broker.js +336 -0
  157. package/dist/sandbox/managed-branch.d.ts +13 -0
  158. package/dist/sandbox/managed-branch.js +36 -0
  159. package/dist/sandbox/preflight.d.ts +31 -1
  160. package/dist/sandbox/preflight.js +237 -51
  161. package/dist/sandbox/provider-auth/codex.js +11 -11
  162. package/dist/sandbox/repository-lock.d.ts +2 -1
  163. package/dist/sandbox/repository-lock.js +19 -9
  164. package/dist/sandbox/runtime.d.ts +16 -2
  165. package/dist/sandbox/runtime.js +183 -114
  166. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  167. package/dist/sandbox/sandbox-cgroups.js +42 -0
  168. package/dist/sandbox/sandbox.types.d.ts +7 -0
  169. package/dist/sandbox/workspace.service.js +2 -0
  170. package/dist/session/architect-waits.d.ts +2 -0
  171. package/dist/session/architect-waits.js +138 -0
  172. package/dist/session/managed-attempt-tools.d.ts +37 -1
  173. package/dist/session/managed-attempt-tools.js +822 -84
  174. package/dist/session/managed-build-coordinator.d.ts +5 -0
  175. package/dist/session/managed-build-coordinator.js +109 -0
  176. package/dist/session/managed-build-receipt.d.ts +26 -0
  177. package/dist/session/managed-build-receipt.js +342 -0
  178. package/dist/session/managed-command-host-load.d.ts +47 -0
  179. package/dist/session/managed-command-host-load.js +83 -0
  180. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  181. package/dist/session/managed-verification-timeouts.js +17 -0
  182. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  183. package/dist/session/mcp-argument-coercion.js +121 -0
  184. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  185. package/dist/session/phase-completion.artifacts.js +321 -45
  186. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  187. package/dist/session/phase-completion.command-validation.js +77 -0
  188. package/dist/session/phase-completion.d.ts +23 -1
  189. package/dist/session/phase-completion.helpers.d.ts +5 -0
  190. package/dist/session/phase-completion.helpers.js +43 -19
  191. package/dist/session/phase-completion.js +19 -3
  192. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  193. package/dist/session/phase-completion.mcp-args.js +156 -0
  194. package/dist/session/phase-completion.prompts.js +22 -18
  195. package/dist/session/phase-completion.runtime.d.ts +6 -10
  196. package/dist/session/phase-completion.runtime.js +214 -224
  197. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  198. package/dist/session/phase-completion.schema-parts.js +188 -0
  199. package/dist/session/phase-completion.schemas.d.ts +3 -3
  200. package/dist/session/phase-completion.schemas.js +250 -226
  201. package/dist/session/phase-completion.validation.d.ts +3 -3
  202. package/dist/session/phase-completion.validation.js +135 -89
  203. package/dist/session/pre-publication-host-load.d.ts +27 -0
  204. package/dist/session/pre-publication-host-load.js +111 -0
  205. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  206. package/dist/session/pre-publication-native-postgres.js +111 -0
  207. package/dist/session/pre-publication-pass.d.ts +61 -0
  208. package/dist/session/pre-publication-pass.js +148 -0
  209. package/dist/session/pre-publication-process.d.ts +23 -0
  210. package/dist/session/pre-publication-process.js +109 -0
  211. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  212. package/dist/session/pre-publication-skipped-tests.js +109 -0
  213. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  214. package/dist/session/pre-publication-step-execution.js +50 -0
  215. package/dist/session/pre-publication-validation.d.ts +91 -0
  216. package/dist/session/pre-publication-validation.js +670 -0
  217. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  218. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  219. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  220. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  221. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  222. package/dist/session/provider-cli/claude-background-work.js +181 -0
  223. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  224. package/dist/session/provider-cli/host-build-lock.js +30 -0
  225. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  226. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  227. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  228. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  229. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  230. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  231. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  232. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  233. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  234. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  235. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  236. package/dist/session/provider-cli/provider-cli.process.d.ts +85 -19
  237. package/dist/session/provider-cli/provider-cli.process.js +566 -283
  238. package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -0
  239. package/dist/session/provider-cli/provider-cli.prompts.js +211 -36
  240. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  241. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  242. package/dist/session/provider-cli/provider-cli.runtime.d.ts +22 -1
  243. package/dist/session/provider-cli/provider-cli.runtime.js +83 -4
  244. package/dist/session/provider-cli/provider-cli.service.d.ts +36 -5
  245. package/dist/session/provider-cli/provider-cli.service.js +818 -99
  246. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  247. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  248. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  249. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  250. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  251. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  252. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  253. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  254. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  255. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  256. package/dist/session/provider-cli/provider-output-state.js +376 -17
  257. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  258. package/dist/session/provider-cli/provider-usage.js +28 -5
  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/publishable-worktree-changes.d.ts +54 -0
  262. package/dist/session/publishable-worktree-changes.js +193 -0
  263. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  264. package/dist/session/qa-sidecar-validation.js +28 -0
  265. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  266. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  267. package/dist/session/session-redaction.js +284 -9
  268. package/dist/session/session.base.d.ts +9 -1
  269. package/dist/session/session.service.d.ts +11 -2
  270. package/dist/session/session.service.js +301 -58
  271. package/dist/session/session.types.d.ts +150 -2
  272. package/dist/session/session.types.js +599 -7
  273. package/dist/session/sidecar-json-shape.d.ts +31 -0
  274. package/dist/session/sidecar-json-shape.js +217 -0
  275. package/dist/session/unreferenced-exports.d.ts +12 -0
  276. package/dist/session/unreferenced-exports.js +59 -0
  277. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  278. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  279. package/dist/shared/format/format-bytes.d.ts +1 -0
  280. package/dist/shared/format/format-bytes.js +9 -0
  281. package/dist/shared/fs/file-identity.d.ts +10 -0
  282. package/dist/shared/fs/file-identity.js +15 -0
  283. package/dist/shared/fs/replace-file.d.ts +7 -0
  284. package/dist/shared/fs/replace-file.js +33 -0
  285. package/dist/shared/git/git.js +2 -1
  286. package/dist/shared/path/path.d.ts +1 -0
  287. package/dist/shared/path/path.js +18 -0
  288. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  289. package/dist/shared/process/dotnet-toolchain.js +307 -0
  290. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  291. package/dist/shared/process/host-process-recovery.js +26 -5
  292. package/dist/shared/process/host-process-supervisor.d.ts +16 -1
  293. package/dist/shared/process/host-process-supervisor.js +124 -23
  294. package/dist/shared/process/process-tree.d.ts +52 -0
  295. package/dist/shared/process/process-tree.js +144 -0
  296. package/dist/shared/process/process.d.ts +69 -0
  297. package/dist/shared/process/process.js +223 -16
  298. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  299. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  300. package/dist/shared/process/windows-launch.d.ts +18 -0
  301. package/dist/shared/process/windows-launch.js +68 -0
  302. package/dist/shared/provider-capabilities.d.ts +3 -0
  303. package/dist/shared/provider-capabilities.js +92 -0
  304. package/dist/shared/redaction/redaction.d.ts +1 -0
  305. package/dist/shared/redaction/redaction.js +39 -3
  306. package/dist/shared/time/monotonic.d.ts +1 -0
  307. package/dist/shared/time/monotonic.js +8 -0
  308. package/dist/version.d.ts +1 -1
  309. package/dist/version.js +1 -1
  310. package/dist/worktree/dependency-warmer.d.ts +66 -9
  311. package/dist/worktree/dependency-warmer.js +609 -24
  312. package/dist/worktree/index.d.ts +1 -1
  313. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  314. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  315. package/dist/worktree/wip-git.d.ts +33 -0
  316. package/dist/worktree/wip-git.js +122 -0
  317. package/dist/worktree/wip-refs.d.ts +62 -0
  318. package/dist/worktree/wip-refs.js +119 -0
  319. package/dist/worktree/wip-restore.d.ts +38 -0
  320. package/dist/worktree/wip-restore.js +190 -0
  321. package/dist/worktree/wip-snapshot.d.ts +50 -0
  322. package/dist/worktree/wip-snapshot.js +268 -0
  323. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  324. package/dist/worktree/worktree-wip-events.js +98 -0
  325. package/dist/worktree/worktree-wip.d.ts +49 -0
  326. package/dist/worktree/worktree-wip.js +182 -0
  327. package/dist/worktree/worktree.base.d.ts +7 -1
  328. package/dist/worktree/worktree.service.d.ts +22 -2
  329. package/dist/worktree/worktree.service.js +302 -25
  330. package/dist/worktree/worktree.types.d.ts +36 -1
  331. package/package.json +8 -6
  332. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -2,29 +2,44 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { failureResult } from "../session/session.types.js";
5
+ import { createFailureEnvelope, ForgeFailureError, failureFactsForCode, failurePolicyForCode, failureResult, parseRunOnceResultPacket, } from "../session/session.types.js";
6
6
  import { dockerfileUpstreamImages, validateDockerfilePolicy, validateSandboxContract } from "./contract.js";
7
7
  import { requireSandboxProcess, runSandboxProcess } from "./process.js";
8
+ import { advanceCheckedOutBranch } from "./managed-branch.js";
8
9
  import { createLeaseUpdate } from "./lease-watchdog.js";
9
10
  import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
10
11
  import { SandboxEventBudget } from "./event-budget.js";
12
+ import { SandboxHostCapacityBroker, sandboxHostCapacityDeliveryExecArgs, withSandboxHostCapacityBroker, } from "./host-capacity-broker.js";
13
+ import { defaultHostLoadGovernorConfig } from "../runtime/host-load-governor-config.js";
14
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
15
+ import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
16
+ import { trackSandboxCgroups } from "./sandbox-cgroups.js";
17
+ import { runtimeAdmissionPriority } from "../runtime/host-runtime-lease.js";
11
18
  import { RepositoryCoordinatorLock } from "./repository-lock.js";
12
19
  import { redactText } from "../shared/redaction/redaction.js";
13
20
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "../runtime/runtime-isolation-lease.js";
14
21
  import { sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "./provider-auth/codex.js";
22
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
15
23
  const managedLabel = "dev.forge.managed=true";
16
24
  const bridgeRuntimeDigestLabel = "dev.forge.bridge-runtime-digest";
17
25
  export class DockerSandboxRuntime {
18
26
  config;
19
27
  publicationGrantRedeemer;
28
+ hostLoadGate;
20
29
  active = new Map();
21
30
  degraded = new Set();
22
31
  builds = new Map();
23
32
  verifiedCatalogImages = new Set();
24
33
  buildTail = Promise.resolve();
25
- constructor(config, publicationGrantRedeemer) {
34
+ /** Shared with every sampler on the state root, so sandbox CPU is never external load. */
35
+ forgeCgroups;
36
+ constructor(config, publicationGrantRedeemer,
37
+ /** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
38
+ hostLoadGate) {
26
39
  this.config = config;
27
40
  this.publicationGrantRedeemer = publicationGrantRedeemer;
41
+ this.hostLoadGate = hostLoadGate;
42
+ this.forgeCgroups = new FileForgeCgroupRegistry(config.sandboxStateRoot);
28
43
  }
29
44
  async runOnce(dispatch, sink, signal) {
30
45
  if (!dispatch.sandbox || dispatch.sandbox.executionMode !== "docker" || dispatch.sandbox.runtime !== "docker") {
@@ -85,7 +100,7 @@ export class DockerSandboxRuntime {
85
100
  await fs.mkdir(path.join(attemptRoot, "output"), { recursive: true, mode: 0o700 });
86
101
  const repoPath = dispatch.repo.serverLocalPath ? path.resolve(dispatch.repo.serverLocalPath) : null;
87
102
  if (!repoPath)
88
- throw new Error("sandbox_input_failed: bridge repository mapping is required for bundle handoff.");
103
+ throw trustedSandboxFailure("sandbox_input_failed", "bridge repository mapping is required for bundle handoff.");
89
104
  await sink.emit(event("sandbox_preparing", `Preparing Docker sandbox attempt ${dispatch.sandbox.dispatchAttemptId}.`));
90
105
  const git = new HostGit(this.config, repoPath);
91
106
  const prepared = await git.prepare(dispatch, attemptRoot, runtimeSignal);
@@ -100,7 +115,7 @@ export class DockerSandboxRuntime {
100
115
  const providerAuthAdapter = sandboxProviderAuthAdapterFor(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
101
116
  const providerAuthUnavailable = sandboxProviderAuthUnavailableMessage(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
102
117
  if (providerAuthUnavailable) {
103
- throw new Error(`sandbox_auth_unavailable: ${providerAuthUnavailable}`);
118
+ throw trustedSandboxFailure("sandbox_auth_unavailable", providerAuthUnavailable);
104
119
  }
105
120
  await sink.emit(event("sandbox_metadata", "Resolved immutable sandbox inputs.", {
106
121
  inputCommitSha: prepared.inputCommitSha,
@@ -125,6 +140,7 @@ export class DockerSandboxRuntime {
125
140
  await this.writeLedger(active.ledger);
126
141
  let teardownComplete = false;
127
142
  let memoryTelemetryEvent = null;
143
+ let trustedHostFailure = null;
128
144
  try {
129
145
  const internalNetworkId = dockerObjectId((await this.docker(["network", "create", ...networkArgs, ...labelArgs(labels), resources.network], 30_000, runtimeSignal)).stdout, "network");
130
146
  await this.docker(["volume", "create", ...labelArgs(labels), resources.workspaceVolume], 30_000, runtimeSignal);
@@ -151,7 +167,11 @@ export class DockerSandboxRuntime {
151
167
  await this.initializeEgressPolicy(builtImage.helperImageDigest, runtimeDispatch, resources, labels, runtimeSignal);
152
168
  const egressProxy = await this.startEgressProxy(runtimeDispatch, resources, labels, securityOptions, sink, runtimeSignal);
153
169
  const serviceContainers = await this.startServices(validated, runtimeDispatch.sandbox.executionPolicy, resources, labels, securityOptions, sink, runtimeSignal);
154
- const createArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
170
+ const brokered = this.hostLoadGate?.enabled === true;
171
+ const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
172
+ const createArgs = brokered
173
+ ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs)
174
+ : workerArgs;
155
175
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
156
176
  const containerId = dockerObjectId(createdContainer.stdout, "container");
157
177
  await this.docker(["cp", prepared.bundlePath, `${containerId}:/control/input/repo.bundle`], 60_000, runtimeSignal);
@@ -181,6 +201,16 @@ export class DockerSandboxRuntime {
181
201
  runtimeLease: active.runtimeLease,
182
202
  }));
183
203
  const eventBudget = new SandboxEventBudget();
204
+ const hostCapacity = brokered
205
+ ? new SandboxHostCapacityBroker(this.hostLoadGate, runtimeDispatch.sandbox.dispatchAttemptId, runtimeAdmissionPriority(runtimeDispatch), async (response) => void await requireSandboxProcess({
206
+ command: this.config.dockerExecutable,
207
+ // As root, into the root-owned reply mount the sandbox user cannot write.
208
+ args: this.dockerArgs(sandboxHostCapacityDeliveryExecArgs(containerId)),
209
+ input: `${JSON.stringify(response)}\n`,
210
+ timeoutMs: 10_000,
211
+ maxOutputBytes: 16 * 1024,
212
+ }), { stepProcess: async () => await this.containerInitProcess(containerId) })
213
+ : null;
184
214
  const startPromise = runSandboxProcess({
185
215
  command: this.config.dockerExecutable,
186
216
  args: this.dockerArgs(["start", "--attach", "--interactive", containerId]),
@@ -196,6 +226,8 @@ export class DockerSandboxRuntime {
196
226
  signal: runtimeSignal,
197
227
  onStdoutLine: async (line) => {
198
228
  eventBudget.accept(line);
229
+ if (hostCapacity?.handleLine(line))
230
+ return;
199
231
  const streamedEvent = parseSandboxEventLine(line);
200
232
  if (streamedEvent) {
201
233
  if (streamedEvent.eventType === "provider_cli_started")
@@ -205,7 +237,14 @@ export class DockerSandboxRuntime {
205
237
  }
206
238
  });
207
239
  const memorySampler = this.startPeakMemorySampler(runtimeContainers);
240
+ // The sandbox's CPU is Forge's own work, not external load, for the governor.
241
+ const untrackCgroups = brokered
242
+ ? trackSandboxCgroups(this.forgeCgroups, runtimeDispatch.sandbox.dispatchAttemptId, runtimeContainers.map(container => container.id), async (ids) => (await this.docker(["inspect", "--format", "{{.State.Pid}}", ...ids], 10_000)).stdout)
243
+ : null;
208
244
  const start = await startPromise.finally(async () => {
245
+ // The worker exited: its queued and admitted host load tokens go back to the budget.
246
+ untrackCgroups?.();
247
+ await hostCapacity?.close();
209
248
  const telemetry = await memorySampler.stop();
210
249
  if (!telemetry)
211
250
  return;
@@ -217,19 +256,18 @@ export class DockerSandboxRuntime {
217
256
  await sink.emit(memoryTelemetryEvent).catch(() => undefined);
218
257
  });
219
258
  if (start.truncated)
220
- throw new Error("sandbox_log_limit: sandbox output exceeded the 8 MiB supervisor capture budget.");
259
+ throw trustedSandboxFailure("sandbox_log_limit", "sandbox output exceeded the 8 MiB supervisor capture budget.");
221
260
  const containerState = await this.inspectContainerState(containerId);
222
261
  if (containerState.oomKilled) {
223
- throw new Error("sandbox_oom_killed: Docker terminated the agent after it exceeded the memory limit.");
262
+ trustedHostFailure = {
263
+ code: "sandbox_oom_killed",
264
+ message: "Docker terminated the agent after it exceeded the memory limit.",
265
+ };
224
266
  }
225
- if (start.exitCode !== 0) {
226
- const resourceFailure = classifySandboxResourceFailure([
227
- containerState.error,
228
- start.stderr,
229
- start.stdout
230
- ].filter(Boolean).join("\n"));
231
- if (resourceFailure)
232
- throw new Error(`${resourceFailure.code}: ${resourceFailure.message}`);
267
+ if (start.exitCode !== 0 && !trustedHostFailure) {
268
+ // Docker's inspect state is trusted host telemetry. Child stdout/stderr is
269
+ // evidence only and must not be able to choose a machine failure code.
270
+ trustedHostFailure = classifySandboxResourceFailure(containerState.error ?? "");
233
271
  }
234
272
  active.phase = "active";
235
273
  await sink.emit(event("sandbox_agent_exited", `Sandbox worker exited with code ${start.exitCode}.`, {
@@ -250,7 +288,7 @@ export class DockerSandboxRuntime {
250
288
  if (runtimeDispatch.sandbox.publicationMode === "bridge_push") {
251
289
  const handle = runtimeDispatch.sandbox.publishGrantHandle;
252
290
  if (!handle || !output.manifest.resultCommitSha || !this.publicationGrantRedeemer) {
253
- throw new Error("sandbox_output_publish_forbidden: bridge publication grant redemption is unavailable.");
291
+ throw trustedSandboxFailure("sandbox_output_publish_forbidden", "bridge publication grant redemption is unavailable.");
254
292
  }
255
293
  const credential = await this.publicationGrantRedeemer({
256
294
  dispatchAttemptId: runtimeDispatch.sandbox.dispatchAttemptId,
@@ -269,29 +307,26 @@ export class DockerSandboxRuntime {
269
307
  resultCommitSha: output.manifest.resultCommitSha
270
308
  }));
271
309
  }
272
- const result = JSON.parse(await fs.readFile(output.resultPath, "utf8"));
273
- if (result.exitCode !== 0) {
274
- const resourceFailure = classifySandboxResourceFailure([
275
- result.summary,
276
- ...result.events.flatMap(resultEvent => [resultEvent.eventType, resultEvent.content, resultEvent.data ?? ""])
277
- ].join("\n"));
278
- if (resourceFailure) {
279
- return appendRunOnceEvent({
280
- ...result,
281
- summary: resourceFailure.message,
282
- events: [...result.events, event(resourceFailure.code, resourceFailure.message, { phase: "agent" })]
283
- }, memoryTelemetryEvent);
284
- }
285
- }
310
+ const rawResult = parseRunOnceResultPacket(JSON.parse(await fs.readFile(output.resultPath, "utf8")));
311
+ const result = {
312
+ ...rawResult,
313
+ resultCommitSha: output.manifest.resultCommitSha ?? rawResult.resultCommitSha ?? null,
314
+ publishedCommitSha: runtimeDispatch.sandbox.publicationMode === "bridge_push"
315
+ ? output.manifest.resultCommitSha
316
+ : rawResult.publishedCommitSha ?? null,
317
+ };
318
+ const canonicalResult = applyTrustedHostFailure(result, trustedHostFailure);
286
319
  await sink.emit(event("sandbox_output_imported", "Validated and imported sandbox output.", {
287
320
  resultCommitSha: output.manifest.resultCommitSha,
288
321
  }));
289
- return appendRunOnceEvent(result, memoryTelemetryEvent);
322
+ return appendRunOnceEvent(canonicalResult, memoryTelemetryEvent);
290
323
  }
291
324
  catch (error) {
292
- const message = error instanceof Error ? error.message : String(error);
293
- const classified = classifySandboxRuntimeFailure(message);
294
- return appendRunOnceEvent(failureResult(classified.message, [event(classified.code, classified.message, { phase: classified.phase })]), memoryTelemetryEvent);
325
+ const effectiveError = trustedHostFailure
326
+ ? new ForgeFailureError(trustedHostFailure.code, trustedHostFailure.message, "sandbox", { cause: error })
327
+ : error;
328
+ const classified = classifySandboxRuntimeFailure(effectiveError);
329
+ return appendRunOnceEvent(failureResult(classified.message, [event(classified.code, classified.message, { phase: classified.phase })], failureFactsForCode(classified.code, "sandbox")), memoryTelemetryEvent);
295
330
  }
296
331
  finally {
297
332
  try {
@@ -525,7 +560,7 @@ export class DockerSandboxRuntime {
525
560
  ledgerPath(dispatchAttemptId) {
526
561
  const attemptHex = dispatchAttemptId.replace(/-/g, "").toLowerCase();
527
562
  if (!/^[0-9a-f]{32}$/.test(attemptHex))
528
- throw new Error("sandbox_identity_invalid: dispatch attempt id must be a full UUID.");
563
+ throw trustedSandboxFailure("sandbox_identity_invalid", "dispatch attempt id must be a full UUID.");
529
564
  return path.join(this.config.sandboxStateRoot, "ledger", `${attemptHex}.json`);
530
565
  }
531
566
  async removeLedger(dispatchAttemptId) {
@@ -534,11 +569,11 @@ export class DockerSandboxRuntime {
534
569
  async buildImage(contextRoot, contextDigest, project, contract, upstreamImages, policy, sink, signal) {
535
570
  const toolingImage = process.env.FORGE_AGENT_TOOLING_IMAGE ?? "node:22.17.0-bookworm-slim";
536
571
  if (policy === "sandbox_required" && !/@sha256:[0-9a-f]{64}$/i.test(toolingImage)) {
537
- throw new Error("sandbox_build_failed: FORGE_AGENT_TOOLING_IMAGE must be digest-pinned for sandbox_required.");
572
+ throw trustedSandboxFailure("sandbox_build_failed", "FORGE_AGENT_TOOLING_IMAGE must be digest-pinned for sandbox_required.");
538
573
  }
539
574
  const codexVersion = process.env.FORGE_CODEX_PACKAGE_VERSION ?? "0.144.1";
540
575
  if (!/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/i.test(codexVersion))
541
- throw new Error("sandbox_build_failed: invalid pinned Codex package version.");
576
+ throw trustedSandboxFailure("sandbox_build_failed", "invalid pinned Codex package version.");
542
577
  const policyConfigurationDigest = await sandboxImagePolicyConfigurationDigest();
543
578
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
544
579
  const bridgeRuntimeDigest = await bridgeRuntimeContentDigest(packageRoot);
@@ -557,10 +592,10 @@ export class DockerSandboxRuntime {
557
592
  const existing = this.builds.get(key);
558
593
  if (existing) {
559
594
  await sink.emit(event("sandbox_image_cache_miss", `Sandbox image ${key.slice(0, 12)} is being built by another dispatch.`, { cacheKey: key, singleflight: true }));
560
- const waitStartedAt = Date.now();
595
+ const waitStartedAt = monotonicNowMs();
561
596
  const built = await existing;
562
597
  await sink.emit(event("sandbox_build_singleflight_wait", `Waited for the existing sandbox image build ${key.slice(0, 12)}.`, {
563
- durationMs: Date.now() - waitStartedAt,
598
+ durationMs: Math.round(monotonicNowMs() - waitStartedAt),
564
599
  imageDigest: built.imageDigest
565
600
  }));
566
601
  return built;
@@ -631,7 +666,7 @@ export class DockerSandboxRuntime {
631
666
  }
632
667
  await sink.emit(event("sandbox_image_cache_miss", `Sandbox image ${key.slice(0, 12)} requires a build.`, { cacheKey: key }));
633
668
  if (policy === "sandbox_required" && process.env.FORGE_SANDBOX_BUILD_EGRESS_ENFORCED !== "true") {
634
- throw new Error("sandbox_build_policy_failed: sandbox_required builds need an operator-enforced builder egress policy.");
669
+ throw trustedSandboxFailure("sandbox_build_policy_failed", "sandbox_required builds need an operator-enforced builder egress policy.");
635
670
  }
636
671
  const buildStartedAt = Date.now();
637
672
  await sink.emit(event("sandbox_build_started", `Building sandbox image ${key.slice(0, 12)}.`, { cacheKey: key }));
@@ -658,7 +693,7 @@ export class DockerSandboxRuntime {
658
693
  const installMode = await copyBridgePackageManifests(packageRoot, stagedBridgeRoot);
659
694
  const stagedBridgeRuntimeDigest = await bridgeRuntimeContentDigest(stagedBridgeRoot);
660
695
  if (stagedBridgeRuntimeDigest !== bridgeRuntimeDigest) {
661
- throw new Error("sandbox_build_failed: bridge runtime payload changed while preparing the sandbox image; retry the dispatch.");
696
+ throw trustedSandboxFailure("sandbox_build_failed", "bridge runtime payload changed while preparing the sandbox image; retry the dispatch.");
662
697
  }
663
698
  const dockerfile = agentOverlayDockerfile(toolingImage, projectContextName, installMode, codexVersion);
664
699
  await fs.writeFile(path.join(overlayRoot, "Dockerfile"), dockerfile);
@@ -666,7 +701,7 @@ export class DockerSandboxRuntime {
666
701
  await this.runBuildStage("tooling", key, buildxBuildArgs(builder, path.join(metadataRoot, "tooling.json"), ["--pull=false", "--target", "tooling", ...imageLabelArgs(project, key, "tooling", bridgeRuntimeDigest), "--tag", helperTag, overlayRoot]), sink, signal);
667
702
  const helperImageDigest = (await this.docker(["image", "inspect", helperTag, "--format", "{{.Id}}"], 15_000)).stdout.trim();
668
703
  if (!/^sha256:[0-9a-f]{64}$/i.test(helperImageDigest))
669
- throw new Error("sandbox_build_failed: helper image did not resolve to an immutable digest.");
704
+ throw trustedSandboxFailure("sandbox_build_failed", "helper image did not resolve to an immutable digest.");
670
705
  const projectContextRef = ociLayoutContextRef(path.relative(overlayRoot, projectOciRoot));
671
706
  await this.runBuildStage("agent", key, buildxBuildArgs(builder, path.join(metadataRoot, "agent.json"), [
672
707
  "--pull=false",
@@ -677,7 +712,7 @@ export class DockerSandboxRuntime {
677
712
  ]), sink, signal, { cwd: overlayRoot });
678
713
  const digest = (await this.docker(["image", "inspect", overlayTag, "--format", "{{.Id}}"], 15_000)).stdout.trim();
679
714
  if (!/^sha256:[0-9a-f]{64}$/i.test(digest))
680
- throw new Error("sandbox_build_failed: overlay image did not resolve to an immutable digest.");
715
+ throw trustedSandboxFailure("sandbox_build_failed", "overlay image did not resolve to an immutable digest.");
681
716
  const imagePolicy = await evaluateSandboxImagePolicy({
682
717
  key,
683
718
  project: dockerLabelValue(project),
@@ -752,7 +787,7 @@ export class DockerSandboxRuntime {
752
787
  byteCount: artifact.byteCount,
753
788
  truncated: artifact.truncated || result.truncated
754
789
  })).catch(() => undefined);
755
- throw new Error(`sandbox_build_failed: ${stage} image build failed; restricted log digest ${artifact.digest}.`);
790
+ throw trustedSandboxFailure("sandbox_build_failed", `${stage} image build failed; restricted log digest ${artifact.digest}.`);
756
791
  }
757
792
  async ensureBuildxBuilder(signal) {
758
793
  const name = dedicatedBuildxBuilderName(this.config.runnerId, this.config.dockerContext);
@@ -775,7 +810,7 @@ export class DockerSandboxRuntime {
775
810
  if (Number(hostConfig.PidsLimit) !== policy.builderPidsLimit
776
811
  || Number(hostConfig.Memory) !== policy.builderMemoryBytes
777
812
  || Number(hostConfig.MemorySwap) !== policy.builderMemoryBytes) {
778
- throw new Error("sandbox_build_policy_failed: dedicated BuildKit builder resource limits were not applied.");
813
+ throw trustedSandboxFailure("sandbox_build_policy_failed", "dedicated BuildKit builder resource limits were not applied.");
779
814
  }
780
815
  return name;
781
816
  }
@@ -848,10 +883,10 @@ export class DockerSandboxRuntime {
848
883
  return null;
849
884
  const image = process.env.FORGE_SANDBOX_EGRESS_PROXY_IMAGE?.trim();
850
885
  if (!image || !/@sha256:[0-9a-f]{64}$/iu.test(image)) {
851
- throw new Error("sandbox_egress_proxy_unavailable: public_allowlist needs a digest-pinned Squid-compatible proxy image.");
886
+ throw trustedSandboxFailure("sandbox_egress_proxy_unavailable", "public_allowlist needs a digest-pinned Squid-compatible proxy image.");
852
887
  }
853
888
  if (process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
854
- throw new Error("sandbox_egress_proxy_unavailable: runner egress enforcement is not enabled.");
889
+ throw trustedSandboxFailure("sandbox_egress_proxy_unavailable", "runner egress enforcement is not enabled.");
855
890
  }
856
891
  await this.verifyCatalogImage(image, dispatch.sandbox.executionPolicy, sink, signal);
857
892
  const name = `${resources.prefix}-egress`;
@@ -892,8 +927,8 @@ export class DockerSandboxRuntime {
892
927
  await sink.emit(event("sandbox_image_signature_warning", `Image signature enforcement is not configured for adoption-mode image ${image}.`));
893
928
  }
894
929
  async waitForServiceHealthy(name, signal) {
895
- const deadline = Date.now() + 60_000;
896
- while (Date.now() < deadline) {
930
+ const deadline = monotonicNowMs() + 60_000;
931
+ while (monotonicNowMs() < deadline) {
897
932
  if (signal?.aborted)
898
933
  throw new Error(String(signal.reason ?? "sandbox service startup cancelled"));
899
934
  const status = (await this.docker(["container", "inspect", name, "--format", "{{.State.Health.Status}}"], 10_000, signal)).stdout.trim();
@@ -1107,6 +1142,13 @@ export class DockerSandboxRuntime {
1107
1142
  docker(args, timeoutMs, signal, maxOutputBytes = 1024 * 1024) {
1108
1143
  return requireSandboxProcess({ command: this.config.dockerExecutable, args: this.dockerArgs(args), timeoutMs, maxOutputBytes, signal });
1109
1144
  }
1145
+ /** The container's init process: stopping it stops every process in the sandbox. */
1146
+ async containerInitProcess(containerId) {
1147
+ const pid = Number((await this.docker(["inspect", "--format", "{{.State.Pid}}", containerId], 10_000)).stdout.trim());
1148
+ return Number.isSafeInteger(pid) && pid > 1
1149
+ ? { rootPid: pid, rootIdentity: captureHostProcessIdentity(pid), processGroup: false }
1150
+ : null;
1151
+ }
1110
1152
  dockerArgs(args) { return this.config.dockerContext ? ["--context", this.config.dockerContext, ...args] : [...args]; }
1111
1153
  }
1112
1154
  class HostGit {
@@ -1162,7 +1204,7 @@ class HostGit {
1162
1204
  || !resultCommitSha
1163
1205
  || handle.branch !== dispatch.lease.worktreeKey
1164
1206
  || !/^[0-9a-f-]{32,36}$/iu.test(handle.grantId)) {
1165
- throw new Error("sandbox_output_publish_forbidden: remote publication grant is missing or outside its attempt scope.");
1207
+ throw trustedSandboxFailure("sandbox_output_publish_forbidden", "remote publication grant is missing or outside its attempt scope.");
1166
1208
  }
1167
1209
  assertCurrent();
1168
1210
  const credentialEnvironment = publicationCredentialEnvironment(credential);
@@ -1202,15 +1244,15 @@ class HostGit {
1202
1244
  terminateOnOutputLimit: true
1203
1245
  });
1204
1246
  if (objectInventory.exitCode !== 0 || objectInventory.truncated) {
1205
- throw new Error("sandbox_output_invalid: Git bundle exceeds object validation limits.");
1247
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git bundle exceeds object validation limits.");
1206
1248
  }
1207
1249
  validateGitObjectBudget(objectInventory.stdout);
1208
1250
  const imported = (await quarantineGit(quarantine, ["rev-parse", `${importRef}^{commit}`], 30_000)).stdout.trim();
1209
1251
  if (imported !== output.manifest.resultCommitSha)
1210
- throw new Error("sandbox_output_invalid: imported result SHA differs from manifest.");
1252
+ throw trustedSandboxFailure("sandbox_output_invalid", "imported result SHA differs from manifest.");
1211
1253
  const ancestry = await runSandboxProcess({ command: "git", args: ["-C", quarantine, "merge-base", "--is-ancestor", output.manifest.inputCommitSha, imported], timeoutMs: 30_000 });
1212
1254
  if (ancestry.exitCode !== 0)
1213
- throw new Error("sandbox_output_invalid: result commit is not descended from input commit.");
1255
+ throw trustedSandboxFailure("sandbox_output_invalid", "result commit is not descended from input commit.");
1214
1256
  const commitDepth = await quarantineGit(quarantine, ["rev-list", "--count", `${output.manifest.inputCommitSha}..${imported}`], 2 * 60_000);
1215
1257
  validateGitCommitDepth(commitDepth.stdout);
1216
1258
  await this.git(["fetch", "--no-write-fetch-head", quarantine, `${importRef}:${importRef}`], 5 * 60_000);
@@ -1235,12 +1277,7 @@ class HostGit {
1235
1277
  await this.git(["update-ref", branchRef, imported, managedBranchUpdateExpectedValue(current, expected, imported)], 30_000);
1236
1278
  return;
1237
1279
  }
1238
- const head = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "rev-parse", "HEAD"], timeoutMs: 30_000 })).stdout.trim();
1239
- const status = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "status", "--porcelain=v1", "--untracked-files=no"], timeoutMs: 30_000, maxOutputBytes: 4 * 1024 * 1024 })).stdout;
1240
- if (head !== expected || status.trim())
1241
- throw new Error("sandbox_output_conflict: managed worktree changed after sandbox input was captured.");
1242
- await this.git(["update-ref", branchRef, imported, expected], 30_000);
1243
- await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "reset", "--hard"], timeoutMs: 2 * 60_000, maxOutputBytes: 4 * 1024 * 1024 });
1280
+ await advanceCheckedOutBranch({ repoPath: this.repoPath, worktreePath: checkedOut.path, branchRef, expected, imported });
1244
1281
  }
1245
1282
  async resolveFirst(refs) {
1246
1283
  for (const ref of refs) {
@@ -1249,7 +1286,7 @@ class HostGit {
1249
1286
  if (result.exitCode === 0 && /^[0-9a-f]{40,64}$/i.test(sha))
1250
1287
  return sha;
1251
1288
  }
1252
- throw new Error("sandbox_input_failed: no approved input Git ref could be resolved.");
1289
+ throw trustedSandboxFailure("sandbox_input_failed", "no approved input Git ref could be resolved.");
1253
1290
  }
1254
1291
  git(args, timeoutMs, signal, env) { return requireSandboxProcess({ command: "git", args: ["-C", this.repoPath, ...args], timeoutMs, maxOutputBytes: 4 * 1024 * 1024, signal, env }); }
1255
1292
  }
@@ -1259,19 +1296,19 @@ export function managedBranchUpdateExpectedValue(current, expectedInput, importe
1259
1296
  return "0".repeat(imported.length);
1260
1297
  }
1261
1298
  if (normalized !== expectedInput) {
1262
- throw new Error("sandbox_output_conflict: managed branch changed after sandbox input was captured.");
1299
+ throw trustedSandboxFailure("sandbox_output_conflict", "managed branch changed after sandbox input was captured.");
1263
1300
  }
1264
1301
  return normalized;
1265
1302
  }
1266
1303
  export function publicationPushArgs(branch, resultCommitSha, inputCommitSha, remoteCommitSha, remote = "origin") {
1267
1304
  const isCommit = (value) => /^[0-9a-f]{40,64}$/iu.test(value);
1268
1305
  if (!branch || branch.length > 240 || !isCommit(resultCommitSha) || !isCommit(inputCommitSha) || (remoteCommitSha && !isCommit(remoteCommitSha))) {
1269
- throw new Error("sandbox_output_publish_rejected: publication inputs contain an invalid branch or object id.");
1306
+ throw trustedSandboxFailure("sandbox_output_publish_rejected", "publication inputs contain an invalid branch or object id.");
1270
1307
  }
1271
1308
  if (remoteCommitSha === resultCommitSha)
1272
1309
  return null;
1273
1310
  if (remoteCommitSha && remoteCommitSha !== inputCommitSha) {
1274
- throw new Error("sandbox_output_publish_stale: remote branch changed after the sandbox input was captured.");
1311
+ throw trustedSandboxFailure("sandbox_output_publish_stale", "remote branch changed after the sandbox input was captured.");
1275
1312
  }
1276
1313
  const remoteRef = `refs/heads/${branch}`;
1277
1314
  return [
@@ -1303,7 +1340,7 @@ export function validatePublicationCredential(credential, nowMs = Date.now()) {
1303
1340
  || credential.secret.length > 16 * 1024
1304
1341
  || /[\r\n\0]/u.test(credential.secret)
1305
1342
  || Date.parse(credential.expiresAt) <= nowMs) {
1306
- throw new Error("sandbox_output_publish_forbidden: redeemed publication credential is invalid or expired.");
1343
+ throw trustedSandboxFailure("sandbox_output_publish_forbidden", "redeemed publication credential is invalid or expired.");
1307
1344
  }
1308
1345
  }
1309
1346
  export function publicationCredentialEnvironment(credential, environment = process.env) {
@@ -1333,7 +1370,7 @@ export function restrictedBuildLog(source, exactSecrets = [], maximumBytes = 4 *
1333
1370
  export function validateGitObjectBudget(inventory, maximumObjectCount = 500_000, maximumExpandedBytes = 2 * 1024 * 1024 * 1024) {
1334
1371
  const lines = inventory.split(/\r?\n/u).filter(Boolean);
1335
1372
  if (lines.length === 0 || lines.length > maximumObjectCount) {
1336
- throw new Error("sandbox_output_invalid: Git bundle exceeds the object-count budget.");
1373
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git bundle exceeds the object-count budget.");
1337
1374
  }
1338
1375
  const maximum = BigInt(maximumExpandedBytes);
1339
1376
  let expanded = 0n;
@@ -1341,13 +1378,13 @@ export function validateGitObjectBudget(inventory, maximumObjectCount = 500_000,
1341
1378
  for (const line of lines) {
1342
1379
  const match = /^([0-9a-f]{40}|[0-9a-f]{64}) (blob|tree|commit|tag) ([0-9]+)$/iu.exec(line);
1343
1380
  if (!match || objects.has(match[1].toLowerCase())) {
1344
- throw new Error("sandbox_output_invalid: Git object inventory is malformed or duplicated.");
1381
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git object inventory is malformed or duplicated.");
1345
1382
  }
1346
1383
  objects.add(match[1].toLowerCase());
1347
1384
  const size = BigInt(match[3]);
1348
1385
  expanded += size;
1349
1386
  if (size > maximum || expanded > maximum) {
1350
- throw new Error("sandbox_output_invalid: Git bundle exceeds the expanded-object byte budget.");
1387
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git bundle exceeds the expanded-object byte budget.");
1351
1388
  }
1352
1389
  }
1353
1390
  return { objectCount: lines.length, expandedBytes: Number(expanded) };
@@ -1355,11 +1392,11 @@ export function validateGitObjectBudget(inventory, maximumObjectCount = 500_000,
1355
1392
  export function validateGitCommitDepth(value, maximumCommitDepth = 50_000) {
1356
1393
  const normalized = value.trim();
1357
1394
  if (!/^[0-9]+$/u.test(normalized)) {
1358
- throw new Error("sandbox_output_invalid: Git commit-depth result is malformed.");
1395
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git commit-depth result is malformed.");
1359
1396
  }
1360
1397
  const depth = BigInt(normalized);
1361
1398
  if (depth > BigInt(maximumCommitDepth)) {
1362
- throw new Error("sandbox_output_invalid: Git result exceeds the commit-depth budget.");
1399
+ throw trustedSandboxFailure("sandbox_output_invalid", "Git result exceeds the commit-depth budget.");
1363
1400
  }
1364
1401
  return Number(depth);
1365
1402
  }
@@ -1375,10 +1412,10 @@ export function selectAuditArtifactGcCandidates(records, retentionCount, retenti
1375
1412
  export function selectSandboxConfigRefs(executionPolicy, configuredSha, defaultBranch) {
1376
1413
  const approvedSha = configuredSha?.trim().toLowerCase() || null;
1377
1414
  if (executionPolicy === "sandbox_required" && !approvedSha) {
1378
- throw new Error("sandbox_config_commit_unapproved: sandbox_required dispatches need a server-approved config commit SHA.");
1415
+ throw trustedSandboxFailure("sandbox_config_commit_unapproved", "sandbox_required dispatches need a server-approved config commit SHA.");
1379
1416
  }
1380
1417
  if (approvedSha && !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(approvedSha)) {
1381
- throw new Error("sandbox_config_commit_invalid: approved sandbox config commit is not a full Git object id.");
1418
+ throw trustedSandboxFailure("sandbox_config_commit_invalid", "approved sandbox config commit is not a full Git object id.");
1382
1419
  }
1383
1420
  return approvedSha
1384
1421
  ? { refs: [approvedSha], approvedSha }
@@ -1423,12 +1460,12 @@ async function validateOutput(attemptRoot, dispatch) {
1423
1460
  const manifestPath = path.join(outputRoot, "manifest.json");
1424
1461
  const stat = await fs.lstat(manifestPath).catch(error => {
1425
1462
  if (isNodeErrorWithCode(error, "ENOENT")) {
1426
- throw new Error("sandbox_output_missing: sandbox worker did not produce manifest.json.");
1463
+ throw trustedSandboxFailure("sandbox_output_missing", "sandbox worker did not produce manifest.json.");
1427
1464
  }
1428
1465
  throw error;
1429
1466
  });
1430
1467
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024)
1431
- throw new Error("sandbox_output_invalid: manifest must be a bounded regular file.");
1468
+ throw trustedSandboxFailure("sandbox_output_invalid", "manifest must be a bounded regular file.");
1432
1469
  const manifest = JSON.parse(await fs.readFile(manifestPath, "utf8"));
1433
1470
  if (!dispatch.sandbox
1434
1471
  || manifest.dispatchAttemptId !== dispatch.sandbox.dispatchAttemptId
@@ -1439,10 +1476,10 @@ async function validateOutput(attemptRoot, dispatch) {
1439
1476
  || manifest.branch !== dispatch.lease.worktreeKey
1440
1477
  || manifest.contractDigest !== dispatch.sandbox.contractDigest
1441
1478
  || manifest.imageDigest !== dispatch.sandbox.imageDigest)
1442
- throw new Error("sandbox_output_invalid: manifest identity or fence mismatch.");
1479
+ throw trustedSandboxFailure("sandbox_output_invalid", "manifest identity or fence mismatch.");
1443
1480
  if ((manifest.resultCommitSha === null) !== (manifest.bundle === null)
1444
1481
  || (manifest.resultCommitSha !== null && !/^[0-9a-f]{40,64}$/i.test(manifest.resultCommitSha))) {
1445
- throw new Error("sandbox_output_invalid: result commit and bundle must be present together.");
1482
+ throw trustedSandboxFailure("sandbox_output_invalid", "result commit and bundle must be present together.");
1446
1483
  }
1447
1484
  const resultPath = await validateManifestFile(outputRoot, manifest.result, 16 * 1024 * 1024);
1448
1485
  const bundlePath = manifest.bundle ? await validateManifestFile(outputRoot, manifest.bundle, 512 * 1024 * 1024) : null;
@@ -1450,14 +1487,14 @@ async function validateOutput(attemptRoot, dispatch) {
1450
1487
  }
1451
1488
  async function validateManifestFile(root, file, max) {
1452
1489
  if (!/^[a-z0-9_.-]+$/i.test(file.path))
1453
- throw new Error("sandbox_output_invalid: output path is invalid.");
1490
+ throw trustedSandboxFailure("sandbox_output_invalid", "output path is invalid.");
1454
1491
  const target = path.join(root, file.path);
1455
1492
  const stat = await fs.lstat(target);
1456
1493
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== file.bytes || stat.size > max)
1457
- throw new Error("sandbox_output_invalid: output file bounds mismatch.");
1494
+ throw trustedSandboxFailure("sandbox_output_invalid", "output file bounds mismatch.");
1458
1495
  const digest = createHash("sha256").update(await fs.readFile(target)).digest("hex");
1459
1496
  if (digest !== file.sha256)
1460
- throw new Error("sandbox_output_invalid: output hash mismatch.");
1497
+ throw trustedSandboxFailure("sandbox_output_invalid", "output hash mismatch.");
1461
1498
  return target;
1462
1499
  }
1463
1500
  function isMissingSandboxManifest(error) {
@@ -1479,7 +1516,7 @@ export function sandboxWorkerFailureMessage(exitCode, stderr, containerError) {
1479
1516
  function identityFor(dispatch) {
1480
1517
  const value = dispatch.sandbox?.dispatchAttemptId.replace(/-/g, "").toLowerCase() ?? "";
1481
1518
  if (!/^[0-9a-f]{32}$/.test(value))
1482
- throw new Error("sandbox_identity_invalid: dispatch attempt id must be a full UUID.");
1519
+ throw trustedSandboxFailure("sandbox_identity_invalid", "dispatch attempt id must be a full UUID.");
1483
1520
  return { attemptHex: value };
1484
1521
  }
1485
1522
  class SandboxTeardownError extends Error {
@@ -1688,7 +1725,7 @@ export function assertSandboxImportCurrent(expected, current, signal, nowMs = Da
1688
1725
  || current.dispatchAttemptId !== expected.dispatchAttemptId
1689
1726
  || current.fencingToken !== expected.fencingToken
1690
1727
  || Date.parse(expected.expiresAt) <= nowMs) {
1691
- throw new Error("sandbox_output_stale: output cannot move the managed ref because its attempt, fence, or lease is no longer current.");
1728
+ throw trustedSandboxFailure("sandbox_output_stale", "output cannot move the managed ref because its attempt, fence, or lease is no longer current.");
1692
1729
  }
1693
1730
  }
1694
1731
  export function validSandboxLedger(value) {
@@ -1830,7 +1867,7 @@ export function sandboxResourceLabels(dispatch, image, contract) {
1830
1867
  ];
1831
1868
  const invalid = ownershipIds.find(([, value]) => !isFullUuid(value));
1832
1869
  if (invalid)
1833
- throw new Error(`sandbox_identity_invalid: ${invalid[0]} id must be a full UUID.`);
1870
+ throw trustedSandboxFailure("sandbox_identity_invalid", `${invalid[0]} id must be a full UUID.`);
1834
1871
  return {
1835
1872
  "dev.forge.managed": "true", "dev.forge.session-id": dispatch.session.id, "dev.forge.resource-lease-id": resourceLeaseId, "dev.forge.execution-lease-id": resourceLeaseId,
1836
1873
  "dev.forge.dispatch-attempt-id": dispatch.sandbox.dispatchAttemptId, "dev.forge.fencing-token": dispatch.lease.fencingToken,
@@ -1919,13 +1956,13 @@ export async function extractOciLayoutArchive(archivePath, destination, signal)
1919
1956
  signal
1920
1957
  });
1921
1958
  if (result.exitCode !== 0 || result.truncated) {
1922
- throw new Error(`sandbox_build_failed: project OCI layout extraction failed with exit code ${result.exitCode}; ${formatOciExtractionFailure(result)}. Archive retained at ${archivePath}.`);
1959
+ throw trustedSandboxFailure("sandbox_build_failed", `project OCI layout extraction failed with exit code ${result.exitCode}; ${formatOciExtractionFailure(result)}. Archive retained at ${archivePath}.`);
1923
1960
  }
1924
1961
  await fs.rm(archivePath, { force: true }).catch(() => undefined);
1925
1962
  }
1926
1963
  export function ociLayoutContextRef(layoutPath) {
1927
1964
  if (/^[A-Za-z]:[\\/]/u.test(layoutPath)) {
1928
- throw new Error("sandbox_build_failed: Windows absolute OCI layout paths are not BuildKit-safe; use a relative path from the build working directory.");
1965
+ throw trustedSandboxFailure("sandbox_build_failed", "Windows absolute OCI layout paths are not BuildKit-safe; use a relative path from the build working directory.");
1929
1966
  }
1930
1967
  const normalized = layoutPath.replace(/\\/gu, "/").replace(/^\.\//u, "");
1931
1968
  // BuildKit's oci-layout resolver expects a raw filesystem path here; it does not percent-decode
@@ -1945,7 +1982,7 @@ export async function readOciLayoutImageDigest(layoutRoot) {
1945
1982
  && /^sha256:[0-9a-f]{64}$/iu.test(entry.digest)
1946
1983
  && entry.annotations?.["vnd.docker.reference.type"] !== "attestation-manifest");
1947
1984
  if (!manifest || typeof manifest.digest !== "string") {
1948
- throw new Error("sandbox_build_failed: project OCI layout did not expose an immutable image digest.");
1985
+ throw trustedSandboxFailure("sandbox_build_failed", "project OCI layout did not expose an immutable image digest.");
1949
1986
  }
1950
1987
  return manifest.digest;
1951
1988
  }
@@ -1980,11 +2017,11 @@ export async function bridgeRuntimeContentDigest(packageRoot) {
1980
2017
  const distRoot = path.join(root, "dist");
1981
2018
  const distStat = await fs.lstat(distRoot).catch(() => null);
1982
2019
  if (!distStat?.isDirectory() || distStat.isSymbolicLink()) {
1983
- throw new Error("sandbox_build_failed: bridge runtime dist must be a real directory.");
2020
+ throw trustedSandboxFailure("sandbox_build_failed", "bridge runtime dist must be a real directory.");
1984
2021
  }
1985
2022
  const distFiles = await collectBridgeRuntimeFiles(root, "dist");
1986
2023
  if (distFiles.length === 0) {
1987
- throw new Error("sandbox_build_failed: bridge runtime dist is empty.");
2024
+ throw trustedSandboxFailure("sandbox_build_failed", "bridge runtime dist is empty.");
1988
2025
  }
1989
2026
  const files = [packageManifest, ...(lockManifest ? [lockManifest] : []), ...distFiles]
1990
2027
  .sort((left, right) => compareBridgeRuntimePaths(left.relativePath, right.relativePath));
@@ -2003,7 +2040,7 @@ export async function bridgeRuntimeContentDigest(packageRoot) {
2003
2040
  async function requireBridgeRuntimeFile(root, relativePath) {
2004
2041
  const file = await optionalBridgeRuntimeFile(root, relativePath);
2005
2042
  if (!file)
2006
- throw new Error(`sandbox_build_failed: bridge runtime ${relativePath} is missing.`);
2043
+ throw trustedSandboxFailure("sandbox_build_failed", `bridge runtime ${relativePath} is missing.`);
2007
2044
  return file;
2008
2045
  }
2009
2046
  async function optionalBridgeRuntimeFile(root, relativePath) {
@@ -2012,7 +2049,7 @@ async function optionalBridgeRuntimeFile(root, relativePath) {
2012
2049
  if (!stat)
2013
2050
  return null;
2014
2051
  if (!stat.isFile() || stat.isSymbolicLink()) {
2015
- throw new Error(`sandbox_build_failed: bridge runtime ${relativePath} must be a regular file.`);
2052
+ throw trustedSandboxFailure("sandbox_build_failed", `bridge runtime ${relativePath} must be a regular file.`);
2016
2053
  }
2017
2054
  return { absolutePath, relativePath: relativePath.replace(/\\/gu, "/") };
2018
2055
  }
@@ -2024,14 +2061,14 @@ async function collectBridgeRuntimeFiles(root, relativeDirectory) {
2024
2061
  for (const entry of entries) {
2025
2062
  const relativePath = path.join(relativeDirectory, entry.name);
2026
2063
  if (entry.isSymbolicLink()) {
2027
- throw new Error(`sandbox_build_failed: bridge runtime ${relativePath.replace(/\\/gu, "/")} cannot be a symbolic link.`);
2064
+ throw trustedSandboxFailure("sandbox_build_failed", `bridge runtime ${relativePath.replace(/\\/gu, "/")} cannot be a symbolic link.`);
2028
2065
  }
2029
2066
  if (entry.isDirectory()) {
2030
2067
  files.push(...await collectBridgeRuntimeFiles(root, relativePath));
2031
2068
  continue;
2032
2069
  }
2033
2070
  if (!entry.isFile()) {
2034
- throw new Error(`sandbox_build_failed: bridge runtime ${relativePath.replace(/\\/gu, "/")} must be a regular file.`);
2071
+ throw trustedSandboxFailure("sandbox_build_failed", `bridge runtime ${relativePath.replace(/\\/gu, "/")} must be a regular file.`);
2035
2072
  }
2036
2073
  files.push({
2037
2074
  absolutePath: path.join(root, relativePath),
@@ -2086,7 +2123,7 @@ async function copyOptionalBridgeManifest(packageRoot, bridgeRoot, fileName) {
2086
2123
  }
2087
2124
  export function buildxBuildArgs(builder, metadataFile, tail, environment = process.env, options = {}) {
2088
2125
  if (!/^forge-[0-9a-f]{20}$/u.test(builder))
2089
- throw new Error("sandbox_build_failed: invalid dedicated builder name.");
2126
+ throw trustedSandboxFailure("sandbox_build_failed", "invalid dedicated builder name.");
2090
2127
  const resources = buildResourcePolicy(environment);
2091
2128
  const args = ["buildx", "build", "--builder", builder];
2092
2129
  if (options.load !== false)
@@ -2108,7 +2145,7 @@ export function dedicatedBuildxBuilderName(runnerId, dockerContext) {
2108
2145
  }
2109
2146
  export function dedicatedBuildxBuilderContainerName(builder) {
2110
2147
  if (!/^forge-[0-9a-f]{20}$/u.test(builder))
2111
- throw new Error("sandbox_build_failed: invalid dedicated builder name.");
2148
+ throw trustedSandboxFailure("sandbox_build_failed", "invalid dedicated builder name.");
2112
2149
  return `buildx_buildkit_${builder}0`;
2113
2150
  }
2114
2151
  function boundedBuildCacheSize(value, fallback) {
@@ -2132,7 +2169,7 @@ export function selectImageGcCandidates(records, keepPerProject, ttlMs, nowMs) {
2132
2169
  async function sandboxProviderAuthForDispatch(dispatch) {
2133
2170
  const unavailable = sandboxProviderAuthUnavailableMessage(dispatch.execution.provider, dispatch.execution.authKind);
2134
2171
  if (unavailable) {
2135
- throw new Error(`sandbox_auth_unavailable: ${unavailable}`);
2172
+ throw trustedSandboxFailure("sandbox_auth_unavailable", unavailable);
2136
2173
  }
2137
2174
  const adapter = sandboxProviderAuthAdapterFor(dispatch.execution.provider, dispatch.execution.authKind);
2138
2175
  return adapter ? adapter.prepareAttemptAuth() : null;
@@ -2176,7 +2213,7 @@ export function proxyEnvironmentArgs(dispatch, contract, resources) {
2176
2213
  export function egressProxyConfig(allowedHosts) {
2177
2214
  const domains = allowedHosts.map(host => host.startsWith("*.") ? `.${host.slice(2)}` : host).join(" ");
2178
2215
  if (!domains)
2179
- throw new Error("sandbox_egress_policy_invalid: public_allowlist requires at least one approved host.");
2216
+ throw trustedSandboxFailure("sandbox_egress_policy_invalid", "public_allowlist requires at least one approved host.");
2180
2217
  return [
2181
2218
  "http_port 3128",
2182
2219
  "access_log none",
@@ -2208,7 +2245,7 @@ export function serviceContainerArgs(service, image, resources, labels, security
2208
2245
  else {
2209
2246
  const healthCommand = environment.FORGE_SERVICE_BROWSER_HEALTH_CMD?.trim();
2210
2247
  if (!healthCommand || /[\r\n\0]/u.test(healthCommand) || healthCommand.length > 1000) {
2211
- throw new Error("sandbox_service_health_policy_invalid: browser service needs an operator-configured bounded health command.");
2248
+ throw trustedSandboxFailure("sandbox_service_health_policy_invalid", "browser service needs an operator-configured bounded health command.");
2212
2249
  }
2213
2250
  args.push("--env", "FORGE_BROWSER_TOKEN_FILE=/run/secrets/browser-token", "--volume", `${resources.secretsVolume}:/run/secrets:ro`, "--health-cmd", healthCommand, "--health-interval", "1s", "--health-timeout", "5s", "--health-retries", "60");
2214
2251
  }
@@ -2221,13 +2258,13 @@ export function resolveSandboxSecurityOptions(executionPolicy, environment = pro
2221
2258
  const seccomp = environment.FORGE_SANDBOX_SECCOMP_PROFILE?.trim();
2222
2259
  const lsm = environment.FORGE_SANDBOX_LSM_SECURITY_OPT?.trim();
2223
2260
  if (seccomp && (!path.isAbsolute(seccomp) || /[\r\n\0]/u.test(seccomp))) {
2224
- throw new Error("sandbox_security_profile_invalid: seccomp profile must be an absolute host path.");
2261
+ throw trustedSandboxFailure("sandbox_security_profile_invalid", "seccomp profile must be an absolute host path.");
2225
2262
  }
2226
2263
  if (lsm && !/^(?:apparmor=[a-zA-Z0-9_.-]{1,128}|label=[a-zA-Z0-9_:,.-]{1,256})$/u.test(lsm)) {
2227
- throw new Error("sandbox_security_profile_invalid: LSM security option is invalid.");
2264
+ throw trustedSandboxFailure("sandbox_security_profile_invalid", "LSM security option is invalid.");
2228
2265
  }
2229
2266
  if (executionPolicy === "sandbox_required" && (!seccomp || !lsm)) {
2230
- throw new Error("sandbox_security_profile_unavailable: sandbox_required needs explicit seccomp and LSM profiles.");
2267
+ throw trustedSandboxFailure("sandbox_security_profile_unavailable", "sandbox_required needs explicit seccomp and LSM profiles.");
2231
2268
  }
2232
2269
  return [
2233
2270
  ...(seccomp ? ["--security-opt", `seccomp=${seccomp}`] : []),
@@ -2263,17 +2300,46 @@ function event(eventType, content, data) {
2263
2300
  };
2264
2301
  }
2265
2302
  export function classifySandboxRuntimeFailure(value) {
2266
- const message = value.replace(/[\r\n\t]+/gu, " ").trim().slice(0, 2000) || "Sandbox execution failed.";
2267
- const explicit = /^([a-z][a-z0-9_.-]{2,79}):/u.exec(message)?.[1] ?? null;
2268
- let code = explicit ?? "sandbox_runtime_failed";
2269
- if (/no space left|disk quota exceeded|enospc/iu.test(message))
2270
- code = "sandbox_storage_exhausted";
2271
- const phase = code.startsWith("sandbox_build") || code.startsWith("image_") ? "build"
2272
- : code.startsWith("sandbox_output") || code.startsWith("sandbox_import") ? "import"
2273
- : code.startsWith("teardown") ? "teardown"
2274
- : code.startsWith("sandbox_config") || code.startsWith("sandbox_auth") || code.startsWith("contract_") || code.startsWith("sandbox_input") || code.startsWith("sandbox_create") ? "prepare"
2275
- : "agent";
2276
- return { code, phase, message };
2303
+ const message = (value instanceof Error ? value.message : String(value))
2304
+ .replace(/[\r\n\t]+/gu, " ")
2305
+ .trim()
2306
+ .slice(0, 2000) || "Sandbox execution failed.";
2307
+ const code = value instanceof ForgeFailureError
2308
+ ? value.failureCode
2309
+ : "sandbox_runtime_failed";
2310
+ return { code, phase: failurePolicyForCode(code).phase, message };
2311
+ }
2312
+ export function applyTrustedHostFailure(result, trustedFailure) {
2313
+ if (!trustedFailure)
2314
+ return result;
2315
+ const originalFailure = result.failure
2316
+ ? [{
2317
+ code: result.failure.code,
2318
+ message: result.failure.message,
2319
+ source: result.failure.source,
2320
+ }, ...result.failure.causalChain]
2321
+ : result.exitCode === 0
2322
+ ? []
2323
+ : [{
2324
+ code: "sandbox_child_result_unknown",
2325
+ message: result.summary,
2326
+ source: "sandbox",
2327
+ }];
2328
+ const facts = {
2329
+ ...failureFactsForCode(trustedFailure.code, "sandbox"),
2330
+ causalChain: originalFailure,
2331
+ };
2332
+ return {
2333
+ ...result,
2334
+ schemaVersion: 2,
2335
+ exitCode: result.exitCode === 0 ? 1 : result.exitCode,
2336
+ summary: trustedFailure.message,
2337
+ failure: createFailureEnvelope(trustedFailure.message, facts),
2338
+ events: [
2339
+ ...result.events,
2340
+ event(trustedFailure.code, trustedFailure.message, { phase: facts.phase }),
2341
+ ],
2342
+ };
2277
2343
  }
2278
2344
  export function classifySandboxResourceFailure(value) {
2279
2345
  const diagnostic = value.replace(/[\r\n\t]+/gu, " ").trim().slice(0, 2000);
@@ -2293,6 +2359,9 @@ export function classifySandboxResourceFailure(value) {
2293
2359
  }
2294
2360
  return null;
2295
2361
  }
2362
+ function trustedSandboxFailure(code, detail, options) {
2363
+ return new ForgeFailureError(code, `${code}: ${detail}`, "sandbox", options);
2364
+ }
2296
2365
  function parseSandboxEventLine(line) {
2297
2366
  if (!line.trim().startsWith("{"))
2298
2367
  return null;
@@ -2307,25 +2376,25 @@ function parseSandboxEventLine(line) {
2307
2376
  return null;
2308
2377
  const candidate = value.event;
2309
2378
  if (!candidate || typeof candidate !== "object")
2310
- throw new Error("sandbox_event_invalid: runner event envelope is missing event data.");
2379
+ throw trustedSandboxFailure("sandbox_event_invalid", "runner event envelope is missing event data.");
2311
2380
  const eventValue = candidate;
2312
2381
  for (const field of ["role", "kind", "content", "eventType"]) {
2313
2382
  if (typeof eventValue[field] !== "string")
2314
- throw new Error(`sandbox_event_invalid: ${field} must be a string.`);
2383
+ throw trustedSandboxFailure("sandbox_event_invalid", `${field} must be a string.`);
2315
2384
  }
2316
2385
  if (eventValue.role.length > 64
2317
2386
  || eventValue.kind.length > 128
2318
2387
  || eventValue.eventType.length > 128
2319
2388
  || Buffer.byteLength(eventValue.content, "utf8") > 256 * 1024) {
2320
- throw new Error("sandbox_event_invalid: runner event exceeds field bounds.");
2389
+ throw trustedSandboxFailure("sandbox_event_invalid", "runner event exceeds field bounds.");
2321
2390
  }
2322
2391
  if (eventValue.data !== undefined && eventValue.data !== null
2323
2392
  && (typeof eventValue.data !== "string" || Buffer.byteLength(eventValue.data, "utf8") > 256 * 1024)) {
2324
- throw new Error("sandbox_event_invalid: runner event data exceeds field bounds.");
2393
+ throw trustedSandboxFailure("sandbox_event_invalid", "runner event data exceeds field bounds.");
2325
2394
  }
2326
2395
  if (eventValue.occurredAt !== undefined && eventValue.occurredAt !== null
2327
2396
  && (typeof eventValue.occurredAt !== "string" || !Number.isFinite(Date.parse(eventValue.occurredAt)))) {
2328
- throw new Error("sandbox_event_invalid: runner event occurredAt is invalid.");
2397
+ throw trustedSandboxFailure("sandbox_event_invalid", "runner event occurredAt is invalid.");
2329
2398
  }
2330
2399
  return {
2331
2400
  role: eventValue.role,