@howlil/ez-agents 2.0.0 → 3.0.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 (145) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +157 -110
  3. package/README.zh-CN.md +84 -84
  4. package/agents/ez-plan-checker.md +2 -2
  5. package/agents/ez-research-synthesizer.md +1 -1
  6. package/agents/ez-ui-auditor.md +0 -2
  7. package/agents/ez-ui-checker.md +2 -4
  8. package/agents/ez-ui-researcher.md +0 -2
  9. package/agents/ez-verifier.md +1 -1
  10. package/bin/install.js +211 -211
  11. package/commands/ez/debug.md +1 -1
  12. package/commands/ez/map-codebase.md +1 -1
  13. package/commands/ez/reapply-patches.md +3 -3
  14. package/commands/ez/research-phase.md +1 -1
  15. package/{get-shit-done → ez-agents}/bin/ez-tools.cjs +1 -1
  16. package/{get-shit-done → ez-agents}/bin/lib/assistant-adapter.cjs +205 -205
  17. package/{get-shit-done → ez-agents}/bin/lib/audit-exec.cjs +150 -150
  18. package/{get-shit-done → ez-agents}/bin/lib/auth.cjs +175 -175
  19. package/{get-shit-done → ez-agents}/bin/lib/circuit-breaker.cjs +118 -118
  20. package/{get-shit-done → ez-agents}/bin/lib/commands.cjs +666 -666
  21. package/{get-shit-done → ez-agents}/bin/lib/config.cjs +183 -183
  22. package/{get-shit-done → ez-agents}/bin/lib/core.cjs +495 -495
  23. package/{get-shit-done → ez-agents}/bin/lib/file-lock.cjs +236 -236
  24. package/{get-shit-done → ez-agents}/bin/lib/frontmatter.cjs +299 -299
  25. package/{get-shit-done → ez-agents}/bin/lib/fs-utils.cjs +153 -153
  26. package/{get-shit-done → ez-agents}/bin/lib/git-utils.cjs +203 -203
  27. package/{get-shit-done → ez-agents}/bin/lib/health-check.cjs +163 -163
  28. package/{get-shit-done → ez-agents}/bin/lib/index.cjs +113 -113
  29. package/{get-shit-done → ez-agents}/bin/lib/init.cjs +710 -710
  30. package/{get-shit-done → ez-agents}/bin/lib/logger.cjs +117 -117
  31. package/{get-shit-done → ez-agents}/bin/lib/milestone.cjs +241 -241
  32. package/{get-shit-done → ez-agents}/bin/lib/model-provider.cjs +146 -146
  33. package/{get-shit-done → ez-agents}/bin/lib/phase.cjs +908 -908
  34. package/{get-shit-done → ez-agents}/bin/lib/retry.cjs +119 -119
  35. package/{get-shit-done → ez-agents}/bin/lib/roadmap.cjs +305 -305
  36. package/{get-shit-done → ez-agents}/bin/lib/safe-exec.cjs +128 -128
  37. package/{get-shit-done → ez-agents}/bin/lib/safe-path.cjs +130 -130
  38. package/{get-shit-done → ez-agents}/bin/lib/state.cjs +721 -721
  39. package/{get-shit-done → ez-agents}/bin/lib/temp-file.cjs +239 -239
  40. package/{get-shit-done → ez-agents}/bin/lib/template.cjs +222 -222
  41. package/{get-shit-done → ez-agents}/bin/lib/test-file-lock.cjs +112 -112
  42. package/{get-shit-done → ez-agents}/bin/lib/test-graceful.cjs +93 -93
  43. package/{get-shit-done → ez-agents}/bin/lib/test-logger.cjs +60 -60
  44. package/{get-shit-done → ez-agents}/bin/lib/test-safe-exec.cjs +38 -38
  45. package/{get-shit-done → ez-agents}/bin/lib/test-safe-path.cjs +33 -33
  46. package/{get-shit-done → ez-agents}/bin/lib/test-temp-file.cjs +125 -125
  47. package/{get-shit-done → ez-agents}/bin/lib/timeout-exec.cjs +62 -62
  48. package/{get-shit-done → ez-agents}/bin/lib/verify.cjs +820 -820
  49. package/{get-shit-done → ez-agents}/references/checkpoints.md +776 -776
  50. package/{get-shit-done → ez-agents}/references/questioning.md +162 -162
  51. package/{get-shit-done → ez-agents}/references/tdd.md +263 -263
  52. package/{get-shit-done → ez-agents}/templates/codebase/concerns.md +310 -310
  53. package/{get-shit-done → ez-agents}/templates/codebase/conventions.md +307 -307
  54. package/{get-shit-done → ez-agents}/templates/codebase/integrations.md +280 -280
  55. package/{get-shit-done → ez-agents}/templates/codebase/stack.md +186 -186
  56. package/{get-shit-done → ez-agents}/templates/codebase/testing.md +480 -480
  57. package/{get-shit-done → ez-agents}/templates/config.json +37 -37
  58. package/{get-shit-done → ez-agents}/templates/continue-here.md +78 -78
  59. package/{get-shit-done → ez-agents}/templates/milestone-archive.md +123 -123
  60. package/{get-shit-done → ez-agents}/templates/milestone.md +115 -115
  61. package/{get-shit-done → ez-agents}/templates/requirements.md +231 -231
  62. package/{get-shit-done → ez-agents}/templates/research-project/ARCHITECTURE.md +204 -204
  63. package/{get-shit-done → ez-agents}/templates/research-project/FEATURES.md +147 -147
  64. package/{get-shit-done → ez-agents}/templates/research-project/PITFALLS.md +200 -200
  65. package/{get-shit-done → ez-agents}/templates/research-project/STACK.md +120 -120
  66. package/{get-shit-done → ez-agents}/templates/research-project/SUMMARY.md +170 -170
  67. package/{get-shit-done → ez-agents}/templates/retrospective.md +54 -54
  68. package/{get-shit-done → ez-agents}/templates/roadmap.md +202 -202
  69. package/{get-shit-done → ez-agents}/templates/summary-minimal.md +41 -41
  70. package/{get-shit-done → ez-agents}/templates/summary-standard.md +48 -48
  71. package/{get-shit-done → ez-agents}/templates/summary.md +248 -248
  72. package/{get-shit-done → ez-agents}/templates/user-setup.md +311 -311
  73. package/{get-shit-done → ez-agents}/templates/verification-report.md +322 -322
  74. package/{get-shit-done → ez-agents}/workflows/add-phase.md +112 -112
  75. package/{get-shit-done → ez-agents}/workflows/add-tests.md +351 -351
  76. package/{get-shit-done → ez-agents}/workflows/add-todo.md +158 -158
  77. package/{get-shit-done → ez-agents}/workflows/audit-milestone.md +332 -332
  78. package/{get-shit-done → ez-agents}/workflows/autonomous.md +743 -743
  79. package/{get-shit-done → ez-agents}/workflows/check-todos.md +177 -177
  80. package/{get-shit-done → ez-agents}/workflows/cleanup.md +152 -152
  81. package/{get-shit-done → ez-agents}/workflows/complete-milestone.md +766 -766
  82. package/ez-agents/workflows/debug.md +0 -0
  83. package/{get-shit-done → ez-agents}/workflows/diagnose-issues.md +219 -219
  84. package/{get-shit-done → ez-agents}/workflows/discovery-phase.md +289 -289
  85. package/{get-shit-done → ez-agents}/workflows/discuss-phase.md +762 -762
  86. package/{get-shit-done → ez-agents}/workflows/execute-phase.md +468 -468
  87. package/{get-shit-done → ez-agents}/workflows/execute-plan.md +483 -483
  88. package/{get-shit-done → ez-agents}/workflows/health.md +159 -159
  89. package/{get-shit-done → ez-agents}/workflows/help.md +492 -492
  90. package/{get-shit-done → ez-agents}/workflows/insert-phase.md +130 -130
  91. package/{get-shit-done → ez-agents}/workflows/list-phase-assumptions.md +178 -178
  92. package/{get-shit-done → ez-agents}/workflows/map-codebase.md +316 -316
  93. package/{get-shit-done → ez-agents}/workflows/new-milestone.md +384 -384
  94. package/{get-shit-done → ez-agents}/workflows/new-project.md +1111 -1111
  95. package/{get-shit-done → ez-agents}/workflows/node-repair.md +92 -92
  96. package/{get-shit-done → ez-agents}/workflows/pause-work.md +122 -122
  97. package/{get-shit-done → ez-agents}/workflows/plan-milestone-gaps.md +274 -274
  98. package/{get-shit-done → ez-agents}/workflows/plan-phase.md +651 -651
  99. package/{get-shit-done → ez-agents}/workflows/progress.md +382 -382
  100. package/{get-shit-done → ez-agents}/workflows/quick.md +610 -610
  101. package/{get-shit-done → ez-agents}/workflows/remove-phase.md +155 -155
  102. package/{get-shit-done → ez-agents}/workflows/research-phase.md +74 -74
  103. package/{get-shit-done → ez-agents}/workflows/resume-project.md +307 -307
  104. package/{get-shit-done → ez-agents}/workflows/set-profile.md +81 -81
  105. package/{get-shit-done → ez-agents}/workflows/settings.md +242 -242
  106. package/{get-shit-done → ez-agents}/workflows/stats.md +57 -57
  107. package/{get-shit-done → ez-agents}/workflows/transition.md +544 -544
  108. package/{get-shit-done → ez-agents}/workflows/ui-phase.md +290 -290
  109. package/{get-shit-done → ez-agents}/workflows/ui-review.md +157 -157
  110. package/{get-shit-done → ez-agents}/workflows/update.md +320 -320
  111. package/{get-shit-done → ez-agents}/workflows/validate-phase.md +167 -167
  112. package/{get-shit-done → ez-agents}/workflows/verify-phase.md +243 -243
  113. package/{get-shit-done → ez-agents}/workflows/verify-work.md +5 -5
  114. package/hooks/dist/ez-check-update.js +81 -0
  115. package/hooks/dist/ez-context-monitor.js +141 -0
  116. package/hooks/dist/ez-statusline.js +115 -0
  117. package/package.json +13 -3
  118. package/scripts/build-hooks.js +43 -43
  119. package/scripts/run-tests.cjs +29 -29
  120. /package/{get-shit-done → ez-agents}/references/continuation-format.md +0 -0
  121. /package/{get-shit-done → ez-agents}/references/decimal-phase-calculation.md +0 -0
  122. /package/{get-shit-done → ez-agents}/references/git-integration.md +0 -0
  123. /package/{get-shit-done → ez-agents}/references/git-planning-commit.md +0 -0
  124. /package/{get-shit-done → ez-agents}/references/model-profile-resolution.md +0 -0
  125. /package/{get-shit-done → ez-agents}/references/model-profiles.md +0 -0
  126. /package/{get-shit-done → ez-agents}/references/phase-argument-parsing.md +0 -0
  127. /package/{get-shit-done → ez-agents}/references/planning-config.md +0 -0
  128. /package/{get-shit-done → ez-agents}/references/ui-brand.md +0 -0
  129. /package/{get-shit-done → ez-agents}/references/verification-patterns.md +0 -0
  130. /package/{get-shit-done → ez-agents}/templates/DEBUG.md +0 -0
  131. /package/{get-shit-done → ez-agents}/templates/UAT.md +0 -0
  132. /package/{get-shit-done → ez-agents}/templates/UI-SPEC.md +0 -0
  133. /package/{get-shit-done → ez-agents}/templates/VALIDATION.md +0 -0
  134. /package/{get-shit-done → ez-agents}/templates/codebase/architecture.md +0 -0
  135. /package/{get-shit-done → ez-agents}/templates/codebase/structure.md +0 -0
  136. /package/{get-shit-done → ez-agents}/templates/context.md +0 -0
  137. /package/{get-shit-done → ez-agents}/templates/copilot-instructions.md +0 -0
  138. /package/{get-shit-done → ez-agents}/templates/debug-subagent-prompt.md +0 -0
  139. /package/{get-shit-done → ez-agents}/templates/discovery.md +0 -0
  140. /package/{get-shit-done → ez-agents}/templates/phase-prompt.md +0 -0
  141. /package/{get-shit-done → ez-agents}/templates/planner-subagent-prompt.md +0 -0
  142. /package/{get-shit-done → ez-agents}/templates/project.md +0 -0
  143. /package/{get-shit-done → ez-agents}/templates/research.md +0 -0
  144. /package/{get-shit-done → ez-agents}/templates/state.md +0 -0
  145. /package/{get-shit-done → ez-agents}/templates/summary-complex.md +0 -0
