pan-wizard 2.8.1

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 (164) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +772 -0
  3. package/agents/pan-debugger.md +1246 -0
  4. package/agents/pan-document_code.md +965 -0
  5. package/agents/pan-executor.md +469 -0
  6. package/agents/pan-integration-checker.md +443 -0
  7. package/agents/pan-phase-researcher.md +572 -0
  8. package/agents/pan-plan-checker.md +763 -0
  9. package/agents/pan-planner.md +1297 -0
  10. package/agents/pan-project-researcher.md +647 -0
  11. package/agents/pan-research-synthesizer.md +239 -0
  12. package/agents/pan-reviewer.md +112 -0
  13. package/agents/pan-roadmapper.md +642 -0
  14. package/agents/pan-verifier.md +672 -0
  15. package/assets/pan-logo-2000-transparent.svg +30 -0
  16. package/assets/pan-logo-2000.svg +43 -0
  17. package/assets/terminal.svg +119 -0
  18. package/bin/install-lib.cjs +616 -0
  19. package/bin/install.js +1936 -0
  20. package/commands/pan/add-phase.md +44 -0
  21. package/commands/pan/assumptions.md +47 -0
  22. package/commands/pan/audit-deployment.md +378 -0
  23. package/commands/pan/debug.md +168 -0
  24. package/commands/pan/discord.md +19 -0
  25. package/commands/pan/discuss-phase.md +84 -0
  26. package/commands/pan/exec-phase.md +45 -0
  27. package/commands/pan/focus-auto.md +323 -0
  28. package/commands/pan/focus-design.md +816 -0
  29. package/commands/pan/focus-exec.md +316 -0
  30. package/commands/pan/focus-plan.md +101 -0
  31. package/commands/pan/focus-scan.md +272 -0
  32. package/commands/pan/focus-sync.md +104 -0
  33. package/commands/pan/health.md +23 -0
  34. package/commands/pan/help.md +23 -0
  35. package/commands/pan/insert-phase.md +33 -0
  36. package/commands/pan/map-codebase.md +72 -0
  37. package/commands/pan/milestone-audit.md +37 -0
  38. package/commands/pan/milestone-cleanup.md +19 -0
  39. package/commands/pan/milestone-done.md +137 -0
  40. package/commands/pan/milestone-gaps.md +35 -0
  41. package/commands/pan/milestone-new.md +45 -0
  42. package/commands/pan/new-project.md +43 -0
  43. package/commands/pan/patches.md +110 -0
  44. package/commands/pan/pause.md +39 -0
  45. package/commands/pan/phase-budget.md +23 -0
  46. package/commands/pan/phase-tests.md +42 -0
  47. package/commands/pan/plan-phase.md +46 -0
  48. package/commands/pan/profile.md +36 -0
  49. package/commands/pan/progress.md +25 -0
  50. package/commands/pan/quick.md +42 -0
  51. package/commands/pan/remove-phase.md +32 -0
  52. package/commands/pan/research-phase.md +190 -0
  53. package/commands/pan/resume.md +41 -0
  54. package/commands/pan/retro.md +33 -0
  55. package/commands/pan/settings.md +37 -0
  56. package/commands/pan/todo-add.md +48 -0
  57. package/commands/pan/todo-check.md +46 -0
  58. package/commands/pan/update.md +38 -0
  59. package/commands/pan/verify-phase.md +39 -0
  60. package/hooks/dist/pan-check-update.js +62 -0
  61. package/hooks/dist/pan-context-monitor.js +122 -0
  62. package/hooks/dist/pan-statusline.js +108 -0
  63. package/package.json +66 -0
  64. package/pan-wizard-core/bin/lib/codebase.cjs +746 -0
  65. package/pan-wizard-core/bin/lib/commands.cjs +1435 -0
  66. package/pan-wizard-core/bin/lib/config.cjs +611 -0
  67. package/pan-wizard-core/bin/lib/constants.cjs +696 -0
  68. package/pan-wizard-core/bin/lib/context-budget.cjs +150 -0
  69. package/pan-wizard-core/bin/lib/core.cjs +650 -0
  70. package/pan-wizard-core/bin/lib/focus.cjs +900 -0
  71. package/pan-wizard-core/bin/lib/frontmatter.cjs +442 -0
  72. package/pan-wizard-core/bin/lib/init.cjs +881 -0
  73. package/pan-wizard-core/bin/lib/milestone.cjs +276 -0
  74. package/pan-wizard-core/bin/lib/phase.cjs +1212 -0
  75. package/pan-wizard-core/bin/lib/roadmap.cjs +470 -0
  76. package/pan-wizard-core/bin/lib/state.cjs +1029 -0
  77. package/pan-wizard-core/bin/lib/template.cjs +314 -0
  78. package/pan-wizard-core/bin/lib/utils.cjs +171 -0
  79. package/pan-wizard-core/bin/lib/verify.cjs +1808 -0
  80. package/pan-wizard-core/bin/pan-tools.cjs +773 -0
  81. package/pan-wizard-core/references/checkpoints.md +776 -0
  82. package/pan-wizard-core/references/continuation-format.md +249 -0
  83. package/pan-wizard-core/references/decimal-phase-calculation.md +65 -0
  84. package/pan-wizard-core/references/git-integration.md +248 -0
  85. package/pan-wizard-core/references/git-planning-commit.md +38 -0
  86. package/pan-wizard-core/references/model-profile-resolution.md +34 -0
  87. package/pan-wizard-core/references/model-profiles.md +111 -0
  88. package/pan-wizard-core/references/phase-argument-parsing.md +61 -0
  89. package/pan-wizard-core/references/planning-config.md +196 -0
  90. package/pan-wizard-core/references/questioning.md +145 -0
  91. package/pan-wizard-core/references/tdd.md +263 -0
  92. package/pan-wizard-core/references/ui-brand.md +160 -0
  93. package/pan-wizard-core/references/verification-patterns.md +612 -0
  94. package/pan-wizard-core/templates/codebase/architecture.md +283 -0
  95. package/pan-wizard-core/templates/codebase/best-practices.md +133 -0
  96. package/pan-wizard-core/templates/codebase/concerns.md +325 -0
  97. package/pan-wizard-core/templates/codebase/conventions.md +307 -0
  98. package/pan-wizard-core/templates/codebase/integrations.md +305 -0
  99. package/pan-wizard-core/templates/codebase/relationships.md +124 -0
  100. package/pan-wizard-core/templates/codebase/stack.md +199 -0
  101. package/pan-wizard-core/templates/codebase/structure.md +298 -0
  102. package/pan-wizard-core/templates/codebase/testing.md +480 -0
  103. package/pan-wizard-core/templates/config.json +37 -0
  104. package/pan-wizard-core/templates/context.md +283 -0
  105. package/pan-wizard-core/templates/continue-here.md +78 -0
  106. package/pan-wizard-core/templates/debug-subagent-prompt.md +91 -0
  107. package/pan-wizard-core/templates/debug.md +164 -0
  108. package/pan-wizard-core/templates/discovery.md +146 -0
  109. package/pan-wizard-core/templates/milestone-archive.md +123 -0
  110. package/pan-wizard-core/templates/milestone.md +115 -0
  111. package/pan-wizard-core/templates/phase-prompt.md +593 -0
  112. package/pan-wizard-core/templates/planner-subagent-prompt.md +117 -0
  113. package/pan-wizard-core/templates/project.md +184 -0
  114. package/pan-wizard-core/templates/requirements.md +231 -0
  115. package/pan-wizard-core/templates/research-project/architecture.md +204 -0
  116. package/pan-wizard-core/templates/research-project/features.md +147 -0
  117. package/pan-wizard-core/templates/research-project/pitfalls.md +200 -0
  118. package/pan-wizard-core/templates/research-project/stack.md +120 -0
  119. package/pan-wizard-core/templates/research-project/summary.md +170 -0
  120. package/pan-wizard-core/templates/research.md +552 -0
  121. package/pan-wizard-core/templates/retrospective.md +54 -0
  122. package/pan-wizard-core/templates/roadmap.md +202 -0
  123. package/pan-wizard-core/templates/standards.md +24 -0
  124. package/pan-wizard-core/templates/state.md +176 -0
  125. package/pan-wizard-core/templates/summary-complex.md +59 -0
  126. package/pan-wizard-core/templates/summary-minimal.md +41 -0
  127. package/pan-wizard-core/templates/summary-standard.md +49 -0
  128. package/pan-wizard-core/templates/summary.md +249 -0
  129. package/pan-wizard-core/templates/uat.md +247 -0
  130. package/pan-wizard-core/templates/user-setup.md +311 -0
  131. package/pan-wizard-core/templates/validation.md +76 -0
  132. package/pan-wizard-core/templates/verification-report.md +322 -0
  133. package/pan-wizard-core/workflows/add-phase.md +111 -0
  134. package/pan-wizard-core/workflows/assumptions.md +178 -0
  135. package/pan-wizard-core/workflows/diagnose-issues.md +219 -0
  136. package/pan-wizard-core/workflows/discuss-phase.md +542 -0
  137. package/pan-wizard-core/workflows/exec-phase.md +572 -0
  138. package/pan-wizard-core/workflows/execute-plan.md +448 -0
  139. package/pan-wizard-core/workflows/health.md +156 -0
  140. package/pan-wizard-core/workflows/help.md +431 -0
  141. package/pan-wizard-core/workflows/insert-phase.md +129 -0
  142. package/pan-wizard-core/workflows/map-codebase.md +401 -0
  143. package/pan-wizard-core/workflows/milestone-audit.md +297 -0
  144. package/pan-wizard-core/workflows/milestone-cleanup.md +152 -0
  145. package/pan-wizard-core/workflows/milestone-gaps.md +274 -0
  146. package/pan-wizard-core/workflows/milestone-new.md +382 -0
  147. package/pan-wizard-core/workflows/new-project.md +1178 -0
  148. package/pan-wizard-core/workflows/pause.md +122 -0
  149. package/pan-wizard-core/workflows/phase-tests.md +388 -0
  150. package/pan-wizard-core/workflows/plan-phase.md +569 -0
  151. package/pan-wizard-core/workflows/profile.md +115 -0
  152. package/pan-wizard-core/workflows/progress.md +381 -0
  153. package/pan-wizard-core/workflows/quick.md +453 -0
  154. package/pan-wizard-core/workflows/remove-phase.md +154 -0
  155. package/pan-wizard-core/workflows/research-phase.md +73 -0
  156. package/pan-wizard-core/workflows/resume-project.md +306 -0
  157. package/pan-wizard-core/workflows/retro.md +121 -0
  158. package/pan-wizard-core/workflows/settings.md +213 -0
  159. package/pan-wizard-core/workflows/todo-add.md +157 -0
  160. package/pan-wizard-core/workflows/todo-check.md +176 -0
  161. package/pan-wizard-core/workflows/transition.md +544 -0
  162. package/pan-wizard-core/workflows/update.md +219 -0
  163. package/pan-wizard-core/workflows/verify-phase.md +301 -0
  164. package/scripts/build-hooks.js +43 -0
