@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 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 (381) hide show
  1. package/README.md +306 -1
  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 +18 -1
  15. package/dist/bridge/bridge.service.d.ts +216 -4
  16. package/dist/bridge/bridge.service.js +2574 -90
  17. package/dist/bridge/bridge.types.d.ts +245 -2
  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 +33 -2
  41. package/dist/cleanup/cleanup.service.js +477 -3
  42. package/dist/cleanup/cleanup.types.d.ts +16 -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/index.d.ts +1 -1
  48. package/dist/cleanup/index.js +1 -1
  49. package/dist/cleanup/internals.d.ts +2 -2
  50. package/dist/cleanup/internals.js +1 -1
  51. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  52. package/dist/cleanup/managed-branch-sweep.js +111 -0
  53. package/dist/cli/cli.help.d.ts +2 -0
  54. package/dist/cli/cli.help.js +279 -0
  55. package/dist/cli/cli.service.d.ts +69 -12
  56. package/dist/cli/cli.service.js +557 -382
  57. package/dist/cli/idle-status.d.ts +84 -0
  58. package/dist/cli/idle-status.js +181 -0
  59. package/dist/cli/local-config.d.ts +13 -0
  60. package/dist/cli/local-config.js +82 -6
  61. package/dist/cli/provider-cli-detection.d.ts +10 -0
  62. package/dist/cli/provider-cli-detection.js +160 -0
  63. package/dist/runtime/aspnet-runtime-prebuild.d.ts +41 -0
  64. package/dist/runtime/aspnet-runtime-prebuild.js +474 -0
  65. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  66. package/dist/runtime/attempt-database-broker.js +390 -0
  67. package/dist/runtime/attempt-node-runtime-launcher.d.ts +18 -0
  68. package/dist/runtime/attempt-node-runtime-launcher.js +140 -0
  69. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  70. package/dist/runtime/attempt-path-operation.js +94 -0
  71. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  72. package/dist/runtime/attempt-private-directory.js +54 -0
  73. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  74. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  75. package/dist/runtime/attempt-process-supervisor.d.ts +121 -0
  76. package/dist/runtime/attempt-process-supervisor.js +471 -0
  77. package/dist/runtime/canonical-source-file.d.ts +3 -0
  78. package/dist/runtime/canonical-source-file.js +54 -0
  79. package/dist/runtime/docker-engine-probe.d.ts +95 -0
  80. package/dist/runtime/docker-engine-probe.js +340 -0
  81. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  82. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  83. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  84. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  85. package/dist/runtime/generated-output-reset.d.ts +20 -0
  86. package/dist/runtime/generated-output-reset.js +157 -0
  87. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  88. package/dist/runtime/host-database-capability-boundary.js +63 -0
  89. package/dist/runtime/host-diagnostics.d.ts +11 -0
  90. package/dist/runtime/host-diagnostics.js +192 -0
  91. package/dist/runtime/host-execution-root.d.ts +4 -0
  92. package/dist/runtime/host-execution-root.js +39 -0
  93. package/dist/runtime/host-facts.d.ts +36 -0
  94. package/dist/runtime/host-facts.js +95 -0
  95. package/dist/runtime/host-listener-inspector.d.ts +51 -0
  96. package/dist/runtime/host-listener-inspector.js +385 -0
  97. package/dist/runtime/host-load-admission.d.ts +67 -0
  98. package/dist/runtime/host-load-admission.js +99 -0
  99. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  100. package/dist/runtime/host-load-child-environment.js +76 -0
  101. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  102. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  103. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  104. package/dist/runtime/host-load-governor-config.js +83 -0
  105. package/dist/runtime/host-load-governor.d.ts +186 -0
  106. package/dist/runtime/host-load-governor.js +632 -0
  107. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  108. package/dist/runtime/host-load-ledger-lock.js +187 -0
  109. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  110. package/dist/runtime/host-load-runtime-settings.js +80 -0
  111. package/dist/runtime/host-load-sampler.d.ts +156 -0
  112. package/dist/runtime/host-load-sampler.js +298 -0
  113. package/dist/runtime/host-load-step-class.d.ts +70 -0
  114. package/dist/runtime/host-load-step-class.js +161 -0
  115. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  116. package/dist/runtime/host-load-step-reaper.js +95 -0
  117. package/dist/runtime/host-load-step-run.d.ts +73 -0
  118. package/dist/runtime/host-load-step-run.js +102 -0
  119. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  120. package/dist/runtime/host-load-test-slot.js +81 -0
  121. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  122. package/dist/runtime/host-load-token-ledger.js +453 -0
  123. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  124. package/dist/runtime/host-load-windows-cpu.js +85 -0
  125. package/dist/runtime/host-port-broker.d.ts +76 -0
  126. package/dist/runtime/host-port-broker.js +333 -0
  127. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  128. package/dist/runtime/host-pressure-stall.js +168 -0
  129. package/dist/runtime/host-runtime-contract.d.ts +74 -0
  130. package/dist/runtime/host-runtime-contract.js +846 -0
  131. package/dist/runtime/host-runtime-lease.d.ts +287 -0
  132. package/dist/runtime/host-runtime-lease.js +2763 -0
  133. package/dist/runtime/host-runtime-promotion.d.ts +55 -0
  134. package/dist/runtime/host-runtime-promotion.js +254 -0
  135. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  136. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  137. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  138. package/dist/runtime/host-runtime-requirements.js +117 -0
  139. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  140. package/dist/runtime/managed-command-teardown.js +596 -0
  141. package/dist/runtime/memory-capacity.d.ts +70 -0
  142. package/dist/runtime/memory-capacity.js +123 -0
  143. package/dist/runtime/native-test-postgres-fallback.d.ts +69 -0
  144. package/dist/runtime/native-test-postgres-fallback.js +143 -0
  145. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  146. package/dist/runtime/node-host-runtime-adapter.js +286 -0
  147. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  148. package/dist/runtime/pinned-directory-process.js +61 -0
  149. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  150. package/dist/runtime/pinned-source-directory.js +94 -0
  151. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  152. package/dist/runtime/playwright-browser-cache.js +227 -0
  153. package/dist/runtime/playwright-host-runtime-adapter.d.ts +39 -0
  154. package/dist/runtime/playwright-host-runtime-adapter.js +274 -0
  155. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  156. package/dist/runtime/prepared-runtime-identity.js +218 -0
  157. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  158. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  159. package/dist/runtime/runner-settings.d.ts +104 -0
  160. package/dist/runtime/runner-settings.js +236 -0
  161. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  162. package/dist/runtime/runtime-isolation-lease.js +161 -0
  163. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  164. package/dist/runtime/workspace-resource-estimator.js +174 -0
  165. package/dist/sandbox/command-runner.d.ts +4 -0
  166. package/dist/sandbox/command-runner.js +47 -0
  167. package/dist/sandbox/contract.d.ts +5 -0
  168. package/dist/sandbox/contract.js +276 -0
  169. package/dist/sandbox/event-budget.d.ts +11 -0
  170. package/dist/sandbox/event-budget.js +27 -0
  171. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  172. package/dist/sandbox/host-capacity-broker.js +336 -0
  173. package/dist/sandbox/image-policy.d.ts +35 -0
  174. package/dist/sandbox/image-policy.js +247 -0
  175. package/dist/sandbox/index.d.ts +5 -0
  176. package/dist/sandbox/index.js +5 -0
  177. package/dist/sandbox/lease-watchdog.d.ts +18 -0
  178. package/dist/sandbox/lease-watchdog.js +67 -0
  179. package/dist/sandbox/managed-branch.d.ts +13 -0
  180. package/dist/sandbox/managed-branch.js +36 -0
  181. package/dist/sandbox/preflight.d.ts +84 -0
  182. package/dist/sandbox/preflight.js +521 -0
  183. package/dist/sandbox/process.d.ts +20 -0
  184. package/dist/sandbox/process.js +209 -0
  185. package/dist/sandbox/provider-auth/codex.d.ts +26 -0
  186. package/dist/sandbox/provider-auth/codex.js +212 -0
  187. package/dist/sandbox/repository-lock.d.ts +6 -0
  188. package/dist/sandbox/repository-lock.js +129 -0
  189. package/dist/sandbox/runtime.d.ts +311 -0
  190. package/dist/sandbox/runtime.js +2407 -0
  191. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  192. package/dist/sandbox/sandbox-cgroups.js +42 -0
  193. package/dist/sandbox/sandbox.types.d.ts +93 -0
  194. package/dist/sandbox/sandbox.types.js +1 -0
  195. package/dist/sandbox/smoke.d.ts +76 -0
  196. package/dist/sandbox/smoke.js +380 -0
  197. package/dist/sandbox/worker-supervisor.d.ts +13 -0
  198. package/dist/sandbox/worker-supervisor.js +36 -0
  199. package/dist/sandbox/worker.d.ts +1 -0
  200. package/dist/sandbox/worker.js +225 -0
  201. package/dist/sandbox/workspace.service.d.ts +13 -0
  202. package/dist/sandbox/workspace.service.js +74 -0
  203. package/dist/session/architect-waits.d.ts +2 -0
  204. package/dist/session/architect-waits.js +138 -0
  205. package/dist/session/managed-attempt-tools.d.ts +48 -0
  206. package/dist/session/managed-attempt-tools.js +1299 -0
  207. package/dist/session/managed-build-coordinator.d.ts +5 -0
  208. package/dist/session/managed-build-coordinator.js +109 -0
  209. package/dist/session/managed-build-receipt.d.ts +26 -0
  210. package/dist/session/managed-build-receipt.js +342 -0
  211. package/dist/session/managed-command-host-load.d.ts +47 -0
  212. package/dist/session/managed-command-host-load.js +83 -0
  213. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  214. package/dist/session/managed-verification-timeouts.js +17 -0
  215. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  216. package/dist/session/mcp-argument-coercion.js +121 -0
  217. package/dist/session/phase-completion.artifacts.d.ts +34 -0
  218. package/dist/session/phase-completion.artifacts.js +903 -0
  219. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  220. package/dist/session/phase-completion.command-validation.js +77 -0
  221. package/dist/session/phase-completion.d.ts +65 -42
  222. package/dist/session/phase-completion.helpers.d.ts +117 -0
  223. package/dist/session/phase-completion.helpers.js +708 -0
  224. package/dist/session/phase-completion.js +130 -3007
  225. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  226. package/dist/session/phase-completion.mcp-args.js +156 -0
  227. package/dist/session/phase-completion.prompts.d.ts +14 -0
  228. package/dist/session/phase-completion.prompts.js +238 -0
  229. package/dist/session/phase-completion.runtime.d.ts +43 -0
  230. package/dist/session/phase-completion.runtime.js +721 -0
  231. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  232. package/dist/session/phase-completion.schema-parts.js +188 -0
  233. package/dist/session/phase-completion.schemas.d.ts +3 -0
  234. package/dist/session/phase-completion.schemas.js +836 -0
  235. package/dist/session/phase-completion.validation.d.ts +37 -0
  236. package/dist/session/phase-completion.validation.js +874 -0
  237. package/dist/session/pre-publication-host-load.d.ts +27 -0
  238. package/dist/session/pre-publication-host-load.js +111 -0
  239. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  240. package/dist/session/pre-publication-native-postgres.js +111 -0
  241. package/dist/session/pre-publication-pass.d.ts +61 -0
  242. package/dist/session/pre-publication-pass.js +148 -0
  243. package/dist/session/pre-publication-process.d.ts +23 -0
  244. package/dist/session/pre-publication-process.js +109 -0
  245. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  246. package/dist/session/pre-publication-skipped-tests.js +109 -0
  247. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  248. package/dist/session/pre-publication-step-execution.js +50 -0
  249. package/dist/session/pre-publication-validation.d.ts +91 -0
  250. package/dist/session/pre-publication-validation.js +670 -0
  251. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  252. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  253. package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
  254. package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
  255. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  256. package/dist/session/provider-cli/claude-background-work.js +181 -0
  257. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  258. package/dist/session/provider-cli/host-build-lock.js +30 -0
  259. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  260. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  261. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +96 -0
  262. package/dist/session/provider-cli/provider-cli.artifacts.js +818 -0
  263. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  264. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  265. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  266. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  267. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  268. package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
  269. package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
  270. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
  271. package/dist/session/provider-cli/provider-cli.deterministic.js +407 -0
  272. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  273. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  274. package/dist/session/provider-cli/provider-cli.process.d.ts +114 -0
  275. package/dist/session/provider-cli/provider-cli.process.js +757 -0
  276. package/dist/session/provider-cli/provider-cli.prompts.d.ts +62 -0
  277. package/dist/session/provider-cli/provider-cli.prompts.js +770 -0
  278. package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
  279. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
  280. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  281. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  282. package/dist/session/provider-cli/provider-cli.runtime.d.ts +30 -0
  283. package/dist/session/provider-cli/provider-cli.runtime.js +120 -0
  284. package/dist/session/provider-cli/provider-cli.service.d.ts +53 -53
  285. package/dist/session/provider-cli/provider-cli.service.js +1299 -2523
  286. package/dist/session/provider-cli/provider-cli.types.d.ts +38 -0
  287. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  288. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  289. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  290. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  291. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  292. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  293. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  294. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  295. package/dist/session/provider-cli/provider-output-state.d.ts +40 -0
  296. package/dist/session/provider-cli/provider-output-state.js +832 -0
  297. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  298. package/dist/session/provider-cli/provider-usage.js +28 -5
  299. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  300. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  301. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  302. package/dist/session/publishable-worktree-changes.js +193 -0
  303. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  304. package/dist/session/qa-sidecar-validation.js +28 -0
  305. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  306. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  307. package/dist/session/session-redaction.d.ts +3 -0
  308. package/dist/session/session-redaction.js +298 -0
  309. package/dist/session/session.base.d.ts +14 -1
  310. package/dist/session/session.service.d.ts +17 -2
  311. package/dist/session/session.service.js +708 -60
  312. package/dist/session/session.types.d.ts +327 -3
  313. package/dist/session/session.types.js +951 -10
  314. package/dist/session/sidecar-json-shape.d.ts +31 -0
  315. package/dist/session/sidecar-json-shape.js +217 -0
  316. package/dist/session/unreferenced-exports.d.ts +12 -0
  317. package/dist/session/unreferenced-exports.js +59 -0
  318. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  319. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  320. package/dist/shared/format/format-bytes.d.ts +1 -0
  321. package/dist/shared/format/format-bytes.js +9 -0
  322. package/dist/shared/fs/file-identity.d.ts +10 -0
  323. package/dist/shared/fs/file-identity.js +15 -0
  324. package/dist/shared/fs/replace-file.d.ts +7 -0
  325. package/dist/shared/fs/replace-file.js +33 -0
  326. package/dist/shared/git/git.js +2 -1
  327. package/dist/shared/path/path.d.ts +1 -0
  328. package/dist/shared/path/path.js +21 -1
  329. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  330. package/dist/shared/process/dotnet-toolchain.js +307 -0
  331. package/dist/shared/process/host-process-recovery.d.ts +23 -0
  332. package/dist/shared/process/host-process-recovery.js +99 -0
  333. package/dist/shared/process/host-process-supervisor.d.ts +72 -0
  334. package/dist/shared/process/host-process-supervisor.js +383 -0
  335. package/dist/shared/process/process-tree.d.ts +52 -0
  336. package/dist/shared/process/process-tree.js +144 -0
  337. package/dist/shared/process/process.d.ts +70 -0
  338. package/dist/shared/process/process.js +224 -16
  339. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  340. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  341. package/dist/shared/process/windows-launch.d.ts +26 -0
  342. package/dist/shared/process/windows-launch.js +109 -0
  343. package/dist/shared/provider-capabilities.d.ts +4 -0
  344. package/dist/shared/provider-capabilities.js +95 -0
  345. package/dist/shared/redaction/redaction.d.ts +1 -0
  346. package/dist/shared/redaction/redaction.js +47 -4
  347. package/dist/shared/time/monotonic.d.ts +1 -0
  348. package/dist/shared/time/monotonic.js +8 -0
  349. package/dist/version.d.ts +1 -1
  350. package/dist/version.js +1 -1
  351. package/dist/worktree/artifact-injector.d.ts +3 -2
  352. package/dist/worktree/artifact-injector.js +82 -10
  353. package/dist/worktree/dependency-warmer.d.ts +78 -1
  354. package/dist/worktree/dependency-warmer.js +731 -13
  355. package/dist/worktree/index.d.ts +2 -1
  356. package/dist/worktree/index.js +1 -0
  357. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  358. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  359. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  360. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  361. package/dist/worktree/wip-git.d.ts +33 -0
  362. package/dist/worktree/wip-git.js +122 -0
  363. package/dist/worktree/wip-refs.d.ts +62 -0
  364. package/dist/worktree/wip-refs.js +119 -0
  365. package/dist/worktree/wip-restore.d.ts +38 -0
  366. package/dist/worktree/wip-restore.js +190 -0
  367. package/dist/worktree/wip-snapshot.d.ts +50 -0
  368. package/dist/worktree/wip-snapshot.js +268 -0
  369. package/dist/worktree/worktree-paths.d.ts +4 -0
  370. package/dist/worktree/worktree-paths.js +30 -0
  371. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  372. package/dist/worktree/worktree-wip-events.js +98 -0
  373. package/dist/worktree/worktree-wip.d.ts +49 -0
  374. package/dist/worktree/worktree-wip.js +182 -0
  375. package/dist/worktree/worktree.base.d.ts +10 -1
  376. package/dist/worktree/worktree.service.d.ts +30 -4
  377. package/dist/worktree/worktree.service.js +379 -54
  378. package/dist/worktree/worktree.types.d.ts +38 -1
  379. package/package.json +12 -7
  380. package/runtime/windows-job-supervisor.ps1 +722 -0
  381. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -1,27 +1,42 @@
