qaa-agent 1.6.2 → 1.6.3

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 (73) hide show
  1. package/.claude/commands/create-test.md +164 -164
  2. package/.claude/commands/qa-audit.md +37 -37
  3. package/.claude/commands/qa-blueprint.md +54 -54
  4. package/.claude/commands/qa-fix.md +36 -36
  5. package/.claude/commands/qa-from-ticket.md +24 -24
  6. package/.claude/commands/qa-gap.md +20 -20
  7. package/.claude/commands/qa-map.md +47 -47
  8. package/.claude/commands/qa-pom.md +36 -36
  9. package/.claude/commands/qa-pr.md +23 -23
  10. package/.claude/commands/qa-pyramid.md +37 -37
  11. package/.claude/commands/qa-report.md +38 -38
  12. package/.claude/commands/qa-research.md +33 -33
  13. package/.claude/commands/qa-start.md +22 -22
  14. package/.claude/commands/qa-testid.md +19 -19
  15. package/.claude/commands/qa-validate.md +42 -42
  16. package/.claude/commands/update-test.md +58 -58
  17. package/.claude/settings.json +20 -20
  18. package/.claude/skills/qa-bug-detective/SKILL.md +122 -122
  19. package/.claude/skills/qa-learner/SKILL.md +150 -150
  20. package/.claude/skills/qa-repo-analyzer/SKILL.md +88 -88
  21. package/.claude/skills/qa-self-validator/SKILL.md +109 -109
  22. package/.claude/skills/qa-template-engine/SKILL.md +113 -113
  23. package/.claude/skills/qa-testid-injector/SKILL.md +93 -93
  24. package/.claude/skills/qa-workflow-documenter/SKILL.md +87 -87
  25. package/.mcp.json +8 -8
  26. package/CHANGELOG.md +71 -71
  27. package/CLAUDE.md +553 -553
  28. package/agents/qa-pipeline-orchestrator.md +1378 -1378
  29. package/agents/qaa-analyzer.md +524 -524
  30. package/agents/qaa-bug-detective.md +446 -446
  31. package/agents/qaa-codebase-mapper.md +935 -935
  32. package/agents/qaa-e2e-runner.md +415 -415
  33. package/agents/qaa-executor.md +651 -651
  34. package/agents/qaa-planner.md +390 -390
  35. package/agents/qaa-project-researcher.md +319 -319
  36. package/agents/qaa-scanner.md +424 -424
  37. package/agents/qaa-testid-injector.md +585 -585
  38. package/agents/qaa-validator.md +452 -452
  39. package/bin/install.cjs +198 -198
  40. package/bin/lib/commands.cjs +709 -709
  41. package/bin/lib/config.cjs +307 -307
  42. package/bin/lib/core.cjs +497 -497
  43. package/bin/lib/frontmatter.cjs +299 -299
  44. package/bin/lib/init.cjs +989 -989
  45. package/bin/lib/milestone.cjs +241 -241
  46. package/bin/lib/model-profiles.cjs +60 -60
  47. package/bin/lib/phase.cjs +911 -911
  48. package/bin/lib/roadmap.cjs +306 -306
  49. package/bin/lib/state.cjs +748 -748
  50. package/bin/lib/template.cjs +222 -222
  51. package/bin/lib/verify.cjs +842 -842
  52. package/bin/qaa-tools.cjs +607 -607
  53. package/docs/COMMANDS.md +341 -341
  54. package/docs/DEMO.md +182 -182
  55. package/docs/TESTING.md +156 -156
  56. package/package.json +41 -41
  57. package/templates/failure-classification.md +391 -391
  58. package/templates/gap-analysis.md +409 -409
  59. package/templates/pr-template.md +48 -48
  60. package/templates/qa-analysis.md +381 -381
  61. package/templates/qa-audit-report.md +465 -465
  62. package/templates/qa-repo-blueprint.md +636 -636
  63. package/templates/scan-manifest.md +312 -312
  64. package/templates/test-inventory.md +582 -582
  65. package/templates/testid-audit-report.md +354 -354
  66. package/templates/validation-report.md +243 -243
  67. package/workflows/qa-analyze.md +296 -296
  68. package/workflows/qa-from-ticket.md +536 -536
  69. package/workflows/qa-gap.md +303 -303
  70. package/workflows/qa-pr.md +389 -389
  71. package/workflows/qa-start.md +1168 -1168
  72. package/workflows/qa-testid.md +356 -356
  73. package/workflows/qa-validate.md +295 -295