@@ -0,0 +1,1212 @@
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, loadConfig, output, error, toPosix, isGitRepo, execGit } = require('./core.cjs');
8
+ const { extractFrontmatter } = require('./frontmatter.cjs');
9
+ const { writeStateMd, readStateSafe } = require('./state.cjs');
10
+ const { PLANNING_DIR, PHASES_DIR, ROADMAP_FILE, REQUIREMENTS_FILE, STATE_FILE, isPlanFile, isSummaryFile, getPlanId, PHASE_DIR_RE, ARCHIVE_DIR_RE } = require('./constants.cjs');
11
+ const { planningPath, phasesPath, filterPlanFiles, filterSummaryFiles, parsePhaseDir, fileAccessible } = require('./utils.cjs');
12
+
13
+ /**
14
+ * List phase directories or files within phases, with optional type and archive filtering.
15
+ * @param {string} cwd - Working directory path
16
+ * @param {Object} options - Filter options (type, phase, includeArchived)
17
+ * @param {boolean} raw - If true, output raw value instead of JSON
18
+ * @returns {void}
19
+ */
20
+ function cmdPhasesList(cwd, options, raw) {
21
+ const phasesDir = phasesPath(cwd);
22
+ const { type, phase, includeArchived } = options;
23
+
24
+ let entries;
25
+ try {
26
+ entries = fs.readdirSync(phasesDir, { withFileTypes: true });
27
+ } catch {
28
+ if (type) {
29
+ output({ files: [], count: 0 }, raw, '');
30
+ } else {
31
+ output({ directories: [], count: 0 }, raw, '');
32
+ }
33
+ return;
34
+ }
35
+
36
+ try {
37
+ // Get all phase directories
38
+ let dirs = entries.filter(entry => entry.isDirectory()).map(entry => entry.name);
39
+
40
+ // Include archived phases if requested
41
+ if (includeArchived) {
42
+ const archived = getArchivedPhaseDirs(cwd);
43
+ for (const arch of archived) {
44
+ dirs.push(`${arch.name} [${arch.milestone}]`);
45
+ }
46
+ }
47
+
48
+ // Sort numerically (handles integers, decimals, letter-suffix, hybrids)
49
+ dirs.sort((left, right) => comparePhaseNum(left, right));
50
+
51
+ // If filtering by phase number
52
+ if (phase) {
53
+ const normalized = normalizePhaseName(phase);
54
+ const match = dirs.find(dir => dir.startsWith(normalized));
55
+ if (!match) {
56
+ output({ files: [], count: 0, phase_dir: null, error: 'Phase not found' }, raw, '');
57
+ return;
58
+ }
59
+ dirs = [match];
60
+ }
61
+
62
+ // If listing files of a specific type
63
+ if (type) {
64
+ const files = [];
65
+ for (const dir of dirs) {
66
+ const dirPath = path.join(phasesDir, dir);
67
+ const dirFiles = fs.readdirSync(dirPath);
68
+
69
+ let filtered;
70
+ if (type === 'plans') {
71
+ filtered = dirFiles.filter(isPlanFile);
72
+ } else if (type === 'summaries') {
73
+ filtered = dirFiles.filter(isSummaryFile);
74
+ } else {
75
+ error(`Unknown type: ${type}. Expected 'plans' or 'summaries'`);
76
+ }
77
+
78
+ files.push(...filtered.sort());
79
+ }
80
+
81
+ const result = {
82
+ files,
83
+ count: files.length,
84
+ phase_dir: phase ? dirs[0].replace(/^\d+(?:\.\d+)*-?/, '') : null,
85
+ };
86
+ output(result, raw, files.join('\n'));
87
+ return;
88
+ }
89
+
90
+ // Default: list directories
91
+ output({ directories: dirs, count: dirs.length }, raw, dirs.join('\n'));
92
+ } catch (err) {
93
+ error('Failed to list phases: ' + err.message);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Calculate the next available decimal phase number for inserting after a base phase.
99
+ * @param {string} cwd - Working directory path
100
+ * @param {string} basePhase - Base phase number to derive decimal from (e.g., "06")
101
+ * @param {boolean} raw - If true, output raw value instead of JSON
102
+ * @returns {void}
103
+ */
104
+ function cmdPhaseNextDecimal(cwd, basePhase, raw) {
105
+ const phasesDir = phasesPath(cwd);
106
+ const normalized = normalizePhaseName(basePhase);
107
+
108
+ let nextDecEntries;
109
+ try {
110
+ nextDecEntries = fs.readdirSync(phasesDir, { withFileTypes: true });
111
+ } catch {
112
+ output(
113
+ {
114
+ found: false,
115
+ base_phase: normalized,
116
+ next: `${normalized}.1`,
117
+ existing: [],
118
+ },
119
+ raw,
120
+ `${normalized}.1`
121
+ );
122
+ return;
123
+ }
124
+
125
+ try {
126
+ const dirs = nextDecEntries.filter(entry => entry.isDirectory()).map(entry => entry.name);
127
+
128
+ // Check if base phase exists
129
+ const baseExists = dirs.some(dir => dir.startsWith(normalized + '-') || dir === normalized);
130
+
131
+ // Find existing decimal phases for this base
132
+ const decimalPattern = new RegExp(`^${normalized}\\.(\\d+)`);
133
+ const existingDecimals = [];
134
+
135
+ for (const dir of dirs) {
136
+ const match = dir.match(decimalPattern);
137
+ if (match) {
138
+ existingDecimals.push(`${normalized}.${match[1]}`);
139
+ }
140
+ }
141
+
142
+ // Sort numerically
143
+ existingDecimals.sort((left, right) => comparePhaseNum(left, right));
144
+
145
+ // Calculate next decimal
146
+ let nextDecimal;
147
+ if (existingDecimals.length === 0) {
148
+ nextDecimal = `${normalized}.1`;
149
+ } else {
150
+ const lastDecimal = existingDecimals[existingDecimals.length - 1];
151
+ const lastNum = parseInt(lastDecimal.split('.')[1], 10);
152
+ nextDecimal = `${normalized}.${lastNum + 1}`;
153
+ }
154
+
155
+ output(
156
+ {
157
+ found: baseExists,
158
+ base_phase: normalized,
159
+ next: nextDecimal,
160
+ existing: existingDecimals,
161
+ },
162
+ raw,
163
+ nextDecimal
164
+ );
165
+ } catch (err) {
166
+ error('Failed to calculate next decimal phase: ' + err.message);
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Find a phase directory by number and return its metadata, plans, and summaries.
172
+ * @param {string} cwd - Working directory path
173
+ * @param {string} phase - Phase number or identifier to find
174
+ * @param {boolean} raw - If true, output raw value instead of JSON
175
+ * @returns {void}
176
+ */
177
+ function cmdFindPhase(cwd, phase, raw) {
178
+ if (!phase) {
179
+ error('phase identifier required');
180
+ }
181
+
182
+ const phasesDir = phasesPath(cwd);
183
+ const normalized = normalizePhaseName(phase);
184
+
185
+ const notFound = { found: false, directory: null, phase_number: null, phase_name: null, plans: [], summaries: [] };
186
+
187
+ try {
188
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
189
+ const dirs = entries.filter(entry => entry.isDirectory()).map(entry => entry.name).sort((left, right) => comparePhaseNum(left, right));
190
+
191
+ const match = dirs.find(dir => dir.startsWith(normalized));
192
+ if (!match) {
193
+ output(notFound, raw, '');
194
+ return;
195
+ }
196
+
197
+ // Parse phase number and name from directory name (e.g. "01-setup-auth")
198
+ const dirMatch = match.match(PHASE_DIR_RE);
199
+ const phaseNumber = dirMatch ? dirMatch[1] : normalized;
200
+ const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
201
+
202
+ const phaseDir = path.join(phasesDir, match);
203
+ const phaseFiles = fs.readdirSync(phaseDir);
204
+ const plans = filterPlanFiles(phaseFiles);
205
+ const summaries = filterSummaryFiles(phaseFiles);
206
+
207
+ const result = {
208
+ found: true,
209
+ directory: toPosix(path.join(PLANNING_DIR, PHASES_DIR, match)),
210
+ phase_number: phaseNumber,
211
+ phase_name: phaseName,
212
+ plans,
213
+ summaries,
214
+ };
215
+
216
+ output(result, raw, result.directory);
217
+ } catch {
218
+ // Phase directory does not exist or is unreadable
219
+ output(notFound, raw, '');
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Build an index of all plans in a phase with wave grouping, frontmatter, and completion status.
225
+ * @param {string} cwd - Working directory path
226
+ * @param {string} phase - Phase number to index
227
+ * @param {boolean} raw - If true, output raw value instead of JSON
228
+ * @returns {void}
229
+ */
230
+ function cmdPhasePlanIndex(cwd, phase, raw) {
231
+ if (!phase) {
232
+ error('phase required for phase-plan-index');
233
+ }
234
+
235
+ const phasesDir = phasesPath(cwd);
236
+ const normalized = normalizePhaseName(phase);
237
+
238
+ // Find phase directory
239
+ let phaseDir = null;
240
+ let phaseDirName = null;
241
+ try {
242
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
243
+ const dirs = entries.filter(entry => entry.isDirectory()).map(entry => entry.name).sort((left, right) => comparePhaseNum(left, right));
244
+ const match = dirs.find(dir => dir.startsWith(normalized));
245
+ if (match) {
246
+ phaseDir = path.join(phasesDir, match);
247
+ phaseDirName = match;
248
+ }
249
+ } catch {
250
+ // Phases directory does not exist or is unreadable
251
+ }
252
+
253
+ if (!phaseDir) {
254
+ output({ phase: normalized, error: 'Phase not found', plans: [], waves: {}, incomplete: [], has_checkpoints: false }, raw);
255
+ return;
256
+ }
257
+
258
+ // Get all files in phase directory
259
+ let phaseFiles;
260
+ try {
261
+ phaseFiles = fs.readdirSync(phaseDir);
262
+ } catch (e) {
263
+ output({ phase: normalized, error: 'Cannot read phase directory: ' + e.message, plans: [], waves: {}, incomplete: [], has_checkpoints: false }, raw);
264
+ return;
265
+ }
266
+ const planFiles = filterPlanFiles(phaseFiles);
267
+ const summaryFiles = filterSummaryFiles(phaseFiles);
268
+
269
+ const { plans, waves, incomplete, hasCheckpoints } = buildPlanIndex(phaseDir, planFiles, summaryFiles);
270
+
271
+ output({ phase: normalized, plans, waves, incomplete, has_checkpoints: hasCheckpoints }, raw);
272
+ }
273
+
274
+ /**
275
+ * Build a plan index from plan and summary file lists within a phase directory.
276
+ * Reads each plan file, extracts frontmatter, and builds plan detail objects.
277
+ * @param {string} phaseDir - Absolute path to the phase directory
278
+ * @param {string[]} planFiles - List of plan filenames
279
+ * @param {string[]} summaryFiles - List of summary filenames
280
+ * @returns {{plans: Array, waves: Object, incomplete: string[], hasCheckpoints: boolean}}
281
+ */
282
+ function buildPlanIndex(phaseDir, planFiles, summaryFiles) {
283
+ const completedPlanIds = new Set(
284
+ summaryFiles.map(summaryFile => summaryFile.replace('-summary.md', '').replace('summary.md', ''))
285
+ );
286
+
287
+ const plans = [];
288
+ const waves = {};
289
+ const incomplete = [];
290
+ let hasCheckpoints = false;
291
+
292
+ for (const planFile of planFiles) {
293
+ const planId = getPlanId(planFile);
294
+ const planFilePath = path.join(phaseDir, planFile);
295
+ let content, frontmatter;
296
+ try {
297
+ content = fs.readFileSync(planFilePath, 'utf-8');
298
+ frontmatter = extractFrontmatter(content);
299
+ } catch { continue; }
300
+
301
+ const taskMatches = content.match(/##\s*Task\s*\d+/gi) || [];
302
+ const taskCount = taskMatches.length;
303
+ const wave = parseInt(frontmatter.wave, 10) || 1;
304
+
305
+ let autonomous = true;
306
+ if (frontmatter.autonomous !== undefined) {
307
+ autonomous = frontmatter.autonomous === 'true' || frontmatter.autonomous === true;
308
+ }
309
+ if (!autonomous) hasCheckpoints = true;
310
+
311
+ let filesModified = [];
312
+ if (frontmatter['files-modified']) {
313
+ filesModified = Array.isArray(frontmatter['files-modified']) ? frontmatter['files-modified'] : [frontmatter['files-modified']];
314
+ }
315
+
316
+ const hasSummary = completedPlanIds.has(planId);
317
+ if (!hasSummary) incomplete.push(planId);
318
+
319
+ plans.push({
320
+ id: planId, wave, autonomous,
321
+ objective: frontmatter.objective || null,
322
+ files_modified: filesModified,
323
+ task_count: taskCount,
324
+ has_summary: hasSummary,
325
+ });
326
+
327
+ const waveKey = String(wave);
328
+ if (!waves[waveKey]) waves[waveKey] = [];
329
+ waves[waveKey].push(planId);
330
+ }
331
+
332
+ return { plans, waves, incomplete, hasCheckpoints };
333
+ }
334
+
335
+ /**
336
+ * Append a new phase to the end of the roadmap and create its directory.
337
+ * @param {string} cwd - Working directory path
338
+ * @param {string} description - Human-readable phase description
339
+ * @param {boolean} raw - If true, output raw value instead of JSON
340
+ * @returns {void}
341
+ */
342
+ function cmdPhaseAdd(cwd, description, raw) {
343
+ if (!description) {
344
+ error('description required for phase add');
345
+ }
346
+
347
+ const roadmapPath = path.join(planningPath(cwd), ROADMAP_FILE);
348
+ let content;
349
+ try {
350
+ content = fs.readFileSync(roadmapPath, 'utf-8');
351
+ } catch {
352
+ error('roadmap.md not found');
353
+ }
354
+ const slug = generateSlugInternal(description);
355
+
356
+ // Find highest integer phase number
357
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
358
+ let maxPhase = 0;
359
+ let phaseMatch;
360
+ while ((phaseMatch = phasePattern.exec(content)) !== null) {
361
+ const num = parseInt(phaseMatch[1], 10);
362
+ if (num > maxPhase) maxPhase = num;
363
+ }
364
+
365
+ const newPhaseNum = maxPhase + 1;
366
+ const paddedNum = String(newPhaseNum).padStart(2, '0');
367
+ const dirName = `${paddedNum}-${slug}`;
368
+ const dirPath = path.join(phasesPath(cwd), dirName);
369
+
370
+ // Create directory with .gitkeep so git tracks empty folders
371
+ try {
372
+ fs.mkdirSync(dirPath, { recursive: true });
373
+ fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
374
+ } catch (e) {
375
+ error(`Failed to create phase directory: ${e.message}`);
376
+ }
377
+
378
+ // Build phase entry
379
+ 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 /pan:plan-phase ${newPhaseNum} to break down)\n`;
380
+
381
+ // Find insertion point: before last "---" or at end
382
+ let updatedContent;
383
+ const lastSeparator = content.lastIndexOf('\n---');
384
+ if (lastSeparator > 0) {
385
+ updatedContent = content.slice(0, lastSeparator) + phaseEntry + content.slice(lastSeparator);
386
+ } else {
387
+ updatedContent = content + phaseEntry;
388
+ }
389
+
390
+ try {
391
+ fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
392
+ } catch (e) {
393
+ error(`Failed to write roadmap.md: ${e.message}`);
394
+ }
395
+
396
+ const result = {
397
+ phase_number: newPhaseNum,
398
+ padded: paddedNum,
399
+ name: description,
400
+ slug,
401
+ directory: `.planning/${PHASES_DIR}/${dirName}`,
402
+ };
403
+
404
+ output(result, raw, paddedNum);
405
+ }
406
+
407
+ /**
408
+ * Insert a decimal phase after an existing phase (e.g., 06.1) and update the roadmap.
409
+ * @param {string} cwd - Working directory path
410
+ * @param {string} afterPhase - Phase number to insert after
411
+ * @param {string} description - Human-readable phase description
412
+ * @param {boolean} raw - If true, output raw value instead of JSON
413
+ * @returns {void}
414
+ */
415
+ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
416
+ if (!afterPhase || !description) {
417
+ error('after-phase and description required for phase insert');
418
+ }
419
+
420
+ const roadmapPath = path.join(planningPath(cwd), ROADMAP_FILE);
421
+ let content;
422
+ try {
423
+ content = fs.readFileSync(roadmapPath, 'utf-8');
424
+ } catch {
425
+ error('roadmap.md not found');
426
+ }
427
+ const slug = generateSlugInternal(description);
428
+
429
+ // Normalize input then strip leading zeros for flexible matching
430
+ const normalizedAfter = normalizePhaseName(afterPhase);
431
+ const unpadded = normalizedAfter.replace(/^0+/, '');
432
+ const afterPhaseEscaped = unpadded.replace(/\./g, '\\.');
433
+ const targetPattern = new RegExp(`#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:`, 'i');
434
+ if (!targetPattern.test(content)) {
435
+ error(`Phase ${afterPhase} not found in roadmap.md`);
436
+ }
437
+
438
+ // Calculate next decimal using existing logic
439
+ const phasesDir = phasesPath(cwd);
440
+ const normalizedBase = normalizePhaseName(afterPhase);
441
+ let existingDecimals = [];
442
+
443
+ try {
444
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
445
+ const dirs = entries.filter(entry => entry.isDirectory()).map(entry => entry.name);
446
+ const decimalPattern = new RegExp(`^${normalizedBase}\\.(\\d+)`);
447
+ for (const dir of dirs) {
448
+ const decMatch = dir.match(decimalPattern);
449
+ if (decMatch) existingDecimals.push(parseInt(decMatch[1], 10));
450
+ }
451
+ } catch {
452
+ // Phases directory does not exist; proceed with empty decimal list
453
+ }
454
+
455
+ const nextDecimal = existingDecimals.length === 0 ? 1 : Math.max(...existingDecimals) + 1;
456
+ const decimalPhase = `${normalizedBase}.${nextDecimal}`;
457
+ const dirName = `${decimalPhase}-${slug}`;
458
+ const dirPath = path.join(phasesDir, dirName);
459
+
460
+ // Create directory with .gitkeep so git tracks empty folders
461
+ try {
462
+ fs.mkdirSync(dirPath, { recursive: true });
463
+ fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
464
+ } catch (e) {
465
+ error(`Failed to create phase directory: ${e.message}`);
466
+ }
467
+
468
+ // Build phase entry
469
+ 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 /pan:plan-phase ${decimalPhase} to break down)\n`;
470
+
471
+ // Insert after the target phase section
472
+ const headerPattern = new RegExp(`(#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:[^\\n]*\\n)`, 'i');
473
+ const headerMatch = content.match(headerPattern);
474
+ if (!headerMatch) {
475
+ error(`Could not find Phase ${afterPhase} header`);
476
+ }
477
+
478
+ const headerIdx = content.indexOf(headerMatch[0]);
479
+ const afterHeader = content.slice(headerIdx + headerMatch[0].length);
480
+ const nextPhaseMatch = afterHeader.match(/\n#{2,4}\s+Phase\s+\d/i);
481
+
482
+ let insertIdx;
483
+ if (nextPhaseMatch) {
484
+ insertIdx = headerIdx + headerMatch[0].length + nextPhaseMatch.index;
485
+ } else {
486
+ insertIdx = content.length;
487
+ }
488
+
489
+ const updatedContent = content.slice(0, insertIdx) + phaseEntry + content.slice(insertIdx);
490
+ try {
491
+ fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
492
+ } catch (e) {
493
+ error(`Failed to write roadmap.md: ${e.message}`);
494
+ }
495
+
496
+ const result = {
497
+ phase_number: decimalPhase,
498
+ after_phase: afterPhase,
499
+ name: description,
500
+ slug,
501
+ directory: `.planning/${PHASES_DIR}/${dirName}`,
502
+ };
503
+
504
+ output(result, raw, decimalPhase);
505
+ }
506
+
507
+ // ─── cmdPhaseRemove helpers ─────────────────────────────────────────────────
508
+
509
+ /**
510
+ * Delete a phase directory from disk.
511
+ * @param {string} phaseDir - Absolute path to the phase directory to remove
512
+ */
513
+ function removePhaseFromDisk(phaseDir) {
514
+ try {
515
+ fs.rmSync(phaseDir, { recursive: true, force: true });
516
+ } catch (e) {
517
+ return { removed: false, error: e.message };
518
+ }
519
+ return { removed: true };
520
+ }
521
+
522
+ /**
523
+ * Renumber sibling decimal phases after one is removed.
524
+ *
525
+ * Algorithm: When a decimal phase like 06.2 is removed, all higher-numbered
526
+ * siblings under the same base integer (06.3, 06.4, ...) must be decremented
527
+ * by 1 to fill the gap. We process in descending order to avoid directory
528
+ * name collisions during rename (e.g. rename 06.4 -> 06.3 before 06.3 -> 06.2).
529
+ *
530
+ * @param {string} phasesDir - Absolute path to the phases directory
531
+ * @param {string} baseInt - The integer portion of the removed phase (e.g. "06")
532
+ * @param {number} removedDecimal - The decimal portion that was removed (e.g. 2)
533
+ * @returns {{ renamedDirs: Array, renamedFiles: Array }}
534
+ */
535
+ function renumberDecimalPhases(phasesDir, baseInt, removedDecimal) {
536
+ const renamedDirs = [];
537
+ const renamedFiles = [];
538
+
539
+ try {
540
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
541
+ const dirs = entries.filter(entry => entry.isDirectory()).map(entry => entry.name).sort((left, right) => comparePhaseNum(left, right));
542
+
543
+ // Find sibling decimals with higher numbers than the removed one
544
+ const decPattern = new RegExp(`^${baseInt}\\.(\\d+)-(.+)$`);
545
+ const toRename = [];
546
+ for (const dir of dirs) {
547
+ const decMatch = dir.match(decPattern);
548
+ if (decMatch && parseInt(decMatch[1], 10) > removedDecimal) {
549
+ toRename.push({ dir, oldDecimal: parseInt(decMatch[1], 10), slug: decMatch[2] });
550
+ }
551
+ }
552
+
553
+ // Sort descending so higher-numbered dirs are renamed first,
554
+ // preventing collisions (e.g. 06.4 -> 06.3 before 06.3 -> 06.2)
555
+ toRename.sort((left, right) => right.oldDecimal - left.oldDecimal);
556
+
557
+ for (const item of toRename) {
558
+ const newDecimal = item.oldDecimal - 1;
559
+ const oldPhaseId = `${baseInt}.${item.oldDecimal}`;
560
+ const newPhaseId = `${baseInt}.${newDecimal}`;
561
+ const newDirName = `${baseInt}.${newDecimal}-${item.slug}`;
562
+
563
+ // Rename the directory itself (e.g. 06.3-foo -> 06.2-foo)
564
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
565
+ renamedDirs.push({ from: item.dir, to: newDirName });
566
+
567
+ // Rename files inside that contain the old phase ID prefix
568
+ const dirFiles = fs.readdirSync(path.join(phasesDir, newDirName));
569
+ for (const file of dirFiles) {
570
+ // Files may have phase prefix like "06.2-01-plan.md"
571
+ if (file.includes(oldPhaseId)) {
572
+ const newFileName = file.replace(oldPhaseId, newPhaseId);
573
+ fs.renameSync(
574
+ path.join(phasesDir, newDirName, file),
575
+ path.join(phasesDir, newDirName, newFileName)
576
+ );
577
+ renamedFiles.push({ from: file, to: newFileName });
578
+ }
579
+ }
580
+ }
581
+ } catch (e) {
582
+ return { renamedDirs, renamedFiles, error: `Partial rename: ${e.message}` };
583
+ }
584
+
585
+ return { renamedDirs, renamedFiles };
586
+ }
587
+
588
+ /**
589
+ * Renumber integer phases (and their decimal/letter children) after one is removed.
590
+ *
591
+ * Algorithm: When an integer phase like 05 is removed, all phases with a higher
592
+ * integer base (06, 06.1, 06A, 07, ...) must be decremented by 1. We process
593
+ * in descending order to avoid directory name collisions during the rename
594
+ * cascade (e.g. rename 07 -> 06 before 06 -> 05). Each directory and its
595
+ * contained files with the old phase prefix are renamed to reflect the new number.
596
+ *
597
+ * @param {string} phasesDir - Absolute path to the phases directory
598
+ * @param {number} removedInt - The integer phase number that was removed
599
+ * @returns {{ renamedDirs: Array, renamedFiles: Array }}
600
+ */
601
+ /**
602
+ * Collect phase directories that need renumbering (integer > removedInt).
603
+ * @param {string[]} dirs - Sorted directory names
604
+ * @param {number} removedInt - Removed phase integer
605
+ * @returns {Array} Items to rename, sorted descending to avoid collisions
606
+ */
607
+ function collectDirsToRenumber(dirs, removedInt) {
608
+ const toRename = [];
609
+ for (const dir of dirs) {
610
+ const dirMatch = dir.match(/^(\d+)([A-Z])?(?:\.(\d+))?-(.+)$/i);
611
+ if (!dirMatch) continue;
612
+ const dirInt = parseInt(dirMatch[1], 10);
613
+ if (dirInt > removedInt) {
614
+ toRename.push({
615
+ dir, oldInt: dirInt,
616
+ letter: dirMatch[2] ? dirMatch[2].toUpperCase() : '',
617
+ decimal: dirMatch[3] ? parseInt(dirMatch[3], 10) : null,
618
+ slug: dirMatch[4],
619
+ });
620
+ }
621
+ }
622
+ toRename.sort((left, right) => {
623
+ if (left.oldInt !== right.oldInt) return right.oldInt - left.oldInt;
624
+ return (right.decimal || 0) - (left.decimal || 0);
625
+ });
626
+ return toRename;
627
+ }
628
+
629
+ /**
630
+ * Rename a single phase directory and its internal files.
631
+ * @param {string} phasesDir - Phases directory path
632
+ * @param {Object} item - Rename item from collectDirsToRenumber
633
+ * @param {Array} renamedDirs - Accumulator for renamed dirs
634
+ * @param {Array} renamedFiles - Accumulator for renamed files
635
+ */
636
+ function renamePhaseDir(phasesDir, item, renamedDirs, renamedFiles) {
637
+ const newPadded = String(item.oldInt - 1).padStart(2, '0');
638
+ const oldPadded = String(item.oldInt).padStart(2, '0');
639
+ const suffix = (item.letter || '') + (item.decimal !== null ? `.${item.decimal}` : '');
640
+ const oldPrefix = oldPadded + suffix;
641
+ const newPrefix = newPadded + suffix;
642
+ const newDirName = `${newPrefix}-${item.slug}`;
643
+
644
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
645
+ renamedDirs.push({ from: item.dir, to: newDirName });
646
+
647
+ for (const file of fs.readdirSync(path.join(phasesDir, newDirName))) {
648
+ if (file.startsWith(oldPrefix)) {
649
+ const newFileName = newPrefix + file.slice(oldPrefix.length);
650
+ fs.renameSync(path.join(phasesDir, newDirName, file), path.join(phasesDir, newDirName, newFileName));
651
+ renamedFiles.push({ from: file, to: newFileName });
652
+ }
653
+ }
654
+ }
655
+
656
+ function renumberIntegerPhases(phasesDir, removedInt) {
657
+ const renamedDirs = [];
658
+ const renamedFiles = [];
659
+ try {
660
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
661
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
662
+ const toRename = collectDirsToRenumber(dirs, removedInt);
663
+ for (const item of toRename) renamePhaseDir(phasesDir, item, renamedDirs, renamedFiles);
664
+ } catch (e) {
665
+ return { renamedDirs, renamedFiles, error: `Partial rename: ${e.message}` };
666
+ }
667
+ return { renamedDirs, renamedFiles };
668
+ }
669
+
670
+ /**
671
+ * Rewrite roadmap.md after a phase is removed: delete the target section,
672
+ * remove checkbox/table references, and renumber subsequent phase references.
673
+ *
674
+ * @param {string} cwd - Working directory path
675
+ * @param {string} phaseNum - The phase number that was removed (as originally specified)
676
+ * @param {boolean} isDecimal - Whether the removed phase was a decimal phase
677
+ * @param {string} normalized - The zero-padded normalized phase number
678
+ */
679
+ function updateRoadmapAfterRemoval(cwd, phaseNum, isDecimal, normalized) {
680
+ const roadmapPath = path.join(planningPath(cwd), ROADMAP_FILE);
681
+ let roadmapContent;
682
+ try {
683
+ roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
684
+ } catch { return; }
685
+
686
+ // Remove the target phase section from roadmap.md.
687
+ // Matches from the phase heading to the next phase heading (or end of file).
688
+ const targetEscaped = escapeRegex(phaseNum);
689
+ const sectionPattern = new RegExp(
690
+ `\\n?#{2,4}\\s*Phase\\s+${targetEscaped}\\s*:[\\s\\S]*?(?=\\n#{2,4}\\s+Phase\\s+\\d|$)`,
691
+ 'i'
692
+ );
693
+ roadmapContent = roadmapContent.replace(sectionPattern, '');
694
+
695
+ // Remove checkbox list items referencing this phase
696
+ const checkboxPattern = new RegExp(`\\n?-\\s*\\[[ x]\\]\\s*.*Phase\\s+${targetEscaped}[:\\s][^\\n]*`, 'gi');
697
+ roadmapContent = roadmapContent.replace(checkboxPattern, '');
698
+
699
+ // Remove progress table rows referencing this phase
700
+ const tableRowPattern = new RegExp(`\\n?\\|\\s*${targetEscaped}\\.?\\s[^|]*\\|[^\\n]*`, 'gi');
701
+ roadmapContent = roadmapContent.replace(tableRowPattern, '');
702
+
703
+ // For integer phase removal, renumber all references to subsequent phases.
704
+ // Walk from highest phase number down to removedInt+1, decrementing each by 1.
705
+ // This avoids double-renaming (e.g. 8->7 then 7->6 would break if done ascending).
706
+ if (!isDecimal) {
707
+ const removedInt = parseInt(normalized, 10);
708
+
709
+ // Reasonable upper bound for phase numbers
710
+ const maxPhase = 99;
711
+ for (let oldNum = maxPhase; oldNum > removedInt; oldNum--) {
712
+ const newNum = oldNum - 1;
713
+ const oldStr = String(oldNum);
714
+ const newStr = String(newNum);
715
+ const oldPad = oldStr.padStart(2, '0');
716
+ const newPad = newStr.padStart(2, '0');
717
+
718
+ // Phase headings: ## Phase 18: or ### Phase 18: -> ## Phase 17:
719
+ roadmapContent = roadmapContent.replace(
720
+ new RegExp(`(#{2,4}\\s*Phase\\s+)${oldStr}(\\s*:)`, 'gi'),
721
+ `$1${newStr}$2`
722
+ );
723
+
724
+ // Inline phase references: "Phase 18:" or "Phase 18 " -> "Phase 17:"
725
+ roadmapContent = roadmapContent.replace(
726
+ new RegExp(`(Phase\\s+)${oldStr}([:\\s])`, 'g'),
727
+ `$1${newStr}$2`
728
+ );
729
+
730
+ // Plan references in padded form: 18-01 -> 17-01
731
+ roadmapContent = roadmapContent.replace(
732
+ new RegExp(`${oldPad}-(\\d{2})`, 'g'),
733
+ `${newPad}-$1`
734
+ );
735
+
736
+ // Progress table row numbers: | 18. -> | 17.
737
+ roadmapContent = roadmapContent.replace(
738
+ new RegExp(`(\\|\\s*)${oldStr}\\.\\s`, 'g'),
739
+ `$1${newStr}. `
740
+ );
741
+
742
+ // Depends-on references: "Depends on:** Phase 18" -> "Phase 17"
743
+ roadmapContent = roadmapContent.replace(
744
+ new RegExp(`(Depends on:\\*\\*\\s*Phase\\s+)${oldStr}\\b`, 'gi'),
745
+ `$1${newStr}`
746
+ );
747
+ }
748
+ }
749
+
750
+ try { fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8'); } catch { /* best-effort */ }
751
+ }
752
+
753
+ /**
754
+ * Remove a phase directory, renumber subsequent phases, and update ROADMAP/STATE.
755
+ * @param {string} cwd - Working directory path
756
+ * @param {string} targetPhase - Phase number to remove
757
+ * @param {Object} options - Options (force: skip executed-work check)
758
+ * @param {boolean} raw - If true, output raw value instead of JSON
759
+ * @returns {void}
760
+ */
761
+ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
762
+ if (!targetPhase) {
763
+ error('phase number required for phase remove');
764
+ }
765
+
766
+ const roadmapPath = path.join(planningPath(cwd), ROADMAP_FILE);
767
+ const phasesDir = phasesPath(cwd);
768
+ const force = options.force || false;
769
+
770
+ if (!fileAccessible(roadmapPath)) {
771
+ error('roadmap.md not found');
772
+ }
773
+
774
+ // Normalize the target
775
+ const normalized = normalizePhaseName(targetPhase);
776
+ const isDecimal = targetPhase.includes('.');
777
+
778
+ // Find and validate target directory
779
+ let targetDir = null;
780
+ try {
781
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
782
+ const dirs = entries.filter(entry => entry.isDirectory()).map(entry => entry.name).sort((left, right) => comparePhaseNum(left, right));
783
+ targetDir = dirs.find(dir => dir.startsWith(normalized + '-') || dir === normalized);
784
+ } catch {
785
+ // Phases directory does not exist; targetDir remains null
786
+ }
787
+
788
+ // Check for executed work (summary.md files)
789
+ if (targetDir && !force) {
790
+ const targetPath = path.join(phasesDir, targetDir);
791
+ const files = fs.readdirSync(targetPath);
792
+ const summaries = files.filter(isSummaryFile);
793
+ if (summaries.length > 0) {
794
+ error(`Phase ${targetPhase} has ${summaries.length} executed plan(s). Use --force to remove anyway.`);
795
+ }
796
+ }
797
+
798
+ // Delete target directory
799
+ let removeWarning = null;
800
+ if (targetDir) {
801
+ const removeResult = removePhaseFromDisk(path.join(phasesDir, targetDir));
802
+ if (!removeResult.removed) {
803
+ removeWarning = removeResult.error;
804
+ }
805
+ }
806
+
807
+ // Renumber subsequent phases using the appropriate strategy
808
+ let renamedDirs = [];
809
+ let renamedFiles = [];
810
+
811
+ let renameError = null;
812
+ if (isDecimal) {
813
+ // Decimal removal: renumber sibling decimals (e.g., removing 06.2 -> 06.3 becomes 06.2)
814
+ const baseParts = normalized.split('.');
815
+ const baseInt = baseParts[0];
816
+ const removedDecimal = parseInt(baseParts[1], 10);
817
+ const result = renumberDecimalPhases(phasesDir, baseInt, removedDecimal);
818
+ renamedDirs = result.renamedDirs;
819
+ renamedFiles = result.renamedFiles;
820
+ renameError = result.error || null;
821
+ } else {
822
+ // Integer removal: renumber all subsequent integer phases
823
+ const removedInt = parseInt(normalized, 10);
824
+ const result = renumberIntegerPhases(phasesDir, removedInt);
825
+ renamedDirs = result.renamedDirs;
826
+ renamedFiles = result.renamedFiles;
827
+ renameError = result.error || null;
828
+ }
829
+
830
+ // Update roadmap.md: remove section and renumber references
831
+ updateRoadmapAfterRemoval(cwd, targetPhase, isDecimal, normalized);
832
+
833
+ // Update state.md phase count
834
+ const stateUpdated = updateStateAfterPhaseRemoval(cwd);
835
+
836
+ const result = {
837
+ removed: targetPhase,
838
+ directory_deleted: targetDir || null,
839
+ renamed_directories: renamedDirs,
840
+ renamed_files: renamedFiles,
841
+ roadmap_updated: true,
842
+ state_updated: stateUpdated,
843
+ };
844
+ if (renameError) result.rename_warning = renameError;
845
+ if (removeWarning) result.remove_warning = removeWarning;
846
+
847
+ output(result, raw);
848
+ }
849
+
850
+ /**
851
+ * Decrement phase count in state.md after a phase is removed.
852
+ * @param {string} cwd - Working directory path
853
+ * @returns {boolean} true if state.md was updated
854
+ */
855
+ function updateStateAfterPhaseRemoval(cwd) {
856
+ const statePath = path.join(planningPath(cwd), STATE_FILE);
857
+ const content = readStateSafe(statePath);
858
+ if (content === null) return false;
859
+
860
+ let updated = content;
861
+ // Decrement "Total Phases" field
862
+ const totalPattern = /(\*\*Total Phases:\*\*\s*)(\d+)/;
863
+ const totalMatch = updated.match(totalPattern);
864
+ if (totalMatch) {
865
+ updated = updated.replace(totalPattern, `$1${parseInt(totalMatch[2], 10) - 1}`);
866
+ }
867
+ // Decrement "Phase: X of Y" pattern
868
+ const ofPattern = /(\bof\s+)(\d+)(\s*(?:\(|phases?))/i;
869
+ const ofMatch = updated.match(ofPattern);
870
+ if (ofMatch) {
871
+ updated = updated.replace(ofPattern, `$1${parseInt(ofMatch[2], 10) - 1}$3`);
872
+ }
873
+ writeStateMd(statePath, updated, cwd);
874
+ return true;
875
+ }
876
+
877
+ // ─── cmdPhaseComplete helpers ───────────────────────────────────────────────
878
+
879
+ /**
880
+ * Update roadmap.md and requirements.md to mark a phase as complete.
881
+ * Checks the phase checkbox, updates the progress table, sets the plan count,
882
+ * and marks any linked requirements as complete.
883
+ *
884
+ * @param {string} cwd - Working directory path
885
+ * @param {string} phaseNum - Phase number being completed
886
+ * @param {string} _phaseName - Human-readable phase name (reserved for future use)
887
+ * @param {number} planCount - Total number of plans in the phase
888
+ * @param {number} summaryCount - Number of completed summaries
889
+ */
890
+ function markPhaseCompleteInRoadmap(cwd, phaseNum, _phaseName, planCount, summaryCount) {
891
+ const roadmapPath = path.join(planningPath(cwd), ROADMAP_FILE);
892
+ const today = new Date().toISOString().split('T')[0];
893
+
894
+ let roadmapContent;
895
+ try {
896
+ roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
897
+ } catch {
898
+ return;
899
+ }
900
+
901
+ // Checkbox: - [ ] Phase N: -> - [x] Phase N: (...completed DATE)
902
+ const checkboxPattern = new RegExp(
903
+ `(-\\s*\\[)[ ](\\]\\s*.*Phase\\s+${escapeRegex(phaseNum)}[:\\s][^\\n]*)`,
904
+ 'i'
905
+ );
906
+ roadmapContent = roadmapContent.replace(checkboxPattern, `$1x$2 (completed ${today})`);
907
+
908
+ // Progress table: update Status to Complete, add date
909
+ const phaseEscaped = escapeRegex(phaseNum);
910
+ const tablePattern = new RegExp(
911
+ `(\\|\\s*${phaseEscaped}\\.?\\s[^|]*\\|[^|]*\\|)\\s*[^|]*(\\|)\\s*[^|]*(\\|)`,
912
+ 'i'
913
+ );
914
+ roadmapContent = roadmapContent.replace(
915
+ tablePattern,
916
+ `$1 Complete $2 ${today} $3`
917
+ );
918
+
919
+ // Update plan count in phase section
920
+ const planCountPattern = new RegExp(
921
+ `(#{2,4}\\s*Phase\\s+${phaseEscaped}[\\s\\S]*?\\*\\*Plans:\\*\\*\\s*)[^\\n]+`,
922
+ 'i'
923
+ );
924
+ roadmapContent = roadmapContent.replace(
925
+ planCountPattern,
926
+ `$1${summaryCount}/${planCount} plans complete`
927
+ );
928
+
929
+ try {
930
+ fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
931
+ } catch {
932
+ // Roadmap write is best-effort during phase completion
933
+ }
934
+
935
+ const reqResult = markRequirementsCompleteForPhase(cwd, phaseNum, roadmapContent);
936
+ return { requirements_warning: reqResult && reqResult.error ? reqResult.error : null };
937
+ }
938
+
939
+ /**
940
+ * Mark requirements as complete in requirements.md for a given phase.
941
+ * Reads the **Requirements:** field from the roadmap section, then updates
942
+ * checkboxes and traceability table rows in requirements.md.
943
+ * @param {string} cwd - Working directory path
944
+ * @param {string} phaseNum - Phase number being completed
945
+ * @param {string} roadmapContent - Current roadmap.md content (to extract req IDs)
946
+ */
947
+ function markRequirementsCompleteForPhase(cwd, phaseNum, roadmapContent) {
948
+ const reqPath = path.join(planningPath(cwd), REQUIREMENTS_FILE);
949
+ try {
950
+ const reqReadContent = fs.readFileSync(reqPath, 'utf-8');
951
+ const reqMatch = roadmapContent.match(
952
+ new RegExp(`Phase\\s+${escapeRegex(phaseNum)}[\\s\\S]*?\\*\\*Requirements:\\*\\*\\s*([^\\n]+)`, 'i')
953
+ );
954
+ if (!reqMatch) return;
955
+
956
+ const reqIds = reqMatch[1].replace(/[\[\]]/g, '').split(/[,\s]+/).map(id => id.trim()).filter(Boolean);
957
+ let reqContent = reqReadContent;
958
+
959
+ for (const reqId of reqIds) {
960
+ const reqEscaped = escapeRegex(reqId);
961
+ reqContent = reqContent.replace(
962
+ new RegExp(`(-\\s*\\[)[ ](\\]\\s*\\*\\*${reqEscaped}\\*\\*)`, 'gi'),
963
+ '$1x$2'
964
+ );
965
+ reqContent = reqContent.replace(
966
+ new RegExp(`(\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|)\\s*Pending\\s*(\\|)`, 'gi'),
967
+ '$1 Complete $2'
968
+ );
969
+ }
970
+
971
+ try {
972
+ fs.writeFileSync(reqPath, reqContent, 'utf-8');
973
+ } catch (e) {
974
+ return { updated: false, error: 'Failed to write requirements.md: ' + e.message };
975
+ }
976
+ return { updated: true };
977
+ } catch {
978
+ // requirements.md not found or unreadable — skip
979
+ return { updated: false };
980
+ }
981
+ }
982
+
983
+ /**
984
+ * Update state.md fields after marking a phase as complete.
985
+ * Advances to the next phase, updates status, resets plan counter.
986
+ *
987
+ * @param {string} cwd - Working directory path
988
+ * @param {string} phaseNum - Phase number just completed
989
+ * @param {number} _totalPhases - Total number of phases (reserved for future use)
990
+ * @param {string|null} nextPhaseNum - The next phase number, or null if last phase
991
+ * @param {string|null} nextPhaseName - The next phase name, or null
992
+ * @param {boolean} isLastPhase - Whether this was the last phase
993
+ */
994
+ function updateStateAfterPhaseComplete(cwd, { phaseNum, totalPhases: _totalPhases, nextPhaseNum, nextPhaseName, isLastPhase }) {
995
+ const statePath = path.join(planningPath(cwd), STATE_FILE);
996
+ const today = new Date().toISOString().split('T')[0];
997
+
998
+ let stateContent;
999
+ try {
1000
+ stateContent = fs.readFileSync(statePath, 'utf-8');
1001
+ } catch {
1002
+ return;
1003
+ }
1004
+
1005
+ // Update Current Phase
1006
+ stateContent = stateContent.replace(
1007
+ /(\*\*Current Phase:\*\*\s*).*/,
1008
+ `$1${nextPhaseNum || phaseNum}`
1009
+ );
1010
+
1011
+ // Update Current Phase Name
1012
+ if (nextPhaseName) {
1013
+ stateContent = stateContent.replace(
1014
+ /(\*\*Current Phase Name:\*\*\s*).*/,
1015
+ `$1${nextPhaseName.replace(/-/g, ' ')}`
1016
+ );
1017
+ }
1018
+
1019
+ // Update Status
1020
+ stateContent = stateContent.replace(
1021
+ /(\*\*Status:\*\*\s*).*/,
1022
+ `$1${isLastPhase ? 'Milestone complete' : 'Ready to plan'}`
1023
+ );
1024
+
1025
+ // Update Current Plan
1026
+ stateContent = stateContent.replace(
1027
+ /(\*\*Current Plan:\*\*\s*).*/,
1028
+ '$1Not started'
1029
+ );
1030
+
1031
+ // Update Last Activity
1032
+ stateContent = stateContent.replace(
1033
+ /(\*\*Last Activity:\*\*\s*).*/,
1034
+ `$1${today}`
1035
+ );
1036
+
1037
+ // Update Last Activity Description
1038
+ stateContent = stateContent.replace(
1039
+ /(\*\*Last Activity Description:\*\*\s*).*/,
1040
+ `$1Phase ${phaseNum} complete${nextPhaseNum ? `, transitioned to Phase ${nextPhaseNum}` : ''}`
1041
+ );
1042
+
1043
+ writeStateMd(statePath, stateContent, cwd);
1044
+ }
1045
+
1046
+ /**
1047
+ * Mark a phase complete, update ROADMAP checkboxes/tables, advance STATE to next phase.
1048
+ * @param {string} cwd - Working directory path
1049
+ * @param {string} phaseNum - Phase number to mark complete
1050
+ * @param {boolean} raw - If true, output raw value instead of JSON
1051
+ * @returns {void}
1052
+ */
1053
+ function cmdPhaseComplete(cwd, phaseNum, raw, opts) {
1054
+ if (!phaseNum) {
1055
+ error('phase number required for phase complete');
1056
+ }
1057
+
1058
+ const phasesDir = phasesPath(cwd);
1059
+ const normalized = normalizePhaseName(phaseNum);
1060
+ const today = new Date().toISOString().split('T')[0];
1061
+
1062
+ // Verify phase info
1063
+ const phaseInfo = findPhaseInternal(cwd, phaseNum);
1064
+ if (!phaseInfo) {
1065
+ error(`Phase ${phaseNum} not found`);
1066
+ }
1067
+
1068
+ const planCount = phaseInfo.plans.length;
1069
+ const summaryCount = phaseInfo.summaries.length;
1070
+
1071
+ // Update roadmap.md and requirements.md
1072
+ const roadmapResult = markPhaseCompleteInRoadmap(cwd, phaseNum, phaseInfo.phase_name, planCount, summaryCount);
1073
+
1074
+ // Find next phase
1075
+ let nextPhaseNum = null;
1076
+ let nextPhaseName = null;
1077
+ let isLastPhase = true;
1078
+
1079
+ try {
1080
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
1081
+ const dirs = entries.filter(entry => entry.isDirectory()).map(entry => entry.name).sort((left, right) => comparePhaseNum(left, right));
1082
+
1083
+ // Find the next phase directory after current by comparing phase numbers
1084
+ for (const dir of dirs) {
1085
+ const dirMatch = dir.match(PHASE_DIR_RE);
1086
+ if (dirMatch) {
1087
+ // comparePhaseNum > 0 means dirMatch[1] comes after phaseNum
1088
+ if (comparePhaseNum(dirMatch[1], phaseNum) > 0) {
1089
+ nextPhaseNum = dirMatch[1];
1090
+ nextPhaseName = dirMatch[2] || null;
1091
+ isLastPhase = false;
1092
+ break;
1093
+ }
1094
+ }
1095
+ }
1096
+ } catch {
1097
+ // Phases directory unreadable; assume this is the last phase
1098
+ }
1099
+
1100
+ // Update state.md
1101
+ updateStateAfterPhaseComplete(cwd, { phaseNum, totalPhases: 0, nextPhaseNum, nextPhaseName, isLastPhase });
1102
+
1103
+ const statePath = path.join(planningPath(cwd), STATE_FILE);
1104
+ const roadmapPath = path.join(planningPath(cwd), ROADMAP_FILE);
1105
+
1106
+ const result = {
1107
+ completed_phase: phaseNum,
1108
+ phase_name: phaseInfo.phase_name,
1109
+ plans_executed: `${summaryCount}/${planCount}`,
1110
+ next_phase: nextPhaseNum,
1111
+ next_phase_name: nextPhaseName,
1112
+ is_last_phase: isLastPhase,
1113
+ date: today,
1114
+ roadmap_updated: fileAccessible(roadmapPath),
1115
+ state_updated: fileAccessible(statePath),
1116
+ };
1117
+ if (roadmapResult && roadmapResult.requirements_warning) {
1118
+ result.requirements_warning = roadmapResult.requirements_warning;
1119
+ }
1120
+
1121
+ // Auto-commit .planning/ metadata unless --no-commit or not a git repo
1122
+ const noCommit = opts && opts.noCommit;
1123
+ if (!noCommit && isGitRepo(cwd)) {
1124
+ const commitMsg = `docs(${normalized}): complete phase — ${phaseInfo.phase_name}`;
1125
+ execGit(cwd, ['add', PLANNING_DIR + '/']);
1126
+ const commitResult = execGit(cwd, ['commit', '-m', commitMsg]);
1127
+ if (commitResult.exitCode === 0) {
1128
+ const hashResult = execGit(cwd, ['rev-parse', '--short', 'HEAD']);
1129
+ result.commit_hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
1130
+ }
1131
+ }
1132
+
1133
+ output(result, raw);
1134
+ }
1135
+
1136
+ /**
1137
+ * Classify a plan as MICRO, STANDARD, or FULL based on complexity.
1138
+ * @param {Object} frontmatter - Parsed plan.md frontmatter
1139
+ * @param {Object} [config] - Optional config with budget.micro_threshold_tasks/files
1140
+ * @returns {string} 'micro' | 'standard' | 'full'
1141
+ */
1142
+ function classifyPlanTier(frontmatter, config) {
1143
+ if (!frontmatter || typeof frontmatter !== 'object') {
1144
+ return 'standard';
1145
+ }
1146
+
1147
+ // Explicit tier in frontmatter always wins
1148
+ if (frontmatter.tier && ['micro', 'standard', 'full'].includes(frontmatter.tier)) {
1149
+ return frontmatter.tier;
1150
+ }
1151
+
1152
+ // autonomous=false forces FULL (handle both boolean and string from YAML)
1153
+ if (frontmatter.autonomous === false || frontmatter.autonomous === 'false') {
1154
+ return 'full';
1155
+ }
1156
+
1157
+ // Get thresholds from config or use defaults
1158
+ const thresholdTasks = (config && config.budget && config.budget.micro_threshold_tasks) || 3;
1159
+ const thresholdFiles = (config && config.budget && config.budget.micro_threshold_files) || 2;
1160
+
1161
+ // Count tasks — check task_count (number or numeric string) or fall back to tasks array
1162
+ let taskCount = null;
1163
+ if (frontmatter.task_count !== undefined && frontmatter.task_count !== null) {
1164
+ const parsed = Number(frontmatter.task_count);
1165
+ if (!isNaN(parsed)) taskCount = parsed;
1166
+ }
1167
+ if (taskCount === null && Array.isArray(frontmatter.tasks)) {
1168
+ taskCount = frontmatter.tasks.length;
1169
+ }
1170
+
1171
+ // Count files modified
1172
+ const filesCount = Array.isArray(frontmatter.files_modified)
1173
+ ? frontmatter.files_modified.length
1174
+ : 0;
1175
+
1176
+ // If we can't determine task count, default to STANDARD
1177
+ if (taskCount === null) {
1178
+ return 'standard';
1179
+ }
1180
+
1181
+ // MICRO: small task count AND small file count
1182
+ if (taskCount <= thresholdTasks && filesCount <= thresholdFiles) {
1183
+ return 'micro';
1184
+ }
1185
+
1186
+ // STANDARD: up to 8 tasks
1187
+ if (taskCount <= 8) {
1188
+ return 'standard';
1189
+ }
1190
+
1191
+ // FULL: everything else
1192
+ return 'full';
1193
+ }
1194
+
1195
+ module.exports = {
1196
+ cmdPhasesList,
1197
+ cmdPhaseNextDecimal,
1198
+ cmdFindPhase,
1199
+ cmdPhasePlanIndex,
1200
+ cmdPhaseAdd,
1201
+ cmdPhaseInsert,
1202
+ cmdPhaseRemove,
1203
+ cmdPhaseComplete,
1204
+ // Exported for testability (helpers)
1205
+ removePhaseFromDisk,
1206
+ renumberDecimalPhases,
1207
+ renumberIntegerPhases,
1208
+ updateRoadmapAfterRemoval,
1209
+ markPhaseCompleteInRoadmap,
1210
+ updateStateAfterPhaseComplete,
1211
+ classifyPlanTier,
1212
+ };