wiggum-cli 0.2.2 → 0.2.3

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.
@@ -0,0 +1,278 @@
1
+ /**
2
+ * AI Tools Module
3
+ * Defines tools the AI agent can use to explore the codebase
4
+ */
5
+
6
+ import { tool, zodSchema } from 'ai';
7
+ import { z } from 'zod';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
10
+ import { join, relative } from 'node:path';
11
+
12
+ /**
13
+ * Create tools for codebase exploration
14
+ */
15
+ export function createExplorationTools(projectRoot: string) {
16
+ return {
17
+ /**
18
+ * Search code using ripgrep patterns
19
+ */
20
+ searchCode: tool({
21
+ description: `Search the codebase using ripgrep. Use this to find:
22
+ - Function/class definitions: pattern="^(def|function|class) NAME", fileType="py"
23
+ - Symbol usage: pattern="\\bSymbolName\\b" (word boundaries critical!)
24
+ - Imports: pattern="^import.*module", fileType="ts"
25
+ - File patterns: pattern="pattern", glob="*.tsx"
26
+
27
+ Tips:
28
+ - Use fileType for filtering (py, js, ts, rust, go)
29
+ - Use \\b for word boundaries to avoid partial matches
30
+ - Use literal=true for exact strings (faster)
31
+ - Always use word boundaries when searching symbols`,
32
+ inputSchema: zodSchema(z.object({
33
+ pattern: z.string().describe('The regex pattern to search for'),
34
+ fileType: z.string().optional().describe('File type filter (py, js, ts, etc.)'),
35
+ glob: z.string().optional().describe('Glob pattern like "*.tsx" or "src/**/*.ts"'),
36
+ literal: z.boolean().optional().describe('Use literal search (faster for exact strings)'),
37
+ context: z.number().optional().describe('Lines of context (default 0)'),
38
+ maxResults: z.number().optional().describe('Max results to return (default 50)'),
39
+ })),
40
+ execute: async ({ pattern, fileType, glob, literal, context, maxResults }) => {
41
+ try {
42
+ const args: string[] = [];
43
+
44
+ if (literal) args.push('-F');
45
+ if (fileType) args.push('-t', fileType);
46
+ if (glob) args.push('-g', glob);
47
+ if (context) args.push('-C', String(context));
48
+
49
+ args.push('--max-count', String(maxResults || 50));
50
+ args.push('--no-heading');
51
+ args.push('--line-number');
52
+ args.push('--');
53
+ args.push(pattern);
54
+ args.push(projectRoot);
55
+
56
+ // Use spawnSync instead of execSync for safety (no shell injection)
57
+ const result = spawnSync('rg', args, {
58
+ encoding: 'utf-8',
59
+ maxBuffer: 1024 * 1024,
60
+ timeout: 30000,
61
+ });
62
+
63
+ if (result.error) {
64
+ return `Search error: ${result.error.message}`;
65
+ }
66
+
67
+ if (result.status === 1) {
68
+ return 'No matches found';
69
+ }
70
+
71
+ if (result.status !== 0) {
72
+ return `Search error: ${result.stderr || 'Unknown error'}`;
73
+ }
74
+
75
+ // Convert absolute paths to relative
76
+ const lines = result.stdout.split('\n').map(line => {
77
+ if (line.startsWith(projectRoot)) {
78
+ return line.replace(projectRoot + '/', '');
79
+ }
80
+ return line;
81
+ });
82
+
83
+ return lines.slice(0, 100).join('\n');
84
+ } catch (error: unknown) {
85
+ const errMsg = error instanceof Error ? error.message : String(error);
86
+ return `Search error: ${errMsg}`;
87
+ }
88
+ },
89
+ }),
90
+
91
+ /**
92
+ * Read a file's contents
93
+ */
94
+ readFile: tool({
95
+ description: 'Read the contents of a file. Use relative paths from project root.',
96
+ inputSchema: zodSchema(z.object({
97
+ path: z.string().describe('Relative path to the file from project root'),
98
+ startLine: z.number().optional().describe('Start line (1-indexed)'),
99
+ endLine: z.number().optional().describe('End line (inclusive)'),
100
+ })),
101
+ execute: async ({ path: filePath, startLine, endLine }) => {
102
+ try {
103
+ // Prevent path traversal
104
+ const normalizedPath = filePath.replace(/\.\./g, '');
105
+ const fullPath = join(projectRoot, normalizedPath);
106
+
107
+ if (!fullPath.startsWith(projectRoot)) {
108
+ return 'Invalid path: cannot access files outside project';
109
+ }
110
+
111
+ if (!existsSync(fullPath)) {
112
+ return `File not found: ${filePath}`;
113
+ }
114
+
115
+ const stat = statSync(fullPath);
116
+ if (stat.isDirectory()) {
117
+ return `Path is a directory, not a file: ${filePath}`;
118
+ }
119
+
120
+ if (stat.size > 100000) {
121
+ return `File too large (${stat.size} bytes). Use startLine/endLine to read a portion.`;
122
+ }
123
+
124
+ const content = readFileSync(fullPath, 'utf-8');
125
+ const lines = content.split('\n');
126
+
127
+ if (startLine || endLine) {
128
+ const start = (startLine || 1) - 1;
129
+ const end = endLine || lines.length;
130
+ return lines.slice(start, end).join('\n');
131
+ }
132
+
133
+ return content;
134
+ } catch (error) {
135
+ const errMsg = error instanceof Error ? error.message : String(error);
136
+ return `Error reading file: ${errMsg}`;
137
+ }
138
+ },
139
+ }),
140
+
141
+ /**
142
+ * List directory contents
143
+ */
144
+ listDirectory: tool({
145
+ description: 'List contents of a directory. Shows files and subdirectories.',
146
+ inputSchema: zodSchema(z.object({
147
+ path: z.string().describe('Relative path to the directory (use "." for project root)'),
148
+ recursive: z.boolean().optional().describe('List recursively (default false)'),
149
+ maxDepth: z.number().optional().describe('Max depth for recursive listing (default 2)'),
150
+ })),
151
+ execute: async ({ path: dirPath, recursive, maxDepth }) => {
152
+ try {
153
+ // Prevent path traversal
154
+ const normalizedPath = dirPath.replace(/\.\./g, '');
155
+ const fullPath = join(projectRoot, normalizedPath);
156
+
157
+ if (!fullPath.startsWith(projectRoot)) {
158
+ return 'Invalid path: cannot access directories outside project';
159
+ }
160
+
161
+ if (!existsSync(fullPath)) {
162
+ return `Directory not found: ${dirPath}`;
163
+ }
164
+
165
+ const stat = statSync(fullPath);
166
+ if (!stat.isDirectory()) {
167
+ return `Path is not a directory: ${dirPath}`;
168
+ }
169
+
170
+ const results: string[] = [];
171
+ const depth = maxDepth || 2;
172
+
173
+ function scanDir(dir: string, currentDepth: number): void {
174
+ if (currentDepth > depth) return;
175
+
176
+ const entries = readdirSync(dir, { withFileTypes: true });
177
+
178
+ for (const entry of entries) {
179
+ // Skip common ignored directories
180
+ if (['node_modules', '.git', 'dist', 'build', '.next', '__pycache__'].includes(entry.name)) {
181
+ continue;
182
+ }
183
+
184
+ const relativePath = relative(projectRoot, join(dir, entry.name));
185
+ const prefix = entry.isDirectory() ? '📁 ' : '📄 ';
186
+ results.push(prefix + relativePath);
187
+
188
+ if (recursive && entry.isDirectory() && currentDepth < depth) {
189
+ scanDir(join(dir, entry.name), currentDepth + 1);
190
+ }
191
+ }
192
+ }
193
+
194
+ scanDir(fullPath, 1);
195
+ return results.slice(0, 200).join('\n');
196
+ } catch (error) {
197
+ const errMsg = error instanceof Error ? error.message : String(error);
198
+ return `Error listing directory: ${errMsg}`;
199
+ }
200
+ },
201
+ }),
202
+
203
+ /**
204
+ * Get package.json info including scripts
205
+ */
206
+ getPackageInfo: tool({
207
+ description: 'Get package.json contents including scripts, dependencies, and metadata.',
208
+ inputSchema: zodSchema(z.object({
209
+ field: z.string().optional().describe('Specific field to get (scripts, dependencies, etc.)'),
210
+ })),
211
+ execute: async ({ field }) => {
212
+ try {
213
+ const pkgPath = join(projectRoot, 'package.json');
214
+
215
+ if (!existsSync(pkgPath)) {
216
+ return 'No package.json found';
217
+ }
218
+
219
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
220
+
221
+ if (field) {
222
+ return JSON.stringify(pkg[field], null, 2) || `Field "${field}" not found`;
223
+ }
224
+
225
+ // Return relevant parts
226
+ return JSON.stringify({
227
+ name: pkg.name,
228
+ scripts: pkg.scripts,
229
+ dependencies: Object.keys(pkg.dependencies || {}),
230
+ devDependencies: Object.keys(pkg.devDependencies || {}),
231
+ }, null, 2);
232
+ } catch (error) {
233
+ const errMsg = error instanceof Error ? error.message : String(error);
234
+ return `Error reading package.json: ${errMsg}`;
235
+ }
236
+ },
237
+ }),
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Ripgrep skill reference for the AI agent
243
+ */
244
+ export const RIPGREP_SKILL = `
245
+ ## ripgrep Code Search Skill
246
+
247
+ ### Essential Patterns
248
+
249
+ **Find definitions:**
250
+ - Python functions: pattern="^def \\w+\\(", fileType="py"
251
+ - JS/TS functions: pattern="^(export )?(function|const) \\w+", fileType="ts"
252
+ - Classes: pattern="^class \\w+", fileType="py"
253
+
254
+ **Find symbol usage (CRITICAL: use word boundaries):**
255
+ - Exact word: pattern="\\bSymbolName\\b"
256
+ - Literal string: pattern="exact.string", literal=true
257
+
258
+ **Find imports:**
259
+ - ES imports: pattern="^import.*from", fileType="ts"
260
+ - CommonJS: pattern="require\\(", fileType="js"
261
+
262
+ **File type options:**
263
+ - py (Python)
264
+ - js (JavaScript)
265
+ - ts (TypeScript)
266
+ - rust (Rust)
267
+ - go (Go)
268
+
269
+ **Performance tips:**
270
+ 1. Always use fileType when possible
271
+ 2. Use literal=true for exact strings
272
+ 3. Use \\b for word boundaries (prevents partial matches)
273
+ 4. Keep maxResults reasonable
274
+
275
+ **Word boundaries are critical:**
276
+ - WITHOUT: pattern="log" matches "logger", "blogger", "catalog"
277
+ - WITH: pattern="\\blog\\b" matches only "log"
278
+ `;
@@ -23,6 +23,8 @@ export interface InitOptions {
23
23
  ai?: boolean;
24
24
  provider?: AIProvider;
25
25
  yes?: boolean;
26
+ /** Use agentic mode for deep codebase exploration */
27
+ agentic?: boolean;
26
28
  }
27
29
 
28
30
  /**
@@ -175,13 +177,31 @@ export async function initCommand(options: InitOptions): Promise<void> {
175
177
  const selectedModel = modelChoice as string;
176
178
  const modelLabel = modelOptions.find(m => m.value === selectedModel)?.label || selectedModel;
177
179
 
180
+ // Ask about agentic mode (deep exploration)
181
+ let useAgentic = options.agentic;
182
+ if (useAgentic === undefined && !options.yes) {
183
+ const wantAgentic = await prompts.confirm({
184
+ message: 'Enable deep codebase exploration? (AI will search files and directories)',
185
+ initialValue: true,
186
+ });
187
+
188
+ if (prompts.isCancel(wantAgentic)) {
189
+ logger.info('Initialization cancelled');
190
+ return;
191
+ }
192
+
193
+ useAgentic = wantAgentic;
194
+ }
195
+
178
196
  console.log('');
179
- console.log(simpson.yellow(`─── AI Enhancement (${provider} / ${modelLabel}) ───`));
197
+ const modeLabel = useAgentic ? 'agentic' : 'simple';
198
+ console.log(simpson.yellow(`─── AI Enhancement (${provider} / ${modelLabel} / ${modeLabel}) ───`));
180
199
 
181
200
  const aiEnhancer = new AIEnhancer({
182
201
  provider,
183
202
  model: selectedModel,
184
203
  verbose: true,
204
+ agentic: useAgentic,
185
205
  });
186
206
 
187
207
  spinner.start('Running AI analysis...');