@luanpdd/kit-mcp 1.26.0 → 1.28.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 (326) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +168 -914
  3. package/gates/agent-no-recursive-dispatch.md +45 -11
  4. package/kit/COMANDOS.md +138 -138
  5. package/kit/README.md +76 -76
  6. package/kit/agents/advisor-researcher.md +106 -106
  7. package/kit/agents/assumptions-analyzer.md +107 -107
  8. package/kit/agents/audit-log-implementer.md +1 -1
  9. package/kit/agents/auditor-consistencia-isolamento.md +1 -1
  10. package/kit/agents/b2b-saas-architect.md +1 -1
  11. package/kit/agents/cascading-failures-auditor.md +1 -1
  12. package/kit/agents/codebase-mapper.md +768 -768
  13. package/kit/agents/crm-pipeline-implementer.md +1 -1
  14. package/kit/agents/debugger.md +813 -813
  15. package/kit/agents/detector-tenant-quente.md +1 -1
  16. package/kit/agents/evolution-go-integrator.md +1 -1
  17. package/kit/agents/example-reviewer.md +21 -21
  18. package/kit/agents/executor.md +564 -564
  19. package/kit/agents/integration-checker.md +200 -200
  20. package/kit/agents/invite-flow-implementer.md +1 -1
  21. package/kit/agents/legacy-characterizer.md +1 -1
  22. package/kit/agents/lgpd-compliance-auditor.md +1 -1
  23. package/kit/agents/multi-tenant-isolation-auditor.md +1 -1
  24. package/kit/agents/multi-tenant-rls-writer.md +1 -1
  25. package/kit/agents/nyquist-auditor.md +178 -178
  26. package/kit/agents/observability-coverage-auditor.md +1 -1
  27. package/kit/agents/org-onboarding-implementer.md +1 -1
  28. package/kit/agents/payload-capture-instrumenter.md +1 -1
  29. package/kit/agents/phase-researcher.md +696 -696
  30. package/kit/agents/plan-checker.md +272 -272
  31. package/kit/agents/planner.md +922 -922
  32. package/kit/agents/project-researcher.md +652 -652
  33. package/kit/agents/refactor-safety-auditor.md +1 -1
  34. package/kit/agents/release-pipeline-auditor.md +11 -0
  35. package/kit/agents/research-synthesizer.md +245 -245
  36. package/kit/agents/roadmapper.md +677 -677
  37. package/kit/agents/seam-finder.md +1 -1
  38. package/kit/agents/shotgun-surgery-detector.md +1 -1
  39. package/kit/agents/supabase-architect.md +14 -0
  40. package/kit/agents/supabase-branching-architect.md +562 -0
  41. package/kit/agents/supabase-cicd-pipeline-implementer.md +777 -0
  42. package/kit/agents/supabase-column-privileges-writer.md +1 -1
  43. package/kit/agents/supabase-migration-writer.md +13 -1
  44. package/kit/agents/supabase-rbac-implementer.md +1 -1
  45. package/kit/agents/supabase-rls-hardener.md +1 -1
  46. package/kit/agents/supabase-rls-writer.md +1 -1
  47. package/kit/agents/supabase-roles-implementer.md +1 -1
  48. package/kit/agents/super-admin-implementer.md +1 -1
  49. package/kit/agents/ui-auditor.md +437 -437
  50. package/kit/agents/ui-checker.md +302 -302
  51. package/kit/agents/ui-researcher.md +355 -355
  52. package/kit/agents/user-profiler.md +175 -175
  53. package/kit/agents/validador-evolucao-schema.md +1 -1
  54. package/kit/agents/verifier.md +728 -728
  55. package/kit/commands/adicionar-backlog.md +75 -75
  56. package/kit/commands/adicionar-fase.md +42 -42
  57. package/kit/commands/adicionar-tarefa.md +45 -45
  58. package/kit/commands/adicionar-testes.md +41 -41
  59. package/kit/commands/ajuda.md +21 -21
  60. package/kit/commands/atualizar.md +37 -37
  61. package/kit/commands/auditar-cascading.md +1 -1
  62. package/kit/commands/auditar-marco.md +179 -179
  63. package/kit/commands/auditar-observabilidade-cobertura.md +1 -1
  64. package/kit/commands/auditar-refactor.md +1 -1
  65. package/kit/commands/auditar-release.md +1 -1
  66. package/kit/commands/auditar-uat.md +23 -23
  67. package/kit/commands/autonomo.md +40 -40
  68. package/kit/commands/branch-pr.md +24 -24
  69. package/kit/commands/burn-rate-status.md +1 -1
  70. package/kit/commands/capturar-payloads.md +1 -1
  71. package/kit/commands/caracterizar.md +1 -1
  72. package/kit/commands/concluir-marco.md +247 -247
  73. package/kit/commands/configuracoes.md +36 -36
  74. package/kit/commands/dados-distribuidos.md +1 -1
  75. package/kit/commands/definir-perfil.md +10 -10
  76. package/kit/commands/depurar.md +190 -190
  77. package/kit/commands/detectar-duplicacao.md +1 -1
  78. package/kit/commands/discutir-fase.md +131 -131
  79. package/kit/commands/encontrar-seams.md +1 -1
  80. package/kit/commands/entrar-discord.md +17 -17
  81. package/kit/commands/estatisticas.md +18 -18
  82. package/kit/commands/example-greeting.md +33 -33
  83. package/kit/commands/executar-fase.md +58 -58
  84. package/kit/commands/expresso.md +56 -56
  85. package/kit/commands/fase-ui.md +34 -34
  86. package/kit/commands/fazer.md +57 -57
  87. package/kit/commands/fio.md +125 -125
  88. package/kit/commands/fluxos-trabalho.md +64 -64
  89. package/kit/commands/forense.md +176 -176
  90. package/kit/commands/gerenciador.md +38 -38
  91. package/kit/commands/inserir-fase.md +31 -31
  92. package/kit/commands/legacy.md +1 -1
  93. package/kit/commands/limpeza.md +17 -17
  94. package/kit/commands/listar-hipoteses-fase.md +45 -45
  95. package/kit/commands/listar-workspaces.md +18 -18
  96. package/kit/commands/load-shedding.md +1 -1
  97. package/kit/commands/mapear-codebase.md +70 -70
  98. package/kit/commands/multi-tenant.md +1 -1
  99. package/kit/commands/nota.md +33 -33
  100. package/kit/commands/novo-marco.md +43 -43
  101. package/kit/commands/novo-projeto.md +41 -41
  102. package/kit/commands/novo-workspace.md +43 -43
  103. package/kit/commands/pausar-trabalho.md +37 -37
  104. package/kit/commands/perfil-usuario.md +45 -45
  105. package/kit/commands/pesquisar-fase.md +195 -195
  106. package/kit/commands/planejar-fase.md +67 -67
  107. package/kit/commands/planejar-lacunas.md +33 -33
  108. package/kit/commands/plantar-ideia.md +25 -25
  109. package/kit/commands/progresso.md +24 -24
  110. package/kit/commands/proximo.md +30 -30
  111. package/kit/commands/publicar.md +490 -490
  112. package/kit/commands/rapido.md +35 -35
  113. package/kit/commands/reaplicar-patches.md +124 -124
  114. package/kit/commands/refactor-seguro.md +1 -1
  115. package/kit/commands/relatorio-sessao.md +19 -19
  116. package/kit/commands/remover-fase.md +31 -31
  117. package/kit/commands/remover-workspace.md +26 -26
  118. package/kit/commands/resumo-marco.md +50 -50
  119. package/kit/commands/retomar-trabalho.md +40 -40
  120. package/kit/commands/revisar-backlog.md +60 -60
  121. package/kit/commands/revisar-ui.md +32 -32
  122. package/kit/commands/revisar.md +37 -37
  123. package/kit/commands/saude.md +21 -21
  124. package/kit/commands/setup-notion.md +93 -93
  125. package/kit/commands/storytelling.md +1 -1
  126. package/kit/commands/supabase.md +1 -1
  127. package/kit/commands/sync-main.md +68 -68
  128. package/kit/commands/validar-fase.md +35 -35
  129. package/kit/commands/verificar-tarefas.md +44 -44
  130. package/kit/commands/verificar-trabalho.md +64 -64
  131. package/kit/file-manifest.json +93 -86
  132. package/kit/framework/bin/lib/commands.cjs +959 -959
  133. package/kit/framework/bin/lib/config.cjs +442 -442
  134. package/kit/framework/bin/lib/core.cjs +1230 -1230
  135. package/kit/framework/bin/lib/frontmatter.cjs +336 -336
  136. package/kit/framework/bin/lib/init.cjs +1442 -1442
  137. package/kit/framework/bin/lib/milestone.cjs +252 -252
  138. package/kit/framework/bin/lib/model-profiles.cjs +68 -68
  139. package/kit/framework/bin/lib/phase.cjs +888 -888
  140. package/kit/framework/bin/lib/profile-output.cjs +952 -952
  141. package/kit/framework/bin/lib/profile-pipeline.cjs +539 -539
  142. package/kit/framework/bin/lib/roadmap.cjs +329 -329
  143. package/kit/framework/bin/lib/security.cjs +382 -382
  144. package/kit/framework/bin/lib/state.cjs +1031 -1031
  145. package/kit/framework/bin/lib/template.cjs +222 -222
  146. package/kit/framework/bin/lib/uat.cjs +282 -282
  147. package/kit/framework/bin/lib/verify.cjs +888 -888
  148. package/kit/framework/bin/lib/workstream.cjs +491 -491
  149. package/kit/framework/bin/tools.cjs +918 -918
  150. package/kit/framework/commands/workstreams.md +63 -63
  151. package/kit/framework/references/checkpoints.md +778 -778
  152. package/kit/framework/references/continuation-format.md +249 -249
  153. package/kit/framework/references/decimal-phase-calculation.md +64 -64
  154. package/kit/framework/references/git-integration.md +295 -295
  155. package/kit/framework/references/git-planning-commit.md +38 -38
  156. package/kit/framework/references/model-profile-resolution.md +36 -36
  157. package/kit/framework/references/model-profiles.md +139 -139
  158. package/kit/framework/references/phase-argument-parsing.md +61 -61
  159. package/kit/framework/references/planning-config.md +202 -202
  160. package/kit/framework/references/questioning.md +162 -162
  161. package/kit/framework/references/tdd.md +263 -263
  162. package/kit/framework/references/ui-brand.md +160 -160
  163. package/kit/framework/references/user-profiling.md +657 -657
  164. package/kit/framework/references/verification-patterns.md +612 -612
  165. package/kit/framework/references/workstream-flag.md +58 -58
  166. package/kit/framework/templates/DEBUG.md +164 -164
  167. package/kit/framework/templates/UAT.md +265 -265
  168. package/kit/framework/templates/UI-SPEC.md +100 -100
  169. package/kit/framework/templates/VALIDATION.md +76 -76
  170. package/kit/framework/templates/claude-md.md +122 -122
  171. package/kit/framework/templates/codebase/architecture.md +185 -185
  172. package/kit/framework/templates/codebase/concerns.md +205 -205
  173. package/kit/framework/templates/codebase/conventions.md +204 -204
  174. package/kit/framework/templates/codebase/integrations.md +192 -192
  175. package/kit/framework/templates/codebase/stack.md +158 -158
  176. package/kit/framework/templates/codebase/structure.md +199 -199
  177. package/kit/framework/templates/codebase/testing.md +301 -301
  178. package/kit/framework/templates/config.json +44 -44
  179. package/kit/framework/templates/context.md +352 -352
  180. package/kit/framework/templates/continue-here.md +78 -78
  181. package/kit/framework/templates/copilot-instructions.md +7 -7
  182. package/kit/framework/templates/debug-subagent-prompt.md +91 -91
  183. package/kit/framework/templates/dev-preferences.md +20 -20
  184. package/kit/framework/templates/discovery.md +146 -146
  185. package/kit/framework/templates/discussion-log.md +63 -63
  186. package/kit/framework/templates/milestone-archive.md +123 -123
  187. package/kit/framework/templates/milestone.md +115 -115
  188. package/kit/framework/templates/phase-prompt.md +610 -610
  189. package/kit/framework/templates/planner-subagent-prompt.md +117 -117
  190. package/kit/framework/templates/project.md +186 -186
  191. package/kit/framework/templates/requirements.md +231 -231
  192. package/kit/framework/templates/research-project/ARCHITECTURE.md +204 -204
  193. package/kit/framework/templates/research-project/FEATURES.md +147 -147
  194. package/kit/framework/templates/research-project/PITFALLS.md +200 -200
  195. package/kit/framework/templates/research-project/STACK.md +120 -120
  196. package/kit/framework/templates/research-project/SUMMARY.md +170 -170
  197. package/kit/framework/templates/research.md +419 -419
  198. package/kit/framework/templates/retrospective.md +54 -54
  199. package/kit/framework/templates/roadmap.md +202 -202
  200. package/kit/framework/templates/state.md +176 -176
  201. package/kit/framework/templates/summary-complex.md +59 -59
  202. package/kit/framework/templates/summary-minimal.md +41 -41
  203. package/kit/framework/templates/summary-standard.md +48 -48
  204. package/kit/framework/templates/summary.md +209 -209
  205. package/kit/framework/templates/user-profile.md +146 -146
  206. package/kit/framework/templates/user-setup.md +256 -256
  207. package/kit/framework/templates/verification-report.md +258 -258
  208. package/kit/framework/workflows/add-phase.md +112 -112
  209. package/kit/framework/workflows/add-tests.md +351 -351
  210. package/kit/framework/workflows/add-todo.md +158 -158
  211. package/kit/framework/workflows/audit-milestone.md +340 -340
  212. package/kit/framework/workflows/audit-uat.md +109 -109
  213. package/kit/framework/workflows/autonomous.md +891 -891
  214. package/kit/framework/workflows/check-todos.md +177 -177
  215. package/kit/framework/workflows/cleanup.md +152 -152
  216. package/kit/framework/workflows/complete-milestone.md +696 -696
  217. package/kit/framework/workflows/diagnose-issues.md +231 -231
  218. package/kit/framework/workflows/discovery-phase.md +289 -289
  219. package/kit/framework/workflows/discuss-phase-assumptions.md +653 -653
  220. package/kit/framework/workflows/discuss-phase.md +784 -784
  221. package/kit/framework/workflows/do.md +104 -104
  222. package/kit/framework/workflows/execute-phase.md +838 -838
  223. package/kit/framework/workflows/execute-plan.md +510 -510
  224. package/kit/framework/workflows/fast.md +102 -102
  225. package/kit/framework/workflows/forensics.md +265 -265
  226. package/kit/framework/workflows/health.md +181 -181
  227. package/kit/framework/workflows/help.md +619 -619
  228. package/kit/framework/workflows/insert-phase.md +130 -130
  229. package/kit/framework/workflows/list-phase-assumptions.md +178 -178
  230. package/kit/framework/workflows/list-workspaces.md +56 -56
  231. package/kit/framework/workflows/manager.md +362 -362
  232. package/kit/framework/workflows/map-codebase.md +377 -377
  233. package/kit/framework/workflows/milestone-summary.md +223 -223
  234. package/kit/framework/workflows/new-milestone.md +486 -486
  235. package/kit/framework/workflows/new-project.md +1159 -1159
  236. package/kit/framework/workflows/new-workspace.md +237 -237
  237. package/kit/framework/workflows/next.md +97 -97
  238. package/kit/framework/workflows/node-repair.md +92 -92
  239. package/kit/framework/workflows/note.md +156 -156
  240. package/kit/framework/workflows/pause-work.md +176 -176
  241. package/kit/framework/workflows/plan-milestone-gaps.md +273 -273
  242. package/kit/framework/workflows/plan-phase.md +765 -765
  243. package/kit/framework/workflows/plant-seed.md +169 -169
  244. package/kit/framework/workflows/pr-branch.md +129 -129
  245. package/kit/framework/workflows/profile-user.md +450 -450
  246. package/kit/framework/workflows/progress.md +507 -507
  247. package/kit/framework/workflows/quick.md +757 -757
  248. package/kit/framework/workflows/remove-phase.md +155 -155
  249. package/kit/framework/workflows/remove-workspace.md +90 -90
  250. package/kit/framework/workflows/research-phase.md +82 -82
  251. package/kit/framework/workflows/resume-project.md +326 -326
  252. package/kit/framework/workflows/review.md +228 -228
  253. package/kit/framework/workflows/session-report.md +146 -146
  254. package/kit/framework/workflows/settings.md +283 -283
  255. package/kit/framework/workflows/ship.md +228 -228
  256. package/kit/framework/workflows/stats.md +60 -60
  257. package/kit/framework/workflows/transition.md +671 -671
  258. package/kit/framework/workflows/ui-phase.md +302 -302
  259. package/kit/framework/workflows/ui-review.md +165 -165
  260. package/kit/framework/workflows/update.md +323 -323
  261. package/kit/framework/workflows/validate-phase.md +174 -174
  262. package/kit/framework/workflows/verify-phase.md +252 -252
  263. package/kit/framework/workflows/verify-work.md +637 -637
  264. package/kit/hooks/check-update.js +118 -118
  265. package/kit/hooks/context-monitor.js +163 -163
  266. package/kit/hooks/prompt-guard.js +103 -103
  267. package/kit/hooks/statusline.js +125 -125
  268. package/kit/hooks/workflow-guard.js +101 -101
  269. package/kit/settings.json +45 -45
  270. package/kit/skills/_shared-supabase/glossary.md +10 -0
  271. package/kit/skills/ai-prompt-characterization/SKILL.md +1 -1
  272. package/kit/skills/armadilhas-sistemas-distribuidos/SKILL.md +1 -1
  273. package/kit/skills/audit-log-multi-tenant/SKILL.md +1 -1
  274. package/kit/skills/b2b-saas-architecture/SKILL.md +1 -1
  275. package/kit/skills/consistencia-leitura-replica/SKILL.md +1 -1
  276. package/kit/skills/crm-lead-pipeline-patterns/SKILL.md +1 -1
  277. package/kit/skills/escolha-modelo-consistencia/SKILL.md +1 -1
  278. package/kit/skills/evolucao-schema-compativel/SKILL.md +1 -1
  279. package/kit/skills/evolution-go-whatsapp-integration/SKILL.md +1 -1
  280. package/kit/skills/example-skill/SKILL.md +42 -42
  281. package/kit/skills/legacy-api-only-applications/SKILL.md +1 -1
  282. package/kit/skills/legacy-characterization-tests/SKILL.md +1 -1
  283. package/kit/skills/legacy-effect-analysis/SKILL.md +1 -1
  284. package/kit/skills/legacy-extract-class/SKILL.md +1 -1
  285. package/kit/skills/legacy-programming-by-difference/SKILL.md +1 -1
  286. package/kit/skills/legacy-seams-and-test-harness/SKILL.md +1 -1
  287. package/kit/skills/legacy-shotgun-surgery/SKILL.md +1 -1
  288. package/kit/skills/legacy-sprout-wrap-techniques/SKILL.md +1 -1
  289. package/kit/skills/legacy-storytelling-naked-crc/SKILL.md +1 -1
  290. package/kit/skills/lgpd-multi-tenant-compliance/SKILL.md +1 -1
  291. package/kit/skills/member-invite-flow/SKILL.md +1 -1
  292. package/kit/skills/member-management-react-shadcn/SKILL.md +1 -1
  293. package/kit/skills/multi-tenant-performance-scaling/SKILL.md +1 -1
  294. package/kit/skills/multi-tenant-rls-hierarchy/SKILL.md +1 -1
  295. package/kit/skills/org-onboarding-flow/SKILL.md +1 -1
  296. package/kit/skills/org-switcher-react-pattern/SKILL.md +1 -1
  297. package/kit/skills/permission-gate-react-pattern/SKILL.md +1 -1
  298. package/kit/skills/postgres-isolamento-concorrencia/SKILL.md +1 -1
  299. package/kit/skills/pre-refactor-characterization/SKILL.md +1 -1
  300. package/kit/skills/rbac-permissions-matrix-supabase/SKILL.md +1 -1
  301. package/kit/skills/streams-eventos-cdc/SKILL.md +1 -1
  302. package/kit/skills/supabase-branching-workflow/SKILL.md +544 -0
  303. package/kit/skills/supabase-ci-cd-github-actions/SKILL.md +880 -0
  304. package/kit/skills/supabase-column-level-security/SKILL.md +1 -1
  305. package/kit/skills/supabase-config-toml-remotes/SKILL.md +807 -0
  306. package/kit/skills/supabase-custom-claims-rbac/SKILL.md +1 -1
  307. package/kit/skills/supabase-migration-repair/SKILL.md +823 -0
  308. package/kit/skills/supabase-migrations/SKILL.md +1 -1
  309. package/kit/skills/supabase-pgtap-testing/SKILL.md +1053 -0
  310. package/kit/skills/supabase-postgres-roles/SKILL.md +1 -1
  311. package/kit/skills/supabase-rls-defense-in-depth/SKILL.md +1 -1
  312. package/kit/skills/supabase-rls-policies/SKILL.md +1 -1
  313. package/kit/skills/super-admin-platform-pattern/SKILL.md +1 -1
  314. package/kit/skills/tenant-quente-mitigacao/SKILL.md +1 -1
  315. package/kit/skills/whatsapp-conversation-state-machine/SKILL.md +1 -1
  316. package/package.json +63 -63
  317. package/src/cli/index.js +345 -6
  318. package/src/cli/render.js +7 -0
  319. package/src/core/kit.js +216 -216
  320. package/src/core/logger.js +170 -0
  321. package/src/core/notify.js +60 -0
  322. package/src/core/reflect.js +247 -247
  323. package/src/core/reverse-sync.js +372 -372
  324. package/src/core/sync.js +418 -418
  325. package/src/core/watch.js +121 -121
  326. package/src/mcp-server/index.js +65 -2
