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