@howlil/ez-agents 2.0.0 → 2.0.1

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 (106) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +93 -93
  3. package/agents/ez-plan-checker.md +2 -2
  4. package/agents/ez-research-synthesizer.md +1 -1
  5. package/agents/ez-ui-researcher.md +1 -1
  6. package/agents/ez-verifier.md +1 -1
  7. package/bin/install.js +132 -132
  8. package/get-shit-done/bin/lib/assistant-adapter.cjs +205 -205
  9. package/get-shit-done/bin/lib/audit-exec.cjs +150 -150
  10. package/get-shit-done/bin/lib/auth.cjs +175 -175
  11. package/get-shit-done/bin/lib/circuit-breaker.cjs +118 -118
  12. package/get-shit-done/bin/lib/commands.cjs +666 -666
  13. package/get-shit-done/bin/lib/config.cjs +183 -183
  14. package/get-shit-done/bin/lib/core.cjs +495 -495
  15. package/get-shit-done/bin/lib/file-lock.cjs +236 -236
  16. package/get-shit-done/bin/lib/frontmatter.cjs +299 -299
  17. package/get-shit-done/bin/lib/fs-utils.cjs +153 -153
  18. package/get-shit-done/bin/lib/git-utils.cjs +203 -203
  19. package/get-shit-done/bin/lib/health-check.cjs +163 -163
  20. package/get-shit-done/bin/lib/index.cjs +113 -113
  21. package/get-shit-done/bin/lib/init.cjs +710 -710
  22. package/get-shit-done/bin/lib/logger.cjs +117 -117
  23. package/get-shit-done/bin/lib/milestone.cjs +241 -241
  24. package/get-shit-done/bin/lib/model-provider.cjs +146 -146
  25. package/get-shit-done/bin/lib/phase.cjs +908 -908
  26. package/get-shit-done/bin/lib/retry.cjs +119 -119
  27. package/get-shit-done/bin/lib/roadmap.cjs +305 -305
  28. package/get-shit-done/bin/lib/safe-exec.cjs +128 -128
  29. package/get-shit-done/bin/lib/safe-path.cjs +130 -130
  30. package/get-shit-done/bin/lib/state.cjs +721 -721
  31. package/get-shit-done/bin/lib/temp-file.cjs +239 -239
  32. package/get-shit-done/bin/lib/template.cjs +222 -222
  33. package/get-shit-done/bin/lib/test-file-lock.cjs +112 -112
  34. package/get-shit-done/bin/lib/test-graceful.cjs +93 -93
  35. package/get-shit-done/bin/lib/test-logger.cjs +60 -60
  36. package/get-shit-done/bin/lib/test-safe-exec.cjs +38 -38
  37. package/get-shit-done/bin/lib/test-safe-path.cjs +33 -33
  38. package/get-shit-done/bin/lib/test-temp-file.cjs +125 -125
  39. package/get-shit-done/bin/lib/timeout-exec.cjs +62 -62
  40. package/get-shit-done/bin/lib/verify.cjs +820 -820
  41. package/get-shit-done/references/checkpoints.md +776 -776
  42. package/get-shit-done/references/questioning.md +162 -162
  43. package/get-shit-done/references/tdd.md +263 -263
  44. package/get-shit-done/templates/codebase/concerns.md +310 -310
  45. package/get-shit-done/templates/codebase/conventions.md +307 -307
  46. package/get-shit-done/templates/codebase/integrations.md +280 -280
  47. package/get-shit-done/templates/codebase/stack.md +186 -186
  48. package/get-shit-done/templates/codebase/testing.md +480 -480
  49. package/get-shit-done/templates/config.json +37 -37
  50. package/get-shit-done/templates/continue-here.md +78 -78
  51. package/get-shit-done/templates/milestone-archive.md +123 -123
  52. package/get-shit-done/templates/milestone.md +115 -115
  53. package/get-shit-done/templates/requirements.md +231 -231
  54. package/get-shit-done/templates/research-project/ARCHITECTURE.md +204 -204
  55. package/get-shit-done/templates/research-project/FEATURES.md +147 -147
  56. package/get-shit-done/templates/research-project/PITFALLS.md +200 -200
  57. package/get-shit-done/templates/research-project/STACK.md +120 -120
  58. package/get-shit-done/templates/research-project/SUMMARY.md +170 -170
  59. package/get-shit-done/templates/retrospective.md +54 -54
  60. package/get-shit-done/templates/roadmap.md +202 -202
  61. package/get-shit-done/templates/summary-minimal.md +41 -41
  62. package/get-shit-done/templates/summary-standard.md +48 -48
  63. package/get-shit-done/templates/summary.md +248 -248
  64. package/get-shit-done/templates/user-setup.md +311 -311
  65. package/get-shit-done/templates/verification-report.md +322 -322
  66. package/get-shit-done/workflows/add-phase.md +112 -112
  67. package/get-shit-done/workflows/add-tests.md +351 -351
  68. package/get-shit-done/workflows/add-todo.md +158 -158
  69. package/get-shit-done/workflows/audit-milestone.md +332 -332
  70. package/get-shit-done/workflows/autonomous.md +743 -743
  71. package/get-shit-done/workflows/check-todos.md +177 -177
  72. package/get-shit-done/workflows/cleanup.md +152 -152
  73. package/get-shit-done/workflows/complete-milestone.md +766 -766
  74. package/get-shit-done/workflows/diagnose-issues.md +219 -219
  75. package/get-shit-done/workflows/discovery-phase.md +289 -289
  76. package/get-shit-done/workflows/discuss-phase.md +762 -762
  77. package/get-shit-done/workflows/execute-phase.md +468 -468
  78. package/get-shit-done/workflows/execute-plan.md +483 -483
  79. package/get-shit-done/workflows/health.md +159 -159
  80. package/get-shit-done/workflows/help.md +492 -492
  81. package/get-shit-done/workflows/insert-phase.md +130 -130
  82. package/get-shit-done/workflows/list-phase-assumptions.md +178 -178
  83. package/get-shit-done/workflows/map-codebase.md +316 -316
  84. package/get-shit-done/workflows/new-milestone.md +384 -384
  85. package/get-shit-done/workflows/new-project.md +1111 -1111
  86. package/get-shit-done/workflows/node-repair.md +92 -92
  87. package/get-shit-done/workflows/pause-work.md +122 -122
  88. package/get-shit-done/workflows/plan-milestone-gaps.md +274 -274
  89. package/get-shit-done/workflows/plan-phase.md +651 -651
  90. package/get-shit-done/workflows/progress.md +382 -382
  91. package/get-shit-done/workflows/quick.md +610 -610
  92. package/get-shit-done/workflows/remove-phase.md +155 -155
  93. package/get-shit-done/workflows/research-phase.md +74 -74
  94. package/get-shit-done/workflows/resume-project.md +307 -307
  95. package/get-shit-done/workflows/set-profile.md +81 -81
  96. package/get-shit-done/workflows/settings.md +242 -242
  97. package/get-shit-done/workflows/stats.md +57 -57
  98. package/get-shit-done/workflows/transition.md +544 -544
  99. package/get-shit-done/workflows/ui-phase.md +290 -290
  100. package/get-shit-done/workflows/ui-review.md +157 -157
  101. package/get-shit-done/workflows/update.md +320 -320
  102. package/get-shit-done/workflows/validate-phase.md +167 -167
  103. package/get-shit-done/workflows/verify-phase.md +243 -243
  104. package/package.json +1 -1
  105. package/scripts/build-hooks.js +43 -43
  106. package/scripts/run-tests.cjs +29 -29
