Skip to main content

lean_ctx/core/
bm25_index.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::time::UNIX_EPOCH;
4
5use serde::{Deserialize, Serialize};
6
7const MAX_BM25_FILES: usize = 5000;
8const CHUNK_COUNT_WARNING: usize = 50_000;
9const ZSTD_LEVEL: i32 = 9;
10
11const DEFAULT_BM25_IGNORES: &[&str] = &[
12    "vendor/**",
13    "dist/**",
14    "build/**",
15    "public/vendor/**",
16    "public/js/**",
17    "public/css/**",
18    "public/build/**",
19    ".next/**",
20    ".nuxt/**",
21    "__pycache__/**",
22    "*.min.js",
23    "*.min.css",
24    "*.bundle.js",
25    "*.chunk.js",
26];
27
28fn max_bm25_cache_bytes() -> u64 {
29    let mb = std::env::var("LEAN_CTX_BM25_MAX_CACHE_MB")
30        .ok()
31        .and_then(|v| v.parse::<u64>().ok())
32        .unwrap_or_else(|| {
33            let cfg = crate::core::config::Config::load();
34            let profile = crate::core::config::MemoryProfile::effective(&cfg);
35            let profile_mb = profile.bm25_max_cache_mb();
36            if cfg.bm25_max_cache_mb == crate::core::config::default_bm25_max_cache_mb() {
37                profile_mb
38            } else {
39                cfg.bm25_max_cache_mb
40            }
41        });
42    mb * 1024 * 1024
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct CodeChunk {
47    pub file_path: String,
48    pub symbol_name: String,
49    pub kind: ChunkKind,
50    pub start_line: usize,
51    pub end_line: usize,
52    pub content: String,
53    #[serde(default)]
54    pub tokens: Vec<String>,
55    pub token_count: usize,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
59pub enum ChunkKind {
60    Function,
61    Struct,
62    Impl,
63    Module,
64    Class,
65    Method,
66    Other,
67    // -- External source kinds (Context Cortex) --
68    Issue,
69    PullRequest,
70    WikiPage,
71    DbSchema,
72    ApiEndpoint,
73    Ticket,
74    ExternalOther,
75}
76
77#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
78pub struct IndexedFileState {
79    pub mtime_ms: u64,
80    pub size_bytes: u64,
81}
82
83impl IndexedFileState {
84    fn from_path(path: &Path) -> Option<Self> {
85        let meta = path.metadata().ok()?;
86        let size_bytes = meta.len();
87        let mtime_ms = meta
88            .modified()
89            .ok()
90            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
91            .map(|d| d.as_millis() as u64)?;
92        Some(Self {
93            mtime_ms,
94            size_bytes,
95        })
96    }
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct BM25Index {
101    pub chunks: Vec<CodeChunk>,
102    pub inverted: HashMap<String, Vec<(usize, f64)>>,
103    pub avg_doc_len: f64,
104    pub doc_count: usize,
105    pub doc_freqs: HashMap<String, usize>,
106    #[serde(default)]
107    pub files: HashMap<String, IndexedFileState>,
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct SearchResult {
112    pub chunk_idx: usize,
113    pub score: f64,
114    pub file_path: String,
115    pub symbol_name: String,
116    pub kind: ChunkKind,
117    pub start_line: usize,
118    pub end_line: usize,
119    pub snippet: String,
120}
121
122const BM25_K1: f64 = 1.2;
123const BM25_B: f64 = 0.75;
124
125impl Default for BM25Index {
126    fn default() -> Self {
127        Self::new()
128    }
129}
130
131impl BM25Index {
132    pub fn new() -> Self {
133        Self {
134            chunks: Vec::new(),
135            inverted: HashMap::new(),
136            avg_doc_len: 0.0,
137            doc_count: 0,
138            doc_freqs: HashMap::new(),
139            files: HashMap::new(),
140        }
141    }
142
143    /// Approximate heap memory used by this index in bytes.
144    pub fn memory_usage_bytes(&self) -> usize {
145        let chunks_size: usize = self
146            .chunks
147            .iter()
148            .map(|c| {
149                c.content.len()
150                    + c.file_path.len()
151                    + c.symbol_name.len()
152                    + c.tokens.iter().map(String::len).sum::<usize>()
153                    + 64
154            })
155            .sum();
156        let inverted_size: usize = self
157            .inverted
158            .iter()
159            .map(|(k, v)| k.len() + v.len() * 16 + 32)
160            .sum();
161        let files_size: usize = self.files.keys().map(|k| k.len() + 24).sum();
162        let freqs_size: usize = self.doc_freqs.keys().map(|k| k.len() + 16).sum();
163        chunks_size + inverted_size + files_size + freqs_size
164    }
165
166    /// Drops all in-memory data, effectively freeing heap. Index can be re-loaded from disk.
167    pub fn unload(&mut self) {
168        let usage = self.memory_usage_bytes();
169        self.chunks = Vec::new();
170        self.inverted = HashMap::new();
171        self.doc_freqs = HashMap::new();
172        self.files = HashMap::new();
173        self.avg_doc_len = 0.0;
174        self.doc_count = 0;
175        tracing::info!(
176            "[bm25] unloaded index, freed ~{:.1}MB",
177            usage as f64 / 1_048_576.0
178        );
179    }
180
181    /// Builds an index from explicit chunks (unit tests; avoids filesystem walking).
182    #[cfg(test)]
183    pub(crate) fn from_chunks_for_test(chunks: Vec<CodeChunk>) -> Self {
184        let mut index = Self::new();
185        for mut chunk in chunks {
186            if chunk.token_count == 0 {
187                chunk.token_count = tokenize(&chunk.content).len();
188            }
189            index.add_chunk(chunk);
190        }
191        index.finalize();
192        index
193    }
194
195    pub fn build_from_directory(root: &Path) -> Self {
196        let root_str = root.to_string_lossy();
197        if !super::graph_index::is_safe_scan_root_public(&root_str) {
198            tracing::warn!("[bm25: scan aborted for unsafe root {root_str}]");
199            return Self::new();
200        }
201        let mut index = Self::new();
202        let files = list_code_files(root);
203        const MAX_FILE_SIZE_BYTES: u64 = 2 * 1024 * 1024;
204
205        for (i, rel) in files.iter().enumerate() {
206            if i.is_multiple_of(500) && crate::core::memory_guard::is_under_pressure() {
207                tracing::warn!(
208                    "[bm25: stopping build at file {i}/{} due to memory pressure]",
209                    files.len()
210                );
211                break;
212            }
213            if crate::core::memory_guard::abort_requested() {
214                tracing::warn!("[bm25: aborting build due to critical memory pressure]");
215                break;
216            }
217
218            let abs = root.join(rel);
219            let Some(state) = IndexedFileState::from_path(&abs) else {
220                continue;
221            };
222            if state.size_bytes > MAX_FILE_SIZE_BYTES {
223                continue;
224            }
225            if let Ok(content) = std::fs::read_to_string(&abs) {
226                let mut chunks = extract_chunks(rel, &content);
227                chunks.sort_by(|a, b| {
228                    a.start_line
229                        .cmp(&b.start_line)
230                        .then_with(|| a.end_line.cmp(&b.end_line))
231                        .then_with(|| a.symbol_name.cmp(&b.symbol_name))
232                });
233                for chunk in chunks {
234                    index.add_chunk(chunk);
235                }
236                index.files.insert(rel.clone(), state);
237            }
238        }
239
240        index.finalize();
241        index
242    }
243
244    pub fn rebuild_incremental(root: &Path, prev: &BM25Index) -> Self {
245        let mut old_by_file: HashMap<String, Vec<CodeChunk>> = HashMap::new();
246        for c in &prev.chunks {
247            old_by_file
248                .entry(c.file_path.clone())
249                .or_default()
250                .push(c.clone());
251        }
252        for v in old_by_file.values_mut() {
253            v.sort_by(|a, b| {
254                a.start_line
255                    .cmp(&b.start_line)
256                    .then_with(|| a.end_line.cmp(&b.end_line))
257                    .then_with(|| a.symbol_name.cmp(&b.symbol_name))
258            });
259        }
260
261        let mut index = Self::new();
262        let files = list_code_files(root);
263        const MAX_FILE_SIZE_BYTES: u64 = 2 * 1024 * 1024;
264
265        for (i, rel) in files.iter().enumerate() {
266            if i.is_multiple_of(500) && crate::core::memory_guard::is_under_pressure() {
267                tracing::warn!(
268                    "[bm25: stopping incremental rebuild at file {i}/{} due to memory pressure]",
269                    files.len()
270                );
271                break;
272            }
273
274            let abs = root.join(rel);
275            let Some(state) = IndexedFileState::from_path(&abs) else {
276                continue;
277            };
278
279            let unchanged = prev.files.get(rel).is_some_and(|old| *old == state);
280            if unchanged {
281                if let Some(chunks) = old_by_file.get(rel) {
282                    if chunks.first().is_some_and(|c| !c.content.is_empty()) {
283                        for chunk in chunks {
284                            index.add_chunk(chunk.clone());
285                        }
286                        index.files.insert(rel.clone(), state);
287                        continue;
288                    }
289                }
290            }
291
292            if state.size_bytes > MAX_FILE_SIZE_BYTES {
293                continue;
294            }
295            if let Ok(content) = std::fs::read_to_string(&abs) {
296                let mut chunks = extract_chunks(rel, &content);
297                chunks.sort_by(|a, b| {
298                    a.start_line
299                        .cmp(&b.start_line)
300                        .then_with(|| a.end_line.cmp(&b.end_line))
301                        .then_with(|| a.symbol_name.cmp(&b.symbol_name))
302                });
303                for chunk in chunks {
304                    index.add_chunk(chunk);
305                }
306                index.files.insert(rel.clone(), state);
307            }
308        }
309
310        index.finalize();
311        index
312    }
313
314    fn add_chunk(&mut self, chunk: CodeChunk) {
315        let idx = self.chunks.len();
316
317        let enriched = enrich_for_bm25(&chunk);
318        let tokens = tokenize(&enriched);
319        for token in &tokens {
320            let lower = token.to_lowercase();
321            let postings = self.inverted.entry(lower.clone()).or_default();
322            if postings.last().map(|(last_idx, _)| *last_idx) != Some(idx) {
323                *self.doc_freqs.entry(lower).or_insert(0) += 1;
324            }
325            postings.push((idx, 1.0));
326        }
327
328        self.chunks.push(CodeChunk {
329            token_count: tokens.len(),
330            tokens: Vec::new(),
331            ..chunk
332        });
333    }
334
335    fn finalize(&mut self) {
336        self.doc_count = self.chunks.len();
337        if self.doc_count == 0 {
338            return;
339        }
340
341        let total_len: usize = self.chunks.iter().map(|c| c.token_count).sum();
342        self.avg_doc_len = total_len as f64 / self.doc_count as f64;
343    }
344
345    pub fn search(&self, query: &str, top_k: usize) -> Vec<SearchResult> {
346        let query_tokens = tokenize(query);
347        if query_tokens.is_empty() || self.doc_count == 0 {
348            return Vec::new();
349        }
350
351        // Pre-allocated score array: O(1) per-access vs HashMap overhead.
352        // Kolmogorov-optimal: minimal allocation for the scoring operation.
353        let n = self.chunks.len();
354        let mut scores = vec![0.0f64; n];
355        let mut touched = Vec::with_capacity(n.min(256));
356
357        for token in &query_tokens {
358            let lower = token.to_lowercase();
359            let df = *self.doc_freqs.get(&lower).unwrap_or(&0) as f64;
360            if df == 0.0 {
361                continue;
362            }
363
364            let idf = ((self.doc_count as f64 - df + 0.5) / (df + 0.5) + 1.0).ln();
365
366            if let Some(postings) = self.inverted.get(&lower) {
367                for &(idx, weight) in postings {
368                    let doc_len = self.chunks[idx].token_count as f64;
369                    let norm_len = doc_len / self.avg_doc_len.max(1.0);
370                    let bm25 = idf * (weight * (BM25_K1 + 1.0))
371                        / (weight + BM25_K1 * (1.0 - BM25_B + BM25_B * norm_len));
372
373                    if scores[idx] == 0.0 {
374                        touched.push(idx);
375                    }
376                    scores[idx] += bm25;
377                }
378            }
379        }
380
381        let mut results: Vec<SearchResult> = touched
382            .iter()
383            .filter(|&&idx| scores[idx] > 0.0)
384            .map(|&idx| {
385                let chunk = &self.chunks[idx];
386                let snippet = chunk.content.lines().take(5).collect::<Vec<_>>().join("\n");
387                SearchResult {
388                    chunk_idx: idx,
389                    score: scores[idx],
390                    file_path: chunk.file_path.clone(),
391                    symbol_name: chunk.symbol_name.clone(),
392                    kind: chunk.kind.clone(),
393                    start_line: chunk.start_line,
394                    end_line: chunk.end_line,
395                    snippet,
396                }
397            })
398            .collect();
399
400        results.sort_by(|a, b| {
401            b.score
402                .partial_cmp(&a.score)
403                .unwrap_or(std::cmp::Ordering::Equal)
404                .then_with(|| a.file_path.cmp(&b.file_path))
405                .then_with(|| a.symbol_name.cmp(&b.symbol_name))
406                .then_with(|| a.start_line.cmp(&b.start_line))
407                .then_with(|| a.end_line.cmp(&b.end_line))
408        });
409        results.truncate(top_k);
410        results
411    }
412
413    pub fn save(&self, root: &Path) -> std::io::Result<()> {
414        if self.chunks.len() > CHUNK_COUNT_WARNING {
415            tracing::warn!(
416                "[bm25] index has {} chunks (threshold {}), consider adding extra_ignore_patterns",
417                self.chunks.len(),
418                CHUNK_COUNT_WARNING
419            );
420        }
421
422        let dir = index_dir(root);
423        std::fs::create_dir_all(&dir)?;
424        let data = bincode::serde::encode_to_vec(self, bincode::config::standard())
425            .map_err(|e| std::io::Error::other(e.to_string()))?;
426
427        let compressed = zstd::encode_all(data.as_slice(), ZSTD_LEVEL)
428            .map_err(|e| std::io::Error::other(format!("zstd compress: {e}")))?;
429
430        let max_bytes = max_bm25_cache_bytes();
431        if compressed.len() as u64 > max_bytes {
432            tracing::warn!(
433                "[bm25] compressed index too large ({:.1} MB, limit {:.0} MB), refusing to persist: {}",
434                compressed.len() as f64 / 1_048_576.0,
435                max_bytes / (1024 * 1024),
436                dir.display()
437            );
438            return Ok(());
439        }
440
441        tracing::info!(
442            "[bm25] index: {:.1} MB bincode → {:.1} MB zstd ({:.0}% saved)",
443            data.len() as f64 / 1_048_576.0,
444            compressed.len() as f64 / 1_048_576.0,
445            (1.0 - compressed.len() as f64 / data.len().max(1) as f64) * 100.0
446        );
447
448        let target = dir.join("bm25_index.bin.zst");
449        let tmp = dir.join("bm25_index.bin.zst.tmp");
450        std::fs::write(&tmp, &compressed)?;
451        std::fs::rename(&tmp, &target)?;
452
453        let _ = std::fs::remove_file(dir.join("bm25_index.bin"));
454        let _ = std::fs::remove_file(dir.join("bm25_index.json"));
455
456        let _ = std::fs::write(
457            dir.join("project_root.txt"),
458            root.to_string_lossy().as_bytes(),
459        );
460
461        Ok(())
462    }
463
464    pub fn load(root: &Path) -> Option<Self> {
465        let dir = index_dir(root);
466        let max_bytes = max_bm25_cache_bytes();
467
468        let zst_path = dir.join("bm25_index.bin.zst");
469        if zst_path.exists() {
470            let meta = std::fs::metadata(&zst_path).ok()?;
471            if meta.len() > max_bytes {
472                tracing::warn!(
473                    "[bm25] compressed index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
474                    meta.len() as f64 / 1_073_741_824.0,
475                    max_bytes / (1024 * 1024),
476                    zst_path.display()
477                );
478                let quarantined = zst_path.with_extension("zst.quarantined");
479                let _ = std::fs::rename(&zst_path, &quarantined);
480                return None;
481            }
482            let compressed = std::fs::read(&zst_path).ok()?;
483            let data = zstd::decode_all(compressed.as_slice()).ok()?;
484            let (idx, _): (Self, _) =
485                bincode::serde::decode_from_slice(&data, bincode::config::standard()).ok()?;
486            return Some(idx);
487        }
488
489        let bin_path = dir.join("bm25_index.bin");
490        if bin_path.exists() {
491            let meta = std::fs::metadata(&bin_path).ok()?;
492            if meta.len() > max_bytes {
493                tracing::warn!(
494                    "[bm25] index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
495                    meta.len() as f64 / 1_073_741_824.0,
496                    max_bytes / (1024 * 1024),
497                    bin_path.display()
498                );
499                let quarantined = bin_path.with_extension("bin.quarantined");
500                let _ = std::fs::rename(&bin_path, &quarantined);
501                return None;
502            }
503            let data = std::fs::read(&bin_path).ok()?;
504            let (idx, _): (Self, _) =
505                bincode::serde::decode_from_slice(&data, bincode::config::standard()).ok()?;
506            // Auto-migrate: compress legacy .bin to .bin.zst
507            if let Ok(compressed) = zstd::encode_all(data.as_slice(), ZSTD_LEVEL) {
508                let zst_tmp = zst_path.with_extension("zst.tmp");
509                if std::fs::write(&zst_tmp, &compressed).is_ok()
510                    && std::fs::rename(&zst_tmp, &zst_path).is_ok()
511                {
512                    tracing::info!(
513                        "[bm25] migrated {:.1} MB → {:.1} MB zstd",
514                        data.len() as f64 / 1_048_576.0,
515                        compressed.len() as f64 / 1_048_576.0
516                    );
517                    let _ = std::fs::remove_file(&bin_path);
518                }
519            }
520            return Some(idx);
521        }
522
523        let json_path = dir.join("bm25_index.json");
524        if json_path.exists() {
525            let meta = std::fs::metadata(&json_path).ok()?;
526            if meta.len() > max_bytes {
527                tracing::warn!(
528                    "[bm25] index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
529                    meta.len() as f64 / 1_073_741_824.0,
530                    max_bytes / (1024 * 1024),
531                    json_path.display()
532                );
533                let quarantined = json_path.with_extension("json.quarantined");
534                let _ = std::fs::rename(&json_path, &quarantined);
535                return None;
536            }
537            let data = std::fs::read_to_string(&json_path).ok()?;
538            return serde_json::from_str(&data).ok();
539        }
540
541        None
542    }
543
544    pub fn load_or_build(root: &Path) -> Self {
545        if !is_safe_bm25_root(root) {
546            return Self::default();
547        }
548        if let Some(idx) = Self::load(root) {
549            if !bm25_index_looks_stale(&idx, root) {
550                return idx;
551            }
552            tracing::debug!(
553                "[bm25_index: stale index detected for {}; rebuilding]",
554                root.display()
555            );
556            let rebuilt = if idx.files.is_empty() {
557                Self::build_from_directory(root)
558            } else {
559                Self::rebuild_incremental(root, &idx)
560            };
561            let _ = rebuilt.save(root);
562            return rebuilt;
563        }
564
565        let built = Self::build_from_directory(root);
566        let _ = built.save(root);
567        built
568    }
569
570    pub fn index_file_path(root: &Path) -> PathBuf {
571        let dir = index_dir(root);
572        let zst = dir.join("bm25_index.bin.zst");
573        if zst.exists() {
574            return zst;
575        }
576        let bin = dir.join("bm25_index.bin");
577        if bin.exists() {
578            return bin;
579        }
580        dir.join("bm25_index.json")
581    }
582
583    /// Ingest external `ContentChunk`s into the BM25 index.
584    /// Converts each chunk to a `CodeChunk` (backward-compatible) and
585    /// rebuilds the inverted index. Returns the number of chunks ingested.
586    pub fn ingest_content_chunks(
587        &mut self,
588        chunks: impl IntoIterator<Item = super::content_chunk::ContentChunk>,
589    ) -> usize {
590        let mut count = 0usize;
591        for cc in chunks {
592            self.add_chunk(cc.into());
593            count += 1;
594        }
595        if count > 0 {
596            self.finalize();
597        }
598        count
599    }
600
601    /// Number of chunks originating from external providers.
602    pub fn external_chunk_count(&self) -> usize {
603        self.chunks
604            .iter()
605            .filter(|c| c.file_path.contains("://"))
606            .count()
607    }
608}
609
610fn is_safe_bm25_root(root: &Path) -> bool {
611    super::graph_index::is_safe_scan_root_public(&root.to_string_lossy())
612}
613
614fn bm25_index_looks_stale(index: &BM25Index, root: &Path) -> bool {
615    if index.chunks.is_empty() {
616        return false;
617    }
618
619    if index.files.is_empty() {
620        // Legacy index (pre file-state tracking): only detect missing files.
621        let mut seen = std::collections::HashSet::<&str>::new();
622        for chunk in &index.chunks {
623            let rel = chunk.file_path.trim_start_matches(['/', '\\']);
624            if rel.is_empty() {
625                continue;
626            }
627            if !seen.insert(rel) {
628                continue;
629            }
630            if !root.join(rel).exists() {
631                return true;
632            }
633        }
634        return false;
635    }
636
637    // Missing or modified tracked files.
638    for (rel, old_state) in &index.files {
639        let abs = root.join(rel);
640        if !abs.exists() {
641            return true;
642        }
643        let Some(cur) = IndexedFileState::from_path(&abs) else {
644            return true;
645        };
646        if &cur != old_state {
647            return true;
648        }
649    }
650
651    // New files (present on disk but not in index).
652    for rel in list_code_files(root) {
653        if !index.files.contains_key(&rel) {
654            return true;
655        }
656    }
657
658    false
659}
660
661fn index_dir(root: &Path) -> PathBuf {
662    crate::core::index_namespace::vectors_dir(root)
663}
664
665fn list_code_files(root: &Path) -> Vec<String> {
666    let walker = ignore::WalkBuilder::new(root)
667        .hidden(true)
668        .git_ignore(true)
669        .git_global(true)
670        .git_exclude(true)
671        .max_depth(Some(20))
672        .build();
673
674    let cfg = crate::core::config::Config::load();
675    let mut ignore_patterns: Vec<glob::Pattern> = DEFAULT_BM25_IGNORES
676        .iter()
677        .filter_map(|p| glob::Pattern::new(p).ok())
678        .collect();
679    ignore_patterns.extend(
680        cfg.extra_ignore_patterns
681            .iter()
682            .filter_map(|p| glob::Pattern::new(p).ok()),
683    );
684
685    let mut files: Vec<String> = Vec::new();
686    for entry in walker.flatten() {
687        let path = entry.path();
688        if !path.is_file() {
689            continue;
690        }
691        if !is_code_file(path) {
692            continue;
693        }
694        let rel = path
695            .strip_prefix(root)
696            .unwrap_or(path)
697            .to_string_lossy()
698            .to_string();
699        if rel.is_empty() {
700            continue;
701        }
702        if ignore_patterns.iter().any(|p| p.matches(&rel)) {
703            continue;
704        }
705        if files.len() >= MAX_BM25_FILES {
706            tracing::warn!(
707                "[bm25] file cap reached ({MAX_BM25_FILES}), skipping remaining files in {}",
708                root.display()
709            );
710            break;
711        }
712        files.push(rel);
713    }
714
715    files.sort();
716    files.dedup();
717    files
718}
719
720pub fn is_code_file(path: &Path) -> bool {
721    let ext = path
722        .extension()
723        .and_then(|e| e.to_str())
724        .unwrap_or("")
725        .to_lowercase();
726    matches!(
727        ext.as_str(),
728        "rs" | "ts"
729            | "tsx"
730            | "js"
731            | "jsx"
732            | "py"
733            | "go"
734            | "java"
735            | "c"
736            | "cc"
737            | "cpp"
738            | "h"
739            | "hpp"
740            | "rb"
741            | "cs"
742            | "kt"
743            | "swift"
744            | "php"
745            | "scala"
746            | "sql"
747            | "ex"
748            | "exs"
749            | "zig"
750            | "lua"
751            | "dart"
752            | "vue"
753            | "svelte"
754    )
755}
756
757fn tokenize(text: &str) -> Vec<String> {
758    let mut tokens = Vec::new();
759    let mut current = String::new();
760
761    for ch in text.chars() {
762        if ch.is_alphanumeric() || ch == '_' {
763            current.push(ch);
764        } else {
765            if current.len() >= 2 {
766                tokens.push(current.clone());
767            }
768            current.clear();
769        }
770    }
771    if current.len() >= 2 {
772        tokens.push(current);
773    }
774
775    split_camel_case_tokens(&tokens)
776}
777
778pub(crate) fn tokenize_for_index(text: &str) -> Vec<String> {
779    tokenize(text)
780}
781
782fn split_camel_case_tokens(tokens: &[String]) -> Vec<String> {
783    let mut result = Vec::new();
784    for token in tokens {
785        result.push(token.clone());
786        let mut start = 0;
787        let chars: Vec<char> = token.chars().collect();
788        for i in 1..chars.len() {
789            if chars[i].is_uppercase() && (i + 1 >= chars.len() || !chars[i + 1].is_uppercase()) {
790                let part: String = chars[start..i].iter().collect();
791                if part.len() >= 2 {
792                    result.push(part);
793                }
794                start = i;
795            }
796        }
797        if start > 0 {
798            let part: String = chars[start..].iter().collect();
799            if part.len() >= 2 {
800                result.push(part);
801            }
802        }
803    }
804    result
805}
806
807fn extract_chunks(file_path: &str, content: &str) -> Vec<CodeChunk> {
808    #[cfg(feature = "tree-sitter")]
809    {
810        let ext = std::path::Path::new(file_path)
811            .extension()
812            .and_then(|e| e.to_str())
813            .unwrap_or("");
814        if let Some(chunks) = crate::core::chunks_ts::extract_chunks_ts(file_path, content, ext) {
815            return chunks;
816        }
817    }
818
819    let lines: Vec<&str> = content.lines().collect();
820    if lines.is_empty() {
821        return Vec::new();
822    }
823
824    let mut chunks = Vec::new();
825    let mut i = 0;
826
827    while i < lines.len() {
828        let trimmed = lines[i].trim();
829
830        if let Some((name, kind)) = detect_symbol(trimmed) {
831            let start = i;
832            let end = find_block_end(&lines, i);
833            let block: String = lines[start..=end.min(lines.len() - 1)].to_vec().join("\n");
834            let token_count = tokenize(&block).len();
835
836            chunks.push(CodeChunk {
837                file_path: file_path.to_string(),
838                symbol_name: name,
839                kind,
840                start_line: start + 1,
841                end_line: end + 1,
842                content: block,
843                tokens: Vec::new(),
844                token_count,
845            });
846
847            i = end + 1;
848        } else {
849            i += 1;
850        }
851    }
852
853    if chunks.is_empty() && !content.is_empty() {
854        // Fallback: when no symbols are detected, chunk the file into stable, content-defined
855        // segments (rolling-hash) to enable meaningful semantic search over non-code assets.
856        //
857        // Safety note: rabin_karp uses byte offsets; we must slice bytes and decode safely.
858        let bytes = content.as_bytes();
859        let rk_chunks = crate::core::rabin_karp::chunk(content);
860        if !rk_chunks.is_empty() && rk_chunks.len() <= 200 {
861            for (idx, c) in rk_chunks.into_iter().take(50).enumerate() {
862                let end = (c.offset + c.length).min(bytes.len());
863                let slice = &bytes[c.offset..end];
864                let chunk_text = String::from_utf8_lossy(slice).into_owned();
865                let token_count = tokenize(&chunk_text).len();
866                let start_line = 1 + bytecount::count(&bytes[..c.offset], b'\n');
867                let end_line = start_line + bytecount::count(slice, b'\n');
868                chunks.push(CodeChunk {
869                    file_path: file_path.to_string(),
870                    symbol_name: format!("{file_path}#chunk-{idx}"),
871                    kind: ChunkKind::Module,
872                    start_line,
873                    end_line: end_line.max(start_line),
874                    content: chunk_text,
875                    tokens: Vec::new(),
876                    token_count,
877                });
878            }
879        } else {
880            let token_count = tokenize(content).len();
881            let snippet = lines
882                .iter()
883                .take(50)
884                .copied()
885                .collect::<Vec<_>>()
886                .join("\n");
887            chunks.push(CodeChunk {
888                file_path: file_path.to_string(),
889                symbol_name: file_path.to_string(),
890                kind: ChunkKind::Module,
891                start_line: 1,
892                end_line: lines.len(),
893                content: snippet,
894                tokens: Vec::new(),
895                token_count,
896            });
897        }
898    }
899
900    chunks
901}
902
903fn detect_symbol(line: &str) -> Option<(String, ChunkKind)> {
904    let trimmed = line.trim();
905
906    let patterns: &[(&str, ChunkKind)] = &[
907        ("pub async fn ", ChunkKind::Function),
908        ("async fn ", ChunkKind::Function),
909        ("pub fn ", ChunkKind::Function),
910        ("fn ", ChunkKind::Function),
911        ("pub struct ", ChunkKind::Struct),
912        ("struct ", ChunkKind::Struct),
913        ("pub enum ", ChunkKind::Struct),
914        ("enum ", ChunkKind::Struct),
915        ("impl ", ChunkKind::Impl),
916        ("pub trait ", ChunkKind::Struct),
917        ("trait ", ChunkKind::Struct),
918        ("export function ", ChunkKind::Function),
919        ("export async function ", ChunkKind::Function),
920        ("export default function ", ChunkKind::Function),
921        ("function ", ChunkKind::Function),
922        ("async function ", ChunkKind::Function),
923        ("export class ", ChunkKind::Class),
924        ("class ", ChunkKind::Class),
925        ("export interface ", ChunkKind::Struct),
926        ("interface ", ChunkKind::Struct),
927        ("def ", ChunkKind::Function),
928        ("async def ", ChunkKind::Function),
929        ("class ", ChunkKind::Class),
930        ("func ", ChunkKind::Function),
931    ];
932
933    for (prefix, kind) in patterns {
934        if let Some(rest) = trimmed.strip_prefix(prefix) {
935            let name: String = rest
936                .chars()
937                .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '<')
938                .take_while(|c| *c != '<')
939                .collect();
940            if !name.is_empty() {
941                return Some((name, kind.clone()));
942            }
943        }
944    }
945
946    None
947}
948
949fn find_block_end(lines: &[&str], start: usize) -> usize {
950    let mut depth = 0i32;
951    let mut found_open = false;
952
953    for (i, line) in lines.iter().enumerate().skip(start) {
954        for ch in line.chars() {
955            match ch {
956                '{' | '(' if !found_open || depth > 0 => {
957                    depth += 1;
958                    found_open = true;
959                }
960                '}' | ')' if depth > 0 => {
961                    depth -= 1;
962                    if depth == 0 && found_open {
963                        return i;
964                    }
965                }
966                _ => {}
967            }
968        }
969
970        if found_open && depth <= 0 && i > start {
971            return i;
972        }
973
974        if !found_open && i > start + 2 {
975            let trimmed = lines[i].trim();
976            if trimmed.is_empty()
977                || (!trimmed.starts_with(' ') && !trimmed.starts_with('\t') && i > start)
978            {
979                return i.saturating_sub(1);
980            }
981        }
982    }
983
984    (start + 50).min(lines.len().saturating_sub(1))
985}
986
987pub fn format_search_results(results: &[SearchResult], compact: bool) -> String {
988    if results.is_empty() {
989        return "No results found.".to_string();
990    }
991
992    let mut out = String::new();
993    for (i, r) in results.iter().enumerate() {
994        if compact {
995            out.push_str(&format!(
996                "{}. {:.2} {}:{}-{} {:?} {}\n",
997                i + 1,
998                r.score,
999                r.file_path,
1000                r.start_line,
1001                r.end_line,
1002                r.kind,
1003                r.symbol_name,
1004            ));
1005        } else {
1006            out.push_str(&format!(
1007                "\n--- Result {} (score: {:.2}) ---\n{} :: {} [{:?}] (L{}-{})\n{}\n",
1008                i + 1,
1009                r.score,
1010                r.file_path,
1011                r.symbol_name,
1012                r.kind,
1013                r.start_line,
1014                r.end_line,
1015                r.snippet,
1016            ));
1017        }
1018    }
1019    out
1020}
1021
1022/// Enrich chunk content with file-path components for BM25 path-matching.
1023///
1024/// SACL (EMNLP 2025) shows that augmenting code with structural information
1025/// improves retrieval by 7-12.8%. We append the file stem twice (for boost)
1026/// and the immediate parent directory once, enabling queries like "auth handler"
1027/// to match `src/auth/handler.rs`.
1028fn enrich_for_bm25(chunk: &CodeChunk) -> String {
1029    let path = Path::new(&chunk.file_path);
1030    let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
1031    let dir = path
1032        .parent()
1033        .and_then(|p| p.file_name())
1034        .and_then(|d| d.to_str())
1035        .unwrap_or("");
1036
1037    if stem.is_empty() {
1038        return chunk.content.clone();
1039    }
1040
1041    format!("{} {} {} {}", chunk.content, stem, stem, dir)
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046    use super::*;
1047    use tempfile::tempdir;
1048
1049    #[cfg(unix)]
1050    use std::os::unix::fs::PermissionsExt;
1051
1052    #[test]
1053    fn tokenize_splits_code() {
1054        let tokens = tokenize("fn calculate_total(items: Vec<Item>) -> f64");
1055        assert!(tokens.contains(&"calculate_total".to_string()));
1056        assert!(tokens.contains(&"items".to_string()));
1057        assert!(tokens.contains(&"Vec".to_string()));
1058    }
1059
1060    #[test]
1061    fn camel_case_splitting() {
1062        let tokens = split_camel_case_tokens(&["calculateTotal".to_string()]);
1063        assert!(tokens.contains(&"calculateTotal".to_string()));
1064        assert!(tokens.contains(&"calculate".to_string()));
1065        assert!(tokens.contains(&"Total".to_string()));
1066    }
1067
1068    #[test]
1069    fn detect_rust_function() {
1070        let (name, kind) =
1071            detect_symbol("pub fn process_request(req: Request) -> Response {").unwrap();
1072        assert_eq!(name, "process_request");
1073        assert_eq!(kind, ChunkKind::Function);
1074    }
1075
1076    #[test]
1077    fn bm25_search_finds_relevant() {
1078        let mut index = BM25Index::new();
1079        index.add_chunk(CodeChunk {
1080            file_path: "auth.rs".into(),
1081            symbol_name: "validate_token".into(),
1082            kind: ChunkKind::Function,
1083            start_line: 1,
1084            end_line: 10,
1085            content: "fn validate_token(token: &str) -> bool { check_jwt_expiry(token) }".into(),
1086            tokens: tokenize("fn validate_token token str bool check_jwt_expiry token"),
1087            token_count: 8,
1088        });
1089        index.add_chunk(CodeChunk {
1090            file_path: "db.rs".into(),
1091            symbol_name: "connect_database".into(),
1092            kind: ChunkKind::Function,
1093            start_line: 1,
1094            end_line: 5,
1095            content: "fn connect_database(url: &str) -> Pool { create_pool(url) }".into(),
1096            tokens: tokenize("fn connect_database url str Pool create_pool url"),
1097            token_count: 7,
1098        });
1099        index.finalize();
1100
1101        let results = index.search("jwt token validation", 5);
1102        assert!(!results.is_empty());
1103        assert_eq!(results[0].symbol_name, "validate_token");
1104    }
1105
1106    #[test]
1107    fn bm25_search_sorts_ties_deterministically() {
1108        let mut index = BM25Index::new();
1109
1110        // Insert in reverse path order to ensure the sort tie-break matters.
1111        index.add_chunk(CodeChunk {
1112            file_path: "b.rs".into(),
1113            symbol_name: "same".into(),
1114            kind: ChunkKind::Function,
1115            start_line: 1,
1116            end_line: 1,
1117            content: "fn same() {}".into(),
1118            tokens: tokenize("same token"),
1119            token_count: 2,
1120        });
1121        index.add_chunk(CodeChunk {
1122            file_path: "a.rs".into(),
1123            symbol_name: "same".into(),
1124            kind: ChunkKind::Function,
1125            start_line: 1,
1126            end_line: 1,
1127            content: "fn same() {}".into(),
1128            tokens: tokenize("same token"),
1129            token_count: 2,
1130        });
1131        index.finalize();
1132
1133        let results = index.search("same", 10);
1134        assert!(results.len() >= 2);
1135        assert_eq!(results[0].file_path, "a.rs");
1136        assert_eq!(results[1].file_path, "b.rs");
1137    }
1138
1139    #[test]
1140    fn bm25_index_is_stale_when_any_indexed_file_is_missing() {
1141        let td = tempdir().expect("tempdir");
1142        let root = td.path();
1143        std::fs::write(root.join("a.rs"), "pub fn a() {}\n").expect("write a.rs");
1144
1145        let idx = BM25Index::build_from_directory(root);
1146        assert!(!bm25_index_looks_stale(&idx, root));
1147
1148        std::fs::remove_file(root.join("a.rs")).expect("remove a.rs");
1149        assert!(bm25_index_looks_stale(&idx, root));
1150    }
1151
1152    #[test]
1153    #[cfg(unix)]
1154    fn bm25_incremental_rebuild_reuses_unchanged_files_without_reading() {
1155        let td = tempdir().expect("tempdir");
1156        let root = td.path();
1157
1158        std::fs::write(root.join("a.rs"), "pub fn a() { println!(\"A\"); }\n").expect("write a.rs");
1159        std::fs::write(root.join("b.rs"), "pub fn b() { println!(\"B\"); }\n").expect("write b.rs");
1160
1161        let idx1 = BM25Index::build_from_directory(root);
1162        assert!(idx1.files.contains_key("a.rs"));
1163        assert!(idx1.files.contains_key("b.rs"));
1164
1165        // Make a.rs unreadable. Incremental rebuild must keep it indexed by reusing prior chunks.
1166        let a_path = root.join("a.rs");
1167        let mut perms = std::fs::metadata(&a_path).expect("meta a.rs").permissions();
1168        perms.set_mode(0o000);
1169        std::fs::set_permissions(&a_path, perms).expect("chmod a.rs");
1170
1171        // Change b.rs (size changes) to force a re-read for that file.
1172        std::fs::write(root.join("b.rs"), "pub fn b() { println!(\"B2\"); }\n")
1173            .expect("rewrite b.rs");
1174
1175        let idx2 = BM25Index::rebuild_incremental(root, &idx1);
1176        assert!(
1177            idx2.files.contains_key("a.rs"),
1178            "a.rs should be kept via reuse"
1179        );
1180        assert!(idx2.files.contains_key("b.rs"));
1181
1182        let b_has_b2 = idx2
1183            .chunks
1184            .iter()
1185            .any(|c| c.file_path == "b.rs" && c.content.contains("B2"));
1186        assert!(b_has_b2, "b.rs should be re-read and re-chunked");
1187
1188        // Restore permissions to avoid cleanup surprises.
1189        let mut perms = std::fs::metadata(&a_path).expect("meta a.rs").permissions();
1190        perms.set_mode(0o644);
1191        let _ = std::fs::set_permissions(&a_path, perms);
1192    }
1193
1194    #[test]
1195    fn load_quarantines_oversized_index() {
1196        let _env = crate::core::data_dir::test_env_lock();
1197        let td = tempdir().expect("tempdir");
1198        let root = td.path();
1199        let dir = crate::core::index_namespace::vectors_dir(root);
1200        std::fs::create_dir_all(&dir).expect("create vectors dir");
1201
1202        let index_path = dir.join("bm25_index.json");
1203        std::env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "0");
1204        std::fs::write(&index_path, r#"{"chunks":[]}"#).expect("write index");
1205
1206        let result = BM25Index::load(root);
1207        assert!(result.is_none(), "oversized index should return None");
1208        assert!(
1209            !index_path.exists(),
1210            "original index should be removed after quarantine"
1211        );
1212        assert!(
1213            dir.join("bm25_index.json.quarantined").exists(),
1214            "quarantined file should exist"
1215        );
1216
1217        std::env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
1218    }
1219
1220    #[test]
1221    fn save_refuses_oversized_output() {
1222        let _env = crate::core::data_dir::test_env_lock();
1223        let data_dir = tempdir().expect("data_dir");
1224        std::env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
1225        std::env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "0");
1226
1227        let td = tempdir().expect("tempdir");
1228        let root = td.path();
1229
1230        let mut index = BM25Index::new();
1231        index.add_chunk(CodeChunk {
1232            file_path: "a.rs".into(),
1233            symbol_name: "a".into(),
1234            kind: ChunkKind::Function,
1235            start_line: 1,
1236            end_line: 1,
1237            content: "fn a() {}".into(),
1238            tokens: tokenize("fn a"),
1239            token_count: 2,
1240        });
1241        index.finalize();
1242
1243        let _ = index.save(root);
1244        let index_path = BM25Index::index_file_path(root);
1245        assert!(
1246            !index_path.exists(),
1247            "save should refuse to persist oversized index"
1248        );
1249
1250        std::env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
1251    }
1252
1253    #[test]
1254    fn save_writes_project_root_marker() {
1255        let _env = crate::core::data_dir::test_env_lock();
1256        let td = tempdir().expect("tempdir");
1257        let root = td.path();
1258        std::fs::write(root.join("a.rs"), "pub fn a() {}\n").expect("write");
1259
1260        std::env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
1261        let index = BM25Index::build_from_directory(root);
1262        index.save(root).expect("save");
1263
1264        let dir = crate::core::index_namespace::vectors_dir(root);
1265        let marker = dir.join("project_root.txt");
1266        assert!(marker.exists(), "project_root.txt marker should exist");
1267        let content = std::fs::read_to_string(&marker).expect("read marker");
1268        assert_eq!(content, root.to_string_lossy());
1269    }
1270
1271    #[test]
1272    fn save_load_roundtrip_uses_zstd() {
1273        let _env = crate::core::data_dir::test_env_lock();
1274        let data_dir = tempdir().expect("data_dir");
1275        std::env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
1276        std::env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "512");
1277        let td = tempdir().expect("tempdir");
1278        let root = td.path();
1279
1280        for i in 0..10 {
1281            std::fs::write(
1282                root.join(format!("mod{i}.rs")),
1283                format!(
1284                    "pub fn handler_{i}() {{\n    println!(\"hello\");\n}}\n\n\
1285                     pub fn helper_{i}() {{\n    println!(\"world\");\n}}\n"
1286                ),
1287            )
1288            .expect("write");
1289        }
1290
1291        let index = BM25Index::build_from_directory(root);
1292        assert!(index.doc_count > 0, "should have indexed chunks");
1293        index.save(root).expect("save");
1294
1295        let dir = crate::core::index_namespace::vectors_dir(root);
1296        let zst = dir.join("bm25_index.bin.zst");
1297        assert!(zst.exists(), "should write .bin.zst");
1298        assert!(
1299            !dir.join("bm25_index.bin").exists(),
1300            ".bin should be deleted"
1301        );
1302
1303        let loaded = BM25Index::load(root).expect("load compressed index");
1304        assert_eq!(loaded.doc_count, index.doc_count);
1305        assert_eq!(loaded.chunks.len(), index.chunks.len());
1306
1307        std::env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
1308        std::env::remove_var("LEAN_CTX_DATA_DIR");
1309    }
1310
1311    #[test]
1312    fn auto_migrate_bin_to_zst() {
1313        let _env = crate::core::data_dir::test_env_lock();
1314        let data_dir = tempdir().expect("data_dir");
1315        std::env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
1316        std::env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "512");
1317        let td = tempdir().expect("tempdir");
1318        let root = td.path();
1319
1320        std::fs::write(root.join("a.rs"), "pub fn a() {}\n").expect("write");
1321        let index = BM25Index::build_from_directory(root);
1322
1323        let dir = crate::core::index_namespace::vectors_dir(root);
1324        std::fs::create_dir_all(&dir).expect("mkdir");
1325        let data =
1326            bincode::serde::encode_to_vec(&index, bincode::config::standard()).expect("encode");
1327        std::fs::write(dir.join("bm25_index.bin"), &data).expect("write bin");
1328
1329        let loaded = BM25Index::load(root).expect("load should auto-migrate");
1330        assert_eq!(loaded.doc_count, index.doc_count);
1331        assert!(
1332            dir.join("bm25_index.bin.zst").exists(),
1333            ".bin.zst should be created"
1334        );
1335        assert!(
1336            !dir.join("bm25_index.bin").exists(),
1337            ".bin should be removed"
1338        );
1339
1340        std::env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
1341        std::env::remove_var("LEAN_CTX_DATA_DIR");
1342    }
1343
1344    #[test]
1345    fn list_code_files_skips_default_vendor_ignores() {
1346        let td = tempdir().expect("tempdir");
1347        let root = td.path();
1348
1349        std::fs::write(root.join("main.rs"), "pub fn main() {}\n").expect("write main");
1350        std::fs::create_dir_all(root.join("vendor/lib")).expect("mkdir vendor");
1351        std::fs::write(root.join("vendor/lib/dep.rs"), "pub fn dep() {}\n").expect("write vendor");
1352        std::fs::create_dir_all(root.join("dist")).expect("mkdir dist");
1353        std::fs::write(root.join("dist/bundle.js"), "function x() {}").expect("write dist");
1354
1355        let files = list_code_files(root);
1356        assert!(
1357            files.iter().any(|f| f == "main.rs"),
1358            "main.rs should be included"
1359        );
1360        assert!(
1361            !files.iter().any(|f| f.starts_with("vendor/")),
1362            "vendor/ files should be excluded by DEFAULT_BM25_IGNORES"
1363        );
1364        assert!(
1365            !files.iter().any(|f| f.starts_with("dist/")),
1366            "dist/ files should be excluded by DEFAULT_BM25_IGNORES"
1367        );
1368    }
1369
1370    #[test]
1371    fn list_code_files_respects_max_files_cap() {
1372        let td = tempdir().expect("tempdir");
1373        let root = td.path();
1374
1375        // Create more files than MAX_BM25_FILES wouldn't let us test easily (5000),
1376        // but we can verify the cap constant exists and the function returns a bounded vec.
1377        for i in 0..10 {
1378            std::fs::write(
1379                root.join(format!("f{i}.rs")),
1380                format!("pub fn f{i}() {{}}\n"),
1381            )
1382            .expect("write");
1383        }
1384        let files = list_code_files(root);
1385        assert!(
1386            files.len() <= MAX_BM25_FILES,
1387            "file count should not exceed MAX_BM25_FILES"
1388        );
1389    }
1390
1391    #[test]
1392    fn max_bm25_cache_bytes_reads_env() {
1393        let _env = crate::core::data_dir::test_env_lock();
1394        std::env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "64");
1395        let bytes = max_bm25_cache_bytes();
1396        assert_eq!(bytes, 64 * 1024 * 1024);
1397        std::env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
1398    }
1399}