@howlil/ez-agents 2.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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +845 -0
  3. package/README.zh-CN.md +702 -0
  4. package/agents/ez-codebase-mapper.md +770 -0
  5. package/agents/ez-debugger.md +1255 -0
  6. package/agents/ez-executor.md +487 -0
  7. package/agents/ez-integration-checker.md +443 -0
  8. package/agents/ez-nyquist-auditor.md +176 -0
  9. package/agents/ez-phase-researcher.md +553 -0
  10. package/agents/ez-plan-checker.md +706 -0
  11. package/agents/ez-planner.md +1307 -0
  12. package/agents/ez-project-researcher.md +629 -0
  13. package/agents/ez-research-synthesizer.md +247 -0
  14. package/agents/ez-roadmapper.md +650 -0
  15. package/agents/ez-ui-auditor.md +441 -0
  16. package/agents/ez-ui-checker.md +302 -0
  17. package/agents/ez-ui-researcher.md +355 -0
  18. package/agents/ez-verifier.md +579 -0
  19. package/bin/install.js +2862 -0
  20. package/bin/update.js +214 -0
  21. package/commands/ez/add-phase.md +43 -0
  22. package/commands/ez/add-tests.md +41 -0
  23. package/commands/ez/add-todo.md +47 -0
  24. package/commands/ez/audit-milestone.md +36 -0
  25. package/commands/ez/autonomous.md +41 -0
  26. package/commands/ez/check-todos.md +45 -0
  27. package/commands/ez/cleanup.md +18 -0
  28. package/commands/ez/complete-milestone.md +136 -0
  29. package/commands/ez/debug.md +168 -0
  30. package/commands/ez/discuss-phase.md +90 -0
  31. package/commands/ez/execute-phase.md +41 -0
  32. package/commands/ez/health.md +22 -0
  33. package/commands/ez/help.md +22 -0
  34. package/commands/ez/insert-phase.md +32 -0
  35. package/commands/ez/join-discord.md +18 -0
  36. package/commands/ez/list-phase-assumptions.md +46 -0
  37. package/commands/ez/map-codebase.md +71 -0
  38. package/commands/ez/new-milestone.md +44 -0
  39. package/commands/ez/new-project.md +42 -0
  40. package/commands/ez/pause-work.md +38 -0
  41. package/commands/ez/plan-milestone-gaps.md +34 -0
  42. package/commands/ez/plan-phase.md +45 -0
  43. package/commands/ez/progress.md +24 -0
  44. package/commands/ez/quick.md +45 -0
  45. package/commands/ez/reapply-patches.md +124 -0
  46. package/commands/ez/remove-phase.md +31 -0
  47. package/commands/ez/research-phase.md +190 -0
  48. package/commands/ez/resume-work.md +40 -0
  49. package/commands/ez/set-profile.md +34 -0
  50. package/commands/ez/settings.md +36 -0
  51. package/commands/ez/stats.md +18 -0
  52. package/commands/ez/ui-phase.md +34 -0
  53. package/commands/ez/ui-review.md +32 -0
  54. package/commands/ez/update.md +37 -0
  55. package/commands/ez/validate-phase.md +35 -0
  56. package/commands/ez/verify-work.md +38 -0
  57. package/get-shit-done/bin/ez-tools.cjs +598 -0
  58. package/get-shit-done/bin/lib/assistant-adapter.cjs +205 -0
  59. package/get-shit-done/bin/lib/audit-exec.cjs +150 -0
  60. package/get-shit-done/bin/lib/auth.cjs +175 -0
  61. package/get-shit-done/bin/lib/circuit-breaker.cjs +118 -0
  62. package/get-shit-done/bin/lib/commands.cjs +666 -0
  63. package/get-shit-done/bin/lib/config.cjs +183 -0
  64. package/get-shit-done/bin/lib/core.cjs +495 -0
  65. package/get-shit-done/bin/lib/file-lock.cjs +236 -0
  66. package/get-shit-done/bin/lib/frontmatter.cjs +299 -0
  67. package/get-shit-done/bin/lib/fs-utils.cjs +153 -0
  68. package/get-shit-done/bin/lib/git-utils.cjs +203 -0
  69. package/get-shit-done/bin/lib/health-check.cjs +163 -0
  70. package/get-shit-done/bin/lib/index.cjs +113 -0
  71. package/get-shit-done/bin/lib/init.cjs +710 -0
  72. package/get-shit-done/bin/lib/logger.cjs +117 -0
  73. package/get-shit-done/bin/lib/milestone.cjs +241 -0
  74. package/get-shit-done/bin/lib/model-provider.cjs +146 -0
  75. package/get-shit-done/bin/lib/phase.cjs +908 -0
  76. package/get-shit-done/bin/lib/retry.cjs +119 -0
  77. package/get-shit-done/bin/lib/roadmap.cjs +305 -0
  78. package/get-shit-done/bin/lib/safe-exec.cjs +128 -0
  79. package/get-shit-done/bin/lib/safe-path.cjs +130 -0
  80. package/get-shit-done/bin/lib/state.cjs +721 -0
  81. package/get-shit-done/bin/lib/temp-file.cjs +239 -0
  82. package/get-shit-done/bin/lib/template.cjs +222 -0
  83. package/get-shit-done/bin/lib/test-file-lock.cjs +112 -0
  84. package/get-shit-done/bin/lib/test-graceful.cjs +93 -0
  85. package/get-shit-done/bin/lib/test-logger.cjs +60 -0
  86. package/get-shit-done/bin/lib/test-safe-exec.cjs +38 -0
  87. package/get-shit-done/bin/lib/test-safe-path.cjs +33 -0
  88. package/get-shit-done/bin/lib/test-temp-file.cjs +125 -0
  89. package/get-shit-done/bin/lib/timeout-exec.cjs +62 -0
  90. package/get-shit-done/bin/lib/verify.cjs +820 -0
  91. package/get-shit-done/references/checkpoints.md +776 -0
  92. package/get-shit-done/references/continuation-format.md +249 -0
  93. package/get-shit-done/references/decimal-phase-calculation.md +65 -0
  94. package/get-shit-done/references/git-integration.md +248 -0
  95. package/get-shit-done/references/git-planning-commit.md +38 -0
  96. package/get-shit-done/references/model-profile-resolution.md +34 -0
  97. package/get-shit-done/references/model-profiles.md +93 -0
  98. package/get-shit-done/references/phase-argument-parsing.md +61 -0
  99. package/get-shit-done/references/planning-config.md +200 -0
  100. package/get-shit-done/references/questioning.md +162 -0
  101. package/get-shit-done/references/tdd.md +263 -0
  102. package/get-shit-done/references/ui-brand.md +160 -0
  103. package/get-shit-done/references/verification-patterns.md +612 -0
  104. package/get-shit-done/templates/DEBUG.md +164 -0
  105. package/get-shit-done/templates/UAT.md +247 -0
  106. package/get-shit-done/templates/UI-SPEC.md +100 -0
  107. package/get-shit-done/templates/VALIDATION.md +76 -0
  108. package/get-shit-done/templates/codebase/architecture.md +255 -0
  109. package/get-shit-done/templates/codebase/concerns.md +310 -0
  110. package/get-shit-done/templates/codebase/conventions.md +307 -0
  111. package/get-shit-done/templates/codebase/integrations.md +280 -0
  112. package/get-shit-done/templates/codebase/stack.md +186 -0
  113. package/get-shit-done/templates/codebase/structure.md +285 -0
  114. package/get-shit-done/templates/codebase/testing.md +480 -0
  115. package/get-shit-done/templates/config.json +37 -0
  116. package/get-shit-done/templates/context.md +352 -0
  117. package/get-shit-done/templates/continue-here.md +78 -0
  118. package/get-shit-done/templates/copilot-instructions.md +7 -0
  119. package/get-shit-done/templates/debug-subagent-prompt.md +91 -0
  120. package/get-shit-done/templates/discovery.md +146 -0
  121. package/get-shit-done/templates/milestone-archive.md +123 -0
  122. package/get-shit-done/templates/milestone.md +115 -0
  123. package/get-shit-done/templates/phase-prompt.md +610 -0
  124. package/get-shit-done/templates/planner-subagent-prompt.md +117 -0
  125. package/get-shit-done/templates/project.md +184 -0
  126. package/get-shit-done/templates/requirements.md +231 -0
  127. package/get-shit-done/templates/research-project/ARCHITECTURE.md +204 -0
  128. package/get-shit-done/templates/research-project/FEATURES.md +147 -0
  129. package/get-shit-done/templates/research-project/PITFALLS.md +200 -0
  130. package/get-shit-done/templates/research-project/STACK.md +120 -0
  131. package/get-shit-done/templates/research-project/SUMMARY.md +170 -0
  132. package/get-shit-done/templates/research.md +552 -0
  133. package/get-shit-done/templates/retrospective.md +54 -0
  134. package/get-shit-done/templates/roadmap.md +202 -0
  135. package/get-shit-done/templates/state.md +176 -0
  136. package/get-shit-done/templates/summary-complex.md +59 -0
  137. package/get-shit-done/templates/summary-minimal.md +41 -0
  138. package/get-shit-done/templates/summary-standard.md +48 -0
  139. package/get-shit-done/templates/summary.md +248 -0
  140. package/get-shit-done/templates/user-setup.md +311 -0
  141. package/get-shit-done/templates/verification-report.md +322 -0
  142. package/get-shit-done/workflows/add-phase.md +112 -0
  143. package/get-shit-done/workflows/add-tests.md +351 -0
  144. package/get-shit-done/workflows/add-todo.md +158 -0
  145. package/get-shit-done/workflows/audit-milestone.md +332 -0
  146. package/get-shit-done/workflows/autonomous.md +743 -0
  147. package/get-shit-done/workflows/check-todos.md +177 -0
  148. package/get-shit-done/workflows/cleanup.md +152 -0
  149. package/get-shit-done/workflows/complete-milestone.md +766 -0
  150. package/get-shit-done/workflows/diagnose-issues.md +219 -0
  151. package/get-shit-done/workflows/discovery-phase.md +289 -0
  152. package/get-shit-done/workflows/discuss-phase.md +762 -0
  153. package/get-shit-done/workflows/execute-phase.md +468 -0
  154. package/get-shit-done/workflows/execute-plan.md +483 -0
  155. package/get-shit-done/workflows/health.md +159 -0
  156. package/get-shit-done/workflows/help.md +492 -0
  157. package/get-shit-done/workflows/insert-phase.md +130 -0
  158. package/get-shit-done/workflows/list-phase-assumptions.md +178 -0
  159. package/get-shit-done/workflows/map-codebase.md +316 -0
  160. package/get-shit-done/workflows/new-milestone.md +384 -0
  161. package/get-shit-done/workflows/new-project.md +1111 -0
  162. package/get-shit-done/workflows/node-repair.md +92 -0
  163. package/get-shit-done/workflows/pause-work.md +122 -0
  164. package/get-shit-done/workflows/plan-milestone-gaps.md +274 -0
  165. package/get-shit-done/workflows/plan-phase.md +651 -0
  166. package/get-shit-done/workflows/progress.md +382 -0
  167. package/get-shit-done/workflows/quick.md +610 -0
  168. package/get-shit-done/workflows/remove-phase.md +155 -0
  169. package/get-shit-done/workflows/research-phase.md +74 -0
  170. package/get-shit-done/workflows/resume-project.md +307 -0
  171. package/get-shit-done/workflows/set-profile.md +81 -0
  172. package/get-shit-done/workflows/settings.md +242 -0
  173. package/get-shit-done/workflows/stats.md +57 -0
  174. package/get-shit-done/workflows/transition.md +544 -0
  175. package/get-shit-done/workflows/ui-phase.md +290 -0
  176. package/get-shit-done/workflows/ui-review.md +157 -0
  177. package/get-shit-done/workflows/update.md +320 -0
  178. package/get-shit-done/workflows/validate-phase.md +167 -0
  179. package/get-shit-done/workflows/verify-phase.md +243 -0
  180. package/get-shit-done/workflows/verify-work.md +584 -0
  181. package/package.json +55 -0
  182. package/scripts/build-hooks.js +43 -0
  183. package/scripts/run-tests.cjs +29 -0
