@therocketcode/gsd-core 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (568) hide show
  1. package/.claude-plugin/plugin.json +23 -0
  2. package/GEMINI.md +53 -0
  3. package/LICENSE +21 -0
  4. package/README.ja-JP.md +125 -0
  5. package/README.ko-KR.md +125 -0
  6. package/README.md +144 -0
  7. package/README.pt-BR.md +125 -0
  8. package/README.zh-CN.md +125 -0
  9. package/agents/gsd-advisor-researcher.md +108 -0
  10. package/agents/gsd-ai-researcher.md +114 -0
  11. package/agents/gsd-assumptions-analyzer.md +105 -0
  12. package/agents/gsd-code-fixer.md +668 -0
  13. package/agents/gsd-code-reviewer.md +387 -0
  14. package/agents/gsd-codebase-mapper.md +853 -0
  15. package/agents/gsd-debug-session-manager.md +314 -0
  16. package/agents/gsd-debugger.md +1452 -0
  17. package/agents/gsd-doc-classifier.md +168 -0
  18. package/agents/gsd-doc-synthesizer.md +204 -0
  19. package/agents/gsd-doc-verifier.md +217 -0
  20. package/agents/gsd-doc-writer.md +616 -0
  21. package/agents/gsd-domain-researcher.md +147 -0
  22. package/agents/gsd-eval-auditor.md +191 -0
  23. package/agents/gsd-eval-planner.md +154 -0
  24. package/agents/gsd-executor.md +785 -0
  25. package/agents/gsd-framework-selector.md +160 -0
  26. package/agents/gsd-integration-checker.md +470 -0
  27. package/agents/gsd-intel-updater.md +342 -0
  28. package/agents/gsd-nyquist-auditor.md +203 -0
  29. package/agents/gsd-pattern-mapper.md +335 -0
  30. package/agents/gsd-phase-researcher.md +867 -0
  31. package/agents/gsd-plan-checker.md +978 -0
  32. package/agents/gsd-planner.md +1204 -0
  33. package/agents/gsd-project-researcher.md +611 -0
  34. package/agents/gsd-research-synthesizer.md +259 -0
  35. package/agents/gsd-roadmapper.md +688 -0
  36. package/agents/gsd-security-auditor.md +155 -0
  37. package/agents/gsd-ui-auditor.md +495 -0
  38. package/agents/gsd-ui-checker.md +309 -0
  39. package/agents/gsd-ui-researcher.md +374 -0
  40. package/agents/gsd-user-profiler.md +171 -0
  41. package/agents/gsd-verifier.md +923 -0
  42. package/assets/gsd-logo-2000-transparent.png +0 -0
  43. package/assets/gsd-logo-2000-transparent.svg +17 -0
  44. package/assets/gsd-logo-2000.png +0 -0
  45. package/assets/gsd-logo-2000.svg +21 -0
  46. package/assets/terminal.svg +68 -0
  47. package/bin/install.js +12726 -0
  48. package/bin/lib/ui-safety-gate.cjs +107 -0
  49. package/commands/gsd/add-tests.md +42 -0
  50. package/commands/gsd/ai-integration-phase.md +37 -0
  51. package/commands/gsd/audit-fix.md +34 -0
  52. package/commands/gsd/audit-milestone.md +37 -0
  53. package/commands/gsd/audit-uat.md +24 -0
  54. package/commands/gsd/autonomous.md +48 -0
  55. package/commands/gsd/capture.md +62 -0
  56. package/commands/gsd/cleanup.md +24 -0
  57. package/commands/gsd/code-review.md +59 -0
  58. package/commands/gsd/complete-milestone.md +143 -0
  59. package/commands/gsd/config.md +56 -0
  60. package/commands/gsd/debug.md +52 -0
  61. package/commands/gsd/discover-product.md +65 -0
  62. package/commands/gsd/discuss-phase.md +77 -0
  63. package/commands/gsd/docs-update.md +49 -0
  64. package/commands/gsd/eval-review.md +33 -0
  65. package/commands/gsd/execute-phase.md +66 -0
  66. package/commands/gsd/explore.md +27 -0
  67. package/commands/gsd/extract-learnings.md +23 -0
  68. package/commands/gsd/fast.md +31 -0
  69. package/commands/gsd/forensics.md +57 -0
  70. package/commands/gsd/graphify.md +204 -0
  71. package/commands/gsd/health.md +31 -0
  72. package/commands/gsd/help.md +28 -0
  73. package/commands/gsd/import.md +45 -0
  74. package/commands/gsd/inbox.md +39 -0
  75. package/commands/gsd/ingest-docs.md +42 -0
  76. package/commands/gsd/manager.md +45 -0
  77. package/commands/gsd/map-codebase.md +83 -0
  78. package/commands/gsd/milestone-summary.md +51 -0
  79. package/commands/gsd/model-domain.md +65 -0
  80. package/commands/gsd/mvp-phase.md +45 -0
  81. package/commands/gsd/new-milestone.md +45 -0
  82. package/commands/gsd/new-project.md +47 -0
  83. package/commands/gsd/ns-context.md +23 -0
  84. package/commands/gsd/ns-ideate.md +24 -0
  85. package/commands/gsd/ns-manage.md +29 -0
  86. package/commands/gsd/ns-project.md +22 -0
  87. package/commands/gsd/ns-review.md +26 -0
  88. package/commands/gsd/ns-workflow.md +28 -0
  89. package/commands/gsd/pause-work.md +43 -0
  90. package/commands/gsd/phase.md +56 -0
  91. package/commands/gsd/plan-phase.md +64 -0
  92. package/commands/gsd/plan-review-convergence.md +59 -0
  93. package/commands/gsd/pr-branch.md +26 -0
  94. package/commands/gsd/profile-user.md +46 -0
  95. package/commands/gsd/progress.md +48 -0
  96. package/commands/gsd/quick.md +174 -0
  97. package/commands/gsd/recommend-architecture.md +64 -0
  98. package/commands/gsd/resume-work.md +30 -0
  99. package/commands/gsd/review-backlog.md +63 -0
  100. package/commands/gsd/review.md +42 -0
  101. package/commands/gsd/secure-phase.md +36 -0
  102. package/commands/gsd/settings.md +29 -0
  103. package/commands/gsd/ship.md +24 -0
  104. package/commands/gsd/sketch.md +60 -0
  105. package/commands/gsd/spec-phase.md +63 -0
  106. package/commands/gsd/spike.md +57 -0
  107. package/commands/gsd/stats.md +20 -0
  108. package/commands/gsd/surface.md +155 -0
  109. package/commands/gsd/testing-strategy.md +65 -0
  110. package/commands/gsd/thread.md +24 -0
  111. package/commands/gsd/ui-phase.md +35 -0
  112. package/commands/gsd/ui-review.md +33 -0
  113. package/commands/gsd/ultraplan-phase.md +34 -0
  114. package/commands/gsd/undo.md +35 -0
  115. package/commands/gsd/update.md +49 -0
  116. package/commands/gsd/validate-phase.md +36 -0
  117. package/commands/gsd/verify-work.md +39 -0
  118. package/commands/gsd/workspace.md +52 -0
  119. package/commands/gsd/workstreams.md +70 -0
  120. package/gemini-extension.json +6 -0
  121. package/gsd-core/bin/check-latest-version.cjs +161 -0
  122. package/gsd-core/bin/gsd-tools.cjs +1928 -0
  123. package/gsd-core/bin/lib/active-workstream-store.cjs +291 -0
  124. package/gsd-core/bin/lib/adr-parser.cjs +399 -0
  125. package/gsd-core/bin/lib/agent-command-router.cjs +68 -0
  126. package/gsd-core/bin/lib/artifacts.cjs +51 -0
  127. package/gsd-core/bin/lib/audit.cjs +743 -0
  128. package/gsd-core/bin/lib/check-command-router.cjs +343 -0
  129. package/gsd-core/bin/lib/cjs-command-router-adapter.cjs +81 -0
  130. package/gsd-core/bin/lib/cli-exit.cjs +42 -0
  131. package/gsd-core/bin/lib/clock.cjs +95 -0
  132. package/gsd-core/bin/lib/clusters.cjs +132 -0
  133. package/gsd-core/bin/lib/code-review-flags.cjs +59 -0
  134. package/gsd-core/bin/lib/command-aliases.cjs +809 -0
  135. package/gsd-core/bin/lib/command-arg-projection.cjs +55 -0
  136. package/gsd-core/bin/lib/command-routing-hub.cjs +300 -0
  137. package/gsd-core/bin/lib/commands.cjs +1203 -0
  138. package/gsd-core/bin/lib/config-schema.cjs +29 -0
  139. package/gsd-core/bin/lib/config-types.cjs +19 -0
  140. package/gsd-core/bin/lib/config.cjs +738 -0
  141. package/gsd-core/bin/lib/configuration.cjs +239 -0
  142. package/gsd-core/bin/lib/context-utilization.cjs +48 -0
  143. package/gsd-core/bin/lib/core.cjs +2051 -0
  144. package/gsd-core/bin/lib/decisions.cjs +118 -0
  145. package/gsd-core/bin/lib/docs.cjs +252 -0
  146. package/gsd-core/bin/lib/drift.cjs +364 -0
  147. package/gsd-core/bin/lib/fallow-runner.cjs +115 -0
  148. package/gsd-core/bin/lib/frontmatter.cjs +442 -0
  149. package/gsd-core/bin/lib/gap-checker.cjs +257 -0
  150. package/gsd-core/bin/lib/graphify.cjs +496 -0
  151. package/gsd-core/bin/lib/gsd2-import.cjs +456 -0
  152. package/gsd-core/bin/lib/init-command-router.cjs +62 -0
  153. package/gsd-core/bin/lib/init.cjs +1815 -0
  154. package/gsd-core/bin/lib/install-profiles.cjs +584 -0
  155. package/gsd-core/bin/lib/installer-migration-authoring.cjs +122 -0
  156. package/gsd-core/bin/lib/installer-migration-report.cjs +350 -0
  157. package/gsd-core/bin/lib/installer-migrations/000-first-time-baseline.cjs +218 -0
  158. package/gsd-core/bin/lib/installer-migrations/001-legacy-orphan-files.cjs +48 -0
  159. package/gsd-core/bin/lib/installer-migrations/002-codex-legacy-hooks-json.cjs +94 -0
  160. package/gsd-core/bin/lib/installer-migrations/003-rename-get-shit-done-to-gsd-core.cjs +108 -0
  161. package/gsd-core/bin/lib/installer-migrations.cjs +823 -0
  162. package/gsd-core/bin/lib/intel.cjs +590 -0
  163. package/gsd-core/bin/lib/learnings.cjs +270 -0
  164. package/gsd-core/bin/lib/legacy-cleanup.cjs +253 -0
  165. package/gsd-core/bin/lib/milestone.cjs +373 -0
  166. package/gsd-core/bin/lib/model-catalog.cjs +154 -0
  167. package/gsd-core/bin/lib/model-profiles.cjs +24 -0
  168. package/gsd-core/bin/lib/observability/event.cjs +51 -0
  169. package/gsd-core/bin/lib/observability/logger.cjs +146 -0
  170. package/gsd-core/bin/lib/observability/redaction.cjs +48 -0
  171. package/gsd-core/bin/lib/package-identity.cjs +35 -0
  172. package/gsd-core/bin/lib/package-legitimacy.cjs +368 -0
  173. package/gsd-core/bin/lib/phase-command-router.cjs +189 -0
  174. package/gsd-core/bin/lib/phase-lifecycle.cjs +74 -0
  175. package/gsd-core/bin/lib/phase.cjs +1307 -0
  176. package/gsd-core/bin/lib/phases-command-router.cjs +43 -0
  177. package/gsd-core/bin/lib/plan-scan.cjs +91 -0
  178. package/gsd-core/bin/lib/planning-workspace.cjs +245 -0
  179. package/gsd-core/bin/lib/profile-output.cjs +1120 -0
  180. package/gsd-core/bin/lib/profile-pipeline.cjs +517 -0
  181. package/gsd-core/bin/lib/project-root.cjs +119 -0
  182. package/gsd-core/bin/lib/prompt-budget.cjs +305 -0
  183. package/gsd-core/bin/lib/research-provider.cjs +137 -0
  184. package/gsd-core/bin/lib/research-store.cjs +167 -0
  185. package/gsd-core/bin/lib/review-reviewer-selection.cjs +121 -0
  186. package/gsd-core/bin/lib/roadmap-command-router.cjs +166 -0
  187. package/gsd-core/bin/lib/roadmap-upgrade.cjs +476 -0
  188. package/gsd-core/bin/lib/roadmap.cjs +600 -0
  189. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +312 -0
  190. package/gsd-core/bin/lib/runtime-config-adapter-registry.cjs +56 -0
  191. package/gsd-core/bin/lib/runtime-homes.cjs +190 -0
  192. package/gsd-core/bin/lib/runtime-name-policy.cjs +96 -0
  193. package/gsd-core/bin/lib/runtime-slash.cjs +119 -0
  194. package/gsd-core/bin/lib/schema-detect.cjs +159 -0
  195. package/gsd-core/bin/lib/secrets.cjs +34 -0
  196. package/gsd-core/bin/lib/security.cjs +480 -0
  197. package/gsd-core/bin/lib/semver-compare.cjs +42 -0
  198. package/gsd-core/bin/lib/shell-command-projection.cjs +533 -0
  199. package/gsd-core/bin/lib/state-command-router.cjs +160 -0
  200. package/gsd-core/bin/lib/state-document.cjs +259 -0
  201. package/gsd-core/bin/lib/state.cjs +2010 -0
  202. package/gsd-core/bin/lib/surface.cjs +449 -0
  203. package/gsd-core/bin/lib/task-command-router.cjs +85 -0
  204. package/gsd-core/bin/lib/template.cjs +237 -0
  205. package/gsd-core/bin/lib/uat.cjs +297 -0
  206. package/gsd-core/bin/lib/ui-safety-gate.cjs +98 -0
  207. package/gsd-core/bin/lib/update-context.cjs +218 -0
  208. package/gsd-core/bin/lib/validate-command-router.cjs +91 -0
  209. package/gsd-core/bin/lib/validate.cjs +112 -0
  210. package/gsd-core/bin/lib/verification-command-router.cjs +31 -0
  211. package/gsd-core/bin/lib/verification.cjs +193 -0
  212. package/gsd-core/bin/lib/verify-command-router.cjs +44 -0
  213. package/gsd-core/bin/lib/verify.cjs +1451 -0
  214. package/gsd-core/bin/lib/workstream-inventory-builder.cjs +81 -0
  215. package/gsd-core/bin/lib/workstream-inventory.cjs +147 -0
  216. package/gsd-core/bin/lib/workstream-name-policy.cjs +91 -0
  217. package/gsd-core/bin/lib/workstream.cjs +380 -0
  218. package/gsd-core/bin/lib/worktree-base-ref.cjs +325 -0
  219. package/gsd-core/bin/lib/worktree-safety.cjs +943 -0
  220. package/gsd-core/bin/shared/config-defaults.manifest.json +98 -0
  221. package/gsd-core/bin/shared/config-schema.manifest.json +192 -0
  222. package/gsd-core/bin/shared/model-catalog.json +149 -0
  223. package/gsd-core/bin/shared/runtime-aliases.manifest.json +75 -0
  224. package/gsd-core/bin/verify-reapply-patches.cjs +349 -0
  225. package/gsd-core/contexts/dev.md +21 -0
  226. package/gsd-core/contexts/research.md +22 -0
  227. package/gsd-core/contexts/review.md +23 -0
  228. package/gsd-core/references/agent-contracts.md +79 -0
  229. package/gsd-core/references/ai-evals.md +156 -0
  230. package/gsd-core/references/ai-frameworks.md +186 -0
  231. package/gsd-core/references/architecture-decision.md +74 -0
  232. package/gsd-core/references/artifact-types.md +131 -0
  233. package/gsd-core/references/auth-in-tests.md +91 -0
  234. package/gsd-core/references/autonomous-smart-discuss.md +277 -0
  235. package/gsd-core/references/checkpoints.md +814 -0
  236. package/gsd-core/references/common-bug-patterns.md +114 -0
  237. package/gsd-core/references/context-budget.md +85 -0
  238. package/gsd-core/references/continuation-format.md +253 -0
  239. package/gsd-core/references/db-test-isolation.md +54 -0
  240. package/gsd-core/references/debugger-philosophy.md +76 -0
  241. package/gsd-core/references/decimal-phase-calculation.md +64 -0
  242. package/gsd-core/references/doc-conflict-engine.md +91 -0
  243. package/gsd-core/references/domain-modeling.md +80 -0
  244. package/gsd-core/references/domain-probes.md +125 -0
  245. package/gsd-core/references/e2e-tiering.md +35 -0
  246. package/gsd-core/references/execute-mvp-tdd.md +81 -0
  247. package/gsd-core/references/executor-examples.md +110 -0
  248. package/gsd-core/references/few-shot-examples/plan-checker.md +73 -0
  249. package/gsd-core/references/few-shot-examples/verifier.md +109 -0
  250. package/gsd-core/references/flaky-test-checklist.md +22 -0
  251. package/gsd-core/references/gate-prompts.md +100 -0
  252. package/gsd-core/references/gates.md +70 -0
  253. package/gsd-core/references/git-integration.md +298 -0
  254. package/gsd-core/references/git-planning-commit.md +40 -0
  255. package/gsd-core/references/ios-scaffold.md +123 -0
  256. package/gsd-core/references/mandatory-initial-read.md +2 -0
  257. package/gsd-core/references/model-profile-resolution.md +38 -0
  258. package/gsd-core/references/model-profiles.md +245 -0
  259. package/gsd-core/references/mvp-concepts.md +49 -0
  260. package/gsd-core/references/phase-argument-parsing.md +61 -0
  261. package/gsd-core/references/planner-antipatterns.md +89 -0
  262. package/gsd-core/references/planner-chunked.md +49 -0
  263. package/gsd-core/references/planner-gap-closure.md +62 -0
  264. package/gsd-core/references/planner-graphify-auto-update.md +67 -0
  265. package/gsd-core/references/planner-human-verify-mode.md +57 -0
  266. package/gsd-core/references/planner-interface-context.md +62 -0
  267. package/gsd-core/references/planner-load-graph-context.md +36 -0
  268. package/gsd-core/references/planner-mvp-mode.md +53 -0
  269. package/gsd-core/references/planner-reviews.md +39 -0
  270. package/gsd-core/references/planner-revision.md +87 -0
  271. package/gsd-core/references/planner-source-audit.md +73 -0
  272. package/gsd-core/references/planning-config.md +473 -0
  273. package/gsd-core/references/product-discovery.md +49 -0
  274. package/gsd-core/references/project-skills-discovery.md +19 -0
  275. package/gsd-core/references/questioning.md +162 -0
  276. package/gsd-core/references/realistic-test-data.md +44 -0
  277. package/gsd-core/references/research-documentation-lookup.md +29 -0
  278. package/gsd-core/references/research-philosophy.md +29 -0
  279. package/gsd-core/references/research-verification-protocol.md +27 -0
  280. package/gsd-core/references/revision-loop.md +97 -0
  281. package/gsd-core/references/scout-codebase.md +51 -0
  282. package/gsd-core/references/skeleton-template.md +48 -0
  283. package/gsd-core/references/sketch-interactivity.md +41 -0
  284. package/gsd-core/references/sketch-theme-system.md +94 -0
  285. package/gsd-core/references/sketch-tooling.md +45 -0
  286. package/gsd-core/references/sketch-variant-patterns.md +81 -0
  287. package/gsd-core/references/spidr-splitting.md +69 -0
  288. package/gsd-core/references/tdd.md +330 -0
  289. package/gsd-core/references/test-containers.md +55 -0
  290. package/gsd-core/references/test-strategy.md +75 -0
  291. package/gsd-core/references/thinking-models-debug.md +44 -0
  292. package/gsd-core/references/thinking-models-execution.md +50 -0
  293. package/gsd-core/references/thinking-models-planning.md +62 -0
  294. package/gsd-core/references/thinking-models-research.md +50 -0
  295. package/gsd-core/references/thinking-models-verification.md +55 -0
  296. package/gsd-core/references/thinking-partner.md +96 -0
  297. package/gsd-core/references/ui-brand.md +162 -0
  298. package/gsd-core/references/universal-anti-patterns.md +63 -0
  299. package/gsd-core/references/user-profiling.md +681 -0
  300. package/gsd-core/references/user-story-template.md +58 -0
  301. package/gsd-core/references/verification-overrides.md +227 -0
  302. package/gsd-core/references/verification-patterns.md +612 -0
  303. package/gsd-core/references/verify-mvp-mode.md +85 -0
  304. package/gsd-core/references/workstream-flag.md +111 -0
  305. package/gsd-core/references/worktree-branch-check.md +38 -0
  306. package/gsd-core/references/worktree-path-safety.md +67 -0
  307. package/gsd-core/templates/AI-SPEC.md +246 -0
  308. package/gsd-core/templates/DEBUG.md +169 -0
  309. package/gsd-core/templates/README.md +77 -0
  310. package/gsd-core/templates/SECURITY.md +61 -0
  311. package/gsd-core/templates/UAT.md +265 -0
  312. package/gsd-core/templates/UI-SPEC.md +100 -0
  313. package/gsd-core/templates/VALIDATION.md +76 -0
  314. package/gsd-core/templates/adr.md +58 -0
  315. package/gsd-core/templates/claude-md.md +145 -0
  316. package/gsd-core/templates/codebase/architecture.md +255 -0
  317. package/gsd-core/templates/codebase/concerns.md +310 -0
  318. package/gsd-core/templates/codebase/conventions.md +307 -0
  319. package/gsd-core/templates/codebase/integrations.md +280 -0
  320. package/gsd-core/templates/codebase/stack.md +186 -0
  321. package/gsd-core/templates/codebase/structure.md +285 -0
  322. package/gsd-core/templates/codebase/testing.md +480 -0
  323. package/gsd-core/templates/config.json +62 -0
  324. package/gsd-core/templates/context.md +352 -0
  325. package/gsd-core/templates/continue-here.md +78 -0
  326. package/gsd-core/templates/copilot-instructions.md +7 -0
  327. package/gsd-core/templates/debug-subagent-prompt.md +91 -0
  328. package/gsd-core/templates/dev-preferences.md +21 -0
  329. package/gsd-core/templates/discovery.md +146 -0
  330. package/gsd-core/templates/discussion-log.md +63 -0
  331. package/gsd-core/templates/domain-model.md +54 -0
  332. package/gsd-core/templates/milestone-archive.md +123 -0
  333. package/gsd-core/templates/milestone.md +115 -0
  334. package/gsd-core/templates/phase-prompt.md +610 -0
  335. package/gsd-core/templates/planner-subagent-prompt.md +117 -0
  336. package/gsd-core/templates/product-brief.md +55 -0
  337. package/gsd-core/templates/project.md +186 -0
  338. package/gsd-core/templates/requirements.md +231 -0
  339. package/gsd-core/templates/research-project/ARCHITECTURE.md +204 -0
  340. package/gsd-core/templates/research-project/FEATURES.md +147 -0
  341. package/gsd-core/templates/research-project/PITFALLS.md +200 -0
  342. package/gsd-core/templates/research-project/STACK.md +120 -0
  343. package/gsd-core/templates/research-project/SUMMARY.md +170 -0
  344. package/gsd-core/templates/research.md +592 -0
  345. package/gsd-core/templates/retrospective.md +54 -0
  346. package/gsd-core/templates/roadmap.md +202 -0
  347. package/gsd-core/templates/spec.md +307 -0
  348. package/gsd-core/templates/state.md +195 -0
  349. package/gsd-core/templates/summary-complex.md +59 -0
  350. package/gsd-core/templates/summary-minimal.md +41 -0
  351. package/gsd-core/templates/summary-standard.md +48 -0
  352. package/gsd-core/templates/summary.md +248 -0
  353. package/gsd-core/templates/test-strategy.md +50 -0
  354. package/gsd-core/templates/user-profile.md +146 -0
  355. package/gsd-core/templates/user-setup.md +311 -0
  356. package/gsd-core/templates/verification-report.md +322 -0
  357. package/gsd-core/workflows/_runtime-launcher.snippet.sh +1 -0
  358. package/gsd-core/workflows/add-backlog.md +91 -0
  359. package/gsd-core/workflows/add-phase.md +113 -0
  360. package/gsd-core/workflows/add-tests.md +355 -0
  361. package/gsd-core/workflows/add-todo.md +161 -0
  362. package/gsd-core/workflows/ai-integration-phase.md +295 -0
  363. package/gsd-core/workflows/analyze-dependencies.md +96 -0
  364. package/gsd-core/workflows/audit-fix.md +178 -0
  365. package/gsd-core/workflows/audit-milestone.md +360 -0
  366. package/gsd-core/workflows/audit-uat.md +110 -0
  367. package/gsd-core/workflows/autonomous.md +797 -0
  368. package/gsd-core/workflows/check-todos.md +180 -0
  369. package/gsd-core/workflows/cleanup.md +195 -0
  370. package/gsd-core/workflows/code-review-fix.md +502 -0
  371. package/gsd-core/workflows/code-review.md +658 -0
  372. package/gsd-core/workflows/complete-milestone.md +855 -0
  373. package/gsd-core/workflows/debug.md +237 -0
  374. package/gsd-core/workflows/diagnose-issues.md +245 -0
  375. package/gsd-core/workflows/discover-product.md +112 -0
  376. package/gsd-core/workflows/discovery-phase.md +291 -0
  377. package/gsd-core/workflows/discuss-phase/modes/advisor.md +176 -0
  378. package/gsd-core/workflows/discuss-phase/modes/all.md +28 -0
  379. package/gsd-core/workflows/discuss-phase/modes/analyze.md +44 -0
  380. package/gsd-core/workflows/discuss-phase/modes/auto.md +57 -0
  381. package/gsd-core/workflows/discuss-phase/modes/batch.md +52 -0
  382. package/gsd-core/workflows/discuss-phase/modes/chain.md +98 -0
  383. package/gsd-core/workflows/discuss-phase/modes/default.md +141 -0
  384. package/gsd-core/workflows/discuss-phase/modes/power.md +44 -0
  385. package/gsd-core/workflows/discuss-phase/modes/text.md +55 -0
  386. package/gsd-core/workflows/discuss-phase/templates/checkpoint.json +18 -0
  387. package/gsd-core/workflows/discuss-phase/templates/context.md +136 -0
  388. package/gsd-core/workflows/discuss-phase/templates/discussion-log.md +50 -0
  389. package/gsd-core/workflows/discuss-phase-assumptions.md +675 -0
  390. package/gsd-core/workflows/discuss-phase-power.md +291 -0
  391. package/gsd-core/workflows/discuss-phase.md +499 -0
  392. package/gsd-core/workflows/do.md +111 -0
  393. package/gsd-core/workflows/docs-update.md +1176 -0
  394. package/gsd-core/workflows/edit-phase.md +295 -0
  395. package/gsd-core/workflows/eval-review.md +156 -0
  396. package/gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md +95 -0
  397. package/gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md +94 -0
  398. package/gsd-core/workflows/execute-phase/steps/post-merge-gate.md +117 -0
  399. package/gsd-core/workflows/execute-phase.md +1752 -0
  400. package/gsd-core/workflows/execute-plan.md +526 -0
  401. package/gsd-core/workflows/explore.md +146 -0
  402. package/gsd-core/workflows/extract-learnings.md +243 -0
  403. package/gsd-core/workflows/fast.md +124 -0
  404. package/gsd-core/workflows/forensics.md +279 -0
  405. package/gsd-core/workflows/graduation.md +196 -0
  406. package/gsd-core/workflows/health.md +224 -0
  407. package/gsd-core/workflows/help/modes/brief.md +22 -0
  408. package/gsd-core/workflows/help/modes/default.md +50 -0
  409. package/gsd-core/workflows/help/modes/full.md +789 -0
  410. package/gsd-core/workflows/help/modes/topic.md +74 -0
  411. package/gsd-core/workflows/help.md +24 -0
  412. package/gsd-core/workflows/import.md +256 -0
  413. package/gsd-core/workflows/inbox.md +387 -0
  414. package/gsd-core/workflows/ingest-docs.md +340 -0
  415. package/gsd-core/workflows/insert-phase.md +152 -0
  416. package/gsd-core/workflows/list-phase-assumptions.md +178 -0
  417. package/gsd-core/workflows/list-workspaces.md +57 -0
  418. package/gsd-core/workflows/manager.md +393 -0
  419. package/gsd-core/workflows/map-codebase.md +446 -0
  420. package/gsd-core/workflows/milestone-summary.md +224 -0
  421. package/gsd-core/workflows/model-domain.md +162 -0
  422. package/gsd-core/workflows/mvp-phase.md +222 -0
  423. package/gsd-core/workflows/new-milestone.md +635 -0
  424. package/gsd-core/workflows/new-project.md +1555 -0
  425. package/gsd-core/workflows/new-workspace.md +240 -0
  426. package/gsd-core/workflows/next.md +299 -0
  427. package/gsd-core/workflows/node-repair.md +92 -0
  428. package/gsd-core/workflows/note.md +158 -0
  429. package/gsd-core/workflows/pause-work.md +244 -0
  430. package/gsd-core/workflows/plan-milestone-gaps.md +281 -0
  431. package/gsd-core/workflows/plan-phase.md +1814 -0
  432. package/gsd-core/workflows/plan-review-convergence.md +346 -0
  433. package/gsd-core/workflows/plant-seed.md +230 -0
  434. package/gsd-core/workflows/pr-branch.md +157 -0
  435. package/gsd-core/workflows/profile-user.md +453 -0
  436. package/gsd-core/workflows/progress.md +699 -0
  437. package/gsd-core/workflows/quick.md +1017 -0
  438. package/gsd-core/workflows/reapply-patches.md +426 -0
  439. package/gsd-core/workflows/recommend-architecture.md +135 -0
  440. package/gsd-core/workflows/remove-phase.md +156 -0
  441. package/gsd-core/workflows/remove-workspace.md +108 -0
  442. package/gsd-core/workflows/resume-project.md +332 -0
  443. package/gsd-core/workflows/review.md +748 -0
  444. package/gsd-core/workflows/scan.md +107 -0
  445. package/gsd-core/workflows/secure-phase.md +182 -0
  446. package/gsd-core/workflows/session-report.md +146 -0
  447. package/gsd-core/workflows/settings-advanced.md +810 -0
  448. package/gsd-core/workflows/settings-integrations.md +312 -0
  449. package/gsd-core/workflows/settings.md +566 -0
  450. package/gsd-core/workflows/ship.md +405 -0
  451. package/gsd-core/workflows/sketch-wrap-up.md +286 -0
  452. package/gsd-core/workflows/sketch.md +361 -0
  453. package/gsd-core/workflows/spec-phase.md +263 -0
  454. package/gsd-core/workflows/spike-wrap-up.md +307 -0
  455. package/gsd-core/workflows/spike.md +453 -0
  456. package/gsd-core/workflows/stats.md +80 -0
  457. package/gsd-core/workflows/sync-skills.md +182 -0
  458. package/gsd-core/workflows/testing-strategy.md +122 -0
  459. package/gsd-core/workflows/thread.md +222 -0
  460. package/gsd-core/workflows/transition.md +694 -0
  461. package/gsd-core/workflows/ui-phase.md +328 -0
  462. package/gsd-core/workflows/ui-review.md +193 -0
  463. package/gsd-core/workflows/ultraplan-phase.md +199 -0
  464. package/gsd-core/workflows/undo.md +314 -0
  465. package/gsd-core/workflows/update.md +496 -0
  466. package/gsd-core/workflows/validate-phase.md +181 -0
  467. package/gsd-core/workflows/verify-phase.md +544 -0
  468. package/gsd-core/workflows/verify-work.md +781 -0
  469. package/hooks/dist/gsd-check-update-worker.js +108 -0
  470. package/hooks/dist/gsd-check-update.js +66 -0
  471. package/hooks/dist/gsd-config-reload.js +133 -0
  472. package/hooks/dist/gsd-context-monitor.js +195 -0
  473. package/hooks/dist/gsd-cursor-post-tool.js +75 -0
  474. package/hooks/dist/gsd-cursor-session-start.js +52 -0
  475. package/hooks/dist/gsd-graphify-update.sh +158 -0
  476. package/hooks/dist/gsd-phase-boundary.sh +47 -0
  477. package/hooks/dist/gsd-prompt-guard.js +97 -0
  478. package/hooks/dist/gsd-read-guard.js +101 -0
  479. package/hooks/dist/gsd-read-injection-scanner.js +203 -0
  480. package/hooks/dist/gsd-session-state.sh +59 -0
  481. package/hooks/dist/gsd-statusline.js +566 -0
  482. package/hooks/dist/gsd-update-banner.js +138 -0
  483. package/hooks/dist/gsd-validate-commit.sh +57 -0
  484. package/hooks/dist/gsd-workflow-guard.js +167 -0
  485. package/hooks/dist/gsd-worktree-path-guard.js +169 -0
  486. package/hooks/dist/lib/git-cmd.js +150 -0
  487. package/hooks/dist/lib/gsd-graphify-rebuild.sh +65 -0
  488. package/hooks/dist/managed-hooks-registry.cjs +38 -0
  489. package/hooks/gsd-check-update-worker.js +108 -0
  490. package/hooks/gsd-check-update.js +66 -0
  491. package/hooks/gsd-config-reload.js +133 -0
  492. package/hooks/gsd-context-monitor.js +195 -0
  493. package/hooks/gsd-cursor-post-tool.js +75 -0
  494. package/hooks/gsd-cursor-session-start.js +52 -0
  495. package/hooks/gsd-graphify-update.sh +158 -0
  496. package/hooks/gsd-phase-boundary.sh +47 -0
  497. package/hooks/gsd-prompt-guard.js +97 -0
  498. package/hooks/gsd-read-guard.js +101 -0
  499. package/hooks/gsd-read-injection-scanner.js +203 -0
  500. package/hooks/gsd-session-state.sh +59 -0
  501. package/hooks/gsd-statusline.js +566 -0
  502. package/hooks/gsd-update-banner.js +138 -0
  503. package/hooks/gsd-validate-commit.sh +57 -0
  504. package/hooks/gsd-workflow-guard.js +167 -0
  505. package/hooks/gsd-worktree-path-guard.js +169 -0
  506. package/hooks/hooks.json +69 -0
  507. package/hooks/lib/git-cmd.js +150 -0
  508. package/hooks/lib/gsd-graphify-rebuild.sh +65 -0
  509. package/hooks/managed-hooks-registry.cjs +38 -0
  510. package/package.json +115 -0
  511. package/scripts/affected-tests-lib.cjs +542 -0
  512. package/scripts/audit-workflow-script-paths.cjs +73 -0
  513. package/scripts/base64-scan.sh +351 -0
  514. package/scripts/build-hooks.js +247 -0
  515. package/scripts/changeset/README.md +129 -0
  516. package/scripts/changeset/cli.cjs +590 -0
  517. package/scripts/changeset/github-release-notes.cjs +199 -0
  518. package/scripts/changeset/lint.cjs +111 -0
  519. package/scripts/changeset/new.cjs +137 -0
  520. package/scripts/changeset/parse.cjs +114 -0
  521. package/scripts/changeset/render.cjs +34 -0
  522. package/scripts/changeset/serialize.cjs +130 -0
  523. package/scripts/check-alias-drift.cjs +114 -0
  524. package/scripts/check-env.cjs +312 -0
  525. package/scripts/check-npm-integrity.cjs +215 -0
  526. package/scripts/ci-guard-runner.cjs +22 -0
  527. package/scripts/ci-prepare-test-scope.cjs +51 -0
  528. package/scripts/ci-rebase-check.cjs +86 -0
  529. package/scripts/ci-test-scope.cjs +431 -0
  530. package/scripts/command-contract-helpers.cjs +64 -0
  531. package/scripts/diff-touches-shipped-paths.cjs +155 -0
  532. package/scripts/fix-slash-commands.cjs +147 -0
  533. package/scripts/gen-inventory-manifest.cjs +115 -0
  534. package/scripts/gen-research-agents.cjs +276 -0
  535. package/scripts/generate-package-identity.cjs +125 -0
  536. package/scripts/issue-dedupe.cjs +278 -0
  537. package/scripts/lib/allowlist-ratchet.cjs +136 -0
  538. package/scripts/lib/cli-exit.cjs +56 -0
  539. package/scripts/lint-command-contract.cjs +114 -0
  540. package/scripts/lint-descriptions.cjs +87 -0
  541. package/scripts/lint-docs-required.cjs +222 -0
  542. package/scripts/lint-legacy-dir-name.cjs +160 -0
  543. package/scripts/lint-package-identity-drift.cjs +141 -0
  544. package/scripts/lint-pr-check-project-dir.cjs +99 -0
  545. package/scripts/lint-shell-command-projection-drift.cjs +62 -0
  546. package/scripts/lint-skill-deps.cjs +185 -0
  547. package/scripts/lint-test-file-count.allowlist.json +135 -0
  548. package/scripts/lint-test-file-count.cjs +246 -0
  549. package/scripts/mutation-matrix.cjs +222 -0
  550. package/scripts/pr-template-policy.cjs +268 -0
  551. package/scripts/prompt-injection-scan.sh +207 -0
  552. package/scripts/release-notes/discord-release-summary.cjs +373 -0
  553. package/scripts/release-notes/format-github-release-notes.cjs +261 -0
  554. package/scripts/release-tarball-smoke.cjs +629 -0
  555. package/scripts/research-profiles.cjs +149 -0
  556. package/scripts/run-affected-tests.cjs +7 -0
  557. package/scripts/run-cross-platform-tests.cjs +67 -0
  558. package/scripts/run-tests.cjs +315 -0
  559. package/scripts/secret-scan-lint.sh +231 -0
  560. package/scripts/secret-scan.sh +358 -0
  561. package/scripts/setup-branch-protection.sh +236 -0
  562. package/scripts/strip-prose-atrefs.cjs +106 -0
  563. package/scripts/sync-manifest-versions.cjs +119 -0
  564. package/scripts/sync-rulesets.sh +34 -0
  565. package/scripts/sync-runtime-launcher.cjs +399 -0
  566. package/scripts/test-failure-reasons.cjs +34 -0
  567. package/scripts/verify-npm-publish.cjs +240 -0
  568. package/scripts/workflow-policy.cjs +450 -0
