opencodekit 0.21.10 → 0.23.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 (213) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +4 -25
  3. package/dist/template/.opencode/.template-manifest.json +115 -188
  4. package/dist/template/.opencode/AGENTS.md +127 -484
  5. package/dist/template/.opencode/README.md +2 -2
  6. package/dist/template/.opencode/agent/build.md +158 -356
  7. package/dist/template/.opencode/agent/explore.md +0 -1
  8. package/dist/template/.opencode/agent/plan.md +7 -16
  9. package/dist/template/.opencode/agent/review.md +0 -1
  10. package/dist/template/.opencode/agent/scout.md +2 -3
  11. package/dist/template/.opencode/agent/vision.md +0 -1
  12. package/dist/template/.opencode/artifacts/.active +1 -0
  13. package/dist/template/.opencode/artifacts/example/plan.md +12 -0
  14. package/dist/template/.opencode/artifacts/example/progress.md +4 -0
  15. package/dist/template/.opencode/artifacts/example/research.md +4 -0
  16. package/dist/template/.opencode/artifacts/example/spec.md +16 -0
  17. package/dist/template/.opencode/artifacts/todo.md +5 -0
  18. package/dist/template/.opencode/artifacts/verify.log +4 -0
  19. package/dist/template/.opencode/command/clarify.md +46 -0
  20. package/dist/template/.opencode/command/commit.md +53 -0
  21. package/dist/template/.opencode/command/create.md +29 -71
  22. package/dist/template/.opencode/command/design.md +1 -2
  23. package/dist/template/.opencode/command/explore.md +3 -4
  24. package/dist/template/.opencode/command/fix.md +55 -0
  25. package/dist/template/.opencode/command/improve-architecture.md +55 -0
  26. package/dist/template/.opencode/command/init.md +86 -69
  27. package/dist/template/.opencode/command/plan.md +30 -60
  28. package/dist/template/.opencode/command/pr.md +10 -28
  29. package/dist/template/.opencode/command/refactor.md +65 -0
  30. package/dist/template/.opencode/command/research.md +7 -29
  31. package/dist/template/.opencode/command/review-codebase.md +6 -13
  32. package/dist/template/.opencode/command/ship.md +136 -78
  33. package/dist/template/.opencode/command/test.md +66 -0
  34. package/dist/template/.opencode/command/ui-review.md +2 -4
  35. package/dist/template/.opencode/command/verify.md +15 -23
  36. package/dist/template/.opencode/dcp.jsonc +96 -85
  37. package/dist/template/.opencode/memory/README.md +4 -6
  38. package/dist/template/.opencode/memory/_templates/adr.md +45 -0
  39. package/dist/template/.opencode/memory/_templates/prd.md +1 -1
  40. package/dist/template/.opencode/memory/_templates/roadmap.md +1 -1
  41. package/dist/template/.opencode/memory/_templates/state.md +1 -1
  42. package/dist/template/.opencode/memory/project/gotchas.md +4 -4
  43. package/dist/template/.opencode/memory/project/project.md +2 -2
  44. package/dist/template/.opencode/memory/project/roadmap.md +1 -1
  45. package/dist/template/.opencode/memory/project/state.md +2 -2
  46. package/dist/template/.opencode/memory/project/tech-stack.md +2 -2
  47. package/dist/template/.opencode/memory/session-context.md +1 -1
  48. package/dist/template/.opencode/opencode.json +14 -152
  49. package/dist/template/.opencode/plugin/README.md +2 -2
  50. package/dist/template/.opencode/plugin/guard.ts +62 -0
  51. package/dist/template/.opencode/plugin/{lib/memory-admin-tools.ts → memory/admin.ts} +4 -4
  52. package/dist/template/.opencode/plugin/{lib → memory}/capture.ts +1 -1
  53. package/dist/template/.opencode/plugin/{lib → memory}/compile.ts +2 -2
  54. package/dist/template/.opencode/plugin/{lib → memory}/context.ts +1 -1
  55. package/dist/template/.opencode/plugin/{lib → memory}/curator.ts +1 -1
  56. package/dist/template/.opencode/plugin/{lib → memory}/db/observations.ts +102 -3
  57. package/dist/template/.opencode/plugin/{lib → memory}/db/schema.ts +43 -1
  58. package/dist/template/.opencode/plugin/{lib → memory}/db/types.ts +22 -0
  59. package/dist/template/.opencode/plugin/{lib/memory-db.ts → memory/db.ts} +1 -1
  60. package/dist/template/.opencode/plugin/{lib → memory}/distill.ts +1 -1
  61. package/dist/template/.opencode/plugin/{lib/memory-helpers.ts → memory/helpers.ts} +5 -1
  62. package/dist/template/.opencode/plugin/{lib/memory-hooks.ts → memory/hooks.ts} +1 -1
  63. package/dist/template/.opencode/plugin/{lib → memory}/index-generator.ts +2 -2
  64. package/dist/template/.opencode/plugin/{lib → memory}/inject.ts +1 -1
  65. package/dist/template/.opencode/plugin/{lib → memory}/lint.ts +2 -2
  66. package/dist/template/.opencode/plugin/memory/tools.ts +322 -0
  67. package/dist/template/.opencode/plugin/{lib → memory}/validate.ts +2 -2
  68. package/dist/template/.opencode/plugin/memory.ts +7 -17
  69. package/dist/template/.opencode/plugin/srcwalk.ts +721 -0
  70. package/dist/template/.opencode/skill/agent-code-quality-gate/SKILL.md +98 -0
  71. package/dist/template/.opencode/skill/behavioral-kernel/SKILL.md +52 -0
  72. package/dist/template/.opencode/skill/brainstorming/SKILL.md +1 -1
  73. package/dist/template/.opencode/skill/browser-testing-with-devtools/SKILL.md +85 -0
  74. package/dist/template/.opencode/skill/code-cleanup/SKILL.md +114 -0
  75. package/dist/template/.opencode/skill/code-navigation/SKILL.md +142 -0
  76. package/dist/template/.opencode/skill/code-review-and-quality/SKILL.md +131 -0
  77. package/dist/template/.opencode/skill/context-engineering/SKILL.md +1 -1
  78. package/dist/template/.opencode/skill/debugging-and-error-recovery/SKILL.md +109 -0
  79. package/dist/template/.opencode/skill/deep-module-design/SKILL.md +207 -0
  80. package/dist/template/.opencode/skill/development-lifecycle/SKILL.md +26 -45
  81. package/dist/template/.opencode/skill/gemini-large-context/SKILL.md +4 -4
  82. package/dist/template/.opencode/skill/git-workflow-and-versioning/SKILL.md +77 -0
  83. package/dist/template/.opencode/skill/grill-me/SKILL.md +140 -0
  84. package/dist/template/.opencode/skill/memory-system/SKILL.md +9 -10
  85. package/dist/template/.opencode/skill/opensrc/references/example-workflow.md +1 -1
  86. package/dist/template/.opencode/skill/planning-and-task-breakdown/SKILL.md +116 -0
  87. package/dist/template/.opencode/skill/shipping-and-launch/SKILL.md +95 -0
  88. package/dist/template/.opencode/skill/source-driven-development/SKILL.md +103 -0
  89. package/dist/template/.opencode/skill/spec-driven-development/SKILL.md +121 -0
  90. package/dist/template/.opencode/skill/srcwalk/SKILL.md +161 -0
  91. package/dist/template/.opencode/skill/subagent-driven-development/SKILL.md +1 -1
  92. package/dist/template/.opencode/skill/ubiquitous-language/SKILL.md +184 -0
  93. package/dist/template/.opencode/skill/using-git-worktrees/SKILL.md +6 -6
  94. package/dist/template/.opencode/skill/verification-before-completion/SKILL.md +6 -6
  95. package/dist/template/.opencode/skill/verification-before-completion/references/VERIFICATION_PROTOCOL.md +5 -5
  96. package/package.json +76 -76
  97. package/dist/template/.opencode/AGENT_ALIGNMENT.md +0 -564
  98. package/dist/template/.opencode/agent/painter.md +0 -83
  99. package/dist/template/.opencode/command/compound.md +0 -240
  100. package/dist/template/.opencode/command/curate.md +0 -299
  101. package/dist/template/.opencode/command/handoff.md +0 -149
  102. package/dist/template/.opencode/command/health.md +0 -356
  103. package/dist/template/.opencode/command/init-context.md +0 -297
  104. package/dist/template/.opencode/command/init-user.md +0 -125
  105. package/dist/template/.opencode/command/iterate.md +0 -200
  106. package/dist/template/.opencode/command/lfg.md +0 -173
  107. package/dist/template/.opencode/command/resume.md +0 -78
  108. package/dist/template/.opencode/command/status.md +0 -126
  109. package/dist/template/.opencode/command/ui-slop-check.md +0 -169
  110. package/dist/template/.opencode/plans/1768385996691-silent-wizard.md +0 -247
  111. package/dist/template/.opencode/plans/1770006237537-mighty-otter.md +0 -418
  112. package/dist/template/.opencode/plans/1770006913647-glowing-forest.md +0 -170
  113. package/dist/template/.opencode/plans/1770013678126-witty-planet.md +0 -278
  114. package/dist/template/.opencode/plans/1770112267595-shiny-rocket.md +0 -258
  115. package/dist/template/.opencode/plans/swarm-protocol.md +0 -123
  116. package/dist/template/.opencode/plugin/lib/memory-tools.ts +0 -535
  117. package/dist/template/.opencode/skill/agent-evals/SKILL.md +0 -208
  118. package/dist/template/.opencode/skill/anti-ai-slop/SKILL.md +0 -76
  119. package/dist/template/.opencode/skill/augment-context-engine/SKILL.md +0 -122
  120. package/dist/template/.opencode/skill/augment-context-engine/mcp.json +0 -6
  121. package/dist/template/.opencode/skill/beads/SKILL.md +0 -182
  122. package/dist/template/.opencode/skill/beads/references/BEST_PRACTICES.md +0 -27
  123. package/dist/template/.opencode/skill/beads/references/BOUNDARIES.md +0 -219
  124. package/dist/template/.opencode/skill/beads/references/DEPENDENCIES.md +0 -124
  125. package/dist/template/.opencode/skill/beads/references/EXAMPLES.md +0 -45
  126. package/dist/template/.opencode/skill/beads/references/FILE_CLAIMING.md +0 -101
  127. package/dist/template/.opencode/skill/beads/references/GIT_SYNC.md +0 -25
  128. package/dist/template/.opencode/skill/beads/references/HIERARCHY.md +0 -71
  129. package/dist/template/.opencode/skill/beads/references/MULTI_AGENT.md +0 -40
  130. package/dist/template/.opencode/skill/beads/references/RESUMABILITY.md +0 -177
  131. package/dist/template/.opencode/skill/beads/references/SESSION_PROTOCOL.md +0 -61
  132. package/dist/template/.opencode/skill/beads/references/TASK_CREATION.md +0 -38
  133. package/dist/template/.opencode/skill/beads/references/TROUBLESHOOTING.md +0 -38
  134. package/dist/template/.opencode/skill/beads/references/WORKFLOWS.md +0 -226
  135. package/dist/template/.opencode/skill/brand-asset-protocol/SKILL.md +0 -222
  136. package/dist/template/.opencode/skill/code-search-patterns/SKILL.md +0 -224
  137. package/dist/template/.opencode/skill/code-simplification/SKILL.md +0 -211
  138. package/dist/template/.opencode/skill/context-condensation/SKILL.md +0 -149
  139. package/dist/template/.opencode/skill/context-initialization/SKILL.md +0 -69
  140. package/dist/template/.opencode/skill/context-management/SKILL.md +0 -390
  141. package/dist/template/.opencode/skill/deep-research/SKILL.md +0 -384
  142. package/dist/template/.opencode/skill/design-direction-advisor/SKILL.md +0 -139
  143. package/dist/template/.opencode/skill/dispatching-parallel-agents/SKILL.md +0 -191
  144. package/dist/template/.opencode/skill/executing-plans/SKILL.md +0 -247
  145. package/dist/template/.opencode/skill/figma-go/SKILL.md +0 -65
  146. package/dist/template/.opencode/skill/finishing-a-development-branch/SKILL.md +0 -357
  147. package/dist/template/.opencode/skill/full-output-enforcement/SKILL.md +0 -62
  148. package/dist/template/.opencode/skill/gh-address-comments/SKILL.md +0 -29
  149. package/dist/template/.opencode/skill/gh-address-comments/scripts/fetch_comments.py +0 -237
  150. package/dist/template/.opencode/skill/gh-fix-ci/SKILL.md +0 -38
  151. package/dist/template/.opencode/skill/gh-fix-ci/scripts/inspect_pr_checks.py +0 -509
  152. package/dist/template/.opencode/skill/hi-fi-prototype-html/SKILL.md +0 -253
  153. package/dist/template/.opencode/skill/html-deck-export/SKILL.md +0 -189
  154. package/dist/template/.opencode/skill/index-knowledge/SKILL.md +0 -413
  155. package/dist/template/.opencode/skill/memory-grounding/SKILL.md +0 -68
  156. package/dist/template/.opencode/skill/playwriter/SKILL.md +0 -158
  157. package/dist/template/.opencode/skill/portless/SKILL.md +0 -109
  158. package/dist/template/.opencode/skill/prd/SKILL.md +0 -146
  159. package/dist/template/.opencode/skill/prd-task/SKILL.md +0 -182
  160. package/dist/template/.opencode/skill/prd-task/references/prd-schema.json +0 -124
  161. package/dist/template/.opencode/skill/prompt-leverage/SKILL.md +0 -90
  162. package/dist/template/.opencode/skill/prompt-leverage/references/framework.md +0 -91
  163. package/dist/template/.opencode/skill/prompt-leverage/scripts/augment_prompt.py +0 -157
  164. package/dist/template/.opencode/skill/receiving-code-review/SKILL.md +0 -263
  165. package/dist/template/.opencode/skill/reconcile/SKILL.md +0 -183
  166. package/dist/template/.opencode/skill/reflection-checkpoints/SKILL.md +0 -183
  167. package/dist/template/.opencode/skill/requesting-code-review/SKILL.md +0 -443
  168. package/dist/template/.opencode/skill/requesting-code-review/references/specialist-profiles.md +0 -108
  169. package/dist/template/.opencode/skill/requesting-code-review/review.md +0 -160
  170. package/dist/template/.opencode/skill/rtk-command-compression/SKILL.md +0 -134
  171. package/dist/template/.opencode/skill/screenshot/SKILL.md +0 -48
  172. package/dist/template/.opencode/skill/screenshot/scripts/ensure_macos_permissions.sh +0 -54
  173. package/dist/template/.opencode/skill/screenshot/scripts/macos_display_info.swift +0 -22
  174. package/dist/template/.opencode/skill/screenshot/scripts/macos_permissions.swift +0 -40
  175. package/dist/template/.opencode/skill/screenshot/scripts/macos_window_info.swift +0 -126
  176. package/dist/template/.opencode/skill/screenshot/scripts/take_screenshot.ps1 +0 -163
  177. package/dist/template/.opencode/skill/screenshot/scripts/take_screenshot.py +0 -585
  178. package/dist/template/.opencode/skill/security-threat-model/SKILL.md +0 -36
  179. package/dist/template/.opencode/skill/security-threat-model/references/prompt-template.md +0 -255
  180. package/dist/template/.opencode/skill/security-threat-model/references/security-controls-and-assets.md +0 -32
  181. package/dist/template/.opencode/skill/sharing-skills/SKILL.md +0 -214
  182. package/dist/template/.opencode/skill/skill-creator/SKILL.md +0 -181
  183. package/dist/template/.opencode/skill/skill-installer/SKILL.md +0 -58
  184. package/dist/template/.opencode/skill/skill-installer/scripts/github_utils.py +0 -21
  185. package/dist/template/.opencode/skill/skill-installer/scripts/install-skill-from-github.py +0 -313
  186. package/dist/template/.opencode/skill/skill-installer/scripts/list-skills.py +0 -106
  187. package/dist/template/.opencode/skill/swarm-coordination/SKILL.md +0 -244
  188. package/dist/template/.opencode/skill/swarm-coordination/references/architecture.md +0 -39
  189. package/dist/template/.opencode/skill/swarm-coordination/references/delegation-worker-protocol.md +0 -145
  190. package/dist/template/.opencode/skill/swarm-coordination/references/dependency-graph.md +0 -50
  191. package/dist/template/.opencode/skill/swarm-coordination/references/drift-check.md +0 -90
  192. package/dist/template/.opencode/skill/swarm-coordination/references/integration-beads.md +0 -20
  193. package/dist/template/.opencode/skill/swarm-coordination/references/launch-flow.md +0 -186
  194. package/dist/template/.opencode/skill/swarm-coordination/references/reconciler.md +0 -172
  195. package/dist/template/.opencode/skill/swarm-coordination/references/tier-enforcement.md +0 -78
  196. package/dist/template/.opencode/skill/swarm-coordination/references/tmux-integration.md +0 -134
  197. package/dist/template/.opencode/skill/systematic-debugging/SKILL.md +0 -402
  198. package/dist/template/.opencode/skill/terse-output-mode/SKILL.md +0 -95
  199. package/dist/template/.opencode/skill/think-in-code/SKILL.md +0 -136
  200. package/dist/template/.opencode/skill/ux-quality-gates/SKILL.md +0 -137
  201. package/dist/template/.opencode/skill/v1-run/SKILL.md +0 -175
  202. package/dist/template/.opencode/skill/v1-run/mcp.json +0 -6
  203. package/dist/template/.opencode/skill/verification-gates/SKILL.md +0 -63
  204. package/dist/template/.opencode/skill/visual-analysis/SKILL.md +0 -154
  205. package/dist/template/.opencode/skill/web-design-guidelines/SKILL.md +0 -46
  206. package/dist/template/.opencode/skill/workspace-setup/SKILL.md +0 -76
  207. package/dist/template/.opencode/skill/writing-plans/SKILL.md +0 -320
  208. /package/dist/template/.opencode/plugin/{lib → memory}/compact.ts +0 -0
  209. /package/dist/template/.opencode/plugin/{lib → memory}/db/graph.ts +0 -0
  210. /package/dist/template/.opencode/plugin/{lib → memory}/db/maintenance.ts +0 -0
  211. /package/dist/template/.opencode/plugin/{lib → memory}/db/pipeline.ts +0 -0
  212. /package/dist/template/.opencode/plugin/{lib → memory}/notify.ts +0 -0
  213. /package/dist/template/.opencode/plugin/{lib → memory}/operation-log.ts +0 -0