@@ -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
+ 'ez-planner': { quality: 'opus', balanced: 'opus', budget: 'sonnet' },
20
+ 'ez-roadmapper': { quality: 'opus', balanced: 'sonnet', budget: 'sonnet' },
21
+ 'ez-executor': { quality: 'opus', balanced: 'sonnet', budget: 'sonnet' },
22
+ 'ez-phase-researcher': { quality: 'opus', balanced: 'sonnet', budget: 'haiku' },
23
+ 'ez-project-researcher': { quality: 'opus', balanced: 'sonnet', budget: 'haiku' },
24
+ 'ez-research-synthesizer': { quality: 'sonnet', balanced: 'sonnet', budget: 'haiku' },
25
+ 'ez-debugger': { quality: 'opus', balanced: 'sonnet', budget: 'sonnet' },
26
+ 'ez-codebase-mapper': { quality: 'sonnet', balanced: 'haiku', budget: 'haiku' },
27
+ 'ez-verifier': { quality: 'sonnet', balanced: 'sonnet', budget: 'haiku' },
28
+ 'ez-plan-checker': { quality: 'sonnet', balanced: 'sonnet', budget: 'haiku' },
29
+ 'ez-integration-checker': { quality: 'sonnet', balanced: 'sonnet', budget: 'haiku' },
30
+ 'ez-nyquist-auditor': { quality: 'sonnet', balanced: 'sonnet', budget: 'haiku' },
31
+ 'ez-ui-researcher': { quality: 'opus', balanced: 'sonnet', budget: 'haiku' },
32
+ 'ez-ui-checker': { quality: 'sonnet', balanced: 'sonnet', budget: 'haiku' },
33
+ 'ez-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(), `${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
+ };