@floydous/pi-agent-kernel 0.4.2 → 0.5.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 (59) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +1 -7
  2. package/CHANGELOG.md +48 -0
  3. package/README.md +6 -53
  4. package/config.example.toml +0 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +10 -9
  8. package/docs/editing-and-verification.md +1 -3
  9. package/docs/retrieval.md +6 -11
  10. package/docs/testing.md +3 -3
  11. package/package.json +4 -2
  12. package/src/config/agent_kernel_command.ts +8 -39
  13. package/src/config/kernel_config.ts +30 -68
  14. package/src/config/toml.ts +6 -1
  15. package/src/editing/auto_heal.ts +1 -1
  16. package/src/editing/patch.ts +27 -16
  17. package/src/editing/post_edit_verification.ts +12 -10
  18. package/src/editing/smart_anchor.ts +7 -5
  19. package/src/editing/syntax-verify.ts +117 -15
  20. package/src/index.ts +15 -257
  21. package/src/retrieval/search_bm25.ts +4 -2
  22. package/src/retrieval/search_chunker.ts +1 -1
  23. package/src/retrieval/search_config.ts +4 -6
  24. package/src/retrieval/search_embedder.ts +3 -2
  25. package/src/retrieval/search_index.ts +82 -35
  26. package/src/retrieval/search_modal.ts +7 -8
  27. package/src/retrieval/{repomap.ts → tag_extractor.ts} +5 -292
  28. package/src/retrieval/tree_sitter_engine.ts +70 -34
  29. package/src/retrieval/workspace_walker.ts +6 -2
  30. package/src/safety/atomic_write.ts +1 -1
  31. package/src/safety/epistemic_guard.ts +122 -32
  32. package/src/safety/output_clamper.ts +57 -35
  33. package/src/tools/code_search_output.ts +2 -1
  34. package/src/tools/code_search_tool.ts +2 -5
  35. package/src/tools/context.ts +0 -14
  36. package/src/tools/edit_tool.ts +82 -115
  37. package/src/tools/read_tool.ts +42 -178
  38. package/src/ui/footer.ts +7 -7
  39. package/docs/lsp.md +0 -31
  40. package/src/lsp/adapters/base.ts +0 -42
  41. package/src/lsp/adapters/index.ts +0 -21
  42. package/src/lsp/adapters/python.ts +0 -37
  43. package/src/lsp/adapters/rust.ts +0 -35
  44. package/src/lsp/adapters/typescript.ts +0 -40
  45. package/src/lsp/index.ts +0 -13
  46. package/src/lsp/lsp_client.ts +0 -765
  47. package/src/lsp/lsp_detector.ts +0 -52
  48. package/src/lsp/lsp_formatter.ts +0 -323
  49. package/src/lsp/lsp_installer.ts +0 -320
  50. package/src/lsp/lsp_manager.ts +0 -202
  51. package/src/lsp/lsp_modal.ts +0 -675
  52. package/src/lsp/lsp_registry.ts +0 -600
  53. package/src/lsp/lsp_types.ts +0 -143
  54. package/src/retrieval/ast_search.ts +0 -999
  55. package/src/retrieval/symbol_reader.ts +0 -228
  56. package/src/tools/ast_search_formatter.ts +0 -161
  57. package/src/tools/ast_search_tool.ts +0 -146
  58. package/src/tools/lsp_tool.ts +0 -794
  59. package/src/tools/repo_map_tool.ts +0 -56