@@ -0,0 +1,1752 @@
1
+ <purpose>
2
+ Execute all plans in a phase using wave-based parallel execution. Orchestrator stays lean — delegates plan execution to subagents.
3
+ </purpose>
4
+
5
+ <core_principle>
6
+ Orchestrator coordinates, not executes. Each subagent loads the full execute-plan context. Orchestrator: discover plans → analyze deps → group waves → spawn agents → handle checkpoints → collect results.
7
+ </core_principle>
8
+
9
+ <runtime_compatibility>
10
+ **Subagent spawning is runtime-specific:**
11
+ - **Claude Code:** Uses `Agent(subagent_type="gsd-executor", ...)` — blocks until complete, returns result
12
+ - **Copilot:** Subagent spawning does not reliably return completion signals. **Default to
13
+ sequential inline execution**: read and follow execute-plan.md directly for each plan
14
+ instead of spawning parallel agents. Only attempt parallel spawning if the user
15
+ explicitly requests it — and in that case, rely on the spot-check fallback in step 3
16
+ to detect completion.
17
+ - **Other runtimes:** If `Agent`/`agent` tool is unavailable, use sequential inline execution as the
18
+ fallback. Check for tool availability at runtime rather than assuming based on runtime name.
19
+
20
+ **Fallback rule:** If a spawned agent completes its work (commits visible, SUMMARY.md exists) but
21
+ the orchestrator never receives the completion signal, treat it as successful based on spot-checks
22
+ and continue to the next wave/plan. Never block indefinitely waiting for a signal — always verify
23
+ via filesystem and git state.
24
+ </runtime_compatibility>
25
+
26
+ <required_reading>
27
+ Read STATE.md before any operation to load project context.
28
+ @~/.claude/gsd-core/references/agent-contracts.md
29
+ @~/.claude/gsd-core/references/context-budget.md
30
+ @~/.claude/gsd-core/references/gates.md
31
+ </required_reading>
32
+
33
+ <available_agent_types>
34
+ These are the valid GSD subagent types registered in .claude/agents/ (or equivalent for your runtime).
35
+ Always use the exact name from this list — do not fall back to 'general-purpose' or other built-in types:
36
+
37
+ - gsd-executor — Executes plan tasks, commits, creates SUMMARY.md
38
+ - gsd-verifier — Verifies phase completion, checks quality gates
39
+ - gsd-planner — Creates detailed plans from phase scope
40
+ - gsd-phase-researcher — Researches technical approaches for a phase
41
+ - gsd-plan-checker — Reviews plan quality before execution
42
+ - gsd-debugger — Diagnoses and fixes issues
43
+ - gsd-codebase-mapper — Maps project structure and dependencies
44
+ - gsd-integration-checker — Checks cross-phase integration
45
+ - gsd-nyquist-auditor — Validates verification coverage
46
+ - gsd-ui-researcher — Researches UI/UX approaches
47
+ - gsd-ui-checker — Reviews UI implementation quality
48
+ - gsd-ui-auditor — Audits UI against design requirements
49
+ </available_agent_types>
50
+
51
+ <process>
52
+
53
+ <step name="parse_args" priority="first">
54
+ Parse `$ARGUMENTS` before loading any context:
55
+
56
+ - First positional token → `PHASE_ARG`
57
+ - Optional `--wave N` → `WAVE_FILTER`
58
+ - Optional `--gaps-only` keeps its current meaning
59
+ - Optional `--cross-ai` → `CROSS_AI_FORCE=true` (force all plans through cross-AI execution)
60
+ - Optional `--no-cross-ai` → `CROSS_AI_DISABLED=true` (disable cross-AI for this run, overrides config and frontmatter)
61
+
62
+ If `--wave` is absent, preserve the current behavior of executing all incomplete waves in the phase.
63
+ </step>
64
+
65
+ <step name="initialize" priority="first">
66
+ Load all context in one call:
67
+
68
+ ```bash
69
+ _GSD_SHIM_NAME="gsd-tools.cjs"; _GSD_RUNTIME_ROOT="${RUNTIME_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"; GSD_TOOLS="${_GSD_RUNTIME_ROOT}/gsd-core/bin/${_GSD_SHIM_NAME}"; if [ -f "$GSD_TOOLS" ]; then gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${_GSD_RUNTIME_ROOT}/.claude/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${_GSD_RUNTIME_ROOT}/.claude/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif command -v gsd-tools >/dev/null 2>&1; then GSD_TOOLS="$(command -v gsd-tools)"; gsd_run() { "$GSD_TOOLS" "$@"; }; elif [ -f "$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; else echo "ERROR: gsd-tools.cjs not found at $GSD_TOOLS and gsd-tools is not on PATH. Run: npx -y @therocketcode/gsd-core@latest --claude --local" >&2; exit 1; fi
70
+ INIT=$(gsd_run query init.execute-phase "${PHASE_ARG}")
71
+ if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
72
+ AGENT_SKILLS=$(gsd_run query agent-skills gsd-executor)
73
+ ```
74
+
75
+ Parse JSON for: `executor_model`, `verifier_model`, `commit_docs`, `parallelization`, `branching_strategy`, `branch_name`, `phase_found`, `phase_dir`, `phase_number`, `phase_name`, `phase_slug`, `plans`, `incomplete_plans`, `plan_count`, `incomplete_count`, `state_exists`, `roadmap_exists`, `phase_req_ids`, `response_language`.
76
+
77
+ **Model resolution:** If `executor_model` is `"inherit"`, omit the `model=` parameter from all `Agent()` calls — do NOT pass `model="inherit"` to Agent. Omitting the `model=` parameter causes Claude Code to inherit the current orchestrator model automatically. Only set `model=` when `executor_model` is an explicit model name (e.g., `"claude-sonnet-4-6"`, `"claude-opus-4-7"`).
78
+
79
+ **If `response_language` is set:** Include `response_language: {value}` in all spawned subagent prompts so any user-facing output stays in the configured language.
80
+
81
+ Read runtime/worktree config and fail closed before any executor dispatch:
82
+
83
+ ```bash
84
+ RUNTIME=$(gsd_run query config-get runtime --default claude 2>/dev/null || echo "claude")
85
+ USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees 2>/dev/null || echo "true")
86
+ EXECUTOR_STALL_INTERVAL_MINUTES=$(gsd_run query config-get executor.stall_detect_interval_minutes 2>/dev/null || echo "5")
87
+ EXECUTOR_STALL_THRESHOLD_MINUTES=$(gsd_run query config-get executor.stall_threshold_minutes 2>/dev/null || echo "10")
88
+
89
+ if [ "$RUNTIME" = "codex" ] && [ "$USE_WORKTREES" != "false" ]; then
90
+ echo "FATAL: Codex execute-phase worktree isolation is unsupported. Set workflow.use_worktrees=false or use a runtime with Agent isolation=\"worktree\" support." >&2
91
+ exit 1
92
+ fi
93
+ # Sweep orphaned locked worktrees from prior crashed sessions before spawning executors (#3707).
94
+ [ "$USE_WORKTREES" != "false" ] && gsd_run query worktree.reap-orphans 2>/dev/null || true
95
+ # Auto-degrade to sequential if HEAD has diverged from the worktree fork base (#683).
96
+ # Only applies to Claude Code (isolation="worktree" is Claude-Code-specific).
97
+ if [ "$RUNTIME" = "claude" ] && [ "$USE_WORKTREES" != "false" ]; then
98
+ _SHOULD_DEGRADE=$(gsd_run query worktree.base-check --pick shouldDegrade 2>/dev/null || true)
99
+ if [ "$_SHOULD_DEGRADE" = "true" ]; then
100
+ _DEGRADE_MSG=$(gsd_run query worktree.base-check --pick message 2>/dev/null || true)
101
+ [ -n "$_DEGRADE_MSG" ] && printf '%s\n' "$_DEGRADE_MSG" >&2
102
+ USE_WORKTREES=false
103
+ fi
104
+ fi
105
+ ```
106
+ Codex maps subagents to `spawn_agent`, which has no direct Codex mapping for Claude Code's `isolation="worktree"` parameter. Failing closed prevents main-checkout edits while the workflow believes agents are isolated.
107
+
108
+ If the project uses git submodules, worktree isolation is unsafe **only when a plan touches a submodule path** — the executor commit protocol cannot correctly handle submodule commits inside isolated worktrees. The previous behavior unconditionally disabled worktree isolation whenever `.gitmodules` existed, which penalised every plan in a submodule project even when the plan was nowhere near a submodule. Compute submodule paths once and intersect them per-plan with the plan's declared `files_modified` frontmatter.
109
+
110
+ ```bash
111
+ # Parse submodule paths from .gitmodules once (empty if no .gitmodules).
112
+ # SUBMODULE_PATHS is a newline-separated list of repo-relative paths.
113
+ if [ -f .gitmodules ]; then
114
+ SUBMODULE_PATHS=$(git config --file .gitmodules --get-regexp '^submodule\..*\.path$' 2>/dev/null | awk '{print $2}')
115
+ else
116
+ SUBMODULE_PATHS=""
117
+ fi
118
+ ```
119
+
120
+ `SUBMODULE_PATHS` is exported to the `execute_waves` step, where the per-plan decision actually happens (see "Per-plan worktree decision" sub-step inside `execute_waves`). The decision is per-plan because different plans in the same wave can touch different files — only plans whose paths intersect a submodule must drop worktree isolation; plans nowhere near a submodule keep parallel isolation.
121
+
122
+ When `USE_WORKTREES` (project-level) is `false`, all executor agents run without `isolation="worktree"` — they execute sequentially on the main working tree instead of in parallel worktrees. The per-plan decision below has no effect when worktrees are project-disabled.
123
+
124
+ `USE_WORKTREES` is also automatically set to `false` for the duration of a run when `worktree base-check` detects that the orchestrator HEAD has diverged from the worktree fork base (the #683 condition — e.g. an unmerged milestone or feature branch). This check runs only when `RUNTIME=claude` because `isolation="worktree"` is a Claude Code-specific feature; other runtimes do not use it. The auto-degrade prints a one-line warning to stderr and falls through to the sequential path so executors do not hit the exit-42 worktree-branch-check halt. To restore parallel worktree execution, set `worktree.baseRef:"head"` in `.claude/settings.local.json` (or run `gsd-tools worktree set-baseref`) — this makes the fork base track the live HEAD instead of a fixed remote ref. The `worktree-branch-check` exit-42 guard inside each executor remains in place as a backstop.
125
+
126
+ Read context window size for adaptive prompt enrichment:
127
+
128
+ ```bash
129
+ CONTEXT_WINDOW=$(gsd_run query config-get context_window 2>/dev/null || echo "200000")
130
+ ```
131
+
132
+ When `CONTEXT_WINDOW >= 500000` (1M-class models), subagent prompts include richer context:
133
+ - Executor agents receive prior wave SUMMARY.md files and the phase CONTEXT.md/RESEARCH.md
134
+ - Verifier agents receive all PLAN.md, SUMMARY.md, CONTEXT.md files plus REQUIREMENTS.md
135
+ - This enables cross-phase awareness and history-aware verification
136
+
137
+ When `CONTEXT_WINDOW < 200000` (sub-200K models), subagent prompts are thinned to reduce static overhead:
138
+ - Executor agents omit extended deviation rule examples and checkpoint examples from inline prompt — load on-demand via @~/.claude/gsd-core/references/executor-examples.md
139
+ - Planner agents omit extended anti-pattern lists and specificity examples from inline prompt — load on-demand via @~/.claude/gsd-core/references/planner-antipatterns.md
140
+ - Core rules and decision logic remain inline; only verbose examples and edge-case lists are extracted
141
+ - This reduces executor static overhead by ~40% while preserving behavioral correctness
142
+
143
+ **If `phase_found` is false:** Error — phase directory not found.
144
+ **If `plan_count` is 0:** Error — no plans found in phase.
145
+ **If `state_exists` is false but `.planning/` exists:** Offer reconstruct or continue.
146
+
147
+ When `parallelization` is false, plans within a wave execute sequentially.
148
+
149
+ **Runtime detection for Copilot:**
150
+ Check if the current runtime is Copilot by testing for the `@gsd-executor` agent pattern
151
+ or absence of the `Agent()` subagent API. If running under Copilot, force sequential inline
152
+ execution regardless of the `parallelization` setting — Copilot's subagent completion
153
+ signals are unreliable (see `<runtime_compatibility>`). Set `COPILOT_SEQUENTIAL=true`
154
+ internally and skip the `execute_waves` step in favor of `check_interactive_mode`'s
155
+ inline path for each plan.
156
+
157
+ **REQUIRED — Sync chain flag with intent.** If user invoked manually (no `--auto`), clear the ephemeral chain flag from any previous interrupted `--auto` chain. This prevents stale `_auto_chain_active: true` from causing unwanted auto-advance. This does NOT touch `workflow.auto_advance` (the user's persistent settings preference). You MUST execute this bash block before any config reads:
158
+ ```bash
159
+ # REQUIRED: prevents stale auto-chain from previous --auto runs
160
+ if [[ ! "$ARGUMENTS" =~ --auto ]]; then
161
+ gsd_run query config-set workflow._auto_chain_active false || true
162
+ fi
163
+ ```
164
+
165
+ Resolve `MVP_MODE` once via the centralized `phase.mvp-mode` query verb (precedence chain: CLI flag → ROADMAP `**Mode:** mvp` → `workflow.mvp_mode` config → false):
166
+ ```bash
167
+ MVP_FLAG_ARG=""
168
+ if [[ "$ARGUMENTS" =~ (^|[[:space:]])--mvp([[:space:]]|$) ]]; then MVP_FLAG_ARG="--cli-flag"; fi
169
+ MVP_MODE=$(gsd_run query phase.mvp-mode "${PHASE_NUMBER}" $MVP_FLAG_ARG --pick active)
170
+ TDD_MODE=$(gsd_run query config-get workflow.tdd_mode 2>/dev/null || echo "false")
171
+ ```
172
+
173
+ <step name="safe_resume_gate">
174
+ Before trusting `STATE.md` or dispatching any executor, derive `CURRENT_PLAN_ID`
175
+ from the active incomplete plan in `INIT`, then search recent history:
176
+ ```bash
177
+ CURRENT_PLAN_ID="{phase_number}-{plan_padded}"
178
+ SUMMARY_PATH="{phase_dir}/{plan_padded}-SUMMARY.md"
179
+ PLAN_COMMITS=$(git log --oneline --grep="${CURRENT_PLAN_ID}" -30)
180
+ ```
181
+ If production commits exist and `SUMMARY.md is missing`, stop before spawning a
182
+ new executor; continuing risks duplicate work and stale `STATE.md`/ROADMAP progress.
183
+ Offer these recovery options:
184
+ - `close out manually` — inspect commits, write SUMMARY.md, then update STATE/ROADMAP.
185
+ - `re-execute from scratch` — revert or supersede partial commits before dispatch.
186
+ - `mark-and-skip` — record the anomaly and move on only with explicit confirmation.
187
+ </step>
188
+
189
+ **MVP+TDD gate.** Task-scoped enforcement runs inside plan execution (immediately before each implementation step), where `TASK_FILE`, `PLAN_ID`, and `TASK_ID` are defined. Keep the same predicate and RED-commit contract:
190
+ ```bash
191
+ if [ "$MVP_MODE" = "true" ] && [ "$TDD_MODE" = "true" ]; then
192
+ IS_BEHAVIOR_ADDING=$(gsd_run query task.is-behavior-adding "$TASK_FILE" --pick is_behavior_adding)
193
+ if [ "$IS_BEHAVIOR_ADDING" = "true" ]; then
194
+ RED_COMMIT=$(git log --oneline --grep="^test(${PHASE_NUMBER}-${PLAN_ID}):" -- "**/*.test.*" "**/*.spec.*" "tests/" | head -1)
195
+ if [ -z "$RED_COMMIT" ]; then
196
+ gsd_run query state.update last_gate_trip "${PLAN_ID}/${TASK_ID}" || true
197
+ echo "MVP+TDD GATE TRIPPED: missing RED commit for ${PLAN_ID}/${TASK_ID}"
198
+ exit 1
199
+ fi
200
+ fi
201
+ fi
202
+ ```
203
+ Pure doc-only / config-only / test-only tasks return `is_behavior_adding=false` and are exempt. When the gate trips, Read `~/.claude/gsd-core/references/execute-mvp-tdd.md` for the exact halt report format.
204
+ </step>
205
+
206
+ <step name="check_blocking_antipatterns" priority="first">
207
+ **MANDATORY — Check for blocking anti-patterns before any other work.**
208
+
209
+ Look for a `.continue-here.md` in the current phase directory:
210
+
211
+ ```bash
212
+ ls ${phase_dir}/.continue-here.md 2>/dev/null || true
213
+ ```
214
+
215
+ If `.continue-here.md` exists, parse its "Critical Anti-Patterns" table for rows with `severity` = `blocking`.
216
+
217
+ **If one or more `blocking` anti-patterns are found:**
218
+
219
+ This step cannot be skipped. Before proceeding to `check_interactive_mode` or any other step, the agent must demonstrate understanding of each blocking anti-pattern by answering all three questions for each one:
220
+
221
+ 1. **What is this anti-pattern?** — Describe it in your own words, not by quoting the handoff.
222
+ 2. **How did it manifest?** — Explain the specific failure that caused it to be recorded.
223
+ 3. **What structural mechanism (not acknowledgment) prevents it?** — Name the concrete step, checklist item, or enforcement mechanism that stops recurrence.
224
+
225
+ Write these answers inline before continuing. If a blocking anti-pattern cannot be answered from the context in `.continue-here.md`, stop and ask the user for clarification.
226
+
227
+ **If no `.continue-here.md` exists, or no `blocking` rows are found:** Proceed directly to `check_interactive_mode`.
228
+ </step>
229
+
230
+ <step name="check_interactive_mode">
231
+ **Parse `--interactive` flag from $ARGUMENTS.**
232
+
233
+ **If `--interactive` flag present:** Switch to interactive execution mode.
234
+
235
+ Interactive mode executes plans sequentially **inline** (no subagent spawning) with user
236
+ checkpoints between tasks. The user can review, modify, or redirect work at any point.
237
+
238
+ **Interactive execution flow:**
239
+
240
+ 1. Load plan inventory as normal (discover_and_group_plans)
241
+ 2. For each plan (sequentially, ignoring wave grouping):
242
+
243
+ a. **Present the plan to the user:**
244
+ ```
245
+ ## Plan {plan_id}: {plan_name}
246
+
247
+ Objective: {from plan file}
248
+ Tasks: {task_count}
249
+
250
+ Options:
251
+ - Execute (proceed with all tasks)
252
+ - Review first (show task breakdown before starting)
253
+ - Skip (move to next plan)
254
+ - Stop (end execution, save progress)
255
+ ```
256
+
257
+ b. **If "Review first":** Read and display the full plan file. Ask again: Execute, Modify, Skip.
258
+
259
+ c. **If "Execute":** Read and follow `~/.claude/gsd-core/workflows/execute-plan.md` **inline**
260
+ (do NOT spawn a subagent). Execute tasks one at a time.
261
+
262
+ d. **After each task:** Pause briefly. If the user intervenes (types anything), stop and address
263
+ their feedback before continuing. Otherwise proceed to next task.
264
+
265
+ e. **After plan complete:** Show results, commit, create SUMMARY.md, then present next plan.
266
+
267
+ 3. After all plans: proceed to verification (same as normal mode).
268
+
269
+ **Benefits of interactive mode:**
270
+ - No subagent overhead — dramatically lower token usage
271
+ - User catches mistakes early — saves costly verification cycles
272
+ - Maintains GSD's planning/tracking structure
273
+ - Best for: small phases, bug fixes, verification gaps, learning GSD
274
+
275
+ **Skip to handle_branching step** (interactive plans execute inline after grouping).
276
+ </step>
277
+
278
+ <step name="handle_branching">
279
+ Check `branching_strategy` from init:
280
+
281
+ **"none":** Skip, continue on current branch.
282
+
283
+ **"phase" or "milestone":** Use pre-computed `branch_name` from init.
284
+
285
+ Fork the new phase branch off `origin/HEAD` (the project's default branch), not the current HEAD — otherwise consecutive phases compound and stay unpushed (#2916). If `$BRANCH_NAME` already exists locally, reuse it as-is.
286
+
287
+ ```bash
288
+ DEFAULT_BRANCH=$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||')
289
+ DEFAULT_BRANCH=${DEFAULT_BRANCH:-main}
290
+
291
+ if git show-ref --verify --quiet "refs/heads/$BRANCH_NAME"; then
292
+ git switch "$BRANCH_NAME" || { echo "ERROR: Could not switch to existing branch '$BRANCH_NAME'." >&2; exit 1; }
293
+ else
294
+ if ! git fetch --quiet origin "$DEFAULT_BRANCH"; then # #2916
295
+ git show-ref --verify --quiet "refs/remotes/origin/$DEFAULT_BRANCH" \
296
+ || { echo "ERROR: fetch origin/$DEFAULT_BRANCH failed and no local copy exists. Refusing to create '$BRANCH_NAME' off current HEAD (#2916)." >&2; exit 1; }
297
+ echo "WARNING: fetch origin/$DEFAULT_BRANCH failed; using local copy as base." >&2
298
+ fi
299
+ if [ -n "$(git status --porcelain)" ]; then
300
+ echo "WARNING: Uncommitted changes will be carried onto '$BRANCH_NAME' (branched off origin/$DEFAULT_BRANCH, not previous HEAD)."
301
+ else
302
+ git switch --quiet "$DEFAULT_BRANCH" 2>/dev/null && git merge --ff-only --quiet "origin/$DEFAULT_BRANCH" 2>/dev/null || true
303
+ fi
304
+ # Pinned base + fail-fast: on success HEAD is exactly at origin/$DEFAULT_BRANCH,
305
+ # so a post-creation merge-base or "ahead-of" guard would be unreachable. The
306
+ # explicit base argument here is the single source of correctness for #2916.
307
+ git checkout -b "$BRANCH_NAME" "origin/$DEFAULT_BRANCH" \
308
+ || { echo "ERROR: Could not create '$BRANCH_NAME' from origin/$DEFAULT_BRANCH (#2916)." >&2; exit 1; }
309
+ fi
310
+ ```
311
+
312
+ All subsequent commits go to this branch. User handles merging.
313
+ </step>
314
+
315
+ <step name="validate_phase">
316
+ From init JSON: `phase_dir`, `plan_count`, `incomplete_count`.
317
+
318
+ Report: "Found {plan_count} plans in {phase_dir} ({incomplete_count} incomplete)"
319
+
320
+ **Update STATE.md for phase start:**
321
+ ```bash
322
+ gsd_run query state.begin-phase --phase "${PHASE_NUMBER}" --name "${PHASE_NAME}" --plans "${PLAN_COUNT}"
323
+ ```
324
+ This updates Status, Last Activity, Current focus, Current Position, and plan counts in STATE.md so frontmatter and body text reflect the active phase immediately.
325
+ </step>
326
+
327
+ <step name="discover_and_group_plans">
328
+ Load plan inventory with wave grouping in one call:
329
+
330
+ ```bash
331
+ PLAN_INDEX=$(gsd_run query phase-plan-index "${PHASE_NUMBER}")
332
+ ```
333
+
334
+ Parse JSON for: `phase`, `plans[]` (each with `id`, `wave`, `autonomous`, `objective`, `files_modified`, `task_count`, `has_summary`), `waves` (map of wave number → plan IDs), `incomplete`, `has_checkpoints`.
335
+
336
+ **Filtering:** Skip plans where `has_summary: true`. If `--gaps-only`: also skip non-gap_closure plans. If `WAVE_FILTER` is set: also skip plans whose `wave` does not equal `WAVE_FILTER`.
337
+
338
+ **Wave safety check:** If `WAVE_FILTER` is set and there are still incomplete plans in any lower wave that match the current execution mode, STOP and tell the user to finish earlier waves first. Do not let Wave 2+ execute while prerequisite earlier-wave plans remain incomplete.
339
+
340
+ If all filtered: "No matching incomplete plans" → exit.
341
+
342
+ Report:
343
+ ```
344
+ ## Execution Plan
345
+
346
+ **Phase {X}: {Name}** — {total_plans} matching plans across {wave_count} wave(s)
347
+
348
+ {If WAVE_FILTER is set: `Wave filter active: executing only Wave {WAVE_FILTER}`.}
349
+
350
+ | Wave | Plans | What it builds |
351
+ |------|-------|----------------|
352
+ | 1 | 01-01, 01-02 | {from plan objectives, 3-8 words} |
353
+ | 2 | 01-03 | ... |
354
+ ```
355
+ </step>
356
+
357
+ <step name="cross_ai_delegation">
358
+ **Optional step 2.5 — Delegate plans to an external AI runtime.**
359
+
360
+ This step runs after plan discovery and before normal wave execution. It identifies plans
361
+ that should be delegated to an external AI command and executes them via stdin-based prompt
362
+ delivery. Plans handled here are removed from the execute_waves plan list so the normal
363
+ executor skips them.
364
+
365
+ **Activation logic:**
366
+
367
+ 1. If `CROSS_AI_DISABLED` is true (`--no-cross-ai` flag): skip this step entirely.
368
+ 2. If `CROSS_AI_FORCE` is true (`--cross-ai` flag): mark ALL incomplete plans for cross-AI execution.
369
+ 3. Otherwise: check each plan's frontmatter for `cross_ai: true` AND verify config
370
+ `workflow.cross_ai_execution` is `true`. Plans matching both conditions are marked for cross-AI.
371
+
372
+ ```bash
373
+ CROSS_AI_ENABLED=$(gsd_run query config-get workflow.cross_ai_execution 2>/dev/null || echo "false")
374
+ CROSS_AI_CMD=$(gsd_run query config-get workflow.cross_ai_command 2>/dev/null || echo "")
375
+ CROSS_AI_TIMEOUT=$(gsd_run query config-get workflow.cross_ai_timeout 2>/dev/null || echo "300")
376
+ ```
377
+
378
+ **If no plans are marked for cross-AI:** Skip to execute_waves.
379
+
380
+ **If plans are marked but `cross_ai_command` is empty:** Error — tell user to set
381
+ `workflow.cross_ai_command` via `gsd-tools.cjs query config-set workflow.cross_ai_command "<command>"`.
382
+
383
+ **For each cross-AI plan (sequentially):**
384
+
385
+ 1. **Construct the task prompt** from the plan file:
386
+ - Extract `<objective>` and `<tasks>` sections from the PLAN.md
387
+ - Append PROJECT.md context (project name, description, tech stack)
388
+ - Format as a self-contained execution prompt
389
+
390
+ 2. **Check for dirty working tree before execution:**
391
+ ```bash
392
+ if ! git diff --quiet HEAD 2>/dev/null; then
393
+ echo "WARNING: dirty working tree detected — the external AI command may produce uncommitted changes that conflict with existing modifications"
394
+ fi
395
+ ```
396
+
397
+ 3. **Run the external command** from the project root, writing the prompt to stdin.
398
+ Never shell-interpolate the prompt — always pipe via stdin to prevent injection:
399
+ ```bash
400
+ echo "$TASK_PROMPT" | timeout "${CROSS_AI_TIMEOUT}s" ${CROSS_AI_CMD} > "$CANDIDATE_SUMMARY" 2>"$ERROR_LOG"
401
+ EXIT_CODE=$?
402
+ ```
403
+
404
+ 4. **Evaluate the result:**
405
+
406
+ **Success (exit 0 + valid summary):**
407
+ - Read `$CANDIDATE_SUMMARY` and validate it contains meaningful content
408
+ (not empty, has at least a heading and description — a valid SUMMARY.md structure)
409
+ - Write it as the plan's SUMMARY.md file
410
+ - Update STATE.md plan status to complete
411
+ - Update ROADMAP.md progress
412
+ - Mark plan as handled — skip it in execute_waves
413
+
414
+ **Failure (non-zero exit or invalid summary):**
415
+ - Display the error output and exit code
416
+ - Warn: "The external command may have left uncommitted changes or partial edits
417
+ in the working tree. Review `git status` and `git diff` before proceeding."
418
+ - Offer three choices:
419
+ - **retry** — run the same plan through cross-AI again
420
+ - **skip** — fall back to normal executor for this plan (re-add to execute_waves list)
421
+ - **abort** — stop execution entirely, preserve state for resume
422
+
423
+ 5. **After all cross-AI plans processed:** Remove successfully handled plans from the
424
+ incomplete plan list so execute_waves skips them. Any skipped-to-fallback plans remain
425
+ in the list for normal executor processing.
426
+ </step>
427
+
428
+ <step name="execute_waves">
429
+ Execute each selected wave in sequence. Within a wave: parallel if `PARALLELIZATION=true`, sequential if `false`.
430
+
431
+ **Orchestrator cwd-drift guard (FIRST ACTION at execute_waves entry — #48):**
432
+
433
+ A prior `Agent(isolation="worktree")` dispatch can silently leave the orchestrator's
434
+ cwd inside an agent worktree (or a subdirectory of one). Every subsequent
435
+ orchestrator-side git call would then target the wrong tree — this is how a wrong-base
436
+ merge nearly shipped ~1000 files. Resolve the *worktree root* (so a subdirectory cwd
437
+ cannot skew the check) and refuse if it is an agent worktree. The discriminator is the
438
+ per-agent branch namespace `worktree-agent-*`, NOT the `.claude/worktrees/` path: the
439
+ orchestrator may itself be legitimately invoked from a feature worktree under
440
+ `.claude/worktrees/`, so a path-substring refusal would break legitimate runs. Do NOT
441
+ pin to `git worktree list`'s first entry — that is the main worktree, the wrong target
442
+ when the orchestrator legitimately runs from a feature worktree.
443
+
444
+ ```bash
445
+ ORCHESTRATOR_WT=$(git rev-parse --show-toplevel 2>/dev/null) || {
446
+ echo "FATAL: execute_waves entry is not inside a git worktree (#48)." >&2; exit 1; }
447
+ ORCH_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
448
+ if printf '%s' "$ORCH_BRANCH" | grep -Eq '^worktree-agent-'; then
449
+ echo "FATAL: orchestrator cwd is inside an agent worktree (branch '$ORCH_BRANCH', root '$ORCHESTRATOR_WT') — refusing to execute waves (#48). A prior isolation=\"worktree\" dispatch drifted the cwd; re-run from the orchestrator's own worktree." >&2
450
+ exit 1
451
+ fi
452
+ # Pin to the worktree root; each later orchestrator-side block re-pins the same way
453
+ # (see the #3174 cleanup guard). Treat $ORCHESTRATOR_WT as the canonical root for the
454
+ # rest of the phase — prefer `git -C "$ORCHESTRATOR_WT"` for cross-step git calls,
455
+ # since a bare `cd` does not persist across separate tool invocations.
456
+ export ORCHESTRATOR_WT
457
+ cd "$ORCHESTRATOR_WT" || { echo "FATAL: cannot cd to orchestrator worktree '$ORCHESTRATOR_WT' (#48)." >&2; exit 1; }
458
+ ```
459
+
460
+ **Stream-idle-timeout prevention — checkpoint heartbeats (#2410):**
461
+
462
+ Multi-plan phases can accumulate enough subagent context that the Claude API
463
+ SSE layer terminates with `Stream idle timeout - partial response received`
464
+ between a large tool_result and the next assistant turn (seen on Claude Code
465
+ + Opus 4.7 at ~200K+ cache_read). To keep the stream warm, emit short
466
+ assistant-text heartbeats — **no tool call, just a literal line** — at every
467
+ wave and plan boundary. Each heartbeat MUST start with `[checkpoint]` so
468
+ tooling and `/gsd:manager`'s background-completion handler can grep partial
469
+ transcripts. `{P}/{Q}` is the phase-wide completed/total plans counter and
470
+ increases monotonically across waves. `{status}` is `complete` (success),
471
+ `failed` (executor error), or `checkpoint` (human-gate returned).
472
+
473
+ ```
474
+ [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} starting, {wave_plan_count} plan(s), {P}/{Q} plans done
475
+ [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} starting ({P}/{Q} plans done)
476
+ [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} {status} ({P}/{Q} plans done)
477
+ [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} complete, {P}/{Q} plans done ({wave_success}/{wave_plan_count} ok)
478
+ ```
479
+
480
+ **For each wave:**
481
+
482
+ 1. **Intra-wave files_modified overlap check (BEFORE spawning):**
483
+
484
+ Before spawning any agents for this wave, inspect the `files_modified` list of all plans
485
+ in the wave. Check every pair of plans in the wave — if any two plans share even one file
486
+ in their `files_modified` lists, those plans have an implicit dependency and MUST NOT run
487
+ in parallel.
488
+
489
+ **Detection algorithm (pseudocode):**
490
+ ```
491
+ seen_files = {}
492
+ overlapping_plans = []
493
+ for each plan in wave_plans:
494
+ for each file in plan.files_modified:
495
+ if file in seen_files:
496
+ overlapping_plans.add(plan, seen_files[file]) # both plans overlap on this file
497
+ else:
498
+ seen_files[file] = plan
499
+ ```
500
+
501
+ **If overlap is detected:**
502
+ - Warn the user:
503
+ ```
504
+ ⚠ Intra-wave files_modified overlap detected in Wave {N}:
505
+ Plan {A} and Plan {B} both modify {file}
506
+ Running these plans sequentially to avoid parallel worktree conflicts.
507
+ ```
508
+ - Override `PARALLELIZATION` to `false` for this wave only — run all plans in the wave
509
+ sequentially regardless of the global parallelization setting.
510
+ - This is a safety net for plans that were incorrectly assigned to the same wave.
511
+ The planner should have caught this; flag it as a planning defect so the user can
512
+ replan the phase if desired.
513
+
514
+ **If no overlap:** proceed normally (parallel if `PARALLELIZATION=true`).
515
+
516
+ 2. **Describe what's being built (BEFORE spawning):**
517
+
518
+ **First, emit the wave-start checkpoint heartbeat as a literal assistant-text
519
+ line — no tool call (#2410). Do NOT skip this even for single-plan waves; it
520
+ is required before any further reasoning or spawning:**
521
+
522
+ ```
523
+ [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} starting, {wave_plan_count} plan(s), {P}/{Q} plans done
524
+ ```
525
+
526
+ Then read each plan's `<objective>`. Extract what's being built and why.
527
+
528
+ ```
529
+ ---
530
+ ## Wave {N}
531
+
532
+ **{Plan ID}: {Plan Name}**
533
+ {2-3 sentences: what this builds, technical approach, why it matters}
534
+
535
+ Spawning {count} agent(s)... (runs in a subagent — no output until it returns, ~1–5 min; expected, not a freeze)
536
+ ---
537
+ ```
538
+
539
+ - Bad: "Executing terrain generation plan"
540
+ - Good: "Procedural terrain generator using Perlin noise — creates height maps, biome zones, and collision meshes. Required before vehicle physics can interact with ground."
541
+
542
+ 2.5. **Per-plan worktree decision (run for each plan in this wave BEFORE its dispatch):**
543
+
544
+ Read and execute `gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md` for each plan. It extracts `PLAN_FILES` from the plan's JSON, intersects against `SUBMODULE_PATHS` (with normalization, bidirectional matching, and glob-prefix handling), and sets `USE_WORKTREES_FOR_PLAN` to `false` when the plan touches a submodule path. Append `plan_id` to a `WAVE_WORKTREE_PLANS` accumulator when `USE_WORKTREES_FOR_PLAN != false`.
545
+
546
+ The dispatch branches in step 3 below MUST gate on `USE_WORKTREES_FOR_PLAN` for the current plan, not on the project-level `USE_WORKTREES`.
547
+
548
+ 3. **Spawn executor agents:**
549
+
550
+ **Emit a plan-start heartbeat (literal line, no tool call) immediately before
551
+ each `Agent()` dispatch (#2410):**
552
+
553
+ `[checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} starting ({P}/{Q} plans done)`
554
+
555
+ Pass paths only — executors read files themselves with their fresh context window.
556
+ For 200k models, this keeps orchestrator context lean (~10-15%).
557
+ For 1M+ models (Opus 4.6, Sonnet 4.6), richer context can be passed directly.
558
+
559
+ **Worktree mode** (`USE_WORKTREES_FOR_PLAN` is not `false` — evaluated per-plan in step 2.5):
560
+
561
+ Before spawning, capture the current HEAD:
562
+ ```bash
563
+ EXPECTED_BASE=$(git rev-parse HEAD)
564
+ DISPATCH_TS=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
565
+ EXPECTED_BRANCH=$(git rev-parse --abbrev-ref HEAD)
566
+ if [ "${USE_WORKTREES_FOR_PLAN:-true}" != "false" ] && [ -z "${WAVE_WORKTREE_MANIFEST:-}" ]; then
567
+ WAVE_WORKTREE_MANIFEST=$(mktemp "${TMPDIR:-/tmp}/gsd-worktree-wave-XXXXXX.json")
568
+ # Persist the dispatch-time orchestrator worktree root so wave-cleanup can pin back to the
569
+ # orchestrator's OWN worktree — NOT `git worktree list`'s first entry (always the main
570
+ # checkout), which pins a non-primary (per-phase lane) orchestrator off its branch (#630).
571
+ # Dispatch runs from the orchestrator's lane, so show-toplevel here is the correct root.
572
+ ORCH_ROOT=$(git rev-parse --show-toplevel)
573
+ ORCH_ROOT="$ORCH_ROOT" MANIFEST="$WAVE_WORKTREE_MANIFEST" node -e 'const fs=require("fs");fs.writeFileSync(process.env.MANIFEST,JSON.stringify({orchestrator_root:process.env.ORCH_ROOT||null,worktrees:[]})+"\n")'
574
+ export WAVE_WORKTREE_MANIFEST
575
+ fi
576
+ ```
577
+
578
+ **Sequential dispatch for parallel execution (waves with 2+ agents):**
579
+ Dispatch each `Agent()` call **one at a time with `run_in_background: true`**. Do NOT
580
+ send all Agent calls in a single message: simultaneous `git worktree add` calls race
581
+ on `.git/config.lock`. Agents still run in parallel once their worktrees are created.
582
+
583
+ ```text
584
+ # CORRECT: one Agent() per message with run_in_background: true
585
+ # WRONG: multiple Agent() calls in one message -> .git/config.lock contention
586
+ ```
587
+
588
+ ```text
589
+ Agent(
590
+ subagent_type="gsd-executor",
591
+ description="Execute plan {plan_number} of phase {phase_number}",
592
+ # Only include model= when executor_model is an explicit model name.
593
+ # When executor_model is "inherit", omit this parameter entirely so
594
+ # Claude Code inherits the orchestrator model automatically.
595
+ model="{executor_model}", # omit this line when executor_model == "inherit"
596
+ isolation="worktree",
597
+ prompt="
598
+ <objective>
599
+ Execute plan {plan_number} of phase {phase_number}-{phase_name}.
600
+ Commit each task atomically. Create SUMMARY.md.
601
+ Do NOT update STATE.md or ROADMAP.md — the orchestrator owns those writes after all worktree agents in the wave complete.
602
+ </objective>
603
+
604
+ <worktree_branch_check>
605
+ ORCHESTRATOR build-time embed (NOT a sub-agent runtime step): before this dispatch, read `gsd-core/references/worktree-branch-check.md`, substitute `{EXPECTED_BASE}` with the base SHA captured above ({EXPECTED_BASE}), and replace this note with that fragment's `<worktree_branch_check>` block so the dispatched prompt carries the runnable guard verbatim — do not pass this instruction through in its place.
606
+ Per-commit HEAD/cwd-drift/path-guard: `agents/gsd-executor.md` steps 0/0a/0b + `references/worktree-path-safety.md` (in <execution_context>).
607
+ </worktree_branch_check>
608
+
609
+ <parallel_execution>
610
+ You are running as a PARALLEL executor agent in a git worktree. Worktree path safety (cwd-drift, absolute-path guards) is in `worktree-path-safety.md` (loaded below).
611
+ Run `git commit` normally — hooks run by default. Do NOT pass `--no-verify`
612
+ unless the orchestrator surfaces `workflow.worktree_skip_hooks=true` in this
613
+ prompt; silent bypass violates project CLAUDE.md guidance (#2924).
614
+
615
+ IMPORTANT: Do NOT modify STATE.md or ROADMAP.md. execute-plan.md
616
+ auto-detects worktree mode (`.git` is a file, not a directory) and skips
617
+ shared file updates automatically. The orchestrator updates them centrally
618
+ after merge.
619
+
620
+ REQUIRED: SUMMARY.md MUST be committed before you return. In worktree mode the
621
+ git_commit_metadata step in execute-plan.md commits SUMMARY.md and REQUIREMENTS.md
622
+ only (STATE.md and ROADMAP.md are excluded automatically). Do NOT skip or defer
623
+ this commit — the orchestrator force-removes the worktree after you return, and
624
+ any uncommitted SUMMARY.md will be permanently lost (#2070).
625
+ REQUIRED ORDER: Write SUMMARY.md → commit → only then any narration. No text between Write and commit (truncation risk; #2070 rescue is not primary defense).
626
+ </parallel_execution>
627
+
628
+ <execution_context>
629
+ @~/.claude/gsd-core/workflows/execute-plan.md
630
+ @~/.claude/gsd-core/templates/summary.md
631
+ @~/.claude/gsd-core/references/checkpoints.md
632
+ @~/.claude/gsd-core/references/tdd.md
633
+ @~/.claude/gsd-core/references/worktree-path-safety.md
634
+ ${CONTEXT_WINDOW < 200000 ? '' : '@~/.claude/gsd-core/references/executor-examples.md'}
635
+ </execution_context>
636
+
637
+ <files_to_read>
638
+ Read these files at execution start using the Read tool.
639
+ First resolve repo root so every path is anchored:
640
+ \`PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)\`
641
+ - ${PROJECT_ROOT}/{phase_dir}/{plan_file} (Plan)
642
+ - ${PROJECT_ROOT}/.planning/PROJECT.md (Project context — core value, requirements, evolution rules)
643
+ - ${PROJECT_ROOT}/.planning/STATE.md (State)
644
+ - ${PROJECT_ROOT}/.planning/config.json (Config, if exists)
645
+ ${CONTEXT_WINDOW >= 500000 ? `
646
+ - ${PROJECT_ROOT}/${phase_dir}/*-CONTEXT.md (User decisions from discuss-phase — honors locked choices)
647
+ - ${PROJECT_ROOT}/${phase_dir}/*-RESEARCH.md (Technical research — pitfalls and patterns to follow)
648
+ - ${PROJECT_ROOT}/${prior_wave_summaries} (SUMMARY.md files from earlier waves in this phase — what was already built)
649
+ ` : ''}
650
+ - ${PROJECT_ROOT}/CLAUDE.md (Project instructions, if exists — follow project-specific guidelines and coding conventions)
651
+ - ${PROJECT_ROOT}/.claude/skills/ or ${PROJECT_ROOT}/.agents/skills/ (Project skills, if either exists — list skills, read SKILL.md for each, follow relevant rules during implementation)
652
+ </files_to_read>
653
+
654
+ ${AGENT_SKILLS}
655
+
656
+ <mcp_tools>
657
+ If CLAUDE.md or project instructions reference MCP tools (e.g. jCodeMunch, context7,
658
+ or other MCP servers), prefer those tools over Grep/Glob for code navigation when available.
659
+ MCP tools often save significant tokens by providing structured code indexes.
660
+ Check tool availability first — if MCP tools are not accessible, fall back to Grep/Glob.
661
+ </mcp_tools>
662
+
663
+ <success_criteria>
664
+ - [ ] All tasks executed
665
+ - [ ] Each task committed individually
666
+ - [ ] SUMMARY.md created in plan directory
667
+ - [ ] No modifications to shared orchestrator artifacts (the orchestrator handles all post-wave shared-file writes)
668
+ </success_criteria>
669
+ "
670
+ )
671
+ ```
672
+
673
+ Immediately after each worktree `Agent()` spawn returns metadata, atomically append `{agent_id, worktree_path, branch, expected_base}` to `WAVE_WORKTREE_MANIFEST`. If any field is missing, stop and ask for recovery instead of scanning all agent worktrees.
674
+
675
+ > **ORCHESTRATOR FAIL-CLOSED RULE (#48):** `worktree_branch_check` is verify-only — an executor that hits a base/HEAD-namespace mismatch prints `FATAL:` and exits **42** instead of self-recovering. If any executor result reports a `FATAL:`/`exit 42` (or its commits never appear because it halted at the check), mark that plan **blocked**: do NOT merge or clean up its worktree (preserve it for inspection), do NOT count the wave as successful, and surface the mismatch with recovery guidance to the user. The orchestrator — the worktree lifecycle owner — performs any base correction (e.g. recreate the worktree on `{EXPECTED_BASE}`); the sub-agent never does. Never proceed past a halted executor on the assumption it succeeded.
676
+
677
+ > **ORCHESTRATOR RULE — CODEX RUNTIME**: After calling Agent() above to spawn executor agent(s), stop working on this task immediately. Do not read more files, edit code, or run tests related to this task while the subagent is active. Wait for the subagent to return its result. This prevents duplicate work, conflicting edits, and wasted context. Only resume when the subagent result is available.
678
+
679
+ **Sequential mode** (`USE_WORKTREES_FOR_PLAN` is `false` — either project-level `USE_WORKTREES=false`, or per-plan submodule intersection forced it false in step 2.5):
680
+
681
+ Omit `isolation="worktree"` from the Agent call. Replace the `<parallel_execution>` block with:
682
+
683
+ ```
684
+ <sequential_execution>
685
+ You are running as a SEQUENTIAL executor agent on the main working tree.
686
+ Use normal git commits (with hooks). Do NOT use --no-verify.
687
+ REQUIRED ORDER: Write SUMMARY.md → commit → only then any narration. No text between Write and commit (truncation risk; #2070 rescue is not primary defense).
688
+ </sequential_execution>
689
+ ```
690
+
691
+ The sequential mode Agent prompt uses the same structure as worktree mode but with these differences in success_criteria — since there is only one agent writing at a time, there are no shared-file conflicts:
692
+
693
+ ```
694
+ <success_criteria>
695
+ - [ ] All tasks executed
696
+ - [ ] Each task committed individually
697
+ - [ ] SUMMARY.md created in plan directory
698
+ - [ ] STATE.md updated with position and decisions
699
+ - [ ] ROADMAP.md updated with plan progress (via `roadmap update-plan-progress`)
700
+ </success_criteria>
701
+ ```
702
+
703
+ When worktrees are disabled for a plan (per-plan or project-level), that plan's executor runs on the main working tree. If **any** plan in the current wave dropped to sequential mode, execute the affected plan(s) **one at a time** to avoid concurrent writes to the main working tree — plans in the same wave that retained worktree isolation can still run in parallel alongside the sequential ones, but two non-worktree plans in the same wave must serialize. When the project-level `USE_WORKTREES=false`, all plans in the wave serialize regardless of the `PARALLELIZATION` setting.
704
+
705
+ 4. **Wait for all agents in wave to complete.**
706
+
707
+ **Plan-complete heartbeat (#2410):** as each executor returns (or is verified
708
+ via spot-check below), emit one line — `complete` advances `{P}`, `failed`
709
+ and `checkpoint` do not but still warm the stream:
710
+
711
+ ```
712
+ [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} complete ({P}/{Q} plans done)
713
+ [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} failed ({P}/{Q} plans done)
714
+ [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} plan {plan_id} checkpoint ({P}/{Q} plans done)
715
+ ```
716
+
717
+ **Completion signal fallback (Copilot and runtimes where Agent() may not return):**
718
+
719
+ If a spawned agent does not return a completion signal but appears to have finished
720
+ its work, do NOT block indefinitely. Instead, verify completion via spot-checks:
721
+
722
+ ```bash
723
+ # For each plan in this wave, check if the executor finished:
724
+ SUMMARY_EXISTS=$(test -f "{phase_dir}/{plan_number}-{plan_padded}-SUMMARY.md" && echo "true" || echo "false")
725
+ COMMITS_FOUND=$(git log --oneline --all --grep="{phase_number}-{plan_padded}" --since="1 hour ago" | head -1)
726
+ COMMITS_SINCE_DISPATCH=$(git log "${EXPECTED_BRANCH}" --since="${DISPATCH_TS}" --oneline | head -1)
727
+ ```
728
+
729
+ **If SUMMARY.md exists AND commits are found:** The agent completed successfully —
730
+ treat as done and proceed to step 5. Log: `"✓ {Plan ID} completed (verified via spot-check — completion signal not received)"`
731
+
732
+ **If SUMMARY.md does NOT exist after a reasonable wait:** The agent may still be
733
+ running or may have failed silently. Check `git log --oneline -5` for recent
734
+ activity. If commits are still appearing, wait longer. If no activity, report
735
+ the plan as failed and route to the failure handler in step 6.
736
+
737
+ **Configurable stall surveillance (#3212):** Every `${EXECUTOR_STALL_INTERVAL_MINUTES}`
738
+ minutes while waiting, inspect `git log "${EXPECTED_BRANCH}" --since="${DISPATCH_TS}"`
739
+ for activity. If no completion signal, no SUMMARY.md, and no expected-branch
740
+ commits appear for `${EXECUTOR_STALL_THRESHOLD_MINUTES}` minutes, pause and
741
+ ask for one recovery path: `continue waiting`, `kill and retry`, or
742
+ `kill and switch to inline execution`.
743
+
744
+ **This fallback applies automatically to all runtimes.** Claude Code's Agent() normally
745
+ returns synchronously, but the fallback ensures resilience if it doesn't.
746
+
747
+ 5. **Post-wave hook validation (parallel mode only):** Hooks run on every executor commit by default (#2924); this post-wave run only fires when `workflow.worktree_skip_hooks=true` opted out of per-commit hooks:
748
+ ```bash
749
+ SKIP_HOOKS=$(gsd_run query config-get workflow.worktree_skip_hooks 2>/dev/null || echo "false")
750
+ if [ "$SKIP_HOOKS" = "true" ]; then
751
+ # Stash uncommitted changes under a named ref so we always pop (bare `git stash` strands them on hook/script failure). #3542: `refs/stash` is shared across worktrees, so this helper runs ONLY in the orchestrator's main checkout after all wave worktrees have been merged + removed; executors are forbidden from running any `git stash` subcommand (see `<destructive_git_prohibition>` in `agents/gsd-executor.md`).
752
+ STASHED=false
753
+ if (! git diff --quiet || ! git diff --cached --quiet) && git stash push -u -m "gsd-post-wave-hook-$$" >/dev/null 2>&1; then STASHED=true; fi
754
+ git hook run pre-commit 2>&1 || echo "⚠ Pre-commit hooks failed — review before continuing"
755
+ [ "$STASHED" = "true" ] && (git stash pop >/dev/null 2>&1 || echo "⚠ Could not pop gsd-post-wave-hook stash — recover manually")
756
+ fi
757
+ ```
758
+ If hooks fail: report the failure and ask "Fix hook issues now?" or "Continue to next wave?"
759
+
760
+ 5.5. **Worktree cleanup (when `isolation="worktree"` was used):**
761
+
762
+ **Standard wave contract:** Each wave's worktrees merge to main via the templated path below before the next wave's worktrees fork. The cleanup loop runs once per wave at the end of the wave lifecycle. Worktrees created in wave N must be fully removed before wave N+1 forks new ones.
763
+
764
+ **Cross-wave dependency deviation (supported execution mode):** When the orchestrator legitimately deviates from the standard wave model — for example, a phase with cross-wave plan dependencies that requires custom inter-worktree base-update merges (e.g., `merge: bring 09-01 + 09-02 into 09-03 base`) — the cleanup loop below is NOT automatically re-entered for those custom merges. The deviation path produces correct final history but bypasses this loop, leaving `worktree-agent-*` directories in place. Use the **cleanup-tail snippet** below to remove any residual worktrees after such a deviation.
765
+
766
+ When executor agents ran in worktree isolation, their commits land on temporary branches in separate working trees. After the wave completes, merge these changes back and clean up:
767
+
768
+ **Manifest source of truth (#3384):** Cleanup consumes the `WAVE_WORKTREE_MANIFEST` created and populated during executor dispatch in step 3. Do not recreate or truncate it here.
769
+
770
+ Prefer the bounded helper, which validates branch identity, expected base, deletion
771
+ diffs, merge result, and worktree removal before deleting the temporary branch.
772
+ If the helper reports a blocked cleanup, resolve the reported manifest entry and
773
+ rerun the same command. Do not fall back to broad worktree discovery.
774
+
775
+ ```bash
776
+ [ -n "${WAVE_WORKTREE_MANIFEST:-}" ] && [ -f "$WAVE_WORKTREE_MANIFEST" ] || {
777
+ echo "BLOCKED: missing WAVE_WORKTREE_MANIFEST; refusing broad worktree cleanup (#3384)." >&2
778
+ exit 1
779
+ }
780
+
781
+ # Guard: pin cleanup back to the orchestrator's OWN worktree and fail on branch drift (#3174, #630).
782
+ # Resolve from the dispatch-time orchestrator root persisted in the manifest — NOT `git worktree
783
+ # list`'s first entry, which is always the main checkout and would pin a non-primary (per-phase
784
+ # lane) orchestrator off its own branch, tripping the #3174 assertion below (#630). Byte-identical
785
+ # for a primary orchestrator (its root IS the first entry); the fallback covers pre-#630 manifests.
786
+ PRIMARY_WT=$(MANIFEST="$WAVE_WORKTREE_MANIFEST" node -e 'const fs=require("fs");try{const j=JSON.parse(fs.readFileSync(process.env.MANIFEST,"utf8"));if(j&&j.orchestrator_root)process.stdout.write(String(j.orchestrator_root))}catch(e){}')
787
+ [ -n "$PRIMARY_WT" ] || PRIMARY_WT=$(git worktree list --porcelain | awk '/^worktree /{print substr($0,10); exit}')
788
+ if [ -z "$PRIMARY_WT" ]; then
789
+ echo "FATAL: could not resolve orchestrator worktree before cleanup" >&2
790
+ exit 1
791
+ fi
792
+ if [ -n "$PRIMARY_WT" ] && [ "$(pwd -P 2>/dev/null)" != "$(cd "$PRIMARY_WT" 2>/dev/null && pwd -P)" ]; then echo "⚠ Orchestrator CWD drifted to $(pwd) — pinning to $PRIMARY_WT before worktree cleanup (#3174)"; cd "$PRIMARY_WT" || { echo "FATAL: cannot cd to primary worktree $PRIMARY_WT" >&2; exit 1; }; fi
793
+ ORCH_BRANCH=$(git rev-parse --abbrev-ref HEAD)
794
+ [ -z "${EXPECTED_BRANCH:-}" ] || [ "$ORCH_BRANCH" = "$EXPECTED_BRANCH" ] || { echo "FATAL: orchestrator on '$ORCH_BRANCH' but expected '$EXPECTED_BRANCH' before worktree cleanup — refusing to merge (#3174-class drift)" >&2; exit 1; }
795
+
796
+ # Fail closed: SDK refusal (safety guard #3174/#3384) must surface — do not swallow exit 1.
797
+ gsd_run query worktree.cleanup-wave --manifest "$WAVE_WORKTREE_MANIFEST" || exit 1
798
+ ```
799
+
800
+ **Cleanup-tail snippet (use after any wave whose merges did not flow through the templated path above):**
801
+
802
+ If the orchestrator deviated from the standard wave merge path (e.g., custom inter-worktree base-update merges with `merge: bring …` style messages), run this snippet after the custom merges are complete. It reads only `WAVE_WORKTREE_MANIFEST`; do not discover unrelated `worktree-agent-*` worktrees.
803
+
804
+ ```bash
805
+ # Cleanup-tail: pin orchestrator CWD to its OWN worktree before cleanup-tail (#3174, #630).
806
+ # Same fix as the templated path: resolve the dispatch-time orchestrator root from the manifest,
807
+ # not `git worktree list`'s first entry (always the main checkout — wrong for a lane orchestrator).
808
+ PRIMARY_WT=$(MANIFEST="$WAVE_WORKTREE_MANIFEST" node -e 'const fs=require("fs");try{const j=JSON.parse(fs.readFileSync(process.env.MANIFEST,"utf8"));if(j&&j.orchestrator_root)process.stdout.write(String(j.orchestrator_root))}catch(e){}')
809
+ [ -n "$PRIMARY_WT" ] || PRIMARY_WT=$(git worktree list --porcelain | awk '/^worktree /{print substr($0,10); exit}')
810
+ if [ -n "$PRIMARY_WT" ] && [ "$(pwd -P 2>/dev/null)" != "$(cd "$PRIMARY_WT" 2>/dev/null && pwd -P)" ]; then echo "⚠ Orchestrator CWD drifted to $(pwd) — pinning to $PRIMARY_WT before cleanup-tail (#3174)"; cd "$PRIMARY_WT" || { echo "FATAL: cannot cd to primary worktree $PRIMARY_WT" >&2; exit 1; }; fi
811
+ # Cleanup-tail: remove residual agent worktrees after a cross-wave-dependency deviation.
812
+ # Uses only the current wave manifest to avoid touching unrelated active agents (#3384).
813
+ WT_PATHS_FILE=$(mktemp "${TMPDIR:-/tmp}/gsd-worktree-paths-XXXXXX")
814
+ node -e 'const fs=require("fs");const p=process.env.WAVE_WORKTREE_MANIFEST;try{if(!p)throw new Error("WAVE_WORKTREE_MANIFEST is unset");if(!fs.existsSync(p))throw new Error("manifest does not exist");const s=fs.readFileSync(p,"utf8");if(!s.trim())throw new Error("manifest is empty");const j=JSON.parse(s);for(const w of j.worktrees||[])if(w.worktree_path)console.log(w.worktree_path)}catch(e){console.error(`ERROR: cannot read worktree manifest ${p||"(unset)"}: ${e.message}`);process.exit(1)}' > "$WT_PATHS_FILE" || { echo "BLOCKED: cannot read WAVE_WORKTREE_MANIFEST; refusing cleanup (#3384)." >&2; exit 1; }
815
+ while IFS= read -r WT; do
816
+ [ -z "$WT" ] && continue
817
+ WT_BRANCH=$(git -C "$WT" rev-parse --abbrev-ref HEAD 2>/dev/null)
818
+ [ -z "$WT_BRANCH" ] || [ "$WT_BRANCH" = "HEAD" ] && continue
819
+ echo "Cleaning up residual worktree: $WT (branch: $WT_BRANCH)"
820
+ git worktree unlock "$WT" 2>/dev/null || true
821
+ if ! git worktree remove "$WT" --force; then
822
+ WT_NAME=$(basename "$WT")
823
+ if [ -f ".git/worktrees/${WT_NAME}/locked" ]; then
824
+ echo "⚠ Worktree $WT is locked — unlock failed; manual cleanup required:"
825
+ echo " git worktree unlock \"$WT\" && git worktree remove \"$WT\" --force && git branch -D \"$WT_BRANCH\""
826
+ else
827
+ echo "⚠ Residual worktree at $WT — remove failed; manual cleanup required"
828
+ fi
829
+ else
830
+ git branch -D "$WT_BRANCH" 2>/dev/null || true
831
+ fi
832
+ done < "$WT_PATHS_FILE"
833
+ git worktree prune
834
+ ```
835
+
836
+ **When to skip step 5.5:**
837
+
838
+ **If no plan in this wave used worktree isolation** (project-level `USE_WORKTREES=false` OR every plan in the wave had `USE_WORKTREES_FOR_PLAN=false` — i.e. `WAVE_WORKTREE_PLANS` from step 2.5 is empty): all agents ran on the main working tree — skip this step entirely.
839
+
840
+ **If the orchestrator merged via custom messages (cross-wave-dependency deviation):** the templated cleanup loop above was not triggered for those merges. Run the cleanup-tail snippet above instead. After the snippet completes, proceed to step 5.6.
841
+
842
+ **If at least one plan used worktrees but others did not:** still run this cleanup — it iterates over actual `git worktree list` output and only merges back the worktrees that were created, leaving sequential plans' commits on the main tree untouched.
843
+
844
+ **If no worktrees found at runtime:** Skip silently — agents may have been spawned without worktree isolation, or the orchestrator already cleaned them up.
845
+
846
+ 5.6. **Post-merge build & test gate:**
847
+
848
+ After merging all worktrees in a wave (parallel mode), or after the last plan completes
849
+ (serial mode), run a build and then the project's test suite to catch cross-plan
850
+ integration issues that individual worktree self-checks cannot detect (e.g., conflicting
851
+ type definitions, removed exports, import changes, link errors).
852
+
853
+ This addresses the Generator self-evaluation blind spot identified in Anthropic's
854
+ harness engineering research: agents reliably report Self-Check: PASSED even when
855
+ merging their work creates failures.
856
+
857
+ Read and execute `gsd-core/workflows/execute-phase/steps/post-merge-gate.md`.
858
+
859
+ 5.7. **Post-wave shared artifact update (when at least one plan used worktrees, skip if tests failed):**
860
+
861
+ When **any** executor agent in this wave ran with `isolation="worktree"`, that agent skipped STATE.md and ROADMAP.md updates to avoid last-merge-wins overwrites. The orchestrator is the single writer for these files. After worktrees are merged back, update shared artifacts once for every completed plan in the wave (worktree-mode plans **and** sequential plans that ran on the main tree but deferred to the orchestrator for tracking writes).
862
+
863
+ **Only update tracking when tests passed (TEST_EXIT=0).**
864
+ If tests failed or timed out, skip the tracking update — plans should
865
+ not be marked as complete when integration tests are failing or inconclusive.
866
+
867
+ ```bash
868
+ # Guard: only update tracking if post-merge tests passed
869
+ # Timeout (124) is treated as inconclusive — do NOT mark plans complete
870
+ if [ "${TEST_EXIT}" -eq 0 ]; then
871
+ # Update ROADMAP plan progress for each completed plan in this wave
872
+ for plan_id in {completed_plan_ids}; do
873
+ gsd_run query roadmap.update-plan-progress "${PHASE_NUMBER}" "${plan_id}" "complete"
874
+ done
875
+
876
+ # Only commit tracking files if they actually changed
877
+ if ! git diff --quiet .planning/ROADMAP.md .planning/STATE.md 2>/dev/null; then
878
+ gsd_run query commit "docs(phase-${PHASE_NUMBER}): update tracking after wave ${N}" --files .planning/ROADMAP.md .planning/STATE.md
879
+ fi
880
+ elif [ "${TEST_EXIT}" -eq 124 ]; then
881
+ echo "⚠ Skipping tracking update — test suite timed out. Plans remain in-progress. Run tests manually to confirm."
882
+ else
883
+ echo "⚠ Skipping tracking update — post-merge tests failed (exit ${TEST_EXIT}). Plans remain in-progress until tests pass."
884
+ fi
885
+ ```
886
+
887
+ Where `WAVE_PLAN_IDS` is the space-separated list of plan IDs that completed in this wave.
888
+
889
+ **If no plan in this wave used worktrees** (project-level `USE_WORKTREES=false` OR `WAVE_WORKTREE_PLANS` is empty): sequential agents already updated STATE.md and ROADMAP.md themselves — skip this step.
890
+
891
+ 5.8. **Handle test gate failures (when `WAVE_FAILURE_COUNT > 0`):**
892
+
893
+ ```
894
+ ## ⚠ Post-Merge Test Failure (cumulative failures: ${WAVE_FAILURE_COUNT})
895
+
896
+ Wave {N} worktrees merged successfully, but {M} tests fail after merge.
897
+ This typically indicates conflicting changes across parallel plans
898
+ (e.g., type definitions, shared imports, API contracts).
899
+
900
+ Failed tests:
901
+ {first 10 lines of failure output}
902
+
903
+ Options:
904
+ 1. Fix now (recommended) — resolve conflicts before next wave
905
+ 2. Continue — failures may compound in subsequent waves
906
+ ```
907
+
908
+ Note: If `WAVE_FAILURE_COUNT > 1`, strongly recommend "Fix now" — compounding
909
+ failures across multiple waves become exponentially harder to diagnose.
910
+
911
+ If "Fix now": diagnose failures (typically import conflicts, missing types,
912
+ or changed function signatures from parallel plans modifying the same module).
913
+ Fix, commit as `fix: resolve post-merge conflicts from wave {N}`, re-run tests.
914
+
915
+ **Why this matters:** Worktree isolation means each agent's Self-Check passes
916
+ in isolation. But when merged, add/add conflicts in shared files (models, registries,
917
+ CLI entry points) can silently drop code. The post-merge gate catches this before
918
+ the next wave builds on a broken foundation.
919
+
920
+ 6. **Report completion — spot-check claims first:**
921
+
922
+ **Wave-close heartbeat (#2410):** after spot-checks finish (pass or fail),
923
+ before the `## Wave {N} Complete` summary, emit as a literal line:
924
+
925
+ ```
926
+ [checkpoint] phase {PHASE_NUMBER} wave {N}/{M} complete, {P}/{Q} plans done ({wave_success}/{wave_plan_count} ok)
927
+ ```
928
+
929
+
930
+
931
+ For each SUMMARY.md:
932
+ - Verify first 2 files from `key-files.created` exist on disk
933
+ - Check `git log --oneline --all --grep="{phase}-{plan}"` returns ≥1 commit
934
+ - Check for `## Self-Check: FAILED` marker
935
+
936
+ If ANY spot-check fails: report which plan failed, route to failure handler — ask "Retry plan?" or "Continue with remaining waves?"
937
+
938
+ If pass:
939
+ ```
940
+ ---
941
+ ## Wave {N} Complete
942
+
943
+ **{Plan ID}: {Plan Name}**
944
+ {What was built — from SUMMARY.md}
945
+ {Notable deviations, if any}
946
+
947
+ {If more waves: what this enables for next wave}
948
+ ---
949
+ ```
950
+
951
+ 7. **Handle failures:**
952
+ **Step 7.0 — classify before branching (#3095):**
953
+ ```bash
954
+ CLASS_JSON=$(gsd_run query agent.classify-failure -- "$AGENT_RETURN_BODY")
955
+ CLASS=$(echo "$CLASS_JSON" | jq -r '.class')
956
+ SENTINEL=$(echo "$CLASS_JSON" | jq -r '.sentinel // empty')
957
+ RETRY_AFTER=$(echo "$CLASS_JSON" | jq -r '.retryAfterSeconds // empty')
958
+ if [ -n "$RETRY_AFTER" ]; then RETRY_HINT=" Provider hinted retry-after: ${RETRY_AFTER}s"; else RETRY_HINT=""; fi
959
+ ```
960
+ One classifier branch handles sentinels across Claude/Copilot/Codex/Gemini. Reference: `docs/research/provider-rate-limit-signals.md`.
961
+ **Step 7.1 — `class == "quota-exceeded"`:**
962
+ Do not offer "retry now". Run step-5 spot-check first; if SUMMARY.md is missing but commits exist, route to safe-resume (`state.verify-against-disk`) instead of immediate redispatch.
963
+ ```text
964
+ ⚠ Plan {plan_id} terminated by provider quota / rate limit
965
+ Runtime sentinel: {SENTINEL}
966
+ {RETRY_HINT}
967
+ Partial commits on worktree branch: {N}
968
+ SUMMARY.md present: {yes|no}
969
+ 1. Wait for quota reset, then resume (recommended)
970
+ 2. Switch to a different runtime / model and resume
971
+ 3. Abort phase and report partial state
972
+ ```
973
+ Re-run `/gsd:execute-phase` after quota reset for Option 1.
974
+ **Step 7.2 — `class == "classify-handoff-bug"`:**
975
+ If error contains `classifyHandoffIfNeeded is not defined`, treat as Claude runtime bug. Run the same step-5 spot-checks; PASS => treat as success, FAIL => fall through.
976
+ **Step 7.3 — `class == "unknown-failure"`:**
977
+ Report failed plan and ask Continue/Stop; continuing may cascade into dependent plan failures.
978
+
979
+ 7b. **Pre-wave dependency check (waves 2+ only):**
980
+ Before wave N+1, run `gsd-tools.cjs query verify.key-links {phase_dir}/{plan}-PLAN.md` for each upcoming plan.
981
+ If any PRIOR-wave artifact link fails, present:
982
+ - `## Cross-Plan Wiring Gap` with plan/link/from/pattern rows
983
+ - Options: investigate+fix before continue, or continue with cascade risk
984
+ Skip key-links that reference files in the CURRENT (upcoming) wave.
985
+ 8. **Execute checkpoint plans between waves** — see `<checkpoint_handling>`.
986
+ 9. **Proceed to next wave.**
987
+ </step>
988
+ <step name="checkpoint_handling">
989
+ Plans with `autonomous: false` require user interaction.
990
+ **Auto-mode checkpoint handling:**
991
+ Read auto-advance config (chain flag OR user preference — same boolean as `check.auto-mode`):
992
+ ```bash
993
+ AUTO_MODE=$(gsd_run query check auto-mode --pick active 2>/dev/null || echo "false")
994
+ ```
995
+
996
+ When executor returns a checkpoint AND `AUTO_MODE` is `true`:
997
+ - **human-verify** → Auto-spawn continuation agent with `{user_response}` = `"approved"`. Log `⚡ Auto-approved checkpoint`.
998
+ - **decision** → Auto-spawn continuation agent with `{user_response}` = first option from checkpoint details. Log `⚡ Auto-selected: [option]`.
999
+ - **human-action** → Present to user (existing behavior below). Auth gates cannot be automated.
1000
+
1001
+ **Standard flow (not auto-mode, or human-action type):**
1002
+
1003
+ 1. Spawn agent for checkpoint plan
1004
+ 2. Agent runs until checkpoint task or auth gate → returns structured state
1005
+ 3. Agent return includes: completed tasks table, current task + blocker, checkpoint type/details, what's awaited
1006
+ 4. **Present to user:**
1007
+ ```
1008
+ ## Checkpoint: [Type]
1009
+
1010
+ **Plan:** 03-03 Dashboard Layout
1011
+ **Progress:** 2/3 tasks complete
1012
+
1013
+ [Checkpoint Details from agent return]
1014
+ [Awaiting section from agent return]
1015
+ ```
1016
+ 5. User responds: "approved"/"done" | issue description | decision selection
1017
+ 6. **Spawn continuation agent (NOT resume)** using continuation-prompt.md template:
1018
+ - `{completed_tasks_table}`: From checkpoint return
1019
+ - `{resume_task_number}` + `{resume_task_name}`: Current task
1020
+ - `{user_response}`: What user provided
1021
+ - `{resume_instructions}`: Based on checkpoint type
1022
+ 7. Continuation agent verifies previous commits, continues from resume point
1023
+ 8. Repeat until plan completes or user stops
1024
+
1025
+ **Why fresh agent, not resume:** Resume relies on internal serialization that breaks with parallel tool calls. Fresh agents with explicit state are more reliable.
1026
+
1027
+ **Checkpoints in parallel waves:** Agent pauses and returns while other parallel agents may complete. Present checkpoint, spawn continuation, wait for all before next wave.
1028
+ </step>
1029
+
1030
+ <step name="aggregate_results">
1031
+ After all waves:
1032
+
1033
+ ```markdown
1034
+ ## Phase {X}: {Name} Execution Complete
1035
+
1036
+ **Waves:** {N} | **Plans:** {M}/{total} complete
1037
+
1038
+ | Wave | Plans | Status |
1039
+ |------|-------|--------|
1040
+ | 1 | plan-01, plan-02 | ✓ Complete |
1041
+ | CP | plan-03 | ✓ Verified |
1042
+ | 2 | plan-04 | ✓ Complete |
1043
+
1044
+ ### Plan Details
1045
+ 1. **03-01**: [one-liner from SUMMARY.md]
1046
+ 2. **03-02**: [one-liner from SUMMARY.md]
1047
+
1048
+ ### Issues Encountered
1049
+ [Aggregate from SUMMARYs, or "None"]
1050
+ ```
1051
+
1052
+ **Security gate check:**
1053
+ ```bash
1054
+ SECURITY_CFG=$(gsd_run query config-get workflow.security_enforcement --raw 2>/dev/null || echo "true")
1055
+ SECURITY_FILE=$(ls "${PHASE_DIR}"/*-SECURITY.md 2>/dev/null | head -1)
1056
+ ```
1057
+
1058
+ If `SECURITY_CFG` is `false`: skip.
1059
+
1060
+ If `SECURITY_CFG` is `true` AND `SECURITY_FILE` is empty (no SECURITY.md yet):
1061
+ Include in the next-steps routing output:
1062
+ ```
1063
+ ⚠ Security enforcement enabled — run before advancing:
1064
+ /gsd:secure-phase {PHASE} ${GSD_WS}
1065
+ ```
1066
+
1067
+ If `SECURITY_CFG` is `true` AND SECURITY.md exists: check frontmatter `threats_open`. If > 0:
1068
+ ```
1069
+ ⚠ Security gate: {threats_open} threats open
1070
+ /gsd:secure-phase {PHASE} — resolve before advancing
1071
+ ```
1072
+ </step>
1073
+
1074
+ <step name="tdd_review_checkpoint">
1075
+ **Optional step — TDD collaborative review.**
1076
+
1077
+ ```bash
1078
+ TDD_MODE=$(gsd_run query config-get workflow.tdd_mode 2>/dev/null || echo "false")
1079
+ ```
1080
+
1081
+ **Skip if `TDD_MODE` is `false`.**
1082
+
1083
+ When `TDD_MODE` is `true`, check whether any completed plans in this phase have `type: tdd` in their frontmatter:
1084
+
1085
+ ```bash
1086
+ TDD_PLANS=$(grep -rl "^type: tdd" "${PHASE_DIR}"/*-PLAN.md 2>/dev/null | wc -l | tr -d ' ')
1087
+ ```
1088
+
1089
+ **If `TDD_PLANS` > 0:** Insert end-of-phase collaborative review checkpoint.
1090
+
1091
+ 1. Collect all SUMMARY.md files for TDD plans
1092
+ 2. For each TDD plan summary, verify the RED/GREEN/REFACTOR gate sequence:
1093
+ - RED gate: A failing test commit exists (`test(...)` commit with MUST-fail evidence)
1094
+ - GREEN gate: An implementation commit exists (`feat(...)` commit making tests pass)
1095
+ - REFACTOR gate: Optional cleanup commit (`refactor(...)` commit, tests still pass)
1096
+ 3. If any TDD plan is missing the RED or GREEN gate commits, flag it:
1097
+ ```
1098
+ ⚠ TDD gate violation: Plan {plan_id} missing {RED|GREEN} phase commit.
1099
+ Expected commit pattern: test({phase}-{plan}): ... → feat({phase}-{plan}): ...
1100
+ ```
1101
+ 4. Present collaborative review summary:
1102
+ ```
1103
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1104
+ TDD REVIEW — Phase {X}
1105
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1106
+
1107
+ TDD Plans: {TDD_PLANS} | Gate violations: {count}
1108
+
1109
+ | Plan | RED | GREEN | REFACTOR | Status |
1110
+ |------|-----|-------|----------|--------|
1111
+ | {id} | ✓ | ✓ | ✓ | Pass |
1112
+ | {id} | ✓ | ✗ | — | FAIL |
1113
+ ```
1114
+
1115
+ **Escalation under MVP+TDD.** When `MVP_MODE=true` AND `TDD_MODE=true`, the review verdict escalates from advisory to **blocking**: missing RED or GREEN gate commits prevent marking the phase complete.
1116
+ ```text
1117
+ Phase blocked: {N} TDD plan(s) violate the RED→GREEN gate sequence under MVP+TDD.
1118
+ Resolve and re-run /gsd execute-phase, or override with
1119
+ /gsd execute-phase {phase} --force-mvp-gate to ship anyway.
1120
+ ```
1121
+ `--force-mvp-gate` is the escape hatch (documented, not yet implemented). Policy is:
1122
+ - `MVP_MODE=true` AND `TDD_MODE=true`: violations are **blocking** unless explicitly overridden.
1123
+ - otherwise: violations are advisory/non-blocking and are surfaced for review.
1124
+ The verifier agent (step `verify_phase_goal`) still checks TDD discipline in both cases.
1125
+ </step>
1126
+
1127
+ <step name="handle_partial_wave_execution">
1128
+ If `WAVE_FILTER` was used, re-run plan discovery after execution:
1129
+
1130
+ ```bash
1131
+ POST_PLAN_INDEX=$(gsd_run query phase-plan-index "${PHASE_NUMBER}")
1132
+ ```
1133
+
1134
+ Apply the same "incomplete" filtering rules as earlier:
1135
+ - ignore plans with `has_summary: true`
1136
+ - if `--gaps-only`, only consider `gap_closure: true` plans
1137
+
1138
+ **If incomplete plans still remain anywhere in the phase:**
1139
+ - STOP here
1140
+ - Do NOT run phase verification
1141
+ - Do NOT mark the phase complete in ROADMAP/STATE
1142
+ - Present:
1143
+
1144
+ ```markdown
1145
+ ## Wave {WAVE_FILTER} Complete
1146
+
1147
+ Selected wave finished successfully. This phase still has incomplete plans, so phase-level verification and completion were intentionally skipped.
1148
+
1149
+ /gsd:execute-phase {phase} ${GSD_WS} # Continue remaining waves
1150
+ /gsd:execute-phase {phase} --wave {next} ${GSD_WS} # Run the next wave explicitly
1151
+ ```
1152
+
1153
+ **If no incomplete plans remain after the selected wave finishes:**
1154
+ - continue with the normal phase-level verification and completion flow below
1155
+ - this means the selected wave happened to be the last remaining work in the phase
1156
+ </step>
1157
+
1158
+ <step name="code_review_gate" required="true">
1159
+ **This step is REQUIRED and must not be skipped.** Auto-invoke code review on the phase's source changes. Advisory only — never blocks execution flow.
1160
+
1161
+ **Config gate:**
1162
+ ```bash
1163
+ CODE_REVIEW_ENABLED=$(gsd_run query config-get workflow.code_review 2>/dev/null || echo "true")
1164
+ ```
1165
+
1166
+ If `CODE_REVIEW_ENABLED` is `"false"`: display "Code review skipped (workflow.code_review=false)" and proceed to next step.
1167
+
1168
+ **Invoke review:**
1169
+ ```
1170
+ Skill(skill="gsd-code-review", args="${PHASE_NUMBER}")
1171
+ ```
1172
+
1173
+ **Check results using deterministic path (not glob):**
1174
+ ```bash
1175
+ PADDED=$(printf "%02d" "${PHASE_NUMBER}")
1176
+ REVIEW_FILE="${PHASE_DIR}/${PADDED}-REVIEW.md"
1177
+ REVIEW_STATUS=$(sed -n '/^---$/,/^---$/p' "$REVIEW_FILE" | grep "^status:" | head -1 | cut -d: -f2 | tr -d ' ')
1178
+ ```
1179
+
1180
+ If REVIEW_STATUS is not "clean" and not "skipped" and not empty, display:
1181
+ ```
1182
+ Code review found issues. Consider running:
1183
+ /gsd:code-review ${PHASE_NUMBER} --fix
1184
+ ```
1185
+
1186
+ **Error handling:** If the Skill invocation fails or throws, catch the error, display "Code review encountered an error (non-blocking): {error}" and proceed to next step. Review failures must never block execution.
1187
+
1188
+ Regardless of review result, ALWAYS proceed to close_parent_artifacts → regression_gate → verify_phase_goal.
1189
+ </step>
1190
+
1191
+ <step name="close_parent_artifacts">
1192
+ **For decimal/polish phases only (X.Y pattern):** Close the feedback loop by resolving parent UAT and debug artifacts.
1193
+
1194
+ **Skip if** phase number has no decimal (e.g., `3`, `04`) — only applies to gap-closure phases like `4.1`, `03.1`.
1195
+
1196
+ **1. Detect decimal phase and derive parent:**
1197
+ ```bash
1198
+ # Check if phase_number contains a decimal
1199
+ if [[ "$PHASE_NUMBER" == *.* ]]; then
1200
+ PARENT_PHASE="${PHASE_NUMBER%%.*}"
1201
+ fi
1202
+ ```
1203
+
1204
+ **2. Find parent UAT file:**
1205
+ ```bash
1206
+ PARENT_INFO=$(gsd_run query find-phase "${PARENT_PHASE}" --raw)
1207
+ # Extract directory from PARENT_INFO JSON, then find UAT file in that directory
1208
+ ```
1209
+
1210
+ **If no parent UAT found:** Skip this step (gap-closure may have been triggered by VERIFICATION.md instead).
1211
+
1212
+ **3. Update UAT gap statuses:**
1213
+
1214
+ Read the parent UAT file's `## Gaps` section. For each gap entry with `status: failed`:
1215
+ - Update to `status: resolved`
1216
+
1217
+ **4. Update UAT frontmatter:**
1218
+
1219
+ If all gaps now have `status: resolved`:
1220
+ - Update frontmatter `status: diagnosed` → `status: resolved`
1221
+ - Update frontmatter `updated:` timestamp
1222
+
1223
+ **5. Resolve referenced debug sessions:**
1224
+
1225
+ For each gap that has a `debug_session:` field:
1226
+ - Read the debug session file
1227
+ - Update frontmatter `status:` → `resolved`
1228
+ - Update frontmatter `updated:` timestamp
1229
+ - Move to resolved directory:
1230
+ ```bash
1231
+ mkdir -p .planning/debug/resolved
1232
+ mv .planning/debug/{slug}.md .planning/debug/resolved/
1233
+ ```
1234
+
1235
+ **6. Commit updated artifacts:**
1236
+ ```bash
1237
+ gsd_run query commit "docs(phase-${PARENT_PHASE}): resolve UAT gaps and debug sessions after ${PHASE_NUMBER} gap closure" --files .planning/phases/*${PARENT_PHASE}*/*-UAT.md .planning/debug/resolved/*.md
1238
+ ```
1239
+ </step>
1240
+
1241
+ <step name="regression_gate">
1242
+ Run prior phases' test suites to catch cross-phase regressions BEFORE verification.
1243
+
1244
+ **Skip if:** This is the first phase (no prior phases), or no prior VERIFICATION.md files exist.
1245
+
1246
+ **Step 1: Discover prior phases' test files**
1247
+ ```bash
1248
+ # Find all VERIFICATION.md files from prior phases in current milestone
1249
+ PRIOR_VERIFICATIONS=$(find .planning/phases/ -name "*-VERIFICATION.md" ! -path "*${PHASE_NUMBER}*" 2>/dev/null)
1250
+ ```
1251
+
1252
+ **Step 2: Extract test file lists from prior verifications**
1253
+
1254
+ For each VERIFICATION.md found, look for test file references:
1255
+ - Lines containing `test`, `spec`, or `__tests__` paths
1256
+ - The "Test Suite" or "Automated Checks" section
1257
+ - File patterns from `key-files.created` in corresponding SUMMARY.md files that match `*.test.*` or `*.spec.*`
1258
+
1259
+ Collect all unique test file paths into `REGRESSION_FILES`.
1260
+
1261
+ **Step 3: Run regression tests (if any found)**
1262
+
1263
+ ```bash
1264
+ # Resolve test command: project config > Makefile > language sniff
1265
+ REG_TEST_CMD=$(gsd_run query config-get workflow.test_command --default "" 2>/dev/null || true)
1266
+ if [ -z "$REG_TEST_CMD" ]; then
1267
+ if [ -f "Makefile" ] && grep -q "^test:" Makefile; then
1268
+ REG_TEST_CMD="make test"
1269
+ elif [ -f "Justfile" ] || [ -f "justfile" ]; then
1270
+ REG_TEST_CMD="just test"
1271
+ elif [ -f "package.json" ]; then
1272
+ REG_TEST_CMD="npm test"
1273
+ elif [ -f "Cargo.toml" ]; then
1274
+ REG_TEST_CMD="cargo test"
1275
+ elif [ -f "go.mod" ]; then
1276
+ REG_TEST_CMD="go test ./..."
1277
+ elif [ -f "requirements.txt" ] || [ -f "pyproject.toml" ]; then
1278
+ REG_TEST_CMD="python -m pytest ${REGRESSION_FILES} -q --tb=short"
1279
+ else
1280
+ REG_TEST_CMD="true"
1281
+ fi
1282
+ fi
1283
+ # Detect test runner and run prior phase tests
1284
+ eval "$REG_TEST_CMD" 2>&1
1285
+ ```
1286
+
1287
+ **Step 4: Report results**
1288
+
1289
+ If all tests pass:
1290
+ ```
1291
+ ✓ Regression gate: {N} prior-phase test files passed — no regressions detected
1292
+ ```
1293
+ → Proceed to verify_phase_goal
1294
+
1295
+ If any tests fail:
1296
+ ```
1297
+ ## ⚠ Cross-Phase Regression Detected
1298
+
1299
+ Phase {X} execution may have broken functionality from prior phases.
1300
+
1301
+ | Test File | Phase | Status | Detail |
1302
+ |-----------|-------|--------|--------|
1303
+ | {file} | {origin_phase} | FAILED | {first_failure_line} |
1304
+
1305
+ Options:
1306
+ 1. Fix regressions before verification (recommended)
1307
+ 2. Continue to verification anyway (regressions will compound)
1308
+ 3. Abort phase — roll back and re-plan
1309
+ ```
1310
+
1311
+ Use AskUserQuestion to present the options.
1312
+ </step>
1313
+
1314
+ <step name="schema_drift_gate">
1315
+ Post-execution schema drift detection. Catches false-positive verification where
1316
+ build/types pass because TypeScript types come from config, not the live database.
1317
+
1318
+ **Run after execution completes but BEFORE verification marks success.**
1319
+
1320
+ ```bash
1321
+ SCHEMA_DRIFT=$(gsd_run query verify.schema-drift "${PHASE_NUMBER}" 2>/dev/null)
1322
+ ```
1323
+
1324
+ Parse JSON result for: `drift_detected`, `blocking`, `schema_files`, `orms`, `unpushed_orms`, `message`.
1325
+
1326
+ **If `drift_detected` is false:** Skip to verify_phase_goal.
1327
+
1328
+ **If `drift_detected` is true AND `blocking` is true:**
1329
+
1330
+ Check for override:
1331
+ ```bash
1332
+ SKIP_SCHEMA=$(echo "${GSD_SKIP_SCHEMA_CHECK:-false}")
1333
+ ```
1334
+
1335
+ **If `SKIP_SCHEMA` is `true`:**
1336
+
1337
+ Display:
1338
+ ```
1339
+ ⚠ Schema drift detected but GSD_SKIP_SCHEMA_CHECK=true — bypassing gate.
1340
+
1341
+ Schema files changed: {schema_files}
1342
+ ORMs requiring push: {unpushed_orms}
1343
+
1344
+ Proceeding to verification (database may be out of sync).
1345
+ ```
1346
+ → Continue to verify_phase_goal.
1347
+
1348
+ **If `SKIP_SCHEMA` is not `true`:**
1349
+
1350
+ BLOCK verification. Display:
1351
+
1352
+ ```
1353
+ ## BLOCKED: Schema Drift Detected
1354
+
1355
+ Schema-relevant files changed during this phase but no database push command
1356
+ was executed. Build and type checks pass because TypeScript types come from
1357
+ config, not the live database — verification would produce a false positive.
1358
+
1359
+ Schema files changed: {schema_files}
1360
+ ORMs requiring push: {unpushed_orms}
1361
+
1362
+ Required push commands:
1363
+ {For each unpushed ORM, show the push command from the message}
1364
+
1365
+ Options:
1366
+ 1. Run push command now (recommended) — execute the push, then re-verify
1367
+ 2. Skip schema check (GSD_SKIP_SCHEMA_CHECK=true) — bypass this gate
1368
+ 3. Abort — stop execution and investigate
1369
+ ```
1370
+
1371
+ If `TEXT_MODE` is true, present as a plain-text numbered list. Otherwise use AskUserQuestion.
1372
+
1373
+ **If user selects option 1:** Present the specific push command(s) to run. After user confirms execution, re-run the schema drift check. If it passes, continue to verify_phase_goal.
1374
+
1375
+ **If user selects option 2:** Set override and continue to verify_phase_goal.
1376
+
1377
+ **If user selects option 3:** Stop execution. Report partial completion.
1378
+ </step>
1379
+
1380
+ <step name="codebase_drift_gate">
1381
+ Post-execution structural drift detection (#2003). Non-blocking by contract:
1382
+ any internal error here MUST fall through to `verify_phase_goal`. The phase
1383
+ is never failed by this gate.
1384
+
1385
+ Load and follow the full step spec from
1386
+ `gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md` —
1387
+ covers the SDK call, JSON contract, `warn` vs `auto-remap` branches, mapper
1388
+ spawn template, and the two `workflow.drift_*` config keys.
1389
+ </step>
1390
+
1391
+ <step name="verify_phase_goal">
1392
+ Verify phase achieved its GOAL, not just completed tasks.
1393
+
1394
+ ```bash
1395
+ VERIFIER_SKILLS=$(gsd_run query agent-skills gsd-verifier)
1396
+ ```
1397
+
1398
+ ```
1399
+ Agent(
1400
+ description="Verify phase {phase_number} goal achievement",
1401
+ prompt="Verify phase {phase_number} goal achievement.
1402
+ Phase directory: {phase_dir}
1403
+ Phase goal: {goal from ROADMAP.md}
1404
+ Phase requirement IDs: {phase_req_ids}
1405
+ Check must_haves against actual codebase.
1406
+ Cross-reference requirement IDs from PLAN frontmatter against REQUIREMENTS.md — every ID MUST be accounted for.
1407
+ Create VERIFICATION.md.
1408
+
1409
+ <files_to_read>
1410
+ Read these files before verification:
1411
+ - {phase_dir}/*-PLAN.md (All plans — understand intent, check must_haves)
1412
+ - {phase_dir}/*-SUMMARY.md (All summaries — cross-reference claimed vs actual)
1413
+ - .planning/REQUIREMENTS.md (Requirement traceability)
1414
+ ${CONTEXT_WINDOW >= 500000 ? `- {phase_dir}/*-CONTEXT.md (User decisions — verify they were honored)
1415
+ - {phase_dir}/*-RESEARCH.md (Known pitfalls — check for traps)
1416
+ - Prior VERIFICATION.md files from earlier phases (regression check)
1417
+ ` : ''}
1418
+ </files_to_read>
1419
+
1420
+ ${VERIFIER_SKILLS}",
1421
+ subagent_type="gsd-verifier",
1422
+ model="{verifier_model}"
1423
+ )
1424
+ ```
1425
+
1426
+ > **ORCHESTRATOR RULE — CODEX RUNTIME**: After calling Agent() above, stop working on this task immediately. Do not read more files, edit code, or run tests related to this task while the subagent is active. Wait for the subagent to return its result. This prevents duplicate work, conflicting edits, and wasted context. Only resume when the subagent result is available.
1427
+
1428
+ Read status via the canonical query (scoped to frontmatter, covers missing/unknown cases):
1429
+ ```bash
1430
+ VERIFICATION=$(gsd_run query verification.status "$PHASE_DIR" 2>/dev/null)
1431
+ STATUS=$(printf '%s' "$VERIFICATION" | jq -r '.status' 2>/dev/null || echo "")
1432
+ NEXT_ACTION=$(printf '%s' "$VERIFICATION" | jq -r '.next_action' 2>/dev/null || echo "")
1433
+ NEXT_COMMAND=$(printf '%s' "$VERIFICATION" | jq -r '.next_command' 2>/dev/null || echo "")
1434
+ ```
1435
+
1436
+ Route on `$STATUS`: if `passed`, proceed to update_roadmap. Otherwise keep the phase pending — present `$NEXT_ACTION` to the user and, when `$NEXT_COMMAND` is non-empty, show it as the next command to run. The query covers all cases including missing files (`missing`) and unexpected values (`unknown`), so no per-status arm needs to be listed here.
1437
+
1438
+ **If human_needed:**
1439
+
1440
+ **Step A: Persist human verification items as UAT file.**
1441
+
1442
+ Create `{phase_dir}/{phase_num}-UAT.md` using UAT template format:
1443
+
1444
+ ```markdown
1445
+ ---
1446
+ status: testing
1447
+ phase: {phase_num}-{phase_name}
1448
+ source: [{phase_num}-VERIFICATION.md]
1449
+ started: [now ISO]
1450
+ updated: [now ISO]
1451
+ ---
1452
+
1453
+ ## Current Test
1454
+
1455
+ number: 1
1456
+ name: {first human_verification item description}
1457
+ expected: |
1458
+ {expected behavior from VERIFICATION.md}
1459
+ awaiting: user response
1460
+
1461
+ ## Tests
1462
+
1463
+ {For each human_verification item from VERIFICATION.md:}
1464
+
1465
+ ### {N}. {item description}
1466
+ expected: {expected behavior from VERIFICATION.md}
1467
+ result: [pending]
1468
+
1469
+ ## Summary
1470
+
1471
+ total: {count}
1472
+ passed: 0
1473
+ issues: 0
1474
+ pending: {count}
1475
+ skipped: 0
1476
+ blocked: 0
1477
+
1478
+ ## Gaps
1479
+ ```
1480
+
1481
+ Commit the file:
1482
+ ```bash
1483
+ gsd_run query commit "test({phase_num}): persist human verification items as UAT" --files "{phase_dir}/{phase_num}-UAT.md"
1484
+ ```
1485
+
1486
+ **Step B: Present to user:**
1487
+
1488
+ ```
1489
+ ## ◷ Phase {X}: {Name} — Human Verification Needed
1490
+
1491
+ All automated checks passed. {N} item(s) require human testing before this phase can be marked complete:
1492
+
1493
+ {From VERIFICATION.md human_verification section}
1494
+
1495
+ Tests saved to `{phase_num}-UAT.md`.
1496
+
1497
+ When ready to run the tests:
1498
+
1499
+ `/gsd:verify-work {X} ${GSD_WS}`
1500
+
1501
+ Verify-work will walk you through each item and mark the phase complete when all tests pass.
1502
+ ```
1503
+
1504
+ **Do NOT advance the phase from this branch.** Phase completion is handled by verify-work's auto-transition after UAT passes.
1505
+
1506
+ **If user acknowledges without reporting issues (including "ok", "noted", "ack", "got it", "approved", "done", "yes", "pass", or similar):** Stop. The phase remains pending. No further orchestrator action — wait for the user to run `/gsd:verify-work`.
1507
+
1508
+ **If user reports issues now (before running verify-work):** Proceed to gap closure as currently implemented.
1509
+
1510
+ **If gaps_found:**
1511
+ ```
1512
+ ## ⚠ Phase {X}: {Name} — Gaps Found
1513
+
1514
+ **Score:** {N}/{M} must-haves verified
1515
+ **Report:** {phase_dir}/{phase_num}-VERIFICATION.md
1516
+
1517
+ ### What's Missing
1518
+ {Gap summaries from VERIFICATION.md}
1519
+
1520
+ ---
1521
+ ## ▶ Next Up — [${PROJECT_CODE}] ${PROJECT_TITLE}
1522
+
1523
+ `/clear` then:
1524
+
1525
+ `/gsd:plan-phase {X} --gaps ${GSD_WS}`
1526
+
1527
+ Also: `cat {phase_dir}/{phase_num}-VERIFICATION.md` — full report
1528
+ Also: `/gsd:verify-work {X} ${GSD_WS}` — manual testing first
1529
+ ```
1530
+
1531
+ Gap closure cycle: `/gsd:plan-phase {X} --gaps ${GSD_WS}` reads VERIFICATION.md → creates gap plans with `gap_closure: true` → user runs `/gsd:execute-phase {X} --gaps-only ${GSD_WS}` → verifier re-runs.
1532
+ </step>
1533
+
1534
+ <step name="update_roadmap">
1535
+ **Mark phase complete and update all tracking files:**
1536
+
1537
+ ```bash
1538
+ COMPLETION=$(gsd_run query phase.complete "${PHASE_NUMBER}")
1539
+ ```
1540
+
1541
+ The CLI handles:
1542
+ - Marking phase checkbox `[x]` with completion date
1543
+ - Updating Progress table (Status → Complete, date)
1544
+ - Updating plan count to final
1545
+ - Advancing STATE.md to next phase
1546
+ - Updating REQUIREMENTS.md traceability
1547
+ - Scanning for verification debt (returns `warnings` array)
1548
+
1549
+ Extract from result: `next_phase`, `next_phase_name`, `is_last_phase`, `warnings`, `has_warnings`.
1550
+
1551
+ **If has_warnings is true:**
1552
+ ```
1553
+ ## Phase {X} marked complete with {N} warnings:
1554
+
1555
+ {list each warning}
1556
+
1557
+ These items are tracked and will appear in `/gsd:progress` and `/gsd:audit-uat`.
1558
+ ```
1559
+
1560
+ ```bash
1561
+ gsd_run query commit "docs(phase-{X}): complete phase execution" --files .planning/ROADMAP.md .planning/STATE.md .planning/REQUIREMENTS.md {phase_dir}/*-VERIFICATION.md
1562
+ ```
1563
+ </step>
1564
+
1565
+ <step name="auto_copy_learnings">
1566
+ **Auto-copy phase learnings to global store (when enabled).**
1567
+
1568
+ This step runs AFTER phase completion and SUMMARY.md is written. It copies any LEARNINGS.md
1569
+ entries from the completed phase to the global learnings store at `~/.gsd/knowledge/`.
1570
+
1571
+ **Check config gate:**
1572
+ ```bash
1573
+ GL_ENABLED=$(gsd_run query config-get features.global_learnings --raw 2>/dev/null || echo "false")
1574
+ ```
1575
+
1576
+ **If `GL_ENABLED` is not `true`:** Skip this step entirely (feature disabled by default).
1577
+
1578
+ **If enabled:**
1579
+
1580
+ 1. Check if LEARNINGS.md exists in the phase directory (use the `phase_dir` value from init context)
1581
+ 2. If found, copy to global store:
1582
+ ```bash
1583
+ gsd_run query learnings.copy 2>/dev/null || echo "⚠ Learnings copy failed — continuing"
1584
+ ```
1585
+ Copy failure must NOT block phase completion.
1586
+ </step>
1587
+
1588
+ <step name="close_phase_todos">
1589
+ **Auto-close pending todos tagged for this phase (#2433).**
1590
+
1591
+ This step runs AFTER `update_roadmap` marks the phase complete. It moves any pending todos that carry `resolves_phase: <current-phase-number>` to the completed directory.
1592
+
1593
+ ```bash
1594
+ PHASE_NUM="${PHASE_NUMBER}"
1595
+ PENDING_DIR=".planning/todos/pending"
1596
+ COMPLETED_DIR=".planning/todos/completed"
1597
+ mkdir -p "$COMPLETED_DIR"
1598
+
1599
+ CLOSED=()
1600
+ for TODO_FILE in "$PENDING_DIR"/*.md; do
1601
+ [ -f "$TODO_FILE" ] || continue
1602
+ # Extract resolves_phase from YAML frontmatter (first --- block only)
1603
+ RP=$(awk '/^---/{c++;next} c==1 && /^resolves_phase:/{print $2;exit} c==2{exit}' "$TODO_FILE" 2>/dev/null || true)
1604
+ if [ "$RP" = "$PHASE_NUM" ] || [ "$RP" = "\"$PHASE_NUM\"" ]; then
1605
+ mv "$TODO_FILE" "$COMPLETED_DIR/"
1606
+ CLOSED+=("$(basename "$TODO_FILE")")
1607
+ fi
1608
+ done
1609
+
1610
+ if [ ${#CLOSED[@]} -gt 0 ]; then
1611
+ gsd_run query commit "docs(phase-${PHASE_NUMBER}): auto-close ${#CLOSED[@]} todo(s) resolved by this phase" --files .planning/todos/completed/ .planning/STATE.md|| true
1612
+ echo "◆ Closed ${#CLOSED[@]} todo(s) resolved by Phase ${PHASE_NUMBER}:"
1613
+ for f in "${CLOSED[@]}"; do echo " ✓ $f"; done
1614
+ fi
1615
+ ```
1616
+
1617
+ **If no todos have `resolves_phase: <this-phase>`:** Skip silently — this step is always additive and never blocks phase completion.
1618
+ </step>
1619
+
1620
+ <step name="update_project_md">
1621
+ **Evolve PROJECT.md to reflect phase completion (prevents planning document drift — #956):**
1622
+
1623
+ PROJECT.md tracks validated requirements, decisions, and current state. Without this step,
1624
+ PROJECT.md falls behind silently over multiple phases.
1625
+
1626
+ 1. Read `.planning/PROJECT.md`
1627
+ 2. If the file exists and has a `## Validated Requirements` or `## Requirements` section:
1628
+ - Move any requirements validated by this phase from Active → Validated
1629
+ - Add a brief note: `Validated in Phase {X}: {Name}`
1630
+ 3. If the file has a `## Current State` or similar section:
1631
+ - Update it to reflect this phase's completion (e.g., "Phase {X} complete — {one-liner}")
1632
+ 4. Update the `Last updated:` footer to today's date
1633
+ 5. Commit the change:
1634
+
1635
+ ```bash
1636
+ gsd_run query commit "docs(phase-{X}): evolve PROJECT.md after phase completion" --files .planning/PROJECT.md
1637
+ ```
1638
+
1639
+ **Skip this step if** `.planning/PROJECT.md` does not exist.
1640
+ </step>
1641
+
1642
+ <step name="offer_next">
1643
+
1644
+ **Exception:** If `gaps_found`, the `verify_phase_goal` step already presents the gap-closure path (`/gsd:plan-phase {X} --gaps`). No additional routing needed — skip auto-advance.
1645
+
1646
+ **No-transition check (spawned by auto-advance chain):**
1647
+
1648
+ Parse `--no-transition` flag from $ARGUMENTS.
1649
+
1650
+ **If `--no-transition` flag present:**
1651
+
1652
+ Execute-phase was spawned by plan-phase's auto-advance. Do NOT run transition.md.
1653
+ After verification passes and roadmap is updated, return completion status to parent:
1654
+
1655
+ ```
1656
+ ## PHASE COMPLETE
1657
+
1658
+ Phase: ${PHASE_NUMBER} - ${PHASE_NAME}
1659
+ Plans: ${completed_count}/${total_count}
1660
+ Verification: {Passed | Gaps Found}
1661
+
1662
+ [Include aggregate_results output]
1663
+ ```
1664
+
1665
+ STOP. Do not proceed to auto-advance or transition.
1666
+
1667
+ **If `--no-transition` flag is NOT present:**
1668
+
1669
+ **Auto-advance detection:**
1670
+
1671
+ 1. Parse `--auto` flag from $ARGUMENTS
1672
+ 2. Read consolidated auto-mode (`active` = chain flag OR user preference; chain flag already synced in init step):
1673
+ ```bash
1674
+ AUTO_MODE=$(gsd_run query check auto-mode --pick active 2>/dev/null || echo "false")
1675
+ ```
1676
+
1677
+ **If `--auto` flag present OR `AUTO_MODE` is true (AND verification passed with no gaps):**
1678
+
1679
+ ```
1680
+ ╔══════════════════════════════════════════╗
1681
+ ║ AUTO-ADVANCING → TRANSITION ║
1682
+ ║ Phase {X} verified, continuing chain ║
1683
+ ╚══════════════════════════════════════════╝
1684
+ ```
1685
+
1686
+ Execute the transition workflow inline (do NOT use Agent — orchestrator context is ~10-15%, transition needs phase completion data already in context):
1687
+
1688
+ Read and follow `~/.claude/gsd-core/workflows/transition.md`, passing through the `--auto` flag so it propagates to the next phase invocation.
1689
+
1690
+ **If neither `--auto` nor `AUTO_MODE` is true:**
1691
+
1692
+ **STOP. Do not auto-advance. Do not execute transition. Do not plan next phase. Present options to the user and wait.**
1693
+
1694
+ **IMPORTANT: There is NO `/gsd-transition` command. Never suggest it. The transition workflow is internal only.**
1695
+
1696
+ Check whether CONTEXT.md already exists for the next phase:
1697
+
1698
+ ```bash
1699
+ ls .planning/phases/*{next}*/{next}-CONTEXT.md 2>/dev/null || echo "no-context"
1700
+ ```
1701
+
1702
+ If CONTEXT.md does **not** exist for the next phase, present:
1703
+
1704
+ ```
1705
+ ## ✓ Phase {X}: {Name} Complete
1706
+
1707
+ /gsd:progress ${GSD_WS} — see updated roadmap
1708
+ /gsd:discuss-phase {next} ${GSD_WS} — start here: discuss next phase before planning ← recommended
1709
+ /gsd:plan-phase {next} ${GSD_WS} — plan next phase (skip discuss)
1710
+ /gsd:execute-phase {next} ${GSD_WS} — execute next phase (skip discuss and plan)
1711
+ ```
1712
+
1713
+ If CONTEXT.md **exists** for the next phase, present:
1714
+
1715
+ ```
1716
+ ## ✓ Phase {X}: {Name} Complete
1717
+
1718
+ /gsd:progress ${GSD_WS} — see updated roadmap
1719
+ /gsd:plan-phase {next} ${GSD_WS} — start here: plan next phase (CONTEXT.md already present) ← recommended
1720
+ /gsd:discuss-phase {next} ${GSD_WS} — re-discuss next phase
1721
+ /gsd:execute-phase {next} ${GSD_WS} — execute next phase (skip planning)
1722
+ ```
1723
+
1724
+ Only suggest the commands listed above. Do not invent or hallucinate command names.
1725
+ </step>
1726
+
1727
+ </process>
1728
+
1729
+ <context_efficiency>
1730
+ Orchestrator: ~10-15% context for 200k windows, can use more for 1M+ windows.
1731
+ Subagents: fresh context each (200k-1M depending on model). No polling (Agent blocks). No context bleed.
1732
+
1733
+ For 1M+ context models, consider:
1734
+ - Passing richer context (code snippets, dependency outputs) directly to executors instead of just file paths
1735
+ - Running small phases (≤3 plans, no dependencies) inline without subagent spawning overhead
1736
+ - Relaxing /clear recommendations — context rot onset is much further out with 5x window
1737
+ </context_efficiency>
1738
+
1739
+ <failure_handling>
1740
+ - **Quota / rate-limit (any runtime — #3095):** Agent return body contains a sentinel like `usage limit`, `rate limit`, `429`, `too many requests`, `RESOURCE_EXHAUSTED`, `usage_limit_reached`. Route via `gsd-tools.cjs query agent.classify-failure` → `class: "quota-exceeded"`. Do not offer retry-now; the right action is wait-for-reset and resume.
1741
+ - **classifyHandoffIfNeeded false failure:** Agent reports "failed" but error is `classifyHandoffIfNeeded is not defined` → Claude Code bug, not GSD. Spot-check (SUMMARY exists, commits present) → if pass, treat as success
1742
+ - **Agent fails mid-plan:** Missing SUMMARY.md → report, ask user how to proceed
1743
+ - **Dependency chain breaks:** Wave 1 fails → Wave 2 dependents likely fail → user chooses attempt or skip
1744
+ - **All agents in wave fail:** Systemic issue → stop, report for investigation
1745
+ - **Checkpoint unresolvable:** "Skip this plan?" or "Abort phase execution?" → record partial progress in STATE.md
1746
+ </failure_handling>
1747
+
1748
+ <resumption>
1749
+ Re-run `/gsd:execute-phase {phase}` → discover_plans finds completed SUMMARYs → skips them → resumes from first incomplete plan → continues wave execution.
1750
+
1751
+ STATE.md tracks: last completed plan, current wave, pending checkpoints.
1752
+ </resumption>