@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,820 +1,820 @@
1
- /**
2
- * Verify — Verification suite, consistency, and health validation
3
- */
4
-
5
- const fs = require('fs');
6
- const path = require('path');
7
- const { safeReadFile, normalizePhaseName, execGit, findPhaseInternal, getMilestoneInfo, output, error } = require('./core.cjs');
8
- const { extractFrontmatter, parseMustHavesBlock } = require('./frontmatter.cjs');
9
- const { writeStateMd } = require('./state.cjs');
10
-
11
- function cmdVerifySummary(cwd, summaryPath, checkFileCount, raw) {
12
- if (!summaryPath) {
13
- error('summary-path required');
14
- }
15
-
16
- const fullPath = path.join(cwd, summaryPath);
17
- const checkCount = checkFileCount || 2;
18
-
19
- // Check 1: Summary exists
20
- if (!fs.existsSync(fullPath)) {
21
- const result = {
22
- passed: false,
23
- checks: {
24
- summary_exists: false,
25
- files_created: { checked: 0, found: 0, missing: [] },
26
- commits_exist: false,
27
- self_check: 'not_found',
28
- },
29
- errors: ['SUMMARY.md not found'],
30
- };
31
- output(result, raw, 'failed');
32
- return;
33
- }
34
-
35
- const content = fs.readFileSync(fullPath, 'utf-8');
36
- const errors = [];
37
-
38
- // Check 2: Spot-check files mentioned in summary
39
- const mentionedFiles = new Set();
40
- const patterns = [
41
- /`([^`]+\.[a-zA-Z]+)`/g,
42
- /(?:Created|Modified|Added|Updated|Edited):\s*`?([^\s`]+\.[a-zA-Z]+)`?/gi,
43
- ];
44
-
45
- for (const pattern of patterns) {
46
- let m;
47
- while ((m = pattern.exec(content)) !== null) {
48
- const filePath = m[1];
49
- if (filePath && !filePath.startsWith('http') && filePath.includes('/')) {
50
- mentionedFiles.add(filePath);
51
- }
52
- }
53
- }
54
-
55
- const filesToCheck = Array.from(mentionedFiles).slice(0, checkCount);
56
- const missing = [];
57
- for (const file of filesToCheck) {
58
- if (!fs.existsSync(path.join(cwd, file))) {
59
- missing.push(file);
60
- }
61
- }
62
-
63
- // Check 3: Commits exist
64
- const commitHashPattern = /\b[0-9a-f]{7,40}\b/g;
65
- const hashes = content.match(commitHashPattern) || [];
66
- let commitsExist = false;
67
- if (hashes.length > 0) {
68
- for (const hash of hashes.slice(0, 3)) {
69
- const result = execGit(cwd, ['cat-file', '-t', hash]);
70
- if (result.exitCode === 0 && result.stdout === 'commit') {
71
- commitsExist = true;
72
- break;
73
- }
74
- }
75
- }
76
-
77
- // Check 4: Self-check section
78
- let selfCheck = 'not_found';
79
- const selfCheckPattern = /##\s*(?:Self[- ]?Check|Verification|Quality Check)/i;
80
- if (selfCheckPattern.test(content)) {
81
- const passPattern = /(?:all\s+)?(?:pass|✓|✅|complete|succeeded)/i;
82
- const failPattern = /(?:fail|✗|❌|incomplete|blocked)/i;
83
- const checkSection = content.slice(content.search(selfCheckPattern));
84
- if (failPattern.test(checkSection)) {
85
- selfCheck = 'failed';
86
- } else if (passPattern.test(checkSection)) {
87
- selfCheck = 'passed';
88
- }
89
- }
90
-
91
- if (missing.length > 0) errors.push('Missing files: ' + missing.join(', '));
92
- if (!commitsExist && hashes.length > 0) errors.push('Referenced commit hashes not found in git history');
93
- if (selfCheck === 'failed') errors.push('Self-check section indicates failure');
94
-
95
- const checks = {
96
- summary_exists: true,
97
- files_created: { checked: filesToCheck.length, found: filesToCheck.length - missing.length, missing },
98
- commits_exist: commitsExist,
99
- self_check: selfCheck,
100
- };
101
-
102
- const passed = missing.length === 0 && selfCheck !== 'failed';
103
- const result = { passed, checks, errors };
104
- output(result, raw, passed ? 'passed' : 'failed');
105
- }
106
-
107
- function cmdVerifyPlanStructure(cwd, filePath, raw) {
108
- if (!filePath) { error('file path required'); }
109
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
110
- const content = safeReadFile(fullPath);
111
- if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
112
-
113
- const fm = extractFrontmatter(content);
114
- const errors = [];
115
- const warnings = [];
116
-
117
- // Check required frontmatter fields
118
- const required = ['phase', 'plan', 'type', 'wave', 'depends_on', 'files_modified', 'autonomous', 'must_haves'];
119
- for (const field of required) {
120
- if (fm[field] === undefined) errors.push(`Missing required frontmatter field: ${field}`);
121
- }
122
-
123
- // Parse and check task elements
124
- const taskPattern = /<task[^>]*>([\s\S]*?)<\/task>/g;
125
- const tasks = [];
126
- let taskMatch;
127
- while ((taskMatch = taskPattern.exec(content)) !== null) {
128
- const taskContent = taskMatch[1];
129
- const nameMatch = taskContent.match(/<name>([\s\S]*?)<\/name>/);
130
- const taskName = nameMatch ? nameMatch[1].trim() : 'unnamed';
131
- const hasFiles = /<files>/.test(taskContent);
132
- const hasAction = /<action>/.test(taskContent);
133
- const hasVerify = /<verify>/.test(taskContent);
134
- const hasDone = /<done>/.test(taskContent);
135
-
136
- if (!nameMatch) errors.push('Task missing <name> element');
137
- if (!hasAction) errors.push(`Task '${taskName}' missing <action>`);
138
- if (!hasVerify) warnings.push(`Task '${taskName}' missing <verify>`);
139
- if (!hasDone) warnings.push(`Task '${taskName}' missing <done>`);
140
- if (!hasFiles) warnings.push(`Task '${taskName}' missing <files>`);
141
-
142
- tasks.push({ name: taskName, hasFiles, hasAction, hasVerify, hasDone });
143
- }
144
-
145
- if (tasks.length === 0) warnings.push('No <task> elements found');
146
-
147
- // Wave/depends_on consistency
148
- if (fm.wave && parseInt(fm.wave) > 1 && (!fm.depends_on || (Array.isArray(fm.depends_on) && fm.depends_on.length === 0))) {
149
- warnings.push('Wave > 1 but depends_on is empty');
150
- }
151
-
152
- // Autonomous/checkpoint consistency
153
- const hasCheckpoints = /<task\s+type=["']?checkpoint/.test(content);
154
- if (hasCheckpoints && fm.autonomous !== 'false' && fm.autonomous !== false) {
155
- errors.push('Has checkpoint tasks but autonomous is not false');
156
- }
157
-
158
- output({
159
- valid: errors.length === 0,
160
- errors,
161
- warnings,
162
- task_count: tasks.length,
163
- tasks,
164
- frontmatter_fields: Object.keys(fm),
165
- }, raw, errors.length === 0 ? 'valid' : 'invalid');
166
- }
167
-
168
- function cmdVerifyPhaseCompleteness(cwd, phase, raw) {
169
- if (!phase) { error('phase required'); }
170
- const phaseInfo = findPhaseInternal(cwd, phase);
171
- if (!phaseInfo || !phaseInfo.found) {
172
- output({ error: 'Phase not found', phase }, raw);
173
- return;
174
- }
175
-
176
- const errors = [];
177
- const warnings = [];
178
- const phaseDir = path.join(cwd, phaseInfo.directory);
179
-
180
- // List plans and summaries
181
- let files;
182
- try { files = fs.readdirSync(phaseDir); } catch { output({ error: 'Cannot read phase directory' }, raw); return; }
183
-
184
- const plans = files.filter(f => f.match(/-PLAN\.md$/i));
185
- const summaries = files.filter(f => f.match(/-SUMMARY\.md$/i));
186
-
187
- // Extract plan IDs (everything before -PLAN.md)
188
- const planIds = new Set(plans.map(p => p.replace(/-PLAN\.md$/i, '')));
189
- const summaryIds = new Set(summaries.map(s => s.replace(/-SUMMARY\.md$/i, '')));
190
-
191
- // Plans without summaries
192
- const incompletePlans = [...planIds].filter(id => !summaryIds.has(id));
193
- if (incompletePlans.length > 0) {
194
- errors.push(`Plans without summaries: ${incompletePlans.join(', ')}`);
195
- }
196
-
197
- // Summaries without plans (orphans)
198
- const orphanSummaries = [...summaryIds].filter(id => !planIds.has(id));
199
- if (orphanSummaries.length > 0) {
200
- warnings.push(`Summaries without plans: ${orphanSummaries.join(', ')}`);
201
- }
202
-
203
- output({
204
- complete: errors.length === 0,
205
- phase: phaseInfo.phase_number,
206
- plan_count: plans.length,
207
- summary_count: summaries.length,
208
- incomplete_plans: incompletePlans,
209
- orphan_summaries: orphanSummaries,
210
- errors,
211
- warnings,
212
- }, raw, errors.length === 0 ? 'complete' : 'incomplete');
213
- }
214
-
215
- function cmdVerifyReferences(cwd, filePath, raw) {
216
- if (!filePath) { error('file path required'); }
217
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
218
- const content = safeReadFile(fullPath);
219
- if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
220
-
221
- const found = [];
222
- const missing = [];
223
-
224
- // Find @-references: @path/to/file (must contain / to be a file path)
225
- const atRefs = content.match(/@([^\s\n,)]+\/[^\s\n,)]+)/g) || [];
226
- for (const ref of atRefs) {
227
- const cleanRef = ref.slice(1); // remove @
228
- const resolved = cleanRef.startsWith('~/')
229
- ? path.join(process.env.HOME || '', cleanRef.slice(2))
230
- : path.join(cwd, cleanRef);
231
- if (fs.existsSync(resolved)) {
232
- found.push(cleanRef);
233
- } else {
234
- missing.push(cleanRef);
235
- }
236
- }
237
-
238
- // Find backtick file paths that look like real paths (contain / and have extension)
239
- const backtickRefs = content.match(/`([^`]+\/[^`]+\.[a-zA-Z]{1,10})`/g) || [];
240
- for (const ref of backtickRefs) {
241
- const cleanRef = ref.slice(1, -1); // remove backticks
242
- if (cleanRef.startsWith('http') || cleanRef.includes('${') || cleanRef.includes('{{')) continue;
243
- if (found.includes(cleanRef) || missing.includes(cleanRef)) continue; // dedup
244
- const resolved = path.join(cwd, cleanRef);
245
- if (fs.existsSync(resolved)) {
246
- found.push(cleanRef);
247
- } else {
248
- missing.push(cleanRef);
249
- }
250
- }
251
-
252
- output({
253
- valid: missing.length === 0,
254
- found: found.length,
255
- missing,
256
- total: found.length + missing.length,
257
- }, raw, missing.length === 0 ? 'valid' : 'invalid');
258
- }
259
-
260
- function cmdVerifyCommits(cwd, hashes, raw) {
261
- if (!hashes || hashes.length === 0) { error('At least one commit hash required'); }
262
-
263
- const valid = [];
264
- const invalid = [];
265
- for (const hash of hashes) {
266
- const result = execGit(cwd, ['cat-file', '-t', hash]);
267
- if (result.exitCode === 0 && result.stdout.trim() === 'commit') {
268
- valid.push(hash);
269
- } else {
270
- invalid.push(hash);
271
- }
272
- }
273
-
274
- output({
275
- all_valid: invalid.length === 0,
276
- valid,
277
- invalid,
278
- total: hashes.length,
279
- }, raw, invalid.length === 0 ? 'valid' : 'invalid');
280
- }
281
-
282
- function cmdVerifyArtifacts(cwd, planFilePath, raw) {
283
- if (!planFilePath) { error('plan file path required'); }
284
- const fullPath = path.isAbsolute(planFilePath) ? planFilePath : path.join(cwd, planFilePath);
285
- const content = safeReadFile(fullPath);
286
- if (!content) { output({ error: 'File not found', path: planFilePath }, raw); return; }
287
-
288
- const artifacts = parseMustHavesBlock(content, 'artifacts');
289
- if (artifacts.length === 0) {
290
- output({ error: 'No must_haves.artifacts found in frontmatter', path: planFilePath }, raw);
291
- return;
292
- }
293
-
294
- const results = [];
295
- for (const artifact of artifacts) {
296
- if (typeof artifact === 'string') continue; // skip simple string items
297
- const artPath = artifact.path;
298
- if (!artPath) continue;
299
-
300
- const artFullPath = path.join(cwd, artPath);
301
- const exists = fs.existsSync(artFullPath);
302
- const check = { path: artPath, exists, issues: [], passed: false };
303
-
304
- if (exists) {
305
- const fileContent = safeReadFile(artFullPath) || '';
306
- const lineCount = fileContent.split('\n').length;
307
-
308
- if (artifact.min_lines && lineCount < artifact.min_lines) {
309
- check.issues.push(`Only ${lineCount} lines, need ${artifact.min_lines}`);
310
- }
311
- if (artifact.contains && !fileContent.includes(artifact.contains)) {
312
- check.issues.push(`Missing pattern: ${artifact.contains}`);
313
- }
314
- if (artifact.exports) {
315
- const exports = Array.isArray(artifact.exports) ? artifact.exports : [artifact.exports];
316
- for (const exp of exports) {
317
- if (!fileContent.includes(exp)) check.issues.push(`Missing export: ${exp}`);
318
- }
319
- }
320
- check.passed = check.issues.length === 0;
321
- } else {
322
- check.issues.push('File not found');
323
- }
324
-
325
- results.push(check);
326
- }
327
-
328
- const passed = results.filter(r => r.passed).length;
329
- output({
330
- all_passed: passed === results.length,
331
- passed,
332
- total: results.length,
333
- artifacts: results,
334
- }, raw, passed === results.length ? 'valid' : 'invalid');
335
- }
336
-
337
- function cmdVerifyKeyLinks(cwd, planFilePath, raw) {
338
- if (!planFilePath) { error('plan file path required'); }
339
- const fullPath = path.isAbsolute(planFilePath) ? planFilePath : path.join(cwd, planFilePath);
340
- const content = safeReadFile(fullPath);
341
- if (!content) { output({ error: 'File not found', path: planFilePath }, raw); return; }
342
-
343
- const keyLinks = parseMustHavesBlock(content, 'key_links');
344
- if (keyLinks.length === 0) {
345
- output({ error: 'No must_haves.key_links found in frontmatter', path: planFilePath }, raw);
346
- return;
347
- }
348
-
349
- const results = [];
350
- for (const link of keyLinks) {
351
- if (typeof link === 'string') continue;
352
- const check = { from: link.from, to: link.to, via: link.via || '', verified: false, detail: '' };
353
-
354
- const sourceContent = safeReadFile(path.join(cwd, link.from || ''));
355
- if (!sourceContent) {
356
- check.detail = 'Source file not found';
357
- } else if (link.pattern) {
358
- try {
359
- const regex = new RegExp(link.pattern);
360
- if (regex.test(sourceContent)) {
361
- check.verified = true;
362
- check.detail = 'Pattern found in source';
363
- } else {
364
- const targetContent = safeReadFile(path.join(cwd, link.to || ''));
365
- if (targetContent && regex.test(targetContent)) {
366
- check.verified = true;
367
- check.detail = 'Pattern found in target';
368
- } else {
369
- check.detail = `Pattern "${link.pattern}" not found in source or target`;
370
- }
371
- }
372
- } catch {
373
- check.detail = `Invalid regex pattern: ${link.pattern}`;
374
- }
375
- } else {
376
- // No pattern: just check source references target
377
- if (sourceContent.includes(link.to || '')) {
378
- check.verified = true;
379
- check.detail = 'Target referenced in source';
380
- } else {
381
- check.detail = 'Target not referenced in source';
382
- }
383
- }
384
-
385
- results.push(check);
386
- }
387
-
388
- const verified = results.filter(r => r.verified).length;
389
- output({
390
- all_verified: verified === results.length,
391
- verified,
392
- total: results.length,
393
- links: results,
394
- }, raw, verified === results.length ? 'valid' : 'invalid');
395
- }
396
-
397
- function cmdValidateConsistency(cwd, raw) {
398
- const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
399
- const phasesDir = path.join(cwd, '.planning', 'phases');
400
- const errors = [];
401
- const warnings = [];
402
-
403
- // Check for ROADMAP
404
- if (!fs.existsSync(roadmapPath)) {
405
- errors.push('ROADMAP.md not found');
406
- output({ passed: false, errors, warnings }, raw, 'failed');
407
- return;
408
- }
409
-
410
- const roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
411
-
412
- // Extract phases from ROADMAP
413
- const roadmapPhases = new Set();
414
- const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
415
- let m;
416
- while ((m = phasePattern.exec(roadmapContent)) !== null) {
417
- roadmapPhases.add(m[1]);
418
- }
419
-
420
- // Get phases on disk
421
- const diskPhases = new Set();
422
- try {
423
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
424
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
425
- for (const dir of dirs) {
426
- const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)/i);
427
- if (dm) diskPhases.add(dm[1]);
428
- }
429
- } catch {}
430
-
431
- // Check: phases in ROADMAP but not on disk
432
- for (const p of roadmapPhases) {
433
- if (!diskPhases.has(p) && !diskPhases.has(normalizePhaseName(p))) {
434
- warnings.push(`Phase ${p} in ROADMAP.md but no directory on disk`);
435
- }
436
- }
437
-
438
- // Check: phases on disk but not in ROADMAP
439
- for (const p of diskPhases) {
440
- const unpadded = String(parseInt(p, 10));
441
- if (!roadmapPhases.has(p) && !roadmapPhases.has(unpadded)) {
442
- warnings.push(`Phase ${p} exists on disk but not in ROADMAP.md`);
443
- }
444
- }
445
-
446
- // Check: sequential phase numbers (integers only)
447
- const integerPhases = [...diskPhases]
448
- .filter(p => !p.includes('.'))
449
- .map(p => parseInt(p, 10))
450
- .sort((a, b) => a - b);
451
-
452
- for (let i = 1; i < integerPhases.length; i++) {
453
- if (integerPhases[i] !== integerPhases[i - 1] + 1) {
454
- warnings.push(`Gap in phase numbering: ${integerPhases[i - 1]} → ${integerPhases[i]}`);
455
- }
456
- }
457
-
458
- // Check: plan numbering within phases
459
- try {
460
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
461
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort();
462
-
463
- for (const dir of dirs) {
464
- const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
465
- const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md')).sort();
466
-
467
- // Extract plan numbers
468
- const planNums = plans.map(p => {
469
- const pm = p.match(/-(\d{2})-PLAN\.md$/);
470
- return pm ? parseInt(pm[1], 10) : null;
471
- }).filter(n => n !== null);
472
-
473
- for (let i = 1; i < planNums.length; i++) {
474
- if (planNums[i] !== planNums[i - 1] + 1) {
475
- warnings.push(`Gap in plan numbering in ${dir}: plan ${planNums[i - 1]} → ${planNums[i]}`);
476
- }
477
- }
478
-
479
- // Check: plans without summaries (completed plans)
480
- const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md'));
481
- const planIds = new Set(plans.map(p => p.replace('-PLAN.md', '')));
482
- const summaryIds = new Set(summaries.map(s => s.replace('-SUMMARY.md', '')));
483
-
484
- // Summary without matching plan is suspicious
485
- for (const sid of summaryIds) {
486
- if (!planIds.has(sid)) {
487
- warnings.push(`Summary ${sid}-SUMMARY.md in ${dir} has no matching PLAN.md`);
488
- }
489
- }
490
- }
491
- } catch {}
492
-
493
- // Check: frontmatter in plans has required fields
494
- try {
495
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
496
- const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
497
-
498
- for (const dir of dirs) {
499
- const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
500
- const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md'));
501
-
502
- for (const plan of plans) {
503
- const content = fs.readFileSync(path.join(phasesDir, dir, plan), 'utf-8');
504
- const fm = extractFrontmatter(content);
505
-
506
- if (!fm.wave) {
507
- warnings.push(`${dir}/${plan}: missing 'wave' in frontmatter`);
508
- }
509
- }
510
- }
511
- } catch {}
512
-
513
- const passed = errors.length === 0;
514
- output({ passed, errors, warnings, warning_count: warnings.length }, raw, passed ? 'passed' : 'failed');
515
- }
516
-
517
- function cmdValidateHealth(cwd, options, raw) {
518
- const planningDir = path.join(cwd, '.planning');
519
- const projectPath = path.join(planningDir, 'PROJECT.md');
520
- const roadmapPath = path.join(planningDir, 'ROADMAP.md');
521
- const statePath = path.join(planningDir, 'STATE.md');
522
- const configPath = path.join(planningDir, 'config.json');
523
- const phasesDir = path.join(planningDir, 'phases');
524
-
525
- const errors = [];
526
- const warnings = [];
527
- const info = [];
528
- const repairs = [];
529
-
530
- // Helper to add issue
531
- const addIssue = (severity, code, message, fix, repairable = false) => {
532
- const issue = { code, message, fix, repairable };
533
- if (severity === 'error') errors.push(issue);
534
- else if (severity === 'warning') warnings.push(issue);
535
- else info.push(issue);
536
- };
537
-
538
- // ─── Check 1: .planning/ exists ───────────────────────────────────────────
539
- if (!fs.existsSync(planningDir)) {
540
- addIssue('error', 'E001', '.planning/ directory not found', 'Run /gsd:new-project to initialize');
541
- output({
542
- status: 'broken',
543
- errors,
544
- warnings,
545
- info,
546
- repairable_count: 0,
547
- }, raw);
548
- return;
549
- }
550
-
551
- // ─── Check 2: PROJECT.md exists and has required sections ─────────────────
552
- if (!fs.existsSync(projectPath)) {
553
- addIssue('error', 'E002', 'PROJECT.md not found', 'Run /gsd:new-project to create');
554
- } else {
555
- const content = fs.readFileSync(projectPath, 'utf-8');
556
- const requiredSections = ['## What This Is', '## Core Value', '## Requirements'];
557
- for (const section of requiredSections) {
558
- if (!content.includes(section)) {
559
- addIssue('warning', 'W001', `PROJECT.md missing section: ${section}`, 'Add section manually');
560
- }
561
- }
562
- }
563
-
564
- // ─── Check 3: ROADMAP.md exists ───────────────────────────────────────────
565
- if (!fs.existsSync(roadmapPath)) {
566
- addIssue('error', 'E003', 'ROADMAP.md not found', 'Run /gsd:new-milestone to create roadmap');
567
- }
568
-
569
- // ─── Check 4: STATE.md exists and references valid phases ─────────────────
570
- if (!fs.existsSync(statePath)) {
571
- addIssue('error', 'E004', 'STATE.md not found', 'Run /gsd:health --repair to regenerate', true);
572
- repairs.push('regenerateState');
573
- } else {
574
- const stateContent = fs.readFileSync(statePath, 'utf-8');
575
- // Extract phase references from STATE.md
576
- const phaseRefs = [...stateContent.matchAll(/[Pp]hase\s+(\d+(?:\.\d+)*)/g)].map(m => m[1]);
577
- // Get disk phases
578
- const diskPhases = new Set();
579
- try {
580
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
581
- for (const e of entries) {
582
- if (e.isDirectory()) {
583
- const m = e.name.match(/^(\d+(?:\.\d+)*)/);
584
- if (m) diskPhases.add(m[1]);
585
- }
586
- }
587
- } catch {}
588
- // Check for invalid references
589
- for (const ref of phaseRefs) {
590
- const normalizedRef = String(parseInt(ref, 10)).padStart(2, '0');
591
- if (!diskPhases.has(ref) && !diskPhases.has(normalizedRef) && !diskPhases.has(String(parseInt(ref, 10)))) {
592
- // Only warn if phases dir has any content (not just an empty project)
593
- if (diskPhases.size > 0) {
594
- addIssue('warning', 'W002', `STATE.md references phase ${ref}, but only phases ${[...diskPhases].sort().join(', ')} exist`, 'Run /gsd:health --repair to regenerate STATE.md', true);
595
- if (!repairs.includes('regenerateState')) repairs.push('regenerateState');
596
- }
597
- }
598
- }
599
- }
600
-
601
- // ─── Check 5: config.json valid JSON + valid schema ───────────────────────
602
- if (!fs.existsSync(configPath)) {
603
- addIssue('warning', 'W003', 'config.json not found', 'Run /gsd:health --repair to create with defaults', true);
604
- repairs.push('createConfig');
605
- } else {
606
- try {
607
- const raw = fs.readFileSync(configPath, 'utf-8');
608
- const parsed = JSON.parse(raw);
609
- // Validate known fields
610
- const validProfiles = ['quality', 'balanced', 'budget'];
611
- if (parsed.model_profile && !validProfiles.includes(parsed.model_profile)) {
612
- addIssue('warning', 'W004', `config.json: invalid model_profile "${parsed.model_profile}"`, `Valid values: ${validProfiles.join(', ')}`);
613
- }
614
- } catch (err) {
615
- addIssue('error', 'E005', `config.json: JSON parse error - ${err.message}`, 'Run /gsd:health --repair to reset to defaults', true);
616
- repairs.push('resetConfig');
617
- }
618
- }
619
-
620
- // ─── Check 5b: Nyquist validation key presence ──────────────────────────
621
- if (fs.existsSync(configPath)) {
622
- try {
623
- const configRaw = fs.readFileSync(configPath, 'utf-8');
624
- const configParsed = JSON.parse(configRaw);
625
- if (configParsed.workflow && configParsed.workflow.nyquist_validation === undefined) {
626
- addIssue('warning', 'W008', 'config.json: workflow.nyquist_validation absent (defaults to enabled but agents may skip)', 'Run /gsd:health --repair to add key', true);
627
- if (!repairs.includes('addNyquistKey')) repairs.push('addNyquistKey');
628
- }
629
- } catch {}
630
- }
631
-
632
- // ─── Check 6: Phase directory naming (NN-name format) ─────────────────────
633
- try {
634
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
635
- for (const e of entries) {
636
- if (e.isDirectory() && !e.name.match(/^\d{2}(?:\.\d+)*-[\w-]+$/)) {
637
- addIssue('warning', 'W005', `Phase directory "${e.name}" doesn't follow NN-name format`, 'Rename to match pattern (e.g., 01-setup)');
638
- }
639
- }
640
- } catch {}
641
-
642
- // ─── Check 7: Orphaned plans (PLAN without SUMMARY) ───────────────────────
643
- try {
644
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
645
- for (const e of entries) {
646
- if (!e.isDirectory()) continue;
647
- const phaseFiles = fs.readdirSync(path.join(phasesDir, e.name));
648
- const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
649
- const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
650
- const summaryBases = new Set(summaries.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', '')));
651
-
652
- for (const plan of plans) {
653
- const planBase = plan.replace('-PLAN.md', '').replace('PLAN.md', '');
654
- if (!summaryBases.has(planBase)) {
655
- addIssue('info', 'I001', `${e.name}/${plan} has no SUMMARY.md`, 'May be in progress');
656
- }
657
- }
658
- }
659
- } catch {}
660
-
661
- // ─── Check 7b: Nyquist VALIDATION.md consistency ────────────────────────
662
- try {
663
- const phaseEntries = fs.readdirSync(phasesDir, { withFileTypes: true });
664
- for (const e of phaseEntries) {
665
- if (!e.isDirectory()) continue;
666
- const phaseFiles = fs.readdirSync(path.join(phasesDir, e.name));
667
- const hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md'));
668
- const hasValidation = phaseFiles.some(f => f.endsWith('-VALIDATION.md'));
669
- if (hasResearch && !hasValidation) {
670
- const researchFile = phaseFiles.find(f => f.endsWith('-RESEARCH.md'));
671
- const researchContent = fs.readFileSync(path.join(phasesDir, e.name, researchFile), 'utf-8');
672
- if (researchContent.includes('## Validation Architecture')) {
673
- addIssue('warning', 'W009', `Phase ${e.name}: has Validation Architecture in RESEARCH.md but no VALIDATION.md`, 'Re-run /gsd:plan-phase with --research to regenerate');
674
- }
675
- }
676
- }
677
- } catch {}
678
-
679
- // ─── Check 8: Run existing consistency checks ─────────────────────────────
680
- // Inline subset of cmdValidateConsistency
681
- if (fs.existsSync(roadmapPath)) {
682
- const roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
683
- const roadmapPhases = new Set();
684
- const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
685
- let m;
686
- while ((m = phasePattern.exec(roadmapContent)) !== null) {
687
- roadmapPhases.add(m[1]);
688
- }
689
-
690
- const diskPhases = new Set();
691
- try {
692
- const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
693
- for (const e of entries) {
694
- if (e.isDirectory()) {
695
- const dm = e.name.match(/^(\d+[A-Z]?(?:\.\d+)*)/i);
696
- if (dm) diskPhases.add(dm[1]);
697
- }
698
- }
699
- } catch {}
700
-
701
- // Phases in ROADMAP but not on disk
702
- for (const p of roadmapPhases) {
703
- const padded = String(parseInt(p, 10)).padStart(2, '0');
704
- if (!diskPhases.has(p) && !diskPhases.has(padded)) {
705
- addIssue('warning', 'W006', `Phase ${p} in ROADMAP.md but no directory on disk`, 'Create phase directory or remove from roadmap');
706
- }
707
- }
708
-
709
- // Phases on disk but not in ROADMAP
710
- for (const p of diskPhases) {
711
- const unpadded = String(parseInt(p, 10));
712
- if (!roadmapPhases.has(p) && !roadmapPhases.has(unpadded)) {
713
- addIssue('warning', 'W007', `Phase ${p} exists on disk but not in ROADMAP.md`, 'Add to roadmap or remove directory');
714
- }
715
- }
716
- }
717
-
718
- // ─── Perform repairs if requested ─────────────────────────────────────────
719
- const repairActions = [];
720
- if (options.repair && repairs.length > 0) {
721
- for (const repair of repairs) {
722
- try {
723
- switch (repair) {
724
- case 'createConfig':
725
- case 'resetConfig': {
726
- const defaults = {
727
- model_profile: 'balanced',
728
- commit_docs: true,
729
- search_gitignored: false,
730
- branching_strategy: 'none',
731
- research: true,
732
- plan_checker: true,
733
- verifier: true,
734
- parallelization: true,
735
- };
736
- fs.writeFileSync(configPath, JSON.stringify(defaults, null, 2), 'utf-8');
737
- repairActions.push({ action: repair, success: true, path: 'config.json' });
738
- break;
739
- }
740
- case 'regenerateState': {
741
- // Create timestamped backup before overwriting
742
- if (fs.existsSync(statePath)) {
743
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
744
- const backupPath = `${statePath}.bak-${timestamp}`;
745
- fs.copyFileSync(statePath, backupPath);
746
- repairActions.push({ action: 'backupState', success: true, path: backupPath });
747
- }
748
- // Generate minimal STATE.md from ROADMAP.md structure
749
- const milestone = getMilestoneInfo(cwd);
750
- let stateContent = `# Session State\n\n`;
751
- stateContent += `## Project Reference\n\n`;
752
- stateContent += `See: .planning/PROJECT.md\n\n`;
753
- stateContent += `## Position\n\n`;
754
- stateContent += `**Milestone:** ${milestone.version} ${milestone.name}\n`;
755
- stateContent += `**Current phase:** (determining...)\n`;
756
- stateContent += `**Status:** Resuming\n\n`;
757
- stateContent += `## Session Log\n\n`;
758
- stateContent += `- ${new Date().toISOString().split('T')[0]}: STATE.md regenerated by /gsd:health --repair\n`;
759
- writeStateMd(statePath, stateContent, cwd);
760
- repairActions.push({ action: repair, success: true, path: 'STATE.md' });
761
- break;
762
- }
763
- case 'addNyquistKey': {
764
- if (fs.existsSync(configPath)) {
765
- try {
766
- const configRaw = fs.readFileSync(configPath, 'utf-8');
767
- const configParsed = JSON.parse(configRaw);
768
- if (!configParsed.workflow) configParsed.workflow = {};
769
- if (configParsed.workflow.nyquist_validation === undefined) {
770
- configParsed.workflow.nyquist_validation = true;
771
- fs.writeFileSync(configPath, JSON.stringify(configParsed, null, 2), 'utf-8');
772
- }
773
- repairActions.push({ action: repair, success: true, path: 'config.json' });
774
- } catch (err) {
775
- repairActions.push({ action: repair, success: false, error: err.message });
776
- }
777
- }
778
- break;
779
- }
780
- }
781
- } catch (err) {
782
- repairActions.push({ action: repair, success: false, error: err.message });
783
- }
784
- }
785
- }
786
-
787
- // ─── Determine overall status ─────────────────────────────────────────────
788
- let status;
789
- if (errors.length > 0) {
790
- status = 'broken';
791
- } else if (warnings.length > 0) {
792
- status = 'degraded';
793
- } else {
794
- status = 'healthy';
795
- }
796
-
797
- const repairableCount = errors.filter(e => e.repairable).length +
798
- warnings.filter(w => w.repairable).length;
799
-
800
- output({
801
- status,
802
- errors,
803
- warnings,
804
- info,
805
- repairable_count: repairableCount,
806
- repairs_performed: repairActions.length > 0 ? repairActions : undefined,
807
- }, raw);
808
- }
809
-
810
- module.exports = {
811
- cmdVerifySummary,
812
- cmdVerifyPlanStructure,
813
- cmdVerifyPhaseCompleteness,
814
- cmdVerifyReferences,
815
- cmdVerifyCommits,
816
- cmdVerifyArtifacts,
817
- cmdVerifyKeyLinks,
818
- cmdValidateConsistency,
819
- cmdValidateHealth,
820
- };
1
+ /**
2
+ * Verify — Verification suite, consistency, and health validation
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { safeReadFile, normalizePhaseName, execGit, findPhaseInternal, getMilestoneInfo, output, error } = require('./core.cjs');
8
+ const { extractFrontmatter, parseMustHavesBlock } = require('./frontmatter.cjs');
9
+ const { writeStateMd } = require('./state.cjs');
10
+
11
+ function cmdVerifySummary(cwd, summaryPath, checkFileCount, raw) {
12
+ if (!summaryPath) {
13
+ error('summary-path required');
14
+ }
15
+
16
+ const fullPath = path.join(cwd, summaryPath);
17
+ const checkCount = checkFileCount || 2;
18
+
19
+ // Check 1: Summary exists
20
+ if (!fs.existsSync(fullPath)) {
21
+ const result = {
22
+ passed: false,
23
+ checks: {
24
+ summary_exists: false,
25
+ files_created: { checked: 0, found: 0, missing: [] },
26
+ commits_exist: false,
27
+ self_check: 'not_found',
28
+ },
29
+ errors: ['SUMMARY.md not found'],
30
+ };
31
+ output(result, raw, 'failed');
32
+ return;
33
+ }
34
+
35
+ const content = fs.readFileSync(fullPath, 'utf-8');
36
+ const errors = [];
37
+
38
+ // Check 2: Spot-check files mentioned in summary
39
+ const mentionedFiles = new Set();
40
+ const patterns = [
41
+ /`([^`]+\.[a-zA-Z]+)`/g,
42
+ /(?:Created|Modified|Added|Updated|Edited):\s*`?([^\s`]+\.[a-zA-Z]+)`?/gi,
43
+ ];
44
+
45
+ for (const pattern of patterns) {
46
+ let m;
47
+ while ((m = pattern.exec(content)) !== null) {
48
+ const filePath = m[1];
49
+ if (filePath && !filePath.startsWith('http') && filePath.includes('/')) {
50
+ mentionedFiles.add(filePath);
51
+ }
52
+ }
53
+ }
54
+
55
+ const filesToCheck = Array.from(mentionedFiles).slice(0, checkCount);
56
+ const missing = [];
57
+ for (const file of filesToCheck) {
58
+ if (!fs.existsSync(path.join(cwd, file))) {
59
+ missing.push(file);
60
+ }
61
+ }
62
+
63
+ // Check 3: Commits exist
64
+ const commitHashPattern = /\b[0-9a-f]{7,40}\b/g;
65
+ const hashes = content.match(commitHashPattern) || [];
66
+ let commitsExist = false;
67
+ if (hashes.length > 0) {
68
+ for (const hash of hashes.slice(0, 3)) {
69
+ const result = execGit(cwd, ['cat-file', '-t', hash]);
70
+ if (result.exitCode === 0 && result.stdout === 'commit') {
71
+ commitsExist = true;
72
+ break;
73
+ }
74
+ }
75
+ }
76
+
77
+ // Check 4: Self-check section
78
+ let selfCheck = 'not_found';
79
+ const selfCheckPattern = /##\s*(?:Self[- ]?Check|Verification|Quality Check)/i;
80
+ if (selfCheckPattern.test(content)) {
81
+ const passPattern = /(?:all\s+)?(?:pass|✓|✅|complete|succeeded)/i;
82
+ const failPattern = /(?:fail|✗|❌|incomplete|blocked)/i;
83
+ const checkSection = content.slice(content.search(selfCheckPattern));
84
+ if (failPattern.test(checkSection)) {
85
+ selfCheck = 'failed';
86
+ } else if (passPattern.test(checkSection)) {
87
+ selfCheck = 'passed';
88
+ }
89
+ }
90
+
91
+ if (missing.length > 0) errors.push('Missing files: ' + missing.join(', '));
92
+ if (!commitsExist && hashes.length > 0) errors.push('Referenced commit hashes not found in git history');
93
+ if (selfCheck === 'failed') errors.push('Self-check section indicates failure');
94
+
95
+ const checks = {
96
+ summary_exists: true,
97
+ files_created: { checked: filesToCheck.length, found: filesToCheck.length - missing.length, missing },
98
+ commits_exist: commitsExist,
99
+ self_check: selfCheck,
100
+ };
101
+
102
+ const passed = missing.length === 0 && selfCheck !== 'failed';
103
+ const result = { passed, checks, errors };
104
+ output(result, raw, passed ? 'passed' : 'failed');
105
+ }
106
+
107
+ function cmdVerifyPlanStructure(cwd, filePath, raw) {
108
+ if (!filePath) { error('file path required'); }
109
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
110
+ const content = safeReadFile(fullPath);
111
+ if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
112
+
113
+ const fm = extractFrontmatter(content);
114
+ const errors = [];
115
+ const warnings = [];
116
+
117
+ // Check required frontmatter fields
118
+ const required = ['phase', 'plan', 'type', 'wave', 'depends_on', 'files_modified', 'autonomous', 'must_haves'];
119
+ for (const field of required) {
120
+ if (fm[field] === undefined) errors.push(`Missing required frontmatter field: ${field}`);
121
+ }
122
+
123
+ // Parse and check task elements
124
+ const taskPattern = /<task[^>]*>([\s\S]*?)<\/task>/g;
125
+ const tasks = [];
126
+ let taskMatch;
127
+ while ((taskMatch = taskPattern.exec(content)) !== null) {
128
+ const taskContent = taskMatch[1];
129
+ const nameMatch = taskContent.match(/<name>([\s\S]*?)<\/name>/);
130
+ const taskName = nameMatch ? nameMatch[1].trim() : 'unnamed';
131
+ const hasFiles = /<files>/.test(taskContent);
132
+ const hasAction = /<action>/.test(taskContent);
133
+ const hasVerify = /<verify>/.test(taskContent);
134
+ const hasDone = /<done>/.test(taskContent);
135
+
136
+ if (!nameMatch) errors.push('Task missing <name> element');
137
+ if (!hasAction) errors.push(`Task '${taskName}' missing <action>`);
138
+ if (!hasVerify) warnings.push(`Task '${taskName}' missing <verify>`);
139
+ if (!hasDone) warnings.push(`Task '${taskName}' missing <done>`);
140
+ if (!hasFiles) warnings.push(`Task '${taskName}' missing <files>`);
141
+
142
+ tasks.push({ name: taskName, hasFiles, hasAction, hasVerify, hasDone });
143
+ }
144
+
145
+ if (tasks.length === 0) warnings.push('No <task> elements found');
146
+
147
+ // Wave/depends_on consistency
148
+ if (fm.wave && parseInt(fm.wave) > 1 && (!fm.depends_on || (Array.isArray(fm.depends_on) && fm.depends_on.length === 0))) {
149
+ warnings.push('Wave > 1 but depends_on is empty');
150
+ }
151
+
152
+ // Autonomous/checkpoint consistency
153
+ const hasCheckpoints = /<task\s+type=["']?checkpoint/.test(content);
154
+ if (hasCheckpoints && fm.autonomous !== 'false' && fm.autonomous !== false) {
155
+ errors.push('Has checkpoint tasks but autonomous is not false');
156
+ }
157
+
158
+ output({
159
+ valid: errors.length === 0,
160
+ errors,
161
+ warnings,
162
+ task_count: tasks.length,
163
+ tasks,
164
+ frontmatter_fields: Object.keys(fm),
165
+ }, raw, errors.length === 0 ? 'valid' : 'invalid');
166
+ }
167
+
168
+ function cmdVerifyPhaseCompleteness(cwd, phase, raw) {
169
+ if (!phase) { error('phase required'); }
170
+ const phaseInfo = findPhaseInternal(cwd, phase);
171
+ if (!phaseInfo || !phaseInfo.found) {
172
+ output({ error: 'Phase not found', phase }, raw);
173
+ return;
174
+ }
175
+
176
+ const errors = [];
177
+ const warnings = [];
178
+ const phaseDir = path.join(cwd, phaseInfo.directory);
179
+
180
+ // List plans and summaries
181
+ let files;
182
+ try { files = fs.readdirSync(phaseDir); } catch { output({ error: 'Cannot read phase directory' }, raw); return; }
183
+
184
+ const plans = files.filter(f => f.match(/-PLAN\.md$/i));
185
+ const summaries = files.filter(f => f.match(/-SUMMARY\.md$/i));
186
+
187
+ // Extract plan IDs (everything before -PLAN.md)
188
+ const planIds = new Set(plans.map(p => p.replace(/-PLAN\.md$/i, '')));
189
+ const summaryIds = new Set(summaries.map(s => s.replace(/-SUMMARY\.md$/i, '')));
190
+
191
+ // Plans without summaries
192
+ const incompletePlans = [...planIds].filter(id => !summaryIds.has(id));
193
+ if (incompletePlans.length > 0) {
194
+ errors.push(`Plans without summaries: ${incompletePlans.join(', ')}`);
195
+ }
196
+
197
+ // Summaries without plans (orphans)
198
+ const orphanSummaries = [...summaryIds].filter(id => !planIds.has(id));
199
+ if (orphanSummaries.length > 0) {
200
+ warnings.push(`Summaries without plans: ${orphanSummaries.join(', ')}`);
201
+ }
202
+
203
+ output({
204
+ complete: errors.length === 0,
205
+ phase: phaseInfo.phase_number,
206
+ plan_count: plans.length,
207
+ summary_count: summaries.length,
208
+ incomplete_plans: incompletePlans,
209
+ orphan_summaries: orphanSummaries,
210
+ errors,
211
+ warnings,
212
+ }, raw, errors.length === 0 ? 'complete' : 'incomplete');
213
+ }
214
+
215
+ function cmdVerifyReferences(cwd, filePath, raw) {
216
+ if (!filePath) { error('file path required'); }
217
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
218
+ const content = safeReadFile(fullPath);
219
+ if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
220
+
221
+ const found = [];
222
+ const missing = [];
223
+
224
+ // Find @-references: @path/to/file (must contain / to be a file path)
225
+ const atRefs = content.match(/@([^\s\n,)]+\/[^\s\n,)]+)/g) || [];
226
+ for (const ref of atRefs) {
227
+ const cleanRef = ref.slice(1); // remove @
228
+ const resolved = cleanRef.startsWith('~/')
229
+ ? path.join(process.env.HOME || '', cleanRef.slice(2))
230
+ : path.join(cwd, cleanRef);
231
+ if (fs.existsSync(resolved)) {
232
+ found.push(cleanRef);
233
+ } else {
234
+ missing.push(cleanRef);
235
+ }
236
+ }
237
+
238
+ // Find backtick file paths that look like real paths (contain / and have extension)
239
+ const backtickRefs = content.match(/`([^`]+\/[^`]+\.[a-zA-Z]{1,10})`/g) || [];
240
+ for (const ref of backtickRefs) {
241
+ const cleanRef = ref.slice(1, -1); // remove backticks
242
+ if (cleanRef.startsWith('http') || cleanRef.includes('${') || cleanRef.includes('{{')) continue;
243
+ if (found.includes(cleanRef) || missing.includes(cleanRef)) continue; // dedup
244
+ const resolved = path.join(cwd, cleanRef);
245
+ if (fs.existsSync(resolved)) {
246
+ found.push(cleanRef);
247
+ } else {
248
+ missing.push(cleanRef);
249
+ }
250
+ }
251
+
252
+ output({
253
+ valid: missing.length === 0,
254
+ found: found.length,
255
+ missing,
256
+ total: found.length + missing.length,
257
+ }, raw, missing.length === 0 ? 'valid' : 'invalid');
258
+ }
259
+
260
+ function cmdVerifyCommits(cwd, hashes, raw) {
261
+ if (!hashes || hashes.length === 0) { error('At least one commit hash required'); }
262
+
263
+ const valid = [];
264
+ const invalid = [];
265
+ for (const hash of hashes) {
266
+ const result = execGit(cwd, ['cat-file', '-t', hash]);
267
+ if (result.exitCode === 0 && result.stdout.trim() === 'commit') {
268
+ valid.push(hash);
269
+ } else {
270
+ invalid.push(hash);
271
+ }
272
+ }
273
+
274
+ output({
275
+ all_valid: invalid.length === 0,
276
+ valid,
277
+ invalid,
278
+ total: hashes.length,
279
+ }, raw, invalid.length === 0 ? 'valid' : 'invalid');
280
+ }
281
+
282
+ function cmdVerifyArtifacts(cwd, planFilePath, raw) {
283
+ if (!planFilePath) { error('plan file path required'); }
284
+ const fullPath = path.isAbsolute(planFilePath) ? planFilePath : path.join(cwd, planFilePath);
285
+ const content = safeReadFile(fullPath);
286
+ if (!content) { output({ error: 'File not found', path: planFilePath }, raw); return; }
287
+
288
+ const artifacts = parseMustHavesBlock(content, 'artifacts');
289
+ if (artifacts.length === 0) {
290
+ output({ error: 'No must_haves.artifacts found in frontmatter', path: planFilePath }, raw);
291
+ return;
292
+ }
293
+
294
+ const results = [];
295
+ for (const artifact of artifacts) {
296
+ if (typeof artifact === 'string') continue; // skip simple string items
297
+ const artPath = artifact.path;
298
+ if (!artPath) continue;
299
+
300
+ const artFullPath = path.join(cwd, artPath);
301
+ const exists = fs.existsSync(artFullPath);
302
+ const check = { path: artPath, exists, issues: [], passed: false };
303
+
304
+ if (exists) {
305
+ const fileContent = safeReadFile(artFullPath) || '';
306
+ const lineCount = fileContent.split('\n').length;
307
+
308
+ if (artifact.min_lines && lineCount < artifact.min_lines) {
309
+ check.issues.push(`Only ${lineCount} lines, need ${artifact.min_lines}`);
310
+ }
311
+ if (artifact.contains && !fileContent.includes(artifact.contains)) {
312
+ check.issues.push(`Missing pattern: ${artifact.contains}`);
313
+ }
314
+ if (artifact.exports) {
315
+ const exports = Array.isArray(artifact.exports) ? artifact.exports : [artifact.exports];
316
+ for (const exp of exports) {
317
+ if (!fileContent.includes(exp)) check.issues.push(`Missing export: ${exp}`);
318
+ }
319
+ }
320
+ check.passed = check.issues.length === 0;
321
+ } else {
322
+ check.issues.push('File not found');
323
+ }
324
+
325
+ results.push(check);
326
+ }
327
+
328
+ const passed = results.filter(r => r.passed).length;
329
+ output({
330
+ all_passed: passed === results.length,
331
+ passed,
332
+ total: results.length,
333
+ artifacts: results,
334
+ }, raw, passed === results.length ? 'valid' : 'invalid');
335
+ }
336
+
337
+ function cmdVerifyKeyLinks(cwd, planFilePath, raw) {
338
+ if (!planFilePath) { error('plan file path required'); }
339
+ const fullPath = path.isAbsolute(planFilePath) ? planFilePath : path.join(cwd, planFilePath);
340
+ const content = safeReadFile(fullPath);
341
+ if (!content) { output({ error: 'File not found', path: planFilePath }, raw); return; }
342
+
343
+ const keyLinks = parseMustHavesBlock(content, 'key_links');
344
+ if (keyLinks.length === 0) {
345
+ output({ error: 'No must_haves.key_links found in frontmatter', path: planFilePath }, raw);
346
+ return;
347
+ }
348
+
349
+ const results = [];
350
+ for (const link of keyLinks) {
351
+ if (typeof link === 'string') continue;
352
+ const check = { from: link.from, to: link.to, via: link.via || '', verified: false, detail: '' };
353
+
354
+ const sourceContent = safeReadFile(path.join(cwd, link.from || ''));
355
+ if (!sourceContent) {
356
+ check.detail = 'Source file not found';
357
+ } else if (link.pattern) {
358
+ try {
359
+ const regex = new RegExp(link.pattern);
360
+ if (regex.test(sourceContent)) {
361
+ check.verified = true;
362
+ check.detail = 'Pattern found in source';
363
+ } else {
364
+ const targetContent = safeReadFile(path.join(cwd, link.to || ''));
365
+ if (targetContent && regex.test(targetContent)) {
366
+ check.verified = true;
367
+ check.detail = 'Pattern found in target';
368
+ } else {
369
+ check.detail = `Pattern "${link.pattern}" not found in source or target`;
370
+ }
371
+ }
372
+ } catch {
373
+ check.detail = `Invalid regex pattern: ${link.pattern}`;
374
+ }
375
+ } else {
376
+ // No pattern: just check source references target
377
+ if (sourceContent.includes(link.to || '')) {
378
+ check.verified = true;
379
+ check.detail = 'Target referenced in source';
380
+ } else {
381
+ check.detail = 'Target not referenced in source';
382
+ }
383
+ }
384
+
385
+ results.push(check);
386
+ }
387
+
388
+ const verified = results.filter(r => r.verified).length;
389
+ output({
390
+ all_verified: verified === results.length,
391
+ verified,
392
+ total: results.length,
393
+ links: results,
394
+ }, raw, verified === results.length ? 'valid' : 'invalid');
395
+ }
396
+
397
+ function cmdValidateConsistency(cwd, raw) {
398
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
399
+ const phasesDir = path.join(cwd, '.planning', 'phases');
400
+ const errors = [];
401
+ const warnings = [];
402
+
403
+ // Check for ROADMAP
404
+ if (!fs.existsSync(roadmapPath)) {
405
+ errors.push('ROADMAP.md not found');
406
+ output({ passed: false, errors, warnings }, raw, 'failed');
407
+ return;
408
+ }
409
+
410
+ const roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
411
+
412
+ // Extract phases from ROADMAP
413
+ const roadmapPhases = new Set();
414
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
415
+ let m;
416
+ while ((m = phasePattern.exec(roadmapContent)) !== null) {
417
+ roadmapPhases.add(m[1]);
418
+ }
419
+
420
+ // Get phases on disk
421
+ const diskPhases = new Set();
422
+ try {
423
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
424
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
425
+ for (const dir of dirs) {
426
+ const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)/i);
427
+ if (dm) diskPhases.add(dm[1]);
428
+ }
429
+ } catch {}
430
+
431
+ // Check: phases in ROADMAP but not on disk
432
+ for (const p of roadmapPhases) {
433
+ if (!diskPhases.has(p) && !diskPhases.has(normalizePhaseName(p))) {
434
+ warnings.push(`Phase ${p} in ROADMAP.md but no directory on disk`);
435
+ }
436
+ }
437
+
438
+ // Check: phases on disk but not in ROADMAP
439
+ for (const p of diskPhases) {
440
+ const unpadded = String(parseInt(p, 10));
441
+ if (!roadmapPhases.has(p) && !roadmapPhases.has(unpadded)) {
442
+ warnings.push(`Phase ${p} exists on disk but not in ROADMAP.md`);
443
+ }
444
+ }
445
+
446
+ // Check: sequential phase numbers (integers only)
447
+ const integerPhases = [...diskPhases]
448
+ .filter(p => !p.includes('.'))
449
+ .map(p => parseInt(p, 10))
450
+ .sort((a, b) => a - b);
451
+
452
+ for (let i = 1; i < integerPhases.length; i++) {
453
+ if (integerPhases[i] !== integerPhases[i - 1] + 1) {
454
+ warnings.push(`Gap in phase numbering: ${integerPhases[i - 1]} → ${integerPhases[i]}`);
455
+ }
456
+ }
457
+
458
+ // Check: plan numbering within phases
459
+ try {
460
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
461
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort();
462
+
463
+ for (const dir of dirs) {
464
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
465
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md')).sort();
466
+
467
+ // Extract plan numbers
468
+ const planNums = plans.map(p => {
469
+ const pm = p.match(/-(\d{2})-PLAN\.md$/);
470
+ return pm ? parseInt(pm[1], 10) : null;
471
+ }).filter(n => n !== null);
472
+
473
+ for (let i = 1; i < planNums.length; i++) {
474
+ if (planNums[i] !== planNums[i - 1] + 1) {
475
+ warnings.push(`Gap in plan numbering in ${dir}: plan ${planNums[i - 1]} → ${planNums[i]}`);
476
+ }
477
+ }
478
+
479
+ // Check: plans without summaries (completed plans)
480
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md'));
481
+ const planIds = new Set(plans.map(p => p.replace('-PLAN.md', '')));
482
+ const summaryIds = new Set(summaries.map(s => s.replace('-SUMMARY.md', '')));
483
+
484
+ // Summary without matching plan is suspicious
485
+ for (const sid of summaryIds) {
486
+ if (!planIds.has(sid)) {
487
+ warnings.push(`Summary ${sid}-SUMMARY.md in ${dir} has no matching PLAN.md`);
488
+ }
489
+ }
490
+ }
491
+ } catch {}
492
+
493
+ // Check: frontmatter in plans has required fields
494
+ try {
495
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
496
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
497
+
498
+ for (const dir of dirs) {
499
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
500
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md'));
501
+
502
+ for (const plan of plans) {
503
+ const content = fs.readFileSync(path.join(phasesDir, dir, plan), 'utf-8');
504
+ const fm = extractFrontmatter(content);
505
+
506
+ if (!fm.wave) {
507
+ warnings.push(`${dir}/${plan}: missing 'wave' in frontmatter`);
508
+ }
509
+ }
510
+ }
511
+ } catch {}
512
+
513
+ const passed = errors.length === 0;
514
+ output({ passed, errors, warnings, warning_count: warnings.length }, raw, passed ? 'passed' : 'failed');
515
+ }
516
+
517
+ function cmdValidateHealth(cwd, options, raw) {
518
+ const planningDir = path.join(cwd, '.planning');
519
+ const projectPath = path.join(planningDir, 'PROJECT.md');
520
+ const roadmapPath = path.join(planningDir, 'ROADMAP.md');
521
+ const statePath = path.join(planningDir, 'STATE.md');
522
+ const configPath = path.join(planningDir, 'config.json');
523
+ const phasesDir = path.join(planningDir, 'phases');
524
+
525
+ const errors = [];
526
+ const warnings = [];
527
+ const info = [];
528
+ const repairs = [];
529
+
530
+ // Helper to add issue
531
+ const addIssue = (severity, code, message, fix, repairable = false) => {
532
+ const issue = { code, message, fix, repairable };
533
+ if (severity === 'error') errors.push(issue);
534
+ else if (severity === 'warning') warnings.push(issue);
535
+ else info.push(issue);
536
+ };
537
+
538
+ // ─── Check 1: .planning/ exists ───────────────────────────────────────────
539
+ if (!fs.existsSync(planningDir)) {
540
+ addIssue('error', 'E001', '.planning/ directory not found', 'Run /gsd:new-project to initialize');
541
+ output({
542
+ status: 'broken',
543
+ errors,
544
+ warnings,
545
+ info,
546
+ repairable_count: 0,
547
+ }, raw);
548
+ return;
549
+ }
550
+
551
+ // ─── Check 2: PROJECT.md exists and has required sections ─────────────────
552
+ if (!fs.existsSync(projectPath)) {
553
+ addIssue('error', 'E002', 'PROJECT.md not found', 'Run /gsd:new-project to create');
554
+ } else {
555
+ const content = fs.readFileSync(projectPath, 'utf-8');
556
+ const requiredSections = ['## What This Is', '## Core Value', '## Requirements'];
557
+ for (const section of requiredSections) {
558
+ if (!content.includes(section)) {
559
+ addIssue('warning', 'W001', `PROJECT.md missing section: ${section}`, 'Add section manually');
560
+ }
561
+ }
562
+ }
563
+
564
+ // ─── Check 3: ROADMAP.md exists ───────────────────────────────────────────
565
+ if (!fs.existsSync(roadmapPath)) {
566
+ addIssue('error', 'E003', 'ROADMAP.md not found', 'Run /gsd:new-milestone to create roadmap');
567
+ }
568
+
569
+ // ─── Check 4: STATE.md exists and references valid phases ─────────────────
570
+ if (!fs.existsSync(statePath)) {
571
+ addIssue('error', 'E004', 'STATE.md not found', 'Run /gsd:health --repair to regenerate', true);
572
+ repairs.push('regenerateState');
573
+ } else {
574
+ const stateContent = fs.readFileSync(statePath, 'utf-8');
575
+ // Extract phase references from STATE.md
576
+ const phaseRefs = [...stateContent.matchAll(/[Pp]hase\s+(\d+(?:\.\d+)*)/g)].map(m => m[1]);
577
+ // Get disk phases
578
+ const diskPhases = new Set();
579
+ try {
580
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
581
+ for (const e of entries) {
582
+ if (e.isDirectory()) {
583
+ const m = e.name.match(/^(\d+(?:\.\d+)*)/);
584
+ if (m) diskPhases.add(m[1]);
585
+ }
586
+ }
587
+ } catch {}
588
+ // Check for invalid references
589
+ for (const ref of phaseRefs) {
590
+ const normalizedRef = String(parseInt(ref, 10)).padStart(2, '0');
591
+ if (!diskPhases.has(ref) && !diskPhases.has(normalizedRef) && !diskPhases.has(String(parseInt(ref, 10)))) {
592
+ // Only warn if phases dir has any content (not just an empty project)
593
+ if (diskPhases.size > 0) {
594
+ addIssue('warning', 'W002', `STATE.md references phase ${ref}, but only phases ${[...diskPhases].sort().join(', ')} exist`, 'Run /gsd:health --repair to regenerate STATE.md', true);
595
+ if (!repairs.includes('regenerateState')) repairs.push('regenerateState');
596
+ }
597
+ }
598
+ }
599
+ }
600
+
601
+ // ─── Check 5: config.json valid JSON + valid schema ───────────────────────
602
+ if (!fs.existsSync(configPath)) {
603
+ addIssue('warning', 'W003', 'config.json not found', 'Run /gsd:health --repair to create with defaults', true);
604
+ repairs.push('createConfig');
605
+ } else {
606
+ try {
607
+ const raw = fs.readFileSync(configPath, 'utf-8');
608
+ const parsed = JSON.parse(raw);
609
+ // Validate known fields
610
+ const validProfiles = ['quality', 'balanced', 'budget'];
611
+ if (parsed.model_profile && !validProfiles.includes(parsed.model_profile)) {
612
+ addIssue('warning', 'W004', `config.json: invalid model_profile "${parsed.model_profile}"`, `Valid values: ${validProfiles.join(', ')}`);
613
+ }
614
+ } catch (err) {
615
+ addIssue('error', 'E005', `config.json: JSON parse error - ${err.message}`, 'Run /gsd:health --repair to reset to defaults', true);
616
+ repairs.push('resetConfig');
617
+ }
618
+ }
619
+
620
+ // ─── Check 5b: Nyquist validation key presence ──────────────────────────
621
+ if (fs.existsSync(configPath)) {
622
+ try {
623
+ const configRaw = fs.readFileSync(configPath, 'utf-8');
624
+ const configParsed = JSON.parse(configRaw);
625
+ if (configParsed.workflow && configParsed.workflow.nyquist_validation === undefined) {
626
+ addIssue('warning', 'W008', 'config.json: workflow.nyquist_validation absent (defaults to enabled but agents may skip)', 'Run /gsd:health --repair to add key', true);
627
+ if (!repairs.includes('addNyquistKey')) repairs.push('addNyquistKey');
628
+ }
629
+ } catch {}
630
+ }
631
+
632
+ // ─── Check 6: Phase directory naming (NN-name format) ─────────────────────
633
+ try {
634
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
635
+ for (const e of entries) {
636
+ if (e.isDirectory() && !e.name.match(/^\d{2}(?:\.\d+)*-[\w-]+$/)) {
637
+ addIssue('warning', 'W005', `Phase directory "${e.name}" doesn't follow NN-name format`, 'Rename to match pattern (e.g., 01-setup)');
638
+ }
639
+ }
640
+ } catch {}
641
+
642
+ // ─── Check 7: Orphaned plans (PLAN without SUMMARY) ───────────────────────
643
+ try {
644
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
645
+ for (const e of entries) {
646
+ if (!e.isDirectory()) continue;
647
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, e.name));
648
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
649
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
650
+ const summaryBases = new Set(summaries.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', '')));
651
+
652
+ for (const plan of plans) {
653
+ const planBase = plan.replace('-PLAN.md', '').replace('PLAN.md', '');
654
+ if (!summaryBases.has(planBase)) {
655
+ addIssue('info', 'I001', `${e.name}/${plan} has no SUMMARY.md`, 'May be in progress');
656
+ }
657
+ }
658
+ }
659
+ } catch {}
660
+
661
+ // ─── Check 7b: Nyquist VALIDATION.md consistency ────────────────────────
662
+ try {
663
+ const phaseEntries = fs.readdirSync(phasesDir, { withFileTypes: true });
664
+ for (const e of phaseEntries) {
665
+ if (!e.isDirectory()) continue;
666
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, e.name));
667
+ const hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md'));
668
+ const hasValidation = phaseFiles.some(f => f.endsWith('-VALIDATION.md'));
669
+ if (hasResearch && !hasValidation) {
670
+ const researchFile = phaseFiles.find(f => f.endsWith('-RESEARCH.md'));
671
+ const researchContent = fs.readFileSync(path.join(phasesDir, e.name, researchFile), 'utf-8');
672
+ if (researchContent.includes('## Validation Architecture')) {
673
+ addIssue('warning', 'W009', `Phase ${e.name}: has Validation Architecture in RESEARCH.md but no VALIDATION.md`, 'Re-run /gsd:plan-phase with --research to regenerate');
674
+ }
675
+ }
676
+ }
677
+ } catch {}
678
+
679
+ // ─── Check 8: Run existing consistency checks ─────────────────────────────
680
+ // Inline subset of cmdValidateConsistency
681
+ if (fs.existsSync(roadmapPath)) {
682
+ const roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
683
+ const roadmapPhases = new Set();
684
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
685
+ let m;
686
+ while ((m = phasePattern.exec(roadmapContent)) !== null) {
687
+ roadmapPhases.add(m[1]);
688
+ }
689
+
690
+ const diskPhases = new Set();
691
+ try {
692
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
693
+ for (const e of entries) {
694
+ if (e.isDirectory()) {
695
+ const dm = e.name.match(/^(\d+[A-Z]?(?:\.\d+)*)/i);
696
+ if (dm) diskPhases.add(dm[1]);
697
+ }
698
+ }
699
+ } catch {}
700
+
701
+ // Phases in ROADMAP but not on disk
702
+ for (const p of roadmapPhases) {
703
+ const padded = String(parseInt(p, 10)).padStart(2, '0');
704
+ if (!diskPhases.has(p) && !diskPhases.has(padded)) {
705
+ addIssue('warning', 'W006', `Phase ${p} in ROADMAP.md but no directory on disk`, 'Create phase directory or remove from roadmap');
706
+ }
707
+ }
708
+
709
+ // Phases on disk but not in ROADMAP
710
+ for (const p of diskPhases) {
711
+ const unpadded = String(parseInt(p, 10));
712
+ if (!roadmapPhases.has(p) && !roadmapPhases.has(unpadded)) {
713
+ addIssue('warning', 'W007', `Phase ${p} exists on disk but not in ROADMAP.md`, 'Add to roadmap or remove directory');
714
+ }
715
+ }
716
+ }
717
+
718
+ // ─── Perform repairs if requested ─────────────────────────────────────────
719
+ const repairActions = [];
720
+ if (options.repair && repairs.length > 0) {
721
+ for (const repair of repairs) {
722
+ try {
723
+ switch (repair) {
724
+ case 'createConfig':
725
+ case 'resetConfig': {
726
+ const defaults = {
727
+ model_profile: 'balanced',
728
+ commit_docs: true,
729
+ search_gitignored: false,
730
+ branching_strategy: 'none',
731
+ research: true,
732
+ plan_checker: true,
733
+ verifier: true,
734
+ parallelization: true,
735
+ };
736
+ fs.writeFileSync(configPath, JSON.stringify(defaults, null, 2), 'utf-8');
737
+ repairActions.push({ action: repair, success: true, path: 'config.json' });
738
+ break;
739
+ }
740
+ case 'regenerateState': {
741
+ // Create timestamped backup before overwriting
742
+ if (fs.existsSync(statePath)) {
743
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
744
+ const backupPath = `${statePath}.bak-${timestamp}`;
745
+ fs.copyFileSync(statePath, backupPath);
746
+ repairActions.push({ action: 'backupState', success: true, path: backupPath });
747
+ }
748
+ // Generate minimal STATE.md from ROADMAP.md structure
749
+ const milestone = getMilestoneInfo(cwd);
750
+ let stateContent = `# Session State\n\n`;
751
+ stateContent += `## Project Reference\n\n`;
752
+ stateContent += `See: .planning/PROJECT.md\n\n`;
753
+ stateContent += `## Position\n\n`;
754
+ stateContent += `**Milestone:** ${milestone.version} ${milestone.name}\n`;
755
+ stateContent += `**Current phase:** (determining...)\n`;
756
+ stateContent += `**Status:** Resuming\n\n`;
757
+ stateContent += `## Session Log\n\n`;
758
+ stateContent += `- ${new Date().toISOString().split('T')[0]}: STATE.md regenerated by /gsd:health --repair\n`;
759
+ writeStateMd(statePath, stateContent, cwd);
760
+ repairActions.push({ action: repair, success: true, path: 'STATE.md' });
761
+ break;
762
+ }
763
+ case 'addNyquistKey': {
764
+ if (fs.existsSync(configPath)) {
765
+ try {
766
+ const configRaw = fs.readFileSync(configPath, 'utf-8');
767
+ const configParsed = JSON.parse(configRaw);
768
+ if (!configParsed.workflow) configParsed.workflow = {};
769
+ if (configParsed.workflow.nyquist_validation === undefined) {
770
+ configParsed.workflow.nyquist_validation = true;
771
+ fs.writeFileSync(configPath, JSON.stringify(configParsed, null, 2), 'utf-8');
772
+ }
773
+ repairActions.push({ action: repair, success: true, path: 'config.json' });
774
+ } catch (err) {
775
+ repairActions.push({ action: repair, success: false, error: err.message });
776
+ }
777
+ }
778
+ break;
779
+ }
780
+ }
781
+ } catch (err) {
782
+ repairActions.push({ action: repair, success: false, error: err.message });
783
+ }
784
+ }
785
+ }
786
+
787
+ // ─── Determine overall status ─────────────────────────────────────────────
788
+ let status;
789
+ if (errors.length > 0) {
790
+ status = 'broken';
791
+ } else if (warnings.length > 0) {
792
+ status = 'degraded';
793
+ } else {
794
+ status = 'healthy';
795
+ }
796
+
797
+ const repairableCount = errors.filter(e => e.repairable).length +
798
+ warnings.filter(w => w.repairable).length;
799
+
800
+ output({
801
+ status,
802
+ errors,
803
+ warnings,
804
+ info,
805
+ repairable_count: repairableCount,
806
+ repairs_performed: repairActions.length > 0 ? repairActions : undefined,
807
+ }, raw);
808
+ }
809
+
810
+ module.exports = {
811
+ cmdVerifySummary,
812
+ cmdVerifyPlanStructure,
813
+ cmdVerifyPhaseCompleteness,
814
+ cmdVerifyReferences,
815
+ cmdVerifyCommits,
816
+ cmdVerifyArtifacts,
817
+ cmdVerifyKeyLinks,
818
+ cmdValidateConsistency,
819
+ cmdValidateHealth,
820
+ };