@floydous/pi-agent-kernel 0.2.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.
@@ -298,11 +298,45 @@ export function extractFileTags(filePath: string, content: string): FileTags {
298
298
  }
299
299
  }
300
300
 
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
+
301
335
  // const variable / constant declaration: const FOO = ... or const FOO: string = ... (only top-level declarations)
302
336
  const constDecl = line.match(
303
337
  /^(?:export\s+)?const\s+([a-zA-Z0-9_]+)(?:\s*:\s*([^=]+))?\s*=/,
304
338
  );
305
- if (constDecl && braceDepth === 0) {
339
+ if (constDecl && braceDepth === 0 && rawLine === rawLine.trimStart()) {
306
340
  const isAllUpper = /^[A-Z0-9_]{2,}$/.test(constDecl[1]);
307
341
  definitions.push({
308
342
  name: constDecl[1],
@@ -544,27 +578,28 @@ export function extractFileTags(filePath: string, content: string): FileTags {
544
578
 
545
579
  // Go
546
580
  if (ext === ".go") {
547
- const goFn = line.match(/^func\s+(?:\([^)]+\)\s+)?([a-zA-Z0-9_]+)/);
581
+ const goFn = line.match(/^func\s+(\([^)]+\)\s+)?([a-zA-Z0-9_]+)/);
548
582
  if (goFn) {
549
583
  const sig =
550
584
  extractBalancedSig(lines, i, "go_fn") || line.split("{")[0].trim();
551
585
  definitions.push({
552
- name: goFn[1],
553
- kind: "function",
586
+ name: goFn[2],
587
+ kind: goFn[1] ? "method" : "function",
554
588
  signature: sig,
555
589
  line: i + 1,
556
590
  });
557
591
  continue;
558
592
  }
559
593
 
560
- 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+(.+)/);
561
595
  if (goType) {
596
+ const typeBody = goType[2].trim();
562
597
  const sig =
563
598
  extractBalancedSig(lines, i, "go_type") ||
564
- `type ${goType[1]} ${goType[2]}`;
599
+ line.replace(/\s*\{\s*$/, "").trim();
565
600
  definitions.push({
566
601
  name: goType[1],
567
- kind: "class",
602
+ kind: typeBody.startsWith("interface") ? "interface" : "class",
568
603
  signature: sig,
569
604
  line: i + 1,
570
605
  });
@@ -585,6 +620,156 @@ export function extractFileTags(filePath: string, content: string): FileTags {
585
620
  }
586
621
  }
587
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
+
588
773
  for (const ch of line) {
589
774
  if (ch === "{") braceDepth++;
590
775
  else if (ch === "}") braceDepth = Math.max(0, braceDepth - 1);
@@ -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
+ }