opencodekit 0.23.1 → 0.23.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.
Files changed (30) hide show
  1. package/dist/index.js +354 -825
  2. package/dist/template/.opencode/AGENTS.md +15 -2
  3. package/dist/template/.opencode/command/init.md +198 -34
  4. package/dist/template/.opencode/context/fallow.md +137 -0
  5. package/dist/template/.opencode/opencode.json +12 -315
  6. package/dist/template/.opencode/plugin/codesearch.ts +730 -0
  7. package/dist/template/.opencode/plugin/memory/compile.ts +171 -186
  8. package/dist/template/.opencode/plugin/memory/index-generator.ts +118 -133
  9. package/dist/template/.opencode/plugin/memory/lint.ts +253 -275
  10. package/dist/template/.opencode/plugin/memory/tools.ts +224 -268
  11. package/dist/template/.opencode/plugin/memory/validate.ts +154 -164
  12. package/dist/template/.opencode/plugin/sdk/copilot/responses/tool/web-search-preview.ts +13 -30
  13. package/dist/template/.opencode/plugin/sdk/copilot/responses/tool/web-search-shared.ts +25 -0
  14. package/dist/template/.opencode/plugin/sdk/copilot/responses/tool/web-search.ts +17 -34
  15. package/dist/template/.opencode/plugin/session-summary.ts +0 -2
  16. package/dist/template/.opencode/plugin/srcwalk.ts +646 -667
  17. package/dist/template/.opencode/skill/code-navigation/SKILL.md +10 -10
  18. package/dist/template/.opencode/skill/code-review-and-quality/SKILL.md +1 -1
  19. package/dist/template/.opencode/skill/condition-based-waiting/example.ts +15 -2
  20. package/dist/template/.opencode/skill/debugging-and-error-recovery/SKILL.md +1 -1
  21. package/dist/template/.opencode/skill/deep-module-design/SKILL.md +1 -1
  22. package/dist/template/.opencode/skill/fallow/SKILL.md +409 -0
  23. package/dist/template/.opencode/skill/fallow/references/cli-reference.md +1905 -0
  24. package/dist/template/.opencode/skill/fallow/references/gotchas.md +644 -0
  25. package/dist/template/.opencode/skill/fallow/references/patterns.md +791 -0
  26. package/dist/template/.opencode/skill/planning-and-task-breakdown/SKILL.md +1 -1
  27. package/dist/template/.opencode/skill/srcwalk/SKILL.md +10 -13
  28. package/dist/template/.opencode/skill/ubiquitous-language/SKILL.md +1 -1
  29. package/dist/template/.opencode/tool/grepsearch.ts +92 -103
  30. package/package.json +1 -1
@@ -5,9 +5,7 @@
5
5
  * Wraps available CLI tools (rg/grep, find, cat, ls) into unified srcwalk_* tools.
6
6
  *
7
7
  * Tools (matching pikit srcwalk extension surface):
8
- * - srcwalk_search — Search symbols/text/regex in codebase
9
8
  * - srcwalk_read — Read files with optional section/range
10
- * - srcwalk_files — Find files by glob pattern
11
9
  * - srcwalk_deps — Show imports and dependents for a file
12
10
  * - srcwalk_map — Directory tree overview
13
11
  * - srcwalk_callers — Reverse call graph (grep-based)
@@ -16,14 +14,13 @@
16
14
  * - srcwalk_impact — Heuristic blast-radius triage
17
15
  */
18
16
 
19
- import { execFile, execFileSync } from "node:child_process";
17
+ import { execFileSync } from "node:child_process";
20
18
  import { existsSync, readFileSync, statSync } from "node:fs";
21
19
  import { readdir } from "node:fs/promises";
22
20
  import path from "node:path";
23
21
  import { tool } from "@opencode-ai/plugin/tool";
24
22
  import type { Plugin } from "@opencode-ai/plugin";
25
23
 
26
- const BIN_RG = "rg";
27
24
  const TIMEOUT_MS = 15_000;
28
25
  const MAX_BUFFER = 5 * 1024 * 1024;
29
26
 
@@ -31,637 +28,613 @@ const MAX_BUFFER = 5 * 1024 * 1024;
31
28
  // Helpers
32
29
  // ---------------------------------------------------------------------------
33
30
 
