gsd-code-first 1.0.0

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