qaa-agent 1.0.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 (56) hide show
  1. package/.claude/commands/create-test.md +40 -0
  2. package/.claude/commands/qa-analyze.md +60 -0
  3. package/.claude/commands/qa-audit.md +37 -0
  4. package/.claude/commands/qa-blueprint.md +54 -0
  5. package/.claude/commands/qa-fix.md +36 -0
  6. package/.claude/commands/qa-from-ticket.md +88 -0
  7. package/.claude/commands/qa-gap.md +54 -0
  8. package/.claude/commands/qa-pom.md +36 -0
  9. package/.claude/commands/qa-pyramid.md +37 -0
  10. package/.claude/commands/qa-report.md +38 -0
  11. package/.claude/commands/qa-start.md +33 -0
  12. package/.claude/commands/qa-testid.md +54 -0
  13. package/.claude/commands/qa-validate.md +54 -0
  14. package/.claude/commands/update-test.md +58 -0
  15. package/.claude/settings.json +19 -0
  16. package/.claude/skills/qa-bug-detective/SKILL.md +122 -0
  17. package/.claude/skills/qa-repo-analyzer/SKILL.md +88 -0
  18. package/.claude/skills/qa-self-validator/SKILL.md +109 -0
  19. package/.claude/skills/qa-template-engine/SKILL.md +113 -0
  20. package/.claude/skills/qa-testid-injector/SKILL.md +93 -0
  21. package/.claude/skills/qa-workflow-documenter/SKILL.md +87 -0
  22. package/CLAUDE.md +543 -0
  23. package/README.md +418 -0
  24. package/agents/qa-pipeline-orchestrator.md +1217 -0
  25. package/agents/qaa-analyzer.md +508 -0
  26. package/agents/qaa-bug-detective.md +444 -0
  27. package/agents/qaa-executor.md +618 -0
  28. package/agents/qaa-planner.md +374 -0
  29. package/agents/qaa-scanner.md +422 -0
  30. package/agents/qaa-testid-injector.md +583 -0
  31. package/agents/qaa-validator.md +450 -0
  32. package/bin/install.cjs +176 -0
  33. package/bin/lib/commands.cjs +709 -0
  34. package/bin/lib/config.cjs +307 -0
  35. package/bin/lib/core.cjs +497 -0
  36. package/bin/lib/frontmatter.cjs +299 -0
  37. package/bin/lib/init.cjs +989 -0
  38. package/bin/lib/milestone.cjs +241 -0
  39. package/bin/lib/model-profiles.cjs +60 -0
  40. package/bin/lib/phase.cjs +911 -0
  41. package/bin/lib/roadmap.cjs +306 -0
  42. package/bin/lib/state.cjs +748 -0
  43. package/bin/lib/template.cjs +222 -0
  44. package/bin/lib/verify.cjs +842 -0
  45. package/bin/qaa-tools.cjs +607 -0
  46. package/package.json +34 -0
  47. package/templates/failure-classification.md +391 -0
  48. package/templates/gap-analysis.md +409 -0
  49. package/templates/pr-template.md +48 -0
  50. package/templates/qa-analysis.md +381 -0
  51. package/templates/qa-audit-report.md +465 -0
  52. package/templates/qa-repo-blueprint.md +636 -0
  53. package/templates/scan-manifest.md +312 -0
  54. package/templates/test-inventory.md +582 -0
  55. package/templates/testid-audit-report.md +354 -0
  56. package/templates/validation-report.md +243 -0
