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