-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathindex.ts
More file actions
257 lines (227 loc) · 11.3 KB
/
index.ts
File metadata and controls
257 lines (227 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import { tool, type ToolDefinition } from "@opencode-ai/plugin";
import { Indexer } from "../indexer/index.js";
import { ParsedCodebaseIndexConfig } from "../config/schema.js";
import { formatCostEstimate } from "../utils/cost.js";
import type { LogLevel } from "../config/schema.js";
import type { LogEntry } from "../utils/logger.js";
import {
formatProgressTitle,
formatIndexStats,
formatStatus,
calculatePercentage,
formatCodebasePeek,
formatHealthCheck,
formatLogs,
formatSearchResults,
} from "./utils.js";
const z = tool.schema;
let sharedIndexer: Indexer | null = null;
export function initializeTools(projectRoot: string, config: ParsedCodebaseIndexConfig): void {
sharedIndexer = new Indexer(projectRoot, config);
}
function getIndexer(): Indexer {
if (!sharedIndexer) {
throw new Error("Codebase index tools not initialized. Plugin may not be loaded correctly.");
}
return sharedIndexer;
}
export const codebase_peek: ToolDefinition = tool({
description:
"Quick lookup of code locations by meaning. Returns only metadata (file, line, name, type) WITHOUT code content. Use this first to find WHERE code is, then use Read tool to examine specific files. Saves tokens by not returning full code blocks. Best for: discovery, navigation, finding multiple related locations.",
args: {
query: z.string().describe("Natural language description of what code you're looking for."),
limit: z.number().optional().default(10).describe("Maximum number of results to return"),
fileType: z.string().optional().describe("Filter by file extension (e.g., 'ts', 'py', 'rs')"),
directory: z.string().optional().describe("Filter by directory path (e.g., 'src/utils', 'lib')"),
chunkType: z.enum(["function", "class", "method", "interface", "type", "enum", "struct", "impl", "trait", "module", "other"]).optional().describe("Filter by code chunk type"),
},
async execute(args) {
const indexer = getIndexer();
const results = await indexer.search(args.query, args.limit ?? 10, {
fileType: args.fileType,
directory: args.directory,
chunkType: args.chunkType,
metadataOnly: true,
});
return formatCodebasePeek(results, args.query);
},
});
export const index_codebase: ToolDefinition = tool({
description:
"Index the codebase for semantic search. Creates vector embeddings of code chunks. Incremental - only re-indexes changed files (~50ms when nothing changed). Run before first codebase_search.",
args: {
force: z.boolean().optional().default(false).describe("Force reindex even if already indexed"),
estimateOnly: z.boolean().optional().default(false).describe("Only show cost estimate without indexing"),
verbose: z.boolean().optional().default(false).describe("Show detailed info about skipped files and parsing failures"),
},
async execute(args, context) {
const indexer = getIndexer();
// Guard: use noop if context is not provided
const safeContext = context || { metadata: () => {} };
if (args.estimateOnly) {
const estimate = await indexer.estimateCost();
return formatCostEstimate(estimate);
}
if (args.force) {
await indexer.clearIndex();
}
const stats = await indexer.index((progress) => {
safeContext.metadata({
title: formatProgressTitle(progress),
metadata: {
phase: progress.phase,
filesProcessed: progress.filesProcessed,
totalFiles: progress.totalFiles,
chunksProcessed: progress.chunksProcessed,
totalChunks: progress.totalChunks,
percentage: calculatePercentage(progress),
},
});
});
return formatIndexStats(stats, args.verbose ?? false);
},
});
export const index_status: ToolDefinition = tool({
description:
"Check the status of the codebase index. Shows whether the codebase is indexed, how many chunks are stored, and the embedding provider being used.",
args: {},
async execute() {
const indexer = getIndexer();
const status = await indexer.getStatus();
return formatStatus(status);
},
});
export const index_health_check: ToolDefinition = tool({
description:
"Check index health and remove stale entries from deleted files. Run this to clean up the index after files have been deleted.",
args: {},
async execute() {
const indexer = getIndexer();
const result = await indexer.healthCheck();
return formatHealthCheck(result);
},
});
export const index_metrics: ToolDefinition = tool({
description:
"Get metrics and performance statistics for the codebase index. Shows indexing stats, search timings, cache hit rates, and API usage. Requires debug.enabled=true and debug.metrics=true in config.",
args: {},
async execute() {
const indexer = getIndexer();
const logger = indexer.getLogger();
if (!logger.isEnabled()) {
return "Debug mode is disabled. Enable it in your config:\n\n```json\n{\n \"debug\": {\n \"enabled\": true,\n \"metrics\": true\n }\n}\n```";
}
if (!logger.isMetricsEnabled()) {
return "Metrics collection is disabled. Enable it in your config:\n\n```json\n{\n \"debug\": {\n \"enabled\": true,\n \"metrics\": true\n }\n}\n```";
}
return logger.formatMetrics();
},
});
export const index_logs: ToolDefinition = tool({
description:
"Get recent debug logs from the codebase indexer. Shows timestamped log entries with level and category. Requires debug.enabled=true in config.",
args: {
limit: z.number().optional().default(20).describe("Maximum number of log entries to return"),
category: z.enum(["search", "embedding", "cache", "gc", "branch", "general"]).optional().describe("Filter by log category"),
level: z.enum(["error", "warn", "info", "debug"]).optional().describe("Filter by minimum log level"),
},
async execute(args) {
const indexer = getIndexer();
const logger = indexer.getLogger();
if (!logger.isEnabled()) {
return "Debug mode is disabled. Enable it in your config:\n\n```json\n{\n \"debug\": {\n \"enabled\": true\n }\n}\n```";
}
let logs: LogEntry[];
if (args.category) {
logs = logger.getLogsByCategory(args.category, args.limit);
} else if (args.level) {
logs = logger.getLogsByLevel(args.level as LogLevel, args.limit);
} else {
logs = logger.getLogs(args.limit);
}
return formatLogs(logs);
},
});
export const find_similar: ToolDefinition = tool({
description:
"Find code similar to a given snippet. Use for duplicate detection, pattern discovery, or refactoring prep. Paste code and find semantically similar implementations elsewhere in the codebase.",
args: {
code: z.string().describe("The code snippet to find similar code for"),
limit: z.number().optional().default(10).describe("Maximum number of results to return"),
fileType: z.string().optional().describe("Filter by file extension (e.g., 'ts', 'py', 'rs')"),
directory: z.string().optional().describe("Filter by directory path (e.g., 'src/utils', 'lib')"),
chunkType: z.enum(["function", "class", "method", "interface", "type", "enum", "struct", "impl", "trait", "module", "other"]).optional().describe("Filter by code chunk type"),
excludeFile: z.string().optional().describe("Exclude results from this file path (useful when searching for duplicates of code from a specific file)"),
},
async execute(args) {
const indexer = getIndexer();
const results = await indexer.findSimilar(args.code, args.limit, {
fileType: args.fileType,
directory: args.directory,
chunkType: args.chunkType,
excludeFile: args.excludeFile,
});
if (results.length === 0) {
return "No similar code found. Try a different snippet or run index_codebase first.";
}
return `Found ${results.length} similar code blocks:\n\n${formatSearchResults(results)}`;
},
});
export const codebase_search: ToolDefinition = tool({
description:
"Search codebase by MEANING, not keywords. Returns full code content. Use when you need to see actual implementation. For just finding WHERE code is (saves ~90% tokens), use codebase_peek instead. For known identifiers like 'validateToken', use grep - it's faster.",
args: {
query: z.string().describe("Natural language description of what code you're looking for. Describe behavior, not syntax."),
limit: z.number().optional().default(5).describe("Maximum number of results to return"),
fileType: z.string().optional().describe("Filter by file extension (e.g., 'ts', 'py', 'rs')"),
directory: z.string().optional().describe("Filter by directory path (e.g., 'src/utils', 'lib')"),
chunkType: z.enum(["function", "class", "method", "interface", "type", "enum", "struct", "impl", "trait", "module", "other"]).optional().describe("Filter by code chunk type"),
contextLines: z.number().optional().describe("Number of extra lines to include before/after each match (default: 0)"),
},
async execute(args) {
const indexer = getIndexer();
const results = await indexer.search(args.query, args.limit ?? 5, {
fileType: args.fileType,
directory: args.directory,
chunkType: args.chunkType,
contextLines: args.contextLines,
});
if (results.length === 0) {
return "No matching code found. Try a different query or run index_codebase first.";
}
return `Found ${results.length} results for "${args.query}":\n\n${formatSearchResults(results, "score")}`;
},
});
export const call_graph: ToolDefinition = tool({
description:
"Query the call graph to find callers or callees of a function/method. Use to understand code flow and dependencies between functions.",
args: {
name: z.string().describe("Function or method name to query"),
direction: z.enum(["callers", "callees"]).default("callers").describe("Direction: 'callers' finds who calls this function, 'callees' finds what this function calls"),
symbolId: z.string().optional().describe("Symbol ID (required for 'callees' direction, returned by previous call_graph queries)"),
},
async execute(args) {
const indexer = getIndexer();
if (args.direction === "callees") {
if (!args.symbolId) {
return "Error: 'symbolId' is required when direction is 'callees'. First use direction='callers' to find the symbol ID.";
}
const callees = await indexer.getCallees(args.symbolId);
if (callees.length === 0) {
return `No callees found for symbol ${args.symbolId}. The function may not call any other tracked functions.`;
}
const formatted = callees.map((e, i) =>
`[${i + 1}] \u2192 ${e.targetName} (${e.callType}) at line ${e.line}${e.isResolved ? ` [resolved: ${e.toSymbolId}]` : " [unresolved]"}`
);
return `${args.name} calls ${callees.length} function(s):\n\n${formatted.join("\n")}`;
}
const callers = await indexer.getCallers(args.name);
if (callers.length === 0) {
return `No callers found for "${args.name}". It may not be called by any tracked function, or the index needs updating.`;
}
const formatted = callers.map((e, i) =>
`[${i + 1}] \u2190 from ${e.fromSymbolName ?? "<unknown>"} in ${e.fromSymbolFilePath ?? "<unknown file>"} [${e.fromSymbolId}] (${e.callType}) at line ${e.line}${e.isResolved ? " [resolved]" : " [unresolved]"}`
);
return `"${args.name}" is called by ${callers.length} function(s):\n\n${formatted.join("\n")}`;
},
});