gsd-pi 2.33.1-dev.235d83a → 2.33.1-dev.29a8268

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 (742) hide show
  1. package/dist/cli.js +0 -16
  2. package/dist/resource-loader.d.ts +0 -2
  3. package/dist/resource-loader.js +3 -36
  4. package/dist/resources/extensions/ask-user-questions.ts +290 -0
  5. package/dist/resources/extensions/async-jobs/async-bash-tool.ts +212 -0
  6. package/dist/resources/extensions/async-jobs/await-tool.ts +103 -0
  7. package/dist/resources/extensions/async-jobs/cancel-job-tool.ts +35 -0
  8. package/dist/resources/extensions/async-jobs/index.ts +141 -0
  9. package/dist/resources/extensions/async-jobs/job-manager.ts +211 -0
  10. package/dist/resources/extensions/aws-auth/index.ts +144 -0
  11. package/dist/resources/extensions/bg-shell/bg-shell-command.ts +219 -0
  12. package/dist/resources/extensions/bg-shell/bg-shell-lifecycle.ts +400 -0
  13. package/dist/resources/extensions/bg-shell/bg-shell-tool.ts +985 -0
  14. package/dist/resources/extensions/bg-shell/index.ts +59 -0
  15. package/dist/resources/extensions/bg-shell/interaction.ts +198 -0
  16. package/dist/resources/extensions/bg-shell/output-formatter.ts +279 -0
  17. package/dist/resources/extensions/bg-shell/overlay.ts +437 -0
  18. package/dist/resources/extensions/bg-shell/process-manager.ts +464 -0
  19. package/dist/resources/extensions/bg-shell/readiness-detector.ts +126 -0
  20. package/dist/resources/extensions/bg-shell/types.ts +303 -0
  21. package/dist/resources/extensions/bg-shell/utilities.ts +57 -0
  22. package/dist/resources/extensions/browser-tools/capture.ts +199 -0
  23. package/dist/resources/extensions/browser-tools/core.ts +1196 -0
  24. package/dist/resources/extensions/browser-tools/{evaluate-helpers.js → evaluate-helpers.ts} +1 -0
  25. package/dist/resources/extensions/browser-tools/index.ts +71 -0
  26. package/dist/resources/extensions/browser-tools/lifecycle.ts +270 -0
  27. package/dist/resources/extensions/browser-tools/refs.ts +264 -0
  28. package/dist/resources/extensions/browser-tools/settle.ts +197 -0
  29. package/dist/resources/extensions/browser-tools/state.ts +408 -0
  30. package/dist/resources/extensions/browser-tools/tools/action-cache.ts +216 -0
  31. package/dist/resources/extensions/browser-tools/tools/assertions.ts +342 -0
  32. package/dist/resources/extensions/browser-tools/tools/codegen.ts +274 -0
  33. package/dist/resources/extensions/browser-tools/tools/device.ts +183 -0
  34. package/dist/resources/extensions/browser-tools/tools/extract.ts +229 -0
  35. package/dist/resources/extensions/browser-tools/tools/forms.ts +801 -0
  36. package/dist/resources/extensions/browser-tools/tools/injection-detect.ts +221 -0
  37. package/dist/resources/extensions/browser-tools/tools/inspection.ts +492 -0
  38. package/dist/resources/extensions/browser-tools/tools/intent.ts +614 -0
  39. package/dist/resources/extensions/browser-tools/tools/interaction.ts +865 -0
  40. package/dist/resources/extensions/browser-tools/tools/navigation.ts +232 -0
  41. package/dist/resources/extensions/browser-tools/tools/network-mock.ts +244 -0
  42. package/dist/resources/extensions/browser-tools/tools/pages.ts +303 -0
  43. package/dist/resources/extensions/browser-tools/tools/pdf.ts +92 -0
  44. package/dist/resources/extensions/browser-tools/tools/refs.ts +541 -0
  45. package/dist/resources/extensions/browser-tools/tools/screenshot.ts +101 -0
  46. package/dist/resources/extensions/browser-tools/tools/session.ts +400 -0
  47. package/dist/resources/extensions/browser-tools/tools/state-persistence.ts +202 -0
  48. package/dist/resources/extensions/browser-tools/tools/visual-diff.ts +209 -0
  49. package/dist/resources/extensions/browser-tools/tools/wait.ts +247 -0
  50. package/dist/resources/extensions/browser-tools/tools/zoom.ts +104 -0
  51. package/dist/resources/extensions/browser-tools/utils.ts +660 -0
  52. package/dist/resources/extensions/context7/index.ts +428 -0
  53. package/dist/resources/extensions/get-secrets-from-user.ts +607 -0
  54. package/dist/resources/extensions/google-search/index.ts +466 -0
  55. package/dist/resources/extensions/gsd/activity-log.ts +162 -0
  56. package/dist/resources/extensions/gsd/atomic-write.ts +35 -0
  57. package/dist/resources/extensions/gsd/auto/session.ts +236 -0
  58. package/dist/resources/extensions/gsd/auto-budget.ts +32 -0
  59. package/dist/resources/extensions/gsd/{auto-constants.js → auto-constants.ts} +1 -0
  60. package/dist/resources/extensions/gsd/auto-dashboard.ts +626 -0
  61. package/dist/resources/extensions/gsd/auto-direct-dispatch.ts +224 -0
  62. package/dist/resources/extensions/gsd/auto-dispatch.ts +409 -0
  63. package/dist/resources/extensions/gsd/auto-idempotency.ts +151 -0
  64. package/dist/resources/extensions/gsd/auto-model-selection.ts +179 -0
  65. package/dist/resources/extensions/gsd/auto-observability.ts +72 -0
  66. package/dist/resources/extensions/gsd/auto-post-unit.ts +618 -0
  67. package/dist/resources/extensions/gsd/auto-prompts.ts +1273 -0
  68. package/dist/resources/extensions/gsd/auto-recovery.ts +578 -0
  69. package/dist/resources/extensions/gsd/auto-start.ts +483 -0
  70. package/dist/resources/extensions/gsd/auto-stuck-detection.ts +221 -0
  71. package/dist/resources/extensions/gsd/{auto-supervisor.js → auto-supervisor.ts} +33 -25
  72. package/dist/resources/extensions/gsd/auto-timeout-recovery.ts +263 -0
  73. package/dist/resources/extensions/gsd/auto-timers.ts +224 -0
  74. package/dist/resources/extensions/gsd/auto-tool-tracking.ts +54 -0
  75. package/dist/resources/extensions/gsd/auto-unit-closeout.ts +48 -0
  76. package/dist/resources/extensions/gsd/auto-verification.ts +229 -0
  77. package/dist/resources/extensions/gsd/auto-worktree.ts +658 -0
  78. package/dist/resources/extensions/gsd/auto.ts +1834 -0
  79. package/dist/resources/extensions/gsd/{cache.js → cache.ts} +7 -5
  80. package/dist/resources/extensions/gsd/captures.ts +427 -0
  81. package/dist/resources/extensions/gsd/claude-import.ts +656 -0
  82. package/dist/resources/extensions/gsd/collision-diagnostics.ts +332 -0
  83. package/dist/resources/extensions/gsd/commands-config.ts +102 -0
  84. package/dist/resources/extensions/gsd/commands-extensions.ts +328 -0
  85. package/dist/resources/extensions/gsd/commands-handlers.ts +395 -0
  86. package/dist/resources/extensions/gsd/commands-inspect.ts +91 -0
  87. package/dist/resources/extensions/gsd/commands-logs.ts +536 -0
  88. package/dist/resources/extensions/gsd/commands-maintenance.ts +206 -0
  89. package/dist/resources/extensions/gsd/commands-prefs-wizard.ts +780 -0
  90. package/dist/resources/extensions/gsd/commands-workflow-templates.ts +543 -0
  91. package/dist/resources/extensions/gsd/commands.ts +1149 -0
  92. package/dist/resources/extensions/gsd/complexity-classifier.ts +320 -0
  93. package/dist/resources/extensions/gsd/{constants.js → constants.ts} +6 -0
  94. package/dist/resources/extensions/gsd/context-budget.ts +266 -0
  95. package/dist/resources/extensions/gsd/context-store.ts +195 -0
  96. package/dist/resources/extensions/gsd/crash-recovery.ts +121 -0
  97. package/dist/resources/extensions/gsd/dashboard-overlay.ts +681 -0
  98. package/dist/resources/extensions/gsd/db-writer.ts +360 -0
  99. package/dist/resources/extensions/gsd/debug-logger.ts +178 -0
  100. package/dist/resources/extensions/gsd/detection.ts +470 -0
  101. package/dist/resources/extensions/gsd/diff-context.ts +214 -0
  102. package/dist/resources/extensions/gsd/dispatch-guard.ts +81 -0
  103. package/dist/resources/extensions/gsd/doctor-checks.ts +612 -0
  104. package/dist/resources/extensions/gsd/doctor-environment.ts +497 -0
  105. package/dist/resources/extensions/gsd/doctor-format.ts +78 -0
  106. package/dist/resources/extensions/gsd/doctor-proactive.ts +292 -0
  107. package/dist/resources/extensions/gsd/doctor-providers.ts +343 -0
  108. package/dist/resources/extensions/gsd/doctor-types.ts +87 -0
  109. package/dist/resources/extensions/gsd/doctor.ts +722 -0
  110. package/dist/resources/extensions/gsd/error-utils.ts +6 -0
  111. package/dist/resources/extensions/gsd/{errors.js → errors.ts} +11 -6
  112. package/dist/resources/extensions/gsd/exit-command.ts +18 -0
  113. package/dist/resources/extensions/gsd/{export-html.js → export-html.ts} +614 -482
  114. package/dist/resources/extensions/gsd/export.ts +317 -0
  115. package/dist/resources/extensions/gsd/file-watcher.ts +97 -0
  116. package/dist/resources/extensions/gsd/files.ts +1058 -0
  117. package/dist/resources/extensions/gsd/forensics.ts +629 -0
  118. package/dist/resources/extensions/gsd/{git-constants.js → git-constants.ts} +5 -4
  119. package/dist/resources/extensions/gsd/git-self-heal.ts +127 -0
  120. package/dist/resources/extensions/gsd/git-service.ts +586 -0
  121. package/dist/resources/extensions/gsd/{gitignore.js → gitignore.ts} +125 -98
  122. package/dist/resources/extensions/gsd/gsd-db.ts +685 -0
  123. package/dist/resources/extensions/gsd/guided-flow-queue.ts +440 -0
  124. package/dist/resources/extensions/gsd/guided-flow.ts +1303 -0
  125. package/dist/resources/extensions/gsd/health-widget.ts +167 -0
  126. package/dist/resources/extensions/gsd/history.ts +143 -0
  127. package/dist/resources/extensions/gsd/index.ts +1401 -0
  128. package/dist/resources/extensions/gsd/init-wizard.ts +587 -0
  129. package/dist/resources/extensions/gsd/json-persistence.ts +67 -0
  130. package/dist/resources/extensions/gsd/{jsonl-utils.js → jsonl-utils.ts} +7 -10
  131. package/dist/resources/extensions/gsd/key-manager.ts +996 -0
  132. package/dist/resources/extensions/gsd/marketplace-discovery.ts +508 -0
  133. package/dist/resources/extensions/gsd/md-importer.ts +527 -0
  134. package/dist/resources/extensions/gsd/mechanical-completion.ts +430 -0
  135. package/dist/resources/extensions/gsd/memory-extractor.ts +352 -0
  136. package/dist/resources/extensions/gsd/memory-store.ts +441 -0
  137. package/dist/resources/extensions/gsd/metrics.ts +532 -0
  138. package/dist/resources/extensions/gsd/migrate/command.ts +219 -0
  139. package/dist/resources/extensions/gsd/migrate/index.ts +42 -0
  140. package/dist/resources/extensions/gsd/migrate/parser.ts +323 -0
  141. package/dist/resources/extensions/gsd/migrate/parsers.ts +539 -0
  142. package/dist/resources/extensions/gsd/migrate/preview.ts +48 -0
  143. package/dist/resources/extensions/gsd/migrate/transformer.ts +346 -0
  144. package/dist/resources/extensions/gsd/migrate/types.ts +370 -0
  145. package/dist/resources/extensions/gsd/migrate/validator.ts +55 -0
  146. package/dist/resources/extensions/gsd/migrate/writer.ts +579 -0
  147. package/dist/resources/extensions/gsd/migrate-external.ts +140 -0
  148. package/dist/resources/extensions/gsd/milestone-actions.ts +126 -0
  149. package/dist/resources/extensions/gsd/{milestone-ids.js → milestone-ids.ts} +63 -50
  150. package/dist/resources/extensions/gsd/model-cost-table.ts +65 -0
  151. package/dist/resources/extensions/gsd/model-router.ts +256 -0
  152. package/dist/resources/extensions/gsd/namespaced-registry.ts +467 -0
  153. package/dist/resources/extensions/gsd/namespaced-resolver.ts +307 -0
  154. package/dist/resources/extensions/gsd/native-git-bridge.ts +1041 -0
  155. package/dist/resources/extensions/gsd/native-parser-bridge.ts +267 -0
  156. package/dist/resources/extensions/gsd/notifications.ts +87 -0
  157. package/dist/resources/extensions/gsd/observability-validator.ts +429 -0
  158. package/dist/resources/extensions/gsd/parallel-eligibility.ts +233 -0
  159. package/dist/resources/extensions/gsd/parallel-merge.ts +157 -0
  160. package/dist/resources/extensions/gsd/parallel-orchestrator.ts +826 -0
  161. package/dist/resources/extensions/gsd/paths.ts +449 -0
  162. package/dist/resources/extensions/gsd/plugin-importer.ts +411 -0
  163. package/dist/resources/extensions/gsd/post-unit-hooks.ts +520 -0
  164. package/dist/resources/extensions/gsd/preferences-models.ts +329 -0
  165. package/dist/resources/extensions/gsd/preferences-skills.ts +169 -0
  166. package/dist/resources/extensions/gsd/preferences-types.ts +229 -0
  167. package/dist/resources/extensions/gsd/preferences-validation.ts +590 -0
  168. package/dist/resources/extensions/gsd/preferences.ts +416 -0
  169. package/dist/resources/extensions/gsd/progress-score.ts +273 -0
  170. package/dist/resources/extensions/gsd/prompt-cache-optimizer.ts +213 -0
  171. package/dist/resources/extensions/gsd/prompt-compressor.ts +508 -0
  172. package/dist/resources/extensions/gsd/prompt-loader.ts +130 -0
  173. package/dist/resources/extensions/gsd/prompt-ordering.ts +200 -0
  174. package/dist/resources/extensions/gsd/provider-error-pause.ts +88 -0
  175. package/dist/resources/extensions/gsd/queue-order.ts +230 -0
  176. package/dist/resources/extensions/gsd/queue-reorder-ui.ts +276 -0
  177. package/dist/resources/extensions/gsd/quick.ts +212 -0
  178. package/dist/resources/extensions/gsd/repo-identity.ts +169 -0
  179. package/dist/resources/extensions/gsd/{reports.js → reports.ts} +241 -146
  180. package/dist/resources/extensions/gsd/{resource-version.js → resource-version.ts} +53 -50
  181. package/dist/resources/extensions/gsd/roadmap-slices.ts +149 -0
  182. package/dist/resources/extensions/gsd/routing-history.ts +286 -0
  183. package/dist/resources/extensions/gsd/safe-fs.ts +47 -0
  184. package/dist/resources/extensions/gsd/semantic-chunker.ts +336 -0
  185. package/dist/resources/extensions/gsd/session-forensics.ts +537 -0
  186. package/dist/resources/extensions/gsd/session-lock.ts +426 -0
  187. package/dist/resources/extensions/gsd/session-status-io.ts +179 -0
  188. package/dist/resources/extensions/gsd/skill-discovery.ts +139 -0
  189. package/dist/resources/extensions/gsd/skill-health.ts +417 -0
  190. package/dist/resources/extensions/gsd/{skill-telemetry.js → skill-telemetry.ts} +74 -58
  191. package/dist/resources/extensions/gsd/state.ts +727 -0
  192. package/dist/resources/extensions/gsd/structured-data-formatter.ts +144 -0
  193. package/dist/resources/extensions/gsd/summary-distiller.ts +258 -0
  194. package/dist/resources/extensions/gsd/tests/activity-log.test.ts +213 -0
  195. package/dist/resources/extensions/gsd/tests/agent-end-retry.test.ts +107 -0
  196. package/dist/resources/extensions/gsd/tests/all-milestones-complete-merge.test.ts +200 -0
  197. package/dist/resources/extensions/gsd/tests/auto-budget-alerts.test.ts +50 -0
  198. package/dist/resources/extensions/gsd/tests/auto-dashboard.test.ts +166 -0
  199. package/dist/resources/extensions/gsd/tests/auto-dispatch-loop.test.ts +691 -0
  200. package/dist/resources/extensions/gsd/tests/auto-lock-creation.test.ts +186 -0
  201. package/dist/resources/extensions/gsd/tests/auto-preflight.test.ts +40 -0
  202. package/dist/resources/extensions/gsd/tests/auto-recovery.test.ts +640 -0
  203. package/dist/resources/extensions/gsd/tests/auto-reentrancy-guard.test.ts +127 -0
  204. package/dist/resources/extensions/gsd/tests/auto-secrets-gate.test.ts +302 -0
  205. package/dist/resources/extensions/gsd/tests/auto-session-encapsulation.test.ts +257 -0
  206. package/dist/resources/extensions/gsd/tests/auto-skip-loop.test.ts +123 -0
  207. package/dist/resources/extensions/gsd/tests/auto-worktree-milestone-merge.test.ts +340 -0
  208. package/dist/resources/extensions/gsd/tests/auto-worktree.test.ts +167 -0
  209. package/dist/resources/extensions/gsd/tests/budget-prediction.test.ts +220 -0
  210. package/dist/resources/extensions/gsd/tests/cache-staleness-regression.test.ts +317 -0
  211. package/dist/resources/extensions/gsd/tests/captures.test.ts +438 -0
  212. package/dist/resources/extensions/gsd/tests/claude-import-tui.test.ts +351 -0
  213. package/dist/resources/extensions/gsd/tests/collect-from-manifest.test.ts +469 -0
  214. package/dist/resources/extensions/gsd/tests/collision-diagnostics.test.ts +705 -0
  215. package/dist/resources/extensions/gsd/tests/commands-logs.test.ts +241 -0
  216. package/dist/resources/extensions/gsd/tests/complete-milestone.test.ts +209 -0
  217. package/dist/resources/extensions/gsd/tests/complexity-classifier.test.ts +181 -0
  218. package/dist/resources/extensions/gsd/tests/context-budget.test.ts +352 -0
  219. package/dist/resources/extensions/gsd/tests/context-compression.test.ts +193 -0
  220. package/dist/resources/extensions/gsd/tests/context-store.test.ts +462 -0
  221. package/dist/resources/extensions/gsd/tests/continue-here.test.ts +285 -0
  222. package/dist/resources/extensions/gsd/tests/cost-projection.test.ts +134 -0
  223. package/dist/resources/extensions/gsd/tests/crash-recovery.test.ts +134 -0
  224. package/dist/resources/extensions/gsd/tests/dashboard-budget.test.ts +346 -0
  225. package/dist/resources/extensions/gsd/tests/db-writer.test.ts +602 -0
  226. package/dist/resources/extensions/gsd/tests/debug-logger.test.ts +185 -0
  227. package/dist/resources/extensions/gsd/tests/derive-state-db.test.ts +405 -0
  228. package/dist/resources/extensions/gsd/tests/derive-state-deps.test.ts +421 -0
  229. package/dist/resources/extensions/gsd/tests/derive-state-draft.test.ts +308 -0
  230. package/dist/resources/extensions/gsd/tests/derive-state.test.ts +788 -0
  231. package/dist/resources/extensions/gsd/tests/detection.test.ts +398 -0
  232. package/dist/resources/extensions/gsd/tests/diff-context.test.ts +136 -0
  233. package/dist/resources/extensions/gsd/tests/discuss-prompt.test.ts +15 -0
  234. package/dist/resources/extensions/gsd/tests/dispatch-guard.test.ts +128 -0
  235. package/dist/resources/extensions/gsd/tests/dispatch-missing-task-plans.test.ts +132 -0
  236. package/dist/resources/extensions/gsd/tests/dispatch-stall-guard.test.ts +126 -0
  237. package/dist/resources/extensions/gsd/tests/doctor-environment.test.ts +314 -0
  238. package/dist/resources/extensions/gsd/tests/doctor-fixlevel.test.ts +245 -0
  239. package/dist/resources/extensions/gsd/tests/doctor-git.test.ts +344 -0
  240. package/dist/resources/extensions/gsd/tests/doctor-proactive.test.ts +278 -0
  241. package/dist/resources/extensions/gsd/tests/doctor-providers.test.ts +298 -0
  242. package/dist/resources/extensions/gsd/tests/doctor-runtime.test.ts +302 -0
  243. package/dist/resources/extensions/gsd/tests/doctor.test.ts +652 -0
  244. package/dist/resources/extensions/gsd/tests/draft-promotion.test.ts +169 -0
  245. package/dist/resources/extensions/gsd/tests/exit-command.test.ts +50 -0
  246. package/dist/resources/extensions/gsd/tests/export-html-all.test.ts +105 -0
  247. package/dist/resources/extensions/gsd/tests/export-html-enhancements.test.ts +378 -0
  248. package/dist/resources/extensions/gsd/tests/extension-selector-separator.test.ts +144 -0
  249. package/dist/resources/extensions/gsd/tests/feature-branch-lifecycle-integration.test.ts +424 -0
  250. package/dist/resources/extensions/gsd/tests/git-self-heal.test.ts +131 -0
  251. package/dist/resources/extensions/gsd/tests/git-service.test.ts +1181 -0
  252. package/dist/resources/extensions/gsd/tests/gsd-db.test.ts +353 -0
  253. package/dist/resources/extensions/gsd/tests/gsd-inspect.test.ts +125 -0
  254. package/dist/resources/extensions/gsd/tests/gsd-tools.test.ts +326 -0
  255. package/dist/resources/extensions/gsd/tests/headless-answers.test.ts +340 -0
  256. package/dist/resources/extensions/gsd/tests/headless-query.test.ts +162 -0
  257. package/dist/resources/extensions/gsd/tests/idle-recovery.test.ts +485 -0
  258. package/dist/resources/extensions/gsd/tests/in-flight-tool-tracking.test.ts +32 -0
  259. package/dist/resources/extensions/gsd/tests/init-wizard.test.ts +197 -0
  260. package/dist/resources/extensions/gsd/tests/integration/headless-command.ts +534 -0
  261. package/dist/resources/extensions/gsd/tests/integration-edge.test.ts +228 -0
  262. package/dist/resources/extensions/gsd/tests/integration-lifecycle.test.ts +277 -0
  263. package/dist/resources/extensions/gsd/tests/integration-mixed-milestones.test.ts +523 -0
  264. package/dist/resources/extensions/gsd/tests/key-manager.test.ts +414 -0
  265. package/dist/resources/extensions/gsd/tests/knowledge.test.ts +161 -0
  266. package/dist/resources/extensions/gsd/tests/loop-regression.test.ts +877 -0
  267. package/dist/resources/extensions/gsd/tests/manifest-status.test.ts +283 -0
  268. package/dist/resources/extensions/gsd/tests/marketplace-test-fixtures.ts +91 -0
  269. package/dist/resources/extensions/gsd/tests/md-importer.test.ts +410 -0
  270. package/dist/resources/extensions/gsd/tests/mechanical-completion.test.ts +356 -0
  271. package/dist/resources/extensions/gsd/tests/memory-extractor.test.ts +180 -0
  272. package/dist/resources/extensions/gsd/tests/memory-leak-guards.test.ts +91 -0
  273. package/dist/resources/extensions/gsd/tests/memory-store.test.ts +345 -0
  274. package/dist/resources/extensions/gsd/tests/metrics.test.ts +253 -0
  275. package/dist/resources/extensions/gsd/tests/migrate-command.test.ts +369 -0
  276. package/dist/resources/extensions/gsd/tests/migrate-parser.test.ts +757 -0
  277. package/dist/resources/extensions/gsd/tests/migrate-transformer.test.ts +635 -0
  278. package/dist/resources/extensions/gsd/tests/migrate-validator-parsers.test.ts +414 -0
  279. package/dist/resources/extensions/gsd/tests/migrate-writer-integration.test.ts +303 -0
  280. package/dist/resources/extensions/gsd/tests/migrate-writer.test.ts +398 -0
  281. package/dist/resources/extensions/gsd/tests/milestone-transition-worktree.test.ts +147 -0
  282. package/dist/resources/extensions/gsd/tests/model-cost-table.test.ts +69 -0
  283. package/dist/resources/extensions/gsd/tests/model-isolation.test.ts +157 -0
  284. package/dist/resources/extensions/gsd/tests/model-router.test.ts +167 -0
  285. package/dist/resources/extensions/gsd/tests/must-have-parser.test.ts +291 -0
  286. package/dist/resources/extensions/gsd/tests/namespaced-registry.test.ts +1027 -0
  287. package/dist/resources/extensions/gsd/tests/namespaced-resolver.test.ts +671 -0
  288. package/dist/resources/extensions/gsd/tests/native-has-changes-cache.test.ts +61 -0
  289. package/dist/resources/extensions/gsd/tests/next-milestone-id.test.ts +23 -0
  290. package/dist/resources/extensions/gsd/tests/none-mode-gates.test.ts +114 -0
  291. package/dist/resources/extensions/gsd/tests/notifications.test.ts +67 -0
  292. package/dist/resources/extensions/gsd/tests/overrides.test.ts +131 -0
  293. package/dist/resources/extensions/gsd/tests/parallel-budget-atomicity.test.ts +331 -0
  294. package/dist/resources/extensions/gsd/tests/parallel-crash-recovery.test.ts +298 -0
  295. package/dist/resources/extensions/gsd/tests/parallel-merge.test.ts +468 -0
  296. package/dist/resources/extensions/gsd/tests/parallel-orchestration.test.ts +685 -0
  297. package/dist/resources/extensions/gsd/tests/parallel-worker-monitoring.test.ts +171 -0
  298. package/dist/resources/extensions/gsd/tests/parallel-workers-multi-milestone-e2e.test.ts +354 -0
  299. package/dist/resources/extensions/gsd/tests/park-edge-cases.test.ts +276 -0
  300. package/dist/resources/extensions/gsd/tests/park-milestone.test.ts +401 -0
  301. package/dist/resources/extensions/gsd/tests/parsers.test.ts +1704 -0
  302. package/dist/resources/extensions/gsd/tests/plan-milestone.test.ts +133 -0
  303. package/dist/resources/extensions/gsd/tests/plan-quality-validator.test.ts +363 -0
  304. package/dist/resources/extensions/gsd/tests/plan-slice-prompt.test.ts +42 -0
  305. package/dist/resources/extensions/gsd/tests/plugin-importer-live.test.ts +481 -0
  306. package/dist/resources/extensions/gsd/tests/plugin-importer.test.ts +1383 -0
  307. package/dist/resources/extensions/gsd/tests/post-unit-hooks.test.ts +337 -0
  308. package/dist/resources/extensions/gsd/tests/preferences.test.ts +276 -0
  309. package/dist/resources/extensions/gsd/tests/progress-score.test.ts +206 -0
  310. package/dist/resources/extensions/gsd/tests/prompt-budget-enforcement.test.ts +464 -0
  311. package/dist/resources/extensions/gsd/tests/prompt-cache-optimizer.test.ts +314 -0
  312. package/dist/resources/extensions/gsd/tests/prompt-compressor.test.ts +529 -0
  313. package/dist/resources/extensions/gsd/tests/prompt-db.test.ts +385 -0
  314. package/dist/resources/extensions/gsd/tests/prompt-ordering.test.ts +296 -0
  315. package/dist/resources/extensions/gsd/tests/provider-errors.test.ts +338 -0
  316. package/dist/resources/extensions/gsd/tests/queue-draft-detection.test.ts +126 -0
  317. package/dist/resources/extensions/gsd/tests/queue-order.test.ts +204 -0
  318. package/dist/resources/extensions/gsd/tests/queue-reorder-e2e.test.ts +282 -0
  319. package/dist/resources/extensions/gsd/tests/reassess-detection.test.ts +154 -0
  320. package/dist/resources/extensions/gsd/tests/reassess-prompt.test.ts +145 -0
  321. package/dist/resources/extensions/gsd/tests/regex-hardening.test.ts +281 -0
  322. package/dist/resources/extensions/gsd/tests/remote-questions.test.ts +642 -0
  323. package/dist/resources/extensions/gsd/tests/remote-status.test.ts +99 -0
  324. package/dist/resources/extensions/gsd/tests/replan-slice.test.ts +538 -0
  325. package/dist/resources/extensions/gsd/tests/requirements.test.ts +106 -0
  326. package/dist/resources/extensions/gsd/tests/roadmap-parse-regression.test.ts +358 -0
  327. package/dist/resources/extensions/gsd/tests/roadmap-slices.test.ts +66 -0
  328. package/dist/resources/extensions/gsd/tests/routing-history.test.ts +240 -0
  329. package/dist/resources/extensions/gsd/tests/run-uat.test.ts +416 -0
  330. package/dist/resources/extensions/gsd/tests/secure-env-collect.test.ts +185 -0
  331. package/dist/resources/extensions/gsd/tests/semantic-chunker.test.ts +426 -0
  332. package/dist/resources/extensions/gsd/tests/session-lock-regression.test.ts +216 -0
  333. package/dist/resources/extensions/gsd/tests/session-lock.test.ts +434 -0
  334. package/dist/resources/extensions/gsd/tests/skill-lifecycle.test.ts +126 -0
  335. package/dist/resources/extensions/gsd/tests/smart-entry-draft.test.ts +123 -0
  336. package/dist/resources/extensions/gsd/tests/stale-worktree-cwd.test.ts +142 -0
  337. package/dist/resources/extensions/gsd/tests/stop-auto-remote.test.ts +156 -0
  338. package/dist/resources/extensions/gsd/tests/structured-data-formatter.test.ts +365 -0
  339. package/dist/resources/extensions/gsd/tests/summary-distiller.test.ts +323 -0
  340. package/dist/resources/extensions/gsd/tests/test-helpers.ts +61 -0
  341. package/dist/resources/extensions/gsd/tests/token-counter.test.ts +129 -0
  342. package/dist/resources/extensions/gsd/tests/token-optimization-benchmark.test.ts +1272 -0
  343. package/dist/resources/extensions/gsd/tests/token-optimization-prefs.test.ts +164 -0
  344. package/dist/resources/extensions/gsd/tests/token-profile.test.ts +268 -0
  345. package/dist/resources/extensions/gsd/tests/token-savings.test.ts +366 -0
  346. package/dist/resources/extensions/gsd/tests/triage-dispatch.test.ts +340 -0
  347. package/dist/resources/extensions/gsd/tests/triage-resolution.test.ts +416 -0
  348. package/dist/resources/extensions/gsd/tests/undo.test.ts +136 -0
  349. package/dist/resources/extensions/gsd/tests/unique-milestone-ids.test.ts +219 -0
  350. package/dist/resources/extensions/gsd/tests/unit-runtime.test.ts +258 -0
  351. package/dist/resources/extensions/gsd/tests/update-command.test.ts +67 -0
  352. package/dist/resources/extensions/gsd/tests/validate-directory.test.ts +222 -0
  353. package/dist/resources/extensions/gsd/tests/validate-milestone.test.ts +375 -0
  354. package/dist/resources/extensions/gsd/tests/verification-evidence.test.ts +745 -0
  355. package/dist/resources/extensions/gsd/tests/verification-gate.test.ts +1208 -0
  356. package/dist/resources/extensions/gsd/tests/visualizer-critical-path.test.ts +145 -0
  357. package/dist/resources/extensions/gsd/tests/visualizer-data.test.ts +446 -0
  358. package/dist/resources/extensions/gsd/tests/visualizer-overlay.test.ts +237 -0
  359. package/dist/resources/extensions/gsd/tests/visualizer-views.test.ts +718 -0
  360. package/dist/resources/extensions/gsd/tests/worker-registry.test.ts +148 -0
  361. package/dist/resources/extensions/gsd/tests/workflow-templates.test.ts +173 -0
  362. package/dist/resources/extensions/gsd/tests/workspace-index.test.ts +38 -0
  363. package/dist/resources/extensions/gsd/tests/worktree-bugfix.test.ts +120 -0
  364. package/dist/resources/extensions/gsd/tests/worktree-e2e.test.ts +244 -0
  365. package/dist/resources/extensions/gsd/tests/worktree-integration.test.ts +207 -0
  366. package/dist/resources/extensions/gsd/tests/worktree-manager.test.ts +141 -0
  367. package/dist/resources/extensions/gsd/tests/worktree-post-create-hook.test.ts +165 -0
  368. package/dist/resources/extensions/gsd/tests/worktree-sync-milestones.test.ts +206 -0
  369. package/dist/resources/extensions/gsd/tests/worktree.test.ts +171 -0
  370. package/dist/resources/extensions/gsd/tests/write-gate.test.ts +211 -0
  371. package/dist/resources/extensions/gsd/token-counter.ts +65 -0
  372. package/dist/resources/extensions/gsd/triage-resolution.ts +284 -0
  373. package/dist/resources/extensions/gsd/triage-ui.ts +175 -0
  374. package/dist/resources/extensions/gsd/types.ts +425 -0
  375. package/dist/resources/extensions/gsd/undo.ts +223 -0
  376. package/dist/resources/extensions/gsd/unit-id.ts +14 -0
  377. package/dist/resources/extensions/gsd/unit-runtime.ts +192 -0
  378. package/dist/resources/extensions/gsd/validate-directory.ts +164 -0
  379. package/dist/resources/extensions/gsd/verification-evidence.ts +188 -0
  380. package/dist/resources/extensions/gsd/verification-gate.ts +643 -0
  381. package/dist/resources/extensions/gsd/visualizer-data.ts +866 -0
  382. package/dist/resources/extensions/gsd/visualizer-overlay.ts +566 -0
  383. package/dist/resources/extensions/gsd/visualizer-views.ts +1171 -0
  384. package/dist/resources/extensions/gsd/workflow-templates.ts +241 -0
  385. package/dist/resources/extensions/gsd/workspace-index.ts +217 -0
  386. package/dist/resources/extensions/gsd/worktree-command.ts +807 -0
  387. package/dist/resources/extensions/gsd/worktree-manager.ts +449 -0
  388. package/dist/resources/extensions/gsd/worktree.ts +257 -0
  389. package/dist/resources/extensions/mac-tools/index.ts +852 -0
  390. package/dist/resources/extensions/mcp-client/index.ts +459 -0
  391. package/dist/resources/extensions/remote-questions/config.ts +83 -0
  392. package/dist/resources/extensions/remote-questions/discord-adapter.ts +148 -0
  393. package/dist/resources/extensions/remote-questions/format.ts +315 -0
  394. package/dist/resources/extensions/remote-questions/http-client.ts +76 -0
  395. package/dist/resources/extensions/remote-questions/manager.ts +184 -0
  396. package/dist/resources/extensions/remote-questions/{mod.js → mod.ts} +10 -1
  397. package/dist/resources/extensions/remote-questions/notify.ts +90 -0
  398. package/dist/resources/extensions/remote-questions/remote-command.ts +457 -0
  399. package/dist/resources/extensions/remote-questions/slack-adapter.ts +141 -0
  400. package/dist/resources/extensions/remote-questions/status.ts +31 -0
  401. package/dist/resources/extensions/remote-questions/store.ts +81 -0
  402. package/dist/resources/extensions/remote-questions/telegram-adapter.ts +149 -0
  403. package/dist/resources/extensions/remote-questions/types.ts +102 -0
  404. package/dist/resources/extensions/search-the-web/cache.ts +78 -0
  405. package/dist/resources/extensions/search-the-web/command-search-provider.ts +101 -0
  406. package/dist/resources/extensions/search-the-web/format.ts +258 -0
  407. package/dist/resources/extensions/search-the-web/http.ts +238 -0
  408. package/dist/resources/extensions/search-the-web/index.ts +65 -0
  409. package/dist/resources/extensions/search-the-web/native-search.ts +193 -0
  410. package/dist/resources/extensions/search-the-web/provider.ts +148 -0
  411. package/dist/resources/extensions/search-the-web/tavily.ts +116 -0
  412. package/dist/resources/extensions/search-the-web/tool-fetch-page.ts +589 -0
  413. package/dist/resources/extensions/search-the-web/tool-llm-context.ts +608 -0
  414. package/dist/resources/extensions/search-the-web/tool-search.ts +649 -0
  415. package/dist/resources/extensions/search-the-web/url-utils.ts +125 -0
  416. package/dist/resources/extensions/shared/confirm-ui.ts +126 -0
  417. package/dist/resources/extensions/shared/{format-utils.js → format-utils.ts} +91 -85
  418. package/dist/resources/extensions/shared/frontmatter.ts +117 -0
  419. package/dist/resources/extensions/shared/interview-ui.ts +613 -0
  420. package/dist/resources/extensions/shared/{mod.js → mod.ts} +24 -2
  421. package/dist/resources/extensions/shared/next-action-ui.ts +212 -0
  422. package/dist/resources/extensions/shared/{path-display.js → path-display.ts} +3 -2
  423. package/dist/resources/extensions/shared/sanitize.ts +19 -0
  424. package/dist/resources/extensions/shared/terminal.ts +23 -0
  425. package/dist/resources/extensions/shared/tests/format-utils.test.ts +153 -0
  426. package/dist/resources/extensions/shared/ui.ts +400 -0
  427. package/dist/resources/extensions/shared/wizard-ui.ts +551 -0
  428. package/dist/resources/extensions/slash-commands/audit.ts +88 -0
  429. package/dist/resources/extensions/slash-commands/clear.ts +10 -0
  430. package/dist/resources/extensions/slash-commands/create-extension.ts +297 -0
  431. package/dist/resources/extensions/slash-commands/create-slash-command.ts +234 -0
  432. package/dist/resources/extensions/slash-commands/index.ts +12 -0
  433. package/dist/resources/extensions/subagent/agents.ts +126 -0
  434. package/dist/resources/extensions/subagent/index.ts +1121 -0
  435. package/dist/resources/extensions/subagent/isolation.ts +501 -0
  436. package/dist/resources/extensions/subagent/worker-registry.ts +99 -0
  437. package/dist/resources/extensions/ttsr/index.ts +168 -0
  438. package/dist/resources/extensions/ttsr/rule-loader.ts +74 -0
  439. package/dist/resources/extensions/ttsr/ttsr-manager.ts +456 -0
  440. package/dist/resources/extensions/universal-config/discovery.ts +104 -0
  441. package/dist/resources/extensions/universal-config/format.ts +191 -0
  442. package/dist/resources/extensions/universal-config/index.ts +120 -0
  443. package/dist/resources/extensions/universal-config/scanners.ts +642 -0
  444. package/dist/resources/extensions/universal-config/tests/discovery.test.ts +119 -0
  445. package/dist/resources/extensions/universal-config/tests/format.test.ts +127 -0
  446. package/dist/resources/extensions/universal-config/tests/scanners.test.ts +456 -0
  447. package/dist/resources/extensions/universal-config/tools.ts +60 -0
  448. package/dist/resources/extensions/universal-config/types.ts +135 -0
  449. package/dist/resources/extensions/voice/index.ts +272 -0
  450. package/dist/resources/skills/create-gsd-extension/templates/extension-skeleton.ts +51 -0
  451. package/dist/resources/skills/create-gsd-extension/templates/stateful-tool-skeleton.ts +143 -0
  452. package/package.json +1 -1
  453. package/packages/pi-coding-agent/dist/core/extensions/index.d.ts +1 -1
  454. package/packages/pi-coding-agent/dist/core/extensions/index.d.ts.map +1 -1
  455. package/packages/pi-coding-agent/dist/core/extensions/index.js +1 -1
  456. package/packages/pi-coding-agent/dist/core/extensions/index.js.map +1 -1
  457. package/packages/pi-coding-agent/dist/core/extensions/loader.d.ts +0 -1
  458. package/packages/pi-coding-agent/dist/core/extensions/loader.d.ts.map +1 -1
  459. package/packages/pi-coding-agent/dist/core/extensions/loader.js +4 -31
  460. package/packages/pi-coding-agent/dist/core/extensions/loader.js.map +1 -1
  461. package/packages/pi-coding-agent/dist/index.d.ts +1 -1
  462. package/packages/pi-coding-agent/dist/index.d.ts.map +1 -1
  463. package/packages/pi-coding-agent/dist/index.js +1 -1
  464. package/packages/pi-coding-agent/dist/index.js.map +1 -1
  465. package/packages/pi-coding-agent/src/core/extensions/index.ts +0 -1
  466. package/packages/pi-coding-agent/src/core/extensions/loader.ts +4 -35
  467. package/packages/pi-coding-agent/src/index.ts +0 -1
  468. package/src/resources/extensions/bg-shell/index.ts +46 -41
  469. package/src/resources/extensions/browser-tools/index.ts +67 -156
  470. package/src/resources/extensions/gsd/auto-verification.ts +2 -20
  471. package/src/resources/extensions/gsd/auto-worktree.ts +2 -3
  472. package/src/resources/extensions/gsd/commands.ts +31 -39
  473. package/src/resources/extensions/gsd/git-service.ts +0 -7
  474. package/src/resources/extensions/gsd/index.ts +32 -93
  475. package/src/resources/extensions/gsd/quick.ts +3 -52
  476. package/src/resources/extensions/gsd/repo-identity.ts +22 -56
  477. package/src/resources/extensions/gsd/tests/loop-regression.test.ts +4 -1
  478. package/src/resources/extensions/gsd/tests/verification-gate.test.ts +0 -65
  479. package/src/resources/extensions/gsd/types.ts +0 -4
  480. package/src/resources/extensions/gsd/verification-evidence.ts +1 -1
  481. package/src/resources/extensions/gsd/verification-gate.ts +2 -23
  482. package/src/resources/extensions/gsd/worktree-command.ts +11 -17
  483. package/src/resources/extensions/search-the-web/command-search-provider.ts +1 -1
  484. package/src/resources/extensions/search-the-web/index.ts +52 -35
  485. package/src/resources/extensions/search-the-web/tavily.ts +1 -1
  486. package/dist/resources/extensions/ask-user-questions.js +0 -217
  487. package/dist/resources/extensions/async-jobs/async-bash-tool.js +0 -180
  488. package/dist/resources/extensions/async-jobs/await-tool.js +0 -90
  489. package/dist/resources/extensions/async-jobs/cancel-job-tool.js +0 -28
  490. package/dist/resources/extensions/async-jobs/index.js +0 -119
  491. package/dist/resources/extensions/async-jobs/job-manager.js +0 -159
  492. package/dist/resources/extensions/aws-auth/index.js +0 -138
  493. package/dist/resources/extensions/bg-shell/bg-shell-command.js +0 -182
  494. package/dist/resources/extensions/bg-shell/bg-shell-lifecycle.js +0 -343
  495. package/dist/resources/extensions/bg-shell/bg-shell-tool.js +0 -831
  496. package/dist/resources/extensions/bg-shell/index.js +0 -41
  497. package/dist/resources/extensions/bg-shell/interaction.js +0 -160
  498. package/dist/resources/extensions/bg-shell/output-formatter.js +0 -245
  499. package/dist/resources/extensions/bg-shell/overlay.js +0 -378
  500. package/dist/resources/extensions/bg-shell/process-manager.js +0 -413
  501. package/dist/resources/extensions/bg-shell/readiness-detector.js +0 -109
  502. package/dist/resources/extensions/bg-shell/types.js +0 -96
  503. package/dist/resources/extensions/bg-shell/utilities.js +0 -50
  504. package/dist/resources/extensions/browser-tools/capture.js +0 -179
  505. package/dist/resources/extensions/browser-tools/core.js +0 -899
  506. package/dist/resources/extensions/browser-tools/index.js +0 -123
  507. package/dist/resources/extensions/browser-tools/lifecycle.js +0 -222
  508. package/dist/resources/extensions/browser-tools/refs.js +0 -254
  509. package/dist/resources/extensions/browser-tools/settle.js +0 -173
  510. package/dist/resources/extensions/browser-tools/state.js +0 -126
  511. package/dist/resources/extensions/browser-tools/tools/action-cache.js +0 -179
  512. package/dist/resources/extensions/browser-tools/tools/assertions.js +0 -320
  513. package/dist/resources/extensions/browser-tools/tools/codegen.js +0 -242
  514. package/dist/resources/extensions/browser-tools/tools/device.js +0 -162
  515. package/dist/resources/extensions/browser-tools/tools/extract.js +0 -191
  516. package/dist/resources/extensions/browser-tools/tools/forms.js +0 -710
  517. package/dist/resources/extensions/browser-tools/tools/injection-detect.js +0 -178
  518. package/dist/resources/extensions/browser-tools/tools/inspection.js +0 -426
  519. package/dist/resources/extensions/browser-tools/tools/intent.js +0 -556
  520. package/dist/resources/extensions/browser-tools/tools/interaction.js +0 -776
  521. package/dist/resources/extensions/browser-tools/tools/navigation.js +0 -208
  522. package/dist/resources/extensions/browser-tools/tools/network-mock.js +0 -194
  523. package/dist/resources/extensions/browser-tools/tools/pages.js +0 -280
  524. package/dist/resources/extensions/browser-tools/tools/pdf.js +0 -74
  525. package/dist/resources/extensions/browser-tools/tools/refs.js +0 -485
  526. package/dist/resources/extensions/browser-tools/tools/screenshot.js +0 -87
  527. package/dist/resources/extensions/browser-tools/tools/session.js +0 -375
  528. package/dist/resources/extensions/browser-tools/tools/state-persistence.js +0 -180
  529. package/dist/resources/extensions/browser-tools/tools/visual-diff.js +0 -174
  530. package/dist/resources/extensions/browser-tools/tools/wait.js +0 -201
  531. package/dist/resources/extensions/browser-tools/tools/zoom.js +0 -90
  532. package/dist/resources/extensions/browser-tools/utils.js +0 -490
  533. package/dist/resources/extensions/context7/index.js +0 -337
  534. package/dist/resources/extensions/get-secrets-from-user.js +0 -492
  535. package/dist/resources/extensions/google-search/index.js +0 -373
  536. package/dist/resources/extensions/gsd/activity-log.js +0 -146
  537. package/dist/resources/extensions/gsd/atomic-write.js +0 -38
  538. package/dist/resources/extensions/gsd/auto/session.js +0 -187
  539. package/dist/resources/extensions/gsd/auto-budget.js +0 -30
  540. package/dist/resources/extensions/gsd/auto-dashboard.js +0 -509
  541. package/dist/resources/extensions/gsd/auto-direct-dispatch.js +0 -180
  542. package/dist/resources/extensions/gsd/auto-dispatch.js +0 -382
  543. package/dist/resources/extensions/gsd/auto-idempotency.js +0 -106
  544. package/dist/resources/extensions/gsd/auto-model-selection.js +0 -133
  545. package/dist/resources/extensions/gsd/auto-observability.js +0 -54
  546. package/dist/resources/extensions/gsd/auto-post-unit.js +0 -495
  547. package/dist/resources/extensions/gsd/auto-prompts.js +0 -1121
  548. package/dist/resources/extensions/gsd/auto-recovery.js +0 -550
  549. package/dist/resources/extensions/gsd/auto-start.js +0 -393
  550. package/dist/resources/extensions/gsd/auto-stuck-detection.js +0 -165
  551. package/dist/resources/extensions/gsd/auto-timeout-recovery.js +0 -183
  552. package/dist/resources/extensions/gsd/auto-timers.js +0 -181
  553. package/dist/resources/extensions/gsd/auto-tool-tracking.js +0 -50
  554. package/dist/resources/extensions/gsd/auto-unit-closeout.js +0 -30
  555. package/dist/resources/extensions/gsd/auto-verification.js +0 -209
  556. package/dist/resources/extensions/gsd/auto-worktree.js +0 -594
  557. package/dist/resources/extensions/gsd/auto.js +0 -1485
  558. package/dist/resources/extensions/gsd/captures.js +0 -348
  559. package/dist/resources/extensions/gsd/claude-import.js +0 -540
  560. package/dist/resources/extensions/gsd/collision-diagnostics.js +0 -226
  561. package/dist/resources/extensions/gsd/commands-bootstrap.js +0 -223
  562. package/dist/resources/extensions/gsd/commands-config.js +0 -89
  563. package/dist/resources/extensions/gsd/commands-extensions.js +0 -259
  564. package/dist/resources/extensions/gsd/commands-handlers.js +0 -310
  565. package/dist/resources/extensions/gsd/commands-inspect.js +0 -70
  566. package/dist/resources/extensions/gsd/commands-logs.js +0 -468
  567. package/dist/resources/extensions/gsd/commands-maintenance.js +0 -185
  568. package/dist/resources/extensions/gsd/commands-prefs-wizard.js +0 -660
  569. package/dist/resources/extensions/gsd/commands-workflow-templates.js +0 -408
  570. package/dist/resources/extensions/gsd/commands.js +0 -1024
  571. package/dist/resources/extensions/gsd/complexity-classifier.js +0 -257
  572. package/dist/resources/extensions/gsd/context-budget.js +0 -187
  573. package/dist/resources/extensions/gsd/context-store.js +0 -165
  574. package/dist/resources/extensions/gsd/crash-recovery.js +0 -110
  575. package/dist/resources/extensions/gsd/dashboard-overlay.js +0 -562
  576. package/dist/resources/extensions/gsd/db-writer.js +0 -298
  577. package/dist/resources/extensions/gsd/debug-logger.js +0 -161
  578. package/dist/resources/extensions/gsd/detection.js +0 -373
  579. package/dist/resources/extensions/gsd/diff-context.js +0 -168
  580. package/dist/resources/extensions/gsd/dispatch-guard.js +0 -76
  581. package/dist/resources/extensions/gsd/doctor-checks.js +0 -563
  582. package/dist/resources/extensions/gsd/doctor-environment.js +0 -429
  583. package/dist/resources/extensions/gsd/doctor-format.js +0 -71
  584. package/dist/resources/extensions/gsd/doctor-proactive.js +0 -239
  585. package/dist/resources/extensions/gsd/doctor-providers.js +0 -292
  586. package/dist/resources/extensions/gsd/doctor-types.js +0 -12
  587. package/dist/resources/extensions/gsd/doctor.js +0 -672
  588. package/dist/resources/extensions/gsd/error-utils.js +0 -6
  589. package/dist/resources/extensions/gsd/exit-command.js +0 -11
  590. package/dist/resources/extensions/gsd/export.js +0 -268
  591. package/dist/resources/extensions/gsd/file-watcher.js +0 -76
  592. package/dist/resources/extensions/gsd/files.js +0 -937
  593. package/dist/resources/extensions/gsd/forensics.js +0 -511
  594. package/dist/resources/extensions/gsd/git-self-heal.js +0 -113
  595. package/dist/resources/extensions/gsd/git-service.js +0 -460
  596. package/dist/resources/extensions/gsd/gsd-db.js +0 -590
  597. package/dist/resources/extensions/gsd/guided-flow-queue.js +0 -366
  598. package/dist/resources/extensions/gsd/guided-flow.js +0 -1149
  599. package/dist/resources/extensions/gsd/health-widget.js +0 -141
  600. package/dist/resources/extensions/gsd/history.js +0 -118
  601. package/dist/resources/extensions/gsd/index.js +0 -1250
  602. package/dist/resources/extensions/gsd/init-wizard.js +0 -479
  603. package/dist/resources/extensions/gsd/json-persistence.js +0 -62
  604. package/dist/resources/extensions/gsd/key-manager.js +0 -829
  605. package/dist/resources/extensions/gsd/marketplace-discovery.js +0 -356
  606. package/dist/resources/extensions/gsd/md-importer.js +0 -440
  607. package/dist/resources/extensions/gsd/mechanical-completion.js +0 -351
  608. package/dist/resources/extensions/gsd/memory-extractor.js +0 -295
  609. package/dist/resources/extensions/gsd/memory-store.js +0 -351
  610. package/dist/resources/extensions/gsd/metrics.js +0 -377
  611. package/dist/resources/extensions/gsd/migrate/command.js +0 -157
  612. package/dist/resources/extensions/gsd/migrate/index.js +0 -7
  613. package/dist/resources/extensions/gsd/migrate/parser.js +0 -268
  614. package/dist/resources/extensions/gsd/migrate/parsers.js +0 -477
  615. package/dist/resources/extensions/gsd/migrate/preview.js +0 -47
  616. package/dist/resources/extensions/gsd/migrate/transformer.js +0 -278
  617. package/dist/resources/extensions/gsd/migrate/types.js +0 -4
  618. package/dist/resources/extensions/gsd/migrate/validator.js +0 -41
  619. package/dist/resources/extensions/gsd/migrate/writer.js +0 -477
  620. package/dist/resources/extensions/gsd/migrate-external.js +0 -130
  621. package/dist/resources/extensions/gsd/milestone-actions.js +0 -111
  622. package/dist/resources/extensions/gsd/model-cost-table.js +0 -48
  623. package/dist/resources/extensions/gsd/model-router.js +0 -187
  624. package/dist/resources/extensions/gsd/namespaced-registry.js +0 -322
  625. package/dist/resources/extensions/gsd/namespaced-resolver.js +0 -176
  626. package/dist/resources/extensions/gsd/native-git-bridge.js +0 -842
  627. package/dist/resources/extensions/gsd/native-parser-bridge.js +0 -156
  628. package/dist/resources/extensions/gsd/notifications.js +0 -58
  629. package/dist/resources/extensions/gsd/observability-validator.js +0 -398
  630. package/dist/resources/extensions/gsd/parallel-eligibility.js +0 -182
  631. package/dist/resources/extensions/gsd/parallel-merge.js +0 -121
  632. package/dist/resources/extensions/gsd/parallel-orchestrator.js +0 -687
  633. package/dist/resources/extensions/gsd/paths.js +0 -414
  634. package/dist/resources/extensions/gsd/plugin-importer.js +0 -254
  635. package/dist/resources/extensions/gsd/post-unit-hooks.js +0 -433
  636. package/dist/resources/extensions/gsd/preferences-models.js +0 -294
  637. package/dist/resources/extensions/gsd/preferences-skills.js +0 -154
  638. package/dist/resources/extensions/gsd/preferences-types.js +0 -73
  639. package/dist/resources/extensions/gsd/preferences-validation.js +0 -607
  640. package/dist/resources/extensions/gsd/preferences.js +0 -325
  641. package/dist/resources/extensions/gsd/progress-score.js +0 -197
  642. package/dist/resources/extensions/gsd/prompt-cache-optimizer.js +0 -150
  643. package/dist/resources/extensions/gsd/prompt-compressor.js +0 -393
  644. package/dist/resources/extensions/gsd/prompt-loader.js +0 -119
  645. package/dist/resources/extensions/gsd/prompt-ordering.js +0 -170
  646. package/dist/resources/extensions/gsd/provider-error-pause.js +0 -60
  647. package/dist/resources/extensions/gsd/queue-order.js +0 -178
  648. package/dist/resources/extensions/gsd/queue-reorder-ui.js +0 -234
  649. package/dist/resources/extensions/gsd/quick.js +0 -230
  650. package/dist/resources/extensions/gsd/repo-identity.js +0 -187
  651. package/dist/resources/extensions/gsd/roadmap-slices.js +0 -130
  652. package/dist/resources/extensions/gsd/routing-history.js +0 -210
  653. package/dist/resources/extensions/gsd/safe-fs.js +0 -52
  654. package/dist/resources/extensions/gsd/semantic-chunker.js +0 -254
  655. package/dist/resources/extensions/gsd/session-forensics.js +0 -427
  656. package/dist/resources/extensions/gsd/session-lock.js +0 -376
  657. package/dist/resources/extensions/gsd/session-status-io.js +0 -134
  658. package/dist/resources/extensions/gsd/skill-discovery.js +0 -121
  659. package/dist/resources/extensions/gsd/skill-health.js +0 -324
  660. package/dist/resources/extensions/gsd/state.js +0 -653
  661. package/dist/resources/extensions/gsd/structured-data-formatter.js +0 -97
  662. package/dist/resources/extensions/gsd/summary-distiller.js +0 -212
  663. package/dist/resources/extensions/gsd/token-counter.js +0 -54
  664. package/dist/resources/extensions/gsd/triage-resolution.js +0 -217
  665. package/dist/resources/extensions/gsd/triage-ui.js +0 -125
  666. package/dist/resources/extensions/gsd/types.js +0 -4
  667. package/dist/resources/extensions/gsd/undo.js +0 -210
  668. package/dist/resources/extensions/gsd/unit-id.js +0 -7
  669. package/dist/resources/extensions/gsd/unit-runtime.js +0 -130
  670. package/dist/resources/extensions/gsd/validate-directory.js +0 -143
  671. package/dist/resources/extensions/gsd/verification-evidence.js +0 -123
  672. package/dist/resources/extensions/gsd/verification-gate.js +0 -543
  673. package/dist/resources/extensions/gsd/visualizer-data.js +0 -612
  674. package/dist/resources/extensions/gsd/visualizer-overlay.js +0 -501
  675. package/dist/resources/extensions/gsd/visualizer-views.js +0 -893
  676. package/dist/resources/extensions/gsd/workflow-templates.js +0 -188
  677. package/dist/resources/extensions/gsd/workspace-index.js +0 -139
  678. package/dist/resources/extensions/gsd/worktree-command-bootstrap.js +0 -40
  679. package/dist/resources/extensions/gsd/worktree-command.js +0 -676
  680. package/dist/resources/extensions/gsd/worktree-manager.js +0 -359
  681. package/dist/resources/extensions/gsd/worktree.js +0 -236
  682. package/dist/resources/extensions/mac-tools/index.js +0 -768
  683. package/dist/resources/extensions/mcp-client/index.js +0 -363
  684. package/dist/resources/extensions/package.json +0 -3
  685. package/dist/resources/extensions/remote-questions/config.js +0 -70
  686. package/dist/resources/extensions/remote-questions/discord-adapter.js +0 -134
  687. package/dist/resources/extensions/remote-questions/format.js +0 -234
  688. package/dist/resources/extensions/remote-questions/http-client.js +0 -43
  689. package/dist/resources/extensions/remote-questions/manager.js +0 -156
  690. package/dist/resources/extensions/remote-questions/notify.js +0 -89
  691. package/dist/resources/extensions/remote-questions/remote-command.js +0 -453
  692. package/dist/resources/extensions/remote-questions/slack-adapter.js +0 -123
  693. package/dist/resources/extensions/remote-questions/status.js +0 -25
  694. package/dist/resources/extensions/remote-questions/store.js +0 -70
  695. package/dist/resources/extensions/remote-questions/telegram-adapter.js +0 -123
  696. package/dist/resources/extensions/remote-questions/types.js +0 -5
  697. package/dist/resources/extensions/search-the-web/cache.js +0 -74
  698. package/dist/resources/extensions/search-the-web/command-search-provider.js +0 -79
  699. package/dist/resources/extensions/search-the-web/format.js +0 -161
  700. package/dist/resources/extensions/search-the-web/http.js +0 -178
  701. package/dist/resources/extensions/search-the-web/index.js +0 -41
  702. package/dist/resources/extensions/search-the-web/native-search.js +0 -166
  703. package/dist/resources/extensions/search-the-web/provider.js +0 -143
  704. package/dist/resources/extensions/search-the-web/tavily.js +0 -82
  705. package/dist/resources/extensions/search-the-web/tool-fetch-page.js +0 -452
  706. package/dist/resources/extensions/search-the-web/tool-llm-context.js +0 -455
  707. package/dist/resources/extensions/search-the-web/tool-search.js +0 -482
  708. package/dist/resources/extensions/search-the-web/url-utils.js +0 -121
  709. package/dist/resources/extensions/shared/confirm-ui.js +0 -96
  710. package/dist/resources/extensions/shared/frontmatter.js +0 -109
  711. package/dist/resources/extensions/shared/interview-ui.js +0 -569
  712. package/dist/resources/extensions/shared/next-action-ui.js +0 -168
  713. package/dist/resources/extensions/shared/sanitize.js +0 -17
  714. package/dist/resources/extensions/shared/terminal.js +0 -21
  715. package/dist/resources/extensions/shared/ui.js +0 -245
  716. package/dist/resources/extensions/shared/wizard-ui.js +0 -478
  717. package/dist/resources/extensions/slash-commands/audit.js +0 -72
  718. package/dist/resources/extensions/slash-commands/clear.js +0 -8
  719. package/dist/resources/extensions/slash-commands/create-extension.js +0 -264
  720. package/dist/resources/extensions/slash-commands/create-slash-command.js +0 -208
  721. package/dist/resources/extensions/slash-commands/index.js +0 -10
  722. package/dist/resources/extensions/subagent/agents.js +0 -103
  723. package/dist/resources/extensions/subagent/index.js +0 -905
  724. package/dist/resources/extensions/subagent/isolation.js +0 -384
  725. package/dist/resources/extensions/subagent/worker-registry.js +0 -73
  726. package/dist/resources/extensions/ttsr/index.js +0 -144
  727. package/dist/resources/extensions/ttsr/rule-loader.js +0 -70
  728. package/dist/resources/extensions/ttsr/ttsr-manager.js +0 -380
  729. package/dist/resources/extensions/universal-config/discovery.js +0 -94
  730. package/dist/resources/extensions/universal-config/format.js +0 -178
  731. package/dist/resources/extensions/universal-config/index.js +0 -99
  732. package/dist/resources/extensions/universal-config/scanners.js +0 -574
  733. package/dist/resources/extensions/universal-config/tools.js +0 -57
  734. package/dist/resources/extensions/universal-config/types.js +0 -8
  735. package/dist/resources/extensions/voice/index.js +0 -247
  736. package/dist/startup-timings.d.ts +0 -2
  737. package/dist/startup-timings.js +0 -22
  738. package/src/resources/extensions/gsd/commands-bootstrap.ts +0 -252
  739. package/src/resources/extensions/gsd/tests/quick-branch-lifecycle.test.ts +0 -281
  740. package/src/resources/extensions/gsd/tests/repo-identity-worktree.test.ts +0 -71
  741. package/src/resources/extensions/gsd/worktree-command-bootstrap.ts +0 -46
  742. package/src/resources/extensions/package.json +0 -3
