Skip to main content

vtcode_indexer/
lib.rs

1#![allow(
2    missing_docs,
3    dead_code,
4    unused_imports,
5    reason = "Intentional compatibility, platform, or test-only suppression."
6)]
7#![expect(
8    unused_results,
9    reason = "Indexer cache and walker updates intentionally use mutation APIs for side effects and discard prior entries."
10)]
11
12//! Workspace-friendly file indexer and file utilities for VT Code.
13//!
14//! `vtcode-indexer` provides:
15//! - A lightweight workspace file indexer with markdown-backed persistence
16//! - Fast parallel fuzzy file search (via `file_search` module)
17//! - Markdown-backed storage utilities (via `markdown_store` module)
18
19pub mod file_search;
20pub mod markdown_store;
21
22mod atomic_write;
23mod snapshot;
24mod storage;
25
26pub use storage::{IndexStorage, MarkdownIndexStorage};
27
28use anyhow::Result;
29use hashbrown::HashMap;
30use ignore::{DirEntry, Walk};
31use rayon::prelude::*;
32use regex::Regex;
33use serde::{Deserialize, Serialize};
34use std::fmt::Write as FmtWrite;
35use std::fs;
36use std::io::ErrorKind;
37use std::path::{Path, PathBuf};
38use std::sync::Arc;
39use std::time::SystemTime;
40
41/// Directory traversal filter hook for [`SimpleIndexer`].
42pub trait TraversalFilter: Send + Sync {
43    /// Determine if the indexer should descend into the provided directory.
44    fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool;
45
46    /// Determine if the indexer should process the provided file.
47    fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool;
48
49    /// Metadata-aware variant of [`TraversalFilter::should_index_file`].
50    ///
51    /// The default implementation delegates to [`TraversalFilter::should_index_file`],
52    /// so existing filters keep their exact behavior. Filters whose file check
53    /// starts with an existence test should override this to reuse `metadata`
54    /// instead of stat-ing the path a second time.
55    fn should_index_file_with_metadata(
56        &self,
57        path: &Path,
58        metadata: &fs::Metadata,
59        config: &SimpleIndexerConfig,
60    ) -> bool {
61        let _ = metadata;
62        self.should_index_file(path, config)
63    }
64}
65
66/// Default traversal filter powered by [`SimpleIndexerConfig`].
67#[derive(Debug, Default, Clone)]
68pub struct ConfigTraversalFilter;
69
70impl TraversalFilter for ConfigTraversalFilter {
71    fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
72        !should_skip_dir(path, config)
73    }
74
75    fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
76        path.is_file() && snapshot::has_indexable_file_name(path, config)
77    }
78
79    fn should_index_file_with_metadata(
80        &self,
81        path: &Path,
82        metadata: &fs::Metadata,
83        config: &SimpleIndexerConfig,
84    ) -> bool {
85        metadata.is_file() && snapshot::has_indexable_file_name(path, config)
86    }
87}
88
89/// Configuration for [`SimpleIndexer`].
90#[derive(Clone, Debug)]
91pub struct SimpleIndexerConfig {
92    workspace_root: PathBuf,
93    index_dir: PathBuf,
94    ignore_hidden: bool,
95    excluded_dirs: Vec<PathBuf>,
96    allowed_dirs: Vec<PathBuf>,
97}
98
99impl SimpleIndexerConfig {
100    /// Builds a configuration using VT Code's legacy layout as defaults.
101    fn new(workspace_root: PathBuf) -> Self {
102        let index_dir = workspace_root.join(".vtcode").join("index");
103        let vtcode_dir = workspace_root.join(".vtcode");
104        let external_dir = vtcode_dir.join("external");
105
106        let mut excluded_dirs: Vec<PathBuf> = vtcode_commons::exclusions::DEFAULT_EXCLUDED_DIRS
107            .iter()
108            .map(|name| workspace_root.join(name))
109            .collect();
110        excluded_dirs.push(index_dir.clone());
111        excluded_dirs.push(vtcode_dir);
112
113        excluded_dirs.dedup();
114
115        Self {
116            workspace_root,
117            index_dir,
118            ignore_hidden: true,
119            excluded_dirs,
120            allowed_dirs: vec![external_dir],
121        }
122    }
123
124    /// Updates the index directory used for persisted metadata.
125    pub fn with_index_dir(mut self, index_dir: impl Into<PathBuf>) -> Self {
126        let index_dir = index_dir.into();
127        self.index_dir = index_dir.clone();
128        self.push_unique_excluded(index_dir);
129        self
130    }
131
132    /// Adds an allowed directory that should be indexed even if hidden or inside an excluded parent.
133    pub fn add_allowed_dir(mut self, path: impl Into<PathBuf>) -> Self {
134        let path = path.into();
135        if !self.allowed_dirs.iter().any(|existing| existing == &path) {
136            self.allowed_dirs.push(path);
137        }
138        self
139    }
140
141    /// Adds an additional excluded directory to skip during traversal.
142    pub fn add_excluded_dir(mut self, path: impl Into<PathBuf>) -> Self {
143        let path = path.into();
144        self.push_unique_excluded(path);
145        self
146    }
147
148    /// Toggles whether hidden directories (prefix `.`) are ignored.
149    fn ignore_hidden(mut self, ignore_hidden: bool) -> Self {
150        self.ignore_hidden = ignore_hidden;
151        self
152    }
153
154    /// Workspace root accessor.
155    pub fn workspace_root(&self) -> &Path {
156        &self.workspace_root
157    }
158
159    /// Index directory accessor.
160    fn index_dir(&self) -> &Path {
161        &self.index_dir
162    }
163
164    fn push_unique_excluded(&mut self, path: PathBuf) {
165        if !self.excluded_dirs.iter().any(|existing| existing == &path) {
166            self.excluded_dirs.push(path);
167        }
168    }
169}
170
171/// Simple file index entry.
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct FileIndex {
174    /// File path.
175    path: String,
176    /// File content hash for change detection.
177    hash: String,
178    /// Last modified timestamp.
179    modified: u64,
180    /// Subsecond part of the modification time; absent in legacy entries.
181    #[serde(default)]
182    modified_nanos: Option<u32>,
183    /// File size.
184    size: u64,
185    /// Language/extension.
186    language: String,
187    /// Simple tags.
188    tags: Vec<String>,
189}
190
191/// Simple search result.
192#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct SearchResult {
194    file_path: String,
195    line_number: usize,
196    line_content: String,
197    matches: Vec<String>,
198}
199
200/// Simple file indexer.
201pub struct SimpleIndexer {
202    config: SimpleIndexerConfig,
203    index_cache: HashMap<String, FileIndex>,
204    content_cache: HashMap<String, (String, Arc<str>)>,
205    storage: Arc<dyn IndexStorage>,
206    filter: Arc<dyn TraversalFilter>,
207}
208
209impl SimpleIndexer {
210    /// Create a new simple indexer with default VT Code paths.
211    pub fn new(workspace_root: PathBuf) -> Self {
212        Self::with_components(
213            SimpleIndexerConfig::new(workspace_root),
214            Arc::new(MarkdownIndexStorage),
215            Arc::new(ConfigTraversalFilter),
216        )
217    }
218
219    /// Create a simple indexer with the provided configuration.
220    fn with_config(config: SimpleIndexerConfig) -> Self {
221        Self::with_components(config, Arc::new(MarkdownIndexStorage), Arc::new(ConfigTraversalFilter))
222    }
223
224    /// Create a new simple indexer using a custom index directory.
225    pub fn with_index_dir(workspace_root: PathBuf, index_dir: PathBuf) -> Self {
226        let config = SimpleIndexerConfig::new(workspace_root).with_index_dir(index_dir);
227        Self::with_config(config)
228    }
229
230    /// Create an indexer with explicit storage and traversal filter implementations.
231    fn with_components(
232        config: SimpleIndexerConfig,
233        storage: Arc<dyn IndexStorage>,
234        filter: Arc<dyn TraversalFilter>,
235    ) -> Self {
236        Self {
237            config,
238            index_cache: HashMap::new(),
239            content_cache: HashMap::new(),
240            storage,
241            filter,
242        }
243    }
244
245    /// Replace the storage backend used to persist index entries.
246    fn with_storage(self, storage: Arc<dyn IndexStorage>) -> Self {
247        Self { storage, ..self }
248    }
249
250    /// Replace the traversal filter used to decide which files and directories are indexed.
251    fn with_filter(self, filter: Arc<dyn TraversalFilter>) -> Self {
252        Self { filter, ..self }
253    }
254
255    /// Initialize the index directory.
256    pub fn init(&self) -> Result<()> {
257        self.storage.init(self.config.index_dir())
258    }
259
260    /// Populate the index cache from the persisted snapshot so re-index runs
261    /// can skip unchanged files (see [`Self::index_directory`]). Entries
262    /// outside the workspace root, in excluded directories, with hidden
263    /// or sensitive names, or with `..` segments are discarded so a tampered
264    /// snapshot can never surface files the indexer would refuse to index.
265    /// Existence is deliberately unchecked: the re-index diff needs deleted
266    /// files' entries to prune them. A missing or malformed snapshot leaves
267    /// the cache empty and never fails. Returns the hydrated count.
268    pub fn hydrate_from_snapshot(&mut self) -> usize {
269        let root = self.config.workspace_root().to_path_buf();
270        let mut hydrated = 0;
271        for entry in snapshot::load_snapshot_entries(self.config.index_dir()) {
272            let path = Path::new(&entry.path);
273            if path.starts_with(&root)
274                && !snapshot::has_parent_reference(path)
275                && (self.is_allowed_path(path) || !self.is_excluded_path(path))
276                && snapshot::has_indexable_file_name(path, &self.config)
277            {
278                self.index_cache.insert(entry.path.clone(), entry);
279                hydrated += 1;
280            }
281        }
282        tracing::debug!(hydrated, total = self.index_cache.len(), "index cache hydrated from snapshot");
283        hydrated
284    }
285
286    /// Get the workspace root path.
287    pub fn workspace_root(&self) -> &Path {
288        self.config.workspace_root()
289    }
290
291    /// Get the index directory used for persisted metadata.
292    pub fn index_dir(&self) -> &Path {
293        self.config.index_dir()
294    }
295
296    /// Index a single file.
297    fn index_file(&mut self, file_path: &Path) -> Result<()> {
298        let cache_key = file_path.to_string_lossy().into_owned();
299
300        if self.storage.prefers_snapshot_persistence() {
301            let previous_content = self.content_cache.remove(cache_key.as_str());
302            let next_entry = if file_path.exists() && self.should_process_file_path(file_path) {
303                match self.build_file_index(file_path) {
304                    Ok(entry) => entry,
305                    Err(err) => {
306                        if let Some(content) = previous_content {
307                            self.content_cache.insert(cache_key, content);
308                        }
309                        return Err(err);
310                    }
311                }
312            } else {
313                None
314            };
315
316            self.apply_snapshot_file_update(cache_key, next_entry, previous_content)?;
317            return Ok(());
318        }
319
320        if !file_path.exists() || !self.should_process_file_path(file_path) {
321            self.index_cache.remove(cache_key.as_str());
322            self.storage.remove(self.config.index_dir(), file_path)?;
323            return Ok(());
324        }
325
326        if let Some(index) = self.build_file_index(file_path)? {
327            self.storage.persist(self.config.index_dir(), &index)?;
328            self.index_cache.insert(index.path.clone(), index);
329        } else {
330            self.index_cache.remove(cache_key.as_str());
331            self.storage.remove(self.config.index_dir(), file_path)?;
332        }
333
334        Ok(())
335    }
336
337    /// Index all files in directory recursively.
338    /// Respects .gitignore, .ignore, and other ignore files.
339    /// SECURITY: Always skips hidden files and sensitive data (.env, .git, etc.)
340    ///
341    /// Hydrated entries matching size and mtime are served without a read or
342    /// hash (see `cached_or_built_index`); an unchanged directory also skips
343    /// the whole-snapshot rewrite.
344    pub fn index_directory(&mut self, dir_path: &Path) -> Result<()> {
345        let walker = self.build_walker(dir_path);
346
347        let mut entries = Vec::new();
348        let mut rebuilt_any = false;
349
350        for entry in walker.filter_map(|e| e.ok()) {
351            let path = entry.path();
352
353            // Only index files, not directories
354            if entry.file_type().is_some_and(|ft| ft.is_file())
355                && let Some(index) = self.cached_or_built_index(path, &mut rebuilt_any)?
356            {
357                entries.push(index);
358            }
359        }
360
361        if self.storage.prefers_snapshot_persistence() {
362            if rebuilt_any || self.cached_subdirectory_differs(dir_path, &entries) {
363                self.apply_snapshot_directory_update(dir_path, &entries)?;
364            }
365            self.prune_orphaned_content(dir_path);
366            return Ok(());
367        }
368
369        entries.sort_unstable_by(|left, right| left.path.cmp(&right.path));
370        self.storage.persist_batch(self.config.index_dir(), &entries)?;
371        self.replace_cached_entries(dir_path, &entries);
372
373        Ok(())
374    }
375
376    /// Serve a cached [`FileIndex`] when size and mtime still match the
377    /// hydrated entry, avoiding a full read + SHA-256 per unchanged file;
378    /// otherwise build. Sets `rebuilt_any` when a file is built so the caller
379    /// can skip no-op snapshot rewrites (entry-set drops are caught by the
380    /// caller's directory diff). Matching metadata is a heuristic: changes
381    /// that preserve both size and the filesystem timestamp can be missed.
382    fn cached_or_built_index(&mut self, file_path: &Path, rebuilt_any: &mut bool) -> Result<Option<FileIndex>> {
383        // Stat once and reuse the metadata for the unchanged screen, the
384        // traversal filter, and the rebuilt entry instead of stat-ing up to
385        // four times per file (filter, screen, filter, mtime).
386        let metadata = match fs::metadata(file_path) {
387            Ok(metadata) => metadata,
388            Err(_) => {
389                // Missing/unreadable: preserve `build_file_index` semantics,
390                // which maps missing files to `None` unless a custom filter
391                // claims the path (in which case the read error propagates).
392                let built = self.build_file_index(file_path)?;
393                *rebuilt_any |= built.is_some();
394                return Ok(built);
395            }
396        };
397
398        let cache_key = file_path.to_string_lossy();
399        if let Some(cached) = self.index_cache.get(cache_key.as_ref())
400            && self.should_process_file_path_with_metadata(file_path, &metadata)
401            && let Ok(modified) = metadata.modified()
402            && let Ok(elapsed) = modified.duration_since(SystemTime::UNIX_EPOCH)
403            && elapsed.as_secs() == cached.modified
404            && cached.modified_nanos == Some(elapsed.subsec_nanos())
405            && metadata.len() == cached.size
406        {
407            return Ok(Some(cached.clone()));
408        }
409
410        let built = self.build_file_index_with_metadata(file_path, &metadata)?;
411        *rebuilt_any |= built.is_some();
412        Ok(built)
413    }
414
415    /// Whether the walked entries differ from the cached entries under
416    /// `dir_path`. Deletions show up here; additions and content changes set
417    /// `rebuilt_any` in [`Self::cached_or_built_index`] instead.
418    ///
419    /// Compares by count plus membership instead of materializing two `HashSet`s.
420    /// Requires: `entries` holds at most one entry per path, as produced by the
421    /// [`Self::index_directory`] walker loop — equal counts plus every walked path
422    /// present in the cache then means the sets match.
423    /// Uniqueness precondition shared by [`Self::cached_subdirectory_differs`].
424    #[cfg(debug_assertions)]
425    fn walked_paths_are_unique(entries: &[FileIndex]) -> bool {
426        let mut seen = std::collections::HashSet::new();
427        entries.iter().all(|entry| seen.insert(entry.path.as_str()))
428    }
429
430    #[must_use]
431    fn cached_subdirectory_differs(&self, dir_path: &Path, entries: &[FileIndex]) -> bool {
432        debug_assert!(
433            Self::walked_paths_are_unique(entries),
434            "cached_subdirectory_differs requires at most one entry per path"
435        );
436        let cached_count = self
437            .index_cache
438            .keys()
439            .filter(|path| Path::new(path).starts_with(dir_path))
440            .count();
441        if cached_count != entries.len() {
442            return true;
443        }
444        entries.iter().any(|entry| !self.index_cache.contains_key(entry.path.as_str()))
445    }
446
447    /// Discover all files in directory recursively without indexing them.
448    /// This is much faster than `index_directory` as it avoids hashing and persistence.
449    pub fn discover_files(&self, dir_path: &Path) -> Vec<String> {
450        let walker = self.build_walker(dir_path);
451
452        let mut files = walker
453            .filter_map(|e| e.ok())
454            .filter(|e| {
455                if !e.file_type().is_some_and(|ft| ft.is_file()) {
456                    return false;
457                }
458
459                self.should_process_file_path(e.path())
460            })
461            .map(|e| e.path().to_string_lossy().into_owned())
462            .collect::<Vec<_>>();
463        files.sort_unstable();
464        files
465    }
466
467    /// List the immediate children of `dir_path` (one level deep) without
468    /// recursing into subdirectories.
469    ///
470    /// Uses the same ignore/hidden/excluded-directory rules as [`Self::discover_files`]
471    /// (via the shared traversal filter), so expensive subtrees such as
472    /// `node_modules`, `.git`, and build directories are never listed. This lets
473    /// callers build a directory navigator that only touches the directories the
474    /// user actually opens, instead of walking the entire workspace up front.
475    ///
476    /// Returns `(path, is_dir)` pairs with directories sorted before files.
477    pub fn discover_dir_entries(&self, dir_path: &Path) -> Vec<(PathBuf, bool)> {
478        let walker = self.build_shallow_walker(dir_path);
479
480        let mut entries: Vec<(PathBuf, bool)> = walker
481            .filter_map(|e| e.ok())
482            .filter(|e| e.path() != dir_path)
483            .map(|e| {
484                let path = e.path().to_path_buf();
485                let is_dir = e.file_type().is_some_and(|ft| ft.is_dir());
486                (path, is_dir)
487            })
488            .filter(|(path, is_dir)| {
489                if *is_dir {
490                    !should_skip_dir(path, &self.config)
491                } else {
492                    self.should_process_file_path(path)
493                }
494            })
495            .collect();
496
497        entries.sort_by_cached_key(|(path, is_dir)| {
498            // Cache the lowercased path once per entry: a plain `sort_by` would
499            // allocate two temporary strings on every one of the ~N·log N
500            // comparisons, and this runs on the interactive file-palette path.
501            (std::cmp::Reverse(*is_dir), path.to_string_lossy().to_lowercase())
502        });
503        entries
504    }
505
506    /// Internal helper for regex-based file content search.
507    /// Used by both `search()` and `grep()` to avoid code duplication.
508    fn search_files_internal(
509        &self,
510        regex: &Regex,
511        path_filter: Option<&str>,
512        extract_matches: bool,
513    ) -> Vec<SearchResult> {
514        const PARALLEL_THRESHOLD: usize = 64;
515
516        let candidate_paths: Vec<&String> = self
517            .index_cache
518            .keys()
519            .filter(|file_path| path_filter.is_none_or(|filter| file_path.contains(filter)))
520            .collect();
521
522        let mut content_lookup: HashMap<&String, Arc<str>> = HashMap::with_capacity(candidate_paths.len());
523        for path in &candidate_paths {
524            if let Some(index) = self.index_cache.get(*path)
525                && let Some((hash, content)) = self.content_cache.get(*path)
526                && hash == &index.hash
527            {
528                content_lookup.insert(*path, content.clone());
529            }
530        }
531
532        let map_file = move |file_path: &&String| -> Vec<SearchResult> {
533            if let Some(cached) = content_lookup.get(file_path) {
534                return Self::search_content(cached.as_ref(), regex, file_path, extract_matches);
535            }
536            let text = match fs::read_to_string(file_path) {
537                Ok(text) => text,
538                Err(_) => return Vec::new(),
539            };
540            Self::search_content(&text, regex, file_path, extract_matches)
541        };
542
543        let mut results: Vec<SearchResult> = if candidate_paths.len() <= PARALLEL_THRESHOLD {
544            candidate_paths.iter().flat_map(map_file).collect()
545        } else {
546            candidate_paths.par_iter().flat_map(map_file).collect()
547        };
548
549        results.sort_unstable_by(|left, right| {
550            left.file_path
551                .cmp(&right.file_path)
552                .then_with(|| left.line_number.cmp(&right.line_number))
553        });
554        results
555    }
556
557    #[inline]
558    fn search_content(content: &str, regex: &Regex, file_path: &&String, extract_matches: bool) -> Vec<SearchResult> {
559        let mut local = Vec::new();
560        for (line_num, line) in content.lines().enumerate() {
561            if regex.is_match(line) {
562                let line_content = line.to_string();
563                let matches = if extract_matches {
564                    regex.find_iter(line).map(|m| m.as_str().to_string()).collect()
565                } else {
566                    vec![line_content.clone()]
567                };
568
569                local.push(SearchResult {
570                    file_path: (*file_path).clone(),
571                    line_number: line_num + 1,
572                    line_content,
573                    matches,
574                });
575            }
576        }
577        local
578    }
579
580    /// Search files using regex pattern.
581    pub fn search(&self, pattern: &str, path_filter: Option<&str>) -> Result<Vec<SearchResult>> {
582        let regex = Regex::new(pattern)?;
583        Ok(self.search_files_internal(&regex, path_filter, true))
584    }
585
586    /// Find files by name pattern.
587    fn find_files(&self, pattern: &str) -> Result<Vec<String>> {
588        let regex = Regex::new(pattern)?;
589        let mut results = Vec::with_capacity(self.index_cache.len());
590
591        for file_path in self.index_cache.keys() {
592            if regex.is_match(file_path) {
593                results.push(file_path.clone());
594            }
595        }
596
597        results.sort_unstable();
598        Ok(results)
599    }
600
601    /// Get all indexed files without pattern matching.
602    /// This is more efficient than using find_files(".*").
603    fn all_files(&self) -> Vec<String> {
604        let mut files = self.index_cache.keys().cloned().collect::<Vec<_>>();
605        files.sort_unstable();
606        files
607    }
608
609    /// Get file content with line numbers.
610    fn get_file_content(&self, file_path: &str, start_line: Option<usize>, end_line: Option<usize>) -> Result<String> {
611        let content = fs::read_to_string(file_path)?;
612        let start = start_line.unwrap_or(1).max(1);
613        let end = end_line.unwrap_or(usize::MAX);
614
615        if start > end {
616            return Ok(String::new());
617        }
618
619        let mut result = String::with_capacity(content.len());
620        for (line_number, line) in content.lines().enumerate() {
621            let line_number = line_number + 1;
622            if line_number < start {
623                continue;
624            }
625            if line_number > end {
626                break;
627            }
628            writeln!(&mut result, "{line_number}: {line}")?;
629        }
630
631        Ok(result)
632    }
633
634    /// List files in directory (like ls).
635    pub fn list_files(&self, dir_path: &str, show_hidden: bool) -> Result<Vec<String>> {
636        let path = Path::new(dir_path);
637        if !path.exists() {
638            return Ok(vec![]);
639        }
640
641        let mut files = Vec::new();
642
643        for entry in fs::read_dir(path)? {
644            let entry = entry?;
645            let file_name = entry.file_name().to_string_lossy().into_owned();
646
647            if !show_hidden && file_name.starts_with('.') {
648                continue;
649            }
650
651            files.push(file_name);
652        }
653
654        files.sort_unstable();
655        Ok(files)
656    }
657
658    /// Grep-like search (like grep command).
659    pub fn grep(&self, pattern: &str, file_pattern: Option<&str>) -> Result<Vec<SearchResult>> {
660        let regex = Regex::new(pattern)?;
661        Ok(self.search_files_internal(&regex, file_pattern, false))
662    }
663
664    fn is_allowed_path(&self, path: &Path) -> bool {
665        self.config.allowed_dirs.iter().any(|allowed| path.starts_with(allowed))
666    }
667
668    #[inline]
669    fn get_modified_time(&self, file_path: &Path) -> Result<std::time::Duration> {
670        snapshot::metadata_modified_time(&fs::metadata(file_path)?)
671    }
672
673    #[inline]
674    fn detect_language(&self, file_path: &Path) -> String {
675        file_path
676            .extension()
677            .and_then(|ext| ext.to_str())
678            .unwrap_or("unknown")
679            .to_string()
680    }
681
682    fn build_file_index(&mut self, file_path: &Path) -> Result<Option<FileIndex>> {
683        if !self.should_process_file_path(file_path) {
684            return Ok(None);
685        }
686
687        let content = match fs::read_to_string(file_path) {
688            Ok(text) => text,
689            Err(err) => {
690                if err.kind() == ErrorKind::InvalidData {
691                    return Ok(None);
692                }
693                return Err(err.into());
694            }
695        };
696
697        let modified = self.get_modified_time(file_path)?;
698        Ok(Some(self.finish_file_index(file_path, content, modified)))
699    }
700
701    /// [`Self::build_file_index`] reusing an already-observed `metadata`.
702    ///
703    /// Used by the directory-walk hot loop so each file is stat-ed once.
704    /// A file that vanishes between the stat and the read maps to `None`,
705    /// matching the legacy path's existence re-check. (A custom filter that
706    /// accepts nonexistent paths would have surfaced the read error in the
707    /// legacy path; here the transient delete is skipped instead.)
708    fn build_file_index_with_metadata(
709        &mut self,
710        file_path: &Path,
711        metadata: &fs::Metadata,
712    ) -> Result<Option<FileIndex>> {
713        if !self.should_process_file_path_with_metadata(file_path, metadata) {
714            return Ok(None);
715        }
716
717        let content = match fs::read_to_string(file_path) {
718            Ok(text) => text,
719            Err(err) => {
720                if err.kind() == ErrorKind::InvalidData || err.kind() == ErrorKind::NotFound {
721                    return Ok(None);
722                }
723                return Err(err.into());
724            }
725        };
726
727        let modified = snapshot::metadata_modified_time(metadata)?;
728        Ok(Some(self.finish_file_index(file_path, content, modified)))
729    }
730
731    /// Assemble a [`FileIndex`] from already-read content and mtime, and cache
732    /// the content for hash-verified searches.
733    fn finish_file_index(&mut self, file_path: &Path, content: String, modified: std::time::Duration) -> FileIndex {
734        let index = FileIndex {
735            path: file_path.to_string_lossy().into_owned(),
736            hash: calculate_hash(&content),
737            modified: modified.as_secs(),
738            modified_nanos: Some(modified.subsec_nanos()),
739            size: content.len() as u64,
740            language: self.detect_language(file_path),
741            tags: vec![],
742        };
743
744        self.content_cache
745            .insert(index.path.clone(), (index.hash.clone(), Arc::from(content)));
746
747        index
748    }
749
750    #[inline]
751    fn is_excluded_path(&self, path: &Path) -> bool {
752        self.config.excluded_dirs.iter().any(|excluded| path.starts_with(excluded))
753    }
754
755    #[inline]
756    fn should_index_file_path(&self, path: &Path) -> bool {
757        self.filter.should_index_file(path, &self.config)
758    }
759
760    #[inline]
761    fn should_process_file_path(&self, path: &Path) -> bool {
762        self.should_process_with(path, || self.should_index_file_path(path))
763    }
764
765    #[inline]
766    fn should_process_file_path_with_metadata(&self, path: &Path, metadata: &fs::Metadata) -> bool {
767        self.should_process_with(path, || self.filter.should_index_file_with_metadata(path, metadata, &self.config))
768    }
769
770    /// Allowed/excluded scope gate shared by both file filters.
771    ///
772    /// Allowed directories bypass exclusion; everywhere else an excluded path
773    /// short-circuits before the (potentially stat-ing) filter runs.
774    #[inline]
775    fn should_process_with(&self, path: &Path, indexable: impl FnOnce() -> bool) -> bool {
776        if self.is_allowed_path(path) {
777            return indexable();
778        }
779
780        !self.is_excluded_path(path) && indexable()
781    }
782
783    fn build_walker(&self, dir_path: &Path) -> Walk {
784        let walk_root = dir_path.to_path_buf();
785        let config = self.config.clone();
786        let filter = Arc::clone(&self.filter);
787
788        let mut builder = vtcode_commons::walk::build_default_walker(dir_path);
789        builder.filter_entry(move |entry| should_visit_entry(entry, walk_root.as_path(), &config, filter.as_ref()));
790        builder.build()
791    }
792
793    fn build_shallow_walker(&self, dir_path: &Path) -> Walk {
794        let walk_root = dir_path.to_path_buf();
795        let config = self.config.clone();
796        let filter = Arc::clone(&self.filter);
797
798        let mut builder = vtcode_commons::walk::build_default_walker(dir_path);
799        // Only immediate children — directory navigation lists one level at a time.
800        builder.max_depth(Some(1));
801        builder.filter_entry(move |entry| should_visit_entry(entry, walk_root.as_path(), &config, filter.as_ref()));
802        builder.build()
803    }
804
805    fn replace_cached_entries(&mut self, dir_path: &Path, entries: &[FileIndex]) {
806        self.index_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
807        self.content_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
808
809        self.index_cache
810            .extend(entries.iter().cloned().map(|entry| (entry.path.clone(), entry)));
811    }
812
813    /// Drop content entries under `dir_path` without an index entry (deleted,
814    /// rejected, or unindexable); content for still-indexed files is kept so
815    /// searches avoid a disk read.
816    fn prune_orphaned_content(&mut self, dir_path: &Path) {
817        self.content_cache
818            .retain(|path, _| !Path::new(path).starts_with(dir_path) || self.index_cache.contains_key(path.as_str()));
819    }
820
821    fn apply_snapshot_file_update(
822        &mut self,
823        cache_key: String,
824        next_entry: Option<FileIndex>,
825        previous_content: Option<(String, Arc<str>)>,
826    ) -> Result<()> {
827        let previous_entry = match next_entry {
828            Some(entry) => self.index_cache.insert(cache_key.clone(), entry),
829            None => self.index_cache.remove(cache_key.as_str()),
830        };
831        if let Err(err) = self.persist_current_snapshot() {
832            match previous_entry {
833                Some(entry) => {
834                    self.index_cache.insert(cache_key.clone(), entry);
835                }
836                None => {
837                    self.index_cache.remove(cache_key.as_str());
838                }
839            }
840            self.content_cache.remove(cache_key.as_str());
841            if let Some(content) = previous_content {
842                self.content_cache.insert(cache_key, content);
843            }
844            return Err(err);
845        }
846
847        Ok(())
848    }
849
850    fn apply_snapshot_directory_update(&mut self, dir_path: &Path, entries: &[FileIndex]) -> Result<()> {
851        let previous_entries = self.take_cached_entries(dir_path);
852        self.index_cache
853            .extend(entries.iter().cloned().map(|entry| (entry.path.clone(), entry)));
854
855        if let Err(err) = self.persist_current_snapshot() {
856            self.index_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
857            self.index_cache
858                .extend(previous_entries.into_iter().map(|entry| (entry.path.clone(), entry)));
859            return Err(err);
860        }
861
862        Ok(())
863    }
864
865    fn take_cached_entries(&mut self, dir_path: &Path) -> Vec<FileIndex> {
866        let keys = self
867            .index_cache
868            .keys()
869            .filter(|path| Path::new(path).starts_with(dir_path))
870            .cloned()
871            .collect::<Vec<_>>();
872
873        keys.into_iter()
874            .filter_map(|path| self.index_cache.remove(path.as_str()))
875            .collect()
876    }
877
878    fn persist_current_snapshot(&self) -> Result<()> {
879        let mut snapshot = self.index_cache.values().collect::<Vec<_>>();
880        snapshot.sort_unstable_by(|left, right| left.path.cmp(&right.path));
881        self.storage.persist_batch_refs(self.config.index_dir(), &snapshot)
882    }
883}
884
885impl Clone for SimpleIndexer {
886    fn clone(&self) -> Self {
887        Self {
888            config: self.config.clone(),
889            index_cache: self.index_cache.clone(),
890            content_cache: self.content_cache.clone(),
891            storage: self.storage.clone(),
892            filter: self.filter.clone(),
893        }
894    }
895}
896
897fn should_skip_dir(path: &Path, config: &SimpleIndexerConfig) -> bool {
898    if is_allowed_path_or_ancestor(path, config) {
899        return false;
900    }
901
902    if config.excluded_dirs.iter().any(|excluded| path.starts_with(excluded)) {
903        return true;
904    }
905
906    if config.ignore_hidden
907        && path
908            .file_name()
909            .and_then(|name| name.to_str())
910            .is_some_and(|name_str| name_str.starts_with('.'))
911    {
912        return true;
913    }
914
915    false
916}
917
918fn is_allowed_path_or_ancestor(path: &Path, config: &SimpleIndexerConfig) -> bool {
919    config
920        .allowed_dirs
921        .iter()
922        .any(|allowed| path.starts_with(allowed) || allowed.starts_with(path))
923}
924
925fn should_visit_entry(
926    entry: &DirEntry,
927    walk_root: &Path,
928    config: &SimpleIndexerConfig,
929    filter: &dyn TraversalFilter,
930) -> bool {
931    if entry.path() == walk_root {
932        return true;
933    }
934
935    if !entry.file_type().is_some_and(|file_type| file_type.is_dir()) {
936        return true;
937    }
938
939    filter.should_descend(entry.path(), config)
940}
941
942#[inline]
943fn calculate_hash(content: &str) -> String {
944    vtcode_commons::utils::calculate_sha256(content.as_bytes())
945}
946
947#[cfg(test)]
948mod snapshot_update_tests;
949#[cfg(test)]
950mod tests;