@opengsd/gsd-pi 1.8.1 → 1.9.0

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 (339) hide show
  1. package/README.md +10 -8
  2. package/dist/cli.js +5 -1
  3. package/dist/headless-events.d.ts +2 -1
  4. package/dist/headless-events.js +11 -3
  5. package/dist/headless-milestone-readiness.d.ts +29 -0
  6. package/dist/headless-milestone-readiness.js +161 -0
  7. package/dist/headless.js +25 -2
  8. package/dist/print-mode-exit.d.ts +12 -0
  9. package/dist/print-mode-exit.js +14 -0
  10. package/dist/resources/.managed-resources-content-hash +1 -1
  11. package/dist/resources/GSD-WORKFLOW.md +16 -47
  12. package/dist/resources/extensions/browser-tools/capture.js +2 -77
  13. package/dist/resources/extensions/browser-tools/screenshot-constraints.js +83 -0
  14. package/dist/resources/extensions/claude-code-cli/stream-adapter.js +17 -2
  15. package/dist/resources/extensions/claude-code-cli/turn-assembler.js +30 -2
  16. package/dist/resources/extensions/gsd/auto-artifact-paths.js +2 -2
  17. package/dist/resources/extensions/gsd/auto-dispatch.js +74 -19
  18. package/dist/resources/extensions/gsd/auto-post-unit.js +4 -0
  19. package/dist/resources/extensions/gsd/auto-prompts.js +35 -1
  20. package/dist/resources/extensions/gsd/auto.js +5 -1
  21. package/dist/resources/extensions/gsd/bootstrap/db-tools.js +78 -4
  22. package/dist/resources/extensions/gsd/bootstrap/write-gate.js +84 -26
  23. package/dist/resources/extensions/gsd/command-feedback.js +16 -12
  24. package/dist/resources/extensions/gsd/compat/compat-marker.js +19 -2
  25. package/dist/resources/extensions/gsd/db/command-queue.js +7 -2
  26. package/dist/resources/extensions/gsd/db/engine.js +51 -16
  27. package/dist/resources/extensions/gsd/db/writers/cascades.js +5 -1
  28. package/dist/resources/extensions/gsd/db/writers/status.js +13 -3
  29. package/dist/resources/extensions/gsd/db-base-schema.js +28 -0
  30. package/dist/resources/extensions/gsd/db-migration-steps.js +30 -0
  31. package/dist/resources/extensions/gsd/db-schema-metadata.js +4 -1
  32. package/dist/resources/extensions/gsd/docs/preferences-reference.md +4 -4
  33. package/dist/resources/extensions/gsd/flat-phase-migration.js +156 -21
  34. package/dist/resources/extensions/gsd/gsd-db.js +187 -45
  35. package/dist/resources/extensions/gsd/guided-flow.js +29 -10
  36. package/dist/resources/extensions/gsd/markdown-renderer.js +16 -2
  37. package/dist/resources/extensions/gsd/md-importer.js +102 -14
  38. package/dist/resources/extensions/gsd/migrate/command.js +19 -162
  39. package/dist/resources/extensions/gsd/migrate/execution.js +98 -0
  40. package/dist/resources/extensions/gsd/migrate/plan.js +49 -0
  41. package/dist/resources/extensions/gsd/migrate/planning-writer.js +12 -17
  42. package/dist/resources/extensions/gsd/migrate/presentation.js +64 -0
  43. package/dist/resources/extensions/gsd/parallel-eligibility.js +5 -4
  44. package/dist/resources/extensions/gsd/parallel-monitor-overlay.js +28 -43
  45. package/dist/resources/extensions/gsd/paths.js +4 -1
  46. package/dist/resources/extensions/gsd/phase-anchor.js +7 -2
  47. package/dist/resources/extensions/gsd/post-execution-checks.js +4 -4
  48. package/dist/resources/extensions/gsd/prompts/refine-slice.md +2 -2
  49. package/dist/resources/extensions/gsd/safety/evidence-collector.js +26 -1
  50. package/dist/resources/extensions/gsd/safety/evidence-cross-ref.js +30 -5
  51. package/dist/resources/extensions/gsd/state-reconciliation/drift/external-markdown-edit.js +27 -13
  52. package/dist/resources/extensions/gsd/state-reconciliation/drift/external-planning-edit.js +13 -3
  53. package/dist/resources/extensions/gsd/stop-notice.js +15 -1
  54. package/dist/resources/extensions/gsd/sync-lock.js +13 -7
  55. package/dist/resources/extensions/gsd/tools/complete-task.js +82 -1
  56. package/dist/resources/extensions/gsd/tools/plan-task.js +13 -15
  57. package/dist/resources/extensions/gsd/tools/reassess-roadmap.js +18 -15
  58. package/dist/resources/extensions/gsd/tools/replan-task.js +128 -0
  59. package/dist/resources/extensions/gsd/tools/rework-brief.js +74 -0
  60. package/dist/resources/extensions/gsd/tools/workflow-tool-executors.js +81 -0
  61. package/dist/resources/extensions/gsd/unit-registry.js +4 -0
  62. package/dist/resources/extensions/gsd/uok/plan-v2.js +19 -3
  63. package/dist/resources/extensions/gsd/worktree-state-projection.js +6 -0
  64. package/dist/resources/extensions/mac-tools/index.js +31 -9
  65. package/dist/tsconfig.extensions.tsbuildinfo +1 -1
  66. package/dist/web/standalone/.next/BUILD_ID +1 -1
  67. package/dist/web/standalone/.next/app-path-routes-manifest.json +8 -8
  68. package/dist/web/standalone/.next/build-manifest.json +2 -2
  69. package/dist/web/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  70. package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
  71. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  72. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  73. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  74. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  75. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  76. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  77. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  78. package/dist/web/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  79. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  80. package/dist/web/standalone/.next/server/app/_not-found.rsc +2 -2
  81. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  82. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  83. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  84. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  85. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  86. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  87. package/dist/web/standalone/.next/server/app/index.html +1 -1
  88. package/dist/web/standalone/.next/server/app/index.rsc +2 -2
  89. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  90. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +2 -2
  91. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  92. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +2 -2
  93. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  94. package/dist/web/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  95. package/dist/web/standalone/.next/server/app-paths-manifest.json +8 -8
  96. package/dist/web/standalone/.next/server/chunks/8357.js +1 -1
  97. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  98. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  99. package/dist/web/standalone/.next/server/pages/500.html +1 -1
  100. package/dist/web/standalone/.next/static/css/3b1ceb7abfb9a230.css +1 -0
  101. package/dist/web/standalone/node_modules/@gsd/native/package.json +1 -1
  102. package/dist/web/standalone/node_modules/node-pty/build/Makefile +2 -2
  103. package/dist/web/standalone/node_modules/node-pty/build/Release/pty.node +0 -0
  104. package/dist/web/standalone/node_modules/node-pty/build/pty.target.mk +14 -14
  105. package/dist/web/standalone/package.json +0 -1
  106. package/dist/web-mode.js +31 -3
  107. package/integrations/hermes/open_gsd_hermes/gsd_client.py +1 -1
  108. package/integrations/hermes/pyproject.toml +1 -1
  109. package/package.json +12 -10
  110. package/packages/cloud-mcp-gateway/package.json +2 -2
  111. package/packages/contracts/dist/workflow.d.ts +14 -0
  112. package/packages/contracts/dist/workflow.d.ts.map +1 -1
  113. package/packages/contracts/dist/workflow.js +16 -0
  114. package/packages/contracts/dist/workflow.js.map +1 -1
  115. package/packages/contracts/package.json +1 -1
  116. package/packages/daemon/dist/cloud-config.d.ts +1 -1
  117. package/packages/daemon/dist/cloud-config.d.ts.map +1 -1
  118. package/packages/daemon/dist/cloud-config.js +5 -1
  119. package/packages/daemon/dist/cloud-config.js.map +1 -1
  120. package/packages/daemon/dist/cloud-config.test.js +51 -1
  121. package/packages/daemon/dist/cloud-config.test.js.map +1 -1
  122. package/packages/daemon/dist/local-tool-executor.d.ts.map +1 -1
  123. package/packages/daemon/dist/local-tool-executor.js +2 -0
  124. package/packages/daemon/dist/local-tool-executor.js.map +1 -1
  125. package/packages/daemon/package.json +6 -6
  126. package/packages/gsd-agent-core/package.json +5 -5
  127. package/packages/gsd-agent-modes/package.json +7 -7
  128. package/packages/gsd-cloud/dist/cli.d.ts +5 -0
  129. package/packages/gsd-cloud/dist/cli.d.ts.map +1 -0
  130. package/packages/gsd-cloud/dist/cli.js +160 -0
  131. package/packages/gsd-cloud/dist/cli.js.map +1 -0
  132. package/packages/gsd-cloud/dist/cloud-config.d.ts +19 -0
  133. package/packages/gsd-cloud/dist/cloud-config.d.ts.map +1 -0
  134. package/packages/gsd-cloud/dist/cloud-config.js +231 -0
  135. package/packages/gsd-cloud/dist/cloud-config.js.map +1 -0
  136. package/packages/gsd-cloud/dist/cloud-config.test.d.ts +2 -0
  137. package/packages/gsd-cloud/dist/cloud-config.test.d.ts.map +1 -0
  138. package/packages/gsd-cloud/dist/cloud-config.test.js +118 -0
  139. package/packages/gsd-cloud/dist/cloud-config.test.js.map +1 -0
  140. package/packages/gsd-cloud/dist/cloud-gateway-lookup.test.d.ts +2 -0
  141. package/packages/gsd-cloud/dist/cloud-gateway-lookup.test.d.ts.map +1 -0
  142. package/packages/gsd-cloud/dist/cloud-gateway-lookup.test.js +37 -0
  143. package/packages/gsd-cloud/dist/cloud-gateway-lookup.test.js.map +1 -0
  144. package/packages/gsd-cloud/dist/cloud-runtime.d.ts +35 -0
  145. package/packages/gsd-cloud/dist/cloud-runtime.d.ts.map +1 -0
  146. package/packages/gsd-cloud/dist/cloud-runtime.js +258 -0
  147. package/packages/gsd-cloud/dist/cloud-runtime.js.map +1 -0
  148. package/packages/gsd-cloud/dist/cloud-runtime.test.d.ts +2 -0
  149. package/packages/gsd-cloud/dist/cloud-runtime.test.d.ts.map +1 -0
  150. package/packages/gsd-cloud/dist/cloud-runtime.test.js +88 -0
  151. package/packages/gsd-cloud/dist/cloud-runtime.test.js.map +1 -0
  152. package/packages/gsd-cloud/dist/cloud-token.d.ts +3 -0
  153. package/packages/gsd-cloud/dist/cloud-token.d.ts.map +1 -0
  154. package/packages/gsd-cloud/dist/cloud-token.js +37 -0
  155. package/packages/gsd-cloud/dist/cloud-token.js.map +1 -0
  156. package/packages/gsd-cloud/dist/config.d.ts +17 -0
  157. package/packages/gsd-cloud/dist/config.d.ts.map +1 -0
  158. package/packages/gsd-cloud/dist/config.js +146 -0
  159. package/packages/gsd-cloud/dist/config.js.map +1 -0
  160. package/packages/gsd-cloud/dist/device-flow.d.ts +24 -0
  161. package/packages/gsd-cloud/dist/device-flow.d.ts.map +1 -0
  162. package/packages/gsd-cloud/dist/device-flow.js +128 -0
  163. package/packages/gsd-cloud/dist/device-flow.js.map +1 -0
  164. package/packages/gsd-cloud/dist/device-flow.test.d.ts +2 -0
  165. package/packages/gsd-cloud/dist/device-flow.test.d.ts.map +1 -0
  166. package/packages/gsd-cloud/dist/device-flow.test.js +155 -0
  167. package/packages/gsd-cloud/dist/device-flow.test.js.map +1 -0
  168. package/packages/gsd-cloud/dist/executors/claude-executor.d.ts +6 -0
  169. package/packages/gsd-cloud/dist/executors/claude-executor.d.ts.map +1 -0
  170. package/packages/gsd-cloud/dist/executors/claude-executor.js +15 -0
  171. package/packages/gsd-cloud/dist/executors/claude-executor.js.map +1 -0
  172. package/packages/gsd-cloud/dist/executors/codex-executor.d.ts +6 -0
  173. package/packages/gsd-cloud/dist/executors/codex-executor.d.ts.map +1 -0
  174. package/packages/gsd-cloud/dist/executors/codex-executor.js +15 -0
  175. package/packages/gsd-cloud/dist/executors/codex-executor.js.map +1 -0
  176. package/packages/gsd-cloud/dist/executors/executor.d.ts +28 -0
  177. package/packages/gsd-cloud/dist/executors/executor.d.ts.map +1 -0
  178. package/packages/gsd-cloud/dist/executors/executor.js +11 -0
  179. package/packages/gsd-cloud/dist/executors/executor.js.map +1 -0
  180. package/packages/gsd-cloud/dist/executors/gsd-pi-executor.d.ts +34 -0
  181. package/packages/gsd-cloud/dist/executors/gsd-pi-executor.d.ts.map +1 -0
  182. package/packages/gsd-cloud/dist/executors/gsd-pi-executor.js +179 -0
  183. package/packages/gsd-cloud/dist/executors/gsd-pi-executor.js.map +1 -0
  184. package/packages/gsd-cloud/dist/executors/gsd-pi-executor.test.d.ts +2 -0
  185. package/packages/gsd-cloud/dist/executors/gsd-pi-executor.test.d.ts.map +1 -0
  186. package/packages/gsd-cloud/dist/executors/gsd-pi-executor.test.js +44 -0
  187. package/packages/gsd-cloud/dist/executors/gsd-pi-executor.test.js.map +1 -0
  188. package/packages/gsd-cloud/dist/executors/index.d.ts +17 -0
  189. package/packages/gsd-cloud/dist/executors/index.d.ts.map +1 -0
  190. package/packages/gsd-cloud/dist/executors/index.js +29 -0
  191. package/packages/gsd-cloud/dist/executors/index.js.map +1 -0
  192. package/packages/gsd-cloud/dist/executors/mcp-stdio-client.d.ts +36 -0
  193. package/packages/gsd-cloud/dist/executors/mcp-stdio-client.d.ts.map +1 -0
  194. package/packages/gsd-cloud/dist/executors/mcp-stdio-client.js +176 -0
  195. package/packages/gsd-cloud/dist/executors/mcp-stdio-client.js.map +1 -0
  196. package/packages/gsd-cloud/dist/executors/mcp-stdio-client.test.d.ts +2 -0
  197. package/packages/gsd-cloud/dist/executors/mcp-stdio-client.test.d.ts.map +1 -0
  198. package/packages/gsd-cloud/dist/executors/mcp-stdio-client.test.js +34 -0
  199. package/packages/gsd-cloud/dist/executors/mcp-stdio-client.test.js.map +1 -0
  200. package/packages/gsd-cloud/dist/index.d.ts +7 -0
  201. package/packages/gsd-cloud/dist/index.d.ts.map +1 -0
  202. package/packages/gsd-cloud/dist/index.js +8 -0
  203. package/packages/gsd-cloud/dist/index.js.map +1 -0
  204. package/packages/gsd-cloud/dist/inject-gateway.d.ts +16 -0
  205. package/packages/gsd-cloud/dist/inject-gateway.d.ts.map +1 -0
  206. package/packages/gsd-cloud/dist/inject-gateway.js +29 -0
  207. package/packages/gsd-cloud/dist/inject-gateway.js.map +1 -0
  208. package/packages/gsd-cloud/dist/inject-gateway.test.d.ts +2 -0
  209. package/packages/gsd-cloud/dist/inject-gateway.test.d.ts.map +1 -0
  210. package/packages/gsd-cloud/dist/inject-gateway.test.js +41 -0
  211. package/packages/gsd-cloud/dist/inject-gateway.test.js.map +1 -0
  212. package/packages/gsd-cloud/dist/logger.d.ts +25 -0
  213. package/packages/gsd-cloud/dist/logger.d.ts.map +1 -0
  214. package/packages/gsd-cloud/dist/logger.js +72 -0
  215. package/packages/gsd-cloud/dist/logger.js.map +1 -0
  216. package/packages/gsd-cloud/dist/types.d.ts +51 -0
  217. package/packages/gsd-cloud/dist/types.d.ts.map +1 -0
  218. package/packages/gsd-cloud/dist/types.js +9 -0
  219. package/packages/gsd-cloud/dist/types.js.map +1 -0
  220. package/packages/gsd-cloud/package.json +3 -3
  221. package/packages/mcp-server/README.md +8 -0
  222. package/packages/mcp-server/dist/workflow-tools.d.ts.map +1 -1
  223. package/packages/mcp-server/dist/workflow-tools.js +64 -2
  224. package/packages/mcp-server/dist/workflow-tools.js.map +1 -1
  225. package/packages/mcp-server/package.json +4 -4
  226. package/packages/native/package.json +1 -1
  227. package/packages/pi-agent-core/package.json +1 -1
  228. package/packages/pi-ai/dist/models.generated.d.ts +60 -0
  229. package/packages/pi-ai/dist/models.generated.d.ts.map +1 -1
  230. package/packages/pi-ai/dist/models.generated.js +54 -0
  231. package/packages/pi-ai/dist/models.generated.js.map +1 -1
  232. package/packages/pi-ai/dist/providers/amazon-bedrock.js +1 -0
  233. package/packages/pi-ai/dist/providers/amazon-bedrock.js.map +1 -1
  234. package/packages/pi-ai/dist/providers/anthropic.js +19 -0
  235. package/packages/pi-ai/dist/providers/anthropic.js.map +1 -1
  236. package/packages/pi-ai/package.json +1 -1
  237. package/packages/pi-coding-agent/package.json +7 -7
  238. package/packages/pi-tui/package.json +2 -2
  239. package/packages/rpc-client/package.json +2 -2
  240. package/pkg/package.json +1 -1
  241. package/src/resources/GSD-WORKFLOW.md +16 -47
  242. package/src/resources/extensions/browser-tools/capture.ts +2 -86
  243. package/src/resources/extensions/browser-tools/screenshot-constraints.ts +94 -0
  244. package/src/resources/extensions/claude-code-cli/stream-adapter.ts +18 -1
  245. package/src/resources/extensions/claude-code-cli/tests/stream-adapter.test.ts +108 -0
  246. package/src/resources/extensions/claude-code-cli/turn-assembler.ts +30 -2
  247. package/src/resources/extensions/gsd/auto-artifact-paths.ts +2 -2
  248. package/src/resources/extensions/gsd/auto-dispatch.ts +86 -19
  249. package/src/resources/extensions/gsd/auto-post-unit.ts +4 -0
  250. package/src/resources/extensions/gsd/auto-prompts.ts +38 -1
  251. package/src/resources/extensions/gsd/auto.ts +5 -1
  252. package/src/resources/extensions/gsd/bootstrap/db-tools.ts +91 -4
  253. package/src/resources/extensions/gsd/bootstrap/write-gate.ts +80 -24
  254. package/src/resources/extensions/gsd/command-feedback.ts +19 -12
  255. package/src/resources/extensions/gsd/compat/compat-marker.ts +21 -4
  256. package/src/resources/extensions/gsd/db/command-queue.ts +7 -1
  257. package/src/resources/extensions/gsd/db/engine.ts +53 -17
  258. package/src/resources/extensions/gsd/db/writers/cascades.ts +5 -1
  259. package/src/resources/extensions/gsd/db/writers/status.ts +25 -8
  260. package/src/resources/extensions/gsd/db-base-schema.ts +30 -0
  261. package/src/resources/extensions/gsd/db-migration-steps.ts +32 -0
  262. package/src/resources/extensions/gsd/db-schema-metadata.ts +4 -1
  263. package/src/resources/extensions/gsd/docs/preferences-reference.md +4 -4
  264. package/src/resources/extensions/gsd/flat-phase-migration.ts +160 -19
  265. package/src/resources/extensions/gsd/gsd-db.ts +255 -52
  266. package/src/resources/extensions/gsd/guided-flow.ts +39 -10
  267. package/src/resources/extensions/gsd/markdown-renderer.ts +23 -7
  268. package/src/resources/extensions/gsd/md-importer.ts +109 -11
  269. package/src/resources/extensions/gsd/migrate/command.ts +21 -227
  270. package/src/resources/extensions/gsd/migrate/execution.ts +136 -0
  271. package/src/resources/extensions/gsd/migrate/plan.ts +101 -0
  272. package/src/resources/extensions/gsd/migrate/planning-writer.ts +12 -20
  273. package/src/resources/extensions/gsd/migrate/presentation.ts +83 -0
  274. package/src/resources/extensions/gsd/parallel-eligibility.ts +5 -4
  275. package/src/resources/extensions/gsd/parallel-monitor-overlay.ts +37 -40
  276. package/src/resources/extensions/gsd/paths.ts +4 -1
  277. package/src/resources/extensions/gsd/phase-anchor.ts +8 -2
  278. package/src/resources/extensions/gsd/post-execution-checks.ts +4 -4
  279. package/src/resources/extensions/gsd/prompts/refine-slice.md +2 -2
  280. package/src/resources/extensions/gsd/safety/evidence-collector.ts +28 -1
  281. package/src/resources/extensions/gsd/safety/evidence-cross-ref.ts +31 -5
  282. package/src/resources/extensions/gsd/state-reconciliation/drift/external-markdown-edit.ts +30 -13
  283. package/src/resources/extensions/gsd/state-reconciliation/drift/external-planning-edit.ts +16 -3
  284. package/src/resources/extensions/gsd/state-reconciliation/types.ts +2 -2
  285. package/src/resources/extensions/gsd/stop-notice.ts +18 -1
  286. package/src/resources/extensions/gsd/sync-lock.ts +14 -6
  287. package/src/resources/extensions/gsd/tests/closeout-git-deferral.test.ts +96 -1
  288. package/src/resources/extensions/gsd/tests/command-feedback.test.ts +12 -0
  289. package/src/resources/extensions/gsd/tests/compat-marker.test.ts +104 -0
  290. package/src/resources/extensions/gsd/tests/complete-task.test.ts +286 -0
  291. package/src/resources/extensions/gsd/tests/db-engine-migrate-guards.test.ts +186 -0
  292. package/src/resources/extensions/gsd/tests/derive-state-db.test.ts +29 -0
  293. package/src/resources/extensions/gsd/tests/discuss-routing-fixes.test.ts +123 -0
  294. package/src/resources/extensions/gsd/tests/dispatch-missing-task-plans.test.ts +50 -0
  295. package/src/resources/extensions/gsd/tests/dispatch-rule-coverage.test.ts +49 -0
  296. package/src/resources/extensions/gsd/tests/evidence-cross-ref.test.ts +81 -0
  297. package/src/resources/extensions/gsd/tests/evidence-xref-gsd-exec.test.ts +22 -0
  298. package/src/resources/extensions/gsd/tests/external-edit-scoped-import.test.ts +262 -0
  299. package/src/resources/extensions/gsd/tests/flat-phase-migration.test.ts +202 -0
  300. package/src/resources/extensions/gsd/tests/gate-storage.test.ts +29 -0
  301. package/src/resources/extensions/gsd/tests/gsd-db.test.ts +25 -0
  302. package/src/resources/extensions/gsd/tests/import-slice-milestone-completion-preserve.test.ts +116 -0
  303. package/src/resources/extensions/gsd/tests/migrate-plan.test.ts +68 -0
  304. package/src/resources/extensions/gsd/tests/migrate-presentation.test.ts +98 -0
  305. package/src/resources/extensions/gsd/tests/migrate-safety-audit.test.ts +1 -1
  306. package/src/resources/extensions/gsd/tests/milestone-leases.test.ts +55 -0
  307. package/src/resources/extensions/gsd/tests/parallel-eligibility-file-overlap.test.ts +146 -0
  308. package/src/resources/extensions/gsd/tests/parallel-monitor-overlay.test.ts +59 -0
  309. package/src/resources/extensions/gsd/tests/phase-anchor.test.ts +32 -4
  310. package/src/resources/extensions/gsd/tests/plan-task.test.ts +26 -23
  311. package/src/resources/extensions/gsd/tests/planning-writer.test.ts +29 -0
  312. package/src/resources/extensions/gsd/tests/post-execution-checks.test.ts +22 -0
  313. package/src/resources/extensions/gsd/tests/reassess-handler.test.ts +50 -0
  314. package/src/resources/extensions/gsd/tests/replan-task-handler.test.ts +103 -0
  315. package/src/resources/extensions/gsd/tests/rework-brief.test.ts +197 -0
  316. package/src/resources/extensions/gsd/tests/skip-slice-cascades-tasks.test.ts +21 -0
  317. package/src/resources/extensions/gsd/tests/stop-notice.test.ts +17 -0
  318. package/src/resources/extensions/gsd/tests/sync-lock.test.ts +19 -0
  319. package/src/resources/extensions/gsd/tests/unit-context-composer.test.ts +34 -0
  320. package/src/resources/extensions/gsd/tests/uok-plan-v2-wiring.test.ts +93 -1
  321. package/src/resources/extensions/gsd/tests/workflow-mcp.test.ts +2 -0
  322. package/src/resources/extensions/gsd/tests/workflow-migration-gates.test.ts +139 -0
  323. package/src/resources/extensions/gsd/tests/worktree-state-projection.test.ts +36 -0
  324. package/src/resources/extensions/gsd/tests/write-gate-seam.test.ts +52 -0
  325. package/src/resources/extensions/gsd/tools/complete-task.ts +120 -0
  326. package/src/resources/extensions/gsd/tools/plan-task.ts +14 -16
  327. package/src/resources/extensions/gsd/tools/reassess-roadmap.ts +18 -17
  328. package/src/resources/extensions/gsd/tools/replan-task.ts +160 -0
  329. package/src/resources/extensions/gsd/tools/rework-brief.ts +91 -0
  330. package/src/resources/extensions/gsd/tools/workflow-tool-executors.ts +92 -0
  331. package/src/resources/extensions/gsd/types.ts +11 -0
  332. package/src/resources/extensions/gsd/unit-registry.ts +4 -0
  333. package/src/resources/extensions/gsd/uok/plan-v2.ts +20 -3
  334. package/src/resources/extensions/gsd/worktree-state-projection.ts +12 -0
  335. package/src/resources/extensions/mac-tools/index.ts +52 -9
  336. package/src/resources/extensions/mac-tools/tests/mac-screenshot-payload.test.cjs +70 -0
  337. package/dist/web/standalone/.next/static/css/18c2fdf261bfc1b7.css +0 -1
  338. /package/dist/web/standalone/.next/static/{UaXRrOYxBpG9QBINKhZkg → BE5XoklToI6lZjRzpXih8}/_buildManifest.js +0 -0
  339. /package/dist/web/standalone/.next/static/{UaXRrOYxBpG9QBINKhZkg → BE5XoklToI6lZjRzpXih8}/_ssgManifest.js +0 -0