@@ -0,0 +1,666 @@
1
+ /**
2
+ * Commands — Standalone utility commands
3
+ */
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { execSync } = require('child_process');
7
+ const { safeReadFile, loadConfig, isGitIgnored, execGit, normalizePhaseName, comparePhaseNum, getArchivedPhaseDirs, generateSlugInternal, getMilestoneInfo, resolveModelInternal, MODEL_PROFILES, toPosixPath, output, error, findPhaseInternal } = require('./core.cjs');
8
+ const { extractFrontmatter } = require('./frontmatter.cjs');
9
+
10
+ function cmdGenerateSlug(text, raw) {
11
+ if (!text) {
12
+ error('text required for slug generation');
13
+ }
14
+
15
+ const slug = text
16
+ .toLowerCase()
17
+ .replace(/[^a-z0-9]+/g, '-')
18
+ .replace(/^-+|-+$/g, '');
19
+
20
+ const result = { slug };
21
+ output(result, raw, slug);
22
+ }
23
+
24
+ function cmdCurrentTimestamp(format, raw) {
25
+ const now = new Date();
26
+ let result;
27
+
28
+ switch (format) {
29
+ case 'date':
30
+ result = now.toISOString().split('T')[0];
31
+ break;
32
+ case 'filename':
33
+ result = now.toISOString().replace(/:/g, '-').replace(/\..+/, '');
34
+ break;
35
+ case 'full':
36
+ default:
37
+ result = now.toISOString();
38
+ break;
39
+ }
40
+
41
+ output({ timestamp: result }, raw, result);
42
+ }
43
+
44
+ function cmdListTodos(cwd, area, raw) {
45
+ const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
46
+
47
+ let count = 0;
48
+ const todos = [];
49
+
50
+ try {
51
+ const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
52
+
53
+ for (const file of files) {
54
+ try {
55
+ const content = fs.readFileSync(path.join(pendingDir, file), 'utf-8');
56
+ const createdMatch = content.match(/^created:\s*(.+)$/m);
57
+ const titleMatch = content.match(/^title:\s*(.+)$/m);
58
+ const areaMatch = content.match(/^area:\s*(.+)$/m);
59
+
60
+ const todoArea = areaMatch ? areaMatch[1].trim() : 'general';
61
+
62
+ // Apply area filter if specified
63
+ if (area && todoArea !== area) continue;
64
+
65
+ count++;
66
+ todos.push({
67
+ file,
68
+ created: createdMatch ? createdMatch[1].trim() : 'unknown',
69
+ title: titleMatch ? titleMatch[1].trim() : 'Untitled',
70
+ area: todoArea,
71
+ path: toPosixPath(path.join('.planning', 'todos', 'pending', file)),
72
+ });
73
+ } catch {}
74
+ }
75
+ } catch {}
76
+
77
+ const result = { count, todos };
78
+ output(result, raw, count.toString());
79
+ }
80
+
81
+ function cmdVerifyPathExists(cwd, targetPath, raw) {
82
+ if (!targetPath) {
83
+ error('path required for verification');
84
+ }
85
+
86
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
87
+
88
+ try {
89
+ const stats = fs.statSync(fullPath);
90
+ const type = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : 'other';
91
+ const result = { exists: true, type };
92
+ output(result, raw, 'true');
93
+ } catch {
94
+ const result = { exists: false, type: null };
95
+ output(result, raw, 'false');
96
+ }
97
+ }
98
+
99
+ function cmdHistoryDigest(cwd, raw) {
100
+ const phasesDir = path.join(cwd, '.planning', 'phases');
101
+ const digest = { phases: {}, decisions: [], tech_stack: new Set() };
102
+
103
+ // Collect all phase directories: archived + current
104
+ const allPhaseDirs = [];
105
+
106
+ // Add archived phases first (oldest milestones first)
107
+ const archived = getArchivedPhaseDirs(cwd);
108
+ for (const a of archived) {
109
+ allPhaseDirs.push({ name: a.name, fullPath: a.fullPath, milestone: a.milestone });
110
+ }
111
+
112
+ // Add current phases
113
+ if (fs.existsSync(phasesDir)) {
114
+ try {
115
+ const currentDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
116
+ .filter(e => e.isDirectory())
117
+ .map(e => e.name)
118
+ .sort();
119
+ for (const dir of currentDirs) {
120
+ allPhaseDirs.push({ name: dir, fullPath: path.join(phasesDir, dir), milestone: null });
121
+ }
122
+ } catch {}
123
+ }
124
+
125
+ if (allPhaseDirs.length === 0) {
126
+ digest.tech_stack = [];
127
+ output(digest, raw);
128
+ return;
129
+ }
130
+
131
+ try {
132
+ for (const { name: dir, fullPath: dirPath } of allPhaseDirs) {
133
+ const summaries = fs.readdirSync(dirPath).filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
134
+
135
+ for (const summary of summaries) {
136
+ try {
137
+ const content = fs.readFileSync(path.join(dirPath, summary), 'utf-8');
138
+ const fm = extractFrontmatter(content);
139
+
140
+ const phaseNum = fm.phase || dir.split('-')[0];
141
+
142
+ if (!digest.phases[phaseNum]) {
143
+ digest.phases[phaseNum] = {
144
+ name: fm.name || dir.split('-').slice(1).join(' ') || 'Unknown',
145
+ provides: new Set(),
146
+ affects: new Set(),
147
+ patterns: new Set(),
148
+ };
149
+ }
150
+
151
+ // Merge provides
152
+ if (fm['dependency-graph'] && fm['dependency-graph'].provides) {
153
+ fm['dependency-graph'].provides.forEach(p => digest.phases[phaseNum].provides.add(p));
154
+ } else if (fm.provides) {
155
+ fm.provides.forEach(p => digest.phases[phaseNum].provides.add(p));
156
+ }
157
+
158
+ // Merge affects
159
+ if (fm['dependency-graph'] && fm['dependency-graph'].affects) {
160
+ fm['dependency-graph'].affects.forEach(a => digest.phases[phaseNum].affects.add(a));
161
+ }
162
+
163
+ // Merge patterns
164
+ if (fm['patterns-established']) {
165
+ fm['patterns-established'].forEach(p => digest.phases[phaseNum].patterns.add(p));
166
+ }
167
+
168
+ // Merge decisions
169
+ if (fm['key-decisions']) {
170
+ fm['key-decisions'].forEach(d => {
171
+ digest.decisions.push({ phase: phaseNum, decision: d });
172
+ });
173
+ }
174
+
175
+ // Merge tech stack
176
+ if (fm['tech-stack'] && fm['tech-stack'].added) {
177
+ fm['tech-stack'].added.forEach(t => digest.tech_stack.add(typeof t === 'string' ? t : t.name));
178
+ }
179
+
180
+ } catch (e) {
181
+ // Skip malformed summaries
182
+ }
183
+ }
184
+ }
185
+
186
+ // Convert Sets to Arrays for JSON output
187
+ Object.keys(digest.phases).forEach(p => {
188
+ digest.phases[p].provides = [...digest.phases[p].provides];
189
+ digest.phases[p].affects = [...digest.phases[p].affects];
190
+ digest.phases[p].patterns = [...digest.phases[p].patterns];
191
+ });
192
+ digest.tech_stack = [...digest.tech_stack];
193
+
194
+ output(digest, raw);
195
+ } catch (e) {
196
+ error('Failed to generate history digest: ' + e.message);
197
+ }
198
+ }
199
+
200
+ function cmdResolveModel(cwd, agentType, raw) {
201
+ if (!agentType) {
202
+ error('agent-type required');
203
+ }
204
+
205
+ const config = loadConfig(cwd);
206
+ const profile = config.model_profile || 'balanced';
207
+ const model = resolveModelInternal(cwd, agentType);
208
+
209
+ const agentModels = MODEL_PROFILES[agentType];
210
+ const result = agentModels
211
+ ? { model, profile }
212
+ : { model, profile, unknown_agent: true };
213
+ output(result, raw, model);
214
+ }
215
+
216
+ function cmdCommit(cwd, message, files, raw, amend) {
217
+ if (!message && !amend) {
218
+ error('commit message required');
219
+ }
220
+
221
+ const config = loadConfig(cwd);
222
+
223
+ // Check commit_docs config
224
+ if (!config.commit_docs) {
225
+ const result = { committed: false, hash: null, reason: 'skipped_commit_docs_false' };
226
+ output(result, raw, 'skipped');
227
+ return;
228
+ }
229
+
230
+ // Check if .planning is gitignored
231
+ if (isGitIgnored(cwd, '.planning')) {
232
+ const result = { committed: false, hash: null, reason: 'skipped_gitignored' };
233
+ output(result, raw, 'skipped');
234
+ return;
235
+ }
236
+
237
+ // Stage files
238
+ const filesToStage = files && files.length > 0 ? files : ['.planning/'];
239
+ for (const file of filesToStage) {
240
+ execGit(cwd, ['add', file]);
241
+ }
242
+
243
+ // Commit
244
+ const commitArgs = amend ? ['commit', '--amend', '--no-edit'] : ['commit', '-m', message];
245
+ const commitResult = execGit(cwd, commitArgs);
246
+ if (commitResult.exitCode !== 0) {
247
+ if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
248
+ const result = { committed: false, hash: null, reason: 'nothing_to_commit' };
249
+ output(result, raw, 'nothing');
250
+ return;
251
+ }
252
+ const result = { committed: false, hash: null, reason: 'nothing_to_commit', error: commitResult.stderr };
253
+ output(result, raw, 'nothing');
254
+ return;
255
+ }
256
+
257
+ // Get short hash
258
+ const hashResult = execGit(cwd, ['rev-parse', '--short', 'HEAD']);
259
+ const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
260
+ const result = { committed: true, hash, reason: 'committed' };
261
+ output(result, raw, hash || 'committed');
262
+ }
263
+
264
+ function cmdSummaryExtract(cwd, summaryPath, fields, raw) {
265
+ if (!summaryPath) {
266
+ error('summary-path required for summary-extract');
267
+ }
268
+
269
+ const fullPath = path.join(cwd, summaryPath);
270
+
271
+ if (!fs.existsSync(fullPath)) {
272
+ output({ error: 'File not found', path: summaryPath }, raw);
273
+ return;
274
+ }
275
+
276
+ const content = fs.readFileSync(fullPath, 'utf-8');
277
+ const fm = extractFrontmatter(content);
278
+
279
+ // Parse key-decisions into structured format
280
+ const parseDecisions = (decisionsList) => {
281
+ if (!decisionsList || !Array.isArray(decisionsList)) return [];
282
+ return decisionsList.map(d => {
283
+ const colonIdx = d.indexOf(':');
284
+ if (colonIdx > 0) {
285
+ return {
286
+ summary: d.substring(0, colonIdx).trim(),
287
+ rationale: d.substring(colonIdx + 1).trim(),
288
+ };
289
+ }
290
+ return { summary: d, rationale: null };
291
+ });
292
+ };
293
+
294
+ // Build full result
295
+ const fullResult = {
296
+ path: summaryPath,
297
+ one_liner: fm['one-liner'] || null,
298
+ key_files: fm['key-files'] || [],
299
+ tech_added: (fm['tech-stack'] && fm['tech-stack'].added) || [],
300
+ patterns: fm['patterns-established'] || [],
301
+ decisions: parseDecisions(fm['key-decisions']),
302
+ requirements_completed: fm['requirements-completed'] || [],
303
+ };
304
+
305
+ // If fields specified, filter to only those fields
306
+ if (fields && fields.length > 0) {
307
+ const filtered = { path: summaryPath };
308
+ for (const field of fields) {
309
+ if (fullResult[field] !== undefined) {
310
+ filtered[field] = fullResult[field];
311
+ }
312
+ }
313
+ output(filtered, raw);
314
+ return;
315
+ }
316
+
317
+ output(fullResult, raw);
318
+ }
319
+
320
+ async function cmdWebsearch(query, options, raw) {
321
+ const apiKey = process.env.BRAVE_API_KEY;
322
+
323
+ if (!apiKey) {
324
+ // No key = silent skip, agent falls back to built-in WebSearch
325
+ output({ available: false, reason: 'BRAVE_API_KEY not set' }, raw, '');
326
+ return;
327
+ }
328
+
329
+ if (!query) {
330
+ output({ available: false, error: 'Query required' }, raw, '');
331
+ return;
332
+ }
333
+
334
+ const params = new URLSearchParams({
335
+ q: query,
336
+ count: String(options.limit || 10),
337
+ country: 'us',
338
+ search_lang: 'en',
339
+ text_decorations: 'false'
340
+ });
341
+
342
+ if (options.freshness) {
343
+ params.set('freshness', options.freshness);
344
+ }
345
+
346
+ try {
347
+ const response = await fetch(
348
+ `https://api.search.brave.com/res/v1/web/search?${params}`,
349
+ {
350
+ headers: {
351
+ 'Accept': 'application/json',
352
+ 'X-Subscription-Token': apiKey
353
+ }
354
+ }
355
+ );
356
+
357
+ if (!response.ok) {
358
+ output({ available: false, error: `API error: ${response.status}` }, raw, '');
359
+ return;
360
+ }
361
+
362
+ const data = await response.json();
363
+
364
+ const results = (data.web?.results || []).map(r => ({
365
+ title: r.title,
366
+ url: r.url,
367
+ description: r.description,
368
+ age: r.age || null
369
+ }));
370
+
371
+ output({
372
+ available: true,
373
+ query,
374
+ count: results.length,
375
+ results
376
+ }, raw, results.map(r => `${r.title}\n${r.url}\n${r.description}`).join('\n\n'));
377
+ } catch (err) {
378
+ output({ available: false, error: err.message }, raw, '');
379
+ }
380
+ }
381
+
382
+ function cmdProgressRender(cwd, format, raw) {
383
+ const phasesDir = path.join(cwd, '.planning', 'phases');
384
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
385
+ const milestone = getMilestoneInfo(cwd);
386
+
387
+ const phases = [];
388
+ let totalPlans = 0;
389
+ let totalSummaries = 0;
390
+
391
+ try {
392
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
393
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
394
+
395
+ for (const dir of dirs) {
396
+ const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
397
+ const phaseNum = dm ? dm[1] : dir;
398
+ const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
399
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
400
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
401
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
402
+
403
+ totalPlans += plans;
404
+ totalSummaries += summaries;
405
+
406
+ let status;
407
+ if (plans === 0) status = 'Pending';
408
+ else if (summaries >= plans) status = 'Complete';
409
+ else if (summaries > 0) status = 'In Progress';
410
+ else status = 'Planned';
411
+
412
+ phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
413
+ }
414
+ } catch {}
415
+
416
+ const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
417
+
418
+ if (format === 'table') {
419
+ // Render markdown table
420
+ const barWidth = 10;
421
+ const filled = Math.round((percent / 100) * barWidth);
422
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
423
+ let out = `# ${milestone.version} ${milestone.name}\n\n`;
424
+ out += `**Progress:** [${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)\n\n`;
425
+ out += `| Phase | Name | Plans | Status |\n`;
426
+ out += `|-------|------|-------|--------|\n`;
427
+ for (const p of phases) {
428
+ out += `| ${p.number} | ${p.name} | ${p.summaries}/${p.plans} | ${p.status} |\n`;
429
+ }
430
+ output({ rendered: out }, raw, out);
431
+ } else if (format === 'bar') {
432
+ const barWidth = 20;
433
+ const filled = Math.round((percent / 100) * barWidth);
434
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
435
+ const text = `[${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)`;
436
+ output({ bar: text, percent, completed: totalSummaries, total: totalPlans }, raw, text);
437
+ } else {
438
+ // JSON format
439
+ output({
440
+ milestone_version: milestone.version,
441
+ milestone_name: milestone.name,
442
+ phases,
443
+ total_plans: totalPlans,
444
+ total_summaries: totalSummaries,
445
+ percent,
446
+ }, raw);
447
+ }
448
+ }
449
+
450
+ function cmdTodoComplete(cwd, filename, raw) {
451
+ if (!filename) {
452
+ error('filename required for todo complete');
453
+ }
454
+
455
+ const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
456
+ const completedDir = path.join(cwd, '.planning', 'todos', 'completed');
457
+ const sourcePath = path.join(pendingDir, filename);
458
+
459
+ if (!fs.existsSync(sourcePath)) {
460
+ error(`Todo not found: ${filename}`);
461
+ }
462
+
463
+ // Ensure completed directory exists
464
+ fs.mkdirSync(completedDir, { recursive: true });
465
+
466
+ // Read, add completion timestamp, move
467
+ let content = fs.readFileSync(sourcePath, 'utf-8');
468
+ const today = new Date().toISOString().split('T')[0];
469
+ content = `completed: ${today}\n` + content;
470
+
471
+ fs.writeFileSync(path.join(completedDir, filename), content, 'utf-8');
472
+ fs.unlinkSync(sourcePath);
473
+
474
+ output({ completed: true, file: filename, date: today }, raw, 'completed');
475
+ }
476
+
477
+ function cmdScaffold(cwd, type, options, raw) {
478
+ const { phase, name } = options;
479
+ const padded = phase ? normalizePhaseName(phase) : '00';
480
+ const today = new Date().toISOString().split('T')[0];
481
+
482
+ // Find phase directory
483
+ const phaseInfo = phase ? findPhaseInternal(cwd, phase) : null;
484
+ const phaseDir = phaseInfo ? path.join(cwd, phaseInfo.directory) : null;
485
+
486
+ if (phase && !phaseDir && type !== 'phase-dir') {
487
+ error(`Phase ${phase} directory not found`);
488
+ }
489
+
490
+ let filePath, content;
491
+
492
+ switch (type) {
493
+ case 'context': {
494
+ filePath = path.join(phaseDir, `${padded}-CONTEXT.md`);
495
+ content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — Context\n\n## Decisions\n\n_Decisions will be captured during /gsd:discuss-phase ${phase}_\n\n## Discretion Areas\n\n_Areas where the executor can use judgment_\n\n## Deferred Ideas\n\n_Ideas to consider later_\n`;
496
+ break;
497
+ }
498
+ case 'uat': {
499
+ filePath = path.join(phaseDir, `${padded}-UAT.md`);
500
+ content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — User Acceptance Testing\n\n## Test Results\n\n| # | Test | Status | Notes |\n|---|------|--------|-------|\n\n## Summary\n\n_Pending UAT_\n`;
501
+ break;
502
+ }
503
+ case 'verification': {
504
+ filePath = path.join(phaseDir, `${padded}-VERIFICATION.md`);
505
+ content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — Verification\n\n## Goal-Backward Verification\n\n**Phase Goal:** [From ROADMAP.md]\n\n## Checks\n\n| # | Requirement | Status | Evidence |\n|---|------------|--------|----------|\n\n## Result\n\n_Pending verification_\n`;
506
+ break;
507
+ }
508
+ case 'phase-dir': {
509
+ if (!phase || !name) {
510
+ error('phase and name required for phase-dir scaffold');
511
+ }
512
+ const slug = generateSlugInternal(name);
513
+ const dirName = `${padded}-${slug}`;
514
+ const phasesParent = path.join(cwd, '.planning', 'phases');
515
+ fs.mkdirSync(phasesParent, { recursive: true });
516
+ const dirPath = path.join(phasesParent, dirName);
517
+ fs.mkdirSync(dirPath, { recursive: true });
518
+ output({ created: true, directory: `.planning/phases/${dirName}`, path: dirPath }, raw, dirPath);
519
+ return;
520
+ }
521
+ default:
522
+ error(`Unknown scaffold type: ${type}. Available: context, uat, verification, phase-dir`);
523
+ }
524
+
525
+ if (fs.existsSync(filePath)) {
526
+ output({ created: false, reason: 'already_exists', path: filePath }, raw, 'exists');
527
+ return;
528
+ }
529
+
530
+ fs.writeFileSync(filePath, content, 'utf-8');
531
+ const relPath = toPosixPath(path.relative(cwd, filePath));
532
+ output({ created: true, path: relPath }, raw, relPath);
533
+ }
534
+
535
+ function cmdStats(cwd, format, raw) {
536
+ const phasesDir = path.join(cwd, '.planning', 'phases');
537
+ const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
538
+ const statePath = path.join(cwd, '.planning', 'STATE.md');
539
+ const milestone = getMilestoneInfo(cwd);
540
+
541
+ // Phase & plan stats (reuse progress pattern)
542
+ const phases = [];
543
+ let totalPlans = 0;
544
+ let totalSummaries = 0;
545
+
546
+ try {
547
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
548
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
549
+
550
+ for (const dir of dirs) {
551
+ const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
552
+ const phaseNum = dm ? dm[1] : dir;
553
+ const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
554
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
555
+ const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
556
+ const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
557
+
558
+ totalPlans += plans;
559
+ totalSummaries += summaries;
560
+
561
+ let status;
562
+ if (plans === 0) status = 'Pending';
563
+ else if (summaries >= plans) status = 'Complete';
564
+ else if (summaries > 0) status = 'In Progress';
565
+ else status = 'Planned';
566
+
567
+ phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
568
+ }
569
+ } catch {}
570
+
571
+ const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
572
+
573
+ // Requirements stats
574
+ let requirementsTotal = 0;
575
+ let requirementsComplete = 0;
576
+ try {
577
+ if (fs.existsSync(reqPath)) {
578
+ const reqContent = fs.readFileSync(reqPath, 'utf-8');
579
+ const checked = reqContent.match(/^- \[x\] \*\*/gm);
580
+ const unchecked = reqContent.match(/^- \[ \] \*\*/gm);
581
+ requirementsComplete = checked ? checked.length : 0;
582
+ requirementsTotal = requirementsComplete + (unchecked ? unchecked.length : 0);
583
+ }
584
+ } catch {}
585
+
586
+ // Last activity from STATE.md
587
+ let lastActivity = null;
588
+ try {
589
+ if (fs.existsSync(statePath)) {
590
+ const stateContent = fs.readFileSync(statePath, 'utf-8');
591
+ const activityMatch = stateContent.match(/\*\*Last Activity:\*\*\s*(.+)/);
592
+ if (activityMatch) lastActivity = activityMatch[1].trim();
593
+ }
594
+ } catch {}
595
+
596
+ // Git stats
597
+ let gitCommits = 0;
598
+ let gitFirstCommitDate = null;
599
+ try {
600
+ const commitCount = execGit(cwd, ['rev-list', '--count', 'HEAD']);
601
+ gitCommits = parseInt(commitCount.trim(), 10) || 0;
602
+ const firstDate = execGit(cwd, ['log', '--reverse', '--format=%as', '--max-count=1']);
603
+ gitFirstCommitDate = firstDate.trim() || null;
604
+ } catch {}
605
+
606
+ const completedPhases = phases.filter(p => p.status === 'Complete').length;
607
+
608
+ const result = {
609
+ milestone_version: milestone.version,
610
+ milestone_name: milestone.name,
611
+ phases,
612
+ phases_completed: completedPhases,
613
+ phases_total: phases.length,
614
+ total_plans: totalPlans,
615
+ total_summaries: totalSummaries,
616
+ percent,
617
+ requirements_total: requirementsTotal,
618
+ requirements_complete: requirementsComplete,
619
+ git_commits: gitCommits,
620
+ git_first_commit_date: gitFirstCommitDate,
621
+ last_activity: lastActivity,
622
+ };
623
+
624
+ if (format === 'table') {
625
+ const barWidth = 10;
626
+ const filled = Math.round((percent / 100) * barWidth);
627
+ const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
628
+ let out = `# ${milestone.version} ${milestone.name} \u2014 Statistics\n\n`;
629
+ out += `**Progress:** [${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)\n`;
630
+ out += `**Phases:** ${completedPhases}/${phases.length} complete\n`;
631
+ if (requirementsTotal > 0) {
632
+ out += `**Requirements:** ${requirementsComplete}/${requirementsTotal} complete\n`;
633
+ }
634
+ out += '\n';
635
+ out += `| Phase | Name | Plans | Completed | Status |\n`;
636
+ out += `|-------|------|-------|-----------|--------|\n`;
637
+ for (const p of phases) {
638
+ out += `| ${p.number} | ${p.name} | ${p.plans} | ${p.summaries} | ${p.status} |\n`;
639
+ }
640
+ if (gitCommits > 0) {
641
+ out += `\n**Git:** ${gitCommits} commits`;
642
+ if (gitFirstCommitDate) out += ` (since ${gitFirstCommitDate})`;
643
+ out += '\n';
644
+ }
645
+ if (lastActivity) out += `**Last activity:** ${lastActivity}\n`;
646
+ output({ rendered: out }, raw, out);
647
+ } else {
648
+ output(result, raw);
649
+ }
650
+ }
651
+
652
+ module.exports = {
653
+ cmdGenerateSlug,
654
+ cmdCurrentTimestamp,
655
+ cmdListTodos,
656
+ cmdVerifyPathExists,
657
+ cmdHistoryDigest,
658
+ cmdResolveModel,
659
+ cmdCommit,
660
+ cmdSummaryExtract,
661
+ cmdWebsearch,
662
+ cmdProgressRender,
663
+ cmdTodoComplete,
664
+ cmdScaffold,
665
+ cmdStats,
666
+ };