1
1
  import fs from "node:fs/promises";
2
- import { execFile } from "node:child_process";
3
2
  import os from "node:os";
4
3
  import path from "node:path";
5
4
  import { createInterface } from "node:readline/promises";
6
- import { promisify } from "node:util";
7
- import { resolveCursorAgentDirectLaunch } from "../shared/cursor-agent/cursor-agent.launch.js";
8
- import { redactSecrets, redactText } from "../shared/redaction/redaction.js";
9
- import { defaultBridgeServiceConfig, ForgeBridgeService } from "../bridge/bridge.service.js";
5
+ import { configureDotNetToolchain } from "../shared/process/dotnet-toolchain.js";
6
+ import { supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
7
+ import { redactText } from "../shared/redaction/redaction.js";
8
+ import { BridgeRevokedError, bridgeRevokedExitCode, defaultBridgeServiceConfig, ForgeBridgeService, } from "../bridge/bridge.service.js";
10
9
  import { forgeBridgeVersion } from "../version.js";
11
- import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, writeLocalConfig } from "./local-config.js";
10
+ import { ManagedWorktreeCleanupService } from "../cleanup/cleanup.service.js";
11
+ import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, resolveLocalYieldFlagPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
12
12
  import { BridgeSessionService } from "../session/session.service.js";
