@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,148 +1,510 @@
1
- import crypto from "node:crypto";
2
1
  import fs from "node:fs/promises";
3
- import os from "node:os";
4
2
  import path from "node:path";
5
- import { execFile, spawn } from "node:child_process";
6
- import readline from "node:readline";
7
- import { promisify } from "node:util";
3
+ import { RepositoryCoordinatorLock } from "../../sandbox/repository-lock.js";
8
4
  import { GitClient } from "../../shared/git/git.js";
9
- import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
10
- import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
5
+ import { sandboxHostLoadGateFromEnvironment } from "../sandbox-host-capacity-gate.js";
11
6
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
12
- import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDebugCycle, completionPromptForDevelopCycle, completionPromptForDraftCycle, completionPromptForPhase, completionPromptForQaCycle, completionRedactionEnv, expectedCompletionToolName, expectedDebugCompletionToolName, expectedQaCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, draftCompletionGateOrder, qaCompletionGateOrder } from "../phase-completion.js";
13
- import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
14
- const fakeWorkerModel = "server-local-fake-worker";
15
- const execFileAsync = promisify(execFile);
16
- const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
17
- const allowedProviderParentEnvNames = [
18
- "PATH",
19
- "HOME",
20
- "USERPROFILE",
21
- "TMPDIR",
22
- "TEMP",
23
- "TMP",
24
- "LANG"
25
- ];
26
- const windowsAllowedProviderParentEnvNames = [
27
- "SystemRoot",
28
- "SystemDrive",
29
- "ComSpec",
30
- "PATHEXT",
31
- "APPDATA",
32
- "LOCALAPPDATA",
33
- "USERNAME",
34
- "USERDOMAIN",
35
- "HOMEDRIVE",
36
- "HOMEPATH",
37
- "ProgramData",
38
- "ProgramFiles",
39
- "ProgramFiles(x86)",
40
- "ProgramW6432",
41
- "DOTNET_ROOT",
42
- "DOTNET_ROOT(x86)",
43
- "DOTNET_CLI_HOME",
44
- "NUGET_PACKAGES",
45
- "NUGET_HTTP_CACHE_PATH"
46
- ];
47
- export function buildProviderChildEnvironment(requestEnv, options = {}) {
48
- const parentEnv = options.parentEnv ?? process.env;
49
- const platform = options.platform ?? process.platform;
50
- const env = {};
51
- for (const [key, value] of Object.entries(parentEnv)) {
52
- if (typeof value === "string" && isAllowedProviderParentEnv(key, platform)) {
53
- env[key] = value;
54
- }
55
- }
56
- if (requestEnv) {
57
- for (const [key, value] of Object.entries(requestEnv)) {
58
- const trimmedKey = key.trim();
59
- if (trimmedKey.length > 0) {
60
- env[trimmedKey] = value;
7
+ import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
8
+ import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
9
+ import { ForgeFailureError } from "../session.types.js";
10
+ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
11
+ import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
12
+ import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
13
+ import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch, shouldPipePromptToStdin, usesManagedWindowsHost } from "./provider-cli.prompts.js";
14
+ import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
15
+ import { admitUserConfigIsolatedProvider, emitProviderUsageEvent, providerProcessEnv } from "./provider-cli.runtime.js";
16
+ import { clip, clipTail, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
17
+ import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
18
+ import { assertRepairHeadEpoch } from "./provider-cli.repair-epoch.js";
19
+ import { PrePublicationValidator } from "../pre-publication-validation.js";
20
+ import { prePublicationRepairTurnsFromEnvironment, prepareRepairTurnLaunch, validatePrePublicationWithRepair, } from "./pre-publication-repair.js";
21
+ const maxQaCompletionRecoveryTurns = 2;
22
+ function assertCommentRepairArtifactMatchesDispatch(dispatch, artifact) {
23
+ const pullRequest = dispatch.pullRequest;
24
+ if (!pullRequest)
25
+ throw new Error("Comment repair completion is missing pull-request context.");
26
+ const payload = JSON.parse(artifact.verdictJson);
27
+ if (payload.repair_head_sha !== pullRequest.headSha || payload.repair_issue_key !== pullRequest.reviewIssueKey) {
28
+ throw new Error("Comment repair completion head or issue key does not match the immutable dispatch snapshot.");
29
+ }
30
+ const expected = new Map(pullRequest.reviewFindings
31
+ .filter(finding => finding.actionable)
32
+ .map(finding => [`${finding.kind}:${finding.claimId}:${finding.bodySha256.toLowerCase()}`, finding]));
33
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
34
+ const actual = new Set();
35
+ for (const value of dispositions) {
36
+ const record = value;
37
+ const identity = `${String(record.kind ?? "")}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").toLowerCase()}`;
38
+ if (actual.has(identity))
39
+ throw new Error("Comment repair completion contains a duplicate finding disposition.");
40
+ actual.add(identity);
41
+ const finding = expected.get(identity);
42
+ if (finding && !finding.contentAvailable && record.disposition !== "needs_decision") {
43
+ throw new Error("Comment repair completion cannot resolve or reject a finding whose content was unavailable.");
44
+ }
45
+ if (record.disposition === "owned_elsewhere") {
46
+ const owner = (record.owned_elsewhere ?? {});
47
+ if (!(pullRequest.openWorkOrderStories ?? []).some(story => story.workItemId.toLowerCase() === String(owner.target_work_item_id ?? "").toLowerCase())) {
48
+ throw new Error("Comment repair completion names an owned_elsewhere owner that is not an open Story in this Work Order.");
61
49
  }
62
50
  }
63
51
  }
64
- if (platform === "win32") {
65
- normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
52
+ if (expected.size !== actual.size || [...expected.keys()].some(identity => !actual.has(identity))) {
53
+ throw new Error("Comment repair completion must disposition every actionable dispatch finding exactly once and no other finding.");
66
54
  }
67
- return env;
68
55
  }
69
- function isAllowedProviderParentEnv(key, platform = process.platform) {
70
- return isAllowedProviderParentEnvName(key, allowedProviderParentEnvNames)
71
- || key.toUpperCase().startsWith("LC_")
72
- || (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
56
+ function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles) {
57
+ const payload = JSON.parse(artifact.verdictJson);
58
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
59
+ const hasFixedDisposition = dispositions.some(value => {
60
+ const record = value;
61
+ return record.disposition === "fixed";
62
+ });
63
+ const claimedChangedFiles = Array.isArray(payload.changed_files)
64
+ ? payload.changed_files.map(value => {
65
+ const record = value;
66
+ return String(record.path ?? "").trim().replaceAll("\\", "/");
67
+ })
68
+ : [];
69
+ const normalizedActual = actualChangedFiles.map(value => value.trim().replaceAll("\\", "/"));
70
+ const claimed = [...new Set(claimedChangedFiles)].sort();
71
+ const actual = [...new Set(normalizedActual)].sort();
72
+ if (hasFixedDisposition && actual.length === 0) {
73
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
74
+ }
75
+ if (claimed.length !== actual.length || claimed.some((value, index) => value !== actual[index])) {
76
+ const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
77
+ throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
78
+ }
79
+ }
80
+ /**
81
+ * A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
82
+ * published commit; otherwise the thread would be resolved without its fix. That covers
83
+ * runtime output Forge unstaged and untracked or git-ignored files it never stages.
84
+ */
85
+ async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
86
+ const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
87
+ `${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
88
+ finding.path ? normalizeChangedFilePath(finding.path) : "",
89
+ ]));
90
+ const payload = JSON.parse(artifact.verdictJson);
91
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
92
+ const fixed = dispositions.flatMap(value => {
93
+ const record = value;
94
+ if (record.disposition !== "fixed")
95
+ return [];
96
+ const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
97
+ const findingPath = findingPaths.get(identity);
98
+ return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
99
+ });
100
+ if (fixed.length === 0)
101
+ return;
102
+ const unpublished = new Set([
103
+ ...changeSet.excluded.map(normalizeChangedFilePath),
104
+ ...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
105
+ ]);
106
+ const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
107
+ if (dropped.length > 0) {
108
+ throw commentRepairChangedFilesMismatch(`Comment repair marked ${dropped.join(", ")} fixed, but Forge does not publish that file (runtime output, untracked, or git-ignored); Forge did not publish or resolve review findings.`);
109
+ }
110
+ }
111
+ function commentRepairChangedFilesMismatch(message) {
112
+ return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
113
+ }
114
+ function formatChangedFilesDelta(missing, unexpected) {
115
+ const parts = [
116
+ missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
117
+ unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
118
+ ].filter(Boolean);
119
+ return parts.length > 0 ? ` (${parts.join("; ")})` : "";
120
+ }
121
+ async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
122
+ const payload = JSON.parse(artifact.verdictJson);
123
+ const claimedRecords = Array.isArray(payload.changed_files)
124
+ ? payload.changed_files.map(value => value)
125
+ : [];
126
+ const claimedByPath = new Map(claimedRecords.map(record => [
127
+ String(record.path ?? "").trim().replaceAll("\\", "/"),
128
+ record,
129
+ ]));
130
+ const authoritativePaths = [...new Set(actualChangedFiles
131
+ .map(value => value.trim().replaceAll("\\", "/"))
132
+ .filter(Boolean))].sort();
133
+ const authoritative = new Set(authoritativePaths);
134
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
135
+ const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
136
+ if (hasFixedDisposition && authoritativePaths.length === 0) {
137
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
138
+ }
139
+ for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
140
+ if (baselinePath && !authoritative.has(baselinePath)) {
141
+ throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
142
+ }
143
+ }
144
+ payload.changed_files = authoritativePaths.map(filePath => {
145
+ const claimed = claimedByPath.get(filePath);
146
+ return claimed
147
+ ? { ...claimed, path: filePath }
148
+ : {
149
+ path: filePath,
150
+ summary: "Updated during bounded Forge pre-publication repair.",
151
+ };
152
+ });
153
+ const verdictJson = `${JSON.stringify(payload, null, 2)}\n`;
154
+ const finalized = { ...artifact, verdictJson };
155
+ assertCommentRepairArtifactMatchesChanges(finalized, authoritativePaths);
156
+ await fs.writeFile(artifact.path, verdictJson, "utf8");
157
+ return finalized;
158
+ }
159
+ export { parseClaudeMcpToolName } from "./provider-output-state.js";
160
+ export { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
161
+ export { buildProviderCliCommand, codexSandboxModeForPlatform, formatProviderCliCommand, formatProviderCliCommandForCheckpoint } from "./provider-cli.prompts.js";
162
+ export { buildProviderChildEnvironment, chooseWindowsCommandCandidate, resolveCodexNpmDirectLaunch, resolveClaudeNpmDirectLaunch, resolvePackageManagerDirectLaunch, resolveWindowsCommandFromPath, PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS, CodexModelsCacheRecoveringProcessRunner, CodexResumeRecoveringProcessRunner, isTransientCodexProviderNotFoundFailure, StreamingProviderProcessRunner } from "./provider-cli.process.js";
163
+ export { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
164
+ async function pushWorktreeBranch(git, worktreePath, branchName, repoPath, coordinator, signal, emit, expectedRemoteHeadSha) {
165
+ return await coordinator.withLock(repoPath, async () => {
166
+ if (expectedRemoteHeadSha) {
167
+ const expected = expectedRemoteHeadSha.trim().toLowerCase();
168
+ const remoteListing = await git.run(worktreePath, ["ls-remote", "--heads", "origin", `refs/heads/${branchName}`]);
169
+ const observed = remoteListing.trim().split(/\s+/u)[0]?.toLowerCase() ?? "";
170
+ if (observed !== expected) {
171
+ throw new Error(`stale_head: repair publication expected remote ${branchName} at ${expected}, but observed ${observed || "no branch"}; refresh provider state before retrying.`);
172
+ }
173
+ try {
174
+ await git.run(worktreePath, [
175
+ "push",
176
+ "--porcelain",
177
+ "origin",
178
+ `HEAD:refs/heads/${branchName}`,
179
+ `--force-with-lease=refs/heads/${branchName}:${expected}`,
180
+ ]);
181
+ }
182
+ catch (error) {
183
+ throw new Error(`stale_head: repair publication for ${branchName} lost its expected-head lease; Forge did not rebase or publish the stale repair: ${errorMessage(error)}`, { cause: error });
184
+ }
185
+ return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
186
+ }
187
+ try {
188
+ await git.run(worktreePath, ["push", "origin", `HEAD:${branchName}`]);
189
+ return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
190
+ }
191
+ catch (err) {
192
+ if (!isNonFastForwardPushError(err)) {
193
+ throw err;
194
+ }
195
+ await emit?.({
196
+ role: "runner",
197
+ kind: "checkpoint",
198
+ content: `Remote branch ${branchName} moved before push; fetching latest and rebasing local changes.`,
199
+ eventType: "worktree_branch_push_rebase"
200
+ });
201
+ try {
202
+ await git.run(worktreePath, ["fetch", "origin", remoteTrackingRefspec(branchName)]);
203
+ await git.run(worktreePath, ["rebase", `refs/remotes/origin/${branchName}`]);
204
+ await git.run(worktreePath, ["push", "origin", `HEAD:${branchName}`]);
205
+ }
206
+ catch (retryErr) {
207
+ throw new Error(`worktree_branch_integration_conflict: git push origin HEAD:${branchName} was rejected because the remote branch moved, and automatic fetch/rebase failed: ${errorMessage(retryErr)}`, { cause: retryErr });
208
+ }
209
+ }
210
+ return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
211
+ }, signal);
212
+ }
213
+ function providerOwnsBranchPublication(context) {
214
+ return context.dispatch.sandbox?.executionMode !== "docker";
215
+ }
216
+ function remoteTrackingRefspec(branchName) {
217
+ return `refs/heads/${branchName}:refs/remotes/origin/${branchName}`;
218
+ }
219
+ function isNonFastForwardPushError(err) {
220
+ const message = errorMessage(err).toLowerCase();
221
+ return message.includes("non-fast-forward")
222
+ || message.includes("fetch first")
223
+ || message.includes("tip of your current branch is behind")
224
+ || message.includes("updates were rejected because the tip of your current branch is behind")
225
+ || message.includes("stale info");
226
+ }
227
+ function errorMessage(err) {
228
+ return err instanceof Error ? err.message : String(err);
229
+ }
230
+ function providerCliExitFailure(command, result) {
231
+ const output = [result.stderr.trim(), result.stdout.trim()]
232
+ .filter(value => value.length > 0)
233
+ .join("\n");
234
+ const detail = clipTail(output, 1200);
235
+ const suffix = detail ? `: ${detail}` : "";
236
+ if (isProviderConfigurationFailure(command, result)) {
237
+ return new ForgeFailureError("provider_configuration_invalid", `${command} rejected its model configuration; correct the configuration before retrying${suffix}`, "provider");
238
+ }
239
+ if (isTransientCodexProviderNotFoundFailure(command, result)) {
240
+ return new ForgeFailureError("provider_request_not_found", `${command} received a transient not-found response from its provider service${suffix}`, "provider");
241
+ }
242
+ if (isProviderCapacityFailure(result)) {
243
+ return new ForgeFailureError("provider_capacity_unavailable", `${command} was deferred because the selected provider model is temporarily at capacity${suffix}`, "provider");
244
+ }
245
+ if (isProviderContextWindowExhausted(command, result)) {
246
+ return new ForgeFailureError("provider_context_window_exhausted", `${command} exhausted the provider context window and must continue in a fresh session${suffix}`, "provider");
247
+ }
248
+ return new Error(`${command} exited ${result.exitCode}${suffix}`);
249
+ }
250
+ /**
251
+ * Capacity is trusted only when a nonzero provider process writes one of the
252
+ * narrow service-level messages to stderr. Stdout can contain arbitrary agent
253
+ * command output and account usage-limit messages remain ordinary failures.
254
+ */
255
+ export function isProviderCapacityFailure(result) {
256
+ if (result.exitCode === 0)
257
+ return false;
258
+ const capacityMessages = new Set([
259
+ "the selected model is at capacity. please try again later.",
260
+ "the selected model is currently at capacity. please try again later.",
261
+ "the model is currently overloaded. please try again later.",
262
+ "the provider is currently overloaded. please try again later.",
263
+ ]);
264
+ return result.stderr
265
+ .split(/\r?\n/u)
266
+ .map(line => line.trim().toLowerCase().replace(/^error:\s*/u, ""))
267
+ .some(line => capacityMessages.has(line));
268
+ }
269
+ /** Only a nonzero Codex service diagnostic can classify a configuration rejection.
270
+ * JSONL turn.failed is a provider envelope; item/tool output is not retry authority. */
271
+ export function isProviderConfigurationFailure(command, result) {
272
+ const names = [path.posix.parse(command).name, path.win32.parse(command).name];
273
+ if (result.exitCode === 0 || !names.some(name => name.toLowerCase() === "codex"))
274
+ return false;
275
+ const reasoningRejected = /Unsupported value: '[^'\r\n]+' is not supported with the '[^'\r\n]+' model\./u.test(result.stderr)
276
+ && result.stderr.includes("reasoning.effort")
277
+ && result.stderr.includes("invalid_request_error")
278
+ && result.stderr.includes("unsupported_value");
279
+ if (reasoningRejected)
280
+ return true;
281
+ return [result.stderr, result.stdout].some(output => output.split(/\r?\n/u).some(line => {
282
+ try {
283
+ const event = JSON.parse(line);
284
+ if (event.type !== "turn.failed")
285
+ return false;
286
+ const error = event.error;
287
+ if (typeof error?.message !== "string")
288
+ return false;
289
+ const service = JSON.parse(error.message);
290
+ return service.type === "error" && service.status === 400
291
+ && service.error?.type === "invalid_request_error"
292
+ && typeof service.error.message === "string"
293
+ && /^The '[^'\r\n]+' model is not supported when using Codex with a ChatGPT account\.$/u.test(service.error.message);
294
+ }
295
+ catch {
296
+ return false;
297
+ }
298
+ }));
299
+ }
300
+ /**
301
+ * A context limit is trusted only at the provider process boundary. The exact
302
+ * Codex message can be embedded in its JSONL stderr envelope, so substring
303
+ * matching is intentional but remains narrow and stderr-only.
304
+ */
305
+ export function isProviderContextWindowExhausted(command, result) {
306
+ const executableNames = [path.posix.parse(command).name, path.win32.parse(command).name]
307
+ .map(name => name.toLowerCase());
308
+ if (result.exitCode === 0 || !executableNames.includes("codex"))
309
+ return false;
310
+ return result.stderr.toLowerCase().includes("codex ran out of room in the model's context window");
311
+ }
312
+ const defaultProviderToolHeartbeatIntervalMs = 60_000;
313
+ const defaultManagedVerificationProgressIntervalMs = 30_000;
314
+ function compareManagedVerificationSnapshots(left, right) {
315
+ const leftOrder = managedVerificationStartedAt(left.startedAt) ?? Number.MAX_SAFE_INTEGER;
316
+ const rightOrder = managedVerificationStartedAt(right.startedAt) ?? Number.MAX_SAFE_INTEGER;
317
+ return leftOrder - rightOrder || left.commandId.localeCompare(right.commandId);
73
318
  }
74
- function isAllowedProviderParentEnvName(key, allowedNames) {
75
- return allowedNames.some((allowed) => allowed.toLowerCase() === key.toLowerCase());
319
+ function managedVerificationStartedAt(value) {
320
+ const parsed = Date.parse(value ?? "");
321
+ return Number.isFinite(parsed) ? parsed : null;
76
322
  }
77
- function normalizeWindowsDotNetEnvironment(env, parentEnv, homeDir) {
78
- const systemRoot = readEnvironmentValue(env, "SystemRoot") ?? readEnvironmentValue(parentEnv, "SystemRoot") ?? "C:\\Windows";
79
- const systemDrive = path.win32.parse(systemRoot).root.replace(/\\$/, "") || "C:";
80
- setEnvironmentValueIfMissing(env, "SystemRoot", systemRoot);
81
- setEnvironmentValueIfMissing(env, "SystemDrive", readEnvironmentValue(parentEnv, "SystemDrive") ?? systemDrive);
82
- setEnvironmentValueIfMissing(env, "ComSpec", readEnvironmentValue(parentEnv, "ComSpec") ?? path.win32.join(systemRoot, "System32", "cmd.exe"));
83
- setEnvironmentValueIfMissing(env, "PATHEXT", readEnvironmentValue(parentEnv, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL");
84
- const userProfile = resolveWindowsUserProfile(env, parentEnv, homeDir);
85
- if (userProfile) {
86
- setEnvironmentValueIfMissing(env, "USERPROFILE", userProfile);
87
- setEnvironmentValueIfMissing(env, "HOME", userProfile);
88
- setEnvironmentValueIfMissing(env, "DOTNET_CLI_HOME", userProfile);
89
- setEnvironmentValueIfMissing(env, "NUGET_PACKAGES", path.win32.join(userProfile, ".nuget", "packages"));
90
- const parsed = path.win32.parse(userProfile);
91
- if (parsed.root) {
92
- setEnvironmentValueIfMissing(env, "HOMEDRIVE", parsed.root.replace(/\\$/, ""));
93
- setEnvironmentValueIfMissing(env, "HOMEPATH", userProfile.slice(parsed.root.length - (parsed.root.endsWith("\\") ? 1 : 0)) || "\\");
94
- }
323
+ export class ManagedVerificationProgressEmitter {
324
+ logDirectory;
325
+ emit;
326
+ intervalMs;
327
+ timer = null;
328
+ observedStatuses = new Map();
329
+ completedCommands = new Set();
330
+ constructor(logDirectory, emit, intervalMs = defaultManagedVerificationProgressIntervalMs) {
331
+ this.logDirectory = logDirectory;
332
+ this.emit = emit;
333
+ this.intervalMs = intervalMs;
95
334
  }
96
- const appData = readEnvironmentValue(env, "APPDATA")
97
- ?? readEnvironmentValue(parentEnv, "APPDATA")
98
- ?? (userProfile ? path.win32.join(userProfile, "AppData", "Roaming") : undefined);
99
- const localAppData = readEnvironmentValue(env, "LOCALAPPDATA")
100
- ?? readEnvironmentValue(parentEnv, "LOCALAPPDATA")
101
- ?? (userProfile ? path.win32.join(userProfile, "AppData", "Local") : undefined);
102
- if (appData) {
103
- setEnvironmentValueIfMissing(env, "APPDATA", appData);
335
+ start() {
336
+ if (!this.logDirectory?.trim() || this.timer)
337
+ return;
338
+ this.timer = setInterval(() => {
339
+ void this.scan().catch(() => undefined);
340
+ }, Math.max(1, this.intervalMs));
341
+ void this.scan().catch(() => undefined);
104
342
  }
105
- if (localAppData) {
106
- setEnvironmentValueIfMissing(env, "LOCALAPPDATA", localAppData);
107
- setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
343
+ async stop() {
344
+ if (this.timer) {
345
+ clearInterval(this.timer);
346
+ this.timer = null;
347
+ }
348
+ await this.scan().catch(() => undefined);
108
349
  }
109
- setEnvironmentValueIfMissing(env, "DOTNET_NOLOGO", "1");
110
- setEnvironmentValueIfMissing(env, "DOTNET_CLI_TELEMETRY_OPTOUT", "1");
111
- setEnvironmentValueIfMissing(env, "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1");
112
- setEnvironmentValueIfMissing(env, "NUGET_XMLDOC_MODE", "skip");
113
- }
114
- function resolveWindowsUserProfile(env, parentEnv, homeDir) {
115
- const existing = readEnvironmentValue(env, "USERPROFILE") ?? readEnvironmentValue(parentEnv, "USERPROFILE");
116
- if (existing) {
117
- return existing;
350
+ async scan() {
351
+ if (!this.logDirectory?.trim())
352
+ return;
353
+ const directory = path.join(this.logDirectory, "managed-commands");
354
+ const names = await fs.readdir(directory).catch(() => []);
355
+ const snapshots = await Promise.all(names
356
+ .filter(name => name.endsWith(".receipt.json"))
357
+ .map(async (name) => parseManagedVerificationSnapshot(path.join(directory, name))));
358
+ const current = snapshots
359
+ .filter((entry) => entry !== null)
360
+ .sort(compareManagedVerificationSnapshots);
361
+ if (current.some(snapshot => isManagedVerificationNonterminal(snapshot.status))) {
362
+ // Durable managed-command receipts are authoritative evidence that Forge
363
+ // still supervises work even when the provider is not inside an MCP tool
364
+ // call. Refresh the API idle deadline without inflating the transcript.
365
+ await this.emit({
366
+ role: "runner",
367
+ kind: "status",
368
+ content: "A supervised managed verification command is still running.",
369
+ eventType: "provider_tool_heartbeat",
370
+ });
371
+ }
372
+ for (const snapshot of current) {
373
+ await this.emitTransition(snapshot);
374
+ }
118
375
  }
119
- const home = readEnvironmentValue(env, "HOME") ?? readEnvironmentValue(parentEnv, "HOME");
120
- if (home && path.win32.isAbsolute(home)) {
121
- return home;
376
+ async emitTransition(current) {
377
+ const terminal = ["pass", "fail", "timed_out", "timeout_termination_failed", "runner_error"].includes(current.status);
378
+ if (terminal && this.completedCommands.has(current.commandId))
379
+ return;
380
+ const previousStatus = this.observedStatuses.get(current.commandId);
381
+ if (previousStatus === current.status)
382
+ return;
383
+ this.observedStatuses.set(current.commandId, current.status);
384
+ if (terminal)
385
+ this.completedCommands.add(current.commandId);
386
+ // Starting and running are one externally meaningful state. The receipt is
387
+ // still refreshed on disk for UI telemetry, but repeated output/elapsed
388
+ // changes must not inflate the provider transcript or session history.
389
+ if (!terminal && previousStatus === "starting" && current.status === "running")
390
+ return;
391
+ const startedAt = managedVerificationStartedAt(current.startedAt);
392
+ const elapsedMs = startedAt !== null
393
+ ? Math.max(current.elapsedMs ?? 0, Date.now() - startedAt)
394
+ : current.elapsedMs;
395
+ const elapsed = elapsedMs === null ? "an unknown duration" : formatElapsed(elapsedMs);
396
+ const outputTail = current.lastOutputStream === "stderr"
397
+ ? current.stderrTail || current.stdoutTail
398
+ : current.stdoutTail || current.stderrTail;
399
+ const recovered = previousStatus === undefined && terminal;
400
+ await this.emit({
401
+ role: "runner",
402
+ kind: terminal && current.status !== "pass" ? "error" : "status",
403
+ content: terminal
404
+ ? `Managed verification ${current.status} after ${elapsed}${recovered ? " (recovered from its durable receipt)" : ""}${outputTail ? `: ${clip(outputTail, 600)}` : "."}`
405
+ : `QA started managed verification ${current.commandId}. Forge is supervising it; durable progress remains available in the UI while the provider continues independent work.`,
406
+ eventType: terminal ? "verification_completed" : "verification_waiting",
407
+ data: JSON.stringify({
408
+ command_id: current.commandId,
409
+ status: current.status,
410
+ elapsed_ms: elapsedMs,
411
+ output_revision: current.outputRevision,
412
+ last_output_at: current.lastOutputAt,
413
+ recovered,
414
+ }),
415
+ });
122
416
  }
123
- const homeDrive = readEnvironmentValue(env, "HOMEDRIVE") ?? readEnvironmentValue(parentEnv, "HOMEDRIVE");
124
- const homePath = readEnvironmentValue(env, "HOMEPATH") ?? readEnvironmentValue(parentEnv, "HOMEPATH");
125
- if (homeDrive && homePath) {
126
- return `${homeDrive}${homePath}`;
417
+ }
418
+ function isManagedVerificationNonterminal(status) {
419
+ return status === "starting" || status === "running" || status === "waiting_for_build_slot"
420
+ || status === "waiting_for_host_capacity";
421
+ }
422
+ async function parseManagedVerificationSnapshot(receiptPath) {
423
+ try {
424
+ const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
425
+ const commandId = typeof receipt.command_id === "string" ? receipt.command_id : null;
426
+ const status = typeof receipt.status === "string" ? receipt.status : null;
427
+ if (!commandId || !status)
428
+ return null;
429
+ return {
430
+ commandId,
431
+ status,
432
+ elapsedMs: typeof receipt.elapsed_ms === "number" ? receipt.elapsed_ms : null,
433
+ startedAt: typeof receipt.started_at === "string" ? receipt.started_at : null,
434
+ outputRevision: typeof receipt.output_revision === "number" ? receipt.output_revision : null,
435
+ lastOutputAt: typeof receipt.last_output_at === "string" ? receipt.last_output_at : null,
436
+ lastOutputStream: receipt.last_output_stream === "stdout" || receipt.last_output_stream === "stderr"
437
+ ? receipt.last_output_stream
438
+ : null,
439
+ stdoutTail: tail(typeof receipt.stdout === "string" ? receipt.stdout : ""),
440
+ stderrTail: tail(typeof receipt.stderr === "string" ? receipt.stderr : ""),
441
+ };
127
442
  }
128
- if (homeDir && path.win32.isAbsolute(homeDir)) {
129
- return homeDir;
443
+ catch {
444
+ return null;
130
445
  }
131
- const systemDrive = readEnvironmentValue(env, "SystemDrive") ?? readEnvironmentValue(parentEnv, "SystemDrive") ?? "C:";
132
- const username = readEnvironmentValue(env, "USERNAME") ?? readEnvironmentValue(parentEnv, "USERNAME");
133
- return username ? path.win32.join(systemDrive, "Users", username) : undefined;
134
446
  }
135
- function readEnvironmentValue(env, name) {
136
- const entry = Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase());
137
- const value = entry?.[1];
138
- return typeof value === "string" && value.trim().length > 0 ? value : undefined;
447
+ function tail(value) {
448
+ return value.trim().split(/\r?\n/u).slice(-4).join("\n");
139
449
  }
140
- function setEnvironmentValueIfMissing(env, name, value) {
141
- if (readEnvironmentValue(env, name)) {
142
- return;
450
+ function formatElapsed(milliseconds) {
451
+ const seconds = Math.max(0, Math.round(milliseconds / 1000));
452
+ const minutes = Math.floor(seconds / 60);
453
+ return minutes > 0 ? `${minutes}m ${seconds % 60}s` : `${seconds}s`;
454
+ }
455
+ class ProviderToolActivityHeartbeat {
456
+ outputState;
457
+ emit;
458
+ intervalMs;
459
+ timer = null;
460
+ /** Lets the provider runner hold its end-of-turn timers while a tool call is in flight. */
461
+ isToolCallInFlight = () => this.outputState.hasActiveToolCall;
462
+ /** Forgets tool calls a previous generation left open; called before every relaunch. */
463
+ startGeneration = () => this.outputState.resetActiveToolCalls();
464
+ constructor(outputState, emit, intervalMs) {
465
+ this.outputState = outputState;
466
+ this.emit = emit;
467
+ this.intervalMs = intervalMs;
468
+ // Each heartbeat watches one provider generation. Calls an earlier generation left
469
+ // open died with it; inheriting them would hold the new generation's timers forever.
470
+ this.outputState.resetActiveToolCalls();
471
+ }
472
+ async consume(line) {
473
+ const events = this.outputState.consume(line);
474
+ this.sync();
475
+ for (const event of events) {
476
+ await this.emit(event);
477
+ }
478
+ }
479
+ stop() {
480
+ if (this.timer) {
481
+ clearInterval(this.timer);
482
+ this.timer = null;
483
+ }
484
+ }
485
+ sync() {
486
+ if (!this.outputState.hasActiveToolCall) {
487
+ this.stop();
488
+ return;
489
+ }
490
+ if (this.timer) {
491
+ return;
492
+ }
493
+ this.timer = setInterval(() => {
494
+ if (!this.outputState.hasActiveToolCall) {
495
+ this.stop();
496
+ return;
497
+ }
498
+ void this.emit({
499
+ role: "runner",
500
+ kind: "status",
501
+ content: "A supervised provider tool is still running.",
502
+ eventType: "provider_tool_heartbeat",
503
+ }).catch(() => undefined);
504
+ }, Math.max(1, this.intervalMs));
143
505
  }
144
- env[name] = value;
145
506
  }
507
+ const fakeWorkerModel = "server-local-fake-worker";
146
508
  export class RoutingProviderCliService {
147
509
  realProvider;
148
510
  deterministicProvider;
@@ -160,6 +522,11 @@ export class RoutingProviderCliService {
160
522
  ? await this.deterministicProvider.runArchitect(context)
161
523
  : await this.realProvider.runArchitect(context);
162
524
  }
525
+ async runCiRepair(context) {
526
+ return isFakeWorkerModel(context.dispatch.execution.model)
527
+ ? await this.deterministicProvider.runCiRepair(context)
528
+ : await this.realProvider.runCiRepair(context);
529
+ }
163
530
  async runConflictResolve(context) {
164
531
  return isFakeWorkerModel(context.dispatch.execution.model)
165
532
  ? await this.deterministicProvider.runConflictResolve(context)
@@ -179,33 +546,46 @@ export class RoutingProviderCliService {
179
546
  export class ProcessBackedProviderCliService {
180
547
  processRunner;
181
548
  git;
182
- constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient()) {
549
+ providerToolHeartbeatIntervalMs;
550
+ publicationCoordinator;
551
+ prePublicationValidator;
552
+ prePublicationRepairTurns;
553
+ constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs, publicationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()),
554
+ // The Docker sandbox worker (`forge` run-once via ForgeBridgeCliService) builds
555
+ // this default. A container cannot reach the host ledger, so when the host
556
+ // bridge enabled it, its steps ask the bridge for tokens over the sandbox
557
+ // channel (decision 0013); elsewhere the gate is absent and validation is ungated.
558
+ prePublicationValidator = new PrePublicationValidator(undefined, undefined, undefined, sandboxHostLoadGateFromEnvironment()), prePublicationRepairTurns = prePublicationRepairTurnsFromEnvironment()) {
183
559
  this.processRunner = processRunner;
184
560
  this.git = git;
561
+ this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
562
+ this.publicationCoordinator = publicationCoordinator;
563
+ this.prePublicationValidator = prePublicationValidator;
564
+ this.prePublicationRepairTurns = prePublicationRepairTurns;
185
565
  }
186
566
  async runDraft(context) {
187
- const { dispatch } = context;
567
+ const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
188
568
  if (!dispatch.draft) {
189
569
  throw new Error("Draft dispatch context is missing.");
190
570
  }
191
- const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "forge-bridge-draft-"));
192
- const draftWorktree = {
193
- repoPath: tempDir,
194
- worktreePath: tempDir,
195
- branchName: "draft",
196
- baseBranch: dispatch.cycleRun.baseBranch || dispatch.repo.defaultBranch || "draft",
197
- cleanupWorktrees: true
198
- };
199
- const metadataRoot = path.join(tempDir, ".forge", "work-items", dispatch.workItem.id);
571
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
200
572
  await fs.mkdir(metadataRoot, { recursive: true });
201
- await fs.writeFile(path.join(metadataRoot, "draft-input.json"), JSON.stringify(dispatch.draft, null, 2) + "\n", "utf8");
573
+ await fs.writeFile(path.join(metadataRoot, "draft-input.json"), JSON.stringify(durableDraftInput(dispatch), null, 2) + "\n", "utf8");
202
574
  await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
203
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree: draftWorktree, phase: "draft" });
575
+ const stagedAttachments = await stageDraftAttachments(dispatch, metadataRoot);
576
+ const decomposeDraft = isDecomposeDraftDispatch(dispatch);
577
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
578
+ const draftPrompt = buildDraftPrompt(dispatch, { attachmentReferences: stagedAttachments.textReferences });
579
+ const providerPrompt = buildProviderCliPrompt(dispatch, draftPrompt, context.runtimeEnvironment);
580
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
204
581
  const command = buildProviderCliCommand(dispatch, {
205
- worktreePath: tempDir,
206
- prompt: buildDraftPrompt(dispatch),
582
+ worktreePath: worktree.worktreePath,
583
+ prompt: draftPrompt,
584
+ promptFromStdin: pipePromptToStdin,
207
585
  completionTools: completionTools ?? undefined,
208
- skipGitRepoCheck: true
586
+ skipGitRepoCheck: false,
587
+ imagePaths: stagedAttachments.imagePaths,
588
+ runtimeEnvironment: context.runtimeEnvironment
209
589
  });
210
590
  const draftArtifactSlugs = dispatch.artifacts
211
591
  .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
@@ -219,16 +599,19 @@ export class ProcessBackedProviderCliService {
219
599
  await context.emit({
220
600
  role: "runner",
221
601
  kind: "checkpoint",
222
- content: `Starting provider CLI Draft: ${formatProviderCliCommand(command)}`,
223
- eventType: "provider_cli_started"
602
+ content: `Starting provider CLI Draft: ${formatProviderCliCommandForCheckpoint(command)}`,
603
+ eventType: "provider_cli_starting"
224
604
  });
225
605
  await context.emit({
226
606
  role: "runner",
227
607
  kind: "checkpoint",
228
- content: "Forge Draft completion tools configured for draft_intent -> draft_repo_context -> draft_graph_context -> draft_product_scope -> draft_work_order_plan -> draft_critic -> draft_proposal; provider must call each MCP completion tool before exit.",
608
+ content: decomposeDraft
609
+ ? "Forge Decompose completion tools configured for decompose_subject_intake -> decompose_context_review -> decompose_breakdown_strategy -> decompose_child_items -> decompose_dependency_graph -> decompose_critic -> decompose_proposal; provider must call each MCP completion tool before exit."
610
+ : "Forge Draft completion tools configured for draft_intent -> draft_repo_context -> draft_graph_context -> draft_product_scope -> draft_work_order_plan -> draft_critic -> draft_proposal; provider must call each MCP completion tool before exit.",
229
611
  eventType: "completion_tools_configured"
230
612
  });
231
613
  const outputState = createProviderOutputState(dispatch.execution.provider);
614
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
232
615
  try {
233
616
  const providerCancellation = new AbortController();
234
617
  const abortProvider = () => providerCancellation.abort();
@@ -238,73 +621,129 @@ export class ProcessBackedProviderCliService {
238
621
  else {
239
622
  context.signal?.addEventListener("abort", abortProvider, { once: true });
240
623
  }
241
- const runPromise = this.processRunner.run({
242
- command: command.command,
243
- args: command.args,
244
- cwd: tempDir,
245
- env: providerProcessEnv(dispatch)
246
- }, {
247
- onStdoutLine: async (line) => {
248
- for (const event of outputState.consume(line)) {
249
- await context.emit(event);
624
+ try {
625
+ const runPromise = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
626
+ command: command.command,
627
+ args: command.args,
628
+ cwd: worktree.worktreePath,
629
+ env: providerProcessEnv(dispatch, context.runtimeEnvironment),
630
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
631
+ stdin: pipePromptToStdin ? providerPrompt : undefined
632
+ }, {
633
+ onStarted: async () => {
634
+ await context.emit({
635
+ role: "runner",
636
+ kind: "checkpoint",
637
+ content: "Provider CLI Draft is supervised and ready.",
638
+ eventType: "provider_cli_started"
639
+ });
640
+ },
641
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
642
+ onGenerationStart: toolHeartbeat.startGeneration,
643
+ onStdoutLine: async (line) => {
644
+ await toolHeartbeat.consume(line);
250
645
  }
646
+ }, providerCancellation.signal);
647
+ const artifactWaitCancellation = new AbortController();
648
+ const abortArtifactWait = () => artifactWaitCancellation.abort();
649
+ if (context.signal?.aborted) {
650
+ abortArtifactWait();
251
651
  }
252
- }, providerCancellation.signal);
253
- let result;
254
- let earlyProposalArtifact = null;
255
- const terminal = await Promise.race([
256
- runPromise.then(value => ({ kind: "process", value })),
257
- waitForDraftProposalArtifact(tempDir, dispatch.workItem.id, context.signal).then(value => ({ kind: "artifact", value }))
258
- ]);
259
- if (terminal.kind === "artifact") {
260
- earlyProposalArtifact = terminal.value;
261
- providerCancellation.abort();
262
- result = await runPromise.catch(() => ({ exitCode: 0, stdout: "", stderr: "" }));
263
- }
264
- else {
265
- result = terminal.value;
266
- }
267
- context.signal?.removeEventListener("abort", abortProvider);
268
- if (result.exitCode !== 0 && !earlyProposalArtifact) {
269
- throw new Error(`Provider CLI exited with code ${result.exitCode}${summarizeStderr(result.stderr)}.`);
270
- }
271
- await context.emit({
272
- role: "runner",
273
- kind: "checkpoint",
274
- content: `Provider CLI Draft completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
275
- eventType: "provider_cli_completed"
276
- });
277
- await emitProviderUsageEvent(context.emit, dispatch, outputState);
278
- await emitDraftGateArtifacts(context.emit, tempDir, dispatch.workItem.id);
279
- const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(tempDir, dispatch.workItem.id, "draft");
280
- if (!proposalArtifact) {
281
- throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
652
+ else {
653
+ context.signal?.addEventListener("abort", abortArtifactWait, { once: true });
654
+ }
655
+ const artifactWaitPromise = waitForCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, decomposeDraft ? "decompose" : "draft", artifactWaitCancellation.signal);
656
+ let result;
657
+ let earlyProposalArtifact = null;
658
+ try {
659
+ const terminal = await Promise.race([
660
+ runPromise.then(value => ({ kind: "process", value })),
661
+ artifactWaitPromise.then(value => ({ kind: "artifact", value }))
662
+ ]);
663
+ artifactWaitCancellation.abort();
664
+ await artifactWaitPromise.catch(() => undefined);
665
+ if (terminal.kind === "artifact") {
666
+ earlyProposalArtifact = terminal.value;
667
+ providerCancellation.abort();
668
+ result = await runPromise.catch(() => ({ exitCode: 0, stdout: "", stderr: "" }));
669
+ }
670
+ else {
671
+ result = terminal.value;
672
+ }
673
+ }
674
+ finally {
675
+ artifactWaitCancellation.abort();
676
+ context.signal?.removeEventListener("abort", abortArtifactWait);
677
+ }
678
+ if (result.exitCode !== 0 && !earlyProposalArtifact) {
679
+ throw providerCliExitFailure(command.command, result);
680
+ }
681
+ await context.emit({
682
+ role: "runner",
683
+ kind: "checkpoint",
684
+ content: `Provider CLI Draft completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
685
+ eventType: "provider_cli_completed"
686
+ });
687
+ await emitProviderUsageEvent(context.emit, dispatch, outputState);
688
+ if (decomposeDraft) {
689
+ await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
690
+ const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
691
+ if (!proposalArtifact) {
692
+ throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
693
+ }
694
+ const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
695
+ const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
696
+ if (!proposalJson || typeof proposalJson !== "object" || Array.isArray(proposalJson)) {
697
+ throw new Error("Provider CLI Decompose completed but decompose.proposal.json did not contain proposal_json.");
698
+ }
699
+ const json = JSON.stringify(proposalJson);
700
+ await context.emit({
701
+ role: "assistant",
702
+ kind: "message",
703
+ content: json,
704
+ eventType: "decompose_proposal"
705
+ });
706
+ return {
707
+ summary: "Decomposition proposal generated through Forge Decompose completion cycle.",
708
+ artifact: proposalArtifact,
709
+ artifacts: [proposalArtifact]
710
+ };
711
+ }
712
+ await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
713
+ const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
714
+ if (!proposalArtifact) {
715
+ throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
716
+ }
717
+ const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
718
+ const draftJson = proposal["draft_json"];
719
+ if (!draftJson || typeof draftJson !== "object" || Array.isArray(draftJson)) {
720
+ throw new Error("Provider CLI Draft completed but draft.proposal.json did not contain draft_json.");
721
+ }
722
+ const json = JSON.stringify(draftJson);
723
+ await context.emit({
724
+ role: "assistant",
725
+ kind: "message",
726
+ content: json,
727
+ eventType: "draft_complete"
728
+ });
729
+ return {
730
+ summary: "Draft generated through Forge Draft completion cycle.",
731
+ artifact: proposalArtifact,
732
+ artifacts: [proposalArtifact]
733
+ };
282
734
  }
283
- const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
284
- const draftJson = proposal["draft_json"];
285
- if (!draftJson || typeof draftJson !== "object" || Array.isArray(draftJson)) {
286
- throw new Error("Provider CLI Draft completed but draft.proposal.json did not contain draft_json.");
735
+ finally {
736
+ context.signal?.removeEventListener("abort", abortProvider);
287
737
  }
288
- const json = JSON.stringify(draftJson);
289
- await context.emit({
290
- role: "assistant",
291
- kind: "message",
292
- content: json,
293
- eventType: "draft_complete"
294
- });
295
- return {
296
- summary: "Draft generated through Forge Draft completion cycle.",
297
- artifact: proposalArtifact,
298
- artifacts: [proposalArtifact]
299
- };
300
738
  }
301
739
  finally {
740
+ toolHeartbeat.stop();
302
741
  await cleanupCompletionTools(completionTools, context.emit);
303
- await fs.rm(tempDir, { recursive: true, force: true });
304
742
  }
305
743
  }
306
744
  async runImplementation(context) {
307
- const { dispatch, worktree } = context;
745
+ const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
746
+ const validationBaselineRevision = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
308
747
  const phase = completionPhaseFromDispatch(dispatch);
309
748
  const developCycle = usesDevelopCycleCompletion(dispatch);
310
749
  const debugCycle = usesDebugCycleCompletion(dispatch);
@@ -318,21 +757,26 @@ export class ProcessBackedProviderCliService {
318
757
  const specPath = path.join(metadataRoot, "spec.md");
319
758
  await fs.writeFile(specPath, specBody, "utf8");
320
759
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
321
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
760
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
761
+ const implementationPrompt = debugCycle
762
+ ? buildDebugCyclePrompt(dispatch, phase)
763
+ : developCycle
764
+ ? buildDevelopCyclePrompt(dispatch, phase)
765
+ : buildImplementationPrompt(dispatch, phase);
766
+ const providerPrompt = buildProviderCliPrompt(dispatch, implementationPrompt, context.runtimeEnvironment);
767
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
322
768
  const command = buildProviderCliCommand(dispatch, {
323
769
  worktreePath: worktree.worktreePath,
324
- prompt: debugCycle
325
- ? buildDebugCyclePrompt(dispatch, phase)
326
- : developCycle
327
- ? buildDevelopCyclePrompt(dispatch, phase)
328
- : buildImplementationPrompt(dispatch, phase),
329
- completionTools
770
+ prompt: implementationPrompt,
771
+ promptFromStdin: pipePromptToStdin,
772
+ completionTools,
773
+ runtimeEnvironment: context.runtimeEnvironment
330
774
  });
331
775
  await context.emit({
332
776
  role: "runner",
333
777
  kind: "checkpoint",
334
- content: `Starting provider CLI: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
335
- eventType: "provider_cli_started"
778
+ content: `Starting provider CLI: ${formatProviderCliCommandForCheckpoint(command)} in ${worktree.worktreePath}`,
779
+ eventType: "provider_cli_starting"
336
780
  });
337
781
  await context.emit({
338
782
  role: "runner",
@@ -345,31 +789,41 @@ export class ProcessBackedProviderCliService {
345
789
  eventType: "completion_tools_configured"
346
790
  });
347
791
  const outputState = createProviderOutputState(dispatch.execution.provider);
792
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
348
793
  const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
349
794
  let result;
350
795
  try {
351
796
  liveCompletionEvents.start();
352
- result = await this.processRunner.run({
797
+ result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
353
798
  command: command.command,
354
799
  args: command.args,
355
800
  cwd: worktree.worktreePath,
356
- env: providerProcessEnv(dispatch)
801
+ env: providerProcessEnv(dispatch, context.runtimeEnvironment),
802
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
803
+ stdin: pipePromptToStdin ? providerPrompt : undefined
357
804
  }, {
805
+ onStarted: async () => {
806
+ await context.emit({
807
+ role: "runner",
808
+ kind: "checkpoint",
809
+ content: "Provider CLI is supervised and ready.",
810
+ eventType: "provider_cli_started"
811
+ });
812
+ },
813
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
814
+ onGenerationStart: toolHeartbeat.startGeneration,
358
815
  onStdoutLine: async (line) => {
359
- for (const event of outputState.consume(line)) {
360
- await context.emit(event);
361
- }
816
+ await toolHeartbeat.consume(line);
362
817
  }
363
818
  }, context.signal);
364
819
  }
365
820
  finally {
821
+ toolHeartbeat.stop();
366
822
  await liveCompletionEvents.stop();
367
823
  await cleanupCompletionTools(completionTools, context.emit);
368
824
  }
369
- if (result.exitCode !== 0) {
370
- const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
371
- throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
372
- }
825
+ if (result.exitCode !== 0)
826
+ throw providerCliExitFailure(command.command, result);
373
827
  await context.emit({
374
828
  role: "runner",
375
829
  kind: "checkpoint",
@@ -377,9 +831,20 @@ export class ProcessBackedProviderCliService {
377
831
  eventType: "provider_cli_completed"
378
832
  });
379
833
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
834
+ if (developCycle || phase === "implementation") {
835
+ await this.validatePrePublicationWithRecovery({
836
+ context,
837
+ validationProfile: "implementation",
838
+ repairEnvironment: context.runtimeEnvironment,
839
+ outputState,
840
+ preparedHeadSha: validationBaselineRevision,
841
+ repairScope: "implementation",
842
+ });
843
+ }
380
844
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
381
- if (developCycle || debugCycle || phase === "implementation") {
382
- await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
845
+ let publishedCommitSha = null;
846
+ if ((developCycle || debugCycle || phase === "implementation") && providerOwnsBranchPublication(context)) {
847
+ publishedCommitSha = await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, worktree.repoPath, this.publicationCoordinator, context.signal, context.emit);
383
848
  await context.emit({
384
849
  role: "runner",
385
850
  kind: "checkpoint",
@@ -387,7 +852,7 @@ export class ProcessBackedProviderCliService {
387
852
  eventType: "worktree_branch_pushed"
388
853
  });
389
854
  }
390
- const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
855
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, result);
391
856
  for (const artifact of completionArtifacts) {
392
857
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
393
858
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -413,7 +878,9 @@ export class ProcessBackedProviderCliService {
413
878
  });
414
879
  }
415
880
  return {
416
- summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
881
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`,
882
+ resultCommitSha: publishedCommitSha ?? committed.commitSha,
883
+ publishedCommitSha: publishedCommitSha ?? undefined,
417
884
  spec: {
418
885
  repoPath: worktree.worktreePath,
419
886
  path: specPath,
@@ -426,7 +893,7 @@ export class ProcessBackedProviderCliService {
426
893
  };
427
894
  }
428
895
  async runArchitect(context) {
429
- const { dispatch, worktree } = context;
896
+ const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
430
897
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
431
898
  await fs.mkdir(metadataRoot, { recursive: true });
432
899
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -437,18 +904,23 @@ export class ProcessBackedProviderCliService {
437
904
  const specPath = path.join(metadataRoot, "spec.md");
438
905
  await fs.writeFile(specPath, specBody, "utf8");
439
906
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-lane-command" }) + "\n", "utf8");
440
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
907
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
908
+ const architectPrompt = buildArchitectPrompt(dispatch);
909
+ const providerPrompt = buildProviderCliPrompt(dispatch, architectPrompt, context.runtimeEnvironment);
910
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
441
911
  const command = buildProviderCliCommand(dispatch, {
442
912
  worktreePath: worktree.worktreePath,
443
- prompt: buildArchitectPrompt(dispatch),
444
- completionTools
913
+ prompt: architectPrompt,
914
+ promptFromStdin: pipePromptToStdin,
915
+ completionTools,
916
+ runtimeEnvironment: context.runtimeEnvironment
445
917
  });
446
- const commandText = formatProviderCliCommand(command);
918
+ const commandText = formatProviderCliCommandForCheckpoint(command);
447
919
  await context.emit({
448
920
  role: "runner",
449
921
  kind: "checkpoint",
450
922
  content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
451
- eventType: "provider_cli_started"
923
+ eventType: "provider_cli_starting"
452
924
  });
453
925
  await context.emit({
454
926
  role: "runner",
@@ -457,30 +929,39 @@ export class ProcessBackedProviderCliService {
457
929
  eventType: "completion_tools_configured"
458
930
  });
459
931
  const outputState = createProviderOutputState(dispatch.execution.provider);
932
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
460
933
  const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
461
934
  let result;
462
935
  try {
463
936
  liveArchitectEvents.start();
464
- result = await this.processRunner.run({
937
+ result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
465
938
  command: command.command,
466
939
  args: command.args,
467
940
  cwd: worktree.worktreePath,
468
- env: providerProcessEnv(dispatch)
941
+ env: providerProcessEnv(dispatch, context.runtimeEnvironment),
942
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
943
+ stdin: pipePromptToStdin ? providerPrompt : undefined
469
944
  }, {
470
- onStdoutLine: async (line) => {
471
- for (const event of outputState.consume(line)) {
472
- await context.emit(event);
473
- }
474
- }
945
+ onStarted: async () => {
946
+ await context.emit({
947
+ role: "runner",
948
+ kind: "checkpoint",
949
+ content: "Provider CLI Architect is supervised and ready.",
950
+ eventType: "provider_cli_started"
951
+ });
952
+ },
953
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
954
+ onGenerationStart: toolHeartbeat.startGeneration,
955
+ onStdoutLine: async (line) => await toolHeartbeat.consume(line)
475
956
  }, context.signal);
476
957
  }
477
958
  finally {
959
+ toolHeartbeat.stop();
478
960
  await liveArchitectEvents.stop();
479
961
  await cleanupCompletionTools(completionTools, context.emit);
480
962
  }
481
963
  if (result.exitCode !== 0) {
482
- const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
483
- throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
964
+ throw providerCliExitFailure(command.command, result);
484
965
  }
485
966
  await context.emit({
486
967
  role: "runner",
@@ -491,7 +972,7 @@ export class ProcessBackedProviderCliService {
491
972
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
492
973
  const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
493
974
  if (!architectArtifact) {
494
- throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
975
+ throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
495
976
  }
496
977
  if (!liveArchitectEvents.hasEmitted()) {
497
978
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
@@ -517,7 +998,7 @@ export class ProcessBackedProviderCliService {
517
998
  };
518
999
  }
519
1000
  async runQa(context) {
520
- const { dispatch, worktree } = context;
1001
+ const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
521
1002
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
522
1003
  await fs.mkdir(metadataRoot, { recursive: true });
523
1004
  const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
@@ -528,18 +1009,23 @@ export class ProcessBackedProviderCliService {
528
1009
  const specPath = path.join(metadataRoot, "spec.md");
529
1010
  await fs.writeFile(specPath, specBody, "utf8");
530
1011
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
531
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
1012
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
1013
+ const qaPrompt = buildQaPrompt(dispatch, specBody);
1014
+ const providerPrompt = buildProviderCliPrompt(dispatch, qaPrompt, context.runtimeEnvironment);
1015
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
532
1016
  const command = buildProviderCliCommand(dispatch, {
533
1017
  worktreePath: worktree.worktreePath,
534
- prompt: buildQaPrompt(dispatch, specBody),
535
- completionTools
1018
+ prompt: qaPrompt,
1019
+ promptFromStdin: pipePromptToStdin,
1020
+ completionTools,
1021
+ runtimeEnvironment: context.runtimeEnvironment
536
1022
  });
537
- const commandText = formatProviderCliCommand(command);
1023
+ const commandText = formatProviderCliCommandForCheckpoint(command);
538
1024
  await context.emit({
539
1025
  role: "runner",
540
1026
  kind: "checkpoint",
541
1027
  content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
542
- eventType: "provider_cli_started"
1028
+ eventType: "provider_cli_starting"
543
1029
  });
544
1030
  await context.emit({
545
1031
  role: "runner",
@@ -548,30 +1034,42 @@ export class ProcessBackedProviderCliService {
548
1034
  eventType: "completion_tools_configured"
549
1035
  });
550
1036
  const outputState = createProviderOutputState(dispatch.execution.provider);
1037
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
1038
+ const verificationProgress = new ManagedVerificationProgressEmitter(context.runtimeEnvironment?.FORGE_LOG_DIR, context.emit);
551
1039
  const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
552
1040
  let result;
553
1041
  try {
554
1042
  liveQaEvents.start();
555
- result = await this.processRunner.run({
1043
+ verificationProgress.start();
1044
+ result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
556
1045
  command: command.command,
557
1046
  args: command.args,
558
1047
  cwd: worktree.worktreePath,
559
- env: providerProcessEnv(dispatch)
1048
+ env: providerProcessEnv(dispatch, context.runtimeEnvironment),
1049
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1050
+ stdin: pipePromptToStdin ? providerPrompt : undefined
560
1051
  }, {
561
- onStdoutLine: async (line) => {
562
- for (const event of outputState.consume(line)) {
563
- await context.emit(event);
564
- }
565
- }
1052
+ onStarted: async () => {
1053
+ await context.emit({
1054
+ role: "runner",
1055
+ kind: "checkpoint",
1056
+ content: "Provider CLI QA is supervised and ready.",
1057
+ eventType: "provider_cli_started"
1058
+ });
1059
+ },
1060
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1061
+ onGenerationStart: toolHeartbeat.startGeneration,
1062
+ onStdoutLine: async (line) => await toolHeartbeat.consume(line)
566
1063
  }, context.signal);
567
1064
  }
568
1065
  finally {
1066
+ toolHeartbeat.stop();
1067
+ await verificationProgress.stop();
569
1068
  await liveQaEvents.stop();
570
1069
  await cleanupCompletionTools(completionTools, context.emit);
571
1070
  }
572
1071
  if (result.exitCode !== 0) {
573
- const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
574
- throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
1072
+ throw providerCliExitFailure(command.command, result);
575
1073
  }
576
1074
  await context.emit({
577
1075
  role: "runner",
@@ -580,14 +1078,21 @@ export class ProcessBackedProviderCliService {
580
1078
  eventType: "provider_cli_completed"
581
1079
  });
582
1080
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
583
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
1081
+ const lastRun = { result };
1082
+ let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
1083
+ if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
1084
+ // A headless provider that ends its turn to "wait for a background watcher"
1085
+ // exits for good. Resume the same thread instead of failing the session.
1086
+ qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
1087
+ }
584
1088
  if (!qaArtifact) {
585
1089
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
586
- throw new Error(verdictOnly
587
- ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
588
- : "Provider CLI QA completed but did not call the Forge QA completion tool.");
1090
+ if (verdictOnly) {
1091
+ throw new Error("Provider CLI QA completed but did not produce the complete durable QA artifact bundle.");
1092
+ }
1093
+ throw providerCompletionToolMissingFailure("Provider CLI QA completed but did not call the Forge QA completion tool.", lastRun.result);
589
1094
  }
590
- enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
1095
+ await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
591
1096
  if (!liveQaEvents.hasEmitted()) {
592
1097
  await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
593
1098
  await emitQaStructuredEvents(context.emit, qaArtifact);
@@ -611,2324 +1116,595 @@ export class ProcessBackedProviderCliService {
611
1116
  artifacts: [qaArtifact]
612
1117
  };
613
1118
  }
1119
+ async runCiRepair(context) {
1120
+ return await this.runPullRequestRepair(context, "ci_repair");
1121
+ }
614
1122
  async runConflictResolve(context) {
615
- const { dispatch, worktree } = context;
616
- const addressComments = isPullRequestCommentsDispatch(dispatch);
1123
+ return await this.runPullRequestRepair(context, "conflict_resolve");
1124
+ }
1125
+ async runPullRequestRepair(context, route) {
1126
+ const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
1127
+ const { expectedRepairHeadSha, preparedHeadSha } = await assertRepairHeadEpoch(context, this.git);
1128
+ const repairChecks = route === "ci_repair" || isPullRequestCheckRepairDispatch(dispatch);
1129
+ const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
1130
+ let repairSpec = null;
1131
+ let repairEnvironment = context.runtimeEnvironment;
1132
+ let ciRepairSpecPath = null;
1133
+ let completionTools = null;
1134
+ if (repairChecks) {
1135
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
1136
+ await fs.mkdir(metadataRoot, { recursive: true });
1137
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
1138
+ if (!laneCommand) {
1139
+ throw new Error(`CI repair readiness failed: lane command for '${dispatch.execution.lane}' was not resolved, so the approved spec cannot be materialized.`);
1140
+ }
1141
+ const specBody = buildSpecBody(laneCommand, dispatch.workItem, "ci_repair");
1142
+ const specPath = path.join(metadataRoot, "spec.md");
1143
+ ciRepairSpecPath = specPath;
1144
+ await fs.writeFile(specPath, specBody, "utf8");
1145
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), `${JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" })}\n`, "utf8");
1146
+ repairSpec = {
1147
+ repoPath: worktree.worktreePath,
1148
+ path: specPath,
1149
+ body: specBody,
1150
+ producedBy: "forge-lane-command",
1151
+ status: "approved",
1152
+ };
1153
+ const readiness = await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, specPath, context.runtimeEnvironment);
1154
+ repairEnvironment = readiness.environment;
1155
+ completionTools = await prepareCompletionToolRuntime({
1156
+ dispatch, worktree, phase: "ci_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
1157
+ });
1158
+ await context.emit({
1159
+ role: "runner",
1160
+ kind: "checkpoint",
1161
+ content: `CI repair readiness contract prepared at ${path.relative(worktree.worktreePath, readiness.path).replaceAll(path.sep, "/")}; approved spec, attempt URLs, browser readiness, and local-equivalence policy are available before provider start.`,
1162
+ eventType: "ci_repair_readiness_ready",
1163
+ });
1164
+ await context.emit({
1165
+ role: "runner",
1166
+ kind: "checkpoint",
1167
+ content: "Forge CI repair completion tool configured; provider must call forge.complete_ci_repair before Bridge-owned commit and push.",
1168
+ eventType: "completion_tools_configured",
1169
+ });
1170
+ }
1171
+ if (addressComments) {
1172
+ completionTools = await prepareCompletionToolRuntime({
1173
+ dispatch, worktree, phase: "comment_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
1174
+ });
1175
+ await context.emit({
1176
+ role: "runner",
1177
+ kind: "checkpoint",
1178
+ content: "Forge comment-repair completion tool configured; provider must record an evidence-backed disposition for every actionable snapshot finding.",
1179
+ eventType: "completion_tools_configured",
1180
+ });
1181
+ }
1182
+ const repairPrompt = repairChecks
1183
+ ? buildPullRequestCheckRepairPrompt(dispatch, worktree.branchName)
1184
+ : addressComments
1185
+ ? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
1186
+ : buildConflictResolvePrompt(dispatch, worktree.branchName);
1187
+ const providerPrompt = buildProviderCliPrompt(dispatch, repairPrompt, repairEnvironment);
1188
+ const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
617
1189
  const command = buildProviderCliCommand(dispatch, {
618
1190
  worktreePath: worktree.worktreePath,
619
- prompt: addressComments
620
- ? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
621
- : buildConflictResolvePrompt(dispatch, worktree.branchName)
1191
+ prompt: repairPrompt,
1192
+ promptFromStdin: pipePromptToStdin,
1193
+ completionTools: completionTools ?? undefined,
1194
+ runtimeEnvironment: repairEnvironment
622
1195
  });
623
1196
  await context.emit({
624
1197
  role: "runner",
625
1198
  kind: "checkpoint",
626
- content: `Starting provider CLI ${addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
627
- eventType: "provider_cli_started"
1199
+ content: `Starting provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommandForCheckpoint(command)} in ${worktree.worktreePath}`,
1200
+ eventType: "provider_cli_starting"
628
1201
  });
629
1202
  const outputState = createProviderOutputState(dispatch.execution.provider);
630
- const result = await this.processRunner.run({
631
- command: command.command,
632
- args: command.args,
633
- cwd: worktree.worktreePath,
634
- env: providerProcessEnv(dispatch)
635
- }, {
636
- onStdoutLine: async (line) => {
637
- for (const event of outputState.consume(line)) {
638
- await context.emit(event);
1203
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
1204
+ let result;
1205
+ let providerStarted = false;
1206
+ try {
1207
+ result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
1208
+ command: command.command,
1209
+ args: command.args,
1210
+ cwd: worktree.worktreePath,
1211
+ env: providerProcessEnv(dispatch, repairEnvironment),
1212
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1213
+ stdin: pipePromptToStdin ? providerPrompt : undefined
1214
+ }, {
1215
+ onStarted: async () => {
1216
+ await context.emit({
1217
+ role: "runner",
1218
+ kind: "checkpoint",
1219
+ content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} is supervised and ready.`,
1220
+ eventType: "provider_cli_started"
1221
+ });
1222
+ providerStarted = true;
1223
+ },
1224
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1225
+ onGenerationStart: toolHeartbeat.startGeneration,
1226
+ onStdoutLine: async (line) => {
1227
+ await toolHeartbeat.consume(line);
1228
+ }
1229
+ }, context.signal);
1230
+ }
1231
+ finally {
1232
+ toolHeartbeat.stop();
1233
+ try {
1234
+ if (providerStarted) {
1235
+ await context.emit({
1236
+ role: "runner",
1237
+ kind: "checkpoint",
1238
+ content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} turn exited.`,
1239
+ eventType: "provider_cli_completed"
1240
+ });
1241
+ }
1242
+ }
1243
+ finally {
1244
+ if (completionTools) {
1245
+ await cleanupCompletionTools(completionTools, context.emit);
639
1246
  }
640
1247
  }
641
- }, context.signal);
1248
+ }
642
1249
  if (result.exitCode !== 0) {
643
- const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
644
- throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
1250
+ throw providerCliExitFailure(command.command, result);
1251
+ }
1252
+ const postProviderHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
1253
+ if (postProviderHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
1254
+ throw new Error(`provider_publication_boundary_violation: PR repair changed HEAD from ${preparedHeadSha} to ${postProviderHeadSha}; Forge requires provider changes to remain uncommitted and unpushed until validation passes.`);
1255
+ }
1256
+ let repairArtifact = null;
1257
+ if (repairChecks) {
1258
+ repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
1259
+ if (!repairArtifact) {
1260
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
1261
+ }
1262
+ if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1263
+ throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
1264
+ }
1265
+ }
1266
+ if (addressComments) {
1267
+ repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
1268
+ const lastRun = { result };
1269
+ if (!repairArtifact) {
1270
+ repairArtifact = await this.recoverMissingCommentRepairCompletion({
1271
+ context,
1272
+ repairEnvironment,
1273
+ outputState,
1274
+ preparedHeadSha,
1275
+ lastRun,
1276
+ });
1277
+ }
1278
+ if (!repairArtifact) {
1279
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.", lastRun.result);
1280
+ }
1281
+ if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1282
+ throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
1283
+ }
1284
+ assertCommentRepairArtifactMatchesDispatch(dispatch, repairArtifact);
1285
+ }
1286
+ let commentRepairBaselineChangedFiles = null;
1287
+ if (addressComments && repairArtifact) {
1288
+ const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1289
+ commentRepairBaselineChangedFiles = baseline.publishable;
1290
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
1291
+ assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
1292
+ }
1293
+ const validationProfile = repairChecks
1294
+ ? "ci_repair"
1295
+ : addressComments
1296
+ ? "comment_repair"
1297
+ : "conflict_repair";
1298
+ const readinessSpecPath = ciRepairSpecPath;
1299
+ await this.validatePrePublicationWithRecovery({
1300
+ context,
1301
+ validationProfile,
1302
+ repairEnvironment,
1303
+ outputState,
1304
+ preparedHeadSha,
1305
+ repairScope: "pull_request",
1306
+ ...(readinessSpecPath ? {
1307
+ // The readiness manifest records the attempt URLs; a restart must not leave it pointing at the old stack.
1308
+ onRuntimeEnvironmentRefreshed: async (runtimeEnvironment) => (await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, readinessSpecPath, runtimeEnvironment)).environment,
1309
+ } : {}),
1310
+ });
1311
+ const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1312
+ const stagedChangedFiles = stagedChangeSet.publishable;
1313
+ if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
1314
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
1315
+ repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
1316
+ }
1317
+ const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
1318
+ const publishedByProvider = providerOwnsBranchPublication(context);
1319
+ const publishedCommitSha = publishedByProvider
1320
+ ? await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, worktree.repoPath, this.publicationCoordinator, context.signal, context.emit, expectedRepairHeadSha)
1321
+ : null;
1322
+ if (repairArtifact) {
1323
+ await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, repairArtifact);
1324
+ await emitPhaseCompletionEvent(context.emit, repairArtifact);
1325
+ await emitPhaseGateEvents(context.emit, repairArtifact);
645
1326
  }
646
- const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
647
- await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
648
1327
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
649
1328
  await context.emit({
650
1329
  role: "assistant",
651
1330
  kind: "message",
652
- content: outputState.finalMessage || (addressComments
653
- ? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
654
- : `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
655
- eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
1331
+ content: outputState.finalMessage || (repairChecks
1332
+ ? `${dispatch.execution.provider} CLI repaired pull request checks for ${worktree.branchName}.`
1333
+ : addressComments
1334
+ ? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
1335
+ : `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
1336
+ eventType: repairChecks ? "pr_checks_complete" : addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
656
1337
  });
657
1338
  return {
658
- summary: addressComments
659
- ? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
660
- : `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
1339
+ summary: repairChecks
1340
+ ? `${dispatch.execution.provider} CLI repaired PR checks on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`
1341
+ : addressComments
1342
+ ? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`
1343
+ : `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`,
1344
+ resultCommitSha: publishedCommitSha ?? committed.commitSha,
1345
+ publishedCommitSha,
1346
+ spec: repairSpec,
1347
+ artifact: repairArtifact,
1348
+ artifacts: repairArtifact ? [repairArtifact] : [],
661
1349
  };
662
1350
  }
663
- }
664
- export class DeterministicProviderCliService {
665
- git;
666
- constructor(git = new GitClient()) {
667
- this.git = git;
668
- }
669
- async runDraft(context) {
670
- const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
671
- await context.emit({
672
- role: "assistant",
673
- kind: "message",
674
- content,
675
- eventType: "draft_complete"
676
- });
677
- await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
678
- return { summary: "forge-bridge generated deterministic draft." };
679
- }
680
- async runImplementation(context) {
1351
+ async recoverMissingQaCompletion(options) {
1352
+ const { context, outputState } = options;
681
1353
  const { dispatch, worktree } = context;
682
- const phase = completionPhaseFromDispatch(dispatch);
683
- const developCycle = usesDevelopCycleCompletion(dispatch);
684
- const debugCycle = usesDebugCycleCompletion(dispatch);
685
- const providerCommand = buildProviderCliCommand(dispatch);
686
- const providerCommandText = formatProviderCliCommand(providerCommand);
687
- const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
688
- const artifactRoot = path.join(metadataRoot, "artifacts");
689
- await fs.mkdir(artifactRoot, { recursive: true });
690
- const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
691
- if (!laneCommand) {
692
- throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
693
- }
694
- const specBody = `${buildSpecBody(laneCommand, dispatch.workItem, phase)}
695
- ## Execution
696
-
697
- - Provider: ${singleLine(dispatch.execution.provider)}
698
- - Model: ${singleLine(dispatch.execution.model)}
699
- - Command: ${providerCommandText}
700
- `;
701
- const specPath = path.join(metadataRoot, "spec.md");
702
- await fs.writeFile(specPath, specBody, "utf8");
703
- await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
704
- const changesetPath = path.join(worktree.worktreePath, "FORGE_PHASE5_CHANGESET.md");
705
- const changesetBody = `# Forge Phase 5 bridge changeset\n\nWork item: ${dispatch.workItem.id}\nTitle: ${dispatch.workItem.title}\nBranch: ${worktree.branchName}\nProvider: ${singleLine(dispatch.execution.provider)}\nModel: ${singleLine(dispatch.execution.model)}\nCommand: ${providerCommandText}\n\nThis deterministic file is written by forge-bridge run-once through the shared session/worktree service path.\n`;
706
- await fs.writeFile(changesetPath, changesetBody, "utf8");
707
- await this.git.run(worktree.worktreePath, ["add", "FORGE_PHASE5_CHANGESET.md"]);
708
- await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge changeset for ${dispatch.workItem.id.slice(0, 8)}`]);
709
- await context.emit({
710
- role: "worker",
711
- kind: "file_edit",
712
- content: `Created bridge changeset at ${changesetPath}`,
713
- eventType: "changeset"
714
- });
715
- const phases = debugCycle
716
- ? debugCompletionPhaseOrder
717
- : developCycle
718
- ? ["implementation", "self_review", "validation"]
719
- : [phase];
720
- const completionArtifacts = [];
721
- for (const completionPhase of phases) {
722
- await writeCompletionArtifact({
723
- worktreePath: worktree.worktreePath,
724
- workItemId: dispatch.workItem.id,
725
- phase: completionPhase,
726
- producedBy: "forge-bridge",
727
- redactionSecrets: exactRedactionSecrets(dispatch)
728
- }, isDebugCompletionPhaseForProvider(completionPhase)
729
- ? expectedDebugCompletionToolName(completionPhase)
730
- : expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
731
- const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
732
- if (!completionArtifact) {
733
- throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
734
- }
735
- completionArtifacts.push(completionArtifact);
736
- await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
1354
+ const normalizedProvider = dispatch.execution.provider.trim().toLowerCase();
1355
+ const providerThreadId = outputState.providerThreadId?.trim();
1356
+ if ((normalizedProvider !== "codex" && normalizedProvider !== "cursor" && normalizedProvider !== "claude")
1357
+ || !providerThreadId) {
737
1358
  await context.emit({
738
- role: "assistant",
739
- kind: "message",
740
- content: `${completionPhase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
741
- eventType: phaseCompleteEventType(completionPhase)
1359
+ role: "runner",
1360
+ kind: "error",
1361
+ content: `Forge could not resume QA for the missing verdict because provider '${dispatch.execution.provider}' did not report a resumable thread.`,
1362
+ eventType: "completion_tool_recovery_unavailable",
1363
+ data: JSON.stringify({ phase: "qa", provider: normalizedProvider }),
742
1364
  });
1365
+ return null;
743
1366
  }
744
- await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
745
- return {
746
- summary: `forge-bridge completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}).`,
747
- spec: {
748
- repoPath: worktree.worktreePath,
749
- path: specPath,
750
- body: specBody,
751
- producedBy: "forge-lane-command",
752
- status: "approved"
753
- },
754
- artifact: completionArtifacts[0],
755
- artifacts: completionArtifacts
756
- };
757
- }
758
- async runArchitect(context) {
759
- const { dispatch, worktree } = context;
760
- const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
761
- await fs.mkdir(metadataRoot, { recursive: true });
762
- const specBody = `---\ntitle: "${dispatch.workItem.title}"\nstatus: pending_approval\nproduced_by: forge-bridge\n---\n\n# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`;
763
- const specPath = path.join(metadataRoot, "spec.md");
764
- await fs.writeFile(specPath, specBody, "utf8");
765
- await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
766
- await writeCompletionArtifact({
767
- worktreePath: worktree.worktreePath,
768
- workItemId: dispatch.workItem.id,
769
- phase: "architect",
770
- producedBy: "forge-bridge",
771
- redactionSecrets: exactRedactionSecrets(dispatch),
772
- architectCycle: true
773
- }, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
774
- const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
775
- if (!artifact) {
776
- throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
777
- }
778
- await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
779
- await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
780
- await context.emit({
781
- role: "assistant",
782
- kind: "message",
783
- content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
784
- eventType: "architect_complete"
785
- });
786
- return {
787
- summary: "forge-bridge completed Architect plan (deterministic).",
788
- spec: {
789
- repoPath: worktree.worktreePath,
790
- path: specPath,
791
- body: specBody,
792
- producedBy: "forge-bridge",
793
- status: "pending_approval"
794
- },
795
- artifact,
796
- artifacts: [artifact]
797
- };
798
- }
799
- async runQa(context) {
800
- const { dispatch, worktree } = context;
801
- await context.emit({
802
- role: "worker",
803
- kind: "message",
804
- content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
805
- eventType: "qa_plan"
806
- });
807
- const qaBrowser = dispatch.qaBrowser;
808
- const launchTarget = qaBrowser?.launchTarget ?? null;
809
- const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
810
- const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
811
- ? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
812
- : null;
813
- const browserChecks = browserSidecar && launchTarget
814
- ? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
815
- : [];
816
- const sidecars = await writeQaSidecarFiles(worktree.worktreePath, browserSidecar ? [browserSidecar] : []);
817
- const summary = missingLaunchTarget
818
- ? "QA blocked because browser testing is required but no app launch target was provided."
819
- : "All checks passed. forge-bridge QA completed.";
820
- const criterion = dispatch.workItem.acceptanceCriteria.trim() || "Forge QA evidence exists";
821
- for (const gate of qaCompletionGateOrder) {
822
- await writeCompletionArtifact({
823
- worktreePath: worktree.worktreePath,
824
- workItemId: dispatch.workItem.id,
825
- phase: "qa",
826
- producedBy: "forge-bridge",
827
- redactionSecrets: exactRedactionSecrets(dispatch),
828
- qaCycle: true,
829
- ownerType: dispatch.cycleRun.ownerType ?? undefined,
830
- ownerId: dispatch.cycleRun.ownerId ?? undefined
831
- }, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
832
- gate,
833
- criterion,
834
- summary,
835
- missingLaunchTarget,
836
- browserChecks,
837
- sidecars
838
- }));
839
- const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
840
- if (gateArtifact) {
841
- await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
842
- }
843
- }
844
- const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
845
- if (!qaArtifact) {
846
- throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
847
- }
848
- await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
849
- await emitQaStructuredEvents(context.emit, qaArtifact);
850
- await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
851
- return {
852
- summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
853
- artifact: qaArtifact,
854
- artifacts: [qaArtifact]
855
- };
856
- }
857
- async runConflictResolve(context) {
858
- const { dispatch, worktree } = context;
859
- const addressComments = isPullRequestCommentsDispatch(dispatch);
860
- await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
861
- await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
862
- await context.emit({
863
- role: "assistant",
864
- kind: "message",
865
- content: addressComments
866
- ? `Deterministic PR comment addressing completed for ${worktree.branchName}.`
867
- : `Deterministic conflict resolve completed for ${worktree.branchName}.`,
868
- eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
869
- });
870
- return {
871
- summary: addressComments
872
- ? `forge-bridge addressed PR comments for ${worktree.branchName}.`
873
- : `forge-bridge resolved conflicts for ${worktree.branchName}.`
874
- };
875
- }
876
- }
877
- function phaseCompleteEventType(phase) {
878
- return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
879
- }
880
- function isDebugCompletionPhaseForProvider(phase) {
881
- return debugCompletionPhaseOrder.includes(phase);
882
- }
883
- function deterministicCompletionPayload(phase, dispatch, changesetBody) {
884
- const changesetHash = sha256(changesetBody);
885
- const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
886
- if (phase === "implementation") {
887
- return {
888
- status: "pass",
889
- summary: "forge-bridge produced a deterministic implementation changeset.",
890
- plan: [{ step: "Create deterministic changeset", status: "done" }],
891
- changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
892
- tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
893
- docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
894
- acceptance_criteria: [
895
- {
896
- criterion,
897
- evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
898
- status: "satisfied"
899
- }
900
- ],
901
- known_gaps: [],
902
- next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
903
- };
904
- }
905
- if (phase === "debug_repro") {
906
- return {
907
- status: "pass",
908
- summary: "forge-bridge reproduced the bug deterministically.",
909
- repro_steps: ["Run the deterministic fake-worker debug reproduction."],
910
- observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
911
- expected: "The bug scenario should be fixed before QA handoff.",
912
- evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
913
- };
914
- }
915
- if (phase === "debug_root_cause") {
916
- return {
917
- status: "pass",
918
- summary: "forge-bridge isolated a deterministic root cause.",
919
- root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
920
- evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
921
- eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
922
- risk_area: "forge-bridge deterministic debug lane"
923
- };
924
- }
925
- if (phase === "debug_fix") {
926
- return {
927
- status: "pass",
928
- summary: "forge-bridge applied a deterministic debug fix.",
929
- changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
930
- tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
931
- remaining_risks: [],
932
- resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
933
- qa_id: qaId,
934
- status: "resolved",
935
- summary: `Resolved deterministic QA finding ${qaId}.`,
936
- evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
937
- changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
938
- tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
939
- regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
940
- }))
941
- };
942
- }
943
- if (phase === "debug_regression") {
944
- return {
945
- status: "pass",
946
- summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
947
- commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
948
- required_regressions: ["Original deterministic repro no longer fails."],
949
- build_status: "not_applicable",
950
- test_status: "pass",
951
- repro_negative: true,
952
- qa_ready: true
953
- };
954
- }
955
- if (phase === "self_review") {
956
- return {
957
- status: "pass",
958
- summary: "forge-bridge fake worker completed deterministic self-review.",
959
- reviewed_diff: true,
960
- findings: [],
961
- security_review: {
962
- status: "pass",
963
- notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
964
- },
965
- edge_case_review: {
966
- status: "pass",
967
- notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
968
- },
969
- design_review: {
970
- status: "not_applicable",
971
- screenshots: [],
972
- notes: "No UI changes."
973
- },
974
- deterministic_comparison: {
975
- status: "pass",
976
- command_or_tool: "git diff --stat HEAD~1..HEAD",
977
- notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
978
- },
979
- fixes_applied: [],
980
- remaining_risks: []
981
- };
982
- }
983
- return {
984
- status: "pass",
985
- summary: "forge-bridge fake worker completed deterministic validation.",
986
- commands: [
987
- {
988
- command: "git status --short && git diff --check",
989
- exit_code: 0,
990
- status: "pass",
991
- summary: "Deterministic validation command completed for the fake-worker changeset."
992
- }
993
- ],
994
- acceptance_criteria: [
995
- {
996
- criterion,
997
- evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
998
- status: "satisfied"
999
- }
1000
- ],
1001
- build_status: "pass",
1002
- test_status: "pass",
1003
- lint_status: "not_applicable",
1004
- design_status: "not_applicable",
1005
- drift_checks: [
1006
- {
1007
- command_or_tool: "git diff --check",
1008
- status: "pass",
1009
- summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
1010
- }
1011
- ],
1012
- ready_for_dev_test: true
1013
- };
1014
- }
1015
- function deterministicArchitectPayload(dispatch) {
1016
- const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
1017
- return {
1018
- status: "pass",
1019
- summary: "forge-bridge produced a deterministic Architect plan.",
1020
- implementation_plan: {
1021
- schema_version: 1,
1022
- plan_id: planId,
1023
- story_id: dispatch.workItem.id,
1024
- phases: [
1025
- { id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
1026
- ],
1027
- tasks: [
1028
- {
1029
- id: "task-1",
1030
- title: `Implement ${dispatch.workItem.title}`,
1031
- phase: "phase-1",
1032
- summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
1033
- acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
1034
- tests: [
1035
- { command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
1036
- ]
1037
- }
1038
- ],
1039
- dependencies: [],
1040
- phase_gates: [
1041
- { id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
1042
- ]
1043
- },
1044
- qa_plan: {
1045
- schema_version: 1,
1046
- plan_id: planId,
1047
- final_qa: [
1048
- { id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
1049
- ]
1050
- },
1051
- report_markdown: `# Architect Report\n\nWork item: ${dispatch.workItem.id}\nTitle: ${dispatch.workItem.title}\n\nVerdict: pass\n\nDeterministic bridge Architect plan produced for pending approval.\n`
1052
- };
1053
- }
1054
- function deterministicQaGatePayload(options) {
1055
- const blocked = options.missingLaunchTarget;
1056
- const skippedBecauseBlocked = blocked
1057
- ? {
1058
- status: "skipped",
1059
- summary: "Skipped because browser QA was blocked by missing launch target.",
1060
- reason: "Upstream browser QA blocker prevents meaningful downstream evidence."
1061
- }
1062
- : null;
1063
- switch (options.gate) {
1064
- case "qa_plan":
1065
- return {
1066
- status: "pass",
1067
- summary: "Deterministic QA plan recorded.",
1068
- checklist: [
1069
- "Review the validated work item against acceptance criteria.",
1070
- "Run deterministic regression evidence.",
1071
- "Confirm no in-scope QA findings remain."
1072
- ],
1073
- acceptance_criteria: [options.criterion]
1074
- };
1075
- case "qa_regression":
1076
- return {
1077
- status: "pass",
1078
- summary: "Deterministic regression QA completed.",
1079
- commands: [
1080
- {
1081
- command: "forge-bridge deterministic QA",
1082
- exit_code: 0,
1083
- status: "pass",
1084
- summary: "Deterministic regression evidence completed."
1085
- }
1086
- ],
1087
- notes: "Regression gate passed in deterministic fake-worker mode."
1088
- };
1089
- case "qa_api":
1090
- return {
1091
- status: "skipped",
1092
- summary: "No API/backend surface was identified for deterministic QA.",
1093
- reason: "The deterministic fake-worker changeset does not exercise API/backend behavior."
1094
- };
1095
- case "qa_manual_web":
1096
- return blocked
1097
- ? {
1098
- status: "blocked",
1099
- summary: "Browser QA could not run because no app launch target was provided.",
1100
- blocker_reason: "missing_app_launch_target"
1101
- }
1102
- : options.browserChecks.length > 0
1103
- ? {
1104
- status: "pass",
1105
- summary: "Deterministic browser QA exercised the configured launch target.",
1106
- browser_checks: options.browserChecks,
1107
- sidecars: options.sidecars,
1108
- notes: "Browser sidecar evidence recorded."
1109
- }
1110
- : {
1111
- status: "skipped",
1112
- summary: "Manual web QA was not required for this deterministic run.",
1113
- reason: "Forge did not require browser QA and no launch target was necessary."
1114
- };
1115
- case "qa_bug_repro":
1116
- return skippedBecauseBlocked ?? {
1117
- status: "skipped",
1118
- summary: "No failed QA observation required bug reproduction.",
1119
- reason: "No defects or candidate bugs were observed."
1120
- };
1121
- case "qa_findings":
1122
- return skippedBecauseBlocked ?? {
1123
- status: "pass",
1124
- summary: "No QA findings or candidate bugs were identified.",
1125
- findings: [],
1126
- candidate_bugs: []
1127
- };
1128
- case "qa_verdict":
1129
- return {
1130
- status: blocked ? "blocked" : "pass",
1131
- summary: options.summary,
1132
- checklist: [
1133
- "Review the validated work item against acceptance criteria.",
1134
- "Run deterministic regression evidence.",
1135
- blocked ? "Record missing browser launch target blocker." : "Confirm no in-scope QA findings remain."
1136
- ],
1137
- tested_acceptance_criteria: blocked ? [] : [options.criterion],
1138
- commands: blocked
1139
- ? []
1140
- : [
1141
- {
1142
- command: "forge-bridge deterministic QA",
1143
- exit_code: 0,
1144
- status: "pass",
1145
- summary: "Deterministic QA command completed."
1146
- }
1147
- ],
1148
- browser_checks: blocked ? [] : options.browserChecks,
1149
- sidecars: blocked ? [] : options.sidecars,
1150
- notes: options.summary,
1151
- findings: [],
1152
- candidate_bugs: [],
1153
- blocker_reason: blocked ? "missing_app_launch_target" : null,
1154
- report_markdown: `# QA report\n\n${options.summary}\n`
1155
- };
1156
- }
1157
- }
1158
- const qaArtifactFileNames = {
1159
- plan: "qa.plan.json",
1160
- evidence: "qa.evidence.json",
1161
- findings: "qa.findings.json",
1162
- verdict: "qa.verdict.json",
1163
- report: "qa.report.md"
1164
- };
1165
- const qaGateArtifactFileNames = {
1166
- qa_plan: "qa.plan.json",
1167
- qa_regression: "qa.regression.json",
1168
- qa_api: "qa.api.json",
1169
- qa_manual_web: "qa.manual-web.json",
1170
- qa_bug_repro: "qa.bug-repro.json",
1171
- qa_findings: "qa.findings.json",
1172
- qa_verdict: "qa.verdict.json"
1173
- };
1174
- function hasLaunchTarget(target) {
1175
- return Boolean(target?.url?.trim()
1176
- || target?.ready_url?.trim()
1177
- || target?.command?.trim()
1178
- || (target?.routes ?? []).some((route) => route.trim().length > 0));
1179
- }
1180
- function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
1181
- const route = primaryLaunchRoute(target);
1182
- return {
1183
- relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
1184
- content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
1185
- };
1186
- }
1187
- function deterministicBrowserCheck(target, screenshotPath) {
1188
- const route = primaryLaunchRoute(target);
1189
- return {
1190
- route,
1191
- url: route,
1192
- status: "pass",
1193
- summary: "Deterministic browser QA exercised the configured launch target.",
1194
- actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
1195
- screenshots: [screenshotPath],
1196
- console_errors: [],
1197
- network_errors: [],
1198
- responsive_checks: ["desktop", "mobile"]
1199
- };
1200
- }
1201
- function primaryLaunchRoute(target) {
1202
- return target.ready_url?.trim()
1203
- || target.url?.trim()
1204
- || target.routes.find((route) => route.trim().length > 0)?.trim()
1205
- || "app launch command";
1206
- }
1207
- async function writeQaSidecarFiles(worktreePath, files) {
1208
- const sidecars = [];
1209
- for (const file of files) {
1210
- const fullPath = path.resolve(worktreePath, file.relativePath);
1211
- const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
1212
- if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
1213
- throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
1214
- }
1215
- await fs.mkdir(path.dirname(fullPath), { recursive: true });
1216
- await fs.writeFile(fullPath, file.content, "utf8");
1217
- sidecars.push({
1218
- path: relativePath,
1219
- content_hash: sha256(file.content),
1220
- bytes: Buffer.byteLength(file.content, "utf8")
1221
- });
1222
- }
1223
- return sidecars;
1224
- }
1225
- async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
1226
- const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1227
- await emit({
1228
- role: "tool",
1229
- kind: "tool_result",
1230
- content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
1231
- eventType: "qa_artifact_recorded"
1232
- });
1233
- await emit({
1234
- role: "hook",
1235
- kind: "checkpoint",
1236
- content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
1237
- eventType: "phase_gate"
1238
- });
1239
- }
1240
- async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1241
- const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
1242
- if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
1243
- return null;
1244
- }
1245
- const artifactRoot = ownerType && ownerId
1246
- ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1247
- : artifactRootFor(worktreePath, workItemId);
1248
- const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
1249
- const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
1250
- const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
1251
- await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
1252
- return {
1253
- ...artifact,
1254
- planJson,
1255
- evidenceJson,
1256
- findingsJson
1257
- };
1258
- }
1259
- async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
1260
- const artifactRoot = ownerType && ownerId
1261
- ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1262
- : artifactRootFor(worktreePath, workItemId);
1263
- for (const fileName of Object.values(qaArtifactFileNames)) {
1264
- try {
1265
- const stat = await fs.stat(path.join(artifactRoot, fileName));
1266
- if (!stat.isFile()) {
1267
- return false;
1268
- }
1269
- }
1270
- catch (error) {
1271
- if (isNodeError(error) && error.code === "ENOENT") {
1272
- return false;
1273
- }
1274
- throw error;
1275
- }
1276
- }
1277
- return true;
1278
- }
1279
- function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
1280
- const qaBrowser = dispatch.qaBrowser;
1281
- if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
1282
- return;
1283
- }
1284
- const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1285
- const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
1286
- const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
1287
- if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
1288
- throw new Error("QA browser testing is required but no app launch target was provided; provider must return blocked with blocker_reason missing_app_launch_target.");
1289
- }
1290
- }
1291
- async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
1292
- const artifactRoot = ownerType && ownerId
1293
- ? artifactRootForOwner(worktreePath, ownerType, ownerId)
1294
- : artifactRootFor(worktreePath, workItemId);
1295
- const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1296
- const sidecars = arrayField(evidence, "sidecars");
1297
- if (sidecars.length === 0) {
1298
- return;
1299
- }
1300
- const qaSidecarRoot = path.resolve(artifactRoot, "qa");
1301
- for (const [index, sidecar] of sidecars.entries()) {
1302
- const sidecarPath = stringField(sidecar, "path");
1303
- const expectedHash = stringField(sidecar, "content_hash");
1304
- const expectedBytes = sidecar.bytes;
1305
- if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
1306
- throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
1307
- }
1308
- if (path.isAbsolute(sidecarPath)) {
1309
- throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
1310
- }
1311
- const fullPath = path.resolve(worktreePath, sidecarPath);
1312
- if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
1313
- const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1314
- const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
1315
- throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
1316
- }
1317
- const stat = await fs.lstat(fullPath).catch((error) => {
1318
- if (isNodeError(error) && error.code === "ENOENT") {
1319
- throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
1320
- }
1321
- throw error;
1322
- });
1323
- if (!stat.isFile() || stat.isSymbolicLink()) {
1324
- throw new Error(`QA sidecar ${index} must reference a regular file.`);
1325
- }
1326
- await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
1327
- if (stat.size !== expectedBytes) {
1328
- throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
1329
- }
1330
- const actualHash = await sha256File(fullPath);
1331
- if (actualHash !== expectedHash.trim().toLowerCase()) {
1332
- throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
1333
- }
1334
- }
1335
- }
1336
- async function emitQaStructuredEvents(emit, artifact) {
1337
- const artifactRoot = path.dirname(artifact.path);
1338
- const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
1339
- const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
1340
- const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
1341
- const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1342
- const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1343
- const checklist = stringArrayField(plan, "checklist");
1344
- await emit({
1345
- role: "worker",
1346
- kind: "message",
1347
- content: checklist.length > 0
1348
- ? `QA plan: ${checklist.join("; ")}`
1349
- : "QA plan recorded.",
1350
- eventType: "qa_plan"
1351
- });
1352
- for (const browserCheck of arrayField(evidence, "browser_checks")) {
1353
- await emit({
1354
- role: "worker",
1355
- kind: "checkpoint",
1356
- content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
1357
- eventType: "qa_browser_check"
1358
- });
1359
- }
1360
- for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
1361
- await emit({
1362
- role: "worker",
1363
- kind: "checkpoint",
1364
- content: `QA finding: ${summarizeQaObject(finding)}`,
1365
- eventType: "qa_finding"
1366
- });
1367
- }
1368
- await emit({
1369
- role: "assistant",
1370
- kind: "message",
1371
- content: status === "blocked"
1372
- ? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
1373
- : `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
1374
- eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
1375
- });
1376
- }
1377
- function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
1378
- return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
1379
- ? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
1380
- : artifactRootFor(worktreePath, workItemId);
1381
- }
1382
- async function readQaGateArtifact(artifactRoot, gate) {
1383
- const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
1384
- try {
1385
- const stat = await fs.stat(artifactPath);
1386
- if (!stat.isFile()) {
1387
- return null;
1388
- }
1389
- }
1390
- catch (error) {
1391
- if (isNodeError(error) && error.code === "ENOENT") {
1392
- return null;
1393
- }
1394
- throw error;
1395
- }
1396
- const payload = await readJsonObjectFile(artifactPath);
1397
- return {
1398
- gate,
1399
- path: artifactPath,
1400
- status: stringField(payload, "status") ?? "unknown",
1401
- producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
1402
- contentHash: stringField(payload, "content_hash") ?? undefined
1403
- };
1404
- }
1405
- function nextQaGate(gate) {
1406
- const index = qaCompletionGateOrder.indexOf(gate);
1407
- return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
1408
- }
1409
- async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
1410
- const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
1411
- await emit({
1412
- role: "hook",
1413
- kind: artifact.status === "blocked" ? "error" : "checkpoint",
1414
- content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
1415
- eventType: "phase_gate",
1416
- data: JSON.stringify({
1417
- phase: "qa",
1418
- qa_gate: artifact.gate,
1419
- status: artifact.status,
1420
- artifact_relative_paths: [relativePath],
1421
- content_hash: artifact.contentHash ?? null,
1422
- produced_by: artifact.producedBy ?? null
1423
- })
1424
- });
1425
- if (!nextGate) {
1426
- return;
1427
- }
1428
- await emit({
1429
- role: "hook",
1430
- kind: "checkpoint",
1431
- content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
1432
- eventType: "phase_gate",
1433
- data: JSON.stringify({
1434
- phase: "qa",
1435
- from_gate: artifact.gate,
1436
- to_gate: nextGate
1437
- })
1438
- });
1439
- }
1440
- class LiveQaArtifactEmitter {
1441
- worktreePath;
1442
- workItemId;
1443
- dispatch;
1444
- emit;
1445
- emittedBundle = false;
1446
- emittedGates = new Set();
1447
- timer = null;
1448
- pending = Promise.resolve();
1449
- constructor(worktreePath, workItemId, dispatch, emit) {
1450
- this.worktreePath = worktreePath;
1451
- this.workItemId = workItemId;
1452
- this.dispatch = dispatch;
1453
- this.emit = emit;
1454
- }
1455
- start() {
1456
- void this.pollQueued();
1457
- this.timer = setInterval(() => {
1458
- void this.pollQueued();
1459
- }, 250);
1460
- }
1461
- async stop() {
1462
- if (this.timer) {
1463
- clearInterval(this.timer);
1464
- this.timer = null;
1465
- }
1466
- await this.pollQueued();
1467
- }
1468
- hasEmitted() {
1469
- return this.emittedBundle;
1470
- }
1471
- pollQueued() {
1472
- this.pending = this.pending
1473
- .then(() => this.poll())
1474
- .catch(() => undefined);
1475
- return this.pending;
1476
- }
1477
- async poll() {
1478
- await this.emitAvailableGateEvents();
1479
- if (this.emittedBundle) {
1480
- return;
1481
- }
1482
- const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
1483
- if (!artifact) {
1484
- return;
1485
- }
1486
- enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
1487
- this.emittedBundle = true;
1488
- await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
1489
- await emitQaStructuredEvents(this.emit, artifact);
1490
- }
1491
- async emitAvailableGateEvents() {
1492
- const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
1493
- for (const gate of qaCompletionGateOrder) {
1494
- if (this.emittedGates.has(gate)) {
1495
- continue;
1496
- }
1497
- const artifact = await readQaGateArtifact(artifactRoot, gate);
1498
- if (!artifact) {
1499
- return;
1500
- }
1501
- this.emittedGates.add(gate);
1502
- await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
1503
- }
1504
- }
1505
- }
1506
- class LiveArchitectArtifactEmitter {
1507
- worktreePath;
1508
- workItemId;
1509
- emit;
1510
- emitted = false;
1511
- timer = null;
1512
- pending = Promise.resolve();
1513
- constructor(worktreePath, workItemId, emit) {
1514
- this.worktreePath = worktreePath;
1515
- this.workItemId = workItemId;
1516
- this.emit = emit;
1517
- }
1518
- start() {
1519
- void this.pollQueued();
1520
- this.timer = setInterval(() => {
1521
- void this.pollQueued();
1522
- }, 250);
1523
- }
1524
- async stop() {
1525
- if (this.timer) {
1526
- clearInterval(this.timer);
1527
- this.timer = null;
1528
- }
1529
- await this.pollQueued();
1530
- }
1531
- hasEmitted() {
1532
- return this.emitted;
1533
- }
1534
- pollQueued() {
1535
- this.pending = this.pending
1536
- .then(() => this.poll())
1537
- .catch(() => undefined);
1538
- return this.pending;
1539
- }
1540
- async poll() {
1541
- if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
1542
- return;
1543
- }
1544
- const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
1545
- if (!artifact) {
1546
- return;
1547
- }
1548
- this.emitted = true;
1549
- await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1550
- await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
1551
- }
1552
- }
1553
- async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
1554
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1555
- for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
1556
- try {
1557
- const stat = await fs.stat(path.join(artifactRoot, fileName));
1558
- if (!stat.isFile()) {
1559
- return false;
1560
- }
1561
- }
1562
- catch (error) {
1563
- if (isNodeError(error) && error.code === "ENOENT") {
1564
- return false;
1565
- }
1566
- throw error;
1567
- }
1568
- }
1569
- return true;
1570
- }
1571
- async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
1572
- const artifactRoot = artifactRootFor(worktreePath, workItemId);
1573
- const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
1574
- const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
1575
- const verdict = parseJsonLine(artifact.verdictJson) ?? {};
1576
- const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
1577
- const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
1578
- await emit({
1579
- role: "worker",
1580
- kind: "checkpoint",
1581
- content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
1582
- eventType: "architect_plan"
1583
- });
1584
- await emit({
1585
- role: "worker",
1586
- kind: "checkpoint",
1587
- content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
1588
- eventType: "architect_qa_seed"
1589
- });
1590
- await emit({
1591
- role: "hook",
1592
- kind: status === "pass" ? "checkpoint" : "error",
1593
- content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
1594
- eventType: "architect_mcp_complete"
1595
- });
1596
- }
1597
- async function readJsonObjectFile(filePath) {
1598
- const content = await fs.readFile(filePath, "utf8").catch(() => "");
1599
- return parseJsonLine(content) ?? {};
1600
- }
1601
- function arrayField(source, key) {
1602
- const value = source[key];
1603
- if (!Array.isArray(value)) {
1604
- return [];
1605
- }
1606
- return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
1607
- }
1608
- function stringArrayField(source, key) {
1609
- const value = source[key];
1610
- if (!Array.isArray(value)) {
1611
- return [];
1612
- }
1613
- return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
1614
- }
1615
- function summarizeQaObject(source) {
1616
- return clip(stringField(source, "title")
1617
- ?? stringField(source, "summary")
1618
- ?? stringField(source, "id")
1619
- ?? JSON.stringify(source), 500);
1620
- }
1621
- function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
1622
- if (ownerType && ownerId) {
1623
- const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
1624
- return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
1625
- }
1626
- return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
1627
- }
1628
- async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
1629
- const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
1630
- await emit({
1631
- role: "tool",
1632
- kind: "checkpoint",
1633
- content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
1634
- eventType: "completion_tool_validation_passed",
1635
- data: JSON.stringify({
1636
- phase: artifact.phase ?? "unknown",
1637
- status: artifact.status,
1638
- artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1639
- })
1640
- });
1641
- await emit({
1642
- role: "tool",
1643
- kind: "tool_result",
1644
- content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
1645
- eventType: "completion_tool_artifact_recorded",
1646
- data: JSON.stringify({
1647
- phase: artifact.phase ?? "unknown",
1648
- status: artifact.status,
1649
- artifact_relative_paths: [relativePath.split(path.sep).join("/")]
1650
- })
1651
- });
1652
- }
1653
- async function emitPhaseCompletionEvent(emit, artifact) {
1654
- const phase = completionPhaseFromArtifact(artifact);
1655
- await emit({
1656
- role: "assistant",
1657
- kind: "message",
1658
- content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
1659
- eventType: phaseCompleteEventType(phase)
1660
- });
1661
- }
1662
- async function emitPhaseGateEvents(emit, artifact) {
1663
- const phase = completionPhaseFromArtifact(artifact);
1664
- const status = (artifact.status ?? "").trim().toLowerCase() || "unknown";
1665
- await emit({
1666
- role: "hook",
1667
- kind: "checkpoint",
1668
- content: `phase_gate: ${phase} artifact accepted with status ${status}.`,
1669
- eventType: "phase_gate"
1670
- });
1671
- if (status !== "pass") {
1672
- return;
1673
- }
1674
- const progression = phase === "implementation"
1675
- ? "phase_progression: implementation -> self_review"
1676
- : phase === "self_review"
1677
- ? "phase_progression: self_review -> validation"
1678
- : phase === "debug_repro"
1679
- ? "phase_progression: debug_repro -> debug_root_cause"
1680
- : phase === "debug_root_cause"
1681
- ? "phase_progression: debug_root_cause -> debug_fix"
1682
- : phase === "debug_fix"
1683
- ? "phase_progression: debug_fix -> debug_regression"
1684
- : phase === "debug_regression"
1685
- ? "phase_progression: debug_regression -> QA ready"
1686
- : "phase_progression: validation -> QA ready";
1687
- await emit({
1688
- role: "hook",
1689
- kind: "checkpoint",
1690
- content: progression,
1691
- eventType: "phase_gate"
1692
- });
1693
- }
1694
- function completionPhaseFromArtifact(artifact) {
1695
- const phase = artifact.phase?.trim();
1696
- return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
1697
- || phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
1698
- ? phase
1699
- : "implementation";
1700
- }
1701
- class LiveCompletionArtifactEmitter {
1702
- worktreePath;
1703
- workItemId;
1704
- emit;
1705
- phases;
1706
- emitted = new Set();
1707
- timer = null;
1708
- pending = Promise.resolve();
1709
- constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
1710
- this.worktreePath = worktreePath;
1711
- this.workItemId = workItemId;
1712
- this.emit = emit;
1713
- if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
1714
- this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
1715
- }
1716
- else {
1717
- this.phases = developCycle
1718
- ? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
1719
- : [phase];
1720
- }
1721
- }
1722
- start() {
1723
- void this.pollQueued();
1724
- this.timer = setInterval(() => {
1725
- void this.pollQueued();
1726
- }, 250);
1727
- }
1728
- async stop() {
1729
- if (this.timer) {
1730
- clearInterval(this.timer);
1731
- this.timer = null;
1732
- }
1733
- await this.pollQueued();
1734
- }
1735
- hasEmitted(phase) {
1736
- return this.emitted.has(phase);
1737
- }
1738
- pollQueued() {
1739
- this.pending = this.pending
1740
- .then(() => this.poll())
1741
- .catch(() => undefined);
1742
- return this.pending;
1743
- }
1744
- async poll() {
1745
- for (const phase of this.phases) {
1746
- if (this.emitted.has(phase)) {
1747
- continue;
1748
- }
1749
- const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, phase);
1750
- if (!artifact) {
1751
- return;
1752
- }
1753
- this.emitted.add(phase);
1754
- await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
1755
- await emitPhaseCompletionEvent(this.emit, artifact);
1756
- await emitPhaseGateEvents(this.emit, artifact);
1757
- if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
1758
- return;
1759
- }
1760
- }
1761
- }
1762
- }
1763
- async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
1764
- if (!developCycle && !debugCycle) {
1765
- const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
1766
- if (!artifact) {
1767
- throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
1768
- }
1769
- return [artifact];
1770
- }
1771
- const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
1772
- ? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
1773
- : ["implementation", "self_review", "validation"];
1774
- const artifacts = [];
1775
- for (const expectedPhase of expectedPhases) {
1776
- const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
1777
- if (!artifact) {
1778
- if (artifacts.length === 0) {
1779
- throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
1780
- }
1781
- const previous = artifacts[artifacts.length - 1];
1782
- if ((previous.status ?? "").trim().toLowerCase() === "pass") {
1783
- throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
1784
- }
1785
- return artifacts;
1786
- }
1787
- artifacts.push(artifact);
1788
- if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
1789
- return artifacts;
1790
- }
1791
- }
1792
- return artifacts;
1793
- }
1794
- function providerProcessEnv(dispatch) {
1795
- const env = {
1796
- ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
1797
- ...providerCredentialEnv(dispatch)
1798
- };
1799
- return Object.keys(env).length > 0 ? env : undefined;
1800
- }
1801
- function providerCredentialEnv(dispatch) {
1802
- const secret = dispatch.apiKeySecretGrant?.secret;
1803
- if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
1804
- return {};
1805
- }
1806
- const provider = dispatch.execution.provider.trim().toLowerCase();
1807
- if (provider === "codex" || provider === "openai") {
1808
- return { OPENAI_API_KEY: secret };
1809
- }
1810
- return {};
1811
- }
1812
- function exactRedactionSecrets(dispatch) {
1813
- return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
1814
- }
1815
- async function emitProviderUsageEvent(emit, dispatch, outputState) {
1816
- const usage = outputState.usage;
1817
- if (hasUsage(usage)) {
1818
- await emit(buildProviderUsageEvent(dispatch, usage));
1819
- }
1820
- }
1821
- function estimatedDeterministicUsage() {
1822
- return addUsage(emptyUsage("estimated"), {
1823
- inputTokens: 1000,
1824
- outputTokens: 400,
1825
- source: "estimated"
1826
- });
1827
- }
1828
- export class StreamingProviderProcessRunner {
1829
- async run(request, handlers = {}, signal) {
1830
- const launch = await resolveProviderProcessLaunch(request.command, request.args);
1831
- return await new Promise((resolve, reject) => {
1832
- const child = spawn(launch.command, launch.args, {
1833
- cwd: request.cwd,
1834
- env: buildProviderChildEnvironment(request.env),
1835
- stdio: ["ignore", "pipe", "pipe"],
1836
- windowsHide: true
1837
- });
1838
- let stdout = "";
1839
- let stderr = "";
1840
- let settled = false;
1841
- const cleanup = () => {
1842
- signal?.removeEventListener("abort", abort);
1843
- };
1844
- const fail = (error) => {
1845
- if (settled) {
1846
- return;
1847
- }
1848
- settled = true;
1849
- cleanup();
1850
- reject(error);
1851
- };
1852
- const abort = () => {
1853
- try {
1854
- child.kill("SIGTERM");
1855
- }
1856
- catch {
1857
- // Best effort; close/error will settle the promise.
1858
- }
1859
- };
1860
- if (signal?.aborted) {
1861
- abort();
1862
- }
1863
- else {
1864
- signal?.addEventListener("abort", abort, { once: true });
1865
- }
1866
- child.on("error", fail);
1867
- const readers = [
1868
- readProcessLines(child.stdout, (line) => {
1869
- stdout += `${line}\n`;
1870
- return handlers.onStdoutLine?.(line);
1871
- }),
1872
- readProcessLines(child.stderr, (line) => {
1873
- stderr += `${line}\n`;
1874
- return handlers.onStderrLine?.(line);
1875
- })
1876
- ];
1877
- child.on("close", (code) => {
1878
- Promise.allSettled(readers).then((readerResults) => {
1879
- const rejected = readerResults.find((result) => result.status === "rejected");
1880
- if (rejected?.status === "rejected") {
1881
- fail(rejected.reason);
1882
- return;
1883
- }
1884
- if (settled) {
1885
- return;
1886
- }
1887
- settled = true;
1888
- cleanup();
1889
- resolve({
1890
- exitCode: code ?? 1,
1891
- stdout,
1892
- stderr
1893
- });
1894
- }).catch(fail);
1895
- });
1896
- });
1897
- }
1898
- }
1899
- async function resolveProviderProcessLaunch(command, args) {
1900
- if (process.platform !== "win32") {
1901
- return { command, args };
1902
- }
1903
- const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
1904
- if (cursorDirect) {
1905
- return cursorDirect;
1906
- }
1907
- const resolved = await resolveWindowsCommand(command);
1908
- return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
1909
- }
1910
- async function resolveWindowsCommand(command) {
1911
- if (path.isAbsolute(command)) {
1912
- return command;
1913
- }
1914
- try {
1915
- const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
1916
- return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
1917
- }
1918
- catch {
1919
- return null;
1920
- }
1921
- }
1922
- export function chooseWindowsCommandCandidate(candidates) {
1923
- const normalized = candidates
1924
- .map((candidate) => candidate.trim())
1925
- .filter((candidate) => candidate.length > 0);
1926
- if (normalized.length === 0) {
1927
- return null;
1928
- }
1929
- const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
1930
- for (const extension of preferredExtensions) {
1931
- const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
1932
- if (candidate) {
1933
- return candidate;
1934
- }
1935
- }
1936
- return normalized[0];
1937
- }
1938
- export function buildWindowsLaunchCommand(commandPath, args) {
1939
- const extension = path.extname(commandPath).toLowerCase();
1940
- if (extension === ".ps1") {
1941
- return {
1942
- command: powershellExecutable(),
1943
- args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", commandPath, ...args]
1944
- };
1945
- }
1946
- if (extension === ".cmd" || extension === ".bat") {
1947
- return {
1948
- command: process.env.ComSpec ?? "cmd.exe",
1949
- args: ["/d", "/s", "/c", windowsCommandLine(commandPath, args)]
1950
- };
1951
- }
1952
- return { command: commandPath, args };
1953
- }
1954
- function powershellExecutable() {
1955
- const systemRoot = process.env.SystemRoot;
1956
- return systemRoot
1957
- ? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
1958
- : "powershell.exe";
1959
- }
1960
- function windowsCommandLine(command, args) {
1961
- return [command, ...args].map(quoteWindowsCommandLineArg).join(" ");
1962
- }
1963
- function quoteWindowsCommandLineArg(value) {
1964
- if (value.length > 0 && !/[\s"]/.test(value)) {
1965
- return value;
1966
- }
1967
- return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
1968
- }
1969
- async function readProcessLines(stream, onLine) {
1970
- const reader = readline.createInterface({ input: stream });
1971
- try {
1972
- for await (const line of reader) {
1973
- await onLine(line);
1974
- }
1975
- }
1976
- finally {
1977
- reader.close();
1978
- }
1979
- }
1980
- function isFakeWorkerModel(model) {
1981
- return model.trim().toLowerCase() === fakeWorkerModel;
1982
- }
1983
- function sha256(content) {
1984
- return crypto.createHash("sha256").update(content).digest("hex");
1985
- }
1986
- function buildDraftSpec(dispatch) {
1987
- return `# Draft Generation Context
1988
-
1989
- Project: ${dispatch.draft?.projectName ?? dispatch.repo.name}
1990
- Repository: ${dispatch.draft?.repoName ?? dispatch.repo.name}
1991
- Draft kind: ${dispatch.draft?.kind ?? "draft"}
1992
-
1993
- ## User Prompt
1994
-
1995
- ${dispatch.draft?.userPrompt ?? ""}
1996
- `;
1997
- }
1998
- async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
1999
- const draftArtifactFiles = {
2000
- draft_intent: "draft.intent.json",
2001
- draft_repo_context: "draft.repo-context.json",
2002
- draft_graph_context: "draft.graph-context.json",
2003
- draft_product_scope: "draft.product-scope.json",
2004
- draft_work_order_plan: "draft.work-order-plan.json",
2005
- draft_critic: "draft.critic.json",
2006
- draft_proposal: "draft.proposal.json"
2007
- };
2008
- for (const gate of draftCompletionGateOrder) {
2009
- const actualPath = path.join(worktreePath, ".forge", "work-items", workItemId, "artifacts", draftArtifactFiles[gate]);
2010
- if (!await fileExists(actualPath)) {
2011
- continue;
2012
- }
2013
- const relativePath = path.relative(worktreePath, actualPath).split(path.sep).join("/");
2014
- await emit({
2015
- role: "tool",
2016
- kind: "tool_result",
2017
- content: `Forge Draft completion tool recorded ${gate} artifact ${relativePath}.`,
2018
- eventType: "completion_tool_artifact_recorded",
2019
- data: JSON.stringify({ phase: "draft", draft_gate: gate, artifact_relative_paths: [relativePath] })
2020
- });
2021
- await emit({
2022
- role: "hook",
2023
- kind: "checkpoint",
2024
- content: `phase_gate: ${gate} artifact accepted with status pass.`,
2025
- eventType: "phase_gate"
2026
- });
2027
- const next = draftCompletionGateOrder[draftCompletionGateOrder.indexOf(gate) + 1];
2028
- if (next) {
2029
- await emit({
2030
- role: "hook",
1367
+ const recoveryDispatch = {
1368
+ ...dispatch,
1369
+ session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
1370
+ };
1371
+ const recoveryPrompt = [
1372
+ "Your previous turn ended before Forge received the QA verdict, so the provider process exited.",
1373
+ "Background watchers, monitors and notifications from that turn did not survive and will never report back.",
1374
+ "Resume QA exactly where it stopped. Do not repeat gates you already recorded.",
1375
+ "Check each managed command with forge.get_managed_command, restart any that were interrupted,",
1376
+ "and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
1377
+ "Do not end your turn until you have called every remaining QA gate through forge.complete_qa_verdict.",
1378
+ "If a gate cannot get evidence, record it as blocked with the reason instead of ending the turn.",
1379
+ ].join(" ");
1380
+ for (let turn = 1; turn <= maxQaCompletionRecoveryTurns; turn += 1) {
1381
+ const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, context.runtimeEnvironment);
1382
+ const pipePromptToStdin = shouldPipePromptToStdin(recoveryDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(recoveryDispatch));
1383
+ const completionTools = await prepareCompletionToolRuntime({
1384
+ dispatch: recoveryDispatch,
1385
+ worktree,
1386
+ phase: "qa",
1387
+ runtimeEnvironment: context.runtimeEnvironment,
1388
+ hostLoadEnvironment: context.hostLoadEnvironment,
1389
+ });
1390
+ const command = buildProviderCliCommand(recoveryDispatch, {
1391
+ worktreePath: worktree.worktreePath,
1392
+ prompt: recoveryPrompt,
1393
+ promptFromStdin: pipePromptToStdin,
1394
+ completionTools,
1395
+ runtimeEnvironment: context.runtimeEnvironment,
1396
+ });
1397
+ await context.emit({
1398
+ role: "runner",
2031
1399
  kind: "checkpoint",
2032
- content: `phase_progression: ${gate} -> ${next}`,
2033
- eventType: "phase_gate"
1400
+ content: `QA ended without a verdict. Resuming ${dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} (turn ${turn}/${maxQaCompletionRecoveryTurns}) to finish the remaining QA gates.`,
1401
+ eventType: "completion_tool_recovery_started",
1402
+ data: JSON.stringify({ phase: "qa", providerThreadId, turn }),
2034
1403
  });
2035
- }
2036
- }
2037
- }
2038
- async function fileExists(filePath) {
2039
- try {
2040
- await fs.access(filePath);
2041
- return true;
2042
- }
2043
- catch {
2044
- return false;
2045
- }
2046
- }
2047
- function buildDraftPrompt(dispatch) {
2048
- const draft = dispatch.draft;
2049
- if (!draft) {
2050
- throw new Error("Draft prompt is missing.");
2051
- }
2052
- const draftArtifacts = dispatch.artifacts
2053
- .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
2054
- .map((artifact) => `## ${artifact.kind}: ${artifact.slug}\n${artifact.body.trim()}`)
2055
- .join("\n\n");
2056
- const artifactSection = draftArtifacts
2057
- ? `\n\n# Injected Draft command/skills/hooks\n\n${draftArtifacts}`
2058
- : "";
2059
- const projectSection = [
2060
- draft.projectName ? `Project: ${draft.projectName}` : null,
2061
- draft.repoName ? `Repository: ${draft.repoName}` : null
2062
- ].filter(Boolean).join("\n");
2063
- const scopedProjectSection = projectSection ? `\n\n# Selected project context\n\n${projectSection}` : "";
2064
- return `${draft.systemPrompt}${scopedProjectSection}${artifactSection}
2065
-
2066
- Draft kind: ${draft.kind}
2067
-
2068
- ${draft.userPrompt}
2069
-
2070
- ${completionPromptForDraftCycle("draft_intent")}
2071
-
2072
- Use the injected command/skills/hooks as lane instructions. You must call each Forge Draft MCP completion tool in order. Do not claim the Draft is complete until forge.complete_draft_proposal accepts the final draft_json.
2073
-
2074
- Do not modify source files.`;
2075
- }
2076
- function summarizeStderr(stderr) {
2077
- const trimmed = stderr.trim();
2078
- return trimmed ? `: ${clip(trimmed, 1000)}` : "";
2079
- }
2080
- async function waitForDraftProposalArtifact(worktreePath, workItemId, signal) {
2081
- while (!signal?.aborted) {
2082
- const artifact = await readCompletionArtifact(worktreePath, workItemId, "draft");
2083
- if (artifact) {
2084
- return artifact;
2085
- }
2086
- await new Promise((resolve) => setTimeout(resolve, 1000));
2087
- }
2088
- throw new Error("Draft proposal artifact wait was cancelled.");
2089
- }
2090
- function deterministicDraftPayload(dispatch) {
2091
- const kind = dispatch.draft?.kind ?? "work_item";
2092
- if (kind === "work_order_decomposition") {
2093
- return {
2094
- summary: "Fake decompose proposed a Feature DAG for the Work Order.",
2095
- blockedReason: "",
2096
- candidates: [
2097
- {
2098
- origin: "agent",
2099
- key: "intake-submission",
2100
- title: "Customer intake submission",
2101
- summary: "Collect, validate, de-duplicate, and confirm incoming customer requests.",
2102
- planningPacket: "# Customer intake submission\n\nPlan Stories for request form validation, attachment support, duplicate prevention, and submission confirmation.",
2103
- sortOrder: 10,
2104
- dependsOn: []
2105
- },
2106
- {
2107
- origin: "agent",
2108
- key: "review-queue",
2109
- title: "Reviewer triage queue",
2110
- summary: "Provide reviewer triage, assignment, notes, status transitions, and audit trail.",
2111
- planningPacket: "# Reviewer triage queue\n\nPlan Stories for queue filtering, assignment, reviewer notes, status changes, and immutable audit trail.",
2112
- sortOrder: 20,
2113
- dependsOn: ["intake-submission"]
2114
- }
2115
- ]
2116
- };
2117
- }
2118
- if (kind === "feature_decomposition") {
2119
- return {
2120
- summary: "Fake decompose proposed a Story DAG for the Feature.",
2121
- blockedReason: "",
2122
- candidates: [
2123
- {
2124
- origin: "agent",
2125
- key: "foundation",
2126
- title: "Build the feature foundation",
2127
- description: "Create the persistence, API, and UI shell needed by the feature.",
2128
- acceptanceCriteria: "Scenario: Foundation exists\nGiven the Feature is selected\nWhen the foundation is delivered\nThen downstream Stories can build on stable contracts",
2129
- points: 3,
2130
- sortOrder: 10,
2131
- dependsOn: []
2132
- },
2133
- {
2134
- origin: "agent",
2135
- key: "workflow-behavior",
2136
- title: "Implement the primary workflow behavior",
2137
- description: "Implement the main user-visible behavior for the feature after the foundation is ready.",
2138
- acceptanceCriteria: "Scenario: Workflow behavior works\nGiven the foundation Story is complete\nWhen the user performs the primary workflow\nThen the expected state change and feedback are visible",
2139
- points: 5,
2140
- sortOrder: 20,
2141
- dependsOn: ["foundation"]
2142
- },
2143
- {
2144
- origin: "agent",
2145
- key: "audit-and-tests",
2146
- title: "Add audit coverage and regression tests",
2147
- description: "Add audit/evidence behavior and automated regression coverage for the feature.",
2148
- acceptanceCriteria: "Scenario: Feature is verifiable\nGiven the workflow behavior is complete\nWhen validation runs\nThen audit evidence and tests cover the expected outcomes",
2149
- points: 3,
2150
- sortOrder: 30,
2151
- dependsOn: ["workflow-behavior"]
2152
- }
2153
- ]
2154
- };
2155
- }
2156
- if (kind === "work_order") {
2157
- return {
2158
- title: "Deterministic runner Work Order draft",
2159
- summary: "Forge Runner generated this deterministic Work Order draft.",
2160
- objective: "Validate runner-backed Draft generation.",
2161
- planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
2162
- decompositionContext: "Use this deterministic fixture only in bridge tests.",
2163
- assumptions: ["Forge Runner dispatch is available."],
2164
- warnings: []
2165
- };
2166
- }
2167
- if (kind === "story") {
2168
- return {
2169
- title: "Deterministic runner Story draft",
2170
- description: "Forge Runner generated this deterministic Story draft.",
2171
- acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
2172
- points: 3
2173
- };
2174
- }
2175
- return {
2176
- title: "Deterministic runner Work Item draft",
2177
- description: "Forge Runner generated this deterministic Work Item draft.",
2178
- acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
2179
- reproSteps: "Run Draft with a Forge Runner provider selected.",
2180
- systemInfo: "forge-bridge deterministic provider",
2181
- points: 1
2182
- };
2183
- }
2184
- export function formatProviderCliCommand(command) {
2185
- return [command.command, ...command.args].map(singleLine).join(" ");
2186
- }
2187
- function singleLine(value) {
2188
- return value.replace(/\s+/g, " ").trim();
2189
- }
2190
- export function buildProviderCliCommand(dispatch, run) {
2191
- const provider = dispatch.execution.provider.trim();
2192
- const normalizedProvider = provider.toLowerCase();
2193
- const model = dispatch.execution.model.trim();
2194
- if (normalizedProvider === "codex") {
2195
- const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
2196
- if (run?.completionTools) {
2197
- args.push(...codexMcpConfigArgs(run.completionTools));
2198
- }
2199
- args.push("--model", model);
2200
- if (run) {
2201
- args.push("--json");
2202
- if (run.worktreePath) {
2203
- args.push("--cd", run.worktreePath);
1404
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
1405
+ let result;
1406
+ try {
1407
+ result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
1408
+ command: command.command,
1409
+ args: command.args,
1410
+ cwd: worktree.worktreePath,
1411
+ env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
1412
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1413
+ stdin: pipePromptToStdin ? providerPrompt : undefined,
1414
+ }, {
1415
+ onStdoutLine: async (line) => await toolHeartbeat.consume(line),
1416
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1417
+ onGenerationStart: toolHeartbeat.startGeneration,
1418
+ }, context.signal);
2204
1419
  }
2205
- if (run.skipGitRepoCheck) {
2206
- args.push("--skip-git-repo-check");
1420
+ finally {
1421
+ toolHeartbeat.stop();
1422
+ await cleanupCompletionTools(completionTools, context.emit);
1423
+ }
1424
+ options.lastRun.result = result;
1425
+ if (result.exitCode !== 0)
1426
+ throw providerCliExitFailure(command.command, result);
1427
+ const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
1428
+ if (artifact || await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa")) {
1429
+ await context.emit({
1430
+ role: "runner",
1431
+ kind: "checkpoint",
1432
+ content: `Forge resumed the QA thread and received its completion record on recovery turn ${turn}.`,
1433
+ eventType: "completion_tool_recovery_completed",
1434
+ data: JSON.stringify({ phase: "qa", providerThreadId, turn }),
1435
+ });
1436
+ return artifact;
2207
1437
  }
2208
- args.push(run.prompt ?? "");
2209
1438
  }
2210
- return { command: "codex", args };
1439
+ await context.emit({
1440
+ role: "runner",
1441
+ kind: "error",
1442
+ content: `The resumed QA thread still did not call the Forge QA completion tool after ${maxQaCompletionRecoveryTurns} recovery turns.`,
1443
+ eventType: "completion_tool_recovery_exhausted",
1444
+ data: JSON.stringify({ phase: "qa", providerThreadId }),
1445
+ });
1446
+ return null;
2211
1447
  }
2212
- if (normalizedProvider === "cursor") {
2213
- const args = ["--print", "--output-format", "stream-json", "--model", model];
2214
- if (run?.worktreePath) {
2215
- args.push("--workspace", run.worktreePath);
1448
+ async recoverMissingCommentRepairCompletion(options) {
1449
+ const { context, repairEnvironment, outputState, preparedHeadSha } = options;
1450
+ const { dispatch, worktree } = context;
1451
+ const normalizedProvider = dispatch.execution.provider.trim().toLowerCase();
1452
+ if (normalizedProvider !== "codex" && normalizedProvider !== "cursor" && normalizedProvider !== "claude") {
1453
+ await context.emit({
1454
+ role: "runner",
1455
+ kind: "error",
1456
+ content: `Forge could not recover the missing comment-repair completion record because provider '${dispatch.execution.provider}' has no declared thread-resume contract. The dirty worktree remains preserved.`,
1457
+ eventType: "completion_tool_recovery_unavailable",
1458
+ data: JSON.stringify({
1459
+ phase: "comment_repair",
1460
+ provider: normalizedProvider,
1461
+ reason: "thread_resume_unsupported",
1462
+ }),
1463
+ });
1464
+ return null;
2216
1465
  }
2217
- if (run?.prompt) {
2218
- args.push("--yolo", "--approve-mcps", "--trust", run.prompt);
1466
+ const providerThreadId = outputState.providerThreadId?.trim();
1467
+ if (!providerThreadId) {
1468
+ await context.emit({
1469
+ role: "runner",
1470
+ kind: "error",
1471
+ content: "Forge could not recover the missing comment-repair completion record because the provider did not report a resumable thread id. The dirty worktree remains preserved.",
1472
+ eventType: "completion_tool_recovery_unavailable",
1473
+ });
1474
+ return null;
2219
1475
  }
2220
- return { command: "cursor-agent", args };
2221
- }
2222
- const args = ["--model", model];
2223
- if (run?.prompt) {
2224
- args.push(run.prompt);
2225
- }
2226
- return { command: provider, args };
2227
- }
2228
- export function codexSandboxModeForPlatform(platform = process.platform) {
2229
- return platform === "win32" ? "danger-full-access" : "workspace-write";
2230
- }
2231
- function buildArchitectPrompt(dispatch) {
2232
- return `You are Forge's Architect lane running locally in a prepared git worktree.
2233
-
2234
- Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
2235
-
2236
- Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
2237
- Read injected Forge context under .forge plus the repository shape, then produce a repo-grounded implementation DAG with task tests, phase gates, final QA coverage, and a pending-approval spec.
2238
- Implementation DAG tasks are Develop child tasks only: include focused repo/product implementation changes. Do not create child Develop tasks for parent-story QA, sign-off, materialized child inventory, child-count evidence, parent plan artifact checks, or final integrated acceptance proof; put those checks in qa_plan.final_qa.
2239
- ${architectRevisionInstruction(dispatch)}
2240
- Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
2241
-
2242
- ${completionPromptForPhase("architect")}
2243
-
2244
- Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
2245
- }
2246
- function architectRevisionInstruction(dispatch) {
2247
- if (!dispatch.architectRevision) {
2248
- return "";
2249
- }
2250
- return `
2251
- Architect revision context:
2252
- - Previous plan id: ${dispatch.architectRevision.priorPlanId}
2253
- - Previous content hash: ${dispatch.architectRevision.priorContentHash}
2254
- - Reviewer feedback: ${dispatch.architectRevision.feedback}
2255
- Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
2256
- }
2257
- function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2258
- return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
2259
-
2260
- Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
2261
- ${phaseWorkInstruction(phase)}
2262
- ${qaReworkImplementationInstruction(dispatch)}
2263
- Use the repository's existing conventions. Run relevant tests when practical.
2264
- Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
2265
- Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
2266
-
2267
- ${completionPromptForPhase(phase)}
2268
-
2269
- Finish with a concise summary of changed files and verification after calling the completion tool.`;
2270
- }
2271
- function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2272
- return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
2273
-
2274
- Read .forge/work-items/${dispatch.workItem.id}/spec.md, implement the work item, self-review the diff, then validate it in this same provider session.
2275
- Start in the ${phase.replace(/_/g, " ")} phase. Do not stop after implementation if it passes; continue through self-review and validation using the next instruction returned by each completion tool.
2276
- ${qaReworkImplementationInstruction(dispatch)}
2277
- Use the repository's existing conventions. Run relevant tests when practical.
2278
- Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
2279
- Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
2280
-
2281
- ${completionPromptForDevelopCycle(phase)}
2282
-
2283
- Finish with a concise summary of changed files and verification after the validation completion tool has accepted the work, or after the current phase tool records a non-pass blocker.`;
2284
- }
2285
- function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
2286
- return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
2287
-
2288
- Read .forge/work-items/${dispatch.workItem.id}/spec.md, reproduce or characterize the bug, isolate root cause, apply the smallest safe fix, then prove the regression in this same provider session.
2289
- Start in the ${phase.replace(/_/g, " ")} gate. Do not stop after a passing Debug gate; continue through the next Debug MCP instruction returned by the tool server until debug_regression is accepted or the current gate records a non-pass blocker.
2290
- ${debugQaReworkInstruction(dispatch)}
2291
- Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
2292
- Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
2293
- Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
2294
-
2295
- ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
2296
-
2297
- Finish with a concise summary of changed files and verification after the debug_regression completion tool has accepted the work, or after the current Debug gate tool records a non-pass blocker.`;
2298
- }
2299
- function qaReworkImplementationInstruction(dispatch) {
2300
- if (!dispatch.qaRework) {
2301
- return "";
2302
- }
2303
- return `
2304
- QA rework context:
2305
- - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2306
- - Rework packet: ${dispatch.qaRework.packetPath}
2307
- - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2308
- Read the packet JSON and fix or explicitly dispute each listed finding. The implementation completion artifact must include resolved_findings entries for every required QA ID with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.
2309
- Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2310
- }
2311
- function debugQaReworkInstruction(dispatch) {
2312
- if (!dispatch.qaRework) {
2313
- return "";
2314
- }
2315
- return `
2316
- QA rework context for Debug:
2317
- - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2318
- - Rework packet: ${dispatch.qaRework.packetPath}
2319
- - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2320
- Read the packet JSON, reproduce or characterize each listed finding, fix or explicitly dispute it, and include resolved_findings entries for every required QA ID in forge.complete_debug_fix with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.
2321
- Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
2322
- }
2323
- function qaReworkRetestInstruction(dispatch) {
2324
- if (!dispatch.qaRework) {
2325
- return "";
2326
- }
2327
- return `
2328
- QA retest context:
2329
- - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
2330
- - Rework packet: ${dispatch.qaRework.packetPath}
2331
- - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
2332
- Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
2333
- }
2334
- function phaseWorkInstruction(phase) {
2335
- if (phase === "self_review") {
2336
- return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
2337
- }
2338
- if (phase === "validation") {
2339
- return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
2340
- }
2341
- return "Implement the work item and keep the change focused.";
2342
- }
2343
- function qaBrowserInstruction(dispatch) {
2344
- const qaBrowser = dispatch.qaBrowser;
2345
- if (!qaBrowser) {
2346
- return "Browser/app launch context: not provided by Forge.";
2347
- }
2348
- const launchTarget = qaBrowser.launchTarget;
2349
- if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
2350
- return `Browser/app launch context:\n- UI/browser QA is required for this item.\n- No app launch target was provided.\n- Return blocked with blocker_reason: missing_app_launch_target instead of pretending browser testing occurred.\n- Artifact sidecars path when available: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
2351
- }
2352
- if (!launchTarget) {
2353
- return `Browser/app launch context:\n- UI/browser QA is not required by Forge heuristics for this item.\n- If you determine browser testing is needed, return blocked with blocker_reason: missing_app_launch_target unless you can safely identify a launch target from the repo.\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
2354
- }
2355
- const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
2356
- return `Browser/app launch context:\n- Browser QA required: ${qaBrowser.required ? "yes" : "no, unless the diff/AC requires it"}\n- URL: ${launchTarget.url || "not specified"}\n- Ready URL: ${launchTarget.ready_url || "not specified"}\n- Launch command: ${launchTarget.command || "not specified"}\n- Working directory: ${launchTarget.working_directory || "repo root"}\n- Routes to cover: ${routes}\n- Notes: ${launchTarget.notes || "none"}\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
2357
- }
2358
- function storyQaInstruction(dispatch) {
2359
- const storyQa = dispatch.storyQa;
2360
- if (!storyQa) {
2361
- return "";
2362
- }
2363
- const childLines = storyQa.childTasks.map((child) => {
2364
- const dependencies = child.dependencyWorkItemIds.length > 0
2365
- ? child.dependencyWorkItemIds.join(", ")
2366
- : "none";
2367
- const validation = child.validationArtifact
2368
- ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
2369
- : "missing";
2370
- const childQa = child.qaArtifact
2371
- ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
2372
- : "not present";
2373
- return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
2374
- }).join("\n");
2375
- const finalQa = storyQa.finalQaChecks.length > 0
2376
- ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
2377
- : "- No final QA checks were provided in qa.plan.final_qa.";
2378
- return `Story QA integration context:
2379
- - Story work item: ${storyQa.storyWorkItemId}
2380
- - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
2381
- - Story worktree: ${storyQa.worktreeKey}
2382
- - Branch: ${storyQa.branch}
2383
- - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
2384
- - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
2385
- Materialized child tasks and evidence:
2386
- ${childLines || "- No child tasks were provided."}
2387
- Architect final QA checks:
2388
- ${finalQa}
2389
- This is parent Story QA: inspect the integrated Story result, all current-plan child specs/evidence, and the final worktree state. Do not treat the final child task as separately signed off.`;
2390
- }
2391
- function buildQaPrompt(dispatch, laneSpec) {
2392
- return `You are Forge's QA lane running locally in a prepared git worktree.
2393
-
2394
- First read and follow the injected QA lane command at .forge/work-items/${dispatch.workItem.id}/spec.md. It defines the required gated QA skill workflow for this run.
2395
-
2396
- Injected QA lane command and work item spec:
2397
- ${laneSpec}
2398
-
2399
- ---
2400
-
2401
- Work item: ${dispatch.workItem.id}
2402
- Title: ${dispatch.workItem.title}
2403
- Description:
2404
- ${dispatch.workItem.description || "Not provided."}
2405
-
2406
- Acceptance criteria:
2407
- ${dispatch.workItem.acceptanceCriteria || "Not specified."}
2408
-
2409
- Repro steps / scenario:
2410
- ${dispatch.workItem.reproSteps || "Not provided."}
2411
-
2412
- System info / environment notes:
2413
- ${dispatch.workItem.systemInfo || "Not provided."}
2414
-
2415
- ${storyQaInstruction(dispatch)}
2416
- Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
2417
- ${qaBrowserInstruction(dispatch)}
2418
- ${qaReworkRetestInstruction(dispatch)}
2419
- QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
2420
- Record concrete evidence. For UI/browser work, include browser_checks with URLs/routes, actions, observed results, screenshots/traces when available, console errors, failed network requests, and responsive checks. Store browser sidecars under .forge/work-items/${dispatch.workItem.id}/artifacts/qa/.
2421
- Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
2422
- Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
2423
-
2424
- ${completionPromptForQaCycle()}
2425
-
2426
- Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
2427
- }
2428
- function buildConflictResolvePrompt(dispatch, branchName) {
2429
- const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
2430
- return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
2431
-
2432
- The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
2433
- Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
2434
- Keep the original work item intent intact:
2435
- - Work item: ${dispatch.workItem.id}
2436
- - Title: ${dispatch.workItem.title}
2437
- - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
2438
-
2439
- Finish with a concise summary of the conflicts resolved and verification performed.`;
2440
- }
2441
- function buildPullRequestCommentsPrompt(dispatch, branchName) {
2442
- const pr = dispatch.pullRequest;
2443
- const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
2444
- const prLocator = pr
2445
- ? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
2446
- : "the open pull request for this work item";
2447
- return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
2448
-
2449
- The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
2450
- PR context:
2451
- - Provider: ${pr?.provider || "not provided"}
2452
- - Source branch: ${pr?.sourceBranch || branchName}
2453
- - Target branch: ${targetBranch}
2454
- - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
2455
-
2456
- Use the PR URL, local git metadata, and available GitHub tooling/auth to inspect unresolved review threads. Make focused code or test changes that answer the feedback, commit the changes, and push ${branchName} to origin.
2457
- After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
2458
- If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
2459
- Keep the original work item intent intact:
2460
- - Work item: ${dispatch.workItem.id}
2461
- - Title: ${dispatch.workItem.title}
2462
- - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
2463
-
2464
- Finish with a concise summary of comments addressed and verification performed.`;
2465
- }
2466
- function isPullRequestCommentsDispatch(dispatch) {
2467
- return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
2468
- }
2469
- async function cleanupCompletionTools(completionTools, emit) {
2470
- try {
2471
- await completionTools.cleanup();
2472
- }
2473
- catch (error) {
2474
- await emit({
1476
+ const recoveryDispatch = {
1477
+ ...dispatch,
1478
+ session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
1479
+ };
1480
+ const recoveryPrompt = [
1481
+ "Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
1482
+ "Background watchers, monitors and notifications from that turn did not survive and will never report back,",
1483
+ "and Forge stopped any managed command that process was still running; its receipt reports that.",
1484
+ "Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
1485
+ "Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
1486
+ "Check each managed command with forge.get_managed_command, restart any that were interrupted,",
1487
+ "and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
1488
+ "Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1489
+ "Do not commit or push; Forge owns publication after the completion gate succeeds.",
1490
+ ].join(" ");
1491
+ const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
1492
+ const pipePromptToStdin = shouldPipePromptToStdin(recoveryDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(recoveryDispatch));
1493
+ const completionTools = await prepareCompletionToolRuntime({
1494
+ dispatch: recoveryDispatch,
1495
+ worktree,
1496
+ phase: "comment_repair",
1497
+ runtimeEnvironment: repairEnvironment,
1498
+ hostLoadEnvironment: context.hostLoadEnvironment,
1499
+ });
1500
+ const command = buildProviderCliCommand(recoveryDispatch, {
1501
+ worktreePath: worktree.worktreePath,
1502
+ prompt: recoveryPrompt,
1503
+ promptFromStdin: pipePromptToStdin,
1504
+ completionTools,
1505
+ runtimeEnvironment: repairEnvironment,
1506
+ });
1507
+ await context.emit({
2475
1508
  role: "runner",
2476
1509
  kind: "checkpoint",
2477
- content: `Forge completion tool cleanup failed and was ignored: ${clip(messageFromError(error), 600)}`,
2478
- eventType: "completion_tools_cleanup_failed"
2479
- }).catch(() => undefined);
2480
- }
2481
- }
2482
- async function commitWorktreeChanges(git, worktreePath, workItemId) {
2483
- await git.run(worktreePath, ["add", "-A"]);
2484
- await git.run(worktreePath, ["reset", "--", ".forge"]).catch(() => "");
2485
- const changedFiles = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
2486
- .split(/\r?\n/)
2487
- .map((line) => line.trim())
2488
- .filter(Boolean);
2489
- if (changedFiles.length > 0) {
2490
- await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
2491
- }
2492
- else {
2493
- await git.run(worktreePath, ["commit", "--allow-empty", "-m", `provider cli completed for ${workItemId.slice(0, 8)}`]);
2494
- }
2495
- const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
2496
- return { commitSha, changedFiles };
2497
- }
2498
- function messageFromError(error) {
2499
- return error instanceof Error ? error.message : String(error);
2500
- }
2501
- function clip(value, maxLength) {
2502
- if (value.length <= maxLength) {
2503
- return value;
2504
- }
2505
- return `${value.slice(0, maxLength)}...`;
2506
- }
2507
- function createProviderOutputState(provider) {
2508
- return provider.trim().toLowerCase() === "cursor"
2509
- ? new CursorStreamJsonState()
2510
- : new CodexJsonState();
2511
- }
2512
- class CursorStreamJsonState {
2513
- sessionId = null;
2514
- finalMessage = null;
2515
- emittedSession = false;
2516
- accumulatedUsage = null;
2517
- get sessionLabel() {
2518
- return this.sessionId ? `session ${this.sessionId}` : null;
2519
- }
2520
- get usage() {
2521
- return this.accumulatedUsage;
2522
- }
2523
- consume(line) {
2524
- const event = parseJsonLine(line);
2525
- if (!event) {
2526
- return [];
2527
- }
2528
- const type = stringField(event, "type");
2529
- if (type === "system" && stringField(event, "subtype") === "init") {
2530
- this.sessionId = stringField(event, "session_id");
2531
- if (this.sessionId && !this.emittedSession) {
2532
- this.emittedSession = true;
2533
- return [{
1510
+ content: `Resuming ${dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} once to record the missing comment-repair completion artifact without repeating implementation work.`,
1511
+ eventType: "completion_tool_recovery_started",
1512
+ data: JSON.stringify({ phase: "comment_repair", providerThreadId }),
1513
+ });
1514
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
1515
+ let result;
1516
+ let providerStarted = false;
1517
+ try {
1518
+ result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
1519
+ command: command.command,
1520
+ args: command.args,
1521
+ cwd: worktree.worktreePath,
1522
+ env: providerProcessEnv(recoveryDispatch, repairEnvironment),
1523
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1524
+ stdin: pipePromptToStdin ? providerPrompt : undefined,
1525
+ }, {
1526
+ onStarted: async () => {
1527
+ providerStarted = true;
1528
+ await context.emit({
2534
1529
  role: "runner",
2535
1530
  kind: "checkpoint",
2536
- content: `Cursor session started: ${this.sessionId}.`,
2537
- eventType: "provider_thread_started"
2538
- }];
2539
- }
2540
- }
2541
- if (type === "assistant") {
2542
- const text = assistantMessageText(event);
2543
- if (text) {
2544
- this.finalMessage = text;
2545
- return [{
2546
- role: "assistant",
2547
- kind: "message",
2548
- content: clip(text, 4000),
2549
- eventType: "provider_message"
2550
- }];
2551
- }
1531
+ content: "Provider completion-tool recovery turn is supervised and ready.",
1532
+ eventType: "provider_cli_started",
1533
+ });
1534
+ },
1535
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1536
+ onGenerationStart: toolHeartbeat.startGeneration,
1537
+ onStdoutLine: async (line) => {
1538
+ await toolHeartbeat.consume(line);
1539
+ },
1540
+ }, context.signal);
2552
1541
  }
2553
- if (type === "tool_call") {
2554
- const subtype = stringField(event, "subtype");
2555
- const toolCall = objectField(event, "tool_call");
2556
- if (subtype === "started") {
2557
- const summary = formatCursorToolCallStarted(toolCall);
2558
- if (summary) {
2559
- return [{
2560
- role: "worker",
2561
- kind: "checkpoint",
2562
- content: summary,
2563
- eventType: "provider_tool_call"
2564
- }];
2565
- }
2566
- }
2567
- if (subtype === "completed") {
2568
- const completed = formatCursorToolCallCompleted(toolCall);
2569
- if (completed) {
2570
- return [{
2571
- role: "worker",
2572
- kind: completed.kind,
2573
- content: completed.content,
2574
- eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
2575
- }];
1542
+ finally {
1543
+ toolHeartbeat.stop();
1544
+ try {
1545
+ if (providerStarted) {
1546
+ await context.emit({
1547
+ role: "runner",
1548
+ kind: "checkpoint",
1549
+ content: "Provider completion-tool recovery turn exited.",
1550
+ eventType: "provider_cli_completed",
1551
+ });
2576
1552
  }
2577
1553
  }
2578
- }
2579
- if (type === "result" && stringField(event, "subtype") === "success") {
2580
- const result = stringField(event, "result");
2581
- if (result) {
2582
- this.finalMessage = result;
1554
+ finally {
1555
+ await cleanupCompletionTools(completionTools, context.emit);
2583
1556
  }
2584
- this.accumulateUsage(event);
2585
- }
2586
- if (type === "error" || (type === "result" && event.is_error === true)) {
2587
- return [{
2588
- role: "runner",
2589
- kind: "error",
2590
- content: clip(line.trim(), 1000),
2591
- eventType: "provider_cli_error"
2592
- }];
2593
1557
  }
2594
- return [];
2595
- }
2596
- accumulateUsage(event) {
2597
- const usage = objectField(event, "usage");
2598
- const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
2599
- if (Object.keys(usage).length === 0 && durationMs === 0) {
2600
- return;
1558
+ options.lastRun.result = result;
1559
+ if (result.exitCode !== 0)
1560
+ throw providerCliExitFailure(command.command, result);
1561
+ const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
1562
+ if (postRecoveryHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
1563
+ throw new Error(`provider_publication_boundary_violation: completion-tool recovery changed HEAD from ${preparedHeadSha} to ${postRecoveryHeadSha}; Forge requires provider changes to remain uncommitted and unpushed until validation passes.`);
2601
1564
  }
2602
- this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
2603
- inputTokens: readUsageNumber(usage, "inputTokens"),
2604
- outputTokens: readUsageNumber(usage, "outputTokens"),
2605
- cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
2606
- cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
2607
- providerDurationMs: durationMs > 0 ? durationMs : null,
2608
- source: "provider_reported"
1565
+ const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
1566
+ await context.emit({
1567
+ role: "runner",
1568
+ kind: artifact ? "checkpoint" : "error",
1569
+ content: artifact
1570
+ ? "Forge recovered the missing comment-repair completion artifact from the same provider thread."
1571
+ : "The resumed provider thread still did not call forge.complete_comment_repair. The dirty worktree remains preserved and unpublished.",
1572
+ eventType: artifact ? "completion_tool_recovery_completed" : "completion_tool_recovery_exhausted",
1573
+ data: JSON.stringify({ phase: "comment_repair", providerThreadId }),
1574
+ });
1575
+ return artifact;
1576
+ }
1577
+ async validatePrePublicationWithRecovery(options) {
1578
+ const processRunner = recoveringProviderProcessRunner(options.context.processRunner ?? this.processRunner);
1579
+ await validatePrePublicationWithRepair(options, {
1580
+ validator: this.prePublicationValidator,
1581
+ defaultProcessRunner: this.processRunner,
1582
+ maxRepairTurns: this.prePublicationRepairTurns,
1583
+ runRepairTurn: async (turn) => await this.runPrePublicationRepairTurn(options, processRunner, turn),
2609
1584
  });
2610
1585
  }
2611
- }
2612
- function formatCursorToolCallStarted(toolCall) {
2613
- const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
2614
- const readPath = stringField(readArgs, "path");
2615
- if (readPath) {
2616
- return `Reading ${readPath}`;
2617
- }
2618
- const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
2619
- const writePath = stringField(writeArgs, "path");
2620
- if (writePath) {
2621
- return `Writing ${writePath}`;
2622
- }
2623
- const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
2624
- const command = stringField(shellArgs, "command");
2625
- if (command) {
2626
- return `Shell command started: ${clip(command, 500)}`;
2627
- }
2628
- const fn = objectField(toolCall, "function");
2629
- const name = stringField(fn, "name");
2630
- if (name) {
2631
- return `Tool call started: ${name}`;
2632
- }
2633
- return null;
2634
- }
2635
- function formatCursorToolCallCompleted(toolCall) {
2636
- const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
2637
- const writePath = stringField(writeArgs, "path");
2638
- const writeResult = objectField(objectField(objectField(toolCall, "writeToolCall"), "result"), "success");
2639
- const writtenPath = stringField(writeResult, "path") ?? writePath;
2640
- if (writtenPath) {
2641
- return {
2642
- kind: "file_edit",
2643
- content: `Wrote ${writtenPath}`
2644
- };
2645
- }
2646
- const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
2647
- const readPath = stringField(readArgs, "path");
2648
- if (readPath) {
2649
- const readResult = objectField(objectField(objectField(toolCall, "readToolCall"), "result"), "success");
2650
- const totalLines = readResult.totalLines;
2651
- const lineSummary = typeof totalLines === "number" ? ` (${totalLines} lines)` : "";
2652
- return {
2653
- kind: "checkpoint",
2654
- content: `Read ${readPath}${lineSummary}`
2655
- };
2656
- }
2657
- const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
2658
- const command = stringField(shellArgs, "command");
2659
- if (command) {
2660
- return {
2661
- kind: "checkpoint",
2662
- content: `Shell command completed: ${clip(command, 500)}`
2663
- };
2664
- }
2665
- const fn = objectField(toolCall, "function");
2666
- const name = stringField(fn, "name");
2667
- if (name) {
2668
- return {
2669
- kind: "checkpoint",
2670
- content: `Tool call completed: ${name}`
2671
- };
2672
- }
2673
- return null;
2674
- }
2675
- function assistantMessageText(event) {
2676
- const message = objectField(event, "message");
2677
- const content = message.content;
2678
- if (!Array.isArray(content)) {
2679
- return null;
2680
- }
2681
- const parts = content
2682
- .map((entry) => {
2683
- if (!entry || typeof entry !== "object") {
2684
- return null;
2685
- }
2686
- const block = entry;
2687
- return stringField(block, "text");
2688
- })
2689
- .filter((text) => Boolean(text));
2690
- if (parts.length === 0) {
2691
- return null;
2692
- }
2693
- return parts.join("");
2694
- }
2695
- function parseJsonLine(line) {
2696
- const trimmed = line.trim();
2697
- if (!trimmed.startsWith("{")) {
2698
- return null;
2699
- }
2700
- let parsed;
2701
- try {
2702
- parsed = JSON.parse(trimmed);
2703
- }
2704
- catch {
2705
- return null;
2706
- }
2707
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
2708
- ? parsed
2709
- : null;
2710
- }
2711
- class CodexJsonState {
2712
- threadId = null;
2713
- finalMessage = null;
2714
- emittedThread = false;
2715
- accumulatedUsage = null;
2716
- get sessionLabel() {
2717
- return this.threadId ? `thread ${this.threadId}` : null;
2718
- }
2719
- get usage() {
2720
- return this.accumulatedUsage;
2721
- }
2722
- consume(line) {
2723
- const event = parseJsonLine(line);
2724
- if (!event) {
2725
- return [];
2726
- }
2727
- const type = stringField(event, "type") ?? "";
2728
- if (type === "thread.started") {
2729
- this.threadId = stringField(event, "thread_id");
2730
- if (this.threadId && !this.emittedThread) {
2731
- this.emittedThread = true;
2732
- return [{
1586
+ /**
1587
+ * Resumes the provider thread for one in-place repair turn; the turn must leave HEAD where it was.
1588
+ * The turn launches with its own Forge MCP server (prepareRepairTurnLaunch), removed when it exits.
1589
+ */
1590
+ async runPrePublicationRepairTurn(options, processRunner, turn) {
1591
+ const { context, outputState, preparedHeadSha } = options;
1592
+ const { worktree } = context;
1593
+ const { repairTurn: nextRepairTurn, maxRepairTurns, environment } = turn;
1594
+ const { repairDispatch, providerPrompt, pipePromptToStdin, completionTools, command } = await prepareRepairTurnLaunch(context, turn);
1595
+ const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
1596
+ let result;
1597
+ let providerStarted = false;
1598
+ try {
1599
+ result = await processRunner.run({
1600
+ command: command.command,
1601
+ args: command.args,
1602
+ cwd: worktree.worktreePath,
1603
+ env: environment,
1604
+ resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
1605
+ stdin: pipePromptToStdin ? providerPrompt : undefined,
1606
+ }, {
1607
+ onStarted: async () => {
1608
+ await context.emit({
2733
1609
  role: "runner",
2734
1610
  kind: "checkpoint",
2735
- content: `Codex thread started: ${this.threadId}.`,
2736
- eventType: "provider_thread_started"
2737
- }];
2738
- }
2739
- }
2740
- if (type === "turn.completed") {
2741
- this.accumulateUsage(event);
2742
- return [{
2743
- role: "runner",
2744
- kind: "checkpoint",
2745
- content: "Codex turn completed.",
2746
- eventType: "provider_turn_completed"
2747
- }];
2748
- }
2749
- if (type === "turn.failed" || type === "error") {
2750
- return [{
2751
- role: "runner",
2752
- kind: "error",
2753
- content: clip(line.trim(), 1000),
2754
- eventType: "provider_cli_error"
2755
- }];
1611
+ content: `Provider pre-publication repair turn ${nextRepairTurn}/${maxRepairTurns} is supervised and ready.`,
1612
+ eventType: "provider_cli_started",
1613
+ });
1614
+ providerStarted = true;
1615
+ },
1616
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1617
+ onGenerationStart: toolHeartbeat.startGeneration,
1618
+ onStdoutLine: async (line) => {
1619
+ await toolHeartbeat.consume(line);
1620
+ },
1621
+ }, context.signal);
2756
1622
  }
2757
- if (type === "item.completed" || type === "item.updated") {
2758
- const item = objectField(event, "item");
2759
- const itemType = stringField(item, "type");
2760
- if (itemType === "agent_message") {
2761
- const text = stringField(item, "text");
2762
- if (text) {
2763
- this.finalMessage = text;
2764
- return [{
2765
- role: "assistant",
2766
- kind: "message",
2767
- content: clip(text, 4000),
2768
- eventType: "provider_message"
2769
- }];
1623
+ finally {
1624
+ toolHeartbeat.stop();
1625
+ try {
1626
+ if (providerStarted) {
1627
+ await context.emit({
1628
+ role: "runner",
1629
+ kind: "checkpoint",
1630
+ content: `Provider pre-publication repair turn ${nextRepairTurn}/${maxRepairTurns} exited.`,
1631
+ eventType: "provider_cli_completed",
1632
+ });
2770
1633
  }
2771
1634
  }
2772
- if (itemType === "command_execution") {
2773
- const command = stringField(item, "command");
2774
- const status = stringField(item, "status");
2775
- if (command) {
2776
- return [{
2777
- role: "worker",
2778
- kind: "checkpoint",
2779
- content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
2780
- eventType: "provider_command"
2781
- }];
2782
- }
1635
+ finally {
1636
+ await cleanupCompletionTools(completionTools, context.emit);
2783
1637
  }
2784
1638
  }
2785
- const mcpEvents = formatCodexMcpToolCallEvents(type, event);
2786
- if (mcpEvents.length > 0) {
2787
- return mcpEvents;
2788
- }
2789
- return [];
2790
- }
2791
- accumulateUsage(event) {
2792
- const usage = objectField(event, "usage");
2793
- if (Object.keys(usage).length === 0) {
2794
- return;
2795
- }
2796
- this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
2797
- inputTokens: readUsageNumber(usage, "input_tokens"),
2798
- outputTokens: readUsageNumber(usage, "output_tokens"),
2799
- cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
2800
- reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
2801
- source: "provider_reported"
2802
- });
2803
- }
2804
- }
2805
- function formatCodexMcpToolCallEvents(type, event) {
2806
- if (type !== "item.started" && type !== "item.updated" && type !== "item.completed") {
2807
- return [];
2808
- }
2809
- const item = objectField(event, "item");
2810
- const itemType = stringField(item, "type") ?? "";
2811
- const serverName = mcpServerName(item);
2812
- const toolName = mcpToolName(item);
2813
- const isMcpItem = itemType.toLowerCase().includes("mcp")
2814
- || Boolean(serverName)
2815
- || (toolName ? isForgeCompletionTool(toolName) || toolName.toLowerCase().includes("mcp") : false);
2816
- if (!isMcpItem || !toolName) {
2817
- return [];
2818
- }
2819
- const status = normalizedString(stringField(item, "status")
2820
- ?? stringField(event, "status")
2821
- ?? (type === "item.started" ? "started" : type === "item.completed" ? "completed" : "updated"));
2822
- const failed = status === "failed" || status === "error" || status === "cancelled" || Boolean(item.error);
2823
- const completed = failed || type === "item.completed" || status === "completed" || status === "succeeded" || status === "success";
2824
- const started = type === "item.started" || status === "started" || status === "running" || status === "in_progress";
2825
- const data = safeProviderMcpData(item, serverName ?? "unknown", toolName, status);
2826
- const label = `${serverName ?? "unknown"}.${toolName}`;
2827
- if (failed) {
2828
- const summary = mcpErrorSummary(item) ?? "MCP tool call failed.";
2829
- const events = [{
2830
- role: "tool",
2831
- kind: "error",
2832
- content: `MCP tool call failed: ${label} - ${summary}`,
2833
- eventType: "provider_mcp_call_failed",
2834
- data
2835
- }];
2836
- if (isForgeCompletionTool(toolName)) {
2837
- events.push({
2838
- role: "tool",
2839
- kind: "error",
2840
- content: `Forge completion tool validation failed: ${label} - ${summary}`,
2841
- eventType: "completion_tool_validation_failed",
2842
- data
2843
- });
1639
+ if (result.exitCode !== 0)
1640
+ throw providerCliExitFailure(command.command, result);
1641
+ const postRepairHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
1642
+ if (postRepairHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
1643
+ throw new Error(`provider_publication_boundary_violation: pre-publication repair changed HEAD from ${preparedHeadSha} to ${postRepairHeadSha}; Forge requires provider changes to remain uncommitted and unpushed until validation passes.`, { cause: turn.failure });
1644
+ }
1645
+ }
1646
+ }
1647
+ async function stageDraftAttachments(dispatch, metadataRoot) {
1648
+ const attachments = dispatch.draft?.attachments ?? [];
1649
+ const stageable = attachments.filter((attachment) => (attachment.kind === "text" && typeof attachment.textContent === "string")
1650
+ || (attachment.kind === "image" && typeof attachment.contentBase64 === "string"));
1651
+ if (stageable.length === 0) {
1652
+ return { textReferences: [], imagePaths: [] };
1653
+ }
1654
+ const attachmentRoot = path.join(metadataRoot, "draft-attachments");
1655
+ const worktreeRoot = path.resolve(metadataRoot, "../../..");
1656
+ await fs.mkdir(attachmentRoot, { recursive: true });
1657
+ const textReferences = [];
1658
+ const imagePaths = [];
1659
+ for (const attachment of stageable) {
1660
+ const fileName = `${String(attachment.index + 1).padStart(2, "0")}-${safeAttachmentFileName(attachment.fileName)}`;
1661
+ const absolutePath = path.join(attachmentRoot, fileName);
1662
+ if (attachment.kind === "text") {
1663
+ await fs.writeFile(absolutePath, attachment.textContent ?? "", { encoding: "utf8", mode: 0o600 });
1664
+ textReferences.push({ index: attachment.index, path: path.relative(worktreeRoot, absolutePath).replaceAll(path.sep, "/") });
1665
+ continue;
2844
1666
  }
2845
- return events;
2846
- }
2847
- if (completed) {
2848
- return [{
2849
- role: "tool",
2850
- kind: "checkpoint",
2851
- content: `MCP tool call completed: ${label}.`,
2852
- eventType: "provider_mcp_call_completed",
2853
- data
2854
- }];
2855
- }
2856
- if (started) {
2857
- return [{
2858
- role: "tool",
2859
- kind: "checkpoint",
2860
- content: `MCP tool call started: ${label}.`,
2861
- eventType: "provider_mcp_call_started",
2862
- data
2863
- }];
2864
- }
2865
- return [];
2866
- }
2867
- function mcpServerName(item) {
2868
- return stringField(item, "server")
2869
- ?? stringField(item, "server_name")
2870
- ?? stringField(item, "mcp_server")
2871
- ?? stringField(objectField(item, "mcp"), "server")
2872
- ?? stringField(objectField(item, "mcp"), "server_name");
2873
- }
2874
- function mcpToolName(item) {
2875
- return stringField(item, "tool")
2876
- ?? stringField(item, "tool_name")
2877
- ?? stringField(item, "name")
2878
- ?? stringField(objectField(item, "function"), "name")
2879
- ?? stringField(objectField(item, "mcp"), "tool")
2880
- ?? stringField(objectField(item, "mcp"), "tool_name");
2881
- }
2882
- function mcpErrorSummary(item) {
2883
- const direct = stringField(item, "error")
2884
- ?? stringField(item, "error_message")
2885
- ?? stringField(item, "message");
2886
- if (direct) {
2887
- return clip(direct, 600);
2888
- }
2889
- const error = objectField(item, "error");
2890
- return stringField(error, "message")
2891
- ?? stringField(error, "summary")
2892
- ?? stringField(objectField(item, "result"), "error")
2893
- ?? null;
2894
- }
2895
- function safeProviderMcpData(item, serverName, toolName, status) {
2896
- const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
2897
- return JSON.stringify(stripUndefined({
2898
- server_name: serverName,
2899
- tool_name: toolName,
2900
- status,
2901
- elapsed_ms: elapsedMs,
2902
- error_summary: mcpErrorSummary(item)
2903
- }));
1667
+ const imageContent = decodeDraftImageAttachment(attachment.contentBase64 ?? "", attachment.fileName, attachment.index);
1668
+ await fs.writeFile(absolutePath, imageContent, { mode: 0o600 });
1669
+ imagePaths.push(absolutePath);
1670
+ }
1671
+ return { textReferences, imagePaths };
1672
+ }
1673
+ function decodeDraftImageAttachment(contentBase64, fileName, index) {
1674
+ const normalized = contentBase64.replace(/\s+/gu, "");
1675
+ if (normalized.length === 0 || normalized.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(normalized)) {
1676
+ throw new Error(`Draft image attachment ${index + 1} (${fileName}) is not valid base64.`);
1677
+ }
1678
+ const decoded = Buffer.from(normalized, "base64");
1679
+ if (decoded.length === 0 || decoded.toString("base64") !== normalized) {
1680
+ throw new Error(`Draft image attachment ${index + 1} (${fileName}) is not valid base64.`);
1681
+ }
1682
+ return decoded;
1683
+ }
1684
+ function safeAttachmentFileName(fileName) {
1685
+ const sanitized = path.basename(fileName || "attachment.txt")
1686
+ .replace(/[^a-zA-Z0-9._-]/gu, "_")
1687
+ .replace(/[. ]+$/gu, "") || "attachment.txt";
1688
+ const maxFileNameLength = 120;
1689
+ const clipped = clipFileName(sanitized, maxFileNameLength);
1690
+ const extension = path.extname(clipped);
1691
+ const stem = path.basename(clipped, extension).replace(/[. ]+$/gu, "") || "attachment";
1692
+ const windowsReservedName = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;
1693
+ const safeStem = stem === "." || stem === ".." || windowsReservedName.test(stem) ? `attachment-${stem.replaceAll(".", "_")}` : stem;
1694
+ return clipFileName(`${safeStem}${extension}`, maxFileNameLength);
1695
+ }
1696
+ function clipFileName(fileName, maxLength) {
1697
+ if (fileName.length <= maxLength) {
1698
+ return fileName;
1699
+ }
1700
+ const originalExtension = path.extname(fileName);
1701
+ const extension = originalExtension.length > maxLength - 1
1702
+ ? originalExtension.slice(0, maxLength - 1)
1703
+ : originalExtension;
1704
+ const stem = path.basename(fileName, originalExtension);
1705
+ const maxStemLength = Math.max(1, maxLength - extension.length);
1706
+ return `${stem.slice(0, maxStemLength)}${extension}`;
2904
1707
  }
2905
- function isForgeCompletionTool(toolName) {
2906
- const normalized = toolName.trim().toLowerCase();
2907
- return normalized.startsWith("forge.complete_")
2908
- || normalized.startsWith("complete_")
2909
- || normalized.includes("forge.complete_")
2910
- || normalized.includes("complete_architect_plan");
2911
- }
2912
- function objectField(source, key) {
2913
- const value = source[key];
2914
- return value && typeof value === "object" && !Array.isArray(value)
2915
- ? value
2916
- : {};
2917
- }
2918
- function stringField(source, key) {
2919
- const value = source[key];
2920
- return typeof value === "string" && value.trim().length > 0 ? value : null;
2921
- }
2922
- function numericField(source, key) {
2923
- const value = source[key];
2924
- return typeof value === "number" && Number.isFinite(value) ? value : null;
2925
- }
2926
- function stripUndefined(value) {
2927
- return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
2928
- }
2929
- function normalizedString(value) {
2930
- return value.trim().toLowerCase().replace(/-/g, "_");
2931
- }
2932
- function isNodeError(error) {
2933
- return error instanceof Error && "code" in error;
1708
+ function isFakeWorkerModel(model) {
1709
+ return model.trim().toLowerCase() === fakeWorkerModel;
2934
1710
  }