@@ -1,888 +1,888 @@
1
- /**
2
- * Phase — Phase CRUD, query, and lifecycle operations
3
- */
4
-
5
- const fs = require('fs');
6
- const path = require('path');
7
- const { escapeRegex, loadConfig, normalizePhaseName, comparePhaseNum, findPhaseInternal, getArchivedPhaseDirs, generateSlugInternal, getMilestonePhaseFilter, stripShippedMilestones, extractCurrentMilestone, replaceInCurrentMilestone, toPosixPath, planningDir, output, error, readSubdirectories } = require('./core.cjs');
8
- const { extractFrontmatter } = require('./frontmatter.cjs');
9
- const { writeStateMd, stateExtractField, stateReplaceField, stateReplaceFieldWithFallback } = require('./state.cjs');
10
-
11
- function cmdPhasesList(cwd, options, raw) {
12
- const phasesDir = path.join(planningDir(cwd), 'phases');
13
- const { type, phase, includeArchived } = options;
14
-
15
- // If no phases directory, return empty
16
- if (!fs.existsSync(phasesDir)) {
17
- if (type) {
18
- output({ files: [], count: 0 }, raw, '');
19
- } else {
20
- output({ directories: [], count: 0 }, raw, '');
21
- }
22
- return;
23
- }
24
-
25
- try {
26
- // Get all phase directories
27
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
28
- let dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
29
-
30
- // Include archived phases if requested
31
- if (includeArchived) {
32
- const archived = getArchivedPhaseDirs(cwd);
33
- for (const a of archived) {
34
- dirs.push(`${a.name} [${a.milestone}]`);
35
- }
36
- }
37
-
38
- // Sort numerically (handles integers, decimals, letter-suffix, hybrids)
39
- dirs.sort((a, b) => comparePhaseNum(a, b));
40
-
41
- // If filtering by phase number
42
- if (phase) {
43
- const normalized = normalizePhaseName(phase);
44
- const match = dirs.find(d => d.startsWith(normalized));
45
- if (!match) {
46
- output({ files: [], count: 0, phase_dir: null, error: 'Phase not found' }, raw, '');
47
- return;
48
- }
49
- dirs = [match];
50
- }
51
-
52
- // If listing files of a specific type
53
- if (type) {
54
- const files = [];
55
- for (const dir of dirs) {
56
- const dirPath = path.join(phasesDir, dir);
57
- const dirFiles = fs.readdirSync(dirPath);
58
-
59
- let filtered;
60
- if (type === 'plans') {
61
- filtered = dirFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
62
- } else if (type === 'summaries') {
63
- filtered = dirFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
64
- } else {
65
- filtered = dirFiles;
66
- }
67
-
68
- files.push(...filtered.sort());
69
- }
70
-
71
- const result = {
72
- files,
73
- count: files.length,
74
- phase_dir: phase ? dirs[0].replace(/^\d+(?:\.\d+)*-?/, '') : null,
75
- };
76
- output(result, raw, files.join('\n'));
77
- return;
78
- }
79
-
80
- // Default: list directories
81
- output({ directories: dirs, count: dirs.length }, raw, dirs.join('\n'));
82
- } catch (e) {
83
- error('Failed to list phases: ' + e.message);
84
- }
85
- }
86
-
87
- function cmdPhaseNextDecimal(cwd, basePhase, raw) {
88
- const phasesDir = path.join(planningDir(cwd), 'phases');
89
- const normalized = normalizePhaseName(basePhase);
90
-
91
- // Check if phases directory exists
92
- if (!fs.existsSync(phasesDir)) {
93
- output(
94
- {
95
- found: false,
96
- base_phase: normalized,
97
- next: `${normalized}.1`,
98
- existing: [],
99
- },
100
- raw,
101
- `${normalized}.1`
102
- );
103
- return;
104
- }
105
-
106
- try {
107
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
108
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
109
-
110
- // Check if base phase exists
111
- const baseExists = dirs.some(d => d.startsWith(normalized + '-') || d === normalized);
112
-
113
- // Find existing decimal phases for this base
114
- const decimalPattern = new RegExp(`^${normalized}\\.(\\d+)`);
115
- const existingDecimals = [];
116
-
117
- for (const dir of dirs) {
118
- const match = dir.match(decimalPattern);
119
- if (match) {
120
- existingDecimals.push(`${normalized}.${match[1]}`);
121
- }
122
- }
123
-
124
- // Sort numerically
125
- existingDecimals.sort((a, b) => comparePhaseNum(a, b));
126
-
127
- // Calculate next decimal
128
- let nextDecimal;
129
- if (existingDecimals.length === 0) {
130
- nextDecimal = `${normalized}.1`;
131
- } else {
132
- const lastDecimal = existingDecimals[existingDecimals.length - 1];
133
- const lastNum = parseInt(lastDecimal.split('.')[1], 10);
134
- nextDecimal = `${normalized}.${lastNum + 1}`;
135
- }
136
-
137
- output(
138
- {
139
- found: baseExists,
140
- base_phase: normalized,
141
- next: nextDecimal,
142
- existing: existingDecimals,
143
- },
144
- raw,
145
- nextDecimal
146
- );
147
- } catch (e) {
148
- error('Failed to calculate next decimal phase: ' + e.message);
149
- }
150
- }
151
-
152
- function cmdFindPhase(cwd, phase, raw) {
153
- if (!phase) {
154
- error('phase identifier required');
155
- }
156
-
157
- const phasesDir = path.join(planningDir(cwd), 'phases');
158
- const normalized = normalizePhaseName(phase);
159
-
160
- const notFound = { found: false, directory: null, phase_number: null, phase_name: null, plans: [], summaries: [] };
161
-
162
- try {
163
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
164
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
165
-
166
- const match = dirs.find(d => d.startsWith(normalized));
167
- if (!match) {
168
- output(notFound, raw, '');
169
- return;
170
- }
171
-
172
- const dirMatch = match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
173
- const phaseNumber = dirMatch ? dirMatch[1] : normalized;
174
- const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
175
-
176
- const phaseDir = path.join(phasesDir, match);
177
- const phaseFiles = fs.readdirSync(phaseDir);
178
- const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
179
- const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').sort();
180
-
181
- const result = {
182
- found: true,
183
- directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', match)),
184
- phase_number: phaseNumber,
185
- phase_name: phaseName,
186
- plans,
187
- summaries,
188
- };
189
-
190
- output(result, raw, result.directory);
191
- } catch {
192
- output(notFound, raw, '');
193
- }
194
- }
195
-
196
- function extractObjective(content) {
197
- const m = content.match(/<objective>\s*\n?\s*(.+)/);
198
- return m ? m[1].trim() : null;
199
- }
200
-
201
- function cmdPhasePlanIndex(cwd, phase, raw) {
202
- if (!phase) {
203
- error('phase required for phase-plan-index');
204
- }
205
-
206
- const phasesDir = path.join(planningDir(cwd), 'phases');
207
- const normalized = normalizePhaseName(phase);
208
-
209
- // Find phase directory
210
- let phaseDir = null;
211
- let phaseDirName = null;
212
- try {
213
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
214
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
215
- const match = dirs.find(d => d.startsWith(normalized));
216
- if (match) {
217
- phaseDir = path.join(phasesDir, match);
218
- phaseDirName = match;
219
- }
220
- } catch {
221
- // phases dir doesn't exist
222
- }
223
-
224
- if (!phaseDir) {
225
- output({ phase: normalized, error: 'Phase not found', plans: [], waves: {}, incomplete: [], has_checkpoints: false }, raw);
226
- return;
227
- }
228
-
229
- // Get all files in phase directory
230
- const phaseFiles = fs.readdirSync(phaseDir);
231
- const planFiles = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
232
- const summaryFiles = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
233
-
234
- // Build set of plan IDs with summaries
235
- const completedPlanIds = new Set(
236
- summaryFiles.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', ''))
237
- );
238
-
239
- const plans = [];
240
- const waves = {};
241
- const incomplete = [];
242
- let hasCheckpoints = false;
243
-
244
- for (const planFile of planFiles) {
245
- const planId = planFile.replace('-PLAN.md', '').replace('PLAN.md', '');
246
- const planPath = path.join(phaseDir, planFile);
247
- const content = fs.readFileSync(planPath, 'utf-8');
248
- const fm = extractFrontmatter(content);
249
-
250
- // Count tasks: XML <task> tags (canonical) or ## Task N markdown (legacy)
251
- const xmlTasks = content.match(/<task[\s>]/gi) || [];
252
- const mdTasks = content.match(/##\s*Task\s*\d+/gi) || [];
253
- const taskCount = xmlTasks.length || mdTasks.length;
254
-
255
- // Parse wave as integer
256
- const wave = parseInt(fm.wave, 10) || 1;
257
-
258
- // Parse autonomous (default true if not specified)
259
- let autonomous = true;
260
- if (fm.autonomous !== undefined) {
261
- autonomous = fm.autonomous === 'true' || fm.autonomous === true;
262
- }
263
-
264
- if (!autonomous) {
265
- hasCheckpoints = true;
266
- }
267
-
268
- // Parse files_modified (underscore is canonical; also accept hyphenated for compat)
269
- let filesModified = [];
270
- const fmFiles = fm['files_modified'] || fm['files-modified'];
271
- if (fmFiles) {
272
- filesModified = Array.isArray(fmFiles) ? fmFiles : [fmFiles];
273
- }
274
-
275
- const hasSummary = completedPlanIds.has(planId);
276
- if (!hasSummary) {
277
- incomplete.push(planId);
278
- }
279
-
280
- const plan = {
281
- id: planId,
282
- wave,
283
- autonomous,
284
- objective: extractObjective(content) || fm.objective || null,
285
- files_modified: filesModified,
286
- task_count: taskCount,
287
- has_summary: hasSummary,
288
- };
289
-
290
- plans.push(plan);
291
-
292
- // Group by wave
293
- const waveKey = String(wave);
294
- if (!waves[waveKey]) {
295
- waves[waveKey] = [];
296
- }
297
- waves[waveKey].push(planId);
298
- }
299
-
300
- const result = {
301
- phase: normalized,
302
- plans,
303
- waves,
304
- incomplete,
305
- has_checkpoints: hasCheckpoints,
306
- };
307
-
308
- output(result, raw);
309
- }
310
-
311
- function cmdPhaseAdd(cwd, description, raw, customId) {
312
- if (!description) {
313
- error('description required for phase add');
314
- }
315
-
316
- const config = loadConfig(cwd);
317
- const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
318
- if (!fs.existsSync(roadmapPath)) {
319
- error('ROADMAP.md not found');
320
- }
321
-
322
- const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
323
- const content = extractCurrentMilestone(rawContent, cwd);
324
- const slug = generateSlugInternal(description);
325
-
326
- let newPhaseId;
327
- let dirName;
328
-
329
- if (customId || config.phase_naming === 'custom') {
330
- // Custom phase naming: use provided ID or generate from description
331
- newPhaseId = customId || slug.toUpperCase().replace(/-/g, '-');
332
- if (!newPhaseId) error('--id required when phase_naming is "custom"');
333
- dirName = `${newPhaseId}-${slug}`;
334
- } else {
335
- // Sequential mode: find highest integer phase number (in current milestone only)
336
- const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
337
- let maxPhase = 0;
338
- let m;
339
- while ((m = phasePattern.exec(content)) !== null) {
340
- const num = parseInt(m[1], 10);
341
- if (num > maxPhase) maxPhase = num;
342
- }
343
-
344
- newPhaseId = maxPhase + 1;
345
- const paddedNum = String(newPhaseId).padStart(2, '0');
346
- dirName = `${paddedNum}-${slug}`;
347
- }
348
-
349
- const dirPath = path.join(planningDir(cwd), 'phases', dirName);
350
-
351
- // Create directory with .gitkeep so git tracks empty folders
352
- fs.mkdirSync(dirPath, { recursive: true });
353
- fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
354
-
355
- // Build phase entry
356
- const dependsOn = config.phase_naming === 'custom' ? '' : `\n**Depends on:** Phase ${typeof newPhaseId === 'number' ? newPhaseId - 1 : 'TBD'}`;
357
- const phaseEntry = `\n### Phase ${newPhaseId}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD${dependsOn}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /plan-phase ${newPhaseId} to break down)\n`;
358
-
359
- // Find insertion point: before last "---" or at end
360
- let updatedContent;
361
- const lastSeparator = rawContent.lastIndexOf('\n---');
362
- if (lastSeparator > 0) {
363
- updatedContent = rawContent.slice(0, lastSeparator) + phaseEntry + rawContent.slice(lastSeparator);
364
- } else {
365
- updatedContent = rawContent + phaseEntry;
366
- }
367
-
368
- fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
369
-
370
- const result = {
371
- phase_number: typeof newPhaseId === 'number' ? newPhaseId : String(newPhaseId),
372
- padded: typeof newPhaseId === 'number' ? String(newPhaseId).padStart(2, '0') : String(newPhaseId),
373
- name: description,
374
- slug,
375
- directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', dirName)),
376
- naming_mode: config.phase_naming,
377
- };
378
-
379
- output(result, raw, result.padded);
380
- }
381
-
382
- function cmdPhaseInsert(cwd, afterPhase, description, raw) {
383
- if (!afterPhase || !description) {
384
- error('after-phase and description required for phase insert');
385
- }
386
-
387
- const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
388
- if (!fs.existsSync(roadmapPath)) {
389
- error('ROADMAP.md not found');
390
- }
391
-
392
- const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
393
- const content = extractCurrentMilestone(rawContent, cwd);
394
- const slug = generateSlugInternal(description);
395
-
396
- // Normalize input then strip leading zeros for flexible matching
397
- const normalizedAfter = normalizePhaseName(afterPhase);
398
- const unpadded = normalizedAfter.replace(/^0+/, '');
399
- const afterPhaseEscaped = unpadded.replace(/\./g, '\\.');
400
- const targetPattern = new RegExp(`#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:`, 'i');
401
- if (!targetPattern.test(content)) {
402
- error(`Phase ${afterPhase} not found in ROADMAP.md`);
403
- }
404
-
405
- // Calculate next decimal using existing logic
406
- const phasesDir = path.join(planningDir(cwd), 'phases');
407
- const normalizedBase = normalizePhaseName(afterPhase);
408
- let existingDecimals = [];
409
-
410
- try {
411
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
412
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
413
- const decimalPattern = new RegExp(`^${normalizedBase}\\.(\\d+)`);
414
- for (const dir of dirs) {
415
- const dm = dir.match(decimalPattern);
416
- if (dm) existingDecimals.push(parseInt(dm[1], 10));
417
- }
418
- } catch { /* intentionally empty */ }
419
-
420
- const nextDecimal = existingDecimals.length === 0 ? 1 : Math.max(...existingDecimals) + 1;
421
- const decimalPhase = `${normalizedBase}.${nextDecimal}`;
422
- const dirName = `${decimalPhase}-${slug}`;
423
- const dirPath = path.join(planningDir(cwd), 'phases', dirName);
424
-
425
- // Create directory with .gitkeep so git tracks empty folders
426
- fs.mkdirSync(dirPath, { recursive: true });
427
- fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
428
-
429
- // Build phase entry
430
- const phaseEntry = `\n### Phase ${decimalPhase}: ${description} (INSERTED)\n\n**Goal:** [Urgent work - to be planned]\n**Requirements**: TBD\n**Depends on:** Phase ${afterPhase}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /plan-phase ${decimalPhase} to break down)\n`;
431
-
432
- // Insert after the target phase section
433
- const headerPattern = new RegExp(`(#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:[^\\n]*\\n)`, 'i');
434
- const headerMatch = rawContent.match(headerPattern);
435
- if (!headerMatch) {
436
- error(`Could not find Phase ${afterPhase} header`);
437
- }
438
-
439
- const headerIdx = rawContent.indexOf(headerMatch[0]);
440
- const afterHeader = rawContent.slice(headerIdx + headerMatch[0].length);
441
- const nextPhaseMatch = afterHeader.match(/\n#{2,4}\s+Phase\s+\d/i);
442
-
443
- let insertIdx;
444
- if (nextPhaseMatch) {
445
- insertIdx = headerIdx + headerMatch[0].length + nextPhaseMatch.index;
446
- } else {
447
- insertIdx = rawContent.length;
448
- }
449
-
450
- const updatedContent = rawContent.slice(0, insertIdx) + phaseEntry + rawContent.slice(insertIdx);
451
- fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
452
-
453
- const result = {
454
- phase_number: decimalPhase,
455
- after_phase: afterPhase,
456
- name: description,
457
- slug,
458
- directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', dirName)),
459
- };
460
-
461
- output(result, raw, decimalPhase);
462
- }
463
-
464
- /**
465
- * Renumber sibling decimal phases after a decimal phase is removed.
466
- * e.g. removing 06.2 → 06.3 becomes 06.2, 06.4 becomes 06.3, etc.
467
- * Returns { renamedDirs, renamedFiles }.
468
- */
469
- function renameDecimalPhases(phasesDir, baseInt, removedDecimal) {
470
- const renamedDirs = [], renamedFiles = [];
471
- const decPattern = new RegExp(`^${baseInt}\\.(\\d+)-(.+)$`);
472
- const dirs = readSubdirectories(phasesDir, true);
473
- const toRename = dirs
474
- .map(dir => { const m = dir.match(decPattern); return m ? { dir, oldDecimal: parseInt(m[1], 10), slug: m[2] } : null; })
475
- .filter(item => item && item.oldDecimal > removedDecimal)
476
- .sort((a, b) => b.oldDecimal - a.oldDecimal); // descending to avoid conflicts
477
-
478
- for (const item of toRename) {
479
- const newDecimal = item.oldDecimal - 1;
480
- const oldPhaseId = `${baseInt}.${item.oldDecimal}`;
481
- const newPhaseId = `${baseInt}.${newDecimal}`;
482
- const newDirName = `${baseInt}.${newDecimal}-${item.slug}`;
483
- fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
484
- renamedDirs.push({ from: item.dir, to: newDirName });
485
- for (const f of fs.readdirSync(path.join(phasesDir, newDirName))) {
486
- if (f.includes(oldPhaseId)) {
487
- const newFileName = f.replace(oldPhaseId, newPhaseId);
488
- fs.renameSync(path.join(phasesDir, newDirName, f), path.join(phasesDir, newDirName, newFileName));
489
- renamedFiles.push({ from: f, to: newFileName });
490
- }
491
- }
492
- }
493
- return { renamedDirs, renamedFiles };
494
- }
495
-
496
- /**
497
- * Renumber all integer phases after removedInt.
498
- * e.g. removing phase 5 → phase 6 becomes 5, phase 7 becomes 6, etc.
499
- * Returns { renamedDirs, renamedFiles }.
500
- */
501
- function renameIntegerPhases(phasesDir, removedInt) {
502
- const renamedDirs = [], renamedFiles = [];
503
- const dirs = readSubdirectories(phasesDir, true);
504
- const toRename = dirs
505
- .map(dir => {
506
- const m = dir.match(/^(\d+)([A-Z])?(?:\.(\d+))?-(.+)$/i);
507
- if (!m) return null;
508
- const dirInt = parseInt(m[1], 10);
509
- return dirInt > removedInt ? { dir, oldInt: dirInt, letter: m[2] ? m[2].toUpperCase() : '', decimal: m[3] ? parseInt(m[3], 10) : null, slug: m[4] } : null;
510
- })
511
- .filter(Boolean)
512
- .sort((a, b) => a.oldInt !== b.oldInt ? b.oldInt - a.oldInt : (b.decimal || 0) - (a.decimal || 0));
513
-
514
- for (const item of toRename) {
515
- const newInt = item.oldInt - 1;
516
- const newPadded = String(newInt).padStart(2, '0');
517
- const oldPadded = String(item.oldInt).padStart(2, '0');
518
- const letterSuffix = item.letter || '';
519
- const decimalSuffix = item.decimal !== null ? `.${item.decimal}` : '';
520
- const oldPrefix = `${oldPadded}${letterSuffix}${decimalSuffix}`;
521
- const newPrefix = `${newPadded}${letterSuffix}${decimalSuffix}`;
522
- const newDirName = `${newPrefix}-${item.slug}`;
523
- fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
524
- renamedDirs.push({ from: item.dir, to: newDirName });
525
- for (const f of fs.readdirSync(path.join(phasesDir, newDirName))) {
526
- if (f.startsWith(oldPrefix)) {
527
- const newFileName = newPrefix + f.slice(oldPrefix.length);
528
- fs.renameSync(path.join(phasesDir, newDirName, f), path.join(phasesDir, newDirName, newFileName));
529
- renamedFiles.push({ from: f, to: newFileName });
530
- }
531
- }
532
- }
533
- return { renamedDirs, renamedFiles };
534
- }
535
-
536
- /**
537
- * Remove a phase section from ROADMAP.md and renumber all subsequent integer phases.
538
- */
539
- function updateRoadmapAfterPhaseRemoval(roadmapPath, targetPhase, isDecimal, removedInt) {
540
- let content = fs.readFileSync(roadmapPath, 'utf-8');
541
- const escaped = escapeRegex(targetPhase);
542
-
543
- content = content.replace(new RegExp(`\\n?#{2,4}\\s*Phase\\s+${escaped}\\s*:[\\s\\S]*?(?=\\n#{2,4}\\s+Phase\\s+\\d|$)`, 'i'), '');
544
- content = content.replace(new RegExp(`\\n?-\\s*\\[[ x]\\]\\s*.*Phase\\s+${escaped}[:\\s][^\\n]*`, 'gi'), '');
545
- content = content.replace(new RegExp(`\\n?\\|\\s*${escaped}\\.?\\s[^|]*\\|[^\\n]*`, 'gi'), '');
546
-
547
- if (!isDecimal) {
548
- const MAX_PHASE = 99;
549
- for (let oldNum = MAX_PHASE; oldNum > removedInt; oldNum--) {
550
- const newNum = oldNum - 1;
551
- const oldStr = String(oldNum), newStr = String(newNum);
552
- const oldPad = oldStr.padStart(2, '0'), newPad = newStr.padStart(2, '0');
553
- content = content.replace(new RegExp(`(#{2,4}\\s*Phase\\s+)${oldStr}(\\s*:)`, 'gi'), `$1${newStr}$2`);
554
- content = content.replace(new RegExp(`(Phase\\s+)${oldStr}([:\\s])`, 'g'), `$1${newStr}$2`);
555
- content = content.replace(new RegExp(`${oldPad}-(\\d{2})`, 'g'), `${newPad}-$1`);
556
- content = content.replace(new RegExp(`(\\|\\s*)${oldStr}\\.\\s`, 'g'), `$1${newStr}. `);
557
- content = content.replace(new RegExp(`(Depends on:\\*\\*\\s*Phase\\s+)${oldStr}\\b`, 'gi'), `$1${newStr}`);
558
- }
559
- }
560
-
561
- fs.writeFileSync(roadmapPath, content, 'utf-8');
562
- }
563
-
564
- function cmdPhaseRemove(cwd, targetPhase, options, raw) {
565
- if (!targetPhase) error('phase number required for phase remove');
566
-
567
- const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
568
- const phasesDir = path.join(planningDir(cwd), 'phases');
569
-
570
- if (!fs.existsSync(roadmapPath)) error('ROADMAP.md not found');
571
-
572
- const normalized = normalizePhaseName(targetPhase);
573
- const isDecimal = targetPhase.includes('.');
574
- const force = options.force || false;
575
-
576
- // Find target directory
577
- const targetDir = readSubdirectories(phasesDir, true)
578
- .find(d => d.startsWith(normalized + '-') || d === normalized) || null;
579
-
580
- // Guard against removing executed work
581
- if (targetDir && !force) {
582
- const files = fs.readdirSync(path.join(phasesDir, targetDir));
583
- const summaries = files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
584
- if (summaries.length > 0) {
585
- error(`Phase ${targetPhase} has ${summaries.length} executed plan(s). Use --force to remove anyway.`);
586
- }
587
- }
588
-
589
- if (targetDir) fs.rmSync(path.join(phasesDir, targetDir), { recursive: true, force: true });
590
-
591
- // Renumber subsequent phases on disk
592
- let renamedDirs = [], renamedFiles = [];
593
- try {
594
- const renamed = isDecimal
595
- ? renameDecimalPhases(phasesDir, normalized.split('.')[0], parseInt(normalized.split('.')[1], 10))
596
- : renameIntegerPhases(phasesDir, parseInt(normalized, 10));
597
- renamedDirs = renamed.renamedDirs;
598
- renamedFiles = renamed.renamedFiles;
599
- } catch { /* intentionally empty */ }
600
-
601
- // Update ROADMAP.md
602
- updateRoadmapAfterPhaseRemoval(roadmapPath, targetPhase, isDecimal, parseInt(normalized, 10));
603
-
604
- // Update STATE.md phase count
605
- const statePath = path.join(planningDir(cwd), 'STATE.md');
606
- if (fs.existsSync(statePath)) {
607
- let stateContent = fs.readFileSync(statePath, 'utf-8');
608
- const totalRaw = stateExtractField(stateContent, 'Total Phases');
609
- if (totalRaw) {
610
- stateContent = stateReplaceField(stateContent, 'Total Phases', String(parseInt(totalRaw, 10) - 1)) || stateContent;
611
- }
612
- const ofMatch = stateContent.match(/(\bof\s+)(\d+)(\s*(?:\(|phases?))/i);
613
- if (ofMatch) {
614
- stateContent = stateContent.replace(/(\bof\s+)(\d+)(\s*(?:\(|phases?))/i, `$1${parseInt(ofMatch[2], 10) - 1}$3`);
615
- }
616
- writeStateMd(statePath, stateContent, cwd);
617
- }
618
-
619
- output({
620
- removed: targetPhase,
621
- directory_deleted: targetDir,
622
- renamed_directories: renamedDirs,
623
- renamed_files: renamedFiles,
624
- roadmap_updated: true,
625
- state_updated: fs.existsSync(statePath),
626
- }, raw);
627
- }
628
-
629
- function cmdPhaseComplete(cwd, phaseNum, raw) {
630
- if (!phaseNum) {
631
- error('phase number required for phase complete');
632
- }
633
-
634
- const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
635
- const statePath = path.join(planningDir(cwd), 'STATE.md');
636
- const phasesDir = path.join(planningDir(cwd), 'phases');
637
- const normalized = normalizePhaseName(phaseNum);
638
- const today = new Date().toISOString().split('T')[0];
639
-
640
- // Verify phase info
641
- const phaseInfo = findPhaseInternal(cwd, phaseNum);
642
- if (!phaseInfo) {
643
- error(`Phase ${phaseNum} not found`);
644
- }
645
-
646
- const planCount = phaseInfo.plans.length;
647
- const summaryCount = phaseInfo.summaries.length;
648
- let requirementsUpdated = false;
649
-
650
- // Check for unresolved verification debt (non-blocking warnings)
651
- const warnings = [];
652
- try {
653
- const phaseFullDir = path.join(cwd, phaseInfo.directory);
654
- const phaseFiles = fs.readdirSync(phaseFullDir);
655
-
656
- for (const file of phaseFiles.filter(f => f.includes('-UAT') && f.endsWith('.md'))) {
657
- const content = fs.readFileSync(path.join(phaseFullDir, file), 'utf-8');
658
- if (/result: pending/.test(content)) warnings.push(`${file}: has pending tests`);
659
- if (/result: blocked/.test(content)) warnings.push(`${file}: has blocked tests`);
660
- if (/status: partial/.test(content)) warnings.push(`${file}: testing incomplete (partial)`);
661
- if (/status: diagnosed/.test(content)) warnings.push(`${file}: has diagnosed gaps`);
662
- }
663
-
664
- for (const file of phaseFiles.filter(f => f.includes('-VERIFICATION') && f.endsWith('.md'))) {
665
- const content = fs.readFileSync(path.join(phaseFullDir, file), 'utf-8');
666
- if (/status: human_needed/.test(content)) warnings.push(`${file}: needs human verification`);
667
- if (/status: gaps_found/.test(content)) warnings.push(`${file}: has unresolved gaps`);
668
- }
669
- } catch {}
670
-
671
- // Update ROADMAP.md: mark phase complete
672
- if (fs.existsSync(roadmapPath)) {
673
- let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
674
-
675
- // Checkbox: - [ ] Phase N: → - [x] Phase N: (...completed DATE)
676
- const checkboxPattern = new RegExp(
677
- `(-\\s*\\[)[ ](\\]\\s*.*Phase\\s+${escapeRegex(phaseNum)}[:\\s][^\\n]*)`,
678
- 'i'
679
- );
680
- roadmapContent = replaceInCurrentMilestone(roadmapContent, checkboxPattern, `$1x$2 (completed ${today})`);
681
-
682
- // Progress table: update Status to Complete, add date (handles 4 or 5 column tables)
683
- const phaseEscaped = escapeRegex(phaseNum);
684
- const tableRowPattern = new RegExp(
685
- `^(\\|\\s*${phaseEscaped}\\.?\\s[^|]*(?:\\|[^\\n]*))$`,
686
- 'im'
687
- );
688
- roadmapContent = roadmapContent.replace(tableRowPattern, (fullRow) => {
689
- const cells = fullRow.split('|').slice(1, -1);
690
- if (cells.length === 5) {
691
- // 5-col: Phase | Milestone | Plans | Status | Completed
692
- cells[3] = ' Complete ';
693
- cells[4] = ` ${today} `;
694
- } else if (cells.length === 4) {
695
- // 4-col: Phase | Plans | Status | Completed
696
- cells[2] = ' Complete ';
697
- cells[3] = ` ${today} `;
698
- }
699
- return '|' + cells.join('|') + '|';
700
- });
701
-
702
- // Update plan count in phase section
703
- const planCountPattern = new RegExp(
704
- `(#{2,4}\\s*Phase\\s+${phaseEscaped}[\\s\\S]*?\\*\\*Plans:\\*\\*\\s*)[^\\n]+`,
705
- 'i'
706
- );
707
- roadmapContent = replaceInCurrentMilestone(
708
- roadmapContent, planCountPattern,
709
- `$1${summaryCount}/${planCount} plans complete`
710
- );
711
-
712
- fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
713
-
714
- // Update REQUIREMENTS.md traceability for this phase's requirements
715
- const reqPath = path.join(planningDir(cwd), 'REQUIREMENTS.md');
716
- if (fs.existsSync(reqPath)) {
717
- // Extract the current phase section from roadmap (scoped to avoid cross-phase matching)
718
- const phaseEsc = escapeRegex(phaseNum);
719
- const currentMilestoneRoadmap = extractCurrentMilestone(roadmapContent, cwd);
720
- const phaseSectionMatch = currentMilestoneRoadmap.match(
721
- new RegExp(`(#{2,4}\\s*Phase\\s+${phaseEsc}[:\\s][\\s\\S]*?)(?=#{2,4}\\s*Phase\\s+|$)`, 'i')
722
- );
723
-
724
- const sectionText = phaseSectionMatch ? phaseSectionMatch[1] : '';
725
- const reqMatch = sectionText.match(/\*\*Requirements:\*\*\s*([^\n]+)/i);
726
-
727
- if (reqMatch) {
728
- const reqIds = reqMatch[1].replace(/[\[\]]/g, '').split(/[,\s]+/).map(r => r.trim()).filter(Boolean);
729
- let reqContent = fs.readFileSync(reqPath, 'utf-8');
730
-
731
- for (const reqId of reqIds) {
732
- const reqEscaped = escapeRegex(reqId);
733
- // Update checkbox: - [ ] **REQ-ID** → - [x] **REQ-ID**
734
- reqContent = reqContent.replace(
735
- new RegExp(`(-\\s*\\[)[ ](\\]\\s*\\*\\*${reqEscaped}\\*\\*)`, 'gi'),
736
- '$1x$2'
737
- );
738
- // Update traceability table: | REQ-ID | Phase N | Pending/In Progress | → | REQ-ID | Phase N | Complete |
739
- reqContent = reqContent.replace(
740
- new RegExp(`(\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|)\\s*(?:Pending|In Progress)\\s*(\\|)`, 'gi'),
741
- '$1 Complete $2'
742
- );
743
- }
744
-
745
- fs.writeFileSync(reqPath, reqContent, 'utf-8');
746
- requirementsUpdated = true;
747
- }
748
- }
749
- }
750
-
751
- // Find next phase — check both filesystem AND roadmap
752
- // Phases may be defined in ROADMAP.md but not yet scaffolded to disk,
753
- // so a filesystem-only scan would incorrectly report is_last_phase:true
754
- let nextPhaseNum = null;
755
- let nextPhaseName = null;
756
- let isLastPhase = true;
757
-
758
- try {
759
- const isDirInMilestone = getMilestonePhaseFilter(cwd);
760
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
761
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name)
762
- .filter(isDirInMilestone)
763
- .sort((a, b) => comparePhaseNum(a, b));
764
-
765
- // Find the next phase directory after current
766
- for (const dir of dirs) {
767
- const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
768
- if (dm) {
769
- if (comparePhaseNum(dm[1], phaseNum) > 0) {
770
- nextPhaseNum = dm[1];
771
- nextPhaseName = dm[2] || null;
772
- isLastPhase = false;
773
- break;
774
- }
775
- }
776
- }
777
- } catch { /* intentionally empty */ }
778
-
779
- // Fallback: if filesystem found no next phase, check ROADMAP.md
780
- // for phases that are defined but not yet planned (no directory on disk)
781
- if (isLastPhase && fs.existsSync(roadmapPath)) {
782
- try {
783
- const roadmapForPhases = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
784
- const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
785
- let pm;
786
- while ((pm = phasePattern.exec(roadmapForPhases)) !== null) {
787
- if (comparePhaseNum(pm[1], phaseNum) > 0) {
788
- nextPhaseNum = pm[1];
789
- nextPhaseName = pm[2].replace(/\(INSERTED\)/i, '').trim().toLowerCase().replace(/\s+/g, '-');
790
- isLastPhase = false;
791
- break;
792
- }
793
- }
794
- } catch { /* intentionally empty */ }
795
- }
796
-
797
- // Update STATE.md — use shared helpers that handle both **bold:** and plain Field: formats
798
- if (fs.existsSync(statePath)) {
799
- let stateContent = fs.readFileSync(statePath, 'utf-8');
800
-
801
- // Update Current Phase — preserve "X of Y (Name)" compound format
802
- const phaseValue = nextPhaseNum || phaseNum;
803
- const existingPhaseField = stateExtractField(stateContent, 'Current Phase')
804
- || stateExtractField(stateContent, 'Phase');
805
- let newPhaseValue = String(phaseValue);
806
- if (existingPhaseField) {
807
- const totalMatch = existingPhaseField.match(/of\s+(\d+)/);
808
- const nameMatch = existingPhaseField.match(/\(([^)]+)\)/);
809
- if (totalMatch) {
810
- const total = totalMatch[1];
811
- const nameStr = nextPhaseName ? ` (${nextPhaseName.replace(/-/g, ' ')})` : (nameMatch ? ` (${nameMatch[1]})` : '');
812
- newPhaseValue = `${phaseValue} of ${total}${nameStr}`;
813
- }
814
- }
815
- stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Phase', 'Phase', newPhaseValue);
816
-
817
- // Update Current Phase Name
818
- if (nextPhaseName) {
819
- stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Phase Name', null, nextPhaseName.replace(/-/g, ' '));
820
- }
821
-
822
- // Update Status
823
- stateContent = stateReplaceFieldWithFallback(stateContent, 'Status', null,
824
- isLastPhase ? 'Milestone complete' : 'Ready to plan');
825
-
826
- // Update Current Plan
827
- stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Plan', 'Plan', 'Not started');
828
-
829
- // Update Last Activity
830
- stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity', 'Last activity', today);
831
-
832
- // Update Last Activity Description
833
- stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity Description', null,
834
- `Phase ${phaseNum} complete${nextPhaseNum ? `, transitioned to Phase ${nextPhaseNum}` : ''}`);
835
-
836
- // Increment Completed Phases counter (#956)
837
- const completedRaw = stateExtractField(stateContent, 'Completed Phases');
838
- if (completedRaw) {
839
- const newCompleted = parseInt(completedRaw, 10) + 1;
840
- stateContent = stateReplaceField(stateContent, 'Completed Phases', String(newCompleted)) || stateContent;
841
-
842
- // Recalculate percent based on completed / total (#956)
843
- const totalRaw = stateExtractField(stateContent, 'Total Phases');
844
- if (totalRaw) {
845
- const totalPhases = parseInt(totalRaw, 10);
846
- if (totalPhases > 0) {
847
- const newPercent = Math.round((newCompleted / totalPhases) * 100);
848
- stateContent = stateReplaceField(stateContent, 'Progress', `${newPercent}%`) || stateContent;
849
- // Also update percent field if it exists separately
850
- stateContent = stateContent.replace(
851
- /(percent:\s*)\d+/,
852
- `$1${newPercent}`
853
- );
854
- }
855
- }
856
- }
857
-
858
- writeStateMd(statePath, stateContent, cwd);
859
- }
860
-
861
- const result = {
862
- completed_phase: phaseNum,
863
- phase_name: phaseInfo.phase_name,
864
- plans_executed: `${summaryCount}/${planCount}`,
865
- next_phase: nextPhaseNum,
866
- next_phase_name: nextPhaseName,
867
- is_last_phase: isLastPhase,
868
- date: today,
869
- roadmap_updated: fs.existsSync(roadmapPath),
870
- state_updated: fs.existsSync(statePath),
871
- requirements_updated: requirementsUpdated,
872
- warnings,
873
- has_warnings: warnings.length > 0,
874
- };
875
-
876
- output(result, raw);
877
- }
878
-
879
- module.exports = {
880
- cmdPhasesList,
881
- cmdPhaseNextDecimal,
882
- cmdFindPhase,
883
- cmdPhasePlanIndex,
884
- cmdPhaseAdd,
885
- cmdPhaseInsert,
886
- cmdPhaseRemove,
887
- cmdPhaseComplete,
888
- };
1
+ /**
2
+ * Phase — Phase CRUD, query, and lifecycle operations
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { escapeRegex, loadConfig, normalizePhaseName, comparePhaseNum, findPhaseInternal, getArchivedPhaseDirs, generateSlugInternal, getMilestonePhaseFilter, stripShippedMilestones, extractCurrentMilestone, replaceInCurrentMilestone, toPosixPath, planningDir, output, error, readSubdirectories } = require('./core.cjs');
8
+ const { extractFrontmatter } = require('./frontmatter.cjs');
9
+ const { writeStateMd, stateExtractField, stateReplaceField, stateReplaceFieldWithFallback } = require('./state.cjs');
10
+
11
+ function cmdPhasesList(cwd, options, raw) {
12
+ const phasesDir = path.join(planningDir(cwd), 'phases');
13
+ const { type, phase, includeArchived } = options;
14
+
15
+ // If no phases directory, return empty
16
+ if (!fs.existsSync(phasesDir)) {
17
+ if (type) {
18
+ output({ files: [], count: 0 }, raw, '');
19
+ } else {
20
+ output({ directories: [], count: 0 }, raw, '');
21
+ }
22
+ return;
23
+ }
24
+
25
+ try {
26
+ // Get all phase directories
27
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
28
+ let dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
29
+
30
+ // Include archived phases if requested
31
+ if (includeArchived) {
32
+ const archived = getArchivedPhaseDirs(cwd);
33
+ for (const a of archived) {
34
+ dirs.push(`${a.name} [${a.milestone}]`);
35
+ }
36
+ }
37
+
38
+ // Sort numerically (handles integers, decimals, letter-suffix, hybrids)
39
+ dirs.sort((a, b) => comparePhaseNum(a, b));
40
+
41
+ // If filtering by phase number
42
+ if (phase) {
43
+ const normalized = normalizePhaseName(phase);
44
+ const match = dirs.find(d => d.startsWith(normalized));
45
+ if (!match) {
46
+ output({ files: [], count: 0, phase_dir: null, error: 'Phase not found' }, raw, '');
47
+ return;
48
+ }
49
+ dirs = [match];
50
+ }
51
+
52
+ // If listing files of a specific type
53
+ if (type) {
54
+ const files = [];
55
+ for (const dir of dirs) {
56
+ const dirPath = path.join(phasesDir, dir);
57
+ const dirFiles = fs.readdirSync(dirPath);
58
+
59
+ let filtered;
60
+ if (type === 'plans') {
61
+ filtered = dirFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
62
+ } else if (type === 'summaries') {
63
+ filtered = dirFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
64
+ } else {
65
+ filtered = dirFiles;
66
+ }
67
+
68
+ files.push(...filtered.sort());
69
+ }
70
+
71
+ const result = {
72
+ files,
73
+ count: files.length,
74
+ phase_dir: phase ? dirs[0].replace(/^\d+(?:\.\d+)*-?/, '') : null,
75
+ };
76
+ output(result, raw, files.join('\n'));
77
+ return;
78
+ }
79
+
80
+ // Default: list directories
81
+ output({ directories: dirs, count: dirs.length }, raw, dirs.join('\n'));
82
+ } catch (e) {
83
+ error('Failed to list phases: ' + e.message);
84
+ }
85
+ }
86
+
87
+ function cmdPhaseNextDecimal(cwd, basePhase, raw) {
88
+ const phasesDir = path.join(planningDir(cwd), 'phases');
89
+ const normalized = normalizePhaseName(basePhase);
90
+
91
+ // Check if phases directory exists
92
+ if (!fs.existsSync(phasesDir)) {
93
+ output(
94
+ {
95
+ found: false,
96
+ base_phase: normalized,
97
+ next: `${normalized}.1`,
98
+ existing: [],
99
+ },
100
+ raw,
101
+ `${normalized}.1`
102
+ );
103
+ return;
104
+ }
105
+
106
+ try {
107
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
108
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
109
+
110
+ // Check if base phase exists
111
+ const baseExists = dirs.some(d => d.startsWith(normalized + '-') || d === normalized);
112
+
113
+ // Find existing decimal phases for this base
114
+ const decimalPattern = new RegExp(`^${normalized}\\.(\\d+)`);
115
+ const existingDecimals = [];
116
+
117
+ for (const dir of dirs) {
118
+ const match = dir.match(decimalPattern);
119
+ if (match) {
120
+ existingDecimals.push(`${normalized}.${match[1]}`);
121
+ }
122
+ }
123
+
124
+ // Sort numerically
125
+ existingDecimals.sort((a, b) => comparePhaseNum(a, b));
126
+
127
+ // Calculate next decimal
128
+ let nextDecimal;
129
+ if (existingDecimals.length === 0) {
130
+ nextDecimal = `${normalized}.1`;
131
+ } else {
132
+ const lastDecimal = existingDecimals[existingDecimals.length - 1];
133
+ const lastNum = parseInt(lastDecimal.split('.')[1], 10);
134
+ nextDecimal = `${normalized}.${lastNum + 1}`;
135
+ }
136
+
137
+ output(
138
+ {
139
+ found: baseExists,
140
+ base_phase: normalized,
141
+ next: nextDecimal,
142
+ existing: existingDecimals,
143
+ },
144
+ raw,
145
+ nextDecimal
146
+ );
147
+ } catch (e) {
148
+ error('Failed to calculate next decimal phase: ' + e.message);
149
+ }
150
+ }
151
+
152
+ function cmdFindPhase(cwd, phase, raw) {
153
+ if (!phase) {
154
+ error('phase identifier required');
155
+ }
156
+
157
+ const phasesDir = path.join(planningDir(cwd), 'phases');
158
+ const normalized = normalizePhaseName(phase);
159
+
160
+ const notFound = { found: false, directory: null, phase_number: null, phase_name: null, plans: [], summaries: [] };
161
+
162
+ try {
163
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
164
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
165
+
166
+ const match = dirs.find(d => d.startsWith(normalized));
167
+ if (!match) {
168
+ output(notFound, raw, '');
169
+ return;
170
+ }
171
+
172
+ const dirMatch = match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
173
+ const phaseNumber = dirMatch ? dirMatch[1] : normalized;
174
+ const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
175
+
176
+ const phaseDir = path.join(phasesDir, match);
177
+ const phaseFiles = fs.readdirSync(phaseDir);
178
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
179
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').sort();
180
+
181
+ const result = {
182
+ found: true,
183
+ directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', match)),
184
+ phase_number: phaseNumber,
185
+ phase_name: phaseName,
186
+ plans,
187
+ summaries,
188
+ };
189
+
190
+ output(result, raw, result.directory);
191
+ } catch {
192
+ output(notFound, raw, '');
193
+ }
194
+ }
195
+
196
+ function extractObjective(content) {
197
+ const m = content.match(/<objective>\s*\n?\s*(.+)/);
198
+ return m ? m[1].trim() : null;
199
+ }
200
+
201
+ function cmdPhasePlanIndex(cwd, phase, raw) {
202
+ if (!phase) {
203
+ error('phase required for phase-plan-index');
204
+ }
205
+
206
+ const phasesDir = path.join(planningDir(cwd), 'phases');
207
+ const normalized = normalizePhaseName(phase);
208
+
209
+ // Find phase directory
210
+ let phaseDir = null;
211
+ let phaseDirName = null;
212
+ try {
213
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
214
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
215
+ const match = dirs.find(d => d.startsWith(normalized));
216
+ if (match) {
217
+ phaseDir = path.join(phasesDir, match);
218
+ phaseDirName = match;
219
+ }
220
+ } catch {
221
+ // phases dir doesn't exist
222
+ }
223
+
224
+ if (!phaseDir) {
225
+ output({ phase: normalized, error: 'Phase not found', plans: [], waves: {}, incomplete: [], has_checkpoints: false }, raw);
226
+ return;
227
+ }
228
+
229
+ // Get all files in phase directory
230
+ const phaseFiles = fs.readdirSync(phaseDir);
231
+ const planFiles = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
232
+ const summaryFiles = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
233
+
234
+ // Build set of plan IDs with summaries
235
+ const completedPlanIds = new Set(
236
+ summaryFiles.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', ''))
237
+ );
238
+
239
+ const plans = [];
240
+ const waves = {};
241
+ const incomplete = [];
242
+ let hasCheckpoints = false;
243
+
244
+ for (const planFile of planFiles) {
245
+ const planId = planFile.replace('-PLAN.md', '').replace('PLAN.md', '');
246
+ const planPath = path.join(phaseDir, planFile);
247
+ const content = fs.readFileSync(planPath, 'utf-8');
248
+ const fm = extractFrontmatter(content);
249
+
250
+ // Count tasks: XML <task> tags (canonical) or ## Task N markdown (legacy)
251
+ const xmlTasks = content.match(/<task[\s>]/gi) || [];
252
+ const mdTasks = content.match(/##\s*Task\s*\d+/gi) || [];
253
+ const taskCount = xmlTasks.length || mdTasks.length;
254
+
255
+ // Parse wave as integer
256
+ const wave = parseInt(fm.wave, 10) || 1;
257
+
258
+ // Parse autonomous (default true if not specified)
259
+ let autonomous = true;
260
+ if (fm.autonomous !== undefined) {
261
+ autonomous = fm.autonomous === 'true' || fm.autonomous === true;
262
+ }
263
+
264
+ if (!autonomous) {
265
+ hasCheckpoints = true;
266
+ }
267
+
268
+ // Parse files_modified (underscore is canonical; also accept hyphenated for compat)
269
+ let filesModified = [];
270
+ const fmFiles = fm['files_modified'] || fm['files-modified'];
271
+ if (fmFiles) {
272
+ filesModified = Array.isArray(fmFiles) ? fmFiles : [fmFiles];
273
+ }
274
+
275
+ const hasSummary = completedPlanIds.has(planId);
276
+ if (!hasSummary) {
277
+ incomplete.push(planId);
278
+ }
279
+
280
+ const plan = {
281
+ id: planId,
282
+ wave,
283
+ autonomous,
284
+ objective: extractObjective(content) || fm.objective || null,
285
+ files_modified: filesModified,
286
+ task_count: taskCount,
287
+ has_summary: hasSummary,
288
+ };
289
+
290
+ plans.push(plan);
291
+
292
+ // Group by wave
293
+ const waveKey = String(wave);
294
+ if (!waves[waveKey]) {
295
+ waves[waveKey] = [];
296
+ }
297
+ waves[waveKey].push(planId);
298
+ }
299
+
300
+ const result = {
301
+ phase: normalized,
302
+ plans,
303
+ waves,
304
+ incomplete,
305
+ has_checkpoints: hasCheckpoints,
306
+ };
307
+
308
+ output(result, raw);
309
+ }
310
+
311
+ function cmdPhaseAdd(cwd, description, raw, customId) {
312
+ if (!description) {
313
+ error('description required for phase add');
314
+ }
315
+
316
+ const config = loadConfig(cwd);
317
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
318
+ if (!fs.existsSync(roadmapPath)) {
319
+ error('ROADMAP.md not found');
320
+ }
321
+
322
+ const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
323
+ const content = extractCurrentMilestone(rawContent, cwd);
324
+ const slug = generateSlugInternal(description);
325
+
326
+ let newPhaseId;
327
+ let dirName;
328
+
329
+ if (customId || config.phase_naming === 'custom') {
330
+ // Custom phase naming: use provided ID or generate from description
331
+ newPhaseId = customId || slug.toUpperCase().replace(/-/g, '-');
332
+ if (!newPhaseId) error('--id required when phase_naming is "custom"');
333
+ dirName = `${newPhaseId}-${slug}`;
334
+ } else {
335
+ // Sequential mode: find highest integer phase number (in current milestone only)
336
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
337
+ let maxPhase = 0;
338
+ let m;
339
+ while ((m = phasePattern.exec(content)) !== null) {
340
+ const num = parseInt(m[1], 10);
341
+ if (num > maxPhase) maxPhase = num;
342
+ }
343
+
344
+ newPhaseId = maxPhase + 1;
345
+ const paddedNum = String(newPhaseId).padStart(2, '0');
346
+ dirName = `${paddedNum}-${slug}`;
347
+ }
348
+
349
+ const dirPath = path.join(planningDir(cwd), 'phases', dirName);
350
+
351
+ // Create directory with .gitkeep so git tracks empty folders
352
+ fs.mkdirSync(dirPath, { recursive: true });
353
+ fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
354
+
355
+ // Build phase entry
356
+ const dependsOn = config.phase_naming === 'custom' ? '' : `\n**Depends on:** Phase ${typeof newPhaseId === 'number' ? newPhaseId - 1 : 'TBD'}`;
357
+ const phaseEntry = `\n### Phase ${newPhaseId}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD${dependsOn}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /plan-phase ${newPhaseId} to break down)\n`;
358
+
359
+ // Find insertion point: before last "---" or at end
360
+ let updatedContent;
361
+ const lastSeparator = rawContent.lastIndexOf('\n---');
362
+ if (lastSeparator > 0) {
363
+ updatedContent = rawContent.slice(0, lastSeparator) + phaseEntry + rawContent.slice(lastSeparator);
364
+ } else {
365
+ updatedContent = rawContent + phaseEntry;
366
+ }
367
+
368
+ fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
369
+
370
+ const result = {
371
+ phase_number: typeof newPhaseId === 'number' ? newPhaseId : String(newPhaseId),
372
+ padded: typeof newPhaseId === 'number' ? String(newPhaseId).padStart(2, '0') : String(newPhaseId),
373
+ name: description,
374
+ slug,
375
+ directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', dirName)),
376
+ naming_mode: config.phase_naming,
377
+ };
378
+
379
+ output(result, raw, result.padded);
380
+ }
381
+
382
+ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
383
+ if (!afterPhase || !description) {
384
+ error('after-phase and description required for phase insert');
385
+ }
386
+
387
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
388
+ if (!fs.existsSync(roadmapPath)) {
389
+ error('ROADMAP.md not found');
390
+ }
391
+
392
+ const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
393
+ const content = extractCurrentMilestone(rawContent, cwd);
394
+ const slug = generateSlugInternal(description);
395
+
396
+ // Normalize input then strip leading zeros for flexible matching
397
+ const normalizedAfter = normalizePhaseName(afterPhase);
398
+ const unpadded = normalizedAfter.replace(/^0+/, '');
399
+ const afterPhaseEscaped = unpadded.replace(/\./g, '\\.');
400
+ const targetPattern = new RegExp(`#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:`, 'i');
401
+ if (!targetPattern.test(content)) {
402
+ error(`Phase ${afterPhase} not found in ROADMAP.md`);
403
+ }
404
+
405
+ // Calculate next decimal using existing logic
406
+ const phasesDir = path.join(planningDir(cwd), 'phases');
407
+ const normalizedBase = normalizePhaseName(afterPhase);
408
+ let existingDecimals = [];
409
+
410
+ try {
411
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
412
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
413
+ const decimalPattern = new RegExp(`^${normalizedBase}\\.(\\d+)`);
414
+ for (const dir of dirs) {
415
+ const dm = dir.match(decimalPattern);
416
+ if (dm) existingDecimals.push(parseInt(dm[1], 10));
417
+ }
418
+ } catch { /* intentionally empty */ }
419
+
420
+ const nextDecimal = existingDecimals.length === 0 ? 1 : Math.max(...existingDecimals) + 1;
421
+ const decimalPhase = `${normalizedBase}.${nextDecimal}`;
422
+ const dirName = `${decimalPhase}-${slug}`;
423
+ const dirPath = path.join(planningDir(cwd), 'phases', dirName);
424
+
425
+ // Create directory with .gitkeep so git tracks empty folders
426
+ fs.mkdirSync(dirPath, { recursive: true });
427
+ fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
428
+
429
+ // Build phase entry
430
+ const phaseEntry = `\n### Phase ${decimalPhase}: ${description} (INSERTED)\n\n**Goal:** [Urgent work - to be planned]\n**Requirements**: TBD\n**Depends on:** Phase ${afterPhase}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /plan-phase ${decimalPhase} to break down)\n`;
431
+
432
+ // Insert after the target phase section
433
+ const headerPattern = new RegExp(`(#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:[^\\n]*\\n)`, 'i');
434
+ const headerMatch = rawContent.match(headerPattern);
435
+ if (!headerMatch) {
436
+ error(`Could not find Phase ${afterPhase} header`);
437
+ }
438
+
439
+ const headerIdx = rawContent.indexOf(headerMatch[0]);
440
+ const afterHeader = rawContent.slice(headerIdx + headerMatch[0].length);
441
+ const nextPhaseMatch = afterHeader.match(/\n#{2,4}\s+Phase\s+\d/i);
442
+
443
+ let insertIdx;
444
+ if (nextPhaseMatch) {
445
+ insertIdx = headerIdx + headerMatch[0].length + nextPhaseMatch.index;
446
+ } else {
447
+ insertIdx = rawContent.length;
448
+ }
449
+
450
+ const updatedContent = rawContent.slice(0, insertIdx) + phaseEntry + rawContent.slice(insertIdx);
451
+ fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
452
+
453
+ const result = {
454
+ phase_number: decimalPhase,
455
+ after_phase: afterPhase,
456
+ name: description,
457
+ slug,
458
+ directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', dirName)),
459
+ };
460
+
461
+ output(result, raw, decimalPhase);
462
+ }
463
+
464
+ /**
465
+ * Renumber sibling decimal phases after a decimal phase is removed.
466
+ * e.g. removing 06.2 → 06.3 becomes 06.2, 06.4 becomes 06.3, etc.
467
+ * Returns { renamedDirs, renamedFiles }.
468
+ */
469
+ function renameDecimalPhases(phasesDir, baseInt, removedDecimal) {
470
+ const renamedDirs = [], renamedFiles = [];
471
+ const decPattern = new RegExp(`^${baseInt}\\.(\\d+)-(.+)$`);
472
+ const dirs = readSubdirectories(phasesDir, true);
473
+ const toRename = dirs
474
+ .map(dir => { const m = dir.match(decPattern); return m ? { dir, oldDecimal: parseInt(m[1], 10), slug: m[2] } : null; })
475
+ .filter(item => item && item.oldDecimal > removedDecimal)
476
+ .sort((a, b) => b.oldDecimal - a.oldDecimal); // descending to avoid conflicts
477
+
478
+ for (const item of toRename) {
479
+ const newDecimal = item.oldDecimal - 1;
480
+ const oldPhaseId = `${baseInt}.${item.oldDecimal}`;
481
+ const newPhaseId = `${baseInt}.${newDecimal}`;
482
+ const newDirName = `${baseInt}.${newDecimal}-${item.slug}`;
483
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
484
+ renamedDirs.push({ from: item.dir, to: newDirName });
485
+ for (const f of fs.readdirSync(path.join(phasesDir, newDirName))) {
486
+ if (f.includes(oldPhaseId)) {
487
+ const newFileName = f.replace(oldPhaseId, newPhaseId);
488
+ fs.renameSync(path.join(phasesDir, newDirName, f), path.join(phasesDir, newDirName, newFileName));
489
+ renamedFiles.push({ from: f, to: newFileName });
490
+ }
491
+ }
492
+ }
493
+ return { renamedDirs, renamedFiles };
494
+ }
495
+
496
+ /**
497
+ * Renumber all integer phases after removedInt.
498
+ * e.g. removing phase 5 → phase 6 becomes 5, phase 7 becomes 6, etc.
499
+ * Returns { renamedDirs, renamedFiles }.
500
+ */
501
+ function renameIntegerPhases(phasesDir, removedInt) {
502
+ const renamedDirs = [], renamedFiles = [];
503
+ const dirs = readSubdirectories(phasesDir, true);
504
+ const toRename = dirs
505
+ .map(dir => {
506
+ const m = dir.match(/^(\d+)([A-Z])?(?:\.(\d+))?-(.+)$/i);
507
+ if (!m) return null;
508
+ const dirInt = parseInt(m[1], 10);
509
+ return dirInt > removedInt ? { dir, oldInt: dirInt, letter: m[2] ? m[2].toUpperCase() : '', decimal: m[3] ? parseInt(m[3], 10) : null, slug: m[4] } : null;
510
+ })
511
+ .filter(Boolean)
512
+ .sort((a, b) => a.oldInt !== b.oldInt ? b.oldInt - a.oldInt : (b.decimal || 0) - (a.decimal || 0));
513
+
514
+ for (const item of toRename) {
515
+ const newInt = item.oldInt - 1;
516
+ const newPadded = String(newInt).padStart(2, '0');
517
+ const oldPadded = String(item.oldInt).padStart(2, '0');
518
+ const letterSuffix = item.letter || '';
519
+ const decimalSuffix = item.decimal !== null ? `.${item.decimal}` : '';
520
+ const oldPrefix = `${oldPadded}${letterSuffix}${decimalSuffix}`;
521
+ const newPrefix = `${newPadded}${letterSuffix}${decimalSuffix}`;
522
+ const newDirName = `${newPrefix}-${item.slug}`;
523
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
524
+ renamedDirs.push({ from: item.dir, to: newDirName });
525
+ for (const f of fs.readdirSync(path.join(phasesDir, newDirName))) {
526
+ if (f.startsWith(oldPrefix)) {
527
+ const newFileName = newPrefix + f.slice(oldPrefix.length);
528
+ fs.renameSync(path.join(phasesDir, newDirName, f), path.join(phasesDir, newDirName, newFileName));
529
+ renamedFiles.push({ from: f, to: newFileName });
530
+ }
531
+ }
532
+ }
533
+ return { renamedDirs, renamedFiles };
534
+ }
535
+
536
+ /**
537
+ * Remove a phase section from ROADMAP.md and renumber all subsequent integer phases.
538
+ */
539
+ function updateRoadmapAfterPhaseRemoval(roadmapPath, targetPhase, isDecimal, removedInt) {
540
+ let content = fs.readFileSync(roadmapPath, 'utf-8');
541
+ const escaped = escapeRegex(targetPhase);
542
+
543
+ content = content.replace(new RegExp(`\\n?#{2,4}\\s*Phase\\s+${escaped}\\s*:[\\s\\S]*?(?=\\n#{2,4}\\s+Phase\\s+\\d|$)`, 'i'), '');
544
+ content = content.replace(new RegExp(`\\n?-\\s*\\[[ x]\\]\\s*.*Phase\\s+${escaped}[:\\s][^\\n]*`, 'gi'), '');
545
+ content = content.replace(new RegExp(`\\n?\\|\\s*${escaped}\\.?\\s[^|]*\\|[^\\n]*`, 'gi'), '');
546
+
547
+ if (!isDecimal) {
548
+ const MAX_PHASE = 99;
549
+ for (let oldNum = MAX_PHASE; oldNum > removedInt; oldNum--) {
550
+ const newNum = oldNum - 1;
551
+ const oldStr = String(oldNum), newStr = String(newNum);
552
+ const oldPad = oldStr.padStart(2, '0'), newPad = newStr.padStart(2, '0');
553
+ content = content.replace(new RegExp(`(#{2,4}\\s*Phase\\s+)${oldStr}(\\s*:)`, 'gi'), `$1${newStr}$2`);
554
+ content = content.replace(new RegExp(`(Phase\\s+)${oldStr}([:\\s])`, 'g'), `$1${newStr}$2`);
555
+ content = content.replace(new RegExp(`${oldPad}-(\\d{2})`, 'g'), `${newPad}-$1`);
556
+ content = content.replace(new RegExp(`(\\|\\s*)${oldStr}\\.\\s`, 'g'), `$1${newStr}. `);
557
+ content = content.replace(new RegExp(`(Depends on:\\*\\*\\s*Phase\\s+)${oldStr}\\b`, 'gi'), `$1${newStr}`);
558
+ }
559
+ }
560
+
561
+ fs.writeFileSync(roadmapPath, content, 'utf-8');
562
+ }
563
+
564
+ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
565
+ if (!targetPhase) error('phase number required for phase remove');
566
+
567
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
568
+ const phasesDir = path.join(planningDir(cwd), 'phases');
569
+
570
+ if (!fs.existsSync(roadmapPath)) error('ROADMAP.md not found');
571
+
572
+ const normalized = normalizePhaseName(targetPhase);
573
+ const isDecimal = targetPhase.includes('.');
574
+ const force = options.force || false;
575
+
576
+ // Find target directory
577
+ const targetDir = readSubdirectories(phasesDir, true)
578
+ .find(d => d.startsWith(normalized + '-') || d === normalized) || null;
579
+
580
+ // Guard against removing executed work
581
+ if (targetDir && !force) {
582
+ const files = fs.readdirSync(path.join(phasesDir, targetDir));
583
+ const summaries = files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
584
+ if (summaries.length > 0) {
585
+ error(`Phase ${targetPhase} has ${summaries.length} executed plan(s). Use --force to remove anyway.`);
586
+ }
587
+ }
588
+
589
+ if (targetDir) fs.rmSync(path.join(phasesDir, targetDir), { recursive: true, force: true });
590
+
591
+ // Renumber subsequent phases on disk
592
+ let renamedDirs = [], renamedFiles = [];
593
+ try {
594
+ const renamed = isDecimal
595
+ ? renameDecimalPhases(phasesDir, normalized.split('.')[0], parseInt(normalized.split('.')[1], 10))
596
+ : renameIntegerPhases(phasesDir, parseInt(normalized, 10));
597
+ renamedDirs = renamed.renamedDirs;
598
+ renamedFiles = renamed.renamedFiles;
599
+ } catch { /* intentionally empty */ }
600
+
601
+ // Update ROADMAP.md
602
+ updateRoadmapAfterPhaseRemoval(roadmapPath, targetPhase, isDecimal, parseInt(normalized, 10));
603
+
604
+ // Update STATE.md phase count
605
+ const statePath = path.join(planningDir(cwd), 'STATE.md');
606
+ if (fs.existsSync(statePath)) {
607
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
608
+ const totalRaw = stateExtractField(stateContent, 'Total Phases');
609
+ if (totalRaw) {
610
+ stateContent = stateReplaceField(stateContent, 'Total Phases', String(parseInt(totalRaw, 10) - 1)) || stateContent;
611
+ }
612
+ const ofMatch = stateContent.match(/(\bof\s+)(\d+)(\s*(?:\(|phases?))/i);
613
+ if (ofMatch) {
614
+ stateContent = stateContent.replace(/(\bof\s+)(\d+)(\s*(?:\(|phases?))/i, `$1${parseInt(ofMatch[2], 10) - 1}$3`);
615
+ }
616
+ writeStateMd(statePath, stateContent, cwd);
617
+ }
618
+
619
+ output({
620
+ removed: targetPhase,
621
+ directory_deleted: targetDir,
622
+ renamed_directories: renamedDirs,
623
+ renamed_files: renamedFiles,
624
+ roadmap_updated: true,
625
+ state_updated: fs.existsSync(statePath),
626
+ }, raw);
627
+ }
628
+
629
+ function cmdPhaseComplete(cwd, phaseNum, raw) {
630
+ if (!phaseNum) {
631
+ error('phase number required for phase complete');
632
+ }
633
+
634
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
635
+ const statePath = path.join(planningDir(cwd), 'STATE.md');
636
+ const phasesDir = path.join(planningDir(cwd), 'phases');
637
+ const normalized = normalizePhaseName(phaseNum);
638
+ const today = new Date().toISOString().split('T')[0];
639
+
640
+ // Verify phase info
641
+ const phaseInfo = findPhaseInternal(cwd, phaseNum);
642
+ if (!phaseInfo) {
643
+ error(`Phase ${phaseNum} not found`);
644
+ }
645
+
646
+ const planCount = phaseInfo.plans.length;
647
+ const summaryCount = phaseInfo.summaries.length;
648
+ let requirementsUpdated = false;
649
+
650
+ // Check for unresolved verification debt (non-blocking warnings)
651
+ const warnings = [];
652
+ try {
653
+ const phaseFullDir = path.join(cwd, phaseInfo.directory);
654
+ const phaseFiles = fs.readdirSync(phaseFullDir);
655
+
656
+ for (const file of phaseFiles.filter(f => f.includes('-UAT') && f.endsWith('.md'))) {
657
+ const content = fs.readFileSync(path.join(phaseFullDir, file), 'utf-8');
658
+ if (/result: pending/.test(content)) warnings.push(`${file}: has pending tests`);
659
+ if (/result: blocked/.test(content)) warnings.push(`${file}: has blocked tests`);
660
+ if (/status: partial/.test(content)) warnings.push(`${file}: testing incomplete (partial)`);
661
+ if (/status: diagnosed/.test(content)) warnings.push(`${file}: has diagnosed gaps`);
662
+ }
663
+
664
+ for (const file of phaseFiles.filter(f => f.includes('-VERIFICATION') && f.endsWith('.md'))) {
665
+ const content = fs.readFileSync(path.join(phaseFullDir, file), 'utf-8');
666
+ if (/status: human_needed/.test(content)) warnings.push(`${file}: needs human verification`);
667
+ if (/status: gaps_found/.test(content)) warnings.push(`${file}: has unresolved gaps`);
668
+ }
669
+ } catch {}
670
+
671
+ // Update ROADMAP.md: mark phase complete
672
+ if (fs.existsSync(roadmapPath)) {
673
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
674
+
675
+ // Checkbox: - [ ] Phase N: → - [x] Phase N: (...completed DATE)
676
+ const checkboxPattern = new RegExp(
677
+ `(-\\s*\\[)[ ](\\]\\s*.*Phase\\s+${escapeRegex(phaseNum)}[:\\s][^\\n]*)`,
678
+ 'i'
679
+ );
680
+ roadmapContent = replaceInCurrentMilestone(roadmapContent, checkboxPattern, `$1x$2 (completed ${today})`);
681
+
682
+ // Progress table: update Status to Complete, add date (handles 4 or 5 column tables)
683
+ const phaseEscaped = escapeRegex(phaseNum);
684
+ const tableRowPattern = new RegExp(
685
+ `^(\\|\\s*${phaseEscaped}\\.?\\s[^|]*(?:\\|[^\\n]*))$`,
686
+ 'im'
687
+ );
688
+ roadmapContent = roadmapContent.replace(tableRowPattern, (fullRow) => {
689
+ const cells = fullRow.split('|').slice(1, -1);
690
+ if (cells.length === 5) {
691
+ // 5-col: Phase | Milestone | Plans | Status | Completed
692
+ cells[3] = ' Complete ';
693
+ cells[4] = ` ${today} `;
694
+ } else if (cells.length === 4) {
695
+ // 4-col: Phase | Plans | Status | Completed
696
+ cells[2] = ' Complete ';
697
+ cells[3] = ` ${today} `;
698
+ }
699
+ return '|' + cells.join('|') + '|';
700
+ });
701
+
702
+ // Update plan count in phase section
703
+ const planCountPattern = new RegExp(
704
+ `(#{2,4}\\s*Phase\\s+${phaseEscaped}[\\s\\S]*?\\*\\*Plans:\\*\\*\\s*)[^\\n]+`,
705
+ 'i'
706
+ );
707
+ roadmapContent = replaceInCurrentMilestone(
708
+ roadmapContent, planCountPattern,
709
+ `$1${summaryCount}/${planCount} plans complete`
710
+ );
711
+
712
+ fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
713
+
714
+ // Update REQUIREMENTS.md traceability for this phase's requirements
715
+ const reqPath = path.join(planningDir(cwd), 'REQUIREMENTS.md');
716
+ if (fs.existsSync(reqPath)) {
717
+ // Extract the current phase section from roadmap (scoped to avoid cross-phase matching)
718
+ const phaseEsc = escapeRegex(phaseNum);
719
+ const currentMilestoneRoadmap = extractCurrentMilestone(roadmapContent, cwd);
720
+ const phaseSectionMatch = currentMilestoneRoadmap.match(
721
+ new RegExp(`(#{2,4}\\s*Phase\\s+${phaseEsc}[:\\s][\\s\\S]*?)(?=#{2,4}\\s*Phase\\s+|$)`, 'i')
722
+ );
723
+
724
+ const sectionText = phaseSectionMatch ? phaseSectionMatch[1] : '';
725
+ const reqMatch = sectionText.match(/\*\*Requirements:\*\*\s*([^\n]+)/i);
726
+
727
+ if (reqMatch) {
728
+ const reqIds = reqMatch[1].replace(/[\[\]]/g, '').split(/[,\s]+/).map(r => r.trim()).filter(Boolean);
729
+ let reqContent = fs.readFileSync(reqPath, 'utf-8');
730
+
731
+ for (const reqId of reqIds) {
732
+ const reqEscaped = escapeRegex(reqId);
733
+ // Update checkbox: - [ ] **REQ-ID** → - [x] **REQ-ID**
734
+ reqContent = reqContent.replace(
735
+ new RegExp(`(-\\s*\\[)[ ](\\]\\s*\\*\\*${reqEscaped}\\*\\*)`, 'gi'),
736
+ '$1x$2'
737
+ );
738
+ // Update traceability table: | REQ-ID | Phase N | Pending/In Progress | → | REQ-ID | Phase N | Complete |
739
+ reqContent = reqContent.replace(
740
+ new RegExp(`(\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|)\\s*(?:Pending|In Progress)\\s*(\\|)`, 'gi'),
741
+ '$1 Complete $2'
742
+ );
743
+ }
744
+
745
+ fs.writeFileSync(reqPath, reqContent, 'utf-8');
746
+ requirementsUpdated = true;
747
+ }
748
+ }
749
+ }
750
+
751
+ // Find next phase — check both filesystem AND roadmap
752
+ // Phases may be defined in ROADMAP.md but not yet scaffolded to disk,
753
+ // so a filesystem-only scan would incorrectly report is_last_phase:true
754
+ let nextPhaseNum = null;
755
+ let nextPhaseName = null;
756
+ let isLastPhase = true;
757
+
758
+ try {
759
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
760
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
761
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name)
762
+ .filter(isDirInMilestone)
763
+ .sort((a, b) => comparePhaseNum(a, b));
764
+
765
+ // Find the next phase directory after current
766
+ for (const dir of dirs) {
767
+ const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
768
+ if (dm) {
769
+ if (comparePhaseNum(dm[1], phaseNum) > 0) {
770
+ nextPhaseNum = dm[1];
771
+ nextPhaseName = dm[2] || null;
772
+ isLastPhase = false;
773
+ break;
774
+ }
775
+ }
776
+ }
777
+ } catch { /* intentionally empty */ }
778
+
779
+ // Fallback: if filesystem found no next phase, check ROADMAP.md
780
+ // for phases that are defined but not yet planned (no directory on disk)
781
+ if (isLastPhase && fs.existsSync(roadmapPath)) {
782
+ try {
783
+ const roadmapForPhases = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
784
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
785
+ let pm;
786
+ while ((pm = phasePattern.exec(roadmapForPhases)) !== null) {
787
+ if (comparePhaseNum(pm[1], phaseNum) > 0) {
788
+ nextPhaseNum = pm[1];
789
+ nextPhaseName = pm[2].replace(/\(INSERTED\)/i, '').trim().toLowerCase().replace(/\s+/g, '-');
790
+ isLastPhase = false;
791
+ break;
792
+ }
793
+ }
794
+ } catch { /* intentionally empty */ }
795
+ }
796
+
797
+ // Update STATE.md — use shared helpers that handle both **bold:** and plain Field: formats
798
+ if (fs.existsSync(statePath)) {
799
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
800
+
801
+ // Update Current Phase — preserve "X of Y (Name)" compound format
802
+ const phaseValue = nextPhaseNum || phaseNum;
803
+ const existingPhaseField = stateExtractField(stateContent, 'Current Phase')
804
+ || stateExtractField(stateContent, 'Phase');
805
+ let newPhaseValue = String(phaseValue);
806
+ if (existingPhaseField) {
807
+ const totalMatch = existingPhaseField.match(/of\s+(\d+)/);
808
+ const nameMatch = existingPhaseField.match(/\(([^)]+)\)/);
809
+ if (totalMatch) {
810
+ const total = totalMatch[1];
811
+ const nameStr = nextPhaseName ? ` (${nextPhaseName.replace(/-/g, ' ')})` : (nameMatch ? ` (${nameMatch[1]})` : '');
812
+ newPhaseValue = `${phaseValue} of ${total}${nameStr}`;
813
+ }
814
+ }
815
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Phase', 'Phase', newPhaseValue);
816
+
817
+ // Update Current Phase Name
818
+ if (nextPhaseName) {
819
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Phase Name', null, nextPhaseName.replace(/-/g, ' '));
820
+ }
821
+
822
+ // Update Status
823
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Status', null,
824
+ isLastPhase ? 'Milestone complete' : 'Ready to plan');
825
+
826
+ // Update Current Plan
827
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Plan', 'Plan', 'Not started');
828
+
829
+ // Update Last Activity
830
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity', 'Last activity', today);
831
+
832
+ // Update Last Activity Description
833
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity Description', null,
834
+ `Phase ${phaseNum} complete${nextPhaseNum ? `, transitioned to Phase ${nextPhaseNum}` : ''}`);
835
+
836
+ // Increment Completed Phases counter (#956)
837
+ const completedRaw = stateExtractField(stateContent, 'Completed Phases');
838
+ if (completedRaw) {
839
+ const newCompleted = parseInt(completedRaw, 10) + 1;
840
+ stateContent = stateReplaceField(stateContent, 'Completed Phases', String(newCompleted)) || stateContent;
841
+
842
+ // Recalculate percent based on completed / total (#956)
843
+ const totalRaw = stateExtractField(stateContent, 'Total Phases');
844
+ if (totalRaw) {
845
+ const totalPhases = parseInt(totalRaw, 10);
846
+ if (totalPhases > 0) {
847
+ const newPercent = Math.round((newCompleted / totalPhases) * 100);
848
+ stateContent = stateReplaceField(stateContent, 'Progress', `${newPercent}%`) || stateContent;
849
+ // Also update percent field if it exists separately
850
+ stateContent = stateContent.replace(
851
+ /(percent:\s*)\d+/,
852
+ `$1${newPercent}`
853
+ );
854
+ }
855
+ }
856
+ }
857
+
858
+ writeStateMd(statePath, stateContent, cwd);
859
+ }
860
+
861
+ const result = {
862
+ completed_phase: phaseNum,
863
+ phase_name: phaseInfo.phase_name,
864
+ plans_executed: `${summaryCount}/${planCount}`,
865
+ next_phase: nextPhaseNum,
866
+ next_phase_name: nextPhaseName,
867
+ is_last_phase: isLastPhase,
868
+ date: today,
869
+ roadmap_updated: fs.existsSync(roadmapPath),
870
+ state_updated: fs.existsSync(statePath),
871
+ requirements_updated: requirementsUpdated,
872
+ warnings,
873
+ has_warnings: warnings.length > 0,
874
+ };
875
+
876
+ output(result, raw);
877
+ }
878
+
879
+ module.exports = {
880
+ cmdPhasesList,
881
+ cmdPhaseNextDecimal,
882
+ cmdFindPhase,
883
+ cmdPhasePlanIndex,
884
+ cmdPhaseAdd,
885
+ cmdPhaseInsert,
886
+ cmdPhaseRemove,
887
+ cmdPhaseComplete,
888
+ };