@ktpartners/dgs-platform 2.6.2

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