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