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 matches = if extract_matches {
537                    regex.find_iter(line).map(|m| m.as_str().to_string()).collect()
538                } else {
539                    vec![line.to_string()]
540                };
541
542                local.push(SearchResult {
543                    file_path: (*file_path).clone(),
544                    line_number: line_num + 1,
545                    line_content: line.to_string(),
546                    matches,
547                });
548            }
549        }
550        local
551    }
552
553    /// Search files using regex pattern.
554    pub fn search(&self, pattern: &str, path_filter: Option<&str>) -> Result<Vec<SearchResult>> {
555        let regex = Regex::new(pattern)?;
556        Ok(self.search_files_internal(&regex, path_filter, true))
557    }
558
559    /// Find files by name pattern.
560    fn find_files(&self, pattern: &str) -> Result<Vec<String>> {
561        let regex = Regex::new(pattern)?;
562        let mut results = Vec::with_capacity(self.index_cache.len());
563
564        for file_path in self.index_cache.keys() {
565            if regex.is_match(file_path) {
566                results.push(file_path.clone());
567            }
568        }
569
570        results.sort_unstable();
571        Ok(results)
572    }
573
574    /// Get all indexed files without pattern matching.
575    /// This is more efficient than using find_files(".*").
576    fn all_files(&self) -> Vec<String> {
577        let mut files = self.index_cache.keys().cloned().collect::<Vec<_>>();
578        files.sort_unstable();
579        files
580    }
581
582    /// Get file content with line numbers.
583    fn get_file_content(&self, file_path: &str, start_line: Option<usize>, end_line: Option<usize>) -> Result<String> {
584        let content = fs::read_to_string(file_path)?;
585        let start = start_line.unwrap_or(1).max(1);
586        let end = end_line.unwrap_or(usize::MAX);
587
588        if start > end {
589            return Ok(String::new());
590        }
591
592        let mut result = String::new();
593        for (line_number, line) in content.lines().enumerate() {
594            let line_number = line_number + 1;
595            if line_number < start {
596                continue;
597            }
598            if line_number > end {
599                break;
600            }
601            writeln!(&mut result, "{line_number}: {line}")?;
602        }
603
604        Ok(result)
605    }
606
607    /// List files in directory (like ls).
608    pub fn list_files(&self, dir_path: &str, show_hidden: bool) -> Result<Vec<String>> {
609        let path = Path::new(dir_path);
610        if !path.exists() {
611            return Ok(vec![]);
612        }
613
614        let mut files = Vec::new();
615
616        for entry in fs::read_dir(path)? {
617            let entry = entry?;
618            let file_name = entry.file_name().to_string_lossy().into_owned();
619
620            if !show_hidden && file_name.starts_with('.') {
621                continue;
622            }
623
624            files.push(file_name);
625        }
626
627        files.sort_unstable();
628        Ok(files)
629    }
630
631    /// Grep-like search (like grep command).
632    pub fn grep(&self, pattern: &str, file_pattern: Option<&str>) -> Result<Vec<SearchResult>> {
633        let regex = Regex::new(pattern)?;
634        Ok(self.search_files_internal(&regex, file_pattern, false))
635    }
636
637    fn is_allowed_path(&self, path: &Path) -> bool {
638        self.config.allowed_dirs.iter().any(|allowed| path.starts_with(allowed))
639    }
640
641    #[inline]
642    fn get_modified_time(&self, file_path: &Path) -> Result<u64> {
643        let metadata = fs::metadata(file_path)?;
644        let modified = metadata.modified()?;
645        Ok(modified.duration_since(SystemTime::UNIX_EPOCH)?.as_secs())
646    }
647
648    #[inline]
649    fn detect_language(&self, file_path: &Path) -> String {
650        file_path
651            .extension()
652            .and_then(|ext| ext.to_str())
653            .unwrap_or("unknown")
654            .to_string()
655    }
656
657    fn build_file_index(&mut self, file_path: &Path) -> Result<Option<FileIndex>> {
658        if !self.should_process_file_path(file_path) {
659            return Ok(None);
660        }
661
662        let content = match fs::read_to_string(file_path) {
663            Ok(text) => text,
664            Err(err) => {
665                if err.kind() == ErrorKind::InvalidData {
666                    return Ok(None);
667                }
668                return Err(err.into());
669            }
670        };
671
672        let index = FileIndex {
673            path: file_path.to_string_lossy().into_owned(),
674            hash: calculate_hash(&content),
675            modified: self.get_modified_time(file_path)?,
676            size: content.len() as u64,
677            language: self.detect_language(file_path),
678            tags: vec![],
679        };
680
681        self.content_cache
682            .insert(index.path.clone(), (index.hash.clone(), Arc::from(content)));
683
684        Ok(Some(index))
685    }
686
687    #[inline]
688    fn is_excluded_path(&self, path: &Path) -> bool {
689        self.config.excluded_dirs.iter().any(|excluded| path.starts_with(excluded))
690    }
691
692    #[inline]
693    fn should_index_file_path(&self, path: &Path) -> bool {
694        self.filter.should_index_file(path, &self.config)
695    }
696
697    #[inline]
698    fn should_process_file_path(&self, path: &Path) -> bool {
699        if self.is_allowed_path(path) {
700            return self.should_index_file_path(path);
701        }
702
703        !self.is_excluded_path(path) && self.should_index_file_path(path)
704    }
705
706    fn build_walker(&self, dir_path: &Path) -> Walk {
707        let walk_root = dir_path.to_path_buf();
708        let config = self.config.clone();
709        let filter = Arc::clone(&self.filter);
710
711        let mut builder = vtcode_commons::walk::build_default_walker(dir_path);
712        builder.filter_entry(move |entry| should_visit_entry(entry, walk_root.as_path(), &config, filter.as_ref()));
713        builder.build()
714    }
715
716    fn build_shallow_walker(&self, dir_path: &Path) -> Walk {
717        let walk_root = dir_path.to_path_buf();
718        let config = self.config.clone();
719        let filter = Arc::clone(&self.filter);
720
721        let mut builder = vtcode_commons::walk::build_default_walker(dir_path);
722        // Only immediate children — directory navigation lists one level at a time.
723        builder.max_depth(Some(1));
724        builder.filter_entry(move |entry| should_visit_entry(entry, walk_root.as_path(), &config, filter.as_ref()));
725        builder.build()
726    }
727
728    fn replace_cached_entries(&mut self, dir_path: &Path, entries: &[FileIndex]) {
729        self.index_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
730        self.content_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
731
732        self.index_cache
733            .extend(entries.iter().cloned().map(|entry| (entry.path.clone(), entry)));
734    }
735
736    fn apply_snapshot_file_update(&mut self, cache_key: String, next_entry: Option<FileIndex>) -> Result<()> {
737        let previous_entry = match next_entry {
738            Some(entry) => self.index_cache.insert(cache_key.clone(), entry),
739            None => self.index_cache.remove(cache_key.as_str()),
740        };
741        let previous_content = self.content_cache.remove(cache_key.as_str());
742
743        if let Err(err) = self.persist_current_snapshot() {
744            match previous_entry {
745                Some(entry) => {
746                    self.index_cache.insert(cache_key.clone(), entry);
747                }
748                None => {
749                    self.index_cache.remove(cache_key.as_str());
750                }
751            }
752            if let Some(content) = previous_content {
753                self.content_cache.insert(cache_key, content);
754            }
755            return Err(err);
756        }
757
758        Ok(())
759    }
760
761    fn apply_snapshot_directory_update(&mut self, dir_path: &Path, entries: &[FileIndex]) -> Result<()> {
762        let previous_entries = self.take_cached_entries(dir_path);
763        self.index_cache
764            .extend(entries.iter().cloned().map(|entry| (entry.path.clone(), entry)));
765
766        if let Err(err) = self.persist_current_snapshot() {
767            self.index_cache.retain(|path, _| !Path::new(path).starts_with(dir_path));
768            self.index_cache
769                .extend(previous_entries.into_iter().map(|entry| (entry.path.clone(), entry)));
770            return Err(err);
771        }
772
773        Ok(())
774    }
775
776    fn take_cached_entries(&mut self, dir_path: &Path) -> Vec<FileIndex> {
777        let keys = self
778            .index_cache
779            .keys()
780            .filter(|path| Path::new(path).starts_with(dir_path))
781            .cloned()
782            .collect::<Vec<_>>();
783
784        keys.into_iter()
785            .filter_map(|path| self.index_cache.remove(path.as_str()))
786            .collect()
787    }
788
789    fn persist_current_snapshot(&self) -> Result<()> {
790        let mut snapshot = self.index_cache.values().collect::<Vec<_>>();
791        snapshot.sort_unstable_by(|left, right| left.path.cmp(&right.path));
792        self.storage.persist_batch_refs(self.config.index_dir(), &snapshot)
793    }
794}
795
796impl Clone for SimpleIndexer {
797    fn clone(&self) -> Self {
798        Self {
799            config: self.config.clone(),
800            index_cache: self.index_cache.clone(),
801            content_cache: self.content_cache.clone(),
802            storage: self.storage.clone(),
803            filter: self.filter.clone(),
804        }
805    }
806}
807
808fn should_skip_dir(path: &Path, config: &SimpleIndexerConfig) -> bool {
809    if is_allowed_path_or_ancestor(path, config) {
810        return false;
811    }
812
813    if config.excluded_dirs.iter().any(|excluded| path.starts_with(excluded)) {
814        return true;
815    }
816
817    if config.ignore_hidden
818        && path
819            .file_name()
820            .and_then(|name| name.to_str())
821            .is_some_and(|name_str| name_str.starts_with('.'))
822    {
823        return true;
824    }
825
826    false
827}
828
829fn is_allowed_path_or_ancestor(path: &Path, config: &SimpleIndexerConfig) -> bool {
830    config
831        .allowed_dirs
832        .iter()
833        .any(|allowed| path.starts_with(allowed) || allowed.starts_with(path))
834}
835
836fn should_visit_entry(
837    entry: &DirEntry,
838    walk_root: &Path,
839    config: &SimpleIndexerConfig,
840    filter: &dyn TraversalFilter,
841) -> bool {
842    if entry.path() == walk_root {
843        return true;
844    }
845
846    if !entry.file_type().is_some_and(|file_type| file_type.is_dir()) {
847        return true;
848    }
849
850    filter.should_descend(entry.path(), config)
851}
852
853#[inline]
854fn calculate_hash(content: &str) -> String {
855    vtcode_commons::utils::calculate_sha256(content.as_bytes())
856}
857
858fn write_markdown_entry(writer: &mut impl Write, entry: &FileIndex) -> std::io::Result<()> {
859    writeln!(writer, "## {}", entry.path)?;
860    writeln!(writer)?;
861    write_markdown_fields(writer, entry)?;
862    writeln!(writer)?;
863    Ok(())
864}
865
866fn write_markdown_fields(writer: &mut impl Write, entry: &FileIndex) -> std::io::Result<()> {
867    writeln!(writer, "- **Path**: {}", entry.path)?;
868    writeln!(writer, "- **Hash**: {}", entry.hash)?;
869    writeln!(writer, "- **Modified**: {}", entry.modified)?;
870    writeln!(writer, "- **Size**: {} bytes", entry.size)?;
871    writeln!(writer, "- **Language**: {}", entry.language)?;
872    writeln!(writer, "- **Tags**: {}", entry.tags.join(", "))?;
873    Ok(())
874}
875
876fn cleanup_legacy_markdown_entries(index_dir: &Path) -> Result<()> {
877    for entry in fs::read_dir(index_dir)? {
878        let entry = entry?;
879        let file_name = entry.file_name();
880        let file_name = file_name.to_string_lossy();
881        if is_legacy_markdown_entry_name(file_name.as_ref()) {
882            fs::remove_file(entry.path())?;
883        }
884    }
885    Ok(())
886}
887
888#[inline]
889fn is_legacy_markdown_entry_name(file_name: &str) -> bool {
890    let Some(hash_part) = file_name.strip_suffix(".md") else {
891        return false;
892    };
893    hash_part.len() == 64 && hash_part.bytes().all(|byte| byte.is_ascii_hexdigit())
894}
895
896#[cfg(test)]
897mod tests {
898    use super::*;
899    use std::fs;
900    use std::sync::{Arc, Mutex};
901    use tempfile::tempdir;
902
903    #[test]
904    fn skips_hidden_directories_by_default() -> Result<()> {
905        let temp = tempdir()?;
906        let workspace = temp.path();
907        let hidden_dir = workspace.join(".private");
908        fs::create_dir_all(&hidden_dir)?;
909        fs::write(hidden_dir.join("secret.txt"), "classified")?;
910
911        let visible_dir = workspace.join("src");
912        fs::create_dir_all(&visible_dir)?;
913        fs::write(visible_dir.join("lib.rs"), "fn main() {}")?;
914
915        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
916        indexer.init()?;
917        indexer.index_directory(workspace)?;
918
919        assert!(indexer.find_files("secret\\.txt$")?.is_empty());
920        assert!(!indexer.find_files("lib\\.rs$")?.is_empty());
921
922        Ok(())
923    }
924
925    #[test]
926    fn can_include_hidden_directories_when_configured() -> Result<()> {
927        let temp = tempdir()?;
928        let workspace = temp.path();
929        let hidden_dir = workspace.join(".cache");
930        fs::create_dir_all(&hidden_dir)?;
931        fs::write(hidden_dir.join("data.log"), "details")?;
932
933        let config = SimpleIndexerConfig::new(workspace.to_path_buf()).ignore_hidden(false);
934        let mut indexer = SimpleIndexer::with_config(config);
935        indexer.init()?;
936        indexer.index_directory(workspace)?;
937
938        let results = indexer.find_files("data\\.log$")?;
939        assert_eq!(results.len(), 1);
940
941        Ok(())
942    }
943
944    #[test]
945    fn indexes_allowed_directories_inside_hidden_excluded_parents() -> Result<()> {
946        let temp = tempdir()?;
947        let workspace = temp.path();
948        let allowed_dir = workspace.join(".vtcode").join("external");
949        fs::create_dir_all(&allowed_dir)?;
950        fs::write(allowed_dir.join("plugin.toml"), "name = 'demo'")?;
951
952        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
953        indexer.init()?;
954        indexer.index_directory(workspace)?;
955
956        let results = indexer.find_files("plugin\\.toml$")?;
957        assert_eq!(results.len(), 1);
958
959        Ok(())
960    }
961
962    #[test]
963    fn reindexing_prunes_deleted_files_from_cache() -> Result<()> {
964        let temp = tempdir()?;
965        let workspace = temp.path();
966        let file_path = workspace.join("notes.txt");
967        fs::write(&file_path, "remember this")?;
968
969        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
970        indexer.init()?;
971        indexer.index_directory(workspace)?;
972        assert_eq!(indexer.find_files("notes\\.txt$")?.len(), 1);
973
974        fs::remove_file(&file_path)?;
975        indexer.index_directory(workspace)?;
976
977        assert!(indexer.find_files("notes\\.txt$")?.is_empty());
978        assert!(indexer.all_files().is_empty());
979
980        Ok(())
981    }
982
983    #[test]
984    fn index_file_skips_excluded_paths() -> Result<()> {
985        let temp = tempdir()?;
986        let workspace = temp.path();
987        let index_dir = workspace.join(".vtcode").join("index");
988        fs::create_dir_all(&index_dir)?;
989        let generated_index = index_dir.join("index.md");
990        fs::write(&generated_index, "# generated")?;
991
992        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
993        indexer.init()?;
994        indexer.index_file(&generated_index)?;
995
996        assert!(indexer.all_files().is_empty());
997
998        Ok(())
999    }
1000
1001    #[test]
1002    fn index_file_removes_stale_entry_when_file_becomes_unreadable() -> Result<()> {
1003        let temp = tempdir()?;
1004        let workspace = temp.path();
1005        let file_path = workspace.join("notes.txt");
1006        fs::write(&file_path, "remember this")?;
1007
1008        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1009        indexer.init()?;
1010        indexer.index_file(&file_path)?;
1011        assert!(
1012            indexer
1013                .find_files("notes\\.txt$")?
1014                .iter()
1015                .any(|file| file.ends_with("notes.txt"))
1016        );
1017
1018        fs::write(&file_path, [0xFF, 0xFE, 0xFD])?;
1019        indexer.index_file(&file_path)?;
1020
1021        assert!(indexer.find_files("notes\\.txt$")?.is_empty());
1022
1023        let index_content = fs::read_to_string(workspace.join(".vtcode").join("index").join("index.md"))?;
1024        assert!(!index_content.contains(file_path.to_string_lossy().as_ref()));
1025
1026        Ok(())
1027    }
1028
1029    #[test]
1030    fn index_file_maintains_markdown_snapshot_across_updates() -> Result<()> {
1031        let temp = tempdir()?;
1032        let workspace = temp.path();
1033        let first = workspace.join("first.txt");
1034        let second = workspace.join("second.txt");
1035        fs::write(&first, "one")?;
1036        fs::write(&second, "two")?;
1037
1038        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1039        indexer.init()?;
1040        indexer.index_file(&first)?;
1041        indexer.index_file(&second)?;
1042
1043        let index_dir = workspace.join(".vtcode").join("index");
1044        let files = fs::read_dir(&index_dir)?
1045            .filter_map(|entry| entry.ok())
1046            .map(|entry| entry.file_name().to_string_lossy().into_owned())
1047            .collect::<Vec<_>>();
1048        assert_eq!(files, vec!["index.md".to_string()]);
1049
1050        let index_content = fs::read_to_string(index_dir.join("index.md"))?;
1051        assert!(index_content.contains(first.to_string_lossy().as_ref()));
1052        assert!(index_content.contains(second.to_string_lossy().as_ref()));
1053
1054        Ok(())
1055    }
1056
1057    #[test]
1058    fn index_directory_writes_markdown_snapshot_without_manual_init() -> Result<()> {
1059        let temp = tempdir()?;
1060        let workspace = temp.path();
1061        fs::write(workspace.join("notes.txt"), "remember this")?;
1062
1063        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1064        indexer.index_directory(workspace)?;
1065
1066        let index_content = fs::read_to_string(workspace.join(".vtcode").join("index").join("index.md"))?;
1067        assert!(index_content.contains(workspace.join("notes.txt").to_string_lossy().as_ref()));
1068
1069        Ok(())
1070    }
1071
1072    #[test]
1073    fn get_file_content_clamps_ranges_without_panicking() -> Result<()> {
1074        let temp = tempdir()?;
1075        let workspace = temp.path();
1076        let file_path = workspace.join("notes.txt");
1077        fs::write(&file_path, "first\nsecond")?;
1078
1079        let indexer = SimpleIndexer::new(workspace.to_path_buf());
1080        let file_path = file_path.to_string_lossy().into_owned();
1081
1082        assert_eq!(indexer.get_file_content(&file_path, Some(5), None)?, "");
1083        assert_eq!(indexer.get_file_content(&file_path, Some(0), Some(1))?, "1: first\n");
1084        assert_eq!(indexer.get_file_content(&file_path, Some(2), Some(1))?, "");
1085
1086        Ok(())
1087    }
1088
1089    #[test]
1090    fn supports_custom_storage_backends() -> Result<()> {
1091        #[derive(Clone, Default)]
1092        struct MemoryStorage {
1093            records: Arc<Mutex<Vec<FileIndex>>>,
1094        }
1095
1096        impl MemoryStorage {
1097            fn new(records: Arc<Mutex<Vec<FileIndex>>>) -> Self {
1098                Self { records }
1099            }
1100        }
1101
1102        impl IndexStorage for MemoryStorage {
1103            fn init(&self, _index_dir: &Path) -> Result<()> {
1104                Ok(())
1105            }
1106
1107            fn persist(&self, _index_dir: &Path, entry: &FileIndex) -> Result<()> {
1108                let mut guard = self.records.lock().expect("lock poisoned");
1109                guard.push(entry.clone());
1110                Ok(())
1111            }
1112        }
1113
1114        let temp = tempdir()?;
1115        let workspace = temp.path();
1116        fs::write(workspace.join("notes.txt"), "remember this")?;
1117
1118        let records: Arc<Mutex<Vec<FileIndex>>> = Arc::new(Mutex::new(Vec::new()));
1119        let storage = MemoryStorage::new(records.clone());
1120
1121        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1122        let mut indexer = SimpleIndexer::with_config(config).with_storage(Arc::new(storage));
1123        indexer.init()?;
1124        indexer.index_directory(workspace)?;
1125
1126        let entries = records.lock().expect("lock poisoned");
1127        assert_eq!(entries.len(), 1);
1128        assert_eq!(entries[0].path, workspace.join("notes.txt").to_string_lossy().into_owned());
1129
1130        Ok(())
1131    }
1132
1133    #[test]
1134    fn custom_filters_can_skip_files() -> Result<()> {
1135        #[derive(Default)]
1136        struct SkipRustFilter {
1137            inner: ConfigTraversalFilter,
1138        }
1139
1140        impl TraversalFilter for SkipRustFilter {
1141            fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
1142                self.inner.should_descend(path, config)
1143            }
1144
1145            fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
1146                if path
1147                    .extension()
1148                    .and_then(|ext| ext.to_str())
1149                    .is_some_and(|ext| ext.eq_ignore_ascii_case("rs"))
1150                {
1151                    return false;
1152                }
1153
1154                self.inner.should_index_file(path, config)
1155            }
1156        }
1157
1158        let temp = tempdir()?;
1159        let workspace = temp.path();
1160        fs::write(workspace.join("lib.rs"), "fn main() {}")?;
1161        fs::write(workspace.join("README.md"), "# Notes")?;
1162
1163        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1164        let mut indexer = SimpleIndexer::with_config(config).with_filter(Arc::new(SkipRustFilter::default()));
1165        indexer.init()?;
1166        indexer.index_directory(workspace)?;
1167
1168        assert!(indexer.find_files("lib\\.rs$")?.is_empty());
1169        assert!(!indexer.find_files("README\\.md$")?.is_empty());
1170
1171        Ok(())
1172    }
1173
1174    #[test]
1175    fn custom_filters_can_skip_directories() -> Result<()> {
1176        #[derive(Default)]
1177        struct SkipGeneratedFilter {
1178            inner: ConfigTraversalFilter,
1179        }
1180
1181        impl TraversalFilter for SkipGeneratedFilter {
1182            fn should_descend(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
1183                if path.ends_with("generated") {
1184                    return false;
1185                }
1186
1187                self.inner.should_descend(path, config)
1188            }
1189
1190            fn should_index_file(&self, path: &Path, config: &SimpleIndexerConfig) -> bool {
1191                self.inner.should_index_file(path, config)
1192            }
1193        }
1194
1195        let temp = tempdir()?;
1196        let workspace = temp.path();
1197        let generated_dir = workspace.join("generated");
1198        fs::create_dir_all(&generated_dir)?;
1199        fs::write(generated_dir.join("skip.txt"), "ignore me")?;
1200        fs::write(workspace.join("README.md"), "# Notes")?;
1201
1202        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1203        let indexer = SimpleIndexer::with_config(config).with_filter(Arc::new(SkipGeneratedFilter::default()));
1204        let files = indexer.discover_files(workspace);
1205
1206        assert!(!files.iter().any(|file| file.ends_with("skip.txt")));
1207        assert!(files.iter().any(|file| file.ends_with("README.md")));
1208
1209        Ok(())
1210    }
1211
1212    #[test]
1213    fn discover_dir_entries_is_shallow_and_ignore_aware() -> Result<()> {
1214        let temp = tempdir()?;
1215        let workspace = temp.path();
1216        fs::create_dir_all(workspace.join("src"))?;
1217        fs::create_dir_all(workspace.join("node_modules"))?;
1218        fs::create_dir_all(workspace.join(".git"))?;
1219        fs::write(workspace.join("README.md"), "# Notes")?;
1220        fs::write(workspace.join("src").join("lib.rs"), "fn main() {}")?;
1221        fs::write(workspace.join("node_modules").join("dep.js"), "x")?;
1222        fs::write(workspace.join(".git").join("config"), "x")?;
1223
1224        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1225        let indexer = SimpleIndexer::with_config(config);
1226        let entries = indexer.discover_dir_entries(workspace);
1227
1228        let names: Vec<String> = entries
1229            .iter()
1230            .map(|(p, _)| p.file_name().unwrap().to_string_lossy().into_owned())
1231            .collect();
1232
1233        assert_eq!(entries.len(), 2, "expected exactly README.md and src, got {names:?}");
1234        assert!(names.contains(&"README.md".to_string()));
1235        assert!(names.contains(&"src".to_string()));
1236
1237        let (_, src_is_dir) = entries.iter().find(|(p, _)| p.ends_with("src")).unwrap();
1238        assert!(*src_is_dir);
1239
1240        Ok(())
1241    }
1242
1243    #[test]
1244    fn indexing_multiple_directories_preserves_existing_cache_entries() -> Result<()> {
1245        let temp = tempdir()?;
1246        let workspace = temp.path();
1247        let src_dir = workspace.join("src");
1248        let docs_dir = workspace.join("docs");
1249        fs::create_dir_all(&src_dir)?;
1250        fs::create_dir_all(&docs_dir)?;
1251        fs::write(src_dir.join("lib.rs"), "fn main() {}")?;
1252        fs::write(docs_dir.join("guide.md"), "# Guide")?;
1253
1254        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1255        indexer.init()?;
1256        indexer.index_directory(&src_dir)?;
1257        indexer.index_directory(&docs_dir)?;
1258
1259        assert!(indexer.find_files("lib\\.rs$")?.iter().any(|file| file.ends_with("lib.rs")));
1260        assert!(indexer.find_files("guide\\.md$")?.iter().any(|file| file.ends_with("guide.md")));
1261
1262        let index_content = fs::read_to_string(workspace.join(".vtcode").join("index").join("index.md"))?;
1263        assert!(index_content.contains(src_dir.join("lib.rs").to_string_lossy().as_ref()));
1264        assert!(index_content.contains(docs_dir.join("guide.md").to_string_lossy().as_ref()));
1265
1266        Ok(())
1267    }
1268
1269    #[test]
1270    fn batch_indexing_writes_single_markdown_file() -> Result<()> {
1271        let temp = tempdir()?;
1272        let workspace = temp.path();
1273        fs::write(workspace.join("lib.rs"), "fn main() {}")?;
1274        fs::write(workspace.join("README.md"), "# Notes")?;
1275
1276        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1277        indexer.init()?;
1278        indexer.index_directory(workspace)?;
1279
1280        let index_dir = workspace.join(".vtcode").join("index");
1281        let files = fs::read_dir(&index_dir)?
1282            .filter_map(|entry| entry.ok())
1283            .map(|entry| entry.file_name().to_string_lossy().into_owned())
1284            .collect::<Vec<_>>();
1285        assert_eq!(files, vec!["index.md".to_string()]);
1286
1287        let index_content = fs::read_to_string(index_dir.join("index.md"))?;
1288        assert!(index_content.contains(workspace.join("lib.rs").to_string_lossy().as_ref()));
1289        assert!(index_content.contains(workspace.join("README.md").to_string_lossy().as_ref()));
1290
1291        Ok(())
1292    }
1293
1294    #[test]
1295    fn batch_indexing_removes_legacy_hashed_entries() -> Result<()> {
1296        let temp = tempdir()?;
1297        let workspace = temp.path();
1298        fs::write(workspace.join("lib.rs"), "fn main() {}")?;
1299
1300        let mut indexer = SimpleIndexer::new(workspace.to_path_buf());
1301        indexer.init()?;
1302
1303        let legacy_file_name = format!("{}.md", calculate_hash("legacy-path"));
1304        let legacy_file_path = workspace.join(".vtcode").join("index").join(&legacy_file_name);
1305        fs::write(&legacy_file_path, "# legacy")?;
1306        assert!(legacy_file_path.exists());
1307
1308        indexer.index_directory(workspace)?;
1309
1310        assert!(!legacy_file_path.exists());
1311        let files = fs::read_dir(workspace.join(".vtcode").join("index"))?
1312            .filter_map(|entry| entry.ok())
1313            .map(|entry| entry.file_name().to_string_lossy().into_owned())
1314            .collect::<Vec<_>>();
1315        assert_eq!(files, vec!["index.md".to_string()]);
1316
1317        Ok(())
1318    }
1319
1320    #[test]
1321    fn snapshot_storage_uses_default_ref_batch_persistence() -> Result<()> {
1322        #[derive(Clone, Default)]
1323        struct SnapshotMemoryStorage {
1324            snapshots: Arc<Mutex<Vec<Vec<FileIndex>>>>,
1325        }
1326
1327        impl SnapshotMemoryStorage {
1328            fn new(snapshots: Arc<Mutex<Vec<Vec<FileIndex>>>>) -> Self {
1329                Self { snapshots }
1330            }
1331        }
1332
1333        impl IndexStorage for SnapshotMemoryStorage {
1334            fn init(&self, _index_dir: &Path) -> Result<()> {
1335                Ok(())
1336            }
1337
1338            fn persist(&self, _index_dir: &Path, _entry: &FileIndex) -> Result<()> {
1339                Ok(())
1340            }
1341
1342            fn prefers_snapshot_persistence(&self) -> bool {
1343                true
1344            }
1345
1346            fn persist_batch(&self, _index_dir: &Path, entries: &[FileIndex]) -> Result<()> {
1347                self.snapshots.lock().expect("lock poisoned").push(entries.to_vec());
1348                Ok(())
1349            }
1350        }
1351
1352        let temp = tempdir()?;
1353        let workspace = temp.path();
1354        let file_path = workspace.join("notes.txt");
1355        fs::write(&file_path, "remember this")?;
1356
1357        let snapshots = Arc::new(Mutex::new(Vec::new()));
1358        let storage = SnapshotMemoryStorage::new(snapshots.clone());
1359
1360        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1361        let mut indexer = SimpleIndexer::with_config(config).with_storage(Arc::new(storage));
1362        indexer.index_file(&file_path)?;
1363
1364        let snapshots = snapshots.lock().expect("lock poisoned");
1365        assert_eq!(snapshots.len(), 1);
1366        assert_eq!(snapshots[0].len(), 1);
1367        assert_eq!(snapshots[0][0].path, workspace.join("notes.txt").to_string_lossy().into_owned());
1368
1369        Ok(())
1370    }
1371
1372    #[test]
1373    fn snapshot_index_file_rolls_back_cache_when_persist_fails() -> Result<()> {
1374        #[derive(Clone, Default)]
1375        struct FlakySnapshotStorage {
1376            persist_count: Arc<Mutex<usize>>,
1377        }
1378
1379        impl IndexStorage for FlakySnapshotStorage {
1380            fn init(&self, _index_dir: &Path) -> Result<()> {
1381                Ok(())
1382            }
1383
1384            fn persist(&self, _index_dir: &Path, _entry: &FileIndex) -> Result<()> {
1385                Ok(())
1386            }
1387
1388            fn prefers_snapshot_persistence(&self) -> bool {
1389                true
1390            }
1391
1392            fn persist_batch(&self, _index_dir: &Path, _entries: &[FileIndex]) -> Result<()> {
1393                let mut count = self.persist_count.lock().expect("lock poisoned");
1394                *count += 1;
1395                if *count == 2 {
1396                    anyhow::bail!("simulated snapshot persistence failure");
1397                }
1398                Ok(())
1399            }
1400        }
1401
1402        let temp = tempdir()?;
1403        let workspace = temp.path();
1404        let first = workspace.join("first.txt");
1405        let second = workspace.join("second.txt");
1406        fs::write(&first, "one")?;
1407        fs::write(&second, "two")?;
1408
1409        let config = SimpleIndexerConfig::new(workspace.to_path_buf());
1410        let storage = Arc::new(FlakySnapshotStorage::default());
1411        let mut indexer = SimpleIndexer::with_config(config).with_storage(storage);
1412
1413        indexer.index_file(&first)?;
1414        assert!(
1415            indexer
1416                .find_files("first\\.txt$")?
1417                .iter()
1418                .any(|path| path.ends_with("first.txt"))
1419        );
1420
1421        let err = indexer.index_file(&second).expect_err("second persist should fail");
1422        assert!(err.to_string().contains("simulated snapshot persistence failure"));
1423        assert!(
1424            indexer
1425                .find_files("first\\.txt$")?
1426                .iter()
1427                .any(|path| path.ends_with("first.txt"))
1428        );
1429        assert!(indexer.find_files("second\\.txt$")?.is_empty());
1430
1431        Ok(())
1432    }
1433}