@luanpdd/kit-mcp 1.21.0 → 1.26.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/LICENSE +21 -21
  2. package/README.md +914 -648
  3. package/kit/COMANDOS.md +138 -138
  4. package/kit/README.md +76 -52
  5. package/kit/agents/advisor-researcher.md +106 -106
  6. package/kit/agents/assumptions-analyzer.md +107 -107
  7. package/kit/agents/audit-log-implementer.md +138 -0
  8. package/kit/agents/auditor-consistencia-isolamento.md +413 -0
  9. package/kit/agents/codebase-mapper.md +768 -768
  10. package/kit/agents/crm-pipeline-implementer.md +106 -0
  11. package/kit/agents/debugger.md +813 -772
  12. package/kit/agents/detector-tenant-quente.md +337 -0
  13. package/kit/agents/evolution-go-integrator.md +21 -0
  14. package/kit/agents/example-reviewer.md +21 -21
  15. package/kit/agents/executor.md +564 -523
  16. package/kit/agents/integration-checker.md +200 -200
  17. package/kit/agents/invite-flow-implementer.md +52 -0
  18. package/kit/agents/lgpd-compliance-auditor.md +89 -0
  19. package/kit/agents/multi-tenant-isolation-auditor.md +10 -0
  20. package/kit/agents/multi-tenant-rls-writer.md +78 -0
  21. package/kit/agents/nyquist-auditor.md +178 -178
  22. package/kit/agents/org-onboarding-implementer.md +21 -0
  23. package/kit/agents/phase-researcher.md +696 -696
  24. package/kit/agents/plan-checker.md +272 -272
  25. package/kit/agents/planner.md +922 -891
  26. package/kit/agents/project-researcher.md +652 -652
  27. package/kit/agents/research-synthesizer.md +245 -245
  28. package/kit/agents/roadmapper.md +677 -677
  29. package/kit/agents/supabase-architect.md +27 -0
  30. package/kit/agents/supabase-auth-bootstrapper.md +80 -0
  31. package/kit/agents/supabase-column-privileges-writer.md +399 -0
  32. package/kit/agents/supabase-migration-writer.md +141 -14
  33. package/kit/agents/supabase-rbac-implementer.md +392 -0
  34. package/kit/agents/supabase-rls-hardener.md +521 -0
  35. package/kit/agents/supabase-rls-writer.md +105 -9
  36. package/kit/agents/supabase-roles-implementer.md +355 -0
  37. package/kit/agents/super-admin-implementer.md +99 -0
  38. package/kit/agents/ui-auditor.md +437 -437
  39. package/kit/agents/ui-checker.md +302 -302
  40. package/kit/agents/ui-researcher.md +355 -355
  41. package/kit/agents/user-profiler.md +175 -175
  42. package/kit/agents/validador-evolucao-schema.md +335 -0
  43. package/kit/agents/verifier.md +728 -728
  44. package/kit/commands/adicionar-backlog.md +75 -75
  45. package/kit/commands/adicionar-fase.md +42 -42
  46. package/kit/commands/adicionar-tarefa.md +45 -45
  47. package/kit/commands/adicionar-testes.md +41 -41
  48. package/kit/commands/ajuda.md +21 -21
  49. package/kit/commands/atualizar.md +37 -37
  50. package/kit/commands/auditar-marco.md +179 -179
  51. package/kit/commands/auditar-uat.md +23 -23
  52. package/kit/commands/autonomo.md +40 -40
  53. package/kit/commands/branch-pr.md +24 -24
  54. package/kit/commands/concluir-marco.md +247 -247
  55. package/kit/commands/configuracoes.md +36 -36
  56. package/kit/commands/dados-distribuidos.md +188 -0
  57. package/kit/commands/definir-perfil.md +10 -10
  58. package/kit/commands/depurar.md +190 -190
  59. package/kit/commands/discutir-fase.md +131 -131
  60. package/kit/commands/entrar-discord.md +17 -17
  61. package/kit/commands/estatisticas.md +18 -18
  62. package/kit/commands/example-greeting.md +33 -33
  63. package/kit/commands/executar-fase.md +58 -58
  64. package/kit/commands/expresso.md +56 -56
  65. package/kit/commands/fase-ui.md +34 -34
  66. package/kit/commands/fazer.md +57 -57
  67. package/kit/commands/fio.md +125 -125
  68. package/kit/commands/fluxos-trabalho.md +64 -64
  69. package/kit/commands/forense.md +176 -176
  70. package/kit/commands/gerenciador.md +38 -38
  71. package/kit/commands/inserir-fase.md +31 -31
  72. package/kit/commands/limpeza.md +17 -17
  73. package/kit/commands/listar-hipoteses-fase.md +45 -45
  74. package/kit/commands/listar-workspaces.md +18 -18
  75. package/kit/commands/mapear-codebase.md +70 -70
  76. package/kit/commands/nota.md +33 -33
  77. package/kit/commands/novo-marco.md +43 -43
  78. package/kit/commands/novo-projeto.md +41 -41
  79. package/kit/commands/novo-workspace.md +43 -43
  80. package/kit/commands/pausar-trabalho.md +37 -37
  81. package/kit/commands/perfil-usuario.md +45 -45
  82. package/kit/commands/pesquisar-fase.md +195 -195
  83. package/kit/commands/planejar-fase.md +67 -67
  84. package/kit/commands/planejar-lacunas.md +33 -33
  85. package/kit/commands/plantar-ideia.md +25 -25
  86. package/kit/commands/progresso.md +24 -24
  87. package/kit/commands/proximo.md +30 -30
  88. package/kit/commands/publicar.md +490 -490
  89. package/kit/commands/rapido.md +35 -35
  90. package/kit/commands/reaplicar-patches.md +124 -124
  91. package/kit/commands/relatorio-sessao.md +19 -19
  92. package/kit/commands/remover-fase.md +31 -31
  93. package/kit/commands/remover-workspace.md +26 -26
  94. package/kit/commands/resumo-marco.md +50 -50
  95. package/kit/commands/retomar-trabalho.md +40 -40
  96. package/kit/commands/revisar-backlog.md +60 -60
  97. package/kit/commands/revisar-ui.md +32 -32
  98. package/kit/commands/revisar.md +37 -37
  99. package/kit/commands/saude.md +21 -21
  100. package/kit/commands/setup-notion.md +93 -93
  101. package/kit/commands/supabase.md +55 -8
  102. package/kit/commands/sync-main.md +68 -68
  103. package/kit/commands/validar-fase.md +35 -35
  104. package/kit/commands/verificar-tarefas.md +44 -44
  105. package/kit/commands/verificar-trabalho.md +64 -64
  106. package/kit/file-manifest.json +52 -32
  107. package/kit/framework/bin/lib/commands.cjs +959 -959
  108. package/kit/framework/bin/lib/config.cjs +442 -442
  109. package/kit/framework/bin/lib/core.cjs +1230 -1230
  110. package/kit/framework/bin/lib/frontmatter.cjs +336 -336
  111. package/kit/framework/bin/lib/init.cjs +1442 -1442
  112. package/kit/framework/bin/lib/milestone.cjs +252 -252
  113. package/kit/framework/bin/lib/model-profiles.cjs +68 -68
  114. package/kit/framework/bin/lib/phase.cjs +888 -888
  115. package/kit/framework/bin/lib/profile-output.cjs +952 -952
  116. package/kit/framework/bin/lib/profile-pipeline.cjs +539 -539
  117. package/kit/framework/bin/lib/roadmap.cjs +329 -329
  118. package/kit/framework/bin/lib/security.cjs +382 -382
  119. package/kit/framework/bin/lib/state.cjs +1031 -1031
  120. package/kit/framework/bin/lib/template.cjs +222 -222
  121. package/kit/framework/bin/lib/uat.cjs +282 -282
  122. package/kit/framework/bin/lib/verify.cjs +888 -888
  123. package/kit/framework/bin/lib/workstream.cjs +491 -491
  124. package/kit/framework/bin/tools.cjs +918 -918
  125. package/kit/framework/commands/workstreams.md +63 -63
  126. package/kit/framework/references/checkpoints.md +778 -778
  127. package/kit/framework/references/continuation-format.md +249 -249
  128. package/kit/framework/references/decimal-phase-calculation.md +64 -64
  129. package/kit/framework/references/git-integration.md +295 -295
  130. package/kit/framework/references/git-planning-commit.md +38 -38
  131. package/kit/framework/references/model-profile-resolution.md +36 -36
  132. package/kit/framework/references/model-profiles.md +139 -139
  133. package/kit/framework/references/phase-argument-parsing.md +61 -61
  134. package/kit/framework/references/planning-config.md +202 -202
  135. package/kit/framework/references/questioning.md +162 -162
  136. package/kit/framework/references/tdd.md +263 -263
  137. package/kit/framework/references/ui-brand.md +160 -160
  138. package/kit/framework/references/user-profiling.md +657 -657
  139. package/kit/framework/references/verification-patterns.md +612 -612
  140. package/kit/framework/references/workstream-flag.md +58 -58
  141. package/kit/framework/templates/DEBUG.md +164 -164
  142. package/kit/framework/templates/UAT.md +265 -265
  143. package/kit/framework/templates/UI-SPEC.md +100 -100
  144. package/kit/framework/templates/VALIDATION.md +76 -76
  145. package/kit/framework/templates/claude-md.md +122 -122
  146. package/kit/framework/templates/codebase/architecture.md +185 -185
  147. package/kit/framework/templates/codebase/concerns.md +205 -205
  148. package/kit/framework/templates/codebase/conventions.md +204 -204
  149. package/kit/framework/templates/codebase/integrations.md +192 -192
  150. package/kit/framework/templates/codebase/stack.md +158 -158
  151. package/kit/framework/templates/codebase/structure.md +199 -199
  152. package/kit/framework/templates/codebase/testing.md +301 -301
  153. package/kit/framework/templates/config.json +44 -44
  154. package/kit/framework/templates/context.md +352 -352
  155. package/kit/framework/templates/continue-here.md +78 -78
  156. package/kit/framework/templates/copilot-instructions.md +7 -7
  157. package/kit/framework/templates/debug-subagent-prompt.md +91 -91
  158. package/kit/framework/templates/dev-preferences.md +20 -20
  159. package/kit/framework/templates/discovery.md +146 -146
  160. package/kit/framework/templates/discussion-log.md +63 -63
  161. package/kit/framework/templates/milestone-archive.md +123 -123
  162. package/kit/framework/templates/milestone.md +115 -115
  163. package/kit/framework/templates/phase-prompt.md +610 -610
  164. package/kit/framework/templates/planner-subagent-prompt.md +117 -117
  165. package/kit/framework/templates/project.md +186 -186
  166. package/kit/framework/templates/requirements.md +231 -231
  167. package/kit/framework/templates/research-project/ARCHITECTURE.md +204 -204
  168. package/kit/framework/templates/research-project/FEATURES.md +147 -147
  169. package/kit/framework/templates/research-project/PITFALLS.md +200 -200
  170. package/kit/framework/templates/research-project/STACK.md +120 -120
  171. package/kit/framework/templates/research-project/SUMMARY.md +170 -170
  172. package/kit/framework/templates/research.md +419 -419
  173. package/kit/framework/templates/retrospective.md +54 -54
  174. package/kit/framework/templates/roadmap.md +202 -202
  175. package/kit/framework/templates/state.md +176 -176
  176. package/kit/framework/templates/summary-complex.md +59 -59
  177. package/kit/framework/templates/summary-minimal.md +41 -41
  178. package/kit/framework/templates/summary-standard.md +48 -48
  179. package/kit/framework/templates/summary.md +209 -209
  180. package/kit/framework/templates/user-profile.md +146 -146
  181. package/kit/framework/templates/user-setup.md +256 -256
  182. package/kit/framework/templates/verification-report.md +258 -258
  183. package/kit/framework/workflows/add-phase.md +112 -112
  184. package/kit/framework/workflows/add-tests.md +351 -351
  185. package/kit/framework/workflows/add-todo.md +158 -158
  186. package/kit/framework/workflows/audit-milestone.md +340 -340
  187. package/kit/framework/workflows/audit-uat.md +109 -109
  188. package/kit/framework/workflows/autonomous.md +891 -891
  189. package/kit/framework/workflows/check-todos.md +177 -177
  190. package/kit/framework/workflows/cleanup.md +152 -152
  191. package/kit/framework/workflows/complete-milestone.md +696 -696
  192. package/kit/framework/workflows/diagnose-issues.md +231 -231
  193. package/kit/framework/workflows/discovery-phase.md +289 -289
  194. package/kit/framework/workflows/discuss-phase-assumptions.md +653 -653
  195. package/kit/framework/workflows/discuss-phase.md +784 -784
  196. package/kit/framework/workflows/do.md +104 -104
  197. package/kit/framework/workflows/execute-phase.md +838 -838
  198. package/kit/framework/workflows/execute-plan.md +510 -510
  199. package/kit/framework/workflows/fast.md +102 -102
  200. package/kit/framework/workflows/forensics.md +265 -265
  201. package/kit/framework/workflows/health.md +181 -181
  202. package/kit/framework/workflows/help.md +619 -619
  203. package/kit/framework/workflows/insert-phase.md +130 -130
  204. package/kit/framework/workflows/list-phase-assumptions.md +178 -178
  205. package/kit/framework/workflows/list-workspaces.md +56 -56
  206. package/kit/framework/workflows/manager.md +362 -362
  207. package/kit/framework/workflows/map-codebase.md +377 -377
  208. package/kit/framework/workflows/milestone-summary.md +223 -223
  209. package/kit/framework/workflows/new-milestone.md +486 -486
  210. package/kit/framework/workflows/new-project.md +1159 -1159
  211. package/kit/framework/workflows/new-workspace.md +237 -237
  212. package/kit/framework/workflows/next.md +97 -97
  213. package/kit/framework/workflows/node-repair.md +92 -92
  214. package/kit/framework/workflows/note.md +156 -156
  215. package/kit/framework/workflows/pause-work.md +176 -176
  216. package/kit/framework/workflows/plan-milestone-gaps.md +273 -273
  217. package/kit/framework/workflows/plan-phase.md +765 -765
  218. package/kit/framework/workflows/plant-seed.md +169 -169
  219. package/kit/framework/workflows/pr-branch.md +129 -129
  220. package/kit/framework/workflows/profile-user.md +450 -450
  221. package/kit/framework/workflows/progress.md +507 -507
  222. package/kit/framework/workflows/quick.md +757 -757
  223. package/kit/framework/workflows/remove-phase.md +155 -155
  224. package/kit/framework/workflows/remove-workspace.md +90 -90
  225. package/kit/framework/workflows/research-phase.md +82 -82
  226. package/kit/framework/workflows/resume-project.md +326 -326
  227. package/kit/framework/workflows/review.md +228 -228
  228. package/kit/framework/workflows/session-report.md +146 -146
  229. package/kit/framework/workflows/settings.md +283 -283
  230. package/kit/framework/workflows/ship.md +228 -228
  231. package/kit/framework/workflows/stats.md +60 -60
  232. package/kit/framework/workflows/transition.md +671 -671
  233. package/kit/framework/workflows/ui-phase.md +302 -302
  234. package/kit/framework/workflows/ui-review.md +165 -165
  235. package/kit/framework/workflows/update.md +323 -323
  236. package/kit/framework/workflows/validate-phase.md +174 -174
  237. package/kit/framework/workflows/verify-phase.md +252 -252
  238. package/kit/framework/workflows/verify-work.md +637 -637
  239. package/kit/hooks/check-update.js +118 -118
  240. package/kit/hooks/context-monitor.js +163 -163
  241. package/kit/hooks/prompt-guard.js +103 -103
  242. package/kit/hooks/statusline.js +125 -125
  243. package/kit/hooks/workflow-guard.js +101 -101
  244. package/kit/settings.json +45 -45
  245. package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -0
  246. package/kit/skills/_shared-supabase/glossary.md +27 -0
  247. package/kit/skills/armadilhas-sistemas-distribuidos/SKILL.md +447 -0
  248. package/kit/skills/audit-log-multi-tenant/SKILL.md +6 -0
  249. package/kit/skills/cascading-failures/SKILL.md +4 -0
  250. package/kit/skills/consistencia-leitura-replica/SKILL.md +385 -0
  251. package/kit/skills/crm-lead-pipeline-patterns/SKILL.md +17 -0
  252. package/kit/skills/escolha-modelo-consistencia/SKILL.md +495 -0
  253. package/kit/skills/evolucao-schema-compativel/SKILL.md +448 -0
  254. package/kit/skills/example-skill/SKILL.md +42 -42
  255. package/kit/skills/multi-tenant-performance-scaling/SKILL.md +4 -0
  256. package/kit/skills/multi-tenant-rls-hierarchy/SKILL.md +4 -0
  257. package/kit/skills/postgres-isolamento-concorrencia/SKILL.md +552 -0
  258. package/kit/skills/rbac-permissions-matrix-supabase/SKILL.md +37 -0
  259. package/kit/skills/streams-eventos-cdc/SKILL.md +712 -0
  260. package/kit/skills/supabase-column-level-security/SKILL.md +426 -0
  261. package/kit/skills/supabase-cron-queues/SKILL.md +9 -0
  262. package/kit/skills/supabase-custom-claims-rbac/SKILL.md +472 -0
  263. package/kit/skills/supabase-database-functions/SKILL.md +85 -0
  264. package/kit/skills/supabase-migrations/SKILL.md +133 -11
  265. package/kit/skills/supabase-postgres-roles/SKILL.md +392 -0
  266. package/kit/skills/supabase-rls-defense-in-depth/SKILL.md +418 -0
  267. package/kit/skills/supabase-rls-policies/SKILL.md +462 -12
  268. package/kit/skills/super-admin-platform-pattern/SKILL.md +4 -0
  269. package/kit/skills/tenant-quente-mitigacao/SKILL.md +605 -0
  270. package/package.json +63 -63
  271. package/src/core/kit.js +216 -216
  272. package/src/core/reflect.js +247 -247
  273. package/src/core/reverse-sync.js +372 -372
  274. package/src/core/sync.js +418 -418
  275. package/src/core/watch.js +121 -121
@@ -1,959 +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 /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
- };
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 /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
+ };