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,961 @@
1
+ /**
2
+ * Commands — Standalone utility commands
3
+ */
4
+ // @cap-feature(feature:F-011) Legacy GSD Modules — standalone utility commands (slug, timestamp, context, etc.)
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { execSync } = require('child_process');
9
+ const { safeReadFile, loadConfig, isGitIgnored, execGit, normalizePhaseName, comparePhaseNum, getArchivedPhaseDirs, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, resolveModelInternal, stripShippedMilestones, extractCurrentMilestone, planningDir, planningPaths, toPosixPath, output, error, findPhaseInternal, extractOneLinerFromBody, getRoadmapPhaseInternal } = require('./core.cjs');
10
+ const { extractFrontmatter } = require('./frontmatter.cjs');
11
+ const { MODEL_PROFILES } = require('./model-profiles.cjs');
12
+
13
+ function cmdGenerateSlug(text, raw) {
14
+ if (!text) {
15
+ error('text required for slug generation');
16
+ }
17
+
18
+ const slug = text
19
+ .toLowerCase()
20
+ .replace(/[^a-z0-9]+/g, '-')
21
+ .replace(/^-+|-+$/g, '');
22
+
23
+ const result = { slug };
24
+ output(result, raw, slug);
25
+ }
26
+
27
+ function cmdCurrentTimestamp(format, raw) {
28
+ const now = new Date();
29
+ let result;
30
+
31
+ switch (format) {
32
+ case 'date':
33
+ result = now.toISOString().split('T')[0];
34
+ break;
35
+ case 'filename':
36
+ result = now.toISOString().replace(/:/g, '-').replace(/\..+/, '');
37
+ break;
38
+ case 'full':
39
+ default:
40
+ result = now.toISOString();
41
+ break;
42
+ }
43
+
44
+ output({ timestamp: result }, raw, result);
45
+ }
46
+
47
+ function cmdListTodos(cwd, area, raw) {
48
+ const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
49
+
50
+ let count = 0;
51
+ const todos = [];
52
+
53
+ try {
54
+ const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
55
+
56
+ for (const file of files) {
57
+ try {
58
+ const content = fs.readFileSync(path.join(pendingDir, file), 'utf-8');
59
+ const createdMatch = content.match(/^created:\s*(.+)$/m);
60
+ const titleMatch = content.match(/^title:\s*(.+)$/m);
61
+ const areaMatch = content.match(/^area:\s*(.+)$/m);
62
+
63
+ const todoArea = areaMatch ? areaMatch[1].trim() : 'general';
64
+
65
+ // Apply area filter if specified
66
+ if (area && todoArea !== area) continue;
67
+
68
+ count++;
69
+ todos.push({
70
+ file,
71
+ created: createdMatch ? createdMatch[1].trim() : 'unknown',
72
+ title: titleMatch ? titleMatch[1].trim() : 'Untitled',
73
+ area: todoArea,
74
+ path: toPosixPath(path.relative(cwd, path.join(pendingDir, file))),
75
+ });
76
+ } catch { /* intentionally empty */ }
77
+ }
78
+ } catch { /* intentionally empty */ }
79
+
80
+ const result = { count, todos };
81
+ output(result, raw, count.toString());
82
+ }
83
+
84
+ function cmdVerifyPathExists(cwd, targetPath, raw) {
85
+ if (!targetPath) {
86
+ error('path required for verification');
87
+ }
88
+
89
+ // Reject null bytes and validate path does not contain traversal attempts
90
+ if (targetPath.includes('\0')) {
91
+ error('path contains null bytes');
92
+ }
93
+
94
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
95
+
96
+ try {
97
+ const stats = fs.statSync(fullPath);
98
+ const type = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : 'other';
99
+ const result = { exists: true, type };
100
+ output(result, raw, 'true');
101
+ } catch {
102
+ const result = { exists: false, type: null };
103
+ output(result, raw, 'false');
104
+ }
105
+ }
106
+
107
+ function cmdHistoryDigest(cwd, raw) {
108
+ const phasesDir = planningPaths(cwd).phases;
109
+ const digest = { phases: {}, decisions: [], tech_stack: new Set() };
110
+
111
+ // Collect all phase directories: archived + current
112
+ const allPhaseDirs = [];
113
+
114
+ // Add archived phases first (oldest milestones first)
115
+ const archived = getArchivedPhaseDirs(cwd);
116
+ for (const a of archived) {
117
+ allPhaseDirs.push({ name: a.name, fullPath: a.fullPath, milestone: a.milestone });
118
+ }
119
+
120
+ // Add current phases
121
+ if (fs.existsSync(phasesDir)) {
122
+ try {
123
+ const currentDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
124
+ .filter(e => e.isDirectory())
125
+ .map(e => e.name)
126
+ .sort();
127
+ for (const dir of currentDirs) {
128
+ allPhaseDirs.push({ name: dir, fullPath: path.join(phasesDir, dir), milestone: null });
129
+ }
130
+ } catch { /* intentionally empty */ }
131
+ }
132
+
133
+ if (allPhaseDirs.length === 0) {
134
+ digest.tech_stack = [];
135
+ output(digest, raw);
136
+ return;
137
+ }
138
+
139
+ try {
140
+ for (const { name: dir, fullPath: dirPath } of allPhaseDirs) {
141
+ const summaries = fs.readdirSync(dirPath).filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
142
+
143
+ for (const summary of summaries) {
144
+ try {
145
+ const content = fs.readFileSync(path.join(dirPath, summary), 'utf-8');
146
+ const fm = extractFrontmatter(content);
147
+
148
+ const phaseNum = fm.phase || dir.split('-')[0];
149
+
150
+ if (!digest.phases[phaseNum]) {
151
+ digest.phases[phaseNum] = {
152
+ name: fm.name || dir.split('-').slice(1).join(' ') || 'Unknown',
153
+ provides: new Set(),
154
+ affects: new Set(),
155
+ patterns: new Set(),
156
+ };
157
+ }
158
+
159
+ // Merge provides
160
+ if (fm['dependency-graph'] && fm['dependency-graph'].provides) {
161
+ fm['dependency-graph'].provides.forEach(p => digest.phases[phaseNum].provides.add(p));
162
+ } else if (fm.provides) {
163
+ fm.provides.forEach(p => digest.phases[phaseNum].provides.add(p));
164
+ }
165
+
166
+ // Merge affects
167
+ if (fm['dependency-graph'] && fm['dependency-graph'].affects) {
168
+ fm['dependency-graph'].affects.forEach(a => digest.phases[phaseNum].affects.add(a));
169
+ }
170
+
171
+ // Merge patterns
172
+ if (fm['patterns-established']) {
173
+ fm['patterns-established'].forEach(p => digest.phases[phaseNum].patterns.add(p));
174
+ }
175
+
176
+ // Merge decisions
177
+ if (fm['key-decisions']) {
178
+ fm['key-decisions'].forEach(d => {
179
+ digest.decisions.push({ phase: phaseNum, decision: d });
180
+ });
181
+ }
182
+
183
+ // Merge tech stack
184
+ if (fm['tech-stack'] && fm['tech-stack'].added) {
185
+ fm['tech-stack'].added.forEach(t => digest.tech_stack.add(typeof t === 'string' ? t : t.name));
186
+ }
187
+
188
+ } catch (e) {
189
+ // Skip malformed summaries
190
+ }
191
+ }
192
+ }
193
+
194
+ // Convert Sets to Arrays for JSON output
195
+ Object.keys(digest.phases).forEach(p => {
196
+ digest.phases[p].provides = [...digest.phases[p].provides];
197
+ digest.phases[p].affects = [...digest.phases[p].affects];
198
+ digest.phases[p].patterns = [...digest.phases[p].patterns];
199
+ });
200
+ digest.tech_stack = [...digest.tech_stack];
201
+
202
+ output(digest, raw);
203
+ } catch (e) {
204
+ error('Failed to generate history digest: ' + e.message);
205
+ }
206
+ }
207
+
208
+ function cmdResolveModel(cwd, agentType, raw) {
209
+ if (!agentType) {
210
+ error('agent-type required');
211
+ }
212
+
213
+ const config = loadConfig(cwd);
214
+ const profile = config.model_profile || 'balanced';
215
+ const model = resolveModelInternal(cwd, agentType);
216
+
217
+ const agentModels = MODEL_PROFILES[agentType];
218
+ const result = agentModels
219
+ ? { model, profile }
220
+ : { model, profile, unknown_agent: true };
221
+ output(result, raw, model);
222
+ }
223
+
224
+ function cmdCommit(cwd, message, files, raw, amend, noVerify) {
225
+ if (!message && !amend) {
226
+ error('commit message required');
227
+ }
228
+
229
+ // Sanitize commit message: strip invisible chars and injection markers
230
+ // that could hijack agent context when commit messages are read back
231
+ if (message) {
232
+ const { sanitizeForPrompt } = require('./security.cjs');
233
+ message = sanitizeForPrompt(message);
234
+ }
235
+
236
+ const config = loadConfig(cwd);
237
+
238
+ // Check commit_docs config
239
+ if (!config.commit_docs) {
240
+ const result = { committed: false, hash: null, reason: 'skipped_commit_docs_false' };
241
+ output(result, raw, 'skipped');
242
+ return;
243
+ }
244
+
245
+ // Check if .planning is gitignored
246
+ if (isGitIgnored(cwd, '.planning')) {
247
+ const result = { committed: false, hash: null, reason: 'skipped_gitignored' };
248
+ output(result, raw, 'skipped');
249
+ return;
250
+ }
251
+
252
+ // Ensure branching strategy branch exists before first commit (#1278).
253
+ // Pre-execution workflows (discuss, plan, research) commit artifacts but the branch
254
+ // was previously only created during execute-phase — too late.
255
+ if (config.branching_strategy && config.branching_strategy !== 'none') {
256
+ let branchName = null;
257
+ if (config.branching_strategy === 'phase') {
258
+ // Determine which phase we're committing for from the file paths
259
+ const phaseMatch = (files || []).join(' ').match(/(\d+)-/);
260
+ if (phaseMatch) {
261
+ const phaseNum = phaseMatch[1];
262
+ const phaseInfo = findPhaseInternal(cwd, phaseNum);
263
+ if (phaseInfo) {
264
+ branchName = config.phase_branch_template
265
+ .replace('{phase}', phaseInfo.phase_number)
266
+ .replace('{slug}', phaseInfo.phase_slug || 'phase');
267
+ }
268
+ }
269
+ } else if (config.branching_strategy === 'milestone') {
270
+ const milestone = getMilestoneInfo(cwd);
271
+ if (milestone && milestone.version) {
272
+ branchName = config.milestone_branch_template
273
+ .replace('{milestone}', milestone.version)
274
+ .replace('{slug}', generateSlugInternal(milestone.name) || 'milestone');
275
+ }
276
+ }
277
+ if (branchName) {
278
+ const currentBranch = execGit(cwd, ['rev-parse', '--abbrev-ref', 'HEAD']);
279
+ if (currentBranch.exitCode === 0 && currentBranch.stdout.trim() !== branchName) {
280
+ // Create branch if it doesn't exist, or switch to it if it does
281
+ const create = execGit(cwd, ['checkout', '-b', branchName]);
282
+ if (create.exitCode !== 0) {
283
+ execGit(cwd, ['checkout', branchName]);
284
+ }
285
+ }
286
+ }
287
+ }
288
+
289
+ // Stage files
290
+ const filesToStage = files && files.length > 0 ? files : ['.planning/'];
291
+ for (const file of filesToStage) {
292
+ const fullPath = path.join(cwd, file);
293
+ if (!fs.existsSync(fullPath)) {
294
+ // File was deleted/moved — stage the deletion
295
+ execGit(cwd, ['rm', '--cached', '--ignore-unmatch', file]);
296
+ } else {
297
+ execGit(cwd, ['add', file]);
298
+ }
299
+ }
300
+
301
+ // Commit (--no-verify skips pre-commit hooks, used by parallel executor agents)
302
+ const commitArgs = amend ? ['commit', '--amend', '--no-edit'] : ['commit', '-m', message];
303
+ if (noVerify) commitArgs.push('--no-verify');
304
+ const commitResult = execGit(cwd, commitArgs);
305
+ if (commitResult.exitCode !== 0) {
306
+ if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
307
+ const result = { committed: false, hash: null, reason: 'nothing_to_commit' };
308
+ output(result, raw, 'nothing');
309
+ return;
310
+ }
311
+ const result = { committed: false, hash: null, reason: 'nothing_to_commit', error: commitResult.stderr };
312
+ output(result, raw, 'nothing');
313
+ return;
314
+ }
315
+
316
+ // Get short hash
317
+ const hashResult = execGit(cwd, ['rev-parse', '--short', 'HEAD']);
318
+ const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
319
+ const result = { committed: true, hash, reason: 'committed' };
320
+ output(result, raw, hash || 'committed');
321
+ }
322
+
323
+ function cmdCommitToSubrepo(cwd, message, files, raw) {
324
+ if (!message) {
325
+ error('commit message required');
326
+ }
327
+
328
+ const config = loadConfig(cwd);
329
+ const subRepos = config.sub_repos;
330
+
331
+ if (!subRepos || subRepos.length === 0) {
332
+ error('no sub_repos configured in .planning/config.json');
333
+ }
334
+
335
+ if (!files || files.length === 0) {
336
+ error('--files required for commit-to-subrepo');
337
+ }
338
+
339
+ // Group files by sub-repo prefix
340
+ const grouped = {};
341
+ const unmatched = [];
342
+ for (const file of files) {
343
+ const match = subRepos.find(repo => file.startsWith(repo + '/'));
344
+ if (match) {
345
+ if (!grouped[match]) grouped[match] = [];
346
+ grouped[match].push(file);
347
+ } else {
348
+ unmatched.push(file);
349
+ }
350
+ }
351
+
352
+ if (unmatched.length > 0) {
353
+ process.stderr.write(`Warning: ${unmatched.length} file(s) did not match any sub-repo prefix: ${unmatched.join(', ')}\n`);
354
+ }
355
+
356
+ const repos = {};
357
+ for (const [repo, repoFiles] of Object.entries(grouped)) {
358
+ const repoCwd = path.join(cwd, repo);
359
+
360
+ // Stage files (strip sub-repo prefix for paths relative to that repo)
361
+ for (const file of repoFiles) {
362
+ const relativePath = file.slice(repo.length + 1);
363
+ execGit(repoCwd, ['add', relativePath]);
364
+ }
365
+
366
+ // Commit
367
+ const commitResult = execGit(repoCwd, ['commit', '-m', message]);
368
+ if (commitResult.exitCode !== 0) {
369
+ if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
370
+ repos[repo] = { committed: false, hash: null, files: repoFiles, reason: 'nothing_to_commit' };
371
+ continue;
372
+ }
373
+ repos[repo] = { committed: false, hash: null, files: repoFiles, reason: 'error', error: commitResult.stderr };
374
+ continue;
375
+ }
376
+
377
+ // Get hash
378
+ const hashResult = execGit(repoCwd, ['rev-parse', '--short', 'HEAD']);
379
+ const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
380
+ repos[repo] = { committed: true, hash, files: repoFiles };
381
+ }
382
+
383
+ const result = {
384
+ committed: Object.values(repos).some(r => r.committed),
385
+ repos,
386
+ unmatched: unmatched.length > 0 ? unmatched : undefined,
387
+ };
388
+ output(result, raw, Object.entries(repos).map(([r, v]) => `${r}:${v.hash || 'skip'}`).join(' '));
389
+ }
390
+
391
+ function cmdSummaryExtract(cwd, summaryPath, fields, raw) {
392
+ if (!summaryPath) {
393
+ error('summary-path required for summary-extract');
394
+ }
395
+
396
+ const fullPath = path.join(cwd, summaryPath);
397
+
398
+ if (!fs.existsSync(fullPath)) {
399
+ output({ error: 'File not found', path: summaryPath }, raw);
400
+ return;
401
+ }
402
+
403
+ const content = fs.readFileSync(fullPath, 'utf-8');
404
+ const fm = extractFrontmatter(content);
405
+
406
+ // Parse key-decisions into structured format
407
+ const parseDecisions = (decisionsList) => {
408
+ if (!decisionsList || !Array.isArray(decisionsList)) return [];
409
+ return decisionsList.map(d => {
410
+ const colonIdx = d.indexOf(':');
411
+ if (colonIdx > 0) {
412
+ return {
413
+ summary: d.substring(0, colonIdx).trim(),
414
+ rationale: d.substring(colonIdx + 1).trim(),
415
+ };
416
+ }
417
+ return { summary: d, rationale: null };
418
+ });
419
+ };
420
+
421
+ // Build full result
422
+ const fullResult = {
423
+ path: summaryPath,
424
+ one_liner: fm['one-liner'] || extractOneLinerFromBody(content) || null,
425
+ key_files: fm['key-files'] || [],
426
+ tech_added: (fm['tech-stack'] && fm['tech-stack'].added) || [],
427
+ patterns: fm['patterns-established'] || [],
428
+ decisions: parseDecisions(fm['key-decisions']),
429
+ requirements_completed: fm['requirements-completed'] || [],
430
+ };
431
+
432
+ // If fields specified, filter to only those fields
433
+ if (fields && fields.length > 0) {
434
+ const filtered = { path: summaryPath };
435
+ for (const field of fields) {
436
+ if (fullResult[field] !== undefined) {
437
+ filtered[field] = fullResult[field];
438
+ }
439
+ }
440
+ output(filtered, raw);
441
+ return;
442
+ }
443
+
444
+ output(fullResult, raw);
445
+ }
446
+
447
+ async function cmdWebsearch(query, options, raw) {
448
+ const apiKey = process.env.BRAVE_API_KEY;
449
+
450
+ if (!apiKey) {
451
+ // No key = silent skip, agent falls back to built-in WebSearch
452
+ output({ available: false, reason: 'BRAVE_API_KEY not set' }, raw, '');
453
+ return;
454
+ }
455
+
456
+ if (!query) {
457
+ output({ available: false, error: 'Query required' }, raw, '');
458
+ return;
459
+ }
460
+
461
+ const params = new URLSearchParams({
462
+ q: query,
463
+ count: String(options.limit || 10),
464
+ country: 'us',
465
+ search_lang: 'en',
466
+ text_decorations: 'false'
467
+ });
468
+
469
+ if (options.freshness) {
470
+ params.set('freshness', options.freshness);
471
+ }
472
+
473
+ try {
474
+ const response = await fetch(
475
+ `https://api.search.brave.com/res/v1/web/search?${params}`,
476
+ {
477
+ headers: {
478
+ 'Accept': 'application/json',
479
+ 'X-Subscription-Token': apiKey
480
+ }
481
+ }
482
+ );
483
+
484
+ if (!response.ok) {
485
+ output({ available: false, error: `API error: ${response.status}` }, raw, '');
486
+ return;
487
+ }
488
+
489
+ const data = await response.json();
490
+
491
+ const results = (data.web?.results || []).map(r => ({
492
+ title: r.title,
493
+ url: r.url,
494
+ description: r.description,
495
+ age: r.age || null
496
+ }));
497
+
498
+ output({
499
+ available: true,
500
+ query,
501
+ count: results.length,
502
+ results
503
+ }, raw, results.map(r => `${r.title}\n${r.url}\n${r.description}`).join('\n\n'));
504
+ } catch (err) {
505
+ output({ available: false, error: err.message }, raw, '');
506
+ }
507
+ }
508
+
509
+ function cmdProgressRender(cwd, format, raw) {
510
+ const phasesDir = planningPaths(cwd).phases;
511
+ const roadmapPath = planningPaths(cwd).roadmap;
512
+ const milestone = getMilestoneInfo(cwd);
513
+
514
+ const phases = [];
515
+ let totalPlans = 0;
516
+ let totalSummaries = 0;
517
+
518
+ try {
519
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
520
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
521
+
522
+ for (const dir of dirs) {
523
+ const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
524
+ const phaseNum = dm ? dm[1] : dir;
525
+ const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
526
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
527
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
528
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
529
+
530
+ totalPlans += plans;
531
+ totalSummaries += summaries;
532
+
533
+ let status;
534
+ if (plans === 0) status = 'Pending';
535
+ else if (summaries >= plans) status = 'Complete';
536
+ else if (summaries > 0) status = 'In Progress';
537
+ else status = 'Planned';
538
+
539
+ phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
540
+ }
541
+ } catch { /* intentionally empty */ }
542
+
543
+ const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
544
+
545
+ if (format === 'table') {
546
+ // Render markdown table
547
+ const barWidth = 10;
548
+ const filled = Math.round((percent / 100) * barWidth);
549
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
550
+ let out = `# ${milestone.version} ${milestone.name}\n\n`;
551
+ out += `**Progress:** [${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)\n\n`;
552
+ out += `| Phase | Name | Plans | Status |\n`;
553
+ out += `|-------|------|-------|--------|\n`;
554
+ for (const p of phases) {
555
+ out += `| ${p.number} | ${p.name} | ${p.summaries}/${p.plans} | ${p.status} |\n`;
556
+ }
557
+ output({ rendered: out }, raw, out);
558
+ } else if (format === 'bar') {
559
+ const barWidth = 20;
560
+ const filled = Math.round((percent / 100) * barWidth);
561
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
562
+ const text = `[${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)`;
563
+ output({ bar: text, percent, completed: totalSummaries, total: totalPlans }, raw, text);
564
+ } else {
565
+ // JSON format
566
+ output({
567
+ milestone_version: milestone.version,
568
+ milestone_name: milestone.name,
569
+ phases,
570
+ total_plans: totalPlans,
571
+ total_summaries: totalSummaries,
572
+ percent,
573
+ }, raw);
574
+ }
575
+ }
576
+
577
+ /**
578
+ * Match pending todos against a phase's goal/name/requirements.
579
+ * Returns todos with relevance scores based on keyword, area, and file overlap.
580
+ * Used by discuss-phase to surface relevant todos before scope-setting.
581
+ */
582
+ function cmdTodoMatchPhase(cwd, phase, raw) {
583
+ if (!phase) { error('phase required for todo match-phase'); }
584
+
585
+ const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
586
+ const todos = [];
587
+
588
+ // Load pending todos
589
+ try {
590
+ const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
591
+ for (const file of files) {
592
+ try {
593
+ const content = fs.readFileSync(path.join(pendingDir, file), 'utf-8');
594
+ const titleMatch = content.match(/^title:\s*(.+)$/m);
595
+ const areaMatch = content.match(/^area:\s*(.+)$/m);
596
+ const filesMatch = content.match(/^files:\s*(.+)$/m);
597
+ const body = content.replace(/^(title|area|files|created|priority):.*$/gm, '').trim();
598
+
599
+ todos.push({
600
+ file,
601
+ title: titleMatch ? titleMatch[1].trim() : 'Untitled',
602
+ area: areaMatch ? areaMatch[1].trim() : 'general',
603
+ files: filesMatch ? filesMatch[1].trim().split(/[,\s]+/).filter(Boolean) : [],
604
+ body: body.slice(0, 200), // first 200 chars for context
605
+ });
606
+ } catch {}
607
+ }
608
+ } catch {}
609
+
610
+ if (todos.length === 0) {
611
+ output({ phase, matches: [], todo_count: 0 }, raw);
612
+ return;
613
+ }
614
+
615
+ // Load phase goal/name from ROADMAP
616
+ const phaseInfo = getRoadmapPhaseInternal(cwd, phase);
617
+ const phaseName = phaseInfo ? (phaseInfo.phase_name || '') : '';
618
+ const phaseGoal = phaseInfo ? (phaseInfo.goal || '') : '';
619
+ const phaseSection = phaseInfo ? (phaseInfo.section || '') : '';
620
+
621
+ // Build keyword set from phase name + goal + section text
622
+ const phaseText = `${phaseName} ${phaseGoal} ${phaseSection}`.toLowerCase();
623
+ const stopWords = new Set(['the', 'and', 'for', 'with', 'from', 'that', 'this', 'will', 'are', 'was', 'has', 'have', 'been', 'not', 'but', 'all', 'can', 'into', 'each', 'when', 'any', 'use', 'new']);
624
+ const phaseKeywords = new Set(
625
+ phaseText.split(/[\s\-_/.,;:()\[\]{}|]+/)
626
+ .map(w => w.replace(/[^a-z0-9]/g, ''))
627
+ .filter(w => w.length > 2 && !stopWords.has(w))
628
+ );
629
+
630
+ // Find phase directory to get expected file paths
631
+ const phaseInfoDisk = findPhaseInternal(cwd, phase);
632
+ const phasePlans = [];
633
+ if (phaseInfoDisk && phaseInfoDisk.found) {
634
+ try {
635
+ const phaseDir = path.join(cwd, phaseInfoDisk.directory);
636
+ const planFiles = fs.readdirSync(phaseDir).filter(f => f.endsWith('-PLAN.md'));
637
+ for (const pf of planFiles) {
638
+ try {
639
+ const planContent = fs.readFileSync(path.join(phaseDir, pf), 'utf-8');
640
+ const fmFiles = planContent.match(/files_modified:\s*\[([^\]]*)\]/);
641
+ if (fmFiles) {
642
+ phasePlans.push(...fmFiles[1].split(',').map(s => s.trim().replace(/['"]/g, '')).filter(Boolean));
643
+ }
644
+ } catch {}
645
+ }
646
+ } catch {}
647
+ }
648
+
649
+ // Score each todo for relevance
650
+ const matches = [];
651
+ for (const todo of todos) {
652
+ let score = 0;
653
+ const reasons = [];
654
+
655
+ // Keyword match: todo title/body terms in phase text
656
+ const todoWords = `${todo.title} ${todo.body}`.toLowerCase()
657
+ .split(/[\s\-_/.,;:()\[\]{}|]+/)
658
+ .map(w => w.replace(/[^a-z0-9]/g, ''))
659
+ .filter(w => w.length > 2 && !stopWords.has(w));
660
+
661
+ const matchedKeywords = todoWords.filter(w => phaseKeywords.has(w));
662
+ if (matchedKeywords.length > 0) {
663
+ score += Math.min(matchedKeywords.length * 0.2, 0.6);
664
+ reasons.push(`keywords: ${[...new Set(matchedKeywords)].slice(0, 5).join(', ')}`);
665
+ }
666
+
667
+ // Area match: todo area appears in phase text
668
+ if (todo.area !== 'general' && phaseText.includes(todo.area.toLowerCase())) {
669
+ score += 0.3;
670
+ reasons.push(`area: ${todo.area}`);
671
+ }
672
+
673
+ // File match: todo files overlap with phase plan files
674
+ if (todo.files.length > 0 && phasePlans.length > 0) {
675
+ const fileOverlap = todo.files.filter(f =>
676
+ phasePlans.some(pf => pf.includes(f) || f.includes(pf))
677
+ );
678
+ if (fileOverlap.length > 0) {
679
+ score += 0.4;
680
+ reasons.push(`files: ${fileOverlap.slice(0, 3).join(', ')}`);
681
+ }
682
+ }
683
+
684
+ if (score > 0) {
685
+ matches.push({
686
+ file: todo.file,
687
+ title: todo.title,
688
+ area: todo.area,
689
+ score: Math.round(score * 100) / 100,
690
+ reasons,
691
+ });
692
+ }
693
+ }
694
+
695
+ // Sort by score descending
696
+ matches.sort((a, b) => b.score - a.score);
697
+
698
+ output({ phase, matches, todo_count: todos.length }, raw);
699
+ }
700
+
701
+ function cmdTodoComplete(cwd, filename, raw) {
702
+ if (!filename) {
703
+ error('filename required for todo complete');
704
+ }
705
+
706
+ const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
707
+ const completedDir = path.join(planningDir(cwd), 'todos', 'completed');
708
+ const sourcePath = path.join(pendingDir, filename);
709
+
710
+ if (!fs.existsSync(sourcePath)) {
711
+ error(`Todo not found: ${filename}`);
712
+ }
713
+
714
+ // Ensure completed directory exists
715
+ fs.mkdirSync(completedDir, { recursive: true });
716
+
717
+ // Read, add completion timestamp, move
718
+ let content = fs.readFileSync(sourcePath, 'utf-8');
719
+ const today = new Date().toISOString().split('T')[0];
720
+ content = `completed: ${today}\n` + content;
721
+
722
+ fs.writeFileSync(path.join(completedDir, filename), content, 'utf-8');
723
+ fs.unlinkSync(sourcePath);
724
+
725
+ output({ completed: true, file: filename, date: today }, raw, 'completed');
726
+ }
727
+
728
+ function cmdScaffold(cwd, type, options, raw) {
729
+ const { phase, name } = options;
730
+ const padded = phase ? normalizePhaseName(phase) : '00';
731
+ const today = new Date().toISOString().split('T')[0];
732
+
733
+ // Find phase directory
734
+ const phaseInfo = phase ? findPhaseInternal(cwd, phase) : null;
735
+ const phaseDir = phaseInfo ? path.join(cwd, phaseInfo.directory) : null;
736
+
737
+ if (phase && !phaseDir && type !== 'phase-dir') {
738
+ error(`Phase ${phase} directory not found`);
739
+ }
740
+
741
+ let filePath, content;
742
+
743
+ switch (type) {
744
+ case 'context': {
745
+ filePath = path.join(phaseDir, `${padded}-CONTEXT.md`);
746
+ content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — Context\n\n## Decisions\n\n_Decisions will be captured during /gsd:discuss-phase ${phase}_\n\n## Discretion Areas\n\n_Areas where the executor can use judgment_\n\n## Deferred Ideas\n\n_Ideas to consider later_\n`;
747
+ break;
748
+ }
749
+ case 'uat': {
750
+ filePath = path.join(phaseDir, `${padded}-UAT.md`);
751
+ content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — User Acceptance Testing\n\n## Test Results\n\n| # | Test | Status | Notes |\n|---|------|--------|-------|\n\n## Summary\n\n_Pending UAT_\n`;
752
+ break;
753
+ }
754
+ case 'verification': {
755
+ filePath = path.join(phaseDir, `${padded}-VERIFICATION.md`);
756
+ content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — Verification\n\n## Goal-Backward Verification\n\n**Phase Goal:** [From ROADMAP.md]\n\n## Checks\n\n| # | Requirement | Status | Evidence |\n|---|------------|--------|----------|\n\n## Result\n\n_Pending verification_\n`;
757
+ break;
758
+ }
759
+ case 'phase-dir': {
760
+ if (!phase || !name) {
761
+ error('phase and name required for phase-dir scaffold');
762
+ }
763
+ const slug = generateSlugInternal(name);
764
+ const dirName = `${padded}-${slug}`;
765
+ const phasesParent = planningPaths(cwd).phases;
766
+ fs.mkdirSync(phasesParent, { recursive: true });
767
+ const dirPath = path.join(phasesParent, dirName);
768
+ fs.mkdirSync(dirPath, { recursive: true });
769
+ output({ created: true, directory: toPosixPath(path.relative(cwd, dirPath)), path: dirPath }, raw, dirPath);
770
+ return;
771
+ }
772
+ default:
773
+ error(`Unknown scaffold type: ${type}. Available: context, uat, verification, phase-dir`);
774
+ }
775
+
776
+ if (fs.existsSync(filePath)) {
777
+ output({ created: false, reason: 'already_exists', path: filePath }, raw, 'exists');
778
+ return;
779
+ }
780
+
781
+ fs.writeFileSync(filePath, content, 'utf-8');
782
+ const relPath = toPosixPath(path.relative(cwd, filePath));
783
+ output({ created: true, path: relPath }, raw, relPath);
784
+ }
785
+
786
+ function cmdStats(cwd, format, raw) {
787
+ const phasesDir = planningPaths(cwd).phases;
788
+ const roadmapPath = planningPaths(cwd).roadmap;
789
+ const reqPath = planningPaths(cwd).requirements;
790
+ const statePath = planningPaths(cwd).state;
791
+ const milestone = getMilestoneInfo(cwd);
792
+ const isDirInMilestone = getMilestonePhaseFilter(cwd);
793
+
794
+ // Phase & plan stats (reuse progress pattern)
795
+ const phasesByNumber = new Map();
796
+ let totalPlans = 0;
797
+ let totalSummaries = 0;
798
+
799
+ try {
800
+ const roadmapContent = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
801
+ const headingPattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
802
+ let match;
803
+ while ((match = headingPattern.exec(roadmapContent)) !== null) {
804
+ phasesByNumber.set(match[1], {
805
+ number: match[1],
806
+ name: match[2].replace(/\(INSERTED\)/i, '').trim(),
807
+ plans: 0,
808
+ summaries: 0,
809
+ status: 'Not Started',
810
+ });
811
+ }
812
+ } catch { /* intentionally empty */ }
813
+
814
+ try {
815
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
816
+ const dirs = entries
817
+ .filter(e => e.isDirectory())
818
+ .map(e => e.name)
819
+ .filter(isDirInMilestone)
820
+ .sort((a, b) => comparePhaseNum(a, b));
821
+
822
+ for (const dir of dirs) {
823
+ const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
824
+ const phaseNum = dm ? dm[1] : dir;
825
+ const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
826
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
827
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
828
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
829
+
830
+ totalPlans += plans;
831
+ totalSummaries += summaries;
832
+
833
+ let status;
834
+ if (plans === 0) status = 'Not Started';
835
+ else if (summaries >= plans) status = 'Complete';
836
+ else if (summaries > 0) status = 'In Progress';
837
+ else status = 'Planned';
838
+
839
+ const existing = phasesByNumber.get(phaseNum);
840
+ phasesByNumber.set(phaseNum, {
841
+ number: phaseNum,
842
+ name: existing?.name || phaseName,
843
+ plans,
844
+ summaries,
845
+ status,
846
+ });
847
+ }
848
+ } catch { /* intentionally empty */ }
849
+
850
+ const phases = [...phasesByNumber.values()].sort((a, b) => comparePhaseNum(a.number, b.number));
851
+ const completedPhases = phases.filter(p => p.status === 'Complete').length;
852
+ const planPercent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
853
+ const percent = phases.length > 0 ? Math.min(100, Math.round((completedPhases / phases.length) * 100)) : 0;
854
+
855
+ // Requirements stats
856
+ let requirementsTotal = 0;
857
+ let requirementsComplete = 0;
858
+ try {
859
+ if (fs.existsSync(reqPath)) {
860
+ const reqContent = fs.readFileSync(reqPath, 'utf-8');
861
+ const checked = reqContent.match(/^- \[x\] \*\*/gm);
862
+ const unchecked = reqContent.match(/^- \[ \] \*\*/gm);
863
+ requirementsComplete = checked ? checked.length : 0;
864
+ requirementsTotal = requirementsComplete + (unchecked ? unchecked.length : 0);
865
+ }
866
+ } catch { /* intentionally empty */ }
867
+
868
+ // Last activity from STATE.md
869
+ let lastActivity = null;
870
+ try {
871
+ if (fs.existsSync(statePath)) {
872
+ const stateContent = fs.readFileSync(statePath, 'utf-8');
873
+ const activityMatch = stateContent.match(/^last_activity:\s*(.+)$/im)
874
+ || stateContent.match(/\*\*Last Activity:\*\*\s*(.+)/i)
875
+ || stateContent.match(/^Last Activity:\s*(.+)$/im)
876
+ || stateContent.match(/^Last activity:\s*(.+)$/im);
877
+ if (activityMatch) lastActivity = activityMatch[1].trim();
878
+ }
879
+ } catch { /* intentionally empty */ }
880
+
881
+ // Git stats
882
+ let gitCommits = 0;
883
+ let gitFirstCommitDate = null;
884
+ const commitCount = execGit(cwd, ['rev-list', '--count', 'HEAD']);
885
+ if (commitCount.exitCode === 0) {
886
+ gitCommits = parseInt(commitCount.stdout, 10) || 0;
887
+ }
888
+ const rootHash = execGit(cwd, ['rev-list', '--max-parents=0', 'HEAD']);
889
+ if (rootHash.exitCode === 0 && rootHash.stdout) {
890
+ const firstCommit = rootHash.stdout.split('\n')[0].trim();
891
+ const firstDate = execGit(cwd, ['show', '-s', '--format=%as', firstCommit]);
892
+ if (firstDate.exitCode === 0) {
893
+ gitFirstCommitDate = firstDate.stdout || null;
894
+ }
895
+ }
896
+
897
+ const result = {
898
+ milestone_version: milestone.version,
899
+ milestone_name: milestone.name,
900
+ phases,
901
+ phases_completed: completedPhases,
902
+ phases_total: phases.length,
903
+ total_plans: totalPlans,
904
+ total_summaries: totalSummaries,
905
+ percent,
906
+ plan_percent: planPercent,
907
+ requirements_total: requirementsTotal,
908
+ requirements_complete: requirementsComplete,
909
+ git_commits: gitCommits,
910
+ git_first_commit_date: gitFirstCommitDate,
911
+ last_activity: lastActivity,
912
+ };
913
+
914
+ if (format === 'table') {
915
+ const barWidth = 10;
916
+ const filled = Math.round((percent / 100) * barWidth);
917
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
918
+ let out = `# ${milestone.version} ${milestone.name} \u2014 Statistics\n\n`;
919
+ out += `**Progress:** [${bar}] ${completedPhases}/${phases.length} phases (${percent}%)\n`;
920
+ if (totalPlans > 0) {
921
+ out += `**Plans:** ${totalSummaries}/${totalPlans} complete (${planPercent}%)\n`;
922
+ }
923
+ out += `**Phases:** ${completedPhases}/${phases.length} complete\n`;
924
+ if (requirementsTotal > 0) {
925
+ out += `**Requirements:** ${requirementsComplete}/${requirementsTotal} complete\n`;
926
+ }
927
+ out += '\n';
928
+ out += `| Phase | Name | Plans | Completed | Status |\n`;
929
+ out += `|-------|------|-------|-----------|--------|\n`;
930
+ for (const p of phases) {
931
+ out += `| ${p.number} | ${p.name} | ${p.plans} | ${p.summaries} | ${p.status} |\n`;
932
+ }
933
+ if (gitCommits > 0) {
934
+ out += `\n**Git:** ${gitCommits} commits`;
935
+ if (gitFirstCommitDate) out += ` (since ${gitFirstCommitDate})`;
936
+ out += '\n';
937
+ }
938
+ if (lastActivity) out += `**Last activity:** ${lastActivity}\n`;
939
+ output({ rendered: out }, raw, out);
940
+ } else {
941
+ output(result, raw);
942
+ }
943
+ }
944
+
945
+ module.exports = {
946
+ cmdGenerateSlug,
947
+ cmdCurrentTimestamp,
948
+ cmdListTodos,
949
+ cmdVerifyPathExists,
950
+ cmdHistoryDigest,
951
+ cmdResolveModel,
952
+ cmdCommit,
953
+ cmdCommitToSubrepo,
954
+ cmdSummaryExtract,
955
+ cmdWebsearch,
956
+ cmdProgressRender,
957
+ cmdTodoComplete,
958
+ cmdTodoMatchPhase,
959
+ cmdScaffold,
960
+ cmdStats,
961
+ };