@mobiman/vector 1.1.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 (225) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -0
  3. package/agents/vector-codebase-mapper.md +770 -0
  4. package/agents/vector-debugger.md +1338 -0
  5. package/agents/vector-executor.md +487 -0
  6. package/agents/vector-integration-checker.md +443 -0
  7. package/agents/vector-nyquist-auditor.md +176 -0
  8. package/agents/vector-phase-researcher.md +553 -0
  9. package/agents/vector-plan-checker.md +706 -0
  10. package/agents/vector-planner.md +1307 -0
  11. package/agents/vector-project-researcher.md +629 -0
  12. package/agents/vector-research-synthesizer.md +247 -0
  13. package/agents/vector-roadmapper.md +650 -0
  14. package/agents/vector-ui-auditor.md +439 -0
  15. package/agents/vector-ui-checker.md +300 -0
  16. package/agents/vector-ui-researcher.md +353 -0
  17. package/agents/vector-verifier.md +579 -0
  18. package/bin/install.cjs +2907 -0
  19. package/bin/install.cjs.map +1 -0
  20. package/bin/install.cts +3103 -0
  21. package/bin/install.d.cts +3 -0
  22. package/bin/install.d.cts.map +1 -0
  23. package/commands/vector/add-phase.md +43 -0
  24. package/commands/vector/add-tests.md +41 -0
  25. package/commands/vector/add-todo.md +47 -0
  26. package/commands/vector/audit-milestone.md +36 -0
  27. package/commands/vector/autonomous.md +41 -0
  28. package/commands/vector/check-todos.md +45 -0
  29. package/commands/vector/cleanup.md +18 -0
  30. package/commands/vector/complete-milestone.md +136 -0
  31. package/commands/vector/debug.md +168 -0
  32. package/commands/vector/discuss-phase.md +90 -0
  33. package/commands/vector/do.md +30 -0
  34. package/commands/vector/execute-phase.md +41 -0
  35. package/commands/vector/health.md +22 -0
  36. package/commands/vector/help.md +22 -0
  37. package/commands/vector/insert-phase.md +32 -0
  38. package/commands/vector/join-discord.md +18 -0
  39. package/commands/vector/list-phase-assumptions.md +46 -0
  40. package/commands/vector/map-codebase.md +71 -0
  41. package/commands/vector/new-milestone.md +44 -0
  42. package/commands/vector/new-project.md +42 -0
  43. package/commands/vector/pause-work.md +38 -0
  44. package/commands/vector/plan-milestone-gaps.md +34 -0
  45. package/commands/vector/plan-phase.md +45 -0
  46. package/commands/vector/progress.md +24 -0
  47. package/commands/vector/quick.md +47 -0
  48. package/commands/vector/reapply-patches.md +123 -0
  49. package/commands/vector/remove-phase.md +31 -0
  50. package/commands/vector/research-phase.md +190 -0
  51. package/commands/vector/resume-work.md +40 -0
  52. package/commands/vector/set-profile.md +12 -0
  53. package/commands/vector/settings.md +36 -0
  54. package/commands/vector/stats.md +18 -0
  55. package/commands/vector/ui-phase.md +34 -0
  56. package/commands/vector/ui-review.md +32 -0
  57. package/commands/vector/update.md +37 -0
  58. package/commands/vector/validate-phase.md +35 -0
  59. package/commands/vector/verify-work.md +38 -0
  60. package/core/bin/lib/commands.cjs +641 -0
  61. package/core/bin/lib/commands.cjs.map +1 -0
  62. package/core/bin/lib/commands.cts +712 -0
  63. package/core/bin/lib/commands.d.cts +23 -0
  64. package/core/bin/lib/commands.d.cts.map +1 -0
  65. package/core/bin/lib/config.cjs +281 -0
  66. package/core/bin/lib/config.cjs.map +1 -0
  67. package/core/bin/lib/config.cts +301 -0
  68. package/core/bin/lib/config.d.cts +50 -0
  69. package/core/bin/lib/config.d.cts.map +1 -0
  70. package/core/bin/lib/core.cjs +483 -0
  71. package/core/bin/lib/core.cjs.map +1 -0
  72. package/core/bin/lib/core.cts +544 -0
  73. package/core/bin/lib/core.d.cts +96 -0
  74. package/core/bin/lib/core.d.cts.map +1 -0
  75. package/core/bin/lib/frontmatter.cjs +341 -0
  76. package/core/bin/lib/frontmatter.cjs.map +1 -0
  77. package/core/bin/lib/frontmatter.cts +295 -0
  78. package/core/bin/lib/frontmatter.d.cts +18 -0
  79. package/core/bin/lib/frontmatter.d.cts.map +1 -0
  80. package/core/bin/lib/init.cjs +674 -0
  81. package/core/bin/lib/init.cjs.map +1 -0
  82. package/core/bin/lib/init.cts +775 -0
  83. package/core/bin/lib/init.d.cts +16 -0
  84. package/core/bin/lib/init.d.cts.map +1 -0
  85. package/core/bin/lib/milestone.cjs +210 -0
  86. package/core/bin/lib/milestone.cjs.map +1 -0
  87. package/core/bin/lib/milestone.cts +241 -0
  88. package/core/bin/lib/milestone.d.cts +11 -0
  89. package/core/bin/lib/milestone.d.cts.map +1 -0
  90. package/core/bin/lib/model-profiles.cjs +62 -0
  91. package/core/bin/lib/model-profiles.cjs.map +1 -0
  92. package/core/bin/lib/model-profiles.cts +66 -0
  93. package/core/bin/lib/model-profiles.d.cts +33 -0
  94. package/core/bin/lib/model-profiles.d.cts.map +1 -0
  95. package/core/bin/lib/phase.cjs +713 -0
  96. package/core/bin/lib/phase.cjs.map +1 -0
  97. package/core/bin/lib/phase.cts +914 -0
  98. package/core/bin/lib/phase.d.cts +21 -0
  99. package/core/bin/lib/phase.d.cts.map +1 -0
  100. package/core/bin/lib/roadmap.cjs +246 -0
  101. package/core/bin/lib/roadmap.cjs.map +1 -0
  102. package/core/bin/lib/roadmap.cts +311 -0
  103. package/core/bin/lib/roadmap.d.cts +7 -0
  104. package/core/bin/lib/roadmap.d.cts.map +1 -0
  105. package/core/bin/lib/state.cjs +709 -0
  106. package/core/bin/lib/state.cjs.map +1 -0
  107. package/core/bin/lib/state.cts +718 -0
  108. package/core/bin/lib/state.d.cts +47 -0
  109. package/core/bin/lib/state.d.cts.map +1 -0
  110. package/core/bin/lib/template.cjs +220 -0
  111. package/core/bin/lib/template.cjs.map +1 -0
  112. package/core/bin/lib/template.cts +229 -0
  113. package/core/bin/lib/template.d.cts +15 -0
  114. package/core/bin/lib/template.d.cts.map +1 -0
  115. package/core/bin/lib/verify.cjs +824 -0
  116. package/core/bin/lib/verify.cjs.map +1 -0
  117. package/core/bin/lib/verify.cts +829 -0
  118. package/core/bin/lib/verify.d.cts +17 -0
  119. package/core/bin/lib/verify.d.cts.map +1 -0
  120. package/core/bin/vector-tools.cjs +641 -0
  121. package/core/bin/vector-tools.cjs.map +1 -0
  122. package/core/bin/vector-tools.cts +603 -0
  123. package/core/bin/vector-tools.d.cts +128 -0
  124. package/core/bin/vector-tools.d.cts.map +1 -0
  125. package/core/references/checkpoints.md +776 -0
  126. package/core/references/continuation-format.md +249 -0
  127. package/core/references/decimal-phase-calculation.md +65 -0
  128. package/core/references/git-integration.md +248 -0
  129. package/core/references/git-planning-commit.md +38 -0
  130. package/core/references/model-profile-resolution.md +36 -0
  131. package/core/references/model-profiles.md +101 -0
  132. package/core/references/phase-argument-parsing.md +61 -0
  133. package/core/references/planning-config.md +200 -0
  134. package/core/references/questioning.md +162 -0
  135. package/core/references/tdd.md +263 -0
  136. package/core/references/ui-brand.md +160 -0
  137. package/core/references/verification-patterns.md +612 -0
  138. package/core/templates/DEBUG.md +164 -0
  139. package/core/templates/UAT.md +247 -0
  140. package/core/templates/UI-SPEC.md +100 -0
  141. package/core/templates/VALIDATION.md +76 -0
  142. package/core/templates/codebase/architecture.md +255 -0
  143. package/core/templates/codebase/concerns.md +310 -0
  144. package/core/templates/codebase/conventions.md +307 -0
  145. package/core/templates/codebase/integrations.md +280 -0
  146. package/core/templates/codebase/stack.md +186 -0
  147. package/core/templates/codebase/structure.md +285 -0
  148. package/core/templates/codebase/testing.md +480 -0
  149. package/core/templates/config.json +37 -0
  150. package/core/templates/context.md +352 -0
  151. package/core/templates/continue-here.md +78 -0
  152. package/core/templates/copilot-instructions.md +7 -0
  153. package/core/templates/debug-subagent-prompt.md +91 -0
  154. package/core/templates/discovery.md +146 -0
  155. package/core/templates/milestone-archive.md +123 -0
  156. package/core/templates/milestone.md +115 -0
  157. package/core/templates/phase-prompt.md +610 -0
  158. package/core/templates/planner-subagent-prompt.md +117 -0
  159. package/core/templates/project.md +184 -0
  160. package/core/templates/requirements.md +231 -0
  161. package/core/templates/research-project/ARCHITECTURE.md +204 -0
  162. package/core/templates/research-project/FEATURES.md +147 -0
  163. package/core/templates/research-project/PITFALLS.md +200 -0
  164. package/core/templates/research-project/STACK.md +120 -0
  165. package/core/templates/research-project/SUMMARY.md +170 -0
  166. package/core/templates/research.md +552 -0
  167. package/core/templates/retrospective.md +54 -0
  168. package/core/templates/roadmap.md +202 -0
  169. package/core/templates/state.md +176 -0
  170. package/core/templates/summary-complex.md +59 -0
  171. package/core/templates/summary-minimal.md +41 -0
  172. package/core/templates/summary-standard.md +48 -0
  173. package/core/templates/summary.md +248 -0
  174. package/core/templates/user-setup.md +311 -0
  175. package/core/templates/verification-report.md +322 -0
  176. package/core/workflows/add-phase.md +112 -0
  177. package/core/workflows/add-tests.md +351 -0
  178. package/core/workflows/add-todo.md +158 -0
  179. package/core/workflows/audit-milestone.md +332 -0
  180. package/core/workflows/autonomous.md +743 -0
  181. package/core/workflows/check-todos.md +177 -0
  182. package/core/workflows/cleanup.md +152 -0
  183. package/core/workflows/complete-milestone.md +766 -0
  184. package/core/workflows/diagnose-issues.md +219 -0
  185. package/core/workflows/discovery-phase.md +289 -0
  186. package/core/workflows/discuss-phase.md +762 -0
  187. package/core/workflows/do.md +104 -0
  188. package/core/workflows/execute-phase.md +468 -0
  189. package/core/workflows/execute-plan.md +483 -0
  190. package/core/workflows/health.md +159 -0
  191. package/core/workflows/help.md +513 -0
  192. package/core/workflows/insert-phase.md +130 -0
  193. package/core/workflows/list-phase-assumptions.md +178 -0
  194. package/core/workflows/map-codebase.md +316 -0
  195. package/core/workflows/new-milestone.md +386 -0
  196. package/core/workflows/new-project.md +1113 -0
  197. package/core/workflows/node-repair.md +92 -0
  198. package/core/workflows/pause-work.md +122 -0
  199. package/core/workflows/plan-milestone-gaps.md +274 -0
  200. package/core/workflows/plan-phase.md +666 -0
  201. package/core/workflows/progress.md +382 -0
  202. package/core/workflows/quick.md +717 -0
  203. package/core/workflows/remove-phase.md +155 -0
  204. package/core/workflows/research-phase.md +74 -0
  205. package/core/workflows/resume-project.md +307 -0
  206. package/core/workflows/settings.md +243 -0
  207. package/core/workflows/stats.md +60 -0
  208. package/core/workflows/transition.md +544 -0
  209. package/core/workflows/ui-phase.md +290 -0
  210. package/core/workflows/ui-review.md +157 -0
  211. package/core/workflows/update.md +320 -0
  212. package/core/workflows/validate-phase.md +167 -0
  213. package/core/workflows/verify-phase.md +243 -0
  214. package/core/workflows/verify-work.md +584 -0
  215. package/package.json +55 -0
  216. package/scripts/build-hooks.cjs +38 -0
  217. package/scripts/build-hooks.cjs.map +1 -0
  218. package/scripts/build-hooks.cts +41 -0
  219. package/scripts/build-hooks.d.cts +6 -0
  220. package/scripts/build-hooks.d.cts.map +1 -0
  221. package/scripts/run-tests.cjs +28 -0
  222. package/scripts/run-tests.cjs.map +1 -0
  223. package/scripts/run-tests.cts +28 -0
  224. package/scripts/run-tests.d.cts +3 -0
  225. package/scripts/run-tests.d.cts.map +1 -0
