@opengsd/gsd-pi 1.2.0-dev.4c756166 → 1.2.0-dev.6ccd27b3

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 (837) hide show
  1. package/dist/cli-model-override.d.ts +15 -0
  2. package/dist/cli-model-override.js +21 -0
  3. package/dist/cli-style.d.ts +17 -0
  4. package/dist/cli-style.js +28 -0
  5. package/dist/cli.js +2 -19
  6. package/dist/headless-events.d.ts +4 -2
  7. package/dist/headless-events.js +14 -34
  8. package/dist/loader.js +6 -4
  9. package/dist/mcp-server.js +2 -1
  10. package/dist/models-resolver.d.ts +3 -13
  11. package/dist/models-resolver.js +3 -22
  12. package/dist/register-agent-bundles.d.ts +11 -2
  13. package/dist/register-agent-bundles.js +18 -4
  14. package/dist/resource-loader.d.ts +10 -5
  15. package/dist/resource-loader.js +123 -20
  16. package/dist/resources/.managed-resources-content-hash +1 -1
  17. package/dist/resources/GSD-WORKFLOW.md +5 -4
  18. package/dist/resources/extensions/ask-user-questions.js +3 -2
  19. package/dist/resources/extensions/async-jobs/async-bash-tool.js +30 -64
  20. package/dist/resources/extensions/async-jobs/await-tool.js +80 -12
  21. package/dist/resources/extensions/async-jobs/index.js +65 -0
  22. package/dist/resources/extensions/async-jobs/job-manager.js +12 -1
  23. package/dist/resources/extensions/bg-shell/bg-shell-command.js +6 -6
  24. package/dist/resources/extensions/bg-shell/bg-shell-tool.js +10 -7
  25. package/dist/resources/extensions/bg-shell/overlay.js +9 -6
  26. package/dist/resources/extensions/bg-shell/process-manager.js +54 -25
  27. package/dist/resources/extensions/bg-shell/readiness-detector.js +11 -0
  28. package/dist/resources/extensions/bg-shell/utilities.js +5 -2
  29. package/dist/resources/extensions/browser-tools/engine/managed-gsd-browser.js +209 -88
  30. package/dist/resources/extensions/browser-tools/engine/selection.js +73 -5
  31. package/dist/resources/extensions/browser-tools/index.js +69 -12
  32. package/dist/resources/extensions/claude-code-cli/models.js +9 -0
  33. package/dist/resources/extensions/claude-code-cli/stream-adapter.js +464 -200
  34. package/dist/resources/extensions/claude-code-cli/turn-assembler.js +33 -1
  35. package/dist/resources/extensions/gsd/auto/closeout.js +215 -0
  36. package/dist/resources/extensions/gsd/auto/custom-verify-retry-store.js +17 -2
  37. package/dist/resources/extensions/gsd/auto/detect-stuck.js +33 -13
  38. package/dist/resources/extensions/gsd/auto/dispatch-history.js +120 -0
  39. package/dist/resources/extensions/gsd/auto/dispatch-key.js +37 -0
  40. package/dist/resources/extensions/gsd/auto/dispatch.js +365 -0
  41. package/dist/resources/extensions/gsd/auto/finalize.js +347 -0
  42. package/dist/resources/extensions/gsd/auto/loop.js +7 -1
  43. package/dist/resources/extensions/gsd/auto/milestone-lease-reclaim.js +56 -0
  44. package/dist/resources/extensions/gsd/auto/orchestrator.js +207 -73
  45. package/dist/resources/extensions/gsd/auto/phase-helpers.js +146 -0
  46. package/dist/resources/extensions/gsd/auto/phases.js +17 -2324
  47. package/dist/resources/extensions/gsd/auto/pre-dispatch.js +534 -0
  48. package/dist/resources/extensions/gsd/auto/session.js +3 -0
  49. package/dist/resources/extensions/gsd/auto/unit-phase.js +694 -0
  50. package/dist/resources/extensions/gsd/auto/workflow-unit-dispatch.js +1 -1
  51. package/dist/resources/extensions/gsd/auto/worktree-safety-phase.js +125 -0
  52. package/dist/resources/extensions/gsd/auto-direct-dispatch.js +11 -34
  53. package/dist/resources/extensions/gsd/auto-dispatch.js +50 -58
  54. package/dist/resources/extensions/gsd/auto-model-selection.js +36 -13
  55. package/dist/resources/extensions/gsd/auto-post-unit.js +43 -14
  56. package/dist/resources/extensions/gsd/auto-prompts.js +81 -19
  57. package/dist/resources/extensions/gsd/auto-start.js +47 -29
  58. package/dist/resources/extensions/gsd/auto-tool-tracking.js +18 -0
  59. package/dist/resources/extensions/gsd/auto-unit-closeout.js +45 -21
  60. package/dist/resources/extensions/gsd/auto-unit-tool-scope.js +12 -20
  61. package/dist/resources/extensions/gsd/auto-verification.js +23 -30
  62. package/dist/resources/extensions/gsd/auto-worktree-repair.js +10 -2
  63. package/dist/resources/extensions/gsd/auto-worktree.js +50 -354
  64. package/dist/resources/extensions/gsd/auto.js +49 -22
  65. package/dist/resources/extensions/gsd/blocked-models.js +28 -0
  66. package/dist/resources/extensions/gsd/bootstrap/agent-end-recovery.js +29 -8
  67. package/dist/resources/extensions/gsd/bootstrap/dynamic-tools.js +69 -19
  68. package/dist/resources/extensions/gsd/bootstrap/exec-tools.js +2 -2
  69. package/dist/resources/extensions/gsd/bootstrap/register-extension.js +19 -0
  70. package/dist/resources/extensions/gsd/bootstrap/register-hooks.js +229 -36
  71. package/dist/resources/extensions/gsd/bootstrap/write-gate.js +319 -71
  72. package/dist/resources/extensions/gsd/branch-patterns.js +2 -0
  73. package/dist/resources/extensions/gsd/browser-daemon-auto-prep.js +83 -0
  74. package/dist/resources/extensions/gsd/browser-evidence.js +8 -2
  75. package/dist/resources/extensions/gsd/captures.js +5 -15
  76. package/dist/resources/extensions/gsd/closeout-recovery.js +3 -2
  77. package/dist/resources/extensions/gsd/closeout-wizard.js +92 -0
  78. package/dist/resources/extensions/gsd/commands/catalog.js +6 -62
  79. package/dist/resources/extensions/gsd/commands/context.js +16 -2
  80. package/dist/resources/extensions/gsd/commands-handlers.js +46 -3
  81. package/dist/resources/extensions/gsd/commands-mcp-status.js +2 -2
  82. package/dist/resources/extensions/gsd/commands-workflow-templates.js +9 -2
  83. package/dist/resources/extensions/gsd/consent-question.js +353 -0
  84. package/dist/resources/extensions/gsd/consent-verdict.js +63 -0
  85. package/dist/resources/extensions/gsd/constants.js +0 -2
  86. package/dist/resources/extensions/gsd/crash-recovery.js +12 -15
  87. package/dist/resources/extensions/gsd/db/engine.js +755 -0
  88. package/dist/resources/extensions/gsd/db/queries.js +428 -0
  89. package/dist/resources/extensions/gsd/db/sql-constants.js +11 -0
  90. package/dist/resources/extensions/gsd/db/writers/cascades.js +194 -0
  91. package/dist/resources/extensions/gsd/db/writers/import-restore.js +182 -0
  92. package/dist/resources/extensions/gsd/db/writers/memory.js +149 -0
  93. package/dist/resources/extensions/gsd/db/writers/reconcile.js +458 -0
  94. package/dist/resources/extensions/gsd/db/writers/status.js +70 -0
  95. package/dist/resources/extensions/gsd/db-writer.js +8 -17
  96. package/dist/resources/extensions/gsd/dispatch-guard.js +10 -35
  97. package/dist/resources/extensions/gsd/doctor-engine-checks.js +5 -5
  98. package/dist/resources/extensions/gsd/doctor-environment.js +261 -136
  99. package/dist/resources/extensions/gsd/doctor-format.js +9 -6
  100. package/dist/resources/extensions/gsd/doctor-git-checks.js +6 -21
  101. package/dist/resources/extensions/gsd/doctor-runtime-checks.js +21 -16
  102. package/dist/resources/extensions/gsd/engine-hook-contract.js +70 -0
  103. package/dist/resources/extensions/gsd/error-classifier.js +9 -0
  104. package/dist/resources/extensions/gsd/exec-sandbox.js +30 -10
  105. package/dist/resources/extensions/gsd/files.js +33 -19
  106. package/dist/resources/extensions/gsd/git-service.js +1 -0
  107. package/dist/resources/extensions/gsd/gitignore.js +3 -0
  108. package/dist/resources/extensions/gsd/gsd-command-home.js +22 -12
  109. package/dist/resources/extensions/gsd/gsd-db.js +172 -2048
  110. package/dist/resources/extensions/gsd/guidance.js +158 -0
  111. package/dist/resources/extensions/gsd/guided-flow.js +144 -9
  112. package/dist/resources/extensions/gsd/health-widget.js +87 -28
  113. package/dist/resources/extensions/gsd/markdown-renderer.js +10 -0
  114. package/dist/resources/extensions/gsd/mcp-bridge.js +10 -0
  115. package/dist/resources/extensions/gsd/mcp-filter.js +2 -19
  116. package/dist/resources/extensions/gsd/mcp-tool-name.js +5 -13
  117. package/dist/resources/extensions/gsd/memory-consolidation-scanner.js +1 -1
  118. package/dist/resources/extensions/gsd/migrate/safety.js +20 -9
  119. package/dist/resources/extensions/gsd/migration-auto-check.js +24 -3
  120. package/dist/resources/extensions/gsd/milestone-closeout.js +85 -24
  121. package/dist/resources/extensions/gsd/milestone-planning-persistence.js +2 -2
  122. package/dist/resources/extensions/gsd/milestone-reopen-events.js +3 -5
  123. package/dist/resources/extensions/gsd/milestone-settlement.js +2 -2
  124. package/dist/resources/extensions/gsd/model-cost-table.js +1 -0
  125. package/dist/resources/extensions/gsd/model-router.js +3 -0
  126. package/dist/resources/extensions/gsd/notification-store.js +11 -4
  127. package/dist/resources/extensions/gsd/notifications.js +12 -7
  128. package/dist/resources/extensions/gsd/parallel-merge.js +14 -11
  129. package/dist/resources/extensions/gsd/parallel-monitor-overlay.js +11 -7
  130. package/dist/resources/extensions/gsd/parsers-legacy.js +16 -4
  131. package/dist/resources/extensions/gsd/paths.js +37 -24
  132. package/dist/resources/extensions/gsd/pre-execution-checks.js +91 -3
  133. package/dist/resources/extensions/gsd/preferences-models.js +14 -48
  134. package/dist/resources/extensions/gsd/preferences.js +14 -0
  135. package/dist/resources/extensions/gsd/projection-flush.js +7 -0
  136. package/dist/resources/extensions/gsd/prompts/complete-slice.md +4 -4
  137. package/dist/resources/extensions/gsd/prompts/execute-task.md +3 -2
  138. package/dist/resources/extensions/gsd/prompts/plan-milestone.md +1 -1
  139. package/dist/resources/extensions/gsd/prompts/plan-slice.md +2 -2
  140. package/dist/resources/extensions/gsd/prompts/quick-task.md +1 -1
  141. package/dist/resources/extensions/gsd/prompts/reassess-roadmap.md +1 -1
  142. package/dist/resources/extensions/gsd/prompts/refine-slice.md +2 -2
  143. package/dist/resources/extensions/gsd/prompts/replan-slice.md +2 -2
  144. package/dist/resources/extensions/gsd/prompts/research-milestone.md +1 -1
  145. package/dist/resources/extensions/gsd/prompts/research-slice.md +1 -1
  146. package/dist/resources/extensions/gsd/prompts/rewrite-docs.md +1 -1
  147. package/dist/resources/extensions/gsd/prompts/run-uat.md +9 -5
  148. package/dist/resources/extensions/gsd/prompts/system.md +5 -2
  149. package/dist/resources/extensions/gsd/prompts/triage-captures.md +1 -1
  150. package/dist/resources/extensions/gsd/prompts/validate-milestone.md +1 -1
  151. package/dist/resources/extensions/gsd/prompts/workflow-start.md +2 -1
  152. package/dist/resources/extensions/gsd/provider-error-guidance.js +1 -5
  153. package/dist/resources/extensions/gsd/provider-switch-observer.js +1 -1
  154. package/dist/resources/extensions/gsd/publication.js +87 -0
  155. package/dist/resources/extensions/gsd/reactive-graph.js +8 -1
  156. package/dist/resources/extensions/gsd/recovery-classification.js +41 -87
  157. package/dist/resources/extensions/gsd/roadmap-slices.js +25 -3
  158. package/dist/resources/extensions/gsd/safety/destructive-confirmation.js +108 -0
  159. package/dist/resources/extensions/gsd/safety/evidence-collector.js +37 -4
  160. package/dist/resources/extensions/gsd/safety/evidence-cross-ref.js +7 -2
  161. package/dist/resources/extensions/gsd/safety/file-change-validator.js +10 -0
  162. package/dist/resources/extensions/gsd/session-lock.js +1 -1
  163. package/dist/resources/extensions/gsd/skill-activation.js +3 -6
  164. package/dist/resources/extensions/gsd/state-transition-matrix.js +38 -0
  165. package/dist/resources/extensions/gsd/state.js +12 -22
  166. package/dist/resources/extensions/gsd/status-guards.js +56 -8
  167. package/dist/resources/extensions/gsd/stop-notice.js +57 -0
  168. package/dist/resources/extensions/gsd/tool-contract.js +14 -3
  169. package/dist/resources/extensions/gsd/tool-presentation-plan.js +4 -4
  170. package/dist/resources/extensions/gsd/tool-surface-readiness.js +108 -0
  171. package/dist/resources/extensions/gsd/tools/complete-milestone.js +3 -2
  172. package/dist/resources/extensions/gsd/tools/complete-slice.js +46 -55
  173. package/dist/resources/extensions/gsd/tools/complete-task.js +65 -2
  174. package/dist/resources/extensions/gsd/tools/exec-tool.js +10 -8
  175. package/dist/resources/extensions/gsd/tools/plan-slice.js +14 -8
  176. package/dist/resources/extensions/gsd/tools/plan-task.js +2 -2
  177. package/dist/resources/extensions/gsd/tools/reassess-roadmap.js +2 -2
  178. package/dist/resources/extensions/gsd/tools/reopen-milestone.js +13 -31
  179. package/dist/resources/extensions/gsd/tools/reopen-slice.js +16 -35
  180. package/dist/resources/extensions/gsd/tools/reopen-task.js +2 -2
  181. package/dist/resources/extensions/gsd/tools/replan-slice.js +2 -2
  182. package/dist/resources/extensions/gsd/tools/skip-slice.js +18 -36
  183. package/dist/resources/extensions/gsd/tools/workflow-tool-executors.js +67 -2
  184. package/dist/resources/extensions/gsd/uat-policy.js +42 -16
  185. package/dist/resources/extensions/gsd/undo.js +8 -7
  186. package/dist/resources/extensions/gsd/unit-closeout.js +138 -0
  187. package/dist/resources/extensions/gsd/unit-context-composer.js +74 -1
  188. package/dist/resources/extensions/gsd/unit-context-manifest.js +4 -27
  189. package/dist/resources/extensions/gsd/unit-registry.js +367 -0
  190. package/dist/resources/extensions/gsd/unit-tool-contracts.js +9 -182
  191. package/dist/resources/extensions/gsd/verdict-parser.js +1 -1
  192. package/dist/resources/extensions/gsd/verification-verdict.js +2 -1
  193. package/dist/resources/extensions/gsd/web-app-uat.js +45 -8
  194. package/dist/resources/extensions/gsd/workflow-event-ledger.js +91 -0
  195. package/dist/resources/extensions/gsd/workflow-event-vocabulary.js +46 -0
  196. package/dist/resources/extensions/gsd/workflow-events.js +6 -18
  197. package/dist/resources/extensions/gsd/workflow-mcp-auto-prep.js +2 -0
  198. package/dist/resources/extensions/gsd/workflow-mcp-readiness-cache.js +105 -0
  199. package/dist/resources/extensions/gsd/workflow-reconcile.js +21 -56
  200. package/dist/resources/extensions/gsd/workflow-tool-surface.js +1 -1
  201. package/dist/resources/extensions/gsd/worktree-git-recovery.js +293 -0
  202. package/dist/resources/extensions/gsd/worktree-lifecycle.js +12 -3
  203. package/dist/resources/extensions/gsd/worktree-manager.js +52 -29
  204. package/dist/resources/extensions/gsd/worktree-placement.js +59 -0
  205. package/dist/resources/extensions/gsd/worktree-reentry.js +12 -8
  206. package/dist/resources/extensions/gsd/worktree-root.js +28 -6
  207. package/dist/resources/extensions/gsd/worktree-safety.js +36 -31
  208. package/dist/resources/extensions/gsd/worktree-session-state.js +12 -11
  209. package/dist/resources/extensions/gsd/worktree.js +8 -1
  210. package/dist/resources/extensions/mcp-client/manager.js +6 -1
  211. package/dist/resources/extensions/search-the-web/native-search.js +5 -3
  212. package/dist/resources/extensions/shared/browser-contract.js +59 -0
  213. package/dist/resources/extensions/shared/gsd-browser-cli.js +116 -6
  214. package/dist/resources/shared/gsd-browser-path-sync.js +214 -0
  215. package/dist/resources/shared/package-manager-detection.js +1 -1
  216. package/dist/resources/shared/package.json +3 -0
  217. package/dist/resources/skills/create-skill/SKILL.md +3 -0
  218. package/dist/resources/skills/create-skill/references/executable-code.md +1 -1
  219. package/dist/resources/skills/create-skill/references/skill-structure.md +1 -0
  220. package/dist/resources/skills/create-skill/workflows/add-reference.md +8 -3
  221. package/dist/resources/skills/create-skill/workflows/add-script.md +4 -2
  222. package/dist/resources/skills/create-skill/workflows/add-template.md +3 -1
  223. package/dist/resources/skills/create-skill/workflows/add-workflow.md +8 -3
  224. package/dist/resources/skills/create-skill/workflows/upgrade-to-router.md +10 -5
  225. package/dist/resources/skills/create-skill/workflows/verify-skill.md +9 -4
  226. package/dist/resources/skills/spike-wrap-up/SKILL.md +9 -9
  227. package/dist/runtime-checks.d.ts +10 -0
  228. package/dist/runtime-checks.js +27 -0
  229. package/dist/tsconfig.extensions.tsbuildinfo +1 -1
  230. package/dist/update-check.d.ts +2 -0
  231. package/dist/update-check.js +24 -1
  232. package/dist/update-cmd.js +20 -3
  233. package/dist/web/standalone/.next/BUILD_ID +1 -1
  234. package/dist/web/standalone/.next/app-path-routes-manifest.json +10 -10
  235. package/dist/web/standalone/.next/build-manifest.json +3 -3
  236. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  237. package/dist/web/standalone/.next/react-loadable-manifest.json +1 -1
  238. package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
  239. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  240. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  241. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  242. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  243. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  244. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  245. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  246. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  247. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  248. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  249. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  250. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  251. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  252. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  253. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  254. package/dist/web/standalone/.next/server/app/api/boot/route.js.nft.json +1 -1
  255. package/dist/web/standalone/.next/server/app/api/bridge-terminal/input/route.js.nft.json +1 -1
  256. package/dist/web/standalone/.next/server/app/api/bridge-terminal/resize/route.js.nft.json +1 -1
  257. package/dist/web/standalone/.next/server/app/api/bridge-terminal/stream/route.js.nft.json +1 -1
  258. package/dist/web/standalone/.next/server/app/api/captures/route.js.nft.json +1 -1
  259. package/dist/web/standalone/.next/server/app/api/cleanup/route.js.nft.json +1 -1
  260. package/dist/web/standalone/.next/server/app/api/doctor/route.js.nft.json +1 -1
  261. package/dist/web/standalone/.next/server/app/api/export-data/route.js.nft.json +1 -1
  262. package/dist/web/standalone/.next/server/app/api/files/route.js.nft.json +1 -1
  263. package/dist/web/standalone/.next/server/app/api/forensics/route.js.nft.json +1 -1
  264. package/dist/web/standalone/.next/server/app/api/git/route.js.nft.json +1 -1
  265. package/dist/web/standalone/.next/server/app/api/history/route.js.nft.json +1 -1
  266. package/dist/web/standalone/.next/server/app/api/hooks/route.js.nft.json +1 -1
  267. package/dist/web/standalone/.next/server/app/api/inspect/route.js.nft.json +1 -1
  268. package/dist/web/standalone/.next/server/app/api/knowledge/route.js.nft.json +1 -1
  269. package/dist/web/standalone/.next/server/app/api/live-state/route.js.nft.json +1 -1
  270. package/dist/web/standalone/.next/server/app/api/mcp-connections/route.js.nft.json +1 -1
  271. package/dist/web/standalone/.next/server/app/api/notifications/route.js.nft.json +1 -1
  272. package/dist/web/standalone/.next/server/app/api/onboarding/route.js.nft.json +1 -1
  273. package/dist/web/standalone/.next/server/app/api/projects/route.js.nft.json +1 -1
  274. package/dist/web/standalone/.next/server/app/api/recovery/route.js.nft.json +1 -1
  275. package/dist/web/standalone/.next/server/app/api/session/browser/route.js.nft.json +1 -1
  276. package/dist/web/standalone/.next/server/app/api/session/command/route.js.nft.json +1 -1
  277. package/dist/web/standalone/.next/server/app/api/session/events/route.js.nft.json +1 -1
  278. package/dist/web/standalone/.next/server/app/api/session/manage/route.js.nft.json +1 -1
  279. package/dist/web/standalone/.next/server/app/api/settings-data/route.js.nft.json +1 -1
  280. package/dist/web/standalone/.next/server/app/api/shutdown/route.js.nft.json +1 -1
  281. package/dist/web/standalone/.next/server/app/api/skill-health/route.js.nft.json +1 -1
  282. package/dist/web/standalone/.next/server/app/api/steer/route.js.nft.json +1 -1
  283. package/dist/web/standalone/.next/server/app/api/switch-root/route.js.nft.json +1 -1
  284. package/dist/web/standalone/.next/server/app/api/terminal/sessions/route.js.nft.json +1 -1
  285. package/dist/web/standalone/.next/server/app/api/terminal/stream/route.js.nft.json +1 -1
  286. package/dist/web/standalone/.next/server/app/api/undo/route.js.nft.json +1 -1
  287. package/dist/web/standalone/.next/server/app/api/update/route.js +1 -1
  288. package/dist/web/standalone/.next/server/app/api/update/route.js.nft.json +1 -1
  289. package/dist/web/standalone/.next/server/app/api/visualizer/route.js.nft.json +1 -1
  290. package/dist/web/standalone/.next/server/app/index.html +1 -1
  291. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  292. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  293. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  294. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  295. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  296. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  297. package/dist/web/standalone/.next/server/app-paths-manifest.json +10 -10
  298. package/dist/web/standalone/.next/server/chunks/5124.js +1 -1
  299. package/dist/web/standalone/.next/server/chunks/{5047.js → 5942.js} +2 -2
  300. package/dist/web/standalone/.next/server/chunks/8357.js +2 -2
  301. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  302. package/dist/web/standalone/.next/server/middleware-react-loadable-manifest.js +1 -1
  303. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  304. package/dist/web/standalone/.next/server/pages/500.html +1 -1
  305. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  306. package/dist/web/standalone/.next/static/chunks/{796.cf859a427a2cb2ac.js → 796.e0bdc932325d7e03.js} +1 -1
  307. package/dist/web/standalone/.next/static/chunks/{webpack-fbea77b5f9953368.js → webpack-f0285ce91d4ec9ef.js} +1 -1
  308. package/dist/web/standalone/node_modules/node-pty/build/Makefile +1 -1
  309. package/dist/web/standalone/package.json +1 -1
  310. package/dist/worktree-cli.js +3 -6
  311. package/dist/worktree-status-banner.js +7 -11
  312. package/package.json +3 -3
  313. package/packages/cloud-mcp-gateway/package.json +2 -2
  314. package/packages/contracts/dist/rpc.d.ts +1 -0
  315. package/packages/contracts/dist/rpc.d.ts.map +1 -1
  316. package/packages/contracts/dist/rpc.js.map +1 -1
  317. package/packages/contracts/dist/workflow.d.ts +4 -0
  318. package/packages/contracts/dist/workflow.d.ts.map +1 -1
  319. package/packages/contracts/dist/workflow.js.map +1 -1
  320. package/packages/contracts/package.json +1 -1
  321. package/packages/daemon/package.json +4 -4
  322. package/packages/gsd-agent-core/dist/sdk.d.ts.map +1 -1
  323. package/packages/gsd-agent-core/dist/sdk.js +6 -4
  324. package/packages/gsd-agent-core/dist/sdk.js.map +1 -1
  325. package/packages/gsd-agent-core/package.json +5 -5
  326. package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  327. package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  328. package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.js +10 -0
  329. package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.js.map +1 -1
  330. package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.d.ts +13 -0
  331. package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  332. package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.js +55 -6
  333. package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.js.map +1 -1
  334. package/packages/gsd-agent-modes/dist/modes/interactive/components/transcript-design.d.ts +2 -0
  335. package/packages/gsd-agent-modes/dist/modes/interactive/components/transcript-design.d.ts.map +1 -1
  336. package/packages/gsd-agent-modes/dist/modes/interactive/components/transcript-design.js +34 -5
  337. package/packages/gsd-agent-modes/dist/modes/interactive/components/transcript-design.js.map +1 -1
  338. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.d.ts.map +1 -1
  339. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.js +7 -0
  340. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.js.map +1 -1
  341. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.d.ts.map +1 -1
  342. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.js +8 -1
  343. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.js.map +1 -1
  344. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-chat-render.d.ts.map +1 -1
  345. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-chat-render.js +11 -1
  346. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-chat-render.js.map +1 -1
  347. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.d.ts +1 -0
  348. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  349. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.js +12 -0
  350. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.js.map +1 -1
  351. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-auth.d.ts.map +1 -1
  352. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-auth.js +4 -4
  353. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-auth.js.map +1 -1
  354. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-settings.d.ts.map +1 -1
  355. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-settings.js +4 -0
  356. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-settings.js.map +1 -1
  357. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  358. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.js +3 -1
  359. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.js.map +1 -1
  360. package/packages/gsd-agent-modes/package.json +7 -7
  361. package/packages/mcp-server/README.md +12 -3
  362. package/packages/mcp-server/dist/cli-runner.d.ts +40 -0
  363. package/packages/mcp-server/dist/cli-runner.d.ts.map +1 -0
  364. package/packages/mcp-server/dist/cli-runner.js +137 -0
  365. package/packages/mcp-server/dist/cli-runner.js.map +1 -0
  366. package/packages/mcp-server/dist/cli.js +2 -50
  367. package/packages/mcp-server/dist/cli.js.map +1 -1
  368. package/packages/mcp-server/dist/moonshot-tool-schema.d.ts +29 -0
  369. package/packages/mcp-server/dist/moonshot-tool-schema.d.ts.map +1 -0
  370. package/packages/mcp-server/dist/moonshot-tool-schema.js +50 -0
  371. package/packages/mcp-server/dist/moonshot-tool-schema.js.map +1 -0
  372. package/packages/mcp-server/dist/pid-registry.d.ts +46 -0
  373. package/packages/mcp-server/dist/pid-registry.d.ts.map +1 -0
  374. package/packages/mcp-server/dist/pid-registry.js +452 -0
  375. package/packages/mcp-server/dist/pid-registry.js.map +1 -0
  376. package/packages/mcp-server/dist/probe-mode.d.ts +4 -0
  377. package/packages/mcp-server/dist/probe-mode.d.ts.map +1 -0
  378. package/packages/mcp-server/dist/probe-mode.js +10 -0
  379. package/packages/mcp-server/dist/probe-mode.js.map +1 -0
  380. package/packages/mcp-server/dist/server.d.ts.map +1 -1
  381. package/packages/mcp-server/dist/server.js +4 -0
  382. package/packages/mcp-server/dist/server.js.map +1 -1
  383. package/packages/mcp-server/dist/stdio-watchdog.d.ts +8 -0
  384. package/packages/mcp-server/dist/stdio-watchdog.d.ts.map +1 -0
  385. package/packages/mcp-server/dist/stdio-watchdog.js +40 -0
  386. package/packages/mcp-server/dist/stdio-watchdog.js.map +1 -0
  387. package/packages/mcp-server/dist/workflow-tools.d.ts +26 -18
  388. package/packages/mcp-server/dist/workflow-tools.d.ts.map +1 -1
  389. package/packages/mcp-server/dist/workflow-tools.js +207 -102
  390. package/packages/mcp-server/dist/workflow-tools.js.map +1 -1
  391. package/packages/mcp-server/package.json +5 -4
  392. package/packages/native/package.json +1 -1
  393. package/packages/pi-agent-core/dist/agent-loop.js +43 -2
  394. package/packages/pi-agent-core/dist/agent-loop.js.map +1 -1
  395. package/packages/pi-agent-core/dist/harness/env/nodejs.d.ts +1 -0
  396. package/packages/pi-agent-core/dist/harness/env/nodejs.d.ts.map +1 -1
  397. package/packages/pi-agent-core/dist/harness/env/nodejs.js +34 -3
  398. package/packages/pi-agent-core/dist/harness/env/nodejs.js.map +1 -1
  399. package/packages/pi-agent-core/dist/index.d.ts +1 -0
  400. package/packages/pi-agent-core/dist/index.d.ts.map +1 -1
  401. package/packages/pi-agent-core/dist/index.js +3 -0
  402. package/packages/pi-agent-core/dist/index.js.map +1 -1
  403. package/packages/pi-agent-core/package.json +1 -1
  404. package/packages/pi-ai/README.md +1 -0
  405. package/packages/pi-ai/dist/image-models.generated.d.ts +2 -2
  406. package/packages/pi-ai/dist/image-models.generated.js +6 -6
  407. package/packages/pi-ai/dist/image-models.generated.js.map +1 -1
  408. package/packages/pi-ai/dist/index.d.ts +2 -0
  409. package/packages/pi-ai/dist/index.d.ts.map +1 -1
  410. package/packages/pi-ai/dist/index.js +2 -0
  411. package/packages/pi-ai/dist/index.js.map +1 -1
  412. package/packages/pi-ai/dist/models.generated.d.ts +158 -17
  413. package/packages/pi-ai/dist/models.generated.d.ts.map +1 -1
  414. package/packages/pi-ai/dist/models.generated.js +132 -17
  415. package/packages/pi-ai/dist/models.generated.js.map +1 -1
  416. package/packages/pi-ai/dist/providers/anthropic.d.ts.map +1 -1
  417. package/packages/pi-ai/dist/providers/anthropic.js +12 -7
  418. package/packages/pi-ai/dist/providers/anthropic.js.map +1 -1
  419. package/packages/pi-ai/dist/providers/google-shared.d.ts +5 -0
  420. package/packages/pi-ai/dist/providers/google-shared.d.ts.map +1 -1
  421. package/packages/pi-ai/dist/providers/google-shared.js +12 -3
  422. package/packages/pi-ai/dist/providers/google-shared.js.map +1 -1
  423. package/packages/pi-ai/dist/providers/openai-completions.d.ts.map +1 -1
  424. package/packages/pi-ai/dist/providers/openai-completions.js +7 -3
  425. package/packages/pi-ai/dist/providers/openai-completions.js.map +1 -1
  426. package/packages/pi-ai/dist/utils/moonshot-tool-schema.d.ts +9 -0
  427. package/packages/pi-ai/dist/utils/moonshot-tool-schema.d.ts.map +1 -0
  428. package/packages/pi-ai/dist/utils/moonshot-tool-schema.js +34 -0
  429. package/packages/pi-ai/dist/utils/moonshot-tool-schema.js.map +1 -0
  430. package/packages/pi-ai/dist/utils/oauth/github-copilot.d.ts.map +1 -1
  431. package/packages/pi-ai/dist/utils/oauth/github-copilot.js +6 -2
  432. package/packages/pi-ai/dist/utils/oauth/github-copilot.js.map +1 -1
  433. package/packages/pi-ai/package.json +3 -2
  434. package/packages/pi-coding-agent/dist/core/auth-storage.d.ts +2 -2
  435. package/packages/pi-coding-agent/dist/core/auth-storage.d.ts.map +1 -1
  436. package/packages/pi-coding-agent/dist/core/auth-storage.js +19 -13
  437. package/packages/pi-coding-agent/dist/core/auth-storage.js.map +1 -1
  438. package/packages/pi-coding-agent/dist/core/capability-patches.d.ts.map +1 -1
  439. package/packages/pi-coding-agent/dist/core/capability-patches.js +3 -1
  440. package/packages/pi-coding-agent/dist/core/capability-patches.js.map +1 -1
  441. package/packages/pi-coding-agent/dist/core/provider-readiness.d.ts.map +1 -1
  442. package/packages/pi-coding-agent/dist/core/provider-readiness.js +13 -6
  443. package/packages/pi-coding-agent/dist/core/provider-readiness.js.map +1 -1
  444. package/packages/pi-coding-agent/dist/core/settings-manager.d.ts +3 -0
  445. package/packages/pi-coding-agent/dist/core/settings-manager.d.ts.map +1 -1
  446. package/packages/pi-coding-agent/dist/core/settings-manager.js +11 -0
  447. package/packages/pi-coding-agent/dist/core/settings-manager.js.map +1 -1
  448. package/packages/pi-coding-agent/dist/core/tools/bash.d.ts +11 -0
  449. package/packages/pi-coding-agent/dist/core/tools/bash.d.ts.map +1 -1
  450. package/packages/pi-coding-agent/dist/core/tools/bash.js +53 -11
  451. package/packages/pi-coding-agent/dist/core/tools/bash.js.map +1 -1
  452. package/packages/pi-coding-agent/dist/index.d.ts +1 -1
  453. package/packages/pi-coding-agent/dist/index.d.ts.map +1 -1
  454. package/packages/pi-coding-agent/dist/index.js +1 -1
  455. package/packages/pi-coding-agent/dist/index.js.map +1 -1
  456. package/packages/pi-coding-agent/dist/theme/theme.d.ts.map +1 -1
  457. package/packages/pi-coding-agent/dist/theme/theme.js +45 -17
  458. package/packages/pi-coding-agent/dist/theme/theme.js.map +1 -1
  459. package/packages/pi-coding-agent/dist/utils/shell.d.ts +28 -2
  460. package/packages/pi-coding-agent/dist/utils/shell.d.ts.map +1 -1
  461. package/packages/pi-coding-agent/dist/utils/shell.js +56 -10
  462. package/packages/pi-coding-agent/dist/utils/shell.js.map +1 -1
  463. package/packages/pi-coding-agent/package.json +7 -7
  464. package/packages/pi-tui/dist/index.d.ts +1 -1
  465. package/packages/pi-tui/dist/index.d.ts.map +1 -1
  466. package/packages/pi-tui/dist/index.js +1 -1
  467. package/packages/pi-tui/dist/index.js.map +1 -1
  468. package/packages/pi-tui/dist/terminal-image.d.ts +33 -0
  469. package/packages/pi-tui/dist/terminal-image.d.ts.map +1 -1
  470. package/packages/pi-tui/dist/terminal-image.js +54 -2
  471. package/packages/pi-tui/dist/terminal-image.js.map +1 -1
  472. package/packages/pi-tui/dist/tui.d.ts +8 -0
  473. package/packages/pi-tui/dist/tui.d.ts.map +1 -1
  474. package/packages/pi-tui/dist/tui.js +72 -18
  475. package/packages/pi-tui/dist/tui.js.map +1 -1
  476. package/packages/pi-tui/dist/utils.d.ts.map +1 -1
  477. package/packages/pi-tui/dist/utils.js +110 -36
  478. package/packages/pi-tui/dist/utils.js.map +1 -1
  479. package/packages/pi-tui/package.json +2 -2
  480. package/packages/rpc-client/package.json +2 -2
  481. package/pkg/dist/theme/theme.d.ts.map +1 -1
  482. package/pkg/dist/theme/theme.js +45 -17
  483. package/pkg/dist/theme/theme.js.map +1 -1
  484. package/pkg/package.json +1 -1
  485. package/src/resources/GSD-WORKFLOW.md +5 -4
  486. package/src/resources/extensions/ask-user-questions.ts +7 -2
  487. package/src/resources/extensions/async-jobs/async-bash-cancel.test.ts +360 -0
  488. package/src/resources/extensions/async-jobs/async-bash-tool.ts +33 -56
  489. package/src/resources/extensions/async-jobs/await-tool.test.ts +139 -0
  490. package/src/resources/extensions/async-jobs/await-tool.ts +82 -12
  491. package/src/resources/extensions/async-jobs/index.ts +79 -0
  492. package/src/resources/extensions/async-jobs/job-manager.ts +21 -1
  493. package/src/resources/extensions/bg-shell/bg-shell-command.ts +6 -6
  494. package/src/resources/extensions/bg-shell/bg-shell-tool.ts +10 -6
  495. package/src/resources/extensions/bg-shell/overlay.ts +9 -5
  496. package/src/resources/extensions/bg-shell/process-manager.ts +50 -25
  497. package/src/resources/extensions/bg-shell/readiness-detector.ts +12 -0
  498. package/src/resources/extensions/bg-shell/tests/lifecycle-and-utilities.test.ts +48 -1
  499. package/src/resources/extensions/bg-shell/utilities.ts +5 -2
  500. package/src/resources/extensions/browser-tools/engine/managed-gsd-browser.ts +265 -98
  501. package/src/resources/extensions/browser-tools/engine/selection.ts +90 -4
  502. package/src/resources/extensions/browser-tools/index.ts +71 -13
  503. package/src/resources/extensions/browser-tools/tests/browser-engine-selection.test.mjs +83 -13
  504. package/src/resources/extensions/browser-tools/tests/gsd-browser-launch-config.test.mjs +40 -1
  505. package/src/resources/extensions/browser-tools/tests/managed-gsd-browser-tools.test.mjs +136 -0
  506. package/src/resources/extensions/claude-code-cli/models.ts +9 -0
  507. package/src/resources/extensions/claude-code-cli/stream-adapter.ts +543 -202
  508. package/src/resources/extensions/claude-code-cli/tests/stream-adapter.test.ts +700 -7
  509. package/src/resources/extensions/claude-code-cli/turn-assembler.ts +38 -1
  510. package/src/resources/extensions/gsd/auto/closeout.ts +309 -0
  511. package/src/resources/extensions/gsd/auto/custom-verify-retry-store.ts +21 -3
  512. package/src/resources/extensions/gsd/auto/detect-stuck.ts +32 -9
  513. package/src/resources/extensions/gsd/auto/dispatch-history.ts +168 -0
  514. package/src/resources/extensions/gsd/auto/dispatch-key.ts +39 -0
  515. package/src/resources/extensions/gsd/auto/dispatch.ts +449 -0
  516. package/src/resources/extensions/gsd/auto/finalize.ts +445 -0
  517. package/src/resources/extensions/gsd/auto/loop-deps.ts +1 -1
  518. package/src/resources/extensions/gsd/auto/loop.ts +7 -1
  519. package/src/resources/extensions/gsd/auto/milestone-lease-reclaim.ts +74 -0
  520. package/src/resources/extensions/gsd/auto/orchestrator.ts +232 -76
  521. package/src/resources/extensions/gsd/auto/phase-helpers.ts +199 -0
  522. package/src/resources/extensions/gsd/auto/phases.ts +58 -3013
  523. package/src/resources/extensions/gsd/auto/pre-dispatch.ts +704 -0
  524. package/src/resources/extensions/gsd/auto/session.ts +3 -0
  525. package/src/resources/extensions/gsd/auto/unit-phase.ts +910 -0
  526. package/src/resources/extensions/gsd/auto/workflow-unit-dispatch.ts +1 -1
  527. package/src/resources/extensions/gsd/auto/worktree-safety-phase.ts +149 -0
  528. package/src/resources/extensions/gsd/auto-direct-dispatch.ts +18 -48
  529. package/src/resources/extensions/gsd/auto-dispatch.ts +48 -61
  530. package/src/resources/extensions/gsd/auto-model-selection.ts +41 -12
  531. package/src/resources/extensions/gsd/auto-post-unit.ts +52 -13
  532. package/src/resources/extensions/gsd/auto-prompts.ts +118 -35
  533. package/src/resources/extensions/gsd/auto-start.ts +48 -33
  534. package/src/resources/extensions/gsd/auto-tool-tracking.ts +19 -0
  535. package/src/resources/extensions/gsd/auto-unit-closeout.ts +83 -28
  536. package/src/resources/extensions/gsd/auto-unit-tool-scope.ts +14 -21
  537. package/src/resources/extensions/gsd/auto-verification.ts +26 -28
  538. package/src/resources/extensions/gsd/auto-worktree-repair.ts +13 -2
  539. package/src/resources/extensions/gsd/auto-worktree.ts +56 -366
  540. package/src/resources/extensions/gsd/auto.ts +69 -26
  541. package/src/resources/extensions/gsd/blocked-models.ts +49 -0
  542. package/src/resources/extensions/gsd/bootstrap/agent-end-recovery.ts +37 -10
  543. package/src/resources/extensions/gsd/bootstrap/dynamic-tools.ts +89 -18
  544. package/src/resources/extensions/gsd/bootstrap/exec-tools.ts +2 -2
  545. package/src/resources/extensions/gsd/bootstrap/register-extension.ts +24 -0
  546. package/src/resources/extensions/gsd/bootstrap/register-hooks.ts +270 -37
  547. package/src/resources/extensions/gsd/bootstrap/write-gate.ts +368 -78
  548. package/src/resources/extensions/gsd/branch-patterns.ts +3 -0
  549. package/src/resources/extensions/gsd/browser-daemon-auto-prep.ts +108 -0
  550. package/src/resources/extensions/gsd/browser-evidence.ts +18 -2
  551. package/src/resources/extensions/gsd/captures.ts +5 -16
  552. package/src/resources/extensions/gsd/closeout-recovery.ts +2 -1
  553. package/src/resources/extensions/gsd/closeout-wizard.ts +102 -0
  554. package/src/resources/extensions/gsd/commands/catalog.ts +6 -68
  555. package/src/resources/extensions/gsd/commands/context.ts +16 -2
  556. package/src/resources/extensions/gsd/commands-handlers.ts +46 -3
  557. package/src/resources/extensions/gsd/commands-mcp-status.ts +2 -2
  558. package/src/resources/extensions/gsd/commands-workflow-templates.ts +11 -4
  559. package/src/resources/extensions/gsd/consent-question.ts +431 -0
  560. package/src/resources/extensions/gsd/consent-verdict.ts +86 -0
  561. package/src/resources/extensions/gsd/constants.ts +0 -3
  562. package/src/resources/extensions/gsd/crash-recovery.ts +13 -11
  563. package/src/resources/extensions/gsd/db/engine.ts +809 -0
  564. package/src/resources/extensions/gsd/db/queries.ts +519 -0
  565. package/src/resources/extensions/gsd/db/sql-constants.ts +12 -0
  566. package/src/resources/extensions/gsd/db/writers/cascades.ts +237 -0
  567. package/src/resources/extensions/gsd/db/writers/import-restore.ts +310 -0
  568. package/src/resources/extensions/gsd/db/writers/memory.ts +220 -0
  569. package/src/resources/extensions/gsd/db/writers/reconcile.ts +500 -0
  570. package/src/resources/extensions/gsd/db/writers/status.ts +88 -0
  571. package/src/resources/extensions/gsd/db-writer.ts +11 -19
  572. package/src/resources/extensions/gsd/dispatch-guard.ts +8 -31
  573. package/src/resources/extensions/gsd/doctor-engine-checks.ts +5 -4
  574. package/src/resources/extensions/gsd/doctor-environment.ts +272 -155
  575. package/src/resources/extensions/gsd/doctor-format.ts +12 -7
  576. package/src/resources/extensions/gsd/doctor-git-checks.ts +5 -22
  577. package/src/resources/extensions/gsd/doctor-runtime-checks.ts +22 -17
  578. package/src/resources/extensions/gsd/engine-hook-contract.ts +79 -0
  579. package/src/resources/extensions/gsd/error-classifier.ts +11 -0
  580. package/src/resources/extensions/gsd/exec-sandbox.ts +49 -9
  581. package/src/resources/extensions/gsd/files.ts +33 -12
  582. package/src/resources/extensions/gsd/git-service.ts +1 -0
  583. package/src/resources/extensions/gsd/gitignore.ts +3 -0
  584. package/src/resources/extensions/gsd/gsd-command-home.ts +13 -3
  585. package/src/resources/extensions/gsd/gsd-db.ts +176 -2375
  586. package/src/resources/extensions/gsd/guidance.ts +217 -0
  587. package/src/resources/extensions/gsd/guided-flow.ts +195 -29
  588. package/src/resources/extensions/gsd/health-widget.ts +91 -27
  589. package/src/resources/extensions/gsd/markdown-renderer.ts +11 -0
  590. package/src/resources/extensions/gsd/mcp-bridge.ts +39 -0
  591. package/src/resources/extensions/gsd/mcp-filter.ts +2 -23
  592. package/src/resources/extensions/gsd/mcp-tool-name.ts +6 -11
  593. package/src/resources/extensions/gsd/memory-consolidation-scanner.ts +1 -1
  594. package/src/resources/extensions/gsd/migrate/safety.ts +18 -7
  595. package/src/resources/extensions/gsd/migration-auto-check.ts +28 -3
  596. package/src/resources/extensions/gsd/milestone-closeout.ts +109 -24
  597. package/src/resources/extensions/gsd/milestone-planning-persistence.ts +2 -2
  598. package/src/resources/extensions/gsd/milestone-reopen-events.ts +3 -6
  599. package/src/resources/extensions/gsd/milestone-settlement.ts +2 -2
  600. package/src/resources/extensions/gsd/model-cost-table.ts +1 -0
  601. package/src/resources/extensions/gsd/model-router.ts +3 -0
  602. package/src/resources/extensions/gsd/notification-store.ts +26 -3
  603. package/src/resources/extensions/gsd/notifications.ts +13 -6
  604. package/src/resources/extensions/gsd/parallel-merge.ts +12 -9
  605. package/src/resources/extensions/gsd/parallel-monitor-overlay.ts +10 -7
  606. package/src/resources/extensions/gsd/parsers-legacy.ts +16 -4
  607. package/src/resources/extensions/gsd/paths.ts +42 -22
  608. package/src/resources/extensions/gsd/pre-execution-checks.ts +109 -3
  609. package/src/resources/extensions/gsd/preferences-models.ts +12 -47
  610. package/src/resources/extensions/gsd/preferences.ts +18 -0
  611. package/src/resources/extensions/gsd/projection-flush.ts +20 -0
  612. package/src/resources/extensions/gsd/prompts/complete-slice.md +4 -4
  613. package/src/resources/extensions/gsd/prompts/execute-task.md +3 -2
  614. package/src/resources/extensions/gsd/prompts/plan-milestone.md +1 -1
  615. package/src/resources/extensions/gsd/prompts/plan-slice.md +2 -2
  616. package/src/resources/extensions/gsd/prompts/quick-task.md +1 -1
  617. package/src/resources/extensions/gsd/prompts/reassess-roadmap.md +1 -1
  618. package/src/resources/extensions/gsd/prompts/refine-slice.md +2 -2
  619. package/src/resources/extensions/gsd/prompts/replan-slice.md +2 -2
  620. package/src/resources/extensions/gsd/prompts/research-milestone.md +1 -1
  621. package/src/resources/extensions/gsd/prompts/research-slice.md +1 -1
  622. package/src/resources/extensions/gsd/prompts/rewrite-docs.md +1 -1
  623. package/src/resources/extensions/gsd/prompts/run-uat.md +9 -5
  624. package/src/resources/extensions/gsd/prompts/system.md +5 -2
  625. package/src/resources/extensions/gsd/prompts/triage-captures.md +1 -1
  626. package/src/resources/extensions/gsd/prompts/validate-milestone.md +1 -1
  627. package/src/resources/extensions/gsd/prompts/workflow-start.md +2 -1
  628. package/src/resources/extensions/gsd/provider-error-guidance.ts +4 -9
  629. package/src/resources/extensions/gsd/provider-switch-observer.ts +1 -1
  630. package/src/resources/extensions/gsd/publication.ts +122 -0
  631. package/src/resources/extensions/gsd/reactive-graph.ts +11 -1
  632. package/src/resources/extensions/gsd/recovery-classification.ts +47 -88
  633. package/src/resources/extensions/gsd/roadmap-slices.ts +28 -3
  634. package/src/resources/extensions/gsd/safety/destructive-confirmation.ts +134 -0
  635. package/src/resources/extensions/gsd/safety/evidence-collector.ts +36 -4
  636. package/src/resources/extensions/gsd/safety/evidence-cross-ref.ts +7 -2
  637. package/src/resources/extensions/gsd/safety/file-change-validator.ts +14 -0
  638. package/src/resources/extensions/gsd/session-lock.ts +1 -1
  639. package/src/resources/extensions/gsd/skill-activation.ts +3 -6
  640. package/src/resources/extensions/gsd/state-transition-matrix.ts +42 -0
  641. package/src/resources/extensions/gsd/state.ts +16 -22
  642. package/src/resources/extensions/gsd/status-guards.ts +59 -8
  643. package/src/resources/extensions/gsd/stop-notice.ts +75 -0
  644. package/src/resources/extensions/gsd/tests/auto-abort-pause-regression.test.ts +1 -1
  645. package/src/resources/extensions/gsd/tests/auto-blocked-remediation-message.test.ts +1 -1
  646. package/src/resources/extensions/gsd/tests/auto-loop.test.ts +329 -22
  647. package/src/resources/extensions/gsd/tests/auto-model-selection.test.ts +97 -1
  648. package/src/resources/extensions/gsd/tests/auto-orchestrator.test.ts +273 -37
  649. package/src/resources/extensions/gsd/tests/auto-pause-double-entry-guard.test.ts +1 -1
  650. package/src/resources/extensions/gsd/tests/auto-paused-ui-cleanup.test.ts +54 -1
  651. package/src/resources/extensions/gsd/tests/auto-phases-lifecycle.test.ts +2 -1
  652. package/src/resources/extensions/gsd/tests/auto-post-unit-evidence-crossref-4909.test.ts +46 -0
  653. package/src/resources/extensions/gsd/tests/auto-remote-session-lock-cleanup.test.ts +65 -3
  654. package/src/resources/extensions/gsd/tests/auto-start-orphan-bootstrap.test.ts +236 -0
  655. package/src/resources/extensions/gsd/tests/auto-unit-closeout.test.ts +169 -1
  656. package/src/resources/extensions/gsd/tests/auto-worktree-registry.test.ts +2 -2
  657. package/src/resources/extensions/gsd/tests/auto-worktree-repair.test.ts +4 -2
  658. package/src/resources/extensions/gsd/tests/blocked-models.test.ts +19 -0
  659. package/src/resources/extensions/gsd/tests/browser-automation-contract-fixture.ts +39 -0
  660. package/src/resources/extensions/gsd/tests/browser-contract.test.ts +44 -0
  661. package/src/resources/extensions/gsd/tests/browser-daemon-auto-prep.test.ts +144 -0
  662. package/src/resources/extensions/gsd/tests/checkout-branch-stash-guard.test.ts +66 -1
  663. package/src/resources/extensions/gsd/tests/clear-stale-autostart.test.ts +44 -0
  664. package/src/resources/extensions/gsd/tests/commands-verdict.test.ts +8 -7
  665. package/src/resources/extensions/gsd/tests/complete-slice-verification-gate.test.ts +42 -0
  666. package/src/resources/extensions/gsd/tests/complete-task.test.ts +141 -5
  667. package/src/resources/extensions/gsd/tests/consent-question.test.ts +351 -0
  668. package/src/resources/extensions/gsd/tests/custom-verify-retry-store.test.ts +67 -0
  669. package/src/resources/extensions/gsd/tests/db-writer.test.ts +15 -4
  670. package/src/resources/extensions/gsd/tests/deep-project-auto-loop.test.ts +12 -11
  671. package/src/resources/extensions/gsd/tests/derive-state-helpers.test.ts +36 -0
  672. package/src/resources/extensions/gsd/tests/destructive-confirmation.test.ts +303 -0
  673. package/src/resources/extensions/gsd/tests/discuss-routing-fixes.test.ts +12 -2
  674. package/src/resources/extensions/gsd/tests/dispatch-history.test.ts +328 -0
  675. package/src/resources/extensions/gsd/tests/dispatch-run-uat-browser-tools.test.ts +2 -1
  676. package/src/resources/extensions/gsd/tests/dist-redirect.mjs +8 -0
  677. package/src/resources/extensions/gsd/tests/doctor-git-checks-terminal.test.ts +73 -0
  678. package/src/resources/extensions/gsd/tests/dynamic-bash-no-cap.test.ts +132 -0
  679. package/src/resources/extensions/gsd/tests/engine-hook-contract.test.ts +148 -0
  680. package/src/resources/extensions/gsd/tests/engine-interfaces-contract.test.ts +117 -91
  681. package/src/resources/extensions/gsd/tests/ensure-db-open.test.ts +113 -0
  682. package/src/resources/extensions/gsd/tests/evidence-xref-gsd-exec.test.ts +157 -0
  683. package/src/resources/extensions/gsd/tests/exec-graceful-kill.test.ts +193 -0
  684. package/src/resources/extensions/gsd/tests/exec-tool.test.ts +29 -1
  685. package/src/resources/extensions/gsd/tests/extension-bootstrap-isolation.test.ts +35 -1
  686. package/src/resources/extensions/gsd/tests/file-change-validator.test.ts +33 -1
  687. package/src/resources/extensions/gsd/tests/gsd-command-home.test.ts +120 -0
  688. package/src/resources/extensions/gsd/tests/gsd-db.test.ts +27 -0
  689. package/src/resources/extensions/gsd/tests/guidance.test.ts +148 -0
  690. package/src/resources/extensions/gsd/tests/guided-dispatch-root.test.ts +18 -6
  691. package/src/resources/extensions/gsd/tests/integration/auto-worktree-milestone-merge.test.ts +58 -15
  692. package/src/resources/extensions/gsd/tests/integration/auto-worktree.test.ts +89 -59
  693. package/src/resources/extensions/gsd/tests/integration/doctor-environment-async.test.ts +104 -0
  694. package/src/resources/extensions/gsd/tests/integration/git-service.test.ts +3 -2
  695. package/src/resources/extensions/gsd/tests/integration/gsd-integration-fixture.ts +80 -0
  696. package/src/resources/extensions/gsd/tests/integration/run-uat.test.ts +217 -0
  697. package/src/resources/extensions/gsd/tests/journal-integration.test.ts +47 -16
  698. package/src/resources/extensions/gsd/tests/mcp-project-config.test.ts +3 -1
  699. package/src/resources/extensions/gsd/tests/mcp-readiness-preflight.test.ts +205 -0
  700. package/src/resources/extensions/gsd/tests/mcp-status.test.ts +6 -5
  701. package/src/resources/extensions/gsd/tests/migration-auto-check.test.ts +85 -1
  702. package/src/resources/extensions/gsd/tests/milestone-closeout.test.ts +95 -4
  703. package/src/resources/extensions/gsd/tests/milestone-merge-stash-restore.test.ts +1 -1
  704. package/src/resources/extensions/gsd/tests/milestone-report-path.test.ts +1 -1
  705. package/src/resources/extensions/gsd/tests/milestone-settlement.test.ts +92 -0
  706. package/src/resources/extensions/gsd/tests/milestone-transition-state-rebuild.test.ts +1 -1
  707. package/src/resources/extensions/gsd/tests/model-unittype-mapping.test.ts +32 -1
  708. package/src/resources/extensions/gsd/tests/notification-store.test.ts +32 -0
  709. package/src/resources/extensions/gsd/tests/notifications.test.ts +64 -9
  710. package/src/resources/extensions/gsd/tests/oauth-api-model-routing.test.ts +167 -0
  711. package/src/resources/extensions/gsd/tests/parallel-research-dispatch.test.ts +18 -0
  712. package/src/resources/extensions/gsd/tests/parallel-skill-prompt-integration.test.ts +2 -2
  713. package/src/resources/extensions/gsd/tests/parsers-legacy-importers.test.ts +143 -0
  714. package/src/resources/extensions/gsd/tests/phases-merge-error-stops-auto.test.ts +1 -1
  715. package/src/resources/extensions/gsd/tests/phases-terminal-complete-idempotent.test.ts +242 -0
  716. package/src/resources/extensions/gsd/tests/plan-gate-failed-doctor-heal-hint.test.ts +3 -3
  717. package/src/resources/extensions/gsd/tests/post-exec-retry-bypass.test.ts +63 -2
  718. package/src/resources/extensions/gsd/tests/pre-execution-checks.test.ts +193 -1
  719. package/src/resources/extensions/gsd/tests/prompt-contracts.test.ts +10 -2
  720. package/src/resources/extensions/gsd/tests/prompt-db.test.ts +124 -6
  721. package/src/resources/extensions/gsd/tests/provider-error-guidance.test.ts +3 -3
  722. package/src/resources/extensions/gsd/tests/provider-errors.test.ts +2 -4
  723. package/src/resources/extensions/gsd/tests/publication.test.ts +120 -0
  724. package/src/resources/extensions/gsd/tests/recovery-classification-illegal-transition.test.ts +30 -0
  725. package/src/resources/extensions/gsd/tests/register-hooks-depth-verification.test.ts +248 -1
  726. package/src/resources/extensions/gsd/tests/remote-notification-from-desktop.test.ts +31 -81
  727. package/src/resources/extensions/gsd/tests/roadmap-slices.test.ts +68 -0
  728. package/src/resources/extensions/gsd/tests/runtime-invariant-modules.test.ts +27 -2
  729. package/src/resources/extensions/gsd/tests/safety-harness-false-positives.test.ts +38 -0
  730. package/src/resources/extensions/gsd/tests/session-switch-clears-pending-autostart.test.ts +108 -0
  731. package/src/resources/extensions/gsd/tests/single-writer-invariant.test.ts +43 -6
  732. package/src/resources/extensions/gsd/tests/skill-activation.test.ts +20 -17
  733. package/src/resources/extensions/gsd/tests/start-auto-detached.test.ts +7 -3
  734. package/src/resources/extensions/gsd/tests/state-transition-matrix.test.ts +36 -0
  735. package/src/resources/extensions/gsd/tests/status-guards.test.ts +38 -0
  736. package/src/resources/extensions/gsd/tests/stop-auto-race-null-unit.test.ts +1 -1
  737. package/src/resources/extensions/gsd/tests/stop-notice.test.ts +70 -0
  738. package/src/resources/extensions/gsd/tests/teardown-chdir-failure-clears-registry.test.ts +17 -0
  739. package/src/resources/extensions/gsd/tests/token-tool-gating.test.ts +80 -2
  740. package/src/resources/extensions/gsd/tests/tool-invocation-error-loop-break.test.ts +8 -0
  741. package/src/resources/extensions/gsd/tests/tool-surface-readiness.test.ts +329 -0
  742. package/src/resources/extensions/gsd/tests/tool-unavailable-retry.test.ts +33 -0
  743. package/src/resources/extensions/gsd/tests/transport-gate-double-complete.test.ts +139 -0
  744. package/src/resources/extensions/gsd/tests/uat-policy.test.ts +112 -29
  745. package/src/resources/extensions/gsd/tests/unit-closeout.test.ts +209 -0
  746. package/src/resources/extensions/gsd/tests/unit-context-composer.test.ts +67 -2
  747. package/src/resources/extensions/gsd/tests/unit-registry.test.ts +163 -0
  748. package/src/resources/extensions/gsd/tests/uok-audit-unified.test.ts +8 -0
  749. package/src/resources/extensions/gsd/tests/uok-plan-v2-wiring.test.ts +1 -1
  750. package/src/resources/extensions/gsd/tests/verification-verdict.test.ts +2 -0
  751. package/src/resources/extensions/gsd/tests/web-app-uat.test.ts +44 -1
  752. package/src/resources/extensions/gsd/tests/workflow-events.test.ts +19 -0
  753. package/src/resources/extensions/gsd/tests/workflow-mcp-readiness-cache.test.ts +119 -0
  754. package/src/resources/extensions/gsd/tests/workflow-mcp.test.ts +67 -4
  755. package/src/resources/extensions/gsd/tests/workflow-phase-contract-matrix.test.ts +332 -0
  756. package/src/resources/extensions/gsd/tests/workflow-reconcile.test.ts +20 -0
  757. package/src/resources/extensions/gsd/tests/workflow-templates.test.ts +92 -0
  758. package/src/resources/extensions/gsd/tests/workflow-tool-executors.test.ts +275 -40
  759. package/src/resources/extensions/gsd/tests/worktree-health-dispatch.test.ts +1 -1
  760. package/src/resources/extensions/gsd/tests/worktree-lifecycle.test.ts +41 -4
  761. package/src/resources/extensions/gsd/tests/worktree-manager.test.ts +22 -1
  762. package/src/resources/extensions/gsd/tests/worktree-placement.test.ts +113 -0
  763. package/src/resources/extensions/gsd/tests/worktree-project-root-degrade.test.ts +1 -1
  764. package/src/resources/extensions/gsd/tests/worktree-reentry.test.ts +1 -1
  765. package/src/resources/extensions/gsd/tests/worktree-safety-phase.test.ts +100 -0
  766. package/src/resources/extensions/gsd/tests/worktree-safety.test.ts +75 -1
  767. package/src/resources/extensions/gsd/tests/worktree-symlink-removal.test.ts +12 -6
  768. package/src/resources/extensions/gsd/tests/worktree-teardown-safety.test.ts +24 -2
  769. package/src/resources/extensions/gsd/tests/worktree.test.ts +18 -0
  770. package/src/resources/extensions/gsd/tests/write-gate-seam.test.ts +358 -0
  771. package/src/resources/extensions/gsd/tests/write-gate.test.ts +109 -1
  772. package/src/resources/extensions/gsd/tool-contract.ts +38 -3
  773. package/src/resources/extensions/gsd/tool-presentation-plan.ts +4 -4
  774. package/src/resources/extensions/gsd/tool-surface-readiness.ts +183 -0
  775. package/src/resources/extensions/gsd/tools/complete-milestone.ts +3 -2
  776. package/src/resources/extensions/gsd/tools/complete-slice.ts +45 -70
  777. package/src/resources/extensions/gsd/tools/complete-task.ts +90 -2
  778. package/src/resources/extensions/gsd/tools/exec-tool.ts +9 -8
  779. package/src/resources/extensions/gsd/tools/plan-slice.ts +14 -8
  780. package/src/resources/extensions/gsd/tools/plan-task.ts +2 -2
  781. package/src/resources/extensions/gsd/tools/reassess-roadmap.ts +2 -2
  782. package/src/resources/extensions/gsd/tools/reopen-milestone.ts +13 -40
  783. package/src/resources/extensions/gsd/tools/reopen-slice.ts +16 -44
  784. package/src/resources/extensions/gsd/tools/reopen-task.ts +2 -2
  785. package/src/resources/extensions/gsd/tools/replan-slice.ts +2 -2
  786. package/src/resources/extensions/gsd/tools/skip-slice.ts +18 -44
  787. package/src/resources/extensions/gsd/tools/workflow-tool-executors.ts +81 -2
  788. package/src/resources/extensions/gsd/uat-policy.ts +62 -16
  789. package/src/resources/extensions/gsd/undo.ts +9 -8
  790. package/src/resources/extensions/gsd/unit-closeout.ts +201 -0
  791. package/src/resources/extensions/gsd/unit-context-composer.ts +111 -1
  792. package/src/resources/extensions/gsd/unit-context-manifest.ts +4 -28
  793. package/src/resources/extensions/gsd/unit-registry.ts +442 -0
  794. package/src/resources/extensions/gsd/unit-tool-contracts.ts +27 -192
  795. package/src/resources/extensions/gsd/verdict-parser.ts +1 -1
  796. package/src/resources/extensions/gsd/verification-verdict.ts +4 -2
  797. package/src/resources/extensions/gsd/web-app-uat.ts +51 -8
  798. package/src/resources/extensions/gsd/workflow-event-ledger.ts +131 -0
  799. package/src/resources/extensions/gsd/workflow-event-vocabulary.ts +59 -0
  800. package/src/resources/extensions/gsd/workflow-events.ts +12 -20
  801. package/src/resources/extensions/gsd/workflow-mcp-auto-prep.ts +2 -0
  802. package/src/resources/extensions/gsd/workflow-mcp-readiness-cache.ts +150 -0
  803. package/src/resources/extensions/gsd/workflow-reconcile.ts +29 -62
  804. package/src/resources/extensions/gsd/workflow-tool-surface.ts +4 -1
  805. package/src/resources/extensions/gsd/worktree-git-recovery.ts +314 -0
  806. package/src/resources/extensions/gsd/worktree-lifecycle.ts +13 -9
  807. package/src/resources/extensions/gsd/worktree-manager.ts +53 -29
  808. package/src/resources/extensions/gsd/worktree-placement.ts +63 -0
  809. package/src/resources/extensions/gsd/worktree-reentry.ts +10 -7
  810. package/src/resources/extensions/gsd/worktree-root.ts +29 -6
  811. package/src/resources/extensions/gsd/worktree-safety.ts +49 -44
  812. package/src/resources/extensions/gsd/worktree-session-state.ts +11 -11
  813. package/src/resources/extensions/gsd/worktree.ts +7 -1
  814. package/src/resources/extensions/mcp-client/manager.ts +7 -1
  815. package/src/resources/extensions/search-the-web/native-search.ts +5 -3
  816. package/src/resources/extensions/shared/browser-contract.ts +66 -0
  817. package/src/resources/extensions/shared/gsd-browser-cli.ts +141 -6
  818. package/src/resources/shared/gsd-browser-path-sync.ts +273 -0
  819. package/src/resources/shared/package-manager-detection.ts +1 -1
  820. package/src/resources/shared/package.json +3 -0
  821. package/src/resources/skills/create-skill/SKILL.md +3 -0
  822. package/src/resources/skills/create-skill/references/executable-code.md +1 -1
  823. package/src/resources/skills/create-skill/references/skill-structure.md +1 -0
  824. package/src/resources/skills/create-skill/workflows/add-reference.md +8 -3
  825. package/src/resources/skills/create-skill/workflows/add-script.md +4 -2
  826. package/src/resources/skills/create-skill/workflows/add-template.md +3 -1
  827. package/src/resources/skills/create-skill/workflows/add-workflow.md +8 -3
  828. package/src/resources/skills/create-skill/workflows/upgrade-to-router.md +10 -5
  829. package/src/resources/skills/create-skill/workflows/verify-skill.md +9 -4
  830. package/src/resources/skills/spike-wrap-up/SKILL.md +9 -9
  831. package/dist/resources/extensions/gsd/user-input-boundary.js +0 -218
  832. package/dist/resources/skills/gsd-browser/SKILL.md +0 -41
  833. package/src/resources/extensions/gsd/tests/user-input-boundary.test.ts +0 -173
  834. package/src/resources/extensions/gsd/user-input-boundary.ts +0 -216
  835. package/src/resources/skills/gsd-browser/SKILL.md +0 -41
  836. /package/dist/web/standalone/.next/static/{DUFWcMFRH3iXh7d2fbrOF → avEtvPrImYTq2gGe-hVNp}/_buildManifest.js +0 -0
  837. /package/dist/web/standalone/.next/static/{DUFWcMFRH3iXh7d2fbrOF → avEtvPrImYTq2gGe-hVNp}/_ssgManifest.js +0 -0
