@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,5 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ import { TreeSitterEngine } from "./tree_sitter_engine";
3
4
 
4
5
  export interface SymbolDef {
5
6
  name: string;
@@ -15,6 +16,7 @@ export interface SymbolDef {
15
16
  | "alias";
16
17
  signature: string;
17
18
  line: number;
19
+ endLine?: number;
18
20
  aliasedFrom?: {
19
21
  module?: string;
20
22
  originalName: string;
@@ -25,6 +27,7 @@ export interface FileTags {
25
27
  filePath: string;
26
28
  definitions: SymbolDef[];
27
29
  references: Set<string>;
30
+ hasSyntaxError?: boolean;
28
31
  }
29
32
 
30
33
  const IGNORED_DIRS = new Set([
@@ -182,10 +185,19 @@ function extractBalancedSig(
182
185
 
183
186
  // Fast AST & Signature tag extractor with multi-line support
184
187
  export function extractFileTags(filePath: string, content: string): FileTags {
188
+ const tsEngine = TreeSitterEngine.getInstance();
189
+ if (tsEngine.isSupported(filePath)) {
190
+ const treeTags = tsEngine.extractTags(filePath, content);
191
+ if (treeTags) {
192
+ return treeTags;
193
+ }
194
+ }
195
+
185
196
  const ext = path.extname(filePath).toLowerCase();
186
197
  const lines = content.split("\n");
187
198
  const definitions: SymbolDef[] = [];
188
199
  const references = new Set<string>();
200
+ let braceDepth = 0;
189
201
 
190
202
  // Extract identifier references (words matching [a-zA-Z_][a-zA-Z0-9_]*)
191
203
  const idRegex = /\b([a-zA-Z_][a-zA-Z0-9_]{2,})\b/g;
@@ -286,11 +298,45 @@ export function extractFileTags(filePath: string, content: string): FileTags {
286
298
  }
287
299
  }
288
300
 
289
- // const variable / constant declaration: const FOO = ... or const FOO: string = ...
301
+ // Class methods and accessors are the important cold-state fallback case.
302
+ // Tree-sitter normally supplies these nested declarations; keep the
303
+ // synchronous fallback useful before a grammar has been loaded.
304
+ const tsJsGenericMethod = line.match(
305
+ /^(?:(?:public|private|protected|static|abstract|override|readonly|async)\s+)*(?:[A-Za-z_$][\w$]*(?:<[^{};]*>)?\s+)*([A-Za-z_$][\w$]*)\s*<[^{};]*>\s*\([^{}]*\)\s*(?::\s*[^{};]+)?\s*\{/,
306
+ );
307
+ const tsJsMethod = tsJsGenericMethod || line.match(
308
+ /^(?:(?:public|private|protected|static|abstract|override|readonly|async)\s+)*(?:[A-Za-z_$][\w$]*(?:<[^>]*>)?(?:\[\])?\??\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\([^)]*\)\s*(?::\s*[^={;]+)?(?:\{|;)/,
309
+ );
310
+ const controlOrExpression = /^(?:if|for|while|switch|catch|return|throw|await|new|super|this|const|let|var)\b/;
311
+ const indentation = rawLine.match(/^\s*/)?.[0].length ?? 0;
312
+ if (tsJsMethod && indentation > 0 && indentation <= 4 && !controlOrExpression.test(line)) {
313
+ definitions.push({
314
+ name: tsJsMethod[1],
315
+ kind: "method",
316
+ signature: line.split("{")[0].trim().replace(/;$/, ""),
317
+ line: i + 1,
318
+ });
319
+ continue;
320
+ }
321
+
322
+ const tsJsAccessor = line.match(
323
+ /^(?:(?:public|private|protected|static|abstract|override|readonly|async)\s+)*(?:get|set)\s+([A-Za-z_$][\w$]*)\s*(?:\([^)]*\))?\s*(?::\s*[^={;]+)?\s*(?:\{|;)/,
324
+ );
325
+ if (tsJsAccessor && indentation > 0 && indentation <= 4) {
326
+ definitions.push({
327
+ name: tsJsAccessor[1],
328
+ kind: "method",
329
+ signature: line.split("{")[0].trim().replace(/;$/, ""),
330
+ line: i + 1,
331
+ });
332
+ continue;
333
+ }
334
+
335
+ // const variable / constant declaration: const FOO = ... or const FOO: string = ... (only top-level declarations)
290
336
  const constDecl = line.match(
291
337
  /^(?:export\s+)?const\s+([a-zA-Z0-9_]+)(?:\s*:\s*([^=]+))?\s*=/,
292
338
  );
293
- if (constDecl) {
339
+ if (constDecl && braceDepth === 0 && rawLine === rawLine.trimStart()) {
294
340
  const isAllUpper = /^[A-Z0-9_]{2,}$/.test(constDecl[1]);
295
341
  definitions.push({
296
342
  name: constDecl[1],
@@ -532,27 +578,28 @@ export function extractFileTags(filePath: string, content: string): FileTags {
532
578
 
533
579
  // Go
534
580
  if (ext === ".go") {
535
- const goFn = line.match(/^func\s+(?:\([^)]+\)\s+)?([a-zA-Z0-9_]+)/);
581
+ const goFn = line.match(/^func\s+(\([^)]+\)\s+)?([a-zA-Z0-9_]+)/);
536
582
  if (goFn) {
537
583
  const sig =
538
584
  extractBalancedSig(lines, i, "go_fn") || line.split("{")[0].trim();
539
585
  definitions.push({
540
- name: goFn[1],
541
- kind: "function",
586
+ name: goFn[2],
587
+ kind: goFn[1] ? "method" : "function",
542
588
  signature: sig,
543
589
  line: i + 1,
544
590
  });
545
591
  continue;
546
592
  }
547
593
 
548
- const goType = line.match(/^type\s+([a-zA-Z0-9_]+)\s+(struct|interface)/);
594
+ const goType = line.match(/^type\s+([a-zA-Z0-9_]+)\s+(.+)/);
549
595
  if (goType) {
596
+ const typeBody = goType[2].trim();
550
597
  const sig =
551
598
  extractBalancedSig(lines, i, "go_type") ||
552
- `type ${goType[1]} ${goType[2]}`;
599
+ line.replace(/\s*\{\s*$/, "").trim();
553
600
  definitions.push({
554
601
  name: goType[1],
555
- kind: "class",
602
+ kind: typeBody.startsWith("interface") ? "interface" : "class",
556
603
  signature: sig,
557
604
  line: i + 1,
558
605
  });
@@ -572,6 +619,161 @@ export function extractFileTags(filePath: string, content: string): FileTags {
572
619
  continue;
573
620
  }
574
621
  }
622
+
623
+ // Java / C# / C++ fallback regex scanner when TreeSitter is cold
624
+ if (ext === ".java" || ext === ".cs") {
625
+ // Methods may be expression-bodied (`... FindById(...) => ...`) and
626
+ // therefore have no opening brace for the balanced-signature helper.
627
+ const expressionMethod = line.match(
628
+ /^(?:public|private|protected|internal|static|final|synchronized|async|virtual|override|sealed|readonly|new|partial|unsafe|extern|\s)+\s+([A-Za-z0-9_<>,.?\[\]\s]+?)\s+([A-Za-z0-9_]+)\s*\(([^)]*)\)\s*=>/,
629
+ );
630
+ if (expressionMethod) {
631
+ definitions.push({
632
+ name: expressionMethod[2],
633
+ kind: "method",
634
+ signature: line.split("=>")[0].trim(),
635
+ line: i + 1,
636
+ });
637
+ continue;
638
+ }
639
+
640
+ // Class / interface / enum
641
+ const jClass = line.match(
642
+ /^(?:public|private|protected|internal|abstract|static|final|\s)*\s*(class|interface|enum)\s+([a-zA-Z0-9_]+)/,
643
+ );
644
+ if (jClass) {
645
+ definitions.push({
646
+ name: jClass[2],
647
+ kind: jClass[1] === "interface" ? "interface" : jClass[1] === "enum" ? "enum" : "class",
648
+ signature: line.split("{")[0].trim(),
649
+ line: i + 1,
650
+ });
651
+ continue;
652
+ }
653
+
654
+ // Method (requires return type and parentheses)
655
+ const jMethod = line.match(
656
+ /^(?:public|private|protected|internal|static|final|synchronized|async|virtual|override|\s)+\s+([a-zA-Z0-9_<>\[\],\s]+)\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)/,
657
+ );
658
+ if (jMethod && !jMethod[1].includes("class") && !jMethod[1].includes("return")) {
659
+ definitions.push({
660
+ name: jMethod[2],
661
+ kind: "method",
662
+ signature: line.split("{")[0].trim(),
663
+ line: i + 1,
664
+ });
665
+ continue;
666
+ }
667
+ }
668
+
669
+ // C / C++
670
+ if (ext === ".c" || ext === ".cpp" || ext === ".cc" || ext === ".h" || ext === ".hpp") {
671
+ const cExpressionFn = line.match(
672
+ /^(?:[A-Za-z_][A-Za-z0-9_:<>*&\s]+?)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)\s*\{/,
673
+ );
674
+ if (cExpressionFn && !cExpressionFn[1].match(/^(if|for|while|switch|return)$/)) {
675
+ definitions.push({
676
+ name: cExpressionFn[1],
677
+ kind: rawLine !== rawLine.trimStart() ? "method" : "function",
678
+ signature: line.split("{")[0].trim(),
679
+ line: i + 1,
680
+ });
681
+ continue;
682
+ }
683
+
684
+ const cClass = line.match(/^(?:class|struct)\s+([a-zA-Z0-9_]+)/);
685
+ if (cClass) {
686
+ definitions.push({
687
+ name: cClass[1],
688
+ kind: "class",
689
+ signature: line.split("{")[0].trim(),
690
+ line: i + 1,
691
+ });
692
+ continue;
693
+ }
694
+
695
+ const cFn = line.match(
696
+ /^(?:[a-zA-Z0-9_&*]+\s+)+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*(?:const)?\s*[{;]?$/,
697
+ );
698
+ if (cFn && !cFn[1].match(/^(if|for|while|switch|return)$/)) {
699
+ definitions.push({
700
+ name: cFn[1],
701
+ kind: rawLine !== rawLine.trimStart() ? "method" : "function",
702
+ signature: line.split("{")[0].trim(),
703
+ line: i + 1,
704
+ });
705
+ continue;
706
+ }
707
+ }
708
+
709
+ // Ruby
710
+ if (ext === ".rb") {
711
+ const rbClass = line.match(/^(?:class|module)\s+([a-zA-Z0-9_:]+)/);
712
+ if (rbClass) {
713
+ definitions.push({
714
+ name: rbClass[1],
715
+ kind: "class",
716
+ signature: line.trim(),
717
+ line: i + 1,
718
+ });
719
+ continue;
720
+ }
721
+
722
+ const rbMethod = line.match(/^\s*def\s+([a-zA-Z0-9_!?=.]+)/);
723
+ if (rbMethod) {
724
+ definitions.push({
725
+ name: rbMethod[1],
726
+ kind: "method",
727
+ signature: line.trim(),
728
+ line: i + 1,
729
+ });
730
+ continue;
731
+ }
732
+ }
733
+
734
+ // PHP
735
+ if (ext === ".php") {
736
+ const phpClass = line.match(/^(?:abstract\s+|final\s+)?(class|interface|trait)\s+([a-zA-Z0-9_]+)/);
737
+ if (phpClass) {
738
+ definitions.push({
739
+ name: phpClass[2],
740
+ kind: phpClass[1] === "interface" ? "interface" : "class",
741
+ signature: line.split("{")[0].trim(),
742
+ line: i + 1,
743
+ });
744
+ continue;
745
+ }
746
+
747
+ const phpFn = line.match(/^(?:public|private|protected|static|\s)*function\s+([a-zA-Z0-9_]+)\s*\(/);
748
+ if (phpFn) {
749
+ definitions.push({
750
+ name: phpFn[1],
751
+ kind: braceDepth > 0 ? "method" : "function",
752
+ signature: line.split("{")[0].trim(),
753
+ line: i + 1,
754
+ });
755
+ continue;
756
+ }
757
+ }
758
+
759
+ // Bash / Shell
760
+ if (ext === ".sh" || ext === ".bash") {
761
+ const shFn = line.match(/^(?:function\s+)?([a-zA-Z0-9_]+)\s*\(\)\s*\{?/);
762
+ if (shFn) {
763
+ definitions.push({
764
+ name: shFn[1],
765
+ kind: "function",
766
+ signature: `${shFn[1]}()`,
767
+ line: i + 1,
768
+ });
769
+ continue;
770
+ }
771
+ }
772
+
773
+ for (const ch of line) {
774
+ if (ch === "{") braceDepth++;
775
+ else if (ch === "}") braceDepth = Math.max(0, braceDepth - 1);
776
+ }
575
777
  }
576
778
 
577
779
  return {
@@ -655,6 +857,16 @@ export function computeRepoMap(rootDir: string, tokenBudget = 1024): string {
655
857
  return "(No supported source files found in repository)";
656
858
  }
657
859
 
860
+ // Ensure languages present in sourceFiles are loaded in TreeSitterEngine
861
+ const detectedExts = new Set<string>();
862
+ for (const f of sourceFiles) {
863
+ const ext = path.extname(f).toLowerCase();
864
+ if (ext) detectedExts.add(ext);
865
+ }
866
+ // Note: loadLanguages is async, but if called from an async context it is pre-warmed.
867
+ // We also trigger loadLanguages asynchronously if not loaded.
868
+ void TreeSitterEngine.getInstance().loadLanguages(Array.from(detectedExts));
869
+
658
870
  const fileTagsMap = new Map<string, FileTags>();
659
871
  const defToFile = new Map<string, Set<string>>();
660
872
 
@@ -1,190 +1,190 @@
1
- import { CodeChunk } from "./search_chunker";
2
-
3
- export interface BM25SearchResult {
4
- chunkId: string;
5
- score: number;
6
- matches: string[];
7
- }
8
-
9
- /**
10
- * Specialized code tokenizer handling CamelCase, snake_case, identifiers and symbols.
11
- */
12
- export function tokenizeCode(text: string): string[] {
13
- if (!text) return [];
14
-
15
- const rawTokens = text.match(/[a-zA-Z0-9_]+/g) || [];
16
- const tokens: string[] = [];
17
-
18
- for (const raw of rawTokens) {
19
- const lower = raw.toLowerCase();
20
- if (lower.length >= 2) {
21
- tokens.push(lower);
22
- }
23
-
24
- // Split snake_case
25
- if (raw.includes("_")) {
26
- const parts = raw.split("_");
27
- for (const p of parts) {
28
- const pl = p.toLowerCase();
29
- if (pl.length >= 2) tokens.push(pl);
30
- }
31
- }
32
-
33
- // Split camelCase and PascalCase (e.g. "verifySignature" -> "verify", "signature")
34
- const camelParts = raw.replace(/([a-z])([A-Z])/g, "$1 $2").split(" ");
35
- if (camelParts.length > 1) {
36
- for (const cp of camelParts) {
37
- const cpl = cp.toLowerCase();
38
- if (cpl.length >= 2) tokens.push(cpl);
39
- }
40
- }
41
- }
42
-
43
- return tokens;
44
- }
45
-
46
- export class BM25Engine {
47
- private k1 = 1.2;
48
- private b = 0.75;
49
-
50
- // chunkId -> term frequency map: term -> count
51
- private docTermFreqs: Map<string, Map<string, number>> = new Map();
52
- // chunkId -> total token count in document
53
- private docLengths: Map<string, number> = new Map();
54
- // term -> document frequency (number of docs containing term)
55
- private termDocFreqs: Map<string, number> = new Map();
56
- // term -> Set of chunkIds (Inverted index for O(Σ matches) query scanning)
57
- private postings: Map<string, Set<string>> = new Map();
58
-
59
- private totalDocs = 0;
60
- private avgDocLength = 0;
61
-
62
- public clear(): void {
63
- this.docTermFreqs.clear();
64
- this.docLengths.clear();
65
- this.termDocFreqs.clear();
66
- this.postings.clear();
67
- this.totalDocs = 0;
68
- this.avgDocLength = 0;
69
- }
70
-
71
- /**
72
- * Index a list of CodeChunks into the BM25 inverted index.
73
- */
74
- public indexChunks(chunks: CodeChunk[]): void {
75
- for (const chunk of chunks) {
76
- this.addChunk(chunk);
77
- }
78
- this.recalculateStats();
79
- }
80
-
81
- public addChunk(chunk: CodeChunk): void {
82
- // Combine breadcrumb, signature and content with extra weight for signature/name
83
- const weightedText = `${chunk.symbolName} ${chunk.symbolName} ${chunk.signature} ${chunk.breadcrumb}\n${chunk.content}`;
84
- const tokens = tokenizeCode(weightedText);
85
-
86
- const tfMap = new Map<string, number>();
87
- for (const t of tokens) {
88
- tfMap.set(t, (tfMap.get(t) || 0) + 1);
89
- }
90
-
91
- this.docTermFreqs.set(chunk.id, tfMap);
92
- this.docLengths.set(chunk.id, tokens.length);
93
-
94
- for (const term of tfMap.keys()) {
95
- this.termDocFreqs.set(term, (this.termDocFreqs.get(term) || 0) + 1);
96
- let chunkSet = this.postings.get(term);
97
- if (!chunkSet) {
98
- chunkSet = new Set();
99
- this.postings.set(term, chunkSet);
100
- }
101
- chunkSet.add(chunk.id);
102
- }
103
-
104
- this.totalDocs++;
105
- }
106
-
107
- /**
108
- * Remove all chunks associated with a specific relative file path.
109
- */
110
- public removeFile(filePath: string): void {
111
- const prefix = `${filePath}:`;
112
- for (const chunkId of Array.from(this.docTermFreqs.keys())) {
113
- if (chunkId.startsWith(prefix) || chunkId.includes(filePath)) {
114
- const tfMap = this.docTermFreqs.get(chunkId);
115
- if (tfMap) {
116
- for (const term of tfMap.keys()) {
117
- const count = (this.termDocFreqs.get(term) || 1) - 1;
118
- if (count <= 0) {
119
- this.termDocFreqs.delete(term);
120
- } else {
121
- this.termDocFreqs.set(term, count);
122
- }
123
- const chunkSet = this.postings.get(term);
124
- if (chunkSet) {
125
- chunkSet.delete(chunkId);
126
- if (chunkSet.size === 0) {
127
- this.postings.delete(term);
128
- }
129
- }
130
- }
131
- }
132
- this.docTermFreqs.delete(chunkId);
133
- this.docLengths.delete(chunkId);
134
- this.totalDocs--;
135
- }
136
- }
137
- this.recalculateStats();
138
- }
139
-
140
- public recalculateStats(): void {
141
- let totalLength = 0;
142
- for (const len of this.docLengths.values()) {
143
- totalLength += len;
144
- }
145
- this.totalDocs = this.docLengths.size;
146
- this.avgDocLength = this.totalDocs > 0 ? totalLength / this.totalDocs : 0;
147
- }
148
-
149
- /**
150
- * Search the BM25 index with a query string.
151
- */
152
- public search(query: string, limit = 50): BM25SearchResult[] {
153
- if (this.totalDocs === 0) return [];
154
- const queryTokens = Array.from(new Set(tokenizeCode(query)));
155
- if (queryTokens.length === 0) return [];
156
-
157
- const scores: Map<string, { score: number; matches: string[] }> = new Map();
158
-
159
- for (const term of queryTokens) {
160
- const n = this.termDocFreqs.get(term) || 0;
161
- if (n === 0) continue;
162
-
163
- // Okapi BM25 Inverse Document Frequency
164
- const idf = Math.log(1 + (this.totalDocs - n + 0.5) / (n + 0.5));
165
- const matchingChunkIds = this.postings.get(term);
166
- if (!matchingChunkIds) continue;
167
-
168
- for (const chunkId of matchingChunkIds) {
169
- const tfMap = this.docTermFreqs.get(chunkId);
170
- if (!tfMap) continue;
171
- const tf = tfMap.get(term) || 0;
172
- if (tf === 0) continue;
173
-
174
- const docLen = this.docLengths.get(chunkId) || this.avgDocLength;
175
- const tfNorm = (tf * (this.k1 + 1)) / (tf + this.k1 * (1 - this.b + this.b * (docLen / (this.avgDocLength || 1))));
176
- const termScore = idf * tfNorm;
177
-
178
- const current = scores.get(chunkId) || { score: 0, matches: [] };
179
- current.score += termScore;
180
- current.matches.push(term);
181
- scores.set(chunkId, current);
182
- }
183
- }
184
-
185
- return Array.from(scores.entries())
186
- .map(([chunkId, data]) => ({ chunkId, score: data.score, matches: data.matches }))
187
- .sort((a, b) => b.score - a.score)
188
- .slice(0, limit);
189
- }
190
- }
1
+ import { CodeChunk } from "./search_chunker";
2
+
3
+ export interface BM25SearchResult {
4
+ chunkId: string;
5
+ score: number;
6
+ matches: string[];
7
+ }
8
+
9
+ /**
10
+ * Specialized code tokenizer handling CamelCase, snake_case, identifiers and symbols.
11
+ */
12
+ export function tokenizeCode(text: string): string[] {
13
+ if (!text) return [];
14
+
15
+ const rawTokens = text.match(/[a-zA-Z0-9_]+/g) || [];
16
+ const tokens: string[] = [];
17
+
18
+ for (const raw of rawTokens) {
19
+ const lower = raw.toLowerCase();
20
+ if (lower.length >= 2) {
21
+ tokens.push(lower);
22
+ }
23
+
24
+ // Split snake_case
25
+ if (raw.includes("_")) {
26
+ const parts = raw.split("_");
27
+ for (const p of parts) {
28
+ const pl = p.toLowerCase();
29
+ if (pl.length >= 2) tokens.push(pl);
30
+ }
31
+ }
32
+
33
+ // Split camelCase and PascalCase (e.g. "verifySignature" -> "verify", "signature")
34
+ const camelParts = raw.replace(/([a-z])([A-Z])/g, "$1 $2").split(" ");
35
+ if (camelParts.length > 1) {
36
+ for (const cp of camelParts) {
37
+ const cpl = cp.toLowerCase();
38
+ if (cpl.length >= 2) tokens.push(cpl);
39
+ }
40
+ }
41
+ }
42
+
43
+ return tokens;
44
+ }
45
+
46
+ export class BM25Engine {
47
+ private k1 = 1.2;
48
+ private b = 0.75;
49
+
50
+ // chunkId -> term frequency map: term -> count
51
+ private docTermFreqs: Map<string, Map<string, number>> = new Map();
52
+ // chunkId -> total token count in document
53
+ private docLengths: Map<string, number> = new Map();
54
+ // term -> document frequency (number of docs containing term)
55
+ private termDocFreqs: Map<string, number> = new Map();
56
+ // term -> Set of chunkIds (Inverted index for O(Σ matches) query scanning)
57
+ private postings: Map<string, Set<string>> = new Map();
58
+
59
+ private totalDocs = 0;
60
+ private avgDocLength = 0;
61
+
62
+ public clear(): void {
63
+ this.docTermFreqs.clear();
64
+ this.docLengths.clear();
65
+ this.termDocFreqs.clear();
66
+ this.postings.clear();
67
+ this.totalDocs = 0;
68
+ this.avgDocLength = 0;
69
+ }
70
+
71
+ /**
72
+ * Index a list of CodeChunks into the BM25 inverted index.
73
+ */
74
+ public indexChunks(chunks: CodeChunk[]): void {
75
+ for (const chunk of chunks) {
76
+ this.addChunk(chunk);
77
+ }
78
+ this.recalculateStats();
79
+ }
80
+
81
+ public addChunk(chunk: CodeChunk): void {
82
+ // Combine breadcrumb, signature and content with extra weight for signature/name
83
+ const weightedText = `${chunk.symbolName} ${chunk.symbolName} ${chunk.signature} ${chunk.breadcrumb}\n${chunk.content}`;
84
+ const tokens = tokenizeCode(weightedText);
85
+
86
+ const tfMap = new Map<string, number>();
87
+ for (const t of tokens) {
88
+ tfMap.set(t, (tfMap.get(t) || 0) + 1);
89
+ }
90
+
91
+ this.docTermFreqs.set(chunk.id, tfMap);
92
+ this.docLengths.set(chunk.id, tokens.length);
93
+
94
+ for (const term of tfMap.keys()) {
95
+ this.termDocFreqs.set(term, (this.termDocFreqs.get(term) || 0) + 1);
96
+ let chunkSet = this.postings.get(term);
97
+ if (!chunkSet) {
98
+ chunkSet = new Set();
99
+ this.postings.set(term, chunkSet);
100
+ }
101
+ chunkSet.add(chunk.id);
102
+ }
103
+
104
+ this.totalDocs++;
105
+ }
106
+
107
+ /**
108
+ * Remove all chunks associated with a specific relative file path.
109
+ */
110
+ public removeFile(filePath: string): void {
111
+ const prefix = `${filePath}:`;
112
+ for (const chunkId of Array.from(this.docTermFreqs.keys())) {
113
+ if (chunkId.startsWith(prefix) || chunkId.includes(filePath)) {
114
+ const tfMap = this.docTermFreqs.get(chunkId);
115
+ if (tfMap) {
116
+ for (const term of tfMap.keys()) {
117
+ const count = (this.termDocFreqs.get(term) || 1) - 1;
118
+ if (count <= 0) {
119
+ this.termDocFreqs.delete(term);
120
+ } else {
121
+ this.termDocFreqs.set(term, count);
122
+ }
123
+ const chunkSet = this.postings.get(term);
124
+ if (chunkSet) {
125
+ chunkSet.delete(chunkId);
126
+ if (chunkSet.size === 0) {
127
+ this.postings.delete(term);
128
+ }
129
+ }
130
+ }
131
+ }
132
+ this.docTermFreqs.delete(chunkId);
133
+ this.docLengths.delete(chunkId);
134
+ this.totalDocs--;
135
+ }
136
+ }
137
+ this.recalculateStats();
138
+ }
139
+
140
+ public recalculateStats(): void {
141
+ let totalLength = 0;
142
+ for (const len of this.docLengths.values()) {
143
+ totalLength += len;
144
+ }
145
+ this.totalDocs = this.docLengths.size;
146
+ this.avgDocLength = this.totalDocs > 0 ? totalLength / this.totalDocs : 0;
147
+ }
148
+
149
+ /**
150
+ * Search the BM25 index with a query string.
151
+ */
152
+ public search(query: string, limit = 50): BM25SearchResult[] {
153
+ if (this.totalDocs === 0) return [];
154
+ const queryTokens = Array.from(new Set(tokenizeCode(query)));
155
+ if (queryTokens.length === 0) return [];
156
+
157
+ const scores: Map<string, { score: number; matches: string[] }> = new Map();
158
+
159
+ for (const term of queryTokens) {
160
+ const n = this.termDocFreqs.get(term) || 0;
161
+ if (n === 0) continue;
162
+
163
+ // Okapi BM25 Inverse Document Frequency
164
+ const idf = Math.log(1 + (this.totalDocs - n + 0.5) / (n + 0.5));
165
+ const matchingChunkIds = this.postings.get(term);
166
+ if (!matchingChunkIds) continue;
167
+
168
+ for (const chunkId of matchingChunkIds) {
169
+ const tfMap = this.docTermFreqs.get(chunkId);
170
+ if (!tfMap) continue;
171
+ const tf = tfMap.get(term) || 0;
172
+ if (tf === 0) continue;
173
+
174
+ const docLen = this.docLengths.get(chunkId) || this.avgDocLength;
175
+ const tfNorm = (tf * (this.k1 + 1)) / (tf + this.k1 * (1 - this.b + this.b * (docLen / (this.avgDocLength || 1))));
176
+ const termScore = idf * tfNorm;
177
+
178
+ const current = scores.get(chunkId) || { score: 0, matches: [] };
179
+ current.score += termScore;
180
+ current.matches.push(term);
181
+ scores.set(chunkId, current);
182
+ }
183
+ }
184
+
185
+ return Array.from(scores.entries())
186
+ .map(([chunkId, data]) => ({ chunkId, score: data.score, matches: data.matches }))
187
+ .sort((a, b) => b.score - a.score)
188
+ .slice(0, limit);
189
+ }
190
+ }