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