34
- function run(cmd: string, args: string[], cwd?: string): { stdout: string; stderr: string; code: number } {
35
- try {
36
- const result = execFileSync(cmd, args, {
37
- encoding: "utf-8",
38
- timeout: TIMEOUT_MS,
39
- maxBuffer: MAX_BUFFER,
40
- cwd: cwd ?? process.cwd(),
41
- stdio: ["ignore", "pipe", "pipe"],
42
- });
43
- return { stdout: result.stdout ?? "", stderr: result.stderr ?? "", code: 0 };
44
- } catch (err: unknown) {
45
- const e = err as { stdout?: string; stderr?: string; status?: number; message?: string };
46
- return {
47
- stdout: e.stdout ?? "",
48
- stderr: e.stderr ?? "",
49
- code: e.status ?? 1,
50
- };
51
- }
52
- }
53
-
54
- function hasRg(): boolean {
55
- try {
56
- execFileSync(BIN_RG, ["--version"], { encoding: "utf-8", timeout: 1000, stdio: "ignore" });
57
- return true;
58
- } catch {
59
- return false;
60
- }
31
+ function run(
32
+ cmd: string,
33
+ args: string[],
34
+ cwd?: string,
35
+ ): { stdout: string; stderr: string; code: number } {
36
+ try {
37
+ const result = execFileSync(cmd, args, {
38
+ encoding: "utf-8",
39
+ timeout: TIMEOUT_MS,
40
+ maxBuffer: MAX_BUFFER,
41
+ cwd: cwd ?? process.cwd(),
42
+ stdio: ["ignore", "pipe", "pipe"],
43
+ });
44
+ return { stdout: result.stdout ?? "", stderr: result.stderr ?? "", code: 0 };
45
+ } catch (err: unknown) {
46
+ const e = err as { stdout?: string; stderr?: string; status?: number; message?: string };
47
+ return {
48
+ stdout: e.stdout ?? "",
49
+ stderr: e.stderr ?? "",
50
+ code: e.status ?? 1,
51
+ };
52
+ }
61
53
  }
62
54
 
63
55
  function plural(n: number, word: string): string {
64
- return `${n} ${word}${n !== 1 ? "s" : ""}`;
56
+ if (n === 1) return `${n} ${word}`;
57
+ if (
58
+ word.endsWith("ch") ||
59
+ word.endsWith("s") ||
60
+ word.endsWith("sh") ||
61
+ word.endsWith("x") ||
62
+ word.endsWith("z")
63
+ ) {
64
+ return `${n} ${word}es`;
65
+ }
66
+ if (
67
+ word.endsWith("y") &&
68
+ word.length > 1 &&
69
+ !["a", "e", "i", "o", "u"].includes(word[word.length - 2])
70
+ ) {
71
+ return `${n} ${word.slice(0, -1)}ies`;
72
+ }
73
+ return `${n} ${word}s`;
65
74
  }
66
75
 
67
76
  // ---------------------------------------------------------------------------
68
77
  // Plugin
69
78
  // ---------------------------------------------------------------------------
70
79
 
71
- interface PluginConfig {
72
- directory?: string;
73
- }
74
-
75
80
  const srcwalkTools = {
76
- // -----------------------------------------------------------------------
77
- // srcwalk_search: Search codebase
78
- // -----------------------------------------------------------------------
79
- "srcwalk_search": tool({
80
- description: `Search for symbols, text, or regex patterns in code.\n\nUses ripgrep (rg) when available, falls back to grep.\nSupports symbol search (definitions first), content search, and regex.`,
81
- args: {
82
- query: tool.schema.string().describe("Search query or regex pattern"),
83
- scope: tool.schema.string().optional().describe("Subdirectory scope (default: project root)"),
84
- kind: tool.schema.string().optional().describe("Search type: text (default), regex, content"),
85
- context: tool.schema.number().optional().describe("Lines of context before/after each match"),
86
- limit: tool.schema.number().optional().describe("Max results (default: 30)"),
87
- },
88
- execute: async (args, context) => {
89
- const query = String(args.query ?? "").trim();
90
- if (!query) return "❌ query is required.";
91
- const scope = args.scope ? String(args.scope) : context.directory;
92
- const limit = Math.min(args.limit ?? 30, 100);
93
- const ctxLines = args.context ?? 0;
94
- const kind = String(args.kind ?? "text");
95
-
96
- const searchDir = path.resolve(context.directory, scope);
97
-
98
- if (hasRg()) {
99
- const rgArgs = ["--no-heading", "--line-number", "--color", "never"];
100
- rgArgs.push("--max-count", String(limit * 2));
101
- if (ctxLines > 0) {
102
- rgArgs.push("-C", String(ctxLines));
103
- }
104
- if (kind === "regex") {
105
- rgArgs.push("-E", "rust");
106
- } else {
107
- rgArgs.push("-F"); // literal
108
- }
109
- rgArgs.push(query, searchDir);
110
-
111
- const result = run(BIN_RG, rgArgs);
112
- if (result.code !== 0 && result.stderr) {
113
- // Try plain grep fallback
114
- } else {
115
- const lines = result.stdout.split("\n").filter(Boolean).slice(0, limit);
116
- if (lines.length === 0) return "No matches found.";
117
- return lines.join("\n");
118
- }
119
- }
120
-
121
- // Fallback to grep
122
- const grepArgs = ["-rn", "--color=never"];
123
- if (ctxLines > 0) grepArgs.push("-C", String(ctxLines));
124
- if (kind === "regex") {
125
- grepArgs.push("-E");
126
- } else {
127
- grepArgs.push("-F");
128
- }
129
- grepArgs.push(query, searchDir);
130
-
131
- const result = run("grep", grepArgs);
132
- const lines = result.stdout.split("\n").filter(Boolean).slice(0, limit);
133
- if (lines.length === 0) return "No matches found.";
134
- return lines.join("\n");
135
- },
136
- }),
137
-
138
- // -----------------------------------------------------------------------
139
- // srcwalk_read: Read files
140
- // -----------------------------------------------------------------------
141
- "srcwalk_read": tool({
142
- description: `Read a file with optional section (line range, symbol, or path:line format).\n\nSmall files return full content; large files support outlining.\nUse path:start-end for range reads (e.g. "src/app.ts:44-89").`,
143
- args: {
144
- path: tool.schema.string().describe("File path to read (supports path:line or path:start-end)"),
145
- section: tool.schema.string().optional().describe("Line range '44-89' or heading/symbol name"),
146
- full: tool.schema.boolean().optional().describe("Force full content"),
147
- },
148
- execute: async (args, context) => {
149
- const fileArg = String(args.path);
150
- const fullFilePath = path.resolve(context.directory, fileArg);
151
-
152
- // Parse path:line or path:start-end shortcut
153
- let startLine: number | undefined;
154
- let endLine: number | undefined;
155
-
156
- const rangeMatch = fileArg.match(/^(.+?):(\d+)(?:-(\d+))?$/);
157
- if (rangeMatch) {
158
- const relPath = rangeMatch[1];
159
- const resolved = path.resolve(context.directory, relPath);
160
- startLine = parseInt(rangeMatch[2], 10);
161
- endLine = rangeMatch[3] ? parseInt(rangeMatch[3], 10) : startLine;
162
- return readFileRange(resolved, startLine, endLine, relPath);
163
- }
164
-
165
- if (!existsSync(fullFilePath)) return `File not found: ${fileArg}`;
166
- const stats = statSync(fullFilePath);
167
-
168
- // If section specified, try grep for symbol/heading
169
- if (args.section) {
170
- const section = String(args.section);
171
- // Check if it's a line range
172
- const lineMatch = section.match(/^(\d+)(?:-(\d+))?$/);
173
- if (lineMatch) {
174
- const start = parseInt(lineMatch[1], 10);
175
- const end = lineMatch[2] ? parseInt(lineMatch[2], 10) : start + 30;
176
- return readFileRange(fullFilePath, start, end);
177
- }
178
- // Symbol/heading: use grep to find location, then read around it
179
- const grepArgs = ["-n", "--color=never", "-E", `^(function |const |let |class |interface |type |export |## |### )?.*${section}`, fullFilePath];
180
- const result = run("grep", grepArgs);
181
- if (result.stdout) {
182
- const firstMatch = result.stdout.split("\n")[0];
183
- const lineNum = parseInt(firstMatch.split(":")[0], 10);
184
- if (!isNaN(lineNum)) {
185
- return readFileRange(fullFilePath, Math.max(1, lineNum - 3), lineNum + 40);
186
- }
187
- }
188
- return `Section "${section}" not found in ${fileArg}`;
189
- }
190
-
191
- // Full content for small files
192
- if (stats.size < 50 * 1024 || args.full) {
193
- const content = readFileSync(fullFilePath, "utf-8");
194
- const lines = content.split("\n");
195
- if (lines.length > 2000)
196
- return `[File too large: ${plural(lines.length, "line")}. Showing first 2000 lines]\n\n${lines.slice(0, 2000).join("\n")}`;
197
- return content;
198
- }
199
-
200
- // Large file: outline
201
- const content = readFileSync(fullFilePath, "utf-8");
202
- const lines = content.split("\n");
203
- const headings: string[] = [];
204
- for (let i = 0; i < Math.min(lines.length, 5000); i++) {
205
- const l = lines[i].trim();
206
- if (l.match(/^(export\s+)?(function|class|interface|type|const|enum|def|struct|impl|pub\s+fn)\s/) ||
207
- l.match(/^(##|###)\s/) ||
208
- l.match(/^\w+\s*[:=]/)) {
209
- headings.push(` ${i + 1}: ${l.slice(0, 120)}`);
210
- }
211
- }
212
- const header = `[File: ${fileArg} — ${plural(lines.length, "line")}, ${(stats.size / 1024).toFixed(1)}KB]\n\n`;
213
- const outline = headings.length > 0
214
- ? `Outline (${plural(headings.length, "entry")}):\n${headings.slice(0, 50).join("\n")}\n\nUse path:line or section to read a specific range.`
215
- : `Use path:line to read a specific range (e.g., ${fileArg}:1-${Math.min(50, lines.length)}).`;
216
- return header + outline;
217
- },
218
- }),
219
-
220
- // -----------------------------------------------------------------------
221
- // srcwalk_files: Find files
222
- // -----------------------------------------------------------------------
223
- "srcwalk_files": tool({
224
- description: `Find files by glob pattern. Returns matched file paths with size estimates, grouped by directory. Respects .gitignore.`,
225
- args: {
226
- pattern: tool.schema.string().describe("Glob pattern (e.g. '*.ts', 'src/**/*.ts')"),
227
- scope: tool.schema.string().optional().describe("Directory to search (default: project root)"),
228
- },
229
- execute: async (args, context) => {
230
- const pattern = String(args.pattern ?? "").trim();
231
- if (!pattern) return "❌ pattern is required.";
232
- const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
233
-
234
- // Use find with simple glob pattern
235
- const findArgs: string[] = [scopeDir, "-type", "f"];
236
-
237
- // Convert simple glob to -name pattern
238
- if (pattern.includes("**")) {
239
- // find handles ** naturally with -path
240
- findArgs.push("-path", `*/${pattern.replace(/\*\*/g, "*")}`);
241
- } else if (pattern.includes("*")) {
242
- findArgs.push("-name", pattern);
243
- } else if (pattern.includes(".")) {
244
- findArgs.push("-name", pattern);
245
- } else {
246
- findArgs.push("-name", `*${pattern}*`);
247
- }
248
-
249
- // Exclude common dirs
250
- for (const dir of [".git", "node_modules", "dist", "build", "coverage", ".next", ".opencode"]) {
251
- findArgs.push("-not", "-path", `*/${dir}/*`);
252
- }
253
-
254
- const result = run("find", findArgs);
255
- const files = result.stdout.split("\n").filter(Boolean).slice(0, 200);
256
-
257
- if (files.length === 0) return `No files matching "${pattern}" found.`;
258
-
259
- // Group by directory
260
- const groups: Record<string, string[]> = {};
261
- for (const f of files) {
262
- const dir = path.dirname(f);
263
- if (!groups[dir]) groups[dir] = [];
264
- groups[dir].push(path.basename(f));
265
- }
266
-
267
- const lines: string[] = [`# Files matching "${pattern}" (${plural(files.length, "file")})\n`];
268
- for (const [dir, files] of Object.entries(groups).sort()) {
269
- const relDir = path.relative(context.directory, dir) || ".";
270
- lines.push(`${relDir}/ (${plural(files.length, "file")})`);
271
- for (const f of files) {
272
- const fp = path.join(dir, f);
273
- try {
274
- const size = statSync(fp).size;
275
- const tokenEst = Math.ceil(size / 4);
276
- lines.push(` ${f} (~${tokenEst.toLocaleString()} tokens)`);
277
- } catch {
278
- lines.push(` ${f}`);
279
- }
280
- }
281
- lines.push("");
282
- }
283
- return lines.join("\n");
284
- },
285
- }),
286
-
287
- // -----------------------------------------------------------------------
288
- // srcwalk_deps: Import analysis
289
- // -----------------------------------------------------------------------
290
- "srcwalk_deps": tool({
291
- description: `Show what imports a file (dependents) and what a file imports (dependencies).\nBlast-radius check before breaking changes.`,
292
- args: {
293
- path: tool.schema.string().describe("File path to analyze"),
294
- scope: tool.schema.string().optional().describe("Search scope (default: project root)"),
295
- },
296
- execute: async (args, context) => {
297
- const filePath = String(args.path);
298
- const absPath = path.resolve(context.directory, filePath);
299
- if (!existsSync(absPath)) return `File not found: ${filePath}`;
300
-
301
- const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
302
- const fileName = path.basename(filePath, path.extname(filePath));
303
-
304
- // What this file imports
305
- const content = readFileSync(absPath, "utf-8");
306
- const importLines: string[] = [];
307
- for (const line of content.split("\n")) {
308
- const m = line.match(/(?:import|require)\s+.*?from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]/);
309
- if (m) importLines.push(` ${line.trim()}`);
310
- }
311
-
312
- // What imports this file (grep for the module name)
313
- const searchName = fileName;
314
- const grepResult = run("grep", [
315
- "-rn",
316
- "--color=never",
317
- "-E",
318
- `from ['"](\\./|\\.\\./|.*/)${searchName}['"]|require\\(['"](\\./|\\.\\./|.*/)${searchName}['"]`,
319
- scopeDir,
320
- "--include=*.ts",
321
- "--include=*.tsx",
322
- "--include=*.js",
323
- "--include=*.jsx",
324
- "--include=*.mjs",
325
- ]);
326
- const importers = grepResult.stdout.split("\n").filter(Boolean).slice(0, 30);
327
-
328
- const result: string[] = [`## Dependencies for ${filePath}\n`];
329
- result.push(`### Imports (${plural(importLines.length, "module")})`);
330
- if (importLines.length === 0) result.push(" (none)");
331
- else result.push(...importLines);
332
-
333
- result.push(`\n### Importers (${plural(importers.length, "file")})`);
334
- if (importers.length === 0) result.push(" (no files import this module)");
335
- else result.push(...importers.map(l => ` ${path.relative(context.directory, l.split(":")[0])}:${l.split(":")[1]}`));
336
-
337
- return result.join("\n");
338
- },
339
- }),
340
-
341
- // -----------------------------------------------------------------------
342
- // srcwalk_map: Directory overview
343
- // -----------------------------------------------------------------------
344
- "srcwalk_map": tool({
345
- description: `Token-annotated directory skeleton. Shows repo structure with file sizes and token estimates. Good for understanding codebase shape.`,
346
- args: {
347
- scope: tool.schema.string().optional().describe("Directory to map (default: project root)"),
348
- depth: tool.schema.number().optional().describe("Max directory depth (default: 3)"),
349
- },
350
- execute: async (args, context) => {
351
- const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
352
- const maxDepth = args.depth ?? 3;
353
-
354
- const treeArgs = ["-L", String(maxDepth), "--dirsfirst"];
355
- // Use tree if available, else ls -R
356
- const treeResult = run("tree", [
357
- ...treeArgs,
358
- "-I", ".git|node_modules|dist|build|coverage|.next",
359
- scopeDir,
360
- ]);
361
- if (treeResult.code === 0) {
362
- return treeResult.stdout.slice(0, 10_000);
363
- }
364
-
365
- // Fallback: simple directory listing
366
- const result: string[] = [`## Directory: ${path.relative(context.directory, scopeDir) || "."}\n`];
367
- await listDirRecursive(scopeDir, "", maxDepth, result, context.directory);
368
- return result.join("\n");
369
- },
370
- }),
371
-
372
- // -----------------------------------------------------------------------
373
- // srcwalk_callers: Reverse call graph
374
- // -----------------------------------------------------------------------
375
- "srcwalk_callers": tool({
376
- description: `Reverse call graph — find what calls a function.\nGrep-based: searches for symbol usage across the codebase.\nUse depth for transitive callers (multi-hop).`,
377
- args: {
378
- symbol: tool.schema.string().describe("Function/symbol name"),
379
- scope: tool.schema.string().optional().describe("Search scope"),
380
- depth: tool.schema.number().optional().describe("BFS hop depth (default: 1, max: 3)"),
381
- filter: tool.schema.string().optional().describe("Optional filter (e.g. path:api)"),
382
- },
383
- execute: async (args, context) => {
384
- const symbol = String(args.symbol ?? "").trim();
385
- if (!symbol) return "❌ symbol is required.";
386
- const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
387
- const depth = Math.min(args.depth ?? 1, 3);
388
-
389
- // Search for direct calls: symbol( or .symbol or symbol.
390
- const grepArgs = [
391
- "-rn",
392
- "--color=never",
393
- "-E",
394
- `[.\\s]${symbol}\\s*\\(|[.]${symbol}\\b|\\b${symbol}\\.`,
395
- scopeDir,
396
- "--include=*.ts",
397
- "--include=*.tsx",
398
- "--include=*.js",
399
- "--include=*.jsx",
400
- ];
401
-
402
- if (args.filter) {
403
- const filterStr = String(args.filter);
404
- if (filterStr.startsWith("path:")) {
405
- grepArgs.push(path.join(scopeDir, filterStr.slice(5)));
406
- }
407
- }
408
-
409
- const result = run("grep", grepArgs);
410
- const lines = result.stdout.split("\n").filter(Boolean).slice(0, 50);
411
-
412
- if (lines.length === 0) return `No callers found for "${symbol}".`;
413
-
414
- const output: string[] = [
415
- `## Callers of \`${symbol}\` (${plural(lines.length, "result")})${depth > 1 ? ` (depth: ${depth})` : ""}\n`,
416
- ];
417
- for (const line of lines) {
418
- const parts = line.split(":");
419
- if (parts.length >= 2) {
420
- const relPath = path.relative(context.directory, parts[0]);
421
- output.push(` ${relPath}:${parts[1]}: ${parts.slice(2).join(":").trim().slice(0, 150)}`);
422
- } else {
423
- output.push(` ${line.slice(0, 200)}`);
424
- }
425
- }
426
-
427
- if (depth > 1) {
428
- output.push(`\n_Note: Multi-hop depth (${depth}) requires re-running on each caller._`);
429
- }
430
- return output.join("\n");
431
- },
432
- }),
433
-
434
- // -----------------------------------------------------------------------
435
- // srcwalk_callees: Forward call graph
436
- // -----------------------------------------------------------------------
437
- "srcwalk_callees": tool({
438
- description: `Forward call graph — what does this function call?\nReads the function body and extracts call sites.`,
439
- args: {
440
- symbol: tool.schema.string().describe("Function/symbol name"),
441
- scope: tool.schema.string().optional().describe("Scope directory"),
442
- detailed: tool.schema.boolean().optional().describe("Show ordered call sites with argument slots"),
443
- },
444
- execute: async (args, context) => {
445
- const symbol = String(args.symbol ?? "").trim();
446
- if (!symbol) return "❌ symbol is required.";
447
- const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
448
-
449
- // Find the function definition
450
- const defArgs = [
451
- "-rn",
452
- "--color=never",
453
- "-E",
454
- `(export\\s+)?(function|const|let|async\\s+function)\\s+${symbol}\\b|${symbol}\\s*[:=]\\s*(async\\s+)?\\(`,
455
- scopeDir,
456
- "--include=*.ts",
457
- "--include=*.tsx",
458
- "--include=*.js",
459
- "--include=*.jsx",
460
- ];
461
- const defResult = run("grep", defArgs);
462
- const defLines = defResult.stdout.split("\n").filter(Boolean).slice(0, 5);
463
-
464
- if (defLines.length === 0) {
465
- return `Definition not found for "${symbol}". Cannot trace callees without finding the function body.`;
466
- }
467
-
468
- const output: string[] = [`## Callees of \`${symbol}\`\n`];
469
-
470
- // For each definition location, show the function and extract calls
471
- for (const def of defLines) {
472
- const parts = def.split(":");
473
- if (parts.length >= 2) {
474
- const relPath = path.relative(context.directory, parts[0]);
475
- const lineNum = parseInt(parts[1], 10);
476
- output.push(`**Definition:** ${relPath}:${lineNum}`);
477
-
478
- // Read function body to extract calls
479
- const filePath = path.resolve(context.directory, parts[0]);
480
- if (existsSync(filePath)) {
481
- const fileLines = readFileSync(filePath, "utf-8").split("\n");
482
- let braceCount = 0;
483
- let inFunc = false;
484
- const calls: string[] = [];
485
-
486
- for (let i = lineNum - 1; i < Math.min(lineNum + 80, fileLines.length); i++) {
487
- const line = fileLines[i];
488
- if (!inFunc) {
489
- if (line.includes("{")) {
490
- inFunc = true;
491
- braceCount = (line.match(/{/g) || []).length;
492
- braceCount -= (line.match(/}/g) || []).length;
493
- }
494
- continue;
495
- }
496
- braceCount += (line.match(/{/g) || []).length;
497
- braceCount -= (line.match(/}/g) || []).length;
498
-
499
- // Extract function calls
500
- const callMatch = [...line.matchAll(/(?<![.\w])(\w+)\s*\(/g)];
501
- for (const m of callMatch) {
502
- const name = m[1];
503
- if (!["if", "for", "while", "switch", "catch", "typeof", "instanceof", "return", "throw", "new", "delete", "await", "yield"].includes(name)) {
504
- const argStart = line.indexOf("(", m.index!);
505
- const argEnd = line.indexOf(")", argStart);
506
- const args_s = argEnd > argStart ? line.slice(argStart + 1, argEnd).trim().slice(0, 60) : "";
507
- calls.push(` ${args.detailed ? `${name}(${args_s})` : `${name}()`}`);
508
- }
509
- }
510
-
511
- if (braceCount <= 0) break;
512
- }
513
-
514
- if (calls.length > 0) {
515
- output.push(...calls);
516
- } else {
517
- output.push(" (no internal calls found)");
518
- }
519
- output.push("");
520
- }
521
- }
522
- }
523
-
524
- return output.join("\n");
525
- },
526
- }),
527
-
528
- // -----------------------------------------------------------------------
529
- // srcwalk_flow: Compact orientation
530
- // -----------------------------------------------------------------------
531
- "srcwalk_flow": tool({
532
- description: `Compact function orientation — ordered callees + direct callers.\nQuick understanding of a function's role in the call graph.`,
533
- args: {
534
- symbol: tool.schema.string().describe("Symbol name to analyze"),
535
- scope: tool.schema.string().optional().describe("Search scope"),
536
- },
537
- execute: async (args, context) => {
538
- const symbol = String(args.symbol ?? "").trim();
539
- if (!symbol) return "❌ symbol is required.";
540
- const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
541
-
542
- // Get callers
543
- const callersResult = run("grep", [
544
- "-rn", "--color=never", "-E",
545
- `[.\\s]${symbol}\\s*\\(|[.]${symbol}\\b`,
546
- scopeDir,
547
- "--include=*.ts", "--include=*.tsx", "--include=*.js", "--include=*.jsx",
548
- ]);
549
- const callers = callersResult.stdout.split("\n").filter(Boolean).slice(0, 15);
550
-
551
- // Get callees by reading function body
552
- const defResult = run("grep", [
553
- "-rn", "--color=never", "-E",
554
- `(function|const|let)\\s+${symbol}\\b|${symbol}\\s*[:=]\\s*(async\\s+)?\\(`,
555
- scopeDir,
556
- "--include=*.ts", "--include=*.tsx", "--include=*.js", "--include=*.jsx",
557
- ]);
558
- const defLine = defResult.stdout.split("\n").filter(Boolean)[0];
559
- let callees: string[] = [];
560
-
561
- if (defLine) {
562
- const parts = defLine.split(":");
563
- if (parts.length >= 2) {
564
- const fp = path.resolve(context.directory, parts[0]);
565
- const ln = parseInt(parts[1], 10);
566
- if (existsSync(fp)) {
567
- const fileLines = readFileSync(fp, "utf-8").split("\n");
568
- let bc = 0, inF = false;
569
- for (let i = ln - 1; i < Math.min(ln + 60, fileLines.length); i++) {
570
- const l = fileLines[i];
571
- if (!inF) { if (l.includes("{")) { inF = true; bc = (l.match(/{/g) || []).length - (l.match(/}/g) || []).length; } continue; }
572
- bc += (l.match(/{/g) || []).length - (l.match(/}/g) || []).length;
573
- for (const m of l.matchAll(/(\w+)\s*\(/g)) {
574
- if (!["if","for","while","switch","catch","typeof","instanceof","return","throw","new","delete","await","yield"].includes(m[1]))
575
- callees.push(m[1]);
576
- }
577
- if (bc <= 0) break;
578
- }
579
- }
580
- }
581
- }
582
-
583
- const output: string[] = [`## Flow: \`${symbol}\``];
584
- output.push(`\n**Callers (${plural(callers.length, "file")}):`);
585
- if (callers.length === 0) output.push(" (none)");
586
- else output.push(...callers.slice(0, 10).map(l => ` ${path.relative(context.directory, l.split(":")[0])}:${l.split(":")[1]}`));
587
-
588
- output.push(`\n**Callees (${plural(callees.length, "call")}):`);
589
- if (callees.length === 0) output.push(" (none)");
590
- else output.push(...[...new Set(callees)].slice(0, 20).map(c => ` ${c}()`));
591
- return output.join("\n");
592
- },
593
- }),
594
-
595
- // -----------------------------------------------------------------------
596
- // srcwalk_impact: Heuristic blast-radius
597
- // -----------------------------------------------------------------------
598
- "srcwalk_impact": tool({
599
- description: `Heuristic blast-radius triage — broad 'what might be affected?' starting point.\nName-matched, not proof. Use as starting point before verifying with srcwalk_callers or exact reads.`,
600
- args: {
601
- symbol: tool.schema.string().describe("Symbol name to triage"),
602
- scope: tool.schema.string().optional().describe("Search scope"),
603
- },
604
- execute: async (args, context) => {
605
- const symbol = String(args.symbol ?? "").trim();
606
- if (!symbol) return " symbol is required.";
607
- const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
608
-
609
- // Count usages per directory
610
- const grepResult = run("grep", [
611
- "-rn",
612
- "--color=never",
613
- "-E",
614
- `\\b${symbol}\\b`,
615
- scopeDir,
616
- "--include=*.ts",
617
- "--include=*.tsx",
618
- "--include=*.js",
619
- "--include=*.jsx",
620
- ]);
621
- const lines = grepResult.stdout.split("\n").filter(Boolean);
622
-
623
- // Group by file
624
- const fileCounts: Record<string, number> = {};
625
- for (const line of lines) {
626
- const filePath = line.split(":")[0];
627
- fileCounts[filePath] = (fileCounts[filePath] || 0) + 1;
628
- }
629
-
630
- // Group by directory
631
- const dirCounts: Record<string, { files: number; total: number }> = {};
632
- for (const [filePath, count] of Object.entries(fileCounts)) {
633
- const dir = path.dirname(filePath);
634
- if (!dirCounts[dir]) dirCounts[dir] = { files: 0, total: 0 };
635
- dirCounts[dir].files++;
636
- dirCounts[dir].total += count;
637
- }
638
-
639
- const totalOccurrences = lines.length;
640
- const totalFiles = Object.keys(fileCounts).length;
641
-
642
- const output: string[] = [
643
- `## Impact: \`${symbol}\``,
644
- `Total: ${plural(totalOccurrences, "occurrence")} across ${plural(totalFiles, "file")}\n`,
645
- `### By directory`,
646
- ];
647
-
648
- const sortedDirs = Object.entries(dirCounts).sort((a, b) => b[1].total - a[1].total);
649
- for (const [dir, info] of sortedDirs.slice(0, 15)) {
650
- const relDir = path.relative(context.directory, dir) || ".";
651
- output.push(` ${relDir}/ — ${plural(info.total, "occurrence")} in ${plural(info.files, "file")}`);
652
- }
653
-
654
- const topFiles = Object.entries(fileCounts).sort((a, b) => b[1] - a[1]).slice(0, 20);
655
- output.push(`\n### Top files`);
656
- for (const [filePath, count] of topFiles) {
657
- const relPath = path.relative(context.directory, filePath);
658
- output.push(` ${relPath} (${plural(count, "occurrence")})`);
659
- }
660
-
661
- output.push(`\n_Heuristic: name-matched, not proof. Follow up with srcwalk_callers for exact call sites._`);
662
- return output.join("\n");
663
- },
664
- }),
81
+ // -----------------------------------------------------------------------
82
+ // srcwalk_read: Read files
83
+ // -----------------------------------------------------------------------
84
+ srcwalk_read: tool({
85
+ description: `Read a file with optional section (line range, symbol, or path:line format).\n\nSmall files return full content; large files support outlining.\nUse path:start-end for range reads (e.g. "src/app.ts:44-89").`,
86
+ args: {
87
+ path: tool.schema
88
+ .string()
89
+ .describe("File path to read (supports path:line or path:start-end)"),
90
+ section: tool.schema
91
+ .string()
92
+ .optional()
93
+ .describe("Line range '44-89' or heading/symbol name"),
94
+ full: tool.schema.boolean().optional().describe("Force full content"),
95
+ },
96
+ execute: async (args, context) => {
97
+ const fileArg = String(args.path);
98
+ const fullFilePath = path.resolve(context.directory, fileArg);
99
+
100
+ // Parse path:line or path:start-end shortcut
101
+ let startLine: number | undefined;
102
+ let endLine: number | undefined;
103
+
104
+ const rangeMatch = fileArg.match(/^(.+?):(\d+)(?:-(\d+))?$/);
105
+ if (rangeMatch) {
106
+ const relPath = rangeMatch[1];
107
+ const resolved = path.resolve(context.directory, relPath);
108
+ startLine = parseInt(rangeMatch[2], 10);
109
+ endLine = rangeMatch[3] ? parseInt(rangeMatch[3], 10) : startLine;
110
+ return readFileRange(resolved, startLine, endLine, relPath);
111
+ }
112
+
113
+ if (!existsSync(fullFilePath)) return `File not found: ${fileArg}`;
114
+ const stats = statSync(fullFilePath);
115
+
116
+ // If section specified, try grep for symbol/heading
117
+ if (args.section) {
118
+ const section = String(args.section);
119
+ // Check if it's a line range
120
+ const lineMatch = section.match(/^(\d+)(?:-(\d+))?$/);
121
+ if (lineMatch) {
122
+ const start = parseInt(lineMatch[1], 10);
123
+ const end = lineMatch[2] ? parseInt(lineMatch[2], 10) : start + 30;
124
+ return readFileRange(fullFilePath, start, end);
125
+ }
126
+ // Symbol/heading: use grep to find location, then read around it
127
+ const grepArgs = [
128
+ "-n",
129
+ "--color=never",
130
+ "-E",
131
+ `^(function |const |let |class |interface |type |export |## |### )?.*${section}`,
132
+ fullFilePath,
133
+ ];
134
+ const result = run("grep", grepArgs);
135
+ if (result.stdout) {
136
+ const firstMatch = result.stdout.split("\n")[0];
137
+ const lineNum = parseInt(firstMatch.split(":")[0], 10);
138
+ if (!isNaN(lineNum)) {
139
+ return readFileRange(fullFilePath, Math.max(1, lineNum - 3), lineNum + 40);
140
+ }
141
+ }
142
+ return `Section "${section}" not found in ${fileArg}`;
143
+ }
144
+
145
+ // Full content for small files
146
+ if (stats.size < 50 * 1024 || args.full) {
147
+ const content = readFileSync(fullFilePath, "utf-8");
148
+ const lines = content.split("\n");
149
+ if (lines.length > 2000)
150
+ return `[File too large: ${plural(lines.length, "line")}. Showing first 2000 lines]\n\n${lines.slice(0, 2000).join("\n")}`;
151
+ return content;
152
+ }
153
+
154
+ // Large file: outline
155
+ const content = readFileSync(fullFilePath, "utf-8");
156
+ const lines = content.split("\n");
157
+ const headings: string[] = [];
158
+ for (let i = 0; i < Math.min(lines.length, 5000); i++) {
159
+ const l = lines[i].trim();
160
+ if (
161
+ l.match(
162
+ /^(export\s+)?(function|class|interface|type|const|enum|def|struct|impl|pub\s+fn)\s/,
163
+ ) ||
164
+ l.match(/^(##|###)\s/) ||
165
+ l.match(/^\w+\s*[:=]/)
166
+ ) {
167
+ headings.push(` ${i + 1}: ${l.slice(0, 120)}`);
168
+ }
169
+ }
170
+ const header = `[File: ${fileArg} — ${plural(lines.length, "line")}, ${(stats.size / 1024).toFixed(1)}KB]\n\n`;
171
+ const outline =
172
+ headings.length > 0
173
+ ? `Outline (${plural(headings.length, "entry")}):\n${headings.slice(0, 50).join("\n")}\n\nUse path:line or section to read a specific range.`
174
+ : `Use path:line to read a specific range (e.g., ${fileArg}:1-${Math.min(50, lines.length)}).`;
175
+ return header + outline;
176
+ },
177
+ }),
178
+
179
+ // -----------------------------------------------------------------------
180
+ // srcwalk_deps: Import analysis
181
+ // -----------------------------------------------------------------------
182
+ srcwalk_deps: tool({
183
+ description: `Show what imports a file (dependents) and what a file imports (dependencies).\nBlast-radius check before breaking changes.`,
184
+ args: {
185
+ path: tool.schema.string().describe("File path to analyze"),
186
+ scope: tool.schema.string().optional().describe("Search scope (default: project root)"),
187
+ },
188
+ execute: async (args, context) => {
189
+ const filePath = String(args.path);
190
+ const absPath = path.resolve(context.directory, filePath);
191
+ if (!existsSync(absPath)) return `File not found: ${filePath}`;
192
+
193
+ const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
194
+ const fileName = path.basename(filePath, path.extname(filePath));
195
+
196
+ // What this file imports
197
+ const content = readFileSync(absPath, "utf-8");
198
+ const importLines: string[] = [];
199
+ for (const line of content.split("\n")) {
200
+ const m = line.match(
201
+ /(?:import|require)\s+.*?from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]/,
202
+ );
203
+ if (m) importLines.push(` ${line.trim()}`);
204
+ }
205
+
206
+ // What imports this file (grep for the module name)
207
+ const searchName = fileName;
208
+ const grepResult = run("grep", [
209
+ "-rn",
210
+ "--color=never",
211
+ "-E",
212
+ `from ['"](\\./|\\.\\./|.*/)${searchName}['"]|require\\(['"](\\./|\\.\\./|.*/)${searchName}['"]`,
213
+ scopeDir,
214
+ "--include=*.ts",
215
+ "--include=*.tsx",
216
+ "--include=*.js",
217
+ "--include=*.jsx",
218
+ "--include=*.mjs",
219
+ ]);
220
+ const importers = grepResult.stdout.split("\n").filter(Boolean).slice(0, 30);
221
+
222
+ const result: string[] = [`## Dependencies for ${filePath}\n`];
223
+ result.push(`### Imports (${plural(importLines.length, "module")})`);
224
+ if (importLines.length === 0) result.push(" (none)");
225
+ else result.push(...importLines);
226
+
227
+ result.push(`\n### Importers (${plural(importers.length, "file")})`);
228
+ if (importers.length === 0) result.push(" (no files import this module)");
229
+ else
230
+ result.push(
231
+ ...importers.map(
232
+ (l) => ` ${path.relative(context.directory, l.split(":")[0])}:${l.split(":")[1]}`,
233
+ ),
234
+ );
235
+
236
+ return result.join("\n");
237
+ },
238
+ }),
239
+
240
+ // -----------------------------------------------------------------------
241
+ // srcwalk_map: Directory overview
242
+ // -----------------------------------------------------------------------
243
+ srcwalk_map: tool({
244
+ description: `Token-annotated directory skeleton. Shows repo structure with file sizes and token estimates. Good for understanding codebase shape.`,
245
+ args: {
246
+ scope: tool.schema.string().optional().describe("Directory to map (default: project root)"),
247
+ depth: tool.schema.number().optional().describe("Max directory depth (default: 3)"),
248
+ },
249
+ execute: async (args, context) => {
250
+ const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
251
+ const maxDepth = args.depth ?? 3;
252
+
253
+ const treeArgs = ["-L", String(maxDepth), "--dirsfirst"];
254
+ // Use tree if available, else ls -R
255
+ const treeResult = run("tree", [
256
+ ...treeArgs,
257
+ "-I",
258
+ ".git|node_modules|dist|build|coverage|.next",
259
+ scopeDir,
260
+ ]);
261
+ if (treeResult.code === 0) {
262
+ return treeResult.stdout.slice(0, 10_000);
263
+ }
264
+
265
+ // Fallback: simple directory listing
266
+ const result: string[] = [
267
+ `## Directory: ${path.relative(context.directory, scopeDir) || "."}\n`,
268
+ ];
269
+ await listDirRecursive(scopeDir, "", maxDepth, result);
270
+ return result.join("\n");
271
+ },
272
+ }),
273
+
274
+ // -----------------------------------------------------------------------
275
+ // srcwalk_callers: Reverse call graph
276
+ // -----------------------------------------------------------------------
277
+ srcwalk_callers: tool({
278
+ description: `Reverse call graph — find what calls a function.\nGrep-based: searches for symbol usage across the codebase.\nUse depth for transitive callers (multi-hop).`,
279
+ args: {
280
+ symbol: tool.schema.string().describe("Function/symbol name"),
281
+ scope: tool.schema.string().optional().describe("Search scope"),
282
+ depth: tool.schema.number().optional().describe("BFS hop depth (default: 1, max: 3)"),
283
+ filter: tool.schema.string().optional().describe("Optional filter (e.g. path:api)"),
284
+ },
285
+ execute: async (args, context) => {
286
+ const symbol = String(args.symbol ?? "").trim();
287
+ if (!symbol) return "symbol is required.";
288
+ const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
289
+ const depth = Math.min(args.depth ?? 1, 3);
290
+
291
+ // Search for direct calls: symbol( or .symbol or symbol.
292
+ const grepArgs = [
293
+ "-rn",
294
+ "--color=never",
295
+ "-E",
296
+ `[.\\s]${symbol}\\s*\\(|[.]${symbol}\\b|\\b${symbol}\\.`,
297
+ scopeDir,
298
+ "--include=*.ts",
299
+ "--include=*.tsx",
300
+ "--include=*.js",
301
+ "--include=*.jsx",
302
+ ];
303
+
304
+ if (args.filter) {
305
+ const filterStr = String(args.filter);
306
+ if (filterStr.startsWith("path:")) {
307
+ grepArgs.push(path.join(scopeDir, filterStr.slice(5)));
308
+ }
309
+ }
310
+
311
+ const result = run("grep", grepArgs);
312
+ const lines = result.stdout.split("\n").filter(Boolean).slice(0, 50);
313
+
314
+ if (lines.length === 0) return `No callers found for "${symbol}".`;
315
+
316
+ const output: string[] = [
317
+ `## Callers of \`${symbol}\` (${plural(lines.length, "result")})${depth > 1 ? ` (depth: ${depth})` : ""}\n`,
318
+ ];
319
+ for (const line of lines) {
320
+ const parts = line.split(":");
321
+ if (parts.length >= 2) {
322
+ const relPath = path.relative(context.directory, parts[0]);
323
+ output.push(` ${relPath}:${parts[1]}: ${parts.slice(2).join(":").trim().slice(0, 150)}`);
324
+ } else {
325
+ output.push(` ${line.slice(0, 200)}`);
326
+ }
327
+ }
328
+
329
+ if (depth > 1) {
330
+ output.push(`\n_Note: Multi-hop depth (${depth}) requires re-running on each caller._`);
331
+ }
332
+ return output.join("\n");
333
+ },
334
+ }),
335
+
336
+ // -----------------------------------------------------------------------
337
+ // srcwalk_callees: Forward call graph
338
+ // -----------------------------------------------------------------------
339
+ srcwalk_callees: tool({
340
+ description: `Forward call graph — what does this function call?\nReads the function body and extracts call sites.`,
341
+ args: {
342
+ symbol: tool.schema.string().describe("Function/symbol name"),
343
+ scope: tool.schema.string().optional().describe("Scope directory"),
344
+ detailed: tool.schema
345
+ .boolean()
346
+ .optional()
347
+ .describe("Show ordered call sites with argument slots"),
348
+ },
349
+ execute: async (args, context) => {
350
+ const symbol = String(args.symbol ?? "").trim();
351
+ if (!symbol) return "symbol is required.";
352
+ const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
353
+
354
+ // Find the function definition
355
+ const defArgs = [
356
+ "-rn",
357
+ "--color=never",
358
+ "-E",
359
+ `(export\\s+)?(function|const|let|async\\s+function)\\s+${symbol}\\b|${symbol}\\s*[:=]\\s*(async\\s+)?\\(`,
360
+ scopeDir,
361
+ "--include=*.ts",
362
+ "--include=*.tsx",
363
+ "--include=*.js",
364
+ "--include=*.jsx",
365
+ ];
366
+ const defResult = run("grep", defArgs);
367
+ const defLines = defResult.stdout.split("\n").filter(Boolean).slice(0, 5);
368
+
369
+ if (defLines.length === 0) {
370
+ return `Definition not found for "${symbol}". Cannot trace callees without finding the function body.`;
371
+ }
372
+
373
+ const output: string[] = [`## Callees of \`${symbol}\`\n`];
374
+
375
+ // For each definition location, show the function and extract calls
376
+ for (const def of defLines) {
377
+ const parts = def.split(":");
378
+ if (parts.length >= 2) {
379
+ const relPath = path.relative(context.directory, parts[0]);
380
+ const lineNum = parseInt(parts[1], 10);
381
+ output.push(`**Definition:** ${relPath}:${lineNum}`);
382
+
383
+ // Read function body to extract calls
384
+ const filePath = path.resolve(context.directory, parts[0]);
385
+ if (existsSync(filePath)) {
386
+ const fileLines = readFileSync(filePath, "utf-8").split("\n");
387
+ let braceCount = 0;
388
+ let inFunc = false;
389
+ const calls: string[] = [];
390
+
391
+ for (let i = lineNum - 1; i < Math.min(lineNum + 80, fileLines.length); i++) {
392
+ const line = fileLines[i];
393
+ if (!inFunc) {
394
+ if (line.includes("{")) {
395
+ inFunc = true;
396
+ braceCount = (line.match(/{/g) || []).length;
397
+ braceCount -= (line.match(/}/g) || []).length;
398
+ }
399
+ continue;
400
+ }
401
+ braceCount += (line.match(/{/g) || []).length;
402
+ braceCount -= (line.match(/}/g) || []).length;
403
+
404
+ // Extract function calls
405
+ const callMatch = [...line.matchAll(/(?<![.\w])(\w+)\s*\(/g)];
406
+ for (const m of callMatch) {
407
+ const name = m[1];
408
+ if (
409
+ ![
410
+ "if",
411
+ "for",
412
+ "while",
413
+ "switch",
414
+ "catch",
415
+ "typeof",
416
+ "instanceof",
417
+ "return",
418
+ "throw",
419
+ "new",
420
+ "delete",
421
+ "await",
422
+ "yield",
423
+ ].includes(name)
424
+ ) {
425
+ const argStart = line.indexOf("(", m.index!);
426
+ const argEnd = line.indexOf(")", argStart);
427
+ const args_s =
428
+ argEnd > argStart
429
+ ? line
430
+ .slice(argStart + 1, argEnd)
431
+ .trim()
432
+ .slice(0, 60)
433
+ : "";
434
+ calls.push(` ${args.detailed ? `${name}(${args_s})` : `${name}()`}`);
435
+ }
436
+ }
437
+
438
+ if (braceCount <= 0) break;
439
+ }
440
+
441
+ if (calls.length > 0) {
442
+ output.push(...calls);
443
+ } else {
444
+ output.push(" (no internal calls found)");
445
+ }
446
+ output.push("");
447
+ }
448
+ }
449
+ }
450
+
451
+ return output.join("\n");
452
+ },
453
+ }),
454
+
455
+ // -----------------------------------------------------------------------
456
+ // srcwalk_flow: Compact orientation
457
+ // -----------------------------------------------------------------------
458
+ srcwalk_flow: tool({
459
+ description: `Compact function orientation — ordered callees + direct callers.\nQuick understanding of a function's role in the call graph.`,
460
+ args: {
461
+ symbol: tool.schema.string().describe("Symbol name to analyze"),
462
+ scope: tool.schema.string().optional().describe("Search scope"),
463
+ },
464
+ execute: async (args, context) => {
465
+ const symbol = String(args.symbol ?? "").trim();
466
+ if (!symbol) return "symbol is required.";
467
+ const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
468
+
469
+ // Get callers
470
+ const callersResult = run("grep", [
471
+ "-rn",
472
+ "--color=never",
473
+ "-E",
474
+ `[.\\s]${symbol}\\s*\\(|[.]${symbol}\\b`,
475
+ scopeDir,
476
+ "--include=*.ts",
477
+ "--include=*.tsx",
478
+ "--include=*.js",
479
+ "--include=*.jsx",
480
+ ]);
481
+ const callers = callersResult.stdout.split("\n").filter(Boolean).slice(0, 15);
482
+
483
+ // Get callees by reading function body
484
+ const defResult = run("grep", [
485
+ "-rn",
486
+ "--color=never",
487
+ "-E",
488
+ `(function|const|let)\\s+${symbol}\\b|${symbol}\\s*[:=]\\s*(async\\s+)?\\(`,
489
+ scopeDir,
490
+ "--include=*.ts",
491
+ "--include=*.tsx",
492
+ "--include=*.js",
493
+ "--include=*.jsx",
494
+ ]);
495
+ const defLine = defResult.stdout.split("\n").filter(Boolean)[0];
496
+ let callees: string[] = [];
497
+
498
+ if (defLine) {
499
+ const parts = defLine.split(":");
500
+ if (parts.length >= 2) {
501
+ const fp = path.resolve(context.directory, parts[0]);
502
+ const ln = parseInt(parts[1], 10);
503
+ if (existsSync(fp)) {
504
+ const fileLines = readFileSync(fp, "utf-8").split("\n");
505
+ let bc = 0,
506
+ inF = false;
507
+ for (let i = ln - 1; i < Math.min(ln + 60, fileLines.length); i++) {
508
+ const l = fileLines[i];
509
+ if (!inF) {
510
+ if (l.includes("{")) {
511
+ inF = true;
512
+ bc = (l.match(/{/g) || []).length - (l.match(/}/g) || []).length;
513
+ }
514
+ continue;
515
+ }
516
+ bc += (l.match(/{/g) || []).length - (l.match(/}/g) || []).length;
517
+ for (const m of l.matchAll(/(\w+)\s*\(/g)) {
518
+ if (
519
+ ![
520
+ "if",
521
+ "for",
522
+ "while",
523
+ "switch",
524
+ "catch",
525
+ "typeof",
526
+ "instanceof",
527
+ "return",
528
+ "throw",
529
+ "new",
530
+ "delete",
531
+ "await",
532
+ "yield",
533
+ ].includes(m[1])
534
+ )
535
+ callees.push(m[1]);
536
+ }
537
+ if (bc <= 0) break;
538
+ }
539
+ }
540
+ }
541
+ }
542
+
543
+ const output: string[] = [`## Flow: \`${symbol}\``];
544
+ output.push(`\n**Callers (${plural(callers.length, "file")}):`);
545
+ if (callers.length === 0) output.push(" (none)");
546
+ else
547
+ output.push(
548
+ ...callers
549
+ .slice(0, 10)
550
+ .map(
551
+ (l) => ` ${path.relative(context.directory, l.split(":")[0])}:${l.split(":")[1]}`,
552
+ ),
553
+ );
554
+
555
+ output.push(`\n**Callees (${plural(callees.length, "call")}):`);
556
+ if (callees.length === 0) output.push(" (none)");
557
+ else output.push(...[...new Set(callees)].slice(0, 20).map((c) => ` ${c}()`));
558
+ return output.join("\n");
559
+ },
560
+ }),
561
+
562
+ // -----------------------------------------------------------------------
563
+ // srcwalk_impact: Heuristic blast-radius
564
+ // -----------------------------------------------------------------------
565
+ srcwalk_impact: tool({
566
+ description: `Heuristic blast-radius triage — broad 'what might be affected?' starting point.\nName-matched, not proof. Use as starting point before verifying with srcwalk_callers or exact reads.`,
567
+ args: {
568
+ symbol: tool.schema.string().describe("Symbol name to triage"),
569
+ scope: tool.schema.string().optional().describe("Search scope"),
570
+ },
571
+ execute: async (args, context) => {
572
+ const symbol = String(args.symbol ?? "").trim();
573
+ if (!symbol) return "symbol is required.";
574
+ const scopeDir = path.resolve(context.directory, args.scope ? String(args.scope) : "");
575
+
576
+ // Count usages per directory
577
+ const grepResult = run("grep", [
578
+ "-rn",
579
+ "--color=never",
580
+ "-E",
581
+ `\\b${symbol}\\b`,
582
+ scopeDir,
583
+ "--include=*.ts",
584
+ "--include=*.tsx",
585
+ "--include=*.js",
586
+ "--include=*.jsx",
587
+ ]);
588
+ const lines = grepResult.stdout.split("\n").filter(Boolean);
589
+
590
+ // Group by file
591
+ const fileCounts: Record<string, number> = {};
592
+ for (const line of lines) {
593
+ const filePath = line.split(":")[0];
594
+ fileCounts[filePath] = (fileCounts[filePath] || 0) + 1;
595
+ }
596
+
597
+ // Group by directory
598
+ const dirCounts: Record<string, { files: number; total: number }> = {};
599
+ for (const [filePath, count] of Object.entries(fileCounts)) {
600
+ const dir = path.dirname(filePath);
601
+ if (!dirCounts[dir]) dirCounts[dir] = { files: 0, total: 0 };
602
+ dirCounts[dir].files++;
603
+ dirCounts[dir].total += count;
604
+ }
605
+
606
+ const totalOccurrences = lines.length;
607
+ const totalFiles = Object.keys(fileCounts).length;
608
+
609
+ const output: string[] = [
610
+ `## Impact: \`${symbol}\``,
611
+ `Total: ${plural(totalOccurrences, "occurrence")} across ${plural(totalFiles, "file")}\n`,
612
+ `### By directory`,
613
+ ];
614
+
615
+ const sortedDirs = Object.entries(dirCounts).sort((a, b) => b[1].total - a[1].total);
616
+ for (const [dir, info] of sortedDirs.slice(0, 15)) {
617
+ const relDir = path.relative(context.directory, dir) || ".";
618
+ output.push(
619
+ ` ${relDir}/ — ${plural(info.total, "occurrence")} in ${plural(info.files, "file")}`,
620
+ );
621
+ }
622
+
623
+ const topFiles = Object.entries(fileCounts)
624
+ .sort((a, b) => b[1] - a[1])
625
+ .slice(0, 20);
626
+ output.push(`\n### Top files`);
627
+ for (const [filePath, count] of topFiles) {
628
+ const relPath = path.relative(context.directory, filePath);
629
+ output.push(` ${relPath} (${plural(count, "occurrence")})`);
630
+ }
631
+
632
+ output.push(
633
+ `\n_Heuristic: name-matched, not proof. Follow up with srcwalk_callers for exact call sites._`,
634
+ );
635
+ return output.join("\n");
636
+ },
637
+ }),
665
638
  };
666
639
 
667
640
  // ---------------------------------------------------------------------------
@@ -669,53 +642,59 @@ const srcwalkTools = {
669
642
  // ---------------------------------------------------------------------------
670
643
 
671
644
  function readFileRange(filePath: string, start: number, end: number, displayPath?: string): string {
672
- try {
673
- const content = readFileSync(filePath, "utf-8");
674
- const lines = content.split("\n");
675
- const from = Math.max(0, start - 1);
676
- const to = Math.min(lines.length, end);
677
- const result: string[] = [`File: ${displayPath ?? filePath} (lines ${start}-${end}):\n`];
678
- for (let i = from; i < to; i++) {
679
- result.push(`${i + 1}: ${lines[i]}`);
680
- }
681
- return result.join("\n");
682
- } catch (err) {
683
- return `Error reading file: ${err instanceof Error ? err.message : String(err)}`;
684
- }
645
+ try {
646
+ const content = readFileSync(filePath, "utf-8");
647
+ const lines = content.split("\n");
648
+ const from = Math.max(0, start - 1);
649
+ const to = Math.min(lines.length, end);
650
+ const result: string[] = [`File: ${displayPath ?? filePath} (lines ${start}-${end}):\n`];
651
+ for (let i = from; i < to; i++) {
652
+ result.push(`${i + 1}: ${lines[i]}`);
653
+ }
654
+ return result.join("\n");
655
+ } catch (err) {
656
+ return `Error reading file: ${err instanceof Error ? err.message : String(err)}`;
657
+ }
685
658
  }
686
659
 
687
- async function listDirRecursive(dir: string, prefix: string, maxDepth: number, output: string[], rootDir: string): Promise<void> {
688
- if (maxDepth <= 0) return;
689
- try {
690
- const entries = await readdir(dir, { withFileTypes: true });
691
- const skipDirs = new Set([".git", "node_modules", "dist", "build", "coverage", ".next"]);
692
- const dirs = entries.filter(e => e.isDirectory() && !skipDirs.has(e.name)).sort((a, b) => a.name.localeCompare(b.name));
693
- const files = entries.filter(e => e.isFile()).sort((a, b) => a.name.localeCompare(b.name));
694
-
695
- for (const d of dirs) {
696
- const relPath = path.relative(rootDir, path.join(dir, d.name));
697
- output.push(`${prefix}${d.name}/`);
698
- await listDirRecursive(path.join(dir, d.name), prefix + " ", maxDepth - 1, output, rootDir);
699
- }
700
- for (const f of files) {
701
- const fp = path.join(dir, f.name);
702
- try {
703
- const size = statSync(fp).size;
704
- const tokenEst = Math.ceil(size / 4);
705
- output.push(`${prefix}${f.name} (~${tokenEst.toLocaleString()} tokens)`);
706
- } catch {
707
- output.push(`${prefix}${f.name}`);
708
- }
709
- }
710
- } catch {
711
- // Permission denied, skip
712
- }
660
+ async function listDirRecursive(
661
+ dir: string,
662
+ prefix: string,
663
+ maxDepth: number,
664
+ output: string[],
665
+ ): Promise<void> {
666
+ if (maxDepth <= 0) return;
667
+ try {
668
+ const entries = await readdir(dir, { withFileTypes: true });
669
+ const skipDirs = new Set([".git", "node_modules", "dist", "build", "coverage", ".next"]);
670
+ const dirs = entries
671
+ .filter((e) => e.isDirectory() && !skipDirs.has(e.name))
672
+ .sort((a, b) => a.name.localeCompare(b.name));
673
+ const files = entries.filter((e) => e.isFile()).sort((a, b) => a.name.localeCompare(b.name));
674
+
675
+ for (const d of dirs) {
676
+ output.push(`${prefix}${d.name}/`);
677
+ await listDirRecursive(path.join(dir, d.name), prefix + " ", maxDepth - 1, output);
678
+ }
679
+ for (const f of files) {
680
+ const fp = path.join(dir, f.name);
681
+ try {
682
+ const size = statSync(fp).size;
683
+ const tokenEst = Math.ceil(size / 4);
684
+ output.push(`${prefix}${f.name} (~${tokenEst.toLocaleString()} tokens)`);
685
+ } catch {
686
+ output.push(`${prefix}${f.name}`);
687
+ }
688
+ }
689
+ } catch {
690
+ // Permission denied, skip
691
+ }
713
692
  }
714
693
 
715
694
  export const SrcwalkPlugin: Plugin = async () => {
716
- return {
717
- tool: srcwalkTools,
718
- };
695
+ return {
696
+ tool: srcwalkTools,
697
+ };
719
698
  };
720
699
 
721
700
  export default SrcwalkPlugin;