@undeemed/get-shit-done-codex 1.20.3 → 1.20.7

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