@@ -1,666 +1,666 @@
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, resolveModelInternal, MODEL_PROFILES, toPosixPath, output, error, findPhaseInternal } = require('./core.cjs');
8
- const { extractFrontmatter } = require('./frontmatter.cjs');
9
-
10
- function cmdGenerateSlug(text, raw) {
11
- if (!text) {
12
- error('text required for slug generation');
13
- }
14
-
15
- const slug = text
16
- .toLowerCase()
17
- .replace(/[^a-z0-9]+/g, '-')
18
- .replace(/^-+|-+$/g, '');
19
-
20
- const result = { slug };
21
- output(result, raw, slug);
22
- }
23
-
24
- function cmdCurrentTimestamp(format, raw) {
25
- const now = new Date();
26
- let result;
27
-
28
- switch (format) {
29
- case 'date':
30
- result = now.toISOString().split('T')[0];
31
- break;
32
- case 'filename':
33
- result = now.toISOString().replace(/:/g, '-').replace(/\..+/, '');
34
- break;
35
- case 'full':
36
- default:
37
- result = now.toISOString();
38
- break;
39
- }
40
-
41
- output({ timestamp: result }, raw, result);
42
- }
43
-
44
- function cmdListTodos(cwd, area, raw) {
45
- const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
46
-
47
- let count = 0;
48
- const todos = [];
49
-
50
- try {
51
- const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
52
-
53
- for (const file of files) {
54
- try {
55
- const content = fs.readFileSync(path.join(pendingDir, file), 'utf-8');
56
- const createdMatch = content.match(/^created:\s*(.+)$/m);
57
- const titleMatch = content.match(/^title:\s*(.+)$/m);
58
- const areaMatch = content.match(/^area:\s*(.+)$/m);
59
-
60
- const todoArea = areaMatch ? areaMatch[1].trim() : 'general';
61
-
62
- // Apply area filter if specified
63
- if (area && todoArea !== area) continue;
64
-
65
- count++;
66
- todos.push({
67
- file,
68
- created: createdMatch ? createdMatch[1].trim() : 'unknown',
69
- title: titleMatch ? titleMatch[1].trim() : 'Untitled',
70
- area: todoArea,
71
- path: toPosixPath(path.join('.planning', 'todos', 'pending', file)),
72
- });
73
- } catch {}
74
- }
75
- } catch {}
76
-
77
- const result = { count, todos };
78
- output(result, raw, count.toString());
79
- }
80
-
81
- function cmdVerifyPathExists(cwd, targetPath, raw) {
82
- if (!targetPath) {
83
- error('path required for verification');
84
- }
85
-
86
- const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
87
-
88
- try {
89
- const stats = fs.statSync(fullPath);
90
- const type = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : 'other';
91
- const result = { exists: true, type };
92
- output(result, raw, 'true');
93
- } catch {
94
- const result = { exists: false, type: null };
95
- output(result, raw, 'false');
96
- }
97
- }
98
-
99
- function cmdHistoryDigest(cwd, raw) {
100
- const phasesDir = path.join(cwd, '.planning', 'phases');
101
- const digest = { phases: {}, decisions: [], tech_stack: new Set() };
102
-
103
- // Collect all phase directories: archived + current
104
- const allPhaseDirs = [];
105
-
106
- // Add archived phases first (oldest milestones first)
107
- const archived = getArchivedPhaseDirs(cwd);
108
- for (const a of archived) {
109
- allPhaseDirs.push({ name: a.name, fullPath: a.fullPath, milestone: a.milestone });
110
- }
111
-
112
- // Add current phases
113
- if (fs.existsSync(phasesDir)) {
114
- try {
115
- const currentDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
116
- .filter(e => e.isDirectory())
117
- .map(e => e.name)
118
- .sort();
119
- for (const dir of currentDirs) {
120
- allPhaseDirs.push({ name: dir, fullPath: path.join(phasesDir, dir), milestone: null });
121
- }
122
- } catch {}
123
- }
124
-
125
- if (allPhaseDirs.length === 0) {
126
- digest.tech_stack = [];
127
- output(digest, raw);
128
- return;
129
- }
130
-
131
- try {
132
- for (const { name: dir, fullPath: dirPath } of allPhaseDirs) {
133
- const summaries = fs.readdirSync(dirPath).filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
134
-
135
- for (const summary of summaries) {
136
- try {
137
- const content = fs.readFileSync(path.join(dirPath, summary), 'utf-8');
138
- const fm = extractFrontmatter(content);
139
-
140
- const phaseNum = fm.phase || dir.split('-')[0];
141
-
142
- if (!digest.phases[phaseNum]) {
143
- digest.phases[phaseNum] = {
144
- name: fm.name || dir.split('-').slice(1).join(' ') || 'Unknown',
145
- provides: new Set(),
146
- affects: new Set(),
147
- patterns: new Set(),
148
- };
149
- }
150
-
151
- // Merge provides
152
- if (fm['dependency-graph'] && fm['dependency-graph'].provides) {
153
- fm['dependency-graph'].provides.forEach(p => digest.phases[phaseNum].provides.add(p));
154
- } else if (fm.provides) {
155
- fm.provides.forEach(p => digest.phases[phaseNum].provides.add(p));
156
- }
157
-
158
- // Merge affects
159
- if (fm['dependency-graph'] && fm['dependency-graph'].affects) {
160
- fm['dependency-graph'].affects.forEach(a => digest.phases[phaseNum].affects.add(a));
161
- }
162
-
163
- // Merge patterns
164
- if (fm['patterns-established']) {
165
- fm['patterns-established'].forEach(p => digest.phases[phaseNum].patterns.add(p));
166
- }
167
-
168
- // Merge decisions
169
- if (fm['key-decisions']) {
170
- fm['key-decisions'].forEach(d => {
171
- digest.decisions.push({ phase: phaseNum, decision: d });
172
- });
173
- }
174
-
175
- // Merge tech stack
176
- if (fm['tech-stack'] && fm['tech-stack'].added) {
177
- fm['tech-stack'].added.forEach(t => digest.tech_stack.add(typeof t === 'string' ? t : t.name));
178
- }
179
-
180
- } catch (e) {
181
- // Skip malformed summaries
182
- }
183
- }
184
- }
185
-
186
- // Convert Sets to Arrays for JSON output
187
- Object.keys(digest.phases).forEach(p => {
188
- digest.phases[p].provides = [...digest.phases[p].provides];
189
- digest.phases[p].affects = [...digest.phases[p].affects];
190
- digest.phases[p].patterns = [...digest.phases[p].patterns];
191
- });
192
- digest.tech_stack = [...digest.tech_stack];
193
-
194
- output(digest, raw);
195
- } catch (e) {
196
- error('Failed to generate history digest: ' + e.message);
197
- }
198
- }
199
-
200
- function cmdResolveModel(cwd, agentType, raw) {
201
- if (!agentType) {
202
- error('agent-type required');
203
- }
204
-
205
- const config = loadConfig(cwd);
206
- const profile = config.model_profile || 'balanced';
207
- const model = resolveModelInternal(cwd, agentType);
208
-
209
- const agentModels = MODEL_PROFILES[agentType];
210
- const result = agentModels
211
- ? { model, profile }
212
- : { model, profile, unknown_agent: true };
213
- output(result, raw, model);
214
- }
215
-
216
- function cmdCommit(cwd, message, files, raw, amend) {
217
- if (!message && !amend) {
218
- error('commit message required');
219
- }
220
-
221
- const config = loadConfig(cwd);
222
-
223
- // Check commit_docs config
224
- if (!config.commit_docs) {
225
- const result = { committed: false, hash: null, reason: 'skipped_commit_docs_false' };
226
- output(result, raw, 'skipped');
227
- return;
228
- }
229
-
230
- // Check if .planning is gitignored
231
- if (isGitIgnored(cwd, '.planning')) {
232
- const result = { committed: false, hash: null, reason: 'skipped_gitignored' };
233
- output(result, raw, 'skipped');
234
- return;
235
- }
236
-
237
- // Stage files
238
- const filesToStage = files && files.length > 0 ? files : ['.planning/'];
239
- for (const file of filesToStage) {
240
- execGit(cwd, ['add', file]);
241
- }
242
-
243
- // Commit
244
- const commitArgs = amend ? ['commit', '--amend', '--no-edit'] : ['commit', '-m', message];
245
- const commitResult = execGit(cwd, commitArgs);
246
- if (commitResult.exitCode !== 0) {
247
- if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
248
- const result = { committed: false, hash: null, reason: 'nothing_to_commit' };
249
- output(result, raw, 'nothing');
250
- return;
251
- }
252
- const result = { committed: false, hash: null, reason: 'nothing_to_commit', error: commitResult.stderr };
253
- output(result, raw, 'nothing');
254
- return;
255
- }
256
-
257
- // Get short hash
258
- const hashResult = execGit(cwd, ['rev-parse', '--short', 'HEAD']);
259
- const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
260
- const result = { committed: true, hash, reason: 'committed' };
261
- output(result, raw, hash || 'committed');
262
- }
263
-
264
- function cmdSummaryExtract(cwd, summaryPath, fields, raw) {
265
- if (!summaryPath) {
266
- error('summary-path required for summary-extract');
267
- }
268
-
269
- const fullPath = path.join(cwd, summaryPath);
270
-
271
- if (!fs.existsSync(fullPath)) {
272
- output({ error: 'File not found', path: summaryPath }, raw);
273
- return;
274
- }
275
-
276
- const content = fs.readFileSync(fullPath, 'utf-8');
277
- const fm = extractFrontmatter(content);
278
-
279
- // Parse key-decisions into structured format
280
- const parseDecisions = (decisionsList) => {
281
- if (!decisionsList || !Array.isArray(decisionsList)) return [];
282
- return decisionsList.map(d => {
283
- const colonIdx = d.indexOf(':');
284
- if (colonIdx > 0) {
285
- return {
286
- summary: d.substring(0, colonIdx).trim(),
287
- rationale: d.substring(colonIdx + 1).trim(),
288
- };
289
- }
290
- return { summary: d, rationale: null };
291
- });
292
- };
293
-
294
- // Build full result
295
- const fullResult = {
296
- path: summaryPath,
297
- one_liner: fm['one-liner'] || null,
298
- key_files: fm['key-files'] || [],
299
- tech_added: (fm['tech-stack'] && fm['tech-stack'].added) || [],
300
- patterns: fm['patterns-established'] || [],
301
- decisions: parseDecisions(fm['key-decisions']),
302
- requirements_completed: fm['requirements-completed'] || [],
303
- };
304
-
305
- // If fields specified, filter to only those fields
306
- if (fields && fields.length > 0) {
307
- const filtered = { path: summaryPath };
308
- for (const field of fields) {
309
- if (fullResult[field] !== undefined) {
310
- filtered[field] = fullResult[field];
311
- }
312
- }
313
- output(filtered, raw);
314
- return;
315
- }
316
-
317
- output(fullResult, raw);
318
- }
319
-
320
- async function cmdWebsearch(query, options, raw) {
321
- const apiKey = process.env.BRAVE_API_KEY;
322
-
323
- if (!apiKey) {
324
- // No key = silent skip, agent falls back to built-in WebSearch
325
- output({ available: false, reason: 'BRAVE_API_KEY not set' }, raw, '');
326
- return;
327
- }
328
-
329
- if (!query) {
330
- output({ available: false, error: 'Query required' }, raw, '');
331
- return;
332
- }
333
-
334
- const params = new URLSearchParams({
335
- q: query,
336
- count: String(options.limit || 10),
337
- country: 'us',
338
- search_lang: 'en',
339
- text_decorations: 'false'
340
- });
341
-
342
- if (options.freshness) {
343
- params.set('freshness', options.freshness);
344
- }
345
-
346
- try {
347
- const response = await fetch(
348
- `https://api.search.brave.com/res/v1/web/search?${params}`,
349
- {
350
- headers: {
351
- 'Accept': 'application/json',
352
- 'X-Subscription-Token': apiKey
353
- }
354
- }
355
- );
356
-
357
- if (!response.ok) {
358
- output({ available: false, error: `API error: ${response.status}` }, raw, '');
359
- return;
360
- }
361
-
362
- const data = await response.json();
363
-
364
- const results = (data.web?.results || []).map(r => ({
365
- title: r.title,
366
- url: r.url,
367
- description: r.description,
368
- age: r.age || null
369
- }));
370
-
371
- output({
372
- available: true,
373
- query,
374
- count: results.length,
375
- results
376
- }, raw, results.map(r => `${r.title}\n${r.url}\n${r.description}`).join('\n\n'));
377
- } catch (err) {
378
- output({ available: false, error: err.message }, raw, '');
379
- }
380
- }
381
-
382
- function cmdProgressRender(cwd, format, raw) {
383
- const phasesDir = path.join(cwd, '.planning', 'phases');
384
- const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
385
- const milestone = getMilestoneInfo(cwd);
386
-
387
- const phases = [];
388
- let totalPlans = 0;
389
- let totalSummaries = 0;
390
-
391
- try {
392
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
393
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
394
-
395
- for (const dir of dirs) {
396
- const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
397
- const phaseNum = dm ? dm[1] : dir;
398
- const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
399
- const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
400
- const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
401
- const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
402
-
403
- totalPlans += plans;
404
- totalSummaries += summaries;
405
-
406
- let status;
407
- if (plans === 0) status = 'Pending';
408
- else if (summaries >= plans) status = 'Complete';
409
- else if (summaries > 0) status = 'In Progress';
410
- else status = 'Planned';
411
-
412
- phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
413
- }
414
- } catch {}
415
-
416
- const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
417
-
418
- if (format === 'table') {
419
- // Render markdown table
420
- const barWidth = 10;
421
- const filled = Math.round((percent / 100) * barWidth);
422
- const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
423
- let out = `# ${milestone.version} ${milestone.name}\n\n`;
424
- out += `**Progress:** [${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)\n\n`;
425
- out += `| Phase | Name | Plans | Status |\n`;
426
- out += `|-------|------|-------|--------|\n`;
427
- for (const p of phases) {
428
- out += `| ${p.number} | ${p.name} | ${p.summaries}/${p.plans} | ${p.status} |\n`;
429
- }
430
- output({ rendered: out }, raw, out);
431
- } else if (format === 'bar') {
432
- const barWidth = 20;
433
- const filled = Math.round((percent / 100) * barWidth);
434
- const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
435
- const text = `[${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)`;
436
- output({ bar: text, percent, completed: totalSummaries, total: totalPlans }, raw, text);
437
- } else {
438
- // JSON format
439
- output({
440
- milestone_version: milestone.version,
441
- milestone_name: milestone.name,
442
- phases,
443
- total_plans: totalPlans,
444
- total_summaries: totalSummaries,
445
- percent,
446
- }, raw);
447
- }
448
- }
449
-
450
- function cmdTodoComplete(cwd, filename, raw) {
451
- if (!filename) {
452
- error('filename required for todo complete');
453
- }
454
-
455
- const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
456
- const completedDir = path.join(cwd, '.planning', 'todos', 'completed');
457
- const sourcePath = path.join(pendingDir, filename);
458
-
459
- if (!fs.existsSync(sourcePath)) {
460
- error(`Todo not found: ${filename}`);
461
- }
462
-
463
- // Ensure completed directory exists
464
- fs.mkdirSync(completedDir, { recursive: true });
465
-
466
- // Read, add completion timestamp, move
467
- let content = fs.readFileSync(sourcePath, 'utf-8');
468
- const today = new Date().toISOString().split('T')[0];
469
- content = `completed: ${today}\n` + content;
470
-
471
- fs.writeFileSync(path.join(completedDir, filename), content, 'utf-8');
472
- fs.unlinkSync(sourcePath);
473
-
474
- output({ completed: true, file: filename, date: today }, raw, 'completed');
475
- }
476
-
477
- function cmdScaffold(cwd, type, options, raw) {
478
- const { phase, name } = options;
479
- const padded = phase ? normalizePhaseName(phase) : '00';
480
- const today = new Date().toISOString().split('T')[0];
481
-
482
- // Find phase directory
483
- const phaseInfo = phase ? findPhaseInternal(cwd, phase) : null;
484
- const phaseDir = phaseInfo ? path.join(cwd, phaseInfo.directory) : null;
485
-
486
- if (phase && !phaseDir && type !== 'phase-dir') {
487
- error(`Phase ${phase} directory not found`);
488
- }
489
-
490
- let filePath, content;
491
-
492
- switch (type) {
493
- case 'context': {
494
- filePath = path.join(phaseDir, `${padded}-CONTEXT.md`);
495
- 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`;
496
- break;
497
- }
498
- case 'uat': {
499
- filePath = path.join(phaseDir, `${padded}-UAT.md`);
500
- 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`;
501
- break;
502
- }
503
- case 'verification': {
504
- filePath = path.join(phaseDir, `${padded}-VERIFICATION.md`);
505
- 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`;
506
- break;
507
- }
508
- case 'phase-dir': {
509
- if (!phase || !name) {
510
- error('phase and name required for phase-dir scaffold');
511
- }
512
- const slug = generateSlugInternal(name);
513
- const dirName = `${padded}-${slug}`;
514
- const phasesParent = path.join(cwd, '.planning', 'phases');
515
- fs.mkdirSync(phasesParent, { recursive: true });
516
- const dirPath = path.join(phasesParent, dirName);
517
- fs.mkdirSync(dirPath, { recursive: true });
518
- output({ created: true, directory: `.planning/phases/${dirName}`, path: dirPath }, raw, dirPath);
519
- return;
520
- }
521
- default:
522
- error(`Unknown scaffold type: ${type}. Available: context, uat, verification, phase-dir`);
523
- }
524
-
525
- if (fs.existsSync(filePath)) {
526
- output({ created: false, reason: 'already_exists', path: filePath }, raw, 'exists');
527
- return;
528
- }
529
-
530
- fs.writeFileSync(filePath, content, 'utf-8');
531
- const relPath = toPosixPath(path.relative(cwd, filePath));
532
- output({ created: true, path: relPath }, raw, relPath);
533
- }
534
-
535
- function cmdStats(cwd, format, raw) {
536
- const phasesDir = path.join(cwd, '.planning', 'phases');
537
- const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
538
- const statePath = path.join(cwd, '.planning', 'STATE.md');
539
- const milestone = getMilestoneInfo(cwd);
540
-
541
- // Phase & plan stats (reuse progress pattern)
542
- const phases = [];
543
- let totalPlans = 0;
544
- let totalSummaries = 0;
545
-
546
- try {
547
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
548
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
549
-
550
- for (const dir of dirs) {
551
- const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
552
- const phaseNum = dm ? dm[1] : dir;
553
- const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
554
- const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
555
- const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
556
- const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
557
-
558
- totalPlans += plans;
559
- totalSummaries += summaries;
560
-
561
- let status;
562
- if (plans === 0) status = 'Pending';
563
- else if (summaries >= plans) status = 'Complete';
564
- else if (summaries > 0) status = 'In Progress';
565
- else status = 'Planned';
566
-
567
- phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
568
- }
569
- } catch {}
570
-
571
- const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
572
-
573
- // Requirements stats
574
- let requirementsTotal = 0;
575
- let requirementsComplete = 0;
576
- try {
577
- if (fs.existsSync(reqPath)) {
578
- const reqContent = fs.readFileSync(reqPath, 'utf-8');
579
- const checked = reqContent.match(/^- \[x\] \*\*/gm);
580
- const unchecked = reqContent.match(/^- \[ \] \*\*/gm);
581
- requirementsComplete = checked ? checked.length : 0;
582
- requirementsTotal = requirementsComplete + (unchecked ? unchecked.length : 0);
583
- }
584
- } catch {}
585
-
586
- // Last activity from STATE.md
587
- let lastActivity = null;
588
- try {
589
- if (fs.existsSync(statePath)) {
590
- const stateContent = fs.readFileSync(statePath, 'utf-8');
591
- const activityMatch = stateContent.match(/\*\*Last Activity:\*\*\s*(.+)/);
592
- if (activityMatch) lastActivity = activityMatch[1].trim();
593
- }
594
- } catch {}
595
-
596
- // Git stats
597
- let gitCommits = 0;
598
- let gitFirstCommitDate = null;
599
- try {
600
- const commitCount = execGit(cwd, ['rev-list', '--count', 'HEAD']);
601
- gitCommits = parseInt(commitCount.trim(), 10) || 0;
602
- const firstDate = execGit(cwd, ['log', '--reverse', '--format=%as', '--max-count=1']);
603
- gitFirstCommitDate = firstDate.trim() || null;
604
- } catch {}
605
-
606
- const completedPhases = phases.filter(p => p.status === 'Complete').length;
607
-
608
- const result = {
609
- milestone_version: milestone.version,
610
- milestone_name: milestone.name,
611
- phases,
612
- phases_completed: completedPhases,
613
- phases_total: phases.length,
614
- total_plans: totalPlans,
615
- total_summaries: totalSummaries,
616
- percent,
617
- requirements_total: requirementsTotal,
618
- requirements_complete: requirementsComplete,
619
- git_commits: gitCommits,
620
- git_first_commit_date: gitFirstCommitDate,
621
- last_activity: lastActivity,
622
- };
623
-
624
- if (format === 'table') {
625
- const barWidth = 10;
626
- const filled = Math.round((percent / 100) * barWidth);
627
- const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
628
- let out = `# ${milestone.version} ${milestone.name} \u2014 Statistics\n\n`;
629
- out += `**Progress:** [${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)\n`;
630
- out += `**Phases:** ${completedPhases}/${phases.length} complete\n`;
631
- if (requirementsTotal > 0) {
632
- out += `**Requirements:** ${requirementsComplete}/${requirementsTotal} complete\n`;
633
- }
634
- out += '\n';
635
- out += `| Phase | Name | Plans | Completed | Status |\n`;
636
- out += `|-------|------|-------|-----------|--------|\n`;
637
- for (const p of phases) {
638
- out += `| ${p.number} | ${p.name} | ${p.plans} | ${p.summaries} | ${p.status} |\n`;
639
- }
640
- if (gitCommits > 0) {
641
- out += `\n**Git:** ${gitCommits} commits`;
642
- if (gitFirstCommitDate) out += ` (since ${gitFirstCommitDate})`;
643
- out += '\n';
644
- }
645
- if (lastActivity) out += `**Last activity:** ${lastActivity}\n`;
646
- output({ rendered: out }, raw, out);
647
- } else {
648
- output(result, raw);
649
- }
650
- }
651
-
652
- module.exports = {
653
- cmdGenerateSlug,
654
- cmdCurrentTimestamp,
655
- cmdListTodos,
656
- cmdVerifyPathExists,
657
- cmdHistoryDigest,
658
- cmdResolveModel,
659
- cmdCommit,
660
- cmdSummaryExtract,
661
- cmdWebsearch,
662
- cmdProgressRender,
663
- cmdTodoComplete,
664
- cmdScaffold,
665
- cmdStats,
666
- };
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, resolveModelInternal, MODEL_PROFILES, toPosixPath, output, error, findPhaseInternal } = require('./core.cjs');
8
+ const { extractFrontmatter } = require('./frontmatter.cjs');
9
+
10
+ function cmdGenerateSlug(text, raw) {
11
+ if (!text) {
12
+ error('text required for slug generation');
13
+ }
14
+
15
+ const slug = text
16
+ .toLowerCase()
17
+ .replace(/[^a-z0-9]+/g, '-')
18
+ .replace(/^-+|-+$/g, '');
19
+
20
+ const result = { slug };
21
+ output(result, raw, slug);
22
+ }
23
+
24
+ function cmdCurrentTimestamp(format, raw) {
25
+ const now = new Date();
26
+ let result;
27
+
28
+ switch (format) {
29
+ case 'date':
30
+ result = now.toISOString().split('T')[0];
31
+ break;
32
+ case 'filename':
33
+ result = now.toISOString().replace(/:/g, '-').replace(/\..+/, '');
34
+ break;
35
+ case 'full':
36
+ default:
37
+ result = now.toISOString();
38
+ break;
39
+ }
40
+
41
+ output({ timestamp: result }, raw, result);
42
+ }
43
+
44
+ function cmdListTodos(cwd, area, raw) {
45
+ const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
46
+
47
+ let count = 0;
48
+ const todos = [];
49
+
50
+ try {
51
+ const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
52
+
53
+ for (const file of files) {
54
+ try {
55
+ const content = fs.readFileSync(path.join(pendingDir, file), 'utf-8');
56
+ const createdMatch = content.match(/^created:\s*(.+)$/m);
57
+ const titleMatch = content.match(/^title:\s*(.+)$/m);
58
+ const areaMatch = content.match(/^area:\s*(.+)$/m);
59
+
60
+ const todoArea = areaMatch ? areaMatch[1].trim() : 'general';
61
+
62
+ // Apply area filter if specified
63
+ if (area && todoArea !== area) continue;
64
+
65
+ count++;
66
+ todos.push({
67
+ file,
68
+ created: createdMatch ? createdMatch[1].trim() : 'unknown',
69
+ title: titleMatch ? titleMatch[1].trim() : 'Untitled',
70
+ area: todoArea,
71
+ path: toPosixPath(path.join('.planning', 'todos', 'pending', file)),
72
+ });
73
+ } catch {}
74
+ }
75
+ } catch {}
76
+
77
+ const result = { count, todos };
78
+ output(result, raw, count.toString());
79
+ }
80
+
81
+ function cmdVerifyPathExists(cwd, targetPath, raw) {
82
+ if (!targetPath) {
83
+ error('path required for verification');
84
+ }
85
+
86
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
87
+
88
+ try {
89
+ const stats = fs.statSync(fullPath);
90
+ const type = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : 'other';
91
+ const result = { exists: true, type };
92
+ output(result, raw, 'true');
93
+ } catch {
94
+ const result = { exists: false, type: null };
95
+ output(result, raw, 'false');
96
+ }
97
+ }
98
+
99
+ function cmdHistoryDigest(cwd, raw) {
100
+ const phasesDir = path.join(cwd, '.planning', 'phases');
101
+ const digest = { phases: {}, decisions: [], tech_stack: new Set() };
102
+
103
+ // Collect all phase directories: archived + current
104
+ const allPhaseDirs = [];
105
+
106
+ // Add archived phases first (oldest milestones first)
107
+ const archived = getArchivedPhaseDirs(cwd);
108
+ for (const a of archived) {
109
+ allPhaseDirs.push({ name: a.name, fullPath: a.fullPath, milestone: a.milestone });
110
+ }
111
+
112
+ // Add current phases
113
+ if (fs.existsSync(phasesDir)) {
114
+ try {
115
+ const currentDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
116
+ .filter(e => e.isDirectory())
117
+ .map(e => e.name)
118
+ .sort();
119
+ for (const dir of currentDirs) {
120
+ allPhaseDirs.push({ name: dir, fullPath: path.join(phasesDir, dir), milestone: null });
121
+ }
122
+ } catch {}
123
+ }
124
+
125
+ if (allPhaseDirs.length === 0) {
126
+ digest.tech_stack = [];
127
+ output(digest, raw);
128
+ return;
129
+ }
130
+
131
+ try {
132
+ for (const { name: dir, fullPath: dirPath } of allPhaseDirs) {
133
+ const summaries = fs.readdirSync(dirPath).filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
134
+
135
+ for (const summary of summaries) {
136
+ try {
137
+ const content = fs.readFileSync(path.join(dirPath, summary), 'utf-8');
138
+ const fm = extractFrontmatter(content);
139
+
140
+ const phaseNum = fm.phase || dir.split('-')[0];
141
+
142
+ if (!digest.phases[phaseNum]) {
143
+ digest.phases[phaseNum] = {
144
+ name: fm.name || dir.split('-').slice(1).join(' ') || 'Unknown',
145
+ provides: new Set(),
146
+ affects: new Set(),
147
+ patterns: new Set(),
148
+ };
149
+ }
150
+
151
+ // Merge provides
152
+ if (fm['dependency-graph'] && fm['dependency-graph'].provides) {
153
+ fm['dependency-graph'].provides.forEach(p => digest.phases[phaseNum].provides.add(p));
154
+ } else if (fm.provides) {
155
+ fm.provides.forEach(p => digest.phases[phaseNum].provides.add(p));
156
+ }
157
+
158
+ // Merge affects
159
+ if (fm['dependency-graph'] && fm['dependency-graph'].affects) {
160
+ fm['dependency-graph'].affects.forEach(a => digest.phases[phaseNum].affects.add(a));
161
+ }
162
+
163
+ // Merge patterns
164
+ if (fm['patterns-established']) {
165
+ fm['patterns-established'].forEach(p => digest.phases[phaseNum].patterns.add(p));
166
+ }
167
+
168
+ // Merge decisions
169
+ if (fm['key-decisions']) {
170
+ fm['key-decisions'].forEach(d => {
171
+ digest.decisions.push({ phase: phaseNum, decision: d });
172
+ });
173
+ }
174
+
175
+ // Merge tech stack
176
+ if (fm['tech-stack'] && fm['tech-stack'].added) {
177
+ fm['tech-stack'].added.forEach(t => digest.tech_stack.add(typeof t === 'string' ? t : t.name));
178
+ }
179
+
180
+ } catch (e) {
181
+ // Skip malformed summaries
182
+ }
183
+ }
184
+ }
185
+
186
+ // Convert Sets to Arrays for JSON output
187
+ Object.keys(digest.phases).forEach(p => {
188
+ digest.phases[p].provides = [...digest.phases[p].provides];
189
+ digest.phases[p].affects = [...digest.phases[p].affects];
190
+ digest.phases[p].patterns = [...digest.phases[p].patterns];
191
+ });
192
+ digest.tech_stack = [...digest.tech_stack];
193
+
194
+ output(digest, raw);
195
+ } catch (e) {
196
+ error('Failed to generate history digest: ' + e.message);
197
+ }
198
+ }
199
+
200
+ function cmdResolveModel(cwd, agentType, raw) {
201
+ if (!agentType) {
202
+ error('agent-type required');
203
+ }
204
+
205
+ const config = loadConfig(cwd);
206
+ const profile = config.model_profile || 'balanced';
207
+ const model = resolveModelInternal(cwd, agentType);
208
+
209
+ const agentModels = MODEL_PROFILES[agentType];
210
+ const result = agentModels
211
+ ? { model, profile }
212
+ : { model, profile, unknown_agent: true };
213
+ output(result, raw, model);
214
+ }
215
+
216
+ function cmdCommit(cwd, message, files, raw, amend) {
217
+ if (!message && !amend) {
218
+ error('commit message required');
219
+ }
220
+
221
+ const config = loadConfig(cwd);
222
+
223
+ // Check commit_docs config
224
+ if (!config.commit_docs) {
225
+ const result = { committed: false, hash: null, reason: 'skipped_commit_docs_false' };
226
+ output(result, raw, 'skipped');
227
+ return;
228
+ }
229
+
230
+ // Check if .planning is gitignored
231
+ if (isGitIgnored(cwd, '.planning')) {
232
+ const result = { committed: false, hash: null, reason: 'skipped_gitignored' };
233
+ output(result, raw, 'skipped');
234
+ return;
235
+ }
236
+
237
+ // Stage files
238
+ const filesToStage = files && files.length > 0 ? files : ['.planning/'];
239
+ for (const file of filesToStage) {
240
+ execGit(cwd, ['add', file]);
241
+ }
242
+
243
+ // Commit
244
+ const commitArgs = amend ? ['commit', '--amend', '--no-edit'] : ['commit', '-m', message];
245
+ const commitResult = execGit(cwd, commitArgs);
246
+ if (commitResult.exitCode !== 0) {
247
+ if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
248
+ const result = { committed: false, hash: null, reason: 'nothing_to_commit' };
249
+ output(result, raw, 'nothing');
250
+ return;
251
+ }
252
+ const result = { committed: false, hash: null, reason: 'nothing_to_commit', error: commitResult.stderr };
253
+ output(result, raw, 'nothing');
254
+ return;
255
+ }
256
+
257
+ // Get short hash
258
+ const hashResult = execGit(cwd, ['rev-parse', '--short', 'HEAD']);
259
+ const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
260
+ const result = { committed: true, hash, reason: 'committed' };
261
+ output(result, raw, hash || 'committed');
262
+ }
263
+
264
+ function cmdSummaryExtract(cwd, summaryPath, fields, raw) {
265
+ if (!summaryPath) {
266
+ error('summary-path required for summary-extract');
267
+ }
268
+
269
+ const fullPath = path.join(cwd, summaryPath);
270
+
271
+ if (!fs.existsSync(fullPath)) {
272
+ output({ error: 'File not found', path: summaryPath }, raw);
273
+ return;
274
+ }
275
+
276
+ const content = fs.readFileSync(fullPath, 'utf-8');
277
+ const fm = extractFrontmatter(content);
278
+
279
+ // Parse key-decisions into structured format
280
+ const parseDecisions = (decisionsList) => {
281
+ if (!decisionsList || !Array.isArray(decisionsList)) return [];
282
+ return decisionsList.map(d => {
283
+ const colonIdx = d.indexOf(':');
284
+ if (colonIdx > 0) {
285
+ return {
286
+ summary: d.substring(0, colonIdx).trim(),
287
+ rationale: d.substring(colonIdx + 1).trim(),
288
+ };
289
+ }
290
+ return { summary: d, rationale: null };
291
+ });
292
+ };
293
+
294
+ // Build full result
295
+ const fullResult = {
296
+ path: summaryPath,
297
+ one_liner: fm['one-liner'] || null,
298
+ key_files: fm['key-files'] || [],
299
+ tech_added: (fm['tech-stack'] && fm['tech-stack'].added) || [],
300
+ patterns: fm['patterns-established'] || [],
301
+ decisions: parseDecisions(fm['key-decisions']),
302
+ requirements_completed: fm['requirements-completed'] || [],
303
+ };
304
+
305
+ // If fields specified, filter to only those fields
306
+ if (fields && fields.length > 0) {
307
+ const filtered = { path: summaryPath };
308
+ for (const field of fields) {
309
+ if (fullResult[field] !== undefined) {
310
+ filtered[field] = fullResult[field];
311
+ }
312
+ }
313
+ output(filtered, raw);
314
+ return;
315
+ }
316
+
317
+ output(fullResult, raw);
318
+ }
319
+
320
+ async function cmdWebsearch(query, options, raw) {
321
+ const apiKey = process.env.BRAVE_API_KEY;
322
+
323
+ if (!apiKey) {
324
+ // No key = silent skip, agent falls back to built-in WebSearch
325
+ output({ available: false, reason: 'BRAVE_API_KEY not set' }, raw, '');
326
+ return;
327
+ }
328
+
329
+ if (!query) {
330
+ output({ available: false, error: 'Query required' }, raw, '');
331
+ return;
332
+ }
333
+
334
+ const params = new URLSearchParams({
335
+ q: query,
336
+ count: String(options.limit || 10),
337
+ country: 'us',
338
+ search_lang: 'en',
339
+ text_decorations: 'false'
340
+ });
341
+
342
+ if (options.freshness) {
343
+ params.set('freshness', options.freshness);
344
+ }
345
+
346
+ try {
347
+ const response = await fetch(
348
+ `https://api.search.brave.com/res/v1/web/search?${params}`,
349
+ {
350
+ headers: {
351
+ 'Accept': 'application/json',
352
+ 'X-Subscription-Token': apiKey
353
+ }
354
+ }
355
+ );
356
+
357
+ if (!response.ok) {
358
+ output({ available: false, error: `API error: ${response.status}` }, raw, '');
359
+ return;
360
+ }
361
+
362
+ const data = await response.json();
363
+
364
+ const results = (data.web?.results || []).map(r => ({
365
+ title: r.title,
366
+ url: r.url,
367
+ description: r.description,
368
+ age: r.age || null
369
+ }));
370
+
371
+ output({
372
+ available: true,
373
+ query,
374
+ count: results.length,
375
+ results
376
+ }, raw, results.map(r => `${r.title}\n${r.url}\n${r.description}`).join('\n\n'));
377
+ } catch (err) {
378
+ output({ available: false, error: err.message }, raw, '');
379
+ }
380
+ }
381
+
382
+ function cmdProgressRender(cwd, format, raw) {
383
+ const phasesDir = path.join(cwd, '.planning', 'phases');
384
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
385
+ const milestone = getMilestoneInfo(cwd);
386
+
387
+ const phases = [];
388
+ let totalPlans = 0;
389
+ let totalSummaries = 0;
390
+
391
+ try {
392
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
393
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
394
+
395
+ for (const dir of dirs) {
396
+ const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
397
+ const phaseNum = dm ? dm[1] : dir;
398
+ const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
399
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
400
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
401
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
402
+
403
+ totalPlans += plans;
404
+ totalSummaries += summaries;
405
+
406
+ let status;
407
+ if (plans === 0) status = 'Pending';
408
+ else if (summaries >= plans) status = 'Complete';
409
+ else if (summaries > 0) status = 'In Progress';
410
+ else status = 'Planned';
411
+
412
+ phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
413
+ }
414
+ } catch {}
415
+
416
+ const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
417
+
418
+ if (format === 'table') {
419
+ // Render markdown table
420
+ const barWidth = 10;
421
+ const filled = Math.round((percent / 100) * barWidth);
422
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
423
+ let out = `# ${milestone.version} ${milestone.name}\n\n`;
424
+ out += `**Progress:** [${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)\n\n`;
425
+ out += `| Phase | Name | Plans | Status |\n`;
426
+ out += `|-------|------|-------|--------|\n`;
427
+ for (const p of phases) {
428
+ out += `| ${p.number} | ${p.name} | ${p.summaries}/${p.plans} | ${p.status} |\n`;
429
+ }
430
+ output({ rendered: out }, raw, out);
431
+ } else if (format === 'bar') {
432
+ const barWidth = 20;
433
+ const filled = Math.round((percent / 100) * barWidth);
434
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
435
+ const text = `[${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)`;
436
+ output({ bar: text, percent, completed: totalSummaries, total: totalPlans }, raw, text);
437
+ } else {
438
+ // JSON format
439
+ output({
440
+ milestone_version: milestone.version,
441
+ milestone_name: milestone.name,
442
+ phases,
443
+ total_plans: totalPlans,
444
+ total_summaries: totalSummaries,
445
+ percent,
446
+ }, raw);
447
+ }
448
+ }
449
+
450
+ function cmdTodoComplete(cwd, filename, raw) {
451
+ if (!filename) {
452
+ error('filename required for todo complete');
453
+ }
454
+
455
+ const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
456
+ const completedDir = path.join(cwd, '.planning', 'todos', 'completed');
457
+ const sourcePath = path.join(pendingDir, filename);
458
+
459
+ if (!fs.existsSync(sourcePath)) {
460
+ error(`Todo not found: ${filename}`);
461
+ }
462
+
463
+ // Ensure completed directory exists
464
+ fs.mkdirSync(completedDir, { recursive: true });
465
+
466
+ // Read, add completion timestamp, move
467
+ let content = fs.readFileSync(sourcePath, 'utf-8');
468
+ const today = new Date().toISOString().split('T')[0];
469
+ content = `completed: ${today}\n` + content;
470
+
471
+ fs.writeFileSync(path.join(completedDir, filename), content, 'utf-8');
472
+ fs.unlinkSync(sourcePath);
473
+
474
+ output({ completed: true, file: filename, date: today }, raw, 'completed');
475
+ }
476
+
477
+ function cmdScaffold(cwd, type, options, raw) {
478
+ const { phase, name } = options;
479
+ const padded = phase ? normalizePhaseName(phase) : '00';
480
+ const today = new Date().toISOString().split('T')[0];
481
+
482
+ // Find phase directory
483
+ const phaseInfo = phase ? findPhaseInternal(cwd, phase) : null;
484
+ const phaseDir = phaseInfo ? path.join(cwd, phaseInfo.directory) : null;
485
+
486
+ if (phase && !phaseDir && type !== 'phase-dir') {
487
+ error(`Phase ${phase} directory not found`);
488
+ }
489
+
490
+ let filePath, content;
491
+
492
+ switch (type) {
493
+ case 'context': {
494
+ filePath = path.join(phaseDir, `${padded}-CONTEXT.md`);
495
+ 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`;
496
+ break;
497
+ }
498
+ case 'uat': {
499
+ filePath = path.join(phaseDir, `${padded}-UAT.md`);
500
+ 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`;
501
+ break;
502
+ }
503
+ case 'verification': {
504
+ filePath = path.join(phaseDir, `${padded}-VERIFICATION.md`);
505
+ 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`;
506
+ break;
507
+ }
508
+ case 'phase-dir': {
509
+ if (!phase || !name) {
510
+ error('phase and name required for phase-dir scaffold');
511
+ }
512
+ const slug = generateSlugInternal(name);
513
+ const dirName = `${padded}-${slug}`;
514
+ const phasesParent = path.join(cwd, '.planning', 'phases');
515
+ fs.mkdirSync(phasesParent, { recursive: true });
516
+ const dirPath = path.join(phasesParent, dirName);
517
+ fs.mkdirSync(dirPath, { recursive: true });
518
+ output({ created: true, directory: `.planning/phases/${dirName}`, path: dirPath }, raw, dirPath);
519
+ return;
520
+ }
521
+ default:
522
+ error(`Unknown scaffold type: ${type}. Available: context, uat, verification, phase-dir`);
523
+ }
524
+
525
+ if (fs.existsSync(filePath)) {
526
+ output({ created: false, reason: 'already_exists', path: filePath }, raw, 'exists');
527
+ return;
528
+ }
529
+
530
+ fs.writeFileSync(filePath, content, 'utf-8');
531
+ const relPath = toPosixPath(path.relative(cwd, filePath));
532
+ output({ created: true, path: relPath }, raw, relPath);
533
+ }
534
+
535
+ function cmdStats(cwd, format, raw) {
536
+ const phasesDir = path.join(cwd, '.planning', 'phases');
537
+ const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
538
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
539
+ const milestone = getMilestoneInfo(cwd);
540
+
541
+ // Phase & plan stats (reuse progress pattern)
542
+ const phases = [];
543
+ let totalPlans = 0;
544
+ let totalSummaries = 0;
545
+
546
+ try {
547
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
548
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
549
+
550
+ for (const dir of dirs) {
551
+ const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
552
+ const phaseNum = dm ? dm[1] : dir;
553
+ const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
554
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
555
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
556
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
557
+
558
+ totalPlans += plans;
559
+ totalSummaries += summaries;
560
+
561
+ let status;
562
+ if (plans === 0) status = 'Pending';
563
+ else if (summaries >= plans) status = 'Complete';
564
+ else if (summaries > 0) status = 'In Progress';
565
+ else status = 'Planned';
566
+
567
+ phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
568
+ }
569
+ } catch {}
570
+
571
+ const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
572
+
573
+ // Requirements stats
574
+ let requirementsTotal = 0;
575
+ let requirementsComplete = 0;
576
+ try {
577
+ if (fs.existsSync(reqPath)) {
578
+ const reqContent = fs.readFileSync(reqPath, 'utf-8');
579
+ const checked = reqContent.match(/^- \[x\] \*\*/gm);
580
+ const unchecked = reqContent.match(/^- \[ \] \*\*/gm);
581
+ requirementsComplete = checked ? checked.length : 0;
582
+ requirementsTotal = requirementsComplete + (unchecked ? unchecked.length : 0);
583
+ }
584
+ } catch {}
585
+
586
+ // Last activity from STATE.md
587
+ let lastActivity = null;
588
+ try {
589
+ if (fs.existsSync(statePath)) {
590
+ const stateContent = fs.readFileSync(statePath, 'utf-8');
591
+ const activityMatch = stateContent.match(/\*\*Last Activity:\*\*\s*(.+)/);
592
+ if (activityMatch) lastActivity = activityMatch[1].trim();
593
+ }
594
+ } catch {}
595
+
596
+ // Git stats
597
+ let gitCommits = 0;
598
+ let gitFirstCommitDate = null;
599
+ try {
600
+ const commitCount = execGit(cwd, ['rev-list', '--count', 'HEAD']);
601
+ gitCommits = parseInt(commitCount.trim(), 10) || 0;
602
+ const firstDate = execGit(cwd, ['log', '--reverse', '--format=%as', '--max-count=1']);
603
+ gitFirstCommitDate = firstDate.trim() || null;
604
+ } catch {}
605
+
606
+ const completedPhases = phases.filter(p => p.status === 'Complete').length;
607
+
608
+ const result = {
609
+ milestone_version: milestone.version,
610
+ milestone_name: milestone.name,
611
+ phases,
612
+ phases_completed: completedPhases,
613
+ phases_total: phases.length,
614
+ total_plans: totalPlans,
615
+ total_summaries: totalSummaries,
616
+ percent,
617
+ requirements_total: requirementsTotal,
618
+ requirements_complete: requirementsComplete,
619
+ git_commits: gitCommits,
620
+ git_first_commit_date: gitFirstCommitDate,
621
+ last_activity: lastActivity,
622
+ };
623
+
624
+ if (format === 'table') {
625
+ const barWidth = 10;
626
+ const filled = Math.round((percent / 100) * barWidth);
627
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
628
+ let out = `# ${milestone.version} ${milestone.name} \u2014 Statistics\n\n`;
629
+ out += `**Progress:** [${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)\n`;
630
+ out += `**Phases:** ${completedPhases}/${phases.length} complete\n`;
631
+ if (requirementsTotal > 0) {
632
+ out += `**Requirements:** ${requirementsComplete}/${requirementsTotal} complete\n`;
633
+ }
634
+ out += '\n';
635
+ out += `| Phase | Name | Plans | Completed | Status |\n`;
636
+ out += `|-------|------|-------|-----------|--------|\n`;
637
+ for (const p of phases) {
638
+ out += `| ${p.number} | ${p.name} | ${p.plans} | ${p.summaries} | ${p.status} |\n`;
639
+ }
640
+ if (gitCommits > 0) {
641
+ out += `\n**Git:** ${gitCommits} commits`;
642
+ if (gitFirstCommitDate) out += ` (since ${gitFirstCommitDate})`;
643
+ out += '\n';
644
+ }
645
+ if (lastActivity) out += `**Last activity:** ${lastActivity}\n`;
646
+ output({ rendered: out }, raw, out);
647
+ } else {
648
+ output(result, raw);
649
+ }
650
+ }
651
+
652
+ module.exports = {
653
+ cmdGenerateSlug,
654
+ cmdCurrentTimestamp,
655
+ cmdListTodos,
656
+ cmdVerifyPathExists,
657
+ cmdHistoryDigest,
658
+ cmdResolveModel,
659
+ cmdCommit,
660
+ cmdSummaryExtract,
661
+ cmdWebsearch,
662
+ cmdProgressRender,
663
+ cmdTodoComplete,
664
+ cmdScaffold,
665
+ cmdStats,
666
+ };