@@ -17,6 +17,8 @@ import {
17
17
  transaction,
18
18
  updateMilestoneStatus,
19
19
  updateSliceStatus,
20
+ getMilestoneSlices,
21
+ getSliceTasks,
20
22
  _getAdapter,
21
23
  } from './gsd-db.js';
22
24
  import { openWorkflowDatabasePath } from './db-workspace.js';
@@ -43,6 +45,26 @@ const VALID_MADE_BY = new Set(['human', 'agent', 'collaborative']);
43
45
 
44
46
  const IMPORT_COMPLETE_STATUSES = new Set(['complete', 'done']);
45
47
 
48
+ /**
49
+ * Derive the set of milestone ids a projection entry's `entities` touch. Marker
50
+ * entity ids are fully-qualified DB ids (`M001`, `M001/S01`, `M001/S01/T01`), so
51
+ * the milestone id is always the first `/`-segment — independent of the on-disk
52
+ * layout (legacy `milestones/<MID>/…` vs flat `phases/NN-slug/…`). The
53
+ * external-edit drift repairs (#027) feed this into
54
+ * `migrateHierarchyToDb(..., { statusAuthoritativeMilestones })` to scope status
55
+ * authority to exactly the milestone(s) a drifted file projects. Empty/blank
56
+ * entries are dropped, so an entity-less entry yields an empty set (repair then
57
+ * preserves DB status everywhere — fail toward the DB, not markdown).
58
+ */
59
+ export function milestoneIdsFromEntities(entities: readonly string[]): Set<string> {
60
+ const ids = new Set<string>();
61
+ for (const e of entities) {
62
+ const milestoneId = e.split('/')[0];
63
+ if (milestoneId) ids.add(milestoneId);
64
+ }
65
+ return ids;
66
+ }
67
+
46
68
  /**
47
69
  * Completion timestamp for an entity imported as complete: the SUMMARY.md mtime
48
70
  * when one exists (deterministic, matches the completion drift handler), else
@@ -676,15 +698,35 @@ function findFileByPrefixAndSuffix(dir: string, idPrefix: string, suffix: string
676
698
  * Uses INSERT OR IGNORE for idempotency. Insert order: milestones → slices → tasks.
677
699
  * Ghost milestones (dirs with no CONTEXT, ROADMAP, or SUMMARY) are skipped.
678
700
  *
701
+ * `opts.statusAuthoritativeMilestones` narrows *status* authority. It exists for
702
+ * the scoped external-edit drift repair: detection knows exactly which
703
+ * projection file drifted, but this import walks the whole tree. Without scoping,
704
+ * an unrelated file that is stale from gsd-pi's own miss (a forgotten render)
705
+ * rides along with markdown authority it was never granted and its stale checked
706
+ * checkbox silently reverts a reopened slice/milestone in the DB (#027).
707
+ *
708
+ * - opts absent → full markdown authority for every milestone (initial migration,
709
+ * gsd-core full import, /gsd recover rebuild). Behavior is identical to before.
710
+ * - opts present → for a milestone NOT in the set whose DB row *already exists*,
711
+ * the existing DB status is preserved: the slice upsert is fed the current DB
712
+ * status (so a stale `complete` checkbox can't overwrite a reopened `pending`),
713
+ * and the complete-status backfills are skipped. Milestone rows are already
714
+ * protected by INSERT OR IGNORE. Rows that do not exist yet are inserted with
715
+ * the parsed status regardless of scope (new content is new content).
716
+ *
679
717
  * Returns count of inserted hierarchy items.
680
718
  */