@@ -0,0 +1,721 @@
1
+ /**
2
+ * Srcwalk Plugin — Code Intelligence Tools
3
+ *
4
+ * Provides structured code navigation tools for OpenCode agents.
5
+ * Wraps available CLI tools (rg/grep, find, cat, ls) into unified srcwalk_* tools.
6
+ *
7
+ * Tools (matching pikit srcwalk extension surface):
8
+ * - srcwalk_search — Search symbols/text/regex in codebase
9
+ * - srcwalk_read — Read files with optional section/range
10
+ * - srcwalk_files — Find files by glob pattern
11
+ * - srcwalk_deps — Show imports and dependents for a file
12
+ * - srcwalk_map — Directory tree overview
13
+ * - srcwalk_callers — Reverse call graph (grep-based)
14
+ * - srcwalk_callees — Forward call graph (grep-based)
15
+ * - srcwalk_flow — Compact function orientation
16
+ * - srcwalk_impact — Heuristic blast-radius triage
17
+ */
18
+
19
+ import { execFile, execFileSync } from "node:child_process";
20
+ import { existsSync, readFileSync, statSync } from "node:fs";
21
+ import { readdir } from "node:fs/promises";
22
+ import path from "node:path";
23
+ import { tool } from "@opencode-ai/plugin/tool";
24
+ import type { Plugin } from "@opencode-ai/plugin";
25
+
26
+ const BIN_RG = "rg";
27
+ const TIMEOUT_MS = 15_000;
28
+ const MAX_BUFFER = 5 * 1024 * 1024;
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Helpers
32
+ // ---------------------------------------------------------------------------
33
+
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
+ }
61
+ }
62
+
63
+ function plural(n: number, word: string): string {
64
+ return `${n} ${word}${n !== 1 ? "s" : ""}`;
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Plugin
69
+ // ---------------------------------------------------------------------------
70
+
71
+ interface PluginConfig {
72
+ directory?: string;
73
+ }
74
+
75
+ 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
+ }),
665
+ };
666
+
667
+ // ---------------------------------------------------------------------------
668
+ // Helpers
669
+ // ---------------------------------------------------------------------------
670
+
671
+ 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
+ }
685
+ }
686
+
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
+ }
713
+ }
714
+
715
+ export const SrcwalkPlugin: Plugin = async () => {
716
+ return {
717
+ tool: srcwalkTools,
718
+ };
719
+ };
720
+
721
+ export default SrcwalkPlugin;