gsd-code-first 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja-JP.md +834 -0
  3. package/README.ko-KR.md +823 -0
  4. package/README.md +937 -0
  5. package/README.pt-BR.md +452 -0
  6. package/README.zh-CN.md +800 -0
  7. package/agents/gsd-advisor-researcher.md +104 -0
  8. package/agents/gsd-annotator.md +148 -0
  9. package/agents/gsd-arc-executor.md +537 -0
  10. package/agents/gsd-arc-planner.md +374 -0
  11. package/agents/gsd-assumptions-analyzer.md +105 -0
  12. package/agents/gsd-code-planner.md +155 -0
  13. package/agents/gsd-codebase-mapper.md +770 -0
  14. package/agents/gsd-debugger.md +1373 -0
  15. package/agents/gsd-executor.md +509 -0
  16. package/agents/gsd-integration-checker.md +443 -0
  17. package/agents/gsd-nyquist-auditor.md +176 -0
  18. package/agents/gsd-phase-researcher.md +698 -0
  19. package/agents/gsd-plan-checker.md +773 -0
  20. package/agents/gsd-planner.md +1354 -0
  21. package/agents/gsd-project-researcher.md +654 -0
  22. package/agents/gsd-prototyper.md +161 -0
  23. package/agents/gsd-research-synthesizer.md +247 -0
  24. package/agents/gsd-roadmapper.md +679 -0
  25. package/agents/gsd-ui-auditor.md +439 -0
  26. package/agents/gsd-ui-checker.md +300 -0
  27. package/agents/gsd-ui-researcher.md +357 -0
  28. package/agents/gsd-user-profiler.md +171 -0
  29. package/agents/gsd-verifier.md +700 -0
  30. package/bin/install.js +5009 -0
  31. package/commands/gsd/add-backlog.md +76 -0
  32. package/commands/gsd/add-phase.md +43 -0
  33. package/commands/gsd/add-tests.md +41 -0
  34. package/commands/gsd/add-todo.md +47 -0
  35. package/commands/gsd/annotate.md +54 -0
  36. package/commands/gsd/audit-milestone.md +36 -0
  37. package/commands/gsd/audit-uat.md +24 -0
  38. package/commands/gsd/autonomous.md +41 -0
  39. package/commands/gsd/check-todos.md +45 -0
  40. package/commands/gsd/cleanup.md +18 -0
  41. package/commands/gsd/complete-milestone.md +136 -0
  42. package/commands/gsd/debug.md +173 -0
  43. package/commands/gsd/deep-plan.md +52 -0
  44. package/commands/gsd/discuss-phase.md +64 -0
  45. package/commands/gsd/do.md +30 -0
  46. package/commands/gsd/execute-phase.md +59 -0
  47. package/commands/gsd/extract-plan.md +35 -0
  48. package/commands/gsd/fast.md +30 -0
  49. package/commands/gsd/forensics.md +56 -0
  50. package/commands/gsd/health.md +22 -0
  51. package/commands/gsd/help.md +22 -0
  52. package/commands/gsd/insert-phase.md +32 -0
  53. package/commands/gsd/iterate.md +124 -0
  54. package/commands/gsd/join-discord.md +18 -0
  55. package/commands/gsd/list-phase-assumptions.md +46 -0
  56. package/commands/gsd/list-workspaces.md +19 -0
  57. package/commands/gsd/manager.md +39 -0
  58. package/commands/gsd/map-codebase.md +71 -0
  59. package/commands/gsd/milestone-summary.md +51 -0
  60. package/commands/gsd/new-milestone.md +44 -0
  61. package/commands/gsd/new-project.md +42 -0
  62. package/commands/gsd/new-workspace.md +44 -0
  63. package/commands/gsd/next.md +24 -0
  64. package/commands/gsd/note.md +34 -0
  65. package/commands/gsd/pause-work.md +38 -0
  66. package/commands/gsd/plan-milestone-gaps.md +34 -0
  67. package/commands/gsd/plan-phase.md +47 -0
  68. package/commands/gsd/plant-seed.md +28 -0
  69. package/commands/gsd/pr-branch.md +25 -0
  70. package/commands/gsd/profile-user.md +46 -0
  71. package/commands/gsd/progress.md +24 -0
  72. package/commands/gsd/prototype.md +56 -0
  73. package/commands/gsd/quick.md +47 -0
  74. package/commands/gsd/reapply-patches.md +123 -0
  75. package/commands/gsd/remove-phase.md +31 -0
  76. package/commands/gsd/remove-workspace.md +26 -0
  77. package/commands/gsd/research-phase.md +195 -0
  78. package/commands/gsd/resume-work.md +40 -0
  79. package/commands/gsd/review-backlog.md +61 -0
  80. package/commands/gsd/review.md +37 -0
  81. package/commands/gsd/session-report.md +19 -0
  82. package/commands/gsd/set-mode.md +41 -0
  83. package/commands/gsd/set-profile.md +12 -0
  84. package/commands/gsd/settings.md +36 -0
  85. package/commands/gsd/ship.md +23 -0
  86. package/commands/gsd/stats.md +18 -0
  87. package/commands/gsd/thread.md +127 -0
  88. package/commands/gsd/ui-phase.md +34 -0
  89. package/commands/gsd/ui-review.md +32 -0
  90. package/commands/gsd/update.md +37 -0
  91. package/commands/gsd/validate-phase.md +35 -0
  92. package/commands/gsd/verify-work.md +38 -0
  93. package/commands/gsd/workstreams.md +63 -0
  94. package/get-shit-done/bin/gsd-tools.cjs +946 -0
  95. package/get-shit-done/bin/lib/arc-scanner.cjs +341 -0
  96. package/get-shit-done/bin/lib/commands.cjs +959 -0
  97. package/get-shit-done/bin/lib/config.cjs +466 -0
  98. package/get-shit-done/bin/lib/core.cjs +1230 -0
  99. package/get-shit-done/bin/lib/frontmatter.cjs +336 -0
  100. package/get-shit-done/bin/lib/init.cjs +1442 -0
  101. package/get-shit-done/bin/lib/milestone.cjs +252 -0
  102. package/get-shit-done/bin/lib/model-profiles.cjs +68 -0
  103. package/get-shit-done/bin/lib/phase.cjs +888 -0
  104. package/get-shit-done/bin/lib/profile-output.cjs +952 -0
  105. package/get-shit-done/bin/lib/profile-pipeline.cjs +539 -0
  106. package/get-shit-done/bin/lib/roadmap.cjs +329 -0
  107. package/get-shit-done/bin/lib/security.cjs +382 -0
  108. package/get-shit-done/bin/lib/state.cjs +1031 -0
  109. package/get-shit-done/bin/lib/template.cjs +222 -0
  110. package/get-shit-done/bin/lib/uat.cjs +282 -0
  111. package/get-shit-done/bin/lib/verify.cjs +888 -0
  112. package/get-shit-done/bin/lib/workstream.cjs +491 -0
  113. package/get-shit-done/commands/gsd/workstreams.md +63 -0
  114. package/get-shit-done/references/arc-standard.md +315 -0
  115. package/get-shit-done/references/checkpoints.md +778 -0
  116. package/get-shit-done/references/continuation-format.md +249 -0
  117. package/get-shit-done/references/decimal-phase-calculation.md +64 -0
  118. package/get-shit-done/references/git-integration.md +295 -0
  119. package/get-shit-done/references/git-planning-commit.md +38 -0
  120. package/get-shit-done/references/model-profile-resolution.md +36 -0
  121. package/get-shit-done/references/model-profiles.md +139 -0
  122. package/get-shit-done/references/phase-argument-parsing.md +61 -0
  123. package/get-shit-done/references/planning-config.md +202 -0
  124. package/get-shit-done/references/questioning.md +162 -0
  125. package/get-shit-done/references/tdd.md +263 -0
  126. package/get-shit-done/references/ui-brand.md +160 -0
  127. package/get-shit-done/references/user-profiling.md +681 -0
  128. package/get-shit-done/references/verification-patterns.md +612 -0
  129. package/get-shit-done/references/workstream-flag.md +58 -0
  130. package/get-shit-done/templates/DEBUG.md +164 -0
  131. package/get-shit-done/templates/UAT.md +265 -0
  132. package/get-shit-done/templates/UI-SPEC.md +100 -0
  133. package/get-shit-done/templates/VALIDATION.md +76 -0
  134. package/get-shit-done/templates/claude-md.md +122 -0
  135. package/get-shit-done/templates/codebase/architecture.md +255 -0
  136. package/get-shit-done/templates/codebase/concerns.md +310 -0
  137. package/get-shit-done/templates/codebase/conventions.md +307 -0
  138. package/get-shit-done/templates/codebase/integrations.md +280 -0
  139. package/get-shit-done/templates/codebase/stack.md +186 -0
  140. package/get-shit-done/templates/codebase/structure.md +285 -0
  141. package/get-shit-done/templates/codebase/testing.md +480 -0
  142. package/get-shit-done/templates/config.json +44 -0
  143. package/get-shit-done/templates/context.md +352 -0
  144. package/get-shit-done/templates/continue-here.md +78 -0
  145. package/get-shit-done/templates/copilot-instructions.md +7 -0
  146. package/get-shit-done/templates/debug-subagent-prompt.md +91 -0
  147. package/get-shit-done/templates/dev-preferences.md +21 -0
  148. package/get-shit-done/templates/discovery.md +146 -0
  149. package/get-shit-done/templates/discussion-log.md +63 -0
  150. package/get-shit-done/templates/milestone-archive.md +123 -0
  151. package/get-shit-done/templates/milestone.md +115 -0
  152. package/get-shit-done/templates/phase-prompt.md +610 -0
  153. package/get-shit-done/templates/planner-subagent-prompt.md +117 -0
  154. package/get-shit-done/templates/project.md +186 -0
  155. package/get-shit-done/templates/requirements.md +231 -0
  156. package/get-shit-done/templates/research-project/ARCHITECTURE.md +204 -0
  157. package/get-shit-done/templates/research-project/FEATURES.md +147 -0
  158. package/get-shit-done/templates/research-project/PITFALLS.md +200 -0
  159. package/get-shit-done/templates/research-project/STACK.md +120 -0
  160. package/get-shit-done/templates/research-project/SUMMARY.md +170 -0
  161. package/get-shit-done/templates/research.md +552 -0
  162. package/get-shit-done/templates/retrospective.md +54 -0
  163. package/get-shit-done/templates/roadmap.md +202 -0
  164. package/get-shit-done/templates/state.md +176 -0
  165. package/get-shit-done/templates/summary-complex.md +59 -0
  166. package/get-shit-done/templates/summary-minimal.md +41 -0
  167. package/get-shit-done/templates/summary-standard.md +48 -0
  168. package/get-shit-done/templates/summary.md +248 -0
  169. package/get-shit-done/templates/user-profile.md +146 -0
  170. package/get-shit-done/templates/user-setup.md +311 -0
  171. package/get-shit-done/templates/verification-report.md +322 -0
  172. package/get-shit-done/workflows/add-phase.md +112 -0
  173. package/get-shit-done/workflows/add-tests.md +351 -0
  174. package/get-shit-done/workflows/add-todo.md +158 -0
  175. package/get-shit-done/workflows/audit-milestone.md +340 -0
  176. package/get-shit-done/workflows/audit-uat.md +109 -0
  177. package/get-shit-done/workflows/autonomous.md +891 -0
  178. package/get-shit-done/workflows/check-todos.md +177 -0
  179. package/get-shit-done/workflows/cleanup.md +152 -0
  180. package/get-shit-done/workflows/complete-milestone.md +767 -0
  181. package/get-shit-done/workflows/diagnose-issues.md +231 -0
  182. package/get-shit-done/workflows/discovery-phase.md +289 -0
  183. package/get-shit-done/workflows/discuss-phase-assumptions.md +653 -0
  184. package/get-shit-done/workflows/discuss-phase.md +1049 -0
  185. package/get-shit-done/workflows/do.md +104 -0
  186. package/get-shit-done/workflows/execute-phase.md +846 -0
  187. package/get-shit-done/workflows/execute-plan.md +514 -0
  188. package/get-shit-done/workflows/fast.md +105 -0
  189. package/get-shit-done/workflows/forensics.md +265 -0
  190. package/get-shit-done/workflows/health.md +181 -0
  191. package/get-shit-done/workflows/help.md +634 -0
  192. package/get-shit-done/workflows/insert-phase.md +130 -0
  193. package/get-shit-done/workflows/list-phase-assumptions.md +178 -0
  194. package/get-shit-done/workflows/list-workspaces.md +56 -0
  195. package/get-shit-done/workflows/manager.md +362 -0
  196. package/get-shit-done/workflows/map-codebase.md +377 -0
  197. package/get-shit-done/workflows/milestone-summary.md +223 -0
  198. package/get-shit-done/workflows/new-milestone.md +486 -0
  199. package/get-shit-done/workflows/new-project.md +1250 -0
  200. package/get-shit-done/workflows/new-workspace.md +237 -0
  201. package/get-shit-done/workflows/next.md +97 -0
  202. package/get-shit-done/workflows/node-repair.md +92 -0
  203. package/get-shit-done/workflows/note.md +156 -0
  204. package/get-shit-done/workflows/pause-work.md +176 -0
  205. package/get-shit-done/workflows/plan-milestone-gaps.md +273 -0
  206. package/get-shit-done/workflows/plan-phase.md +859 -0
  207. package/get-shit-done/workflows/plant-seed.md +169 -0
  208. package/get-shit-done/workflows/pr-branch.md +129 -0
  209. package/get-shit-done/workflows/profile-user.md +450 -0
  210. package/get-shit-done/workflows/progress.md +507 -0
  211. package/get-shit-done/workflows/quick.md +757 -0
  212. package/get-shit-done/workflows/remove-phase.md +155 -0
  213. package/get-shit-done/workflows/remove-workspace.md +90 -0
  214. package/get-shit-done/workflows/research-phase.md +82 -0
  215. package/get-shit-done/workflows/resume-project.md +326 -0
  216. package/get-shit-done/workflows/review.md +228 -0
  217. package/get-shit-done/workflows/session-report.md +146 -0
  218. package/get-shit-done/workflows/settings.md +283 -0
  219. package/get-shit-done/workflows/ship.md +228 -0
  220. package/get-shit-done/workflows/stats.md +60 -0
  221. package/get-shit-done/workflows/transition.md +671 -0
  222. package/get-shit-done/workflows/ui-phase.md +302 -0
  223. package/get-shit-done/workflows/ui-review.md +165 -0
  224. package/get-shit-done/workflows/update.md +323 -0
  225. package/get-shit-done/workflows/validate-phase.md +174 -0
  226. package/get-shit-done/workflows/verify-phase.md +254 -0
  227. package/get-shit-done/workflows/verify-work.md +637 -0
  228. package/hooks/dist/gsd-check-update.js +114 -0
  229. package/hooks/dist/gsd-context-monitor.js +156 -0
  230. package/hooks/dist/gsd-prompt-guard.js +96 -0
  231. package/hooks/dist/gsd-statusline.js +119 -0
  232. package/hooks/dist/gsd-workflow-guard.js +94 -0
  233. package/package.json +52 -0
  234. package/scripts/base64-scan.sh +262 -0
  235. package/scripts/build-hooks.js +82 -0
  236. package/scripts/prompt-injection-scan.sh +198 -0
  237. package/scripts/run-tests.cjs +29 -0
  238. package/scripts/secret-scan.sh +227 -0