681
- export function migrateHierarchyToDb(basePath: string): {
719
+ export function migrateHierarchyToDb(
720
+ basePath: string,
721
+ opts?: { statusAuthoritativeMilestones?: ReadonlySet<string> },
722
+ ): {
682
723
  milestones: number;
683
724
  slices: number;
684
725
  tasks: number;
685
726
  } {
686
727
  const counts = { milestones: 0, slices: 0, tasks: 0 };
687
728
  const milestoneIds = findMilestoneIds(basePath);
729
+ const statusScope = opts?.statusAuthoritativeMilestones;
688
730
 
689
731
  for (const milestoneId of milestoneIds) {
690
732
  // Check for ghost milestones — skip dirs with no meaningful content
@@ -745,8 +787,30 @@ export function migrateHierarchyToDb(basePath: string): {
745
787
  }
746
788
  }
747
789
 
748
- // Insert milestone (FK parent must come first)
749
- insertMilestone({
790
+ // #027: when a status scope is supplied, a milestone outside it keeps DB
791
+ // status authority for rows that already exist — only the drifted file's
792
+ // milestone(s) may drive status closes from checkboxes. Absent scope, every
793
+ // milestone is authoritative (unchanged full-import behavior).
794
+ const milestoneStatusAuthoritative = !statusScope || statusScope.has(milestoneId);
795
+ // Snapshot existing slice statuses once (only needed when preserving DB
796
+ // authority for this milestone) so the upsert can echo them back instead of
797
+ // flipping an open slice closed from a stale checkbox.
798
+ const existingSliceStatus = new Map<string, string>();
799
+ const existingTaskStatus = new Map<string, string>();
800
+ if (!milestoneStatusAuthoritative) {
801
+ for (const s of getMilestoneSlices(milestoneId)) {
802
+ existingSliceStatus.set(s.id, s.status);
803
+ for (const t of getSliceTasks(milestoneId, s.id)) {
804
+ existingTaskStatus.set(`${s.id}/${t.id}`, t.status);
805
+ }
806
+ }
807
+ }
808
+
809
+ // Insert milestone (FK parent — must come first). INSERT OR IGNORE: an
810
+ // existing milestone row is never overwritten, so DB status is already
811
+ // preserved for out-of-scope milestones. `inserted` tells us whether this
812
+ // row is new (parsed status applies) vs pre-existing (backfill gated below).
813
+ const milestoneInserted = insertMilestone({
750
814
  id: milestoneId,
751
815
  title: milestoneTitle,
752
816
  status: milestoneStatus,
@@ -760,10 +824,14 @@ export function migrateHierarchyToDb(basePath: string): {
760
824
  // insertMilestone never sets completed_at; backfill it now for milestones
761
825
  // imported as complete so the DB is internally coherent immediately after
762
826
  // import (rather than relying on a later reconciliation pass that can't even
763
- // see the drift when no SUMMARY file exists).
764
- if (IMPORT_COMPLETE_STATUSES.has(milestoneStatus)) {
827
+ // see the drift when no SUMMARY file exists). #027: skip the backfill for an
828
+ // out-of-scope milestone that already existed — its DB status is authoritative.
829
+ if (IMPORT_COMPLETE_STATUSES.has(milestoneStatus) && (milestoneStatusAuthoritative || milestoneInserted)) {
765
830
  const summaryPath = resolveMilestoneFile(basePath, milestoneId, 'SUMMARY');
766
- updateMilestoneStatus(milestoneId, milestoneStatus, importCompletionTimestamp(summaryPath));
831
+ // #1291: preserve an existing completion timestamp so a re-import backfills
832
+ // only rows that lack one, never re-stamping an already-complete milestone
833
+ // with the current import time. Same guard as the task path below.
834
+ updateMilestoneStatus(milestoneId, milestoneStatus, importCompletionTimestamp(summaryPath), true);
767
835
  }
768
836
  counts.milestones++;
769
837
 
@@ -783,11 +851,22 @@ export function migrateHierarchyToDb(basePath: string): {
783
851
  plan = parsePlan(planContent);
784
852
  }
785
853
 
854
+ // #027: for an out-of-scope milestone, echo the existing DB status of a
855
+ // slice that already exists so the upsert's `ELSE excluded.status` branch
856
+ // becomes a no-op instead of flipping a reopened `pending` slice back to
857
+ // `complete` from a stale checkbox. New slices (not yet in the DB) take the
858
+ // parsed status regardless of scope.
859
+ const sliceRowExists = existingSliceStatus.has(sliceEntry.id);
860
+ const sliceStatusAuthoritative = milestoneStatusAuthoritative || !sliceRowExists;
861
+ const effectiveSliceStatus = sliceStatusAuthoritative
862
+ ? sliceStatus
863
+ : existingSliceStatus.get(sliceEntry.id)!;
864
+
786
865
  insertSlice({
787
866
  id: sliceEntry.id,
788
867
  milestoneId: milestoneId,
789
868
  title: sliceEntry.title,
790
- status: sliceStatus,
869
+ status: effectiveSliceStatus,
791
870
  risk: sliceEntry.risk,
792
871
  depends: (sliceEntry.depends ?? []).map(d => d.replace(/^\[|\]$/g, '')).filter(d => /^[A-Za-z0-9][A-Za-z0-9-]*$/.test(d)),
793
872
  demo: sliceEntry.demo,
@@ -798,14 +877,19 @@ export function migrateHierarchyToDb(basePath: string): {
798
877
  },
799
878
  });
800
879
  // insertSlice never sets completed_at; backfill it for slices imported as
801
- // complete (same rationale as milestones above).
802
- if (IMPORT_COMPLETE_STATUSES.has(sliceStatus)) {
880
+ // complete (same rationale as milestones above). #027: skip when preserving
881
+ // an out-of-scope slice's existing DB status.
882
+ if (IMPORT_COMPLETE_STATUSES.has(sliceStatus) && sliceStatusAuthoritative) {
803
883
  const sliceSummary = resolveSliceFile(basePath, milestoneId, sliceEntry.id, 'SUMMARY');
884
+ // #1291: preserve an existing completion timestamp so a re-import backfills
885
+ // only slices that lack one, never re-stamping an already-complete slice
886
+ // with the current import time. Same guard as the task path below.
804
887
  updateSliceStatus(
805
888
  milestoneId,
806
889
  sliceEntry.id,
807
890
  sliceStatus,
808
891
  importCompletionTimestamp(sliceSummary),
892
+ true,
809
893
  );
810
894
  }
811
895
  counts.slices++;
@@ -885,12 +969,20 @@ export function migrateHierarchyToDb(basePath: string): {
885
969
  );
886
970
  }
887
971
 
972
+ // #027: same scope guard as slices — out-of-scope milestones echo existing
973
+ // DB task status so stale plan checkboxes cannot re-complete reopened tasks.
974
+ const taskRowExists = existingTaskStatus.has(`${sliceEntry.id}/${taskEntry.id}`);
975
+ const taskStatusAuthoritative = milestoneStatusAuthoritative || !taskRowExists;
976
+ const effectiveTaskStatus = taskStatusAuthoritative
977
+ ? taskStatus
978
+ : existingTaskStatus.get(`${sliceEntry.id}/${taskEntry.id}`)!;
979
+
888
980
  insertTask({
889
981
  id: taskEntry.id,
890
982
  sliceId: sliceEntry.id,
891
983
  milestoneId: milestoneId,
892
984
  title: taskEntry.title,
893
- status: taskStatus,
985
+ status: effectiveTaskStatus,
894
986
  planning: {
895
987
  files: taskEntry.files ?? [],
896
988
  verify: taskEntry.verify ?? '',
@@ -940,13 +1032,19 @@ export function migrateHierarchyToDb(basePath: string): {
940
1032
  // checkbox (#1222); flat-phase checkboxes are authoritative without summary.
941
1033
  return summaryAttestsCompletion || (t.done && !isLegacySliceLayout);
942
1034
  });
943
- if (allTasksDone && hasSliceSummary) {
1035
+ // #027: the same close guard as the backfill above — a stale slice
1036
+ // SUMMARY under an out-of-scope milestone must not upgrade a reopened
1037
+ // slice to complete. New slices stay authoritative.
1038
+ if (allTasksDone && hasSliceSummary && sliceStatusAuthoritative) {
944
1039
  if (_getAdapter()) {
1040
+ // #1291: preserve an existing completion timestamp — this consistency
1041
+ // upgrade sets a completion time only when the row lacks one.
945
1042
  updateSliceStatus(
946
1043
  milestoneId,
947
1044
  sliceEntry.id,
948
1045
  'complete',
949
1046
  importCompletionTimestamp(sliceSummaryPath),
1047
+ true,
950
1048
  );
951
1049
  process.stderr.write(
952
1050
  `gsd-migrate: ${milestoneId}/${sliceEntry.id} all tasks + slice summary complete — upgrading slice to complete\n`,
@@ -10,198 +10,24 @@
10
10
  */
11
11
 
12
12
  import type { ExtensionAPI, ExtensionCommandContext } from "@gsd/pi-coding-agent";
13
- import { existsSync, readFileSync } from "node:fs";
14
- import { join, dirname } from "node:path";
15
13
  import { gsdRoot } from "../paths.js";
16
- import { fileURLToPath } from "node:url";
17
14
  import { showNextAction } from "../../shared/tui.js";
18
15
  import {
19
16
  notifyMigrateNeedsInteractiveMenu,
20
17
  requiresInteractiveMenu,
21
18
  } from "../command-feedback.js";
22
- import {
23
- validatePlanningDirectory,
24
- parsePlanningDirectory,
25
- transformToGSD,
26
- generatePreview,
27
- writeGSDDirectory,
28
- } from "./index.js";
29
-
30
- import type { MigrationPreview, WrittenFiles } from "./writer.js";
31
- import { ensureDbOpen } from "../bootstrap/dynamic-tools.js";
32
- import { clearArtifacts, clearDecisions, clearRequirements, clearEngineHierarchy, transaction } from "../gsd-db.js";
33
- import { migrateFromMarkdown } from "../md-importer.js";
34
- import { deriveState, invalidateStateCache } from "../state.js";
35
- import {
36
- archiveLegacyPlanningDirectory,
37
- verifyMigrationProjection,
38
- writeMigrationAudit,
39
- type LegacyArchiveResult,
40
- type MigrationAuditResult,
41
- type MigrationProjectionVerification,
42
- } from "./audit.js";
43
- import {
44
- assertMigrationHasSlices,
45
- assertMigrationTargetAvailable,
46
- prepareMigrationTarget,
47
- resolveMigrationPaths,
48
- restoreMigrationTarget,
49
- type MigrationBackup,
50
- } from "./safety.js";
51
-
52
- export type MigrationImportCounts = ReturnType<typeof migrateFromMarkdown>;
53
-
54
- export interface MigrationExecutionResult {
55
- backup: MigrationBackup;
56
- written: WrittenFiles;
57
- imported: MigrationImportCounts;
58
- legacyArchive: LegacyArchiveResult;
59
- verification: MigrationProjectionVerification;
60
- audit: MigrationAuditResult;
61
- }
62
-
63
- function assertMigrationImportMatchesPreview(imported: MigrationImportCounts, preview: MigrationPreview): void {
64
- const mismatches: string[] = [];
65
- if (imported.decisions !== preview.decisions.total) {
66
- mismatches.push(`decisions ${imported.decisions}/${preview.decisions.total}`);
67
- }
68
- if (imported.hierarchy.milestones !== preview.milestoneCount) {
69
- mismatches.push(`milestones ${imported.hierarchy.milestones}/${preview.milestoneCount}`);
70
- }
71
- if (imported.hierarchy.slices !== preview.totalSlices) {
72
- mismatches.push(`slices ${imported.hierarchy.slices}/${preview.totalSlices}`);
73
- }
74
- if (imported.hierarchy.tasks !== preview.totalTasks) {
75
- mismatches.push(`tasks ${imported.hierarchy.tasks}/${preview.totalTasks}`);
76
- }
77
- if (imported.requirements !== preview.requirements.total) {
78
- mismatches.push(`requirements ${imported.requirements}/${preview.requirements.total}`);
79
- }
80
- if (mismatches.length > 0) {
81
- throw new Error(`migration DB import verification failed: ${mismatches.join(", ")}`);
82
- }
83
- }
19
+ import { executeMigrationWrite, type MigrationExecutionResult } from "./execution.js";
20
+ import { createMigrationPlan } from "./plan.js";
21
+ import { buildMigrationPreviewSummary, buildReviewPrompt } from "./presentation.js";
22
+ import type { MigrationPreview } from "./writer.js";
84
23
 
85
- export async function importWrittenMigrationToDb(
86
- basePath: string,
87
- preview?: MigrationPreview,
88
- ): Promise<MigrationImportCounts> {
89
- const opened = await ensureDbOpen(basePath);
90
- if (!opened) {
91
- throw new Error(`failed to open or create the GSD database at ${basePath}`);
92
- }
93
-
94
- const counts = transaction(() => {
95
- clearEngineHierarchy();
96
- clearArtifacts();
97
- clearDecisions();
98
- clearRequirements();
99
- const imported = migrateFromMarkdown(basePath);
100
- if (preview) assertMigrationImportMatchesPreview(imported, preview);
101
- return imported;
102
- });
103
- invalidateStateCache();
104
- return counts;
105
- }
106
-
107
- export async function assertMigrationDbReadiness(
108
- targetRoot: string,
109
- preview: MigrationPreview,
110
- ): Promise<{ phase: string; registry: number }> {
111
- invalidateStateCache();
112
- const state = await deriveState(targetRoot);
113
- const dbUnavailable = state.blockers.some((blocker) => blocker.includes("DB unavailable"));
114
- if (dbUnavailable) {
115
- throw new Error(`migration DB readiness failed: ${state.blockers.join("; ")}`);
116
- }
117
- if (state.registry.length !== preview.milestoneCount) {
118
- throw new Error(`migration DB readiness failed: registry ${state.registry.length}/${preview.milestoneCount}`);
119
- }
120
- return {
121
- phase: state.phase,
122
- registry: state.registry.length,
123
- };
124
- }
125
-
126
- export async function executeMigrationWrite(
127
- sourcePath: string,
128
- targetRoot: string,
129
- project: ReturnType<typeof transformToGSD>,
130
- preview: MigrationPreview,
131
- startedAt: string = new Date().toISOString(),
132
- ): Promise<MigrationExecutionResult> {
133
- const backup = prepareMigrationTarget(targetRoot);
134
-
135
- try {
136
- const written = await writeGSDDirectory(project, targetRoot);
137
- const legacyArchive = await archiveLegacyPlanningDirectory(sourcePath, targetRoot);
138
- const imported = await importWrittenMigrationToDb(targetRoot, preview);
139
- const verification = await verifyMigrationProjection(targetRoot, preview);
140
- verification.dbReadiness = await assertMigrationDbReadiness(targetRoot, preview);
141
- const audit = await writeMigrationAudit({
142
- sourcePath,
143
- targetRoot,
144
- backupPath: backup.backupPath,
145
- preview,
146
- written,
147
- imported,
148
- legacyArchive,
149
- verification,
150
- startedAt,
151
- completedAt: new Date().toISOString(),
152
- });
153
-
154
- return { backup, written, imported, legacyArchive, verification, audit };
155
- } catch (err) {
156
- restoreMigrationTarget(backup);
157
- throw err;
158
- }
159
- }
160
-
161
- /** Format preview stats for embedding in the review prompt. */
162
- function formatPreviewStats(preview: MigrationPreview): string {
163
- const lines = [
164
- `- Decisions: ${preview.decisions.total}`,
165
- `- Milestones: ${preview.milestoneCount}`,
166
- `- Slices: ${preview.totalSlices} (${preview.doneSlices} done — ${preview.sliceCompletionPct}%)`,
167
- `- Tasks: ${preview.totalTasks} (${preview.doneTasks} done — ${preview.taskCompletionPct}%)`,
168
- ];
169
- if (preview.requirements.total > 0) {
170
- lines.push(
171
- `- Requirements: ${preview.requirements.total} (${preview.requirements.validated} validated, ${preview.requirements.active} active, ${preview.requirements.deferred} deferred, ${preview.requirements.outOfScope} out of scope)`,
172
- );
173
- }
174
- if (preview.migrationInputs) {
175
- lines.push(`- Legacy inputs: ${preview.migrationInputs.milestonePhaseDirs} milestone phase dir(s), ${preview.migrationInputs.decisions} decision file(s), ${preview.migrationInputs.seeds} seed file(s)`);
176
- }
177
- return lines.join("\n");
178
- }
179
-
180
- /** Load and interpolate the review-migration prompt template. */
181
- function buildReviewPrompt(
182
- sourcePath: string,
183
- gsdPath: string,
184
- preview: MigrationPreview,
185
- ): string {
186
- const promptsDir = join(dirname(fileURLToPath(import.meta.url)), "..", "prompts");
187
- const templatePath = join(promptsDir, "review-migration.md");
188
- let content = readFileSync(templatePath, "utf-8");
189
-
190
- content = content.replaceAll("{{sourcePath}}", sourcePath);
191
- content = content.replaceAll("{{gsdPath}}", gsdPath);
192
- content = content.replaceAll("{{previewStats}}", formatPreviewStats(preview));
193
-
194
- return content.trim();
195
- }
196
-
197
- /** Dispatch the review prompt to the agent. */
198
24
  function dispatchReview(
199
25
  pi: ExtensionAPI,
200
26
  sourcePath: string,
201
27
  gsdPath: string,
202
28
  preview: MigrationPreview,
203
29
  ): void {
204
- const prompt = buildReviewPrompt(sourcePath, gsdPath, preview);
30
+ const prompt = buildReviewPrompt({ sourcePath, gsdPath, preview });
205
31
 
206
32
  pi.sendMessage(
207
33
  {
@@ -218,34 +44,28 @@ export async function handleMigrate(
218
44
  ctx: ExtensionCommandContext,
219
45
  pi: ExtensionAPI,
220
46
  ): Promise<void> {
221
- // ── Resolve source path ────────────────────────────────────────────────────
222
- const { sourcePath, targetRoot } = resolveMigrationPaths(args);
47
+ const plan = await createMigrationPlan(args);
48
+ const { sourcePath, targetRoot } = plan;
223
49
 
224
- if (!existsSync(sourcePath)) {
50
+ if (plan.status === "missing-source") {
225
51
  ctx.ui.notify(
226
52
  `Directory not found: ${sourcePath}\n\n` +
227
- 'Migration converts a .planning/ directory (from older GSD versions) into .gsd/ format.\n' +
228
- 'If you are starting a new project, use /gsd:new-project instead.\n' +
229
- 'If migrating, ensure the path contains a .planning/ directory.',
53
+ "Migration converts a .planning/ directory (from older GSD versions) into .gsd/ format.\n" +
54
+ "If you are starting a new project, use /gsd:new-project instead.\n" +
55
+ "If migrating, ensure the path contains a .planning/ directory.",
230
56
  "error",
231
57
  );
232
58
  return;
233
59
  }
234
60
 
235
- // ── Validate ───────────────────────────────────────────────────────────────
236
- const validation = await validatePlanningDirectory(sourcePath);
237
-
238
- const warnings = validation.issues.filter((i) => i.severity === "warning");
239
- const fatals = validation.issues.filter((i) => i.severity === "fatal");
240
-
241
- for (const w of warnings) {
242
- ctx.ui.notify(`⚠ ${w.message} (${w.file})`, "warning");
61
+ for (const warning of plan.warnings) {
62
+ ctx.ui.notify(`⚠ ${warning.message} (${warning.file})`, "warning");
243
63
  }
244
- for (const f of fatals) {
245
- ctx.ui.notify(`✖ ${f.message} (${f.file})`, "error");
64
+ for (const fatal of plan.fatals) {
65
+ ctx.ui.notify(`✖ ${fatal.message} (${fatal.file})`, "error");
246
66
  }
247
67
 
248
- if (!validation.valid) {
68
+ if (plan.status === "invalid") {
249
69
  ctx.ui.notify(
250
70
  "Migration blocked — fix the fatal issues above before retrying.",
251
71
  "error",
@@ -253,41 +73,15 @@ export async function handleMigrate(
253
73
  return;
254
74
  }
255
75
 
256
- // ── Parse Transform → Preview ───────────────────────────────────────────
257
- const parsed = await parsePlanningDirectory(sourcePath);
258
- const project = transformToGSD(parsed);
259
- const preview = generatePreview(project);
260
- try {
261
- assertMigrationHasSlices(preview);
262
- await assertMigrationTargetAvailable(targetRoot);
263
- } catch (err) {
264
- ctx.ui.notify((err as Error).message, "error");
76
+ if (plan.status === "blocked") {
77
+ ctx.ui.notify(plan.message, "error");
265
78
  return;
266
79
  }
267
80
 
268
- // ── Build preview text ─────────────────────────────────────────────────────
269
- const lines: string[] = [
270
- `Decisions: ${preview.decisions.total}`,
271
- `Milestones: ${preview.milestoneCount}`,
272
- `Slices: ${preview.totalSlices} (${preview.doneSlices} done — ${preview.sliceCompletionPct}%)`,
273
- `Tasks: ${preview.totalTasks} (${preview.doneTasks} done — ${preview.taskCompletionPct}%)`,
274
- ];
81
+ const { project, preview } = plan;
275
82
 
276
- if (preview.requirements.total > 0) {
277
- lines.push(
278
- `Requirements: ${preview.requirements.total} (${preview.requirements.validated} validated, ${preview.requirements.active} active, ${preview.requirements.deferred} deferred, ${preview.requirements.outOfScope} out of scope)`,
279
- );
280
- }
281
- if (preview.migrationInputs) {
282
- lines.push(`Legacy inputs: ${preview.migrationInputs.milestonePhaseDirs} milestone phase dir(s), ${preview.migrationInputs.decisions} decision file(s), ${preview.migrationInputs.seeds} seed file(s)`);
283
- }
284
-
285
- const targetGsdExists = existsSync(gsdRoot(targetRoot));
286
- if (targetGsdExists) {
287
- lines.push("");
288
- lines.push(`⚠ A .gsd directory already exists at ${gsdRoot(targetRoot)}.`);
289
- lines.push("It will be backed up, deleted, and rewritten fresh before DB import.");
290
- }
83
+ // ── Build preview text ─────────────────────────────────────────────────────
84
+ const lines = buildMigrationPreviewSummary(preview, targetRoot);
291
85
 
292
86
  // ── Confirmation via showNextAction ────────────────────────────────────────
293
87
  if (requiresInteractiveMenu(ctx, false)) {
@@ -0,0 +1,136 @@
1
+ // gsd-pi - /gsd migrate execution service.
2
+ // File Purpose: Write migrated .gsd files, import them into the DB, verify projection/readiness, and rollback on failure.
3
+
4
+ import { ensureDbOpen } from "../bootstrap/dynamic-tools.js";
5
+ import { closeWorkflowDatabase } from "../db-workspace.js";
6
+ import { clearArtifacts, clearDecisions, clearEngineHierarchy, clearRequirements, transaction } from "../gsd-db.js";
7
+ import { migrateFromMarkdown } from "../md-importer.js";
8
+ import { deriveState, invalidateStateCache } from "../state.js";
9
+ import {
10
+ archiveLegacyPlanningDirectory,
11
+ verifyMigrationProjection,
12
+ writeMigrationAudit,
13
+ type LegacyArchiveResult,
14
+ type MigrationAuditResult,
15
+ type MigrationProjectionVerification,
16
+ } from "./audit.js";
17
+ import {
18
+ prepareMigrationTarget,
19
+ restoreMigrationTarget,
20
+ type MigrationBackup,
21
+ } from "./safety.js";
22
+ import { writeGSDDirectory, type MigrationPreview, type WrittenFiles } from "./writer.js";
23
+ import type { GSDProject } from "./types.js";
24
+
25
+ export type MigrationImportCounts = ReturnType<typeof migrateFromMarkdown>;
26
+
27
+ export interface MigrationExecutionResult {
28
+ backup: MigrationBackup;
29
+ written: WrittenFiles;
30
+ imported: MigrationImportCounts;
31
+ legacyArchive: LegacyArchiveResult;
32
+ verification: MigrationProjectionVerification;
33
+ audit: MigrationAuditResult;
34
+ }
35
+
36
+ function assertMigrationImportMatchesPreview(imported: MigrationImportCounts, preview: MigrationPreview): void {
37
+ const mismatches: string[] = [];
38
+ if (imported.decisions !== preview.decisions.total) {
39
+ mismatches.push(`decisions ${imported.decisions}/${preview.decisions.total}`);
40
+ }
41
+ if (imported.hierarchy.milestones !== preview.milestoneCount) {
42
+ mismatches.push(`milestones ${imported.hierarchy.milestones}/${preview.milestoneCount}`);
43
+ }
44
+ if (imported.hierarchy.slices !== preview.totalSlices) {
45
+ mismatches.push(`slices ${imported.hierarchy.slices}/${preview.totalSlices}`);
46
+ }
47
+ if (imported.hierarchy.tasks !== preview.totalTasks) {
48
+ mismatches.push(`tasks ${imported.hierarchy.tasks}/${preview.totalTasks}`);
49
+ }
50
+ if (imported.requirements !== preview.requirements.total) {
51
+ mismatches.push(`requirements ${imported.requirements}/${preview.requirements.total}`);
52
+ }
53
+ if (mismatches.length > 0) {
54
+ throw new Error(`migration DB import verification failed: ${mismatches.join(", ")}`);
55
+ }
56
+ }
57
+
58
+ export async function importWrittenMigrationToDb(
59
+ basePath: string,
60
+ preview?: MigrationPreview,
61
+ ): Promise<MigrationImportCounts> {
62
+ const opened = await ensureDbOpen(basePath);
63
+ if (!opened) {
64
+ throw new Error(`failed to open or create the GSD database at ${basePath}`);
65
+ }
66
+
67
+ const counts = transaction(() => {
68
+ clearEngineHierarchy();
69
+ clearArtifacts();
70
+ clearDecisions();
71
+ clearRequirements();
72
+ const imported = migrateFromMarkdown(basePath);
73
+ if (preview) assertMigrationImportMatchesPreview(imported, preview);
74
+ return imported;
75
+ });
76
+ invalidateStateCache();
77
+ return counts;
78
+ }
79
+
80
+ export async function assertMigrationDbReadiness(
81
+ targetRoot: string,
82
+ preview: MigrationPreview,
83
+ ): Promise<{ phase: string; registry: number }> {
84
+ invalidateStateCache();
85
+ const state = await deriveState(targetRoot);
86
+ const dbUnavailable = state.blockers.some((blocker) => blocker.includes("DB unavailable"));
87
+ if (dbUnavailable) {
88
+ throw new Error(`migration DB readiness failed: ${state.blockers.join("; ")}`);
89
+ }
90
+ if (state.registry.length !== preview.milestoneCount) {
91
+ throw new Error(`migration DB readiness failed: registry ${state.registry.length}/${preview.milestoneCount}`);
92
+ }
93
+ return {
94
+ phase: state.phase,
95
+ registry: state.registry.length,
96
+ };
97
+ }
98
+
99
+ export async function executeMigrationWrite(
100
+ sourcePath: string,
101
+ targetRoot: string,
102
+ project: GSDProject,
103
+ preview: MigrationPreview,
104
+ startedAt: string = new Date().toISOString(),
105
+ ): Promise<MigrationExecutionResult> {
106
+ const backup = prepareMigrationTarget(targetRoot);
107
+
108
+ try {
109
+ const written = await writeGSDDirectory(project, targetRoot);
110
+ const legacyArchive = await archiveLegacyPlanningDirectory(sourcePath, targetRoot);
111
+ const imported = await importWrittenMigrationToDb(targetRoot, preview);
112
+ const verification = await verifyMigrationProjection(targetRoot, preview);
113
+ verification.dbReadiness = await assertMigrationDbReadiness(targetRoot, preview);
114
+ const audit = await writeMigrationAudit({
115
+ sourcePath,
116
+ targetRoot,
117
+ backupPath: backup.backupPath,
118
+ preview,
119
+ written,
120
+ imported,
121
+ legacyArchive,
122
+ verification,
123
+ startedAt,
124
+ completedAt: new Date().toISOString(),
125
+ });
126
+
127
+ return { backup, written, imported, legacyArchive, verification, audit };
128
+ } catch (error) {
129
+ // The import transaction may have committed and the process may hold an
130
+ // open handle to the target gsd.db; close before the restore replaces the
131
+ // file on disk, and leave closed so the next open rebinds to the restored file.
132
+ try { closeWorkflowDatabase(); } catch { /* best-effort: restore must proceed */ }
133
+ restoreMigrationTarget(backup);
134
+ throw error;
135
+ }
136
+ }