Skip to main content

lean_ctx/core/bm25_index/
mod.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::time::UNIX_EPOCH;
4
5use serde::{Deserialize, Serialize};
6mod build;
7mod chunking;
8pub use chunking::*;
9mod coordinator;
10pub(crate) mod coverage;
11pub use coordinator::{SearchIndexBuildProgress, get_or_start_build};
12#[cfg(test)]
13mod tests;
14
15pub(crate) const MAX_BM25_FILES: usize = 5000;
16const CHUNK_COUNT_WARNING: usize = 50_000;
17const ZSTD_LEVEL: i32 = 9;
18
19const DEFAULT_BM25_IGNORES: &[&str] = &[
20    "vendor/**",
21    "dist/**",
22    "build/**",
23    "public/vendor/**",
24    "public/js/**",
25    "public/css/**",
26    "public/build/**",
27    ".next/**",
28    ".nuxt/**",
29    "__pycache__/**",
30    "*.min.js",
31    "*.min.css",
32    "*.bundle.js",
33    "*.chunk.js",
34];
35
36fn max_bm25_cache_bytes() -> u64 {
37    // Single source of truth: `Config::bm25_max_cache_mb_effective` (env override
38    // › explicit config › disk-budget › generous default). Decoupled from the RAM
39    // profile so large repos persist instead of rebuilding forever (issue #249).
40    let mb = std::env::var("LEAN_CTX_BM25_MAX_CACHE_MB")
41        .ok()
42        .and_then(|v| v.parse::<u64>().ok())
43        .unwrap_or_else(|| crate::core::config::Config::load().bm25_max_cache_mb_effective());
44    mb * 1024 * 1024
45}
46
47/// Effective on-disk ceiling (bytes) for the persisted BM25 index. Single source
48/// of truth shared with `doctor` so its "oversized index" warning matches what
49/// `save`/`load` actually enforce.
50pub fn persist_ceiling_bytes() -> u64 {
51    max_bm25_cache_bytes()
52}
53
54/// Outcome of persisting a BM25 index to disk. Distinguishes a real write from a
55/// size-capped refusal so callers never mistake "refused to persist" for
56/// success (the bug behind the perpetual "index warming" report, issue #249).
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum SaveOutcome {
59    /// Written to disk. Carries the compressed (zstd) size in bytes.
60    Persisted { compressed_bytes: u64 },
61    /// Built fine but NOT written — the compressed size exceeds the disk
62    /// ceiling. The in-memory index is still usable for this process; callers
63    /// should surface the remedy (raise the cap / add ignore patterns) instead
64    /// of silently rebuilding on every call.
65    SkippedTooLarge {
66        compressed_bytes: u64,
67        limit_bytes: u64,
68    },
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
72pub struct CodeChunk {
73    pub file_path: String,
74    pub symbol_name: String,
75    pub kind: ChunkKind,
76    pub start_line: usize,
77    pub end_line: usize,
78    pub content: String,
79    #[serde(default)]
80    pub tokens: Vec<String>,
81    pub token_count: usize,
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
85pub enum ChunkKind {
86    Function,
87    Struct,
88    Impl,
89    Module,
90    Class,
91    Method,
92    Other,
93    // -- External source kinds (Context Engine) --
94    Issue,
95    PullRequest,
96    WikiPage,
97    DbSchema,
98    ApiEndpoint,
99    Ticket,
100    ExternalOther,
101}
102
103#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
104pub struct IndexedFileState {
105    pub mtime_ms: u64,
106    pub size_bytes: u64,
107}
108
109impl IndexedFileState {
110    fn from_path(path: &Path) -> Option<Self> {
111        let meta = path.metadata().ok()?;
112        let size_bytes = meta.len();
113        let mtime_ms = meta
114            .modified()
115            .ok()
116            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
117            .map(|d| d.as_millis() as u64)?;
118        Some(Self {
119            mtime_ms,
120            size_bytes,
121        })
122    }
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct BM25Index {
127    pub chunks: Vec<CodeChunk>,
128    pub inverted: HashMap<String, Vec<(usize, f64)>>,
129    pub avg_doc_len: f64,
130    pub doc_count: usize,
131    pub doc_freqs: HashMap<String, usize>,
132    #[serde(default)]
133    pub files: HashMap<String, IndexedFileState>,
134    /// Content fingerprint of every directory that contained an indexed file
135    /// when this index was built, keyed by root-relative path (`""` = the root
136    /// itself). Sampling tracked *files* can never reveal a file that was never
137    /// indexed, so the fast staleness check would keep serving a partial index
138    /// forever after new files appear (#1724). Creating or removing an entry
139    /// bumps its parent directory's mtime on every filesystem we support, so
140    /// comparing this snapshot detects added/deleted files in one stat per
141    /// directory instead of a full ingest walk.
142    #[serde(default)]
143    pub dirs: HashMap<String, u64>,
144    /// Digest of the Context Gateway policy the chunk contents were admitted
145    /// under. An index built under another policy (or before admission
146    /// existed — its postcard layout lacks this field and no longer loads) is
147    /// rebuilt in full, never reused (G5, E3).
148    #[serde(default)]
149    pub admission_policy: Option<String>,
150    /// True once `shrink_resident_content_to_snippet` has trimmed each chunk's
151    /// `content` down to the snippet lines. Resident-only RAM-saving state: never
152    /// persisted (`skip`) so the on-disk index keeps full content, and a reload
153    /// always starts as `false`. Guards the embedding pass against re-embedding
154    /// truncated bodies (see `ensure_embeddings`).
155    #[serde(default, skip)]
156    pub content_truncated: bool,
157}
158
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct SearchResult {
161    pub chunk_idx: usize,
162    pub score: f64,
163    pub file_path: String,
164    pub symbol_name: String,
165    pub kind: ChunkKind,
166    pub start_line: usize,
167    pub end_line: usize,
168    pub snippet: String,
169}
170
171const BM25_K1: f64 = 1.2;
172const BM25_B: f64 = 0.75;
173
174fn structural_query_boost(query: &str, chunk: &CodeChunk) -> f64 {
175    let raw_terms: std::collections::HashSet<String> = query
176        .split(|c: char| !(c.is_alphanumeric() || c == '_'))
177        .filter(|term| term.len() >= 3)
178        .map(str::to_ascii_lowercase)
179        .collect();
180    let path_terms: std::collections::HashSet<String> = tokenize(&chunk.file_path)
181        .into_iter()
182        .map(|term| term.to_ascii_lowercase())
183        .collect();
184
185    let mut boost = 0.0;
186    if raw_terms.contains(&chunk.symbol_name.to_ascii_lowercase()) {
187        boost += 32.0;
188    }
189    boost += raw_terms.intersection(&path_terms).count() as f64 * 8.0;
190
191    let has_identifier = query.split_whitespace().any(|term| {
192        let has_lower = term.chars().any(char::is_lowercase);
193        let has_upper = term.chars().any(char::is_uppercase);
194        (has_lower && has_upper) || term.contains('_') || term.contains('.')
195    });
196    if has_identifier {
197        let extension = std::path::Path::new(&chunk.file_path)
198            .extension()
199            .and_then(std::ffi::OsStr::to_str)
200            .unwrap_or_default()
201            .to_ascii_lowercase();
202        if matches!(extension.as_str(), "md" | "mdx" | "rst" | "txt" | "adoc") {
203            boost -= 8.0;
204        } else if !extension.is_empty() {
205            boost += 4.0;
206        }
207    }
208    boost
209}
210
211impl Default for BM25Index {
212    fn default() -> Self {
213        Self::new()
214    }
215}
216
217impl BM25Index {
218    pub fn new() -> Self {
219        Self {
220            chunks: Vec::new(),
221            inverted: HashMap::new(),
222            avg_doc_len: 0.0,
223            doc_count: 0,
224            doc_freqs: HashMap::new(),
225            files: HashMap::new(),
226            dirs: HashMap::new(),
227            admission_policy: None,
228            content_truncated: false,
229        }
230    }
231
232    /// Approximate heap memory used by this index in bytes.
233    pub fn memory_usage_bytes(&self) -> usize {
234        let chunks_size: usize = self
235            .chunks
236            .iter()
237            .map(|c| {
238                c.content.len()
239                    + c.file_path.len()
240                    + c.symbol_name.len()
241                    + c.tokens.iter().map(String::len).sum::<usize>()
242                    + 64
243            })
244            .sum();
245        let inverted_size: usize = self
246            .inverted
247            .iter()
248            .map(|(k, v)| k.len() + v.len() * 16 + 32)
249            .sum();
250        let files_size: usize = self.files.keys().map(|k| k.len() + 24).sum();
251        let dirs_size: usize = self.dirs.keys().map(|k| k.len() + 16).sum();
252        let freqs_size: usize = self.doc_freqs.keys().map(|k| k.len() + 16).sum();
253        chunks_size + inverted_size + files_size + dirs_size + freqs_size
254    }
255
256    /// Drops all in-memory data, effectively freeing heap. Index can be re-loaded from disk.
257    pub fn unload(&mut self) {
258        let usage = self.memory_usage_bytes();
259        self.chunks = Vec::new();
260        self.inverted = HashMap::new();
261        self.doc_freqs = HashMap::new();
262        self.files = HashMap::new();
263        self.dirs = HashMap::new();
264        self.avg_doc_len = 0.0;
265        self.doc_count = 0;
266        tracing::info!(
267            "[bm25] unloaded index, freed ~{:.1}MB",
268            usage as f64 / 1_048_576.0
269        );
270    }
271
272    /// Shrinks each resident chunk's `content` to its first `keep_lines` lines,
273    /// reclaiming the RAM held by the full source bodies once the embedding pass
274    /// has already consumed them. Query previews can only select lines still
275    /// resident, so this trades preview coverage for memory in cached indexes.
276    /// Fresh admitted retrieval views retain their separately budgeted content.
277    ///
278    /// Further shrinks resident content (chunks are already truncated to 10 lines
279    /// during `add_chunk`; this method can tighten that further). Sets
280    /// `content_truncated` so a later `ensure_embeddings` against this same
281    /// resident index skips re-embedding (which would otherwise feed truncated
282    /// bodies to the embedder).
283    ///
284    /// Idempotent and only ever shrinks: chunks shorter than `keep_lines` are
285    /// left untouched.
286    pub fn shrink_resident_content_to_snippet(&mut self, keep_lines: usize) {
287        let before = self.memory_usage_bytes();
288        for chunk in &mut self.chunks {
289            // Cheap line-count gate: only allocate a new string when the body is
290            // actually longer than the snippet window.
291            if chunk.content.lines().nth(keep_lines).is_some() {
292                let trimmed: String = chunk
293                    .content
294                    .lines()
295                    .take(keep_lines)
296                    .collect::<Vec<_>>()
297                    .join("\n");
298                chunk.content = trimmed;
299                // Reclaim the spare capacity left by the larger original body.
300                chunk.content.shrink_to_fit();
301            }
302        }
303        self.content_truncated = true;
304        let after = self.memory_usage_bytes();
305        tracing::debug!(
306            "[bm25] shrank resident content to {keep_lines} lines/chunk, freed ~{:.1}MB",
307            before.saturating_sub(after) as f64 / 1_048_576.0
308        );
309    }
310
311    /// Builds an index from explicit chunks (unit tests; avoids filesystem walking).
312    #[cfg(test)]
313    pub(crate) fn from_chunks_for_test(chunks: Vec<CodeChunk>) -> Self {
314        let mut index = Self::new();
315        for mut chunk in chunks {
316            if chunk.token_count == 0 {
317                chunk.token_count = tokenize(&chunk.content).len();
318            }
319            index.add_chunk(chunk);
320        }
321        index.finalize();
322        index
323    }
324
325    pub fn build_from_directory(root: &Path) -> Self {
326        Self::build_from_directory_inner(root, &HashMap::new())
327    }
328
329    /// Ephemeral retrieval view: admit each complete original source before
330    /// tokenization. Never consult metadata-only caches or persist this view.
331    pub(crate) fn build_from_admitted_sources(
332        root: &Path,
333        mut admit: impl FnMut(&str) -> Result<Option<String>, String>,
334    ) -> Result<Self, String> {
335        if !is_safe_bm25_root(root) {
336            return Err("source root is not safe to scan".into());
337        }
338        let mut index = Self::new();
339        let mut chunk_bytes = 64 * 1024 * 1024;
340        let mut chunk_count = 100_000;
341        for path in list_code_files_inner(root, true)? {
342            if crate::core::memory_guard::abort_requested()
343                || crate::core::memory_guard::is_under_pressure()
344            {
345                return Err("source search withheld under memory pressure".into());
346            }
347            let Some(content) = admit(&path)? else {
348                continue;
349            };
350            if looks_minified(&content) {
351                continue;
352            }
353            let allowance = chunk_bytes.min(content.len().saturating_mul(5).max(64 * 1024));
354            if !crate::core::index_admission::admit(
355                crate::core::index_admission::BuildKind::Bm25,
356                allowance as u64,
357            )
358            .parallel_ok
359            {
360                return Err("source search exceeds available memory headroom".into());
361            }
362            let mut file_chunk_bytes = allowance;
363            let count_allowance = chunk_count.min(4096);
364            let mut file_chunk_count = count_allowance;
365            let mut chunks = extract_admitted_chunks(
366                &path,
367                &content,
368                &mut file_chunk_bytes,
369                &mut file_chunk_count,
370            )?;
371            chunk_bytes -= allowance - file_chunk_bytes;
372            chunk_count -= count_allowance - file_chunk_count;
373            chunks.sort_by(|a, b| {
374                (a.start_line, a.end_line, &a.symbol_name).cmp(&(
375                    b.start_line,
376                    b.end_line,
377                    &b.symbol_name,
378                ))
379            });
380            for chunk in chunks {
381                if crate::core::memory_guard::abort_requested()
382                    || crate::core::memory_guard::is_under_pressure()
383                {
384                    return Err("source search withheld under memory pressure".into());
385                }
386                // This ephemeral view already charges the full admitted chunk
387                // against its byte budget; retain it for query-centred previews.
388                index.add_chunk_with_content_limit(chunk, None);
389            }
390        }
391        index.finalize();
392        Ok(index)
393    }
394
395    /// Like `build_from_directory` but reuses file content from a prior scan
396    /// (e.g. the graph index walk) to avoid redundant disk reads.
397    pub fn build_with_content_hint(root: &Path, content_hint: &HashMap<String, String>) -> Self {
398        Self::build_from_directory_inner(root, content_hint)
399    }
400
401    fn build_from_directory_inner(root: &Path, content_hint: &HashMap<String, String>) -> Self {
402        let root_str = root.to_string_lossy();
403        if !super::graph_index::is_safe_scan_root_public(&root_str) {
404            tracing::warn!("[bm25: scan aborted for unsafe root {root_str}]");
405            return Self::new();
406        }
407        let files = list_code_files(root);
408        // Snapshot directory mtimes *before* the (slow) chunking pass: a file
409        // that lands while we build then leaves its directory newer than the
410        // snapshot, so the next staleness check sees it instead of silently
411        // pinning the partial tree (#1724).
412        let dirs = dir_states(root, &files);
413        // One policy for the whole build, recorded with the index (G5).
414        let admission = crate::core::context_admission::stores::StoreAdmission::current();
415
416        // #933: parallel fast path for the common case. The per-file parse +
417        // tokenize work is pure and thread-safe, so we fan it across a rayon pool
418        // and merge sequentially in file order — measured 2.85 s → 0.69 s (~4x) on
419        // the lean-ctx repo. Under memory pressure (or for tiny corpora, where pool
420        // setup is not worth it) we fall back to the sequential build, which carries
421        // the incremental early-break. #685 adds admission control: a corpus whose
422        // estimated peak would blow past the guardian's hard threshold degrades to
423        // the sequential build up front instead of OOMing mid-fan-out. Both paths
424        // produce an identical index (see `build` module + determinism tests).
425        if files.len() >= build::PARALLEL_MIN_FILES
426            && !crate::core::memory_guard::is_under_pressure()
427            && !crate::core::memory_guard::abort_requested()
428            && crate::core::index_admission::admit_files(
429                crate::core::index_admission::BuildKind::Bm25,
430                root,
431                &files,
432            )
433            .parallel_ok
434        {
435            let mut index = Self::build_parallel(root, content_hint, &files, &admission);
436            index.dirs = dirs;
437            index.admission_policy = Some(admission.digest().to_owned());
438            return index;
439        }
440        let mut index = Self::build_sequential(root, content_hint, &files, &admission);
441        index.dirs = dirs;
442        index.admission_policy = Some(admission.digest().to_owned());
443        index
444    }
445
446    /// Group a previous index's chunks by file, each file's list sorted by
447    /// (start_line, end_line, symbol_name) — the deterministic reuse order shared
448    /// by both incremental rebuild paths (and the equivalence test, so it feeds
449    /// them identical inputs).
450    fn group_prev_chunks_by_file(prev: &BM25Index) -> HashMap<String, Vec<CodeChunk>> {
451        let mut old_by_file: HashMap<String, Vec<CodeChunk>> = HashMap::new();
452        for c in &prev.chunks {
453            old_by_file
454                .entry(c.file_path.clone())
455                .or_default()
456                .push(c.clone());
457        }
458        for v in old_by_file.values_mut() {
459            v.sort_by(|a, b| {
460                a.start_line
461                    .cmp(&b.start_line)
462                    .then_with(|| a.end_line.cmp(&b.end_line))
463                    .then_with(|| a.symbol_name.cmp(&b.symbol_name))
464            });
465        }
466        old_by_file
467    }
468
469    pub fn rebuild_incremental(root: &Path, prev: &BM25Index) -> Self {
470        // Reused chunks must have been admitted under the current policy.
471        let admission = crate::core::context_admission::stores::StoreAdmission::current();
472        if prev.admission_policy.as_deref() != Some(admission.digest()) {
473            return Self::build_from_directory(root);
474        }
475        let old_by_file = Self::group_prev_chunks_by_file(prev);
476        let files = list_code_files(root);
477        let dirs = dir_states(root, &files);
478
479        // #581: mirror `build()`'s dispatch. The edit loop is the hottest path in
480        // daily use, and its serial cost is dominated by re-tokenizing the *many
481        // unchanged* files' reused chunks — not the few changed ones. So the
482        // parallel path fans the entire tokenization (changed files via
483        // `prepare_file`, unchanged via re-`prepare_chunk`) across the rayon pool
484        // and merges sequentially in file order. The sequential path keeps the
485        // per-file memory-pressure early-break and serves small corpora / pressure.
486        // #685: oversized corpora degrade to sequential via admission control.
487        // Both produce an identical index (see determinism tests).
488        if files.len() >= build::PARALLEL_MIN_FILES
489            && !crate::core::memory_guard::is_under_pressure()
490            && !crate::core::memory_guard::abort_requested()
491            && crate::core::index_admission::admit_files(
492                crate::core::index_admission::BuildKind::Bm25,
493                root,
494                &files,
495            )
496            .parallel_ok
497        {
498            let mut index =
499                Self::rebuild_incremental_parallel(root, prev, &old_by_file, &files, &admission);
500            index.dirs = dirs;
501            index.admission_policy = Some(admission.digest().to_owned());
502            return index;
503        }
504        let mut index =
505            Self::rebuild_incremental_sequential(root, prev, &old_by_file, &files, &admission);
506        index.dirs = dirs;
507        index.admission_policy = Some(admission.digest().to_owned());
508        index
509    }
510
511    /// Sequential incremental rebuild with per-file memory-pressure guards. Reuses
512    /// unchanged files' chunks and re-extracts changed ones. Used for small
513    /// corpora and as the safe fallback under memory pressure.
514    pub(crate) fn rebuild_incremental_sequential(
515        root: &Path,
516        prev: &BM25Index,
517        old_by_file: &HashMap<String, Vec<CodeChunk>>,
518        files: &[String],
519        admission: &crate::core::context_admission::stores::StoreAdmission,
520    ) -> Self {
521        let mut index = Self::new();
522        const MAX_FILE_SIZE_BYTES: u64 = 2 * 1024 * 1024;
523        let root_key = root.to_string_lossy().to_string();
524        let total = files.len() as u64;
525        crate::core::index_progress::report_bm25(&root_key, 0, total);
526
527        for (i, rel) in files.iter().enumerate() {
528            if i.is_multiple_of(16) || i + 1 == files.len() {
529                crate::core::index_progress::report_bm25(&root_key, (i + 1) as u64, total);
530            }
531            if i.is_multiple_of(500) && crate::core::memory_guard::is_under_pressure() {
532                tracing::warn!(
533                    "[bm25: stopping incremental rebuild at file {i}/{} due to memory pressure]",
534                    files.len()
535                );
536                break;
537            }
538
539            let abs = root.join(rel);
540            let Some(state) = IndexedFileState::from_path(&abs) else {
541                continue;
542            };
543
544            let unchanged = prev.files.get(rel).is_some_and(|old| *old == state);
545            if unchanged
546                && let Some(chunks) = old_by_file.get(rel)
547                && chunks.first().is_some_and(|c| !c.content.is_empty())
548            {
549                for chunk in chunks {
550                    index.add_chunk(chunk.clone());
551                }
552                index.files.insert(rel.clone(), state);
553                continue;
554            }
555
556            if state.size_bytes > MAX_FILE_SIZE_BYTES {
557                continue;
558            }
559            let content = if crate::core::extractors::is_binary_document(&abs) {
560                match std::fs::read(&abs) {
561                    Ok(bytes) => crate::core::extractors::extract(&abs, &bytes).text,
562                    Err(_) => continue,
563                }
564            } else {
565                match crate::core::text_decode::read_text(&abs) {
566                    Ok(c) => c,
567                    Err(_) => continue,
568                }
569            };
570            if content.is_empty() {
571                continue;
572            }
573            // Derived store: only admitted text, never restricted (E3).
574            let Some(content) = admission.admit(&content, &abs) else {
575                continue;
576            };
577            // #1739: see `build::prepare_file` — same predicate, same position.
578            if looks_minified(&content) {
579                tracing::debug!("[bm25: skipping minified payload {rel}]");
580                continue;
581            }
582            let mut chunks = extract_chunks(rel, &content);
583            chunks.sort_by(|a, b| {
584                a.start_line
585                    .cmp(&b.start_line)
586                    .then_with(|| a.end_line.cmp(&b.end_line))
587                    .then_with(|| a.symbol_name.cmp(&b.symbol_name))
588            });
589            for chunk in chunks {
590                index.add_chunk(chunk);
591            }
592            index.files.insert(rel.clone(), state);
593        }
594
595        index.finalize();
596        index
597    }
598
599    fn add_chunk(&mut self, chunk: CodeChunk) {
600        self.add_chunk_with_content_limit(chunk, Some(10));
601    }
602
603    fn add_chunk_with_content_limit(&mut self, mut chunk: CodeChunk, keep_lines: Option<usize>) {
604        let idx = self.chunks.len();
605
606        let enriched = enrich_for_bm25(&chunk);
607        let tokens = tokenize(&enriched);
608        for token in &tokens {
609            let lower = token.to_lowercase();
610            let postings = self.inverted.entry(lower.clone()).or_default();
611            if postings.last().map(|(last_idx, _)| *last_idx) != Some(idx) {
612                *self.doc_freqs.entry(lower).or_insert(0) += 1;
613            }
614            postings.push((idx, 1.0));
615        }
616
617        // #790: truncate content to snippet AFTER tokenization — full text was
618        // used for BM25 scoring above; stored content is only for result display.
619        if let Some(keep_lines) = keep_lines.filter(|&n| chunk.content.lines().nth(n).is_some()) {
620            chunk.content = chunk
621                .content
622                .lines()
623                .take(keep_lines)
624                .collect::<Vec<_>>()
625                .join("\n");
626            chunk.content.shrink_to_fit();
627        }
628
629        self.chunks.push(CodeChunk {
630            token_count: tokens.len(),
631            tokens: Vec::new(),
632            ..chunk
633        });
634    }
635
636    fn finalize(&mut self) {
637        self.doc_count = self.chunks.len();
638        if self.doc_count == 0 {
639            return;
640        }
641
642        let total_len: usize = self.chunks.iter().map(|c| c.token_count).sum();
643        self.avg_doc_len = total_len as f64 / self.doc_count as f64;
644    }
645
646    pub fn search(&self, query: &str, top_k: usize) -> Vec<SearchResult> {
647        let query_tokens = tokenize(query);
648        if query_tokens.is_empty() || self.doc_count == 0 {
649            return Vec::new();
650        }
651
652        // Pre-allocated score array: O(1) per-access vs HashMap overhead.
653        // Kolmogorov-optimal: minimal allocation for the scoring operation.
654        let n = self.chunks.len();
655        let mut scores = vec![0.0f64; n];
656        let mut touched = Vec::with_capacity(n.min(256));
657
658        for token in &query_tokens {
659            let lower = token.to_lowercase();
660            let df = *self.doc_freqs.get(&lower).unwrap_or(&0) as f64;
661            if df == 0.0 {
662                continue;
663            }
664
665            let idf = ((self.doc_count as f64 - df + 0.5) / (df + 0.5) + 1.0).ln();
666
667            if let Some(postings) = self.inverted.get(&lower) {
668                for &(idx, weight) in postings {
669                    let doc_len = self.chunks[idx].token_count as f64;
670                    let norm_len = doc_len / self.avg_doc_len.max(1.0);
671                    let bm25 = idf * (weight * (BM25_K1 + 1.0))
672                        / (weight + BM25_K1 * (1.0 - BM25_B + BM25_B * norm_len));
673
674                    if scores[idx] == 0.0 {
675                        touched.push(idx);
676                    }
677                    scores[idx] += bm25;
678                }
679            }
680        }
681
682        for &idx in &touched {
683            scores[idx] += structural_query_boost(query, &self.chunks[idx]);
684        }
685
686        let mut results: Vec<SearchResult> = touched
687            .iter()
688            .filter(|&&idx| scores[idx] > 0.0)
689            .map(|&idx| {
690                let chunk = &self.chunks[idx];
691                let snippet = query_snippet(&chunk.content, &query_tokens);
692                SearchResult {
693                    chunk_idx: idx,
694                    score: scores[idx],
695                    file_path: chunk.file_path.clone(),
696                    symbol_name: chunk.symbol_name.clone(),
697                    kind: chunk.kind.clone(),
698                    start_line: chunk.start_line,
699                    end_line: chunk.end_line,
700                    snippet,
701                }
702            })
703            .collect();
704
705        results.sort_by(|a, b| {
706            b.score
707                .partial_cmp(&a.score)
708                .unwrap_or(std::cmp::Ordering::Equal)
709                .then_with(|| a.file_path.cmp(&b.file_path))
710                .then_with(|| a.symbol_name.cmp(&b.symbol_name))
711                .then_with(|| a.start_line.cmp(&b.start_line))
712                .then_with(|| a.end_line.cmp(&b.end_line))
713        });
714        results.truncate(top_k);
715        results
716    }
717
718    pub fn save(&self, root: &Path) -> std::io::Result<SaveOutcome> {
719        if self.chunks.len() > CHUNK_COUNT_WARNING {
720            tracing::warn!(
721                "[bm25] index has {} chunks (threshold {}), consider adding extra_ignore_patterns",
722                self.chunks.len(),
723                CHUNK_COUNT_WARNING
724            );
725        }
726
727        let dir = index_dir(root);
728        std::fs::create_dir_all(&dir)?;
729
730        // #790: stream postcard → zstd → file to avoid holding the full
731        // serialized buffer in memory. Temp-file + rename for atomicity.
732        let target = dir.join("bm25_index.bin.zst");
733        let tmp = dir.join("bm25_index.bin.zst.tmp");
734        {
735            let file = std::fs::File::create(&tmp)?;
736            let buf_writer = std::io::BufWriter::new(file);
737            let mut encoder = zstd::Encoder::new(buf_writer, ZSTD_LEVEL)
738                .map_err(|e| std::io::Error::other(format!("zstd encoder init: {e}")))?;
739            postcard::to_io(self, &mut encoder)
740                .map_err(|e| std::io::Error::other(e.to_string()))?;
741            encoder.finish()?;
742        }
743
744        let compressed_bytes = std::fs::metadata(&tmp)?.len();
745        let max_bytes = max_bm25_cache_bytes();
746        if compressed_bytes > max_bytes {
747            let _ = std::fs::remove_file(&tmp);
748            tracing::warn!(
749                "[bm25] compressed index too large ({:.1} MB, limit {:.0} MB), refusing to persist: {}",
750                compressed_bytes as f64 / 1_048_576.0,
751                max_bytes / (1024 * 1024),
752                dir.display()
753            );
754            return Ok(SaveOutcome::SkippedTooLarge {
755                compressed_bytes,
756                limit_bytes: max_bytes,
757            });
758        }
759
760        tracing::info!(
761            "[bm25] index: {:.1} MB zstd compressed",
762            compressed_bytes as f64 / 1_048_576.0,
763        );
764
765        std::fs::rename(&tmp, &target)?;
766
767        let _ = std::fs::remove_file(dir.join("bm25_index.bin"));
768        let _ = std::fs::remove_file(dir.join("bm25_index.json"));
769
770        let _ = std::fs::write(
771            dir.join("project_root.txt"),
772            root.to_string_lossy().as_bytes(),
773        );
774
775        Ok(SaveOutcome::Persisted { compressed_bytes })
776    }
777
778    /// The persisted index, only when it was admitted under the current
779    /// admission policy: chunks admitted under another policy (or a legacy
780    /// index built from raw sources) are never served or reused (G5, E3).
781    pub fn load(root: &Path) -> Option<Self> {
782        let admission = crate::core::context_admission::stores::StoreAdmission::current();
783        Self::load_persisted(root)
784            .filter(|idx| idx.admission_policy.as_deref() == Some(admission.digest()))
785    }
786
787    fn load_persisted(root: &Path) -> Option<Self> {
788        let dir = index_dir(root);
789        let max_bytes = max_bm25_cache_bytes();
790
791        let zst_path = dir.join("bm25_index.bin.zst");
792        if zst_path.exists() {
793            let meta = std::fs::metadata(&zst_path).ok()?;
794            if meta.len() > max_bytes {
795                tracing::warn!(
796                    "[bm25] compressed index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
797                    meta.len() as f64 / 1_073_741_824.0,
798                    max_bytes / (1024 * 1024),
799                    zst_path.display()
800                );
801                let quarantined = zst_path.with_extension("zst.quarantined");
802                let _ = std::fs::rename(&zst_path, &quarantined);
803                return None;
804            }
805            let compressed = std::fs::read(&zst_path).ok()?;
806            let max_decompressed = max_decompressed_bytes(meta.len());
807            let data = bounded_zstd_decode(&compressed, max_decompressed)?;
808            let idx: Self = postcard::from_bytes(&data).ok()?;
809            return Some(idx);
810        }
811
812        let bin_path = dir.join("bm25_index.bin");
813        if bin_path.exists() {
814            let meta = std::fs::metadata(&bin_path).ok()?;
815            if meta.len() > max_bytes {
816                tracing::warn!(
817                    "[bm25] index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
818                    meta.len() as f64 / 1_073_741_824.0,
819                    max_bytes / (1024 * 1024),
820                    bin_path.display()
821                );
822                let quarantined = bin_path.with_extension("bin.quarantined");
823                let _ = std::fs::rename(&bin_path, &quarantined);
824                return None;
825            }
826            let data = std::fs::read(&bin_path).ok()?;
827            let idx: Self = postcard::from_bytes(&data).ok()?;
828            // Auto-migrate: compress legacy .bin to .bin.zst
829            if let Ok(compressed) = zstd::encode_all(data.as_slice(), ZSTD_LEVEL) {
830                let zst_tmp = zst_path.with_extension("zst.tmp");
831                if std::fs::write(&zst_tmp, &compressed).is_ok()
832                    && std::fs::rename(&zst_tmp, &zst_path).is_ok()
833                {
834                    tracing::info!(
835                        "[bm25] migrated {:.1} MB → {:.1} MB zstd",
836                        data.len() as f64 / 1_048_576.0,
837                        compressed.len() as f64 / 1_048_576.0
838                    );
839                    let _ = std::fs::remove_file(&bin_path);
840                }
841            }
842            return Some(idx);
843        }
844
845        let json_path = dir.join("bm25_index.json");
846        if json_path.exists() {
847            let meta = std::fs::metadata(&json_path).ok()?;
848            if meta.len() > max_bytes {
849                tracing::warn!(
850                    "[bm25] index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
851                    meta.len() as f64 / 1_073_741_824.0,
852                    max_bytes / (1024 * 1024),
853                    json_path.display()
854                );
855                let quarantined = json_path.with_extension("json.quarantined");
856                let _ = std::fs::rename(&json_path, &quarantined);
857                return None;
858            }
859            let data = std::fs::read_to_string(&json_path).ok()?;
860            return serde_json::from_str(&data).ok();
861        }
862
863        None
864    }
865
866    pub fn load_or_build(root: &Path) -> Self {
867        Self::load_or_build_inner(root, false)
868    }
869
870    /// Like `load_or_build` but uses a fast sentinel-sampling staleness check
871    /// that skips the expensive full directory walk for new-file detection.
872    pub fn load_or_build_fast(root: &Path) -> Self {
873        Self::load_or_build_inner(root, true)
874    }
875
876    fn load_or_build_inner(root: &Path, fast_stale: bool) -> Self {
877        if !is_safe_bm25_root(root) {
878            return Self::default();
879        }
880        if let Some(idx) = Self::load(root) {
881            let stale = if fast_stale {
882                bm25_index_looks_stale_fast(&idx, root)
883            } else {
884                bm25_index_looks_stale(&idx, root)
885            };
886            if !stale {
887                return idx;
888            }
889            tracing::debug!(
890                "[bm25_index: stale index detected for {}; rebuilding]",
891                root.display()
892            );
893            let rebuilt = if idx.files.is_empty() {
894                Self::build_from_directory(root)
895            } else {
896                Self::rebuild_incremental(root, &idx)
897            };
898            let _ = rebuilt.save(root);
899            return rebuilt;
900        }
901
902        let built = Self::build_from_directory(root);
903        let _ = built.save(root);
904        built
905    }
906
907    pub fn index_file_path(root: &Path) -> PathBuf {
908        let dir = index_dir(root);
909        let zst = dir.join("bm25_index.bin.zst");
910        if zst.exists() {
911            return zst;
912        }
913        let bin = dir.join("bm25_index.bin");
914        if bin.exists() {
915            return bin;
916        }
917        dir.join("bm25_index.json")
918    }
919
920    /// Chunk count of the persisted index without loading it (#1914): postcard
921    /// writes `chunks` — the first field — as a varint length prefix, so only
922    /// the first few decompressed bytes are read. `None` for the legacy JSON
923    /// format or an unreadable file; `Some(0)` for an index that holds nothing.
924    pub fn persisted_chunk_count(root: &Path) -> Option<u64> {
925        use std::io::Read;
926        let path = Self::index_file_path(root);
927        let file = std::fs::File::open(&path).ok()?;
928        let mut head: Box<dyn Read> = match path.extension().and_then(|e| e.to_str()) {
929            Some("zst") => Box::new(zstd::Decoder::new(file).ok()?),
930            Some("bin") => Box::new(file),
931            _ => return None,
932        };
933        let mut count = 0u64;
934        for shift in (0..64).step_by(7) {
935            let mut byte = [0u8; 1];
936            head.read_exact(&mut byte).ok()?;
937            count |= u64::from(byte[0] & 0x7f) << shift;
938            if byte[0] & 0x80 == 0 {
939                return Some(count);
940            }
941        }
942        None
943    }
944
945    /// Ingest external `ContentChunk`s into the BM25 index.
946    /// Converts each chunk to a `CodeChunk` (backward-compatible) and
947    /// rebuilds the inverted index. Returns the number of chunks ingested.
948    pub fn ingest_content_chunks(
949        &mut self,
950        chunks: impl IntoIterator<Item = super::content_chunk::ContentChunk>,
951    ) -> usize {
952        let mut count = 0usize;
953        for cc in chunks {
954            self.add_chunk(cc.into());
955            count += 1;
956        }
957        if count > 0 {
958            self.finalize();
959        }
960        count
961    }
962
963    /// Number of chunks originating from external providers.
964    pub fn external_chunk_count(&self) -> usize {
965        self.chunks
966            .iter()
967            .filter(|c| c.file_path.contains("://"))
968            .count()
969    }
970
971    /// Remove every chunk whose `file_path` starts with `prefix` (e.g.
972    /// `health://`) and rebuild the inverted index. Lets a recomputed source
973    /// (like the code-health fabric) evict its prior pass so stale entries never
974    /// linger in search. Returns the number of chunks removed.
975    pub fn remove_chunks_with_prefix(&mut self, prefix: &str) -> usize {
976        let before = self.chunks.len();
977        self.chunks.retain(|c| !c.file_path.starts_with(prefix));
978        let removed = before - self.chunks.len();
979        if removed > 0 {
980            self.finalize();
981        }
982        removed
983    }
984}
985
986fn is_safe_bm25_root(root: &Path) -> bool {
987    super::graph_index::is_safe_scan_root_public(&root.to_string_lossy())
988}
989
990fn bm25_index_looks_stale(index: &BM25Index, root: &Path) -> bool {
991    bm25_index_looks_stale_inner(index, root, false)
992}
993
994/// Fast staleness check: samples a subset of tracked files and skips the
995/// expensive `list_code_files()` walk for new-file detection.
996pub fn bm25_index_looks_stale_fast(index: &BM25Index, root: &Path) -> bool {
997    bm25_index_looks_stale_inner(index, root, true)
998}
999
1000fn bm25_index_looks_stale_inner(index: &BM25Index, root: &Path, fast: bool) -> bool {
1001    if index.chunks.is_empty() {
1002        return false;
1003    }
1004
1005    if index.files.is_empty() {
1006        let mut seen = std::collections::HashSet::<&str>::new();
1007        for chunk in &index.chunks {
1008            let rel = chunk.file_path.trim_start_matches(['/', '\\']);
1009            if rel.is_empty() {
1010                continue;
1011            }
1012            if !seen.insert(rel) {
1013                continue;
1014            }
1015            if !root.join(rel).exists() {
1016                return true;
1017            }
1018        }
1019        return false;
1020    }
1021
1022    if fast {
1023        let sample_size = index.files.len().min(SENTINEL_SAMPLE_SIZE);
1024        let step = if index.files.len() > sample_size {
1025            index.files.len() / sample_size
1026        } else {
1027            1
1028        };
1029        for (i, (rel, old_state)) in index.files.iter().enumerate() {
1030            if i % step != 0 {
1031                continue;
1032            }
1033            let abs = root.join(rel);
1034            if !abs.exists() {
1035                return true;
1036            }
1037            let Some(cur) = IndexedFileState::from_path(&abs) else {
1038                return true;
1039            };
1040            if &cur != old_state {
1041                return true;
1042            }
1043        }
1044        // Sampling tracked files says nothing about files that were never
1045        // indexed, so without this the fast path serves a partial tree forever
1046        // (#1724). The directory snapshot closes that hole for one stat per
1047        // indexed directory.
1048        return dirs_look_stale(index, root);
1049    }
1050
1051    for (rel, old_state) in &index.files {
1052        let abs = root.join(rel);
1053        if !abs.exists() {
1054            return true;
1055        }
1056        let Some(cur) = IndexedFileState::from_path(&abs) else {
1057            return true;
1058        };
1059        if &cur != old_state {
1060            return true;
1061        }
1062    }
1063
1064    for rel in list_code_files(root) {
1065        if !index.files.contains_key(&rel) {
1066            return true;
1067        }
1068    }
1069
1070    false
1071}
1072
1073const SENTINEL_SAMPLE_SIZE: usize = 10;
1074
1075/// True when recorded directory fingerprints no longer match the filesystem —
1076/// i.e. a file was added to (or removed from) the indexed tree.
1077///
1078/// An index persisted before directory snapshots existed carries no `dirs`, so
1079/// its freshness cannot be proven cheaply: it is reported stale exactly once,
1080/// and the resulting rebuild records the snapshot for every later call.
1081fn dirs_look_stale(index: &BM25Index, root: &Path) -> bool {
1082    if index.dirs.is_empty() {
1083        return true;
1084    }
1085    for (rel, recorded) in &index.dirs {
1086        let abs = if rel.is_empty() {
1087            root.to_path_buf()
1088        } else {
1089            root.join(rel)
1090        };
1091        if dir_fingerprint(&abs) != Some(*recorded) {
1092            return true;
1093        }
1094    }
1095    false
1096}
1097
1098fn dir_fingerprint(path: &Path) -> Option<u64> {
1099    use std::hash::{Hash, Hasher};
1100
1101    let meta = std::fs::metadata(path).ok()?;
1102    let modified = meta.modified().ok()?.duration_since(UNIX_EPOCH).ok()?;
1103    let mut entries = std::fs::read_dir(path)
1104        .ok()?
1105        .filter_map(Result::ok)
1106        .map(|entry| entry.file_name().to_string_lossy().into_owned())
1107        .collect::<Vec<_>>();
1108    entries.sort_unstable();
1109    let mut hasher = std::collections::hash_map::DefaultHasher::new();
1110    modified.as_nanos().hash(&mut hasher);
1111    entries.hash(&mut hasher);
1112    Some(hasher.finish())
1113}
1114
1115/// Content snapshot of the root plus every ancestor directory of an indexed file.
1116/// Ancestors are included so a brand-new top-level directory (whose own mtime
1117/// was never recorded) is still caught through its recorded parent.
1118fn dir_states(root: &Path, files: &[String]) -> HashMap<String, u64> {
1119    let mut rels: std::collections::HashSet<String> = std::collections::HashSet::new();
1120    rels.insert(String::new());
1121    for rel in files {
1122        let mut cur = Path::new(rel);
1123        while let Some(parent) = cur.parent() {
1124            let key = parent.to_string_lossy().to_string();
1125            // Once a directory is known, so are all of its ancestors.
1126            if !rels.insert(key) {
1127                break;
1128            }
1129            cur = parent;
1130        }
1131    }
1132    rels.into_iter()
1133        .filter_map(|rel| {
1134            let abs = if rel.is_empty() {
1135                root.to_path_buf()
1136            } else {
1137                root.join(&rel)
1138            };
1139            dir_fingerprint(&abs).map(|fingerprint| (rel, fingerprint))
1140        })
1141        .collect()
1142}
1143
1144/// Streams the persisted index out, refusing anything past `max_bytes`.
1145///
1146/// The buffer never grows beyond `max_bytes`, so the ceiling passed in *is* the
1147/// worst-case allocation — which is why #1739 hinged on that ceiling being a
1148/// sane number rather than on this loop. Our own writer streams postcard into
1149/// the encoder (#790) and so never records a frame content size, which rules
1150/// out a cheap header pre-check.
1151fn bounded_zstd_decode(compressed: &[u8], max_bytes: u64) -> Option<Vec<u8>> {
1152    use std::io::Read;
1153    let mut decoder = zstd::Decoder::new(compressed).ok()?;
1154    let mut buf = Vec::new();
1155    let mut chunk = vec![0u8; 65536];
1156    let mut total = 0u64;
1157    loop {
1158        let n = decoder.read(&mut chunk).ok()?;
1159        if n == 0 {
1160            break;
1161        }
1162        total += n as u64;
1163        if total > max_bytes {
1164            tracing::warn!(
1165                "[bm25] decompressed index exceeds limit ({:.0} MB > {:.0} MB), aborting load",
1166                total as f64 / (1024.0 * 1024.0),
1167                max_bytes as f64 / (1024.0 * 1024.0)
1168            );
1169            return None;
1170        }
1171        buf.extend_from_slice(&chunk[..n]);
1172    }
1173    Some(buf)
1174}
1175
1176/// Worst-case RAM this process will spend decompressing a persisted index.
1177///
1178/// #1739: this was `max_bm25_cache_bytes() * 20` — twenty times a **disk**
1179/// budget, with no reference to the file at hand or to the machine's memory. On
1180/// the default 512 MB disk budget that authorised a 10 GB allocation for any
1181/// index, however small the file; because `ctx_search` reloads on demand,
1182/// repeated calls stacked to 20 GB RSS and froze the host.
1183///
1184/// The index is decompressed into RAM, so RAM is what has to bound it, and a
1185/// given file cannot plausibly expand past a fixed ratio of its own size.
1186fn max_decompressed_bytes(compressed_bytes: u64) -> u64 {
1187    /// postcard + zstd on an index this shape expands well under this.
1188    const MAX_EXPANSION_RATIO: u64 = 20;
1189    /// Keeps small indices loadable on hosts that report little or no RAM.
1190    const FLOOR: u64 = 64 * 1024 * 1024;
1191
1192    let file_derived = compressed_bytes
1193        .saturating_mul(MAX_EXPANSION_RATIO)
1194        .max(FLOOR);
1195    match crate::core::memory_guard::rss_limit_bytes() {
1196        Some(limit) => file_derived.min(limit.max(FLOOR)),
1197        None => file_derived,
1198    }
1199}
1200
1201fn index_dir(root: &Path) -> PathBuf {
1202    crate::core::index_namespace::vectors_dir(root)
1203}
1204
1205/// Walk depth of the corpus walk. Deeper files are never indexed.
1206const CORPUS_MAX_DEPTH: usize = 20;
1207
1208/// The rules that decide corpus membership, loaded once. Shared by
1209/// [`list_code_files`] and the `index why` diagnostic ([`coverage`]), so the
1210/// explanation can never drift from what the indexer actually does.
1211pub(crate) struct CorpusRules {
1212    filter: crate::core::index_filter::IndexFileFilter,
1213    /// `DEFAULT_BM25_IGNORES` followed by `extra_ignore_patterns`, with the
1214    /// source text kept so a diagnostic can name the pattern that matched.
1215    ignore_patterns: Vec<(String, glob::Pattern)>,
1216    max_files: usize,
1217}
1218
1219impl CorpusRules {
1220    pub(crate) fn load() -> Self {
1221        Self::from_config(&crate::core::config::Config::load())
1222    }
1223
1224    fn from_config(cfg: &crate::core::config::Config) -> Self {
1225        // #735: the declared corpus filter ([index] config + CLI overlay) decides
1226        // membership before anything is chunked; the semantic index chunks this
1227        // corpus, so it inherits the same universe.
1228        let filter = crate::core::index_filter::IndexFileFilter::resolve(cfg);
1229        let ignore_patterns = DEFAULT_BM25_IGNORES
1230            .iter()
1231            .map(|p| (*p).to_string())
1232            .chain(cfg.extra_ignore_patterns.iter().cloned())
1233            .filter_map(|p| glob::Pattern::new(&p).ok().map(|g| (p, g)))
1234            .collect();
1235        // Mirrors graph_index_max_files: 0 = unlimited, default 5000 (MAX_BM25_FILES).
1236        let max_files = if cfg.bm25_max_files == 0 {
1237            usize::MAX
1238        } else {
1239            cfg.bm25_max_files as usize
1240        };
1241        Self {
1242            filter,
1243            ignore_patterns,
1244            max_files,
1245        }
1246    }
1247
1248    /// The corpus walker: gitignore per the filter, bounded depth. Callers add
1249    /// their own `filter_entry`.
1250    fn walker(&self, root: &Path) -> ignore::WalkBuilder {
1251        let mut builder = ignore::WalkBuilder::new(root);
1252        builder
1253            // #1792: the BM25 corpus is authoritative for `ctx_compose`/`ctx_overview`,
1254            // so omitting tracked dotfiles made "no match" indistinguishable from
1255            // "not indexed".
1256            .hidden(crate::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
1257            .git_ignore(self.filter.respect_gitignore)
1258            .git_global(self.filter.respect_gitignore)
1259            .git_exclude(self.filter.respect_gitignore)
1260            .require_git(false)
1261            .max_depth(Some(CORPUS_MAX_DEPTH));
1262        builder
1263    }
1264
1265    /// First default/extra ignore pattern matching `rel`.
1266    fn ignore_pattern_for(&self, rel: &str) -> Option<&str> {
1267        self.ignore_patterns
1268            .iter()
1269            .find(|(_, p)| p.matches(rel))
1270            .map(|(src, _)| src.as_str())
1271    }
1272
1273    /// Whether the declared `[index]` filter drops `rel`. Globs match on
1274    /// forward slashes so they behave identically on Windows; the index key
1275    /// keeps the platform separator (existing indexes stay valid).
1276    fn filter_excludes(&self, rel: &str) -> bool {
1277        self.filter.is_excluded(&rel.replace('\\', "/"))
1278    }
1279}
1280
1281fn list_code_files(root: &Path) -> Vec<String> {
1282    list_code_files_with(root, &CorpusRules::load())
1283}
1284
1285fn list_code_files_with(root: &Path, rules: &CorpusRules) -> Vec<String> {
1286    list_code_files_bounded(root, rules, false).unwrap_or_default()
1287}
1288
1289fn list_code_files_inner(root: &Path, bounded: bool) -> Result<Vec<String>, String> {
1290    list_code_files_bounded(root, &CorpusRules::load(), bounded)
1291}
1292
1293/// The corpus walk. `bounded` (source-admission views) fails closed on a
1294/// walk or file budget instead of silently truncating.
1295fn list_code_files_bounded(
1296    root: &Path,
1297    rules: &CorpusRules,
1298    bounded: bool,
1299) -> Result<Vec<String>, String> {
1300    let walker = rules
1301        .walker(root)
1302        .filter_entry(crate::core::walk_filter::keep_entry)
1303        .build();
1304
1305    let mut files: Vec<String> = Vec::new();
1306    let mut filtered_out = 0usize;
1307    for (visited, entry) in walker.enumerate() {
1308        if bounded && visited >= 100_000 {
1309            return Err("source discovery budget exceeded; narrow the search scope".into());
1310        }
1311        let entry = match entry {
1312            Ok(entry) => entry,
1313            Err(_) if bounded => return Err("source discovery could not be completed".into()),
1314            Err(_) => continue,
1315        };
1316        let path = entry.path();
1317        if !path.is_file() {
1318            continue;
1319        }
1320        if !crate::core::ingestion::is_ingestible(path) {
1321            continue;
1322        }
1323        let rel = path
1324            .strip_prefix(root)
1325            .unwrap_or(path)
1326            .to_string_lossy()
1327            .to_string();
1328        if rel.is_empty() {
1329            continue;
1330        }
1331        if rules.ignore_pattern_for(&rel).is_some() {
1332            continue;
1333        }
1334        if rules.filter_excludes(&rel) {
1335            filtered_out += 1;
1336            continue;
1337        }
1338        if files.len() >= rules.max_files {
1339            if bounded {
1340                return Err("source file budget exceeded; narrow the search scope".into());
1341            }
1342            tracing::warn!(
1343                "[bm25] file cap reached ({}), skipping remaining files in {}. \
1344                 Set bm25_max_files in config (0 = unlimited) to index more.",
1345                rules.max_files,
1346                root.display()
1347            );
1348            break;
1349        }
1350        files.push(rel);
1351    }
1352
1353    if filtered_out > 0 {
1354        tracing::info!(
1355            "[bm25] index filter excluded {filtered_out} files ({})",
1356            rules.filter.summary().unwrap_or_default()
1357        );
1358    }
1359
1360    files.sort();
1361    files.dedup();
1362    Ok(files)
1363}
1364
1365pub fn is_code_file(path: &Path) -> bool {
1366    let ext = path
1367        .extension()
1368        .and_then(|e| e.to_str())
1369        .unwrap_or("")
1370        .to_lowercase();
1371    matches!(
1372        ext.as_str(),
1373        "rs" | "ts"
1374            | "tsx"
1375            | "js"
1376            | "jsx"
1377            | "py"
1378            | "go"
1379            | "java"
1380            | "c"
1381            | "cc"
1382            | "cpp"
1383            | "h"
1384            | "hpp"
1385            | "rb"
1386            | "cs"
1387            | "kt"
1388            | "swift"
1389            | "php"
1390            | "scala"
1391            | "sql"
1392            | "ex"
1393            | "exs"
1394            | "zig"
1395            | "lua"
1396            | "dart"
1397            | "vue"
1398            | "svelte"
1399    )
1400}