gsdd-cli 0.18.4 → 0.19.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 (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +625 -607
  3. package/agents/DISTILLATION.md +421 -421
  4. package/agents/README.md +62 -62
  5. package/agents/approach-explorer.md +361 -361
  6. package/agents/debugger.md +82 -82
  7. package/agents/executor.md +394 -394
  8. package/agents/integration-checker.md +318 -318
  9. package/agents/mapper.md +103 -103
  10. package/agents/planner.md +313 -313
  11. package/agents/researcher.md +84 -84
  12. package/agents/roadmapper.md +296 -296
  13. package/agents/synthesizer.md +236 -236
  14. package/agents/verifier.md +337 -337
  15. package/bin/adapters/agents.mjs +34 -34
  16. package/bin/adapters/claude.mjs +191 -191
  17. package/bin/adapters/codex.mjs +85 -85
  18. package/bin/adapters/index.mjs +20 -20
  19. package/bin/adapters/opencode.mjs +278 -278
  20. package/bin/gsdd.mjs +123 -116
  21. package/bin/lib/cli-utils.mjs +28 -28
  22. package/bin/lib/evidence-contract.mjs +112 -112
  23. package/bin/lib/file-ops.mjs +209 -161
  24. package/bin/lib/health-truth.mjs +181 -178
  25. package/bin/lib/health.mjs +265 -235
  26. package/bin/lib/init-flow.mjs +252 -236
  27. package/bin/lib/init-prompts.mjs +248 -247
  28. package/bin/lib/init-runtime.mjs +225 -212
  29. package/bin/lib/init.mjs +17 -17
  30. package/bin/lib/lifecycle-preflight.mjs +360 -333
  31. package/bin/lib/lifecycle-state.mjs +351 -267
  32. package/bin/lib/manifest.mjs +116 -114
  33. package/bin/lib/models.mjs +411 -411
  34. package/bin/lib/phase.mjs +397 -378
  35. package/bin/lib/plan-constants.mjs +30 -30
  36. package/bin/lib/provenance.mjs +109 -106
  37. package/bin/lib/rendering.mjs +178 -130
  38. package/bin/lib/runtime-freshness.mjs +221 -219
  39. package/bin/lib/templates.mjs +225 -224
  40. package/bin/lib/workspace-root.mjs +132 -0
  41. package/distilled/DESIGN.md +2347 -2327
  42. package/distilled/EVIDENCE-INDEX.md +397 -394
  43. package/distilled/README.md +196 -193
  44. package/distilled/SKILL.md +86 -85
  45. package/distilled/templates/agents.block.md +21 -21
  46. package/distilled/templates/agents.md +6 -6
  47. package/distilled/templates/approach.md +232 -232
  48. package/distilled/templates/auth-matrix.md +78 -78
  49. package/distilled/templates/brownfield-change/CHANGE.md +99 -0
  50. package/distilled/templates/brownfield-change/HANDOFF.md +38 -0
  51. package/distilled/templates/brownfield-change/VERIFICATION.md +56 -0
  52. package/distilled/templates/codebase/architecture.md +110 -110
  53. package/distilled/templates/codebase/concerns.md +95 -95
  54. package/distilled/templates/codebase/conventions.md +193 -193
  55. package/distilled/templates/codebase/stack.md +96 -96
  56. package/distilled/templates/delegates/approach-explorer.md +25 -25
  57. package/distilled/templates/delegates/mapper-arch.md +26 -26
  58. package/distilled/templates/delegates/mapper-concerns.md +27 -27
  59. package/distilled/templates/delegates/mapper-quality.md +28 -28
  60. package/distilled/templates/delegates/mapper-tech.md +25 -25
  61. package/distilled/templates/delegates/plan-checker.md +68 -68
  62. package/distilled/templates/delegates/researcher-architecture.md +30 -30
  63. package/distilled/templates/delegates/researcher-features.md +30 -30
  64. package/distilled/templates/delegates/researcher-pitfalls.md +30 -30
  65. package/distilled/templates/delegates/researcher-stack.md +30 -30
  66. package/distilled/templates/delegates/researcher-synthesizer.md +31 -31
  67. package/distilled/templates/research/architecture.md +57 -57
  68. package/distilled/templates/research/features.md +23 -23
  69. package/distilled/templates/research/pitfalls.md +46 -46
  70. package/distilled/templates/research/stack.md +45 -45
  71. package/distilled/templates/research/summary.md +67 -67
  72. package/distilled/templates/roadmap.md +74 -62
  73. package/distilled/templates/spec.md +110 -110
  74. package/distilled/workflows/audit-milestone.md +275 -271
  75. package/distilled/workflows/complete-milestone.md +336 -332
  76. package/distilled/workflows/execute.md +454 -449
  77. package/distilled/workflows/map-codebase.md +253 -253
  78. package/distilled/workflows/new-milestone.md +242 -238
  79. package/distilled/workflows/new-project.md +398 -398
  80. package/distilled/workflows/pause.md +160 -156
  81. package/distilled/workflows/plan-milestone-gaps.md +183 -183
  82. package/distilled/workflows/plan.md +451 -447
  83. package/distilled/workflows/progress.md +227 -223
  84. package/distilled/workflows/quick.md +351 -347
  85. package/distilled/workflows/resume.md +220 -212
  86. package/distilled/workflows/verify-work.md +260 -260
  87. package/distilled/workflows/verify.md +431 -429
  88. package/docs/BROWNFIELD-PROOF.md +95 -95
  89. package/docs/RUNTIME-SUPPORT.md +93 -75
  90. package/docs/USER-GUIDE.md +440 -399
  91. package/docs/VERIFICATION-DISCIPLINE.md +59 -59
  92. package/docs/claude/context-monitor.md +98 -98
  93. package/docs/proof/consumer-node-cli/README.md +37 -37
  94. package/docs/proof/consumer-node-cli/ROADMAP.md +14 -14
  95. package/docs/proof/consumer-node-cli/SPEC.md +17 -17
  96. package/docs/proof/consumer-node-cli/brief.md +9 -9
  97. package/docs/proof/consumer-node-cli/phases/01-foundation/01-01-PLAN.md +34 -34
  98. package/docs/proof/consumer-node-cli/phases/01-foundation/01-01-SUMMARY.md +10 -10
  99. package/docs/proof/consumer-node-cli/phases/01-foundation/01-VERIFICATION.md +30 -30
  100. package/package.json +62 -61
package/bin/lib/phase.mjs CHANGED
@@ -1,378 +1,397 @@
1
- // phase.mjs — Phase discovery, verification, and scaffolding
2
- //
3
- // IMPORTANT: No module-scope process.cwd() — ESM caching means sub-modules
4
- // evaluate once, so CWD must be computed inside function bodies.
5
-
6
- import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync } from 'fs';
7
- import { join, basename } from 'path';
8
- import { output } from './cli-utils.mjs';
9
- import { writeFingerprint } from './session-fingerprint.mjs';
10
-
11
- const PHASE_STATUS_MARKERS = {
12
- not_started: '[ ]',
13
- todo: '[ ]',
14
- in_progress: '[-]',
15
- done: '[x]',
16
- };
17
-
18
- const PHASE_MARKER_RE = '(\\[[ x]\\]|\\[-\\]|⬜|ðŸ"„|✅|⬜|🔄|✅)';
19
- const PHASE_TOKEN_RE = '(\\d+(?:\\.\\d+)*[a-z]?)';
20
- const PHASE_LINE_RE = new RegExp(
21
- `^[-*]\\s*${PHASE_MARKER_RE}\\s*\\*\\*Phase\\s+${PHASE_TOKEN_RE}:\\s*(.+?)\\*\\*`,
22
- 'i'
23
- );
24
- const ROADMAP_PHASE_STATUS_RE = new RegExp(
25
- `^(\\s*[-*]\\s*)${PHASE_MARKER_RE}(\\s*\\*\\*Phase\\s+${PHASE_TOKEN_RE}:.*)$`,
26
- 'i'
27
- );
28
-
29
- function findFiles(dir, prefix) {
30
- if (!existsSync(dir)) return [];
31
-
32
- const phaseArtifactPrefix = String(prefix).match(/^(\d+(?:\.\d+)*[a-z]?)-(PLAN|SUMMARY)$/i);
33
- if (!phaseArtifactPrefix) {
34
- return readdirSync(dir).filter((f) => f.startsWith(prefix) || f.startsWith(prefix.replace(/^0+/, '')));
35
- }
36
-
37
- const targetPhase = normalizePhaseToken(phaseArtifactPrefix[1]);
38
- const targetKind = phaseArtifactPrefix[2].toUpperCase();
39
-
40
- return listPhaseArtifacts(dir)
41
- .filter((artifact) => artifact.phaseToken === targetPhase && artifact.kind === targetKind)
42
- .map((artifact) => artifact.displayPath);
43
- }
44
-
45
- function listPhaseArtifacts(dir) {
46
- if (!existsSync(dir)) return [];
47
-
48
- const artifacts = [];
49
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
50
- if (entry.isFile()) {
51
- const artifact = classifyPhaseArtifact('', entry.name);
52
- if (artifact) artifacts.push(artifact);
53
- continue;
54
- }
55
-
56
- if (!entry.isDirectory()) continue;
57
-
58
- const entryPath = join(dir, entry.name);
59
- for (const child of readdirSync(entryPath, { withFileTypes: true })) {
60
- if (!child.isFile()) continue;
61
- const artifact = classifyPhaseArtifact(entry.name, child.name);
62
- if (artifact) artifacts.push(artifact);
63
- }
64
- }
65
-
66
- return artifacts;
67
- }
68
-
69
- function classifyPhaseArtifact(dir, name) {
70
- const dirMatch = dir ? dir.match(/^(\d+(?:\.\d+)*[a-z]?)-/i) : null;
71
- const nameMatch = name.match(/^(\d+(?:\.\d+)*[a-z]?)/i);
72
- const phaseToken = normalizePhaseToken((dirMatch || nameMatch)?.[1] || '');
73
-
74
- let kind = 'OTHER';
75
- if (name.includes('PLAN')) kind = 'PLAN';
76
- else if (name.includes('SUMMARY')) kind = 'SUMMARY';
77
-
78
- return {
79
- dir,
80
- name,
81
- displayPath: dir ? `${dir}/${name}` : name,
82
- phaseToken,
83
- kind,
84
- };
85
- }
86
-
87
- function padPhase(n) {
88
- return String(n).padStart(2, '0');
89
- }
90
-
91
- function parsePhaseStatuses(roadmap) {
92
- const phases = [];
93
- const lines = roadmap.split('\n');
94
- for (const line of lines) {
95
- const match = line.match(PHASE_LINE_RE);
96
- if (match) {
97
- const rawStatus = match[1].toLowerCase();
98
- let status = 'not_started';
99
- if (rawStatus === '[x]' || rawStatus === '✅' || rawStatus === '✅') status = 'done';
100
- else if (rawStatus === '[-]') status = 'in_progress';
101
- else if (rawStatus === 'ðÿ"„' || rawStatus === '🔄') status = 'in_progress';
102
- phases.push({
103
- number: match[2],
104
- name: match[3].replace(/\*\*/g, '').split('-')[0].trim(),
105
- status,
106
- });
107
- }
108
- }
109
- return phases;
110
- }
111
-
112
- function normalizePhaseToken(value) {
113
- const raw = String(value).trim().toLowerCase();
114
- const match = raw.match(/^(\d+(?:\.\d+)*)([a-z]?)$/i);
115
- if (!match) return raw;
116
-
117
- const numericSegments = match[1]
118
- .split('.')
119
- .map((segment) => String(parseInt(segment, 10)));
120
- return `${numericSegments.join('.')}${match[2] || ''}`;
121
- }
122
-
123
- export function updateRoadmapPhaseStatus(roadmap, phaseNumber, status) {
124
- const marker = PHASE_STATUS_MARKERS[status];
125
- if (!marker) {
126
- throw new Error(`Unsupported phase status: ${status}`);
127
- }
128
-
129
- const normalizedTarget = normalizePhaseToken(phaseNumber);
130
- let matchCount = 0;
131
-
132
- const updated = roadmap
133
- .split('\n')
134
- .map((line) => {
135
- const match = line.match(ROADMAP_PHASE_STATUS_RE);
136
- if (!match) return line;
137
- if (normalizePhaseToken(match[4]) !== normalizedTarget) return line;
138
- matchCount += 1;
139
- return `${match[1]}${marker}${match[3]}`;
140
- })
141
- .join('\n');
142
-
143
- if (matchCount === 0) {
144
- throw new Error(`Phase ${phaseNumber} was not found in ROADMAP.md`);
145
- }
146
-
147
- if (matchCount > 1) {
148
- throw new Error(`Phase ${phaseNumber} matched multiple ROADMAP.md entries`);
149
- }
150
-
151
- return updated;
152
- }
153
-
154
- export function cmdPhaseStatus(...args) {
155
- const cwd = process.cwd();
156
- const planningDir = join(cwd, '.planning');
157
- const roadmapPath = join(planningDir, 'ROADMAP.md');
158
- const [phaseNumber, status] = args;
159
-
160
- if (!phaseNumber || !status) {
161
- console.error('Usage: gsdd phase-status <phase-number> <not_started|todo|in_progress|done>');
162
- process.exitCode = 1;
163
- return;
164
- }
165
-
166
- if (!existsSync(roadmapPath)) {
167
- console.error('No ROADMAP.md found. Run the new-project workflow first.');
168
- process.exitCode = 1;
169
- return;
170
- }
171
-
172
- try {
173
- const roadmap = readFileSync(roadmapPath, 'utf-8');
174
- const updated = updateRoadmapPhaseStatus(roadmap, phaseNumber, status);
175
- const changed = updated !== roadmap;
176
- if (changed) {
177
- writeFileSync(roadmapPath, updated);
178
- try { writeFingerprint(planningDir); } catch { /* best-effort */ }
179
- }
180
- output({ phase: phaseNumber, status, roadmap: '.planning/ROADMAP.md', changed });
181
- } catch (error) {
182
- console.error(error.message);
183
- process.exitCode = 1;
184
- }
185
- }
186
-
187
- export function cmdFindPhase(...args) {
188
- const cwd = process.cwd();
189
- const planningDir = join(cwd, '.planning');
190
- const phaseNum = args[0];
191
-
192
- if (!existsSync(planningDir)) {
193
- output({ error: 'No .planning/ directory found. Run `gsdd init` then the new-project workflow first.' });
194
- return;
195
- }
196
-
197
- const roadmapPath = join(planningDir, 'ROADMAP.md');
198
- if (!existsSync(roadmapPath)) {
199
- output({ error: 'No ROADMAP.md found. Run the new-project workflow first.' });
200
- return;
201
- }
202
-
203
- const phasesDir = join(planningDir, 'phases');
204
- const researchDir = join(planningDir, 'research');
205
-
206
- if (phaseNum) {
207
- const plans = findFiles(phasesDir, `${padPhase(phaseNum)}-PLAN`);
208
- const summaries = findFiles(phasesDir, `${padPhase(phaseNum)}-SUMMARY`);
209
-
210
- output({
211
- phase: normalizePhaseToken(phaseNum),
212
- directory: phasesDir,
213
- plans,
214
- summaries,
215
- hasResearch: existsSync(researchDir) && readdirSync(researchDir).length > 0,
216
- incomplete: plans.filter((p) => !summaries.some((s) => s.replace('SUMMARY', '') === p.replace('PLAN', ''))),
217
- });
218
- return;
219
- }
220
-
221
- const allArtifacts = listPhaseArtifacts(phasesDir);
222
- const plans = allArtifacts.filter((artifact) => artifact.kind === 'PLAN');
223
- const summaries = allArtifacts.filter((artifact) => artifact.kind === 'SUMMARY');
224
-
225
- const roadmap = readFileSync(roadmapPath, 'utf-8');
226
- const phases = parsePhaseStatuses(roadmap);
227
-
228
- output({
229
- phases,
230
- planCount: plans.length,
231
- summaryCount: summaries.length,
232
- currentPhase: phases.find((p) => p.status === 'in_progress') || phases.find((p) => p.status === 'not_started') || null,
233
- hasResearch: existsSync(researchDir) && readdirSync(researchDir).length > 0,
234
- });
235
- }
236
-
237
- export function cmdVerify(...args) {
238
- const cwd = process.cwd();
239
- const planningDir = join(cwd, '.planning');
240
- const phaseNum = args[0];
241
- if (!phaseNum) {
242
- console.error('Usage: gsdd verify <phase-number>');
243
- process.exitCode = 1; return;
244
- }
245
-
246
- if (!existsSync(planningDir)) {
247
- console.error('No .planning/ directory found.');
248
- process.exitCode = 1; return;
249
- }
250
-
251
- const planFile = findFiles(join(planningDir, 'phases'), `${padPhase(phaseNum)}-PLAN`)[0];
252
- if (!planFile) {
253
- console.error(`No plan found for phase ${phaseNum}`);
254
- process.exitCode = 1; return;
255
- }
256
-
257
- const planPath = join(planningDir, 'phases', planFile);
258
- const plan = readFileSync(planPath, 'utf-8');
259
-
260
- const fileMatches = plan.matchAll(/<files>([\s\S]*?)<\/files>/g);
261
- const expectedFiles = [];
262
- for (const match of fileMatches) {
263
- const lines = match[1]
264
- .split('\n')
265
- .map((l) => l.trim())
266
- .filter((l) => l.startsWith('-'));
267
- for (const line of lines) {
268
- const fileMatch = line.match(/(?:CREATE|MODIFY):\s*(.+)/);
269
- if (fileMatch) expectedFiles.push(fileMatch[1].trim());
270
- }
271
- }
272
-
273
- const results = expectedFiles.map((f) => {
274
- const fullPath = join(cwd, f);
275
- const exists = existsSync(fullPath);
276
- let substantive = false;
277
- if (exists) {
278
- try {
279
- const content = readFileSync(fullPath, 'utf-8');
280
- const meaningfulLines = content.split('\n').filter(
281
- (l) => l.trim() && !/^\s*(\/\/|\/\*|\*|#)/.test(l)
282
- );
283
- substantive = meaningfulLines.length >= 3 && !content.includes('// TODO: implement');
284
- } catch {
285
- substantive = false;
286
- }
287
- }
288
- return { file: f, exists, substantive };
289
- });
290
-
291
- const antiPatterns = [];
292
- for (const r of results) {
293
- if (!r.exists) continue;
294
- try {
295
- const content = readFileSync(join(cwd, r.file), 'utf-8');
296
- const lines = content.split('\n');
297
- lines.forEach((line, i) => {
298
- if (/TODO|FIXME|HACK|XXX/.test(line)) {
299
- antiPatterns.push({ file: r.file, line: i + 1, pattern: 'TODO/FIXME', content: line.trim() });
300
- }
301
- if (/catch\s*\([^)]*\)\s*\{[\s]*\}/.test(line) || /catch\s*\([^)]*\)\s*\{\s*$/.test(line)) {
302
- antiPatterns.push({ file: r.file, line: i + 1, pattern: 'Empty catch', content: line.trim() });
303
- }
304
- });
305
- } catch {
306
- // skip unreadable files
307
- }
308
- }
309
-
310
- output({
311
- phase: parseInt(phaseNum, 10),
312
- artifacts: results,
313
- allExist: results.every((r) => r.exists),
314
- allSubstantive: results.filter((r) => r.exists).every((r) => r.substantive),
315
- antiPatterns,
316
- antiPatternCount: antiPatterns.length,
317
- });
318
- }
319
-
320
- export function cmdScaffold(...args) {
321
- const cwd = process.cwd();
322
- const planningDir = join(cwd, '.planning');
323
- const [type, ...rest] = args;
324
-
325
- if (type !== 'phase') {
326
- console.error('Usage: gsdd scaffold phase <number> [name]');
327
- process.exitCode = 1; return;
328
- }
329
-
330
- const phaseNum = rest[0];
331
- const phaseName = rest.slice(1).join(' ');
332
- if (!phaseNum) {
333
- console.error('Usage: gsdd scaffold phase <number> [name]');
334
- process.exitCode = 1; return;
335
- }
336
-
337
- const phasesDir = join(planningDir, 'phases');
338
- mkdirSync(phasesDir, { recursive: true });
339
-
340
- const planFile = join(phasesDir, `${padPhase(phaseNum)}-PLAN.md`);
341
- if (existsSync(planFile)) {
342
- console.log(` - ${basename(planFile)} already exists`);
343
- return;
344
- }
345
-
346
- const content = `# Phase ${phaseNum}: ${phaseName || '[Name]'} - Plan
347
-
348
- ## Phase Goal
349
- [From ROADMAP.md]
350
-
351
- ## Requirements Covered
352
- [REQ-IDs from SPEC.md]
353
-
354
- ## Approach
355
- [2-3 sentences]
356
-
357
- ## Must-Haves (from success criteria)
358
- 1. [Success criterion]
359
-
360
- ## Tasks
361
-
362
- <!-- Add tasks using XML format:
363
- <task id="${phaseNum}-01">
364
- <files>
365
- - CREATE: path/to/file
366
- </files>
367
- <action>Description of what to implement</action>
368
- <verify>How to verify it works</verify>
369
- <done>When is this task done</done>
370
- </task>
371
- -->
372
-
373
- ## Notes
374
- `;
375
-
376
- writeFileSync(planFile, content);
377
- console.log(` - created ${basename(planFile)}`);
378
- }
1
+ // phase.mjs — Phase discovery, verification, and scaffolding
2
+ //
3
+ // IMPORTANT: No module-scope process.cwd() — ESM caching means sub-modules
4
+ // evaluate once, so CWD must be computed inside function bodies.
5
+
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync } from 'fs';
7
+ import { join, basename } from 'path';
8
+ import { output } from './cli-utils.mjs';
9
+ import { writeFingerprint } from './session-fingerprint.mjs';
10
+ import { resolveWorkspaceContext } from './workspace-root.mjs';
11
+
12
+ const PHASE_STATUS_MARKERS = {
13
+ not_started: '[ ]',
14
+ todo: '[ ]',
15
+ in_progress: '[-]',
16
+ done: '[x]',
17
+ };
18
+
19
+ const PHASE_MARKER_RE = '(\\[[ x]\\]|\\[-\\]|⬜|ðŸ"„|✅|⬜|🔄|✅)';
20
+ const PHASE_TOKEN_RE = '(\\d+(?:\\.\\d+)*[a-z]?)';
21
+ const PHASE_LINE_RE = new RegExp(
22
+ `^[-*]\\s*${PHASE_MARKER_RE}\\s*\\*\\*Phase\\s+${PHASE_TOKEN_RE}:\\s*(.+?)\\*\\*`,
23
+ 'i'
24
+ );
25
+ const ROADMAP_PHASE_STATUS_RE = new RegExp(
26
+ `^(\\s*[-*]\\s*)${PHASE_MARKER_RE}(\\s*\\*\\*Phase\\s+${PHASE_TOKEN_RE}:.*)$`,
27
+ 'i'
28
+ );
29
+ const PHASE_DETAIL_HEADING_RE = new RegExp(`^#{3,}\\s+Phase\\s+${PHASE_TOKEN_RE}(?::|\\b)`, 'i');
30
+ const PHASE_DETAIL_STATUS_RE = new RegExp(`^(\\s*\\*\\*Status\\*\\*:\\s*)${PHASE_MARKER_RE}(.*)$`, 'i');
31
+ const DETAILS_OPEN_RE = /<details\b/i;
32
+ const DETAILS_CLOSE_RE = /<\/details>/i;
33
+
34
+ function findFiles(dir, prefix) {
35
+ if (!existsSync(dir)) return [];
36
+
37
+ const phaseArtifactPrefix = String(prefix).match(/^(\d+(?:\.\d+)*[a-z]?)-(PLAN|SUMMARY)$/i);
38
+ if (!phaseArtifactPrefix) {
39
+ return readdirSync(dir).filter((f) => f.startsWith(prefix) || f.startsWith(prefix.replace(/^0+/, '')));
40
+ }
41
+
42
+ const targetPhase = normalizePhaseToken(phaseArtifactPrefix[1]);
43
+ const targetKind = phaseArtifactPrefix[2].toUpperCase();
44
+
45
+ return listPhaseArtifacts(dir)
46
+ .filter((artifact) => artifact.phaseToken === targetPhase && artifact.kind === targetKind)
47
+ .map((artifact) => artifact.displayPath);
48
+ }
49
+
50
+ function listPhaseArtifacts(dir) {
51
+ if (!existsSync(dir)) return [];
52
+
53
+ const artifacts = [];
54
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
55
+ if (entry.isFile()) {
56
+ const artifact = classifyPhaseArtifact('', entry.name);
57
+ if (artifact) artifacts.push(artifact);
58
+ continue;
59
+ }
60
+
61
+ if (!entry.isDirectory()) continue;
62
+
63
+ const entryPath = join(dir, entry.name);
64
+ for (const child of readdirSync(entryPath, { withFileTypes: true })) {
65
+ if (!child.isFile()) continue;
66
+ const artifact = classifyPhaseArtifact(entry.name, child.name);
67
+ if (artifact) artifacts.push(artifact);
68
+ }
69
+ }
70
+
71
+ return artifacts;
72
+ }
73
+
74
+ function classifyPhaseArtifact(dir, name) {
75
+ const dirMatch = dir ? dir.match(/^(\d+(?:\.\d+)*[a-z]?)-/i) : null;
76
+ const nameMatch = name.match(/^(\d+(?:\.\d+)*[a-z]?)/i);
77
+ const phaseToken = normalizePhaseToken((dirMatch || nameMatch)?.[1] || '');
78
+
79
+ let kind = 'OTHER';
80
+ if (name.includes('PLAN')) kind = 'PLAN';
81
+ else if (name.includes('SUMMARY')) kind = 'SUMMARY';
82
+
83
+ return {
84
+ dir,
85
+ name,
86
+ displayPath: dir ? `${dir}/${name}` : name,
87
+ phaseToken,
88
+ kind,
89
+ };
90
+ }
91
+
92
+ function padPhase(n) {
93
+ return String(n).padStart(2, '0');
94
+ }
95
+
96
+ function parsePhaseStatuses(roadmap) {
97
+ const phases = [];
98
+ const lines = roadmap.split('\n');
99
+ for (const line of lines) {
100
+ const match = line.match(PHASE_LINE_RE);
101
+ if (match) {
102
+ const rawStatus = match[1].toLowerCase();
103
+ let status = 'not_started';
104
+ if (rawStatus === '[x]' || rawStatus === '✅' || rawStatus === '✅') status = 'done';
105
+ else if (rawStatus === '[-]') status = 'in_progress';
106
+ else if (rawStatus === 'ðÿ"„' || rawStatus === '🔄') status = 'in_progress';
107
+ phases.push({
108
+ number: match[2],
109
+ name: match[3].replace(/\*\*/g, '').split('-')[0].trim(),
110
+ status,
111
+ });
112
+ }
113
+ }
114
+ return phases;
115
+ }
116
+
117
+ function normalizePhaseToken(value) {
118
+ const raw = String(value).trim().toLowerCase();
119
+ const match = raw.match(/^(\d+(?:\.\d+)*)([a-z]?)$/i);
120
+ if (!match) return raw;
121
+
122
+ const numericSegments = match[1]
123
+ .split('.')
124
+ .map((segment) => String(parseInt(segment, 10)));
125
+ return `${numericSegments.join('.')}${match[2] || ''}`;
126
+ }
127
+
128
+ function extractPlanFileArtifacts(planContent, workspaceRoot) {
129
+ const artifacts = [];
130
+ const seen = new Set();
131
+
132
+ for (const line of planContent.split('\n')) {
133
+ const moveMatch = line.match(/^\s*-\s*(RENAME|MOVE):\s*(.+?)\s*->\s*(.+?)\s*$/i);
134
+ if (moveMatch) {
135
+ const operation = moveMatch[1].toLowerCase();
136
+ const from = moveMatch[2].replace(/^`|`$/g, '').trim();
137
+ const to = moveMatch[3].replace(/^`|`$/g, '').trim();
138
+ if (!from || !to || seen.has(`${operation}:${from}->${to}`)) continue;
139
+ seen.add(`${operation}:${from}->${to}`);
140
+ artifacts.push({
141
+ operation,
142
+ from,
143
+ to,
144
+ file: to,
145
+ exists: existsSync(join(workspaceRoot, to)),
146
+ });
147
+ continue;
148
+ }
149
+
150
+ const match = line.match(/^\s*-\s*(CREATE|MODIFY|DELETE|READ|TOUCH):\s*(.+?)\s*$/i);
151
+ if (!match) continue;
152
+
153
+ const operation = match[1].toLowerCase();
154
+ const file = match[2].replace(/^`|`$/g, '').trim();
155
+ if (!file || seen.has(`${operation}:${file}`)) continue;
156
+ seen.add(`${operation}:${file}`);
157
+ artifacts.push({
158
+ operation,
159
+ file,
160
+ exists: existsSync(join(workspaceRoot, file)),
161
+ });
162
+ }
163
+
164
+ return artifacts;
165
+ }
166
+
167
+ export function updateRoadmapPhaseStatus(roadmap, phaseNumber, status) {
168
+ const marker = PHASE_STATUS_MARKERS[status];
169
+ if (!marker) {
170
+ throw new Error(`Unsupported phase status: ${status}`);
171
+ }
172
+
173
+ const normalizedTarget = normalizePhaseToken(phaseNumber);
174
+ const lines = roadmap.split('\n');
175
+ const overviewIndexes = [];
176
+ const detailSections = [];
177
+ let inArchivedDetails = false;
178
+
179
+ for (let index = 0; index < lines.length; index += 1) {
180
+ if (DETAILS_OPEN_RE.test(lines[index]) && !DETAILS_CLOSE_RE.test(lines[index])) {
181
+ inArchivedDetails = true;
182
+ continue;
183
+ }
184
+ if (DETAILS_CLOSE_RE.test(lines[index])) {
185
+ inArchivedDetails = false;
186
+ continue;
187
+ }
188
+ if (inArchivedDetails) continue;
189
+
190
+ const overviewMatch = lines[index].match(ROADMAP_PHASE_STATUS_RE);
191
+ if (overviewMatch && normalizePhaseToken(overviewMatch[4]) === normalizedTarget) {
192
+ overviewIndexes.push({ index, match: overviewMatch });
193
+ continue;
194
+ }
195
+
196
+ const headingMatch = lines[index].match(PHASE_DETAIL_HEADING_RE);
197
+ if (headingMatch && normalizePhaseToken(headingMatch[1]) === normalizedTarget) {
198
+ let statusIndex = -1;
199
+ let statusMatch = null;
200
+ for (let detailIndex = index + 1; detailIndex < lines.length; detailIndex += 1) {
201
+ if (/^#+\s+/.test(lines[detailIndex])) break;
202
+ const candidate = lines[detailIndex].match(PHASE_DETAIL_STATUS_RE);
203
+ if (candidate) {
204
+ statusIndex = detailIndex;
205
+ statusMatch = candidate;
206
+ break;
207
+ }
208
+ }
209
+ detailSections.push({ headingIndex: index, statusIndex, statusMatch });
210
+ }
211
+ }
212
+
213
+ if (overviewIndexes.length === 0) {
214
+ throw new Error(`Phase ${phaseNumber} was not found in ROADMAP.md`);
215
+ }
216
+
217
+ if (overviewIndexes.length > 1) {
218
+ throw new Error(`Phase ${phaseNumber} matched multiple ROADMAP.md entries`);
219
+ }
220
+
221
+ if (detailSections.length > 1) {
222
+ throw new Error(`Phase ${phaseNumber} matched multiple Phase Details sections in ROADMAP.md`);
223
+ }
224
+
225
+ if (detailSections.length === 1 && detailSections[0].statusIndex === -1) {
226
+ throw new Error(`Phase ${phaseNumber} has a Phase Details section but no **Status** line in ROADMAP.md`);
227
+ }
228
+
229
+ const updatedLines = [...lines];
230
+ const overview = overviewIndexes[0];
231
+ updatedLines[overview.index] = `${overview.match[1]}${marker}${overview.match[3]}`;
232
+
233
+ if (detailSections.length === 1) {
234
+ const detail = detailSections[0];
235
+ updatedLines[detail.statusIndex] = `${detail.statusMatch[1]}${marker}${detail.statusMatch[3]}`;
236
+ }
237
+
238
+ return updatedLines.join('\n');
239
+ }
240
+
241
+ export function cmdPhaseStatus(...args) {
242
+ const { args: normalizedArgs, planningDir, invalid, error } = resolveWorkspaceContext(args);
243
+ if (invalid) {
244
+ console.error(error);
245
+ process.exitCode = 1;
246
+ return;
247
+ }
248
+ const roadmapPath = join(planningDir, 'ROADMAP.md');
249
+ const [phaseNumber, status] = normalizedArgs;
250
+
251
+ if (!phaseNumber || !status) {
252
+ console.error('Usage: gsdd phase-status <phase-number> <not_started|todo|in_progress|done>');
253
+ process.exitCode = 1;
254
+ return;
255
+ }
256
+
257
+ if (!existsSync(roadmapPath)) {
258
+ console.error('No ROADMAP.md found. Run the new-project workflow first.');
259
+ process.exitCode = 1;
260
+ return;
261
+ }
262
+
263
+ try {
264
+ const roadmap = readFileSync(roadmapPath, 'utf-8');
265
+ const updated = updateRoadmapPhaseStatus(roadmap, phaseNumber, status);
266
+ const changed = updated !== roadmap;
267
+ if (changed) {
268
+ writeFileSync(roadmapPath, updated);
269
+ try { writeFingerprint(planningDir); } catch { /* best-effort */ }
270
+ }
271
+ output({ phase: phaseNumber, status, roadmap: '.planning/ROADMAP.md', changed });
272
+ } catch (error) {
273
+ console.error(error.message);
274
+ process.exitCode = 1;
275
+ }
276
+ }
277
+
278
+ export function cmdFindPhase(...args) {
279
+ const { args: normalizedArgs, planningDir, invalid, error } = resolveWorkspaceContext(args);
280
+ if (invalid) {
281
+ output({ error });
282
+ process.exitCode = 1;
283
+ return;
284
+ }
285
+ const phaseNum = normalizedArgs[0];
286
+
287
+ if (!existsSync(planningDir)) {
288
+ output({ error: 'No .planning/ directory found. Run `npx -y gsdd-cli init` then the new-project workflow first.' });
289
+ return;
290
+ }
291
+
292
+ const roadmapPath = join(planningDir, 'ROADMAP.md');
293
+ if (!existsSync(roadmapPath)) {
294
+ output({ error: 'No ROADMAP.md found. Run the new-project workflow first.' });
295
+ return;
296
+ }
297
+
298
+ const phasesDir = join(planningDir, 'phases');
299
+ const researchDir = join(planningDir, 'research');
300
+
301
+ if (phaseNum) {
302
+ const plans = findFiles(phasesDir, `${padPhase(phaseNum)}-PLAN`);
303
+ const summaries = findFiles(phasesDir, `${padPhase(phaseNum)}-SUMMARY`);
304
+
305
+ output({
306
+ phase: normalizePhaseToken(phaseNum),
307
+ directory: phasesDir,
308
+ plans,
309
+ summaries,
310
+ hasResearch: existsSync(researchDir) && readdirSync(researchDir).length > 0,
311
+ incomplete: plans.filter((p) => !summaries.some((s) => s.replace('SUMMARY', '') === p.replace('PLAN', ''))),
312
+ });
313
+ return;
314
+ }
315
+
316
+ const allArtifacts = listPhaseArtifacts(phasesDir);
317
+ const plans = allArtifacts.filter((artifact) => artifact.kind === 'PLAN');
318
+ const summaries = allArtifacts.filter((artifact) => artifact.kind === 'SUMMARY');
319
+
320
+ const roadmap = readFileSync(roadmapPath, 'utf-8');
321
+ const phases = parsePhaseStatuses(roadmap);
322
+
323
+ output({
324
+ phases,
325
+ planCount: plans.length,
326
+ summaryCount: summaries.length,
327
+ currentPhase: phases.find((p) => p.status === 'in_progress') || phases.find((p) => p.status === 'not_started') || null,
328
+ hasResearch: existsSync(researchDir) && readdirSync(researchDir).length > 0,
329
+ });
330
+ }
331
+
332
+ export function cmdVerify(...args) {
333
+ const { args: normalizedArgs, workspaceRoot, planningDir, invalid, error } = resolveWorkspaceContext(args);
334
+ if (invalid) {
335
+ console.error(error);
336
+ process.exitCode = 1;
337
+ return;
338
+ }
339
+ const phaseNum = normalizedArgs[0];
340
+ if (!phaseNum) {
341
+ console.error('Usage: gsdd verify <phase-number>');
342
+ process.exitCode = 1; return;
343
+ }
344
+
345
+ if (!existsSync(planningDir)) {
346
+ console.error('No .planning/ directory found.');
347
+ process.exitCode = 1; return;
348
+ }
349
+ const phasesDir = join(planningDir, 'phases');
350
+ const matchingPlans = findFiles(phasesDir, `${padPhase(phaseNum)}-PLAN`);
351
+ const matchingSummaries = findFiles(phasesDir, `${padPhase(phaseNum)}-SUMMARY`);
352
+ const artifacts = matchingPlans.flatMap((planPath) => {
353
+ const fullPath = join(phasesDir, planPath);
354
+ return existsSync(fullPath)
355
+ ? extractPlanFileArtifacts(readFileSync(fullPath, 'utf-8'), workspaceRoot)
356
+ : [];
357
+ });
358
+
359
+ const result = {
360
+ phase: normalizePhaseToken(phaseNum),
361
+ exists: matchingPlans.length > 0,
362
+ plans: matchingPlans,
363
+ summaries: matchingSummaries,
364
+ artifacts,
365
+ allExist: artifacts.every((artifact) => artifact.exists),
366
+ verified: matchingPlans.length > 0 && matchingSummaries.length > 0,
367
+ };
368
+ output(result);
369
+ }
370
+
371
+ export function cmdScaffold(...args) {
372
+ const { args: normalizedArgs, planningDir, invalid, error } = resolveWorkspaceContext(args);
373
+ if (invalid) {
374
+ console.error(error);
375
+ process.exitCode = 1;
376
+ return;
377
+ }
378
+ const kind = normalizedArgs[0];
379
+ const phaseNum = normalizedArgs[1];
380
+ const phaseName = normalizedArgs[2] || 'phase';
381
+ if (kind !== 'phase' || !phaseNum) {
382
+ console.error('Usage: gsdd scaffold phase <phase-number> [phase-name]');
383
+ process.exitCode = 1; return;
384
+ }
385
+ mkdirSync(planningDir, { recursive: true });
386
+ const phasesDir = join(planningDir, 'phases');
387
+ mkdirSync(phasesDir, { recursive: true });
388
+ const dirName = `${padPhase(phaseNum)}-${phaseName.replace(/\s+/g, '-').toLowerCase()}`;
389
+ const phaseDir = join(phasesDir, dirName);
390
+ mkdirSync(phaseDir, { recursive: true });
391
+ const planPath = join(phaseDir, `${padPhase(phaseNum)}-PLAN.md`);
392
+ const created = !existsSync(planPath);
393
+ if (created) {
394
+ writeFileSync(planPath, `# Phase ${phaseNum} Plan\n\n## Goal\n- \n\n## Tasks\n- [ ] \n`);
395
+ }
396
+ output({ created, path: planPath.replace(/\\/g, '/'), phase: normalizePhaseToken(phaseNum) });
397
+ }