gsd-pi 2.80.0-dev.2848d9009 → 2.80.0-dev.3065f7bfa

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 (377) hide show
  1. package/README.md +4 -2
  2. package/dist/resources/.managed-resources-content-hash +1 -1
  3. package/dist/resources/extensions/gsd/auto/loop.js +32 -1
  4. package/dist/resources/extensions/gsd/auto/phases.js +178 -108
  5. package/dist/resources/extensions/gsd/auto/resolve.js +17 -0
  6. package/dist/resources/extensions/gsd/auto/run-unit.js +20 -30
  7. package/dist/resources/extensions/gsd/auto/session.js +8 -0
  8. package/dist/resources/extensions/gsd/auto-direct-dispatch.js +5 -32
  9. package/dist/resources/extensions/gsd/auto-dispatch.js +16 -0
  10. package/dist/resources/extensions/gsd/auto-post-unit.js +17 -4
  11. package/dist/resources/extensions/gsd/auto-prompts.js +103 -16
  12. package/dist/resources/extensions/gsd/auto-recovery.js +43 -1
  13. package/dist/resources/extensions/gsd/auto-start.js +197 -6
  14. package/dist/resources/extensions/gsd/auto-supervisor.js +8 -1
  15. package/dist/resources/extensions/gsd/auto-timeout-recovery.js +2 -2
  16. package/dist/resources/extensions/gsd/auto-worktree.js +111 -1
  17. package/dist/resources/extensions/gsd/auto.js +86 -26
  18. package/dist/resources/extensions/gsd/bootstrap/agent-end-recovery.js +42 -2
  19. package/dist/resources/extensions/gsd/bootstrap/db-tools.js +49 -36
  20. package/dist/resources/extensions/gsd/bootstrap/dynamic-tools.js +15 -5
  21. package/dist/resources/extensions/gsd/bootstrap/exec-tools.js +33 -20
  22. package/dist/resources/extensions/gsd/bootstrap/journal-tools.js +7 -1
  23. package/dist/resources/extensions/gsd/bootstrap/memory-tools.js +9 -3
  24. package/dist/resources/extensions/gsd/bootstrap/query-tools.js +8 -2
  25. package/dist/resources/extensions/gsd/bootstrap/register-hooks.js +259 -28
  26. package/dist/resources/extensions/gsd/bootstrap/system-context.js +82 -23
  27. package/dist/resources/extensions/gsd/clean-root-preflight.js +24 -6
  28. package/dist/resources/extensions/gsd/commands-handlers.js +23 -9
  29. package/dist/resources/extensions/gsd/context-budget.js +37 -2
  30. package/dist/resources/extensions/gsd/crash-recovery.js +56 -10
  31. package/dist/resources/extensions/gsd/db/unit-dispatches.js +39 -0
  32. package/dist/resources/extensions/gsd/db-base-schema.js +4 -2
  33. package/dist/resources/extensions/gsd/db-migration-steps.js +6 -0
  34. package/dist/resources/extensions/gsd/ecosystem/gsd-extension-api.js +2 -0
  35. package/dist/resources/extensions/gsd/git-service.js +36 -4
  36. package/dist/resources/extensions/gsd/gsd-db.js +46 -13
  37. package/dist/resources/extensions/gsd/guided-flow.js +99 -38
  38. package/dist/resources/extensions/gsd/memory-store.js +69 -12
  39. package/dist/resources/extensions/gsd/migrate/command.js +40 -1
  40. package/dist/resources/extensions/gsd/migration-auto-check.js +87 -0
  41. package/dist/resources/extensions/gsd/native-git-bridge.js +32 -8
  42. package/dist/resources/extensions/gsd/orphan-stash-audit.js +101 -0
  43. package/dist/resources/extensions/gsd/parallel-orchestrator.js +13 -3
  44. package/dist/resources/extensions/gsd/planning-path-scope.js +26 -0
  45. package/dist/resources/extensions/gsd/pre-execution-checks.js +22 -0
  46. package/dist/resources/extensions/gsd/prompt-loader.js +28 -2
  47. package/dist/resources/extensions/gsd/prompts/complete-milestone.md +16 -13
  48. package/dist/resources/extensions/gsd/prompts/complete-slice.md +1 -1
  49. package/dist/resources/extensions/gsd/prompts/execute-task.md +4 -2
  50. package/dist/resources/extensions/gsd/prompts/parallel-research-slices.md +1 -1
  51. package/dist/resources/extensions/gsd/prompts/plan-slice.md +1 -1
  52. package/dist/resources/extensions/gsd/prompts/quick-task.md +1 -5
  53. package/dist/resources/extensions/gsd/prompts/replan-slice.md +2 -2
  54. package/dist/resources/extensions/gsd/prompts/validate-milestone.md +2 -2
  55. package/dist/resources/extensions/gsd/quick.js +34 -2
  56. package/dist/resources/extensions/gsd/tools/context-mode-tool-result.js +15 -0
  57. package/dist/resources/extensions/gsd/tools/exec-search-tool.js +5 -0
  58. package/dist/resources/extensions/gsd/tools/exec-tool.js +3 -15
  59. package/dist/resources/extensions/gsd/tools/memory-tools.js +1 -0
  60. package/dist/resources/extensions/gsd/tools/plan-slice.js +9 -0
  61. package/dist/resources/extensions/gsd/tools/plan-task.js +9 -0
  62. package/dist/resources/extensions/gsd/tools/resume-tool.js +5 -0
  63. package/dist/resources/extensions/gsd/tools/workflow-tool-executors.js +1 -1
  64. package/dist/resources/extensions/gsd/unit-context-composer.js +12 -3
  65. package/dist/resources/extensions/gsd/unit-runtime.js +22 -0
  66. package/dist/resources/extensions/gsd/workflow-protocol.js +131 -0
  67. package/dist/resources/extensions/gsd/worktree-resolver.js +68 -21
  68. package/dist/tsconfig.extensions.tsbuildinfo +1 -1
  69. package/dist/web/standalone/.next/BUILD_ID +1 -1
  70. package/dist/web/standalone/.next/app-path-routes-manifest.json +15 -15
  71. package/dist/web/standalone/.next/build-manifest.json +2 -2
  72. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  73. package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
  74. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  75. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  76. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  77. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  78. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  79. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  80. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  81. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  82. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  83. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  84. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  85. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  86. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  87. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  88. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  89. package/dist/web/standalone/.next/server/app/index.html +1 -1
  90. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  91. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  92. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  93. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  94. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  95. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  96. package/dist/web/standalone/.next/server/app-paths-manifest.json +15 -15
  97. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  98. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  99. package/dist/web/standalone/.next/server/pages/500.html +1 -1
  100. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  101. package/package.json +3 -3
  102. package/packages/mcp-server/dist/workflow-tools.d.ts.map +1 -1
  103. package/packages/mcp-server/dist/workflow-tools.js +22 -17
  104. package/packages/mcp-server/dist/workflow-tools.js.map +1 -1
  105. package/packages/mcp-server/src/workflow-tools.test.ts +75 -2
  106. package/packages/mcp-server/src/workflow-tools.ts +30 -16
  107. package/packages/mcp-server/tsconfig.tsbuildinfo +1 -1
  108. package/packages/native/tsconfig.tsbuildinfo +1 -1
  109. package/packages/pi-agent-core/dist/agent-loop.d.ts.map +1 -1
  110. package/packages/pi-agent-core/dist/agent-loop.js +4 -1
  111. package/packages/pi-agent-core/dist/agent-loop.js.map +1 -1
  112. package/packages/pi-agent-core/dist/agent.d.ts +5 -0
  113. package/packages/pi-agent-core/dist/agent.d.ts.map +1 -1
  114. package/packages/pi-agent-core/dist/agent.js +2 -0
  115. package/packages/pi-agent-core/dist/agent.js.map +1 -1
  116. package/packages/pi-agent-core/dist/index.d.ts +1 -0
  117. package/packages/pi-agent-core/dist/index.d.ts.map +1 -1
  118. package/packages/pi-agent-core/dist/index.js +2 -0
  119. package/packages/pi-agent-core/dist/index.js.map +1 -1
  120. package/packages/pi-agent-core/dist/token-audit.d.ts +47 -0
  121. package/packages/pi-agent-core/dist/token-audit.d.ts.map +1 -0
  122. package/packages/pi-agent-core/dist/token-audit.js +221 -0
  123. package/packages/pi-agent-core/dist/token-audit.js.map +1 -0
  124. package/packages/pi-agent-core/dist/types.d.ts +9 -0
  125. package/packages/pi-agent-core/dist/types.d.ts.map +1 -1
  126. package/packages/pi-agent-core/dist/types.js.map +1 -1
  127. package/packages/pi-agent-core/src/agent-loop.test.ts +128 -0
  128. package/packages/pi-agent-core/src/agent-loop.ts +4 -1
  129. package/packages/pi-agent-core/src/agent.ts +8 -0
  130. package/packages/pi-agent-core/src/index.ts +2 -0
  131. package/packages/pi-agent-core/src/token-audit.test.ts +189 -0
  132. package/packages/pi-agent-core/src/token-audit.ts +287 -0
  133. package/packages/pi-agent-core/src/types.ts +14 -0
  134. package/packages/pi-agent-core/tsconfig.tsbuildinfo +1 -1
  135. package/packages/pi-coding-agent/dist/core/agent-session-abort-order.test.js +32 -0
  136. package/packages/pi-coding-agent/dist/core/agent-session-abort-order.test.js.map +1 -1
  137. package/packages/pi-coding-agent/dist/core/agent-session-tool-refresh.test.js +18 -0
  138. package/packages/pi-coding-agent/dist/core/agent-session-tool-refresh.test.js.map +1 -1
  139. package/packages/pi-coding-agent/dist/core/agent-session.d.ts +12 -0
  140. package/packages/pi-coding-agent/dist/core/agent-session.d.ts.map +1 -1
  141. package/packages/pi-coding-agent/dist/core/agent-session.js +44 -7
  142. package/packages/pi-coding-agent/dist/core/agent-session.js.map +1 -1
  143. package/packages/pi-coding-agent/dist/core/chat-controller-ordering.test.js +3 -1
  144. package/packages/pi-coding-agent/dist/core/chat-controller-ordering.test.js.map +1 -1
  145. package/packages/pi-coding-agent/dist/core/compaction/compaction.d.ts +11 -0
  146. package/packages/pi-coding-agent/dist/core/compaction/compaction.d.ts.map +1 -1
  147. package/packages/pi-coding-agent/dist/core/compaction/compaction.js +9 -0
  148. package/packages/pi-coding-agent/dist/core/compaction/compaction.js.map +1 -1
  149. package/packages/pi-coding-agent/dist/core/compaction-threshold.test.d.ts +2 -0
  150. package/packages/pi-coding-agent/dist/core/compaction-threshold.test.d.ts.map +1 -0
  151. package/packages/pi-coding-agent/dist/core/compaction-threshold.test.js +103 -0
  152. package/packages/pi-coding-agent/dist/core/compaction-threshold.test.js.map +1 -0
  153. package/packages/pi-coding-agent/dist/core/db-snapshot.d.ts +15 -0
  154. package/packages/pi-coding-agent/dist/core/db-snapshot.d.ts.map +1 -0
  155. package/packages/pi-coding-agent/dist/core/db-snapshot.js +66 -0
  156. package/packages/pi-coding-agent/dist/core/db-snapshot.js.map +1 -0
  157. package/packages/pi-coding-agent/dist/core/db-snapshot.test.d.ts +2 -0
  158. package/packages/pi-coding-agent/dist/core/db-snapshot.test.d.ts.map +1 -0
  159. package/packages/pi-coding-agent/dist/core/db-snapshot.test.js +24 -0
  160. package/packages/pi-coding-agent/dist/core/db-snapshot.test.js.map +1 -0
  161. package/packages/pi-coding-agent/dist/core/extensions/loader.d.ts.map +1 -1
  162. package/packages/pi-coding-agent/dist/core/extensions/loader.js +8 -0
  163. package/packages/pi-coding-agent/dist/core/extensions/loader.js.map +1 -1
  164. package/packages/pi-coding-agent/dist/core/extensions/runner.d.ts +3 -0
  165. package/packages/pi-coding-agent/dist/core/extensions/runner.d.ts.map +1 -1
  166. package/packages/pi-coding-agent/dist/core/extensions/runner.js +6 -6
  167. package/packages/pi-coding-agent/dist/core/extensions/runner.js.map +1 -1
  168. package/packages/pi-coding-agent/dist/core/extensions/runner.test.js +5 -3
  169. package/packages/pi-coding-agent/dist/core/extensions/runner.test.js.map +1 -1
  170. package/packages/pi-coding-agent/dist/core/extensions/types.d.ts +39 -1
  171. package/packages/pi-coding-agent/dist/core/extensions/types.d.ts.map +1 -1
  172. package/packages/pi-coding-agent/dist/core/extensions/types.js.map +1 -1
  173. package/packages/pi-coding-agent/dist/core/hooks-runner.test.js +2 -0
  174. package/packages/pi-coding-agent/dist/core/hooks-runner.test.js.map +1 -1
  175. package/packages/pi-coding-agent/dist/core/sdk-tool-filter.test.d.ts +2 -0
  176. package/packages/pi-coding-agent/dist/core/sdk-tool-filter.test.d.ts.map +1 -0
  177. package/packages/pi-coding-agent/dist/core/sdk-tool-filter.test.js +46 -0
  178. package/packages/pi-coding-agent/dist/core/sdk-tool-filter.test.js.map +1 -0
  179. package/packages/pi-coding-agent/dist/core/sdk.d.ts +10 -2
  180. package/packages/pi-coding-agent/dist/core/sdk.d.ts.map +1 -1
  181. package/packages/pi-coding-agent/dist/core/sdk.js +74 -2
  182. package/packages/pi-coding-agent/dist/core/sdk.js.map +1 -1
  183. package/packages/pi-coding-agent/dist/core/settings-manager.d.ts +20 -0
  184. package/packages/pi-coding-agent/dist/core/settings-manager.d.ts.map +1 -1
  185. package/packages/pi-coding-agent/dist/core/settings-manager.js +25 -0
  186. package/packages/pi-coding-agent/dist/core/settings-manager.js.map +1 -1
  187. package/packages/pi-coding-agent/dist/core/skill-tool.test.js +22 -0
  188. package/packages/pi-coding-agent/dist/core/skill-tool.test.js.map +1 -1
  189. package/packages/pi-coding-agent/dist/core/system-prompt.d.ts +6 -7
  190. package/packages/pi-coding-agent/dist/core/system-prompt.d.ts.map +1 -1
  191. package/packages/pi-coding-agent/dist/core/system-prompt.js +2 -3
  192. package/packages/pi-coding-agent/dist/core/system-prompt.js.map +1 -1
  193. package/packages/pi-coding-agent/dist/modes/interactive/components/tool-execution.d.ts +1 -0
  194. package/packages/pi-coding-agent/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  195. package/packages/pi-coding-agent/dist/modes/interactive/components/tool-execution.js +3 -0
  196. package/packages/pi-coding-agent/dist/modes/interactive/components/tool-execution.js.map +1 -1
  197. package/packages/pi-coding-agent/dist/modes/interactive/controllers/chat-controller.d.ts.map +1 -1
  198. package/packages/pi-coding-agent/dist/modes/interactive/controllers/chat-controller.js +13 -5
  199. package/packages/pi-coding-agent/dist/modes/interactive/controllers/chat-controller.js.map +1 -1
  200. package/packages/pi-coding-agent/dist/modes/interactive/controllers/chat-controller.test.js +53 -0
  201. package/packages/pi-coding-agent/dist/modes/interactive/controllers/chat-controller.test.js.map +1 -1
  202. package/packages/pi-coding-agent/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  203. package/packages/pi-coding-agent/dist/modes/interactive/interactive-mode.js +3 -0
  204. package/packages/pi-coding-agent/dist/modes/interactive/interactive-mode.js.map +1 -1
  205. package/packages/pi-coding-agent/dist/resources/extensions/memory/storage-safety-guard.test.d.ts +2 -0
  206. package/packages/pi-coding-agent/dist/resources/extensions/memory/storage-safety-guard.test.d.ts.map +1 -0
  207. package/packages/pi-coding-agent/dist/resources/extensions/memory/storage-safety-guard.test.js +10 -0
  208. package/packages/pi-coding-agent/dist/resources/extensions/memory/storage-safety-guard.test.js.map +1 -0
  209. package/packages/pi-coding-agent/dist/resources/extensions/memory/storage.d.ts.map +1 -1
  210. package/packages/pi-coding-agent/dist/resources/extensions/memory/storage.js +3 -2
  211. package/packages/pi-coding-agent/dist/resources/extensions/memory/storage.js.map +1 -1
  212. package/packages/pi-coding-agent/src/core/agent-session-abort-order.test.ts +36 -0
  213. package/packages/pi-coding-agent/src/core/agent-session-tool-refresh.test.ts +25 -0
  214. package/packages/pi-coding-agent/src/core/agent-session.ts +48 -7
  215. package/packages/pi-coding-agent/src/core/chat-controller-ordering.test.ts +3 -1
  216. package/packages/pi-coding-agent/src/core/compaction/compaction.ts +18 -0
  217. package/packages/pi-coding-agent/src/core/compaction-threshold.test.ts +121 -0
  218. package/packages/pi-coding-agent/src/core/db-snapshot.test.ts +32 -0
  219. package/packages/pi-coding-agent/src/core/db-snapshot.ts +66 -0
  220. package/packages/pi-coding-agent/src/core/extensions/loader.ts +10 -0
  221. package/packages/pi-coding-agent/src/core/extensions/runner.test.ts +5 -3
  222. package/packages/pi-coding-agent/src/core/extensions/runner.ts +8 -5
  223. package/packages/pi-coding-agent/src/core/extensions/types.ts +42 -1
  224. package/packages/pi-coding-agent/src/core/hooks-runner.test.ts +2 -0
  225. package/packages/pi-coding-agent/src/core/sdk-tool-filter.test.ts +60 -0
  226. package/packages/pi-coding-agent/src/core/sdk.ts +85 -3
  227. package/packages/pi-coding-agent/src/core/settings-manager.ts +39 -1
  228. package/packages/pi-coding-agent/src/core/skill-tool.test.ts +28 -0
  229. package/packages/pi-coding-agent/src/core/system-prompt.ts +8 -10
  230. package/packages/pi-coding-agent/src/modes/interactive/components/tool-execution.ts +4 -0
  231. package/packages/pi-coding-agent/src/modes/interactive/controllers/chat-controller.test.ts +56 -0
  232. package/packages/pi-coding-agent/src/modes/interactive/controllers/chat-controller.ts +22 -7
  233. package/packages/pi-coding-agent/src/modes/interactive/interactive-mode.ts +3 -0
  234. package/packages/pi-coding-agent/src/resources/extensions/memory/storage-safety-guard.test.ts +14 -0
  235. package/packages/pi-coding-agent/src/resources/extensions/memory/storage.ts +3 -2
  236. package/packages/pi-coding-agent/tsconfig.tsbuildinfo +1 -1
  237. package/packages/pi-tui/dist/tui.d.ts.map +1 -1
  238. package/packages/pi-tui/dist/tui.js +18 -8
  239. package/packages/pi-tui/dist/tui.js.map +1 -1
  240. package/packages/pi-tui/src/tui.ts +20 -8
  241. package/packages/pi-tui/tsconfig.tsbuildinfo +1 -1
  242. package/src/resources/extensions/gsd/auto/loop-deps.ts +2 -2
  243. package/src/resources/extensions/gsd/auto/loop.ts +50 -8
  244. package/src/resources/extensions/gsd/auto/phases.ts +251 -172
  245. package/src/resources/extensions/gsd/auto/resolve.ts +23 -1
  246. package/src/resources/extensions/gsd/auto/run-unit.ts +25 -30
  247. package/src/resources/extensions/gsd/auto/session.ts +8 -0
  248. package/src/resources/extensions/gsd/auto-direct-dispatch.ts +8 -34
  249. package/src/resources/extensions/gsd/auto-dispatch.ts +16 -0
  250. package/src/resources/extensions/gsd/auto-post-unit.ts +18 -4
  251. package/src/resources/extensions/gsd/auto-prompts.ts +112 -15
  252. package/src/resources/extensions/gsd/auto-recovery.ts +54 -0
  253. package/src/resources/extensions/gsd/auto-start.ts +230 -9
  254. package/src/resources/extensions/gsd/auto-supervisor.ts +7 -0
  255. package/src/resources/extensions/gsd/auto-timeout-recovery.ts +2 -2
  256. package/src/resources/extensions/gsd/auto-worktree.ts +123 -0
  257. package/src/resources/extensions/gsd/auto.ts +98 -21
  258. package/src/resources/extensions/gsd/bootstrap/agent-end-recovery.ts +49 -1
  259. package/src/resources/extensions/gsd/bootstrap/db-tools.ts +50 -36
  260. package/src/resources/extensions/gsd/bootstrap/dynamic-tools.ts +16 -5
  261. package/src/resources/extensions/gsd/bootstrap/exec-tools.ts +34 -19
  262. package/src/resources/extensions/gsd/bootstrap/journal-tools.ts +8 -1
  263. package/src/resources/extensions/gsd/bootstrap/memory-tools.ts +10 -3
  264. package/src/resources/extensions/gsd/bootstrap/query-tools.ts +9 -2
  265. package/src/resources/extensions/gsd/bootstrap/register-hooks.ts +305 -28
  266. package/src/resources/extensions/gsd/bootstrap/system-context.ts +90 -22
  267. package/src/resources/extensions/gsd/clean-root-preflight.ts +32 -7
  268. package/src/resources/extensions/gsd/commands-handlers.ts +34 -15
  269. package/src/resources/extensions/gsd/context-budget.ts +44 -2
  270. package/src/resources/extensions/gsd/crash-recovery.ts +67 -10
  271. package/src/resources/extensions/gsd/db/unit-dispatches.ts +41 -0
  272. package/src/resources/extensions/gsd/db-base-schema.ts +4 -2
  273. package/src/resources/extensions/gsd/db-migration-steps.ts +8 -0
  274. package/src/resources/extensions/gsd/ecosystem/gsd-extension-api.ts +3 -0
  275. package/src/resources/extensions/gsd/git-service.ts +46 -8
  276. package/src/resources/extensions/gsd/gsd-db.ts +50 -13
  277. package/src/resources/extensions/gsd/guided-flow.ts +123 -45
  278. package/src/resources/extensions/gsd/memory-store.ts +77 -12
  279. package/src/resources/extensions/gsd/migrate/command.ts +47 -1
  280. package/src/resources/extensions/gsd/migration-auto-check.ts +129 -0
  281. package/src/resources/extensions/gsd/native-git-bridge.ts +39 -6
  282. package/src/resources/extensions/gsd/orphan-stash-audit.ts +117 -0
  283. package/src/resources/extensions/gsd/parallel-orchestrator.ts +13 -3
  284. package/src/resources/extensions/gsd/planning-path-scope.ts +35 -0
  285. package/src/resources/extensions/gsd/pre-execution-checks.ts +23 -0
  286. package/src/resources/extensions/gsd/preferences-types.ts +1 -1
  287. package/src/resources/extensions/gsd/prompt-loader.ts +27 -2
  288. package/src/resources/extensions/gsd/prompts/complete-milestone.md +16 -13
  289. package/src/resources/extensions/gsd/prompts/complete-slice.md +1 -1
  290. package/src/resources/extensions/gsd/prompts/execute-task.md +4 -2
  291. package/src/resources/extensions/gsd/prompts/parallel-research-slices.md +1 -1
  292. package/src/resources/extensions/gsd/prompts/plan-slice.md +1 -1
  293. package/src/resources/extensions/gsd/prompts/quick-task.md +1 -5
  294. package/src/resources/extensions/gsd/prompts/replan-slice.md +2 -2
  295. package/src/resources/extensions/gsd/prompts/validate-milestone.md +2 -2
  296. package/src/resources/extensions/gsd/quick.ts +37 -2
  297. package/src/resources/extensions/gsd/tests/artifact-retry-cap.test.ts +2 -2
  298. package/src/resources/extensions/gsd/tests/auto-loop.test.ts +417 -10
  299. package/src/resources/extensions/gsd/tests/auto-phases-lifecycle.test.ts +56 -13
  300. package/src/resources/extensions/gsd/tests/auto-recovery.test.ts +14 -1
  301. package/src/resources/extensions/gsd/tests/auto-wrapup-inflight-guard.test.ts +168 -6
  302. package/src/resources/extensions/gsd/tests/clean-root-preflight.test.ts +15 -6
  303. package/src/resources/extensions/gsd/tests/compaction-snapshot.test.ts +14 -1
  304. package/src/resources/extensions/gsd/tests/complete-milestone-excerpt.test.ts +31 -0
  305. package/src/resources/extensions/gsd/tests/complete-slice-composer.test.ts +3 -2
  306. package/src/resources/extensions/gsd/tests/context-budget.test.ts +10 -1
  307. package/src/resources/extensions/gsd/tests/context-store.test.ts +7 -1
  308. package/src/resources/extensions/gsd/tests/crash-handler-secondary.test.ts +55 -0
  309. package/src/resources/extensions/gsd/tests/crash-recovery-via-db.test.ts +22 -0
  310. package/src/resources/extensions/gsd/tests/custom-engine-loop-integration.test.ts +5 -1
  311. package/src/resources/extensions/gsd/tests/dispatch-rule-coverage.test.ts +313 -0
  312. package/src/resources/extensions/gsd/tests/exec-history.test.ts +15 -0
  313. package/src/resources/extensions/gsd/tests/exec-sandbox.test.ts +65 -0
  314. package/src/resources/extensions/gsd/tests/execute-task-rendering.test.ts +5 -2
  315. package/src/resources/extensions/gsd/tests/fast-forward-reused-milestone-branch.test.ts +219 -0
  316. package/src/resources/extensions/gsd/tests/finalize-survivor-branch.test.ts +132 -0
  317. package/src/resources/extensions/gsd/tests/integration/git-service.test.ts +54 -0
  318. package/src/resources/extensions/gsd/tests/isolation-none-branch-guard.test.ts +6 -3
  319. package/src/resources/extensions/gsd/tests/journal-integration.test.ts +239 -1
  320. package/src/resources/extensions/gsd/tests/journal-query-tool.test.ts +32 -0
  321. package/src/resources/extensions/gsd/tests/knowledge.test.ts +47 -0
  322. package/src/resources/extensions/gsd/tests/memory-decay-factor.test.ts +90 -0
  323. package/src/resources/extensions/gsd/tests/merge-conflict-stops-loop.test.ts +1 -0
  324. package/src/resources/extensions/gsd/tests/migrate-writer-integration.test.ts +48 -0
  325. package/src/resources/extensions/gsd/tests/migration-auto-check.test.ts +127 -0
  326. package/src/resources/extensions/gsd/tests/milestone-merge-stash-restore.test.ts +242 -0
  327. package/src/resources/extensions/gsd/tests/native-git-bridge-exec-fallback.test.ts +34 -2
  328. package/src/resources/extensions/gsd/tests/originalbase-path-comparison.test.ts +3 -0
  329. package/src/resources/extensions/gsd/tests/orphan-merge-bootstrap.test.ts +133 -0
  330. package/src/resources/extensions/gsd/tests/orphan-stash-audit.test.ts +201 -0
  331. package/src/resources/extensions/gsd/tests/parallel-orchestrator-fast-forward.test.ts +113 -0
  332. package/src/resources/extensions/gsd/tests/plan-slice.test.ts +50 -0
  333. package/src/resources/extensions/gsd/tests/plan-task.test.ts +21 -0
  334. package/src/resources/extensions/gsd/tests/pre-execution-checks.test.ts +45 -5
  335. package/src/resources/extensions/gsd/tests/prompt-duplication-cuts.test.ts +230 -0
  336. package/src/resources/extensions/gsd/tests/prompt-path-audit.test.ts +40 -0
  337. package/src/resources/extensions/gsd/tests/prompt-step-ordering.test.ts +19 -0
  338. package/src/resources/extensions/gsd/tests/query-tools-db-open.test.ts +3 -3
  339. package/src/resources/extensions/gsd/tests/quick-external-gsd.test.ts +40 -0
  340. package/src/resources/extensions/gsd/tests/restore-tools-after-discuss.test.ts +38 -17
  341. package/src/resources/extensions/gsd/tests/schema-v27-v28-sequence.test.ts +156 -0
  342. package/src/resources/extensions/gsd/tests/select-resumable-milestone.test.ts +96 -0
  343. package/src/resources/extensions/gsd/tests/session-switch-abort-misclassification.test.ts +106 -0
  344. package/src/resources/extensions/gsd/tests/signal-handlers.test.ts +27 -0
  345. package/src/resources/extensions/gsd/tests/smart-entry-complete.test.ts +20 -0
  346. package/src/resources/extensions/gsd/tests/stalled-tool-recovery.test.ts +49 -1
  347. package/src/resources/extensions/gsd/tests/start-auto-detached.test.ts +55 -0
  348. package/src/resources/extensions/gsd/tests/state-corruption-2945.test.ts +1 -0
  349. package/src/resources/extensions/gsd/tests/status-db-open.test.ts +9 -0
  350. package/src/resources/extensions/gsd/tests/system-context-memory.test.ts +112 -0
  351. package/src/resources/extensions/gsd/tests/system-context-message-routing.test.ts +7 -9
  352. package/src/resources/extensions/gsd/tests/token-tool-gating.test.ts +291 -0
  353. package/src/resources/extensions/gsd/tests/unit-context-composer.test.ts +136 -4
  354. package/src/resources/extensions/gsd/tests/unit-dispatches.test.ts +30 -0
  355. package/src/resources/extensions/gsd/tests/unit-runtime.test.ts +37 -0
  356. package/src/resources/extensions/gsd/tests/unstructured-continue-context-injection.test.ts +5 -4
  357. package/src/resources/extensions/gsd/tests/workflow-protocol-excerpt.test.ts +99 -0
  358. package/src/resources/extensions/gsd/tests/workflow-tool-executors.test.ts +3 -0
  359. package/src/resources/extensions/gsd/tests/worktree-journal-events.test.ts +1 -0
  360. package/src/resources/extensions/gsd/tests/worktree-path-injection.test.ts +22 -19
  361. package/src/resources/extensions/gsd/tests/worktree-project-root-degrade.test.ts +66 -0
  362. package/src/resources/extensions/gsd/tests/worktree-resolver.test.ts +167 -4
  363. package/src/resources/extensions/gsd/tools/context-mode-tool-result.ts +25 -0
  364. package/src/resources/extensions/gsd/tools/exec-search-tool.ts +7 -7
  365. package/src/resources/extensions/gsd/tools/exec-tool.ts +4 -23
  366. package/src/resources/extensions/gsd/tools/memory-tools.ts +1 -0
  367. package/src/resources/extensions/gsd/tools/plan-slice.ts +13 -0
  368. package/src/resources/extensions/gsd/tools/plan-task.ts +10 -0
  369. package/src/resources/extensions/gsd/tools/resume-tool.ts +7 -7
  370. package/src/resources/extensions/gsd/tools/workflow-tool-executors.ts +1 -1
  371. package/src/resources/extensions/gsd/unit-context-composer.ts +19 -4
  372. package/src/resources/extensions/gsd/unit-runtime.ts +25 -0
  373. package/src/resources/extensions/gsd/workflow-protocol.ts +160 -0
  374. package/src/resources/extensions/gsd/worktree-resolver.ts +85 -19
  375. package/src/resources/extensions/gsd/tests/phases-merge-error-stops-auto.test.ts +0 -97
  376. /package/dist/web/standalone/.next/static/{vaQ47E8aNlbbNEDoeME6G → O2WvnXROue6l7nAp_4dhC}/_buildManifest.js +0 -0
  377. /package/dist/web/standalone/.next/static/{vaQ47E8aNlbbNEDoeME6G → O2WvnXROue6l7nAp_4dhC}/_ssgManifest.js +0 -0
