Skip to main content

vtcode_indexer/
lib.rs

1#![allow(missing_docs, dead_code, unused_imports)]
2//! Workspace-friendly file indexer and file utilities for VT Code.
3//!
4//! `vtcode-indexer` provides:
5//! - A lightweight workspace file indexer with markdown-backed persistence
6//! - Fast parallel fuzzy file search (via `file_search` module)
7//! - Markdown-backed storage utilities (via `markdown_store` module)
8
9pub mod file_search;
10pub mod markdown_store;
11
12use anyhow::Result;
13use hashbrown::HashMap;
14use ignore::{DirEntry, Walk};
15use rayon::prelude::*;
16use regex::Regex;
17use serde::{Deserialize, Serialize};
18use std::fmt::Write as FmtWrite;
19use std::fs;
20use std::io::{BufWriter, ErrorKind, Write};
21use std::path::{Path, PathBuf};
22use std::sync::Arc;
23use std::time::SystemTime;
24
25/// Persistence backend for [`SimpleIndexer`].
26pub trait IndexStorage: Send + Sync {
27    /// Prepare any directories or resources required for persistence.
28    fn init(&self, index_dir: &Path) -> Result<()>;
29
30    /// Persist an indexed file entry.
31    fn persist(&self, index_dir: &Path, entry: &FileIndex) -> Result<()>;
32
33    /// Whether this backend expects full-snapshot persistence.
34    ///
35    /// Snapshot-aware backends receive the complete in-memory index on each
36    /// update so on-disk state stays consistent across single-file and
37    /// directory indexing flows.
38    fn prefers_snapshot_persistence(&self) -> bool {
39        false
40    }
41
42    /// Remove a previously persisted file entry.
43    ///
44    /// Defaults to a no-op to keep existing custom storage backends compatible.
45    fn remove(&self, _index_dir: &Path, _file_path: &Path) -> Result<()> {
46        Ok(())
47    }
48
49    /// Persist a batch of indexed file entries.
50    ///
51    /// Defaults to calling [`IndexStorage::persist`] for each entry, keeping
52    /// existing custom storage backends compatible.
53    fn persist_batch(&self, index_dir: &Path, entries: &[FileIndex]) -> Result<()> {
54        for entry in entries {
55            self.persist(index_dir, entry)?;
56        }
57        Ok(())
58    }
59
60    /// Persist a batch of indexed file entries borrowed from the in-memory cache.
61    ///
62    /// Defaults to cloning the borrowed entries and delegating to
63    /// [`IndexStorage::persist_batch`] so existing custom storage backends remain
64    /// compatible.
65    fn persist_batch_refs(&self, index_dir: &Path, entries: &[&FileIndex]) -> Result<()> {
66        let owned = entries.iter().map(|entry| (*entry).clone()).collect::<Vec<_>>();
67        self.persist_batch(index_dir, &owned)
68    }
69}
70
71/// Directory traversal filter hook for [`SimpleIndexer`].
72pub trait TraversalFilter: Send + Sync {
73    /// Determine if the indexer should descend into the provided directory.
74    fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool;
75
76    /// Determine if the indexer should process the provided file.
77    fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool;
78}
79
80/// Markdown-backed [`IndexStorage`] implementation.
81#[derive(Debug, Default, Clone)]
82pub struct MarkdownIndexStorage;
83
84impl IndexStorage for MarkdownIndexStorage {
85    fn init(&self, index_dir: &Path) -> Result<()> {
86        fs::create_dir_all(index_dir)?;
87        Ok(())
88    }
89
90    fn persist(&self, index_dir: &Path, entry: &FileIndex) -> Result<()> {
91        fs::create_dir_all(index_dir)?;
92        let file_name = format!("{}.md", calculate_hash(&entry.path));
93        let index_path = index_dir.join(file_name);
94        let file = fs::File::create(index_path)?;
95        let mut writer = BufWriter::new(file);
96        writeln!(writer, "# File Index: {}", entry.path)?;
97        writeln!(writer)?;
98        write_markdown_fields(&mut writer, entry)?;
99        writer.flush()?;
100        Ok(())
101    }
102
103    fn prefers_snapshot_persistence(&self) -> bool {
104        true
105    }
106
107    fn remove(&self, index_dir: &Path, file_path: &Path) -> Result<()> {
108        let file_name = format!("{}.md", calculate_hash(file_path.to_string_lossy().as_ref()));
109        let index_path = index_dir.join(file_name);
110        match fs::remove_file(index_path) {
111            Ok(()) => Ok(()),
112            Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
113            Err(err) => Err(err.into()),
114        }
115    }
116
117    fn persist_batch(&self, index_dir: &Path, entries: &[FileIndex]) -> Result<()> {
118        persist_markdown_snapshot(index_dir, entries.iter())
119    }
120
121    fn persist_batch_refs(&self, index_dir: &Path, entries: &[&FileIndex]) -> Result<()> {
122        persist_markdown_snapshot(index_dir, entries.iter().copied())
123    }
124}
125
126fn persist_markdown_snapshot<'a>(index_dir: &Path, entries: impl IntoIterator<Item = &'a FileIndex>) -> Result<()> {
127    let entries = entries.into_iter().collect::<Vec<_>>();
128
129    fs::create_dir_all(index_dir)?;
130    let temp_path = index_dir.join(".index.md.tmp");
131    let final_path = index_dir.join("index.md");
132    let file = fs::File::create(&temp_path)?;
133    let mut writer = BufWriter::new(file);
134
135    writeln!(writer, "# Workspace File Index")?;
136    writeln!(writer)?;
137    writeln!(writer, "- **Entries**: {}", entries.len())?;
138    writeln!(writer)?;
139
140    for entry in entries {
141        write_markdown_entry(&mut writer, entry)?;
142    }
143
144    writer.flush()?;
145    fs::rename(temp_path, final_path)?;
146    cleanup_legacy_markdown_entries(index_dir)?;
147    Ok(())
148}
149
150/// Default traversal filter powered by [`SimpleIndexerConfig`].
151#[derive(Debug, Default, Clone)]
152pub struct ConfigTraversalFilter;
153
154impl TraversalFilter for ConfigTraversalFilter {
155    fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
156        !should_skip_dir(path, config)
157    }
158
159    fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
160        if !path.is_file() {
161            return false;
162        }
163
164        // Skip hidden files when configured.
165        if config.ignore_hidden && path.file_name().and_then(|n| n.to_str()).is_some_and(|s| s.starts_with('.')) {
166            return false;
167        }
168
169        // Always skip known sensitive files regardless of config.
170        if let Some(file_name) = path.file_name().and_then(|n| n.to_str())
171            && (vtcode_commons::exclusions::is_sensitive_file(file_name)
172                || file_name == ".gitignore"
173                || file_name == ".git")
174        {
175            return false;
176        }
177
178        true
179    }
180}
181
182/// Configuration for [`SimpleIndexer`].
183#[derive(Clone, Debug)]
184pub struct SimpleIndexerConfig {
185    workspace_root: PathBuf,
186    index_dir: PathBuf,
187    ignore_hidden: bool,
188    excluded_dirs: Vec<PathBuf>,
189    allowed_dirs: Vec<PathBuf>,
190}
191
192impl SimpleIndexerConfig {
193    /// Builds a configuration using VT Code's legacy layout as defaults.
194    fn new(workspace_root: PathBuf) -> Self {
195        let index_dir = workspace_root.join(".vtcode").join("index");
196        let vtcode_dir = workspace_root.join(".vtcode");
197        let external_dir = vtcode_dir.join("external");
198
199        let mut excluded_dirs: Vec<PathBuf> = vtcode_commons::exclusions::DEFAULT_EXCLUDED_DIRS
200            .iter()
201            .map(|name| workspace_root.join(name))
202            .collect();
203        excluded_dirs.push(index_dir.clone());
204        excluded_dirs.push(vtcode_dir);
205
206        excluded_dirs.dedup();
207
208        Self {
209            workspace_root,
210            index_dir,
211            ignore_hidden: true,
212            excluded_dirs,
213            allowed_dirs: vec![external_dir],
214        }
215    }
216
217    /// Updates the index directory used for persisted metadata.
218    pub fn with_index_dir(mut self, index_dir: impl Into<PathBuf>) -> Self {
219        let index_dir = index_dir.into();
220        self.index_dir = index_dir.clone();
221        self.push_unique_excluded(index_dir);
222        self
223    }
224
225    /// Adds an allowed directory that should be indexed even if hidden or inside an excluded parent.
226    pub fn add_allowed_dir(mut self, path: impl Into<PathBuf>) -> Self {
227        let path = path.into();
228        if !self.allowed_dirs.iter().any(|existing| existing == &path) {
229            self.allowed_dirs.push(path);
230        }
231        self
232    }
233
234    /// Adds an additional excluded directory to skip during traversal.
235    pub fn add_excluded_dir(mut self, path: impl Into<PathBuf>) -> Self {
236        let path = path.into();
237        self.push_unique_excluded(path);
238        self
239    }
240
241    /// Toggles whether hidden directories (prefix `.`) are ignored.
242    fn ignore_hidden(mut self, ignore_hidden: bool) -> Self {
243        self.ignore_hidden = ignore_hidden;
244        self
245    }
246
247    /// Workspace root accessor.
248    pub fn workspace_root(&self) -> &Path {
249        &self.workspace_root
250    }
251
252    /// Index directory accessor.
253    fn index_dir(&self) -> &Path {
254        &self.index_dir
255    }
256
257    fn push_unique_excluded(&mut self, path: PathBuf) {
258        if !self.excluded_dirs.iter().any(|existing| existing == &path) {
259            self.excluded_dirs.push(path);
260        }
261    }
262}
263
264/// Simple file index entry.
265#[derive(Debug, Clone, Serialize, Deserialize)]
266pub struct FileIndex {
267    /// File path.
268    path: String,
269    /// File content hash for change detection.
270    hash: String,
271    /// Last modified timestamp.
272    modified: u64,
273    /// File size.
274    size: u64,
275    /// Language/extension.
276    language: String,
277    /// Simple tags.
278    tags: Vec<String>,
279}
280
281/// Simple search result.
282#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct SearchResult {
284    file_path: String,
285    line_number: usize,
286    line_content: String,
287    matches: Vec<String>,
288}
289
290/// Simple file indexer.
291pub struct SimpleIndexer {
292    config: SimpleIndexerConfig,
293    index_cache: HashMap<String, FileIndex>,
294    content_cache: HashMap<String, (String, Arc<str>)>,
295    storage: Arc<dyn IndexStorage>,
296    filter: Arc<dyn TraversalFilter>,
297}
298
299impl SimpleIndexer {
300    /// Create a new simple indexer with default VT Code paths.
301    pub fn new(workspace_root: PathBuf) -> Self {
302        Self::with_components(
303            SimpleIndexerConfig::new(workspace_root),
304            Arc::new(MarkdownIndexStorage),
305            Arc::new(ConfigTraversalFilter),
306        )
307    }
308
309    /// Create a simple indexer with the provided configuration.
310    fn with_config(config: SimpleIndexerConfig) -> Self {
311        Self::with_components(config, Arc::new(MarkdownIndexStorage), Arc::new(ConfigTraversalFilter))
312    }
313
314    /// Create a new simple indexer using a custom index directory.
315    pub fn with_index_dir(workspace_root: PathBuf, index_dir: PathBuf) -> Self {
316        let config = SimpleIndexerConfig::new(workspace_root).with_index_dir(index_dir);
317        Self::with_config(config)
318    }
319
320    /// Create an indexer with explicit storage and traversal filter implementations.
321    fn with_components(
322        config: SimpleIndexerConfig,
323        storage: Arc<dyn IndexStorage>,
324        filter: Arc<dyn TraversalFilter>,
325    ) -> Self {
326        Self {
327            config,
328            index_cache: HashMap::new(),
329            content_cache: HashMap::new(),
330            storage,
331            filter,
332        }
333    }
334
335    /// Replace the storage backend used to persist index entries.
336    fn with_storage(self, storage: Arc<dyn IndexStorage>) -> Self {
337        Self { storage, ..self }
338    }
339
340    /// Replace the traversal filter used to decide which files and directories are indexed.
341    fn with_filter(self, filter: Arc<dyn TraversalFilter>) -> Self {
342        Self { filter, ..self }
343    }
344
345    /// Initialize the index directory.
346    pub fn init(&self) -> Result<()> {
347        self.storage.init(self.config.index_dir())
348    }
349
350    /// Get the workspace root path.
351    pub fn workspace_root(&self) -> &Path {
352        self.config.workspace_root()
353    }
354
355    /// Get the index directory used for persisted metadata.
356    pub fn index_dir(&self) -> &Path {
357        self.config.index_dir()
358    }
359
360    /// Index a single file.
361    fn index_file(&mut self, file_path: &Path) -> Result<()> {
362        let cache_key = file_path.to_string_lossy().into_owned();
363
364        if self.storage.prefers_snapshot_persistence() {
365            let next_entry = if file_path.exists() && self.should_process_file_path(file_path) {
366                self.build_file_index(file_path)?
367            } else {
368                None
369            };
370
371            self.apply_snapshot_file_update(cache_key, next_entry)?;
372            return Ok(());
373        }
374
375        if !file_path.exists() || !self.should_process_file_path(file_path) {
376            self.index_cache.remove(cache_key.as_str());
377            self.storage.remove(self.config.index_dir(), file_path)?;
378            return Ok(());
379        }
380
381        if let Some(index) = self.build_file_index(file_path)? {
382            self.storage.persist(self.config.index_dir(), &index)?;
383            self.index_cache.insert(index.path.clone(), index);
384        } else {
385            self.index_cache.remove(cache_key.as_str());
386            self.storage.remove(self.config.index_dir(), file_path)?;
387        }
388
389        Ok(())
390    }
391
392    /// Index all files in directory recursively.
393    /// Respects .gitignore, .ignore, and other ignore files.
394    /// SECURITY: Always skips hidden files and sensitive data (.env, .git, etc.)
395    pub fn index_directory(&mut self, dir_path: &Path) -> Result<()> {
396        let walker = self.build_walker(dir_path);
397
398        let mut entries = Vec::new();
399
400        for entry in walker.filter_map(|e| e.ok()) {
401            let path = entry.path();
402
403            // Only index files, not directories
404            if entry.file_type().is_some_and(|ft| ft.is_file())
405                && let Some(index) = self.build_file_index(path)?
406            {
407                entries.push(index);
408            }
409        }
410
411        if self.storage.prefers_snapshot_persistence() {
412            self.apply_snapshot_directory_update(dir_path, &entries)?;
413        } else {
414            entries.sort_unstable_by(|left, right| left.path.cmp(&right.path));
415            self.storage.persist_batch(self.config.index_dir(), &entries)?;
416        }
417
418        self.replace_cached_entries(dir_path, &entries);
419
420        Ok(())
421    }
422
423    /// Discover all files in directory recursively without indexing them.
424    /// This is much faster than `index_directory` as it avoids hashing and persistence.
425    pub fn discover_files(&self, dir_path: &Path) -> Vec<String> {
426        let walker = self.build_walker(dir_path);
427
428        let mut files = walker
429            .filter_map(|e| e.ok())
430            .filter(|e| {
431                if !e.file_type().is_some_and(|ft| ft.is_file()) {
432                    return false;
433                }
434
435                self.should_process_file_path(e.path())
436            })
437            .map(|e| e.path().to_string_lossy().into_owned())
438            .collect::<Vec<_>>();
439        files.sort_unstable();
440        files
441    }
442
443    /// List the immediate children of `dir_path` (one level deep) without
444    /// recursing into subdirectories.
445    ///
446    /// Uses the same ignore/hidden/excluded-directory rules as [`Self::discover_files`]
447    /// (via the shared traversal filter), so expensive subtrees such as
448    /// `node_modules`, `.git`, and build directories are never listed. This lets
449    /// callers build a directory navigator that only touches the directories the
450    /// user actually opens, instead of walking the entire workspace up front.
451    ///
452    /// Returns `(path, is_dir)` pairs with directories sorted before files.
453    pub fn discover_dir_entries(&self, dir_path: &Path) -> Vec<(PathBuf, bool)> {
454        let walker = self.build_shallow_walker(dir_path);
455
456        let mut entries: Vec<(PathBuf, bool)> = walker
457            .filter_map(|e| e.ok())
458            .filter(|e| e.path() != dir_path)
459            .map(|e| {
460                let path = e.path().to_path_buf();
461                let is_dir = e.file_type().is_some_and(|ft| ft.is_dir());
462                (path, is_dir)
463            })
464            .filter(|(path, is_dir)| {
465                if *is_dir {
466                    !should_skip_dir(path, &self.config)
467                } else {
468                    self.should_process_file_path(path)
469                }
470            })
471            .collect();
472
473        entries.sort_by(|a, b| {
474            b.1.cmp(&a.1)
475                .then_with(|| a.0.to_string_lossy().to_lowercase().cmp(&b.0.to_string_lossy().to_lowercase()))
476        });
477        entries
478    }
479
480    /// Internal helper for regex-based file content search.
481    /// Used by both `search()` and `grep()` to avoid code duplication.
482    fn search_files_internal(
483        &self,
484        regex: &Regex,
485        path_filter: Option<&str>,
486        extract_matches: bool,
487    ) -> Vec<SearchResult> {
488        const PARALLEL_THRESHOLD: usize = 64;
489
490        let candidate_paths: Vec<&String> = self
491            .index_cache
492            .keys()
493            .filter(|file_path| path_filter.is_none_or(|filter| file_path.contains(filter)))
494            .collect();
495
496        let mut content_lookup: HashMap<&String, Arc<str>> = HashMap::with_capacity(candidate_paths.len());
497        for path in &candidate_paths {
498            if let Some(index) = self.index_cache.get(*path)
499                && let Some((hash, content)) = self.content_cache.get(*path)
500                && hash == &index.hash
501            {
502                content_lookup.insert(*path, content.clone());
503            }
504        }
505
506        let map_file = move |file_path: &&String| -> Vec<SearchResult> {
507            if let Some(cached) = content_lookup.get(file_path) {
508                return Self::search_content(cached.as_ref(), regex, file_path, extract_matches);
509            }
510            let text = match fs::read_to_string(file_path) {
511                Ok(text) => text,
512                Err(_) => return Vec::new(),
513            };
514            Self::search_content(&text, regex, file_path, extract_matches)
515        };
516
517        let mut results: Vec<SearchResult> = if candidate_paths.len() <= PARALLEL_THRESHOLD {
518            candidate_paths.iter().flat_map(map_file).collect()
519        } else {
520            candidate_paths.par_iter().flat_map(map_file).collect()
521        };
522
523        results.sort_unstable_by(|left, right| {
524            left.file_path
525                .cmp(&right.file_path)
526                .then_with(|| left.line_number.cmp(&right.line_number))
527        });
528        results
529    }
530
531    #[inline]
532    fn search_content(content: &str, regex: &Regex, file_path: &&String, extract_matches: bool) -> Vec<SearchResult> {
533        let mut local = Vec::new();
534        for (line_num, line) in content.lines().enumerate() {
535            if regex.is_match(line) {
536                let line_content = line.to_string();
537                let matches = if extract_matches {
538                    regex.find_iter(line).map(|m| m.as_str().to_string()).collect()
539                } else {
540                    vec![line_content.clone()]
541                };
542
543                local.push(SearchResult {
544                    file_path: (*file_path).clone(),
545                    line_number: line_num + 1,
546                    line_content,
547                    matches,
548                });
549            }
550        }
551        local
552    }
553
554    /// Search files using regex pattern.
555    pub fn search(&self, pattern: &str, path_filter: Option<&str>) -> Result<Vec<SearchResult>> {
556        let regex = Regex::new(pattern)?;
557        Ok(self.search_files_internal(&regex, path_filter, true))
558    }
559
560    /// Find files by name pattern.
561    fn find_files(&self, pattern: &str) -> Result<Vec<String>> {
562        let regex = Regex::new(pattern)?;
563        let mut results = Vec::with_capacity(self.index_cache.len());
564
565        for file_path in self.index_cache.keys() {
566            if regex.is_match(file_path) {
567                results.push(file_path.clone());
568            }
569        }
570
571        results.sort_unstable();
572        Ok(results)
573    }
574
575    /// Get all indexed files without pattern matching.
576    /// This is more efficient than using find_files(".*").
577    fn all_files(&self) -> Vec<String> {
578        let mut files = self.index_cache.keys().cloned().collect::<Vec<_>>();
579        files.sort_unstable();
580        files
581    }
582
583    /// Get file content with line numbers.
584    fn get_file_content(&self, file_path: &str, start_line: Option<usize>, end_line: Option<usize>) -> Result<String> {
585        let content = fs::read_to_string(file_path)?;
586        let start = start_line.unwrap_or(1).max(1);
587        let end = end_line.unwrap_or(usize::MAX);
588
589        if start > end {
590            return Ok(String::new());
591        }
592
593        let mut result = String::with_capacity(content.len());
594        for (line_number, line) in content.lines().enumerate() {
595            let line_number = line_number + 1;
596            if line_number < start {
597                continue;
598            }
599            if line_number > end {
600                break;
601            }
602            writeln!(&mut result, "{line_number}: {line}")?;
603        }
604
605        Ok(result)
606    }
607
608    /// List files in directory (like ls).
609    pub fn list_files(&self, dir_path: &str, show_hidden: bool) -> Result<Vec<String>> {
610        let path = Path::new(dir_path);
611        if !path.exists() {
612            return Ok(vec![]);
613        }
614
615        let mut files = Vec::new();
616
617        for entry in fs::read_dir(path)? {
618            let entry = entry?;
619            let file_name = entry.file_name().to_string_lossy().into_owned();
620
621            if !show_hidden && file_name.starts_with('.') {
622                continue;
623            }
624
625            files.push(file_name);
626        }
627
628        files.sort_unstable();
629        Ok(files)
630    }
631
632    /// Grep-like search (like grep command).
633    pub fn grep(&self, pattern: &str, file_pattern: Option<&str>) -> Result<Vec<SearchResult>> {
634        let regex = Regex::new(pattern)?;
635        Ok(self.search_files_internal(&regex, file_pattern, false))
636    }
637
638    fn is_allowed_path(&self, path: &Path) -> bool {
639        self.config.allowed_dirs.iter().any(|allowed| path.starts_with(allowed))
640    }
641
642    #[inline]
643    fn get_modified_time(&self, file_path: &Path) -> Result<u64> {
644        let metadata = fs::metadata(file_path)?;
645        let modified = metadata.modified()?;
646        Ok(modified.duration_since(SystemTime::UNIX_EPOCH)?.as_secs())
647    }
648
649    #[inline]
650    fn detect_language(&self, file_path: &Path) -> String {
651        file_path
652            .extension()
653            .and_then(|ext| ext.to_str())
654            .unwrap_or("unknown")
655            .to_string()
656    }
657
658    fn build_file_index(&mut self, file_path: &Path) -> Result<Option<FileIndex>> {
659        if !self.should_process_file_path(file_path) {
660            return Ok(None);
661        }
662
663        let content = match fs::read_to_string(file_path) {
664            Ok(text) => text,
665            Err(err) => {
666                if err.kind() == ErrorKind::InvalidData {
667                    return Ok(None);
668                }
669                return Err(err.into());
670            }
671        };
672
673        let index = FileIndex {
674            path: file_path.to_string_lossy().into_owned(),
675            hash: calculate_hash(&content),
676            modified: self.get_modified_time(file_path)?,
677            size: content.len() as u64,
678            language: self.detect_language(file_path),
679            tags: vec![],
680        };
681
682        self.content_cache
683            .insert(index.path.clone(), (index.hash.clone(), Arc::from(content)));
684
685        Ok(Some(index))
686    }
687
688    #[inline]
689    fn is_excluded_path(&self, path: &Path) -> bool {
690        self.config.excluded_dirs.iter().any(|excluded| path.starts_with(excluded))
691    }
692
693    #[inline]
694    fn should_index_file_path(&self, path: &Path) -> bool {
695        self.filter.should_index_file(path, &self.config)
696    }
697
698    #[inline]
699    fn should_process_file_path(&self, path: &Path) -> bool {
700        if self.is_allowed_path(path) {
701            return self.should_index_file_path(path);
702        }
703
704        !self.is_excluded_path(path) && self.should_index_file_path(path)
705    }
706
707    fn build_walker(&self, dir_path: &Path) -> Walk {
708        let walk_root = dir_path.to_path_buf();
709        let config = self.config.clone();
710        let filter = Arc::clone(&self.filter);
711
712        let mut builder = vtcode_commons::walk::build_default_walker(dir_path);
713        builder.filter_entry(move |entry| should_visit_entry(entry, walk_root.as_path(), &config, filter.as_ref()));
714        builder.build()
715    }
716
717    fn build_shallow_walker(&self, dir_path: &Path) -> Walk {
718        let walk_root = dir_path.to_path_buf();
719        let config = self.config.clone();
720        let filter = Arc::clone(&self.filter);
721
722        let mut builder = vtcode_commons::walk::build_default_walker(dir_path);
723        // Only immediate children — directory navigation lists one level at a time.
724        builder.max_depth(Some(1));
725        builder.filter_entry(move |entry| should_visit_entry(entry, walk_root.as_path(), &config, filter.as_ref()));
726        builder.build()
727    }
728
729    fn replace_cached_entries(&mut self, dir_path: &Path, entries: &[FileIndex]) {
730        self.index_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
731        self.content_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
732
733        self.index_cache
734            .extend(entries.iter().cloned().map(|entry| (entry.path.clone(), entry)));
735    }
736
737    fn apply_snapshot_file_update(&mut self, cache_key: String, next_entry: Option<FileIndex>) -> Result<()> {
738        let previous_entry = match next_entry {
739            Some(entry) => self.index_cache.insert(cache_key.clone(), entry),
740            None => self.index_cache.remove(cache_key.as_str()),
741        };
742        let previous_content = self.content_cache.remove(cache_key.as_str());
743
744        if let Err(err) = self.persist_current_snapshot() {
745            match previous_entry {
746                Some(entry) => {
747                    self.index_cache.insert(cache_key.clone(), entry);
748                }
749                None => {
750                    self.index_cache.remove(cache_key.as_str());
751                }
752            }
753            if let Some(content) = previous_content {
754                self.content_cache.insert(cache_key, content);
755            }
756            return Err(err);
757        }
758
759        Ok(())
760    }
761
762    fn apply_snapshot_directory_update(&mut self, dir_path: &Path, entries: &[FileIndex]) -> Result<()> {
763        let previous_entries = self.take_cached_entries(dir_path);
764        self.index_cache
765            .extend(entries.iter().cloned().map(|entry| (entry.path.clone(), entry)));
766
767        if let Err(err) = self.persist_current_snapshot() {
768            self.index_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
769            self.index_cache
770                .extend(previous_entries.into_iter().map(|entry| (entry.path.clone(), entry)));
771            return Err(err);
772        }
773
774        Ok(())
775    }
776
777    fn take_cached_entries(&mut self, dir_path: &Path) -> Vec<FileIndex> {
778        let keys = self
779            .index_cache
780            .keys()
781            .filter(|path| Path::new(path).starts_with(dir_path))
782            .cloned()
783            .collect::<Vec<_>>();
784
785        keys.into_iter()
786            .filter_map(|path| self.index_cache.remove(path.as_str()))
787            .collect()
788    }
789
790    fn persist_current_snapshot(&self) -> Result<()> {
791        let mut snapshot = self.index_cache.values().collect::<Vec<_>>();
792        snapshot.sort_unstable_by(|left, right| left.path.cmp(&right.path));
793        self.storage.persist_batch_refs(self.config.index_dir(), &snapshot)
794    }
795}
796
797impl Clone for SimpleIndexer {
798    fn clone(&self) -> Self {
799        Self {
800            config: self.config.clone(),
801            index_cache: self.index_cache.clone(),
802            content_cache: self.content_cache.clone(),
803            storage: self.storage.clone(),
804            filter: self.filter.clone(),
805        }
806    }
807}
808
809fn should_skip_dir(path: &Path, config: &SimpleIndexerConfig) -> bool {
810    if is_allowed_path_or_ancestor(path, config) {
811        return false;
812    }
813
814    if config.excluded_dirs.iter().any(|excluded| path.starts_with(excluded)) {
815        return true;
816    }
817
818    if config.ignore_hidden
819        && path
820            .file_name()
821            .and_then(|name| name.to_str())
822            .is_some_and(|name_str| name_str.starts_with('.'))
823    {
824        return true;
825    }
826
827    false
828}
829
830fn is_allowed_path_or_ancestor(path: &Path, config: &SimpleIndexerConfig) -> bool {
831    config
832        .allowed_dirs
833        .iter()
834        .any(|allowed| path.starts_with(allowed) || allowed.starts_with(path))
835}
836
837fn should_visit_entry(
838    entry: &DirEntry,
839    walk_root: &Path,
840    config: &SimpleIndexerConfig,
841    filter: &dyn TraversalFilter,
842) -> bool {
843    if entry.path() == walk_root {
844        return true;
845    }
846
847    if !entry.file_type().is_some_and(|file_type| file_type.is_dir()) {
848        return true;
849    }
850
851    filter.should_descend(entry.path(), config)
852}
853
854#[inline]
855fn calculate_hash(content: &str) -> String {
856    vtcode_commons::utils::calculate_sha256(content.as_bytes())
857}
858
859fn write_markdown_entry(writer: &mut impl Write, entry: &FileIndex) -> std::io::Result<()> {
860    writeln!(writer, "## {}", entry.path)?;
861    writeln!(writer)?;
862    write_markdown_fields(writer, entry)?;
863    writeln!(writer)?;
864    Ok(())
865}
866
867fn write_markdown_fields(writer: &mut impl Write, entry: &FileIndex) -> std::io::Result<()> {
868    writeln!(writer, "- **Path**: {}", entry.path)?;
869    writeln!(writer, "- **Hash**: {}", entry.hash)?;
870    writeln!(writer, "- **Modified**: {}", entry.modified)?;
871    writeln!(writer, "- **Size**: {} bytes", entry.size)?;
872    writeln!(writer, "- **Language**: {}", entry.language)?;
873    writeln!(writer, "- **Tags**: {}", entry.tags.join(", "))?;
874    Ok(())
875}
876
877fn cleanup_legacy_markdown_entries(index_dir: &Path) -> Result<()> {
878    for entry in fs::read_dir(index_dir)? {
879        let entry = entry?;
880        let file_name = entry.file_name();
881        let file_name = file_name.to_string_lossy();
882        if is_legacy_markdown_entry_name(file_name.as_ref()) {
883            fs::remove_file(entry.path())?;
884        }
885    }
886    Ok(())
887}
888
889#[inline]
890fn is_legacy_markdown_entry_name(file_name: &str) -> bool {
891    let Some(hash_part) = file_name.strip_suffix(".md") else {
892        return false;
893    };
894    hash_part.len() == 64 && hash_part.bytes().all(|byte| byte.is_ascii_hexdigit())
895}
896
897#[cfg(test)]
898mod tests {
899    use super::*;
900    use std::fs;
901    use std::sync::{Arc, Mutex};
902    use tempfile::tempdir;
903
904    #[test]
905    fn skips_hidden_directories_by_default() -> Result<()> {
906        let temp = tempdir()?;
907        let workspace = temp.path();
908        let hidden_dir = workspace.join(".private");
909        fs::create_dir_all(&hidden_dir)?;
910        fs::write(hidden_dir.join("secret.txt"), "classified")?;
911
912        let visible_dir = workspace.join("src");
913        fs::create_dir_all(&visible_dir)?;
914        fs::write(visible_dir.join("lib.rs"), "fn main() {}")?;
915
916        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
917        indexer.init()?;
918        indexer.index_directory(workspace)?;
919
920        assert!(indexer.find_files("secret\\.txt$")?.is_empty());
921        assert!(!indexer.find_files("lib\\.rs$")?.is_empty());
922
923        Ok(())
924    }
925
926    #[test]
927    fn can_include_hidden_directories_when_configured() -> Result<()> {
928        let temp = tempdir()?;
929        let workspace = temp.path();
930        let hidden_dir = workspace.join(".cache");
931        fs::create_dir_all(&hidden_dir)?;
932        fs::write(hidden_dir.join("data.log"), "details")?;
933
934        let config = SimpleIndexerConfig::new(workspace.to_path_buf()).ignore_hidden(false);
935        let mut indexer = SimpleIndexer::with_config(config);
936        indexer.init()?;
937        indexer.index_directory(workspace)?;
938
939        let results = indexer.find_files("data\\.log$")?;
940        assert_eq!(results.len(), 1);
941
942        Ok(())
943    }
944
945    #[test]
946    fn indexes_allowed_directories_inside_hidden_excluded_parents() -> Result<()> {
947        let temp = tempdir()?;
948        let workspace = temp.path();
949        let allowed_dir = workspace.join(".vtcode").join("external");
950        fs::create_dir_all(&allowed_dir)?;
951        fs::write(allowed_dir.join("plugin.toml"), "name = 'demo'")?;
952
953        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
954        indexer.init()?;
955        indexer.index_directory(workspace)?;
956
957        let results = indexer.find_files("plugin\\.toml$")?;
958        assert_eq!(results.len(), 1);
959
960        Ok(())
961    }
962
963    #[test]
964    fn reindexing_prunes_deleted_files_from_cache() -> Result<()> {
965        let temp = tempdir()?;
966        let workspace = temp.path();
967        let file_path = workspace.join("notes.txt");
968        fs::write(&file_path, "remember this")?;
969
970        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
971        indexer.init()?;
972        indexer.index_directory(workspace)?;
973        assert_eq!(indexer.find_files("notes\\.txt$")?.len(), 1);
974
975        fs::remove_file(&file_path)?;
976        indexer.index_directory(workspace)?;
977
978        assert!(indexer.find_files("notes\\.txt$")?.is_empty());
979        assert!(indexer.all_files().is_empty());
980
981        Ok(())
982    }
983
984    #[test]
985    fn index_file_skips_excluded_paths() -> Result<()> {
986        let temp = tempdir()?;
987        let workspace = temp.path();
988        let index_dir = workspace.join(".vtcode").join("index");
989        fs::create_dir_all(&index_dir)?;
990        let generated_index = index_dir.join("index.md");
991        fs::write(&generated_index, "# generated")?;
992
993        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
994        indexer.init()?;
995        indexer.index_file(&generated_index)?;
996
997        assert!(indexer.all_files().is_empty());
998
999        Ok(())
1000    }
1001
1002    #[test]
1003    fn index_file_removes_stale_entry_when_file_becomes_unreadable() -> Result<()> {
1004        let temp = tempdir()?;
1005        let workspace = temp.path();
1006        let file_path = workspace.join("notes.txt");
1007        fs::write(&file_path, "remember this")?;
1008
1009        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1010        indexer.init()?;
1011        indexer.index_file(&file_path)?;
1012        assert!(
1013            indexer
1014                .find_files("notes\\.txt$")?
1015                .iter()
1016                .any(|file| file.ends_with("notes.txt"))
1017        );
1018
1019        fs::write(&file_path, [0xFF, 0xFE, 0xFD])?;
1020        indexer.index_file(&file_path)?;
1021
1022        assert!(indexer.find_files("notes\\.txt$")?.is_empty());
1023
1024        let index_content = fs::read_to_string(workspace.join(".vtcode").join("index").join("index.md"))?;
1025        assert!(!index_content.contains(file_path.to_string_lossy().as_ref()));
1026
1027        Ok(())
1028    }
1029
1030    #[test]
1031    fn index_file_maintains_markdown_snapshot_across_updates() -> Result<()> {
1032        let temp = tempdir()?;
1033        let workspace = temp.path();
1034        let first = workspace.join("first.txt");
1035        let second = workspace.join("second.txt");
1036        fs::write(&first, "one")?;
1037        fs::write(&second, "two")?;
1038
1039        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1040        indexer.init()?;
1041        indexer.index_file(&first)?;
1042        indexer.index_file(&second)?;
1043
1044        let index_dir = workspace.join(".vtcode").join("index");
1045        let files = fs::read_dir(&index_dir)?
1046            .filter_map(|entry| entry.ok())
1047            .map(|entry| entry.file_name().to_string_lossy().into_owned())
1048            .collect::<Vec<_>>();
1049        assert_eq!(files, vec!["index.md".to_string()]);
1050
1051        let index_content = fs::read_to_string(index_dir.join("index.md"))?;
1052        assert!(index_content.contains(first.to_string_lossy().as_ref()));
1053        assert!(index_content.contains(second.to_string_lossy().as_ref()));
1054
1055        Ok(())
1056    }
1057
1058    #[test]
1059    fn index_directory_writes_markdown_snapshot_without_manual_init() -> Result<()> {
1060        let temp = tempdir()?;
1061        let workspace = temp.path();
1062        fs::write(workspace.join("notes.txt"), "remember this")?;
1063
1064        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1065        indexer.index_directory(workspace)?;
1066
1067        let index_content = fs::read_to_string(workspace.join(".vtcode").join("index").join("index.md"))?;
1068        assert!(index_content.contains(workspace.join("notes.txt").to_string_lossy().as_ref()));
1069
1070        Ok(())
1071    }
1072
1073    #[test]
1074    fn get_file_content_clamps_ranges_without_panicking() -> Result<()> {
1075        let temp = tempdir()?;
1076        let workspace = temp.path();
1077        let file_path = workspace.join("notes.txt");
1078        fs::write(&file_path, "first\nsecond")?;
1079
1080        let indexer = SimpleIndexer::new(workspace.to_path_buf());
1081        let file_path = file_path.to_string_lossy().into_owned();
1082
1083        assert_eq!(indexer.get_file_content(&file_path, Some(5), None)?, "");
1084        assert_eq!(indexer.get_file_content(&file_path, Some(0), Some(1))?, "1: first\n");
1085        assert_eq!(indexer.get_file_content(&file_path, Some(2), Some(1))?, "");
1086
1087        Ok(())
1088    }
1089
1090    #[test]
1091    fn supports_custom_storage_backends() -> Result<()> {
1092        #[derive(Clone, Default)]
1093        struct MemoryStorage {
1094            records: Arc<Mutex<Vec<FileIndex>>>,
1095        }
1096
1097        impl MemoryStorage {
1098            fn new(records: Arc<Mutex<Vec<FileIndex>>>) -> Self {
1099                Self { records }
1100            }
1101        }
1102
1103        impl IndexStorage for MemoryStorage {
1104            fn init(&self, _index_dir: &Path) -> Result<()> {
1105                Ok(())
1106            }
1107
1108            fn persist(&self, _index_dir: &Path, entry: &FileIndex) -> Result<()> {
1109                let mut guard = self.records.lock().expect("lock poisoned");
1110                guard.push(entry.clone());
1111                Ok(())
1112            }
1113        }
1114
1115        let temp = tempdir()?;
1116        let workspace = temp.path();
1117        fs::write(workspace.join("notes.txt"), "remember this")?;
1118
1119        let records: Arc<Mutex<Vec<FileIndex>>> = Arc::new(Mutex::new(Vec::new()));
1120        let storage = MemoryStorage::new(records.clone());
1121
1122        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1123        let mut indexer = SimpleIndexer::with_config(config).with_storage(Arc::new(storage));
1124        indexer.init()?;
1125        indexer.index_directory(workspace)?;
1126
1127        let entries = records.lock().expect("lock poisoned");
1128        assert_eq!(entries.len(), 1);
1129        assert_eq!(entries[0].path, workspace.join("notes.txt").to_string_lossy().into_owned());
1130
1131        Ok(())
1132    }
1133
1134    #[test]
1135    fn custom_filters_can_skip_files() -> Result<()> {
1136        #[derive(Default)]
1137        struct SkipRustFilter {
1138            inner: ConfigTraversalFilter,
1139        }
1140
1141        impl TraversalFilter for SkipRustFilter {
1142            fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
1143                self.inner.should_descend(path, config)
1144            }
1145
1146            fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
1147                if path
1148                    .extension()
1149                    .and_then(|ext| ext.to_str())
1150                    .is_some_and(|ext| ext.eq_ignore_ascii_case("rs"))
1151                {
1152                    return false;
1153                }
1154
1155                self.inner.should_index_file(path, config)
1156            }
1157        }
1158
1159        let temp = tempdir()?;
1160        let workspace = temp.path();
1161        fs::write(workspace.join("lib.rs"), "fn main() {}")?;
1162        fs::write(workspace.join("README.md"), "# Notes")?;
1163
1164        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1165        let mut indexer = SimpleIndexer::with_config(config).with_filter(Arc::new(SkipRustFilter::default()));
1166        indexer.init()?;
1167        indexer.index_directory(workspace)?;
1168
1169        assert!(indexer.find_files("lib\\.rs$")?.is_empty());
1170        assert!(!indexer.find_files("README\\.md$")?.is_empty());
1171
1172        Ok(())
1173    }
1174
1175    #[test]
1176    fn custom_filters_can_skip_directories() -> Result<()> {
1177        #[derive(Default)]
1178        struct SkipGeneratedFilter {
1179            inner: ConfigTraversalFilter,
1180        }
1181
1182        impl TraversalFilter for SkipGeneratedFilter {
1183            fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
1184                if path.ends_with("generated") {
1185                    return false;
1186                }
1187
1188                self.inner.should_descend(path, config)
1189            }
1190
1191            fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
1192                self.inner.should_index_file(path, config)
1193            }
1194        }
1195
1196        let temp = tempdir()?;
1197        let workspace = temp.path();
1198        let generated_dir = workspace.join("generated");
1199        fs::create_dir_all(&generated_dir)?;
1200        fs::write(generated_dir.join("skip.txt"), "ignore me")?;
1201        fs::write(workspace.join("README.md"), "# Notes")?;
1202
1203        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1204        let indexer = SimpleIndexer::with_config(config).with_filter(Arc::new(SkipGeneratedFilter::default()));
1205        let files = indexer.discover_files(workspace);
1206
1207        assert!(!files.iter().any(|file| file.ends_with("skip.txt")));
1208        assert!(files.iter().any(|file| file.ends_with("README.md")));
1209
1210        Ok(())
1211    }
1212
1213    #[test]
1214    fn discover_dir_entries_is_shallow_and_ignore_aware() -> Result<()> {
1215        let temp = tempdir()?;
1216        let workspace = temp.path();
1217        fs::create_dir_all(workspace.join("src"))?;
1218        fs::create_dir_all(workspace.join("node_modules"))?;
1219        fs::create_dir_all(workspace.join(".git"))?;
1220        fs::write(workspace.join("README.md"), "# Notes")?;
1221        fs::write(workspace.join("src").join("lib.rs"), "fn main() {}")?;
1222        fs::write(workspace.join("node_modules").join("dep.js"), "x")?;
1223        fs::write(workspace.join(".git").join("config"), "x")?;
1224
1225        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1226        let indexer = SimpleIndexer::with_config(config);
1227        let entries = indexer.discover_dir_entries(workspace);
1228
1229        let names: Vec<String> = entries
1230            .iter()
1231            .map(|(p, _)| p.file_name().unwrap().to_string_lossy().into_owned())
1232            .collect();
1233
1234        assert_eq!(entries.len(), 2, "expected exactly README.md and src, got {names:?}");
1235        assert!(names.contains(&"README.md".to_string()));
1236        assert!(names.contains(&"src".to_string()));
1237
1238        let (_, src_is_dir) = entries.iter().find(|(p, _)| p.ends_with("src")).unwrap();
1239        assert!(*src_is_dir);
1240
1241        Ok(())
1242    }
1243
1244    #[test]
1245    fn indexing_multiple_directories_preserves_existing_cache_entries() -> Result<()> {
1246        let temp = tempdir()?;
1247        let workspace = temp.path();
1248        let src_dir = workspace.join("src");
1249        let docs_dir = workspace.join("docs");
1250        fs::create_dir_all(&src_dir)?;
1251        fs::create_dir_all(&docs_dir)?;
1252        fs::write(src_dir.join("lib.rs"), "fn main() {}")?;
1253        fs::write(docs_dir.join("guide.md"), "# Guide")?;
1254
1255        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1256        indexer.init()?;
1257        indexer.index_directory(&src_dir)?;
1258        indexer.index_directory(&docs_dir)?;
1259
1260        assert!(indexer.find_files("lib\\.rs$")?.iter().any(|file| file.ends_with("lib.rs")));
1261        assert!(indexer.find_files("guide\\.md$")?.iter().any(|file| file.ends_with("guide.md")));
1262
1263        let index_content = fs::read_to_string(workspace.join(".vtcode").join("index").join("index.md"))?;
1264        assert!(index_content.contains(src_dir.join("lib.rs").to_string_lossy().as_ref()));
1265        assert!(index_content.contains(docs_dir.join("guide.md").to_string_lossy().as_ref()));
1266
1267        Ok(())
1268    }
1269
1270    #[test]
1271    fn batch_indexing_writes_single_markdown_file() -> Result<()> {
1272        let temp = tempdir()?;
1273        let workspace = temp.path();
1274        fs::write(workspace.join("lib.rs"), "fn main() {}")?;
1275        fs::write(workspace.join("README.md"), "# Notes")?;
1276
1277        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1278        indexer.init()?;
1279        indexer.index_directory(workspace)?;
1280
1281        let index_dir = workspace.join(".vtcode").join("index");
1282        let files = fs::read_dir(&index_dir)?
1283            .filter_map(|entry| entry.ok())
1284            .map(|entry| entry.file_name().to_string_lossy().into_owned())
1285            .collect::<Vec<_>>();
1286        assert_eq!(files, vec!["index.md".to_string()]);
1287
1288        let index_content = fs::read_to_string(index_dir.join("index.md"))?;
1289        assert!(index_content.contains(workspace.join("lib.rs").to_string_lossy().as_ref()));
1290        assert!(index_content.contains(workspace.join("README.md").to_string_lossy().as_ref()));
1291
1292        Ok(())
1293    }
1294
1295    #[test]
1296    fn batch_indexing_removes_legacy_hashed_entries() -> Result<()> {
1297        let temp = tempdir()?;
1298        let workspace = temp.path();
1299        fs::write(workspace.join("lib.rs"), "fn main() {}")?;
1300
1301        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1302        indexer.init()?;
1303
1304        let legacy_file_name = format!("{}.md", calculate_hash("legacy-path"));
1305        let legacy_file_path = workspace.join(".vtcode").join("index").join(&legacy_file_name);
1306        fs::write(&legacy_file_path, "# legacy")?;
1307        assert!(legacy_file_path.exists());
1308
1309        indexer.index_directory(workspace)?;
1310
1311        assert!(!legacy_file_path.exists());
1312        let files = fs::read_dir(workspace.join(".vtcode").join("index"))?
1313            .filter_map(|entry| entry.ok())
1314            .map(|entry| entry.file_name().to_string_lossy().into_owned())
1315            .collect::<Vec<_>>();
1316        assert_eq!(files, vec!["index.md".to_string()]);
1317
1318        Ok(())
1319    }
1320
1321    #[test]
1322    fn snapshot_storage_uses_default_ref_batch_persistence() -> Result<()> {
1323        #[derive(Clone, Default)]
1324        struct SnapshotMemoryStorage {
1325            snapshots: Arc<Mutex<Vec<Vec<FileIndex>>>>,
1326        }
1327
1328        impl SnapshotMemoryStorage {
1329            fn new(snapshots: Arc<Mutex<Vec<Vec<FileIndex>>>>) -> Self {
1330                Self { snapshots }
1331            }
1332        }
1333
1334        impl IndexStorage for SnapshotMemoryStorage {
1335            fn init(&self, _index_dir: &Path) -> Result<()> {
1336                Ok(())
1337            }
1338
1339            fn persist(&self, _index_dir: &Path, _entry: &FileIndex) -> Result<()> {
1340                Ok(())
1341            }
1342
1343            fn prefers_snapshot_persistence(&self) -> bool {
1344                true
1345            }
1346
1347            fn persist_batch(&self, _index_dir: &Path, entries: &[FileIndex]) -> Result<()> {
1348                self.snapshots.lock().expect("lock poisoned").push(entries.to_vec());
1349                Ok(())
1350            }
1351        }
1352
1353        let temp = tempdir()?;
1354        let workspace = temp.path();
1355        let file_path = workspace.join("notes.txt");
1356        fs::write(&file_path, "remember this")?;
1357
1358        let snapshots = Arc::new(Mutex::new(Vec::new()));
1359        let storage = SnapshotMemoryStorage::new(snapshots.clone());
1360
1361        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1362        let mut indexer = SimpleIndexer::with_config(config).with_storage(Arc::new(storage));
1363        indexer.index_file(&file_path)?;
1364
1365        let snapshots = snapshots.lock().expect("lock poisoned");
1366        assert_eq!(snapshots.len(), 1);
1367        assert_eq!(snapshots[0].len(), 1);
1368        assert_eq!(snapshots[0][0].path, workspace.join("notes.txt").to_string_lossy().into_owned());
1369
1370        Ok(())
1371    }
1372
1373    #[test]
1374    fn snapshot_index_file_rolls_back_cache_when_persist_fails() -> Result<()> {
1375        #[derive(Clone, Default)]
1376        struct FlakySnapshotStorage {
1377            persist_count: Arc<Mutex<usize>>,
1378        }
1379
1380        impl IndexStorage for FlakySnapshotStorage {
1381            fn init(&self, _index_dir: &Path) -> Result<()> {
1382                Ok(())
1383            }
1384
1385            fn persist(&self, _index_dir: &Path, _entry: &FileIndex) -> Result<()> {
1386                Ok(())
1387            }
1388
1389            fn prefers_snapshot_persistence(&self) -> bool {
1390                true
1391            }
1392
1393            fn persist_batch(&self, _index_dir: &Path, _entries: &[FileIndex]) -> Result<()> {
1394                let mut count = self.persist_count.lock().expect("lock poisoned");
1395                *count += 1;
1396                if *count == 2 {
1397                    anyhow::bail!("simulated snapshot persistence failure");
1398                }
1399                Ok(())
1400            }
1401        }
1402
1403        let temp = tempdir()?;
1404        let workspace = temp.path();
1405        let first = workspace.join("first.txt");
1406        let second = workspace.join("second.txt");
1407        fs::write(&first, "one")?;
1408        fs::write(&second, "two")?;
1409
1410        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1411        let storage = Arc::new(FlakySnapshotStorage::default());
1412        let mut indexer = SimpleIndexer::with_config(config).with_storage(storage);
1413
1414        indexer.index_file(&first)?;
1415        assert!(
1416            indexer
1417                .find_files("first\\.txt$")?
1418                .iter()
1419                .any(|path| path.ends_with("first.txt"))
1420        );
1421
1422        let err = indexer.index_file(&second).expect_err("second persist should fail");
1423        assert!(err.to_string().contains("simulated snapshot persistence failure"));
1424        assert!(
1425            indexer
1426                .find_files("first\\.txt$")?
1427                .iter()
1428                .any(|path| path.ends_with("first.txt"))
1429        );
1430        assert!(indexer.find_files("second\\.txt$")?.is_empty());
1431
1432        Ok(())
1433    }
1434}