@howlil/ez-agents 3.1.0 → 3.4.2

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