@luanpdd/kit-mcp 1.21.0 → 1.22.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 (253) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +648 -648
  3. package/kit/COMANDOS.md +138 -138
  4. package/kit/README.md +76 -52
  5. package/kit/agents/advisor-researcher.md +106 -106
  6. package/kit/agents/assumptions-analyzer.md +107 -107
  7. package/kit/agents/auditor-consistencia-isolamento.md +380 -0
  8. package/kit/agents/codebase-mapper.md +768 -768
  9. package/kit/agents/crm-pipeline-implementer.md +17 -0
  10. package/kit/agents/debugger.md +772 -772
  11. package/kit/agents/detector-tenant-quente.md +337 -0
  12. package/kit/agents/example-reviewer.md +21 -21
  13. package/kit/agents/executor.md +523 -523
  14. package/kit/agents/integration-checker.md +200 -200
  15. package/kit/agents/multi-tenant-isolation-auditor.md +10 -0
  16. package/kit/agents/nyquist-auditor.md +178 -178
  17. package/kit/agents/phase-researcher.md +696 -696
  18. package/kit/agents/plan-checker.md +272 -272
  19. package/kit/agents/planner.md +891 -891
  20. package/kit/agents/project-researcher.md +652 -652
  21. package/kit/agents/research-synthesizer.md +245 -245
  22. package/kit/agents/roadmapper.md +677 -677
  23. package/kit/agents/supabase-architect.md +10 -0
  24. package/kit/agents/supabase-migration-writer.md +12 -0
  25. package/kit/agents/ui-auditor.md +437 -437
  26. package/kit/agents/ui-checker.md +302 -302
  27. package/kit/agents/ui-researcher.md +355 -355
  28. package/kit/agents/user-profiler.md +175 -175
  29. package/kit/agents/validador-evolucao-schema.md +335 -0
  30. package/kit/agents/verifier.md +728 -728
  31. package/kit/commands/adicionar-backlog.md +75 -75
  32. package/kit/commands/adicionar-fase.md +42 -42
  33. package/kit/commands/adicionar-tarefa.md +45 -45
  34. package/kit/commands/adicionar-testes.md +41 -41
  35. package/kit/commands/ajuda.md +21 -21
  36. package/kit/commands/atualizar.md +37 -37
  37. package/kit/commands/auditar-marco.md +179 -179
  38. package/kit/commands/auditar-uat.md +23 -23
  39. package/kit/commands/autonomo.md +40 -40
  40. package/kit/commands/branch-pr.md +24 -24
  41. package/kit/commands/concluir-marco.md +247 -247
  42. package/kit/commands/configuracoes.md +36 -36
  43. package/kit/commands/dados-distribuidos.md +188 -0
  44. package/kit/commands/definir-perfil.md +10 -10
  45. package/kit/commands/depurar.md +190 -190
  46. package/kit/commands/discutir-fase.md +131 -131
  47. package/kit/commands/entrar-discord.md +17 -17
  48. package/kit/commands/estatisticas.md +18 -18
  49. package/kit/commands/example-greeting.md +33 -33
  50. package/kit/commands/executar-fase.md +58 -58
  51. package/kit/commands/expresso.md +56 -56
  52. package/kit/commands/fase-ui.md +34 -34
  53. package/kit/commands/fazer.md +57 -57
  54. package/kit/commands/fio.md +125 -125
  55. package/kit/commands/fluxos-trabalho.md +64 -64
  56. package/kit/commands/forense.md +176 -176
  57. package/kit/commands/gerenciador.md +38 -38
  58. package/kit/commands/inserir-fase.md +31 -31
  59. package/kit/commands/limpeza.md +17 -17
  60. package/kit/commands/listar-hipoteses-fase.md +45 -45
  61. package/kit/commands/listar-workspaces.md +18 -18
  62. package/kit/commands/mapear-codebase.md +70 -70
  63. package/kit/commands/nota.md +33 -33
  64. package/kit/commands/novo-marco.md +43 -43
  65. package/kit/commands/novo-projeto.md +41 -41
  66. package/kit/commands/novo-workspace.md +43 -43
  67. package/kit/commands/pausar-trabalho.md +37 -37
  68. package/kit/commands/perfil-usuario.md +45 -45
  69. package/kit/commands/pesquisar-fase.md +195 -195
  70. package/kit/commands/planejar-fase.md +67 -67
  71. package/kit/commands/planejar-lacunas.md +33 -33
  72. package/kit/commands/plantar-ideia.md +25 -25
  73. package/kit/commands/progresso.md +24 -24
  74. package/kit/commands/proximo.md +30 -30
  75. package/kit/commands/publicar.md +490 -490
  76. package/kit/commands/rapido.md +35 -35
  77. package/kit/commands/reaplicar-patches.md +124 -124
  78. package/kit/commands/relatorio-sessao.md +19 -19
  79. package/kit/commands/remover-fase.md +31 -31
  80. package/kit/commands/remover-workspace.md +26 -26
  81. package/kit/commands/resumo-marco.md +50 -50
  82. package/kit/commands/retomar-trabalho.md +40 -40
  83. package/kit/commands/revisar-backlog.md +60 -60
  84. package/kit/commands/revisar-ui.md +32 -32
  85. package/kit/commands/revisar.md +37 -37
  86. package/kit/commands/saude.md +21 -21
  87. package/kit/commands/setup-notion.md +93 -93
  88. package/kit/commands/sync-main.md +68 -68
  89. package/kit/commands/validar-fase.md +35 -35
  90. package/kit/commands/verificar-tarefas.md +44 -44
  91. package/kit/commands/verificar-trabalho.md +64 -64
  92. package/kit/file-manifest.json +27 -15
  93. package/kit/framework/bin/lib/commands.cjs +959 -959
  94. package/kit/framework/bin/lib/config.cjs +442 -442
  95. package/kit/framework/bin/lib/core.cjs +1230 -1230
  96. package/kit/framework/bin/lib/frontmatter.cjs +336 -336
  97. package/kit/framework/bin/lib/init.cjs +1442 -1442
  98. package/kit/framework/bin/lib/milestone.cjs +252 -252
  99. package/kit/framework/bin/lib/model-profiles.cjs +68 -68
  100. package/kit/framework/bin/lib/phase.cjs +888 -888
  101. package/kit/framework/bin/lib/profile-output.cjs +952 -952
  102. package/kit/framework/bin/lib/profile-pipeline.cjs +539 -539
  103. package/kit/framework/bin/lib/roadmap.cjs +329 -329
  104. package/kit/framework/bin/lib/security.cjs +382 -382
  105. package/kit/framework/bin/lib/state.cjs +1031 -1031
  106. package/kit/framework/bin/lib/template.cjs +222 -222
  107. package/kit/framework/bin/lib/uat.cjs +282 -282
  108. package/kit/framework/bin/lib/verify.cjs +888 -888
  109. package/kit/framework/bin/lib/workstream.cjs +491 -491
  110. package/kit/framework/bin/tools.cjs +918 -918
  111. package/kit/framework/commands/workstreams.md +63 -63
  112. package/kit/framework/references/checkpoints.md +778 -778
  113. package/kit/framework/references/continuation-format.md +249 -249
  114. package/kit/framework/references/decimal-phase-calculation.md +64 -64
  115. package/kit/framework/references/git-integration.md +295 -295
  116. package/kit/framework/references/git-planning-commit.md +38 -38
  117. package/kit/framework/references/model-profile-resolution.md +36 -36
  118. package/kit/framework/references/model-profiles.md +139 -139
  119. package/kit/framework/references/phase-argument-parsing.md +61 -61
  120. package/kit/framework/references/planning-config.md +202 -202
  121. package/kit/framework/references/questioning.md +162 -162
  122. package/kit/framework/references/tdd.md +263 -263
  123. package/kit/framework/references/ui-brand.md +160 -160
  124. package/kit/framework/references/user-profiling.md +657 -657
  125. package/kit/framework/references/verification-patterns.md +612 -612
  126. package/kit/framework/references/workstream-flag.md +58 -58
  127. package/kit/framework/templates/DEBUG.md +164 -164
  128. package/kit/framework/templates/UAT.md +265 -265
  129. package/kit/framework/templates/UI-SPEC.md +100 -100
  130. package/kit/framework/templates/VALIDATION.md +76 -76
  131. package/kit/framework/templates/claude-md.md +122 -122
  132. package/kit/framework/templates/codebase/architecture.md +185 -185
  133. package/kit/framework/templates/codebase/concerns.md +205 -205
  134. package/kit/framework/templates/codebase/conventions.md +204 -204
  135. package/kit/framework/templates/codebase/integrations.md +192 -192
  136. package/kit/framework/templates/codebase/stack.md +158 -158
  137. package/kit/framework/templates/codebase/structure.md +199 -199
  138. package/kit/framework/templates/codebase/testing.md +301 -301
  139. package/kit/framework/templates/config.json +44 -44
  140. package/kit/framework/templates/context.md +352 -352
  141. package/kit/framework/templates/continue-here.md +78 -78
  142. package/kit/framework/templates/copilot-instructions.md +7 -7
  143. package/kit/framework/templates/debug-subagent-prompt.md +91 -91
  144. package/kit/framework/templates/dev-preferences.md +20 -20
  145. package/kit/framework/templates/discovery.md +146 -146
  146. package/kit/framework/templates/discussion-log.md +63 -63
  147. package/kit/framework/templates/milestone-archive.md +123 -123
  148. package/kit/framework/templates/milestone.md +115 -115
  149. package/kit/framework/templates/phase-prompt.md +610 -610
  150. package/kit/framework/templates/planner-subagent-prompt.md +117 -117
  151. package/kit/framework/templates/project.md +186 -186
  152. package/kit/framework/templates/requirements.md +231 -231
  153. package/kit/framework/templates/research-project/ARCHITECTURE.md +204 -204
  154. package/kit/framework/templates/research-project/FEATURES.md +147 -147
  155. package/kit/framework/templates/research-project/PITFALLS.md +200 -200
  156. package/kit/framework/templates/research-project/STACK.md +120 -120
  157. package/kit/framework/templates/research-project/SUMMARY.md +170 -170
  158. package/kit/framework/templates/research.md +419 -419
  159. package/kit/framework/templates/retrospective.md +54 -54
  160. package/kit/framework/templates/roadmap.md +202 -202
  161. package/kit/framework/templates/state.md +176 -176
  162. package/kit/framework/templates/summary-complex.md +59 -59
  163. package/kit/framework/templates/summary-minimal.md +41 -41
  164. package/kit/framework/templates/summary-standard.md +48 -48
  165. package/kit/framework/templates/summary.md +209 -209
  166. package/kit/framework/templates/user-profile.md +146 -146
  167. package/kit/framework/templates/user-setup.md +256 -256
  168. package/kit/framework/templates/verification-report.md +258 -258
  169. package/kit/framework/workflows/add-phase.md +112 -112
  170. package/kit/framework/workflows/add-tests.md +351 -351
  171. package/kit/framework/workflows/add-todo.md +158 -158
  172. package/kit/framework/workflows/audit-milestone.md +340 -340
  173. package/kit/framework/workflows/audit-uat.md +109 -109
  174. package/kit/framework/workflows/autonomous.md +891 -891
  175. package/kit/framework/workflows/check-todos.md +177 -177
  176. package/kit/framework/workflows/cleanup.md +152 -152
  177. package/kit/framework/workflows/complete-milestone.md +696 -696
  178. package/kit/framework/workflows/diagnose-issues.md +231 -231
  179. package/kit/framework/workflows/discovery-phase.md +289 -289
  180. package/kit/framework/workflows/discuss-phase-assumptions.md +653 -653
  181. package/kit/framework/workflows/discuss-phase.md +784 -784
  182. package/kit/framework/workflows/do.md +104 -104
  183. package/kit/framework/workflows/execute-phase.md +838 -838
  184. package/kit/framework/workflows/execute-plan.md +510 -510
  185. package/kit/framework/workflows/fast.md +102 -102
  186. package/kit/framework/workflows/forensics.md +265 -265
  187. package/kit/framework/workflows/health.md +181 -181
  188. package/kit/framework/workflows/help.md +619 -619
  189. package/kit/framework/workflows/insert-phase.md +130 -130
  190. package/kit/framework/workflows/list-phase-assumptions.md +178 -178
  191. package/kit/framework/workflows/list-workspaces.md +56 -56
  192. package/kit/framework/workflows/manager.md +362 -362
  193. package/kit/framework/workflows/map-codebase.md +377 -377
  194. package/kit/framework/workflows/milestone-summary.md +223 -223
  195. package/kit/framework/workflows/new-milestone.md +486 -486
  196. package/kit/framework/workflows/new-project.md +1159 -1159
  197. package/kit/framework/workflows/new-workspace.md +237 -237
  198. package/kit/framework/workflows/next.md +97 -97
  199. package/kit/framework/workflows/node-repair.md +92 -92
  200. package/kit/framework/workflows/note.md +156 -156
  201. package/kit/framework/workflows/pause-work.md +176 -176
  202. package/kit/framework/workflows/plan-milestone-gaps.md +273 -273
  203. package/kit/framework/workflows/plan-phase.md +765 -765
  204. package/kit/framework/workflows/plant-seed.md +169 -169
  205. package/kit/framework/workflows/pr-branch.md +129 -129
  206. package/kit/framework/workflows/profile-user.md +450 -450
  207. package/kit/framework/workflows/progress.md +507 -507
  208. package/kit/framework/workflows/quick.md +757 -757
  209. package/kit/framework/workflows/remove-phase.md +155 -155
  210. package/kit/framework/workflows/remove-workspace.md +90 -90
  211. package/kit/framework/workflows/research-phase.md +82 -82
  212. package/kit/framework/workflows/resume-project.md +326 -326
  213. package/kit/framework/workflows/review.md +228 -228
  214. package/kit/framework/workflows/session-report.md +146 -146
  215. package/kit/framework/workflows/settings.md +283 -283
  216. package/kit/framework/workflows/ship.md +228 -228
  217. package/kit/framework/workflows/stats.md +60 -60
  218. package/kit/framework/workflows/transition.md +671 -671
  219. package/kit/framework/workflows/ui-phase.md +302 -302
  220. package/kit/framework/workflows/ui-review.md +165 -165
  221. package/kit/framework/workflows/update.md +323 -323
  222. package/kit/framework/workflows/validate-phase.md +174 -174
  223. package/kit/framework/workflows/verify-phase.md +252 -252
  224. package/kit/framework/workflows/verify-work.md +637 -637
  225. package/kit/hooks/check-update.js +118 -118
  226. package/kit/hooks/context-monitor.js +163 -163
  227. package/kit/hooks/prompt-guard.js +103 -103
  228. package/kit/hooks/statusline.js +125 -125
  229. package/kit/hooks/workflow-guard.js +101 -101
  230. package/kit/settings.json +45 -45
  231. package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -0
  232. package/kit/skills/armadilhas-sistemas-distribuidos/SKILL.md +447 -0
  233. package/kit/skills/audit-log-multi-tenant/SKILL.md +6 -0
  234. package/kit/skills/cascading-failures/SKILL.md +4 -0
  235. package/kit/skills/consistencia-leitura-replica/SKILL.md +385 -0
  236. package/kit/skills/crm-lead-pipeline-patterns/SKILL.md +17 -0
  237. package/kit/skills/escolha-modelo-consistencia/SKILL.md +495 -0
  238. package/kit/skills/evolucao-schema-compativel/SKILL.md +448 -0
  239. package/kit/skills/example-skill/SKILL.md +42 -42
  240. package/kit/skills/multi-tenant-performance-scaling/SKILL.md +4 -0
  241. package/kit/skills/multi-tenant-rls-hierarchy/SKILL.md +4 -0
  242. package/kit/skills/postgres-isolamento-concorrencia/SKILL.md +552 -0
  243. package/kit/skills/streams-eventos-cdc/SKILL.md +712 -0
  244. package/kit/skills/supabase-cron-queues/SKILL.md +9 -0
  245. package/kit/skills/supabase-migrations/SKILL.md +10 -0
  246. package/kit/skills/super-admin-platform-pattern/SKILL.md +4 -0
  247. package/kit/skills/tenant-quente-mitigacao/SKILL.md +605 -0
  248. package/package.json +63 -63
  249. package/src/core/kit.js +216 -216
  250. package/src/core/reflect.js +247 -247
  251. package/src/core/reverse-sync.js +372 -372
  252. package/src/core/sync.js +418 -418
  253. package/src/core/watch.js +121 -121
@@ -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
+ };