@@ -1,1406 +1,26 @@
1
1
  // Project/App: gsd-pi
2
- // File Purpose: Auto-loop pipeline phases, merge closeout, and finalize handling.
2
+ // File Purpose: Auto-loop pipeline phases compatibility shim.
3
3
  /**
4
4
  * auto/phases.ts — Pipeline phases for the auto-loop.
5
5
  *
6
- * Contains: runPreDispatch, runDispatch, runGuards, runUnitPhase, runFinalize,
7
- * plus internal helpers generateMilestoneReport and closeoutAndStop.
8
- *
9
- * Imports from: auto/types, auto/detect-stuck, auto/run-unit, auto/loop-deps
6
+ * This file is now a thin compatibility shim. The implementation lives in
7
+ * focused modules (pre-dispatch, dispatch, unit-phase, finalize, closeout)
8
+ * and in the shared helpers (phase-helpers, worktree-safety-phase).
10
9
  */
11
- import { importExtensionModule } from "@gsd/pi-coding-agent";
12
- import { USER_DRIVEN_DEEP_UNITS, isAwaitingUserInput, } from "../auto-post-unit.js";
13
- import { lastAssistantText } from "../user-input-boundary.js";
14
- import { MAX_RECOVERY_CHARS, BUDGET_THRESHOLDS, MAX_FINALIZE_TIMEOUTS, } from "./types.js";
15
- import { detectStuck } from "./detect-stuck.js";
16
- import { runUnit } from "./run-unit.js";
10
+ import { basename } from "node:path";
17
11
  import { debugLog } from "../debug-logger.js";