@@ -25,6 +25,50 @@ import {
25
25
 
26
26
  import type { MigrationPreview } from "./writer.js";
27
27
  import { homedir } from "node:os";
28
+ import { ensureDbOpen } from "../bootstrap/dynamic-tools.js";
29
+ import { clearEngineHierarchy, transaction } from "../gsd-db.js";
30
+ import { migrateFromMarkdown } from "../md-importer.js";
31
+ import { invalidateStateCache } from "../state.js";
32
+
33
+ export type MigrationImportCounts = ReturnType<typeof migrateFromMarkdown>;
34
+
35
+ function assertMigrationImportMatchesPreview(imported: MigrationImportCounts, preview: MigrationPreview): void {
36
+ const mismatches: string[] = [];
37
+ if (imported.hierarchy.milestones !== preview.milestoneCount) {
38
+ mismatches.push(`milestones ${imported.hierarchy.milestones}/${preview.milestoneCount}`);
39
+ }
40
+ if (imported.hierarchy.slices !== preview.totalSlices) {
41
+ mismatches.push(`slices ${imported.hierarchy.slices}/${preview.totalSlices}`);
42
+ }
43
+ if (imported.hierarchy.tasks !== preview.totalTasks) {
44
+ mismatches.push(`tasks ${imported.hierarchy.tasks}/${preview.totalTasks}`);
45
+ }
46
+ if (imported.requirements !== preview.requirements.total) {
47
+ mismatches.push(`requirements ${imported.requirements}/${preview.requirements.total}`);
48
+ }
49
+ if (mismatches.length > 0) {
50
+ throw new Error(`migration DB import verification failed: ${mismatches.join(", ")}`);
51
+ }
52
+ }
53
+
54
+ export async function importWrittenMigrationToDb(
55
+ basePath: string,
56
+ preview?: MigrationPreview,
57
+ ): Promise<MigrationImportCounts> {
58
+ const opened = await ensureDbOpen(basePath);
59
+ if (!opened) {
60
+ throw new Error(`failed to open or create the GSD database at ${basePath}`);
61
+ }
62
+
63
+ const counts = transaction(() => {
64
+ clearEngineHierarchy();
65
+ const imported = migrateFromMarkdown(basePath);
66
+ if (preview) assertMigrationImportMatchesPreview(imported, preview);
67
+ return imported;
68
+ });
69
+ invalidateStateCache();
70
+ return counts;
71
+ }
28
72
 
29
73
  /** Format preview stats for embedding in the review prompt. */
30
74
  function formatPreviewStats(preview: MigrationPreview): string {
@@ -182,9 +226,10 @@ export async function handleMigrate(
182
226
 
183
227
  const result = await writeGSDDirectory(project, process.cwd());
184
228
  const gsdPath = gsdRoot(process.cwd());
229
+ const imported = await importWrittenMigrationToDb(process.cwd(), preview);
185
230
 
186
231
  ctx.ui.notify(
187
- `✓ Migration complete — ${result.paths.length} file(s) written to .gsd/`,
232
+ `✓ Migration complete — ${result.paths.length} file(s) written to .gsd/ and ${imported.hierarchy.milestones}M/${imported.hierarchy.slices}S/${imported.hierarchy.tasks}T imported to the database`,
188
233
  "info",
189
234
  );
190
235
 
@@ -193,6 +238,7 @@ export async function handleMigrate(
193
238
  title: "Migration written",
194
239
  summary: [
195
240
  `${result.paths.length} files written to .gsd/`,
241
+ `${imported.hierarchy.milestones} milestone(s), ${imported.hierarchy.slices} slice(s), and ${imported.hierarchy.tasks} task(s) imported to gsd.db`,
196
242
  "",
197
243
  "The agent can now review the migrated output against GSD-2 standards —",
198
244
  "checking structure, content quality, deriveState() round-trip, and",
@@ -0,0 +1,129 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+
3
+ import { ensureDbOpen } from "./bootstrap/dynamic-tools.js";
4
+ import {
5
+ clearEngineHierarchy,
6
+ getAllMilestones,
7
+ getMilestoneSlices,
8
+ getSliceTasks,
9
+ isDbAvailable,
10
+ transaction,
11
+ } from "./gsd-db.js";
12
+ import { migrateHierarchyToDb } from "./md-importer.js";
13
+ import { parsePlan, parseRoadmap } from "./parsers-legacy.js";
14
+ import {
15
+ milestonesDir,
16
+ resolveMilestoneFile,
17
+ resolveSliceFile,
18
+ } from "./paths.js";
19
+ import { invalidateStateCache } from "./state.js";
20
+
21
+ export interface HierarchyCounts {
22
+ milestones: number;
23
+ slices: number;
24
+ tasks: number;
25
+ }
26
+
27
+ export interface MigrationAutoCheckResult {
28
+ action: "none" | "imported";
29
+ reason: "no-markdown" | "in-sync" | "db-empty" | "count-mismatch";
30
+ markdown: HierarchyCounts;
31
+ beforeDb: HierarchyCounts;
32
+ afterDb: HierarchyCounts;
33
+ }
34
+
35
+ function zeroCounts(): HierarchyCounts {
36
+ return { milestones: 0, slices: 0, tasks: 0 };
37
+ }
38
+
39
+ function sameCounts(a: HierarchyCounts, b: HierarchyCounts): boolean {
40
+ return a.milestones === b.milestones && a.slices === b.slices && a.tasks === b.tasks;
41
+ }
42
+
43
+ export function countMarkdownHierarchy(basePath: string): HierarchyCounts {
44
+ const root = milestonesDir(basePath);
45
+ if (!existsSync(root)) return zeroCounts();
46
+
47
+ const counts = zeroCounts();
48
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
49
+ if (!entry.isDirectory() || !/^M\d+/.test(entry.name)) continue;
50
+ counts.milestones++;
51
+
52
+ const roadmapPath = resolveMilestoneFile(basePath, entry.name, "ROADMAP");
53
+ if (!roadmapPath || !existsSync(roadmapPath)) continue;
54
+
55
+ const roadmap = parseRoadmap(readFileSync(roadmapPath, "utf-8"));
56
+ counts.slices += roadmap.slices.length;
57
+
58
+ for (const slice of roadmap.slices) {
59
+ const planPath = resolveSliceFile(basePath, entry.name, slice.id, "PLAN");
60
+ if (!planPath || !existsSync(planPath)) continue;
61
+ const plan = parsePlan(readFileSync(planPath, "utf-8"));
62
+ counts.tasks += plan.tasks.length;
63
+ }
64
+ }
65
+
66
+ return counts;
67
+ }
68
+
69
+ export function countDbHierarchy(): HierarchyCounts {
70
+ if (!isDbAvailable()) return zeroCounts();
71
+ const counts = zeroCounts();
72
+ const milestones = getAllMilestones();
73
+ counts.milestones = milestones.length;
74
+
75
+ for (const milestone of milestones) {
76
+ const slices = getMilestoneSlices(milestone.id);
77
+ counts.slices += slices.length;
78
+ for (const slice of slices) {
79
+ counts.tasks += getSliceTasks(milestone.id, slice.id).length;
80
+ }
81
+ }
82
+
83
+ return counts;
84
+ }
85
+
86
+ export async function autoImportMarkdownHierarchyIfDbMismatch(
87
+ basePath: string,
88
+ ): Promise<MigrationAutoCheckResult> {
89
+ const markdown = countMarkdownHierarchy(basePath);
90
+ if (sameCounts(markdown, zeroCounts())) {
91
+ return {
92
+ action: "none",
93
+ reason: "no-markdown",
94
+ markdown,
95
+ beforeDb: zeroCounts(),
96
+ afterDb: zeroCounts(),
97
+ };
98
+ }
99
+
100
+ const opened = await ensureDbOpen(basePath);
101
+ if (!opened || !isDbAvailable()) {
102
+ throw new Error(`failed to open or create the GSD database at ${basePath}`);
103
+ }
104
+
105
+ const beforeDb = countDbHierarchy();
106
+ if (sameCounts(markdown, beforeDb)) {
107
+ return { action: "none", reason: "in-sync", markdown, beforeDb, afterDb: beforeDb };
108
+ }
109
+
110
+ const reason = sameCounts(beforeDb, zeroCounts()) ? "db-empty" : "count-mismatch";
111
+ const imported = transaction(() => {
112
+ clearEngineHierarchy();
113
+ return migrateHierarchyToDb(basePath);
114
+ });
115
+ invalidateStateCache();
116
+
117
+ const afterDb = {
118
+ milestones: imported.milestones,
119
+ slices: imported.slices,
120
+ tasks: imported.tasks,
121
+ };
122
+ if (!sameCounts(markdown, afterDb)) {
123
+ throw new Error(
124
+ `migration auto-import verification failed: markdown ${markdown.milestones}M/${markdown.slices}S/${markdown.tasks}T, db ${afterDb.milestones}M/${afterDb.slices}S/${afterDb.tasks}T`,
125
+ );
126
+ }
127
+
128
+ return { action: "imported", reason, markdown, beforeDb, afterDb };
129
+ }
@@ -1183,6 +1183,33 @@ export function nativeRmForce(basePath: string, paths: string[]): void {
1183
1183
  }
1184
1184
  }
1185
1185
 
1186
+ function runGitWorktreeAdd(
1187
+ basePath: string,
1188
+ wtPath: string,
1189
+ branch: string,
1190
+ createBranch?: boolean,
1191
+ startPoint?: string,
1192
+ ): void {
1193
+ if (createBranch) {
1194
+ const branchRef = gitExec(basePath, ["show-ref", "--verify", `refs/heads/${branch}`], true);
1195
+ if (branchRef) {
1196
+ gitExec(basePath, ["worktree", "add", wtPath, branch]);
1197
+ return;
1198
+ }
1199
+ gitExec(basePath, ["worktree", "add", "-b", branch, wtPath, startPoint ?? "HEAD"]);
1200
+ } else {
1201
+ gitExec(basePath, ["worktree", "add", wtPath, branch]);
1202
+ }
1203
+ }
1204
+
1205
+ export function assertWorktreeMaterialized(wtPath: string): void {
1206
+ if (existsSync(join(wtPath, ".git"))) return;
1207
+ throw new GSDError(
1208
+ GSD_GIT_ERROR,
1209
+ `git worktree add did not materialize a valid worktree at ${wtPath}: missing .git file`,
1210
+ );
1211
+ }
1212
+
1186
1213
  /**
1187
1214
  * Add a new git worktree.
1188
1215
  * Native: libgit2 worktree API.
@@ -1198,14 +1225,20 @@ export function nativeWorktreeAdd(
1198
1225
  const native = loadNative();
1199
1226
  if (native) {
1200
1227
  native.gitWorktreeAdd(basePath, wtPath, branch, createBranch, startPoint);
1201
- return;
1228
+ try {
1229
+ assertWorktreeMaterialized(wtPath);
1230
+ return;
1231
+ } catch {
1232
+ rmSync(wtPath, { recursive: true, force: true });
1233
+ gitExec(basePath, ["worktree", "prune"], true);
1234
+ runGitWorktreeAdd(basePath, wtPath, branch, createBranch, startPoint);
1235
+ assertWorktreeMaterialized(wtPath);
1236
+ return;
1237
+ }
1202
1238
  }
1203
1239
 
1204
- if (createBranch) {
1205
- gitExec(basePath, ["worktree", "add", "-b", branch, wtPath, startPoint ?? "HEAD"]);
1206
- } else {
1207
- gitExec(basePath, ["worktree", "add", wtPath, branch]);
1208
- }
1240
+ runGitWorktreeAdd(basePath, wtPath, branch, createBranch, startPoint);
1241
+ assertWorktreeMaterialized(wtPath);
1209
1242
  }
1210
1243
 
1211
1244
  /**
@@ -0,0 +1,117 @@
1
+ // GSD-2 + src/resources/extensions/gsd/orphan-stash-audit.ts
2
+ // Startup sweep for orphaned gsd-preflight-stash entries left behind by
3
+ // interrupted milestone merges (#5538-followup).
4
+
5
+ import { execFileSync } from "node:child_process";
6
+ import { GIT_NO_PROMPT_ENV } from "./git-constants.js";
7
+
8
+ export interface OrphanPreflightStashAuditResult {
9
+ applied: Array<{ milestoneId: string; stashRef: string }>;
10
+ warnings: string[];
11
+ }
12
+
13
+ /**
14
+ * Recognize the "already restored" failure mode of `git stash apply`.
15
+ *
16
+ * When a preflight stash captured untracked files via `--include-untracked`
17
+ * and those files are now present in the working tree (e.g. a prior audit
18
+ * run already applied this stash), `git stash apply` aborts with
19
+ * `<path> already exists, no checkout` and exits non-zero. That is the
20
+ * idempotent steady state for this audit, not a recovery failure — treat
21
+ * it as a no-op so repeated GSD startups stop spamming the user with
22
+ * warnings about stashes that have already been restored (#5538-followup
23
+ * peer-review feedback).
24
+ */
25
+ function _isAlreadyRestoredApplyError(err: unknown): boolean {
26
+ if (!err || typeof err !== "object") return false;
27
+ const stderr = (err as { stderr?: unknown }).stderr;
28
+ const stderrText = typeof stderr === "string" ? stderr : stderr instanceof Uint8Array ? Buffer.from(stderr).toString("utf-8") : "";
29
+ if (stderrText && /already exists, no checkout/i.test(stderrText)) return true;
30
+ const message = err instanceof Error ? err.message : String(err);
31
+ return /already exists, no checkout/i.test(message);
32
+ }
33
+
34
+ export { _isAlreadyRestoredApplyError };
35
+
36
+ /**
37
+ * Audit `git stash list` for orphaned `gsd-preflight-stash:M00x:*` entries.
38
+ *
39
+ * The matching merge code in `phases.ts` previously skipped the postflight
40
+ * pop whenever `mergeAndExit` threw, leaking the user's pre-merge working
41
+ * tree into the stash list. For every preflight-stash entry whose milestone
42
+ * is now complete (per the supplied callback), `git stash apply` is invoked —
43
+ * NOT `pop`. The stash entry stays in the list so the user retains a backup
44
+ * if the apply produces unexpected merge results. Idempotent across repeated
45
+ * startup runs.
46
+ *
47
+ * Failures are best-effort: a list error (no repo, git unavailable) returns
48
+ * an empty result. An apply error becomes a warning the user sees alongside
49
+ * the existing orphan-branch audit messages — startup continues.
50
+ */
51
+ export function auditOrphanedPreflightStashes(
52
+ basePath: string,
53
+ isMilestoneComplete: (milestoneId: string) => boolean,
54
+ ): OrphanPreflightStashAuditResult {
55
+ const result: OrphanPreflightStashAuditResult = { applied: [], warnings: [] };
56
+
57
+ let listOutput: string;
58
+ try {
59
+ listOutput = execFileSync(
60
+ "git",
61
+ ["stash", "list", "--format=%gd%x00%s"],
62
+ {
63
+ cwd: basePath,
64
+ stdio: ["ignore", "pipe", "pipe"],
65
+ encoding: "utf-8",
66
+ env: GIT_NO_PROMPT_ENV,
67
+ },
68
+ );
69
+ } catch {
70
+ return result;
71
+ }
72
+
73
+ const MARKER_RE = /\bgsd-preflight-stash:([A-Za-z0-9_-]+):/;
74
+ for (const line of listOutput.split("\n")) {
75
+ const sep = line.indexOf("\x00");
76
+ if (sep < 0) continue;
77
+ const ref = line.slice(0, sep);
78
+ const subject = line.slice(sep + 1);
79
+ if (!ref || !subject) continue;
80
+
81
+ const match = MARKER_RE.exec(subject);
82
+ if (!match) continue;
83
+ const milestoneId = match[1];
84
+
85
+ let complete = false;
86
+ try {
87
+ complete = isMilestoneComplete(milestoneId);
88
+ } catch (err) {
89
+ result.warnings.push(
90
+ `Could not determine completion status for ${milestoneId} during preflight-stash audit: ${err instanceof Error ? err.message : String(err)}.`,
91
+ );
92
+ continue;
93
+ }
94
+ if (!complete) continue;
95
+
96
+ try {
97
+ execFileSync("git", ["stash", "apply", "--quiet", ref], {
98
+ cwd: basePath,
99
+ stdio: ["ignore", "pipe", "pipe"],
100
+ encoding: "utf-8",
101
+ env: GIT_NO_PROMPT_ENV,
102
+ });
103
+ result.applied.push({ milestoneId, stashRef: ref });
104
+ } catch (err) {
105
+ // Idempotent steady state: stash was already applied in a prior audit
106
+ // run; the files exist and `git stash apply` refuses to overwrite.
107
+ // Skip silently so repeat runs are no-ops.
108
+ if (_isAlreadyRestoredApplyError(err)) continue;
109
+ result.warnings.push(
110
+ `Could not apply orphaned preflight stash ${ref} (milestone ${milestoneId}): ${err instanceof Error ? err.message : String(err)}. ` +
111
+ `Run \`git stash apply ${ref}\` manually to restore your pre-merge changes.`,
112
+ );
113
+ }
114
+ }
115
+
116
+ return result;
117
+ }
@@ -21,7 +21,7 @@ import { join, dirname } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
22
  import { gsdRoot } from "./paths.js";
23
23
  import { createWorktree, worktreePath } from "./worktree-manager.js";
24
- import { autoWorktreeBranch, runWorktreePostCreateHook, syncGsdStateToWorktree } from "./auto-worktree.js";
24
+ import { autoWorktreeBranch, fastForwardReusedMilestoneBranchIfSafe, runWorktreePostCreateHook, syncGsdStateToWorktree } from "./auto-worktree.js";
25
25
  import { nativeBranchExists } from "./native-git-bridge.js";
26
26
  import { readIntegrationBranch } from "./git-service.js";
27
27
  import { resolveParallelConfig } from "./preferences.js";
@@ -471,7 +471,7 @@ export async function startParallel(
471
471
  // Create the worktree (without chdir — coordinator stays in project root)
472
472
  let wtPath: string;
473
473
  try {
474
- wtPath = createMilestoneWorktree(basePath, mid);
474
+ wtPath = _createMilestoneWorktree(basePath, mid);
475
475
  } catch (e) {
476
476
  logWarning("parallel", `createMilestoneWorktree fallback for ${mid}: ${(e as Error).message}`);
477
477
  wtPath = worktreePath(basePath, mid);
@@ -532,13 +532,23 @@ export async function startParallel(
532
532
  /**
533
533
  * Create a git worktree for a milestone without changing the coordinator's cwd.
534
534
  * Uses milestone/<MID> branch naming (same as auto-worktree.ts).
535
+ *
536
+ * Exported with the `_` prefix purely for tests — production callers stay on
537
+ * the closure-private name `createMilestoneWorktree` below.
535
538
  */
536
- function createMilestoneWorktree(basePath: string, milestoneId: string): string {
539
+ export function _createMilestoneWorktree(basePath: string, milestoneId: string): string {
537
540
  const branch = autoWorktreeBranch(milestoneId);
538
541
  const branchExists = nativeBranchExists(basePath, branch);
539
542
 
540
543
  let info: { name: string; path: string; branch: string; exists: boolean };
541
544
  if (branchExists) {
545
+ // #5549 post-merge audit (R3): match the fast-forward behavior added to
546
+ // `createAutoWorktree` in commit 8996cb68e. When a worker reuses an
547
+ // existing milestone branch, fast-forward it onto the integration branch
548
+ // when safe so per-worker worktrees don't fork from a stale base after a
549
+ // sibling milestone has merged. Same `nativeIsAncestor` + worktree-list
550
+ // safety guards apply.
551
+ fastForwardReusedMilestoneBranchIfSafe(basePath, milestoneId, branch);
542
552
  info = createWorktree(basePath, milestoneId, { branch, reuseExistingBranch: true });
543
553
  } else {
544
554
  const integrationBranch = readIntegrationBranch(basePath, milestoneId) ?? undefined;
@@ -0,0 +1,35 @@
1
+ import { isAbsolute, relative, resolve } from "node:path";
2
+ import { normalizePlannedFileReference } from "./files.js";
3
+
4
+ export interface PlanningPathScopeField {
5
+ field: string;
6
+ values: string[];
7
+ }
8
+
9
+ function isInsideBase(basePath: string, candidate: string): boolean {
10
+ const base = resolve(basePath);
11
+ const abs = resolve(candidate);
12
+ const rel = relative(base, abs);
13
+ return rel === "" || (!!rel && !rel.startsWith("..") && !isAbsolute(rel));
14
+ }
15
+
16
+ /**
17
+ * Planning IO fields are execution contracts. Absolute paths are only safe when
18
+ * they stay inside the active working directory; in worktree mode, an absolute
19
+ * path to the original checkout makes executors edit the wrong tree.
20
+ */
21
+ export function validatePlanningPathScope(
22
+ basePath: string,
23
+ fields: PlanningPathScopeField[],
24
+ ): string | null {
25
+ for (const { field, values } of fields) {
26
+ for (const raw of values) {
27
+ const candidate = normalizePlannedFileReference(raw);
28
+ if (!isAbsolute(candidate)) continue;
29
+ if (isInsideBase(basePath, candidate)) continue;
30
+ return `${field} contains absolute path outside working directory: ${candidate}. Use a path relative to ${basePath}.`;
31
+ }
32
+ }
33
+
34
+ return null;
35
+ }
@@ -380,6 +380,8 @@ function shouldValidateInputAsPath(raw: string): boolean {
380
380
  const trimmed = raw.trim();
381
381
  if (!trimmed) return false;
382
382
 
383
+ if (isRuntimeOnlyInput(trimmed)) return false;
384
+
383
385
  const candidate = extractPathFromAnnotation(trimmed);
384
386
  if (!candidate) return false;
385
387
 
@@ -405,6 +407,10 @@ function shouldValidateInputAsPath(raw: string): boolean {
405
407
  );
406
408
  }
407
409
 
410
+ function isRuntimeOnlyInput(raw: string): boolean {
411
+ return /\(\s*runtime\s*\)/i.test(raw);
412
+ }
413
+
408
414
  function containsGlobPattern(candidate: string): boolean {
409
415
  return ["*", "?", "[", "]", "{", "}"].some((char) => candidate.includes(char));
410
416
  }
@@ -448,6 +454,16 @@ export function checkFilePathConsistency(
448
454
  ): PreExecutionCheckJSON[] {
449
455
  const results: PreExecutionCheckJSON[] = [];
450
456
 
457
+ // Build a set of all files created by any task at any position (normalized).
458
+ // Used to suppress consistency errors for files that will be caught with a
459
+ // more precise message by checkTaskOrdering (sequence violation).
460
+ const allTaskOutputs = new Set<string>();
461
+ for (const t of tasks) {
462
+ for (const f of t.expected_output) {
463
+ allTaskOutputs.add(normalizeFilePath(f));
464
+ }
465
+ }
466
+
451
467
  for (let i = 0; i < tasks.length; i++) {
452
468
  const task = tasks[i];
453
469
  const priorOutputs = getExpectedOutputsUpTo(tasks, i);
@@ -481,6 +497,12 @@ export function checkFilePathConsistency(
481
497
  }
482
498
 
483
499
  if (!existsOnDisk && !inPriorOutputs && !inOwnOutputs && !directorySatisfied) {
500
+ // If a later task claims to create this file, the ordering check will
501
+ // fire a more precise "sequence violation" error for the same file.
502
+ // Suppress the consistency error here to avoid duplicate noise.
503
+ if (allTaskOutputs.has(normalizedFile) && !ownOutputs.has(normalizedFile)) {
504
+ continue;
505
+ }
484
506
  results.push({
485
507
  category: "file",
486
508
  target: file,
@@ -535,6 +557,7 @@ export function checkTaskOrdering(
535
557
  const filesToCheck = [...task.inputs];
536
558
 
537
559
  for (const file of filesToCheck) {
560
+ if (isRuntimeOnlyInput(file)) continue;
538
561
  if (!shouldValidateInputAsPath(file)) continue;
539
562
 
540
563
  const normalizedFile = normalizeFilePath(file);
@@ -32,7 +32,7 @@ export interface ContextManagementConfig {
32
32
  /**
33
33
  * Opt-in tool-output sandboxing for sub-sessions. When enabled, the gsd_exec
34
34
  * MCP tool runs scripts in an isolated subprocess and returns only a short
35
- * digest to the calling agent's context window; full stdout/stderr persist
35
+ * digest to the calling agent's context window; capped stdout/stderr persist
36
36
  * in the project memory store and can be retrieved by id later.
37
37
  *
38
38
  * Inspired by mksglu/context-mode (Elastic License 2.0). This is an
@@ -123,17 +123,42 @@ function warmCache(): void {
123
123
  }
124
124
 
125
125
  let warmCacheScheduled = false;
126
+ let warmCacheRan = false;
127
+ let warmCacheTimer: ReturnType<typeof setTimeout> | undefined;
128
+
129
+ /**
130
+ * Synchronously snapshot the prompt/template tree into the cache.
131
+ *
132
+ * Safe to call immediately after `initResources()` because that function uses
133
+ * synchronous fs APIs — there is no race window that requires deferring the
134
+ * cache warm via setTimeout. Idempotent: subsequent calls are no-ops.
135
+ *
136
+ * Cancels the fallback `scheduleWarmCache` timer if it is still pending.
137
+ */
138
+ export function primeCache(): void {
139
+ if (warmCacheRan) return;
140
+ if (warmCacheTimer) {
141
+ clearTimeout(warmCacheTimer);
142
+ warmCacheTimer = undefined;
143
+ }
144
+ warmCacheScheduled = true;
145
+ warmCacheRan = true;
146
+ warmCache();
147
+ }
126
148
 
127
149
  function scheduleWarmCache(): void {
128
150
  if (warmCacheScheduled) return;
129
151
  warmCacheScheduled = true;
130
152
 
131
153
  const run = () => {
154
+ warmCacheTimer = undefined;
155
+ if (warmCacheRan) return;
156
+ warmCacheRan = true;
132
157
  warmCache();
133
158
  };
134
159
 
135
- const timer = setTimeout(run, 1000);
136
- timer.unref?.();
160
+ warmCacheTimer = setTimeout(run, 1000);
161
+ warmCacheTimer.unref?.();
137
162
  }
138
163
 
139
164
  // Snapshot the full prompt/template tree after import so extension startup only
@@ -6,6 +6,8 @@ You are executing GSD auto-mode.
6
6
 
7
7
  Your working directory is `{{workingDirectory}}`. All file reads, writes, and shell commands MUST operate relative to this directory. Do NOT `cd` to any other directory.
8
8
 
9
+ If any inlined plan, summary, verification command, or prior artifact names an absolute path outside `{{workingDirectory}}`, treat that path as stale context. Convert it to the equivalent relative path under `{{workingDirectory}}` before reading, writing, or executing. If no equivalent path exists under `{{workingDirectory}}`, record a verification failure and stop; do not edit or run commands in another checkout.
10
+
9
11
  ## Mission
10
12
 
11
13
  All slices are complete. Verify the integrated work, persist milestone completion, refresh project state, and write the final record future milestones will rely on.
@@ -29,14 +31,15 @@ Subagents report only; they do not write user source. Fold any findings into Dec
29
31
 
30
32
  ## Steps
31
33
 
32
- 1. Use the **Milestone Summary** output template from the inlined context above
33
- 2. {{skillActivation}}
34
- 3. **Verify code changes exist.** Compare milestone work against the integration branch (`main`, `master`, or recorded branch), using merge-base as older revision and `HEAD` as newer. If the diff lists non-`.gsd/` files, pass. If `HEAD` equals the integration branch/merge-base, treat it as a self-diff retry: inspect milestone-scoped commit evidence (`GSD-Unit: {{milestoneId}}` or production `GSD-Task: Sxx/Tyy` trailers touching `.gsd/milestones/{{milestoneId}}/`) and verify those commits touched non-`.gsd/` files. Record **verification failure** only when neither source shows implementation files.
35
- 4. Verify every **success criterion** from `{{roadmapPath}}`. If passing validation is present, summarize the validation evidence instead of re-auditing it; otherwise verify with evidence from summaries, tests, or observable behavior. Record unmet criteria as **verification failure**.
36
- 5. Verify **definition of done**: all slices `[x]`, summaries exist, and integrations work. If passing validation is present, trust its integration/verification verdict unless inconsistent with current artifacts. Record unmet items as **verification failure**.
37
- 6. If the roadmap includes a **Horizontal Checklist**, verify each item and note unchecked items in the summary.
38
- 7. Fill the **Decision Re-evaluation** table: compare each key `.gsd/DECISIONS.md` decision from this milestone with what shipped, and flag decisions to revisit.
39
- 8. Validate **requirement status transitions**. For each changed requirement, confirm evidence supports the new status. Requirements may move between Active, Validated, Deferred, Blocked, or Out of Scope only with proof.
34
+ 1. **Duplicate completion guard:** Call `gsd_milestone_status` for `{{milestoneId}}` before any durable writes. If the returned milestone **status is `complete`**, this is a stale or duplicate closeout turn: do NOT mutate requirements, do NOT refresh the project document, do NOT write LEARNINGS, and do NOT persist milestone completion again. Say: "Milestone {{milestoneId}} is already complete." and stop.
35
+ 2. Use the **Milestone Summary** output template from the inlined context above
36
+ 3. {{skillActivation}}
37
+ 4. **Verify code changes exist.** Compare milestone work against the integration branch (`main`, `master`, or recorded branch), using merge-base as older revision and `HEAD` as newer. If the diff lists non-`.gsd/` files, pass. If `HEAD` equals the integration branch/merge-base, treat it as a self-diff retry: inspect milestone-scoped commit evidence (`GSD-Unit: {{milestoneId}}` or production `GSD-Task: Sxx/Tyy` trailers touching `.gsd/milestones/{{milestoneId}}/`) and verify those commits touched non-`.gsd/` files. Record **verification failure** only when neither source shows implementation files.
38
+ 5. Verify every **success criterion** from `{{roadmapPath}}`. If passing validation is present, summarize the validation evidence instead of re-auditing it; otherwise verify with evidence from summaries, tests, or observable behavior. Record unmet criteria as **verification failure**.
39
+ 6. Verify **definition of done**: all slices `[x]`, summaries exist, and integrations work. If passing validation is present, trust its integration/verification verdict unless inconsistent with current artifacts. Record unmet items as **verification failure**.
40
+ 7. If the roadmap includes a **Horizontal Checklist**, verify each item and note unchecked items in the summary.
41
+ 8. Fill the **Decision Re-evaluation** table: compare each key `.gsd/DECISIONS.md` decision from this milestone with what shipped, and flag decisions to revisit.
42
+ 9. Validate **requirement status transitions**. For each changed requirement, confirm evidence supports the new status. Requirements may move between Active, Validated, Deferred, Blocked, or Out of Scope only with proof.
40
43
 
41
44
  **DB access safety:** Do NOT query `.gsd/gsd.db` directly via `sqlite3` or `node -e require('better-sqlite3')`; the engine owns the WAL connection. Use `gsd_milestone_status`, inlined context, or `gsd_*` tools; never direct SQL.
42
45
 
@@ -53,13 +56,13 @@ Subagents report only; they do not write user source. Fold any findings into Dec
53
56
 
54
57
  **Success path** (all verifications passed):
55
58
 
56
- 9. For each requirement whose status changed in step 8, call `gsd_requirement_update` with the requirement ID and updated `status` and `validation` fields — the tool regenerates `.gsd/REQUIREMENTS.md` automatically. Do this BEFORE completing the milestone so requirement updates are persisted.
57
- 10. Update `.gsd/PROJECT.md`: use the `write` tool with `path: ".gsd/PROJECT.md"` and `content` containing the full updated document reflecting milestone completion and current project state. Do NOT use the `edit` tool for this — PROJECT.md is a full-document refresh.
58
- 11. Extract structured learnings from this milestone and persist them to the GSD memory store. Follow the procedure block immediately below — it writes `{{milestoneId}}-LEARNINGS.md` as the audit trail and persists Patterns, Lessons, and Decisions via `capture_thought` (categories: pattern, gotcha/convention, architecture). The memory store is the single source of truth for cross-session durable knowledge (ADR-013).
59
+ 10. For each requirement whose status changed in step 9, call `gsd_requirement_update` with the requirement ID and updated `status` and `validation` fields — the tool regenerates `.gsd/REQUIREMENTS.md` automatically. Do this BEFORE completing the milestone so requirement updates are persisted.
60
+ 11. Update `.gsd/PROJECT.md`: use the `write` tool with `path: ".gsd/PROJECT.md"` and `content` containing the full updated document reflecting milestone completion and current project state. Do NOT use the `edit` tool for this — PROJECT.md is a full-document refresh.
61
+ 12. Extract structured learnings from this milestone and persist them to the GSD memory store. Follow the procedure block immediately below — it writes `{{milestoneId}}-LEARNINGS.md` as the audit trail and persists Patterns, Lessons, and Decisions via `capture_thought` (categories: pattern, gotcha/convention, architecture). The memory store is the single source of truth for cross-session durable knowledge (ADR-013).
59
62
 
60
63
  {{extractLearningsSteps}}
61
64
 
62
- 12. **Persist completion through `gsd_complete_milestone`.** Call it with the parameters below. This must be the final persistent write in the unit. The tool updates the milestone status in the DB, renders `{{milestoneSummaryPath}}`, and validates all slices are complete.
65
+ 13. **Persist completion through `gsd_complete_milestone`.** Call it with the parameters below. This must be the final persistent write in the unit. The tool updates the milestone status in the DB, renders `{{milestoneSummaryPath}}`, and validates all slices are complete.
63
66
 
64
67
  **Required parameters:**
65
68
  - `milestoneId` (string) — Milestone ID (e.g. M001)
@@ -78,7 +81,7 @@ Subagents report only; they do not write user source. Fold any findings into Dec
78
81
  - `followUps` (string) — Follow-up items for future milestones
79
82
  - `deviations` (string) — Deviations from the original plan
80
83
 
81
- 13. Do not commit manually — the system auto-commits your changes after this unit completes.
84
+ 14. Do not commit manually — the system auto-commits your changes after this unit completes.
82
85
  - Say: "Milestone {{milestoneId}} complete."
83
86
 
84
87
  **Important:** Do NOT skip code-change, success-criteria, or definition-of-done verification (steps 3-5). The summary must reflect verified outcomes. Verification failures block completion; there is no override. If a verification tool fails, errors, or returns unexpected output, treat it as failure.
@@ -29,7 +29,7 @@ Use `subagent` only for fresh-context review when useful: reviewer for cross-cut
29
29
  7. If requirement status changed, call `gsd_requirement_update`; do not write `.gsd/REQUIREMENTS.md` directly.
30
30
  8. Prepare `gsd_slice_complete` content with camelCase fields `milestoneId`, `sliceId`, `sliceTitle`, `oneLiner`, `narrative`, `verification`, and `uatContent`.
31
31
  9. Draft concrete UAT with preconditions, numbered steps, expected outcomes, edge cases, UAT Type, and Not Proven By This UAT.
32
- 10. Review task summaries for DECISIONS.md and KNOWLEDGE.md-worthy decisions, patterns, and gotchas. Capture significant items with `capture_thought`; do not append knowledge files directly.
32
+ 10. Review the inlined task-summary excerpts for DECISIONS.md and KNOWLEDGE.md-worthy decisions, patterns, and gotchas. Read full `*-SUMMARY.md` files only when an excerpt is absent, truncated, or lacks the specific evidence needed for the slice narrative. Capture significant items with `capture_thought`; do not append knowledge files directly.
33
33
  11. Call `gsd_slice_complete`. The DB-backed tool is the canonical write path. Do **not** manually write `{{sliceSummaryPath}}`. Do **not** manually write `{{sliceUatPath}}`. Do not edit roadmap checkboxes; the tool renders files and updates projections.
34
34
  12. Do not run git commands.
35
35
  13. Update `.gsd/PROJECT.md` with a full `write` only if the current project state needs refresh.