13
+ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
14
+ import { validateDockerfilePolicy, validateSandboxContract } from "../sandbox/contract.js";
15
+ import { DockerPreflight } from "../sandbox/preflight.js";
16
+ import { DockerSandboxRuntime } from "../sandbox/runtime.js";
17
+ import { DockerSandboxSmoke } from "../sandbox/smoke.js";
13
18
  import { parseCompletionMcpArgs, runCompletionMcpServer } from "../session/phase-completion.js";
14
- import { failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
19
+ import { failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
20
+ import { commandHelpText, helpText } from "./cli.help.js";
21
+ import { readLocalYieldFlag, writeLocalYieldFlag } from "../bridge/local-yield-flag.js";
22
+ import { detectCliProviders } from "./provider-cli-detection.js";
23
+ import { idleSummaryLine, parseStatusArgs, runIdleStatusCommand } from "./idle-status.js";
24
+ export { claudeDefaultModels, parseCodexModelCatalog, parseCursorModelList } from "./provider-cli-detection.js";
15
25
  const apiKeySecretGrantEnv = "FORGE_API_KEY_SECRET_GRANT";
16
- const execFileAsync = promisify(execFile);
17
26
  export class ForgeBridgeCliService {
18
27
  sessions;
19
28
  bridgeFactory;
20
29
  pairRunner;
21
- constructor(sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner) {
30
+ cleanupFactory;
31
+ dotNetToolchainConfigurator;
32
+ constructor(
33
+ // In a Docker sandbox the default chain's validator asks the host bridge for host load tokens (decision 0013).
34
+ sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
22
35
  this.sessions = sessions;
23
36
  this.bridgeFactory = bridgeFactory;
24
37
  this.pairRunner = pairRunner;
38
+ this.cleanupFactory = cleanupFactory;
39
+ this.dotNetToolchainConfigurator = dotNetToolchainConfigurator;
25
40
  }
26
41
  async run(argv, io = { stdout: process.stdout, stderr: process.stderr }) {
27
42
  if (argv.length === 0 || argv[0] === "--help" || argv[0] === "-h") {
@@ -56,15 +71,41 @@ export class ForgeBridgeCliService {
56
71
  io.stderr.write(`forge-bridge connect requires ${missing[0]}.\n`);
57
72
  return 2;
58
73
  }
74
+ let dotNetToolchain;
75
+ try {
76
+ dotNetToolchain = await this.dotNetToolchainConfigurator(await dotNetPreflightRoots(config, args.implicitCloneDestination), { cloneFolders: [config.defaultRepoRoot.trim()].filter(Boolean) });
77
+ }
78
+ catch (error) {
79
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
80
+ return 1;
81
+ }
82
+ if (dotNetToolchain) {
83
+ io.stdout.write(`Using .NET SDK ${dotNetToolchain.sdkVersion}: ${dotNetToolchain.executablePath}\n`);
84
+ }
59
85
  const controller = new AbortController();
60
86
  const stop = () => controller.abort("signal received");
61
87
  process.once("SIGINT", stop);
62
88
  process.once("SIGTERM", stop);
63
89
  try {
90
+ if (config.cleanupWorktrees && config.repoMappings.some(mapping => mapping.localPath?.trim())) {
91
+ io.stdout.write("Cleaning stale managed worktrees before accepting dispatches.\n");
92
+ await cleanupRepos(config, "stale", true, this.cleanupFactory(config.sandboxStateRoot), io);
93
+ // Forge branches on this device whose work has merged since the bridge last ran.
94
+ await cleanupRepos(config, "merged", true, this.cleanupFactory(config.sandboxStateRoot), io);
95
+ }
64
96
  io.stdout.write(connectStartupText(config));
65
97
  await this.bridgeFactory(config).run(controller.signal);
66
98
  return 0;
67
99
  }
100
+ catch (error) {
101
+ if (error instanceof BridgeRevokedError) {
102
+ // Decision 0014: removed from Forge. Exit with a distinct code so a supervisor can
103
+ // tell "pair again" apart from a crash.
104
+ io.stderr.write(`${error.message}\n`);
105
+ return bridgeRevokedExitCode;
106
+ }
107
+ throw error;
108
+ }
68
109
  finally {
69
110
  process.off("SIGINT", stop);
70
111
  process.off("SIGTERM", stop);
@@ -86,14 +127,24 @@ export class ForgeBridgeCliService {
86
127
  if (args.command === "pair") {
87
128
  try {
88
129
  const current = readLocalConfigSync();
130
+ io.stdout.write(`Pairing with server: ${args.serverUrl}\n`);
89
131
  const code = await resolvePairingCode(args.code);
90
- const repoRoot = await resolvePairRepoRoot(args.repoRoot, current.defaultRepoRoot);
91
- await fs.mkdir(repoRoot, { recursive: true });
92
- const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot });
132
+ const provisionalRoot = path.resolve(args.repoRoot ?? current.defaultRepoRoot ?? path.join(os.homedir(), "ForgeRepos"));
133
+ const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot: provisionalRoot });
93
134
  const claim = await this.pairRunner(pairArgs);
94
- const next = pairedConfig(current, pairArgs, claim);
95
- await writeLocalConfig(next);
96
- io.stdout.write(`Paired runner ${claim.runnerId}.\n`);
135
+ // The code is spent now: save the credentials before anything else can fail or prompt.
136
+ const applied = applyPairHost(pairArgs, claim.host, args.repoRoot !== undefined, io);
137
+ await writeLocalConfig(pairedConfig(current, applied.args, claim));
138
+ let repoRoot = applied.args.repoRoot;
139
+ if (!args.repoRoot && !applied.repoRootFromHost) {
140
+ const answered = await promptPairRepoRoot(repoRoot);
141
+ if (answered !== repoRoot) {
142
+ repoRoot = answered;
143
+ await writeLocalConfig(pairedConfig(current, { ...applied.args, repoRoot }, claim));
144
+ }
145
+ }
146
+ await fs.mkdir(repoRoot, { recursive: true });
147
+ io.stdout.write(`Paired runner ${claim.runnerId}${applied.args.name ? ` (${applied.args.name})` : ""}.\n`);
97
148
  io.stdout.write(`Repo folder: ${repoRoot}\n`);
98
149
  io.stdout.write(`Config: ${resolveLocalConfigPath()}\n`);
99
150
  io.stdout.write("Start the bridge with: forge-bridge connect\n");
@@ -115,12 +166,68 @@ export class ForgeBridgeCliService {
115
166
  return 2;
116
167
  }
117
168
  }
118
- if (args.command === "status") {
119
- await writeStatus(args.config, args.checkUpdates, io);
169
+ if (args.command === "server-show") {
170
+ const saved = readLocalConfigSync().serverUrl ?? "not configured";
171
+ io.stdout.write(`Saved server: ${saved}\n`);
172
+ if (process.env.FORGE_URL?.trim()) {
173
+ io.stdout.write(`Effective server: ${process.env.FORGE_URL.trim()} (FORGE_URL override)\n`);
174
+ }
175
+ else {
176
+ io.stdout.write(`Effective server: ${args.config.serverUrl || "not configured"}\n`);
177
+ }
120
178
  return 0;
121
179
  }
180
+ if (args.command === "server-set") {
181
+ try {
182
+ const config = await setServerUrl(args.serverUrl);
183
+ io.stdout.write(`Saved Forge server: ${config.serverUrl}\n`);
184
+ io.stdout.write("Existing runner credentials were retained. Re-run `forge-bridge pair --server <url>` if this is a different Forge deployment.\n");
185
+ if (process.env.FORGE_URL?.trim()) {
186
+ io.stdout.write(`Warning: FORGE_URL is set to ${process.env.FORGE_URL.trim()} and overrides the saved server.\n`);
187
+ }
188
+ return 0;
189
+ }
190
+ catch (error) {
191
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
192
+ return 2;
193
+ }
194
+ }
195
+ if (args.command === "status") {
196
+ return await runStatus(args, io);
197
+ }
122
198
  if (args.command === "cleanup") {
123
- return await cleanupRepos(args.config, args.mode, args.force, io);
199
+ return await cleanupRepos(args.config, args.mode, args.force, this.cleanupFactory(args.config.sandboxStateRoot), io);
200
+ }
201
+ if (args.command === "sandbox-init") {
202
+ return await initializeSandbox(args.repoPath, io);
203
+ }
204
+ if (args.command === "sandbox-doctor") {
205
+ return await diagnoseSandbox(args.repoPath, args.requirePinnedBase, io);
206
+ }
207
+ if (args.command === "sandbox-smoke") {
208
+ return await smokeSandbox(args.repoPath, args.reportPath, args.requirePinnedBase, args.probeLoopbackPort, io);
209
+ }
210
+ if (args.command === "sandbox-reap") {
211
+ return await reapSandboxes(io);
212
+ }
213
+ if (args.command === "sandbox-on") {
214
+ const saved = await setSandboxPolicy(true, args.allowOpenPublic);
215
+ io.stdout.write("Saved local Docker sandbox policy. Restart the bridge to apply it.\n");
216
+ writeSandboxPolicyStatus(saved, io);
217
+ return 0;
218
+ }
219
+ if (args.command === "sandbox-off") {
220
+ const saved = await setSandboxPolicy(false, false);
221
+ io.stdout.write("Disabled local Docker sandbox placement. Restart the bridge to apply it.\n");
222
+ writeSandboxPolicyStatus(saved, io);
223
+ return 0;
224
+ }
225
+ if (args.command === "sandbox-status") {
226
+ writeSandboxPolicyStatus(readLocalConfigSync(), io);
227
+ return 0;
228
+ }
229
+ if (args.command === "yield") {
230
+ return await runYieldCommand(args.action, io);
124
231
  }
125
232
  if (args.command === "mcp") {
126
233
  const parsed = parseCompletionMcpArgs(args.argv);
@@ -140,17 +247,17 @@ export class ForgeBridgeCliService {
140
247
  emit: async (event) => {
141
248
  const line = {
142
249
  type: "runner_event",
143
- event: redactSecrets(event, redactionSecrets)
250
+ event: redactRunnerDispatchEvent(event, redactionSecrets)
144
251
  };
145
252
  io.stdout.write(`${JSON.stringify(line)}\n`);
146
253
  }
147
254
  });
148
- await writeJsonAtomic(args.resultPath, redactSecrets(result, redactionSecrets));
255
+ await writeJsonAtomic(args.resultPath, redactRunOnceResultPacket(result, redactionSecrets));
149
256
  return result.exitCode;
150
257
  }
151
258
  catch (error) {
152
259
  const summary = redactText(error instanceof Error ? error.message : String(error), redactionSecrets);
153
- await writeJsonAtomic(args.resultPath, failureResult(summary)).catch(() => undefined);
260
+ await writeJsonAtomic(args.resultPath, redactRunOnceResultPacket(failureResult(summary, [], failureFactsFromError(error, { source: "bridge" })), redactionSecrets)).catch(() => undefined);
154
261
  io.stderr.write(`${summary}\n`);
155
262
  return 1;
156
263
  }
@@ -159,6 +266,36 @@ export class ForgeBridgeCliService {
159
266
  }
160
267
  }
161
268
  }
269
+ /**
270
+ * Decision 0014 `forge-bridge yield`: the host's own yield switch. It writes a
271
+ * flag file next to the bridge config (never bridge.json); a running bridge
272
+ * polls it and stops taking new attempts without a restart.
273
+ */
274
+ async function runYieldCommand(action, io) {
275
+ const flagPath = resolveLocalYieldFlagPath();
276
+ try {
277
+ if (action !== "status") {
278
+ await writeLocalYieldFlag(flagPath, action === "on");
279
+ }
280
+ const on = await readLocalYieldFlag(flagPath);
281
+ if (action === "on") {
282
+ io.stdout.write("Local yield to foreground is on. A running bridge takes no new attempts within one heartbeat; running attempts finish.\n");
283
+ }
284
+ else if (action === "off") {
285
+ io.stdout.write("Local yield to foreground is off. The bridge takes new attempts again unless yield is on in Forge.\n");
286
+ }
287
+ else {
288
+ io.stdout.write(`Local yield to foreground: ${on ? "on" : "off"}\n`);
289
+ }
290
+ io.stdout.write(`Flag file: ${flagPath}\n`);
291
+ io.stdout.write("The effective state also depends on Forge: the runner yields when this flag or its Yield toggle in Forge is on.\n");
292
+ return 0;
293
+ }
294
+ catch (error) {
295
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
296
+ return 1;
297
+ }
298
+ }
162
299
  function attachEnvSecretGrant(dispatch) {
163
300
  if (!dispatch.execution.requiresApiKeySecretGrant) {
164
301
  delete process.env[apiKeySecretGrantEnv];
@@ -231,18 +368,17 @@ export function parseArgs(argv) {
231
368
  }
232
369
  return { ok: true, command: "remove-repo", label: argv[1] };
233
370
  }
234
- if (argv[0] === "status") {
235
- let checkUpdates = false;
236
- for (let index = 1; index < argv.length; index += 1) {
237
- const arg = argv[index];
238
- if (arg === "--check-updates") {
239
- checkUpdates = true;
240
- }
241
- else {
242
- return { ok: false, error: `Unknown argument: ${arg}` };
243
- }
371
+ if (argv[0] === "server") {
372
+ if (argv.length === 1 || (argv[1] === "show" && argv.length === 2)) {
373
+ return { ok: true, command: "server-show", config: configuredBridgeServiceConfig() };
374
+ }
375
+ if (argv[1] === "set" && argv[2] && argv.length === 3) {
376
+ return { ok: true, command: "server-set", serverUrl: argv[2] };
244
377
  }
245
- return { ok: true, command: "status", config: configuredBridgeServiceConfig(), checkUpdates };
378
+ return { ok: false, error: "Usage: forge-bridge server <show|set <url>>" };
379
+ }
380
+ if (argv[0] === "status") {
381
+ return parseStatusArgs(argv, configuredBridgeServiceConfig);
246
382
  }
247
383
  if (argv[0] === "cleanup") {
248
384
  return parseCleanupArgs(argv);
@@ -250,10 +386,20 @@ export function parseArgs(argv) {
250
386
  if (argv[0] === "mcp") {
251
387
  return { ok: true, command: "mcp", argv };
252
388
  }
389
+ if (argv[0] === "sandbox") {
390
+ return parseSandboxArgs(argv);
391
+ }
392
+ if (argv[0] === "yield") {
393
+ const action = argv[1] ?? "status";
394
+ if (argv.length > 2 || (action !== "on" && action !== "off" && action !== "status")) {
395
+ return { ok: false, error: "Usage: forge-bridge yield [on|off|status]" };
396
+ }
397
+ return { ok: true, command: "yield", action };
398
+ }
253
399
  if (argv[0] !== "run-once") {
254
400
  return {
255
401
  ok: false,
256
- error: usage()
402
+ error: helpText()
257
403
  };
258
404
  }
259
405
  let dispatchPath = null;
@@ -280,6 +426,252 @@ export function parseArgs(argv) {
280
426
  resultPath: path.resolve(resultPath)
281
427
  };
282
428
  }
429
+ function parseSandboxArgs(argv) {
430
+ const action = argv[1];
431
+ if (action === "on") {
432
+ let allowOpenPublic = false;
433
+ for (let index = 2; index < argv.length; index += 1) {
434
+ if (argv[index] === "--allow-open-public") {
435
+ allowOpenPublic = true;
436
+ }
437
+ else {
438
+ return { ok: false, error: `Unknown sandbox argument: ${argv[index]}` };
439
+ }
440
+ }
441
+ return { ok: true, command: "sandbox-on", allowOpenPublic };
442
+ }
443
+ if (action === "off" && argv.length === 2)
444
+ return { ok: true, command: "sandbox-off" };
445
+ if (action === "status" && argv.length === 2)
446
+ return { ok: true, command: "sandbox-status" };
447
+ let repoPath = process.cwd();
448
+ let reportPath;
449
+ let requirePinnedBase = false;
450
+ let probeLoopbackPort = false;
451
+ for (let index = 2; index < argv.length; index += 1) {
452
+ const arg = argv[index];
453
+ if (arg === "--repo") {
454
+ repoPath = argv[++index] ?? "";
455
+ if (!repoPath)
456
+ return { ok: false, error: "--repo requires a path." };
457
+ }
458
+ else if (arg === "--report" && action === "smoke") {
459
+ reportPath = argv[++index];
460
+ if (!reportPath)
461
+ return { ok: false, error: "--report requires a path." };
462
+ }
463
+ else if (arg === "--require-pinned-base" && (action === "doctor" || action === "smoke")) {
464
+ requirePinnedBase = true;
465
+ }
466
+ else if (arg === "--probe-loopback-port" && action === "smoke") {
467
+ probeLoopbackPort = true;
468
+ }
469
+ else {
470
+ return { ok: false, error: `Unknown sandbox argument: ${arg}` };
471
+ }
472
+ }
473
+ if (action === "init")
474
+ return { ok: true, command: "sandbox-init", repoPath: path.resolve(repoPath) };
475
+ if (action === "doctor")
476
+ return { ok: true, command: "sandbox-doctor", repoPath: path.resolve(repoPath), requirePinnedBase };
477
+ if (action === "smoke")
478
+ return {
479
+ ok: true,
480
+ command: "sandbox-smoke",
481
+ repoPath: path.resolve(repoPath),
482
+ reportPath: reportPath ? path.resolve(reportPath) : undefined,
483
+ requirePinnedBase,
484
+ probeLoopbackPort,
485
+ };
486
+ if (action === "reap" && argv.length === 2)
487
+ return { ok: true, command: "sandbox-reap" };
488
+ return { ok: false, error: "Usage: forge-bridge sandbox <on|off|status|init|doctor|smoke|reap> [--allow-open-public] [--repo <path>] [--report <path>] [--require-pinned-base] [--probe-loopback-port]" };
489
+ }
490
+ const sandboxContractTemplate = `schemaVersion: 1
491
+ workingDirectory: /workspace
492
+ commands:
493
+ install: npm ci
494
+ test: npm test
495
+ caches:
496
+ - name: npm
497
+ mode: readonly
498
+ services: []
499
+ environment: []
500
+ artifacts: []
501
+ logs: []
502
+ browser: false
503
+ `;
504
+ const sandboxDockerfileTemplate = `# Pin this base by digest before enabling sandbox_required.
505
+ FROM node:22.17.0-bookworm-slim
506
+ WORKDIR /workspace
507
+ `;
508
+ async function initializeSandbox(repoPath, io) {
509
+ const forgePath = path.join(repoPath, ".forge");
510
+ const files = [
511
+ ["forge.sandbox.yml", sandboxContractTemplate],
512
+ ["Dockerfile", sandboxDockerfileTemplate],
513
+ ["forge.env.example", "# List non-secret variable names in forge.sandbox.yml. Never commit secret values.\n"]
514
+ ];
515
+ await fs.mkdir(forgePath, { recursive: true });
516
+ let created = 0;
517
+ for (const [name, contents] of files) {
518
+ const target = path.join(forgePath, name);
519
+ try {
520
+ const handle = await fs.open(target, "wx", 0o600);
521
+ await handle.writeFile(contents);
522
+ await handle.close();
523
+ io.stdout.write(`Created ${path.relative(repoPath, target)}\n`);
524
+ created += 1;
525
+ }
526
+ catch (error) {
527
+ if (error.code !== "EEXIST")
528
+ throw error;
529
+ io.stdout.write(`Kept existing ${path.relative(repoPath, target)}\n`);
530
+ }
531
+ }
532
+ io.stdout.write(created > 0 ? "Sandbox scaffold is ready. Run `forge-bridge sandbox doctor`.\n" : "Sandbox scaffold already exists.\n");
533
+ return 0;
534
+ }
535
+ async function diagnoseSandbox(repoPath, requirePinnedBase, io) {
536
+ try {
537
+ const forgePath = path.join(repoPath, ".forge");
538
+ const contractSource = await fs.readFile(path.join(forgePath, "forge.sandbox.yml"), "utf8");
539
+ const dockerfile = await fs.readFile(path.join(forgePath, "Dockerfile"), "utf8");
540
+ const contract = validateSandboxContract(contractSource);
541
+ const warnings = validateDockerfilePolicy(dockerfile, requirePinnedBase);
542
+ io.stdout.write(`Contract: valid (${contract.digest})\n`);
543
+ for (const warning of warnings)
544
+ io.stdout.write(`Warning: ${warning}\n`);
545
+ const config = defaultBridgeServiceConfig();
546
+ const preflight = new DockerPreflight({
547
+ dockerExecutable: config.dockerExecutable,
548
+ dockerContext: config.dockerContext,
549
+ stateRoot: config.sandboxStateRoot,
550
+ maxConcurrentSandboxes: config.maxConcurrentSandboxes,
551
+ diskHighWatermarkPercent: config.diskHighWatermarkPercent,
552
+ diskLowWatermarkPercent: config.diskLowWatermarkPercent,
553
+ minimumWorkspaceBytes: config.minimumWorkspaceBytes,
554
+ hostMemoryReserveBytes: config.sandboxHostMemoryReserveBytes,
555
+ defaultWorkerMemoryLimitBytes: config.defaultSandboxWorkerMemoryLimitBytes,
556
+ defaultServiceMemoryLimitBytes: config.defaultSandboxServiceMemoryLimitBytes,
557
+ runtimeOverheadBytes: config.sandboxRuntimeOverheadBytes,
558
+ requireRootless: config.requireRootlessDocker
559
+ });
560
+ try {
561
+ const result = await preflight.refresh();
562
+ if (!result.healthy) {
563
+ io.stderr.write(`Docker: unavailable (${result.unavailableCode ?? "preflight_failed"}): ${result.unavailableReason ?? "unknown reason"}\n`);
564
+ return 1;
565
+ }
566
+ io.stdout.write(`Docker: healthy (${result.runtimeVersion}; capacity ${result.maxConcurrentSandboxes})\n`);
567
+ return 0;
568
+ }
569
+ finally {
570
+ await preflight.release();
571
+ }
572
+ }
573
+ catch (error) {
574
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
575
+ return 1;
576
+ }
577
+ }
578
+ async function smokeSandbox(repoPath, reportPath, requirePinnedBase, probeLoopbackPort, io) {
579
+ try {
580
+ const result = await new DockerSandboxSmoke(defaultBridgeServiceConfig()).run({
581
+ repoPath,
582
+ reportPath,
583
+ requirePinnedBase,
584
+ probeLoopbackPort,
585
+ onProgress: (stage) => io.stdout.write(`Smoke: ${stage}...\n`),
586
+ });
587
+ const { report } = result;
588
+ if (report.repository.contractDigest)
589
+ io.stdout.write(`Contract: valid (${report.repository.contractDigest})\n`);
590
+ for (const warning of report.repository.policyWarnings)
591
+ io.stdout.write(`Warning: ${warning}\n`);
592
+ if (report.docker.runtimeVersion) {
593
+ io.stdout.write(`Docker: healthy (${report.docker.runtimeVersion}; capacity ${report.docker.capacity})\n`);
594
+ }
595
+ io.stdout.write(`Attempt: ${report.dispatchAttemptId}\n`);
596
+ io.stdout.write(`Resource lease: ${report.resourceLeaseId}\n`);
597
+ if (report.publishedPortProbe) {
598
+ io.stdout.write(`Loopback port: ${report.publishedPortProbe.hostIp}:${report.publishedPortProbe.hostPort} -> ${report.publishedPortProbe.containerPort}/tcp\n`);
599
+ }
600
+ io.stdout.write(`Cleanup: ${report.cleanup.verified ? "verified (zero exact-label resources)" : "failed"}\n`);
601
+ io.stdout.write(`Report: ${result.reportPath}\n`);
602
+ if (report.status === "passed") {
603
+ io.stdout.write("Sandbox smoke: PASS\n");
604
+ return 0;
605
+ }
606
+ io.stderr.write(`Sandbox smoke: FAIL (${report.failure?.code ?? "sandbox_smoke_failed"} at ${report.failure?.stage ?? "unknown"}): ${report.failure?.message ?? "unknown failure"}\n`);
607
+ return 1;
608
+ }
609
+ catch (error) {
610
+ io.stderr.write(`Sandbox smoke could not write its report: ${error instanceof Error ? error.message : String(error)}\n`);
611
+ return 1;
612
+ }
613
+ }
614
+ async function reapSandboxes(io) {
615
+ const config = defaultBridgeServiceConfig();
616
+ if (!/^[0-9a-f-]{32,36}$/iu.test(config.runnerId)) {
617
+ io.stderr.write("FORGE_RUNNER_ID must identify the runner whose exact-labeled resources may be reaped.\n");
618
+ return 2;
619
+ }
620
+ const preflight = new DockerPreflight({
621
+ dockerExecutable: config.dockerExecutable,
622
+ dockerContext: config.dockerContext,
623
+ stateRoot: config.sandboxStateRoot,
624
+ maxConcurrentSandboxes: config.maxConcurrentSandboxes,
625
+ diskHighWatermarkPercent: config.diskHighWatermarkPercent,
626
+ diskLowWatermarkPercent: config.diskLowWatermarkPercent,
627
+ minimumWorkspaceBytes: config.minimumWorkspaceBytes,
628
+ hostMemoryReserveBytes: config.sandboxHostMemoryReserveBytes,
629
+ defaultWorkerMemoryLimitBytes: config.defaultSandboxWorkerMemoryLimitBytes,
630
+ defaultServiceMemoryLimitBytes: config.defaultSandboxServiceMemoryLimitBytes,
631
+ runtimeOverheadBytes: config.sandboxRuntimeOverheadBytes,
632
+ requireRootless: config.requireRootlessDocker
633
+ });
634
+ try {
635
+ const result = await preflight.refresh();
636
+ if (!result.healthy && result.unavailableCode !== "docker_disk_low") {
637
+ io.stderr.write(`Docker: unavailable (${result.unavailableCode ?? "preflight_failed"}): ${result.unavailableReason ?? "unknown reason"}\n`);
638
+ return 1;
639
+ }
640
+ const runtime = new DockerSandboxRuntime(config);
641
+ await runtime.reap({ diskLow: result.diskLow });
642
+ io.stdout.write(`Sandbox reaper completed for runner ${config.runnerId}.\n`);
643
+ return 0;
644
+ }
645
+ catch (error) {
646
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
647
+ return 1;
648
+ }
649
+ finally {
650
+ await preflight.release();
651
+ }
652
+ }
653
+ async function dotNetPreflightRoots(config, implicitCloneDestination) {
654
+ const roots = config.repoMappings.map((mapping) => mapping.localPath?.trim())
655
+ .filter((repoRoot) => Boolean(repoRoot));
656
+ const defaultRoot = config.defaultRepoRoot.trim();
657
+ if (!defaultRoot)
658
+ return roots;
659
+ if (implicitCloneDestination) {
660
+ try {
661
+ // The built-in clone destination need not exist on first connect. lstat
662
+ // deliberately retains dangling links for the strict SDK scanner to reject.
663
+ // Explicit mappings (including this same path) remain required inputs.
664
+ await fs.lstat(defaultRoot);
665
+ }
666
+ catch (error) {
667
+ if (error.code === "ENOENT")
668
+ return roots;
669
+ throw error;
670
+ }
671
+ }
672
+ roots.push(defaultRoot);
673
+ return roots;
674
+ }
283
675
  function parseConnectArgs(argv) {
284
676
  let serverUrl = null;
285
677
  let runnerId = null;
@@ -349,7 +741,10 @@ function parseConnectArgs(argv) {
349
741
  return {
350
742
  ok: true,
351
743
  command: "connect",
352
- config: configuredBridgeServiceConfig(overrides, localConfig)
744
+ config: configuredBridgeServiceConfig(overrides, localConfig),
745
+ implicitCloneDestination: repoRoot === null
746
+ && process.env.FORGE_REPO_ROOT === undefined
747
+ && localConfig.defaultRepoRoot === undefined,
353
748
  };
354
749
  }
355
750
  function parsePairArgs(argv) {
@@ -412,8 +807,9 @@ function parsePairArgs(argv) {
412
807
  name: name?.trim() || defaultName,
413
808
  fingerprint: fingerprint?.trim() || `local-bridge:${os.hostname()}:${user}`,
414
809
  repoRoot: repoRoot?.trim() ? path.resolve(repoRoot) : undefined,
415
- cleanupWorktrees: cleanupWorktrees ?? localConfig.cleanupWorktrees ?? false,
810
+ cleanupWorktrees: cleanupWorktrees ?? defaultConfig.cleanupWorktrees,
416
811
  cliProviders: cliProviders.length > 0 ? cliProviders : localConfig.cliProviders && localConfig.cliProviders.length > 0 ? [...localConfig.cliProviders] : ["codex"],
812
+ cliProvidersFromFlag: cliProviders.length > 0,
417
813
  projectLabels: projectLabels.length > 0 ? projectLabels : localConfig.projectLabels ? [...localConfig.projectLabels] : []
418
814
  };
419
815
  }
@@ -468,7 +864,7 @@ async function claimBridgeRunner(args) {
468
864
  })
469
865
  });
470
866
  if (!response.ok) {
471
- throw new Error(`Pairing failed (${response.status}): ${await response.text()}`);
867
+ throw new Error(formatPairingFailure(response.status, args.serverUrl, await response.text()));
472
868
  }
473
869
  const value = await response.json();
474
870
  if (!value.runnerId || !value.deviceToken) {
@@ -476,9 +872,71 @@ async function claimBridgeRunner(args) {
476
872
  }
477
873
  return {
478
874
  runnerId: value.runnerId,
479
- deviceToken: value.deviceToken
875
+ deviceToken: value.deviceToken,
876
+ host: parsePairRunnerHost(value.host)
480
877
  };
481
878
  }
879
+ function parsePairRunnerHost(value) {
880
+ if (!value || typeof value !== "object") {
881
+ return undefined;
882
+ }
883
+ const host = value;
884
+ const name = typeof host.name === "string" && host.name.trim() ? host.name.trim() : undefined;
885
+ const repoRoot = typeof host.repoRoot === "string" && host.repoRoot.trim() ? host.repoRoot.trim() : undefined;
886
+ const cliProviders = Array.isArray(host.cliProviders)
887
+ ? host.cliProviders.filter((provider) => typeof provider === "string" && provider.trim().length > 0)
888
+ : [];
889
+ return { name, repoRoot, cliProviders: cliProviders.length > 0 ? cliProviders : undefined };
890
+ }
891
+ /**
892
+ * Decision 0014 §5: the claim's host block carries what the Connect dialog chose. The runner name
893
+ * is the server's; providers and the repo folder apply unless a flag named them on this command line.
894
+ */
895
+ function applyPairHost(args, host, repoRootFromFlag, io) {
896
+ if (!host) {
897
+ return { args, repoRootFromHost: false };
898
+ }
899
+ let repoRoot = args.repoRoot;
900
+ let repoRootFromHost = false;
901
+ if (host.repoRoot && !repoRootFromFlag) {
902
+ const resolved = resolveHostRepoRoot(host.repoRoot);
903
+ if (!resolved) {
904
+ io.stderr.write(`Ignoring the repo folder chosen in Forge (${host.repoRoot}): it is not a path on this machine.\n`);
905
+ }
906
+ else {
907
+ repoRootFromHost = true;
908
+ repoRoot = resolved;
909
+ }
910
+ }
911
+ return {
912
+ args: {
913
+ ...args,
914
+ name: host.name ?? args.name,
915
+ cliProviders: host.cliProviders && !args.cliProvidersFromFlag ? [...host.cliProviders] : args.cliProviders,
916
+ repoRoot
917
+ },
918
+ repoRootFromHost
919
+ };
920
+ }
921
+ /** Expands `~` in a repo folder chosen in Forge and rejects one shaped for another OS. */
922
+ export function resolveHostRepoRoot(value, platform = process.platform, home = os.homedir()) {
923
+ const trimmed = value.trim();
924
+ if (!trimmed) {
925
+ return undefined;
926
+ }
927
+ const pathApi = platform === "win32" ? path.win32 : path.posix;
928
+ if (trimmed === "~") {
929
+ return home;
930
+ }
931
+ if (/^~[\\/]/.test(trimmed)) {
932
+ return pathApi.resolve(home, trimmed.slice(2));
933
+ }
934
+ const windowsShaped = /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.startsWith("\\\\");
935
+ if (platform === "win32") {
936
+ return windowsShaped || trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
937
+ }
938
+ return !windowsShaped && trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
939
+ }
482
940
  function pairedConfig(current, args, claim) {
483
941
  return {
484
942
  ...current,
@@ -497,6 +955,8 @@ function pairedConfig(current, args, claim) {
497
955
  supportsManagedForgeArtifacts: current.supportsManagedForgeArtifacts ?? true,
498
956
  supportsRunnerAuthoredPhaseArtifacts: current.supportsRunnerAuthoredPhaseArtifacts ?? true,
499
957
  supportsDraftRunOnce: current.supportsDraftRunOnce ?? true,
958
+ supportsDraftAttachments: current.supportsDraftAttachments ?? true,
959
+ supportsDraftImageAttachments: supportsDraftImageAttachmentsFor(args.cliProviders),
500
960
  repoMappings: current.repoMappings ?? []
501
961
  };
502
962
  }
@@ -521,11 +981,7 @@ async function resolvePairingCode(code) {
521
981
  prompt.close();
522
982
  }
523
983
  }
524
- async function resolvePairRepoRoot(repoRoot, configuredRoot) {
525
- const fallback = path.resolve(repoRoot ?? configuredRoot ?? path.join(os.homedir(), "ForgeRepos"));
526
- if (repoRoot?.trim()) {
527
- return fallback;
528
- }
984
+ async function promptPairRepoRoot(fallback) {
529
985
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
530
986
  return fallback;
531
987
  }
@@ -541,181 +997,15 @@ async function resolvePairRepoRoot(repoRoot, configuredRoot) {
541
997
  function normalizePairingCode(code) {
542
998
  return code?.replace(/[\s-]/g, "").trim() ?? "";
543
999
  }
1000
+ function formatPairingFailure(status, serverUrl, body) {
1001
+ const hint = body.includes("runner.invalid_pairing_code")
1002
+ ? " Make sure the code was generated by the same Forge server shown above."
1003
+ : "";
1004
+ return `Pairing failed (${status}) against ${serverUrl}: ${body}${hint}`;
1005
+ }
544
1006
  function normalizeServerUrl(serverUrl) {
545
1007
  return serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`;
546
1008
  }
547
- function usage() {
548
- return helpText();
549
- }
550
- function helpText() {
551
- const version = defaultBridgeServiceConfig().version ?? forgeBridgeVersion;
552
- return [
553
- `🛠 Forge Bridge ${version} — Local provider runners for Forge.`,
554
- "",
555
- "Usage: forge-bridge [options] [command]",
556
- "",
557
- "Options:",
558
- " -h, --help Display help for command",
559
- " -v, --version Output the version number",
560
- "",
561
- "Commands:",
562
- " Hint: commands suffixed with * have detailed help. Run <command> --help for details.",
563
- " connect * Start the runner bridge and wait for Forge dispatches",
564
- " pair * Pair this machine with Forge and save runner credentials",
565
- " status * Show config, runner identity, repos, provider CLIs, and updates",
566
- " add-repo * Map a Forge repo label/name to a local checkout path",
567
- " remove-repo * Remove a saved repo mapping",
568
- " cleanup * Prune managed bridge worktrees",
569
- " version * Print the installed bridge package version",
570
- " help * Display help for command",
571
- " run-once * Internal: run one dispatch packet from JSON",
572
- " mcp * Internal: run the phase-completion MCP server",
573
- "",
574
- "Examples:",
575
- " npm install -g @loucompanion/forge-bridge@next",
576
- " forge-bridge pair 1234-5678 --server https://srv1493013.tail66073d.ts.net:8443 --repo-root \"%USERPROFILE%\\ForgeRepos\"",
577
- " forge-bridge connect",
578
- " forge-bridge status --check-updates",
579
- " forge-bridge add-repo Forge D:\\Programming\\repos\\Forge",
580
- " forge-bridge cleanup --stale",
581
- "",
582
- "Troubleshooting:",
583
- " If Forge says the bridge is old: npm install -g @loucompanion/forge-bridge@next",
584
- " If connect shows 502/500: leave it open; it reconnects with backoff while dev restarts.",
585
- " If a provider is missing: run forge-bridge status --check-updates and verify CLI login.",
586
- "",
587
- "Docs:",
588
- " https://github.com/coleman399/Forge/tree/develop/tools/forge-bridge#readme",
589
- "",
590
- ].join("\n");
591
- }
592
- function commandHelpText(command) {
593
- switch (command) {
594
- case "pair":
595
- return [
596
- "Forge Bridge — pair",
597
- "Pair this machine with Forge and save runner credentials.",
598
- "",
599
- "Usage:",
600
- " forge-bridge pair [code] [options]",
601
- "",
602
- "Options:",
603
- " --server <url> Forge server URL.",
604
- " --repo-root <path> Folder where bridge-managed repos/worktrees live.",
605
- " --name <name> Display name for this runner.",
606
- " --fingerprint <value> Stable device fingerprint override.",
607
- " --cli-provider <list> Comma-separated providers, e.g. codex,cursor.",
608
- " --cleanup-worktrees Enable managed worktree cleanup.",
609
- " --no-cleanup-worktrees Disable managed worktree cleanup.",
610
- "",
611
- "Example:",
612
- " forge-bridge pair 1234-5678 --server https://forge.example.com --repo-root \"%USERPROFILE%\\ForgeRepos\"",
613
- "",
614
- ].join("\n");
615
- case "connect":
616
- return [
617
- "Forge Bridge — connect",
618
- "Start the runner bridge and keep it connected for Forge dispatches.",
619
- "",
620
- "Usage:",
621
- " forge-bridge connect [options]",
622
- "",
623
- "Options:",
624
- " --server <url> Forge server URL; saved config is used when omitted.",
625
- " --runner-id <id> Runner id; saved config is used when omitted.",
626
- " --device-token <token> Device token; saved config is used when omitted.",
627
- " --repo-root <path> Override repo/worktree folder for this run.",
628
- " --cli-provider <list> Comma-separated providers, e.g. codex,cursor.",
629
- " --heartbeat-interval-ms <n> Heartbeat interval in milliseconds.",
630
- " --cleanup-worktrees Enable managed worktree cleanup for this run.",
631
- " --no-cleanup-worktrees Disable managed worktree cleanup for this run.",
632
- "",
633
- "Example:",
634
- " forge-bridge connect",
635
- "",
636
- ].join("\n");
637
- case "status":
638
- return [
639
- "Forge Bridge — status",
640
- "Show saved configuration, paired runner identity, repo mappings, detected provider CLIs, and optional update info.",
641
- "",
642
- "Usage:",
643
- " forge-bridge status [--check-updates]",
644
- "",
645
- "Example:",
646
- " forge-bridge status --check-updates",
647
- "",
648
- ].join("\n");
649
- case "add-repo":
650
- return [
651
- "Forge Bridge — add-repo",
652
- "Map a Forge repo label/name to an existing local checkout.",
653
- "",
654
- "Usage:",
655
- " forge-bridge add-repo <label> <path>",
656
- "",
657
- "Example:",
658
- " forge-bridge add-repo Forge D:\\Programming\\repos\\Forge",
659
- "",
660
- ].join("\n");
661
- case "remove-repo":
662
- return [
663
- "Forge Bridge — remove-repo",
664
- "Remove a saved local repo mapping.",
665
- "",
666
- "Usage:",
667
- " forge-bridge remove-repo <label>",
668
- "",
669
- ].join("\n");
670
- case "cleanup":
671
- return [
672
- "Forge Bridge — cleanup",
673
- "Prune managed bridge worktrees under the configured repo folder.",
674
- "",
675
- "Usage:",
676
- " forge-bridge cleanup [--stale|--merged|--all] [--force]",
677
- "",
678
- "Examples:",
679
- " forge-bridge cleanup --stale",
680
- " forge-bridge cleanup --all --force",
681
- "",
682
- ].join("\n");
683
- case "run-once":
684
- return [
685
- "Forge Bridge — run-once",
686
- "Internal command used by Forge to run a single dispatch packet.",
687
- "",
688
- "Usage:",
689
- " forge-bridge run-once --dispatch <dispatch-json-path> --result <result-json-path>",
690
- "",
691
- ].join("\n");
692
- case "mcp":
693
- return [
694
- "Forge Bridge — mcp",
695
- "Internal MCP server used by provider CLIs to report Forge phase artifacts.",
696
- "",
697
- "Usage:",
698
- " forge-bridge mcp --worktree <path> --work-item-id <id> --phase <phase>",
699
- "",
700
- ].join("\n");
701
- case "version":
702
- return [
703
- "Forge Bridge — version",
704
- "Print the installed bridge package version.",
705
- "",
706
- "Usage:",
707
- " forge-bridge version",
708
- "",
709
- ].join("\n");
710
- default:
711
- return [
712
- `Unknown forge-bridge command: ${command}`,
713
- "",
714
- "Run `forge-bridge help` to see available commands.",
715
- "",
716
- ].join("\n");
717
- }
718
- }
719
1009
  function connectStartupText(config) {
720
1010
  const runner = config.runnerId
721
1011
  ? `${config.runnerId}${config.deviceName ? ` (${config.deviceName})` : ""}`
@@ -731,11 +1021,28 @@ function connectStartupText(config) {
731
1021
  ` repo folder: ${config.defaultRepoRoot || "not configured"}`,
732
1022
  ` providers: ${formatList(config.cliProviders)}`,
733
1023
  ` cleanup worktrees: ${config.cleanupWorktrees ? "enabled" : "disabled"}`,
1024
+ ` Docker Desktop auto-recovery: ${config.dockerDesktopRecoveryEnabled ? "enabled" : "disabled"}`,
1025
+ ` open public sandbox networking: ${config.allowOpenPublicSandbox ? "enabled" : "disabled"}`,
734
1026
  "",
735
1027
  "Press Ctrl+C to stop.",
736
1028
  "",
737
1029
  ].join("\n");
738
1030
  }
1031
+ function writeSandboxPolicyStatus(local, io) {
1032
+ const effective = configuredBridgeServiceConfig({}, local);
1033
+ io.stdout.write(`Config: ${resolveLocalConfigPath()}\n`);
1034
+ io.stdout.write(`Docker sandbox placement: ${effective.dockerEnabled ? "on" : "off"}\n`);
1035
+ io.stdout.write(`Open public sandbox networking: ${effective.allowOpenPublicSandbox ? "allowed" : "denied"}\n`);
1036
+ if (process.env.FORGE_DOCKER_SANDBOX !== undefined) {
1037
+ io.stdout.write("Docker setting source: FORGE_DOCKER_SANDBOX override\n");
1038
+ }
1039
+ if (process.env.FORGE_ALLOW_OPEN_PUBLIC_SANDBOX !== undefined) {
1040
+ io.stdout.write("Open public setting source: FORGE_ALLOW_OPEN_PUBLIC_SANDBOX override\n");
1041
+ }
1042
+ if (effective.allowOpenPublicSandbox) {
1043
+ io.stdout.write("Warning: open_public permits unrestricted outbound network access from developer sandboxes.\n");
1044
+ }
1045
+ }
739
1046
  function formatList(values) {
740
1047
  return values.length > 0 ? values.join(", ") : "none";
741
1048
  }
@@ -745,15 +1052,18 @@ async function writeJsonAtomic(outputPath, value) {
745
1052
  await fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
746
1053
  await fs.rename(tempPath, outputPath);
747
1054
  }
1055
+ async function runStatus(args, io) {
1056
+ return args.idle ? await runIdleStatusCommand(args.idle, io) : await writeStatus(args.config, args.checkUpdates, io);
1057
+ }
748
1058
  async function writeStatus(config, checkUpdates, io) {
749
- const detected = await detectCliProviders([...new Set([...config.cliProviders, "codex", "cursor"])]);
1059
+ const detected = await detectCliProviders([...new Set([...config.cliProviders, "codex", "cursor", "claude"])]);
750
1060
  const repos = config.repoMappings.filter((mapping) => mapping.localPath?.trim());
751
1061
  io.stdout.write(`Forge bridge ${config.version}\n`);
752
1062
  io.stdout.write(`Config: ${resolveLocalConfigPath()}\n`);
753
1063
  io.stdout.write(`Server: ${config.serverUrl || "not configured"}\n`);
754
1064
  io.stdout.write(`Device: ${config.runnerId || "not configured"}${config.deviceName ? ` (${config.deviceName})` : ""}\n`);
755
1065
  io.stdout.write(`Device token: ${config.deviceToken ? "configured" : "missing"}\n`);
756
- io.stdout.write(`Active sessions: 0\n`);
1066
+ io.stdout.write(`${await idleSummaryLine()}\n`);
757
1067
  io.stdout.write("Repos:\n");
758
1068
  if (repos.length === 0) {
759
1069
  io.stdout.write(" none\n");
@@ -771,8 +1081,9 @@ async function writeStatus(config, checkUpdates, io) {
771
1081
  if (checkUpdates) {
772
1082
  io.stdout.write("Update check: no update channel configured.\n");
773
1083
  }
1084
+ return 0;
774
1085
  }
775
- async function cleanupRepos(config, mode, force, io) {
1086
+ async function cleanupRepos(config, mode, force, cleanup, io) {
776
1087
  const repos = config.repoMappings.filter((mapping) => mapping.localPath?.trim());
777
1088
  if (repos.length === 0) {
778
1089
  io.stdout.write("No repos configured.\n");
@@ -781,21 +1092,33 @@ async function cleanupRepos(config, mode, force, io) {
781
1092
  let failures = 0;
782
1093
  for (const repo of repos) {
783
1094
  const repoPath = path.resolve(repo.localPath);
784
- const worktreeRoot = path.join(path.dirname(repoPath), ".forge-worktrees", path.basename(repoPath));
785
- if (!force) {
786
- const action = mode === "all" ? "remove" : "prune";
787
- io.stdout.write(`[dry-run] Would ${action} ${worktreeRoot}\n`);
788
- continue;
789
- }
790
1095
  try {
791
- if (mode === "all") {
792
- await fs.rm(worktreeRoot, { recursive: true, force: true });
793
- await runGit(repoPath, ["worktree", "prune"]);
794
- io.stdout.write(`Removed ${worktreeRoot}\n`);
1096
+ const result = await cleanup.run({
1097
+ repoRoot: repoPath,
1098
+ allowedRepoRoot: config.defaultRepoRoot || undefined,
1099
+ mode,
1100
+ force,
1101
+ });
1102
+ if (!force) {
1103
+ const action = mode === "all"
1104
+ ? "remove"
1105
+ : mode === "stale"
1106
+ ? `remove ${result.candidateWorktrees} stale managed ${result.candidateWorktrees === 1 ? "worktree" : "worktrees"} from`
1107
+ : "prune";
1108
+ io.stdout.write(`[dry-run] Would ${action} ${result.worktreeRoot}\n`);
1109
+ }
1110
+ else if (mode === "all") {
1111
+ io.stdout.write(`Removed ${result.worktreeRoot}\n`);
1112
+ }
1113
+ else if (mode === "stale") {
1114
+ io.stdout.write(`Removed ${result.removedWorktrees} stale managed ${result.removedWorktrees === 1 ? "worktree" : "worktrees"} from ${result.worktreeRoot}\n`);
795
1115
  }
796
1116
  else {
797
- await runGit(repoPath, ["worktree", "prune"]);
798
- io.stdout.write(`Pruned stale worktree metadata for ${repoPath}\n`);
1117
+ const deleted = result.deletedBranches ?? 0;
1118
+ io.stdout.write(`Pruned stale worktree metadata and deleted ${deleted} Forge ${deleted === 1 ? "branch" : "branches"} (merged work and leftover readiness probes) in ${repoPath}\n`);
1119
+ if (result.mergedBaseUnresolved) {
1120
+ io.stderr.write(`${repoPath}: merged work branches were kept because the base branch couldn't be determined: origin/HEAD is unset or names a branch that no longer exists, and origin has none or more than one of develop, main and master. Run \`git fetch origin && git remote set-head origin --auto\`.\n`);
1121
+ }
799
1122
  }
800
1123
  }
801
1124
  catch (error) {
@@ -805,154 +1128,8 @@ async function cleanupRepos(config, mode, force, io) {
805
1128
  }
806
1129
  return failures === 0 ? 0 : 1;
807
1130
  }
808
- async function detectCliProviders(providers) {
809
- const results = [];
810
- for (const provider of providers) {
811
- let detected = null;
812
- for (const probe of cliProbeCommandsFor(provider)) {
813
- try {
814
- detected = await execVersionCommand(probe);
815
- break;
816
- }
817
- catch {
818
- // Try the next provider-specific probe.
819
- }
820
- }
821
- results.push({
822
- provider,
823
- found: detected !== null,
824
- version: detected ? versionLine(`${detected.stdout || detected.stderr}`) : "",
825
- models: detected ? await detectCliModels(provider) : []
826
- });
827
- }
828
- return results;
829
- }
830
- function cliProbeCommandsFor(provider) {
831
- const normalized = provider.toLowerCase();
832
- if (normalized === "codex") {
833
- return [
834
- { command: "codex", args: ["-V"] },
835
- { command: "codex", args: ["--version"] }
836
- ];
837
- }
838
- if (normalized === "cursor") {
839
- return [
840
- { command: "cursor-agent", args: ["-v"] },
841
- { command: "agent", args: ["-v"] },
842
- { command: "cursor-agent", args: ["--version"] },
843
- { command: "agent", args: ["--version"] }
844
- ];
845
- }
846
- return [
847
- { command: provider, args: ["--version"] },
848
- { command: provider, args: ["-V"] }
849
- ];
850
- }
851
- async function execVersionCommand(probe, timeout = 2000) {
852
- const directLaunch = process.platform === "win32"
853
- ? await resolveCursorAgentDirectLaunch(probe.command, probe.args)
854
- : null;
855
- if (directLaunch) {
856
- return await execFileAsync(directLaunch.command, [...directLaunch.args], { timeout });
857
- }
858
- try {
859
- return await execFileAsync(probe.command, probe.args, { timeout });
860
- }
861
- catch (error) {
862
- if (process.platform !== "win32") {
863
- throw error;
864
- }
865
- return await execFileAsync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", windowsCommandLine(probe)], { timeout });
866
- }
867
- }
868
- function windowsCommandLine(probe) {
869
- return [probe.command, ...probe.args].map(quoteWindowsCommandLineArg).join(" ");
870
- }
871
- function quoteWindowsCommandLineArg(value) {
872
- if (value.length > 0 && !/[\s"]/.test(value)) {
873
- return value;
874
- }
875
- return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
876
- }
877
- function versionLine(output) {
878
- const lines = output
879
- .trim()
880
- .split(/\r?\n/)
881
- .map((line) => line.trim())
882
- .filter((line) => line.length > 0);
883
- return lines.at(-1) ?? "";
884
- }
885
- async function detectCliModels(provider) {
886
- const normalized = provider.toLowerCase();
887
- try {
888
- if (normalized === "codex") {
889
- const result = await execFileAsync("codex", ["debug", "models"], { timeout: 5000, maxBuffer: 10 * 1024 * 1024 });
890
- return parseCodexModelCatalog(result.stdout);
891
- }
892
- if (normalized === "cursor") {
893
- const result = await execVersionCommand({ command: "cursor-agent", args: ["models"] }, 10_000);
894
- return parseCursorModelList(`${result.stdout || result.stderr}`);
895
- }
896
- }
897
- catch {
898
- return [];
899
- }
900
- return [];
901
- }
902
- export function parseCodexModelCatalog(raw) {
903
- try {
904
- const parsed = JSON.parse(raw);
905
- if (!isRecord(parsed) || !Array.isArray(parsed.models)) {
906
- return [];
907
- }
908
- const entries = parsed.models
909
- .map((entry, index) => {
910
- if (!isRecord(entry) || typeof entry.slug !== "string") {
911
- return null;
912
- }
913
- const visibility = typeof entry.visibility === "string" ? entry.visibility.toLowerCase() : "list";
914
- if (visibility !== "list") {
915
- return null;
916
- }
917
- const priority = typeof entry.priority === "number" && Number.isFinite(entry.priority) ? entry.priority : index;
918
- return { slug: entry.slug, priority, index };
919
- })
920
- .filter((entry) => entry !== null)
921
- .sort((left, right) => left.priority - right.priority || left.index - right.index)
922
- .map((entry) => entry.slug);
923
- return uniqueModels(entries);
924
- }
925
- catch {
926
- return [];
927
- }
928
- }
929
- export function parseCursorModelList(raw) {
930
- return uniqueModels(raw
931
- .split(/\r?\n/)
932
- .map((line) => line.trim())
933
- .filter((line) => line.length > 0 && !line.toLowerCase().startsWith("available models"))
934
- .map((line) => line.split(/\s+-\s+/, 1)[0]?.trim() ?? "")
935
- .filter((model) => model.length > 0));
936
- }
937
- function uniqueModels(models) {
938
- const seen = new Set();
939
- const result = [];
940
- for (const model of models) {
941
- const trimmed = model.trim();
942
- const key = trimmed.toLowerCase();
943
- if (!trimmed || seen.has(key)) {
944
- continue;
945
- }
946
- seen.add(key);
947
- result.push(trimmed);
948
- }
949
- return result;
950
- }
951
- function isRecord(value) {
952
- return typeof value === "object" && value !== null;
953
- }
954
- async function withDetectedCliProviders(config) {
955
- const detected = await detectCliProviders(configuredProviderCandidates(config.cliProviders));
1131
+ async function withDetectedCliProviders(config, candidates = config.cliProviders) {
1132
+ const detected = await detectCliProviders(uniqueProviders(candidates));
956
1133
  const found = detected.filter((result) => result.found);
957
1134
  if (found.length === 0) {
958
1135
  return config;
@@ -976,6 +1153,7 @@ async function withDetectedCliProviders(config) {
976
1153
  };
977
1154
  }
978
1155
  async function withDetectedPairCliProviders(args) {
1156
+ const configured = configuredProviderCandidates(args.cliProviders);
979
1157
  const detectedConfig = await withDetectedCliProviders({
980
1158
  ...defaultBridgeServiceConfig({
981
1159
  serverUrl: args.serverUrl,
@@ -985,14 +1163,14 @@ async function withDetectedPairCliProviders(args) {
985
1163
  cleanupWorktrees: args.cleanupWorktrees,
986
1164
  defaultRepoRoot: args.repoRoot ?? defaultBridgeServiceConfig().defaultRepoRoot
987
1165
  })
988
- });
1166
+ }, configured);
989
1167
  return {
990
1168
  ...args,
991
1169
  cliProviders: detectedConfig.cliProviders
992
1170
  };
993
1171
  }
994
1172
  function configuredProviderCandidates(providers) {
995
- return uniqueProviders([...providers, "codex", "cursor"]);
1173
+ return uniqueProviders([...providers, "codex", "cursor", "claude"]);
996
1174
  }
997
1175
  function uniqueProviders(providers) {
998
1176
  return providers
@@ -1000,6 +1178,3 @@ function uniqueProviders(providers) {
1000
1178
  .filter((provider) => provider.length > 0)
1001
1179
  .filter((provider, index, all) => all.findIndex((candidate) => candidate.toLowerCase() === provider.toLowerCase()) === index);
1002
1180
  }
1003
- async function runGit(cwd, args) {
1004
- await execFileAsync("git", args, { cwd, timeout: 10_000 });
1005
- }