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