@@ -0,0 +1,888 @@
1
+ /**
2
+ * Phase — Phase CRUD, query, and lifecycle operations
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { escapeRegex, loadConfig, normalizePhaseName, comparePhaseNum, findPhaseInternal, getArchivedPhaseDirs, generateSlugInternal, getMilestonePhaseFilter, stripShippedMilestones, extractCurrentMilestone, replaceInCurrentMilestone, toPosixPath, planningDir, output, error, readSubdirectories } = require('./core.cjs');
8
+ const { extractFrontmatter } = require('./frontmatter.cjs');
9
+ const { writeStateMd, stateExtractField, stateReplaceField, stateReplaceFieldWithFallback } = require('./state.cjs');
10
+
11
+ function cmdPhasesList(cwd, options, raw) {
12
+ const phasesDir = path.join(planningDir(cwd), '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(planningDir(cwd), '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(planningDir(cwd), '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(path.relative(cwd, planningDir(cwd)), '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(planningDir(cwd), '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, customId) {
312
+ if (!description) {
313
+ error('description required for phase add');
314
+ }
315
+
316
+ const config = loadConfig(cwd);
317
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
318
+ if (!fs.existsSync(roadmapPath)) {
319
+ error('ROADMAP.md not found');
320
+ }
321
+
322
+ const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
323
+ const content = extractCurrentMilestone(rawContent, cwd);
324
+ const slug = generateSlugInternal(description);
325
+
326
+ let newPhaseId;
327
+ let dirName;
328
+
329
+ if (customId || config.phase_naming === 'custom') {
330
+ // Custom phase naming: use provided ID or generate from description
331
+ newPhaseId = customId || slug.toUpperCase().replace(/-/g, '-');
332
+ if (!newPhaseId) error('--id required when phase_naming is "custom"');
333
+ dirName = `${newPhaseId}-${slug}`;
334
+ } else {
335
+ // Sequential mode: find highest integer phase number (in current milestone only)
336
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
337
+ let maxPhase = 0;
338
+ let m;
339
+ while ((m = phasePattern.exec(content)) !== null) {
340
+ const num = parseInt(m[1], 10);
341
+ if (num > maxPhase) maxPhase = num;
342
+ }
343
+
344
+ newPhaseId = maxPhase + 1;
345
+ const paddedNum = String(newPhaseId).padStart(2, '0');
346
+ dirName = `${paddedNum}-${slug}`;
347
+ }
348
+
349
+ const dirPath = path.join(planningDir(cwd), 'phases', dirName);
350
+
351
+ // Create directory with .gitkeep so git tracks empty folders
352
+ fs.mkdirSync(dirPath, { recursive: true });
353
+ fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
354
+
355
+ // Build phase entry
356
+ const dependsOn = config.phase_naming === 'custom' ? '' : `\n**Depends on:** Phase ${typeof newPhaseId === 'number' ? newPhaseId - 1 : 'TBD'}`;
357
+ const phaseEntry = `\n### Phase ${newPhaseId}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD${dependsOn}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /gsd:plan-phase ${newPhaseId} to break down)\n`;
358
+
359
+ // Find insertion point: before last "---" or at end
360
+ let updatedContent;
361
+ const lastSeparator = rawContent.lastIndexOf('\n---');
362
+ if (lastSeparator > 0) {
363
+ updatedContent = rawContent.slice(0, lastSeparator) + phaseEntry + rawContent.slice(lastSeparator);
364
+ } else {
365
+ updatedContent = rawContent + phaseEntry;
366
+ }
367
+
368
+ fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
369
+
370
+ const result = {
371
+ phase_number: typeof newPhaseId === 'number' ? newPhaseId : String(newPhaseId),
372
+ padded: typeof newPhaseId === 'number' ? String(newPhaseId).padStart(2, '0') : String(newPhaseId),
373
+ name: description,
374
+ slug,
375
+ directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', dirName)),
376
+ naming_mode: config.phase_naming,
377
+ };
378
+
379
+ output(result, raw, result.padded);
380
+ }
381
+
382
+ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
383
+ if (!afterPhase || !description) {
384
+ error('after-phase and description required for phase insert');
385
+ }
386
+
387
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
388
+ if (!fs.existsSync(roadmapPath)) {
389
+ error('ROADMAP.md not found');
390
+ }
391
+
392
+ const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
393
+ const content = extractCurrentMilestone(rawContent, cwd);
394
+ const slug = generateSlugInternal(description);
395
+
396
+ // Normalize input then strip leading zeros for flexible matching
397
+ const normalizedAfter = normalizePhaseName(afterPhase);
398
+ const unpadded = normalizedAfter.replace(/^0+/, '');
399
+ const afterPhaseEscaped = unpadded.replace(/\./g, '\\.');
400
+ const targetPattern = new RegExp(`#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:`, 'i');
401
+ if (!targetPattern.test(content)) {
402
+ error(`Phase ${afterPhase} not found in ROADMAP.md`);
403
+ }
404
+
405
+ // Calculate next decimal using existing logic
406
+ const phasesDir = path.join(planningDir(cwd), 'phases');
407
+ const normalizedBase = normalizePhaseName(afterPhase);
408
+ let existingDecimals = [];
409
+
410
+ try {
411
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
412
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
413
+ const decimalPattern = new RegExp(`^${normalizedBase}\\.(\\d+)`);
414
+ for (const dir of dirs) {
415
+ const dm = dir.match(decimalPattern);
416
+ if (dm) existingDecimals.push(parseInt(dm[1], 10));
417
+ }
418
+ } catch { /* intentionally empty */ }
419
+
420
+ const nextDecimal = existingDecimals.length === 0 ? 1 : Math.max(...existingDecimals) + 1;
421
+ const decimalPhase = `${normalizedBase}.${nextDecimal}`;
422
+ const dirName = `${decimalPhase}-${slug}`;
423
+ const dirPath = path.join(planningDir(cwd), 'phases', dirName);
424
+
425
+ // Create directory with .gitkeep so git tracks empty folders
426
+ fs.mkdirSync(dirPath, { recursive: true });
427
+ fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
428
+
429
+ // Build phase entry
430
+ 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`;
431
+
432
+ // Insert after the target phase section
433
+ const headerPattern = new RegExp(`(#{2,4}\\s*Phase\\s+0*${afterPhaseEscaped}:[^\\n]*\\n)`, 'i');
434
+ const headerMatch = rawContent.match(headerPattern);
435
+ if (!headerMatch) {
436
+ error(`Could not find Phase ${afterPhase} header`);
437
+ }
438
+
439
+ const headerIdx = rawContent.indexOf(headerMatch[0]);
440
+ const afterHeader = rawContent.slice(headerIdx + headerMatch[0].length);
441
+ const nextPhaseMatch = afterHeader.match(/\n#{2,4}\s+Phase\s+\d/i);
442
+
443
+ let insertIdx;
444
+ if (nextPhaseMatch) {
445
+ insertIdx = headerIdx + headerMatch[0].length + nextPhaseMatch.index;
446
+ } else {
447
+ insertIdx = rawContent.length;
448
+ }
449
+
450
+ const updatedContent = rawContent.slice(0, insertIdx) + phaseEntry + rawContent.slice(insertIdx);
451
+ fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
452
+
453
+ const result = {
454
+ phase_number: decimalPhase,
455
+ after_phase: afterPhase,
456
+ name: description,
457
+ slug,
458
+ directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', dirName)),
459
+ };
460
+
461
+ output(result, raw, decimalPhase);
462
+ }
463
+
464
+ /**
465
+ * Renumber sibling decimal phases after a decimal phase is removed.
466
+ * e.g. removing 06.2 → 06.3 becomes 06.2, 06.4 becomes 06.3, etc.
467
+ * Returns { renamedDirs, renamedFiles }.
468
+ */
469
+ function renameDecimalPhases(phasesDir, baseInt, removedDecimal) {
470
+ const renamedDirs = [], renamedFiles = [];
471
+ const decPattern = new RegExp(`^${baseInt}\\.(\\d+)-(.+)$`);
472
+ const dirs = readSubdirectories(phasesDir, true);
473
+ const toRename = dirs
474
+ .map(dir => { const m = dir.match(decPattern); return m ? { dir, oldDecimal: parseInt(m[1], 10), slug: m[2] } : null; })
475
+ .filter(item => item && item.oldDecimal > removedDecimal)
476
+ .sort((a, b) => b.oldDecimal - a.oldDecimal); // descending to avoid conflicts
477
+
478
+ for (const item of toRename) {
479
+ const newDecimal = item.oldDecimal - 1;
480
+ const oldPhaseId = `${baseInt}.${item.oldDecimal}`;
481
+ const newPhaseId = `${baseInt}.${newDecimal}`;
482
+ const newDirName = `${baseInt}.${newDecimal}-${item.slug}`;
483
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
484
+ renamedDirs.push({ from: item.dir, to: newDirName });
485
+ for (const f of fs.readdirSync(path.join(phasesDir, newDirName))) {
486
+ if (f.includes(oldPhaseId)) {
487
+ const newFileName = f.replace(oldPhaseId, newPhaseId);
488
+ fs.renameSync(path.join(phasesDir, newDirName, f), path.join(phasesDir, newDirName, newFileName));
489
+ renamedFiles.push({ from: f, to: newFileName });
490
+ }
491
+ }
492
+ }
493
+ return { renamedDirs, renamedFiles };
494
+ }
495
+
496
+ /**
497
+ * Renumber all integer phases after removedInt.
498
+ * e.g. removing phase 5 → phase 6 becomes 5, phase 7 becomes 6, etc.
499
+ * Returns { renamedDirs, renamedFiles }.
500
+ */
501
+ function renameIntegerPhases(phasesDir, removedInt) {
502
+ const renamedDirs = [], renamedFiles = [];
503
+ const dirs = readSubdirectories(phasesDir, true);
504
+ const toRename = dirs
505
+ .map(dir => {
506
+ const m = dir.match(/^(\d+)([A-Z])?(?:\.(\d+))?-(.+)$/i);
507
+ if (!m) return null;
508
+ const dirInt = parseInt(m[1], 10);
509
+ return dirInt > removedInt ? { dir, oldInt: dirInt, letter: m[2] ? m[2].toUpperCase() : '', decimal: m[3] ? parseInt(m[3], 10) : null, slug: m[4] } : null;
510
+ })
511
+ .filter(Boolean)
512
+ .sort((a, b) => a.oldInt !== b.oldInt ? b.oldInt - a.oldInt : (b.decimal || 0) - (a.decimal || 0));
513
+
514
+ for (const item of toRename) {
515
+ const newInt = item.oldInt - 1;
516
+ const newPadded = String(newInt).padStart(2, '0');
517
+ const oldPadded = String(item.oldInt).padStart(2, '0');
518
+ const letterSuffix = item.letter || '';
519
+ const decimalSuffix = item.decimal !== null ? `.${item.decimal}` : '';
520
+ const oldPrefix = `${oldPadded}${letterSuffix}${decimalSuffix}`;
521
+ const newPrefix = `${newPadded}${letterSuffix}${decimalSuffix}`;
522
+ const newDirName = `${newPrefix}-${item.slug}`;
523
+ fs.renameSync(path.join(phasesDir, item.dir), path.join(phasesDir, newDirName));
524
+ renamedDirs.push({ from: item.dir, to: newDirName });
525
+ for (const f of fs.readdirSync(path.join(phasesDir, newDirName))) {
526
+ if (f.startsWith(oldPrefix)) {
527
+ const newFileName = newPrefix + f.slice(oldPrefix.length);
528
+ fs.renameSync(path.join(phasesDir, newDirName, f), path.join(phasesDir, newDirName, newFileName));
529
+ renamedFiles.push({ from: f, to: newFileName });
530
+ }
531
+ }
532
+ }
533
+ return { renamedDirs, renamedFiles };
534
+ }
535
+
536
+ /**
537
+ * Remove a phase section from ROADMAP.md and renumber all subsequent integer phases.
538
+ */
539
+ function updateRoadmapAfterPhaseRemoval(roadmapPath, targetPhase, isDecimal, removedInt) {
540
+ let content = fs.readFileSync(roadmapPath, 'utf-8');
541
+ const escaped = escapeRegex(targetPhase);
542
+
543
+ content = content.replace(new RegExp(`\\n?#{2,4}\\s*Phase\\s+${escaped}\\s*:[\\s\\S]*?(?=\\n#{2,4}\\s+Phase\\s+\\d|$)`, 'i'), '');
544
+ content = content.replace(new RegExp(`\\n?-\\s*\\[[ x]\\]\\s*.*Phase\\s+${escaped}[:\\s][^\\n]*`, 'gi'), '');
545
+ content = content.replace(new RegExp(`\\n?\\|\\s*${escaped}\\.?\\s[^|]*\\|[^\\n]*`, 'gi'), '');
546
+
547
+ if (!isDecimal) {
548
+ const MAX_PHASE = 99;
549
+ for (let oldNum = MAX_PHASE; oldNum > removedInt; oldNum--) {
550
+ const newNum = oldNum - 1;
551
+ const oldStr = String(oldNum), newStr = String(newNum);
552
+ const oldPad = oldStr.padStart(2, '0'), newPad = newStr.padStart(2, '0');
553
+ content = content.replace(new RegExp(`(#{2,4}\\s*Phase\\s+)${oldStr}(\\s*:)`, 'gi'), `$1${newStr}$2`);
554
+ content = content.replace(new RegExp(`(Phase\\s+)${oldStr}([:\\s])`, 'g'), `$1${newStr}$2`);
555
+ content = content.replace(new RegExp(`${oldPad}-(\\d{2})`, 'g'), `${newPad}-$1`);
556
+ content = content.replace(new RegExp(`(\\|\\s*)${oldStr}\\.\\s`, 'g'), `$1${newStr}. `);
557
+ content = content.replace(new RegExp(`(Depends on:\\*\\*\\s*Phase\\s+)${oldStr}\\b`, 'gi'), `$1${newStr}`);
558
+ }
559
+ }
560
+
561
+ fs.writeFileSync(roadmapPath, content, 'utf-8');
562
+ }
563
+
564
+ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
565
+ if (!targetPhase) error('phase number required for phase remove');
566
+
567
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
568
+ const phasesDir = path.join(planningDir(cwd), 'phases');
569
+
570
+ if (!fs.existsSync(roadmapPath)) error('ROADMAP.md not found');
571
+
572
+ const normalized = normalizePhaseName(targetPhase);
573
+ const isDecimal = targetPhase.includes('.');
574
+ const force = options.force || false;
575
+
576
+ // Find target directory
577
+ const targetDir = readSubdirectories(phasesDir, true)
578
+ .find(d => d.startsWith(normalized + '-') || d === normalized) || null;
579
+
580
+ // Guard against removing executed work
581
+ if (targetDir && !force) {
582
+ const files = fs.readdirSync(path.join(phasesDir, targetDir));
583
+ const summaries = files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
584
+ if (summaries.length > 0) {
585
+ error(`Phase ${targetPhase} has ${summaries.length} executed plan(s). Use --force to remove anyway.`);
586
+ }
587
+ }
588
+
589
+ if (targetDir) fs.rmSync(path.join(phasesDir, targetDir), { recursive: true, force: true });
590
+
591
+ // Renumber subsequent phases on disk
592
+ let renamedDirs = [], renamedFiles = [];
593
+ try {
594
+ const renamed = isDecimal
595
+ ? renameDecimalPhases(phasesDir, normalized.split('.')[0], parseInt(normalized.split('.')[1], 10))
596
+ : renameIntegerPhases(phasesDir, parseInt(normalized, 10));
597
+ renamedDirs = renamed.renamedDirs;
598
+ renamedFiles = renamed.renamedFiles;
599
+ } catch { /* intentionally empty */ }
600
+
601
+ // Update ROADMAP.md
602
+ updateRoadmapAfterPhaseRemoval(roadmapPath, targetPhase, isDecimal, parseInt(normalized, 10));
603
+
604
+ // Update STATE.md phase count
605
+ const statePath = path.join(planningDir(cwd), 'STATE.md');
606
+ if (fs.existsSync(statePath)) {
607
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
608
+ const totalRaw = stateExtractField(stateContent, 'Total Phases');
609
+ if (totalRaw) {
610
+ stateContent = stateReplaceField(stateContent, 'Total Phases', String(parseInt(totalRaw, 10) - 1)) || stateContent;
611
+ }
612
+ const ofMatch = stateContent.match(/(\bof\s+)(\d+)(\s*(?:\(|phases?))/i);
613
+ if (ofMatch) {
614
+ stateContent = stateContent.replace(/(\bof\s+)(\d+)(\s*(?:\(|phases?))/i, `$1${parseInt(ofMatch[2], 10) - 1}$3`);
615
+ }
616
+ writeStateMd(statePath, stateContent, cwd);
617
+ }
618
+
619
+ output({
620
+ removed: targetPhase,
621
+ directory_deleted: targetDir,
622
+ renamed_directories: renamedDirs,
623
+ renamed_files: renamedFiles,
624
+ roadmap_updated: true,
625
+ state_updated: fs.existsSync(statePath),
626
+ }, raw);
627
+ }
628
+
629
+ function cmdPhaseComplete(cwd, phaseNum, raw) {
630
+ if (!phaseNum) {
631
+ error('phase number required for phase complete');
632
+ }
633
+
634
+ const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
635
+ const statePath = path.join(planningDir(cwd), 'STATE.md');
636
+ const phasesDir = path.join(planningDir(cwd), 'phases');
637
+ const normalized = normalizePhaseName(phaseNum);
638
+ const today = new Date().toISOString().split('T')[0];
639
+
640
+ // Verify phase info
641
+ const phaseInfo = findPhaseInternal(cwd, phaseNum);
642
+ if (!phaseInfo) {
643
+ error(`Phase ${phaseNum} not found`);
644
+ }
645
+
646
+ const planCount = phaseInfo.plans.length;
647
+ const summaryCount = phaseInfo.summaries.length;
648
+ let requirementsUpdated = false;
649
+
650
+ // Check for unresolved verification debt (non-blocking warnings)
651
+ const warnings = [];
652
+ try {
653
+ const phaseFullDir = path.join(cwd, phaseInfo.directory);
654
+ const phaseFiles = fs.readdirSync(phaseFullDir);
655
+
656
+ for (const file of phaseFiles.filter(f => f.includes('-UAT') && f.endsWith('.md'))) {
657
+ const content = fs.readFileSync(path.join(phaseFullDir, file), 'utf-8');
658
+ if (/result: pending/.test(content)) warnings.push(`${file}: has pending tests`);
659
+ if (/result: blocked/.test(content)) warnings.push(`${file}: has blocked tests`);
660
+ if (/status: partial/.test(content)) warnings.push(`${file}: testing incomplete (partial)`);
661
+ if (/status: diagnosed/.test(content)) warnings.push(`${file}: has diagnosed gaps`);
662
+ }
663
+
664
+ for (const file of phaseFiles.filter(f => f.includes('-VERIFICATION') && f.endsWith('.md'))) {
665
+ const content = fs.readFileSync(path.join(phaseFullDir, file), 'utf-8');
666
+ if (/status: human_needed/.test(content)) warnings.push(`${file}: needs human verification`);
667
+ if (/status: gaps_found/.test(content)) warnings.push(`${file}: has unresolved gaps`);
668
+ }
669
+ } catch {}
670
+
671
+ // Update ROADMAP.md: mark phase complete
672
+ if (fs.existsSync(roadmapPath)) {
673
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
674
+
675
+ // Checkbox: - [ ] Phase N: → - [x] Phase N: (...completed DATE)
676
+ const checkboxPattern = new RegExp(
677
+ `(-\\s*\\[)[ ](\\]\\s*.*Phase\\s+${escapeRegex(phaseNum)}[:\\s][^\\n]*)`,
678
+ 'i'
679
+ );
680
+ roadmapContent = replaceInCurrentMilestone(roadmapContent, checkboxPattern, `$1x$2 (completed ${today})`);
681
+
682
+ // Progress table: update Status to Complete, add date (handles 4 or 5 column tables)
683
+ const phaseEscaped = escapeRegex(phaseNum);
684
+ const tableRowPattern = new RegExp(
685
+ `^(\\|\\s*${phaseEscaped}\\.?\\s[^|]*(?:\\|[^\\n]*))$`,
686
+ 'im'
687
+ );
688
+ roadmapContent = roadmapContent.replace(tableRowPattern, (fullRow) => {
689
+ const cells = fullRow.split('|').slice(1, -1);
690
+ if (cells.length === 5) {
691
+ // 5-col: Phase | Milestone | Plans | Status | Completed
692
+ cells[3] = ' Complete ';
693
+ cells[4] = ` ${today} `;
694
+ } else if (cells.length === 4) {
695
+ // 4-col: Phase | Plans | Status | Completed
696
+ cells[2] = ' Complete ';
697
+ cells[3] = ` ${today} `;
698
+ }
699
+ return '|' + cells.join('|') + '|';
700
+ });
701
+
702
+ // Update plan count in phase section
703
+ const planCountPattern = new RegExp(
704
+ `(#{2,4}\\s*Phase\\s+${phaseEscaped}[\\s\\S]*?\\*\\*Plans:\\*\\*\\s*)[^\\n]+`,
705
+ 'i'
706
+ );
707
+ roadmapContent = replaceInCurrentMilestone(
708
+ roadmapContent, planCountPattern,
709
+ `$1${summaryCount}/${planCount} plans complete`
710
+ );
711
+
712
+ fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
713
+
714
+ // Update REQUIREMENTS.md traceability for this phase's requirements
715
+ const reqPath = path.join(planningDir(cwd), 'REQUIREMENTS.md');
716
+ if (fs.existsSync(reqPath)) {
717
+ // Extract the current phase section from roadmap (scoped to avoid cross-phase matching)
718
+ const phaseEsc = escapeRegex(phaseNum);
719
+ const currentMilestoneRoadmap = extractCurrentMilestone(roadmapContent, cwd);
720
+ const phaseSectionMatch = currentMilestoneRoadmap.match(
721
+ new RegExp(`(#{2,4}\\s*Phase\\s+${phaseEsc}[:\\s][\\s\\S]*?)(?=#{2,4}\\s*Phase\\s+|$)`, 'i')
722
+ );
723
+
724
+ const sectionText = phaseSectionMatch ? phaseSectionMatch[1] : '';
725
+ const reqMatch = sectionText.match(/\*\*Requirements:\*\*\s*([^\n]+)/i);
726
+
727
+ if (reqMatch) {
728
+ const reqIds = reqMatch[1].replace(/[\[\]]/g, '').split(/[,\s]+/).map(r => r.trim()).filter(Boolean);
729
+ let reqContent = fs.readFileSync(reqPath, 'utf-8');
730
+
731
+ for (const reqId of reqIds) {
732
+ const reqEscaped = escapeRegex(reqId);
733
+ // Update checkbox: - [ ] **REQ-ID** → - [x] **REQ-ID**
734
+ reqContent = reqContent.replace(
735
+ new RegExp(`(-\\s*\\[)[ ](\\]\\s*\\*\\*${reqEscaped}\\*\\*)`, 'gi'),
736
+ '$1x$2'
737
+ );
738
+ // Update traceability table: | REQ-ID | Phase N | Pending/In Progress | → | REQ-ID | Phase N | Complete |
739
+ reqContent = reqContent.replace(
740
+ new RegExp(`(\\|\\s*${reqEscaped}\\s*\\|[^|]+\\|)\\s*(?:Pending|In Progress)\\s*(\\|)`, 'gi'),
741
+ '$1 Complete $2'
742
+ );
743
+ }
744
+
745
+ fs.writeFileSync(reqPath, reqContent, 'utf-8');
746
+ requirementsUpdated = true;
747
+ }
748
+ }
749
+ }
750
+
751
+ // Find next phase — check both filesystem AND roadmap
752
+ // Phases may be defined in ROADMAP.md but not yet scaffolded to disk,
753
+ // so a filesystem-only scan would incorrectly report is_last_phase:true
754
+ let nextPhaseNum = null;
755
+ let nextPhaseName = null;
756
+ let isLastPhase = true;
757
+
758
+ try {
759
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
760
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
761
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name)
762
+ .filter(isDirInMilestone)
763
+ .sort((a, b) => comparePhaseNum(a, b));
764
+
765
+ // Find the next phase directory after current
766
+ for (const dir of dirs) {
767
+ const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
768
+ if (dm) {
769
+ if (comparePhaseNum(dm[1], phaseNum) > 0) {
770
+ nextPhaseNum = dm[1];
771
+ nextPhaseName = dm[2] || null;
772
+ isLastPhase = false;
773
+ break;
774
+ }
775
+ }
776
+ }
777
+ } catch { /* intentionally empty */ }
778
+
779
+ // Fallback: if filesystem found no next phase, check ROADMAP.md
780
+ // for phases that are defined but not yet planned (no directory on disk)
781
+ if (isLastPhase && fs.existsSync(roadmapPath)) {
782
+ try {
783
+ const roadmapForPhases = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
784
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
785
+ let pm;
786
+ while ((pm = phasePattern.exec(roadmapForPhases)) !== null) {
787
+ if (comparePhaseNum(pm[1], phaseNum) > 0) {
788
+ nextPhaseNum = pm[1];
789
+ nextPhaseName = pm[2].replace(/\(INSERTED\)/i, '').trim().toLowerCase().replace(/\s+/g, '-');
790
+ isLastPhase = false;
791
+ break;
792
+ }
793
+ }
794
+ } catch { /* intentionally empty */ }
795
+ }
796
+
797
+ // Update STATE.md — use shared helpers that handle both **bold:** and plain Field: formats
798
+ if (fs.existsSync(statePath)) {
799
+ let stateContent = fs.readFileSync(statePath, 'utf-8');
800
+
801
+ // Update Current Phase — preserve "X of Y (Name)" compound format
802
+ const phaseValue = nextPhaseNum || phaseNum;
803
+ const existingPhaseField = stateExtractField(stateContent, 'Current Phase')
804
+ || stateExtractField(stateContent, 'Phase');
805
+ let newPhaseValue = String(phaseValue);
806
+ if (existingPhaseField) {
807
+ const totalMatch = existingPhaseField.match(/of\s+(\d+)/);
808
+ const nameMatch = existingPhaseField.match(/\(([^)]+)\)/);
809
+ if (totalMatch) {
810
+ const total = totalMatch[1];
811
+ const nameStr = nextPhaseName ? ` (${nextPhaseName.replace(/-/g, ' ')})` : (nameMatch ? ` (${nameMatch[1]})` : '');
812
+ newPhaseValue = `${phaseValue} of ${total}${nameStr}`;
813
+ }
814
+ }
815
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Phase', 'Phase', newPhaseValue);
816
+
817
+ // Update Current Phase Name
818
+ if (nextPhaseName) {
819
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Phase Name', null, nextPhaseName.replace(/-/g, ' '));
820
+ }
821
+
822
+ // Update Status
823
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Status', null,
824
+ isLastPhase ? 'Milestone complete' : 'Ready to plan');
825
+
826
+ // Update Current Plan
827
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Plan', 'Plan', 'Not started');
828
+
829
+ // Update Last Activity
830
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity', 'Last activity', today);
831
+
832
+ // Update Last Activity Description
833
+ stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity Description', null,
834
+ `Phase ${phaseNum} complete${nextPhaseNum ? `, transitioned to Phase ${nextPhaseNum}` : ''}`);
835
+
836
+ // Increment Completed Phases counter (#956)
837
+ const completedRaw = stateExtractField(stateContent, 'Completed Phases');
838
+ if (completedRaw) {
839
+ const newCompleted = parseInt(completedRaw, 10) + 1;
840
+ stateContent = stateReplaceField(stateContent, 'Completed Phases', String(newCompleted)) || stateContent;
841
+
842
+ // Recalculate percent based on completed / total (#956)
843
+ const totalRaw = stateExtractField(stateContent, 'Total Phases');
844
+ if (totalRaw) {
845
+ const totalPhases = parseInt(totalRaw, 10);
846
+ if (totalPhases > 0) {
847
+ const newPercent = Math.round((newCompleted / totalPhases) * 100);
848
+ stateContent = stateReplaceField(stateContent, 'Progress', `${newPercent}%`) || stateContent;
849
+ // Also update percent field if it exists separately
850
+ stateContent = stateContent.replace(
851
+ /(percent:\s*)\d+/,
852
+ `$1${newPercent}`
853
+ );
854
+ }
855
+ }
856
+ }
857
+
858
+ writeStateMd(statePath, stateContent, cwd);
859
+ }
860
+
861
+ const result = {
862
+ completed_phase: phaseNum,
863
+ phase_name: phaseInfo.phase_name,
864
+ plans_executed: `${summaryCount}/${planCount}`,
865
+ next_phase: nextPhaseNum,
866
+ next_phase_name: nextPhaseName,
867
+ is_last_phase: isLastPhase,
868
+ date: today,
869
+ roadmap_updated: fs.existsSync(roadmapPath),
870
+ state_updated: fs.existsSync(statePath),
871
+ requirements_updated: requirementsUpdated,
872
+ warnings,
873
+ has_warnings: warnings.length > 0,
874
+ };
875
+
876
+ output(result, raw);
877
+ }
878
+
879
+ module.exports = {
880
+ cmdPhasesList,
881
+ cmdPhaseNextDecimal,
882
+ cmdFindPhase,
883
+ cmdPhasePlanIndex,
884
+ cmdPhaseAdd,
885
+ cmdPhaseInsert,
886
+ cmdPhaseRemove,
887
+ cmdPhaseComplete,
888
+ };