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