@@ -0,0 +1,911 @@
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, stripShippedMilestones, replaceInCurrentMilestone, 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 rawContent = fs.readFileSync(roadmapPath, 'utf-8');
322
+ const content = stripShippedMilestones(rawContent);
323
+ const slug = generateSlugInternal(description);
324
+
325
+ // Find highest integer phase number (in current milestone only)
326
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
327
+ let maxPhase = 0;
328
+ let m;
329
+ while ((m = phasePattern.exec(content)) !== null) {
330
+ const num = parseInt(m[1], 10);
331
+ if (num > maxPhase) maxPhase = num;
332
+ }
333
+
334
+ const newPhaseNum = maxPhase + 1;
335
+ const paddedNum = String(newPhaseNum).padStart(2, '0');
336
+ const dirName = `${paddedNum}-${slug}`;
337
+ const dirPath = path.join(cwd, '.planning', 'phases', dirName);
338
+
339
+ // Create directory with .gitkeep so git tracks empty folders
340
+ fs.mkdirSync(dirPath, { recursive: true });
341
+ fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
342
+
343
+ // Build phase entry
344
+ 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 planning for phase ${newPhaseNum})\n`;
345
+
346
+ // Find insertion point: before last "---" or at end
347
+ let updatedContent;
348
+ const lastSeparator = rawContent.lastIndexOf('\n---');
349
+ if (lastSeparator > 0) {
350
+ updatedContent = rawContent.slice(0, lastSeparator) + phaseEntry + rawContent.slice(lastSeparator);
351
+ } else {
352
+ updatedContent = rawContent + phaseEntry;
353
+ }
354
+
355
+ fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
356
+
357
+ const result = {
358
+ phase_number: newPhaseNum,
359
+ padded: paddedNum,
360
+ name: description,
361
+ slug,
362
+ directory: `.planning/phases/${dirName}`,
363
+ };
364
+
365
+ output(result, raw, paddedNum);
366
+ }
367
+
368
+ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
369
+ if (!afterPhase || !description) {
370
+ error('after-phase and description required for phase insert');
371
+ }
372
+
373
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
374
+ if (!fs.existsSync(roadmapPath)) {
375
+ error('ROADMAP.md not found');
376
+ }
377
+
378
+ const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
379
+ const content = stripShippedMilestones(rawContent);
380
+ const slug = generateSlugInternal(description);
381
+
382
+ // Normalize input then strip leading zeros for flexible matching
383
+ const normalizedAfter = normalizePhaseName(afterPhase);
384
+ const unpadded = normalizedAfter.replace(/^0+/, '');
385
+ const afterPhaseEscaped = unpadded.replace(/\./g, '\\.');
386
+ const targetPattern = new RegExp(`#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:`, 'i');
387
+ if (!targetPattern.test(content)) {
388
+ error(`Phase ${afterPhase} not found in ROADMAP.md`);
389
+ }
390
+
391
+ // Calculate next decimal using existing logic
392
+ const phasesDir = path.join(cwd, '.planning', 'phases');
393
+ const normalizedBase = normalizePhaseName(afterPhase);
394
+ let existingDecimals = [];
395
+
396
+ try {
397
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
398
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
399
+ const decimalPattern = new RegExp(`^${normalizedBase}\\.(\\d+)`);
400
+ for (const dir of dirs) {
401
+ const dm = dir.match(decimalPattern);
402
+ if (dm) existingDecimals.push(parseInt(dm[1], 10));
403
+ }
404
+ } catch {}
405
+
406
+ const nextDecimal = existingDecimals.length === 0 ? 1 : Math.max(...existingDecimals) + 1;
407
+ const decimalPhase = `${normalizedBase}.${nextDecimal}`;
408
+ const dirName = `${decimalPhase}-${slug}`;
409
+ const dirPath = path.join(cwd, '.planning', 'phases', dirName);
410
+
411
+ // Create directory with .gitkeep so git tracks empty folders
412
+ fs.mkdirSync(dirPath, { recursive: true });
413
+ fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
414
+
415
+ // Build phase entry
416
+ 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 planning for phase ${decimalPhase})\n`;
417
+
418
+ // Insert after the target phase section
419
+ const headerPattern = new RegExp(`(#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:[^\\n]*\\n)`, 'i');
420
+ const headerMatch = rawContent.match(headerPattern);
421
+ if (!headerMatch) {
422
+ error(`Could not find Phase ${afterPhase} header`);
423
+ }
424
+
425
+ const headerIdx = rawContent.indexOf(headerMatch[0]);
426
+ const afterHeader = rawContent.slice(headerIdx + headerMatch[0].length);
427
+ const nextPhaseMatch = afterHeader.match(/\n#{2,4}\s+Phase\s+\d/i);
428
+
429
+ let insertIdx;
430
+ if (nextPhaseMatch) {
431
+ insertIdx = headerIdx + headerMatch[0].length + nextPhaseMatch.index;
432
+ } else {
433
+ insertIdx = rawContent.length;
434
+ }
435
+
436
+ const updatedContent = rawContent.slice(0, insertIdx) + phaseEntry + rawContent.slice(insertIdx);
437
+ fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
438
+
439
+ const result = {
440
+ phase_number: decimalPhase,
441
+ after_phase: afterPhase,
442
+ name: description,
443
+ slug,
444
+ directory: `.planning/phases/${dirName}`,
445
+ };
446
+
447
+ output(result, raw, decimalPhase);
448
+ }
449
+
450
+ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
451
+ if (!targetPhase) {
452
+ error('phase number required for phase remove');
453
+ }
454
+
455
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
456
+ const phasesDir = path.join(cwd, '.planning', 'phases');
457
+ const force = options.force || false;
458
+
459
+ if (!fs.existsSync(roadmapPath)) {
460
+ error('ROADMAP.md not found');
461
+ }
462
+
463
+ // Normalize the target
464
+ const normalized = normalizePhaseName(targetPhase);
465
+ const isDecimal = targetPhase.includes('.');
466
+
467
+ // Find and validate target directory
468
+ let targetDir = null;
469
+ try {
470
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
471
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
472
+ targetDir = dirs.find(d => d.startsWith(normalized + '-') || d === normalized);
473
+ } catch {}
474
+
475
+ // Check for executed work (SUMMARY.md files)
476
+ if (targetDir && !force) {
477
+ const targetPath = path.join(phasesDir, targetDir);
478
+ const files = fs.readdirSync(targetPath);
479
+ const summaries = files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
480
+ if (summaries.length > 0) {
481
+ error(`Phase ${targetPhase} has ${summaries.length} executed plan(s). Use --force to remove anyway.`);
482
+ }
483
+ }
484
+
485
+ // Delete target directory
486
+ if (targetDir) {
487
+ fs.rmSync(path.join(phasesDir, targetDir), { recursive: true, force: true });
488
+ }
489
+
490
+ // Renumber subsequent phases
491
+ const renamedDirs = [];
492
+ const renamedFiles = [];
493
+
494
+ if (isDecimal) {
495
+ // Decimal removal: renumber sibling decimals (e.g., removing 06.2 -> 06.3 becomes 06.2)
496
+ const baseParts = normalized.split('.');
497
+ const baseInt = baseParts[0];
498
+ const removedDecimal = parseInt(baseParts[1], 10);
499
+
500
+ try {
501
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
502
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
503
+
504
+ // Find sibling decimals with higher numbers
505
+ const decPattern = new RegExp(`^${baseInt}\\.(\\d+)-(.+)$`);
506
+ const toRename = [];
507
+ for (const dir of dirs) {
508
+ const dm = dir.match(decPattern);
509
+ if (dm && parseInt(dm[1], 10) > removedDecimal) {
510
+ toRename.push({ dir, oldDecimal: parseInt(dm[1], 10), slug: dm[2] });
511
+ }
512
+ }
513
+
514
+ // Sort descending to avoid conflicts
515
+ toRename.sort((a, b) => b.oldDecimal - a.oldDecimal);
516
+
517
+ for (const item of toRename) {
518
+ const newDecimal = item.oldDecimal - 1;
519
+ const oldPhaseId = `${baseInt}.${item.oldDecimal}`;
520
+ const newPhaseId = `${baseInt}.${newDecimal}`;
521
+ const newDirName = `${baseInt}.${newDecimal}-${item.slug}`;
522
+
523
+ // Rename directory
524
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
525
+ renamedDirs.push({ from: item.dir, to: newDirName });
526
+
527
+ // Rename files inside
528
+ const dirFiles = fs.readdirSync(path.join(phasesDir, newDirName));
529
+ for (const f of dirFiles) {
530
+ // Files may have phase prefix like "06.2-01-PLAN.md"
531
+ if (f.includes(oldPhaseId)) {
532
+ const newFileName = f.replace(oldPhaseId, newPhaseId);
533
+ fs.renameSync(
534
+ path.join(phasesDir, newDirName, f),
535
+ path.join(phasesDir, newDirName, newFileName)
536
+ );
537
+ renamedFiles.push({ from: f, to: newFileName });
538
+ }
539
+ }
540
+ }
541
+ } catch {}
542
+
543
+ } else {
544
+ // Integer removal: renumber all subsequent integer phases
545
+ const removedInt = parseInt(normalized, 10);
546
+
547
+ try {
548
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
549
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
550
+
551
+ // Collect directories that need renumbering (integer phases > removed, and their decimals/letters)
552
+ const toRename = [];
553
+ for (const dir of dirs) {
554
+ const dm = dir.match(/^(\d+)([A-Z])?(?:\.(\d+))?-(.+)$/i);
555
+ if (!dm) continue;
556
+ const dirInt = parseInt(dm[1], 10);
557
+ if (dirInt > removedInt) {
558
+ toRename.push({
559
+ dir,
560
+ oldInt: dirInt,
561
+ letter: dm[2] ? dm[2].toUpperCase() : '',
562
+ decimal: dm[3] ? parseInt(dm[3], 10) : null,
563
+ slug: dm[4],
564
+ });
565
+ }
566
+ }
567
+
568
+ // Sort descending to avoid conflicts
569
+ toRename.sort((a, b) => {
570
+ if (a.oldInt !== b.oldInt) return b.oldInt - a.oldInt;
571
+ return (b.decimal || 0) - (a.decimal || 0);
572
+ });
573
+
574
+ for (const item of toRename) {
575
+ const newInt = item.oldInt - 1;
576
+ const newPadded = String(newInt).padStart(2, '0');
577
+ const oldPadded = String(item.oldInt).padStart(2, '0');
578
+ const letterSuffix = item.letter || '';
579
+ const decimalSuffix = item.decimal !== null ? `.${item.decimal}` : '';
580
+ const oldPrefix = `${oldPadded}${letterSuffix}${decimalSuffix}`;
581
+ const newPrefix = `${newPadded}${letterSuffix}${decimalSuffix}`;
582
+ const newDirName = `${newPrefix}-${item.slug}`;
583
+
584
+ // Rename directory
585
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
586
+ renamedDirs.push({ from: item.dir, to: newDirName });
587
+
588
+ // Rename files inside
589
+ const dirFiles = fs.readdirSync(path.join(phasesDir, newDirName));
590
+ for (const f of dirFiles) {
591
+ if (f.startsWith(oldPrefix)) {
592
+ const newFileName = newPrefix + f.slice(oldPrefix.length);
593
+ fs.renameSync(
594
+ path.join(phasesDir, newDirName, f),
595
+ path.join(phasesDir, newDirName, newFileName)
596
+ );
597
+ renamedFiles.push({ from: f, to: newFileName });
598
+ }
599
+ }
600
+ }
601
+ } catch {}
602
+ }
603
+
604
+ // Update ROADMAP.md
605
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
606
+
607
+ // Remove the target phase section
608
+ const targetEscaped = escapeRegex(targetPhase);
609
+ const sectionPattern = new RegExp(
610
+ `\\n?#{2,4}\\s*Phase\\s+${targetEscaped}\\s*:[\\s\\S]*?(?=\\n#{2,4}\\s+Phase\\s+\\d|$)`,
611
+ 'i'
612
+ );
613
+ roadmapContent = roadmapContent.replace(sectionPattern, '');
614
+
615
+ // Remove from phase list (checkbox)
616
+ const checkboxPattern = new RegExp(`\\n?-\\s*\\[[ x]\\]\\s*.*Phase\\s+${targetEscaped}[:\\s][^\\n]*`, 'gi');
617
+ roadmapContent = roadmapContent.replace(checkboxPattern, '');
618
+
619
+ // Remove from progress table
620
+ const tableRowPattern = new RegExp(`\\n?\\|\\s*${targetEscaped}\\.?\\s[^|]*\\|[^\\n]*`, 'gi');
621
+ roadmapContent = roadmapContent.replace(tableRowPattern, '');
622
+
623
+ // Renumber references in ROADMAP for subsequent phases
624
+ if (!isDecimal) {
625
+ const removedInt = parseInt(normalized, 10);
626
+
627
+ // Collect all integer phases > removedInt
628
+ const maxPhase = 99; // reasonable upper bound
629
+ for (let oldNum = maxPhase; oldNum > removedInt; oldNum--) {
630
+ const newNum = oldNum - 1;
631
+ const oldStr = String(oldNum);
632
+ const newStr = String(newNum);
633
+ const oldPad = oldStr.padStart(2, '0');
634
+ const newPad = newStr.padStart(2, '0');
635
+
636
+ // Phase headings: ## Phase 18: or ### Phase 18: -> ## Phase 17: or ### Phase 17:
637
+ roadmapContent = roadmapContent.replace(
638
+ new RegExp(`(#{2,4}\\s*Phase\\s+)${oldStr}(\\s*:)`, 'gi'),
639
+ `$1${newStr}$2`
640
+ );
641
+
642
+ // Checkbox items: - [ ] **Phase 18:** -> - [ ] **Phase 17:**
643
+ roadmapContent = roadmapContent.replace(
644
+ new RegExp(`(Phase\\s+)${oldStr}([:\\s])`, 'g'),
645
+ `$1${newStr}$2`
646
+ );
647
+
648
+ // Plan references: 18-01 -> 17-01
649
+ roadmapContent = roadmapContent.replace(
650
+ new RegExp(`${oldPad}-(\\d{2})`, 'g'),
651
+ `${newPad}-$1`
652
+ );
653
+
654
+ // Table rows: | 18. -> | 17.
655
+ roadmapContent = roadmapContent.replace(
656
+ new RegExp(`(\\|\\s*)${oldStr}\\.\\s`, 'g'),
657
+ `$1${newStr}. `
658
+ );
659
+
660
+ // Depends on references
661
+ roadmapContent = roadmapContent.replace(
662
+ new RegExp(`(Depends on:\\*\\*\\s*Phase\\s+)${oldStr}\\b`, 'gi'),
663
+ `$1${newStr}`
664
+ );
665
+ }
666
+ }
667
+
668
+ fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
669
+
670
+ // Update STATE.md phase count
671
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
672
+ if (fs.existsSync(statePath)) {
673
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
674
+ // Update "Total Phases" field
675
+ const totalPattern = /(\*\*Total Phases:\*\*\s*)(\d+)/;
676
+ const totalMatch = stateContent.match(totalPattern);
677
+ if (totalMatch) {
678
+ const oldTotal = parseInt(totalMatch[2], 10);
679
+ stateContent = stateContent.replace(totalPattern, `$1${oldTotal - 1}`);
680
+ }
681
+ // Update "Phase: X of Y" pattern
682
+ const ofPattern = /(\bof\s+)(\d+)(\s*(?:\(|phases?))/i;
683
+ const ofMatch = stateContent.match(ofPattern);
684
+ if (ofMatch) {
685
+ const oldTotal = parseInt(ofMatch[2], 10);
686
+ stateContent = stateContent.replace(ofPattern, `$1${oldTotal - 1}$3`);
687
+ }
688
+ writeStateMd(statePath, stateContent, cwd);
689
+ }
690
+
691
+ const result = {
692
+ removed: targetPhase,
693
+ directory_deleted: targetDir || null,
694
+ renamed_directories: renamedDirs,
695
+ renamed_files: renamedFiles,
696
+ roadmap_updated: true,
697
+ state_updated: fs.existsSync(statePath),
698
+ };
699
+
700
+ output(result, raw);
701
+ }
702
+
703
+ function cmdPhaseComplete(cwd, phaseNum, raw) {
704
+ if (!phaseNum) {
705
+ error('phase number required for phase complete');
706
+ }
707
+
708
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
709
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
710
+ const phasesDir = path.join(cwd, '.planning', 'phases');
711
+ const normalized = normalizePhaseName(phaseNum);
712
+ const today = new Date().toISOString().split('T')[0];
713
+
714
+ // Verify phase info
715
+ const phaseInfo = findPhaseInternal(cwd, phaseNum);
716
+ if (!phaseInfo) {
717
+ error(`Phase ${phaseNum} not found`);
718
+ }
719
+
720
+ const planCount = phaseInfo.plans.length;
721
+ const summaryCount = phaseInfo.summaries.length;
722
+ let requirementsUpdated = false;
723
+
724
+ // Update ROADMAP.md: mark phase complete
725
+ if (fs.existsSync(roadmapPath)) {
726
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
727
+
728
+ // Checkbox: - [ ] Phase N: -> - [x] Phase N: (...completed DATE)
729
+ const checkboxPattern = new RegExp(
730
+ `(-\\s*\\[)[ ](\\]\\s*.*Phase\\s+${escapeRegex(phaseNum)}[:\\s][^\\n]*)`,
731
+ 'i'
732
+ );
733
+ roadmapContent = replaceInCurrentMilestone(roadmapContent, checkboxPattern, `$1x$2 (completed ${today})`);
734
+
735
+ // Progress table: update Status to Complete, add date
736
+ const phaseEscaped = escapeRegex(phaseNum);
737
+ const tablePattern = new RegExp(
738
+ `(\\|\\s*${phaseEscaped}\\.?\\s[^|]*\\|[^|]*\\|)\\s*[^|]*(\\|)\\s*[^|]*(\\|)`,
739
+ 'i'
740
+ );
741
+ roadmapContent = replaceInCurrentMilestone(
742
+ roadmapContent, tablePattern,
743
+ `$1 Complete $2 ${today} $3`
744
+ );
745
+
746
+ // Update plan count in phase section
747
+ const planCountPattern = new RegExp(
748
+ `(#{2,4}\\s*Phase\\s+${phaseEscaped}[\\s\\S]*?\\*\\*Plans:\\*\\*\\s*)[^\\n]+`,
749
+ 'i'
750
+ );
751
+ roadmapContent = replaceInCurrentMilestone(
752
+ roadmapContent, planCountPattern,
753
+ `$1${summaryCount}/${planCount} plans complete`
754
+ );
755
+
756
+ fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
757
+
758
+ // Update REQUIREMENTS.md traceability for this phase's requirements
759
+ const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
760
+ if (fs.existsSync(reqPath)) {
761
+ // Extract the current phase section from roadmap (scoped to avoid cross-phase matching)
762
+ const phaseEsc = escapeRegex(phaseNum);
763
+ const currentMilestoneRoadmap = stripShippedMilestones(roadmapContent);
764
+ const phaseSectionMatch = currentMilestoneRoadmap.match(
765
+ new RegExp(`(#{2,4}\\s*Phase\\s+${phaseEsc}[:\\s][\\s\\S]*?)(?=#{2,4}\\s*Phase\\s+|$)`, 'i')
766
+ );
767
+
768
+ const sectionText = phaseSectionMatch ? phaseSectionMatch[1] : '';
769
+ const reqMatch = sectionText.match(/\*\*Requirements:\*\*\s*([^\n]+)/i);
770
+
771
+ if (reqMatch) {
772
+ const reqIds = reqMatch[1].replace(/[\[\]]/g, '').split(/[,\s]+/).map(r => r.trim()).filter(Boolean);
773
+ let reqContent = fs.readFileSync(reqPath, 'utf-8');
774
+
775
+ for (const reqId of reqIds) {
776
+ const reqEscaped = escapeRegex(reqId);
777
+ // Update checkbox: - [ ] **REQ-ID** -> - [x] **REQ-ID**
778
+ reqContent = reqContent.replace(
779
+ new RegExp(`(-\\s*\\[)[ ](\\]\\s*\\*\\*${reqEscaped}\\*\\*)`, 'gi'),
780
+ '$1x$2'
781
+ );
782
+ // Update traceability table: | REQ-ID | Phase N | Pending/In Progress | -> | REQ-ID | Phase N | Complete |
783
+ reqContent = reqContent.replace(
784
+ new RegExp(`(\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|)\\s*(?:Pending|In Progress)\\s*(\\|)`, 'gi'),
785
+ '$1 Complete $2'
786
+ );
787
+ }
788
+
789
+ fs.writeFileSync(reqPath, reqContent, 'utf-8');
790
+ requirementsUpdated = true;
791
+ }
792
+ }
793
+ }
794
+
795
+ // Find next phase -- check both filesystem AND roadmap
796
+ // Phases may be defined in ROADMAP.md but not yet scaffolded to disk,
797
+ // so a filesystem-only scan would incorrectly report is_last_phase:true
798
+ let nextPhaseNum = null;
799
+ let nextPhaseName = null;
800
+ let isLastPhase = true;
801
+
802
+ try {
803
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
804
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
805
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name)
806
+ .filter(isDirInMilestone)
807
+ .sort((a, b) => comparePhaseNum(a, b));
808
+
809
+ // Find the next phase directory after current
810
+ for (const dir of dirs) {
811
+ const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
812
+ if (dm) {
813
+ if (comparePhaseNum(dm[1], phaseNum) > 0) {
814
+ nextPhaseNum = dm[1];
815
+ nextPhaseName = dm[2] || null;
816
+ isLastPhase = false;
817
+ break;
818
+ }
819
+ }
820
+ }
821
+ } catch {}
822
+
823
+ // Fallback: if filesystem found no next phase, check ROADMAP.md
824
+ // for phases that are defined but not yet planned (no directory on disk)
825
+ if (isLastPhase && fs.existsSync(roadmapPath)) {
826
+ try {
827
+ const roadmapForPhases = stripShippedMilestones(fs.readFileSync(roadmapPath, 'utf-8'));
828
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
829
+ let pm;
830
+ while ((pm = phasePattern.exec(roadmapForPhases)) !== null) {
831
+ if (comparePhaseNum(pm[1], phaseNum) > 0) {
832
+ nextPhaseNum = pm[1];
833
+ nextPhaseName = pm[2].replace(/\(INSERTED\)/i, '').trim().toLowerCase().replace(/\s+/g, '-');
834
+ isLastPhase = false;
835
+ break;
836
+ }
837
+ }
838
+ } catch {}
839
+ }
840
+
841
+ // Update STATE.md
842
+ if (fs.existsSync(statePath)) {
843
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
844
+
845
+ // Update Current Phase
846
+ stateContent = stateContent.replace(
847
+ /(\*\*Current Phase:\*\*\s*).*/,
848
+ `$1${nextPhaseNum || phaseNum}`
849
+ );
850
+
851
+ // Update Current Phase Name
852
+ if (nextPhaseName) {
853
+ stateContent = stateContent.replace(
854
+ /(\*\*Current Phase Name:\*\*\s*).*/,
855
+ `$1${nextPhaseName.replace(/-/g, ' ')}`
856
+ );
857
+ }
858
+
859
+ // Update Status
860
+ stateContent = stateContent.replace(
861
+ /(\*\*Status:\*\*\s*).*/,
862
+ `$1${isLastPhase ? 'Milestone complete' : 'Ready to plan'}`
863
+ );
864
+
865
+ // Update Current Plan
866
+ stateContent = stateContent.replace(
867
+ /(\*\*Current Plan:\*\*\s*).*/,
868
+ `$1Not started`
869
+ );
870
+
871
+ // Update Last Activity
872
+ stateContent = stateContent.replace(
873
+ /(\*\*Last Activity:\*\*\s*).*/,
874
+ `$1${today}`
875
+ );
876
+
877
+ // Update Last Activity Description
878
+ stateContent = stateContent.replace(
879
+ /(\*\*Last Activity Description:\*\*\s*).*/,
880
+ `$1Phase ${phaseNum} complete${nextPhaseNum ? `, transitioned to Phase ${nextPhaseNum}` : ''}`
881
+ );
882
+
883
+ writeStateMd(statePath, stateContent, cwd);
884
+ }
885
+
886
+ const result = {
887
+ completed_phase: phaseNum,
888
+ phase_name: phaseInfo.phase_name,
889
+ plans_executed: `${summaryCount}/${planCount}`,
890
+ next_phase: nextPhaseNum,
891
+ next_phase_name: nextPhaseName,
892
+ is_last_phase: isLastPhase,
893
+ date: today,
894
+ roadmap_updated: fs.existsSync(roadmapPath),
895
+ state_updated: fs.existsSync(statePath),
896
+ requirements_updated: requirementsUpdated,
897
+ };
898
+
899
+ output(result, raw);
900
+ }
901
+
902
+ module.exports = {
903
+ cmdPhasesList,
904
+ cmdPhaseNextDecimal,
905
+ cmdFindPhase,
906
+ cmdPhasePlanIndex,
907
+ cmdPhaseAdd,
908
+ cmdPhaseInsert,
909
+ cmdPhaseRemove,
910
+ cmdPhaseComplete,
911
+ };