@@ -0,0 +1,1401 @@
1
+ /**
2
+ * GSD Extension — /gsd
3
+ *
4
+ * One command, one wizard. Reads state from disk, shows contextual options,
5
+ * dispatches through GSD-WORKFLOW.md. The LLM does the rest.
6
+ *
7
+ * Auto-mode: /gsd auto loops fresh sessions until milestone complete.
8
+ *
9
+ * Commands:
10
+ * /gsd — contextual wizard (smart entry point)
11
+ * /gsd auto — start auto-mode (fresh session per unit)
12
+ * /gsd stop — stop auto-mode gracefully
13
+ * /gsd status — progress dashboard
14
+ *
15
+ * Hooks:
16
+ * before_agent_start — inject GSD system context for GSD projects
17
+ * agent_end — auto-mode advancement
18
+ * session_before_compact — save continue.md OR block during auto
19
+ */
20
+
21
+ import type {
22
+ ExtensionAPI,
23
+ ExtensionCommandContext,
24
+ ExtensionContext,
25
+ } from "@gsd/pi-coding-agent";
26
+ import { createBashTool, createWriteTool, createReadTool, createEditTool, isToolCallEventType } from "@gsd/pi-coding-agent";
27
+ import { Type } from "@sinclair/typebox";
28
+
29
+ import { debugLog, debugTime } from "./debug-logger.js";
30
+ import { registerGSDCommand } from "./commands.js";
31
+ import { loadToolApiKeys } from "./commands-config.js";
32
+ import { registerExitCommand } from "./exit-command.js";
33
+ import { registerWorktreeCommand, getWorktreeOriginalCwd, getActiveWorktreeName } from "./worktree-command.js";
34
+ import { getActiveAutoWorktreeContext } from "./auto-worktree.js";
35
+ import { saveFile, formatContinue, loadFile, parseContinue, parseSummary, loadActiveOverrides, formatOverridesSection } from "./files.js";
36
+ import { loadPrompt } from "./prompt-loader.js";
37
+ import { deriveState } from "./state.js";
38
+ import { isAutoActive, isAutoPaused, handleAgentEnd, pauseAuto, getAutoDashboardData, getAutoModeStartModel, markToolStart, markToolEnd } from "./auto.js";
39
+ import { saveActivityLog } from "./activity-log.js";
40
+ import { checkAutoStartAfterDiscuss, getDiscussionMilestoneId, findMilestoneIds, nextMilestoneId } from "./guided-flow.js";
41
+ import { GSDDashboardOverlay } from "./dashboard-overlay.js";
42
+ import {
43
+ loadEffectiveGSDPreferences,
44
+ renderPreferencesForSystemPrompt,
45
+ resolveAllSkillReferences,
46
+ resolveModelWithFallbacksForUnit,
47
+ getNextFallbackModel,
48
+ isTransientNetworkError,
49
+ } from "./preferences.js";
50
+ import { hasSkillSnapshot, detectNewSkills, formatSkillsXml } from "./skill-discovery.js";
51
+ import {
52
+ resolveSlicePath, resolveSliceFile, resolveTaskFile, resolveTaskFiles, resolveTasksDir,
53
+ relSliceFile, relSlicePath, relTaskFile,
54
+ buildSliceFileName, buildMilestoneFileName, gsdRoot, resolveMilestonePath,
55
+ resolveGsdRootFile,
56
+ } from "./paths.js";
57
+ import { Key } from "@gsd/pi-tui";
58
+ import { join } from "node:path";
59
+ import { existsSync, readFileSync } from "node:fs";
60
+ import { homedir } from "node:os";
61
+ import { shortcutDesc } from "../shared/mod.js";
62
+ import { Text } from "@gsd/pi-tui";
63
+ import { pauseAutoForProviderError, classifyProviderError } from "./provider-error-pause.js";
64
+ import { toPosixPath } from "../shared/mod.js";
65
+ import { isParallelActive, shutdownParallel } from "./parallel-orchestrator.js";
66
+ import { DEFAULT_BASH_TIMEOUT_SECS } from "./constants.js";
67
+ import { getErrorMessage } from "./error-utils.js";
68
+
69
+ /**
70
+ * Ensure the GSD database is available, auto-initializing if needed.
71
+ * Returns true if the DB is ready, false if initialization failed.
72
+ */
73
+ async function ensureDbAvailable(): Promise<boolean> {
74
+ try {
75
+ const db = await import("./gsd-db.js");
76
+ if (db.isDbAvailable()) return true;
77
+
78
+ // Auto-initialize: open (and create if needed) the DB at the standard path
79
+ const gsdDir = gsdRoot(process.cwd());
80
+ if (!existsSync(gsdDir)) return false; // No GSD project — can't create DB
81
+ const dbPath = join(gsdDir, "gsd.db");
82
+ return db.openDatabase(dbPath);
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ // ── Agent Instructions ────────────────────────────────────────────────────
89
+ // Lightweight "always follow" files injected into every GSD agent session.
90
+ // Global: ~/.gsd/agent-instructions.md Project: .gsd/agent-instructions.md
91
+ // Both are loaded and concatenated (global first, project appends).
92
+
93
+ function loadAgentInstructions(): string | null {
94
+ const parts: string[] = [];
95
+
96
+ const globalPath = join(homedir(), ".gsd", "agent-instructions.md");
97
+ if (existsSync(globalPath)) {
98
+ try {
99
+ const content = readFileSync(globalPath, "utf-8").trim();
100
+ if (content) parts.push(content);
101
+ } catch { /* non-fatal — skip unreadable file */ }
102
+ }
103
+
104
+ const projectPath = join(process.cwd(), ".gsd", "agent-instructions.md");
105
+ if (existsSync(projectPath)) {
106
+ try {
107
+ const content = readFileSync(projectPath, "utf-8").trim();
108
+ if (content) parts.push(content);
109
+ } catch { /* non-fatal — skip unreadable file */ }
110
+ }
111
+
112
+ if (parts.length === 0) return null;
113
+ return parts.join("\n\n");
114
+ }
115
+
116
+ // ── Depth verification state ──────────────────────────────────────────────
117
+ // Tracks which milestones have passed depth verification.
118
+ // Single-milestone flows set '*' (wildcard). Multi-milestone flows set per-ID.
119
+ const depthVerifiedMilestones = new Set<string>();
120
+
121
+ // ── Queue phase tracking ──────────────────────────────────────────────────
122
+ // When true, the LLM is in a queue flow writing CONTEXT.md files.
123
+ // The write-gate applies during queue flows just like discussion flows.
124
+ let activeQueuePhase = false;
125
+
126
+ // ── Network error retry counters ──────────────────────────────────────────
127
+ // Tracks per-model retry attempts for transient network errors.
128
+ // Cleared when a model switch occurs or retries are exhausted.
129
+ const networkRetryCounters = new Map<string, number>();
130
+
131
+ // ── Transient error escalation ───────────────────────────────────────────
132
+ // Tracks consecutive transient auto-resume attempts. Each attempt doubles
133
+ // the delay. After MAX_TRANSIENT_AUTO_RESUMES consecutive failures, auto-mode
134
+ // pauses indefinitely to avoid infinite rapid-fire retries (#1166).
135
+ const MAX_TRANSIENT_AUTO_RESUMES = 5;
136
+ let consecutiveTransientErrors = 0;
137
+
138
+ export function isDepthVerified(): boolean {
139
+ return depthVerifiedMilestones.has("*") || depthVerifiedMilestones.size > 0;
140
+ }
141
+
142
+ /** Check whether a specific milestone has passed depth verification. */
143
+ export function isDepthVerifiedFor(milestoneId: string): boolean {
144
+ // Wildcard means "all milestones verified" (single-milestone flow)
145
+ if (depthVerifiedMilestones.has("*")) return true;
146
+ return depthVerifiedMilestones.has(milestoneId);
147
+ }
148
+
149
+ /** Mark a specific milestone as depth-verified. */
150
+ export function markDepthVerified(milestoneId: string): void {
151
+ depthVerifiedMilestones.add(milestoneId);
152
+ }
153
+
154
+ /** Check whether a queue phase is active. */
155
+ export function isQueuePhaseActive(): boolean {
156
+ return activeQueuePhase;
157
+ }
158
+
159
+ /** Set the queue phase state — called from guided-flow-queue.ts on dispatch. */
160
+ export function setQueuePhaseActive(active: boolean): void {
161
+ activeQueuePhase = active;
162
+ }
163
+
164
+ // ── Write-gate: block CONTEXT.md writes during discussion without depth verification ──
165
+ const MILESTONE_CONTEXT_RE = /M\d+(?:-[a-z0-9]{6})?-CONTEXT\.md$/;
166
+
167
+ export function shouldBlockContextWrite(
168
+ toolName: string,
169
+ inputPath: string,
170
+ milestoneId: string | null,
171
+ depthVerified: boolean,
172
+ queuePhaseActive?: boolean,
173
+ ): { block: boolean; reason?: string } {
174
+ if (toolName !== "write") return { block: false };
175
+
176
+ // Gate applies during both discussion (milestoneId set) and queue (queuePhaseActive) flows
177
+ const inDiscussion = milestoneId !== null;
178
+ const inQueue = queuePhaseActive ?? false;
179
+ if (!inDiscussion && !inQueue) return { block: false };
180
+
181
+ if (!MILESTONE_CONTEXT_RE.test(inputPath)) return { block: false };
182
+
183
+ // For discussion flows: check global depth verification (backward compat)
184
+ if (inDiscussion && depthVerified) return { block: false };
185
+
186
+ // For queue flows: extract milestone ID from the path and check per-milestone verification
187
+ if (inQueue) {
188
+ const pathMatch = inputPath.match(/\/(M\d+(?:-[a-z0-9]{6})?)-CONTEXT\.md$/);
189
+ const targetMid = pathMatch?.[1];
190
+ if (targetMid && depthVerifiedMilestones.has(targetMid)) return { block: false };
191
+ // Wildcard passes all
192
+ if (depthVerifiedMilestones.has("*")) return { block: false };
193
+ }
194
+
195
+ return {
196
+ block: true,
197
+ reason: `Blocked: Cannot write milestone CONTEXT.md without depth verification. ` +
198
+ `Use ask_user_questions with a question id containing "depth_verification" first. ` +
199
+ `For multi-milestone flows, include the milestone ID in the question id (e.g., "depth_verification_M001"). ` +
200
+ `This ensures each milestone's context has been critically examined before being written.`,
201
+ };
202
+ }
203
+
204
+ // ── ASCII logo ────────────────────────────────────────────────────────────
205
+ const GSD_LOGO_LINES = [
206
+ " ██████╗ ███████╗██████╗ ",
207
+ " ██╔════╝ ██╔════╝██╔══██╗",
208
+ " ██║ ███╗███████╗██║ ██║",
209
+ " ██║ ██║╚════██║██║ ██║",
210
+ " ╚██████╔╝███████║██████╔╝",
211
+ " ╚═════╝ ╚══════╝╚═════╝ ",
212
+ ];
213
+
214
+ export default function (pi: ExtensionAPI) {
215
+ registerGSDCommand(pi);
216
+ registerWorktreeCommand(pi);
217
+ registerExitCommand(pi);
218
+
219
+ // ── EPIPE guard — prevent crash when stdout/stderr pipe closes unexpectedly ──
220
+ // Node.js throws a fatal `Error: write EPIPE` when the parent process closes
221
+ // its end of the stdio pipe (e.g. during shell/IPC teardown) while auto-mode
222
+ // is still writing diagnostics. Catching this here gives auto-mode a clean
223
+ // chance to persist state and pause instead of crashing (see issue #739).
224
+ if (!process.listeners("uncaughtException").some(l => l.name === "_gsdEpipeGuard")) {
225
+ const _gsdEpipeGuard = (err: Error): void => {
226
+ const code = (err as NodeJS.ErrnoException).code;
227
+ if (code === "EPIPE") {
228
+ // Pipe closed — nothing we can write; just exit cleanly
229
+ process.exit(0);
230
+ }
231
+ // ECOMPROMISED: proper-lockfile's update timer detected mtime drift (system
232
+ // sleep, heavy event loop stall, or filesystem precision mismatch on Node.js
233
+ // v25+). The onCompromised callback already set _lockCompromised = true, but
234
+ // due to a subtle interaction between the synchronous fs adapter and the
235
+ // setTimeout boundary, the error can still propagate here as an uncaught
236
+ // exception. Exit cleanly so the process.once("exit") handler removes the
237
+ // lock directory — allowing the next session to acquire cleanly (#1322).
238
+ if (code === "ECOMPROMISED") {
239
+ process.exit(1);
240
+ }
241
+ // Re-throw anything that isn't EPIPE or ECOMPROMISED so real crashes still surface
242
+ throw err;
243
+ };
244
+ process.on("uncaughtException", _gsdEpipeGuard);
245
+ }
246
+
247
+ // ── /kill — immediate exit (bypass cleanup) ─────────────────────────────
248
+ pi.registerCommand("kill", {
249
+ description: "Exit GSD immediately (no cleanup)",
250
+ handler: async (_args: string, _ctx: ExtensionCommandContext) => {
251
+ process.exit(0);
252
+ },
253
+ });
254
+
255
+ // ── Dynamic-cwd bash tool with default timeout ────────────────────────
256
+ // The built-in bash tool captures cwd at startup. This replacement uses
257
+ // a spawnHook to read process.cwd() dynamically so that process.chdir()
258
+ // (used by /worktree switch) propagates to shell commands.
259
+ //
260
+ // The upstream SDK's bash tool has no default timeout — if the LLM omits
261
+ // the timeout parameter, commands run indefinitely, causing hangs on
262
+ // Windows where process killing is unreliable (see #40). We wrap execute
263
+ // to inject a 120-second default when no timeout is provided.
264
+ const baseBash = createBashTool(process.cwd(), {
265
+ spawnHook: (ctx) => ({ ...ctx, cwd: process.cwd() }),
266
+ });
267
+ const dynamicBash = {
268
+ ...baseBash,
269
+ execute: async (
270
+ toolCallId: string,
271
+ params: { command: string; timeout?: number },
272
+ signal?: AbortSignal,
273
+ onUpdate?: any,
274
+ ctx?: any,
275
+ ) => {
276
+ const paramsWithTimeout = {
277
+ ...params,
278
+ timeout: params.timeout ?? DEFAULT_BASH_TIMEOUT_SECS,
279
+ };
280
+ return (baseBash as any).execute(toolCallId, paramsWithTimeout, signal, onUpdate, ctx);
281
+ },
282
+ };
283
+ pi.registerTool(dynamicBash as any);
284
+
285
+ // ── Dynamic-cwd file tools (write, read, edit) ────────────────────────
286
+ // The built-in file tools capture cwd at startup. When process.chdir()
287
+ // moves us into a worktree, relative paths still resolve against the
288
+ // original launch directory. These replacements delegate to freshly-
289
+ // created tools on each call so that process.cwd() is read dynamically.
290
+ const baseWrite = createWriteTool(process.cwd());
291
+ const dynamicWrite = {
292
+ ...baseWrite,
293
+ execute: async (
294
+ toolCallId: string,
295
+ params: { path: string; content: string },
296
+ signal?: AbortSignal,
297
+ onUpdate?: any,
298
+ ctx?: any,
299
+ ) => {
300
+ const fresh = createWriteTool(process.cwd());
301
+ return (fresh as any).execute(toolCallId, params, signal, onUpdate, ctx);
302
+ },
303
+ };
304
+ pi.registerTool(dynamicWrite as any);
305
+
306
+ const baseRead = createReadTool(process.cwd());
307
+ const dynamicRead = {
308
+ ...baseRead,
309
+ execute: async (
310
+ toolCallId: string,
311
+ params: { path: string; offset?: number; limit?: number },
312
+ signal?: AbortSignal,
313
+ onUpdate?: any,
314
+ ctx?: any,
315
+ ) => {
316
+ const fresh = createReadTool(process.cwd());
317
+ return (fresh as any).execute(toolCallId, params, signal, onUpdate, ctx);
318
+ },
319
+ };
320
+ pi.registerTool(dynamicRead as any);
321
+
322
+ const baseEdit = createEditTool(process.cwd());
323
+ const dynamicEdit = {
324
+ ...baseEdit,
325
+ execute: async (
326
+ toolCallId: string,
327
+ params: { path: string; oldText: string; newText: string },
328
+ signal?: AbortSignal,
329
+ onUpdate?: any,
330
+ ctx?: any,
331
+ ) => {
332
+ const fresh = createEditTool(process.cwd());
333
+ return (fresh as any).execute(toolCallId, params, signal, onUpdate, ctx);
334
+ },
335
+ };
336
+ pi.registerTool(dynamicEdit as any);
337
+
338
+ // ── Structured LLM tools — DB-first write path (R014) ──────────────────
339
+
340
+ pi.registerTool({
341
+ name: "gsd_save_decision",
342
+ label: "Save Decision",
343
+ description:
344
+ "Record a project decision to the GSD database and regenerate DECISIONS.md. " +
345
+ "Decision IDs are auto-assigned — never provide an ID manually.",
346
+ promptSnippet: "Record a project decision to the GSD database (auto-assigns ID, regenerates DECISIONS.md)",
347
+ promptGuidelines: [
348
+ "Use gsd_save_decision when recording an architectural, pattern, library, or observability decision.",
349
+ "Decision IDs are auto-assigned (D001, D002, ...) — never guess or provide an ID.",
350
+ "All fields except revisable and when_context are required.",
351
+ "The tool writes to the DB and regenerates .gsd/DECISIONS.md automatically.",
352
+ ],
353
+ parameters: Type.Object({
354
+ scope: Type.String({ description: "Scope of the decision (e.g. 'architecture', 'library', 'observability')" }),
355
+ decision: Type.String({ description: "What is being decided" }),
356
+ choice: Type.String({ description: "The choice made" }),
357
+ rationale: Type.String({ description: "Why this choice was made" }),
358
+ revisable: Type.Optional(Type.String({ description: "Whether this can be revisited (default: 'Yes')" })),
359
+ when_context: Type.Optional(Type.String({ description: "When/context for the decision (e.g. milestone ID)" })),
360
+ }),
361
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
362
+ // Ensure DB is available (auto-initialize if needed)
363
+ if (!await ensureDbAvailable()) {
364
+ return {
365
+ content: [{ type: "text" as const, text: "Error: GSD database is not available. Cannot save decision." }],
366
+ isError: true,
367
+ details: { operation: "save_decision", error: "db_unavailable" },
368
+ };
369
+ }
370
+
371
+ try {
372
+ const { saveDecisionToDb } = await import("./db-writer.js");
373
+ const { id } = await saveDecisionToDb(
374
+ {
375
+ scope: params.scope,
376
+ decision: params.decision,
377
+ choice: params.choice,
378
+ rationale: params.rationale,
379
+ revisable: params.revisable,
380
+ when_context: params.when_context,
381
+ },
382
+ process.cwd(),
383
+ );
384
+ return {
385
+ content: [{ type: "text" as const, text: `Saved decision ${id}` }],
386
+ details: { operation: "save_decision", id },
387
+ };
388
+ } catch (err) {
389
+ const msg = getErrorMessage(err);
390
+ process.stderr.write(`gsd-db: gsd_save_decision tool failed: ${msg}\n`);
391
+ return {
392
+ content: [{ type: "text" as const, text: `Error saving decision: ${msg}` }],
393
+ isError: true,
394
+ details: { operation: "save_decision", error: msg },
395
+ };
396
+ }
397
+ },
398
+ });
399
+
400
+ pi.registerTool({
401
+ name: "gsd_update_requirement",
402
+ label: "Update Requirement",
403
+ description:
404
+ "Update an existing requirement in the GSD database and regenerate REQUIREMENTS.md. " +
405
+ "Provide the requirement ID (e.g. R001) and any fields to update.",
406
+ promptSnippet: "Update an existing GSD requirement by ID (regenerates REQUIREMENTS.md)",
407
+ promptGuidelines: [
408
+ "Use gsd_update_requirement to change status, validation, notes, or other fields on an existing requirement.",
409
+ "The id parameter is required — it must be an existing RXXX identifier.",
410
+ "All other fields are optional — only provided fields are updated.",
411
+ "The tool verifies the requirement exists before updating.",
412
+ ],
413
+ parameters: Type.Object({
414
+ id: Type.String({ description: "The requirement ID (e.g. R001, R014)" }),
415
+ status: Type.Optional(Type.String({ description: "New status (e.g. 'active', 'validated', 'deferred')" })),
416
+ validation: Type.Optional(Type.String({ description: "Validation criteria or proof" })),
417
+ notes: Type.Optional(Type.String({ description: "Additional notes" })),
418
+ description: Type.Optional(Type.String({ description: "Updated description" })),
419
+ primary_owner: Type.Optional(Type.String({ description: "Primary owning slice" })),
420
+ supporting_slices: Type.Optional(Type.String({ description: "Supporting slices" })),
421
+ }),
422
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
423
+ // Ensure DB is available (auto-initialize if needed)
424
+ if (!await ensureDbAvailable()) {
425
+ return {
426
+ content: [{ type: "text" as const, text: "Error: GSD database is not available. Cannot update requirement." }],
427
+ isError: true,
428
+ details: { operation: "update_requirement", id: params.id, error: "db_unavailable" },
429
+ };
430
+ }
431
+
432
+ try {
433
+ // Verify requirement exists
434
+ const db = await import("./gsd-db.js");
435
+ const existing = db.getRequirementById(params.id);
436
+ if (!existing) {
437
+ return {
438
+ content: [{ type: "text" as const, text: `Error: Requirement ${params.id} not found.` }],
439
+ isError: true,
440
+ details: { operation: "update_requirement", id: params.id, error: "not_found" },
441
+ };
442
+ }
443
+
444
+ const { updateRequirementInDb } = await import("./db-writer.js");
445
+ const updates: Record<string, string | undefined> = {};
446
+ if (params.status !== undefined) updates.status = params.status;
447
+ if (params.validation !== undefined) updates.validation = params.validation;
448
+ if (params.notes !== undefined) updates.notes = params.notes;
449
+ if (params.description !== undefined) updates.description = params.description;
450
+ if (params.primary_owner !== undefined) updates.primary_owner = params.primary_owner;
451
+ if (params.supporting_slices !== undefined) updates.supporting_slices = params.supporting_slices;
452
+
453
+ await updateRequirementInDb(params.id, updates, process.cwd());
454
+
455
+ return {
456
+ content: [{ type: "text" as const, text: `Updated requirement ${params.id}` }],
457
+ details: { operation: "update_requirement", id: params.id },
458
+ };
459
+ } catch (err) {
460
+ const msg = getErrorMessage(err);
461
+ process.stderr.write(`gsd-db: gsd_update_requirement tool failed: ${msg}\n`);
462
+ return {
463
+ content: [{ type: "text" as const, text: `Error updating requirement: ${msg}` }],
464
+ isError: true,
465
+ details: { operation: "update_requirement", id: params.id, error: msg },
466
+ };
467
+ }
468
+ },
469
+ });
470
+
471
+ pi.registerTool({
472
+ name: "gsd_save_summary",
473
+ label: "Save Summary",
474
+ description:
475
+ "Save a summary, research, context, or assessment artifact to the GSD database and write it to disk. " +
476
+ "Computes the file path from milestone/slice/task IDs automatically.",
477
+ promptSnippet: "Save a GSD artifact (summary/research/context/assessment) to DB and disk",
478
+ promptGuidelines: [
479
+ "Use gsd_save_summary to persist structured artifacts (SUMMARY, RESEARCH, CONTEXT, ASSESSMENT).",
480
+ "milestone_id is required. slice_id and task_id are optional — they determine the file path.",
481
+ "The tool computes the relative path automatically: milestones/M001/M001-SUMMARY.md, milestones/M001/slices/S01/S01-SUMMARY.md, etc.",
482
+ "artifact_type must be one of: SUMMARY, RESEARCH, CONTEXT, ASSESSMENT.",
483
+ ],
484
+ parameters: Type.Object({
485
+ milestone_id: Type.String({ description: "Milestone ID (e.g. M001)" }),
486
+ slice_id: Type.Optional(Type.String({ description: "Slice ID (e.g. S01)" })),
487
+ task_id: Type.Optional(Type.String({ description: "Task ID (e.g. T01)" })),
488
+ artifact_type: Type.String({ description: "One of: SUMMARY, RESEARCH, CONTEXT, ASSESSMENT" }),
489
+ content: Type.String({ description: "The full markdown content of the artifact" }),
490
+ }),
491
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
492
+ // Ensure DB is available (auto-initialize if needed)
493
+ if (!await ensureDbAvailable()) {
494
+ return {
495
+ content: [{ type: "text" as const, text: "Error: GSD database is not available. Cannot save artifact." }],
496
+ isError: true,
497
+ details: { operation: "save_summary", error: "db_unavailable" },
498
+ };
499
+ }
500
+
501
+ // Validate artifact_type
502
+ const validTypes = ["SUMMARY", "RESEARCH", "CONTEXT", "ASSESSMENT"];
503
+ if (!validTypes.includes(params.artifact_type)) {
504
+ return {
505
+ content: [{ type: "text" as const, text: `Error: Invalid artifact_type "${params.artifact_type}". Must be one of: ${validTypes.join(", ")}` }],
506
+ isError: true,
507
+ details: { operation: "save_summary", error: "invalid_artifact_type" },
508
+ };
509
+ }
510
+
511
+ try {
512
+ // Compute relative path from IDs
513
+ let relativePath: string;
514
+ if (params.task_id && params.slice_id) {
515
+ relativePath = `milestones/${params.milestone_id}/slices/${params.slice_id}/tasks/${params.task_id}-${params.artifact_type}.md`;
516
+ } else if (params.slice_id) {
517
+ relativePath = `milestones/${params.milestone_id}/slices/${params.slice_id}/${params.slice_id}-${params.artifact_type}.md`;
518
+ } else {
519
+ relativePath = `milestones/${params.milestone_id}/${params.milestone_id}-${params.artifact_type}.md`;
520
+ }
521
+
522
+ const { saveArtifactToDb } = await import("./db-writer.js");
523
+ await saveArtifactToDb(
524
+ {
525
+ path: relativePath,
526
+ artifact_type: params.artifact_type,
527
+ content: params.content,
528
+ milestone_id: params.milestone_id,
529
+ slice_id: params.slice_id,
530
+ task_id: params.task_id,
531
+ },
532
+ process.cwd(),
533
+ );
534
+
535
+ return {
536
+ content: [{ type: "text" as const, text: `Saved ${params.artifact_type} artifact to ${relativePath}` }],
537
+ details: { operation: "save_summary", path: relativePath, artifact_type: params.artifact_type },
538
+ };
539
+ } catch (err) {
540
+ const msg = getErrorMessage(err);
541
+ process.stderr.write(`gsd-db: gsd_save_summary tool failed: ${msg}\n`);
542
+ return {
543
+ content: [{ type: "text" as const, text: `Error saving artifact: ${msg}` }],
544
+ isError: true,
545
+ details: { operation: "save_summary", error: msg },
546
+ };
547
+ }
548
+ },
549
+ });
550
+
551
+ // ── gsd_generate_milestone_id — canonical milestone ID generation ──────
552
+ // The LLM cannot generate random suffixes for unique_milestone_ids on its
553
+ // own. This tool calls back into the TS code that owns ID generation,
554
+ // ensuring the preference is always respected and IDs are always valid.
555
+ //
556
+ // Reservation set: tracks IDs returned by this tool but not yet persisted
557
+ // to disk, preventing duplicate M001 when called multiple times (#961).
558
+ const reservedMilestoneIds = new Set<string>();
559
+
560
+ pi.registerTool({
561
+ name: "gsd_generate_milestone_id",
562
+ label: "Generate Milestone ID",
563
+ description:
564
+ "Generate the next milestone ID for a new GSD milestone. " +
565
+ "Scans existing milestones on disk and respects the unique_milestone_ids preference. " +
566
+ "Always use this tool when creating a new milestone — never invent milestone IDs manually.",
567
+ promptSnippet: "Generate a valid milestone ID (respects unique_milestone_ids preference)",
568
+ promptGuidelines: [
569
+ "ALWAYS call gsd_generate_milestone_id before creating a new milestone directory or writing milestone files.",
570
+ "Never invent or hardcode milestone IDs like M001, M002 — always use this tool.",
571
+ "Call it once per milestone you need to create. For multi-milestone projects, call it once for each milestone in sequence.",
572
+ "The tool returns the correct format based on project preferences (e.g. M001 or M001-r5jzab).",
573
+ ],
574
+ parameters: Type.Object({}),
575
+ async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
576
+ try {
577
+ const basePath = process.cwd();
578
+ const existingIds = findMilestoneIds(basePath);
579
+ const uniqueEnabled = !!loadEffectiveGSDPreferences()?.preferences?.unique_milestone_ids;
580
+ // Combine on-disk IDs with previously reserved (but not yet persisted) IDs
581
+ const allIds = [...new Set([...existingIds, ...reservedMilestoneIds])];
582
+ const newId = nextMilestoneId(allIds, uniqueEnabled);
583
+ reservedMilestoneIds.add(newId);
584
+ return {
585
+ content: [{ type: "text" as const, text: newId }],
586
+ details: { operation: "generate_milestone_id", id: newId, existingCount: existingIds.length, reservedCount: reservedMilestoneIds.size, uniqueEnabled },
587
+ };
588
+ } catch (err) {
589
+ const msg = getErrorMessage(err);
590
+ return {
591
+ content: [{ type: "text" as const, text: `Error generating milestone ID: ${msg}` }],
592
+ isError: true,
593
+ details: { operation: "generate_milestone_id", error: msg },
594
+ };
595
+ }
596
+ },
597
+ });
598
+
599
+ // ── session_start: render branded GSD header + load tool keys + remote status ──
600
+ pi.on("session_start", async (_event, ctx) => {
601
+ // Clear depth verification and queue phase state from any prior session
602
+ depthVerifiedMilestones.clear();
603
+ activeQueuePhase = false;
604
+
605
+ // Theme access throws in RPC mode (no TUI) — header is decorative, skip it
606
+ try {
607
+ const theme = ctx.ui.theme;
608
+ const version = process.env.GSD_VERSION || "0.0.0";
609
+
610
+ const logoText = GSD_LOGO_LINES.map((line) => theme.fg("accent", line)).join("\n");
611
+ const titleLine = ` ${theme.bold("Get Shit Done")} ${theme.fg("dim", `v${version}`)}`;
612
+
613
+ const headerContent = `${logoText}\n${titleLine}`;
614
+ ctx.ui.setHeader((_ui, _theme) => new Text(headerContent, 1, 0));
615
+ } catch {
616
+ // RPC mode — no TUI, skip header rendering
617
+ }
618
+
619
+ // Load tool API keys from auth.json into environment
620
+ loadToolApiKeys();
621
+
622
+ // Always-on health widget — ambient system health signal below the editor
623
+ try {
624
+ const { initHealthWidget } = await import("./health-widget.js");
625
+ initHealthWidget(ctx);
626
+ } catch { /* non-fatal — widget is best-effort */ }
627
+
628
+ // Notify remote questions status if configured
629
+ try {
630
+ const [{ getRemoteConfigStatus }, { getLatestPromptSummary }] = await Promise.all([
631
+ import("../remote-questions/config.js"),
632
+ import("../remote-questions/status.js"),
633
+ ]);
634
+ const status = getRemoteConfigStatus();
635
+ const latest = getLatestPromptSummary();
636
+ if (!status.includes("not configured")) {
637
+ const suffix = latest ? `\nLast remote prompt: ${latest.id} (${latest.status})` : "";
638
+ ctx.ui.notify(`${status}${suffix}`, status.includes("disabled") ? "warning" : "info");
639
+ }
640
+ } catch {
641
+ // Remote questions module not available — ignore
642
+ }
643
+ });
644
+
645
+ // ── Ctrl+Alt+G shortcut — GSD dashboard overlay ────────────────────────
646
+ pi.registerShortcut(Key.ctrlAlt("g"), {
647
+ description: shortcutDesc("Open GSD dashboard", "/gsd status"),
648
+ handler: async (ctx) => {
649
+ // Only show if .gsd/ exists
650
+ if (!existsSync(gsdRoot(process.cwd()))) {
651
+ ctx.ui.notify("No .gsd/ directory found. Run /gsd to start.", "info");
652
+ return;
653
+ }
654
+
655
+ const result = await ctx.ui.custom<void>(
656
+ (tui, theme, _kb, done) => {
657
+ return new GSDDashboardOverlay(tui, theme, () => done());
658
+ },
659
+ {
660
+ overlay: true,
661
+ overlayOptions: {
662
+ width: "90%",
663
+ minWidth: 80,
664
+ maxHeight: "92%",
665
+ anchor: "center",
666
+ },
667
+ },
668
+ );
669
+
670
+ // Fallback for RPC mode where ctx.ui.custom() returns undefined.
671
+ if (result === undefined) {
672
+ const { fireStatusViaCommand } = await import("./commands.js");
673
+ await fireStatusViaCommand(ctx);
674
+ }
675
+ },
676
+ });
677
+
678
+ // ── before_agent_start: inject GSD contract into true system prompt ─────
679
+ pi.on("before_agent_start", async (event, ctx: ExtensionContext) => {
680
+ if (!existsSync(gsdRoot(process.cwd()))) return;
681
+
682
+ const stopContextTimer = debugTime("context-inject");
683
+ const systemContent = loadPrompt("system");
684
+ const loadedPreferences = loadEffectiveGSDPreferences();
685
+ let preferenceBlock = "";
686
+ if (loadedPreferences) {
687
+ const cwd = process.cwd();
688
+ const report = resolveAllSkillReferences(loadedPreferences.preferences, cwd);
689
+ preferenceBlock = `\n\n${renderPreferencesForSystemPrompt(loadedPreferences.preferences, report.resolutions)}`;
690
+
691
+ // Emit warnings for unresolved skill references
692
+ if (report.warnings.length > 0) {
693
+ ctx.ui.notify(
694
+ `GSD skill preferences: ${report.warnings.length} unresolved skill${report.warnings.length === 1 ? "" : "s"}: ${report.warnings.join(", ")}`,
695
+ "warning",
696
+ );
697
+ }
698
+ }
699
+
700
+ // Load project knowledge if available
701
+ let knowledgeBlock = "";
702
+ const knowledgePath = resolveGsdRootFile(process.cwd(), "KNOWLEDGE");
703
+ if (existsSync(knowledgePath)) {
704
+ try {
705
+ const content = readFileSync(knowledgePath, "utf-8").trim();
706
+ if (content) {
707
+ knowledgeBlock = `\n\n[PROJECT KNOWLEDGE — Rules, patterns, and lessons learned]\n\n${content}`;
708
+ }
709
+ } catch {
710
+ // File read error — skip knowledge injection
711
+ }
712
+ }
713
+
714
+ // Inject auto-learned project memories
715
+ let memoryBlock = "";
716
+ try {
717
+ const { getActiveMemoriesRanked, formatMemoriesForPrompt } = await import("./memory-store.js");
718
+ const memories = getActiveMemoriesRanked(30);
719
+ if (memories.length > 0) {
720
+ const formatted = formatMemoriesForPrompt(memories, 2000);
721
+ if (formatted) {
722
+ memoryBlock = `\n\n${formatted}`;
723
+ }
724
+ }
725
+ } catch { /* non-fatal */ }
726
+
727
+ // Detect skills installed during this auto-mode session
728
+ let newSkillsBlock = "";
729
+ if (hasSkillSnapshot()) {
730
+ const newSkills = detectNewSkills();
731
+ if (newSkills.length > 0) {
732
+ newSkillsBlock = formatSkillsXml(newSkills);
733
+ }
734
+ }
735
+
736
+ // Load agent instructions (global + project)
737
+ let agentInstructionsBlock = "";
738
+ const agentInstructions = loadAgentInstructions();
739
+ if (agentInstructions) {
740
+ agentInstructionsBlock = `\n\n## Agent Instructions\n\nThe following instructions were provided by the user and must be followed in every session:\n\n${agentInstructions}`;
741
+ }
742
+
743
+ const injection = await buildGuidedExecuteContextInjection(event.prompt, process.cwd());
744
+
745
+ // Worktree context — override the static CWD in the system prompt
746
+ let worktreeBlock = "";
747
+ const worktreeName = getActiveWorktreeName();
748
+ const worktreeMainCwd = getWorktreeOriginalCwd();
749
+ const autoWorktree = getActiveAutoWorktreeContext();
750
+ if (worktreeName && worktreeMainCwd) {
751
+ worktreeBlock = [
752
+ "",
753
+ "",
754
+ "[WORKTREE CONTEXT — OVERRIDES CURRENT WORKING DIRECTORY ABOVE]",
755
+ `IMPORTANT: Ignore the "Current working directory" shown earlier in this prompt.`,
756
+ `The actual current working directory is: ${toPosixPath(process.cwd())}`,
757
+ "",
758
+ `You are working inside a GSD worktree.`,
759
+ `- Worktree name: ${worktreeName}`,
760
+ `- Worktree path (this is the real cwd): ${toPosixPath(process.cwd())}`,
761
+ `- Main project: ${toPosixPath(worktreeMainCwd)}`,
762
+ `- Branch: worktree/${worktreeName}`,
763
+ "",
764
+ "All file operations, bash commands, and GSD state resolve against the worktree path above.",
765
+ "Use /worktree merge to merge changes back. Use /worktree return to switch back to the main tree.",
766
+ ].join("\n");
767
+ } else if (autoWorktree) {
768
+ worktreeBlock = [
769
+ "",
770
+ "",
771
+ "[WORKTREE CONTEXT — OVERRIDES CURRENT WORKING DIRECTORY ABOVE]",
772
+ `IMPORTANT: Ignore the "Current working directory" shown earlier in this prompt.`,
773
+ `The actual current working directory is: ${toPosixPath(process.cwd())}`,
774
+ "",
775
+ "You are working inside a GSD auto-worktree.",
776
+ `- Milestone worktree: ${autoWorktree.worktreeName}`,
777
+ `- Worktree path (this is the real cwd): ${toPosixPath(process.cwd())}`,
778
+ `- Main project: ${toPosixPath(autoWorktree.originalBase)}`,
779
+ `- Branch: ${autoWorktree.branch}`,
780
+ "",
781
+ "All file operations, bash commands, and GSD state resolve against the worktree path above.",
782
+ "Write every .gsd artifact in the worktree path above, never in the main project tree.",
783
+ ].join("\n");
784
+ }
785
+
786
+ const fullSystem = `${event.systemPrompt}\n\n[SYSTEM CONTEXT — GSD]\n\n${systemContent}${preferenceBlock}${agentInstructionsBlock}${knowledgeBlock}${memoryBlock}${newSkillsBlock}${worktreeBlock}`;
787
+ stopContextTimer({
788
+ systemPromptSize: fullSystem.length,
789
+ injectionSize: injection?.length ?? 0,
790
+ hasPreferences: preferenceBlock.length > 0,
791
+ hasNewSkills: newSkillsBlock.length > 0,
792
+ });
793
+
794
+ return {
795
+ systemPrompt: fullSystem,
796
+ ...(injection
797
+ ? {
798
+ message: {
799
+ customType: "gsd-guided-context",
800
+ content: injection,
801
+ display: false,
802
+ },
803
+ }
804
+ : {}),
805
+ };
806
+ });
807
+
808
+ // ── agent_end: auto-mode advancement or auto-start after discuss ───────────
809
+ pi.on("agent_end", async (event, ctx: ExtensionContext) => {
810
+ // Clean up quick-task branch if one just completed (#1269)
811
+ try {
812
+ const { cleanupQuickBranch } = await import("./quick.js");
813
+ cleanupQuickBranch();
814
+ } catch { /* non-fatal */ }
815
+
816
+ // If discuss phase just finished, start auto-mode
817
+ if (checkAutoStartAfterDiscuss()) {
818
+ depthVerifiedMilestones.clear();
819
+ activeQueuePhase = false;
820
+ return;
821
+ }
822
+
823
+ // If auto-mode is already running, advance to next unit
824
+ if (!isAutoActive()) return;
825
+
826
+ // If the agent was aborted (user pressed Escape) or hit a provider
827
+ // error (fetch failure, rate limit, etc.), pause auto-mode instead of
828
+ // advancing. This preserves the conversation so the user can inspect
829
+ // what happened, interact with the agent, or resume.
830
+ const lastMsg = event.messages[event.messages.length - 1];
831
+ if (lastMsg && "stopReason" in lastMsg && lastMsg.stopReason === "aborted") {
832
+ await pauseAuto(ctx, pi);
833
+ return;
834
+ }
835
+ if (lastMsg && "stopReason" in lastMsg && lastMsg.stopReason === "error") {
836
+ const errorDetail =
837
+ "errorMessage" in lastMsg && lastMsg.errorMessage
838
+ ? `: ${lastMsg.errorMessage}`
839
+ : "";
840
+
841
+ const errorMsg = ("errorMessage" in lastMsg && lastMsg.errorMessage) ? String(lastMsg.errorMessage) : "";
842
+
843
+ // ── Transient network error retry ──────────────────────────────────
844
+ // Before falling back to a different model, retry the current model
845
+ // for transient network errors (connection reset, timeout, DNS, etc.).
846
+ // This prevents providers with occasional network flakiness from being
847
+ // immediately abandoned in favor of fallback models (#941).
848
+ if (isTransientNetworkError(errorMsg)) {
849
+ const currentModelId = ctx.model?.id ?? "unknown";
850
+ const retryKey = `network-retry:${currentModelId}`;
851
+ const maxRetries = 2;
852
+ const currentRetries = networkRetryCounters.get(retryKey) ?? 0;
853
+
854
+ if (currentRetries < maxRetries) {
855
+ networkRetryCounters.set(retryKey, currentRetries + 1);
856
+ const attempt = currentRetries + 1;
857
+ const delayMs = attempt * 3000; // 3s, 6s backoff
858
+ ctx.ui.notify(
859
+ `Network error on ${currentModelId}${errorDetail}. Retry ${attempt}/${maxRetries} in ${delayMs / 1000}s...`,
860
+ "warning",
861
+ );
862
+ setTimeout(() => {
863
+ pi.sendMessage(
864
+ { customType: "gsd-auto-timeout-recovery", content: "Continue execution — retrying after transient network error.", display: false },
865
+ { triggerTurn: true },
866
+ );
867
+ }, delayMs);
868
+ return;
869
+ }
870
+ // Retries exhausted — clear counter and fall through to fallback logic
871
+ networkRetryCounters.delete(retryKey);
872
+ ctx.ui.notify(
873
+ `Network retries exhausted for ${currentModelId}. Attempting model fallback.`,
874
+ "warning",
875
+ );
876
+ }
877
+
878
+ const dash = getAutoDashboardData();
879
+ if (dash.currentUnit) {
880
+ const modelConfig = resolveModelWithFallbacksForUnit(dash.currentUnit.type);
881
+ if (modelConfig && modelConfig.fallbacks.length > 0) {
882
+ const availableModels = ctx.modelRegistry.getAvailable();
883
+ const currentModelId = ctx.model?.id;
884
+
885
+ const nextModelId = getNextFallbackModel(currentModelId, modelConfig);
886
+
887
+ if (nextModelId) {
888
+ // Clear any network retry counters when switching models
889
+ networkRetryCounters.clear();
890
+
891
+ let modelToSet;
892
+ const slashIdx = nextModelId.indexOf("/");
893
+ if (slashIdx !== -1) {
894
+ const provider = nextModelId.substring(0, slashIdx);
895
+ const id = nextModelId.substring(slashIdx + 1);
896
+ modelToSet = availableModels.find(
897
+ m => m.provider.toLowerCase() === provider.toLowerCase()
898
+ && m.id.toLowerCase() === id.toLowerCase()
899
+ );
900
+ } else {
901
+ const currentProvider = ctx.model?.provider;
902
+ const exactProviderMatch = availableModels.find(
903
+ m => m.id === nextModelId && m.provider === currentProvider
904
+ );
905
+ modelToSet = exactProviderMatch ?? availableModels.find(m => m.id === nextModelId);
906
+ }
907
+
908
+ if (modelToSet) {
909
+ const ok = await pi.setModel(modelToSet, { persist: false });
910
+ if (ok) {
911
+ ctx.ui.notify(`Model error${errorDetail}. Switched to fallback: ${nextModelId} and resuming.`, "warning");
912
+ // Trigger a generic "Continue execution" to resume the task since the previous attempt failed
913
+ pi.sendMessage(
914
+ { customType: "gsd-auto-timeout-recovery", content: "Continue execution.", display: false },
915
+ { triggerTurn: true }
916
+ );
917
+ return;
918
+ }
919
+ }
920
+ }
921
+ }
922
+ }
923
+
924
+ // ── Session model recovery (#1065) ──────────────────────────────────
925
+ // Before pausing, attempt to restore the model captured at auto-mode
926
+ // start. This prevents cross-session model leakage: when fallback
927
+ // chains are exhausted (or absent), the session retries with the model
928
+ // the user originally chose instead of reading (possibly stale) global
929
+ // preferences that another concurrent session may have modified.
930
+ const sessionModel = getAutoModeStartModel();
931
+ if (sessionModel) {
932
+ const currentModelId = ctx.model?.id;
933
+ const currentProvider = ctx.model?.provider;
934
+ // Only attempt recovery if the current model diverged from the session model
935
+ if (currentModelId !== sessionModel.id || currentProvider !== sessionModel.provider) {
936
+ const availableModels = ctx.modelRegistry.getAvailable();
937
+ const startModel = availableModels.find(
938
+ m => m.provider === sessionModel.provider && m.id === sessionModel.id,
939
+ );
940
+ if (startModel) {
941
+ const ok = await pi.setModel(startModel, { persist: false });
942
+ if (ok) {
943
+ networkRetryCounters.clear();
944
+ ctx.ui.notify(
945
+ `Model error${errorDetail}. Restored session model: ${sessionModel.provider}/${sessionModel.id} and resuming.`,
946
+ "warning",
947
+ );
948
+ pi.sendMessage(
949
+ { customType: "gsd-auto-timeout-recovery", content: "Continue execution.", display: false },
950
+ { triggerTurn: true },
951
+ );
952
+ return;
953
+ }
954
+ }
955
+ }
956
+ }
957
+
958
+ // Classify the error: transient (auto-resume) vs permanent (manual resume)
959
+ const classification = classifyProviderError(errorMsg);
960
+
961
+ // Extract explicit retry-after from the message or response metadata
962
+ const explicitRetryAfterMs = ("retryAfterMs" in lastMsg && typeof lastMsg.retryAfterMs === "number")
963
+ ? lastMsg.retryAfterMs
964
+ : undefined;
965
+ let retryAfterMs = explicitRetryAfterMs ?? classification.suggestedDelayMs;
966
+
967
+ // ── Escalating backoff for repeated transient errors ──────────────
968
+ // Each consecutive transient auto-resume doubles the delay. After
969
+ // MAX_TRANSIENT_AUTO_RESUMES consecutive failures, treat as permanent
970
+ // to avoid infinite rapid-fire retries (#1166).
971
+ let effectiveTransient = classification.isTransient;
972
+ if (classification.isTransient) {
973
+ consecutiveTransientErrors++;
974
+ if (consecutiveTransientErrors > MAX_TRANSIENT_AUTO_RESUMES) {
975
+ effectiveTransient = false;
976
+ ctx.ui.notify(
977
+ `${consecutiveTransientErrors} consecutive transient errors. Pausing indefinitely — resume manually with /gsd auto.`,
978
+ "error",
979
+ );
980
+ consecutiveTransientErrors = 0;
981
+ } else {
982
+ // Escalate: base delay × 2^(consecutive-1) → 30s, 60s, 120s, 240s, 480s
983
+ retryAfterMs = retryAfterMs * 2 ** (consecutiveTransientErrors - 1);
984
+ }
985
+ }
986
+
987
+ await pauseAutoForProviderError(ctx.ui, errorDetail, () => pauseAuto(ctx, pi), {
988
+ isRateLimit: classification.isRateLimit,
989
+ isTransient: effectiveTransient,
990
+ retryAfterMs,
991
+ resume: () => {
992
+ pi.sendMessage(
993
+ { customType: "gsd-auto-timeout-recovery", content: "Continue execution \u2014 provider error recovery delay elapsed.", display: false },
994
+ { triggerTurn: true },
995
+ );
996
+ },
997
+ });
998
+ return;
999
+ }
1000
+
1001
+ try {
1002
+ networkRetryCounters.clear(); // Clear network retry state on successful unit completion
1003
+ consecutiveTransientErrors = 0; // Reset escalating backoff on success
1004
+ await handleAgentEnd(ctx, pi);
1005
+ } catch (err) {
1006
+ // Safety net: if handleAgentEnd throws despite its internal try-catch,
1007
+ // ensure auto-mode stops gracefully instead of silently stalling (#381).
1008
+ const message = getErrorMessage(err);
1009
+ ctx.ui.notify(
1010
+ `Auto-mode error in agent_end handler: ${message}. Stopping auto-mode.`,
1011
+ "error",
1012
+ );
1013
+ try {
1014
+ await pauseAuto(ctx, pi);
1015
+ } catch {
1016
+ // Last resort — at least log
1017
+ }
1018
+ }
1019
+ });
1020
+
1021
+ // ── session_before_compact ────────────────────────────────────────────────
1022
+ pi.on("session_before_compact", async (_event, _ctx: ExtensionContext) => {
1023
+ // Block compaction during auto-mode — each unit is a fresh session
1024
+ // Also block during paused state — context is valuable for the user
1025
+ if (isAutoActive() || isAutoPaused()) {
1026
+ return { cancel: true };
1027
+ }
1028
+
1029
+ const basePath = process.cwd();
1030
+ const state = await deriveState(basePath);
1031
+
1032
+ // Only save continue.md if we're actively executing a task
1033
+ if (!state.activeMilestone || !state.activeSlice || !state.activeTask) return;
1034
+ if (state.phase !== "executing") return;
1035
+
1036
+ const sDir = resolveSlicePath(basePath, state.activeMilestone.id, state.activeSlice.id);
1037
+ if (!sDir) return;
1038
+
1039
+ // Check for existing continue file (new naming or legacy)
1040
+ const existingFile = resolveSliceFile(basePath, state.activeMilestone.id, state.activeSlice.id, "CONTINUE");
1041
+ if (existingFile && await loadFile(existingFile)) return;
1042
+ const legacyContinue = join(sDir, "continue.md");
1043
+ if (await loadFile(legacyContinue)) return;
1044
+
1045
+ const continuePath = join(sDir, buildSliceFileName(state.activeSlice.id, "CONTINUE"));
1046
+
1047
+ const continueData = {
1048
+ frontmatter: {
1049
+ milestone: state.activeMilestone.id,
1050
+ slice: state.activeSlice.id,
1051
+ task: state.activeTask.id,
1052
+ step: 0,
1053
+ totalSteps: 0,
1054
+ status: "compacted" as const,
1055
+ savedAt: new Date().toISOString(),
1056
+ },
1057
+ completedWork: `Task ${state.activeTask.id} (${state.activeTask.title}) was in progress when compaction occurred.`,
1058
+ remainingWork: "Check the task plan for remaining steps.",
1059
+ decisions: "Check task summary files for prior decisions.",
1060
+ context: "Session was auto-compacted by Pi. Resume with /gsd.",
1061
+ nextAction: `Resume task ${state.activeTask.id}: ${state.activeTask.title}.`,
1062
+ };
1063
+
1064
+ await saveFile(continuePath, formatContinue(continueData));
1065
+ });
1066
+
1067
+ // ── session_shutdown: save activity log on Ctrl+C / SIGTERM ─────────────
1068
+ pi.on("session_shutdown", async (_event, ctx: ExtensionContext) => {
1069
+ if (isParallelActive()) {
1070
+ try {
1071
+ await shutdownParallel(process.cwd());
1072
+ } catch { /* best-effort */ }
1073
+ }
1074
+
1075
+ // Auto-commit dirty work in CLI-spawned worktrees so nothing is lost.
1076
+ // The CLI sets GSD_CLI_WORKTREE when launched with -w.
1077
+ const cliWorktree = process.env.GSD_CLI_WORKTREE;
1078
+ if (cliWorktree) {
1079
+ try {
1080
+ const { autoCommitCurrentBranch } = await import("./worktree.js");
1081
+ const msg = autoCommitCurrentBranch(process.cwd(), "session-end", cliWorktree);
1082
+ if (msg) {
1083
+ ctx.ui.notify(`Auto-committed worktree ${cliWorktree} before exit.`, "info");
1084
+ }
1085
+ } catch { /* best-effort */ }
1086
+ }
1087
+
1088
+ if (!isAutoActive() && !isAutoPaused()) return;
1089
+
1090
+ // Save the current session — the lock file stays on disk
1091
+ // so the next /gsd auto knows it was interrupted
1092
+ const dash = getAutoDashboardData();
1093
+ if (dash.currentUnit) {
1094
+ saveActivityLog(ctx, dash.basePath, dash.currentUnit.type, dash.currentUnit.id);
1095
+ }
1096
+ });
1097
+
1098
+ // ── tool_call: block CONTEXT.md writes without depth verification ──
1099
+ // Active during both discussion flows (pendingAutoStart set) and
1100
+ // queue flows (activeQueuePhase set). For multi-milestone queue flows,
1101
+ // each milestone must pass its own depth verification before its
1102
+ // CONTEXT.md can be written.
1103
+ pi.on("tool_call", async (event) => {
1104
+ if (!isToolCallEventType("write", event)) return;
1105
+ const result = shouldBlockContextWrite(
1106
+ event.toolName,
1107
+ event.input.path,
1108
+ getDiscussionMilestoneId(),
1109
+ isDepthVerified(),
1110
+ activeQueuePhase,
1111
+ );
1112
+ if (result.block) return result;
1113
+ });
1114
+
1115
+ // ── tool_result: persist discussion exchanges & detect depth gate ──────
1116
+ // Handles both discussion flows and queue flows. For queue flows,
1117
+ // depth verification question IDs may include milestone IDs
1118
+ // (e.g., "depth_verification_M001") for per-milestone gating.
1119
+ pi.on("tool_result", async (event) => {
1120
+ if (event.toolName !== "ask_user_questions") return;
1121
+
1122
+ const milestoneId = getDiscussionMilestoneId();
1123
+ // Queue flows don't set pendingAutoStart, so milestoneId may be null.
1124
+ // Depth gate detection still applies — it sets per-milestone flags.
1125
+ const inQueue = activeQueuePhase;
1126
+
1127
+ const details = event.details as any;
1128
+ if (details?.cancelled || !details?.response) return;
1129
+
1130
+ // ── Depth gate detection ──────────────────────────────────────────
1131
+ // Supports two patterns:
1132
+ // 1. "depth_verification" — wildcard, marks all milestones verified
1133
+ // 2. "depth_verification_M001" — per-milestone verification
1134
+ const questions: any[] = (event.input as any)?.questions ?? [];
1135
+ for (const q of questions) {
1136
+ if (typeof q.id === "string" && q.id.includes("depth_verification")) {
1137
+ // Extract milestone ID from question ID if present
1138
+ const midMatch = q.id.match(/depth_verification[_-](M\d+(?:-[a-z0-9]{6})?)/i);
1139
+ if (midMatch) {
1140
+ depthVerifiedMilestones.add(midMatch[1]);
1141
+ } else {
1142
+ // Wildcard — all milestones verified (backward compat for single-milestone)
1143
+ depthVerifiedMilestones.add("*");
1144
+ }
1145
+ break;
1146
+ }
1147
+ }
1148
+
1149
+ // Discussion persistence only applies when in a discussion flow with a known milestone
1150
+ if (!milestoneId) return;
1151
+
1152
+ // ── Persist exchange to DISCUSSION.md ──────────────────────────────
1153
+ const basePath = process.cwd();
1154
+ const milestoneDir = resolveMilestonePath(basePath, milestoneId);
1155
+ if (!milestoneDir) return;
1156
+
1157
+ const fileName = buildMilestoneFileName(milestoneId, "DISCUSSION");
1158
+ const discussionPath = join(milestoneDir, fileName);
1159
+ const timestamp = new Date().toISOString();
1160
+
1161
+ // Format exchange as markdown
1162
+ const lines: string[] = [`## Exchange — ${timestamp}`, ""];
1163
+
1164
+ for (const q of questions) {
1165
+ lines.push(`### ${q.header ?? "Question"}`);
1166
+ lines.push("");
1167
+ lines.push(q.question ?? "");
1168
+ if (Array.isArray(q.options)) {
1169
+ lines.push("");
1170
+ for (const opt of q.options) {
1171
+ lines.push(`- **${opt.label}** — ${opt.description ?? ""}`);
1172
+ }
1173
+ }
1174
+
1175
+ // Append user response for this question
1176
+ const answer = details.response?.answers?.[q.id];
1177
+ if (answer) {
1178
+ lines.push("");
1179
+ const selected = Array.isArray(answer.selected) ? answer.selected.join(", ") : answer.selected;
1180
+ lines.push(`**Selected:** ${selected}`);
1181
+ if (answer.notes) {
1182
+ lines.push(`**Notes:** ${answer.notes}`);
1183
+ }
1184
+ }
1185
+ lines.push("");
1186
+ }
1187
+
1188
+ lines.push("---", "");
1189
+
1190
+ const newBlock = lines.join("\n");
1191
+ const existing = await loadFile(discussionPath) ?? `# ${milestoneId} Discussion Log\n\n`;
1192
+ await saveFile(discussionPath, existing + newBlock);
1193
+ });
1194
+
1195
+ // ── tool_execution_start/end: track in-flight tools for idle detection ──
1196
+ pi.on("tool_execution_start", async (event) => {
1197
+ if (!isAutoActive()) return;
1198
+ markToolStart(event.toolCallId);
1199
+ });
1200
+
1201
+ pi.on("tool_execution_end", async (event) => {
1202
+ markToolEnd(event.toolCallId);
1203
+ });
1204
+ }
1205
+
1206
+ async function buildGuidedExecuteContextInjection(prompt: string, basePath: string): Promise<string | null> {
1207
+ const executeMatch = prompt.match(/Execute the next task:\s+(T\d+)\s+\("([^"]+)"\)\s+in slice\s+(S\d+)\s+of milestone\s+(M\d+(?:-[a-z0-9]{6})?)/i);
1208
+ if (executeMatch) {
1209
+ const [, taskId, taskTitle, sliceId, milestoneId] = executeMatch;
1210
+ return buildTaskExecutionContextInjection(basePath, milestoneId, sliceId, taskId, taskTitle);
1211
+ }
1212
+
1213
+ const resumeMatch = prompt.match(/Resume interrupted work\.[\s\S]*?slice\s+(S\d+)\s+of milestone\s+(M\d+(?:-[a-z0-9]{6})?)/i);
1214
+ if (resumeMatch) {
1215
+ const [, sliceId, milestoneId] = resumeMatch;
1216
+ const state = await deriveState(basePath);
1217
+ if (
1218
+ state.activeMilestone?.id === milestoneId &&
1219
+ state.activeSlice?.id === sliceId &&
1220
+ state.activeTask
1221
+ ) {
1222
+ return buildTaskExecutionContextInjection(
1223
+ basePath,
1224
+ milestoneId,
1225
+ sliceId,
1226
+ state.activeTask.id,
1227
+ state.activeTask.title,
1228
+ );
1229
+ }
1230
+ }
1231
+
1232
+ return null;
1233
+ }
1234
+
1235
+ async function buildTaskExecutionContextInjection(
1236
+ basePath: string,
1237
+ milestoneId: string,
1238
+ sliceId: string,
1239
+ taskId: string,
1240
+ taskTitle: string,
1241
+ ): Promise<string> {
1242
+ const taskPlanPath = resolveTaskFile(basePath, milestoneId, sliceId, taskId, "PLAN");
1243
+ const taskPlanRelPath = relTaskFile(basePath, milestoneId, sliceId, taskId, "PLAN");
1244
+ const taskPlanContent = taskPlanPath ? await loadFile(taskPlanPath) : null;
1245
+ const taskPlanInline = taskPlanContent
1246
+ ? [
1247
+ "## Inlined Task Plan (authoritative local execution contract)",
1248
+ `Source: \`${taskPlanRelPath}\``,
1249
+ "",
1250
+ taskPlanContent.trim(),
1251
+ ].join("\n")
1252
+ : [
1253
+ "## Inlined Task Plan (authoritative local execution contract)",
1254
+ `Task plan not found at dispatch time. Read \`${taskPlanRelPath}\` before executing.`,
1255
+ ].join("\n");
1256
+
1257
+ const slicePlanPath = resolveSliceFile(basePath, milestoneId, sliceId, "PLAN");
1258
+ const slicePlanRelPath = relSliceFile(basePath, milestoneId, sliceId, "PLAN");
1259
+ const slicePlanContent = slicePlanPath ? await loadFile(slicePlanPath) : null;
1260
+ const slicePlanExcerpt = extractSliceExecutionExcerpt(slicePlanContent, slicePlanRelPath);
1261
+
1262
+ const priorTaskLines = await buildCarryForwardLines(basePath, milestoneId, sliceId, taskId);
1263
+ const resumeSection = await buildResumeSection(basePath, milestoneId, sliceId);
1264
+
1265
+ const activeOverrides = await loadActiveOverrides(basePath);
1266
+ const overridesSection = formatOverridesSection(activeOverrides);
1267
+
1268
+ return [
1269
+ "[GSD Guided Execute Context]",
1270
+ "Use this injected context as startup context for guided task execution. Treat the inlined task plan as the authoritative local execution contract. Use source artifacts to verify details and run checks.",
1271
+ overridesSection, "",
1272
+ "",
1273
+ resumeSection,
1274
+ "",
1275
+ "## Carry-Forward Context",
1276
+ ...priorTaskLines,
1277
+ "",
1278
+ taskPlanInline,
1279
+ "",
1280
+ slicePlanExcerpt,
1281
+ "",
1282
+ "## Backing Source Artifacts",
1283
+ `- Slice plan: \`${slicePlanRelPath}\``,
1284
+ `- Task plan source: \`${taskPlanRelPath}\``,
1285
+ ].join("\n");
1286
+ }
1287
+
1288
+ async function buildCarryForwardLines(
1289
+ basePath: string,
1290
+ milestoneId: string,
1291
+ sliceId: string,
1292
+ taskId: string,
1293
+ ): Promise<string[]> {
1294
+ const tDir = resolveTasksDir(basePath, milestoneId, sliceId);
1295
+ if (!tDir) return ["- No prior task summaries in this slice."];
1296
+
1297
+ const currentNum = parseInt(taskId.replace(/^T/, ""), 10);
1298
+ const sRel = relSlicePath(basePath, milestoneId, sliceId);
1299
+ const summaryFiles = resolveTaskFiles(tDir, "SUMMARY")
1300
+ .filter((file) => parseInt(file.replace(/^T/, ""), 10) < currentNum)
1301
+ .sort();
1302
+
1303
+ if (summaryFiles.length === 0) return ["- No prior task summaries in this slice."];
1304
+
1305
+ const lines = await Promise.all(summaryFiles.map(async (file) => {
1306
+ const absPath = join(tDir, file);
1307
+ const content = await loadFile(absPath);
1308
+ const relPath = `${sRel}/tasks/${file}`;
1309
+ if (!content) return `- \`${relPath}\``;
1310
+
1311
+ const summary = parseSummary(content);
1312
+ const provided = summary.frontmatter.provides.slice(0, 2).join("; ");
1313
+ const decisions = summary.frontmatter.key_decisions.slice(0, 2).join("; ");
1314
+ const patterns = summary.frontmatter.patterns_established.slice(0, 2).join("; ");
1315
+ const diagnostics = extractMarkdownSection(content, "Diagnostics");
1316
+
1317
+ const parts = [summary.title || relPath];
1318
+ if (summary.oneLiner) parts.push(summary.oneLiner);
1319
+ if (provided) parts.push(`provides: ${provided}`);
1320
+ if (decisions) parts.push(`decisions: ${decisions}`);
1321
+ if (patterns) parts.push(`patterns: ${patterns}`);
1322
+ if (diagnostics) parts.push(`diagnostics: ${oneLine(diagnostics)}`);
1323
+
1324
+ return `- \`${relPath}\` — ${parts.join(" | ")}`;
1325
+ }));
1326
+
1327
+ return lines;
1328
+ }
1329
+
1330
+ async function buildResumeSection(basePath: string, milestoneId: string, sliceId: string): Promise<string> {
1331
+ const continueFile = resolveSliceFile(basePath, milestoneId, sliceId, "CONTINUE");
1332
+ const legacyDir = resolveSlicePath(basePath, milestoneId, sliceId);
1333
+ const legacyPath = legacyDir ? join(legacyDir, "continue.md") : null;
1334
+ const continueContent = continueFile ? await loadFile(continueFile) : null;
1335
+ const legacyContent = !continueContent && legacyPath ? await loadFile(legacyPath) : null;
1336
+ const resolvedContent = continueContent ?? legacyContent;
1337
+ const resolvedRelPath = continueContent
1338
+ ? relSliceFile(basePath, milestoneId, sliceId, "CONTINUE")
1339
+ : (legacyPath ? `${relSlicePath(basePath, milestoneId, sliceId)}/continue.md` : null);
1340
+
1341
+ if (!resolvedContent || !resolvedRelPath) {
1342
+ return ["## Resume State", "- No continue file present. Start from the top of the task plan."].join("\n");
1343
+ }
1344
+
1345
+ const cont = parseContinue(resolvedContent);
1346
+ const lines = [
1347
+ "## Resume State",
1348
+ `Source: \`${resolvedRelPath}\``,
1349
+ `- Status: ${cont.frontmatter.status || "in_progress"}`,
1350
+ ];
1351
+
1352
+ if (cont.frontmatter.step && cont.frontmatter.totalSteps) {
1353
+ lines.push(`- Progress: step ${cont.frontmatter.step} of ${cont.frontmatter.totalSteps}`);
1354
+ }
1355
+ if (cont.completedWork) lines.push(`- Completed: ${oneLine(cont.completedWork)}`);
1356
+ if (cont.remainingWork) lines.push(`- Remaining: ${oneLine(cont.remainingWork)}`);
1357
+ if (cont.decisions) lines.push(`- Decisions: ${oneLine(cont.decisions)}`);
1358
+ if (cont.nextAction) lines.push(`- Next action: ${oneLine(cont.nextAction)}`);
1359
+
1360
+ return lines.join("\n");
1361
+ }
1362
+
1363
+ function extractSliceExecutionExcerpt(content: string | null, relPath: string): string {
1364
+ if (!content) {
1365
+ return [
1366
+ "## Slice Plan Excerpt",
1367
+ `Slice plan not found at dispatch time. Read \`${relPath}\` before running slice-level verification.`,
1368
+ ].join("\n");
1369
+ }
1370
+
1371
+ const lines = content.split("\n");
1372
+ const goalLine = lines.find((line) => line.startsWith("**Goal:**"))?.trim();
1373
+ const demoLine = lines.find((line) => line.startsWith("**Demo:**"))?.trim();
1374
+ const verification = extractMarkdownSection(content, "Verification");
1375
+ const observability = extractMarkdownSection(content, "Observability / Diagnostics");
1376
+
1377
+ const parts = ["## Slice Plan Excerpt", `Source: \`${relPath}\``];
1378
+ if (goalLine) parts.push(goalLine);
1379
+ if (demoLine) parts.push(demoLine);
1380
+ if (verification) parts.push("", "### Slice Verification", verification.trim());
1381
+ if (observability) parts.push("", "### Slice Observability / Diagnostics", observability.trim());
1382
+ return parts.join("\n");
1383
+ }
1384
+
1385
+ function extractMarkdownSection(content: string, heading: string): string | null {
1386
+ const match = new RegExp(`^## ${escapeRegExp(heading)}\\s*$`, "m").exec(content);
1387
+ if (!match) return null;
1388
+ const start = match.index + match[0].length;
1389
+ const rest = content.slice(start);
1390
+ const nextHeading = rest.match(/^##\s+/m);
1391
+ const end = nextHeading?.index ?? rest.length;
1392
+ return rest.slice(0, end).trim();
1393
+ }
1394
+
1395
+ function escapeRegExp(value: string): string {
1396
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1397
+ }
1398
+
1399
+ function oneLine(text: string): string {
1400
+ return text.replace(/\s+/g, " ").trim();
1401
+ }