qaa-agent 1.0.0

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