@@ -1,999 +0,0 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import { extractFileTags } from "./repomap";
4
- import { kernelDebug } from "../safety/kernel_debug";
5
- import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS } from "./workspace_walker";
6
-
7
- export interface AstQueryResult {
8
- filePath: string;
9
- name: string;
10
- kind: string;
11
- signature: string;
12
- line: number;
13
- endLine?: number;
14
- codeBlock?: string;
15
- /** Inclusive line where the bounded preview ends, when a preview is present. */
16
- visibleEndLine?: number;
17
- bodyTruncated?: boolean;
18
- aliasedFrom?: {
19
- module?: string;
20
- originalName: string;
21
- };
22
- }
23
-
24
- export interface SymbolReference {
25
- filePath: string;
26
- line: number;
27
- column: number;
28
- lineText: string;
29
- }
30
-
31
- /** Escape regex metacharacters in user-supplied symbol names before RegExp interpolation. */
32
- function escapeRegExp(input: string): string {
33
- return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
34
- }
35
-
36
- const RESERVED_KEYWORDS = new Set([
37
- "import",
38
- "from",
39
- "as",
40
- "export",
41
- "default",
42
- "return",
43
- "const",
44
- "let",
45
- "var",
46
- "function",
47
- "async",
48
- "await",
49
- "class",
50
- "interface",
51
- "type",
52
- "def",
53
- "self",
54
- "cls",
55
- "if",
56
- "else",
57
- "elif",
58
- "for",
59
- "while",
60
- "try",
61
- "except",
62
- "catch",
63
- "finally",
64
- "with",
65
- "pub",
66
- "fn",
67
- "struct",
68
- "enum",
69
- "trait",
70
- "impl",
71
- "use",
72
- "mod",
73
- "crate",
74
- "super",
75
- "mut",
76
- "ref",
77
- "static",
78
- "func",
79
- "package",
80
- ]);
81
-
82
- const SUPPORTED_EXTENSIONS = new Set([
83
- ".ts",
84
- ".tsx",
85
- ".js",
86
- ".jsx",
87
- ".mjs",
88
- ".cjs",
89
- ".py",
90
- ".rs",
91
- ".go",
92
- ".c",
93
- ".cpp",
94
- ".cc",
95
- ".h",
96
- ".hpp",
97
- ".zig",
98
- ".rb",
99
- ".java",
100
- ".cs",
101
- ".sh",
102
- ".bash",
103
- ".kt",
104
- ".php",
105
- ".lua",
106
- ]);
107
-
108
- const IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
109
-
110
- /**
111
- * Extract top-level symbols from a single file using fast AST tagging
112
- */
113
- export function extractDocumentSymbols(filePath: string): AstQueryResult[] {
114
- try {
115
- if (!fs.existsSync(filePath)) return [];
116
- const content = fs.readFileSync(filePath, "utf-8");
117
- const tags = extractFileTags(filePath, content);
118
- const relPath = filePath.replace(/\\/g, "/");
119
-
120
- return tags.definitions.map((def) => ({
121
- filePath: relPath,
122
- name: def.name,
123
- kind: def.kind,
124
- signature: def.signature,
125
- line: def.line,
126
- aliasedFrom: def.aliasedFrom,
127
- }));
128
- } catch {
129
- return [];
130
- }
131
- }
132
-
133
- // Helper to check if a character index is inside a comment or string literal
134
- function isInsideCommentOrString(line: string, index: number): boolean {
135
- let inSingleQuote = false;
136
- let inDoubleQuote = false;
137
- let inBacktick = false;
138
-
139
- for (let i = 0; i < line.length; i++) {
140
- const ch = line[i];
141
- const nextCh = line[i + 1];
142
-
143
- if (i === index) {
144
- if (inSingleQuote || inDoubleQuote || inBacktick) return true;
145
- }
146
-
147
- if (ch === "\\" && (inSingleQuote || inDoubleQuote || inBacktick)) {
148
- i++; // skip escaped char
149
- continue;
150
- }
151
-
152
- if (!inSingleQuote && !inDoubleQuote && !inBacktick) {
153
- if (ch === "/" && nextCh === "/") {
154
- return index >= i;
155
- }
156
- if (ch === "#") {
157
- return index >= i;
158
- }
159
- if (ch === "-" && nextCh === "-") {
160
- return index >= i;
161
- }
162
- }
163
-
164
- if (ch === "'" && !inDoubleQuote && !inBacktick)
165
- inSingleQuote = !inSingleQuote;
166
- else if (ch === '"' && !inSingleQuote && !inBacktick)
167
- inDoubleQuote = !inDoubleQuote;
168
- else if (ch === "`" && !inSingleQuote && !inDoubleQuote)
169
- inBacktick = !inBacktick;
170
- }
171
-
172
- return false;
173
- }
174
-
175
- /**
176
- * Find word-boundary symbol references across the workspace
177
- */
178
- export function findSymbolReferences(
179
- rootDir: string,
180
- symbolName: string,
181
- maxResults = 40,
182
- ): SymbolReference[] {
183
- const results: SymbolReference[] = [];
184
- if (!symbolName || !symbolName.trim()) return results;
185
-
186
- // Strip potential module prefixes if passed
187
- const cleanSym = symbolName.includes("::")
188
- ? symbolName.split("::").pop()!.trim()
189
- : symbolName.includes(".")
190
- ? symbolName.split(".").pop()!.trim()
191
- : symbolName.trim();
192
- if (!cleanSym || RESERVED_KEYWORDS.has(cleanSym.toLowerCase())) return results;
193
-
194
- const escaped = cleanSym.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
195
- const regex = new RegExp(`\\b${escaped}\\b`, "g");
196
-
197
- walkWorkspaceFiles({
198
- rootDir,
199
- extensions: SUPPORTED_EXTENSIONS,
200
- includeGithub: false,
201
- onFile: (fullPath) => {
202
- if (results.length >= maxResults) return false;
203
- try {
204
- const content = fs.readFileSync(fullPath, "utf-8");
205
- const lines = content.split("\n");
206
- let inBlockComment = false;
207
-
208
- for (let i = 0; i < lines.length; i++) {
209
- if (results.length >= maxResults) return false;
210
- const lineText = lines[i];
211
- const trimmed = lineText.trim();
212
-
213
- // Block comment handling (/* ... */)
214
- if (inBlockComment) {
215
- if (trimmed.includes("*/")) {
216
- inBlockComment = false;
217
- }
218
- continue;
219
- }
220
- if (trimmed.startsWith("/*")) {
221
- if (!trimmed.includes("*/")) {
222
- inBlockComment = true;
223
- }
224
- continue;
225
- }
226
-
227
- // Skip lines starting with comment markers
228
- if (
229
- trimmed.startsWith("//") ||
230
- trimmed.startsWith("///") ||
231
- trimmed.startsWith("//!") ||
232
- trimmed.startsWith("#") ||
233
- trimmed.startsWith("*") ||
234
- trimmed.startsWith("--")
235
- ) {
236
- continue;
237
- }
238
-
239
- let match;
240
- regex.lastIndex = 0;
241
- while ((match = regex.exec(lineText)) !== null) {
242
- // Filter out matches inside inline comments or string literals
243
- if (isInsideCommentOrString(lineText, match.index)) {
244
- continue;
245
- }
246
-
247
- results.push({
248
- filePath:
249
- path.relative(rootDir, fullPath).replace(/\\/g, "/") || fullPath,
250
- line: i + 1,
251
- column: match.index + 1,
252
- lineText: lineText.trim(),
253
- });
254
- if (results.length >= maxResults) return false;
255
- }
256
- }
257
- } catch (e) {
258
- kernelDebug(e);
259
- }
260
- return results.length < maxResults;
261
- },
262
- });
263
-
264
- return results;
265
- }
266
-
267
- /**
268
- * Extract hover information for local variable, parameter, import alias, or local assignment in scope
269
- */
270
- export function extractLocalSymbolHover(
271
- filePath: string,
272
- line0: number,
273
- _col0: number,
274
- symName: string,
275
- ): string | null {
276
- try {
277
- if (!fs.existsSync(filePath)) return null;
278
- if (!symName || RESERVED_KEYWORDS.has(symName.toLowerCase())) {
279
- return null;
280
- }
281
-
282
- const content = fs.readFileSync(filePath, "utf-8");
283
- const lines = content.split("\n");
284
- const currentLine = lines[line0] || "";
285
-
286
- // 1. If current line is an import statement containing symName:
287
- if (
288
- currentLine.includes("import") ||
289
- currentLine.includes("from ") ||
290
- currentLine.includes("export ") ||
291
- currentLine.includes("use ")
292
- ) {
293
- // Check for alias: `from ... import orig as symName` or `import ... as symName` or `use ... as symName`
294
- const aliasRegex = new RegExp(
295
- `\\b([a-zA-Z0-9_]+)\\s+as\\s+${escapeRegExp(symName)}\\b`,
296
- );
297
- const aliasMatch = currentLine.match(aliasRegex);
298
- if (aliasMatch) {
299
- const modMatch =
300
- currentLine.match(/from\s+([.\w]+)/) ||
301
- currentLine.match(/from\s+['"]([^'"]+)['"]/) ||
302
- currentLine.match(/use\s+([^;]+)/);
303
- const mod = modMatch ? modMatch[1] : "module";
304
- return `(import alias) ${symName} → ${aliasMatch[1]}\nImported from ${mod} in ${path.basename(filePath)}:${line0 + 1}:\n${currentLine.trim()}`;
305
- }
306
-
307
- // Check for direct import: `from mod import ..., symName, ...` or `use crate::...::symName;`
308
- const directImportRegex = new RegExp(`\\b${escapeRegExp(symName)}\\b`);
309
- if (directImportRegex.test(currentLine)) {
310
- const modMatch =
311
- currentLine.match(/from\s+([.\w]+)/) ||
312
- currentLine.match(/from\s+['"]([^'"]+)['"]/) ||
313
- currentLine.match(/use\s+([^;]+)/);
314
- const mod = modMatch ? modMatch[1] : "module";
315
- return `(imported symbol) ${symName}\nImported from ${mod} in ${path.basename(filePath)}:${line0 + 1}:\n${currentLine.trim()}`;
316
- }
317
- }
318
-
319
- // 2. First scan upwards for enclosing function header to check if symName is a parameter
320
- const startScan = Math.max(0, line0 - 80);
321
- for (let i = line0; i >= startScan; i--) {
322
- const line = lines[i] || "";
323
- const trimmed = line.trim();
324
-
325
- if (
326
- trimmed.startsWith("import ") ||
327
- trimmed.startsWith("from ") ||
328
- trimmed.startsWith("export {") ||
329
- trimmed.startsWith("use ")
330
- ) {
331
- continue;
332
- }
333
-
334
- const isFnHeader =
335
- trimmed.startsWith("def ") ||
336
- trimmed.startsWith("async def ") ||
337
- trimmed.startsWith("function ") ||
338
- trimmed.startsWith("async function ") ||
339
- trimmed.includes("function ") ||
340
- trimmed.startsWith("pub fn ") ||
341
- trimmed.startsWith("pub async fn ") ||
342
- trimmed.startsWith("fn ") ||
343
- trimmed.startsWith("async fn ") ||
344
- trimmed.startsWith("func ") ||
345
- trimmed.includes("=>") ||
346
- /^(?:export\s+)?(?:public\s+|private\s+|protected\s+)?(?:async\s+)?(?:def|function|[a-zA-Z0-9_]+\s*\()/.test(
347
- trimmed,
348
- ) ||
349
- /^(?:export\s+)?const\s+[a-zA-Z0-9_]+\s*=\s*(?:async\s*)?\(/.test(trimmed);
350
-
351
- if (isFnHeader) {
352
- // Collect the entire parameter block between ( and )
353
- let parenDepth = 0;
354
- let seenOpen = false;
355
- let paramBlock = "";
356
-
357
- for (let j = i; j < Math.min(lines.length, i + 25); j++) {
358
- const l = lines[j];
359
- for (let c = 0; c < l.length; c++) {
360
- const ch = l[c];
361
- if (ch === "(") {
362
- parenDepth++;
363
- seenOpen = true;
364
- if (parenDepth === 1) continue;
365
- } else if (ch === ")") {
366
- parenDepth--;
367
- if (seenOpen && parenDepth === 0) break;
368
- }
369
- if (seenOpen && parenDepth > 0) {
370
- paramBlock += ch;
371
- }
372
- }
373
- if (seenOpen && parenDepth === 0) break;
374
- paramBlock += " ";
375
- }
376
-
377
- if (seenOpen && paramBlock) {
378
- const cleanParams = paramBlock.replace(/\s+/g, " ");
379
- const paramRegex = new RegExp(
380
- `\\b${escapeRegExp(symName)}\\b(?:\\s*:\\s*([^,)=]+))?(?:\\s*=\\s*([^,)]+))?`,
381
- );
382
- const m = cleanParams.match(paramRegex);
383
- if (m) {
384
- const typeAnnot = m[1] ? `: ${m[1].trim()}` : "";
385
- const defVal = m[2] ? ` = ${m[2].trim()}` : "";
386
- return `(parameter) ${symName}${typeAnnot}${defVal}\nDefined in ${path.basename(filePath)}:${i + 1}`;
387
- }
388
- }
389
- }
390
- }
391
-
392
- // 3. Scan upwards for local variable declarations (Rust let/static/const, Go :=/var, TS/JS const/let/var, Python)
393
- for (let i = line0; i >= startScan; i--) {
394
- const line = lines[i] || "";
395
- const trimmed = line.trim();
396
-
397
- if (
398
- trimmed.startsWith("import ") ||
399
- trimmed.startsWith("from ") ||
400
- trimmed.startsWith("def ") ||
401
- trimmed.startsWith("class ") ||
402
- trimmed.startsWith("use ")
403
- ) {
404
- continue;
405
- }
406
-
407
- // Don't treat parameter lines ending with comma as local variable statements
408
- if (trimmed.endsWith(",")) {
409
- continue;
410
- }
411
-
412
- // Rust: `let [mut] [ref] symName[: Type] [= value];`
413
- const rsLetMatch = line.match(
414
- new RegExp(
415
- `^\\s*let\\s+(?:mut\\s+|ref\\s+mut\\s+|ref\\s+)?${escapeRegExp(symName)}\\b(?:\\s*:\\s*([^=;]+))?(?:\\s*=\\s*([^;\\n]+))?`,
416
- ),
417
- );
418
- if (rsLetMatch) {
419
- const typeAnnot = rsLetMatch[1] ? `: ${rsLetMatch[1].trim()}` : "";
420
- const valPreview = rsLetMatch[2]
421
- ? ` = ${rsLetMatch[2].trim().slice(0, 60)}`
422
- : "";
423
- return `(local variable) ${symName}${typeAnnot}${valPreview}\nDeclared in ${path.basename(filePath)}:${i + 1}`;
424
- }
425
-
426
- // Rust/C++: `[pub] static [mut] symName: Type = value;` or `[pub] const symName: Type = value;`
427
- const rsStaticMatch = line.match(
428
- new RegExp(
429
- `^\\s*(?:pub\\s+)?(static|const)\\s+(?:mut\\s+)?${escapeRegExp(symName)}\\b(?:\\s*:\\s*([^=;]+))?(?:\\s*=\\s*([^;\\n]+))?`,
430
- ),
431
- );
432
- if (rsStaticMatch) {
433
- const kindLabel =
434
- rsStaticMatch[1] === "static" ? "static variable" : "constant";
435
- const typeAnnot = rsStaticMatch[2] ? `: ${rsStaticMatch[2].trim()}` : "";
436
- const valPreview = rsStaticMatch[3]
437
- ? ` = ${rsStaticMatch[3].trim().slice(0, 60)}`
438
- : "";
439
- return `(${kindLabel}) ${symName}${typeAnnot}${valPreview}\nDeclared in ${path.basename(filePath)}:${i + 1}`;
440
- }
441
-
442
- // Go: `symName := value` or `var symName [Type] [= value]`
443
- const goShortMatch = line.match(
444
- new RegExp(`^\\s*${escapeRegExp(symName)}\\s*:=\\s*([^;\\n]+)`),
445
- );
446
- if (goShortMatch) {
447
- return `(local variable) ${symName} := ${goShortMatch[1].trim().slice(0, 60)}\nDeclared in ${path.basename(filePath)}:${i + 1}`;
448
- }
449
- const goVarMatch = line.match(
450
- new RegExp(
451
- `^\\s*var\\s+${escapeRegExp(symName)}\\b(?:\\s+([^=;]+))?(?:\\s*=\\s*([^;\\n]+))?`,
452
- ),
453
- );
454
- if (goVarMatch) {
455
- const typeAnnot = goVarMatch[1] ? ` ${goVarMatch[1].trim()}` : "";
456
- const valPreview = goVarMatch[2]
457
- ? ` = ${goVarMatch[2].trim().slice(0, 60)}`
458
- : "";
459
- return `(variable) ${symName}${typeAnnot}${valPreview}\nDeclared in ${path.basename(filePath)}:${i + 1}`;
460
- }
461
-
462
- // TS/JS: `(const|let|var|this.) symName[: Type] = value;`
463
- const assignRegex = new RegExp(
464
- `^\\s*(?:const|let|var|self\\.|this\\.)\\s*${escapeRegExp(symName)}\\b(?:\\s*:\\s*([^=]+))?\\s*=\\s*([^;\\n]+)`,
465
- );
466
- const assignMatch = line.match(assignRegex);
467
- if (assignMatch) {
468
- const typeAnnot = assignMatch[1] ? `: ${assignMatch[1].trim()}` : "";
469
- const valPreview = assignMatch[2]
470
- ? ` = ${assignMatch[2].trim().slice(0, 60)}`
471
- : "";
472
- return `(local variable) ${symName}${typeAnnot}${valPreview}\nDeclared in ${path.basename(filePath)}:${i + 1}`;
473
- }
474
-
475
- // Python dynamic variable assignment (e.g. `symName = ...` or `self.symName = ...`)
476
- const pyAssignRegex = new RegExp(
477
- `^\\s*${escapeRegExp(symName)}\\b(?:\\s*:\\s*([^=]+))?\\s*=\\s*([^;\\n]+)`,
478
- );
479
- const pyAssignMatch = line.match(pyAssignRegex);
480
- if (pyAssignMatch && !trimmed.endsWith(",")) {
481
- const typeAnnot = pyAssignMatch[1] ? `: ${pyAssignMatch[1].trim()}` : "";
482
- const valPreview = pyAssignMatch[2]
483
- ? ` = ${pyAssignMatch[2].trim().slice(0, 60)}`
484
- : "";
485
- return `(local variable) ${symName}${typeAnnot}${valPreview}\nDeclared in ${path.basename(filePath)}:${i + 1}`;
486
- }
487
- }
488
-
489
- // 4. Check if symName is declared directly in this file's document symbols (top priority for local file hover)
490
- const localDocSyms = extractDocumentSymbols(filePath);
491
- const exactLocal = localDocSyms.find(
492
- (s) => s.name === symName || s.name.toLowerCase() === symName.toLowerCase(),
493
- );
494
- if (exactLocal) {
495
- return `[${exactLocal.kind}] ${exactLocal.name}\n${exactLocal.signature}\nDeclared in ${path.basename(filePath)}:${exactLocal.line}`;
496
- }
497
-
498
- // 5. Scan file-level import statements
499
- for (let i = 0; i < Math.min(lines.length, 120); i++) {
500
- const line = lines[i].trim();
501
- if (
502
- line.startsWith("import ") ||
503
- line.startsWith("from ") ||
504
- line.startsWith("export ") ||
505
- line.startsWith("use ")
506
- ) {
507
- const aliasRegex = new RegExp(
508
- `\\b([a-zA-Z0-9_]+)\\s+as\\s+${escapeRegExp(symName)}\\b`,
509
- );
510
- const m = line.match(aliasRegex);
511
- if (m) {
512
- return `(import alias) ${symName} → ${m[1]}\nImport statement in ${path.basename(filePath)}:${i + 1}:\n${line}`;
513
- }
514
- }
515
- }
516
- } catch (e) {
517
- kernelDebug(e);
518
- }
519
- return null;
520
- }
521
-
522
- /**
523
- * Multi-tier ranking function to sort AST symbols:
524
- * 1. Current File Bonus (local declarations in current active file always rank first)
525
- * 2. Match Precision (Exact > Case-Insensitive > Word-Boundary > StartsWith > Test-Match > Substring)
526
- * 3. Source Code vs Tests/Benchmarks/Examples (Production files heavily favored)
527
- * 4. Module Hint Matching (for dotted / qualified lookups e.g. webshocket.WebSocketClient, state::KeyUsage)
528
- * 5. Symbol Kind (Class/Struct/Enum > Interface/Trait > Function > Method > Alias > Variable)
529
- * 6. Path Depth
530
- */
531
- export function computeSymbolRankScore(
532
- symbol: AstQueryResult,
533
- queryName?: string,
534
- currentFilePath?: string,
535
- ): number {
536
- if (!queryName) return 0;
537
-
538
- // Handle dotted / colon-qualified query expressions (e.g. "crate::state::KeyUsage" or "webshocket.WebSocketClient")
539
- const cleanQuery = queryName.replace(/::/g, ".");
540
- const parts = cleanQuery.split(".");
541
- const leafQuery = parts[parts.length - 1];
542
- const moduleHint =
543
- parts.length > 1 ? parts.slice(0, -1).join("/").toLowerCase() : "";
544
-
545
- const sName = symbol.name.toLowerCase();
546
- const qName = leafQuery.toLowerCase();
547
- const fPath = symbol.filePath.toLowerCase().replace(/\\/g, "/");
548
-
549
- // Tier 0: Current File Priority Boost (-200 bonus ensures active file always wins)
550
- let localFileBonus = 0;
551
- if (currentFilePath) {
552
- const normCurrent = currentFilePath.replace(/\\/g, "/").toLowerCase();
553
- if (
554
- normCurrent.endsWith(fPath) ||
555
- fPath.endsWith(normCurrent) ||
556
- normCurrent === fPath
557
- ) {
558
- localFileBonus = -200;
559
- }
560
- }
561
-
562
- // Tier 1: Match precision
563
- let matchScore = 50;
564
- if (symbol.name === leafQuery) {
565
- matchScore = 0; // Exact case match
566
- } else if (sName === qName) {
567
- matchScore = 5; // Exact case-insensitive match
568
- } else if (
569
- new RegExp(`\\b${qName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i").test(
570
- symbol.name,
571
- )
572
- ) {
573
- matchScore = 15; // Word boundary match
574
- } else if (sName.startsWith(qName)) {
575
- matchScore = 25; // Prefix match
576
- } else if (
577
- sName.startsWith("test_") ||
578
- sName.endsWith("_test") ||
579
- sName.startsWith("test")
580
- ) {
581
- matchScore = 80; // Test function match
582
- } else {
583
- matchScore = 50; // Generic substring match
584
- }
585
-
586
- // Tier 2: Source Code vs Tests / Benchmarks / Examples
587
- let locationPenalty = 0;
588
- const isTestPath =
589
- fPath.includes("/test/") ||
590
- fPath.includes("/tests/") ||
591
- fPath.includes("/__tests__/") ||
592
- fPath.includes("/spec/") ||
593
- fPath.includes("/specs/") ||
594
- fPath.startsWith("test/") ||
595
- fPath.startsWith("tests/") ||
596
- fPath.startsWith("spec/") ||
597
- fPath.includes("test_") ||
598
- fPath.includes("_test.") ||
599
- fPath.includes(".test.") ||
600
- fPath.includes(".spec.");
601
-
602
- const isBenchmarkOrExample =
603
- fPath.includes("/benchmarks/") ||
604
- fPath.includes("/benchmark/") ||
605
- fPath.includes("/examples/") ||
606
- fPath.includes("/example/") ||
607
- fPath.includes("/samples/") ||
608
- fPath.includes("/fixtures/") ||
609
- fPath.startsWith("benchmarks/") ||
610
- fPath.startsWith("examples/") ||
611
- fPath.startsWith("samples/");
612
-
613
- if (isTestPath) {
614
- locationPenalty = 150; // Strong penalty for test files
615
- } else if (isBenchmarkOrExample) {
616
- locationPenalty = 60; // Moderate penalty for examples/benchmarks
617
- } else if (
618
- fPath.startsWith("src/") ||
619
- fPath.startsWith("lib/") ||
620
- fPath.startsWith("app/") ||
621
- fPath.startsWith("core/") ||
622
- fPath.startsWith("pkg/") ||
623
- fPath.includes("/src/") ||
624
- fPath.includes("/lib/") ||
625
- fPath.includes("/app/")
626
- ) {
627
- locationPenalty = 0; // Production source code gets highest priority
628
- } else {
629
- locationPenalty = 10; // Root source files
630
- }
631
-
632
- // Tier 3: Module hint match bonus
633
- let moduleBonus = 0;
634
- if (moduleHint && fPath.includes(moduleHint)) {
635
- moduleBonus = -30; // Boost for matching module path
636
- }
637
-
638
- // Tier 4: Symbol Kind Weight
639
- let kindScore = 5;
640
- switch (symbol.kind.toLowerCase()) {
641
- case "class":
642
- case "struct":
643
- case "enum":
644
- kindScore = 0;
645
- break;
646
- case "interface":
647
- case "trait":
648
- case "type":
649
- kindScore = 1;
650
- break;
651
- case "function":
652
- kindScore = 2;
653
- break;
654
- case "method":
655
- kindScore = 3;
656
- break;
657
- case "alias":
658
- kindScore = 4;
659
- break;
660
- case "variable":
661
- case "constant":
662
- kindScore = 5;
663
- break;
664
- default:
665
- kindScore = 6;
666
- }
667
-
668
- // Tier 5: Path depth (shallower files preferred)
669
- const pathDepth = (fPath.match(/\//g) || []).length * 0.1;
670
-
671
- return (
672
- localFileBonus +
673
- matchScore +
674
- locationPenalty +
675
- moduleBonus +
676
- kindScore * 0.1 +
677
- pathDepth
678
- );
679
- }
680
-
681
- function findSymbolEndLine(lines: string[], startIdx: number, ext: string): number {
682
- if (ext === ".py") {
683
- const baseIndent = lines[startIdx].match(/^(\s*)/)?.[1].length || 0;
684
- let end = startIdx;
685
- for (let i = startIdx + 1; i < lines.length; i++) {
686
- if (lines[i].trim() && (lines[i].match(/^(\s*)/)?.[1].length || 0) <= baseIndent) break;
687
- end = i;
688
- }
689
- return end + 1;
690
- }
691
- let depth = 0;
692
- let opened = false;
693
- for (let i = startIdx; i < lines.length; i++) {
694
- for (const ch of lines[i]) {
695
- if (ch === "{") { depth++; opened = true; }
696
- else if (ch === "}") depth--;
697
- }
698
- if (opened && depth <= 0) return i + 1;
699
- }
700
- return startIdx + 1;
701
- }
702
-
703
- export function searchAstSymbols(
704
- rootDir: string,
705
- query: {
706
- name?: string;
707
- kind?: string;
708
- filePattern?: string;
709
- includeBody?: boolean;
710
- exactMatch?: boolean;
711
- currentFilePath?: string;
712
- },
713
- ): AstQueryResult[] {
714
- const rawResults: AstQueryResult[] = [];
715
- const allDefsByFile = new Map<string, AstQueryResult[]>();
716
-
717
- // If query.name contains dots or colons (e.g. "crate::state::KeyUsage" or "webshocket.WebSocketClient"), extract leaf
718
- const cleanQueryName = query.name ? query.name.replace(/::/g, ".") : undefined;
719
- const queryLeaf =
720
- cleanQueryName && cleanQueryName.includes(".")
721
- ? cleanQueryName.split(".").pop()!
722
- : cleanQueryName;
723
- const includeBody = query.includeBody ?? false;
724
-
725
- walkWorkspaceFiles({
726
- rootDir,
727
- extensions: SUPPORTED_EXTENSIONS,
728
- includeGithub: false,
729
- onFile: (fullPath) => {
730
- const relPath = path.relative(rootDir, fullPath).replace(/\\/g, "/");
731
- if (
732
- query.filePattern &&
733
- !relPath
734
- .toLowerCase()
735
- .includes(query.filePattern.replace(/\\/g, "/").toLowerCase())
736
- ) {
737
- return;
738
- }
739
- const ext = path.extname(fullPath).toLowerCase();
740
- if (!SUPPORTED_EXTENSIONS.has(ext)) {
741
- return;
742
- }
743
- try {
744
- const content = fs.readFileSync(fullPath, "utf-8");
745
- const tags = extractFileTags(fullPath, content);
746
- const lines = content.split("\n");
747
- const fileDefs: AstQueryResult[] = [];
748
-
749
- for (const def of tags.definitions) {
750
- let codeBlock: string | undefined;
751
- let bodyTruncated = false;
752
- let visibleEndLine: number | undefined;
753
- if (includeBody) {
754
- const start = Math.max(0, def.line - 1);
755
- const end = Math.min(lines.length, start + 25);
756
- codeBlock = lines.slice(start, end).join("\n");
757
- visibleEndLine = end;
758
- bodyTruncated = end < lines.length;
759
- }
760
-
761
- const item: AstQueryResult = {
762
- filePath: relPath,
763
- name: def.name,
764
- kind: def.kind,
765
- signature: def.signature,
766
- line: def.line,
767
- endLine: def.endLine && def.endLine >= def.line ? def.endLine : findSymbolEndLine(lines, def.line - 1, ext),
768
- codeBlock,
769
- visibleEndLine,
770
- bodyTruncated: includeBody ? bodyTruncated : undefined,
771
- aliasedFrom: def.aliasedFrom,
772
- };
773
-
774
- fileDefs.push(item);
775
-
776
- if (query.kind) {
777
- const qKind = query.kind.toLowerCase();
778
- const dKind = def.kind.toLowerCase();
779
- const matchKind =
780
- qKind === dKind ||
781
- (qKind === "struct" && dKind === "class") ||
782
- (qKind === "trait" && dKind === "class") ||
783
- (qKind === "constant" && (dKind === "constant" || dKind === "variable")) ||
784
- (qKind === "variable" && (dKind === "variable" || dKind === "constant"));
785
- if (!matchKind) continue;
786
- }
787
-
788
- if (queryLeaf) {
789
- const qName = queryLeaf.toLowerCase();
790
- const dName = def.name.toLowerCase();
791
- if (query.exactMatch) {
792
- if (dName !== qName) continue;
793
- } else if (!dName.includes(qName)) continue;
794
- }
795
-
796
- rawResults.push(item);
797
- }
798
-
799
- allDefsByFile.set(relPath, fileDefs);
800
- } catch {
801
- // skip unreadable
802
- }
803
- },
804
- });
805
-
806
- // Resolve aliased re-exports (e.g. `WebSocketClient` -> `client` in `.websocket`)
807
- const resolvedResults: AstQueryResult[] = [...rawResults];
808
-
809
- for (const hit of rawResults) {
810
- if (hit.kind === "alias" && hit.aliasedFrom) {
811
- const origName = hit.aliasedFrom.originalName;
812
- let foundOrig: AstQueryResult | null = null;
813
-
814
- // Check all parsed files for exact definition of `origName`
815
- for (const [fPath, defs] of allDefsByFile.entries()) {
816
- if (hit.aliasedFrom.module) {
817
- const cleanMod = hit.aliasedFrom.module
818
- .replace(/^\.+/, "")
819
- .replace(/::/g, "/")
820
- .replace(/\//g, ".");
821
- if (cleanMod && fPath.toLowerCase().includes(cleanMod.toLowerCase())) {
822
- const match = defs.find(
823
- (d) =>
824
- (d.name.toLowerCase() === origName.toLowerCase() ||
825
- d.name === origName) &&
826
- d.kind !== "alias",
827
- );
828
- if (match) {
829
- foundOrig = match;
830
- break;
831
- }
832
- }
833
- }
834
- }
835
-
836
- // Fallback: search across any file if not found by module hint
837
- if (!foundOrig) {
838
- for (const defs of allDefsByFile.values()) {
839
- const match = defs.find(
840
- (d) =>
841
- (d.name.toLowerCase() === origName.toLowerCase() ||
842
- d.name === origName) &&
843
- d.kind !== "alias",
844
- );
845
- if (match) {
846
- foundOrig = match;
847
- break;
848
- }
849
- }
850
- }
851
-
852
- if (foundOrig) {
853
- resolvedResults.push({
854
- filePath: foundOrig.filePath,
855
- name: hit.name,
856
- kind: foundOrig.kind,
857
- signature: foundOrig.signature,
858
- line: foundOrig.line,
859
- endLine: foundOrig.endLine,
860
- codeBlock: foundOrig.codeBlock,
861
- visibleEndLine: foundOrig.visibleEndLine,
862
- bodyTruncated: foundOrig.bodyTruncated,
863
- aliasedFrom: {
864
- module: `${hit.filePath}:${hit.line}`,
865
- originalName: origName,
866
- },
867
- });
868
- }
869
- }
870
- }
871
-
872
- // Sort results with multi-tier ranking
873
- resolvedResults.sort((a, b) => {
874
- const scoreA = computeSymbolRankScore(a, query.name, query.currentFilePath);
875
- const scoreB = computeSymbolRankScore(b, query.name, query.currentFilePath);
876
- return scoreA - scoreB;
877
- });
878
-
879
- // Deduplicate by filePath + line + name
880
- const seen = new Set<string>();
881
- const deduped: AstQueryResult[] = [];
882
- for (const item of resolvedResults) {
883
- const key = `${item.filePath}:${item.line}:${item.name}:${item.kind}`;
884
- if (!seen.has(key)) {
885
- seen.add(key);
886
- deduped.push(item);
887
- }
888
- }
889
-
890
- return deduped;
891
- }
892
-
893
- export function levenshteinDistance(a: string, b: string): number {
894
- if (a === b) return 0;
895
- if (!a.length) return b.length;
896
- if (!b.length) return a.length;
897
- const row = Array.from({ length: b.length + 1 }, (_, i) => i);
898
- for (let i = 1; i <= a.length; i++) {
899
- let prev = row[0];
900
- row[0] = i;
901
- for (let j = 1; j <= b.length; j++) {
902
- const next = row[j];
903
- row[j] = Math.min(
904
- row[j] + 1,
905
- row[j - 1] + 1,
906
- prev + (a[i - 1] === b[j - 1] ? 0 : 1),
907
- );
908
- prev = next;
909
- }
910
- }
911
- return row[b.length];
912
- }
913
-
914
- export interface SymbolSuggestion {
915
- name: string;
916
- filePath: string;
917
- line: number;
918
- kind: string;
919
- signature: string;
920
- }
921
-
922
- export function findSymbolSuggestions(
923
- cwd: string,
924
- targetFilePath: string,
925
- query: string,
926
- maxCandidates = 3,
927
- ): SymbolSuggestion[] {
928
- if (!query || !query.trim()) return [];
929
- const qTrim = query.trim();
930
- const qLower = qTrim.toLowerCase();
931
- const relTarget = path.relative(cwd, targetFilePath).replace(/\\/g, "/");
932
-
933
- // 1. Search AST symbols across workspace matching query substring
934
- let hits = searchAstSymbols(cwd, { name: qTrim, exactMatch: false });
935
-
936
- // 2. If no hits, search symbols in the target file specifically (handles substitutions/transpositions)
937
- if (hits.length === 0) {
938
- hits = searchAstSymbols(cwd, { filePattern: relTarget || targetFilePath, exactMatch: false });
939
- }
940
-
941
- if (hits.length === 0) return [];
942
-
943
- const maxDistance =
944
- qLower.length <= 3 ? 1 : qLower.length <= 6 ? 2 : Math.max(3, Math.floor(qLower.length * 0.35));
945
-
946
- const scored = hits
947
- .filter((h) => {
948
- const nameLower = h.name.toLowerCase();
949
- if (nameLower === qLower) return true;
950
- if (nameLower.includes(qLower) || qLower.includes(nameLower)) return true;
951
- const dist = levenshteinDistance(qLower, nameLower);
952
- return dist <= maxDistance;
953
- })
954
- .map((h) => {
955
- const nameLower = h.name.toLowerCase();
956
- const dist = levenshteinDistance(qLower, nameLower);
957
- const normHitPath = h.filePath.replace(/\\/g, "/");
958
- const isWindows = process.platform === "win32";
959
- const r1 = path.resolve(cwd, normHitPath);
960
- const r2 = path.resolve(cwd, targetFilePath);
961
- const isSameFile =
962
- normHitPath === relTarget ||
963
- (isWindows ? r1.toLowerCase() === r2.toLowerCase() : r1 === r2);
964
- const exactCaseSub = h.name.includes(qTrim);
965
- return {
966
- hit: h,
967
- dist,
968
- isSameFile,
969
- exactCaseSub,
970
- lengthDiff: Math.abs(h.name.length - qTrim.length),
971
- };
972
- })
973
- .sort((a, b) => {
974
- if (a.isSameFile !== b.isSameFile) return a.isSameFile ? -1 : 1;
975
- if (a.dist !== b.dist) return a.dist - b.dist;
976
- if (a.exactCaseSub !== b.exactCaseSub) return a.exactCaseSub ? -1 : 1;
977
- if (a.lengthDiff !== b.lengthDiff) return a.lengthDiff - b.lengthDiff;
978
- return a.hit.line - b.hit.line;
979
- });
980
-
981
- const seen = new Set<string>();
982
- const results: SymbolSuggestion[] = [];
983
- for (const item of scored) {
984
- const normPath = item.hit.filePath.replace(/\\/g, "/");
985
- const key = `${normPath}:${item.hit.name}`;
986
- if (seen.has(key)) continue;
987
- seen.add(key);
988
- results.push({
989
- name: item.hit.name,
990
- filePath: normPath,
991
- line: item.hit.line,
992
- kind: item.hit.kind,
993
- signature: item.hit.signature,
994
- });
995
- if (results.length >= maxCandidates) break;
996
- }
997
-
998
- return results;
999
- }