package/bin/lib/core.cjs CHANGED
@@ -1,497 +1,497 @@
1
- /**
2
- * Core — Shared utilities, constants, and internal helpers
3
- */
4
-
5
- const fs = require('fs');
6
- const path = require('path');
7
- const { execSync, spawnSync } = require('child_process');
8
- const { MODEL_PROFILES } = require('./model-profiles.cjs');
9
-
10
- // ─── Path helpers ────────────────────────────────────────────────────────────
11
-
12
- /** Normalize a relative path to always use forward slashes (cross-platform). */
13
- function toPosixPath(p) {
14
- return p.split(path.sep).join('/');
15
- }
16
-
17
- // ─── Output helpers ───────────────────────────────────────────────────────────
18
-
19
- function output(result, raw, rawValue) {
20
- if (raw && rawValue !== undefined) {
21
- process.stdout.write(String(rawValue));
22
- } else {
23
- const json = JSON.stringify(result, null, 2);
24
- // Large payloads exceed Claude Code's Bash tool buffer (~50KB).
25
- // Write to tmpfile and output the path prefixed with @file: so callers can detect it.
26
- if (json.length > 50000) {
27
- const tmpPath = path.join(require('os').tmpdir(), `qaa-${Date.now()}.json`);
28
- fs.writeFileSync(tmpPath, json, 'utf-8');
29
- process.stdout.write('@file:' + tmpPath);
30
- } else {
31
- process.stdout.write(json);
32
- }
33
- }
34
- process.exit(0);
35
- }
36
-
37
- function error(message) {
38
- process.stderr.write('Error: ' + message + '\n');
39
- process.exit(1);
40
- }
41
-
42
- // ─── File & Config utilities ──────────────────────────────────────────────────
43
-
44
- function safeReadFile(filePath) {
45
- try {
46
- return fs.readFileSync(filePath, 'utf-8');
47
- } catch {
48
- return null;
49
- }
50
- }
51
-
52
- function loadConfig(cwd) {
53
- const configPath = path.join(cwd, '.planning', 'config.json');
54
- const defaults = {
55
- model_profile: 'balanced',
56
- commit_docs: true,
57
- search_gitignored: false,
58
- branching_strategy: 'none',
59
- phase_branch_template: 'qaa/phase-{phase}-{slug}',
60
- milestone_branch_template: 'qaa/{milestone}-{slug}',
61
- research: true,
62
- plan_checker: true,
63
- verifier: true,
64
- nyquist_validation: true,
65
- parallelization: true,
66
- brave_search: false,
67
- };
68
-
69
- try {
70
- const raw = fs.readFileSync(configPath, 'utf-8');
71
- const parsed = JSON.parse(raw);
72
-
73
- // Migrate deprecated "depth" key to "granularity" with value mapping
74
- if ('depth' in parsed && !('granularity' in parsed)) {
75
- const depthToGranularity = { quick: 'coarse', standard: 'standard', comprehensive: 'fine' };
76
- parsed.granularity = depthToGranularity[parsed.depth] || parsed.depth;
77
- delete parsed.depth;
78
- try { fs.writeFileSync(configPath, JSON.stringify(parsed, null, 2), 'utf-8'); } catch {}
79
- }
80
-
81
- const get = (key, nested) => {
82
- if (parsed[key] !== undefined) return parsed[key];
83
- if (nested && parsed[nested.section] && parsed[nested.section][nested.field] !== undefined) {
84
- return parsed[nested.section][nested.field];
85
- }
86
- return undefined;
87
- };
88
-
89
- const parallelization = (() => {
90
- const val = get('parallelization');
91
- if (typeof val === 'boolean') return val;
92
- if (typeof val === 'object' && val !== null && 'enabled' in val) return val.enabled;
93
- return defaults.parallelization;
94
- })();
95
-
96
- return {
97
- model_profile: get('model_profile') ?? defaults.model_profile,
98
- commit_docs: get('commit_docs', { section: 'planning', field: 'commit_docs' }) ?? defaults.commit_docs,
99
- search_gitignored: get('search_gitignored', { section: 'planning', field: 'search_gitignored' }) ?? defaults.search_gitignored,
100
- branching_strategy: get('branching_strategy', { section: 'git', field: 'branching_strategy' }) ?? defaults.branching_strategy,
101
- phase_branch_template: get('phase_branch_template', { section: 'git', field: 'phase_branch_template' }) ?? defaults.phase_branch_template,
102
- milestone_branch_template: get('milestone_branch_template', { section: 'git', field: 'milestone_branch_template' }) ?? defaults.milestone_branch_template,
103
- research: get('research', { section: 'workflow', field: 'research' }) ?? defaults.research,
104
- plan_checker: get('plan_checker', { section: 'workflow', field: 'plan_check' }) ?? defaults.plan_checker,
105
- verifier: get('verifier', { section: 'workflow', field: 'verifier' }) ?? defaults.verifier,
106
- nyquist_validation: get('nyquist_validation', { section: 'workflow', field: 'nyquist_validation' }) ?? defaults.nyquist_validation,
107
- parallelization,
108
- brave_search: get('brave_search') ?? defaults.brave_search,
109
- model_overrides: parsed.model_overrides || null,
110
- };
111
- } catch {
112
- return defaults;
113
- }
114
- }
115
-
116
- // ─── Git utilities ────────────────────────────────────────────────────────────
117
-
118
- function isGitIgnored(cwd, targetPath) {
119
- try {
120
- // --no-index checks .gitignore rules regardless of whether the file is tracked.
121
- // Without it, git check-ignore returns "not ignored" for tracked files even when
122
- // .gitignore explicitly lists them — a common source of confusion when .planning/
123
- // was committed before being added to .gitignore.
124
- execSync('git check-ignore -q --no-index -- ' + targetPath.replace(/[^a-zA-Z0-9._\-/]/g, ''), {
125
- cwd,
126
- stdio: 'pipe',
127
- });
128
- return true;
129
- } catch {
130
- return false;
131
- }
132
- }
133
-
134
- function execGit(cwd, args) {
135
- const result = spawnSync('git', args, {
136
- cwd,
137
- stdio: 'pipe',
138
- encoding: 'utf-8',
139
- });
140
- return {
141
- exitCode: result.status ?? 1,
142
- stdout: (result.stdout ?? '').toString().trim(),
143
- stderr: (result.stderr ?? '').toString().trim(),
144
- };
145
- }
146
-
147
- // ─── Phase utilities ──────────────────────────────────────────────────────────
148
-
149
- function escapeRegex(value) {
150
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
151
- }
152
-
153
- function normalizePhaseName(phase) {
154
- const match = String(phase).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
155
- if (!match) return phase;
156
- const padded = match[1].padStart(2, '0');
157
- const letter = match[2] ? match[2].toUpperCase() : '';
158
- const decimal = match[3] || '';
159
- return padded + letter + decimal;
160
- }
161
-
162
- function comparePhaseNum(a, b) {
163
- const pa = String(a).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
164
- const pb = String(b).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
165
- if (!pa || !pb) return String(a).localeCompare(String(b));
166
- const intDiff = parseInt(pa[1], 10) - parseInt(pb[1], 10);
167
- if (intDiff !== 0) return intDiff;
168
- // No letter sorts before letter: 12 < 12A < 12B
169
- const la = (pa[2] || '').toUpperCase();
170
- const lb = (pb[2] || '').toUpperCase();
171
- if (la !== lb) {
172
- if (!la) return -1;
173
- if (!lb) return 1;
174
- return la < lb ? -1 : 1;
175
- }
176
- // Segment-by-segment decimal comparison: 12A < 12A.1 < 12A.1.2 < 12A.2
177
- const aDecParts = pa[3] ? pa[3].slice(1).split('.').map(p => parseInt(p, 10)) : [];
178
- const bDecParts = pb[3] ? pb[3].slice(1).split('.').map(p => parseInt(p, 10)) : [];
179
- const maxLen = Math.max(aDecParts.length, bDecParts.length);
180
- if (aDecParts.length === 0 && bDecParts.length > 0) return -1;
181
- if (bDecParts.length === 0 && aDecParts.length > 0) return 1;
182
- for (let i = 0; i < maxLen; i++) {
183
- const av = Number.isFinite(aDecParts[i]) ? aDecParts[i] : 0;
184
- const bv = Number.isFinite(bDecParts[i]) ? bDecParts[i] : 0;
185
- if (av !== bv) return av - bv;
186
- }
187
- return 0;
188
- }
189
-
190
- function searchPhaseInDir(baseDir, relBase, normalized) {
191
- try {
192
- const entries = fs.readdirSync(baseDir, { withFileTypes: true });
193
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
194
- const match = dirs.find(d => d.startsWith(normalized));
195
- if (!match) return null;
196
-
197
- const dirMatch = match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
198
- const phaseNumber = dirMatch ? dirMatch[1] : normalized;
199
- const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
200
- const phaseDir = path.join(baseDir, match);
201
- const phaseFiles = fs.readdirSync(phaseDir);
202
-
203
- const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
204
- const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').sort();
205
- const hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');
206
- const hasContext = phaseFiles.some(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');
207
- const hasVerification = phaseFiles.some(f => f.endsWith('-VERIFICATION.md') || f === 'VERIFICATION.md');
208
-
209
- const completedPlanIds = new Set(
210
- summaries.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', ''))
211
- );
212
- const incompletePlans = plans.filter(p => {
213
- const planId = p.replace('-PLAN.md', '').replace('PLAN.md', '');
214
- return !completedPlanIds.has(planId);
215
- });
216
-
217
- return {
218
- found: true,
219
- directory: toPosixPath(path.join(relBase, match)),
220
- phase_number: phaseNumber,
221
- phase_name: phaseName,
222
- phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
223
- plans,
224
- summaries,
225
- incomplete_plans: incompletePlans,
226
- has_research: hasResearch,
227
- has_context: hasContext,
228
- has_verification: hasVerification,
229
- };
230
- } catch {
231
- return null;
232
- }
233
- }
234
-
235
- function findPhaseInternal(cwd, phase) {
236
- if (!phase) return null;
237
-
238
- const phasesDir = path.join(cwd, '.planning', 'phases');
239
- const normalized = normalizePhaseName(phase);
240
-
241
- // Search current phases first
242
- const current = searchPhaseInDir(phasesDir, '.planning/phases', normalized);
243
- if (current) return current;
244
-
245
- // Search archived milestone phases (newest first)
246
- const milestonesDir = path.join(cwd, '.planning', 'milestones');
247
- if (!fs.existsSync(milestonesDir)) return null;
248
-
249
- try {
250
- const milestoneEntries = fs.readdirSync(milestonesDir, { withFileTypes: true });
251
- const archiveDirs = milestoneEntries
252
- .filter(e => e.isDirectory() && /^v[\d.]+-phases$/.test(e.name))
253
- .map(e => e.name)
254
- .sort()
255
- .reverse();
256
-
257
- for (const archiveName of archiveDirs) {
258
- const version = archiveName.match(/^(v[\d.]+)-phases$/)[1];
259
- const archivePath = path.join(milestonesDir, archiveName);
260
- const relBase = '.planning/milestones/' + archiveName;
261
- const result = searchPhaseInDir(archivePath, relBase, normalized);
262
- if (result) {
263
- result.archived = version;
264
- return result;
265
- }
266
- }
267
- } catch {}
268
-
269
- return null;
270
- }
271
-
272
- function getArchivedPhaseDirs(cwd) {
273
- const milestonesDir = path.join(cwd, '.planning', 'milestones');
274
- const results = [];
275
-
276
- if (!fs.existsSync(milestonesDir)) return results;
277
-
278
- try {
279
- const milestoneEntries = fs.readdirSync(milestonesDir, { withFileTypes: true });
280
- // Find v*-phases directories, sort newest first
281
- const phaseDirs = milestoneEntries
282
- .filter(e => e.isDirectory() && /^v[\d.]+-phases$/.test(e.name))
283
- .map(e => e.name)
284
- .sort()
285
- .reverse();
286
-
287
- for (const archiveName of phaseDirs) {
288
- const version = archiveName.match(/^(v[\d.]+)-phases$/)[1];
289
- const archivePath = path.join(milestonesDir, archiveName);
290
- const entries = fs.readdirSync(archivePath, { withFileTypes: true });
291
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
292
-
293
- for (const dir of dirs) {
294
- results.push({
295
- name: dir,
296
- milestone: version,
297
- basePath: path.join('.planning', 'milestones', archiveName),
298
- fullPath: path.join(archivePath, dir),
299
- });
300
- }
301
- }
302
- } catch {}
303
-
304
- return results;
305
- }
306
-
307
- // ─── Roadmap milestone scoping ───────────────────────────────────────────────
308
-
309
- /**
310
- * Strip shipped milestone content wrapped in <details> blocks.
311
- * Used to isolate current milestone phases when searching ROADMAP.md
312
- * for phase headings or checkboxes — prevents matching archived milestone
313
- * phases that share the same numbers as current milestone phases.
314
- */
315
- function stripShippedMilestones(content) {
316
- return content.replace(/<details>[\s\S]*?<\/details>/gi, '');
317
- }
318
-
319
- /**
320
- * Replace a pattern only in the current milestone section of ROADMAP.md
321
- * (everything after the last </details> close tag). Used for write operations
322
- * that must not accidentally modify archived milestone checkboxes/tables.
323
- */
324
- function replaceInCurrentMilestone(content, pattern, replacement) {
325
- const lastDetailsClose = content.lastIndexOf('</details>');
326
- if (lastDetailsClose === -1) {
327
- return content.replace(pattern, replacement);
328
- }
329
- const offset = lastDetailsClose + '</details>'.length;
330
- const before = content.slice(0, offset);
331
- const after = content.slice(offset);
332
- return before + after.replace(pattern, replacement);
333
- }
334
-
335
- // ─── Roadmap & model utilities ────────────────────────────────────────────────
336
-
337
- function getRoadmapPhaseInternal(cwd, phaseNum) {
338
- if (!phaseNum) return null;
339
- const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
340
- if (!fs.existsSync(roadmapPath)) return null;
341
-
342
- try {
343
- const content = stripShippedMilestones(fs.readFileSync(roadmapPath, 'utf-8'));
344
- const escapedPhase = escapeRegex(phaseNum.toString());
345
- const phasePattern = new RegExp(`#{2,4}\\s*Phase\\s+${escapedPhase}:\\s*([^\\n]+)`, 'i');
346
- const headerMatch = content.match(phasePattern);
347
- if (!headerMatch) return null;
348
-
349
- const phaseName = headerMatch[1].trim();
350
- const headerIndex = headerMatch.index;
351
- const restOfContent = content.slice(headerIndex);
352
- const nextHeaderMatch = restOfContent.match(/\n#{2,4}\s+Phase\s+\d/i);
353
- const sectionEnd = nextHeaderMatch ? headerIndex + nextHeaderMatch.index : content.length;
354
- const section = content.slice(headerIndex, sectionEnd).trim();
355
-
356
- const goalMatch = section.match(/\*\*Goal(?:\*\*:|\*?\*?:\*\*)\s*([^\n]+)/i);
357
- const goal = goalMatch ? goalMatch[1].trim() : null;
358
-
359
- return {
360
- found: true,
361
- phase_number: phaseNum.toString(),
362
- phase_name: phaseName,
363
- goal,
364
- section,
365
- };
366
- } catch {
367
- return null;
368
- }
369
- }
370
-
371
- function resolveModelInternal(cwd, agentType) {
372
- const config = loadConfig(cwd);
373
-
374
- // Check per-agent override first
375
- const override = config.model_overrides?.[agentType];
376
- if (override) {
377
- return override;
378
- }
379
-
380
- // Fall back to profile lookup
381
- const profile = String(config.model_profile || 'balanced').toLowerCase();
382
- const agentModels = MODEL_PROFILES[agentType];
383
- if (!agentModels) return 'sonnet';
384
- if (profile === 'inherit') return 'inherit';
385
- return agentModels[profile] || agentModels['balanced'] || 'sonnet';
386
- }
387
-
388
- // ─── Misc utilities ───────────────────────────────────────────────────────────
389
-
390
- function pathExistsInternal(cwd, targetPath) {
391
- const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
392
- try {
393
- fs.statSync(fullPath);
394
- return true;
395
- } catch {
396
- return false;
397
- }
398
- }
399
-
400
- function generateSlugInternal(text) {
401
- if (!text) return null;
402
- return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
403
- }
404
-
405
- function getMilestoneInfo(cwd) {
406
- try {
407
- const roadmap = fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8');
408
-
409
- // First: check for list-format roadmaps using 🚧 (in-progress) marker
410
- // e.g. "- 🚧 **v2.1 Belgium** — Phases 24-28 (in progress)"
411
- const inProgressMatch = roadmap.match(/🚧\s*\*\*v(\d+\.\d+)\s+([^*]+)\*\*/);
412
- if (inProgressMatch) {
413
- return {
414
- version: 'v' + inProgressMatch[1],
415
- name: inProgressMatch[2].trim(),
416
- };
417
- }
418
-
419
- // Second: heading-format roadmaps — strip shipped milestones in <details> blocks
420
- const cleaned = stripShippedMilestones(roadmap);
421
- // Extract version and name from the same ## heading for consistency
422
- const headingMatch = cleaned.match(/## .*v(\d+\.\d+)[:\s]+([^\n(]+)/);
423
- if (headingMatch) {
424
- return {
425
- version: 'v' + headingMatch[1],
426
- name: headingMatch[2].trim(),
427
- };
428
- }
429
- // Fallback: try bare version match
430
- const versionMatch = cleaned.match(/v(\d+\.\d+)/);
431
- return {
432
- version: versionMatch ? versionMatch[0] : 'v1.0',
433
- name: 'milestone',
434
- };
435
- } catch {
436
- return { version: 'v1.0', name: 'milestone' };
437
- }
438
- }
439
-
440
- /**
441
- * Returns a filter function that checks whether a phase directory belongs
442
- * to the current milestone based on ROADMAP.md phase headings.
443
- * If no ROADMAP exists or no phases are listed, returns a pass-all filter.
444
- */
445
- function getMilestonePhaseFilter(cwd) {
446
- const milestonePhaseNums = new Set();
447
- try {
448
- const roadmap = stripShippedMilestones(fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8'));
449
- const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
450
- let m;
451
- while ((m = phasePattern.exec(roadmap)) !== null) {
452
- milestonePhaseNums.add(m[1]);
453
- }
454
- } catch {}
455
-
456
- if (milestonePhaseNums.size === 0) {
457
- const passAll = () => true;
458
- passAll.phaseCount = 0;
459
- return passAll;
460
- }
461
-
462
- const normalized = new Set(
463
- [...milestonePhaseNums].map(n => (n.replace(/^0+/, '') || '0').toLowerCase())
464
- );
465
-
466
- function isDirInMilestone(dirName) {
467
- const m = dirName.match(/^0*(\d+[A-Za-z]?(?:\.\d+)*)/);
468
- if (!m) return false;
469
- return normalized.has(m[1].toLowerCase());
470
- }
471
- isDirInMilestone.phaseCount = milestonePhaseNums.size;
472
- return isDirInMilestone;
473
- }
474
-
475
- module.exports = {
476
- output,
477
- error,
478
- safeReadFile,
479
- loadConfig,
480
- isGitIgnored,
481
- execGit,
482
- escapeRegex,
483
- normalizePhaseName,
484
- comparePhaseNum,
485
- searchPhaseInDir,
486
- findPhaseInternal,
487
- getArchivedPhaseDirs,
488
- getRoadmapPhaseInternal,
489
- resolveModelInternal,
490
- pathExistsInternal,
491
- generateSlugInternal,
492
- getMilestoneInfo,
493
- getMilestonePhaseFilter,
494
- stripShippedMilestones,
495
- replaceInCurrentMilestone,
496
- toPosixPath,
497
- };
1
+ /**
2
+ * Core — Shared utilities, constants, and internal helpers
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { execSync, spawnSync } = require('child_process');
8
+ const { MODEL_PROFILES } = require('./model-profiles.cjs');
9
+
10
+ // ─── Path helpers ────────────────────────────────────────────────────────────
11
+
12
+ /** Normalize a relative path to always use forward slashes (cross-platform). */
13
+ function toPosixPath(p) {
14
+ return p.split(path.sep).join('/');
15
+ }
16
+
17
+ // ─── Output helpers ───────────────────────────────────────────────────────────
18
+
19
+ function output(result, raw, rawValue) {
20
+ if (raw && rawValue !== undefined) {
21
+ process.stdout.write(String(rawValue));
22
+ } else {
23
+ const json = JSON.stringify(result, null, 2);
24
+ // Large payloads exceed Claude Code's Bash tool buffer (~50KB).
25
+ // Write to tmpfile and output the path prefixed with @file: so callers can detect it.
26
+ if (json.length > 50000) {
27
+ const tmpPath = path.join(require('os').tmpdir(), `qaa-${Date.now()}.json`);
28
+ fs.writeFileSync(tmpPath, json, 'utf-8');
29
+ process.stdout.write('@file:' + tmpPath);
30
+ } else {
31
+ process.stdout.write(json);
32
+ }
33
+ }
34
+ process.exit(0);
35
+ }
36
+
37
+ function error(message) {
38
+ process.stderr.write('Error: ' + message + '\n');
39
+ process.exit(1);
40
+ }
41
+
42
+ // ─── File & Config utilities ──────────────────────────────────────────────────
43
+
44
+ function safeReadFile(filePath) {
45
+ try {
46
+ return fs.readFileSync(filePath, 'utf-8');
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ function loadConfig(cwd) {
53
+ const configPath = path.join(cwd, '.planning', 'config.json');
54
+ const defaults = {
55
+ model_profile: 'balanced',
56
+ commit_docs: true,
57
+ search_gitignored: false,
58
+ branching_strategy: 'none',
59
+ phase_branch_template: 'qaa/phase-{phase}-{slug}',
60
+ milestone_branch_template: 'qaa/{milestone}-{slug}',
61
+ research: true,
62
+ plan_checker: true,
63
+ verifier: true,
64
+ nyquist_validation: true,
65
+ parallelization: true,
66
+ brave_search: false,
67
+ };
68
+
69
+ try {
70
+ const raw = fs.readFileSync(configPath, 'utf-8');
71
+ const parsed = JSON.parse(raw);
72
+
73
+ // Migrate deprecated "depth" key to "granularity" with value mapping
74
+ if ('depth' in parsed && !('granularity' in parsed)) {
75
+ const depthToGranularity = { quick: 'coarse', standard: 'standard', comprehensive: 'fine' };
76
+ parsed.granularity = depthToGranularity[parsed.depth] || parsed.depth;
77
+ delete parsed.depth;
78
+ try { fs.writeFileSync(configPath, JSON.stringify(parsed, null, 2), 'utf-8'); } catch {}
79
+ }
80
+
81
+ const get = (key, nested) => {
82
+ if (parsed[key] !== undefined) return parsed[key];
83
+ if (nested && parsed[nested.section] && parsed[nested.section][nested.field] !== undefined) {
84
+ return parsed[nested.section][nested.field];
85
+ }
86
+ return undefined;
87
+ };
88
+
89
+ const parallelization = (() => {
90
+ const val = get('parallelization');
91
+ if (typeof val === 'boolean') return val;
92
+ if (typeof val === 'object' && val !== null && 'enabled' in val) return val.enabled;
93
+ return defaults.parallelization;
94
+ })();
95
+
96
+ return {
97
+ model_profile: get('model_profile') ?? defaults.model_profile,
98
+ commit_docs: get('commit_docs', { section: 'planning', field: 'commit_docs' }) ?? defaults.commit_docs,
99
+ search_gitignored: get('search_gitignored', { section: 'planning', field: 'search_gitignored' }) ?? defaults.search_gitignored,
100
+ branching_strategy: get('branching_strategy', { section: 'git', field: 'branching_strategy' }) ?? defaults.branching_strategy,
101
+ phase_branch_template: get('phase_branch_template', { section: 'git', field: 'phase_branch_template' }) ?? defaults.phase_branch_template,
102
+ milestone_branch_template: get('milestone_branch_template', { section: 'git', field: 'milestone_branch_template' }) ?? defaults.milestone_branch_template,
103
+ research: get('research', { section: 'workflow', field: 'research' }) ?? defaults.research,
104
+ plan_checker: get('plan_checker', { section: 'workflow', field: 'plan_check' }) ?? defaults.plan_checker,
105
+ verifier: get('verifier', { section: 'workflow', field: 'verifier' }) ?? defaults.verifier,
106
+ nyquist_validation: get('nyquist_validation', { section: 'workflow', field: 'nyquist_validation' }) ?? defaults.nyquist_validation,
107
+ parallelization,
108
+ brave_search: get('brave_search') ?? defaults.brave_search,
109
+ model_overrides: parsed.model_overrides || null,
110
+ };
111
+ } catch {
112
+ return defaults;
113
+ }
114
+ }
115
+
116
+ // ─── Git utilities ────────────────────────────────────────────────────────────
117
+
118
+ function isGitIgnored(cwd, targetPath) {
119
+ try {
120
+ // --no-index checks .gitignore rules regardless of whether the file is tracked.
121
+ // Without it, git check-ignore returns "not ignored" for tracked files even when
122
+ // .gitignore explicitly lists them — a common source of confusion when .planning/
123
+ // was committed before being added to .gitignore.
124
+ execSync('git check-ignore -q --no-index -- ' + targetPath.replace(/[^a-zA-Z0-9._\-/]/g, ''), {
125
+ cwd,
126
+ stdio: 'pipe',
127
+ });
128
+ return true;
129
+ } catch {
130
+ return false;
131
+ }
132
+ }
133
+
134
+ function execGit(cwd, args) {
135
+ const result = spawnSync('git', args, {
136
+ cwd,
137
+ stdio: 'pipe',
138
+ encoding: 'utf-8',
139
+ });
140
+ return {
141
+ exitCode: result.status ?? 1,
142
+ stdout: (result.stdout ?? '').toString().trim(),
143
+ stderr: (result.stderr ?? '').toString().trim(),
144
+ };
145
+ }
146
+
147
+ // ─── Phase utilities ──────────────────────────────────────────────────────────
148
+
149
+ function escapeRegex(value) {
150
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
151
+ }
152
+
153
+ function normalizePhaseName(phase) {
154
+ const match = String(phase).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
155
+ if (!match) return phase;
156
+ const padded = match[1].padStart(2, '0');
157
+ const letter = match[2] ? match[2].toUpperCase() : '';
158
+ const decimal = match[3] || '';
159
+ return padded + letter + decimal;
160
+ }
161
+
162
+ function comparePhaseNum(a, b) {
163
+ const pa = String(a).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
164
+ const pb = String(b).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
165
+ if (!pa || !pb) return String(a).localeCompare(String(b));
166
+ const intDiff = parseInt(pa[1], 10) - parseInt(pb[1], 10);
167
+ if (intDiff !== 0) return intDiff;
168
+ // No letter sorts before letter: 12 < 12A < 12B
169
+ const la = (pa[2] || '').toUpperCase();
170
+ const lb = (pb[2] || '').toUpperCase();
171
+ if (la !== lb) {
172
+ if (!la) return -1;
173
+ if (!lb) return 1;
174
+ return la < lb ? -1 : 1;
175
+ }
176
+ // Segment-by-segment decimal comparison: 12A < 12A.1 < 12A.1.2 < 12A.2
177
+ const aDecParts = pa[3] ? pa[3].slice(1).split('.').map(p => parseInt(p, 10)) : [];
178
+ const bDecParts = pb[3] ? pb[3].slice(1).split('.').map(p => parseInt(p, 10)) : [];
179
+ const maxLen = Math.max(aDecParts.length, bDecParts.length);
180
+ if (aDecParts.length === 0 && bDecParts.length > 0) return -1;
181
+ if (bDecParts.length === 0 && aDecParts.length > 0) return 1;
182
+ for (let i = 0; i < maxLen; i++) {
183
+ const av = Number.isFinite(aDecParts[i]) ? aDecParts[i] : 0;
184
+ const bv = Number.isFinite(bDecParts[i]) ? bDecParts[i] : 0;
185
+ if (av !== bv) return av - bv;
186
+ }
187
+ return 0;
188
+ }
189
+
190
+ function searchPhaseInDir(baseDir, relBase, normalized) {
191
+ try {
192
+ const entries = fs.readdirSync(baseDir, { withFileTypes: true });
193
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
194
+ const match = dirs.find(d => d.startsWith(normalized));
195
+ if (!match) return null;
196
+
197
+ const dirMatch = match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
198
+ const phaseNumber = dirMatch ? dirMatch[1] : normalized;
199
+ const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
200
+ const phaseDir = path.join(baseDir, match);
201
+ const phaseFiles = fs.readdirSync(phaseDir);
202
+
203
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').sort();
204
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').sort();
205
+ const hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');
206
+ const hasContext = phaseFiles.some(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');
207
+ const hasVerification = phaseFiles.some(f => f.endsWith('-VERIFICATION.md') || f === 'VERIFICATION.md');
208
+
209
+ const completedPlanIds = new Set(
210
+ summaries.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', ''))
211
+ );
212
+ const incompletePlans = plans.filter(p => {
213
+ const planId = p.replace('-PLAN.md', '').replace('PLAN.md', '');
214
+ return !completedPlanIds.has(planId);
215
+ });
216
+
217
+ return {
218
+ found: true,
219
+ directory: toPosixPath(path.join(relBase, match)),
220
+ phase_number: phaseNumber,
221
+ phase_name: phaseName,
222
+ phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
223
+ plans,
224
+ summaries,
225
+ incomplete_plans: incompletePlans,
226
+ has_research: hasResearch,
227
+ has_context: hasContext,
228
+ has_verification: hasVerification,
229
+ };
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+
235
+ function findPhaseInternal(cwd, phase) {
236
+ if (!phase) return null;
237
+
238
+ const phasesDir = path.join(cwd, '.planning', 'phases');
239
+ const normalized = normalizePhaseName(phase);
240
+
241
+ // Search current phases first
242
+ const current = searchPhaseInDir(phasesDir, '.planning/phases', normalized);
243
+ if (current) return current;
244
+
245
+ // Search archived milestone phases (newest first)
246
+ const milestonesDir = path.join(cwd, '.planning', 'milestones');
247
+ if (!fs.existsSync(milestonesDir)) return null;
248
+
249
+ try {
250
+ const milestoneEntries = fs.readdirSync(milestonesDir, { withFileTypes: true });
251
+ const archiveDirs = milestoneEntries
252
+ .filter(e => e.isDirectory() && /^v[\d.]+-phases$/.test(e.name))
253
+ .map(e => e.name)
254
+ .sort()
255
+ .reverse();
256
+
257
+ for (const archiveName of archiveDirs) {
258
+ const version = archiveName.match(/^(v[\d.]+)-phases$/)[1];
259
+ const archivePath = path.join(milestonesDir, archiveName);
260
+ const relBase = '.planning/milestones/' + archiveName;
261
+ const result = searchPhaseInDir(archivePath, relBase, normalized);
262
+ if (result) {
263
+ result.archived = version;
264
+ return result;
265
+ }
266
+ }
267
+ } catch {}
268
+
269
+ return null;
270
+ }
271
+
272
+ function getArchivedPhaseDirs(cwd) {
273
+ const milestonesDir = path.join(cwd, '.planning', 'milestones');
274
+ const results = [];
275
+
276
+ if (!fs.existsSync(milestonesDir)) return results;
277
+
278
+ try {
279
+ const milestoneEntries = fs.readdirSync(milestonesDir, { withFileTypes: true });
280
+ // Find v*-phases directories, sort newest first
281
+ const phaseDirs = milestoneEntries
282
+ .filter(e => e.isDirectory() && /^v[\d.]+-phases$/.test(e.name))
283
+ .map(e => e.name)
284
+ .sort()
285
+ .reverse();
286
+
287
+ for (const archiveName of phaseDirs) {
288
+ const version = archiveName.match(/^(v[\d.]+)-phases$/)[1];
289
+ const archivePath = path.join(milestonesDir, archiveName);
290
+ const entries = fs.readdirSync(archivePath, { withFileTypes: true });
291
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
292
+
293
+ for (const dir of dirs) {
294
+ results.push({
295
+ name: dir,
296
+ milestone: version,
297
+ basePath: path.join('.planning', 'milestones', archiveName),
298
+ fullPath: path.join(archivePath, dir),
299
+ });
300
+ }
301
+ }
302
+ } catch {}
303
+
304
+ return results;
305
+ }
306
+
307
+ // ─── Roadmap milestone scoping ───────────────────────────────────────────────
308
+
309
+ /**
310
+ * Strip shipped milestone content wrapped in <details> blocks.
311
+ * Used to isolate current milestone phases when searching ROADMAP.md
312
+ * for phase headings or checkboxes — prevents matching archived milestone
313
+ * phases that share the same numbers as current milestone phases.
314
+ */
315
+ function stripShippedMilestones(content) {
316
+ return content.replace(/<details>[\s\S]*?<\/details>/gi, '');
317
+ }
318
+
319
+ /**
320
+ * Replace a pattern only in the current milestone section of ROADMAP.md
321
+ * (everything after the last </details> close tag). Used for write operations
322
+ * that must not accidentally modify archived milestone checkboxes/tables.
323
+ */
324
+ function replaceInCurrentMilestone(content, pattern, replacement) {
325
+ const lastDetailsClose = content.lastIndexOf('</details>');
326
+ if (lastDetailsClose === -1) {
327
+ return content.replace(pattern, replacement);
328
+ }
329
+ const offset = lastDetailsClose + '</details>'.length;
330
+ const before = content.slice(0, offset);
331
+ const after = content.slice(offset);
332
+ return before + after.replace(pattern, replacement);
333
+ }
334
+
335
+ // ─── Roadmap & model utilities ────────────────────────────────────────────────
336
+
337
+ function getRoadmapPhaseInternal(cwd, phaseNum) {
338
+ if (!phaseNum) return null;
339
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
340
+ if (!fs.existsSync(roadmapPath)) return null;
341
+
342
+ try {
343
+ const content = stripShippedMilestones(fs.readFileSync(roadmapPath, 'utf-8'));
344
+ const escapedPhase = escapeRegex(phaseNum.toString());
345
+ const phasePattern = new RegExp(`#{2,4}\\s*Phase\\s+${escapedPhase}:\\s*([^\\n]+)`, 'i');
346
+ const headerMatch = content.match(phasePattern);
347
+ if (!headerMatch) return null;
348
+
349
+ const phaseName = headerMatch[1].trim();
350
+ const headerIndex = headerMatch.index;
351
+ const restOfContent = content.slice(headerIndex);
352
+ const nextHeaderMatch = restOfContent.match(/\n#{2,4}\s+Phase\s+\d/i);
353
+ const sectionEnd = nextHeaderMatch ? headerIndex + nextHeaderMatch.index : content.length;
354
+ const section = content.slice(headerIndex, sectionEnd).trim();
355
+
356
+ const goalMatch = section.match(/\*\*Goal(?:\*\*:|\*?\*?:\*\*)\s*([^\n]+)/i);
357
+ const goal = goalMatch ? goalMatch[1].trim() : null;
358
+
359
+ return {
360
+ found: true,
361
+ phase_number: phaseNum.toString(),
362
+ phase_name: phaseName,
363
+ goal,
364
+ section,
365
+ };
366
+ } catch {
367
+ return null;
368
+ }
369
+ }
370
+
371
+ function resolveModelInternal(cwd, agentType) {
372
+ const config = loadConfig(cwd);
373
+
374
+ // Check per-agent override first
375
+ const override = config.model_overrides?.[agentType];
376
+ if (override) {
377
+ return override;
378
+ }
379
+
380
+ // Fall back to profile lookup
381
+ const profile = String(config.model_profile || 'balanced').toLowerCase();
382
+ const agentModels = MODEL_PROFILES[agentType];
383
+ if (!agentModels) return 'sonnet';
384
+ if (profile === 'inherit') return 'inherit';
385
+ return agentModels[profile] || agentModels['balanced'] || 'sonnet';
386
+ }
387
+
388
+ // ─── Misc utilities ───────────────────────────────────────────────────────────
389
+
390
+ function pathExistsInternal(cwd, targetPath) {
391
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
392
+ try {
393
+ fs.statSync(fullPath);
394
+ return true;
395
+ } catch {
396
+ return false;
397
+ }
398
+ }
399
+
400
+ function generateSlugInternal(text) {
401
+ if (!text) return null;
402
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
403
+ }
404
+
405
+ function getMilestoneInfo(cwd) {
406
+ try {
407
+ const roadmap = fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8');
408
+
409
+ // First: check for list-format roadmaps using 🚧 (in-progress) marker
410
+ // e.g. "- 🚧 **v2.1 Belgium** — Phases 24-28 (in progress)"
411
+ const inProgressMatch = roadmap.match(/🚧\s*\*\*v(\d+\.\d+)\s+([^*]+)\*\*/);
412
+ if (inProgressMatch) {
413
+ return {
414
+ version: 'v' + inProgressMatch[1],
415
+ name: inProgressMatch[2].trim(),
416
+ };
417
+ }
418
+
419
+ // Second: heading-format roadmaps — strip shipped milestones in <details> blocks
420
+ const cleaned = stripShippedMilestones(roadmap);
421
+ // Extract version and name from the same ## heading for consistency
422
+ const headingMatch = cleaned.match(/## .*v(\d+\.\d+)[:\s]+([^\n(]+)/);
423
+ if (headingMatch) {
424
+ return {
425
+ version: 'v' + headingMatch[1],
426
+ name: headingMatch[2].trim(),
427
+ };
428
+ }
429
+ // Fallback: try bare version match
430
+ const versionMatch = cleaned.match(/v(\d+\.\d+)/);
431
+ return {
432
+ version: versionMatch ? versionMatch[0] : 'v1.0',
433
+ name: 'milestone',
434
+ };
435
+ } catch {
436
+ return { version: 'v1.0', name: 'milestone' };
437
+ }
438
+ }
439
+
440
+ /**
441
+ * Returns a filter function that checks whether a phase directory belongs
442
+ * to the current milestone based on ROADMAP.md phase headings.
443
+ * If no ROADMAP exists or no phases are listed, returns a pass-all filter.
444
+ */
445
+ function getMilestonePhaseFilter(cwd) {
446
+ const milestonePhaseNums = new Set();
447
+ try {
448
+ const roadmap = stripShippedMilestones(fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8'));
449
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
450
+ let m;
451
+ while ((m = phasePattern.exec(roadmap)) !== null) {
452
+ milestonePhaseNums.add(m[1]);
453
+ }
454
+ } catch {}
455
+
456
+ if (milestonePhaseNums.size === 0) {
457
+ const passAll = () => true;
458
+ passAll.phaseCount = 0;
459
+ return passAll;
460
+ }
461
+
462
+ const normalized = new Set(
463
+ [...milestonePhaseNums].map(n => (n.replace(/^0+/, '') || '0').toLowerCase())
464
+ );
465
+
466
+ function isDirInMilestone(dirName) {
467
+ const m = dirName.match(/^0*(\d+[A-Za-z]?(?:\.\d+)*)/);
468
+ if (!m) return false;
469
+ return normalized.has(m[1].toLowerCase());
470
+ }
471
+ isDirInMilestone.phaseCount = milestonePhaseNums.size;
472
+ return isDirInMilestone;
473
+ }
474
+
475
+ module.exports = {
476
+ output,
477
+ error,
478
+ safeReadFile,
479
+ loadConfig,
480
+ isGitIgnored,
481
+ execGit,
482
+ escapeRegex,
483
+ normalizePhaseName,
484
+ comparePhaseNum,
485
+ searchPhaseInDir,
486
+ findPhaseInternal,
487
+ getArchivedPhaseDirs,
488
+ getRoadmapPhaseInternal,
489
+ resolveModelInternal,
490
+ pathExistsInternal,
491
+ generateSlugInternal,
492
+ getMilestoneInfo,
493
+ getMilestonePhaseFilter,
494
+ stripShippedMilestones,
495
+ replaceInCurrentMilestone,
496
+ toPosixPath,
497
+ };