@@ -0,0 +1,914 @@
1
+ /**
2
+ * Phase — Phase CRUD, query, and lifecycle operations
3
+ */
4
+
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import { escapeRegex, normalizePhaseName, comparePhaseNum, findPhaseInternal, getArchivedPhaseDirs, generateSlugInternal, getMilestonePhaseFilter, stripShippedMilestones, replaceInCurrentMilestone, toPosixPath, output, error } from './core.cjs';
8
+ import { extractFrontmatter } from './frontmatter.cjs';
9
+ import { writeStateMd } from './state.cjs';
10
+
11
+ interface PhasesListOptions {
12
+ type?: string | null;
13
+ phase?: string | null;
14
+ includeArchived?: boolean;
15
+ }
16
+
17
+ export function cmdPhasesList(cwd: string, options: PhasesListOptions, raw: boolean): void {
18
+ const phasesDir = path.join(cwd, '.planning', 'phases');
19
+ const { type, phase, includeArchived } = options;
20
+
21
+ // If no phases directory, return empty
22
+ if (!fs.existsSync(phasesDir)) {
23
+ if (type) {
24
+ output({ files: [], count: 0 }, raw, '');
25
+ } else {
26
+ output({ directories: [], count: 0 }, raw, '');
27
+ }
28
+ return;
29
+ }
30
+
31
+ try {
32
+ // Get all phase directories
33
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
34
+ let dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
35
+
36
+ // Include archived phases if requested
37
+ if (includeArchived) {
38
+ const archived = getArchivedPhaseDirs(cwd);
39
+ for (const a of archived) {
40
+ dirs.push(`${a.name} [${a.milestone}]`);
41
+ }
42
+ }
43
+
44
+ // Sort numerically (handles integers, decimals, letter-suffix, hybrids)
45
+ dirs.sort((a, b) => comparePhaseNum(a, b));
46
+
47
+ // If filtering by phase number
48
+ if (phase) {
49
+ const normalized = normalizePhaseName(phase);
50
+ const match = dirs.find(d => d.startsWith(normalized));
51
+ if (!match) {
52
+ output({ files: [], count: 0, phase_dir: null, error: 'Phase not found' }, raw, '');
53
+ return;
54
+ }
55
+ dirs = [match];
56
+ }
57
+
58
+ // If listing files of a specific type
59
+ if (type) {
60
+ const files: string[] = [];
61
+ for (const dir of dirs) {
62
+ const dirPath = path.join(phasesDir, dir);
63
+ const dirFiles = fs.readdirSync(dirPath);
64
+
65
+ let filtered: string[];
66
+ if (type === 'plans') {
67
+ filtered = dirFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
68
+ } else if (type === 'summaries') {
69
+ filtered = dirFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
70
+ } else {
71
+ filtered = dirFiles;
72
+ }
73
+
74
+ files.push(...filtered.sort());
75
+ }
76
+
77
+ const result = {
78
+ files,
79
+ count: files.length,
80
+ phase_dir: phase ? dirs[0].replace(/^\d+(?:\.\d+)*-?/, '') : null,
81
+ };
82
+ output(result, raw, files.join('\n'));
83
+ return;
84
+ }
85
+
86
+ // Default: list directories
87
+ output({ directories: dirs, count: dirs.length }, raw, dirs.join('\n'));
88
+ } catch (e) {
89
+ error('Failed to list phases: ' + (e as Error).message);
90
+ }
91
+ }
92
+
93
+ export function cmdPhaseNextDecimal(cwd: string, basePhase: string, raw: boolean): void {
94
+ const phasesDir = path.join(cwd, '.planning', 'phases');
95
+ const normalized = normalizePhaseName(basePhase);
96
+
97
+ // Check if phases directory exists
98
+ if (!fs.existsSync(phasesDir)) {
99
+ output(
100
+ {
101
+ found: false,
102
+ base_phase: normalized,
103
+ next: `${normalized}.1`,
104
+ existing: [],
105
+ },
106
+ raw,
107
+ `${normalized}.1`
108
+ );
109
+ return;
110
+ }
111
+
112
+ try {
113
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
114
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
115
+
116
+ // Check if base phase exists
117
+ const baseExists = dirs.some(d => d.startsWith(normalized + '-') || d === normalized);
118
+
119
+ // Find existing decimal phases for this base
120
+ const decimalPattern = new RegExp(`^${normalized}\\.(\\d+)`);
121
+ const existingDecimals: string[] = [];
122
+
123
+ for (const dir of dirs) {
124
+ const match = dir.match(decimalPattern);
125
+ if (match) {
126
+ existingDecimals.push(`${normalized}.${match[1]}`);
127
+ }
128
+ }
129
+
130
+ // Sort numerically
131
+ existingDecimals.sort((a, b) => comparePhaseNum(a, b));
132
+
133
+ // Calculate next decimal
134
+ let nextDecimal: string;
135
+ if (existingDecimals.length === 0) {
136
+ nextDecimal = `${normalized}.1`;
137
+ } else {
138
+ const lastDecimal = existingDecimals[existingDecimals.length - 1];
139
+ const lastNum = parseInt(lastDecimal.split('.')[1], 10);
140
+ nextDecimal = `${normalized}.${lastNum + 1}`;
141
+ }
142
+
143
+ output(
144
+ {
145
+ found: baseExists,
146
+ base_phase: normalized,
147
+ next: nextDecimal,
148
+ existing: existingDecimals,
149
+ },
150
+ raw,
151
+ nextDecimal
152
+ );
153
+ } catch (e) {
154
+ error('Failed to calculate next decimal phase: ' + (e as Error).message);
155
+ }
156
+ }
157
+
158
+ export function cmdFindPhase(cwd: string, phase: string | undefined, raw: boolean): void {
159
+ if (!phase) {
160
+ error('phase identifier required');
161
+ }
162
+
163
+ const phasesDir = path.join(cwd, '.planning', 'phases');
164
+ const normalized = normalizePhaseName(phase);
165
+
166
+ const notFound = { found: false, directory: null, phase_number: null, phase_name: null, plans: [], summaries: [] };
167
+
168
+ try {
169
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
170
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
171
+
172
+ const match = dirs.find(d => d.startsWith(normalized));
173
+ if (!match) {
174
+ output(notFound, raw, '');
175
+ return;
176
+ }
177
+
178
+ const dirMatch = match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
179
+ const phaseNumber = dirMatch ? dirMatch[1] : normalized;
180
+ const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
181
+
182
+ const phaseDir = path.join(phasesDir, match);
183
+ const phaseFiles = fs.readdirSync(phaseDir);
184
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
185
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').sort();
186
+
187
+ const result = {
188
+ found: true,
189
+ directory: toPosixPath(path.join('.planning', 'phases', match)),
190
+ phase_number: phaseNumber,
191
+ phase_name: phaseName,
192
+ plans,
193
+ summaries,
194
+ };
195
+
196
+ output(result, raw, result.directory);
197
+ } catch {
198
+ output(notFound, raw, '');
199
+ }
200
+ }
201
+
202
+ function extractObjective(content: string): string | null {
203
+ const m = content.match(/<objective>\s*\n?\s*(.+)/);
204
+ return m ? m[1].trim() : null;
205
+ }
206
+
207
+ export function cmdPhasePlanIndex(cwd: string, phase: string | undefined, raw: boolean): void {
208
+ if (!phase) {
209
+ error('phase required for phase-plan-index');
210
+ }
211
+
212
+ const phasesDir = path.join(cwd, '.planning', 'phases');
213
+ const normalized = normalizePhaseName(phase);
214
+
215
+ // Find phase directory
216
+ let phaseDir: string | null = null;
217
+ try {
218
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
219
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
220
+ const match = dirs.find(d => d.startsWith(normalized));
221
+ if (match) {
222
+ phaseDir = path.join(phasesDir, match);
223
+ }
224
+ } catch {
225
+ // phases dir doesn't exist
226
+ }
227
+
228
+ if (!phaseDir) {
229
+ output({ phase: normalized, error: 'Phase not found', plans: [], waves: {}, incomplete: [], has_checkpoints: false }, raw);
230
+ return;
231
+ }
232
+
233
+ // Get all files in phase directory
234
+ const phaseFiles = fs.readdirSync(phaseDir);
235
+ const planFiles = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
236
+ const summaryFiles = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
237
+
238
+ // Build set of plan IDs with summaries
239
+ const completedPlanIds = new Set(
240
+ summaryFiles.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', ''))
241
+ );
242
+
243
+ interface PlanInfo {
244
+ id: string;
245
+ wave: number;
246
+ autonomous: boolean;
247
+ objective: string | null;
248
+ files_modified: string[];
249
+ task_count: number;
250
+ has_summary: boolean;
251
+ }
252
+
253
+ const plans: PlanInfo[] = [];
254
+ const waves: Record<string, string[]> = {};
255
+ const incomplete: string[] = [];
256
+ let hasCheckpoints = false;
257
+
258
+ for (const planFile of planFiles) {
259
+ const planId = planFile.replace('-PLAN.md', '').replace('PLAN.md', '');
260
+ const planPath = path.join(phaseDir, planFile);
261
+ const content = fs.readFileSync(planPath, 'utf-8');
262
+ const fm = extractFrontmatter(content);
263
+
264
+ // Count tasks: XML <task> tags (canonical) or ## Task N markdown (legacy)
265
+ const xmlTasks = content.match(/<task[\s>]/gi) || [];
266
+ const mdTasks = content.match(/##\s*Task\s*\d+/gi) || [];
267
+ const taskCount = xmlTasks.length || mdTasks.length;
268
+
269
+ // Parse wave as integer
270
+ const wave = parseInt(fm.wave as string, 10) || 1;
271
+
272
+ // Parse autonomous (default true if not specified)
273
+ let autonomous = true;
274
+ if (fm.autonomous !== undefined) {
275
+ autonomous = fm.autonomous === 'true' || fm.autonomous === true;
276
+ }
277
+
278
+ if (!autonomous) {
279
+ hasCheckpoints = true;
280
+ }
281
+
282
+ // Parse files_modified (underscore is canonical; also accept hyphenated for compat)
283
+ let filesModified: string[] = [];
284
+ const fmFiles = fm['files_modified'] || fm['files-modified'];
285
+ if (fmFiles) {
286
+ filesModified = Array.isArray(fmFiles) ? fmFiles as string[] : [fmFiles as string];
287
+ }
288
+
289
+ const hasSummary = completedPlanIds.has(planId);
290
+ if (!hasSummary) {
291
+ incomplete.push(planId);
292
+ }
293
+
294
+ const plan: PlanInfo = {
295
+ id: planId,
296
+ wave,
297
+ autonomous,
298
+ objective: extractObjective(content) || (fm.objective as string | null) || null,
299
+ files_modified: filesModified,
300
+ task_count: taskCount,
301
+ has_summary: hasSummary,
302
+ };
303
+
304
+ plans.push(plan);
305
+
306
+ // Group by wave
307
+ const waveKey = String(wave);
308
+ if (!waves[waveKey]) {
309
+ waves[waveKey] = [];
310
+ }
311
+ waves[waveKey].push(planId);
312
+ }
313
+
314
+ const result = {
315
+ phase: normalized,
316
+ plans,
317
+ waves,
318
+ incomplete,
319
+ has_checkpoints: hasCheckpoints,
320
+ };
321
+
322
+ output(result, raw);
323
+ }
324
+
325
+ export function cmdPhaseAdd(cwd: string, description: string, raw: boolean): void {
326
+ if (!description) {
327
+ error('description required for phase add');
328
+ }
329
+
330
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
331
+ if (!fs.existsSync(roadmapPath)) {
332
+ error('ROADMAP.md not found');
333
+ }
334
+
335
+ const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
336
+ const content = stripShippedMilestones(rawContent);
337
+ const slug = generateSlugInternal(description);
338
+
339
+ // Find highest integer phase number (in current milestone only)
340
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
341
+ let maxPhase = 0;
342
+ let m: RegExpExecArray | null;
343
+ while ((m = phasePattern.exec(content)) !== null) {
344
+ const num = parseInt(m[1], 10);
345
+ if (num > maxPhase) maxPhase = num;
346
+ }
347
+
348
+ const newPhaseNum = maxPhase + 1;
349
+ const paddedNum = String(newPhaseNum).padStart(2, '0');
350
+ const dirName = `${paddedNum}-${slug}`;
351
+ const dirPath = path.join(cwd, '.planning', 'phases', dirName);
352
+
353
+ // Create directory with .gitkeep so git tracks empty folders
354
+ fs.mkdirSync(dirPath, { recursive: true });
355
+ fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
356
+
357
+ // Build phase entry
358
+ const phaseEntry = `\n### Phase ${newPhaseNum}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD\n**Depends on:** Phase ${maxPhase}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /vector:plan-phase ${newPhaseNum} to break down)\n`;
359
+
360
+ // Find insertion point: before last "---" or at end
361
+ let updatedContent: string;
362
+ const lastSeparator = rawContent.lastIndexOf('\n---');
363
+ if (lastSeparator > 0) {
364
+ updatedContent = rawContent.slice(0, lastSeparator) + phaseEntry + rawContent.slice(lastSeparator);
365
+ } else {
366
+ updatedContent = rawContent + phaseEntry;
367
+ }
368
+
369
+ fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
370
+
371
+ const result = {
372
+ phase_number: newPhaseNum,
373
+ padded: paddedNum,
374
+ name: description,
375
+ slug,
376
+ directory: `.planning/phases/${dirName}`,
377
+ };
378
+
379
+ output(result, raw, paddedNum);
380
+ }
381
+
382
+ export function cmdPhaseInsert(cwd: string, afterPhase: string, description: string, raw: boolean): void {
383
+ if (!afterPhase || !description) {
384
+ error('after-phase and description required for phase insert');
385
+ }
386
+
387
+ const roadmapPath = path.join(cwd, '.planning', '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 = stripShippedMilestones(rawContent);
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(cwd, '.planning', 'phases');
407
+ const normalizedBase = normalizePhaseName(afterPhase);
408
+ const existingDecimals: number[] = [];
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 {}
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(cwd, '.planning', '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 /vector: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: number;
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: `.planning/phases/${dirName}`,
459
+ };
460
+
461
+ output(result, raw, decimalPhase);
462
+ }
463
+
464
+ interface PhaseRemoveOptions {
465
+ force?: boolean;
466
+ }
467
+
468
+ export function cmdPhaseRemove(cwd: string, targetPhase: string | undefined, options: PhaseRemoveOptions, raw: boolean): void {
469
+ if (!targetPhase) {
470
+ error('phase number required for phase remove');
471
+ }
472
+
473
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
474
+ const phasesDir = path.join(cwd, '.planning', 'phases');
475
+ const force = options.force || false;
476
+
477
+ if (!fs.existsSync(roadmapPath)) {
478
+ error('ROADMAP.md not found');
479
+ }
480
+
481
+ // Normalize the target
482
+ const normalized = normalizePhaseName(targetPhase!);
483
+ const isDecimal = targetPhase!.includes('.');
484
+
485
+ // Find and validate target directory
486
+ let targetDir: string | null = null;
487
+ try {
488
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
489
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
490
+ targetDir = dirs.find(d => d.startsWith(normalized + '-') || d === normalized) || null;
491
+ } catch {}
492
+
493
+ // Check for executed work (SUMMARY.md files)
494
+ if (targetDir && !force) {
495
+ const targetPath = path.join(phasesDir, targetDir);
496
+ const files = fs.readdirSync(targetPath);
497
+ const summaries = files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
498
+ if (summaries.length > 0) {
499
+ error(`Phase ${targetPhase} has ${summaries.length} executed plan(s). Use --force to remove anyway.`);
500
+ }
501
+ }
502
+
503
+ // Delete target directory
504
+ if (targetDir) {
505
+ fs.rmSync(path.join(phasesDir, targetDir), { recursive: true, force: true });
506
+ }
507
+
508
+ // Renumber subsequent phases
509
+ const renamedDirs: Array<{ from: string; to: string }> = [];
510
+ const renamedFiles: Array<{ from: string; to: string }> = [];
511
+
512
+ if (isDecimal) {
513
+ // Decimal removal: renumber sibling decimals (e.g., removing 06.2 → 06.3 becomes 06.2)
514
+ const baseParts = normalized.split('.');
515
+ const baseInt = baseParts[0];
516
+ const removedDecimal = parseInt(baseParts[1], 10);
517
+
518
+ try {
519
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
520
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
521
+
522
+ // Find sibling decimals with higher numbers
523
+ const decPattern = new RegExp(`^${baseInt}\\.(\\d+)-(.+)$`);
524
+ const toRename: Array<{ dir: string; oldDecimal: number; slug: string }> = [];
525
+ for (const dir of dirs) {
526
+ const dm = dir.match(decPattern);
527
+ if (dm && parseInt(dm[1], 10) > removedDecimal) {
528
+ toRename.push({ dir, oldDecimal: parseInt(dm[1], 10), slug: dm[2] });
529
+ }
530
+ }
531
+
532
+ // Sort descending to avoid conflicts
533
+ toRename.sort((a, b) => b.oldDecimal - a.oldDecimal);
534
+
535
+ for (const item of toRename) {
536
+ const newDecimal = item.oldDecimal - 1;
537
+ const oldPhaseId = `${baseInt}.${item.oldDecimal}`;
538
+ const newPhaseId = `${baseInt}.${newDecimal}`;
539
+ const newDirName = `${baseInt}.${newDecimal}-${item.slug}`;
540
+
541
+ // Rename directory
542
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
543
+ renamedDirs.push({ from: item.dir, to: newDirName });
544
+
545
+ // Rename files inside
546
+ const dirFiles = fs.readdirSync(path.join(phasesDir, newDirName));
547
+ for (const f of dirFiles) {
548
+ // Files may have phase prefix like "06.2-01-PLAN.md"
549
+ if (f.includes(oldPhaseId)) {
550
+ const newFileName = f.replace(oldPhaseId, newPhaseId);
551
+ fs.renameSync(
552
+ path.join(phasesDir, newDirName, f),
553
+ path.join(phasesDir, newDirName, newFileName)
554
+ );
555
+ renamedFiles.push({ from: f, to: newFileName });
556
+ }
557
+ }
558
+ }
559
+ } catch {}
560
+
561
+ } else {
562
+ // Integer removal: renumber all subsequent integer phases
563
+ const removedInt = parseInt(normalized, 10);
564
+
565
+ try {
566
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
567
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
568
+
569
+ // Collect directories that need renumbering (integer phases > removed, and their decimals/letters)
570
+ const toRename: Array<{ dir: string; oldInt: number; letter: string; decimal: number | null; slug: string }> = [];
571
+ for (const dir of dirs) {
572
+ const dm = dir.match(/^(\d+)([A-Z])?(?:\.(\d+))?-(.+)$/i);
573
+ if (!dm) continue;
574
+ const dirInt = parseInt(dm[1], 10);
575
+ if (dirInt > removedInt) {
576
+ toRename.push({
577
+ dir,
578
+ oldInt: dirInt,
579
+ letter: dm[2] ? dm[2].toUpperCase() : '',
580
+ decimal: dm[3] ? parseInt(dm[3], 10) : null,
581
+ slug: dm[4],
582
+ });
583
+ }
584
+ }
585
+
586
+ // Sort descending to avoid conflicts
587
+ toRename.sort((a, b) => {
588
+ if (a.oldInt !== b.oldInt) return b.oldInt - a.oldInt;
589
+ return (b.decimal || 0) - (a.decimal || 0);
590
+ });
591
+
592
+ for (const item of toRename) {
593
+ const newInt = item.oldInt - 1;
594
+ const newPadded = String(newInt).padStart(2, '0');
595
+ const oldPadded = String(item.oldInt).padStart(2, '0');
596
+ const letterSuffix = item.letter || '';
597
+ const decimalSuffix = item.decimal !== null ? `.${item.decimal}` : '';
598
+ const oldPrefix = `${oldPadded}${letterSuffix}${decimalSuffix}`;
599
+ const newPrefix = `${newPadded}${letterSuffix}${decimalSuffix}`;
600
+ const newDirName = `${newPrefix}-${item.slug}`;
601
+
602
+ // Rename directory
603
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
604
+ renamedDirs.push({ from: item.dir, to: newDirName });
605
+
606
+ // Rename files inside
607
+ const dirFiles = fs.readdirSync(path.join(phasesDir, newDirName));
608
+ for (const f of dirFiles) {
609
+ if (f.startsWith(oldPrefix)) {
610
+ const newFileName = newPrefix + f.slice(oldPrefix.length);
611
+ fs.renameSync(
612
+ path.join(phasesDir, newDirName, f),
613
+ path.join(phasesDir, newDirName, newFileName)
614
+ );
615
+ renamedFiles.push({ from: f, to: newFileName });
616
+ }
617
+ }
618
+ }
619
+ } catch {}
620
+ }
621
+
622
+ // Update ROADMAP.md
623
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
624
+
625
+ // Remove the target phase section
626
+ const targetEscaped = escapeRegex(targetPhase!);
627
+ const sectionPattern = new RegExp(
628
+ `\\n?#{2,4}\\s*Phase\\s+${targetEscaped}\\s*:[\\s\\S]*?(?=\\n#{2,4}\\s+Phase\\s+\\d|$)`,
629
+ 'i'
630
+ );
631
+ roadmapContent = roadmapContent.replace(sectionPattern, '');
632
+
633
+ // Remove from phase list (checkbox)
634
+ const checkboxPattern = new RegExp(`\\n?-\\s*\\[[ x]\\]\\s*.*Phase\\s+${targetEscaped}[:\\s][^\\n]*`, 'gi');
635
+ roadmapContent = roadmapContent.replace(checkboxPattern, '');
636
+
637
+ // Remove from progress table
638
+ const tableRowPattern = new RegExp(`\\n?\\|\\s*${targetEscaped}\\.?\\s[^|]*\\|[^\\n]*`, 'gi');
639
+ roadmapContent = roadmapContent.replace(tableRowPattern, '');
640
+
641
+ // Renumber references in ROADMAP for subsequent phases
642
+ if (!isDecimal) {
643
+ const removedInt = parseInt(normalized, 10);
644
+
645
+ // Collect all integer phases > removedInt
646
+ const maxPhase = 99; // reasonable upper bound
647
+ for (let oldNum = maxPhase; oldNum > removedInt; oldNum--) {
648
+ const newNum = oldNum - 1;
649
+ const oldStr = String(oldNum);
650
+ const newStr = String(newNum);
651
+ const oldPad = oldStr.padStart(2, '0');
652
+ const newPad = newStr.padStart(2, '0');
653
+
654
+ // Phase headings: ## Phase 18: or ### Phase 18: → ## Phase 17: or ### Phase 17:
655
+ roadmapContent = roadmapContent.replace(
656
+ new RegExp(`(#{2,4}\\s*Phase\\s+)${oldStr}(\\s*:)`, 'gi'),
657
+ `$1${newStr}$2`
658
+ );
659
+
660
+ // Checkbox items: - [ ] **Phase 18:** → - [ ] **Phase 17:**
661
+ roadmapContent = roadmapContent.replace(
662
+ new RegExp(`(Phase\\s+)${oldStr}([:\\s])`, 'g'),
663
+ `$1${newStr}$2`
664
+ );
665
+
666
+ // Plan references: 18-01 → 17-01
667
+ roadmapContent = roadmapContent.replace(
668
+ new RegExp(`${oldPad}-(\\d{2})`, 'g'),
669
+ `${newPad}-$1`
670
+ );
671
+
672
+ // Table rows: | 18. → | 17.
673
+ roadmapContent = roadmapContent.replace(
674
+ new RegExp(`(\\|\\s*)${oldStr}\\.\\s`, 'g'),
675
+ `$1${newStr}. `
676
+ );
677
+
678
+ // Depends on references
679
+ roadmapContent = roadmapContent.replace(
680
+ new RegExp(`(Depends on:\\*\\*\\s*Phase\\s+)${oldStr}\\b`, 'gi'),
681
+ `$1${newStr}`
682
+ );
683
+ }
684
+ }
685
+
686
+ fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
687
+
688
+ // Update STATE.md phase count
689
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
690
+ if (fs.existsSync(statePath)) {
691
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
692
+ // Update "Total Phases" field
693
+ const totalPattern = /(\*\*Total Phases:\*\*\s*)(\d+)/;
694
+ const totalMatch = stateContent.match(totalPattern);
695
+ if (totalMatch) {
696
+ const oldTotal = parseInt(totalMatch[2], 10);
697
+ stateContent = stateContent.replace(totalPattern, `$1${oldTotal - 1}`);
698
+ }
699
+ // Update "Phase: X of Y" pattern
700
+ const ofPattern = /(\bof\s+)(\d+)(\s*(?:\(|phases?))/i;
701
+ const ofMatch = stateContent.match(ofPattern);
702
+ if (ofMatch) {
703
+ const oldTotal = parseInt(ofMatch[2], 10);
704
+ stateContent = stateContent.replace(ofPattern, `$1${oldTotal - 1}$3`);
705
+ }
706
+ writeStateMd(statePath, stateContent, cwd);
707
+ }
708
+
709
+ const result = {
710
+ removed: targetPhase,
711
+ directory_deleted: targetDir || null,
712
+ renamed_directories: renamedDirs,
713
+ renamed_files: renamedFiles,
714
+ roadmap_updated: true,
715
+ state_updated: fs.existsSync(statePath),
716
+ };
717
+
718
+ output(result, raw);
719
+ }
720
+
721
+ export function cmdPhaseComplete(cwd: string, phaseNum: string | undefined, raw: boolean): void {
722
+ if (!phaseNum) {
723
+ error('phase number required for phase complete');
724
+ }
725
+
726
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
727
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
728
+ const phasesDir = path.join(cwd, '.planning', 'phases');
729
+ const today = new Date().toISOString().split('T')[0];
730
+
731
+ // Verify phase info
732
+ const phaseInfo = findPhaseInternal(cwd, phaseNum);
733
+ if (!phaseInfo) {
734
+ error(`Phase ${phaseNum} not found`);
735
+ }
736
+
737
+ const planCount = phaseInfo!.plans.length;
738
+ const summaryCount = phaseInfo!.summaries.length;
739
+ let requirementsUpdated = false;
740
+
741
+ // Update ROADMAP.md: mark phase complete
742
+ if (fs.existsSync(roadmapPath)) {
743
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
744
+
745
+ // Checkbox: - [ ] Phase N: → - [x] Phase N: (...completed DATE)
746
+ const checkboxPattern = new RegExp(
747
+ `(-\\s*\\[)[ ](\\]\\s*.*Phase\\s+${escapeRegex(phaseNum!)}[:\\s][^\\n]*)`,
748
+ 'i'
749
+ );
750
+ roadmapContent = replaceInCurrentMilestone(roadmapContent, checkboxPattern, `$1x$2 (completed ${today})`);
751
+
752
+ // Progress table: update Status to Complete, add date
753
+ const phaseEscaped = escapeRegex(phaseNum!);
754
+ const tablePattern = new RegExp(
755
+ `(\\|\\s*${phaseEscaped}\\.?\\s[^|]*\\|[^|]*\\|)\\s*[^|]*(\\|)\\s*[^|]*(\\|)`,
756
+ 'i'
757
+ );
758
+ roadmapContent = replaceInCurrentMilestone(
759
+ roadmapContent, tablePattern,
760
+ `$1 Complete $2 ${today} $3`
761
+ );
762
+
763
+ // Update plan count in phase section
764
+ const planCountPattern = new RegExp(
765
+ `(#{2,4}\\s*Phase\\s+${phaseEscaped}[\\s\\S]*?\\*\\*Plans:\\*\\*\\s*)[^\\n]+`,
766
+ 'i'
767
+ );
768
+ roadmapContent = replaceInCurrentMilestone(
769
+ roadmapContent, planCountPattern,
770
+ `$1${summaryCount}/${planCount} plans complete`
771
+ );
772
+
773
+ fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
774
+
775
+ // Update REQUIREMENTS.md traceability for this phase's requirements
776
+ const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
777
+ if (fs.existsSync(reqPath)) {
778
+ // Extract the current phase section from roadmap (scoped to avoid cross-phase matching)
779
+ const phaseEsc = escapeRegex(phaseNum!);
780
+ const currentMilestoneRoadmap = stripShippedMilestones(roadmapContent);
781
+ const phaseSectionMatch = currentMilestoneRoadmap.match(
782
+ new RegExp(`(#{2,4}\\s*Phase\\s+${phaseEsc}[:\\s][\\s\\S]*?)(?=#{2,4}\\s*Phase\\s+|$)`, 'i')
783
+ );
784
+
785
+ const sectionText = phaseSectionMatch ? phaseSectionMatch[1] : '';
786
+ const reqMatch = sectionText.match(/\*\*Requirements:\*\*\s*([^\n]+)/i);
787
+
788
+ if (reqMatch) {
789
+ const reqIds = reqMatch[1].replace(/[\[\]]/g, '').split(/[,\s]+/).map(r => r.trim()).filter(Boolean);
790
+ let reqContent = fs.readFileSync(reqPath, 'utf-8');
791
+
792
+ for (const reqId of reqIds) {
793
+ const reqEscaped = escapeRegex(reqId);
794
+ // Update checkbox: - [ ] **REQ-ID** → - [x] **REQ-ID**
795
+ reqContent = reqContent.replace(
796
+ new RegExp(`(-\\s*\\[)[ ](\\]\\s*\\*\\*${reqEscaped}\\*\\*)`, 'gi'),
797
+ '$1x$2'
798
+ );
799
+ // Update traceability table: | REQ-ID | Phase N | Pending/In Progress | → | REQ-ID | Phase N | Complete |
800
+ reqContent = reqContent.replace(
801
+ new RegExp(`(\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|)\\s*(?:Pending|In Progress)\\s*(\\|)`, 'gi'),
802
+ '$1 Complete $2'
803
+ );
804
+ }
805
+
806
+ fs.writeFileSync(reqPath, reqContent, 'utf-8');
807
+ requirementsUpdated = true;
808
+ }
809
+ }
810
+ }
811
+
812
+ // Find next phase — check both filesystem AND roadmap
813
+ let nextPhaseNum: string | null = null;
814
+ let nextPhaseName: string | null = null;
815
+ let isLastPhase = true;
816
+
817
+ try {
818
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
819
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
820
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name)
821
+ .filter(isDirInMilestone)
822
+ .sort((a, b) => comparePhaseNum(a, b));
823
+
824
+ // Find the next phase directory after current
825
+ for (const dir of dirs) {
826
+ const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
827
+ if (dm) {
828
+ if (comparePhaseNum(dm[1], phaseNum!) > 0) {
829
+ nextPhaseNum = dm[1];
830
+ nextPhaseName = dm[2] || null;
831
+ isLastPhase = false;
832
+ break;
833
+ }
834
+ }
835
+ }
836
+ } catch {}
837
+
838
+ // Fallback: if filesystem found no next phase, check ROADMAP.md
839
+ if (isLastPhase && fs.existsSync(roadmapPath)) {
840
+ try {
841
+ const roadmapForPhases = stripShippedMilestones(fs.readFileSync(roadmapPath, 'utf-8'));
842
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
843
+ let pm: RegExpExecArray | null;
844
+ while ((pm = phasePattern.exec(roadmapForPhases)) !== null) {
845
+ if (comparePhaseNum(pm[1], phaseNum!) > 0) {
846
+ nextPhaseNum = pm[1];
847
+ nextPhaseName = pm[2].replace(/\(INSERTED\)/i, '').trim().toLowerCase().replace(/\s+/g, '-');
848
+ isLastPhase = false;
849
+ break;
850
+ }
851
+ }
852
+ } catch {}
853
+ }
854
+
855
+ // Update STATE.md
856
+ if (fs.existsSync(statePath)) {
857
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
858
+
859
+ // Update Current Phase
860
+ stateContent = stateContent.replace(
861
+ /(\*\*Current Phase:\*\*\s*).*/,
862
+ `$1${nextPhaseNum || phaseNum}`
863
+ );
864
+
865
+ // Update Current Phase Name
866
+ if (nextPhaseName) {
867
+ stateContent = stateContent.replace(
868
+ /(\*\*Current Phase Name:\*\*\s*).*/,
869
+ `$1${nextPhaseName.replace(/-/g, ' ')}`
870
+ );
871
+ }
872
+
873
+ // Update Status
874
+ stateContent = stateContent.replace(
875
+ /(\*\*Status:\*\*\s*).*/,
876
+ `$1${isLastPhase ? 'Milestone complete' : 'Ready to plan'}`
877
+ );
878
+
879
+ // Update Current Plan
880
+ stateContent = stateContent.replace(
881
+ /(\*\*Current Plan:\*\*\s*).*/,
882
+ `$1Not started`
883
+ );
884
+
885
+ // Update Last Activity
886
+ stateContent = stateContent.replace(
887
+ /(\*\*Last Activity:\*\*\s*).*/,
888
+ `$1${today}`
889
+ );
890
+
891
+ // Update Last Activity Description
892
+ stateContent = stateContent.replace(
893
+ /(\*\*Last Activity Description:\*\*\s*).*/,
894
+ `$1Phase ${phaseNum} complete${nextPhaseNum ? `, transitioned to Phase ${nextPhaseNum}` : ''}`
895
+ );
896
+
897
+ writeStateMd(statePath, stateContent, cwd);
898
+ }
899
+
900
+ const result = {
901
+ completed_phase: phaseNum,
902
+ phase_name: phaseInfo!.phase_name,
903
+ plans_executed: `${summaryCount}/${planCount}`,
904
+ next_phase: nextPhaseNum,
905
+ next_phase_name: nextPhaseName,
906
+ is_last_phase: isLastPhase,
907
+ date: today,
908
+ roadmap_updated: fs.existsSync(roadmapPath),
909
+ state_updated: fs.existsSync(statePath),
910
+ requirements_updated: requirementsUpdated,
911
+ };
912
+
913
+ output(result, raw);
914
+ }