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
@@ -11,7 +11,12 @@ import type { ExtensionAPI, ExtensionContext } from "@gsd/pi-coding-agent";
11
11
  import type { AutoSession } from "./session.js";
12
12
  import { NEW_SESSION_TIMEOUT_MS } from "./session.js";
13
13
  import type { UnitResult } from "./types.js";
14
- import { _clearCurrentResolve, _setCurrentResolve, _setSessionSwitchInFlight } from "./resolve.js";
14
+ import {
15
+ _clearCurrentResolve,
16
+ _consumePendingSwitchCancellation,
17
+ _setCurrentResolve,
18
+ _setSessionSwitchInFlight,
19
+ } from "./resolve.js";
15
20
  import {
16
21
  getCurrentTurnGeneration,
17
22
  runWithTurnGeneration,
@@ -43,44 +48,22 @@ export async function runUnit(
43
48
  ): Promise<UnitResult> {
44
49
  debugLog("runUnit", { phase: "start", unitType, unitId });
45
50
 
46
- // Ensure cwd matches basePath BEFORE newSession() captures it. The new
47
- // session reads process.cwd() during construction to anchor its tool
48
- // runtime and system prompt; if cwd has drifted (async_bash, background
49
- // jobs, prior unit cleanup), the session would otherwise be rooted to
50
- // the wrong directory. Must be synchronous — no awaits between chdir
51
- // and newSession (#1389, #4762 follow-up).
52
- try {
53
- if (process.cwd() !== s.basePath) {
54
- process.chdir(s.basePath);
55
- }
56
- } catch (e) {
57
- const msg = `Failed to chdir to basePath before newSession (basePath: ${s.basePath}): ${String(e)}`;
58
- logWarning("engine", msg, { basePath: s.basePath, error: String(e) });
59
- return {
60
- status: "cancelled",
61
- errorContext: {
62
- message: msg,
63
- category: "session-failed",
64
- isTransient: true,
65
- },
66
- };
67
- }
68
-
69
51
  // ── Session creation with timeout ──
70
52
  debugLog("runUnit", { phase: "session-create", unitType, unitId });
71
53
 
72
54
  let sessionResult: { cancelled: boolean };
73
55
  let sessionTimeoutHandle: ReturnType<typeof setTimeout> | undefined;
74
56
  const mySessionSwitchGeneration = ++sessionSwitchGeneration;
75
- // #3731: Cancellation controller for newSession(). When the session-creation
76
- // timeout fires, we abort this controller so that the still-in-flight
77
- // newSession() discards itself after await this.abort() completes, preventing
78
- // it from capturing the (now-root) process.cwd() and rebuilding the tool
79
- // runtime with the wrong cwd.
57
+ // #3731: Cancellation controller for newSession(). When session creation
58
+ // times out, abort before a late session switch can rebuild the tool runtime
59
+ // against a stale workspace root.
80
60
  const sessionAbortController = new AbortController();
81
61
  _setSessionSwitchInFlight(true);
82
62
  try {
83
- const sessionPromise = s.cmdCtx!.newSession({ abortSignal: sessionAbortController.signal }).finally(() => {
63
+ const sessionPromise = s.cmdCtx!.newSession({
64
+ abortSignal: sessionAbortController.signal,
65
+ workspaceRoot: s.basePath,
66
+ }).finally(() => {
84
67
  if (sessionSwitchGeneration === mySessionSwitchGeneration) {
85
68
  _setSessionSwitchInFlight(false);
86
69
  }
@@ -97,6 +80,7 @@ export async function runUnit(
97
80
  sessionResult = await Promise.race([sessionPromise, timeoutPromise]);
98
81
  } catch (sessionErr) {
99
82
  if (sessionTimeoutHandle) clearTimeout(sessionTimeoutHandle);
83
+ _consumePendingSwitchCancellation();
100
84
  const msg =
101
85
  sessionErr instanceof Error ? sessionErr.message : String(sessionErr);
102
86
  debugLog("runUnit", {
@@ -110,17 +94,20 @@ export async function runUnit(
110
94
  if (sessionTimeoutHandle) clearTimeout(sessionTimeoutHandle);
111
95
 
112
96
  if (sessionResult.cancelled) {
97
+ _consumePendingSwitchCancellation();
113
98
  debugLog("runUnit-session-timeout", { unitType, unitId });
114
99
  return { status: "cancelled", errorContext: { message: "Session creation timed out", category: "timeout", isTransient: true } };
115
100
  }
116
101
 
117
102
  if (!s.active) {
103
+ _consumePendingSwitchCancellation();
118
104
  return { status: "cancelled" };
119
105
  }
120
106
 
121
107
  if (s.currentUnitModel && typeof pi.setModel === "function") {
122
108
  const restored = await pi.setModel(s.currentUnitModel, { persist: false });
123
109
  if (!restored) {
110
+ _consumePendingSwitchCancellation();
124
111
  const message =
125
112
  `Failed to restore configured model ${s.currentUnitModel.provider}/${s.currentUnitModel.id} after session creation`;
126
113
  ctx.ui.notify(
@@ -145,6 +132,14 @@ export async function runUnit(
145
132
  const unitPromise = new Promise<UnitResult>((resolve) => {
146
133
  _setCurrentResolve(resolve);
147
134
  });
135
+ const pendingSwitchCancellation = _consumePendingSwitchCancellation();
136
+ if (pendingSwitchCancellation) {
137
+ _clearCurrentResolve();
138
+ return {
139
+ status: "cancelled",
140
+ ...(pendingSwitchCancellation.errorContext ? { errorContext: pendingSwitchCancellation.errorContext } : {}),
141
+ };
142
+ }
148
143
 
149
144
  // ── Provider request-readiness pre-check (#4555) ──
150
145
  // Verify the provider can accept requests before dispatching. If the token
@@ -178,6 +178,13 @@ export class AutoSession {
178
178
  * stale context bleeding into unrelated slices.
179
179
  */
180
180
  lastPreExecFailure: PreExecFailure | null = null;
181
+ /**
182
+ * Tracks how many consecutive times each slice unit has failed pre-execution
183
+ * checks. Keyed by unitId (e.g. "M001/S01"). Used to break the infinite
184
+ * plan-slice → pre-exec fail → re-dispatch loop when the planner cannot fix
185
+ * the issues after MAX_PRE_EXEC_RETRIES re-attempts.
186
+ */
187
+ readonly preExecRetryCount: Map<string, number> = new Map();
181
188
 
182
189
  // ── Tool invocation errors (#2883) ──────────────────────────────────
183
190
  /** Set when a GSD tool execution ends with isError due to malformed/truncated
@@ -343,6 +350,7 @@ export class AutoSession {
343
350
  this.rewriteAttemptCount = 0;
344
351
  this.consecutiveCompleteBootstraps = 0;
345
352
  this.lastPreExecFailure = null;
353
+ this.preExecRetryCount.clear();
346
354
  this.lastToolInvocationError = null;
347
355
  this.lastUnitAgentEndMessages = null;
348
356
  this.lastGitActionFailure = null;
@@ -31,7 +31,6 @@ import { loadEffectiveGSDPreferences } from "./preferences.js";
31
31
  import type { MinimalModelRegistry } from "./context-budget.js";
32
32
  import { pauseAuto } from "./auto.js";
33
33
  import { resolveCanonicalMilestoneRoot } from "./worktree-manager.js";
34
- import { logWarning } from "./workflow-logger.js";
35
34
  import {
36
35
  getWorkflowTransportSupportError,
37
36
  getRequiredWorkflowToolsForAutoUnit,
@@ -290,38 +289,13 @@ export async function dispatchDirectPhase(
290
289
 
291
290
  ctx.ui.notify(`Dispatching ${unitType} for ${unitId}...`, "info");
292
291
 
293
- const originalCwd = process.cwd();
294
-
295
- try {
296
- // Ensure cwd matches dispatchBase BEFORE newSession() captures it. Synchronous —
297
- // no awaits between chdir and newSession.
298
- try {
299
- if (process.cwd() !== dispatchBase) {
300
- process.chdir(dispatchBase);
301
- }
302
- } catch (err) {
303
- const msg = `Failed to chdir before direct-dispatch newSession (basePath: ${dispatchBase}): ${err instanceof Error ? err.message : String(err)}`;
304
- logWarning("engine", msg, { file: "auto-direct-dispatch.ts", basePath: dispatchBase, error: err instanceof Error ? err.message : String(err) });
305
- ctx.ui.notify(`${msg}. Cancelling dispatch to avoid running in the wrong directory.`, "error");
306
- return;
307
- }
308
-
309
- const result = await ctx.newSession();
310
- if (result.cancelled) {
311
- ctx.ui.notify("Session creation cancelled.", "warning");
312
- return;
313
- }
314
- pi.sendMessage(
315
- { customType: "gsd-dispatch", content: prompt, display: false },
316
- { triggerTurn: true },
317
- );
318
- } finally {
319
- try {
320
- if (process.cwd() !== originalCwd) {
321
- process.chdir(originalCwd);
322
- }
323
- } catch (err) {
324
- logWarning("engine", `Failed to restore cwd after direct dispatch: ${err instanceof Error ? err.message : String(err)}`, { file: "auto-direct-dispatch.ts", basePath: originalCwd });
325
- }
292
+ const result = await ctx.newSession({ workspaceRoot: dispatchBase });
293
+ if (result.cancelled) {
294
+ ctx.ui.notify("Session creation cancelled.", "warning");
295
+ return;
326
296
  }
297
+ pi.sendMessage(
298
+ { customType: "gsd-dispatch", content: prompt, display: false },
299
+ { triggerTurn: true },
300
+ );
327
301
  }
@@ -938,6 +938,22 @@ export const DISPATCH_RULES: DispatchRule[] = [
938
938
  const unitId = `${mid}/${sid}`;
939
939
  let priorPreExecFailure: { blockingFindings: string[]; verdictExcerpt: string } | undefined;
940
940
  if (session?.lastPreExecFailure?.unitId === unitId) {
941
+ // Circuit breaker: stop re-dispatching after 2 failed retries. The
942
+ // planner has had multiple attempts with injected failure context and
943
+ // still cannot produce a valid plan — human review is required.
944
+ const MAX_PRE_EXEC_RETRIES = 2;
945
+ const retryCount = session.preExecRetryCount?.get(unitId) ?? 0;
946
+ if (retryCount >= MAX_PRE_EXEC_RETRIES) {
947
+ const findings = session.lastPreExecFailure.blockingFindings.join("; ");
948
+ session.lastPreExecFailure = null;
949
+ session.preExecRetryCount?.delete(unitId);
950
+ return {
951
+ action: "stop",
952
+ reason: `Pre-execution checks failed ${retryCount} times for ${unitId} — manual intervention required. Blocking findings: ${findings}. Fix the plan manually, then run /gsd auto to resume.`,
953
+ level: "error",
954
+ matchedRule: "planning → plan-slice",
955
+ };
956
+ }
941
957
  priorPreExecFailure = {
942
958
  blockingFindings: session.lastPreExecFailure.blockingFindings,
943
959
  verdictExcerpt: session.lastPreExecFailure.verdictExcerpt,
@@ -1320,8 +1320,11 @@ export async function postUnitPostVerification(pctx: PostUnitContext): Promise<"
1320
1320
 
1321
1321
  const strictMode = prefs?.enhanced_verification_strict === true;
1322
1322
 
1323
- // Run pre-execution checks
1324
- const result: PreExecutionResult = await runPreExecutionChecks(tasks, s.basePath);
1323
+ // Run pre-execution checks against the canonical project root. In
1324
+ // worktree isolation, s.basePath can point at a metadata-only worktree,
1325
+ // while source files remain under the project root.
1326
+ const preExecutionBasePath = s.canonicalProjectRoot;
1327
+ const result: PreExecutionResult = await runPreExecutionChecks(tasks, preExecutionBasePath);
1325
1328
 
1326
1329
  // Log summary to stderr in existing verification output format
1327
1330
  const emoji = result.status === "pass" ? "✅" : result.status === "warn" ? "⚠️" : "❌";
@@ -1338,12 +1341,12 @@ export async function postUnitPostVerification(pctx: PostUnitContext): Promise<"
1338
1341
  }
1339
1342
 
1340
1343
  // Write evidence JSON to slice artifacts directory
1341
- const slicePath = resolveSlicePath(s.basePath, mid, sid);
1344
+ const slicePath = resolveSlicePath(preExecutionBasePath, mid, sid);
1342
1345
  const evidenceFileName = `${sid}-PRE-EXEC-VERIFY.json`;
1343
1346
  let evidencePath = join(".gsd", "milestones", mid, "slices", sid, evidenceFileName);
1344
1347
  if (slicePath) {
1345
1348
  writePreExecutionEvidence(result, slicePath, mid, sid);
1346
- evidencePath = relative(s.basePath, join(slicePath, evidenceFileName)) || evidenceFileName;
1349
+ evidencePath = relative(preExecutionBasePath, join(slicePath, evidenceFileName)) || evidenceFileName;
1347
1350
  }
1348
1351
 
1349
1352
  if (uokFlags.gates) {
@@ -1398,6 +1401,9 @@ export async function postUnitPostVerification(pctx: PostUnitContext): Promise<"
1398
1401
  ),
1399
1402
  verdictExcerpt: `status=${result.status}; ${blockingCount} blocking issue${blockingCount === 1 ? "" : "s"} detected`,
1400
1403
  };
1404
+ // Track consecutive pre-exec failures per slice for loop detection.
1405
+ const retryKey = currentUnit.id;
1406
+ s.preExecRetryCount.set(retryKey, (s.preExecRetryCount.get(retryKey) ?? 0) + 1);
1401
1407
  preExecPauseNeeded = true;
1402
1408
  } else if (result.status === "warn") {
1403
1409
  ctx.ui.notify(
@@ -1414,10 +1420,18 @@ export async function postUnitPostVerification(pctx: PostUnitContext): Promise<"
1414
1420
  ),
1415
1421
  verdictExcerpt: `status=${result.status} (strict mode); ${warnChecks.length} warning${warnChecks.length === 1 ? "" : "s"} treated as blocking`,
1416
1422
  };
1423
+ const retryKey = currentUnit.id;
1424
+ s.preExecRetryCount.set(retryKey, (s.preExecRetryCount.get(retryKey) ?? 0) + 1);
1417
1425
  preExecPauseNeeded = true;
1418
1426
  }
1419
1427
  }
1420
1428
 
1429
+ // Reset the retry counter when checks pass — a successful re-plan
1430
+ // should not carry over a stale failure count into future slices.
1431
+ if (result.status === "pass") {
1432
+ s.preExecRetryCount.delete(currentUnit.id);
1433
+ }
1434
+
1421
1435
  debugLog("postUnitPostVerification", {
1422
1436
  phase: "pre-execution-checks",
1423
1437
  status: result.status,
@@ -35,6 +35,7 @@ import {
35
35
  import { formatDecisionsCompact, formatRequirementsCompact } from "./structured-data-formatter.js";
36
36
  import { readPhaseAnchor, formatAnchorForPrompt } from "./phase-anchor.js";
37
37
  import { composeContextModeInstructions, composeInlinedContext, type ArtifactResolver, type ContextModeRenderMode } from "./unit-context-composer.js";
38
+ import { readCompactionSnapshot } from "./compaction-snapshot.js";
38
39
  import { logWarning } from "./workflow-logger.js";
39
40
  import { inlineGraphSubgraph } from "./graph-context.js";
40
41
  import { buildExtractionStepsBlock } from "./commands-extract-learnings.js";
@@ -44,12 +45,12 @@ import { classifyProject, type ProjectClassification } from "./detection.js";
44
45
  // ─── Preamble Cap ─────────────────────────────────────────────────────────────
45
46
 
46
47
  /**
47
- * Historical static ceiling for the preamble cap. Kept as an upper bound even
48
+ * Static ceiling for the preamble cap. Kept as an upper bound even
48
49
  * after context-window-aware sizing so large-window users don't suddenly see
49
- * 10× looser caps than before. Small-window users get a tighter cap derived
50
+ * 10× looser caps than needed. Small-window users get a tighter cap derived
50
51
  * from their configured executor window.
51
52
  */
52
- const MAX_PREAMBLE_CHARS = 30_000;
53
+ const MAX_PREAMBLE_CHARS = 20_000;
53
54
 
54
55
  /**
55
56
  * Resolve prompt budgets from the configured executor context window.
@@ -184,8 +185,8 @@ function formatCloseoutReviewInstructions(validationContent: string | null, vali
184
185
  }
185
186
 
186
187
  function capPreamble(preamble: string): string {
187
- // Cap inlined context at min(historical 30K ceiling, scaled inline budget).
188
- // The ceiling preserves pre-fix behavior for large-window users; the scaled
188
+ // Cap inlined context at min(static ceiling, scaled inline budget).
189
+ // The ceiling bounds repeated auto prompt payloads; the scaled
189
190
  // budget tightens the cap for small-window users whose true safe limit is
190
191
  // below 30K. `computeBudgets` allocates 40% of total chars to inline context.
191
192
  const budget = Math.min(MAX_PREAMBLE_CHARS, resolvePromptBudgets().inlineContextBudgetChars);
@@ -205,13 +206,28 @@ function renderContextModeForPrompt(
205
206
  });
206
207
  }
207
208
 
209
+ function renderContextModeBlockForPrompt(
210
+ unitType: string,
211
+ base: string,
212
+ renderMode: ContextModeRenderMode = "standalone",
213
+ ): string {
214
+ const contextMode = renderContextModeForPrompt(unitType, base, renderMode);
215
+ if (!contextMode) return "";
216
+ if (renderMode === "nested") return contextMode;
217
+
218
+ const snapshot = readCompactionSnapshot(base);
219
+ if (!snapshot?.trim()) return contextMode;
220
+
221
+ return `${contextMode}\n\n## Context Snapshot\nSource: \`.gsd/last-snapshot.md\`\n\n${snapshot.trimEnd()}`;
222
+ }
223
+
208
224
  function prependContextModeToBlock(
209
225
  unitType: string,
210
226
  base: string,
211
227
  block: string,
212
228
  renderMode: ContextModeRenderMode = "standalone",
213
229
  ): string {
214
- const contextMode = renderContextModeForPrompt(unitType, base, renderMode);
230
+ const contextMode = renderContextModeBlockForPrompt(unitType, base, renderMode);
215
231
  if (!contextMode) return block;
216
232
  if (!block.trim()) return contextMode;
217
233
  return `${contextMode}\n\n${block}`;
@@ -620,10 +636,83 @@ export async function buildSliceSummaryExcerpt(
620
636
  return lines.join("\n");
621
637
  } catch {
622
638
  // Defensive — any parse failure falls back to full inline.
623
- return `### ${sid} Summary\nSource: \`${relPath}\`\n\n${content.trim()}`;
639
+ return `### ${sid} Summary\nSource: \`${relPath}\`\n\n${capMalformedSummary(content, relPath)}`;
624
640
  }
625
641
  }
626
642
 
643
+ export async function buildTaskSummaryExcerpt(
644
+ absPath: string | null, relPath: string, tid: string, options?: { blocker?: boolean },
645
+ ): Promise<string> {
646
+ const label = options?.blocker ? "Blocker Task Summary" : "Task Summary";
647
+ const header = `### ${label}: ${tid} (excerpt)\nSource: \`${relPath}\``;
648
+ const content = absPath ? await loadFile(absPath) : null;
649
+ if (!content) {
650
+ return `${header}\n\n_(not found — file does not exist yet)_`;
651
+ }
652
+
653
+ try {
654
+ const s = parseSummary(content);
655
+ if (!s.frontmatter.id) {
656
+ return `### ${label}: ${tid}\nSource: \`${relPath}\`\n\n${capMalformedSummary(content, relPath)}`;
657
+ }
658
+
659
+ const lines: string[] = [header, ""];
660
+ if (s.title) lines.push(`**Title:** ${s.title}`);
661
+ if (s.oneLiner) lines.push(`**One-liner:** ${s.oneLiner}`);
662
+ if (s.frontmatter.verification_result) {
663
+ lines.push(`**Verification:** \`${s.frontmatter.verification_result}\``);
664
+ }
665
+ lines.push(`**Blocker discovered:** ${s.frontmatter.blocker_discovered ? "yes — read full summary if blocker details are insufficient" : "no"}`);
666
+ if (s.frontmatter.provides.length > 0) lines.push(`**Provides:** ${s.frontmatter.provides.slice(0, 4).join("; ")}`);
667
+ if (s.frontmatter.key_decisions.length > 0) lines.push(`**Key decisions:** ${s.frontmatter.key_decisions.slice(0, 4).join("; ")}`);
668
+ if (s.frontmatter.patterns_established.length > 0) lines.push(`**Patterns established:** ${s.frontmatter.patterns_established.slice(0, 4).join("; ")}`);
669
+ if (s.frontmatter.key_files.length > 0) {
670
+ const files = s.frontmatter.key_files.slice(0, 6);
671
+ const more = s.frontmatter.key_files.length > files.length ? ` (+${s.frontmatter.key_files.length - files.length} more)` : "";
672
+ lines.push(`**Key files:** ${files.join(", ")}${more}`);
673
+ }
674
+
675
+ const SECTION_CAP_CHARS = 500;
676
+ const capSection = (body: string): string => {
677
+ const trimmed = body.trim();
678
+ if (trimmed.length <= SECTION_CAP_CHARS) return trimmed;
679
+ return `${trimmed.slice(0, SECTION_CAP_CHARS)}\n… (truncated — see full \`${relPath}\`)`;
680
+ };
681
+
682
+ const verification = extractMarkdownSection(content, "Verification");
683
+ const diagnostics = extractMarkdownSection(content, "Diagnostics");
684
+ const knownIssues = extractMarkdownSection(content, "Known Issues");
685
+
686
+ if (verification && verification.trim()) {
687
+ lines.push("", "#### Verification", capSection(verification));
688
+ }
689
+ if (diagnostics && diagnostics.trim()) {
690
+ lines.push("", "#### Diagnostics", capSection(diagnostics));
691
+ }
692
+ if (s.deviations && s.deviations.trim()) {
693
+ lines.push("", "#### Deviations", capSection(s.deviations));
694
+ }
695
+ if (knownIssues && knownIssues.trim()) {
696
+ lines.push("", "#### Known issues", capSection(knownIssues));
697
+ }
698
+
699
+ lines.push(
700
+ "",
701
+ `> **On-demand:** read \`${relPath}\` only when this excerpt is absent/truncated or you need fuller blocker, implementation, or file-change evidence.`,
702
+ );
703
+ return lines.join("\n");
704
+ } catch {
705
+ return `### ${label}: ${tid}\nSource: \`${relPath}\`\n\n${capMalformedSummary(content, relPath)}`;
706
+ }
707
+ }
708
+
709
+ function capMalformedSummary(content: string, relPath: string): string {
710
+ const trimmed = content.trim();
711
+ const limit = 1_500;
712
+ if (trimmed.length <= limit) return trimmed;
713
+ return `${trimmed.slice(0, limit).trimEnd()}\n\n[Truncated malformed summary — read \`${relPath}\` for full details.]`;
714
+ }
715
+
627
716
  /**
628
717
  * Load and inline dependency slice summaries (full content, not just paths).
629
718
  */
@@ -898,7 +987,7 @@ export async function inlineKnowledgeScoped(
898
987
  * plan-milestone, complete-slice, complete-milestone, validate-milestone,
899
988
  * reassess-roadmap) previously injected the full KNOWLEDGE.md (~226KB for a
900
989
  * real project) on every invocation. This helper scopes by caller-supplied
901
- * keywords and caps the payload at `maxChars` (default 30,000 chars).
990
+ * keywords and caps the payload at `maxChars` (default 12,000 chars).
902
991
  *
903
992
  * Returns null when no KNOWLEDGE.md exists or no entries match any keyword.
904
993
  */
@@ -907,7 +996,7 @@ export async function inlineKnowledgeBudgeted(
907
996
  keywords: string[],
908
997
  options?: { maxChars?: number },
909
998
  ): Promise<string | null> {
910
- const DEFAULT_MAX_CHARS = 30_000;
999
+ const DEFAULT_MAX_CHARS = 12_000;
911
1000
  const HARD_MAX_CHARS = 100_000;
912
1001
  const raw = Number(options?.maxChars ?? DEFAULT_MAX_CHARS);
913
1002
  const maxChars = Number.isFinite(raw)
@@ -2069,8 +2158,17 @@ export async function buildPlanSlicePrompt(
2069
2158
  `The previous plan-slice attempt was blocked by pre-execution validation.\n` +
2070
2159
  `Gate verdict: ${verdictExcerpt}\n\n` +
2071
2160
  `Blocked references that must be resolved in this plan:\n${findingsList}\n\n` +
2072
- `Revise the plan so that every reference listed above is satisfied before execution begins. ` +
2073
- `Do not reproduce the same file paths, package names, or task ordering that caused these failures.`,
2161
+ `**How to fix each type of issue:**\n` +
2162
+ `- **"[file] X doesn't exist and isn't created by prior or same-task outputs"**: ` +
2163
+ `Either (a) add an earlier task that creates X on disk before the task that needs it, ` +
2164
+ `or (b) if this task IS the one that creates X, move X from inputs to expected_output. ` +
2165
+ `Do NOT put X in a task's expected_output if that task only reads or verifies X — only tasks that actually write X to disk should list it in expected_output.\n` +
2166
+ `- **"[file] X: Task T_early reads X but it's created by task T_late (sequence violation)"**: ` +
2167
+ `Either (a) reorder tasks so T_late (the creator) runs before T_early (the reader), ` +
2168
+ `or (b) if T_late doesn't actually create X (it only reads/tests it), remove X from T_late's expected_output entirely.\n` +
2169
+ `- **"[package] P not found on npm"**: Either remove the npm install for P, or use the correct package name.\n\n` +
2170
+ `Every file listed in a task's inputs must either exist on disk already or appear in an earlier task's expected_output. ` +
2171
+ `A task's expected_output must only list files it actually writes to disk.`,
2074
2172
  );
2075
2173
  }
2076
2174
  return renderSlicePrompt({
@@ -2353,10 +2451,9 @@ export async function buildCompleteSlicePrompt(
2353
2451
  const blocks: string[] = [];
2354
2452
  for (const file of summaryFiles) {
2355
2453
  const absPath = join(tDir, file);
2356
- const content = await loadFile(absPath);
2357
- if (!content) continue;
2358
2454
  const relPath = `${sRel}/tasks/${file}`;
2359
- blocks.push(`### Task Summary: ${file.replace(/-SUMMARY\.md$/i, "")}\nSource: \`${relPath}\`\n\n${content.trim()}`);
2455
+ const taskId = file.replace(/-SUMMARY\.md$/i, "");
2456
+ blocks.push(await buildTaskSummaryExcerpt(absPath, relPath, taskId));
2360
2457
  }
2361
2458
  return blocks.length > 0 ? blocks.join("\n\n---\n\n") : null;
2362
2459
  }
@@ -2733,7 +2830,7 @@ export async function buildReplanSlicePrompt(
2733
2830
  const relPath = `${sRel}/tasks/${file}`;
2734
2831
  if (summary.frontmatter.blocker_discovered) {
2735
2832
  blockerTaskId = summary.frontmatter.id || file.replace(/-SUMMARY\.md$/i, "");
2736
- inlined.push(`### Blocker Task Summary: ${blockerTaskId}\nSource: \`${relPath}\`\n\n${content.trim()}`);
2833
+ inlined.push(await buildTaskSummaryExcerpt(absPath, relPath, blockerTaskId, { blocker: true }));
2737
2834
  }
2738
2835
  }
2739
2836
  }
@@ -67,6 +67,60 @@ export {
67
67
 
68
68
  // ─── Artifact Resolution & Verification ───────────────────────────────────────
69
69
 
70
+ export type ArtifactRecoveryDbRefreshResult =
71
+ | { ok: true }
72
+ | { ok: false; fatal: boolean; message: string; reason: string };
73
+
74
+ export function refreshRecoveryDbForArtifact(
75
+ unitType: string,
76
+ unitId: string,
77
+ ): ArtifactRecoveryDbRefreshResult {
78
+ if (unitType !== "plan-slice" && unitType !== "execute-task") return { ok: true };
79
+ if (!isDbAvailable()) return { ok: true };
80
+
81
+ if (!refreshOpenDatabaseFromDisk()) {
82
+ return {
83
+ ok: false,
84
+ fatal: unitType === "execute-task",
85
+ reason: `${unitType}-db-refresh-failed`,
86
+ message: `Stuck recovery found ${unitType} ${unitId} artifacts, but the DB refresh failed.`,
87
+ };
88
+ }
89
+
90
+ if (unitType !== "execute-task") return { ok: true };
91
+
92
+ const { milestone: mid, slice: sid, task: tid } = parseUnitId(unitId);
93
+ if (!mid || !sid || !tid) {
94
+ return {
95
+ ok: false,
96
+ fatal: true,
97
+ reason: "execute-task-invalid-unit-id",
98
+ message: `Stuck recovery found execute-task ${unitId} artifacts, but the unit id could not be parsed for DB verification.`,
99
+ };
100
+ }
101
+
102
+ const task = getTask(mid, sid, tid);
103
+ if (!task) {
104
+ return {
105
+ ok: false,
106
+ fatal: true,
107
+ reason: "execute-task-artifact-db-missing",
108
+ message: `Stuck recovery found execute-task ${unitId} artifacts, but no matching DB task row exists after refresh.`,
109
+ };
110
+ }
111
+
112
+ if (!isClosedStatus(task.status)) {
113
+ return {
114
+ ok: false,
115
+ fatal: true,
116
+ reason: "execute-task-artifact-db-mismatch",
117
+ message: `Stuck recovery found execute-task ${unitId} artifacts, but the DB task status is still '${task.status}' after refresh.`,
118
+ };
119
+ }
120
+
121
+ return { ok: true };
122
+ }
123
+
70
124
  function hasCapturedWorkflowPrefs(base: string): boolean {
71
125
  const prefsPath = resolveExpectedArtifactPath("workflow-preferences", "WORKFLOW-PREFS", base);
72
126
  if (!prefsPath || !existsSync(prefsPath)) return false;