gsd-opencode 1.10.2 → 1.20.0

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