@howlil/ez-agents 3.4.1 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +84 -20
  3. package/agents/ez-observer-agent.md +260 -0
  4. package/agents/ez-release-agent.md +333 -0
  5. package/agents/ez-requirements-agent.md +377 -0
  6. package/agents/ez-scrum-master-agent.md +242 -0
  7. package/agents/ez-tech-lead-agent.md +267 -0
  8. package/bin/install.js +3221 -3230
  9. package/commands/ez/arch-review.md +102 -0
  10. package/commands/ez/execute-phase.md +11 -0
  11. package/commands/ez/export-session.md +79 -0
  12. package/commands/ez/gather-requirements.md +117 -0
  13. package/commands/ez/git-workflow.md +72 -0
  14. package/commands/ez/hotfix.md +120 -0
  15. package/commands/ez/import-session.md +82 -0
  16. package/commands/ez/join-discord.md +18 -18
  17. package/commands/ez/list-sessions.md +96 -0
  18. package/commands/ez/package-manager.md +316 -0
  19. package/commands/ez/plan-phase.md +9 -1
  20. package/commands/ez/preflight.md +79 -0
  21. package/commands/ez/progress.md +13 -1
  22. package/commands/ez/release.md +153 -0
  23. package/commands/ez/resume.md +107 -0
  24. package/commands/ez/standup.md +85 -0
  25. package/ez-agents/bin/ez-tools.cjs +1095 -716
  26. package/ez-agents/bin/lib/assistant-adapter.cjs +264 -264
  27. package/ez-agents/bin/lib/audit-exec.cjs +7 -2
  28. package/ez-agents/bin/lib/bdd-validator.cjs +622 -0
  29. package/ez-agents/bin/lib/circuit-breaker.cjs +118 -118
  30. package/ez-agents/bin/lib/config.cjs +190 -190
  31. package/ez-agents/bin/lib/content-scanner.cjs +238 -0
  32. package/ez-agents/bin/lib/context-cache.cjs +154 -0
  33. package/ez-agents/bin/lib/context-errors.cjs +71 -0
  34. package/ez-agents/bin/lib/context-manager.cjs +220 -0
  35. package/ez-agents/bin/lib/discussion-synthesizer.cjs +458 -0
  36. package/ez-agents/bin/lib/file-access.cjs +207 -0
  37. package/ez-agents/bin/lib/file-lock.cjs +236 -236
  38. package/ez-agents/bin/lib/frontmatter.cjs +299 -299
  39. package/ez-agents/bin/lib/fs-utils.cjs +153 -153
  40. package/ez-agents/bin/lib/git-errors.cjs +83 -0
  41. package/ez-agents/bin/lib/git-utils.cjs +118 -0
  42. package/ez-agents/bin/lib/git-workflow-engine.cjs +1157 -0
  43. package/ez-agents/bin/lib/index.cjs +157 -113
  44. package/ez-agents/bin/lib/init.cjs +757 -757
  45. package/ez-agents/bin/lib/lockfile-validator.cjs +227 -0
  46. package/ez-agents/bin/lib/logger.cjs +124 -124
  47. package/ez-agents/bin/lib/memory-compression.cjs +256 -0
  48. package/ez-agents/bin/lib/metrics-tracker.cjs +406 -0
  49. package/ez-agents/bin/lib/milestone.cjs +241 -241
  50. package/ez-agents/bin/lib/model-provider.cjs +241 -241
  51. package/ez-agents/bin/lib/package-manager-detector.cjs +203 -0
  52. package/ez-agents/bin/lib/package-manager-executor.cjs +385 -0
  53. package/ez-agents/bin/lib/package-manager-service.cjs +216 -0
  54. package/ez-agents/bin/lib/phase.cjs +925 -925
  55. package/ez-agents/bin/lib/planning-write.cjs +107 -107
  56. package/ez-agents/bin/lib/release-validator.cjs +614 -0
  57. package/ez-agents/bin/lib/retry.cjs +119 -119
  58. package/ez-agents/bin/lib/roadmap.cjs +306 -306
  59. package/ez-agents/bin/lib/safe-exec.cjs +128 -128
  60. package/ez-agents/bin/lib/safe-path.cjs +130 -130
  61. package/ez-agents/bin/lib/session-chain.cjs +304 -0
  62. package/ez-agents/bin/lib/session-errors.cjs +81 -0
  63. package/ez-agents/bin/lib/session-export.cjs +251 -0
  64. package/ez-agents/bin/lib/session-import.cjs +262 -0
  65. package/ez-agents/bin/lib/session-manager.cjs +280 -0
  66. package/ez-agents/bin/lib/state.cjs +736 -736
  67. package/ez-agents/bin/lib/temp-file.cjs +239 -239
  68. package/ez-agents/bin/lib/template.cjs +223 -223
  69. package/ez-agents/bin/lib/test-file-lock.cjs +112 -112
  70. package/ez-agents/bin/lib/test-graceful.cjs +93 -93
  71. package/ez-agents/bin/lib/test-logger.cjs +60 -60
  72. package/ez-agents/bin/lib/test-safe-exec.cjs +38 -38
  73. package/ez-agents/bin/lib/test-safe-path.cjs +33 -33
  74. package/ez-agents/bin/lib/test-temp-file.cjs +125 -125
  75. package/ez-agents/bin/lib/tier-manager.cjs +428 -0
  76. package/ez-agents/bin/lib/timeout-exec.cjs +63 -63
  77. package/ez-agents/bin/lib/url-fetch.cjs +170 -0
  78. package/ez-agents/bin/lib/verify.cjs +15 -1
  79. package/ez-agents/references/checkpoints.md +776 -776
  80. package/ez-agents/references/continuation-format.md +249 -249
  81. package/ez-agents/references/metrics-schema.md +118 -0
  82. package/ez-agents/references/planning-config.md +140 -0
  83. package/ez-agents/references/questioning.md +162 -162
  84. package/ez-agents/references/tdd.md +263 -263
  85. package/ez-agents/references/tier-strategy.md +103 -0
  86. package/ez-agents/templates/bdd-feature.md +173 -0
  87. package/ez-agents/templates/codebase/concerns.md +310 -310
  88. package/ez-agents/templates/codebase/conventions.md +307 -307
  89. package/ez-agents/templates/codebase/integrations.md +280 -280
  90. package/ez-agents/templates/codebase/stack.md +186 -186
  91. package/ez-agents/templates/codebase/testing.md +480 -480
  92. package/ez-agents/templates/config.json +37 -37
  93. package/ez-agents/templates/continue-here.md +78 -78
  94. package/ez-agents/templates/discussion.md +68 -0
  95. package/ez-agents/templates/incident-runbook.md +205 -0
  96. package/ez-agents/templates/milestone-archive.md +123 -123
  97. package/ez-agents/templates/milestone.md +115 -115
  98. package/ez-agents/templates/release-checklist.md +133 -0
  99. package/ez-agents/templates/requirements.md +231 -231
  100. package/ez-agents/templates/research-project/ARCHITECTURE.md +204 -204
  101. package/ez-agents/templates/research-project/FEATURES.md +147 -147
  102. package/ez-agents/templates/research-project/PITFALLS.md +200 -200
  103. package/ez-agents/templates/research-project/STACK.md +120 -120
  104. package/ez-agents/templates/research-project/SUMMARY.md +170 -170
  105. package/ez-agents/templates/retrospective.md +54 -54
  106. package/ez-agents/templates/roadmap.md +202 -202
  107. package/ez-agents/templates/rollback-plan.md +201 -0
  108. package/ez-agents/templates/summary-minimal.md +41 -41
  109. package/ez-agents/templates/summary-standard.md +48 -48
  110. package/ez-agents/templates/summary.md +248 -248
  111. package/ez-agents/templates/user-setup.md +311 -311
  112. package/ez-agents/templates/verification-report.md +322 -322
  113. package/ez-agents/workflows/add-phase.md +112 -112
  114. package/ez-agents/workflows/add-tests.md +351 -351
  115. package/ez-agents/workflows/add-todo.md +158 -158
  116. package/ez-agents/workflows/arch-review.md +54 -0
  117. package/ez-agents/workflows/audit-milestone.md +332 -332
  118. package/ez-agents/workflows/autonomous.md +131 -30
  119. package/ez-agents/workflows/check-todos.md +177 -177
  120. package/ez-agents/workflows/cleanup.md +152 -152
  121. package/ez-agents/workflows/complete-milestone.md +766 -766
  122. package/ez-agents/workflows/diagnose-issues.md +219 -219
  123. package/ez-agents/workflows/discovery-phase.md +289 -289
  124. package/ez-agents/workflows/discuss-phase.md +762 -762
  125. package/ez-agents/workflows/execute-phase.md +513 -468
  126. package/ez-agents/workflows/execute-plan.md +483 -483
  127. package/ez-agents/workflows/export-session.md +255 -0
  128. package/ez-agents/workflows/gather-requirements.md +206 -0
  129. package/ez-agents/workflows/health.md +159 -159
  130. package/ez-agents/workflows/help.md +584 -492
  131. package/ez-agents/workflows/hotfix.md +291 -0
  132. package/ez-agents/workflows/import-session.md +303 -0
  133. package/ez-agents/workflows/insert-phase.md +130 -130
  134. package/ez-agents/workflows/list-phase-assumptions.md +178 -178
  135. package/ez-agents/workflows/map-codebase.md +316 -316
  136. package/ez-agents/workflows/new-milestone.md +339 -10
  137. package/ez-agents/workflows/new-project.md +293 -299
  138. package/ez-agents/workflows/node-repair.md +92 -92
  139. package/ez-agents/workflows/pause-work.md +122 -122
  140. package/ez-agents/workflows/plan-milestone-gaps.md +274 -274
  141. package/ez-agents/workflows/plan-phase.md +673 -651
  142. package/ez-agents/workflows/progress.md +372 -382
  143. package/ez-agents/workflows/quick.md +610 -610
  144. package/ez-agents/workflows/release.md +253 -0
  145. package/ez-agents/workflows/remove-phase.md +155 -155
  146. package/ez-agents/workflows/research-phase.md +74 -74
  147. package/ez-agents/workflows/resume-project.md +307 -307
  148. package/ez-agents/workflows/resume-session.md +215 -0
  149. package/ez-agents/workflows/set-profile.md +81 -81
  150. package/ez-agents/workflows/settings.md +242 -242
  151. package/ez-agents/workflows/standup.md +64 -0
  152. package/ez-agents/workflows/stats.md +57 -57
  153. package/ez-agents/workflows/transition.md +544 -544
  154. package/ez-agents/workflows/ui-phase.md +290 -290
  155. package/ez-agents/workflows/ui-review.md +157 -157
  156. package/ez-agents/workflows/update.md +320 -320
  157. package/ez-agents/workflows/validate-phase.md +167 -167
  158. package/ez-agents/workflows/verify-phase.md +243 -243
  159. package/ez-agents/workflows/verify-work.md +584 -584
  160. package/package.json +10 -4
  161. package/scripts/build-hooks.js +43 -43
  162. package/scripts/run-tests.cjs +29 -29
@@ -1,925 +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
- 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
- };
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
+ };