import { CodeChunk } from "./search_chunker"; export interface BM25SearchResult { chunkId: string; score: number; matches: string[]; } /** * Specialized code tokenizer handling CamelCase, snake_case, identifiers and symbols. */ export function tokenizeCode(text: string): string[] { if (!text) return []; const rawTokens = text.match(/[a-zA-Z0-9_]+/g) || []; const tokens: string[] = []; for (const raw of rawTokens) { const lower = raw.toLowerCase(); if (lower.length >= 2) { tokens.push(lower); } // Split snake_case if (raw.includes("_")) { const parts = raw.split("_"); for (const p of parts) { const pl = p.toLowerCase(); if (pl.length >= 2) tokens.push(pl); } } // Split camelCase and PascalCase (e.g. "verifySignature" -> "verify", "signature") const camelParts = raw.replace(/([a-z])([A-Z])/g, "$1 $2").split(" "); if (camelParts.length > 1) { for (const cp of camelParts) { const cpl = cp.toLowerCase(); if (cpl.length >= 2) tokens.push(cpl); } } } return tokens; } const COMMON_QUERY_STOPWORDS = new Set([ "a", "an", "the", "and", "or", "in", "on", "at", "to", "for", "with", "by", "of", "is", "as", "it", "from", "be", "are", "was", "were", "which", "whose", "whether", "shown", "showing", "over" ]); /** * Filter common natural-language stopwords from query tokens if substantive code identifiers exist. */ export function filterQueryTokens(tokens: string[]): string[] { const nonStopwords = tokens.filter((t) => !COMMON_QUERY_STOPWORDS.has(t)); return nonStopwords.length > 0 ? nonStopwords : tokens; } export class BM25Engine { private k1 = 1.2; private b = 0.75; // chunkId -> term frequency map: term -> count private docTermFreqs: Map> = new Map(); // chunkId -> total token count in document private docLengths: Map = new Map(); // term -> document frequency (number of docs containing term) private termDocFreqs: Map = new Map(); // term -> Set of chunkIds (Inverted index for O(Σ matches) query scanning) private postings: Map> = new Map(); // filePath -> chunkIds, so removeFile touches only that file's chunks private docIdsByFile: Map> = new Map(); private totalDocs = 0; private avgDocLength = 0; // Running sum of docLengths, so recalculateStats is O(1) private totalLength = 0; public clear(): void { this.docTermFreqs.clear(); this.docLengths.clear(); this.termDocFreqs.clear(); this.postings.clear(); this.docIdsByFile.clear(); this.totalDocs = 0; this.avgDocLength = 0; this.totalLength = 0; } /** * Index a list of CodeChunks into the BM25 inverted index. */ public indexChunks(chunks: CodeChunk[]): void { for (const chunk of chunks) { this.addChunk(chunk); } this.recalculateStats(); } public addChunk(chunk: CodeChunk): void { // Combine breadcrumb, signature and content with extra weight for signature/name const weightedText = `${chunk.symbolName} ${chunk.symbolName} ${chunk.signature} ${chunk.breadcrumb}\n${chunk.content}`; const tokens = tokenizeCode(weightedText); const tfMap = new Map(); for (const t of tokens) { tfMap.set(t, (tfMap.get(t) || 0) + 1); } this.docTermFreqs.set(chunk.id, tfMap); this.totalLength += tokens.length - (this.docLengths.get(chunk.id) ?? 0); this.docLengths.set(chunk.id, tokens.length); let fileIds = this.docIdsByFile.get(chunk.filePath); if (!fileIds) { fileIds = new Set(); this.docIdsByFile.set(chunk.filePath, fileIds); } fileIds.add(chunk.id); for (const term of tfMap.keys()) { this.termDocFreqs.set(term, (this.termDocFreqs.get(term) || 0) + 1); let chunkSet = this.postings.get(term); if (!chunkSet) { chunkSet = new Set(); this.postings.set(term, chunkSet); } chunkSet.add(chunk.id); } this.totalDocs++; } /** * Remove all chunks associated with a specific relative file path. */ public removeFile(filePath: string): void { for (const chunkId of this.docIdsByFile.get(filePath) ?? []) { const tfMap = this.docTermFreqs.get(chunkId); if (tfMap) { for (const term of tfMap.keys()) { const count = (this.termDocFreqs.get(term) || 1) - 1; if (count <= 0) { this.termDocFreqs.delete(term); } else { this.termDocFreqs.set(term, count); } const chunkSet = this.postings.get(term); if (chunkSet) { chunkSet.delete(chunkId); if (chunkSet.size === 0) { this.postings.delete(term); } } } } this.docTermFreqs.delete(chunkId); this.totalLength -= this.docLengths.get(chunkId) ?? 0; this.docLengths.delete(chunkId); this.totalDocs--; } this.docIdsByFile.delete(filePath); this.recalculateStats(); } public recalculateStats(): void { this.totalDocs = this.docLengths.size; this.avgDocLength = this.totalDocs > 0 ? this.totalLength / this.totalDocs : 0; } /** * Search the BM25 index with a query string. */ public search( query: string, limit = 50, filter?: (chunkId: string) => boolean, ): BM25SearchResult[] { if (this.totalDocs === 0) return []; const rawTokens = tokenizeCode(query); const queryTokens = Array.from(new Set(filterQueryTokens(rawTokens))); if (queryTokens.length === 0) return []; const scores: Map = new Map(); for (const term of queryTokens) { const n = this.termDocFreqs.get(term) || 0; if (n === 0) continue; // Okapi BM25 Inverse Document Frequency const idf = Math.log(1 + (this.totalDocs - n + 0.5) / (n + 0.5)); const matchingChunkIds = this.postings.get(term); if (!matchingChunkIds) continue; for (const chunkId of matchingChunkIds) { if (filter && !filter(chunkId)) continue; const tfMap = this.docTermFreqs.get(chunkId); if (!tfMap) continue; const tf = tfMap.get(term) || 0; if (tf === 0) continue; const docLen = this.docLengths.get(chunkId) || this.avgDocLength; const tfNorm = (tf * (this.k1 + 1)) / (tf + this.k1 * (1 - this.b + this.b * (docLen / (this.avgDocLength || 1)))); const termScore = idf * tfNorm; const current = scores.get(chunkId) || { score: 0, matches: [] }; current.score += termScore; current.matches.push(term); scores.set(chunkId, current); } } return Array.from(scores.entries()) .map(([chunkId, data]) => ({ chunkId, score: data.score, matches: data.matches })) .sort((a, b) => { if (b.score !== a.score) return b.score - a.score; if (a.chunkId < b.chunkId) return -1; if (a.chunkId > b.chunkId) return 1; return 0; }) .slice(0, limit); } }