Skip to main content

aft/
search_index.rs

1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
2use std::fs::{self, File};
3use std::io::{BufReader, BufWriter, Read, Seek, Write};
4use std::path::{Component, Path, PathBuf};
5use std::process::Command;
6use std::sync::{
7    atomic::{AtomicBool, AtomicUsize, Ordering},
8    Arc,
9};
10use std::time::{Duration, SystemTime, UNIX_EPOCH};
11
12use globset::{Glob, GlobSet, GlobSetBuilder};
13use ignore::WalkBuilder;
14use rayon::prelude::*;
15use regex::bytes::{Regex, RegexBuilder};
16use regex_syntax::hir::{Hir, HirKind};
17
18const DEFAULT_MAX_FILE_SIZE: u64 = 1_048_576;
19const INDEX_MAGIC: &[u8; 8] = b"AFTIDX01";
20const LOOKUP_MAGIC: &[u8; 8] = b"AFTLKP01";
21const INDEX_VERSION: u32 = 1;
22const PREVIEW_BYTES: usize = 8 * 1024;
23const EOF_SENTINEL: u8 = 0;
24const MAX_ENTRIES: usize = 10_000_000;
25const MIN_FILE_ENTRY_BYTES: usize = 25;
26const LOOKUP_ENTRY_BYTES: usize = 16;
27const POSTING_BYTES: usize = 6;
28
29#[derive(Clone, Debug)]
30pub struct SearchIndex {
31    pub postings: HashMap<u32, Vec<Posting>>,
32    pub files: Vec<FileEntry>,
33    pub path_to_id: HashMap<PathBuf, u32>,
34    pub ready: bool,
35    project_root: PathBuf,
36    git_head: Option<String>,
37    max_file_size: u64,
38    file_trigrams: HashMap<u32, Vec<u32>>,
39    unindexed_files: HashSet<u32>,
40}
41
42impl SearchIndex {
43    /// Number of indexed files.
44    pub fn file_count(&self) -> usize {
45        self.files.len()
46    }
47
48    /// Number of unique trigrams in the index.
49    pub fn trigram_count(&self) -> usize {
50        self.postings.len()
51    }
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct Posting {
56    pub file_id: u32,
57    pub next_mask: u8,
58    pub loc_mask: u8,
59}
60
61#[derive(Clone, Debug)]
62pub struct FileEntry {
63    pub path: PathBuf,
64    pub size: u64,
65    pub modified: SystemTime,
66}
67
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub struct GrepMatch {
70    pub file: PathBuf,
71    pub line: u32,
72    pub column: u32,
73    pub line_text: String,
74    pub match_text: String,
75}
76
77#[derive(Clone, Debug)]
78pub struct GrepResult {
79    pub matches: Vec<GrepMatch>,
80    pub total_matches: usize,
81    pub files_searched: usize,
82    pub files_with_matches: usize,
83    pub index_status: IndexStatus,
84    pub truncated: bool,
85}
86
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub enum IndexStatus {
89    Ready,
90    Building,
91    Fallback,
92}
93
94impl IndexStatus {
95    pub fn as_str(&self) -> &'static str {
96        match self {
97            IndexStatus::Ready => "Ready",
98            IndexStatus::Building => "Building",
99            IndexStatus::Fallback => "Fallback",
100        }
101    }
102}
103
104#[derive(Clone, Debug, Default)]
105pub struct RegexQuery {
106    pub and_trigrams: Vec<u32>,
107    pub or_groups: Vec<Vec<u32>>,
108    pub(crate) and_filters: HashMap<u32, PostingFilter>,
109    pub(crate) or_filters: Vec<HashMap<u32, PostingFilter>>,
110}
111
112#[derive(Clone, Copy, Debug, Default)]
113pub(crate) struct PostingFilter {
114    next_mask: u8,
115    loc_mask: u8,
116}
117
118#[derive(Clone, Debug, Default)]
119struct QueryBuild {
120    and_runs: Vec<Vec<u8>>,
121    or_groups: Vec<Vec<Vec<u8>>>,
122}
123
124#[derive(Clone, Debug, Default)]
125pub(crate) struct PathFilters {
126    includes: Option<GlobSet>,
127    excludes: Option<GlobSet>,
128}
129
130#[derive(Clone, Debug)]
131pub(crate) struct SearchScope {
132    pub root: PathBuf,
133    pub use_index: bool,
134}
135
136#[derive(Clone, Debug)]
137struct SharedGrepMatch {
138    file: Arc<PathBuf>,
139    line: u32,
140    column: u32,
141    line_text: String,
142    match_text: String,
143}
144
145#[derive(Clone, Debug)]
146enum SearchMatcher {
147    Literal(LiteralSearch),
148    Regex(Regex),
149}
150
151#[derive(Clone, Debug)]
152enum LiteralSearch {
153    CaseSensitive(Vec<u8>),
154    AsciiCaseInsensitive(Vec<u8>),
155}
156
157impl SearchIndex {
158    pub fn new() -> Self {
159        SearchIndex {
160            postings: HashMap::new(),
161            files: Vec::new(),
162            path_to_id: HashMap::new(),
163            ready: false,
164            project_root: PathBuf::new(),
165            git_head: None,
166            max_file_size: DEFAULT_MAX_FILE_SIZE,
167            file_trigrams: HashMap::new(),
168            unindexed_files: HashSet::new(),
169        }
170    }
171
172    pub fn build(root: &Path) -> Self {
173        Self::build_with_limit(root, DEFAULT_MAX_FILE_SIZE)
174    }
175
176    pub(crate) fn build_with_limit(root: &Path, max_file_size: u64) -> Self {
177        let project_root = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
178        let mut index = SearchIndex {
179            project_root: project_root.clone(),
180            max_file_size,
181            ..SearchIndex::new()
182        };
183
184        let filters = PathFilters::default();
185        for path in walk_project_files(&project_root, &filters) {
186            index.update_file(&path);
187        }
188
189        index.git_head = current_git_head(&project_root);
190        index.ready = true;
191        index
192    }
193
194    pub fn index_file(&mut self, path: &Path, content: &[u8]) {
195        self.remove_file(path);
196
197        let file_id = match self.allocate_file_id(path, content.len() as u64) {
198            Some(file_id) => file_id,
199            None => return,
200        };
201
202        let mut trigram_map: BTreeMap<u32, PostingFilter> = BTreeMap::new();
203        for (trigram, next_char, position) in extract_trigrams(content) {
204            let entry = trigram_map.entry(trigram).or_default();
205            entry.next_mask |= mask_for_next_char(next_char);
206            entry.loc_mask |= mask_for_position(position);
207        }
208
209        let mut file_trigrams = Vec::with_capacity(trigram_map.len());
210        for (trigram, filter) in trigram_map {
211            let postings = self.postings.entry(trigram).or_default();
212            postings.push(Posting {
213                file_id,
214                next_mask: filter.next_mask,
215                loc_mask: filter.loc_mask,
216            });
217            // Posting lists are kept sorted by file_id for binary search during
218            // intersection. Since file_ids are allocated incrementally, the new
219            // entry is usually already in order. Only sort when needed.
220            if postings.len() > 1
221                && postings[postings.len() - 2].file_id > postings[postings.len() - 1].file_id
222            {
223                postings.sort_unstable_by_key(|p| p.file_id);
224            }
225            file_trigrams.push(trigram);
226        }
227
228        self.file_trigrams.insert(file_id, file_trigrams);
229        self.unindexed_files.remove(&file_id);
230    }
231
232    pub fn remove_file(&mut self, path: &Path) {
233        let Some(file_id) = self.path_to_id.remove(path) else {
234            return;
235        };
236
237        if let Some(trigrams) = self.file_trigrams.remove(&file_id) {
238            for trigram in trigrams {
239                let should_remove = if let Some(postings) = self.postings.get_mut(&trigram) {
240                    postings.retain(|posting| posting.file_id != file_id);
241                    postings.is_empty()
242                } else {
243                    false
244                };
245
246                if should_remove {
247                    self.postings.remove(&trigram);
248                }
249            }
250        }
251
252        self.unindexed_files.remove(&file_id);
253        if let Some(file) = self.files.get_mut(file_id as usize) {
254            file.path = PathBuf::new();
255            file.size = 0;
256            file.modified = UNIX_EPOCH;
257        }
258    }
259
260    pub fn update_file(&mut self, path: &Path) {
261        self.remove_file(path);
262
263        let metadata = match fs::metadata(path) {
264            Ok(metadata) if metadata.is_file() => metadata,
265            _ => return,
266        };
267
268        if is_binary_path(path, metadata.len()) {
269            self.track_unindexed_file(path, &metadata);
270            return;
271        }
272
273        if metadata.len() > self.max_file_size {
274            self.track_unindexed_file(path, &metadata);
275            return;
276        }
277
278        let content = match fs::read(path) {
279            Ok(content) => content,
280            Err(_) => return,
281        };
282
283        if is_binary_bytes(&content) {
284            self.track_unindexed_file(path, &metadata);
285            return;
286        }
287
288        self.index_file(path, &content);
289    }
290
291    pub fn grep(
292        &self,
293        pattern: &str,
294        case_sensitive: bool,
295        include: &[String],
296        exclude: &[String],
297        search_root: &Path,
298        max_results: usize,
299    ) -> GrepResult {
300        self.search_grep(
301            pattern,
302            case_sensitive,
303            include,
304            exclude,
305            search_root,
306            max_results,
307        )
308    }
309
310    pub fn search_grep(
311        &self,
312        pattern: &str,
313        case_sensitive: bool,
314        include: &[String],
315        exclude: &[String],
316        search_root: &Path,
317        max_results: usize,
318    ) -> GrepResult {
319        // Detect if pattern is a plain literal (no regex metacharacters).
320        // If so, use memchr::memmem which is 3-10x faster than regex for byte scanning.
321        let is_literal = !pattern.chars().any(|c| {
322            matches!(
323                c,
324                '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '^' | '$' | '\\'
325            )
326        });
327
328        let literal_search = if is_literal {
329            if case_sensitive {
330                Some(LiteralSearch::CaseSensitive(pattern.as_bytes().to_vec()))
331            } else if pattern.is_ascii() {
332                Some(LiteralSearch::AsciiCaseInsensitive(
333                    pattern
334                        .as_bytes()
335                        .iter()
336                        .map(|byte| byte.to_ascii_lowercase())
337                        .collect(),
338                ))
339            } else {
340                None
341            }
342        } else {
343            None
344        };
345
346        // Build the regex for non-literal patterns (or literal Unicode fallback).
347        let regex = if literal_search.is_some() {
348            None
349        } else {
350            let regex_pattern = if is_literal {
351                regex::escape(pattern)
352            } else {
353                pattern.to_string()
354            };
355            let mut builder = RegexBuilder::new(&regex_pattern);
356            builder.case_insensitive(!case_sensitive);
357            // Treat `^` and `$` as line anchors (grep semantics), not file anchors.
358            builder.multi_line(true);
359            match builder.build() {
360                Ok(r) => Some(r),
361                Err(_) => {
362                    return GrepResult {
363                        matches: Vec::new(),
364                        total_matches: 0,
365                        files_searched: 0,
366                        files_with_matches: 0,
367                        index_status: if self.ready {
368                            IndexStatus::Ready
369                        } else {
370                            IndexStatus::Building
371                        },
372                        truncated: false,
373                    };
374                }
375            }
376        };
377
378        let matcher = if let Some(literal_search) = literal_search {
379            SearchMatcher::Literal(literal_search)
380        } else {
381            SearchMatcher::Regex(
382                regex.expect("regex should exist when literal matcher is unavailable"),
383            )
384        };
385
386        let filters = match build_path_filters(include, exclude) {
387            Ok(filters) => filters,
388            Err(_) => PathFilters::default(),
389        };
390        let search_root = canonicalize_or_normalize(search_root);
391
392        let query = decompose_regex(pattern);
393        let candidate_ids = self.candidates(&query);
394
395        let candidate_files: Vec<&FileEntry> = candidate_ids
396            .into_iter()
397            .filter_map(|file_id| self.files.get(file_id as usize))
398            .filter(|file| !file.path.as_os_str().is_empty())
399            .filter(|file| is_within_search_root(&search_root, &file.path))
400            .filter(|file| filters.matches(&self.project_root, &file.path))
401            .collect();
402
403        let total_matches = AtomicUsize::new(0);
404        let files_searched = AtomicUsize::new(0);
405        let files_with_matches = AtomicUsize::new(0);
406        let truncated = AtomicBool::new(false);
407        let stop_after = max_results.saturating_mul(2);
408
409        let mut matches = if candidate_files.len() > 10 {
410            candidate_files
411                .par_iter()
412                .map(|file| {
413                    search_candidate_file(
414                        file,
415                        &matcher,
416                        max_results,
417                        stop_after,
418                        &total_matches,
419                        &files_searched,
420                        &files_with_matches,
421                        &truncated,
422                    )
423                })
424                .reduce(Vec::new, |mut left, mut right| {
425                    left.append(&mut right);
426                    left
427                })
428        } else {
429            let mut matches = Vec::new();
430            for file in candidate_files {
431                matches.extend(search_candidate_file(
432                    file,
433                    &matcher,
434                    max_results,
435                    stop_after,
436                    &total_matches,
437                    &files_searched,
438                    &files_with_matches,
439                    &truncated,
440                ));
441
442                if should_stop_search(&truncated, &total_matches, stop_after) {
443                    break;
444                }
445            }
446            matches
447        };
448
449        sort_shared_grep_matches_by_cached_mtime_desc(&mut matches, |path| {
450            self.path_to_id
451                .get(path)
452                .and_then(|file_id| self.files.get(*file_id as usize))
453                .map(|file| file.modified)
454        });
455
456        let matches = matches
457            .into_iter()
458            .map(|matched| GrepMatch {
459                file: matched.file.as_ref().clone(),
460                line: matched.line,
461                column: matched.column,
462                line_text: matched.line_text,
463                match_text: matched.match_text,
464            })
465            .collect();
466
467        GrepResult {
468            total_matches: total_matches.load(Ordering::Relaxed),
469            matches,
470            files_searched: files_searched.load(Ordering::Relaxed),
471            files_with_matches: files_with_matches.load(Ordering::Relaxed),
472            index_status: if self.ready {
473                IndexStatus::Ready
474            } else {
475                IndexStatus::Building
476            },
477            truncated: truncated.load(Ordering::Relaxed),
478        }
479    }
480
481    pub fn glob(&self, pattern: &str, search_root: &Path) -> Vec<PathBuf> {
482        let filters = match build_path_filters(&[pattern.to_string()], &[]) {
483            Ok(filters) => filters,
484            Err(_) => return Vec::new(),
485        };
486        let search_root = canonicalize_or_normalize(search_root);
487        let mut entries = self
488            .files
489            .iter()
490            .filter(|file| !file.path.as_os_str().is_empty())
491            .filter(|file| is_within_search_root(&search_root, &file.path))
492            .filter(|file| filters.matches(&self.project_root, &file.path))
493            .map(|file| (file.path.clone(), file.modified))
494            .collect::<Vec<_>>();
495
496        entries.sort_by(|(left_path, left_mtime), (right_path, right_mtime)| {
497            right_mtime
498                .cmp(left_mtime)
499                .then_with(|| left_path.cmp(right_path))
500        });
501
502        entries.into_iter().map(|(path, _)| path).collect()
503    }
504
505    pub fn candidates(&self, query: &RegexQuery) -> Vec<u32> {
506        if query.and_trigrams.is_empty() && query.or_groups.is_empty() {
507            return self.active_file_ids();
508        }
509
510        let mut and_trigrams = query.and_trigrams.clone();
511        and_trigrams.sort_unstable_by_key(|trigram| self.postings.get(trigram).map_or(0, Vec::len));
512
513        let mut current: Option<Vec<u32>> = None;
514
515        for trigram in and_trigrams {
516            let filter = query.and_filters.get(&trigram).copied();
517            let matches = self.postings_for_trigram(trigram, filter);
518            current = Some(match current.take() {
519                Some(existing) => intersect_sorted_ids(&existing, &matches),
520                None => matches,
521            });
522
523            if current.as_ref().is_some_and(|ids| ids.is_empty()) {
524                break;
525            }
526        }
527
528        let mut current = current.unwrap_or_else(|| self.active_file_ids());
529
530        for (index, group) in query.or_groups.iter().enumerate() {
531            let mut group_matches = Vec::new();
532            let filters = query.or_filters.get(index);
533
534            for trigram in group {
535                let filter = filters.and_then(|filters| filters.get(trigram).copied());
536                let matches = self.postings_for_trigram(*trigram, filter);
537                if group_matches.is_empty() {
538                    group_matches = matches;
539                } else {
540                    group_matches = union_sorted_ids(&group_matches, &matches);
541                }
542            }
543
544            current = intersect_sorted_ids(&current, &group_matches);
545            if current.is_empty() {
546                break;
547            }
548        }
549
550        let mut unindexed = self
551            .unindexed_files
552            .iter()
553            .copied()
554            .filter(|file_id| self.is_active_file(*file_id))
555            .collect::<Vec<_>>();
556        if !unindexed.is_empty() {
557            unindexed.sort_unstable();
558            current = union_sorted_ids(&current, &unindexed);
559        }
560
561        current
562    }
563
564    pub fn write_to_disk(&self, cache_dir: &Path, git_head: Option<&str>) {
565        if fs::create_dir_all(cache_dir).is_err() {
566            return;
567        }
568
569        let postings_path = cache_dir.join("postings.bin");
570        let lookup_path = cache_dir.join("lookup.bin");
571        let tmp_postings = cache_dir.join("postings.bin.tmp");
572        let tmp_lookup = cache_dir.join("lookup.bin.tmp");
573
574        let active_ids = self.active_file_ids();
575        let mut id_map = HashMap::new();
576        for (new_id, old_id) in active_ids.iter().enumerate() {
577            let Ok(new_id_u32) = u32::try_from(new_id) else {
578                return;
579            };
580            id_map.insert(*old_id, new_id_u32);
581        }
582
583        let write_result = (|| -> std::io::Result<()> {
584            let mut postings_writer = BufWriter::new(File::create(&tmp_postings)?);
585
586            postings_writer.write_all(INDEX_MAGIC)?;
587            write_u32(&mut postings_writer, INDEX_VERSION)?;
588
589            let head = git_head.unwrap_or_default();
590            let root = self.project_root.to_string_lossy();
591            let head_len = u32::try_from(head.len())
592                .map_err(|_| std::io::Error::other("git head too large to cache"))?;
593            let root_len = u32::try_from(root.len())
594                .map_err(|_| std::io::Error::other("project root too large to cache"))?;
595            let file_count = u32::try_from(active_ids.len())
596                .map_err(|_| std::io::Error::other("too many files to cache"))?;
597
598            write_u32(&mut postings_writer, head_len)?;
599            write_u32(&mut postings_writer, root_len)?;
600            write_u64(&mut postings_writer, self.max_file_size)?;
601            write_u32(&mut postings_writer, file_count)?;
602            postings_writer.write_all(head.as_bytes())?;
603            postings_writer.write_all(root.as_bytes())?;
604
605            for old_id in &active_ids {
606                let Some(file) = self.files.get(*old_id as usize) else {
607                    return Err(std::io::Error::other("missing file entry for cache write"));
608                };
609                let path = relative_to_root(&self.project_root, &file.path);
610                let path = path.to_string_lossy();
611                let path_len = u32::try_from(path.len())
612                    .map_err(|_| std::io::Error::other("cached path too large"))?;
613                let modified = file
614                    .modified
615                    .duration_since(UNIX_EPOCH)
616                    .unwrap_or(Duration::ZERO);
617                let unindexed = if self.unindexed_files.contains(old_id) {
618                    1u8
619                } else {
620                    0u8
621                };
622
623                postings_writer.write_all(&[unindexed])?;
624                write_u32(&mut postings_writer, path_len)?;
625                write_u64(&mut postings_writer, file.size)?;
626                write_u64(&mut postings_writer, modified.as_secs())?;
627                write_u32(&mut postings_writer, modified.subsec_nanos())?;
628                postings_writer.write_all(path.as_bytes())?;
629            }
630
631            let mut lookup_entries = Vec::new();
632            let mut postings_blob = Vec::new();
633            let mut sorted_postings: Vec<_> = self.postings.iter().collect();
634            sorted_postings.sort_by_key(|(trigram, _)| **trigram);
635
636            for (trigram, postings) in sorted_postings {
637                let offset = u64::try_from(postings_blob.len())
638                    .map_err(|_| std::io::Error::other("postings blob too large"))?;
639                let mut count = 0u32;
640
641                for posting in postings {
642                    let Some(mapped_file_id) = id_map.get(&posting.file_id).copied() else {
643                        continue;
644                    };
645
646                    postings_blob.extend_from_slice(&mapped_file_id.to_le_bytes());
647                    postings_blob.push(posting.next_mask);
648                    postings_blob.push(posting.loc_mask);
649                    count = count.saturating_add(1);
650                }
651
652                if count > 0 {
653                    lookup_entries.push((*trigram, offset, count));
654                }
655            }
656
657            write_u64(
658                &mut postings_writer,
659                u64::try_from(postings_blob.len())
660                    .map_err(|_| std::io::Error::other("postings blob too large"))?,
661            )?;
662            postings_writer.write_all(&postings_blob)?;
663            postings_writer.flush()?;
664            drop(postings_writer);
665
666            let mut lookup_writer = BufWriter::new(File::create(&tmp_lookup)?);
667            let entry_count = u32::try_from(lookup_entries.len())
668                .map_err(|_| std::io::Error::other("too many lookup entries to cache"))?;
669
670            lookup_writer.write_all(LOOKUP_MAGIC)?;
671            write_u32(&mut lookup_writer, INDEX_VERSION)?;
672            write_u32(&mut lookup_writer, entry_count)?;
673
674            for (trigram, offset, count) in lookup_entries {
675                write_u32(&mut lookup_writer, trigram)?;
676                write_u64(&mut lookup_writer, offset)?;
677                write_u32(&mut lookup_writer, count)?;
678            }
679
680            lookup_writer.flush()?;
681            drop(lookup_writer);
682
683            fs::rename(&tmp_postings, &postings_path)?;
684            fs::rename(&tmp_lookup, &lookup_path)?;
685
686            Ok(())
687        })();
688
689        if write_result.is_err() {
690            let _ = fs::remove_file(&tmp_postings);
691            let _ = fs::remove_file(&tmp_lookup);
692        }
693    }
694
695    pub fn read_from_disk(cache_dir: &Path) -> Option<Self> {
696        let postings_path = cache_dir.join("postings.bin");
697        let lookup_path = cache_dir.join("lookup.bin");
698
699        let mut postings_reader = BufReader::new(File::open(postings_path).ok()?);
700        let mut lookup_reader = BufReader::new(File::open(lookup_path).ok()?);
701        let postings_len_total =
702            usize::try_from(postings_reader.get_ref().metadata().ok()?.len()).ok()?;
703        let lookup_len_total =
704            usize::try_from(lookup_reader.get_ref().metadata().ok()?.len()).ok()?;
705
706        let mut magic = [0u8; 8];
707        postings_reader.read_exact(&mut magic).ok()?;
708        if &magic != INDEX_MAGIC {
709            return None;
710        }
711        if read_u32(&mut postings_reader).ok()? != INDEX_VERSION {
712            return None;
713        }
714
715        let head_len = read_u32(&mut postings_reader).ok()? as usize;
716        let root_len = read_u32(&mut postings_reader).ok()? as usize;
717        let max_file_size = read_u64(&mut postings_reader).ok()?;
718        let file_count = read_u32(&mut postings_reader).ok()? as usize;
719        if file_count > MAX_ENTRIES {
720            return None;
721        }
722        let remaining_postings = remaining_bytes(&mut postings_reader, postings_len_total)?;
723        let minimum_file_bytes = file_count.checked_mul(MIN_FILE_ENTRY_BYTES)?;
724        if minimum_file_bytes > remaining_postings {
725            return None;
726        }
727
728        if head_len > remaining_bytes(&mut postings_reader, postings_len_total)? {
729            return None;
730        }
731        let mut head_bytes = vec![0u8; head_len];
732        postings_reader.read_exact(&mut head_bytes).ok()?;
733        let git_head = String::from_utf8(head_bytes)
734            .ok()
735            .filter(|head| !head.is_empty());
736
737        if root_len > remaining_bytes(&mut postings_reader, postings_len_total)? {
738            return None;
739        }
740        let mut root_bytes = vec![0u8; root_len];
741        postings_reader.read_exact(&mut root_bytes).ok()?;
742        let project_root = PathBuf::from(String::from_utf8(root_bytes).ok()?);
743
744        let mut files = Vec::with_capacity(file_count);
745        let mut path_to_id = HashMap::new();
746        let mut unindexed_files = HashSet::new();
747
748        for file_id in 0..file_count {
749            let mut unindexed = [0u8; 1];
750            postings_reader.read_exact(&mut unindexed).ok()?;
751            let path_len = read_u32(&mut postings_reader).ok()? as usize;
752            let size = read_u64(&mut postings_reader).ok()?;
753            let secs = read_u64(&mut postings_reader).ok()?;
754            let nanos = read_u32(&mut postings_reader).ok()?;
755            if nanos >= 1_000_000_000 {
756                return None;
757            }
758            if path_len > remaining_bytes(&mut postings_reader, postings_len_total)? {
759                return None;
760            }
761            let mut path_bytes = vec![0u8; path_len];
762            postings_reader.read_exact(&mut path_bytes).ok()?;
763            let relative_path = PathBuf::from(String::from_utf8(path_bytes).ok()?);
764            let full_path = project_root.join(relative_path);
765            let file_id_u32 = u32::try_from(file_id).ok()?;
766
767            files.push(FileEntry {
768                path: full_path.clone(),
769                size,
770                modified: UNIX_EPOCH + Duration::new(secs, nanos),
771            });
772            path_to_id.insert(full_path, file_id_u32);
773            if unindexed[0] == 1 {
774                unindexed_files.insert(file_id_u32);
775            }
776        }
777
778        let postings_len = read_u64(&mut postings_reader).ok()? as usize;
779        let max_postings_bytes = MAX_ENTRIES.checked_mul(POSTING_BYTES)?;
780        if postings_len > max_postings_bytes {
781            return None;
782        }
783        if postings_len > remaining_bytes(&mut postings_reader, postings_len_total)? {
784            return None;
785        }
786        let mut postings_blob = vec![0u8; postings_len];
787        postings_reader.read_exact(&mut postings_blob).ok()?;
788
789        let mut lookup_magic = [0u8; 8];
790        lookup_reader.read_exact(&mut lookup_magic).ok()?;
791        if &lookup_magic != LOOKUP_MAGIC {
792            return None;
793        }
794        if read_u32(&mut lookup_reader).ok()? != INDEX_VERSION {
795            return None;
796        }
797        let entry_count = read_u32(&mut lookup_reader).ok()? as usize;
798        if entry_count > MAX_ENTRIES {
799            return None;
800        }
801        let remaining_lookup = remaining_bytes(&mut lookup_reader, lookup_len_total)?;
802        let minimum_lookup_bytes = entry_count.checked_mul(LOOKUP_ENTRY_BYTES)?;
803        if minimum_lookup_bytes > remaining_lookup {
804            return None;
805        }
806
807        let mut postings = HashMap::new();
808        let mut file_trigrams: HashMap<u32, Vec<u32>> = HashMap::new();
809
810        for _ in 0..entry_count {
811            let trigram = read_u32(&mut lookup_reader).ok()?;
812            let offset = read_u64(&mut lookup_reader).ok()? as usize;
813            let count = read_u32(&mut lookup_reader).ok()? as usize;
814            if count > MAX_ENTRIES {
815                return None;
816            }
817            let bytes_len = count.checked_mul(POSTING_BYTES)?;
818            let end = offset.checked_add(bytes_len)?;
819            if end > postings_blob.len() {
820                return None;
821            }
822
823            let mut trigram_postings = Vec::with_capacity(count);
824            for chunk in postings_blob[offset..end].chunks_exact(6) {
825                let file_id = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
826                let posting = Posting {
827                    file_id,
828                    next_mask: chunk[4],
829                    loc_mask: chunk[5],
830                };
831                trigram_postings.push(posting.clone());
832                file_trigrams.entry(file_id).or_default().push(trigram);
833            }
834            postings.insert(trigram, trigram_postings);
835        }
836
837        Some(SearchIndex {
838            postings,
839            files,
840            path_to_id,
841            ready: true,
842            project_root,
843            git_head,
844            max_file_size,
845            file_trigrams,
846            unindexed_files,
847        })
848    }
849
850    pub(crate) fn stored_git_head(&self) -> Option<&str> {
851        self.git_head.as_deref()
852    }
853
854    pub(crate) fn set_ready(&mut self, ready: bool) {
855        self.ready = ready;
856    }
857
858    pub(crate) fn rebuild_or_refresh(
859        root: &Path,
860        max_file_size: u64,
861        current_head: Option<String>,
862        baseline: Option<SearchIndex>,
863    ) -> Self {
864        if current_head.is_none() {
865            return SearchIndex::build_with_limit(root, max_file_size);
866        }
867
868        if let Some(mut baseline) = baseline {
869            baseline.project_root = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
870            baseline.max_file_size = max_file_size;
871
872            if baseline.git_head == current_head {
873                // HEAD matches, but files may have changed on disk since the index was
874                // last written (e.g., uncommitted edits, stash pop, manual file changes
875                // while OpenCode was closed). Verify mtimes and re-index stale files.
876                verify_file_mtimes(&mut baseline);
877                baseline.ready = true;
878                return baseline;
879            }
880
881            if let (Some(previous), Some(current)) =
882                (baseline.git_head.clone(), current_head.clone())
883            {
884                let project_root = baseline.project_root.clone();
885                if apply_git_diff_updates(&mut baseline, &project_root, &previous, &current) {
886                    baseline.git_head = Some(current);
887                    baseline.ready = true;
888                    return baseline;
889                }
890            }
891        }
892
893        SearchIndex::build_with_limit(root, max_file_size)
894    }
895
896    fn allocate_file_id(&mut self, path: &Path, size_hint: u64) -> Option<u32> {
897        let file_id = u32::try_from(self.files.len()).ok()?;
898        let metadata = fs::metadata(path).ok();
899        let size = metadata
900            .as_ref()
901            .map_or(size_hint, |metadata| metadata.len());
902        let modified = metadata
903            .and_then(|metadata| metadata.modified().ok())
904            .unwrap_or(UNIX_EPOCH);
905
906        self.files.push(FileEntry {
907            path: path.to_path_buf(),
908            size,
909            modified,
910        });
911        self.path_to_id.insert(path.to_path_buf(), file_id);
912        Some(file_id)
913    }
914
915    fn track_unindexed_file(&mut self, path: &Path, metadata: &fs::Metadata) {
916        let Some(file_id) = self.allocate_file_id(path, metadata.len()) else {
917            return;
918        };
919        self.unindexed_files.insert(file_id);
920        self.file_trigrams.insert(file_id, Vec::new());
921    }
922
923    fn active_file_ids(&self) -> Vec<u32> {
924        let mut ids: Vec<u32> = self.path_to_id.values().copied().collect();
925        ids.sort_unstable();
926        ids
927    }
928
929    fn is_active_file(&self, file_id: u32) -> bool {
930        self.files
931            .get(file_id as usize)
932            .map(|file| !file.path.as_os_str().is_empty())
933            .unwrap_or(false)
934    }
935
936    fn postings_for_trigram(&self, trigram: u32, filter: Option<PostingFilter>) -> Vec<u32> {
937        let Some(postings) = self.postings.get(&trigram) else {
938            return Vec::new();
939        };
940
941        let mut matches = Vec::with_capacity(postings.len());
942
943        for posting in postings {
944            if let Some(filter) = filter {
945                // next_mask: bloom filter check — the character following this trigram in the
946                // query must also appear after this trigram somewhere in the file.
947                if filter.next_mask != 0 && posting.next_mask & filter.next_mask == 0 {
948                    continue;
949                }
950                // NOTE: loc_mask (position mod 8) is stored for future adjacency checks
951                // between consecutive trigram pairs, but is NOT used as a single-trigram
952                // filter because the position in the query string has no relationship to
953                // the position in the file. Using it here causes false negatives.
954            }
955            if self.is_active_file(posting.file_id) {
956                matches.push(posting.file_id);
957            }
958        }
959
960        matches
961    }
962}
963
964fn search_candidate_file(
965    file: &FileEntry,
966    matcher: &SearchMatcher,
967    max_results: usize,
968    stop_after: usize,
969    total_matches: &AtomicUsize,
970    files_searched: &AtomicUsize,
971    files_with_matches: &AtomicUsize,
972    truncated: &AtomicBool,
973) -> Vec<SharedGrepMatch> {
974    if should_stop_search(truncated, total_matches, stop_after) {
975        return Vec::new();
976    }
977
978    let content = match read_indexed_file_bytes(&file.path) {
979        Some(content) => content,
980        None => return Vec::new(),
981    };
982    // Defense in depth: even though indexing tries to filter binaries via
983    // `is_binary_path` + full-content `is_binary_bytes`, we double-check at
984    // query time. content_inspector is fast (~bytes-per-cycle on a small
985    // preview) and this guarantees we never surface matches inside binary
986    // files even if the indexer somehow let one through (e.g. file changed
987    // between indexing and query).
988    if is_binary_bytes(&content) {
989        return Vec::new();
990    }
991    files_searched.fetch_add(1, Ordering::Relaxed);
992
993    let shared_path = Arc::new(file.path.clone());
994    let mut matches = Vec::new();
995    let mut line_starts = None;
996    let mut seen_lines = HashSet::new();
997    let mut matched_this_file = false;
998
999    match matcher {
1000        SearchMatcher::Literal(LiteralSearch::CaseSensitive(needle)) => {
1001            let finder = memchr::memmem::Finder::new(needle);
1002            let mut start = 0;
1003
1004            while let Some(position) = finder.find(&content[start..]) {
1005                if should_stop_search(truncated, total_matches, stop_after) {
1006                    break;
1007                }
1008
1009                let offset = start + position;
1010                start = offset + 1;
1011
1012                let line_starts = line_starts.get_or_insert_with(|| line_starts_bytes(&content));
1013                let (line, column, line_text) = line_details_bytes(&content, line_starts, offset);
1014                if !seen_lines.insert(line) {
1015                    continue;
1016                }
1017
1018                matched_this_file = true;
1019                let match_number = total_matches.fetch_add(1, Ordering::Relaxed) + 1;
1020                if match_number > max_results {
1021                    truncated.store(true, Ordering::Relaxed);
1022                    break;
1023                }
1024
1025                let end = offset + needle.len();
1026                matches.push(SharedGrepMatch {
1027                    file: shared_path.clone(),
1028                    line,
1029                    column,
1030                    line_text,
1031                    match_text: String::from_utf8_lossy(&content[offset..end]).into_owned(),
1032                });
1033            }
1034        }
1035        SearchMatcher::Literal(LiteralSearch::AsciiCaseInsensitive(needle)) => {
1036            let search_content = content.to_ascii_lowercase();
1037            let finder = memchr::memmem::Finder::new(needle);
1038            let mut start = 0;
1039
1040            while let Some(position) = finder.find(&search_content[start..]) {
1041                if should_stop_search(truncated, total_matches, stop_after) {
1042                    break;
1043                }
1044
1045                let offset = start + position;
1046                start = offset + 1;
1047
1048                let line_starts = line_starts.get_or_insert_with(|| line_starts_bytes(&content));
1049                let (line, column, line_text) = line_details_bytes(&content, line_starts, offset);
1050                if !seen_lines.insert(line) {
1051                    continue;
1052                }
1053
1054                matched_this_file = true;
1055                let match_number = total_matches.fetch_add(1, Ordering::Relaxed) + 1;
1056                if match_number > max_results {
1057                    truncated.store(true, Ordering::Relaxed);
1058                    break;
1059                }
1060
1061                let end = offset + needle.len();
1062                matches.push(SharedGrepMatch {
1063                    file: shared_path.clone(),
1064                    line,
1065                    column,
1066                    line_text,
1067                    match_text: String::from_utf8_lossy(&content[offset..end]).into_owned(),
1068                });
1069            }
1070        }
1071        SearchMatcher::Regex(regex) => {
1072            for matched in regex.find_iter(&content) {
1073                if should_stop_search(truncated, total_matches, stop_after) {
1074                    break;
1075                }
1076
1077                let line_starts = line_starts.get_or_insert_with(|| line_starts_bytes(&content));
1078                let (line, column, line_text) =
1079                    line_details_bytes(&content, line_starts, matched.start());
1080                if !seen_lines.insert(line) {
1081                    continue;
1082                }
1083
1084                matched_this_file = true;
1085                let match_number = total_matches.fetch_add(1, Ordering::Relaxed) + 1;
1086                if match_number > max_results {
1087                    truncated.store(true, Ordering::Relaxed);
1088                    break;
1089                }
1090
1091                matches.push(SharedGrepMatch {
1092                    file: shared_path.clone(),
1093                    line,
1094                    column,
1095                    line_text,
1096                    match_text: String::from_utf8_lossy(matched.as_bytes()).into_owned(),
1097                });
1098            }
1099        }
1100    }
1101
1102    if matched_this_file {
1103        files_with_matches.fetch_add(1, Ordering::Relaxed);
1104    }
1105
1106    matches
1107}
1108
1109fn should_stop_search(
1110    truncated: &AtomicBool,
1111    total_matches: &AtomicUsize,
1112    stop_after: usize,
1113) -> bool {
1114    truncated.load(Ordering::Relaxed) && total_matches.load(Ordering::Relaxed) >= stop_after
1115}
1116
1117fn intersect_sorted_ids(left: &[u32], right: &[u32]) -> Vec<u32> {
1118    let mut merged = Vec::with_capacity(left.len().min(right.len()));
1119    let mut left_index = 0;
1120    let mut right_index = 0;
1121
1122    while left_index < left.len() && right_index < right.len() {
1123        match left[left_index].cmp(&right[right_index]) {
1124            std::cmp::Ordering::Less => left_index += 1,
1125            std::cmp::Ordering::Greater => right_index += 1,
1126            std::cmp::Ordering::Equal => {
1127                merged.push(left[left_index]);
1128                left_index += 1;
1129                right_index += 1;
1130            }
1131        }
1132    }
1133
1134    merged
1135}
1136
1137fn union_sorted_ids(left: &[u32], right: &[u32]) -> Vec<u32> {
1138    let mut merged = Vec::with_capacity(left.len() + right.len());
1139    let mut left_index = 0;
1140    let mut right_index = 0;
1141
1142    while left_index < left.len() && right_index < right.len() {
1143        match left[left_index].cmp(&right[right_index]) {
1144            std::cmp::Ordering::Less => {
1145                merged.push(left[left_index]);
1146                left_index += 1;
1147            }
1148            std::cmp::Ordering::Greater => {
1149                merged.push(right[right_index]);
1150                right_index += 1;
1151            }
1152            std::cmp::Ordering::Equal => {
1153                merged.push(left[left_index]);
1154                left_index += 1;
1155                right_index += 1;
1156            }
1157        }
1158    }
1159
1160    merged.extend_from_slice(&left[left_index..]);
1161    merged.extend_from_slice(&right[right_index..]);
1162    merged
1163}
1164
1165pub fn decompose_regex(pattern: &str) -> RegexQuery {
1166    let hir = match regex_syntax::parse(pattern) {
1167        Ok(hir) => hir,
1168        Err(_) => return RegexQuery::default(),
1169    };
1170
1171    let build = build_query(&hir);
1172    build.into_query()
1173}
1174
1175pub fn pack_trigram(a: u8, b: u8, c: u8) -> u32 {
1176    ((a as u32) << 16) | ((b as u32) << 8) | c as u32
1177}
1178
1179pub fn normalize_char(c: u8) -> u8 {
1180    c.to_ascii_lowercase()
1181}
1182
1183pub fn extract_trigrams(content: &[u8]) -> Vec<(u32, u8, usize)> {
1184    if content.len() < 3 {
1185        return Vec::new();
1186    }
1187
1188    let mut trigrams = Vec::with_capacity(content.len().saturating_sub(2));
1189    for start in 0..=content.len() - 3 {
1190        let trigram = pack_trigram(
1191            normalize_char(content[start]),
1192            normalize_char(content[start + 1]),
1193            normalize_char(content[start + 2]),
1194        );
1195        let next_char = content.get(start + 3).copied().unwrap_or(EOF_SENTINEL);
1196        trigrams.push((trigram, next_char, start));
1197    }
1198    trigrams
1199}
1200
1201pub fn resolve_cache_dir(project_root: &Path, storage_dir: Option<&Path>) -> PathBuf {
1202    // Respect AFT_CACHE_DIR for testing — prevents tests from polluting the user's storage
1203    if let Some(override_dir) = std::env::var_os("AFT_CACHE_DIR") {
1204        return PathBuf::from(override_dir)
1205            .join("index")
1206            .join(project_cache_key(project_root));
1207    }
1208    // Use configured storage dir (from plugin, XDG-compliant)
1209    if let Some(dir) = storage_dir {
1210        return dir.join("index").join(project_cache_key(project_root));
1211    }
1212    // Fallback to ~/.cache/aft/ (legacy, for standalone binary usage)
1213    let home = std::env::var_os("HOME")
1214        .map(PathBuf::from)
1215        .unwrap_or_else(|| PathBuf::from("."));
1216    home.join(".cache")
1217        .join("aft")
1218        .join("index")
1219        .join(project_cache_key(project_root))
1220}
1221
1222pub(crate) fn build_path_filters(
1223    include: &[String],
1224    exclude: &[String],
1225) -> Result<PathFilters, String> {
1226    Ok(PathFilters {
1227        includes: build_globset(include)?,
1228        excludes: build_globset(exclude)?,
1229    })
1230}
1231
1232pub(crate) fn walk_project_files(root: &Path, filters: &PathFilters) -> Vec<PathBuf> {
1233    walk_project_files_from(root, root, filters)
1234}
1235
1236pub(crate) fn walk_project_files_from(
1237    filter_root: &Path,
1238    search_root: &Path,
1239    filters: &PathFilters,
1240) -> Vec<PathBuf> {
1241    let mut builder = WalkBuilder::new(search_root);
1242    builder
1243        .hidden(false)
1244        .git_ignore(true)
1245        .git_global(true)
1246        .git_exclude(true)
1247        .filter_entry(|entry| {
1248            let name = entry.file_name().to_string_lossy();
1249            if entry.file_type().map_or(false, |ft| ft.is_dir()) {
1250                return !matches!(
1251                    name.as_ref(),
1252                    "node_modules"
1253                        | "target"
1254                        | "venv"
1255                        | ".venv"
1256                        | ".git"
1257                        | "__pycache__"
1258                        | ".tox"
1259                        | "dist"
1260                        | "build"
1261                );
1262            }
1263            true
1264        });
1265
1266    let mut files = Vec::new();
1267    for entry in builder.build().filter_map(|entry| entry.ok()) {
1268        if !entry
1269            .file_type()
1270            .map_or(false, |file_type| file_type.is_file())
1271        {
1272            continue;
1273        }
1274        let path = entry.into_path();
1275        if filters.matches(filter_root, &path) {
1276            files.push(path);
1277        }
1278    }
1279
1280    sort_paths_by_mtime_desc(&mut files);
1281    files
1282}
1283
1284pub(crate) fn read_searchable_text(path: &Path) -> Option<String> {
1285    let bytes = fs::read(path).ok()?;
1286    if is_binary_bytes(&bytes) {
1287        return None;
1288    }
1289    String::from_utf8(bytes).ok()
1290}
1291
1292fn read_indexed_file_bytes(path: &Path) -> Option<Vec<u8>> {
1293    fs::read(path).ok()
1294}
1295
1296pub(crate) fn relative_to_root(root: &Path, path: &Path) -> PathBuf {
1297    path.strip_prefix(root)
1298        .map(PathBuf::from)
1299        .unwrap_or_else(|_| path.to_path_buf())
1300}
1301
1302/// Sort paths newest-first by mtime, falling back to lexicographic order.
1303///
1304/// Pre-v0.15.2 this called `path_modified_time(...)` directly inside the
1305/// `sort_by()` closure. That made the comparator non-deterministic — a
1306/// `stat()` syscall for the same path can return different values across
1307/// invocations (file edited mid-sort, file deleted, OS clock adjustments,
1308/// concurrent file-watcher activity), and Rust's slice::sort panics at
1309/// runtime when it detects a non-total-order comparator. CI hit this on
1310/// a Pi e2e test where the bridge invalidated files in parallel with grep.
1311///
1312/// Fix: snapshot mtimes ONCE into a HashMap before sorting, then look up
1313/// from the map inside the closure. Pure function ⇒ guaranteed total order.
1314pub(crate) fn sort_paths_by_mtime_desc(paths: &mut [PathBuf]) {
1315    use std::collections::HashMap;
1316    let mut mtimes: HashMap<PathBuf, Option<SystemTime>> = HashMap::with_capacity(paths.len());
1317    for path in paths.iter() {
1318        mtimes
1319            .entry(path.clone())
1320            .or_insert_with(|| path_modified_time(path));
1321    }
1322    paths.sort_by(|left, right| {
1323        let left_mtime = mtimes.get(left).and_then(|v| *v);
1324        let right_mtime = mtimes.get(right).and_then(|v| *v);
1325        right_mtime.cmp(&left_mtime).then_with(|| left.cmp(right))
1326    });
1327}
1328
1329/// See `sort_paths_by_mtime_desc` for why mtimes are snapshotted ahead of
1330/// the sort. Same fix, applied to grep matches that share files.
1331pub(crate) fn sort_grep_matches_by_mtime_desc(matches: &mut [GrepMatch], project_root: &Path) {
1332    use std::collections::HashMap;
1333    let mut mtimes: HashMap<PathBuf, Option<SystemTime>> = HashMap::new();
1334    for m in matches.iter() {
1335        mtimes.entry(m.file.clone()).or_insert_with(|| {
1336            let resolved = resolve_match_path(project_root, &m.file);
1337            path_modified_time(&resolved)
1338        });
1339    }
1340    matches.sort_by(|left, right| {
1341        let left_mtime = mtimes.get(&left.file).and_then(|v| *v);
1342        let right_mtime = mtimes.get(&right.file).and_then(|v| *v);
1343        right_mtime
1344            .cmp(&left_mtime)
1345            .then_with(|| left.file.cmp(&right.file))
1346            .then_with(|| left.line.cmp(&right.line))
1347            .then_with(|| left.column.cmp(&right.column))
1348    });
1349}
1350
1351/// See `sort_paths_by_mtime_desc` for why mtimes are snapshotted ahead of
1352/// the sort. The cached lookup function `modified_for_path` is fast (in-memory
1353/// table from the search index), but it can still return different values if
1354/// the file is modified mid-sort. Snapshot once.
1355fn sort_shared_grep_matches_by_cached_mtime_desc<F>(
1356    matches: &mut [SharedGrepMatch],
1357    modified_for_path: F,
1358) where
1359    F: Fn(&Path) -> Option<SystemTime>,
1360{
1361    use std::collections::HashMap;
1362    let mut mtimes: HashMap<PathBuf, Option<SystemTime>> = HashMap::with_capacity(matches.len());
1363    for m in matches.iter() {
1364        let path = m.file.as_path().to_path_buf();
1365        mtimes
1366            .entry(path.clone())
1367            .or_insert_with(|| modified_for_path(&path));
1368    }
1369    matches.sort_by(|left, right| {
1370        let left_mtime = mtimes.get(left.file.as_path()).and_then(|v| *v);
1371        let right_mtime = mtimes.get(right.file.as_path()).and_then(|v| *v);
1372        right_mtime
1373            .cmp(&left_mtime)
1374            .then_with(|| left.file.as_path().cmp(right.file.as_path()))
1375            .then_with(|| left.line.cmp(&right.line))
1376            .then_with(|| left.column.cmp(&right.column))
1377    });
1378}
1379
1380pub(crate) fn resolve_search_scope(project_root: &Path, path: Option<&str>) -> SearchScope {
1381    let resolved_project_root = canonicalize_or_normalize(project_root);
1382    let root = match path {
1383        Some(path) => {
1384            let path = PathBuf::from(path);
1385            if path.is_absolute() {
1386                canonicalize_or_normalize(&path)
1387            } else {
1388                normalize_path(&resolved_project_root.join(path))
1389            }
1390        }
1391        None => resolved_project_root.clone(),
1392    };
1393
1394    let use_index = is_within_search_root(&resolved_project_root, &root);
1395    SearchScope { root, use_index }
1396}
1397
1398pub(crate) fn is_binary_bytes(content: &[u8]) -> bool {
1399    content_inspector::inspect(content).is_binary()
1400}
1401
1402pub(crate) fn current_git_head(root: &Path) -> Option<String> {
1403    run_git(root, &["rev-parse", "HEAD"])
1404}
1405
1406pub(crate) fn project_cache_key(project_root: &Path) -> String {
1407    use sha2::{Digest, Sha256};
1408
1409    let mut hasher = Sha256::new();
1410
1411    if let Some(root_commit) = run_git(project_root, &["rev-list", "--max-parents=0", "HEAD"]) {
1412        // Git repo: root commit is the unique identity.
1413        // Same repo cloned anywhere produces the same key.
1414        hasher.update(root_commit.as_bytes());
1415    } else {
1416        // Non-git project: use the canonical filesystem path as identity.
1417        let canonical_root = canonicalize_or_normalize(project_root);
1418        hasher.update(canonical_root.to_string_lossy().as_bytes());
1419    }
1420
1421    let digest = format!("{:x}", hasher.finalize());
1422    digest[..16].to_string()
1423}
1424
1425impl PathFilters {
1426    fn matches(&self, root: &Path, path: &Path) -> bool {
1427        let relative = to_glob_path(&relative_to_root(root, path));
1428        if self
1429            .includes
1430            .as_ref()
1431            .is_some_and(|includes| !includes.is_match(&relative))
1432        {
1433            return false;
1434        }
1435        if self
1436            .excludes
1437            .as_ref()
1438            .is_some_and(|excludes| excludes.is_match(&relative))
1439        {
1440            return false;
1441        }
1442        true
1443    }
1444}
1445
1446fn canonicalize_or_normalize(path: &Path) -> PathBuf {
1447    fs::canonicalize(path).unwrap_or_else(|_| normalize_path(path))
1448}
1449
1450fn resolve_match_path(project_root: &Path, path: &Path) -> PathBuf {
1451    if path.is_absolute() {
1452        path.to_path_buf()
1453    } else {
1454        project_root.join(path)
1455    }
1456}
1457
1458fn path_modified_time(path: &Path) -> Option<SystemTime> {
1459    fs::metadata(path)
1460        .and_then(|metadata| metadata.modified())
1461        .ok()
1462}
1463
1464fn normalize_path(path: &Path) -> PathBuf {
1465    let mut result = PathBuf::new();
1466    for component in path.components() {
1467        match component {
1468            Component::ParentDir => {
1469                if !result.pop() {
1470                    result.push(component);
1471                }
1472            }
1473            Component::CurDir => {}
1474            _ => result.push(component),
1475        }
1476    }
1477    result
1478}
1479
1480/// Verify stored file mtimes against disk. Re-index any files whose mtime changed
1481/// since the index was last written. Also detect new files and deleted files.
1482fn verify_file_mtimes(index: &mut SearchIndex) {
1483    // Collect stale files (mtime mismatch or deleted)
1484    let mut stale_paths = Vec::new();
1485    for entry in &index.files {
1486        if entry.path.as_os_str().is_empty() {
1487            continue; // tombstoned entry
1488        }
1489        match fs::metadata(&entry.path) {
1490            Ok(meta) => {
1491                let current_mtime = meta.modified().unwrap_or(UNIX_EPOCH);
1492                if current_mtime != entry.modified || meta.len() != entry.size {
1493                    stale_paths.push(entry.path.clone());
1494                }
1495            }
1496            Err(_) => {
1497                // File deleted
1498                stale_paths.push(entry.path.clone());
1499            }
1500        }
1501    }
1502
1503    // Re-index stale files
1504    for path in &stale_paths {
1505        index.update_file(path);
1506    }
1507
1508    // Detect new files not in the index
1509    let filters = PathFilters::default();
1510    for path in walk_project_files(&index.project_root, &filters) {
1511        if !index.path_to_id.contains_key(&path) {
1512            index.update_file(&path);
1513        }
1514    }
1515
1516    if !stale_paths.is_empty() {
1517        log::info!(
1518            "[aft] search index: refreshed {} stale file(s) from disk cache",
1519            stale_paths.len()
1520        );
1521    }
1522}
1523
1524fn is_within_search_root(search_root: &Path, path: &Path) -> bool {
1525    path.starts_with(search_root)
1526}
1527
1528impl QueryBuild {
1529    fn into_query(self) -> RegexQuery {
1530        let mut query = RegexQuery::default();
1531
1532        for run in self.and_runs {
1533            add_run_to_and_query(&mut query, &run);
1534        }
1535
1536        for group in self.or_groups {
1537            let mut trigrams = BTreeSet::new();
1538            let mut filters = HashMap::new();
1539            for run in group {
1540                for (trigram, filter) in trigram_filters(&run) {
1541                    trigrams.insert(trigram);
1542                    merge_filter(filters.entry(trigram).or_default(), filter);
1543                }
1544            }
1545            if !trigrams.is_empty() {
1546                query.or_groups.push(trigrams.into_iter().collect());
1547                query.or_filters.push(filters);
1548            }
1549        }
1550
1551        query
1552    }
1553}
1554
1555fn build_query(hir: &Hir) -> QueryBuild {
1556    match hir.kind() {
1557        HirKind::Literal(literal) => {
1558            if literal.0.len() >= 3 {
1559                QueryBuild {
1560                    and_runs: vec![literal.0.to_vec()],
1561                    or_groups: Vec::new(),
1562                }
1563            } else {
1564                QueryBuild::default()
1565            }
1566        }
1567        HirKind::Capture(capture) => build_query(&capture.sub),
1568        HirKind::Concat(parts) => {
1569            let mut build = QueryBuild::default();
1570            for part in parts {
1571                let part_build = build_query(part);
1572                build.and_runs.extend(part_build.and_runs);
1573                build.or_groups.extend(part_build.or_groups);
1574            }
1575            build
1576        }
1577        HirKind::Alternation(parts) => {
1578            let mut group = Vec::new();
1579            for part in parts {
1580                let Some(mut choices) = guaranteed_run_choices(part) else {
1581                    return QueryBuild::default();
1582                };
1583                group.append(&mut choices);
1584            }
1585            if group.is_empty() {
1586                QueryBuild::default()
1587            } else {
1588                QueryBuild {
1589                    and_runs: Vec::new(),
1590                    or_groups: vec![group],
1591                }
1592            }
1593        }
1594        HirKind::Repetition(repetition) => {
1595            if repetition.min == 0 {
1596                QueryBuild::default()
1597            } else {
1598                build_query(&repetition.sub)
1599            }
1600        }
1601        HirKind::Empty | HirKind::Class(_) | HirKind::Look(_) => QueryBuild::default(),
1602    }
1603}
1604
1605fn guaranteed_run_choices(hir: &Hir) -> Option<Vec<Vec<u8>>> {
1606    match hir.kind() {
1607        HirKind::Literal(literal) => {
1608            if literal.0.len() >= 3 {
1609                Some(vec![literal.0.to_vec()])
1610            } else {
1611                None
1612            }
1613        }
1614        HirKind::Capture(capture) => guaranteed_run_choices(&capture.sub),
1615        HirKind::Concat(parts) => {
1616            let mut runs = Vec::new();
1617            for part in parts {
1618                if let Some(mut part_runs) = guaranteed_run_choices(part) {
1619                    runs.append(&mut part_runs);
1620                }
1621            }
1622            if runs.is_empty() {
1623                None
1624            } else {
1625                Some(runs)
1626            }
1627        }
1628        HirKind::Alternation(parts) => {
1629            let mut runs = Vec::new();
1630            for part in parts {
1631                let Some(mut part_runs) = guaranteed_run_choices(part) else {
1632                    return None;
1633                };
1634                runs.append(&mut part_runs);
1635            }
1636            if runs.is_empty() {
1637                None
1638            } else {
1639                Some(runs)
1640            }
1641        }
1642        HirKind::Repetition(repetition) => {
1643            if repetition.min == 0 {
1644                None
1645            } else {
1646                guaranteed_run_choices(&repetition.sub)
1647            }
1648        }
1649        HirKind::Empty | HirKind::Class(_) | HirKind::Look(_) => None,
1650    }
1651}
1652
1653fn add_run_to_and_query(query: &mut RegexQuery, run: &[u8]) {
1654    for (trigram, filter) in trigram_filters(run) {
1655        if !query.and_trigrams.contains(&trigram) {
1656            query.and_trigrams.push(trigram);
1657        }
1658        merge_filter(query.and_filters.entry(trigram).or_default(), filter);
1659    }
1660}
1661
1662fn trigram_filters(run: &[u8]) -> Vec<(u32, PostingFilter)> {
1663    let mut filters: BTreeMap<u32, PostingFilter> = BTreeMap::new();
1664    for (trigram, next_char, position) in extract_trigrams(run) {
1665        let entry: &mut PostingFilter = filters.entry(trigram).or_default();
1666        if next_char != EOF_SENTINEL {
1667            entry.next_mask |= mask_for_next_char(next_char);
1668        }
1669        entry.loc_mask |= mask_for_position(position);
1670    }
1671    filters.into_iter().collect()
1672}
1673
1674fn merge_filter(target: &mut PostingFilter, filter: PostingFilter) {
1675    target.next_mask |= filter.next_mask;
1676    target.loc_mask |= filter.loc_mask;
1677}
1678
1679fn mask_for_next_char(next_char: u8) -> u8 {
1680    let bit = (normalize_char(next_char).wrapping_mul(31) & 7) as u32;
1681    1u8 << bit
1682}
1683
1684fn mask_for_position(position: usize) -> u8 {
1685    1u8 << (position % 8)
1686}
1687
1688fn build_globset(patterns: &[String]) -> Result<Option<GlobSet>, String> {
1689    if patterns.is_empty() {
1690        return Ok(None);
1691    }
1692
1693    let mut builder = GlobSetBuilder::new();
1694    for pattern in patterns {
1695        let glob = Glob::new(pattern).map_err(|error| error.to_string())?;
1696        builder.add(glob);
1697    }
1698    builder.build().map(Some).map_err(|error| error.to_string())
1699}
1700
1701fn read_u32<R: Read>(reader: &mut R) -> std::io::Result<u32> {
1702    let mut buffer = [0u8; 4];
1703    reader.read_exact(&mut buffer)?;
1704    Ok(u32::from_le_bytes(buffer))
1705}
1706
1707fn read_u64<R: Read>(reader: &mut R) -> std::io::Result<u64> {
1708    let mut buffer = [0u8; 8];
1709    reader.read_exact(&mut buffer)?;
1710    Ok(u64::from_le_bytes(buffer))
1711}
1712
1713fn write_u32<W: Write>(writer: &mut W, value: u32) -> std::io::Result<()> {
1714    writer.write_all(&value.to_le_bytes())
1715}
1716
1717fn write_u64<W: Write>(writer: &mut W, value: u64) -> std::io::Result<()> {
1718    writer.write_all(&value.to_le_bytes())
1719}
1720
1721fn remaining_bytes<R: Seek>(reader: &mut R, total_len: usize) -> Option<usize> {
1722    let pos = usize::try_from(reader.stream_position().ok()?).ok()?;
1723    total_len.checked_sub(pos)
1724}
1725
1726fn run_git(root: &Path, args: &[&str]) -> Option<String> {
1727    let output = Command::new("git")
1728        .arg("-C")
1729        .arg(root)
1730        .args(args)
1731        .output()
1732        .ok()?;
1733    if !output.status.success() {
1734        return None;
1735    }
1736    let value = String::from_utf8(output.stdout).ok()?;
1737    let value = value.trim().to_string();
1738    if value.is_empty() {
1739        None
1740    } else {
1741        Some(value)
1742    }
1743}
1744
1745fn apply_git_diff_updates(index: &mut SearchIndex, root: &Path, from: &str, to: &str) -> bool {
1746    let diff_range = format!("{}..{}", from, to);
1747    let output = match Command::new("git")
1748        .arg("-C")
1749        .arg(root)
1750        .args(["diff", "--name-only", &diff_range])
1751        .output()
1752    {
1753        Ok(output) => output,
1754        Err(_) => return false,
1755    };
1756
1757    if !output.status.success() {
1758        return false;
1759    }
1760
1761    let Ok(paths) = String::from_utf8(output.stdout) else {
1762        return false;
1763    };
1764
1765    for relative_path in paths.lines().map(str::trim).filter(|path| !path.is_empty()) {
1766        let path = root.join(relative_path);
1767        if path.exists() {
1768            index.update_file(&path);
1769        } else {
1770            index.remove_file(&path);
1771        }
1772    }
1773
1774    true
1775}
1776
1777fn is_binary_path(path: &Path, size: u64) -> bool {
1778    if size == 0 {
1779        return false;
1780    }
1781
1782    let mut file = match File::open(path) {
1783        Ok(file) => file,
1784        Err(_) => return true,
1785    };
1786
1787    let mut preview = vec![0u8; PREVIEW_BYTES.min(size as usize)];
1788    match file.read(&mut preview) {
1789        Ok(read) => is_binary_bytes(&preview[..read]),
1790        Err(_) => true,
1791    }
1792}
1793
1794fn line_starts_bytes(content: &[u8]) -> Vec<usize> {
1795    let mut starts = vec![0usize];
1796    for (index, byte) in content.iter().copied().enumerate() {
1797        if byte == b'\n' {
1798            starts.push(index + 1);
1799        }
1800    }
1801    starts
1802}
1803
1804fn line_details_bytes(content: &[u8], line_starts: &[usize], offset: usize) -> (u32, u32, String) {
1805    let line_index = match line_starts.binary_search(&offset) {
1806        Ok(index) => index,
1807        Err(index) => index.saturating_sub(1),
1808    };
1809    let line_start = line_starts.get(line_index).copied().unwrap_or(0);
1810    let line_end = content[line_start..]
1811        .iter()
1812        .position(|byte| *byte == b'\n')
1813        .map(|length| line_start + length)
1814        .unwrap_or(content.len());
1815    let mut line_slice = &content[line_start..line_end];
1816    if line_slice.ends_with(b"\r") {
1817        line_slice = &line_slice[..line_slice.len() - 1];
1818    }
1819    let line_text = String::from_utf8_lossy(line_slice).into_owned();
1820    let column = String::from_utf8_lossy(&content[line_start..offset])
1821        .chars()
1822        .count() as u32
1823        + 1;
1824    (line_index as u32 + 1, column, line_text)
1825}
1826
1827fn to_glob_path(path: &Path) -> String {
1828    path.to_string_lossy().replace('\\', "/")
1829}
1830
1831#[cfg(test)]
1832mod tests {
1833    use std::process::Command;
1834
1835    use super::*;
1836
1837    #[test]
1838    fn extract_trigrams_tracks_next_char_and_position() {
1839        let trigrams = extract_trigrams(b"Rust");
1840        assert_eq!(trigrams.len(), 2);
1841        assert_eq!(trigrams[0], (pack_trigram(b'r', b'u', b's'), b't', 0));
1842        assert_eq!(
1843            trigrams[1],
1844            (pack_trigram(b'u', b's', b't'), EOF_SENTINEL, 1)
1845        );
1846    }
1847
1848    #[test]
1849    fn decompose_regex_extracts_literals_and_alternations() {
1850        let query = decompose_regex("abc(def|ghi)xyz");
1851        assert!(query.and_trigrams.contains(&pack_trigram(b'a', b'b', b'c')));
1852        assert!(query.and_trigrams.contains(&pack_trigram(b'x', b'y', b'z')));
1853        assert_eq!(query.or_groups.len(), 1);
1854        assert!(query.or_groups[0].contains(&pack_trigram(b'd', b'e', b'f')));
1855        assert!(query.or_groups[0].contains(&pack_trigram(b'g', b'h', b'i')));
1856    }
1857
1858    #[test]
1859    fn candidates_intersect_posting_lists() {
1860        let mut index = SearchIndex::new();
1861        let dir = tempfile::tempdir().expect("create temp dir");
1862        let alpha = dir.path().join("alpha.txt");
1863        let beta = dir.path().join("beta.txt");
1864        fs::write(&alpha, "abcdef").expect("write alpha");
1865        fs::write(&beta, "abcxyz").expect("write beta");
1866        index.project_root = dir.path().to_path_buf();
1867        index.index_file(&alpha, b"abcdef");
1868        index.index_file(&beta, b"abcxyz");
1869
1870        let query = RegexQuery {
1871            and_trigrams: vec![
1872                pack_trigram(b'a', b'b', b'c'),
1873                pack_trigram(b'd', b'e', b'f'),
1874            ],
1875            ..RegexQuery::default()
1876        };
1877
1878        let candidates = index.candidates(&query);
1879        assert_eq!(candidates.len(), 1);
1880        assert_eq!(index.files[candidates[0] as usize].path, alpha);
1881    }
1882
1883    #[test]
1884    fn candidates_apply_bloom_filters() {
1885        let mut index = SearchIndex::new();
1886        let dir = tempfile::tempdir().expect("create temp dir");
1887        let file = dir.path().join("sample.txt");
1888        fs::write(&file, "abcd efgh").expect("write sample");
1889        index.project_root = dir.path().to_path_buf();
1890        index.index_file(&file, b"abcd efgh");
1891
1892        let trigram = pack_trigram(b'a', b'b', b'c');
1893        let matching_filter = PostingFilter {
1894            next_mask: mask_for_next_char(b'd'),
1895            loc_mask: mask_for_position(0),
1896        };
1897        let non_matching_filter = PostingFilter {
1898            next_mask: mask_for_next_char(b'z'),
1899            loc_mask: mask_for_position(0),
1900        };
1901
1902        assert_eq!(
1903            index
1904                .postings_for_trigram(trigram, Some(matching_filter))
1905                .len(),
1906            1
1907        );
1908        assert!(index
1909            .postings_for_trigram(trigram, Some(non_matching_filter))
1910            .is_empty());
1911    }
1912
1913    #[test]
1914    fn disk_round_trip_preserves_postings_and_files() {
1915        let dir = tempfile::tempdir().expect("create temp dir");
1916        let project = dir.path().join("project");
1917        fs::create_dir_all(&project).expect("create project dir");
1918        let file = project.join("src.txt");
1919        fs::write(&file, "abcdef").expect("write source");
1920
1921        let mut index = SearchIndex::build(&project);
1922        index.git_head = Some("deadbeef".to_string());
1923        let cache_dir = dir.path().join("cache");
1924        index.write_to_disk(&cache_dir, index.git_head.as_deref());
1925
1926        let loaded = SearchIndex::read_from_disk(&cache_dir).expect("load index from disk");
1927        assert_eq!(loaded.stored_git_head(), Some("deadbeef"));
1928        assert_eq!(loaded.files.len(), 1);
1929        assert_eq!(
1930            relative_to_root(&loaded.project_root, &loaded.files[0].path),
1931            PathBuf::from("src.txt")
1932        );
1933        assert_eq!(loaded.postings.len(), index.postings.len());
1934        assert!(loaded
1935            .postings
1936            .contains_key(&pack_trigram(b'a', b'b', b'c')));
1937    }
1938
1939    #[test]
1940    fn write_to_disk_uses_temp_files_and_cleans_them_up() {
1941        let dir = tempfile::tempdir().expect("create temp dir");
1942        let project = dir.path().join("project");
1943        fs::create_dir_all(&project).expect("create project dir");
1944        fs::write(project.join("src.txt"), "abcdef").expect("write source");
1945
1946        let index = SearchIndex::build(&project);
1947        let cache_dir = dir.path().join("cache");
1948        index.write_to_disk(&cache_dir, None);
1949
1950        assert!(cache_dir.join("postings.bin").is_file());
1951        assert!(cache_dir.join("lookup.bin").is_file());
1952        assert!(!cache_dir.join("postings.bin.tmp").exists());
1953        assert!(!cache_dir.join("lookup.bin.tmp").exists());
1954    }
1955
1956    #[test]
1957    fn project_cache_key_includes_checkout_path() {
1958        let dir = tempfile::tempdir().expect("create temp dir");
1959        let source = dir.path().join("source");
1960        fs::create_dir_all(&source).expect("create source repo dir");
1961        fs::write(source.join("tracked.txt"), "content\n").expect("write tracked file");
1962
1963        assert!(Command::new("git")
1964            .current_dir(&source)
1965            .args(["init"])
1966            .status()
1967            .expect("init git repo")
1968            .success());
1969        assert!(Command::new("git")
1970            .current_dir(&source)
1971            .args(["add", "."])
1972            .status()
1973            .expect("git add")
1974            .success());
1975        assert!(Command::new("git")
1976            .current_dir(&source)
1977            .args([
1978                "-c",
1979                "user.name=AFT Tests",
1980                "-c",
1981                "user.email=aft-tests@example.com",
1982                "commit",
1983                "-m",
1984                "initial",
1985            ])
1986            .status()
1987            .expect("git commit")
1988            .success());
1989
1990        let clone = dir.path().join("clone");
1991        assert!(Command::new("git")
1992            .args(["clone", "--quiet"])
1993            .arg(&source)
1994            .arg(&clone)
1995            .status()
1996            .expect("git clone")
1997            .success());
1998
1999        let source_key = project_cache_key(&source);
2000        let clone_key = project_cache_key(&clone);
2001
2002        assert_eq!(source_key.len(), 16);
2003        assert_eq!(clone_key.len(), 16);
2004        // Same repo (same root commit) → same cache key regardless of clone path
2005        assert_eq!(source_key, clone_key);
2006    }
2007
2008    #[test]
2009    fn resolve_search_scope_disables_index_for_external_path() {
2010        let dir = tempfile::tempdir().expect("create temp dir");
2011        let project = dir.path().join("project");
2012        let outside = dir.path().join("outside");
2013        fs::create_dir_all(&project).expect("create project dir");
2014        fs::create_dir_all(&outside).expect("create outside dir");
2015
2016        let scope = resolve_search_scope(&project, outside.to_str());
2017
2018        assert_eq!(
2019            scope.root,
2020            fs::canonicalize(&outside).expect("canonicalize outside")
2021        );
2022        assert!(!scope.use_index);
2023    }
2024
2025    #[test]
2026    fn grep_filters_matches_to_search_root() {
2027        let dir = tempfile::tempdir().expect("create temp dir");
2028        let project = dir.path().join("project");
2029        let src = project.join("src");
2030        let docs = project.join("docs");
2031        fs::create_dir_all(&src).expect("create src dir");
2032        fs::create_dir_all(&docs).expect("create docs dir");
2033        fs::write(src.join("main.rs"), "pub struct SearchIndex;\n").expect("write src file");
2034        fs::write(docs.join("guide.md"), "SearchIndex guide\n").expect("write docs file");
2035
2036        let index = SearchIndex::build(&project);
2037        let result = index.search_grep("SearchIndex", true, &[], &[], &src, 10);
2038
2039        assert_eq!(result.files_searched, 1);
2040        assert_eq!(result.files_with_matches, 1);
2041        assert_eq!(result.matches.len(), 1);
2042        // Index stores canonicalized paths; on macOS /var → /private/var
2043        let expected = fs::canonicalize(src.join("main.rs")).expect("canonicalize");
2044        assert_eq!(result.matches[0].file, expected);
2045    }
2046
2047    #[test]
2048    fn grep_deduplicates_multiple_matches_on_same_line() {
2049        let dir = tempfile::tempdir().expect("create temp dir");
2050        let project = dir.path().join("project");
2051        let src = project.join("src");
2052        fs::create_dir_all(&src).expect("create src dir");
2053        fs::write(src.join("main.rs"), "SearchIndex SearchIndex\n").expect("write src file");
2054
2055        let index = SearchIndex::build(&project);
2056        let result = index.search_grep("SearchIndex", true, &[], &[], &src, 10);
2057
2058        assert_eq!(result.total_matches, 1);
2059        assert_eq!(result.matches.len(), 1);
2060    }
2061
2062    #[test]
2063    fn grep_reports_total_matches_before_truncation() {
2064        let dir = tempfile::tempdir().expect("create temp dir");
2065        let project = dir.path().join("project");
2066        let src = project.join("src");
2067        fs::create_dir_all(&src).expect("create src dir");
2068        fs::write(src.join("main.rs"), "SearchIndex\nSearchIndex\n").expect("write src file");
2069
2070        let index = SearchIndex::build(&project);
2071        let result = index.search_grep("SearchIndex", true, &[], &[], &src, 1);
2072
2073        assert_eq!(result.total_matches, 2);
2074        assert_eq!(result.matches.len(), 1);
2075        assert!(result.truncated);
2076    }
2077
2078    #[test]
2079    fn glob_filters_results_to_search_root() {
2080        let dir = tempfile::tempdir().expect("create temp dir");
2081        let project = dir.path().join("project");
2082        let src = project.join("src");
2083        let scripts = project.join("scripts");
2084        fs::create_dir_all(&src).expect("create src dir");
2085        fs::create_dir_all(&scripts).expect("create scripts dir");
2086        fs::write(src.join("main.rs"), "pub fn main() {}\n").expect("write src file");
2087        fs::write(scripts.join("tool.rs"), "pub fn tool() {}\n").expect("write scripts file");
2088
2089        let index = SearchIndex::build(&project);
2090        let files = index.glob("**/*.rs", &src);
2091
2092        assert_eq!(
2093            files,
2094            vec![fs::canonicalize(src.join("main.rs")).expect("canonicalize src file")]
2095        );
2096    }
2097
2098    #[test]
2099    fn glob_includes_hidden_and_binary_files() {
2100        let dir = tempfile::tempdir().expect("create temp dir");
2101        let project = dir.path().join("project");
2102        let hidden_dir = project.join(".hidden");
2103        fs::create_dir_all(&hidden_dir).expect("create hidden dir");
2104        let hidden_file = hidden_dir.join("data.bin");
2105        fs::write(&hidden_file, [0u8, 159, 146, 150]).expect("write binary file");
2106
2107        let index = SearchIndex::build(&project);
2108        let files = index.glob("**/*.bin", &project);
2109
2110        assert_eq!(
2111            files,
2112            vec![fs::canonicalize(hidden_file).expect("canonicalize binary file")]
2113        );
2114    }
2115
2116    #[test]
2117    fn read_from_disk_rejects_invalid_nanos() {
2118        let dir = tempfile::tempdir().expect("create temp dir");
2119        let cache_dir = dir.path().join("cache");
2120        fs::create_dir_all(&cache_dir).expect("create cache dir");
2121
2122        let mut postings = Vec::new();
2123        postings.extend_from_slice(INDEX_MAGIC);
2124        postings.extend_from_slice(&INDEX_VERSION.to_le_bytes());
2125        postings.extend_from_slice(&0u32.to_le_bytes());
2126        postings.extend_from_slice(&1u32.to_le_bytes());
2127        postings.extend_from_slice(&DEFAULT_MAX_FILE_SIZE.to_le_bytes());
2128        postings.extend_from_slice(&1u32.to_le_bytes());
2129        postings.extend_from_slice(b"/");
2130        postings.push(0u8);
2131        postings.extend_from_slice(&1u32.to_le_bytes());
2132        postings.extend_from_slice(&0u64.to_le_bytes());
2133        postings.extend_from_slice(&0u64.to_le_bytes());
2134        postings.extend_from_slice(&1_000_000_000u32.to_le_bytes());
2135        postings.extend_from_slice(b"a");
2136        postings.extend_from_slice(&0u64.to_le_bytes());
2137
2138        let mut lookup = Vec::new();
2139        lookup.extend_from_slice(LOOKUP_MAGIC);
2140        lookup.extend_from_slice(&INDEX_VERSION.to_le_bytes());
2141        lookup.extend_from_slice(&0u32.to_le_bytes());
2142
2143        fs::write(cache_dir.join("postings.bin"), postings).expect("write postings");
2144        fs::write(cache_dir.join("lookup.bin"), lookup).expect("write lookup");
2145
2146        assert!(SearchIndex::read_from_disk(&cache_dir).is_none());
2147    }
2148
2149    /// Regression: v0.15.2 — sort_paths_by_mtime_desc panicked when files
2150    /// changed between cmp() calls.
2151    ///
2152    /// Pre-fix, the sort closure called `path_modified_time(path)` directly,
2153    /// which does a `stat()` syscall. If the file was deleted, modified, or
2154    /// touched mid-sort, the comparator returned different values for the
2155    /// same input pair on different invocations. Rust's slice::sort detects
2156    /// this and panics with "user-provided comparison function does not
2157    /// correctly implement a total order".
2158    ///
2159    /// CI hit this on a Pi e2e test (workflow run 24887807972) where the
2160    /// bridge invalidated files in parallel with grep's sort path. This
2161    /// test simulates the worst case: most paths don't exist (Err from
2162    /// fs::metadata) and sort still completes successfully.
2163    #[test]
2164    fn sort_paths_by_mtime_desc_does_not_panic_on_missing_files() {
2165        // Mix of existing and non-existing paths in deliberately
2166        // non-monotonic order — pre-fix, the sort would call stat() at
2167        // least N log N times and any flakiness would trigger the panic.
2168        let dir = tempfile::tempdir().expect("create tempdir");
2169        let mut paths: Vec<PathBuf> = Vec::new();
2170        for i in 0..30 {
2171            // Half exist, half don't.
2172            let path = if i % 2 == 0 {
2173                let p = dir.path().join(format!("real-{i}.rs"));
2174                fs::write(&p, format!("// {i}\n")).expect("write");
2175                p
2176            } else {
2177                dir.path().join(format!("missing-{i}.rs"))
2178            };
2179            paths.push(path);
2180        }
2181
2182        // Run the sort many times to maximise the chance of catching any
2183        // residual non-determinism. Pre-fix: panic. Post-fix: stable.
2184        for _ in 0..50 {
2185            let mut copy = paths.clone();
2186            sort_paths_by_mtime_desc(&mut copy);
2187            assert_eq!(copy.len(), paths.len());
2188        }
2189    }
2190
2191    /// Regression: v0.15.2 — sort_grep_matches_by_mtime_desc panicked under
2192    /// the same conditions as sort_paths_by_mtime_desc. See the
2193    /// sort_paths_... test above for the full rationale.
2194    #[test]
2195    fn sort_grep_matches_by_mtime_desc_does_not_panic_on_missing_files() {
2196        let dir = tempfile::tempdir().expect("create tempdir");
2197        let mut matches: Vec<GrepMatch> = Vec::new();
2198        for i in 0..30 {
2199            let file = if i % 2 == 0 {
2200                let p = dir.path().join(format!("real-{i}.rs"));
2201                fs::write(&p, format!("// {i}\n")).expect("write");
2202                p
2203            } else {
2204                dir.path().join(format!("missing-{i}.rs"))
2205            };
2206            matches.push(GrepMatch {
2207                file,
2208                line: u32::try_from(i).unwrap_or(0),
2209                column: 0,
2210                line_text: format!("match {i}"),
2211                match_text: format!("match {i}"),
2212            });
2213        }
2214
2215        for _ in 0..50 {
2216            let mut copy = matches.clone();
2217            sort_grep_matches_by_mtime_desc(&mut copy, dir.path());
2218            assert_eq!(copy.len(), matches.len());
2219        }
2220    }
2221}