18
- import { resolveWorktreeProjectRoot, normalizeWorktreePathForCompare } from "../worktree-root.js";
19
- import { buildManualValidationGuidance } from "../worktree-manager.js";
20
- import { relSliceFile } from "../paths.js";
21
- import { classifyProject } from "../detection.js";
22
- import { MergeConflictError } from "../git-service.js";
23
- import { setCurrentPhase, clearCurrentPhase } from "../../shared/gsd-phase-state.js";
24
- import { pauseAutoForProviderError } from "../provider-error-pause.js";
25
- import { resumeAutoAfterProviderDelay } from "../bootstrap/provider-error-resume.js";
26
- import { join, basename } from "node:path";
27
- import { existsSync, cpSync } from "node:fs";
28
- import { logWarning, logError, _resetLogs, drainLogs, drainAndSummarize, formatForNotification, hasAnyIssues, } from "../workflow-logger.js";
29
- import { gsdRoot, normalizeRealPath } from "../paths.js";
30
- import { atomicWriteSync } from "../atomic-write.js";
31
- import { verifyExpectedArtifact, diagnoseExpectedArtifact, buildLoopRemediationSteps, refreshRecoveryDbForArtifact } from "../auto-recovery.js";
32
- import { writeUnitRuntimeRecord } from "../unit-runtime.js";
33
- import { withTimeout, FINALIZE_PRE_TIMEOUT_MS, FINALIZE_POST_TIMEOUT_MS } from "./finalize-timeout.js";
34
- import { getEligibleSlices } from "../slice-parallel-eligibility.js";
35
- import { isSliceParallelActive, startSliceParallel } from "../slice-parallel-orchestrator.js";
36
- import { isDbAvailable, getMilestoneSlices, getSlice, getTask } from "../gsd-db.js";
37
- import { refreshWorkflowDatabaseFromDisk } from "../db-workspace.js";
38
- import { isClosedStatus } from "../status-guards.js";
39
- import { setRuntimeKv } from "../db/runtime-kv.js";
40
- import { getLatestForUnit } from "../db/unit-dispatches.js";
41
- import { reconcileBeforeSpawn } from "../state-reconciliation.js";
42
- import { countUnmappedActiveRequirements, formatCompletePhaseNextAction, } from "../requirements-backlog.js";
43
- import { ensurePlanV2Graph, isEmptyPlanV2GraphResult, isMissingFinalizedContextResult } from "../uok/plan-v2.js";
44
- import { resolveUokFlags } from "../uok/flags.js";
45
- import { UokGateRunner } from "../uok/gate-runner.js";
46
- import { resetEvidence, loadEvidenceFromDisk } from "../safety/evidence-collector.js";
47
- import { parseUnitId } from "../unit-id.js";
48
- import { createCheckpoint, cleanupCheckpoint, rollbackToCheckpoint } from "../safety/git-checkpoint.js";
49
- import { resolveSafetyHarnessConfig } from "../safety/safety-harness.js";
12
+ import { logWarning } from "../workflow-logger.js";
50
13
  import { getContextPauseAction } from "../auto-budget.js";
