@floydous/pi-agent-kernel 0.1.0 → 0.2.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.
@@ -0,0 +1,799 @@
1
+ import * as path from "node:path";
2
+ import * as fs from "node:fs";
3
+ import { type SymbolDef, type FileTags } from "./repomap";
4
+ import { kernelDebug } from "../safety/kernel_debug";
5
+
6
+ type WtsParser = any;
7
+ type WtsLanguage = any;
8
+
9
+ interface LanguageGrammarSpec {
10
+ wasmFile: string;
11
+ langKey: string;
12
+ }
13
+
14
+ const EXTENSION_TO_GRAMMAR: Record<string, LanguageGrammarSpec> = {
15
+ // TypeScript / TSX
16
+ ".ts": { wasmFile: "tree-sitter-typescript.wasm", langKey: "typescript" },
17
+ ".tsx": { wasmFile: "tree-sitter-tsx.wasm", langKey: "tsx" },
18
+ // JavaScript / JSX
19
+ ".js": { wasmFile: "tree-sitter-javascript.wasm", langKey: "javascript" },
20
+ ".jsx": { wasmFile: "tree-sitter-javascript.wasm", langKey: "javascript" },
21
+ ".mjs": { wasmFile: "tree-sitter-javascript.wasm", langKey: "javascript" },
22
+ ".cjs": { wasmFile: "tree-sitter-javascript.wasm", langKey: "javascript" },
23
+ // Python
24
+ ".py": { wasmFile: "tree-sitter-python.wasm", langKey: "python" },
25
+ // Rust
26
+ ".rs": { wasmFile: "tree-sitter-rust.wasm", langKey: "rust" },
27
+ // Go
28
+ ".go": { wasmFile: "tree-sitter-go.wasm", langKey: "go" },
29
+ // C / C++
30
+ ".c": { wasmFile: "tree-sitter-c.wasm", langKey: "c" },
31
+ ".h": { wasmFile: "tree-sitter-c.wasm", langKey: "c" },
32
+ ".cpp": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
33
+ ".hpp": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
34
+ ".cc": { wasmFile: "tree-sitter-cpp.wasm", langKey: "cpp" },
35
+ // Java
36
+ ".java": { wasmFile: "tree-sitter-java.wasm", langKey: "java" },
37
+ // C#
38
+ ".cs": { wasmFile: "tree-sitter-c_sharp.wasm", langKey: "c_sharp" },
39
+ // Bash / Shell
40
+ ".sh": { wasmFile: "tree-sitter-bash.wasm", langKey: "bash" },
41
+ ".bash": { wasmFile: "tree-sitter-bash.wasm", langKey: "bash" },
42
+ // Ruby
43
+ ".rb": { wasmFile: "tree-sitter-ruby.wasm", langKey: "ruby" },
44
+ // PHP
45
+ ".php": { wasmFile: "tree-sitter-php.wasm", langKey: "php" },
46
+ };
47
+
48
+ function getGrammarsDir(): string {
49
+ // Root of agent-kernel extension: ../../grammars relative to src/retrieval or dist/retrieval
50
+ const candidate1 = path.join(__dirname, "..", "..", "grammars");
51
+ if (fs.existsSync(candidate1)) return candidate1;
52
+ const candidate2 = path.join(process.cwd(), "grammars");
53
+ if (fs.existsSync(candidate2)) return candidate2;
54
+ return candidate1;
55
+ }
56
+
57
+ function resolveWasmPath(wasmFileName: string): string | null {
58
+ const grammarsDir = getGrammarsDir();
59
+ const target = path.join(grammarsDir, wasmFileName);
60
+ if (fs.existsSync(target)) return target;
61
+ return null;
62
+ }
63
+
64
+ export class TreeSitterEngine {
65
+ private static instance: TreeSitterEngine | null = null;
66
+ private initialized = false;
67
+ private initPromise: Promise<boolean> | null = null;
68
+ private parsers = new Map<string, WtsParser>();
69
+ private languages = new Map<string, WtsLanguage>();
70
+ private ParserClass: any = null;
71
+ private LanguageClass: any = null;
72
+
73
+ public static getInstance(): TreeSitterEngine {
74
+ if (!TreeSitterEngine.instance) {
75
+ TreeSitterEngine.instance = new TreeSitterEngine();
76
+ }
77
+ return TreeSitterEngine.instance;
78
+ }
79
+
80
+ public isSupported(filePath: string): boolean {
81
+ const ext = path.extname(filePath).toLowerCase();
82
+ return ext in EXTENSION_TO_GRAMMAR;
83
+ }
84
+
85
+ public getSupportedExtensions(): string[] {
86
+ return Object.keys(EXTENSION_TO_GRAMMAR);
87
+ }
88
+
89
+ public async init(): Promise<boolean> {
90
+ if (this.initialized) return true;
91
+ if (this.initPromise) return this.initPromise;
92
+
93
+ this.initPromise = (async () => {
94
+ try {
95
+ const wts = await import("web-tree-sitter");
96
+ this.ParserClass = (wts as any).Parser || (wts as any).default?.Parser || wts;
97
+ this.LanguageClass = (wts as any).Language || (wts as any).default?.Language;
98
+
99
+ let wtsDir = getGrammarsDir();
100
+ const localWtsWasm = path.join(wtsDir, "web-tree-sitter.wasm");
101
+ if (!fs.existsSync(localWtsWasm)) {
102
+ try {
103
+ const pkgPath = require.resolve("web-tree-sitter");
104
+ wtsDir = path.dirname(pkgPath);
105
+ } catch {
106
+ wtsDir = path.join(process.cwd(), "node_modules", "web-tree-sitter");
107
+ }
108
+ }
109
+
110
+ await this.ParserClass.init({
111
+ locateFile: (name: string) => path.join(wtsDir, name),
112
+ });
113
+
114
+ this.initialized = true;
115
+ return true;
116
+ } catch (e) {
117
+ kernelDebug(`TreeSitterEngine init failed: ${e}`);
118
+ this.initialized = false;
119
+ return false;
120
+ }
121
+ })();
122
+
123
+ return this.initPromise;
124
+ }
125
+
126
+ /**
127
+ * Preload grammars for specific file extensions or common workspace languages.
128
+ */
129
+ public async loadLanguages(extensions: string[]): Promise<void> {
130
+ await this.init();
131
+ if (!this.initialized || !this.ParserClass || !this.LanguageClass) return;
132
+
133
+ const pending: Promise<void>[] = [];
134
+ for (const ext of extensions) {
135
+ const spec = EXTENSION_TO_GRAMMAR[ext];
136
+ if (!spec) continue;
137
+
138
+ if (!this.languages.has(spec.langKey)) {
139
+ const wasmPath = resolveWasmPath(spec.wasmFile);
140
+ if (wasmPath && fs.existsSync(wasmPath)) {
141
+ pending.push(
142
+ this.LanguageClass.load(wasmPath)
143
+ .then((lang: any) => {
144
+ this.languages.set(spec.langKey, lang);
145
+ })
146
+ .catch((e: any) => {
147
+ kernelDebug(`Failed to load grammar for ${spec.langKey}: ${e}`);
148
+ }),
149
+ );
150
+ }
151
+ }
152
+ }
153
+
154
+ if (pending.length > 0) {
155
+ await Promise.all(pending);
156
+ }
157
+
158
+ for (const ext of extensions) {
159
+ const spec = EXTENSION_TO_GRAMMAR[ext];
160
+ if (!spec) continue;
161
+ const loadedLang = this.languages.get(spec.langKey);
162
+ if (loadedLang && !this.parsers.has(ext)) {
163
+ const parser = new this.ParserClass();
164
+ parser.setLanguage(loadedLang);
165
+ this.parsers.set(ext, parser);
166
+ }
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Synchronously get an initialized parser if language is already loaded,
172
+ * or initialize parser if the Language object exists.
173
+ */
174
+ public getParser(ext: string): WtsParser | null {
175
+ const existing = this.parsers.get(ext);
176
+ if (existing) return existing;
177
+
178
+ const spec = EXTENSION_TO_GRAMMAR[ext];
179
+ if (!spec || !this.ParserClass) return null;
180
+
181
+ const loadedLang = this.languages.get(spec.langKey);
182
+ if (loadedLang) {
183
+ const parser = new this.ParserClass();
184
+ parser.setLanguage(loadedLang);
185
+ this.parsers.set(ext, parser);
186
+ return parser;
187
+ }
188
+ return null;
189
+ }
190
+
191
+ public extractTags(filePath: string, content: string): FileTags | null {
192
+ const ext = path.extname(filePath).toLowerCase();
193
+ let parser = this.getParser(ext);
194
+ if (!parser) {
195
+ return null;
196
+ }
197
+
198
+ let tree: any = null;
199
+ try {
200
+ tree = parser.parse(content);
201
+ const root = tree.rootNode;
202
+ const hasSyntaxError = root.hasError;
203
+ const definitions: SymbolDef[] = [];
204
+ const references = new Set<string>();
205
+
206
+ function getCleanSignature(node: any): string {
207
+ const body = node.childForFieldName("body");
208
+ let headerText = "";
209
+ if (body) {
210
+ headerText = content.slice(node.startIndex, body.startIndex).trim();
211
+ } else {
212
+ headerText = node.text.split("\n")[0].trim();
213
+ }
214
+ return headerText.replace(/\s*\{$/, "").replace(/\s+/g, " ").trim();
215
+ }
216
+
217
+ function visit(node: any, inFunctionScope = false) {
218
+ const type = node.type;
219
+
220
+ // --- Python import_from_statement (Aliases) ---
221
+ if (type === "import_from_statement") {
222
+ const modNode = node.childForFieldName("module_name") || node.namedChildren.find((c: any) => c.type === "dotted_name" || c.type === "relative_import");
223
+ let modName = modNode ? modNode.text.replace(/^\.+/, "") : undefined;
224
+ function findAliases(n: any) {
225
+ if (n.type === "aliased_import") {
226
+ const orig = n.childForFieldName("name")?.text;
227
+ const alias = n.childForFieldName("alias")?.text;
228
+ if (orig && alias) {
229
+ definitions.push({
230
+ name: alias,
231
+ kind: "alias",
232
+ signature: `${alias} = ${orig}`,
233
+ line: n.startPosition.row + 1,
234
+ endLine: n.endPosition.row + 1,
235
+ aliasedFrom: {
236
+ module: modName,
237
+ originalName: orig,
238
+ },
239
+ });
240
+ }
241
+ return;
242
+ }
243
+ for (const c of n.namedChildren) findAliases(c);
244
+ }
245
+ findAliases(node);
246
+ return;
247
+ }
248
+
249
+ // Reject declarations inside function/method bodies (prevents local variables and closures from leaking into repo symbols)
250
+ if (inFunctionScope) {
251
+ return;
252
+ }
253
+
254
+ // --- TypeScript / JavaScript / TSX ---
255
+ if (type === "function_declaration") {
256
+ const nameNode = node.childForFieldName("name");
257
+ if (nameNode) {
258
+ definitions.push({
259
+ name: nameNode.text,
260
+ kind: "function",
261
+ signature: getCleanSignature(node).replace(/^export\s+/, ""),
262
+ line: node.startPosition.row + 1,
263
+ endLine: node.endPosition.row + 1,
264
+ });
265
+ }
266
+ // Stop traversal into function body
267
+ return;
268
+ } else if (type === "class_declaration" || type === "abstract_class_declaration") {
269
+ const nameNode = node.childForFieldName("name");
270
+ if (nameNode) {
271
+ definitions.push({
272
+ name: nameNode.text,
273
+ kind: "class",
274
+ signature: getCleanSignature(node).replace(/^export\s+/, ""),
275
+ line: node.startPosition.row + 1,
276
+ endLine: node.endPosition.row + 1,
277
+ });
278
+ }
279
+ // Traverse class members, but NOT function scope yet
280
+ const body = node.childForFieldName("body");
281
+ if (body) {
282
+ for (const member of body.namedChildren) {
283
+ visit(member, false);
284
+ }
285
+ }
286
+ return;
287
+ } else if (type === "ambient_declaration") {
288
+ // Unwrap ambient_declaration (e.g. declare function foo(), declare const X)
289
+ for (const child of node.namedChildren) {
290
+ visit(child, inFunctionScope);
291
+ }
292
+ return;
293
+ } else if (type === "function_signature") {
294
+ const nameNode = node.childForFieldName("name");
295
+ if (nameNode) {
296
+ definitions.push({
297
+ name: nameNode.text,
298
+ kind: "function",
299
+ signature: getCleanSignature(node).replace(/^export\s+/, "").replace(/^declare\s+/, ""),
300
+ line: node.startPosition.row + 1,
301
+ endLine: node.endPosition.row + 1,
302
+ });
303
+ }
304
+ return;
305
+ } else if (type === "interface_declaration") {
306
+ const nameNode = node.childForFieldName("name");
307
+ if (nameNode) {
308
+ definitions.push({
309
+ name: nameNode.text,
310
+ kind: "interface",
311
+ signature: getCleanSignature(node).replace(/^export\s+/, ""),
312
+ line: node.startPosition.row + 1,
313
+ endLine: node.endPosition.row + 1,
314
+ });
315
+ }
316
+ const body = node.childForFieldName("body");
317
+ if (body) {
318
+ for (const member of body.namedChildren) {
319
+ visit(member, false);
320
+ }
321
+ }
322
+ return;
323
+ } else if (type === "method_signature" || type === "abstract_method_signature") {
324
+ const nameNode = node.childForFieldName("name");
325
+ if (nameNode) {
326
+ definitions.push({
327
+ name: nameNode.text,
328
+ kind: "method",
329
+ signature: getCleanSignature(node),
330
+ line: node.startPosition.row + 1,
331
+ endLine: node.endPosition.row + 1,
332
+ });
333
+ }
334
+ return;
335
+ } else if (type === "type_alias_declaration") {
336
+ const nameNode = node.childForFieldName("name");
337
+ if (nameNode) {
338
+ definitions.push({
339
+ name: nameNode.text,
340
+ kind: "type",
341
+ signature: `type ${nameNode.text}`,
342
+ line: node.startPosition.row + 1,
343
+ endLine: node.endPosition.row + 1,
344
+ });
345
+ }
346
+ return;
347
+ } else if (type === "enum_declaration") {
348
+ const nameNode = node.childForFieldName("name");
349
+ if (nameNode) {
350
+ definitions.push({
351
+ name: nameNode.text,
352
+ kind: "enum",
353
+ signature: `enum ${nameNode.text}`,
354
+ line: node.startPosition.row + 1,
355
+ endLine: node.endPosition.row + 1,
356
+ });
357
+ }
358
+ return;
359
+ } else if (type === "method_definition") {
360
+ const nameNode = node.childForFieldName("name");
361
+ if (nameNode) {
362
+ definitions.push({
363
+ name: nameNode.text,
364
+ kind: "method",
365
+ signature: getCleanSignature(node),
366
+ line: node.startPosition.row + 1,
367
+ endLine: node.endPosition.row + 1,
368
+ });
369
+ }
370
+ // Method definition has been recorded; do not traverse inside method body
371
+ return;
372
+ } else if ((type === "lexical_declaration" || type === "variable_declaration") && (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx" || ext === ".mjs" || ext === ".cjs")) {
373
+ // Only top-level variable declarations (in program or export statement)
374
+ const isTopLevel = node.parent?.type === "program" || node.parent?.type === "export_statement";
375
+ if (isTopLevel) {
376
+ for (const child of node.namedChildren) {
377
+ if (child.type === "variable_declarator") {
378
+ const nameNode = child.childForFieldName("name");
379
+ const valueNode = child.childForFieldName("value");
380
+ if (nameNode) {
381
+ const isFn = valueNode && (valueNode.type === "arrow_function" || valueNode.type === "function");
382
+ const isAllUpper = /^[A-Z0-9_]{2,}$/.test(nameNode.text);
383
+ definitions.push({
384
+ name: nameNode.text,
385
+ kind: isFn ? "function" : isAllUpper ? "constant" : "variable",
386
+ signature: getCleanSignature(node).replace(/^export\s+/, ""),
387
+ line: node.startPosition.row + 1,
388
+ endLine: node.endPosition.row + 1,
389
+ });
390
+ }
391
+ }
392
+ }
393
+ }
394
+ return;
395
+ }
396
+
397
+ // --- Python ---
398
+ else if (type === "function_definition" && (ext === ".py")) {
399
+ const nameNode = node.childForFieldName("name");
400
+ if (nameNode) {
401
+ let isMethod = false;
402
+ let p = node.parent;
403
+ while (p) {
404
+ if (p.type === "class_definition") {
405
+ isMethod = true;
406
+ break;
407
+ }
408
+ p = p.parent;
409
+ }
410
+ definitions.push({
411
+ name: nameNode.text,
412
+ kind: isMethod ? "method" : "function",
413
+ signature: getCleanSignature(node),
414
+ line: node.startPosition.row + 1,
415
+ endLine: node.endPosition.row + 1,
416
+ });
417
+ }
418
+ return;
419
+ } else if (type === "decorated_definition" && (ext === ".py")) {
420
+ // Unwrap python decorator to find inner function or class definition
421
+ const defNode = node.childForFieldName("definition") || node.namedChildren.find((c: any) => c.type === "function_definition" || c.type === "class_definition");
422
+ if (defNode) {
423
+ visit(defNode, inFunctionScope);
424
+ }
425
+ return;
426
+ } else if (type === "class_definition" && (ext === ".py")) {
427
+ const nameNode = node.childForFieldName("name");
428
+ if (nameNode) {
429
+ definitions.push({
430
+ name: nameNode.text,
431
+ kind: "class",
432
+ signature: getCleanSignature(node),
433
+ line: node.startPosition.row + 1,
434
+ endLine: node.endPosition.row + 1,
435
+ });
436
+ }
437
+ const body = node.childForFieldName("body");
438
+ if (body) {
439
+ for (const member of body.namedChildren) {
440
+ visit(member, false);
441
+ }
442
+ }
443
+ return;
444
+ } else if (type === "expression_statement" && (ext === ".py")) {
445
+ // Expression statements in Python do not define repository symbols
446
+ return;
447
+ }
448
+
449
+ // --- Rust ---
450
+ else if (type === "function_item") {
451
+ const nameNode = node.childForFieldName("name");
452
+ if (nameNode) {
453
+ const isMethod = node.parent && node.parent.type === "declaration_list" && node.parent.parent && node.parent.parent.type === "impl_item";
454
+ definitions.push({
455
+ name: nameNode.text,
456
+ kind: isMethod ? "method" : "function",
457
+ signature: getCleanSignature(node),
458
+ line: node.startPosition.row + 1,
459
+ endLine: node.endPosition.row + 1,
460
+ });
461
+ }
462
+ return;
463
+ } else if (type === "struct_item" || type === "enum_item" || type === "trait_item") {
464
+ const nameNode = node.childForFieldName("name");
465
+ if (nameNode) {
466
+ definitions.push({
467
+ name: nameNode.text,
468
+ kind: type === "enum_item" ? "enum" : "class",
469
+ signature: getCleanSignature(node),
470
+ line: node.startPosition.row + 1,
471
+ endLine: node.endPosition.row + 1,
472
+ });
473
+ }
474
+ const body = node.childForFieldName("body") || node.namedChildren.find((c: any) => c.type === "declaration_list");
475
+ if (body) {
476
+ for (const member of body.namedChildren) {
477
+ if (member.type === "function_signature_item" || member.type === "function_item") {
478
+ const mName = member.childForFieldName("name");
479
+ if (mName) {
480
+ definitions.push({
481
+ name: mName.text,
482
+ kind: "method",
483
+ signature: getCleanSignature(member),
484
+ line: member.startPosition.row + 1,
485
+ endLine: member.endPosition.row + 1,
486
+ });
487
+ }
488
+ }
489
+ }
490
+ }
491
+ return;
492
+ } else if (type === "type_item") {
493
+ const nameNode = node.childForFieldName("name");
494
+ if (nameNode) {
495
+ definitions.push({
496
+ name: nameNode.text,
497
+ kind: "type",
498
+ signature: getCleanSignature(node),
499
+ line: node.startPosition.row + 1,
500
+ endLine: node.endPosition.row + 1,
501
+ });
502
+ }
503
+ return;
504
+ } else if (type === "const_item" || type === "static_item") {
505
+ const isTopLevel = node.parent?.type === "source_file";
506
+ if (isTopLevel) {
507
+ const nameNode = node.childForFieldName("name");
508
+ if (nameNode) {
509
+ definitions.push({
510
+ name: nameNode.text,
511
+ kind: type === "const_item" ? "constant" : "variable",
512
+ signature: getCleanSignature(node),
513
+ line: node.startPosition.row + 1,
514
+ endLine: node.endPosition.row + 1,
515
+ });
516
+ }
517
+ }
518
+ return;
519
+ }
520
+
521
+ // --- Go ---
522
+ else if (type === "function_declaration") {
523
+ const nameNode = node.childForFieldName("name");
524
+ if (nameNode) {
525
+ definitions.push({
526
+ name: nameNode.text,
527
+ kind: "function",
528
+ signature: getCleanSignature(node),
529
+ line: node.startPosition.row + 1,
530
+ endLine: node.endPosition.row + 1,
531
+ });
532
+ }
533
+ return;
534
+ } else if (type === "method_declaration") {
535
+ const nameNode = node.childForFieldName("name");
536
+ if (nameNode) {
537
+ definitions.push({
538
+ name: nameNode.text,
539
+ kind: "method",
540
+ signature: getCleanSignature(node),
541
+ line: node.startPosition.row + 1,
542
+ endLine: node.endPosition.row + 1,
543
+ });
544
+ }
545
+ return;
546
+ } else if (type === "type_declaration") {
547
+ for (const child of node.namedChildren) {
548
+ if (child.type === "type_spec") {
549
+ const nameNode = child.childForFieldName("name");
550
+ const typeNode = child.childForFieldName("type") || child.namedChildren.find((c: any) => c.type === "interface_type" || c.type === "struct_type");
551
+ const isInterface = typeNode && typeNode.type === "interface_type";
552
+ if (nameNode) {
553
+ definitions.push({
554
+ name: nameNode.text,
555
+ kind: isInterface ? "interface" : "class",
556
+ signature: getCleanSignature(child),
557
+ line: child.startPosition.row + 1,
558
+ endLine: child.endPosition.row + 1,
559
+ });
560
+ }
561
+ if (isInterface && typeNode) {
562
+ for (const elem of typeNode.namedChildren) {
563
+ if (elem.type === "method_elem") {
564
+ const mName = elem.childForFieldName("name");
565
+ if (mName) {
566
+ definitions.push({
567
+ name: mName.text,
568
+ kind: "method",
569
+ signature: getCleanSignature(elem),
570
+ line: elem.startPosition.row + 1,
571
+ endLine: elem.endPosition.row + 1,
572
+ });
573
+ }
574
+ }
575
+ }
576
+ }
577
+ }
578
+ }
579
+ return;
580
+ }
581
+
582
+ // --- C / C++ ---
583
+ else if (type === "function_definition" && (ext === ".c" || ext === ".cpp" || ext === ".h" || ext === ".hpp" || ext === ".cc")) {
584
+ let isMethod = false;
585
+ let p = node.parent;
586
+ while (p) {
587
+ if (p.type === "class_specifier" || p.type === "struct_specifier") {
588
+ isMethod = true;
589
+ break;
590
+ }
591
+ p = p.parent;
592
+ }
593
+ const declarator = node.childForFieldName("declarator");
594
+ let name = "";
595
+ if (declarator) {
596
+ if (declarator.type === "identifier" || declarator.type === "field_identifier") {
597
+ name = declarator.text;
598
+ } else {
599
+ const idNode = declarator.childForFieldName("declarator") || declarator.namedChildren.find((c: any) => c.type === "identifier" || c.type === "field_identifier");
600
+ if (idNode) {
601
+ name = idNode.text;
602
+ } else {
603
+ name = declarator.text.split("(")[0].trim();
604
+ }
605
+ }
606
+ }
607
+ if (name) {
608
+ definitions.push({
609
+ name: name.replace(/^[*&]+/, "").trim(),
610
+ kind: isMethod ? "method" : "function",
611
+ signature: getCleanSignature(node),
612
+ line: node.startPosition.row + 1,
613
+ endLine: node.endPosition.row + 1,
614
+ });
615
+ }
616
+ return;
617
+ } else if (type === "class_specifier" || type === "struct_specifier") {
618
+ const nameNode = node.childForFieldName("name");
619
+ if (nameNode) {
620
+ definitions.push({
621
+ name: nameNode.text,
622
+ kind: "class",
623
+ signature: getCleanSignature(node),
624
+ line: node.startPosition.row + 1,
625
+ endLine: node.endPosition.row + 1,
626
+ });
627
+ }
628
+ const body = node.childForFieldName("body");
629
+ if (body) {
630
+ for (const member of body.namedChildren) {
631
+ visit(member, false);
632
+ }
633
+ }
634
+ return;
635
+ }
636
+
637
+ // --- Java / C# ---
638
+ else if (type === "constructor_declaration" || type === "method_declaration") {
639
+ const nameNode = node.childForFieldName("name");
640
+ if (nameNode) {
641
+ definitions.push({
642
+ name: nameNode.text,
643
+ kind: "method",
644
+ signature: getCleanSignature(node),
645
+ line: node.startPosition.row + 1,
646
+ endLine: node.endPosition.row + 1,
647
+ });
648
+ }
649
+ return;
650
+ } else if (type === "enum_declaration" && (ext === ".cs" || ext === ".java")) {
651
+ const nameNode = node.childForFieldName("name");
652
+ if (nameNode) {
653
+ definitions.push({
654
+ name: nameNode.text,
655
+ kind: "enum",
656
+ signature: `enum ${nameNode.text}`,
657
+ line: node.startPosition.row + 1,
658
+ endLine: node.endPosition.row + 1,
659
+ });
660
+ }
661
+ return;
662
+ }
663
+
664
+ // --- Ruby ---
665
+ else if (type === "method" || type === "singleton_method") {
666
+ const nameNode = node.childForFieldName("name");
667
+ if (nameNode) {
668
+ let isMethod = false;
669
+ let p = node.parent;
670
+ while (p) {
671
+ if (p.type === "class" || p.type === "module") {
672
+ isMethod = true;
673
+ break;
674
+ }
675
+ p = p.parent;
676
+ }
677
+ definitions.push({
678
+ name: nameNode.text,
679
+ kind: isMethod ? "method" : "function",
680
+ signature: getCleanSignature(node),
681
+ line: node.startPosition.row + 1,
682
+ endLine: node.endPosition.row + 1,
683
+ });
684
+ }
685
+ return;
686
+ } else if ((type === "class" || type === "module") && ext === ".rb") {
687
+ const nameNode = node.childForFieldName("name");
688
+ if (nameNode) {
689
+ definitions.push({
690
+ name: nameNode.text,
691
+ kind: "class",
692
+ signature: getCleanSignature(node),
693
+ line: node.startPosition.row + 1,
694
+ endLine: node.endPosition.row + 1,
695
+ });
696
+ }
697
+ const body = node.childForFieldName("body");
698
+ if (body) {
699
+ for (const member of body.namedChildren) {
700
+ visit(member, false);
701
+ }
702
+ }
703
+ return;
704
+ }
705
+
706
+ // --- PHP ---
707
+ else if (type === "method_declaration") {
708
+ const nameNode = node.childForFieldName("name");
709
+ if (nameNode) {
710
+ definitions.push({
711
+ name: nameNode.text,
712
+ kind: "method",
713
+ signature: getCleanSignature(node),
714
+ line: node.startPosition.row + 1,
715
+ endLine: node.endPosition.row + 1,
716
+ });
717
+ }
718
+ return;
719
+ }
720
+
721
+ // --- Bash ---
722
+ else if (type === "function_definition" && (ext === ".sh" || ext === ".bash")) {
723
+ const nameNode = node.childForFieldName("name") || node.namedChildren.find((c: any) => c.type === "word");
724
+ if (nameNode) {
725
+ definitions.push({
726
+ name: nameNode.text,
727
+ kind: "function",
728
+ signature: getCleanSignature(node),
729
+ line: node.startPosition.row + 1,
730
+ endLine: node.endPosition.row + 1,
731
+ });
732
+ }
733
+ return;
734
+ }
735
+
736
+ // --- Imports / Exports Aliases (TS/JS) ---
737
+ else if (type === "export_statement" || type === "import_statement") {
738
+ const text = node.text;
739
+ if (text.includes(" as ")) {
740
+ const asMatch = text.match(/\b([a-zA-Z0-9_]+)\s+as\s+([a-zA-Z0-9_]+)\b/);
741
+ if (asMatch) {
742
+ const modMatch = text.match(/from\s*['"]([^'"]+)['"]/);
743
+ definitions.push({
744
+ name: asMatch[2],
745
+ kind: "alias",
746
+ signature: text.split("\n")[0].trim(),
747
+ line: node.startPosition.row + 1,
748
+ endLine: node.endPosition.row + 1,
749
+ aliasedFrom: {
750
+ module: modMatch ? modMatch[1] : undefined,
751
+ originalName: asMatch[1],
752
+ },
753
+ });
754
+ }
755
+ }
756
+ }
757
+
758
+ for (const child of node.namedChildren) {
759
+ visit(child, false);
760
+ }
761
+ }
762
+
763
+ visit(root, false);
764
+
765
+ // Extract clean AST identifiers for PageRank graph (skips comments, docstrings, and strings)
766
+ function collectAstReferences(n: any) {
767
+ const t = n.type;
768
+ if (t === "identifier" || t === "property_identifier" || t === "type_identifier" || t === "field_identifier" || t === "word") {
769
+ const text = n.text;
770
+ if (text && text.length >= 3 && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(text)) {
771
+ references.add(text);
772
+ }
773
+ }
774
+ for (const child of n.namedChildren) {
775
+ collectAstReferences(child);
776
+ }
777
+ }
778
+ collectAstReferences(root);
779
+
780
+ return {
781
+ filePath,
782
+ definitions,
783
+ references,
784
+ hasSyntaxError: hasSyntaxError || undefined,
785
+ };
786
+ } catch (e) {
787
+ kernelDebug(`TreeSitterEngine extractTags error on ${filePath}: ${e}`);
788
+ return null;
789
+ } finally {
790
+ if (tree) {
791
+ try {
792
+ tree.delete();
793
+ } catch {
794
+ // ignore deletion error
795
+ }
796
+ }
797
+ }
798
+ }
799
+ }