51
- import { getWorkflowTransportSupportError, getRequiredWorkflowToolsForAutoUnit, supportsStructuredQuestions, } from "../workflow-mcp.js";
52
- import { prepareWorkflowMcpForProject } from "../workflow-mcp-auto-prep.js";
53
- import { applyThinkingLevelForModel, floorThinkingLevelForUnit, getRegisteredToolSnapshot, getToolBaselineSnapshot, } from "../auto-model-selection.js";
54
- import { resolveManifest } from "../unit-context-manifest.js";
55
- import { createWorktreeSafetyModule } from "../worktree-safety.js";
56
- import { isSuspiciousGhostCompletion } from "../auto-unit-closeout.js";
57
- import { decideVerificationRetry, verificationRetryKey } from "./verification-retry-policy.js";
58
- import { buildPhaseHandoffOutcome, setAutoActiveStatus, setAutoOutcomeWidget } from "../auto-dashboard.js";
59
- import { getConsecutiveDispatchBlocker } from "../dispatch-guard.js";
60
- import { captureRootDirtySnapshot, detectRootWriteLeak, formatRootWriteLeakMessage, } from "../root-write-leak-guard.js";
61
- import { classifyError, isTransient } from "../error-classifier.js";
62
- export const STUCK_WINDOW_SIZE = 6;
63
- const STUCK_RECOVERY_ATTEMPTS_KEY = "stuck_recovery_attempts";
64
- const ZERO_TOOL_PROVIDER_ERROR_PREFIX_RE = /^(?:api error(?::|$|\s*\()|provider error(?::|$|\s*\()|request failed\b|(?:http\s*)?(?:429|500|502|503)\b|\b(?:econnreset|etimedout|econnrefused|epipe)\b|socket hang up\b|fetch failed\b|(?:network|connection|server) error(?::|$)|connection (?:reset|refused)(?::|$|\s+by\b)|dns\b.*(?:fail|error|timeout)|unexpected eof\b|stream idle timeout\b|partial response received\b|stream_exhausted\b|terminated(?::|$)|(?:connection|stream|request)\b.{0,40}\bterminated\b|other side closed\b|rate.?limit(?:ed| exceeded| reached| error)|too many requests\b|you(?:'ve| have) (?:hit|reached) your (?:\w+ )?limit\b|.*\b(?:usage|session|weekly|daily|monthly|quota) limit\b|limit\b.{0,40}\bresets?\b|out of extra usage\b|service.?unavailable\b|internal(?: server)? error(?::|$)|internal(?:[_-]server)?[_-]error\b|server[_-]error\b|(?:provider|server|api|model|codex|claude|openai|anthropic|gemini)\b.{0,80}\boverloaded\b|overloaded\b.{0,80}\b(?:provider|server|api|model)\b|context (?:window|length) exceed|context window exceed)/i;
65
- const ZERO_TOOL_PROVIDER_ERROR_SIGNAL_RE = /(?:\b(?:http|status(?: code)?|code|error:)\s*(?:429|500|502|503)\b|\b(?:api|provider) error\s*[:(]?\s*(?:429|500|502|503)\b|\b(?:typeerror|error):\s*(?:fetch failed\b|socket hang up\b|terminated(?::|$)|connection (?:reset|refused)(?::|$|\s+by\b)|(?:network|connection|server) error(?::|$)|stream idle timeout\b|partial response received\b|unexpected eof\b)|\b(?:server_error|api_error|stream_exhausted(?:_without_result)?)\b|\b(?:econnreset|etimedout|econnrefused|epipe)\b|context (?:window|length) exceed|context window exceed)/i;
66
- function classifyZeroToolProviderMessage(message) {
67
- const firstLine = message.trim().split(/\r?\n/, 1)[0]?.trim() ?? "";
68
- if (!firstLine ||
69
- (!ZERO_TOOL_PROVIDER_ERROR_PREFIX_RE.test(firstLine) &&
70
- !ZERO_TOOL_PROVIDER_ERROR_SIGNAL_RE.test(firstLine)))
71
- return null;
72
- return classifyError(firstLine);
73
- }
74
- export const _classifyZeroToolProviderMessageForTest = classifyZeroToolProviderMessage;
75
- export function resolveDispatchRecoveryAttempts(unitRecoveryCount, unitType, unitId) {
76
- return (unitRecoveryCount.get(`${unitType}/${unitId}`) ?? 0) > 0
77
- ? 0
78
- : undefined;
79
- }
80
- // ─── Path Comparison Helper ───────────────────────────────────────────────
81
- /** Compare two paths for physical identity, tolerating trailing slashes and symlinks. */
82
- function isSamePathLocal(a, b) {
83
- return normalizeWorktreePathForCompare(a) === normalizeWorktreePathForCompare(b);
84
- }
85
- function isIsolatedWorktreeSession(s) {
86
- return Boolean(s.originalBasePath)
87
- && Boolean(s.basePath)
88
- && !isSamePathLocal(s.originalBasePath, s.basePath);
89
- }
90
- function persistStuckRecoveryAttempts(s, loopState) {
91
- const scopeId = normalizeRealPath(s.scope?.workspace.projectRoot ?? (s.originalBasePath || s.basePath));
92
- if (!scopeId)
93
- return;
94
- try {
95
- setRuntimeKv("global", scopeId, STUCK_RECOVERY_ATTEMPTS_KEY, loopState.stuckRecoveryAttempts);
96
- }
97
- catch (err) {
98
- debugLog("autoLoop", {
99
- phase: "save-stuck-state-failed",
100
- error: err instanceof Error ? err.message : String(err),
101
- });
102
- }
103
- }
104
- async function applyVerificationRetryPolicy(ic, unitType, phase) {
105
- const { ctx, pi, s, deps } = ic;
106
- const retryInfo = s.pendingVerificationRetry;
107
- const key = unitType && retryInfo
108
- ? verificationRetryKey(unitType, retryInfo.unitId)
109
- : undefined;
110
- const decision = decideVerificationRetry({
111
- unitType,
112
- retryInfo,
113
- previousFailureHash: key ? s.verificationRetryFailureHashes.get(key) : undefined,
114
- });
115
- if (decision.action === "pause") {
116
- s.pendingVerificationRetry = null;
117
- debugLog("autoLoop", {
118
- phase: `${phase}-paused`,
119
- reason: decision.reason,
120
- unitType,
121
- unitId: retryInfo?.unitId,
122
- failureHash: decision.failureHash,
123
- });
124
- ctx.ui.notify(decision.reason === "duplicate-failure-context"
125
- ? `Verification retry for ${unitType ?? "unit"} ${retryInfo?.unitId ?? "unknown"} produced the same failure context. Pausing auto-mode instead of re-dispatching.`
126
- : "Verification retry requested without retry context. Pausing auto-mode instead of re-dispatching.", "warning");
127
- await deps.pauseAuto(ctx, pi);
128
- return { action: "break", reason: decision.reason };
129
- }
130
- s.verificationRetryFailureHashes.set(decision.key, decision.failureHash);
131
- debugLog("autoLoop", {
132
- phase: `${phase}-backoff`,
133
- iteration: ic.iteration,
134
- unitType,
135
- unitId: retryInfo?.unitId,
136
- attempt: retryInfo?.attempt,
137
- delayMs: decision.delayMs,
138
- baseDelayMs: decision.baseDelayMs,
139
- failureHash: decision.failureHash,
140
- });
141
- await new Promise((resolve) => setTimeout(resolve, decision.delayMs));
142
- return null;
143
- }
144
- function rememberRetryDispatch(s, unit, iterData) {
145
- if (!unit)
146
- return;
147
- s.pendingVerificationRetryDispatch = {
148
- unitType: unit.type,
149
- unitId: unit.id,
150
- prompt: iterData.prompt,
151
- pauseAfterUatDispatch: iterData.pauseAfterUatDispatch,
152
- state: iterData.state,
153
- mid: iterData.mid,
154
- midTitle: iterData.midTitle,
155
- };
156
- }
157
- function getAlreadyClosedDispatchReason(unitType, unitId) {
158
- if (!isDbAvailable())
159
- return null;
160
- refreshWorkflowDatabaseFromDisk();
161
- const { milestone, slice, task } = parseUnitId(unitId);
162
- if (unitType === "execute-task" && milestone && slice && task) {
163
- const row = getTask(milestone, slice, task);
164
- return row && isClosedStatus(row.status)
165
- ? `execute-task ${unitId} is already ${row.status}`
166
- : null;
167
- }
168
- if (unitType === "complete-slice" && milestone && slice) {
169
- const row = getSlice(milestone, slice);
170
- return row && isClosedStatus(row.status)
171
- ? `complete-slice ${unitId} is already ${row.status}`
172
- : null;
173
- }
174
- return null;
175
- }
176
- export function shouldDegradeEmptyWorktreeToProjectRoot(worktreeClassification, projectRootClassification) {
177
- return (worktreeClassification.kind === "greenfield" &&
178
- projectRootClassification.kind !== "greenfield" &&
179
- projectRootClassification.kind !== "invalid-repo");
180
- }
181
- function unitWritesSource(unitType) {
182
- if (unitType.startsWith("hook/"))
183
- return false;
184
- // Backward compatibility: sidecar queues from older builds may persist
185
- // prefixed unit types (e.g. "sidecar/quick-task").
186
- const normalizedUnitType = unitType.startsWith("sidecar/")
187
- ? unitType.slice("sidecar/".length)
188
- : unitType;
189
- const manifest = resolveManifest(normalizedUnitType);
190
- if (!manifest)
191
- return null;
192
- return manifest.tools.mode === "all" || manifest.tools.mode === "docs";
193
- }
194
- function formatWorktreeSafetyFailure(result) {
195
- return `Worktree Safety failed (${result.kind}): ${result.reason} ${result.remediation}`;
196
- }
197
- function formatWorktreeSafetyStopReason(result) {
198
- if (result.kind === "empty-worktree-with-project-content") {
199
- return `Worktree Safety failed (${result.kind}). Run /gsd doctor fix, then /gsd auto.`;
200
- }
201
- return `Worktree Safety failed (${result.kind}).`;
202
- }
203
- function classifyBlocker(blocker) {
204
- const normalized = blocker.toLowerCase();
205
- if (normalized.includes("needs-remediation") && normalized.includes("all slices are complete")) {
206
- return "needs-remediation-dead-end";
207
- }
208
- return "other";
209
- }
210
- function sanitizeBlockerForUser(blocker) {
211
- return blocker.replaceAll("gsd_reassess_roadmap", "/gsd dispatch reassess");
212
- }
213
- /**
214
- * Formats blocked resume guidance for users, ensuring internal tool names are
215
- * never surfaced in notification text.
216
- */
217
- function formatBlockedResumeMessage(blockers) {
218
- const classifiedBlockers = blockers.map((blocker) => ({
219
- blocker: sanitizeBlockerForUser(blocker),
220
- kind: classifyBlocker(blocker),
221
- }));
222
- const hasNeedsRemediationDeadEnd = classifiedBlockers.some((classifiedBlocker) => classifiedBlocker.kind === "needs-remediation-dead-end");
223
- if (hasNeedsRemediationDeadEnd) {
224
- return "Blocked: milestone validation requires remediation but all slices are complete. Run /gsd dispatch reassess to add remediation slices, then /gsd auto to continue.";
225
- }
226
- return `Blocked: ${classifiedBlockers.map((classifiedBlocker) => classifiedBlocker.blocker).join(", ")}. Fix and run /gsd auto to resume.`;
227
- }
228
- function resolveEmptyWorktreeWithProjectContent(unitRoot, projectRoot) {
229
- if (isSamePathLocal(unitRoot, projectRoot))
230
- return false;
231
- const worktreeClassification = classifyProject(unitRoot);
232
- if (worktreeClassification.kind !== "greenfield")
233
- return false;
234
- const projectRootClassification = classifyProject(projectRoot);
235
- return shouldDegradeEmptyWorktreeToProjectRoot(worktreeClassification, projectRootClassification);
236
- }
237
- async function validateSourceWriteWorktreeSafety(ic, unitType, unitId, milestoneId, phase) {
238
- const { ctx, pi, s, deps } = ic;
239
- if (!s.basePath)
240
- return null;
241
- // Custom engine workflows (graph-driven, registered via run dirs) define
242
- // their own step ids that are not in the GSD UnitContextManifest. Don't
243
- // fail closed for those — the custom engine owns its own dispatch
244
- // contract. The fail-closed safety check applies only to built-in GSD
245
- // units whose Tool Contract is registered in the manifest. Use a truthy
246
- // check so undefined (test sessions that never set the field) routes
247
- // through the safety check, matching the regression test contract.
248
- if (s.activeEngineId)
249
- return null;
250
- const writesSource = unitWritesSource(unitType);
251
- if (writesSource === null) {
252
- const msg = `Worktree Safety failed (missing-tool-contract): missing Tool Contract for ${unitType}. Add a UnitContextManifest entry before dispatching this Unit.`;
253
- debugLog("worktreeSafety", {
254
- phase,
255
- unitType,
256
- unitId,
257
- milestoneId,
258
- result: { ok: false, kind: "missing-tool-contract", reason: msg },
259
- basePath: s.basePath,
260
- });
261
- ctx.ui.notify(msg, "error");
262
- await deps.stopAuto(ctx, pi, msg);
263
- return { action: "break", reason: "missing-tool-contract" };
264
- }
265
- if (!writesSource)
266
- return null;
267
- const projectRoot = s.canonicalProjectRoot ?? resolveWorktreeProjectRoot(s.basePath, s.originalBasePath);
268
- const isolationMode = deps.getIsolationMode(projectRoot);
269
- if (isolationMode !== "worktree")
270
- return null;
271
- const safety = createWorktreeSafetyModule();
272
- const result = safety.validateUnitRoot({
273
- unitType,
274
- unitId,
275
- writeScope: "source-writing",
276
- projectRoot,
277
- unitRoot: s.basePath,
278
- milestoneId,
279
- isolationMode,
280
- expectedBranch: milestoneId ? deps.autoWorktreeBranch(milestoneId) : null,
281
- emptyWorktreeWithProjectContent: resolveEmptyWorktreeWithProjectContent(s.basePath, projectRoot),
282
- lease: s.workerId
283
- ? {
284
- required: true,
285
- held: s.currentMilestoneId === milestoneId && s.milestoneLeaseToken !== null,
286
- owner: s.workerId,
287
- }
288
- : undefined,
289
- });
290
- if (result.ok)
291
- return null;
292
- const msg = formatWorktreeSafetyFailure(result);
293
- debugLog("worktreeSafety", {
294
- phase,
295
- unitType,
296
- unitId,
297
- milestoneId,
298
- result,
299
- basePath: s.basePath,
300
- projectRoot,
301
- });
302
- ctx.ui.notify(msg, "error");
303
- await deps.stopAuto(ctx, pi, formatWorktreeSafetyStopReason(result));
304
- return { action: "break", reason: result.kind };
305
- }
306
- // ─── Session timeout auto-resume state ────────────────────────────────────────
307
- let consecutiveSessionTimeouts = 0;
308
- const MAX_SESSION_TIMEOUT_AUTO_RESUMES = 3;
309
- /** Maximum zero-tool-call retries before pausing — context exhaustion is deterministic. */
310
- const MAX_ZERO_TOOL_RETRIES = 1;
311
- export function resetSessionTimeoutState() {
312
- consecutiveSessionTimeouts = 0;
313
- }
314
- // ─── generateMilestoneReport ──────────────────────────────────────────────────
315
- /**
316
- * Resolve the base path for milestone reports.
317
- * Prefers originalBasePath (project root) over basePath (which may be a worktree).
318
- * Exported for testing as _resolveReportBasePath.
319
- */
320
- export function _resolveReportBasePath(s) {
321
- return resolveWorktreeProjectRoot(s.basePath, s.originalBasePath);
322
- }
323
- /**
324
- * Resolve the authoritative project base for dispatch guards.
325
- * Prior-milestone completion lives at the project root, even when the active
326
- * unit is running inside an auto worktree.
327
- */
328
- export function _resolveDispatchGuardBasePath(s) {
329
- return resolveWorktreeProjectRoot(s.basePath, s.originalBasePath);
330
- }
331
- const PLAN_V2_GATE_PHASES = new Set([
332
- "executing",
333
- "summarizing",
334
- "validating-milestone",
335
- "completing-milestone",
336
- ]);
337
- export function shouldRunPlanV2Gate(phase) {
338
- return PLAN_V2_GATE_PHASES.has(phase);
339
- }
340
- export function _shouldProceedWithInvalidRepoClassificationForTest(reason, hasGit) {
341
- return reason === "missing .git" && hasGit;
342
- }
343
- export function _resolveCurrentUnitStartedAtForTest(currentUnit) {
344
- return currentUnit?.startedAt;
345
- }
346
- /**
347
- * Generate and write an HTML milestone report snapshot.
348
- * Extracted from the milestone-transition block in autoLoop.
349
- */
350
- async function generateMilestoneReport(s, ctx, milestoneId) {
351
- const { loadVisualizerData } = await importExtensionModule(import.meta.url, "../visualizer-data.js");
352
- const { generateHtmlReport } = await importExtensionModule(import.meta.url, "../export-html.js");
353
- const { writeReportSnapshot } = await importExtensionModule(import.meta.url, "../reports.js");
354
- const { basename } = await import("node:path");
355
- const reportBasePath = _resolveReportBasePath(s);
356
- const snapData = await loadVisualizerData(reportBasePath);
357
- const completedMs = snapData.milestones.find((m) => m.id === milestoneId);
358
- const msTitle = completedMs?.title ?? milestoneId;
359
- const gsdVersion = process.env.GSD_VERSION ?? "0.0.0";
360
- const projName = basename(reportBasePath);
361
- const doneSlices = snapData.milestones.reduce((acc, m) => acc + m.slices.filter((sl) => sl.done).length, 0);
362
- const totalSlices = snapData.milestones.reduce((acc, m) => acc + m.slices.length, 0);
363
- const outPath = writeReportSnapshot({
364
- basePath: reportBasePath,
365
- html: generateHtmlReport(snapData, {
366
- projectName: projName,
367
- projectPath: reportBasePath,
368
- gsdVersion,
369
- milestoneId,
370
- indexRelPath: "index.html",
371
- }),
372
- milestoneId,
373
- milestoneTitle: msTitle,
374
- kind: "milestone",
375
- projectName: projName,
376
- projectPath: reportBasePath,
377
- gsdVersion,
378
- totalCost: snapData.totals?.cost ?? 0,
379
- totalTokens: snapData.totals?.tokens.total ?? 0,
380
- totalDuration: snapData.totals?.duration ?? 0,
381
- doneSlices,
382
- totalSlices,
383
- doneMilestones: snapData.milestones.filter((m) => m.status === "complete").length,
384
- totalMilestones: snapData.milestones.length,
385
- phase: snapData.phase,
386
- });
387
- ctx.ui.notify(`Report saved: .gsd/reports/${basename(outPath)} — open index.html to browse progression.`, "info");
388
- }
389
- // ─── closeoutAndStop ──────────────────────────────────────────────────────────
390
- /**
391
- * If a unit is in-flight, close it out, then stop auto-mode.
392
- * Extracted from ~4 identical if-closeout-then-stop sequences in autoLoop.
393
- */
394
- async function closeoutAndStop(ctx, pi, s, deps, reason) {
395
- if (s.currentUnit) {
396
- await deps.closeoutUnit(ctx, s.basePath, s.currentUnit.type, s.currentUnit.id, s.currentUnit.startedAt, deps.buildSnapshotOpts(s.currentUnit.type, s.currentUnit.id));
397
- s.clearCurrentUnit();
398
- }
399
- await deps.stopAuto(ctx, pi, reason);
400
- }
401
- async function stopOnPostflightRecoveryNeeded(ic, result, milestoneId) {
402
- if (!result.needsManualRecovery)
403
- return null;
404
- const { ctx, pi, deps } = ic;
405
- const reason = `Post-merge stash restore failed for milestone ${milestoneId}`;
406
- ctx.ui.notify(`${reason}. Resolve the working tree before resuming auto-mode. ${result.message}`, "error");
407
- await deps.stopAuto(ctx, pi, reason);
408
- return { action: "break", reason: "postflight-stash-restore-failed" };
409
- }
410
- async function restorePreflightStashOrStop(ic, preflight, milestoneId) {
411
- if (!preflight.stashPushed)
412
- return null;
413
- const { ctx, s, deps } = ic;
414
- const result = deps.postflightPopStash(s.originalBasePath || s.basePath, milestoneId, preflight.stashMarker, ctx.ui.notify.bind(ctx.ui));
415
- return stopOnPostflightRecoveryNeeded(ic, result, milestoneId);
416
- }
417
- /**
418
- * Run a milestone merge surrounded by preflight stash + always-on postflight
419
- * pop. The previous code popped the stash only after a successful merge, which
420
- * leaked `gsd-preflight-stash:M00x:*` entries whenever `mergeAndExit` threw —
421
- * leaving the user's pre-merge working tree silently stashed away after a
422
- * merge-conflict or other merge error. This helper restores the stash on
423
- * every exit path, then surfaces the merge or stash failure (in priority
424
- * order) as the loop's stop reason.
425
- *
426
- * Returns a `break` action when auto-mode must stop, or `null` when the merge
427
- * succeeded and the stash (if any) was restored cleanly.
428
- */
429
- export async function _runMilestoneMergeWithStashRestore(ic, milestoneId, options = {}) {
430
- const { ctx, pi, s, deps } = ic;
431
- const preflight = deps.preflightCleanRoot(s.originalBasePath || s.basePath, milestoneId, ctx.ui.notify.bind(ctx.ui));
432
- if (preflight.blocked) {
433
- const reason = preflight.blockedReason === "unmerged-conflicts"
434
- ? `Pre-merge unresolved Git conflicts block milestone ${milestoneId}`
435
- : `Pre-merge dirty working tree overlaps milestone ${milestoneId}`;
436
- await deps.stopAuto(ctx, pi, reason, {
437
- preserveCompletedMilestoneBranch: true,
438
- preserveCloseoutTranscript: options.preserveCloseoutTranscript,
439
- });
440
- return {
441
- action: "break",
442
- reason: preflight.blockedReason === "unmerged-conflicts"
443
- ? "preflight-unmerged-conflicts"
444
- : "preflight-dirty-overlap",
445
- };
446
- }
447
- let mergeError = null;
448
- const exitResult = deps.lifecycle.exitMilestone(milestoneId, { merge: true }, ctx.ui);
449
- if (exitResult.ok) {
450
- s.milestoneMergedInPhases = true;
451
- try {
452
- const projectRoot = s.originalBasePath || s.canonicalProjectRoot || s.basePath;
453
- const { rebuildMarkdownProjectionsFromDb } = await import("../commands-maintenance.js");
454
- await rebuildMarkdownProjectionsFromDb(projectRoot);
455
- }
456
- catch (err) {
457
- logWarning("engine", `markdown projection rebuild after milestone merge failed: ${err instanceof Error ? err.message : String(err)}`);
458
- }
459
- }
460
- else {
461
- mergeError = exitResult.cause ?? new Error(`exit ${exitResult.reason}`);
462
- }
463
- // Always attempt to restore the stashed working tree, even on merge error.
464
- // postflightPopStash itself does not throw; failures surface via the
465
- // PostflightResult.needsManualRecovery flag.
466
- let stashResult = null;
467
- if (preflight.stashPushed) {
468
- stashResult = deps.postflightPopStash(s.originalBasePath || s.basePath, milestoneId, preflight.stashMarker, ctx.ui.notify.bind(ctx.ui));
469
- }
470
- // Merge failure takes priority over stash recovery — the merge is the
471
- // authoritative gate. If the stash also needed manual recovery, the user
472
- // already saw the postflightPopStash notify above.
473
- if (mergeError) {
474
- if (mergeError instanceof MergeConflictError) {
475
- // A merge conflict is a recoverable human checkpoint, not an
476
- // infrastructure failure — the user resolves the conflict and runs
477
- // `/gsd auto` to resume. Pause (don't stop): stopAuto tears down the
478
- // session and, because `milestoneMergedInPhases` stays false here,
479
- // re-runs the already-failed worktree merge in its cleanup step
480
- // (#2645), then drops the user out of the interactive TUI onto a
481
- // "stopped" surface.
482
- const conflictReason = `Merge conflict on milestone ${milestoneId}: ${mergeError.conflictedFiles.join(", ")}. Resolve conflicts manually and run /gsd auto to resume.`;
483
- ctx.ui.notify(conflictReason, "error");
484
- await deps.pauseAuto(ctx, pi, {
485
- message: conflictReason,
486
- category: "unknown",
487
- });
488
- return { action: "break", reason: "merge-conflict" };
489
- }
490
- logError("engine", "Milestone merge failed with non-conflict error", {
491
- milestone: milestoneId,
492
- error: String(mergeError),
493
- });
494
- // Like a merge conflict, a non-conflict merge failure (index lock,
495
- // network, permissions) is recoverable — the user fixes the cause and
496
- // runs `/gsd auto` to resume. Pause (don't stop) so the session stays
497
- // resumable and stopAuto's teardown does not re-run the failed merge.
498
- const mergeFailReason = `Merge error on milestone ${milestoneId}: ${mergeError instanceof Error ? mergeError.message : String(mergeError)}. Resolve and run /gsd auto to resume.`;
499
- ctx.ui.notify(mergeFailReason, "error");
500
- await deps.pauseAuto(ctx, pi, {
501
- message: mergeFailReason,
502
- category: "unknown",
503
- });
504
- return { action: "break", reason: "merge-failed" };
505
- }
506
- if (stashResult) {
507
- return stopOnPostflightRecoveryNeeded(ic, stashResult, milestoneId);
508
- }
509
- return null;
510
- }
511
- export async function _runMilestoneMergeOnceWithStashRestore(ic, milestoneId, options = {}) {
512
- if (ic.s.milestoneMergedInPhases) {
513
- debugLog("autoLoop", {
514
- phase: "milestone-merge-skip",
515
- reason: "already-merged-in-phases",
516
- milestoneId,
517
- });
518
- return null;
519
- }
520
- return _runMilestoneMergeWithStashRestore(ic, milestoneId, options);
521
- }
522
- async function emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, errorContext) {
523
- ic.deps.emitJournalEvent({
524
- ts: new Date().toISOString(),
525
- flowId: ic.flowId,
526
- seq: ic.nextSeq(),
527
- eventType: "unit-end",
528
- data: {
529
- unitType,
530
- unitId,
531
- status: "cancelled",
532
- artifactVerified: false,
533
- ...(errorContext ? { errorContext } : {}),
534
- },
535
- causedBy: { flowId: ic.flowId, seq: unitStartSeq },
536
- });
537
- }
538
- export function _buildCancelledUnitStopReason(unitType, unitId, errorContext) {
539
- const cancellationMessage = errorContext?.message ?? "unknown";
540
- const isSessionCreationFailure = errorContext?.category === "session-failed";
541
- if (isSessionCreationFailure) {
542
- return {
543
- notifyMessage: `Session creation failed for ${unitType} ${unitId}: ${cancellationMessage}. Stopping auto-mode.`,
544
- stopReason: `Session creation failed: ${cancellationMessage}`,
545
- loopReason: "session-failed",
546
- };
547
- }
548
- return {
549
- notifyMessage: `Unit ${unitType} ${unitId} aborted after dispatch: ${cancellationMessage}. Stopping auto-mode.`,
550
- stopReason: `Unit aborted: ${cancellationMessage}`,
551
- loopReason: "unit-aborted",
552
- };
553
- }
554
- export function _isPauseOriginCancelledResult(isPaused, errorContext) {
555
- return isPaused && !errorContext;
556
- }
557
- async function failClosedOnFinalizeTimeout(ic, iterData, loopState, stage, startedAt) {
558
- const { ctx, pi, s, deps } = ic;
559
- const now = Date.now();
560
- const unitType = iterData.unitType;
561
- const unitId = iterData.unitId;
562
- const timeoutMs = stage === "pre" ? FINALIZE_PRE_TIMEOUT_MS : FINALIZE_POST_TIMEOUT_MS;
563
- const progressKind = stage === "pre" ? "finalize-pre-timeout" : "finalize-post-timeout";
564
- writeUnitRuntimeRecord(s.basePath, unitType, unitId, startedAt, {
565
- phase: "finalize-timeout",
566
- timeoutAt: now,
567
- lastProgressAt: now,
568
- lastProgressKind: progressKind,
569
- });
570
- deps.emitJournalEvent({
571
- ts: new Date(now).toISOString(),
572
- flowId: ic.flowId,
573
- seq: ic.nextSeq(),
574
- eventType: "unit-end",
575
- data: {
576
- unitType,
577
- unitId,
578
- status: "timed-out-finalize",
579
- artifactVerified: false,
580
- finalizeStage: stage,
581
- },
582
- });
583
- loopState.consecutiveFinalizeTimeouts++;
584
- debugLog("autoLoop", {
585
- phase: progressKind,
586
- iteration: ic.iteration,
587
- unitType,
588
- unitId,
589
- consecutiveTimeouts: loopState.consecutiveFinalizeTimeouts,
590
- });
591
- ctx.ui.notify(`${stage === "pre" ? "postUnitPreVerification" : "postUnitPostVerification"} timed out after ${timeoutMs / 1000}s for ${unitType} ${unitId} (${loopState.consecutiveFinalizeTimeouts}/${MAX_FINALIZE_TIMEOUTS}) — pausing auto-mode for recovery.`, "warning");
592
- await deps.pauseAuto(ctx, pi);
593
- s.clearCurrentUnit();
594
- clearCurrentPhase();
595
- drainLogs();
596
- return { action: "break", reason: progressKind };
597
- }
598
- // ─── runPreDispatch ───────────────────────────────────────────────────────────
599
- /**
600
- * Phase 1: Pre-dispatch — resource guard, health gate, state derivation,
601
- * milestone transition, terminal conditions.
602
- * Returns break to exit the loop, or next with PreDispatchData on success.
603
- */
604
- export async function runPreDispatch(ic, loopState) {
605
- const { ctx, pi, s, deps, prefs } = ic;
606
- const uokFlags = resolveUokFlags(prefs);
607
- const runPreDispatchGate = async (input) => {
608
- if (!uokFlags.gates)
609
- return;
610
- const gateRunner = new UokGateRunner();
611
- gateRunner.register({
612
- id: input.gateId,
613
- type: input.gateType,
614
- execute: async () => ({
615
- outcome: input.outcome,
616
- failureClass: input.failureClass,
617
- rationale: input.rationale,
618
- findings: input.findings ?? "",
619
- }),
620
- });
621
- await gateRunner.run(input.gateId, {
622
- basePath: s.basePath,
623
- traceId: `pre-dispatch:${ic.flowId}`,
624
- turnId: `iter-${ic.iteration}`,
625
- milestoneId: input.milestoneId ?? s.currentMilestoneId ?? undefined,
626
- unitType: "pre-dispatch",
627
- unitId: `iter-${ic.iteration}`,
628
- });
629
- };
630
- // Resource version guard
631
- const staleMsg = deps.checkResourcesStale(s.resourceVersionOnStart);
632
- if (staleMsg) {
633
- await runPreDispatchGate({
634
- gateId: "resource-version-guard",
635
- gateType: "policy",
636
- outcome: "fail",
637
- failureClass: "policy",
638
- rationale: "resource version guard blocked dispatch",
639
- findings: staleMsg,
640
- });
641
- await deps.stopAuto(ctx, pi, staleMsg);
642
- debugLog("autoLoop", { phase: "exit", reason: "resources-stale" });
643
- return { action: "break", reason: "resources-stale" };
644
- }
645
- await runPreDispatchGate({
646
- gateId: "resource-version-guard",
647
- gateType: "policy",
648
- outcome: "pass",
649
- failureClass: "none",
650
- rationale: "resource version guard passed",
651
- });
652
- deps.invalidateAllCaches();
653
- s.lastPromptCharCount = undefined;
654
- s.lastBaselineCharCount = undefined;
655
- // Pre-dispatch health gate
656
- try {
657
- const expectedCurrentUnit = null;
658
- const healthGate = await deps.preDispatchHealthGate(s.basePath);
659
- if (healthGate.fixesApplied.length > 0) {
660
- ctx.ui.notify(`Pre-dispatch: ${healthGate.fixesApplied.join(", ")}`, "info");
661
- }
662
- if (!healthGate.proceed) {
663
- await runPreDispatchGate({
664
- gateId: "pre-dispatch-health-gate",
665
- gateType: "execution",
666
- outcome: "manual-attention",
667
- failureClass: "manual-attention",
668
- rationale: "pre-dispatch health gate blocked dispatch",
669
- findings: healthGate.reason,
670
- });
671
- ctx.ui.notify(healthGate.reason || "Pre-dispatch health check failed — run /gsd doctor for details.", "error");
672
- await deps.pauseAuto(ctx, pi, undefined, { expectedCurrentUnit });
673
- debugLog("autoLoop", { phase: "exit", reason: "health-gate-failed" });
674
- return { action: "break", reason: "health-gate-failed" };
675
- }
676
- await runPreDispatchGate({
677
- gateId: "pre-dispatch-health-gate",
678
- gateType: "execution",
679
- outcome: "pass",
680
- failureClass: "none",
681
- rationale: "pre-dispatch health gate passed",
682
- findings: healthGate.fixesApplied.length > 0 ? healthGate.fixesApplied.join(", ") : "",
683
- });
684
- }
685
- catch (e) {
686
- await runPreDispatchGate({
687
- gateId: "pre-dispatch-health-gate",
688
- gateType: "execution",
689
- outcome: "manual-attention",
690
- failureClass: "manual-attention",
691
- rationale: "pre-dispatch health gate threw unexpectedly",
692
- findings: String(e),
693
- });
694
- logWarning("engine", "Pre-dispatch health gate threw unexpectedly", { error: String(e) });
695
- }
696
- // Sync project root artifacts into worktree
697
- if (s.originalBasePath &&
698
- !isSamePathLocal(s.basePath, s.originalBasePath) &&
699
- s.currentMilestoneId &&
700
- s.scope) {
701
- deps.worktreeProjection.projectRootToWorktree(s.scope);
702
- }
703
- // Derive state — use canonical project root so the cache key is stable
704
- // across worktree↔project-root path-form alternation. See PR #5236
705
- // (workspace handle infrastructure) and the Phase A pt 2 plan.
706
- let state = await deps.deriveState(s.canonicalProjectRoot);
707
- const { getDeepStageGate } = await import("../auto-dispatch.js");
708
- const deepStageGate = getDeepStageGate(prefs, s.basePath);
709
- const canRunDeepSetupGate = state.phase === "pre-planning" ||
710
- state.phase === "needs-discussion" ||
711
- state.phase === "planning";
712
- if (canRunDeepSetupGate &&
713
- (deepStageGate.status === "pending" || deepStageGate.status === "blocked")) {
714
- debugLog("autoLoop", {
715
- phase: "deep-project-stage-gate",
716
- stage: deepStageGate.stage,
717
- status: deepStageGate.status,
718
- reason: deepStageGate.reason,
719
- });
720
- return {
721
- action: "next",
722
- data: {
723
- state: {
724
- ...state,
725
- phase: "pre-planning",
726
- activeMilestone: null,
727
- activeSlice: null,
728
- activeTask: null,
729
- nextAction: deepStageGate.reason,
730
- },
731
- mid: "PROJECT",
732
- midTitle: "Project setup",
733
- },
734
- };
735
- }
736
- if (uokFlags.planV2 && shouldRunPlanV2Gate(state.phase)) {
737
- let compiled = ensurePlanV2Graph(s.basePath, state);
738
- if (isEmptyPlanV2GraphResult(compiled)) {
739
- deps.invalidateAllCaches();
740
- state = await deps.deriveState(s.canonicalProjectRoot);
741
- compiled = shouldRunPlanV2Gate(state.phase)
742
- ? ensurePlanV2Graph(s.basePath, state)
743
- : {
744
- ok: true,
745
- reason: "empty plan-v2 graph recovered by state rederive",
746
- nodeCount: 0,
747
- };
748
- }
749
- if (!compiled.ok) {
750
- const reason = compiled.reason ?? "Plan v2 compilation failed";
751
- if (isMissingFinalizedContextResult(compiled)) {
752
- await runPreDispatchGate({
753
- gateId: "plan-v2-gate",
754
- gateType: "policy",
755
- outcome: "pass",
756
- failureClass: "none",
757
- rationale: "plan v2 missing context recovery deferred to dispatch",
758
- findings: reason,
759
- milestoneId: state.activeMilestone?.id ?? undefined,
760
- });
761
- }
762
- else {
763
- await runPreDispatchGate({
764
- gateId: "plan-v2-gate",
765
- gateType: "policy",
766
- outcome: "manual-attention",
767
- failureClass: "manual-attention",
768
- rationale: "plan v2 compile gate failed",
769
- findings: reason,
770
- milestoneId: state.activeMilestone?.id ?? undefined,
771
- });
772
- ctx.ui.notify(`Plan gate failed-closed: ${reason}\n\nIf this keeps happening, try: /gsd doctor heal`, "error");
773
- await deps.pauseAuto(ctx, pi);
774
- return { action: "break", reason: "plan-v2-gate-failed" };
775
- }
776
- }
777
- if (compiled.ok) {
778
- await runPreDispatchGate({
779
- gateId: "plan-v2-gate",
780
- gateType: "policy",
781
- outcome: "pass",
782
- failureClass: "none",
783
- rationale: "plan v2 compile gate passed",
784
- milestoneId: state.activeMilestone?.id ?? undefined,
785
- });
786
- }
787
- }
788
- deps.syncCmuxSidebar(prefs, state);
789
- let mid = state.activeMilestone?.id;
790
- let midTitle = state.activeMilestone?.title;
791
- debugLog("autoLoop", {
792
- phase: "state-derived",
793
- iteration: ic.iteration,
794
- mid,
795
- statePhase: state.phase,
796
- });
797
- // ── Slice-level parallelism gate (#2340) ─────────────────────────────
798
- // When slice_parallel is enabled, check if multiple slices are eligible
799
- // for parallel execution. If so, dispatch them in parallel and stop the
800
- // sequential loop. Workers are spawned via slice-parallel-orchestrator.ts.
801
- if (prefs?.slice_parallel?.enabled &&
802
- mid &&
803
- !process.env.GSD_PARALLEL_WORKER &&
804
- isDbAvailable()) {
805
- try {
806
- const projectRoot = _resolveDispatchGuardBasePath(s);
807
- if (isSliceParallelActive(projectRoot)) {
808
- ctx.ui.notify("Slice-parallel: workers are still running; waiting for completion before next dispatch.", "info");
809
- await new Promise((resolve) => setTimeout(resolve, 1000));
810
- return { action: "continue" };
811
- }
812
- const dbSlices = getMilestoneSlices(mid);
813
- if (dbSlices.length > 0) {
814
- const doneIds = new Set(dbSlices.filter(sl => sl.status === "complete" || sl.status === "done").map(sl => sl.id));
815
- const sliceInputs = dbSlices.map(sl => ({
816
- id: sl.id,
817
- done: doneIds.has(sl.id),
818
- depends: sl.depends ?? [],
819
- }));
820
- const eligible = getEligibleSlices(sliceInputs, doneIds);
821
- if (eligible.length > 1) {
822
- debugLog("autoLoop", {
823
- phase: "slice-parallel-dispatch",
824
- iteration: ic.iteration,
825
- mid,
826
- eligibleSlices: eligible.map(e => e.id),
827
- });
828
- ctx.ui.notify(`Slice-parallel: dispatching ${eligible.length} eligible slices for ${mid}.`, "info");
829
- // ADR-017 #5707: reconcile before spawning so each worker doesn't
830
- // independently race on the same drift. Failure aborts the spawn.
831
- const spawnGate = await reconcileBeforeSpawn(projectRoot);
832
- if (!spawnGate.ok) {
833
- ctx.ui.notify(`Slice-parallel: aborting spawn — ${spawnGate.reason}`, "error");
834
- return { action: "break", reason: `slice-parallel-reconciliation-failed: ${spawnGate.reason}` };
835
- }
836
- const result = await startSliceParallel(projectRoot, mid, eligible, {
837
- maxWorkers: prefs.slice_parallel.max_workers ?? 2,
838
- useExecutionGraph: uokFlags.executionGraph,
839
- });
840
- if (result.started.length > 0) {
841
- ctx.ui.notify(`Slice-parallel: started ${result.started.length} worker(s): ${result.started.join(", ")}.`, "info");
842
- return { action: "continue" };
843
- }
844
- if (result.errors.length > 0) {
845
- const detail = result.errors
846
- .map((err) => `${err.sid}: ${err.error}`)
847
- .join("; ");
848
- ctx.ui.notify(`Slice-parallel startup failed; falling back to sequential execution. ${detail}`, "warning");
849
- }
850
- // Fall through to sequential if no workers started
851
- }
852
- }
853
- }
854
- catch (err) {
855
- debugLog("autoLoop", {
856
- phase: "slice-parallel-check-error",
857
- error: err instanceof Error ? err.message : String(err),
858
- });
859
- // Non-fatal — fall through to sequential dispatch
860
- }
861
- }
862
- // ── Milestone transition ────────────────────────────────────────────
863
- if (mid && s.currentMilestoneId && mid !== s.currentMilestoneId) {
864
- deps.emitJournalEvent({ ts: new Date().toISOString(), flowId: ic.flowId, seq: ic.nextSeq(), eventType: "milestone-transition", data: { from: s.currentMilestoneId, to: mid } });
865
- ctx.ui.notify(`Milestone ${s.currentMilestoneId} complete. Advancing to ${mid}: ${midTitle}.`, "info");
866
- deps.sendDesktopNotification("GSD", `Milestone ${s.currentMilestoneId} complete!`, "success", "milestone", basename(s.originalBasePath || s.basePath));
867
- deps.logCmuxEvent(prefs, `Milestone ${s.currentMilestoneId} complete. Advancing to ${mid}.`, "success");
868
- const vizPrefs = prefs;
869
- if (vizPrefs?.auto_visualize) {
870
- ctx.ui.notify("Run /gsd visualize to see progress overview.", "info");
871
- }
872
- if (vizPrefs?.auto_report !== false) {
873
- try {
874
- await generateMilestoneReport(s, ctx, s.currentMilestoneId);
875
- }
876
- catch (err) {
877
- ctx.ui.notify(`Report generation failed: ${err instanceof Error ? err.message : String(err)}`, "warning");
878
- }
879
- }
880
- // Reset dispatch counters for new milestone
881
- s.unitDispatchCount.clear();
882
- s.unitRecoveryCount.clear();
883
- s.unitLifetimeDispatches.clear();
884
- loopState.recentUnits.length = 0;
885
- loopState.stuckRecoveryAttempts = 0;
886
- persistStuckRecoveryAttempts(s, loopState);
887
- // Worktree lifecycle on milestone transition — merge current, enter next.
888
- // #2909 / #5538-followup: preflight stash + always-on postflight pop.
889
- {
890
- const stop = await _runMilestoneMergeOnceWithStashRestore(ic, s.currentMilestoneId);
891
- if (stop)
892
- return stop;
893
- }
894
- // PR creation (auto_pr) is handled inside mergeMilestoneToMain (#2302)
895
- deps.invalidateAllCaches();
896
- state = await deps.deriveState(s.canonicalProjectRoot);
897
- mid = state.activeMilestone?.id;
898
- midTitle = state.activeMilestone?.title;
899
- if (mid) {
900
- if (deps.getIsolationMode(s.basePath) !== "none") {
901
- deps.captureIntegrationBranch(s.basePath, mid);
902
- }
903
- const enterResult = deps.lifecycle.enterMilestone(mid, ctx.ui);
904
- if (!enterResult.ok) {
905
- ctx.ui.notify(`Milestone transition stopped: failed to enter ${mid} (${enterResult.reason}).`, "error");
906
- if (enterResult.reason === "lease-conflict") {
907
- await deps.pauseAuto(ctx, pi);
908
- }
909
- return { action: "break", reason: "milestone-enter-failed" };
910
- }
911
- }
912
- else {
913
- // mid is undefined — no milestone to capture integration branch for
914
- }
915
- const pendingIds = state.registry
916
- .filter((m) => m.status !== "complete" && m.status !== "parked")
917
- .map((m) => m.id);
918
- deps.pruneQueueOrder(s.basePath, pendingIds);
919
- // Archive the old completed-units.json instead of wiping it (#2313).
920
- try {
921
- const completedKeysPath = join(gsdRoot(s.basePath), "completed-units.json");
922
- if (existsSync(completedKeysPath) && s.currentMilestoneId) {
923
- const archivePath = join(gsdRoot(s.basePath), `completed-units-${s.currentMilestoneId}.json`);
924
- cpSync(completedKeysPath, archivePath);
925
- }
926
- atomicWriteSync(completedKeysPath, JSON.stringify([], null, 2));
927
- }
928
- catch (e) {
929
- logWarning("engine", "Failed to archive completed-units on milestone transition", { error: String(e) });
930
- }
931
- // Rebuild STATE.md immediately so it reflects the new active milestone.
932
- // This bypasses the 30-second throttle in the normal rebuild path —
933
- // milestone transitions are rare and important enough to warrant an
934
- // immediate write.
935
- try {
936
- await deps.rebuildState(s.basePath);
937
- }
938
- catch (e) {
939
- logWarning("engine", "STATE.md rebuild failed after milestone transition", { error: String(e) });
940
- }
941
- // Re-project ROADMAP/PLAN markdown from the authoritative DB. Worktree DB
942
- // reconciliation during merge can leave main-branch markdown stale relative
943
- // to gsd.db (the 3M/3S/10T vs 3M/5S/16T drift class at /gsd startup).
944
- try {
945
- const { rebuildMarkdownProjectionsFromDb } = await import("../commands-maintenance.js");
946
- await rebuildMarkdownProjectionsFromDb(s.canonicalProjectRoot);
947
- if (s.basePath !== s.canonicalProjectRoot) {
948
- await rebuildMarkdownProjectionsFromDb(s.basePath);
949
- }
950
- }
951
- catch (e) {
952
- logWarning("engine", "markdown projection rebuild failed after milestone transition", { error: String(e) });
953
- }
954
- }
955
- if (mid) {
956
- s.currentMilestoneId = mid;
957
- deps.setActiveMilestoneId(s.basePath, mid);
958
- }
959
- // ── Terminal conditions ──────────────────────────────────────────────
960
- if (!mid) {
961
- if (s.currentUnit) {
962
- await deps.closeoutUnit(ctx, s.basePath, s.currentUnit.type, s.currentUnit.id, s.currentUnit.startedAt, deps.buildSnapshotOpts(s.currentUnit.type, s.currentUnit.id));
963
- }
964
- const incomplete = state.registry.filter((m) => m.status !== "complete" && m.status !== "parked");
965
- if (incomplete.length === 0 && state.registry.length > 0) {
966
- // All milestones complete — merge milestone branch before stopping.
967
- if (s.currentMilestoneId) {
968
- // #2909 / #5538-followup: preflight stash + always-on postflight pop.
969
- const stop = await _runMilestoneMergeOnceWithStashRestore(ic, s.currentMilestoneId);
970
- if (stop)
971
- return stop;
972
- // PR creation (auto_pr) is handled inside mergeMilestoneToMain (#2302)
973
- }
974
- const unmappedActive = countUnmappedActiveRequirements();
975
- const completionStopReason = formatCompletePhaseNextAction(unmappedActive);
976
- deps.sendDesktopNotification("GSD", unmappedActive > 0 ? "All milestones complete — requirements backlog remains" : "All milestones complete!", "success", "milestone", basename(s.originalBasePath || s.basePath));
977
- deps.logCmuxEvent(prefs, completionStopReason, "success");
978
- await deps.stopAuto(ctx, pi, completionStopReason, {
979
- completionWidget: {
980
- milestoneId: s.currentMilestoneId,
981
- milestoneTitle: midTitle,
982
- allMilestonesComplete: true,
983
- },
984
- });
985
- }
986
- else if (incomplete.length === 0 && state.registry.length === 0) {
987
- // Empty registry — no milestones visible, likely a path resolution bug
988
- const diag = `basePath=${s.basePath}, phase=${state.phase}`;
989
- ctx.ui.notify(`No milestones visible in current scope. Possible path resolution issue.\n Diagnostic: ${diag}`, "error");
990
- await deps.stopAuto(ctx, pi, `No milestones found — check basePath resolution`);
991
- }
992
- else if (state.phase === "blocked") {
993
- const blockedResumeMessage = formatBlockedResumeMessage(state.blockers);
994
- // Pause instead of hard-stop so the session is resumable with `/gsd auto`.
995
- // Hard-stop here was causing premature termination when slice dependencies
996
- // were temporarily unresolvable (e.g. after reassessment added new slices).
997
- await deps.pauseAuto(ctx, pi);
998
- ctx.ui.notify(blockedResumeMessage, "warning");
999
- deps.sendDesktopNotification("GSD", blockedResumeMessage, "warning", "attention", basename(s.originalBasePath || s.basePath));
1000
- deps.logCmuxEvent(prefs, blockedResumeMessage, "warning");
1001
- }
1002
- else {
1003
- const ids = incomplete.map((m) => m.id).join(", ");
1004
- const diag = `basePath=${s.basePath}, milestones=[${state.registry.map((m) => `${m.id}:${m.status}`).join(", ")}], phase=${state.phase}`;
1005
- ctx.ui.notify(`Unexpected: ${incomplete.length} incomplete milestone(s) (${ids}) but no active milestone.\n Diagnostic: ${diag}`, "error");
1006
- await deps.stopAuto(ctx, pi, `No active milestone — ${incomplete.length} incomplete (${ids}), see diagnostic above`);
1007
- }
1008
- debugLog("autoLoop", { phase: "exit", reason: "no-active-milestone" });
1009
- deps.emitJournalEvent({ ts: new Date().toISOString(), flowId: ic.flowId, seq: ic.nextSeq(), eventType: "terminal", data: { reason: "no-active-milestone" } });
1010
- return { action: "break", reason: "no-active-milestone" };
1011
- }
1012
- if (!midTitle) {
1013
- midTitle = mid;
1014
- ctx.ui.notify(`Milestone ${mid} has no title in roadmap — using ID as fallback.`, "warning");
1015
- }
1016
- // Mid-merge safety check
1017
- const mergeReconcileResult = deps.reconcileMergeState(s.basePath, ctx);
1018
- if (mergeReconcileResult === "blocked") {
1019
- await deps.pauseAuto(ctx, pi);
1020
- debugLog("autoLoop", { phase: "exit", reason: "merge-reconciliation-blocked" });
1021
- return { action: "break", reason: "merge-reconciliation-blocked" };
1022
- }
1023
- if (mergeReconcileResult === "reconciled") {
1024
- deps.invalidateAllCaches();
1025
- state = await deps.deriveState(s.canonicalProjectRoot);
1026
- mid = state.activeMilestone?.id;
1027
- midTitle = state.activeMilestone?.title;
1028
- }
1029
- if (!mid || !midTitle) {
1030
- const noMilestoneReason = !mid
1031
- ? "No active milestone after merge reconciliation"
1032
- : `Milestone ${mid} has no title after reconciliation`;
1033
- await closeoutAndStop(ctx, pi, s, deps, noMilestoneReason);
1034
- debugLog("autoLoop", {
1035
- phase: "exit",
1036
- reason: "no-milestone-after-reconciliation",
1037
- });
1038
- return { action: "break", reason: "no-milestone-after-reconciliation" };
1039
- }
1040
- // Terminal: complete
1041
- if (state.phase === "complete") {
1042
- // Milestone merge on complete (before closeout so branch state is clean).
1043
- if (s.currentMilestoneId) {
1044
- // #2909 / #5538-followup: preflight stash + always-on postflight pop.
1045
- const stop = await _runMilestoneMergeOnceWithStashRestore(ic, s.currentMilestoneId);
1046
- if (stop)
1047
- return stop;
1048
- // PR creation (auto_pr) is handled inside mergeMilestoneToMain (#2302)
1049
- }
1050
- deps.sendDesktopNotification("GSD", `Milestone ${mid} complete!`, "success", "milestone", basename(s.originalBasePath || s.basePath));
1051
- deps.logCmuxEvent(prefs, `Milestone ${mid} complete.`, "success");
1052
- if (s.currentUnit) {
1053
- await deps.closeoutUnit(ctx, s.basePath, s.currentUnit.type, s.currentUnit.id, s.currentUnit.startedAt, deps.buildSnapshotOpts(s.currentUnit.type, s.currentUnit.id));
1054
- s.clearCurrentUnit();
1055
- }
1056
- await deps.stopAuto(ctx, pi, `Milestone ${mid} complete`, {
1057
- completionWidget: {
1058
- milestoneId: mid,
1059
- milestoneTitle: midTitle,
1060
- },
1061
- });
1062
- debugLog("autoLoop", { phase: "exit", reason: "milestone-complete" });
1063
- deps.emitJournalEvent({ ts: new Date().toISOString(), flowId: ic.flowId, seq: ic.nextSeq(), eventType: "terminal", data: { reason: "milestone-complete", milestoneId: mid } });
1064
- return { action: "break", reason: "milestone-complete" };
1065
- }
1066
- // Terminal: blocked — pause instead of hard-stop so the session is resumable.
1067
- if (state.phase === "blocked") {
1068
- const blockedResumeMessage = formatBlockedResumeMessage(state.blockers);
1069
- if (s.currentUnit) {
1070
- await deps.closeoutUnit(ctx, s.basePath, s.currentUnit.type, s.currentUnit.id, s.currentUnit.startedAt, deps.buildSnapshotOpts(s.currentUnit.type, s.currentUnit.id));
1071
- }
1072
- await deps.pauseAuto(ctx, pi);
1073
- ctx.ui.notify(blockedResumeMessage, "warning");
1074
- deps.sendDesktopNotification("GSD", blockedResumeMessage, "warning", "attention", basename(s.originalBasePath || s.basePath));
1075
- deps.logCmuxEvent(prefs, blockedResumeMessage, "warning");
1076
- debugLog("autoLoop", { phase: "exit", reason: "blocked" });
1077
- deps.emitJournalEvent({ ts: new Date().toISOString(), flowId: ic.flowId, seq: ic.nextSeq(), eventType: "terminal", data: { reason: "blocked", blockers: state.blockers } });
1078
- return { action: "break", reason: "blocked" };
1079
- }
1080
- return { action: "next", data: { state, mid, midTitle } };
1081
- }
1082
- // ─── runDispatch ──────────────────────────────────────────────────────────────
1083
- function isUnhandledPhaseWarning(dispatchResult) {
1084
- return dispatchResult.action === "stop" &&
1085
- dispatchResult.level === "warning" &&
1086
- dispatchResult.matchedRule === "<no-match>" &&
1087
- /^Unhandled phase "/.test(dispatchResult.reason);
1088
- }
1089
- /**
1090
- * Phase 3: Dispatch resolution — resolve next unit, stuck detection, pre-dispatch hooks.
1091
- * Returns break/continue to control the loop, or next with IterationData on success.
1092
- */
1093
- export async function runDispatch(ic, preData, loopState) {
1094
- const { ctx, pi, s, deps, prefs } = ic;
1095
- const { state, mid, midTitle } = preData;
1096
- const provider = ctx.model?.provider;
1097
- const authMode = provider && typeof ctx.modelRegistry?.getProviderAuthMode === "function"
1098
- ? ctx.modelRegistry.getProviderAuthMode(provider)
1099
- : undefined;
1100
- // Use the baseline snapshot rather than the live active-tool set: a prior
1101
- // unit's per-provider narrowing (hook overrides, Groq 128-tool cap, etc.)
1102
- // can strip required MCP tools from the live set even though
1103
- // selectAndApplyModel will restore them before the unit is dispatched.
1104
- // Checking a stale-narrowed set causes false transport-preflight warnings
1105
- // that repeat on every /gsd auto resume (#477 follow-up).
1106
- const activeTools = getToolBaselineSnapshot(pi);
1107
- const registeredTools = getRegisteredToolSnapshot(pi);
1108
- // Deep planning intentionally keeps human checkpoints in plain chat. In
1109
- // Claude Code/local MCP transports, structured question requests can be
1110
- // cancelled outside the normal chat flow, which made approval gates easy to
1111
- // skip or bury under tool output.
1112
- const structuredQuestionsAvailable = prefs?.planning_depth === "deep"
1113
- ? "false"
1114
- : supportsStructuredQuestions(activeTools, {
1115
- authMode,
1116
- baseUrl: ctx.model?.baseUrl,
1117
- }) ? "true" : "false";
1118
- debugLog("autoLoop", { phase: "dispatch-resolve", iteration: ic.iteration });
1119
- let dispatchResult = await deps.resolveDispatch({
1120
- basePath: s.basePath,
1121
- mid,
1122
- midTitle,
1123
- state,
1124
- prefs,
1125
- session: s,
1126
- structuredQuestionsAvailable,
1127
- sessionContextWindow: ctx.model?.contextWindow,
1128
- sessionProvider: ctx.model?.provider,
1129
- modelRegistry: ctx.modelRegistry,
1130
- activeTools,
1131
- registeredTools,
1132
- sessionBaseUrl: ctx.model?.baseUrl,
1133
- sessionAuthMode: authMode,
1134
- });
1135
- if (isUnhandledPhaseWarning(dispatchResult)) {
1136
- deps.invalidateAllCaches();
1137
- const freshState = await deps.deriveState(s.canonicalProjectRoot);
1138
- const freshMid = freshState.activeMilestone?.id ?? mid;
1139
- const freshMidTitle = freshState.activeMilestone?.title ?? freshMid ?? midTitle;
1140
- debugLog("autoLoop", {
1141
- phase: "dispatch-unhandled-phase-retry",
1142
- iteration: ic.iteration,
1143
- stalePhase: state.phase,
1144
- freshPhase: freshState.phase,
1145
- });
1146
- dispatchResult = await deps.resolveDispatch({
1147
- basePath: s.basePath,
1148
- mid: freshMid,
1149
- midTitle: freshMidTitle,
1150
- state: freshState,
1151
- prefs,
1152
- session: s,
1153
- structuredQuestionsAvailable,
1154
- sessionContextWindow: ctx.model?.contextWindow,
1155
- sessionProvider: ctx.model?.provider,
1156
- modelRegistry: ctx.modelRegistry,
1157
- activeTools,
1158
- registeredTools,
1159
- sessionBaseUrl: ctx.model?.baseUrl,
1160
- sessionAuthMode: authMode,
1161
- });
1162
- }
1163
- if (dispatchResult.action === "stop") {
1164
- deps.emitJournalEvent({ ts: new Date().toISOString(), flowId: ic.flowId, seq: ic.nextSeq(), eventType: "dispatch-stop", rule: dispatchResult.matchedRule, data: { reason: dispatchResult.reason } });
1165
- // Warning-level stops are recoverable human checkpoints (e.g. UAT verdict
1166
- // gate) — pause instead of hard-stopping so the session is resumable with
1167
- // `/gsd auto`. Error/info-level stops remain hard stops for infrastructure
1168
- // failures and terminal conditions respectively.
1169
- // See: https://github.com/open-gsd/gsd-pi/issues/2474
1170
- if (dispatchResult.level === "warning") {
1171
- ctx.ui.notify(dispatchResult.reason, "warning");
1172
- await deps.pauseAuto(ctx, pi, {
1173
- message: dispatchResult.reason,
1174
- category: "unknown",
1175
- });
1176
- }
1177
- else {
1178
- await closeoutAndStop(ctx, pi, s, deps, dispatchResult.reason);
1179
- }
1180
- debugLog("autoLoop", { phase: "exit", reason: "dispatch-stop" });
1181
- return { action: "break", reason: "dispatch-stop" };
1182
- }
1183
- if (dispatchResult.action !== "dispatch") {
1184
- // Non-dispatch action (e.g. "skip") — re-derive state
1185
- await new Promise((r) => setImmediate(r));
1186
- return { action: "continue" };
1187
- }
1188
- let unitType = dispatchResult.unitType;
1189
- let unitId = dispatchResult.unitId;
1190
- let prompt = dispatchResult.prompt;
1191
- let pauseAfterUatDispatch = dispatchResult.pauseAfterDispatch ?? false;
1192
- let dispatchState = state;
1193
- let dispatchMid = mid;
1194
- let dispatchMidTitle = midTitle;
1195
- const pendingRetryDispatch = s.pendingVerificationRetryDispatch;
1196
- if (pendingRetryDispatch) {
1197
- unitType = pendingRetryDispatch.unitType;
1198
- unitId = pendingRetryDispatch.unitId;
1199
- prompt = pendingRetryDispatch.prompt;
1200
- pauseAfterUatDispatch = pendingRetryDispatch.pauseAfterUatDispatch;
1201
- dispatchState = pendingRetryDispatch.state;
1202
- dispatchMid = pendingRetryDispatch.mid ?? mid;
1203
- dispatchMidTitle = pendingRetryDispatch.midTitle ?? midTitle;
1204
- s.pendingVerificationRetryDispatch = null;
1205
- debugLog("autoLoop", {
1206
- phase: "dispatch-pending-verification-retry",
1207
- unitType,
1208
- unitId,
1209
- });
1210
- }
1211
- const alreadyClosedReason = getAlreadyClosedDispatchReason(unitType, unitId);
1212
- if (alreadyClosedReason) {
1213
- s.pendingVerificationRetry = null;
1214
- loopState.recentUnits = [];
1215
- loopState.stuckRecoveryAttempts = Math.max(loopState.stuckRecoveryAttempts, 1);
1216
- deps.invalidateAllCaches();
1217
- debugLog("autoLoop", {
1218
- phase: "dispatch-skip-already-closed",
1219
- unitType,
1220
- unitId,
1221
- reason: alreadyClosedReason,
1222
- });
1223
- deps.emitJournalEvent({
1224
- ts: new Date().toISOString(),
1225
- flowId: ic.flowId,
1226
- seq: ic.nextSeq(),
1227
- eventType: "guard-block",
1228
- data: { unitType, unitId, reason: alreadyClosedReason },
1229
- });
1230
- ctx.ui.notify(`Skipping ${unitType} ${unitId}: ${alreadyClosedReason}.`, "info");
1231
- await new Promise((r) => setImmediate(r));
1232
- return { action: "continue" };
1233
- }
1234
- deps.emitJournalEvent({
1235
- ts: new Date().toISOString(),
1236
- flowId: ic.flowId,
1237
- seq: ic.nextSeq(),
1238
- eventType: "dispatch-match",
1239
- rule: pendingRetryDispatch ? "verification-retry" : dispatchResult.matchedRule,
1240
- data: { unitType, unitId },
1241
- });
1242
- // Resolve hooks and prior-slice gating before health/stuck accounting so
1243
- // those checks run against the final dispatch unit.
1244
- const preDispatchResult = deps.runPreDispatchHooks(unitType, unitId, prompt, s.basePath);
1245
- if (preDispatchResult.firedHooks.length > 0) {
1246
- ctx.ui.notify(`Pre-dispatch hook${preDispatchResult.firedHooks.length > 1 ? "s" : ""}: ${preDispatchResult.firedHooks.join(", ")}`, "info");
1247
- deps.emitJournalEvent({ ts: new Date().toISOString(), flowId: ic.flowId, seq: ic.nextSeq(), eventType: "pre-dispatch-hook", data: { firedHooks: preDispatchResult.firedHooks, action: preDispatchResult.action } });
1248
- }
1249
- if (preDispatchResult.action === "skip") {
1250
- ctx.ui.notify(`Skipping ${unitType} ${unitId} (pre-dispatch hook).`, "info");
1251
- await new Promise((r) => setImmediate(r));
1252
- return { action: "continue" };
1253
- }
1254
- if (preDispatchResult.action === "replace") {
1255
- prompt = preDispatchResult.prompt ?? prompt;
1256
- if (preDispatchResult.unitType)
1257
- unitType = preDispatchResult.unitType;
1258
- }
1259
- else if (preDispatchResult.prompt) {
1260
- prompt = preDispatchResult.prompt;
1261
- }
1262
- const guardBasePath = _resolveDispatchGuardBasePath(s);
1263
- let mainBranch = "main";
1264
- try {
1265
- mainBranch = deps.getMainBranch(guardBasePath);
1266
- }
1267
- catch (err) {
1268
- debugLog("autoLoop", { phase: "getMainBranch-failed", error: String(err) });
1269
- }
1270
- const priorSliceBlocker = deps.getPriorSliceCompletionBlocker(guardBasePath, mainBranch, unitType, unitId);
1271
- if (priorSliceBlocker) {
1272
- await deps.stopAuto(ctx, pi, priorSliceBlocker);
1273
- debugLog("autoLoop", { phase: "exit", reason: "prior-slice-blocker" });
1274
- return { action: "break", reason: "prior-slice-blocker" };
1275
- }
1276
- const consecutiveDispatchBlocker = getConsecutiveDispatchBlocker(loopState, state.phase, unitType, unitId);
1277
- if (consecutiveDispatchBlocker) {
1278
- await deps.stopAuto(ctx, pi, consecutiveDispatchBlocker);
1279
- debugLog("autoLoop", { phase: "exit", reason: "consecutive-dispatch-blocker" });
1280
- return { action: "break", reason: "consecutive-dispatch-blocker" };
1281
- }
1282
- const worktreeSafetyBlock = await validateSourceWriteWorktreeSafety(ic, unitType, unitId, mid, "pre-dispatch");
1283
- if (worktreeSafetyBlock)
1284
- return worktreeSafetyBlock;
1285
- // ── Sliding-window stuck detection with graduated recovery ──
1286
- const derivedKey = `${unitType}/${unitId}`;
1287
- // Always record this dispatch in the sliding window and run detection so
1288
- // Rules 1/3/4 can catch retry loops with repeated failure content (#5719).
1289
- // Rules 2/2b suppress legitimate retry backoff through the dispatch ledger.
1290
- const latestDispatch = getLatestForUnit(derivedKey);
1291
- const recentError = latestDispatch?.error_summary ?? undefined;
1292
- loopState.recentUnits.push({ key: derivedKey, error: recentError });
1293
- while (loopState.recentUnits.length > STUCK_WINDOW_SIZE) {
1294
- loopState.recentUnits.shift();
1295
- }
1296
- const stuckSignal = detectStuck(loopState.recentUnits, {
1297
- pendingRetry: !!s.pendingVerificationRetry,
1298
- retryAttempt: s.pendingVerificationRetry?.attempt,
1299
- });
1300
- if (stuckSignal) {
1301
- debugLog("autoLoop", {
1302
- phase: "stuck-check",
1303
- unitType,
1304
- unitId,
1305
- reason: stuckSignal.reason,
1306
- recoveryAttempts: loopState.stuckRecoveryAttempts,
1307
- });
1308
- if (loopState.stuckRecoveryAttempts === 0) {
1309
- // Level 1: try verifying the artifact, then cache invalidation + retry
1310
- loopState.stuckRecoveryAttempts++;
1311
- persistStuckRecoveryAttempts(s, loopState);
1312
- const artifactExists = verifyExpectedArtifact(unitType, unitId, s.basePath);
1313
- if (artifactExists) {
1314
- debugLog("autoLoop", {
1315
- phase: "stuck-recovery",
1316
- level: 1,
1317
- action: "artifact-found",
1318
- });
1319
- const recoveryDb = refreshRecoveryDbForArtifact(unitType, unitId, s.basePath);
1320
- if (!recoveryDb.ok) {
1321
- ctx.ui.notify(recoveryDb.fatal
1322
- ? `${recoveryDb.message} Pausing auto-mode for manual recovery.`
1323
- : `${recoveryDb.message} Keeping stuck state for retry.`, "warning");
1324
- if (recoveryDb.fatal) {
1325
- await deps.pauseAuto(ctx, pi);
1326
- return { action: "break", reason: recoveryDb.reason };
1327
- }
1328
- return { action: "continue" };
1329
- }
1330
- ctx.ui.notify(`Stuck recovery: artifact for ${unitType} ${unitId} found on disk. Invalidating caches.`, "info");
1331
- deps.invalidateAllCaches();
1332
- loopState.recentUnits.length = 0;
1333
- return { action: "continue" };
1334
- }
1335
- ctx.ui.notify(`Stuck on ${unitType} ${unitId} (${stuckSignal.reason}). Invalidating caches and retrying.`, "warning");
1336
- deps.invalidateAllCaches();
1337
- }
1338
- else {
1339
- // Level 2: hard stop — genuinely stuck
1340
- deps.invalidateAllCaches();
1341
- const artifactExists = verifyExpectedArtifact(unitType, unitId, s.basePath);
1342
- if (artifactExists) {
1343
- debugLog("autoLoop", {
1344
- phase: "stuck-recovery",
1345
- level: 2,
1346
- action: "artifact-found",
1347
- });
1348
- const recoveryDb = refreshRecoveryDbForArtifact(unitType, unitId, s.basePath);
1349
- if (recoveryDb.ok) {
1350
- ctx.ui.notify(`Stuck recovery: artifact for ${unitType} ${unitId} found on disk after cache invalidation. Continuing.`, "info");
1351
- loopState.recentUnits.length = 0;
1352
- return { action: "continue" };
1353
- }
1354
- ctx.ui.notify(recoveryDb.fatal
1355
- ? `${recoveryDb.message} Pausing auto-mode for manual recovery.`
1356
- : `${recoveryDb.message} Stopping for manual recovery.`, "warning");
1357
- if (recoveryDb.fatal) {
1358
- await deps.pauseAuto(ctx, pi);
1359
- return { action: "break", reason: recoveryDb.reason };
1360
- }
1361
- }
1362
- debugLog("autoLoop", {
1363
- phase: "stuck-detected",
1364
- unitType,
1365
- unitId,
1366
- reason: stuckSignal.reason,
1367
- });
1368
- const stuckDiag = diagnoseExpectedArtifact(unitType, unitId, s.basePath);
1369
- const stuckRemediation = buildLoopRemediationSteps(unitType, unitId, s.basePath);
1370
- const stuckParts = [`Stuck on ${unitType} ${unitId} — ${stuckSignal.reason}.`];
1371
- if (stuckDiag)
1372
- stuckParts.push(`Expected: ${stuckDiag}`);
1373
- if (stuckRemediation)
1374
- stuckParts.push(`To recover:\n${stuckRemediation}`);
1375
- ctx.ui.notify(stuckParts.join(" "), "error");
1376
- await deps.stopAuto(ctx, pi, `Stuck: ${stuckSignal.reason}`);
1377
- return { action: "break", reason: "stuck-detected" };
1378
- }
1379
- }
1380
- else {
1381
- // Progress detected — reset recovery counter
1382
- if (loopState.stuckRecoveryAttempts > 0) {
1383
- debugLog("autoLoop", {
1384
- phase: "stuck-counter-reset",
1385
- from: loopState.recentUnits[loopState.recentUnits.length - 2]?.key ?? "",
1386
- to: derivedKey,
1387
- });
1388
- loopState.stuckRecoveryAttempts = 0;
1389
- persistStuckRecoveryAttempts(s, loopState);
1390
- }
1391
- }
1392
- return {
1393
- action: "next",
1394
- data: {
1395
- unitType, unitId, prompt, finalPrompt: prompt,
1396
- pauseAfterUatDispatch,
1397
- state: dispatchState, mid: dispatchMid, midTitle: dispatchMidTitle,
1398
- isRetry: Boolean(pendingRetryDispatch), previousTier: undefined,
1399
- hookModelOverride: preDispatchResult.model,
1400
- },
1401
- };
1402
- }
1403
- // ─── runGuards ────────────────────────────────────────────────────────────────
14
+ import { BUDGET_THRESHOLDS } from "./types.js";
15
+ // Re-export phase implementations.
16
+ export { runPreDispatch } from "./pre-dispatch.js";
17
+ export { runDispatch, getAlreadyClosedDispatchReason, isUnhandledPhaseWarning } from "./dispatch.js";
18
+ export { runUnitPhase, resetSessionTimeoutState, _classifyZeroToolProviderMessageForTest, resolveDispatchRecoveryAttempts, _shouldProceedWithInvalidRepoClassificationForTest, } from "./unit-phase.js";
19
+ export { runFinalize, failClosedOnFinalizeTimeout } from "./finalize.js";
20
+ export { closeoutAndStop, generateMilestoneReport, _runMilestoneMergeWithStashRestore, _runMilestoneMergeOnceWithStashRestore, stopOnPostflightRecoveryNeeded, restorePreflightStashOrStop, shouldSkipTerminalMilestoneCloseout, } from "./closeout.js";
21
+ // Re-export shared helpers.
22
+ export { persistStuckRecoveryAttempts, isSamePathLocal, isIsolatedWorktreeSession, _resolveReportBasePath, _resolveDispatchGuardBasePath, shouldRunPlanV2Gate, _resolveCurrentUnitStartedAtForTest, applyVerificationRetryPolicy, rememberRetryDispatch, emitCancelledUnitEnd, _buildCancelledUnitStopReason, _isPauseOriginCancelledResult, } from "./phase-helpers.js";
23
+ export { validateSourceWriteWorktreeSafety, formatWorktreeSafetyFailure, formatWorktreeSafetyStopReason, resolveEmptyWorktreeWithProjectContent, shouldDegradeEmptyWorktreeToProjectRoot, unitWritesSource, } from "./worktree-safety-phase.js";
1404
24
  /**
1405
25
  * Phase 2: Guards — stop directives, budget ceiling, context window, secrets re-check.
1406
26
  * Returns break to exit the loop, or next to proceed to dispatch.
@@ -1423,7 +43,7 @@ export async function runGuards(ic, mid) {
1423
43
  : `Stop directive: ${first.text}`;
1424
44
  ctx.ui.notify(label, "warning");
1425
45
  deps.sendDesktopNotification("GSD", label, "warning", "stop-directive", basename(s.originalBasePath || s.basePath));
1426
- // Pause first — ensures auto-mode stops even if later steps fail
46
+ // Pause first — Ensures auto-mode stops even if later steps fail
1427
47
  await deps.pauseAuto(ctx, pi);
1428
48
  // For backtrack captures, write the backtrack trigger after pausing
1429
49
  if (isBacktrack) {
@@ -1572,930 +192,3 @@ export async function runGuards(ic, mid) {
1572
192
  }
1573
193
  return { action: "next", data: undefined };
1574
194
  }
1575
- // ─── runUnitPhase ─────────────────────────────────────────────────────────────
1576
- /**
1577
- * Phase 4: Unit execution — dispatch prompt, await agent_end, closeout, artifact verify.
1578
- * Returns break or next with unitStartedAt for downstream phases.
1579
- */
1580
- export async function runUnitPhase(ic, iterData, loopState, sidecarItem) {
1581
- const { ctx, pi, s, deps, prefs } = ic;
1582
- const { unitType, unitId, prompt, state, mid } = iterData;
1583
- debugLog("autoLoop", {
1584
- phase: "unit-execution",
1585
- iteration: ic.iteration,
1586
- unitType,
1587
- unitId,
1588
- });
1589
- const worktreeSafetyBlock = await validateSourceWriteWorktreeSafety(ic, unitType, unitId, mid, "unit-execution");
1590
- if (worktreeSafetyBlock)
1591
- return worktreeSafetyBlock;
1592
- // ── Project classification notice (#1833, #1843) ─────────────────────
1593
- // Worktree Safety owns source-write root validity. Classification now only
1594
- // shapes user/model guidance for valid roots.
1595
- let projectClassification = null;
1596
- if (s.basePath && unitType === "execute-task") {
1597
- projectClassification = classifyProject(s.basePath);
1598
- if (projectClassification.kind === "invalid-repo") {
1599
- const msg = `Worktree health check failed: ${s.basePath} classified as invalid-repo (${projectClassification.reason}) — refusing to dispatch ${unitType} ${unitId}`;
1600
- debugLog("runUnitPhase", { phase: "worktree-health-invalid-repo", basePath: s.basePath, classification: projectClassification });
1601
- const hasGit = deps.existsSync(join(s.basePath, ".git"));
1602
- if (_shouldProceedWithInvalidRepoClassificationForTest(projectClassification.reason, hasGit)) {
1603
- ctx.ui.notify(`Warning: ${s.basePath} project classification could not confirm .git; assuming it has no project content yet — proceeding as greenfield project because worktree health reported .git present`, "warning");
1604
- }
1605
- else {
1606
- ctx.ui.notify(msg, "error");
1607
- await deps.stopAuto(ctx, pi, msg);
1608
- return { action: "break", reason: "worktree-invalid" };
1609
- }
1610
- }
1611
- if (projectClassification.kind === "greenfield") {
1612
- debugLog("runUnitPhase", { phase: "worktree-health-greenfield", basePath: s.basePath, classification: projectClassification });
1613
- ctx.ui.notify(`Warning: ${s.basePath} has no project content yet — proceeding as greenfield project`, "warning");
1614
- }
1615
- else if (projectClassification.kind === "untyped-existing") {
1616
- debugLog("runUnitPhase", { phase: "worktree-health-untyped-existing", basePath: s.basePath, classification: projectClassification });
1617
- ctx.ui.notify(`Notice: ${s.basePath} has existing project content but no recognized tooling markers — using generic file-level workflow guidance`, "info");
1618
- }
1619
- }
1620
- // Detect retry and capture previous tier for escalation
1621
- const isRetry = !!(s.currentUnit &&
1622
- s.currentUnit.type === unitType &&
1623
- s.currentUnit.id === unitId);
1624
- const previousTier = s.currentUnitRouting?.tier;
1625
- const dispatchKey = `${unitType}/${unitId}`;
1626
- const nextDispatchCount = (s.unitDispatchCount.get(dispatchKey) ?? 0) + 1;
1627
- // Status bar (widget + preconditions deferred until after model selection — see #2899)
1628
- setAutoActiveStatus(ctx, s.stepMode ? "next" : "auto");
1629
- if (mid)
1630
- deps.updateSliceProgressCache(s.basePath, mid, state.activeSlice?.id);
1631
- // ── Safety harness: reset evidence + create checkpoint ──
1632
- const safetyConfig = resolveSafetyHarnessConfig(prefs?.safety_harness);
1633
- if (safetyConfig.enabled && safetyConfig.evidence_collection) {
1634
- resetEvidence();
1635
- // Restore persisted evidence so session-restart resumes don't produce
1636
- // false-positive "no bash calls" warnings (Bug #4385).
1637
- if (s.basePath && unitType === "execute-task") {
1638
- const { milestone: eMid, slice: eSid, task: eTid } = parseUnitId(unitId);
1639
- if (eMid && eSid && eTid) {
1640
- loadEvidenceFromDisk(s.basePath, eMid, eSid, eTid);
1641
- }
1642
- }
1643
- }
1644
- // Only checkpoint code-executing units (not lifecycle/planning units)
1645
- if (safetyConfig.enabled && safetyConfig.checkpoints && unitType === "execute-task") {
1646
- s.checkpointSha = createCheckpoint(s.basePath, unitId);
1647
- if (s.checkpointSha) {
1648
- debugLog("runUnitPhase", { phase: "checkpoint-created", unitId, sha: s.checkpointSha.slice(0, 8) });
1649
- }
1650
- }
1651
- // Prompt injection
1652
- let finalPrompt = prompt;
1653
- if (unitType === "execute-task") {
1654
- projectClassification ??= classifyProject(s.basePath);
1655
- if (projectClassification.kind === "untyped-existing") {
1656
- const samples = projectClassification.contentFiles.slice(0, 8).join(", ") || "project files";
1657
- finalPrompt +=
1658
- "\n\n**Project classification:** Existing untyped project. No recognized build/tooling markers were detected, " +
1659
- "so use generic file-level workflow guidance. Task plans and completion summaries must list every concrete " +
1660
- `project file changed in \`files\` or \`expected_output\`. Detected content sample: ${samples}.`;
1661
- }
1662
- }
1663
- if (s.pendingVerificationRetry && s.pendingVerificationRetry.unitId === unitId) {
1664
- const retryCtx = s.pendingVerificationRetry;
1665
- s.pendingVerificationRetry = null;
1666
- const capped = retryCtx.failureContext.length > MAX_RECOVERY_CHARS
1667
- ? retryCtx.failureContext.slice(0, MAX_RECOVERY_CHARS) +
1668
- "\n\n[...failure context truncated]"
1669
- : retryCtx.failureContext;
1670
- finalPrompt = `**VERIFICATION FAILED — AUTO-FIX ATTEMPT ${retryCtx.attempt}**\n\nThe verification gate ran after your previous attempt and found failures. Fix these issues before completing the task.\n\n${capped}\n\n---\n\n${finalPrompt}`;
1671
- }
1672
- if (s.pendingCrashRecovery) {
1673
- const capped = s.pendingCrashRecovery.length > MAX_RECOVERY_CHARS
1674
- ? s.pendingCrashRecovery.slice(0, MAX_RECOVERY_CHARS) +
1675
- "\n\n[...recovery briefing truncated to prevent memory exhaustion]"
1676
- : s.pendingCrashRecovery;
1677
- finalPrompt = `${capped}\n\n---\n\n${finalPrompt}`;
1678
- s.pendingCrashRecovery = null;
1679
- }
1680
- else if (nextDispatchCount > 1) {
1681
- const diagnostic = deps.getDeepDiagnostic(s.basePath);
1682
- if (diagnostic) {
1683
- const cappedDiag = diagnostic.length > MAX_RECOVERY_CHARS
1684
- ? diagnostic.slice(0, MAX_RECOVERY_CHARS) +
1685
- "\n\n[...diagnostic truncated to prevent memory exhaustion]"
1686
- : diagnostic;
1687
- const retryInstruction = unitType === "execute-task"
1688
- ? "The required artifact is `T##-SUMMARY.md`. Do NOT manually write this file. Call `gsd_task_complete` with `milestoneId`, `sliceId`, `taskId`, and the required completion fields. Do not re-run implementation work — call the tool."
1689
- : "Fix whatever went wrong and make sure you write the required file this time.";
1690
- finalPrompt = `**RETRY — your previous attempt did not produce the required artifact.**\n\nDiagnostic from previous attempt:\n${cappedDiag}\n\n${retryInstruction}\n\n---\n\n${finalPrompt}`;
1691
- }
1692
- }
1693
- // Prompt char measurement
1694
- s.lastPromptCharCount = finalPrompt.length;
1695
- s.lastBaselineCharCount = undefined;
1696
- if (deps.isDbAvailable()) {
1697
- try {
1698
- const { inlineGsdRootFile } = await importExtensionModule(import.meta.url, "../auto-prompts.js");
1699
- const [decisionsContent, requirementsContent, projectContent] = await Promise.all([
1700
- inlineGsdRootFile(s.basePath, "decisions.md", "Decisions"),
1701
- inlineGsdRootFile(s.basePath, "requirements.md", "Requirements"),
1702
- inlineGsdRootFile(s.basePath, "project.md", "Project"),
1703
- ]);
1704
- s.lastBaselineCharCount =
1705
- (decisionsContent?.length ?? 0) +
1706
- (requirementsContent?.length ?? 0) +
1707
- (projectContent?.length ?? 0);
1708
- }
1709
- catch (e) {
1710
- logWarning("engine", "Baseline char count measurement failed", { error: String(e) });
1711
- }
1712
- }
1713
- // Cache-optimize prompt section ordering
1714
- try {
1715
- finalPrompt = deps.reorderForCaching(finalPrompt);
1716
- }
1717
- catch (reorderErr) {
1718
- const msg = reorderErr instanceof Error ? reorderErr.message : String(reorderErr);
1719
- logWarning("engine", "Prompt reorder failed", { error: msg });
1720
- }
1721
- // Select and apply model (with tier escalation on retry — normal units only)
1722
- const prevUnitRouting = s.currentUnitRouting;
1723
- const prevUnitModel = s.currentUnitModel;
1724
- const prevDispatchedModelId = s.currentDispatchedModelId;
1725
- const prevSessionModel = ctx.model;
1726
- const prevSessionThinkingLevel = pi.getThinkingLevel();
1727
- const modelResult = await deps.selectAndApplyModel(ctx, pi, unitType, unitId, s.basePath, prefs, s.verbose, s.autoModeStartModel, sidecarItem ? undefined : { isRetry, previousTier }, undefined, s.manualSessionModelOverride, s.autoModeStartThinkingLevel);
1728
- s.currentUnitRouting =
1729
- modelResult.routing;
1730
- s.currentUnitModel =
1731
- modelResult.appliedModel;
1732
- // Apply sidecar/pre-dispatch hook model override (takes priority over standard model selection)
1733
- const hookModelOverride = sidecarItem?.model ?? iterData.hookModelOverride;
1734
- if (hookModelOverride) {
1735
- const availableModels = ctx.modelRegistry.getAvailable();
1736
- const match = deps.resolveModelId(hookModelOverride, availableModels, ctx.model?.provider);
1737
- if (match) {
1738
- const ok = await pi.setModel(match, { persist: false });
1739
- if (ok) {
1740
- // Apply the per-phase reasoning effort selectAndApplyModel resolved for
1741
- // this unit — not the auto-start session snapshot — but route it through
1742
- // the same floor + capability-clamp pipeline against the *hook* model
1743
- // (ADR-026). The hook override can pick a different model family than the
1744
- // one selectAndApplyModel clamped against, so re-clamping here prevents
1745
- // sending an unsupported level; the floor fills in when no phase level
1746
- // resolved so a hook-overridden execute-task still meets the floor.
1747
- const hookThinkingBase = modelResult.appliedThinkingLevel
1748
- ?? floorThinkingLevelForUnit(unitType, s.autoModeStartThinkingLevel);
1749
- applyThinkingLevelForModel(pi, hookThinkingBase, match, ctx);
1750
- s.currentUnitModel = match;
1751
- ctx.ui.notify(`Hook model override: ${match.provider}/${match.id}`, "info");
1752
- }
1753
- else {
1754
- ctx.ui.notify(`Hook model "${hookModelOverride}" found but setModel failed. Using default.`, "warning");
1755
- }
1756
- }
1757
- else {
1758
- ctx.ui.notify(`Hook model "${hookModelOverride}" not found in available models. Falling back to current session model. ` +
1759
- `Ensure the model is defined in models.json and has auth configured.`, "warning");
1760
- }
1761
- }
1762
- // Store the final dispatched model ID so the dashboard can read it (#2899).
1763
- // This accounts for hook model overrides applied after selectAndApplyModel.
1764
- s.currentDispatchedModelId = s.currentUnitModel
1765
- ? `${s.currentUnitModel.provider ?? ""}/${s.currentUnitModel.id ?? ""}`
1766
- : null;
1767
- const compatibilityError = getWorkflowTransportSupportError(s.currentUnitModel?.provider ?? ctx.model?.provider, getRequiredWorkflowToolsForAutoUnit(unitType), {
1768
- projectRoot: s.basePath,
1769
- surface: "auto-mode",
1770
- unitType,
1771
- authMode: s.currentUnitModel?.provider
1772
- ? ctx.modelRegistry.getProviderAuthMode(s.currentUnitModel.provider)
1773
- : ctx.model?.provider
1774
- ? ctx.modelRegistry.getProviderAuthMode(ctx.model.provider)
1775
- : undefined,
1776
- baseUrl: s.currentUnitModel?.baseUrl ?? ctx.model?.baseUrl,
1777
- activeTools: typeof pi.getActiveTools === "function" ? pi.getActiveTools() : [],
1778
- });
1779
- const workflowMcpPrepModel = s.currentUnitModel;
1780
- if (compatibilityError) {
1781
- s.currentUnitRouting = prevUnitRouting;
1782
- s.currentUnitModel = prevUnitModel;
1783
- s.currentDispatchedModelId = prevDispatchedModelId;
1784
- if (s.checkpointSha) {
1785
- cleanupCheckpoint(s.basePath, unitId);
1786
- s.checkpointSha = null;
1787
- }
1788
- if (prevSessionModel) {
1789
- const ok = await pi.setModel(prevSessionModel, { persist: false });
1790
- if (!ok) {
1791
- ctx.ui.notify("Failed to restore previous session model after compatibility check failure.", "warning");
1792
- }
1793
- if (prevSessionThinkingLevel) {
1794
- pi.setThinkingLevel(prevSessionThinkingLevel);
1795
- }
1796
- }
1797
- const workflowMcpPrep = prepareWorkflowMcpForProject(ctx, s.basePath, workflowMcpPrepModel);
1798
- if (workflowMcpPrep && workflowMcpPrep.status !== "unchanged") {
1799
- const pauseMsg = "GSD workflow MCP config has been written. Restart Claude Code (or reload MCP servers), then run /gsd auto to continue.";
1800
- ctx.ui.notify(pauseMsg, "warning");
1801
- await deps.pauseAuto(ctx, pi, {
1802
- category: "provider",
1803
- isTransient: true,
1804
- message: pauseMsg,
1805
- });
1806
- return { action: "break", reason: "workflow-capability" };
1807
- }
1808
- ctx.ui.notify(compatibilityError, "error");
1809
- await deps.stopAuto(ctx, pi, compatibilityError);
1810
- return { action: "break", reason: "workflow-capability" };
1811
- }
1812
- // Scope workflow-logger buffer to this unit so post-finalize drains are
1813
- // per-unit. Without this, the module-level _buffer accumulates across every
1814
- // unit in the same Node process (see workflow-logger.ts module header).
1815
- _resetLogs();
1816
- const unitStartedAt = Date.now();
1817
- s.unitDispatchCount.set(dispatchKey, nextDispatchCount);
1818
- s.setCurrentUnit({ type: unitType, id: unitId, startedAt: unitStartedAt, workspaceRoot: s.basePath });
1819
- if (unitType === "execute-task") {
1820
- const { milestone, slice, task } = parseUnitId(unitId);
1821
- if (milestone && slice && task && isDbAvailable()) {
1822
- try {
1823
- const taskRow = getTask(milestone, slice, task);
1824
- if (taskRow)
1825
- s.sourceObservations.observePlanTask(taskRow);
1826
- }
1827
- catch (err) {
1828
- const message = err instanceof Error ? err.message : String(err);
1829
- logWarning("prompt", `failed to preload source observations for ${unitId}: ${message}`);
1830
- }
1831
- }
1832
- }
1833
- s.rootWriteBaseline = isIsolatedWorktreeSession(s)
1834
- ? captureRootDirtySnapshot(s.originalBasePath)
1835
- : null;
1836
- s.lastGitActionFailure = null;
1837
- s.lastGitActionStatus = null;
1838
- s.lastUnitAgentEndMessages = null;
1839
- setCurrentPhase(unitType, {
1840
- basePath: s.basePath,
1841
- traceId: ic.flowId,
1842
- turnId: `iter-${ic.iteration}`,
1843
- causedBy: "unit-start",
1844
- });
1845
- s.lastToolInvocationError = null; // #2883: clear stale error from previous unit
1846
- const unitStartSeq = ic.nextSeq();
1847
- deps.emitJournalEvent({ ts: new Date().toISOString(), flowId: ic.flowId, seq: unitStartSeq, eventType: "unit-start", data: { unitType, unitId } });
1848
- deps.captureAvailableSkills();
1849
- writeUnitRuntimeRecord(s.basePath, unitType, unitId, unitStartedAt, {
1850
- phase: "dispatched",
1851
- wrapupWarningSent: false,
1852
- timeoutAt: null,
1853
- lastProgressAt: unitStartedAt,
1854
- progressCount: 0,
1855
- lastProgressKind: "dispatch",
1856
- recoveryAttempts: resolveDispatchRecoveryAttempts(s.unitRecoveryCount, unitType, unitId),
1857
- });
1858
- // Progress widget + preconditions — deferred to after model selection so the
1859
- // widget's first render tick shows the correct model (#2899).
1860
- deps.updateProgressWidget(ctx, unitType, unitId, state);
1861
- deps.ensurePreconditions(unitType, unitId, s.basePath, state);
1862
- // Start unit supervision
1863
- deps.clearUnitTimeout();
1864
- deps.startUnitSupervision({
1865
- s,
1866
- ctx,
1867
- pi,
1868
- unitType,
1869
- unitId,
1870
- prefs,
1871
- buildSnapshotOpts: () => deps.buildSnapshotOpts(unitType, unitId),
1872
- buildRecoveryContext: () => ({
1873
- basePath: s.basePath,
1874
- verbose: s.verbose,
1875
- currentUnitStartedAt: s.currentUnit?.startedAt ?? Date.now(),
1876
- unitRecoveryCount: s.unitRecoveryCount,
1877
- }),
1878
- pauseAuto: deps.pauseAuto,
1879
- });
1880
- // Write preliminary lock (no session path yet — runUnit creates a new session).
1881
- // Crash recovery can still identify the in-flight unit from this lock.
1882
- deps.writeLock(deps.lockBase(), unitType, unitId);
1883
- debugLog("autoLoop", {
1884
- phase: "runUnit-start",
1885
- iteration: ic.iteration,
1886
- unitType,
1887
- unitId,
1888
- });
1889
- const pausedBeforeRun = s.paused;
1890
- const unitResult = await runUnit(ctx, pi, s, unitType, unitId, finalPrompt);
1891
- s.lastUnitAgentEndMessages = unitResult.event?.messages ?? null;
1892
- debugLog("autoLoop", {
1893
- phase: "runUnit-end",
1894
- iteration: ic.iteration,
1895
- unitType,
1896
- unitId,
1897
- status: unitResult.status,
1898
- });
1899
- if (unitResult.status === "completed" &&
1900
- s.currentUnit &&
1901
- (unitResult.event?.messages?.length ?? 0) === 0 &&
1902
- isSuspiciousGhostCompletion(ctx, unitResult.requestDispatchedAt ?? s.currentUnit.startedAt)) {
1903
- const message = `${unitType} ${unitId} completed without assistant output or tool calls; treating as a stale ghost completion.`;
1904
- debugLog("autoLoop", {
1905
- phase: "ghost-completion",
1906
- iteration: ic.iteration,
1907
- unitType,
1908
- unitId,
1909
- elapsedMs: Date.now() - (unitResult.requestDispatchedAt ?? s.currentUnit.startedAt),
1910
- });
1911
- logWarning("engine", message);
1912
- ctx.ui.notify(`${message} Pausing auto-mode before closeout side effects.`, "warning");
1913
- await emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, {
1914
- message,
1915
- category: "unknown",
1916
- isTransient: true,
1917
- });
1918
- s.clearCurrentUnit();
1919
- await deps.pauseAuto(ctx, pi);
1920
- return { action: "break", reason: "ghost-completion" };
1921
- }
1922
- // Now that runUnit has called newSession(), the session file path is correct.
1923
- const sessionFile = deps.getSessionFile(ctx);
1924
- deps.updateSessionLock(deps.lockBase(), unitType, unitId, sessionFile);
1925
- deps.writeLock(deps.lockBase(), unitType, unitId, sessionFile);
1926
- // Tag the most recent window entry with error info for stuck detection
1927
- const lastEntry = loopState.recentUnits[loopState.recentUnits.length - 1];
1928
- if (lastEntry) {
1929
- if (unitResult.errorContext) {
1930
- lastEntry.error = `${unitResult.errorContext.category}:${unitResult.errorContext.message}`.slice(0, 200);
1931
- }
1932
- else if (unitResult.status === "error" || unitResult.status === "cancelled") {
1933
- lastEntry.error = `${unitResult.status}:${unitType}/${unitId}`;
1934
- }
1935
- else if (unitResult.event?.messages?.length) {
1936
- const lastMsg = unitResult.event.messages[unitResult.event.messages.length - 1];
1937
- const msgStr = typeof lastMsg === "string" ? lastMsg : JSON.stringify(lastMsg);
1938
- if (/error|fail|exception/i.test(msgStr)) {
1939
- lastEntry.error = msgStr.slice(0, 200);
1940
- }
1941
- }
1942
- }
1943
- if (unitResult.status === "cancelled") {
1944
- if (_isPauseOriginCancelledResult(s.paused, unitResult.errorContext)) {
1945
- if (!pausedBeforeRun) {
1946
- const pauseContext = {
1947
- message: "Auto-mode paused during unit setup",
1948
- category: "aborted",
1949
- isTransient: true,
1950
- };
1951
- await deps.autoCommitUnit?.(s.basePath, unitType, unitId, ctx);
1952
- await emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, pauseContext);
1953
- return { action: "break", reason: "pause-during-setup" };
1954
- }
1955
- debugLog("autoLoop", { phase: "cancelled-after-pause", unitType, unitId });
1956
- return { action: "break", reason: "paused" };
1957
- }
1958
- const errorCategory = unitResult.errorContext?.category;
1959
- // Provider-error pause: agent_end recovery normally pauses before this
1960
- // branch. Provider readiness failures happen before dispatch, so pause here
1961
- // if nothing upstream already did.
1962
- if (errorCategory === "provider") {
1963
- if (!s.paused) {
1964
- const detail = unitResult.errorContext?.message ?? `Provider unavailable for ${unitType} ${unitId}`;
1965
- const isTransient = Boolean(unitResult.errorContext?.isTransient);
1966
- const retryAfterMs = unitResult.errorContext?.retryAfterMs ?? (isTransient ? 30_000 : undefined);
1967
- await pauseAutoForProviderError(ctx.ui, detail, () => deps.pauseAuto(ctx, pi), {
1968
- isRateLimit: false,
1969
- isTransient,
1970
- retryAfterMs,
1971
- resume: isTransient
1972
- ? () => {
1973
- void resumeAutoAfterProviderDelay(pi, ctx).catch((err) => {
1974
- logWarning("engine", `Provider error auto-resume failed: ${err instanceof Error ? err.message : String(err)}`);
1975
- });
1976
- }
1977
- : undefined,
1978
- });
1979
- }
1980
- await emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, unitResult.errorContext);
1981
- debugLog("autoLoop", { phase: "exit", reason: "provider-pause", isTransient: unitResult.errorContext?.isTransient });
1982
- return { action: "break", reason: "provider-pause" };
1983
- }
1984
- // Timeout category covers two distinct scenarios:
1985
- // 1. Session creation timeout (120s) — transient, auto-resume with backoff
1986
- // 2. Unit hard timeout (30min+) — stuck agent, pause for manual review
1987
- // Transient session-failed covers recoverable newSession failures and should
1988
- // pause instead of hard-stopping.
1989
- // Structural errors (TypeError, is not a function) are NOT transient
1990
- // and must hard-stop to avoid infinite retry loops.
1991
- if (unitResult.errorContext?.isTransient &&
1992
- errorCategory === "timeout") {
1993
- const isSessionCreationTimeout = unitResult.errorContext.message?.includes("Session creation timed out");
1994
- if (isSessionCreationTimeout) {
1995
- consecutiveSessionTimeouts += 1;
1996
- const baseRetryAfterMs = 30_000;
1997
- const retryAfterMs = baseRetryAfterMs * 2 ** Math.max(0, consecutiveSessionTimeouts - 1);
1998
- const allowAutoResume = consecutiveSessionTimeouts <= MAX_SESSION_TIMEOUT_AUTO_RESUMES;
1999
- if (!allowAutoResume) {
2000
- ctx.ui.notify(`Session creation timed out ${consecutiveSessionTimeouts} consecutive times for ${unitType} ${unitId}. Pausing for manual review.`, "warning");
2001
- }
2002
- debugLog("autoLoop", {
2003
- phase: "session-timeout-pause",
2004
- unitType, unitId,
2005
- consecutiveSessionTimeouts,
2006
- retryAfterMs,
2007
- allowAutoResume,
2008
- });
2009
- const errorDetail = ` for ${unitType} ${unitId}`;
2010
- await pauseAutoForProviderError(ctx.ui, errorDetail, () => deps.pauseAuto(ctx, pi), {
2011
- isRateLimit: false,
2012
- isTransient: allowAutoResume,
2013
- retryAfterMs,
2014
- resume: allowAutoResume
2015
- ? () => {
2016
- void resumeAutoAfterProviderDelay(pi, ctx).catch((err) => {
2017
- const message = err instanceof Error ? err.message : String(err);
2018
- ctx.ui.notify(`Session timeout recovery failed: ${message}`, "error");
2019
- });
2020
- }
2021
- : undefined,
2022
- });
2023
- await deps.autoCommitUnit?.(s.basePath, unitType, unitId, ctx);
2024
- await emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, unitResult.errorContext);
2025
- return { action: "break", reason: "session-timeout" };
2026
- }
2027
- // Unit hard timeout (30min+): pause without auto-resume — stuck agent
2028
- ctx.ui.notify(`Unit timed out for ${unitType} ${unitId} (supervision may have failed). Pausing auto-mode.`, "warning");
2029
- debugLog("autoLoop", { phase: "unit-hard-timeout-pause", unitType, unitId });
2030
- await deps.pauseAuto(ctx, pi);
2031
- await deps.autoCommitUnit?.(s.basePath, unitType, unitId, ctx);
2032
- await emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, unitResult.errorContext);
2033
- return { action: "break", reason: "unit-hard-timeout" };
2034
- }
2035
- if (unitResult.errorContext?.isTransient &&
2036
- errorCategory === "session-failed") {
2037
- ctx.ui.notify(`Session creation failed transiently for ${unitType} ${unitId}: ${unitResult.errorContext?.message ?? "unknown"}. Pausing auto-mode (recoverable).`, "warning");
2038
- debugLog("autoLoop", { phase: "session-start-transient-pause", unitType, unitId, category: errorCategory });
2039
- await deps.pauseAuto(ctx, pi);
2040
- await deps.autoCommitUnit?.(s.basePath, unitType, unitId, ctx);
2041
- await emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, unitResult.errorContext);
2042
- return { action: "break", reason: "session-timeout" };
2043
- }
2044
- if (unitResult.errorContext?.isTransient &&
2045
- errorCategory === "aborted") {
2046
- rememberRetryDispatch(s, { type: unitType, id: unitId }, iterData);
2047
- writeUnitRuntimeRecord(s.basePath, unitType, unitId, s.currentUnit?.startedAt ?? Date.now(), {
2048
- phase: "paused",
2049
- lastProgressAt: Date.now(),
2050
- lastProgressKind: "unit-aborted-pause",
2051
- });
2052
- ctx.ui.notify(`Unit ${unitType} ${unitId} was aborted (transient). Pausing auto-mode (recoverable).`, "warning");
2053
- debugLog("autoLoop", { phase: "unit-aborted-transient-pause", unitType, unitId, category: errorCategory });
2054
- await deps.pauseAuto(ctx, pi, unitResult.errorContext);
2055
- await deps.autoCommitUnit?.(s.basePath, unitType, unitId, ctx);
2056
- await emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, unitResult.errorContext);
2057
- return { action: "break", reason: "unit-aborted-pause" };
2058
- }
2059
- // All other cancelled states (structural errors, non-transient failures): hard stop
2060
- if (s.currentUnit) {
2061
- await deps.closeoutUnit(ctx, s.basePath, unitType, unitId, s.currentUnit.startedAt, deps.buildSnapshotOpts(unitType, unitId));
2062
- }
2063
- await deps.autoCommitUnit?.(s.basePath, unitType, unitId, ctx);
2064
- await emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, unitResult.errorContext);
2065
- const cancelledStop = _buildCancelledUnitStopReason(unitType, unitId, unitResult.errorContext);
2066
- ctx.ui.notify(cancelledStop.notifyMessage, "warning");
2067
- await deps.stopAuto(ctx, pi, cancelledStop.stopReason);
2068
- debugLog("autoLoop", { phase: "exit", reason: cancelledStop.loopReason });
2069
- return { action: "break", reason: cancelledStop.loopReason };
2070
- }
2071
- // ── Immediate unit closeout (metrics, activity log, memory) ────────
2072
- // Run right after runUnit() returns so telemetry is never lost to a
2073
- // crash between iterations.
2074
- // Guard: stopAuto() may have nulled s.currentUnit via s.reset() while
2075
- // this coroutine was suspended at `await runUnit(...)` (#2939).
2076
- if (s.currentUnit) {
2077
- // Reset session timeout counter — any successful unit clears the slate
2078
- consecutiveSessionTimeouts = 0;
2079
- await deps.closeoutUnit(ctx, s.basePath, unitType, unitId, s.currentUnit.startedAt, deps.buildSnapshotOpts(unitType, unitId));
2080
- }
2081
- // ── Zero tool-call guard (#1833, #2653) ──────────────────────────
2082
- // Any unit that completes with 0 tool calls made no real progress —
2083
- // likely context exhaustion where all tool calls errored out. Treat
2084
- // as failed so the unit is retried in a fresh context instead of
2085
- // silently passing through to artifact verification (which loops
2086
- // forever when the unit never produced its artifact).
2087
- {
2088
- const currentLedger = deps.getLedger();
2089
- if (currentLedger?.units) {
2090
- const lastUnit = [...currentLedger.units].reverse().find((u) => u.type === unitType && u.id === unitId && u.startedAt === _resolveCurrentUnitStartedAtForTest(s.currentUnit));
2091
- if (lastUnit && lastUnit.toolCalls === 0) {
2092
- const lastAssistantMessage = lastAssistantText(s.lastUnitAgentEndMessages);
2093
- const providerMessageClass = classifyZeroToolProviderMessage(lastAssistantMessage);
2094
- if (providerMessageClass && isTransient(providerMessageClass)) {
2095
- const retryAfterMs = "retryAfterMs" in providerMessageClass ? providerMessageClass.retryAfterMs : 15_000;
2096
- await pauseAutoForProviderError(ctx.ui, ` for ${unitType} ${unitId}`, () => deps.pauseAuto(ctx, pi), {
2097
- isRateLimit: providerMessageClass.kind === "rate-limit",
2098
- isTransient: true,
2099
- retryAfterMs,
2100
- resume: () => {
2101
- void resumeAutoAfterProviderDelay(pi, ctx).catch((err) => {
2102
- logWarning("engine", `Provider error auto-resume failed: ${err instanceof Error ? err.message : String(err)}`);
2103
- });
2104
- },
2105
- });
2106
- await emitCancelledUnitEnd(ic, unitType, unitId, unitStartSeq, {
2107
- message: lastAssistantMessage.slice(0, 200),
2108
- category: "provider",
2109
- isTransient: true,
2110
- retryAfterMs,
2111
- });
2112
- return {
2113
- action: "break",
2114
- reason: providerMessageClass.kind === "rate-limit" ? "rate-limit" : "api-timeout",
2115
- };
2116
- }
2117
- if (USER_DRIVEN_DEEP_UNITS.has(unitType) && isAwaitingUserInput(s.lastUnitAgentEndMessages ?? undefined)) {
2118
- debugLog("runUnitPhase", {
2119
- phase: "zero-tool-calls-awaiting-user-input",
2120
- unitType,
2121
- unitId,
2122
- });
2123
- }
2124
- else {
2125
- const zeroToolKey = `${unitType}/${unitId}`;
2126
- const attempt = (s.zeroToolRetryCount.get(zeroToolKey) ?? 0) + 1;
2127
- debugLog("runUnitPhase", {
2128
- phase: "zero-tool-calls",
2129
- unitType,
2130
- unitId,
2131
- attempt,
2132
- warning: "Unit completed with 0 tool calls — likely context exhaustion, marking as failed",
2133
- });
2134
- if (attempt > MAX_ZERO_TOOL_RETRIES) {
2135
- s.zeroToolRetryCount.delete(zeroToolKey);
2136
- ctx.ui.notify(`${unitType} ${unitId} completed with 0 tool calls — context exhaustion, pausing auto-mode after ${MAX_ZERO_TOOL_RETRIES} retry.`, "error");
2137
- await deps.pauseAuto(ctx, pi);
2138
- return { action: "break", reason: "zero-tool-calls-exhausted" };
2139
- }
2140
- s.zeroToolRetryCount.set(zeroToolKey, attempt);
2141
- ctx.ui.notify(`${unitType} ${unitId} completed with 0 tool calls — context exhaustion, will retry (attempt ${attempt}/${MAX_ZERO_TOOL_RETRIES})`, "warning");
2142
- return {
2143
- action: "retry",
2144
- reason: "zero-tool-calls",
2145
- data: {
2146
- unitStartedAt: _resolveCurrentUnitStartedAtForTest(s.currentUnit),
2147
- requestDispatchedAt: unitResult.requestDispatchedAt,
2148
- },
2149
- };
2150
- }
2151
- }
2152
- }
2153
- }
2154
- const skipArtifactVerification = unitType.startsWith("hook/") || unitType === "custom-step";
2155
- const artifactVerified = skipArtifactVerification ||
2156
- verifyExpectedArtifact(unitType, unitId, s.basePath);
2157
- if (s.currentUnitRouting) {
2158
- deps.recordOutcome(unitType, s.currentUnitRouting.tier, artifactVerified);
2159
- }
2160
- if (artifactVerified) {
2161
- s.unitDispatchCount.delete(dispatchKey);
2162
- s.unitRecoveryCount.delete(`${unitType}/${unitId}`);
2163
- s.zeroToolRetryCount.delete(dispatchKey);
2164
- }
2165
- // Write phase handoff anchor after successful research/planning completion
2166
- const anchorPhases = new Set(["research-milestone", "research-slice", "plan-milestone", "plan-slice"]);
2167
- if (artifactVerified && mid && anchorPhases.has(unitType)) {
2168
- try {
2169
- const { writePhaseAnchor } = await import("../phase-anchor.js");
2170
- writePhaseAnchor(s.basePath, mid, {
2171
- phase: unitType,
2172
- milestoneId: mid,
2173
- generatedAt: new Date().toISOString(),
2174
- intent: `Completed ${unitType} for ${unitId}`,
2175
- decisions: [],
2176
- blockers: [],
2177
- nextSteps: [],
2178
- });
2179
- }
2180
- catch (err) { /* non-fatal — anchor is advisory */
2181
- logWarning("engine", `phase anchor failed: ${err instanceof Error ? err.message : String(err)}`);
2182
- }
2183
- }
2184
- const unitEndStatus = !artifactVerified && unitResult.status === "completed"
2185
- ? "no-artifact"
2186
- : unitResult.status;
2187
- deps.emitJournalEvent({ ts: new Date().toISOString(), flowId: ic.flowId, seq: ic.nextSeq(), eventType: "unit-end", data: { unitType, unitId, status: unitEndStatus, artifactVerified, ...(unitResult.errorContext ? { errorContext: unitResult.errorContext } : {}) }, causedBy: { flowId: ic.flowId, seq: unitStartSeq } });
2188
- // ── Safety harness: checkpoint cleanup or rollback ──
2189
- if (s.checkpointSha) {
2190
- if (unitResult.status === "error" && safetyConfig.auto_rollback) {
2191
- const rolled = rollbackToCheckpoint(s.basePath, unitId, s.checkpointSha);
2192
- if (rolled) {
2193
- ctx.ui.notify(`Rolled back to pre-unit checkpoint for ${unitId}`, "info");
2194
- debugLog("runUnitPhase", { phase: "checkpoint-rollback", unitId });
2195
- }
2196
- }
2197
- else if (unitResult.status === "error") {
2198
- ctx.ui.notify(`Unit ${unitId} failed. Pre-unit checkpoint available at ${s.checkpointSha.slice(0, 8)}`, "warning");
2199
- }
2200
- else {
2201
- // Success — clean up checkpoint ref
2202
- cleanupCheckpoint(s.basePath, unitId);
2203
- debugLog("runUnitPhase", { phase: "checkpoint-cleaned", unitId });
2204
- }
2205
- s.checkpointSha = null;
2206
- }
2207
- return { action: "next", data: { unitStartedAt: _resolveCurrentUnitStartedAtForTest(s.currentUnit), requestDispatchedAt: unitResult.requestDispatchedAt } };
2208
- }
2209
- // ─── runFinalize ──────────────────────────────────────────────────────────────
2210
- /**
2211
- * Phase 5: Post-unit finalize — pre/post verification, UAT pause, step-wizard.
2212
- * Returns break/continue/next to control the outer loop.
2213
- */
2214
- export async function runFinalize(ic, iterData, loopState, sidecarItem) {
2215
- const { ctx, pi, s, deps } = ic;
2216
- const { pauseAfterUatDispatch } = iterData;
2217
- debugLog("autoLoop", { phase: "finalize", iteration: ic.iteration });
2218
- // Clear unit timeout (unit completed)
2219
- deps.clearUnitTimeout();
2220
- // Post-unit context for pre/post verification
2221
- const postUnitCtx = {
2222
- s,
2223
- ctx,
2224
- pi,
2225
- buildSnapshotOpts: deps.buildSnapshotOpts,
2226
- lockBase: deps.lockBase,
2227
- stopAuto: deps.stopAuto,
2228
- pauseAuto: deps.pauseAuto,
2229
- updateProgressWidget: deps.updateProgressWidget,
2230
- };
2231
- // Pre-verification processing (commit, doctor, state rebuild, etc.)
2232
- // Timeout guard: if postUnitPreVerification hangs (e.g., safety harness
2233
- // deadlock, browser teardown hang, worktree sync stall), force-continue
2234
- // after timeout so the auto-loop is not permanently frozen (#3757).
2235
- //
2236
- // On timeout, null out s.currentUnit so the timed-out task's late async
2237
- // mutations are harmless — postUnitPreVerification guards all side effects
2238
- // behind `if (s.currentUnit)`. The next iteration sets a fresh currentUnit.
2239
- // Sidecar items use lightweight pre-verification opts
2240
- const preVerificationOpts = sidecarItem
2241
- ? sidecarItem.kind === "hook"
2242
- ? { skipSettleDelay: true, skipWorktreeSync: true, agentEndMessages: s.lastUnitAgentEndMessages ?? undefined }
2243
- : { skipSettleDelay: true, agentEndMessages: s.lastUnitAgentEndMessages ?? undefined }
2244
- : { agentEndMessages: s.lastUnitAgentEndMessages ?? undefined };
2245
- const preUnitSnapshot = s.currentUnit
2246
- ? { type: s.currentUnit.type, id: s.currentUnit.id, startedAt: s.currentUnit.startedAt }
2247
- : null;
2248
- const clearFinalizingUnit = () => {
2249
- if (preUnitSnapshot &&
2250
- s.currentUnit?.type === preUnitSnapshot.type &&
2251
- s.currentUnit?.id === preUnitSnapshot.id &&
2252
- s.currentUnit?.startedAt === preUnitSnapshot.startedAt) {
2253
- s.clearCurrentUnit();
2254
- }
2255
- s.rootWriteBaseline = null;
2256
- };
2257
- clearCurrentPhase();
2258
- const preResultGuard = await withTimeout(deps.postUnitPreVerification(postUnitCtx, preVerificationOpts), FINALIZE_PRE_TIMEOUT_MS, "postUnitPreVerification");
2259
- if (preResultGuard.timedOut) {
2260
- return failClosedOnFinalizeTimeout(ic, iterData, loopState, "pre", preUnitSnapshot?.startedAt ?? Date.now());
2261
- }
2262
- const preResult = preResultGuard.value;
2263
- if (preResult === "dispatched") {
2264
- const dispatchedReason = s.lastGitActionFailure
2265
- ? "git-closeout-failure"
2266
- : "pre-verification-dispatched";
2267
- debugLog("autoLoop", {
2268
- phase: "exit",
2269
- reason: dispatchedReason,
2270
- gitError: s.lastGitActionFailure ?? undefined,
2271
- });
2272
- clearFinalizingUnit();
2273
- return { action: "break", reason: dispatchedReason };
2274
- }
2275
- if (preResult === "retry") {
2276
- if (sidecarItem) {
2277
- // Sidecar artifact retries are skipped — just continue
2278
- debugLog("autoLoop", { phase: "sidecar-artifact-retry-skipped", iteration: ic.iteration });
2279
- }
2280
- else {
2281
- // s.pendingVerificationRetry was set by postUnitPreVerification.
2282
- // Emit a dedicated journal event so forensics can distinguish bounded
2283
- // verification retries from genuine stuck-loop dispatch repetitions (#4540).
2284
- const retryInfo = s.pendingVerificationRetry;
2285
- deps.emitJournalEvent({
2286
- ts: new Date().toISOString(),
2287
- flowId: ic.flowId,
2288
- seq: ic.nextSeq(),
2289
- eventType: "artifact-verification-retry",
2290
- data: {
2291
- unitType: preUnitSnapshot?.type,
2292
- unitId: retryInfo?.unitId,
2293
- attempt: retryInfo?.attempt,
2294
- },
2295
- });
2296
- const retryPolicyResult = await applyVerificationRetryPolicy(ic, preUnitSnapshot?.type, "artifact-verification-retry");
2297
- if (retryPolicyResult) {
2298
- clearFinalizingUnit();
2299
- return retryPolicyResult;
2300
- }
2301
- // Continue the loop — next iteration will inject the retry context into the prompt.
2302
- rememberRetryDispatch(s, preUnitSnapshot, iterData);
2303
- debugLog("autoLoop", { phase: "artifact-verification-retry", iteration: ic.iteration });
2304
- clearFinalizingUnit();
2305
- return { action: "continue" };
2306
- }
2307
- }
2308
- if (pauseAfterUatDispatch) {
2309
- const pauseMid = iterData.mid;
2310
- const pauseSliceId = pauseMid && iterData.unitId.startsWith(`${pauseMid}/`)
2311
- ? iterData.unitId.slice(pauseMid.length + 1)
2312
- : undefined;
2313
- const guidance = pauseMid
2314
- ? buildManualValidationGuidance(s.basePath, pauseMid, {
2315
- uatPath: pauseSliceId
2316
- ? relSliceFile(s.basePath, pauseMid, pauseSliceId, "UAT")
2317
- : undefined,
2318
- })
2319
- : null;
2320
- const pauseMessage = guidance
2321
- ? `UAT requires human execution. Auto-mode will pause after this unit writes the result file.\n\n${guidance}`
2322
- : "UAT requires human execution. Auto-mode will pause after this unit writes the result file.";
2323
- ctx.ui.notify(pauseMessage, "info");
2324
- await deps.pauseAuto(ctx, pi);
2325
- debugLog("autoLoop", { phase: "exit", reason: "uat-pause" });
2326
- clearFinalizingUnit();
2327
- return { action: "break", reason: "uat-pause" };
2328
- }
2329
- // Verification gate
2330
- // Hook sidecar items skip verification entirely.
2331
- // Non-hook sidecar items run verification but skip retries (just continue).
2332
- const skipVerification = sidecarItem?.kind === "hook";
2333
- if (!skipVerification) {
2334
- const verificationResult = await deps.runPostUnitVerification({ s, ctx, pi }, deps.pauseAuto);
2335
- if (verificationResult === "pause") {
2336
- debugLog("autoLoop", { phase: "exit", reason: "verification-pause" });
2337
- clearFinalizingUnit();
2338
- return { action: "break", reason: "verification-pause" };
2339
- }
2340
- if (verificationResult === "retry") {
2341
- if (sidecarItem) {
2342
- // Sidecar verification retries are skipped — just continue
2343
- debugLog("autoLoop", { phase: "sidecar-verification-retry-skipped", iteration: ic.iteration });
2344
- }
2345
- else {
2346
- // s.pendingVerificationRetry was set by runPostUnitVerification.
2347
- const retryPolicyResult = await applyVerificationRetryPolicy(ic, iterData.unitType, "verification-retry");
2348
- if (retryPolicyResult) {
2349
- clearFinalizingUnit();
2350
- return retryPolicyResult;
2351
- }
2352
- // Continue the loop — next iteration will inject the retry context into the prompt.
2353
- rememberRetryDispatch(s, preUnitSnapshot, iterData);
2354
- debugLog("autoLoop", { phase: "verification-retry", iteration: ic.iteration });
2355
- clearFinalizingUnit();
2356
- return { action: "continue" };
2357
- }
2358
- }
2359
- }
2360
- // Post-verification processing (DB dual-write, hooks, triage, quick-tasks)
2361
- // Timeout guard: if postUnitPostVerification hangs (e.g., module import
2362
- // deadlock, SQLite transaction hang), force-continue after timeout so the
2363
- // auto-loop is not permanently frozen (#2344).
2364
- const postResultGuard = await withTimeout(deps.postUnitPostVerification(postUnitCtx), FINALIZE_POST_TIMEOUT_MS, "postUnitPostVerification");
2365
- if (postResultGuard.timedOut) {
2366
- return failClosedOnFinalizeTimeout(ic, iterData, loopState, "post", preUnitSnapshot?.startedAt ?? Date.now());
2367
- }
2368
- const postResult = postResultGuard.value;
2369
- if (postResult === "retry") {
2370
- if (sidecarItem) {
2371
- debugLog("autoLoop", { phase: "sidecar-pre-execution-retry-skipped", iteration: ic.iteration });
2372
- }
2373
- else {
2374
- const retryInfo = s.pendingVerificationRetry;
2375
- deps.emitJournalEvent({
2376
- ts: new Date().toISOString(),
2377
- flowId: ic.flowId,
2378
- seq: ic.nextSeq(),
2379
- eventType: "pre-execution-retry",
2380
- data: {
2381
- unitType: preUnitSnapshot?.type,
2382
- unitId: retryInfo?.unitId,
2383
- attempt: retryInfo?.attempt,
2384
- },
2385
- });
2386
- const retryPolicyResult = await applyVerificationRetryPolicy(ic, preUnitSnapshot?.type, "pre-execution-retry");
2387
- if (retryPolicyResult) {
2388
- clearFinalizingUnit();
2389
- return retryPolicyResult;
2390
- }
2391
- rememberRetryDispatch(s, preUnitSnapshot, iterData);
2392
- debugLog("autoLoop", {
2393
- phase: "pre-execution-retry",
2394
- iteration: ic.iteration,
2395
- unitType: preUnitSnapshot?.type,
2396
- unitId: retryInfo?.unitId,
2397
- attempt: retryInfo?.attempt,
2398
- });
2399
- clearFinalizingUnit();
2400
- return { action: "continue" };
2401
- }
2402
- }
2403
- if (postResult === "stopped") {
2404
- debugLog("autoLoop", {
2405
- phase: "exit",
2406
- reason: "post-verification-stopped",
2407
- });
2408
- clearFinalizingUnit();
2409
- return { action: "break", reason: "post-verification-stopped" };
2410
- }
2411
- if (postResult === "step-wizard") {
2412
- // Step mode — exit the loop (caller handles wizard)
2413
- debugLog("autoLoop", { phase: "exit", reason: "step-wizard" });
2414
- clearFinalizingUnit();
2415
- return { action: "break", reason: "step-wizard" };
2416
- }
2417
- if (preUnitSnapshot && isIsolatedWorktreeSession(s)) {
2418
- const leak = detectRootWriteLeak({
2419
- rootPath: s.originalBasePath,
2420
- worktreePath: s.basePath,
2421
- unitType: preUnitSnapshot.type,
2422
- unitId: preUnitSnapshot.id,
2423
- before: s.rootWriteBaseline,
2424
- });
2425
- s.rootWriteBaseline = null;
2426
- if (leak) {
2427
- const message = formatRootWriteLeakMessage(leak);
2428
- debugLog("autoLoop", {
2429
- phase: "root-write-leak",
2430
- unitType: preUnitSnapshot.type,
2431
- unitId: preUnitSnapshot.id,
2432
- rootPath: leak.rootPath,
2433
- worktreePath: leak.worktreePath,
2434
- files: leak.files.map((file) => ({ path: file.path, status: file.status })),
2435
- });
2436
- ctx.ui.notify(message, "error");
2437
- await deps.stopAuto(ctx, pi, "Root-write leak during isolated auto-mode", {
2438
- preserveCompletedMilestoneBranch: true,
2439
- });
2440
- clearFinalizingUnit();
2441
- return { action: "break", reason: "root-write-leak" };
2442
- }
2443
- }
2444
- else {
2445
- s.rootWriteBaseline = null;
2446
- }
2447
- if (preUnitSnapshot?.type === "complete-milestone" && s.currentMilestoneId) {
2448
- const stop = await _runMilestoneMergeOnceWithStashRestore(ic, s.currentMilestoneId, {
2449
- preserveCloseoutTranscript: true,
2450
- });
2451
- if (stop) {
2452
- clearFinalizingUnit();
2453
- return stop;
2454
- }
2455
- }
2456
- // Both pre and post verification completed without timeout — reset counter
2457
- loopState.consecutiveFinalizeTimeouts = 0;
2458
- if (preUnitSnapshot) {
2459
- writeUnitRuntimeRecord(s.basePath, preUnitSnapshot.type, preUnitSnapshot.id, preUnitSnapshot.startedAt, {
2460
- phase: "finalized",
2461
- lastProgressAt: Date.now(),
2462
- lastProgressKind: "finalize-success",
2463
- });
2464
- if (!preUnitSnapshot.type.startsWith("hook/") &&
2465
- preUnitSnapshot.type !== "custom-step" &&
2466
- preUnitSnapshot.type !== "complete-milestone") {
2467
- setAutoOutcomeWidget(ctx, {
2468
- ...buildPhaseHandoffOutcome({
2469
- unitType: preUnitSnapshot.type,
2470
- unitId: preUnitSnapshot.id,
2471
- agentEndMessages: s.lastUnitAgentEndMessages,
2472
- }),
2473
- startedAt: s.autoStartTime,
2474
- });
2475
- }
2476
- }
2477
- clearFinalizingUnit();
2478
- // Surface accumulated workflow-logger issues for this unit to the user.
2479
- // Warnings/errors logged during the unit are buffered in the logger and
2480
- // drained here so the user sees a single consolidated post-unit alert.
2481
- if (hasAnyIssues()) {
2482
- const { logs } = drainAndSummarize();
2483
- if (logs.length > 0) {
2484
- const severity = logs.some((e) => e.severity === "error") ? "error" : "warning";
2485
- ctx.ui.notify(formatForNotification(logs), severity);
2486
- }
2487
- }
2488
- if (preUnitSnapshot?.type === "complete-milestone" && s.currentMilestoneId) {
2489
- // cleanupAfterLoopExit skips gsd-progress when preserveCompletionSurface is true, so clear stale controls here.
2490
- ctx.ui.setStatus?.("gsd-step", undefined);
2491
- ctx.ui.setWidget?.("gsd-progress", undefined);
2492
- await deps.stopAuto(ctx, pi, `Milestone ${s.currentMilestoneId} complete`, {
2493
- completionWidget: {
2494
- milestoneId: s.currentMilestoneId,
2495
- milestoneTitle: iterData.midTitle,
2496
- },
2497
- });
2498
- return { action: "break", reason: "milestone-complete" };
2499
- }
2500
- return { action: "next", data: undefined };
2501
- }