cx-cli 0.7.0

Semantic code navigation for AI agents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
use ignore::WalkBuilder;
use rayon::prelude::*;
use redb::{Database, ReadOnlyDatabase, ReadableDatabase, ReadableTable, TableDefinition};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::language::{LangError, detect_language, download_names_for, parse_and_extract, primary_extension};

pub const INDEX_VERSION: u32 = 8;

/// Compute the cache path for a given project root.
/// Returns `~/.cache/cx/indexes/<hash>.db` where hash is derived from the canonical path.
pub fn cache_path_for(root: &Path) -> PathBuf {
    let canonical = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let mut hasher = DefaultHasher::new();
    canonical.hash(&mut hasher);
    let hash = hasher.finish();
    let dir = index_cache_dir();
    dir.join(format!("{hash:016x}.db"))
}

fn index_cache_dir() -> PathBuf {
    crate::lang::cx_cache_dir().join("indexes")
}

const META_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("meta");
const FILES_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("files");
const SYMBOLS_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("symbols");

pub struct Index {
    pub root: PathBuf,
    db: Option<Database>,
    /// In-memory mirror for fast query access.
    pub entries: HashMap<PathBuf, FileData>,
}

enum CrawlResult {
    Indexed(PathBuf, FileData),
    MissingLang(String),
    ReadFailed(PathBuf, std::io::Error),
    ParseFailed,
}

#[derive(Debug, Clone)]
pub struct FileData {
    pub meta: FileEntry,
    pub symbols: Vec<Symbol>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEntry {
    pub mtime_secs: u64,
    pub mtime_nanos: u32,
    pub language: String,
}

impl FileEntry {
    fn new(mtime: SystemTime, language: &str) -> Self {
        let dur = mtime.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
        Self {
            mtime_secs: dur.as_secs(),
            mtime_nanos: dur.subsec_nanos(),
            language: language.to_string(),
        }
    }

    pub fn mtime(&self) -> SystemTime {
        UNIX_EPOCH + Duration::new(self.mtime_secs, self.mtime_nanos)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Symbol {
    pub name: String,
    pub kind: SymbolKind,
    pub signature: String,
    pub byte_range: (usize, usize),
    /// Whether this symbol is a test (e.g. `#[test]` in Rust, `test` block in Zig).
    #[serde(default)]
    pub is_test: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
#[clap(rename_all = "lowercase")]
pub enum SymbolKind {
    Fn,
    Struct,
    Enum,
    Trait,
    Type,
    Const,
    Class,
    Interface,
    Module,
    Event,
    Field,
    Heading,
}

impl SymbolKind {
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Fn => "fn",
            Self::Struct => "struct",
            Self::Enum => "enum",
            Self::Trait => "trait",
            Self::Type => "type",
            Self::Const => "const",
            Self::Class => "class",
            Self::Interface => "interface",
            Self::Module => "module",
            Self::Event => "event",
            Self::Field => "field",
            Self::Heading => "heading",
        }
    }
}

fn encode_file_entry(entry: &FileEntry) -> Vec<u8> {
    bincode::serialize(entry).expect("FileEntry serialization should not fail")
}

fn decode_file_entry(bytes: &[u8]) -> Option<FileEntry> {
    bincode::deserialize(bytes).ok()
}

/// Open the database exclusively, retrying on lock contention.
fn open_db_exclusive(path: &Path) -> Result<Database, redb::DatabaseError> {
    let mut attempts = 0;
    loop {
        match Database::create(path) {
            Ok(db) => return Ok(db),
            Err(redb::DatabaseError::DatabaseAlreadyOpen) if attempts < 20 => {
                attempts += 1;
                if attempts == 1 {
                    eprintln!("cx: database locked, waiting...");
                }
                std::thread::sleep(std::time::Duration::from_millis(100));
            }
            Err(e) => return Err(e),
        }
    }
}

/// Load entries from a readable database into memory.
fn load_entries(db: &impl ReadableDatabase) -> Option<HashMap<PathBuf, FileData>> {
    let read_txn = db.begin_read().ok()?;

    // Check version
    let version_ok = (|| -> Option<bool> {
        let table = read_txn.open_table(META_TABLE).ok()?;
        let val = table.get("version").ok()??;
        let bytes = val.value();
        if bytes.len() == 4 {
            Some(u32::from_le_bytes(bytes.try_into().unwrap()) == INDEX_VERSION)
        } else {
            None
        }
    })().unwrap_or(false);

    if !version_ok {
        return None;
    }

    let mut entries: HashMap<PathBuf, FileData> = HashMap::new();

    if let Ok(table) = read_txn.open_table(FILES_TABLE) {
        for item in table.iter().into_iter().flatten() {
            let Ok((key, val)) = item else { continue };
            let path = PathBuf::from(key.value());
            if let Some(meta) = decode_file_entry(val.value()) {
                entries.insert(path, FileData { meta, symbols: Vec::new() });
            }
        }
    }
    if let Ok(table) = read_txn.open_table(SYMBOLS_TABLE) {
        for item in table.iter().into_iter().flatten() {
            let Ok((key, val)) = item else { continue };
            let path = PathBuf::from(key.value());
            let syms: Vec<Symbol> = bincode::deserialize(val.value()).unwrap_or_default();
            if let Some(data) = entries.get_mut(&path) {
                data.symbols = syms;
            }
        }
    }

    Some(entries)
}

/// Check if any files on disk have changed compared to indexed entries.
fn needs_update(root: &Path, entries: &HashMap<PathBuf, FileData>) -> bool {
    // Collect languages that are known-installed (have at least one indexed file).
    let indexed_langs: std::collections::HashSet<&str> = entries
        .values()
        .map(|d| d.meta.language.as_str())
        .collect();
    let installed_grammars = tree_sitter_language_pack::downloaded_languages();

    let mut matched_count = 0usize;
    for entry in walk(root) {
        let path = entry.path();
        let Some(lang) = detect_language(path) else {
            continue;
        };
        let rel_path = match path.strip_prefix(root) {
            Ok(p) => p.to_path_buf(),
            Err(_) => continue,
        };
        match entries.get(&rel_path) {
            Some(data) => {
                let mtime = entry.metadata().ok()
                    .and_then(|m| m.modified().ok())
                    .unwrap_or(SystemTime::UNIX_EPOCH);
                if data.meta.mtime() != mtime {
                    return true; // mtime changed
                }
                matched_count += 1;
            }
            None => {
                // File not in index. If we've indexed other files of this
                // language, or all required grammars are installed, this is a
                // genuinely new indexable file.
                let grammar_installed = download_names_for(lang)
                    .iter()
                    .all(|name| installed_grammars.iter().any(|installed| installed == name));
                if indexed_langs.contains(lang) || grammar_installed {
                    return true;
                }
                // Otherwise grammar isn't installed — skip, don't trigger update.
            }
        }
    }
    // Check for deleted files
    matched_count != entries.len()
}

impl Index {
    /// Load or build the index for the given project root.
    ///
    /// Tries a shared (read-only) open first so multiple cx processes can
    /// run concurrently.  Falls back to an exclusive open only when the
    /// index needs to be created or updated.
    pub fn load_or_build(root: &Path) -> Self {
        let db_path = cache_path_for(root);
        if let Some(parent) = db_path.parent() {
            let _ = fs::create_dir_all(parent);
        }

        // Fast path: open read-only (shared lock) and check if index is fresh
        if db_path.exists() {
            match ReadOnlyDatabase::open(&db_path) {
                Ok(ro_db) => {
                    if let Some(entries) = load_entries(&ro_db)
                        && !needs_update(root, &entries) {
                        return Self { root: root.to_path_buf(), db: None, entries };
                    }
                }
                Err(redb::DatabaseError::UpgradeRequired(_)) => {
                    // Old redb format; delete so exclusive path recreates it
                    let _ = fs::remove_file(&db_path);
                }
                Err(_) => {}
            }
        }

        // Slow path: need exclusive access to create or update the index
        let db = match open_db_exclusive(&db_path) {
            Ok(db) => db,
            Err(redb::DatabaseError::UpgradeRequired(_)) => {
                // Old redb format (e.g. v2 → v3 upgrade); delete and recreate
                let _ = fs::remove_file(&db_path);
                match open_db_exclusive(&db_path) {
                    Ok(db) => db,
                    Err(e) => {
                        eprintln!("cx: failed to open database: {e}");
                        std::process::exit(1);
                    }
                }
            }
            Err(e) => {
                eprintln!("cx: failed to open database: {e}");
                std::process::exit(1);
            }
        };

        if let Some(entries) = load_entries(&db) {
            let mut idx = Self { root: root.to_path_buf(), db: Some(db), entries };
            idx.incremental_update();
            idx
        } else {
            let mut idx = Self {
                root: root.to_path_buf(),
                db: Some(db),
                entries: HashMap::new(),
            };
            idx.full_crawl();
            idx.save_all();
            idx
        }
    }

    /// Crawl from project root, collecting all supported files.
    fn full_crawl(&mut self) {
        let mut missing_langs: HashMap<String, usize> = HashMap::new();

        // Collect files first so we can show progress
        let files: Vec<_> = walk(&self.root)
            .filter_map(|entry| {
                let path = entry.path();
                let lang = detect_language(path)?;
                let rel_path = path.strip_prefix(&self.root).ok()?.to_path_buf();
                let mtime = entry.metadata().ok()
                    .and_then(|m| m.modified().ok())
                    .unwrap_or(SystemTime::UNIX_EPOCH);
                Some((path.to_path_buf(), rel_path, lang, mtime))
            })
            .collect();

        let total = files.len();
        if total > 0 {
            eprintln!("cx: indexing {total} files...");
        }

        let completed = AtomicUsize::new(0);
        let progress_step = if total >= 100 { Some(total / 10) } else { None };
        let results: Vec<_> = files
            .par_iter()
            .map(|(abs_path, rel_path, lang, mtime)| {
                let result = match fs::read(abs_path) {
                    Ok(source) => match parse_and_extract(lang, &source, abs_path) {
                        Ok(symbols) => CrawlResult::Indexed(
                            rel_path.clone(),
                            FileData {
                                meta: FileEntry::new(*mtime, lang),
                                symbols,
                            },
                        ),
                        Err(LangError::NotInstalled(name)) => CrawlResult::MissingLang(name),
                        Err(_) => CrawlResult::ParseFailed,
                    },
                    Err(e) => CrawlResult::ReadFailed(abs_path.clone(), e),
                };

                let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
                if let Some(step) = progress_step
                    && done.is_multiple_of(step)
                {
                    eprintln!("cx: indexed {done}/{total}...");
                }

                result
            })
            .collect();

        for result in results {
            match result {
                CrawlResult::Indexed(rel_path, data) => {
                    self.entries.insert(rel_path, data);
                }
                CrawlResult::MissingLang(name) => {
                    *missing_langs.entry(name).or_insert(0) += 1;
                }
                CrawlResult::ReadFailed(path, e) => {
                    eprintln!("cx: warning: failed to read {}: {}", path.display(), e);
                }
                CrawlResult::ParseFailed => {}
            }
        }

        // UX: warn about missing grammars
        if !missing_langs.is_empty() {
            if self.entries.is_empty() {
                // No files indexed at all
                eprintln!("cx: no language grammars installed\n");
                eprintln!("Detected languages in this project:");
                let mut langs: Vec<_> = missing_langs.iter().collect();
                langs.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
                for (lang, count) in &langs {
                    eprintln!("  {lang} ({count} files)");
                }
                let names: Vec<&str> = langs.iter().map(|(n, _)| n.as_str()).collect();
                eprintln!("\nInstall with: cx lang add {}", names.join(" "));
            } else {
                // Some files indexed, some missing
                for lang in missing_langs.keys() {
                    let ext = primary_extension(lang);
                    eprintln!("cx: skipping .{ext} files — install with: cx lang add {lang}");
                }
            }
        }
    }

    /// Check for changed/new/deleted files and update the index.
    fn incremental_update(&mut self) {
        let mut on_disk: HashMap<PathBuf, (SystemTime, &str)> = HashMap::new();
        let mut missing_langs: HashSet<String> = HashSet::new();

        for entry in walk(&self.root) {
            let path = entry.path();
            let Some(lang) = detect_language(path) else {
                continue;
            };

            let rel_path = match path.strip_prefix(&self.root) {
                Ok(p) => p.to_path_buf(),
                Err(_) => continue,
            };

            let mtime = entry
                .metadata()
                .ok()
                .and_then(|m| m.modified().ok())
                .unwrap_or(SystemTime::UNIX_EPOCH);

            on_disk.insert(rel_path, (mtime, lang));
        }

        // Remove deleted files
        let indexed_paths: Vec<PathBuf> = self.entries.keys().cloned().collect();
        let mut deleted = Vec::new();
        for path in indexed_paths {
            if !on_disk.contains_key(&path) {
                self.entries.remove(&path);
                deleted.push(path);
            }
        }

        // Add new or update changed files
        let stale: Vec<_> = on_disk.iter()
            .filter(|(path, (mtime, _))| {
                !matches!(self.entries.get(*path), Some(data) if data.meta.mtime() == *mtime)
            })
            .map(|(path, (mtime, lang))| (path.clone(), *mtime, *lang))
            .collect();

        let total = stale.len();
        if total > 0 {
            eprintln!("cx: updating {total} files...");
        }

        let mut changed_paths: Vec<PathBuf> = Vec::new();
        for (i, (path, mtime, lang)) in stale.iter().enumerate() {
            if total >= 100 && (i + 1) % (total / 10) == 0 {
                eprintln!("cx: indexed {}/{}...", i + 1, total);
            }
            let file_entry = FileEntry::new(*mtime, lang);
            let abs_path = self.root.join(path);
            let symbols = match fs::read(&abs_path) {
                Ok(source) => match parse_and_extract(lang, &source, &abs_path) {
                    Ok(syms) => syms,
                    Err(LangError::NotInstalled(name)) => {
                        missing_langs.insert(name);
                        continue;
                    }
                    Err(_) => continue,
                },
                Err(_) => continue,
            };
            self.entries.insert(path.clone(), FileData {
                meta: file_entry,
                symbols,
            });
            changed_paths.push(path.clone());
        }

        for lang in &missing_langs {
            let ext = primary_extension(lang);
            eprintln!("cx: skipping .{ext} files — install with: cx lang add {lang}");
        }

        if !deleted.is_empty() || !changed_paths.is_empty() {
            let Some(ref db) = self.db else { return };
            let write_txn = match db.begin_write() {
                Ok(txn) => txn,
                Err(e) => {
                    eprintln!("cx: failed to begin write for incremental update: {e}");
                    return;
                }
            };
            {
                let Ok(mut files_table) = write_txn.open_table(FILES_TABLE) else {
                    eprintln!("cx: failed to open files table — rebuild with: cx cache clean");
                    return;
                };
                let Ok(mut syms_table) = write_txn.open_table(SYMBOLS_TABLE) else {
                    eprintln!("cx: failed to open symbols table — rebuild with: cx cache clean");
                    return;
                };
                for path in &deleted {
                    let key = path.to_string_lossy();
                    let _ = files_table.remove(key.as_ref());
                    let _ = syms_table.remove(key.as_ref());
                }
                for path in &changed_paths {
                    if let Some(data) = self.entries.get(path) {
                        let key = path.to_string_lossy();
                        match bincode::serialize(&data.symbols) {
                            Ok(sym_bytes) => {
                                let entry_bytes = encode_file_entry(&data.meta);
                                let _ = files_table.insert(key.as_ref(), entry_bytes.as_slice());
                                let _ = syms_table.insert(key.as_ref(), sym_bytes.as_slice());
                            }
                            Err(e) => eprintln!("cx: failed to serialize symbols for {key}: {e}"),
                        }
                    }
                }
            }
            if let Err(e) = write_txn.commit() {
                eprintln!("cx: failed to commit incremental update: {e}");
            }
        }
    }

    /// Write the entire index to the database (used after `full_crawl`).
    /// Clears all existing data first to avoid stale entries.
    fn save_all(&self) {
        let Some(ref db) = self.db else { return };
        let write_txn = match db.begin_write() {
            Ok(txn) => txn,
            Err(e) => {
                eprintln!("cx: failed to begin write: {e}");
                return;
            }
        };

        // Delete and recreate tables to clear stale entries
        let _ = write_txn.delete_table(FILES_TABLE);
        let _ = write_txn.delete_table(SYMBOLS_TABLE);

        // Write version
        {
            let Ok(mut table) = write_txn.open_table(META_TABLE) else {
                eprintln!("cx: failed to open meta table — rebuild with: cx cache clean");
                return;
            };
            let _ = table.insert("version", INDEX_VERSION.to_le_bytes().as_slice());
        }

        // Write files and symbols
        {
            let Ok(mut files_table) = write_txn.open_table(FILES_TABLE) else {
                eprintln!("cx: failed to open files table — rebuild with: cx cache clean");
                return;
            };
            let Ok(mut syms_table) = write_txn.open_table(SYMBOLS_TABLE) else {
                eprintln!("cx: failed to open symbols table — rebuild with: cx cache clean");
                return;
            };
            for (path, data) in &self.entries {
                let key = path.to_string_lossy();
                let entry_bytes = encode_file_entry(&data.meta);
                let _ = files_table.insert(key.as_ref(), entry_bytes.as_slice());
                match bincode::serialize(&data.symbols) {
                    Ok(sym_bytes) => { let _ = syms_table.insert(key.as_ref(), sym_bytes.as_slice()); }
                    Err(e) => eprintln!("cx: failed to serialize symbols for {key}: {e}"),
                }
            }
        }

        if let Err(e) = write_txn.commit() {
            eprintln!("cx: failed to commit: {e}");
        }
    }

}

/// Walk the project tree, respecting .gitignore and skipping the index/db files.
fn walk(root: &Path) -> impl Iterator<Item = ignore::DirEntry> {
    WalkBuilder::new(root)
        .hidden(false)
        .git_ignore(true)
        .git_global(true)
        .git_exclude(true)
        .filter_entry(|e| {
            let name = e.file_name().to_str().unwrap_or("");
            if name == ".git" {
                return false;
            }
            if e.file_type().is_some_and(|ft| ft.is_dir()) && e.path().join(".cx-ignore").exists() {
                return false;
            }
            true
        })
        .build()
        .filter_map(std::result::Result::ok)
        .filter(|e| e.file_type().is_some_and(|ft| ft.is_file()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    use std::sync::Once;

    static INIT: Once = Once::new();

    fn init_grammar_cache() {
        INIT.call_once(|| {
            let config = tree_sitter_language_pack::PackConfig {
                cache_dir: Some(crate::lang::grammar_cache_dir()),
                ..Default::default()
            };
            tree_sitter_language_pack::configure(&config)
                .expect("failed to configure grammar cache");
        });
    }

    #[test]
    fn test_file_entry_encode_roundtrip() {
        let entry = FileEntry::new(
            UNIX_EPOCH + Duration::new(1234567890, 42),
            "rust",
        );
        let bytes = encode_file_entry(&entry);
        let decoded = decode_file_entry(&bytes).expect("should decode");
        assert_eq!(entry.mtime(), decoded.mtime());
        assert_eq!(entry.language, decoded.language);
    }

    #[test]
    fn test_file_entry_decode_garbage_returns_none() {
        assert!(decode_file_entry(&[0u8; 5]).is_none());
        assert!(decode_file_entry(&[]).is_none());
    }

    #[test]
    fn test_symbol_bincode_roundtrip() {
        let symbols = vec![
            Symbol {
                name: "foo".to_string(),
                kind: SymbolKind::Fn,
                signature: "pub fn foo(x: i32) -> bool".to_string(),
                byte_range: (100, 500),
                is_test: false,
            },
            Symbol {
                name: "Bar".to_string(),
                kind: SymbolKind::Struct,
                signature: "pub struct Bar".to_string(),
                byte_range: (600, 800),
                is_test: false,
            },
            Symbol {
                name: "test_bar".to_string(),
                kind: SymbolKind::Fn,
                signature: "fn test_bar()".to_string(),
                byte_range: (900, 1000),
                is_test: true,
            },
        ];
        let bytes = bincode::serialize(&symbols).unwrap();
        let decoded: Vec<Symbol> = bincode::deserialize(&bytes).unwrap();
        assert_eq!(decoded.len(), 3);
        assert_eq!(decoded[0].name, "foo");
        assert!(!decoded[0].is_test);
        assert_eq!(decoded[1].kind, SymbolKind::Struct);
        assert_eq!(decoded[0].byte_range, (100, 500));
        assert_eq!(decoded[2].name, "test_bar");
        assert!(decoded[2].is_test);
    }

    #[test]
    fn test_full_crawl_finds_rust_files() {
        init_grammar_cache();
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test-crawl.db");
        let db = Database::create(&db_path).unwrap();
        // Use the real project root for crawling, but store db in tempdir
        let cwd = env::current_dir().unwrap();
        let mut idx = Index {
            root: cwd,
            db: Some(db),
            entries: HashMap::new(),
        };
        idx.full_crawl();

        assert!(idx.entries.contains_key(&PathBuf::from("src/main.rs")));
        for path in idx.entries.keys() {
            assert!(!path.starts_with("target/"), "found target/ file: {path:?}");
        }
    }

    #[test]
    fn test_walk_respects_gitignore() {
        let cwd = env::current_dir().unwrap();
        let entries: Vec<_> = walk(&cwd).collect();
        for entry in &entries {
            let path = entry.path();
            let rel = path.strip_prefix(&cwd).unwrap_or(path);
            assert!(!rel.starts_with(".git/"), "found .git file: {rel:?}");
            assert!(!rel.starts_with("target/"), "found target file: {rel:?}");
        }
    }

    /// Helper: create a temp project with .git dir and source files, return (tempdir, Index).
    fn build_temp_index(files: &[(&str, &str)]) -> (tempfile::TempDir, Index) {
        init_grammar_cache();
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir(dir.path().join(".git")).unwrap();
        for (path, content) in files {
            let full = dir.path().join(path);
            if let Some(parent) = full.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::write(&full, content).unwrap();
        }
        let idx = Index::load_or_build(dir.path());
        (dir, idx)
    }

    #[test]
    fn test_load_or_build_fresh_db() {
        let (dir, idx) = build_temp_index(&[
            ("src/main.rs", "fn main() {}\n"),
            ("src/lib.rs", "pub fn hello() {}\n"),
        ]);

        assert!(idx.entries.contains_key(&PathBuf::from("src/main.rs")));
        assert!(idx.entries.contains_key(&PathBuf::from("src/lib.rs")));
        assert_eq!(idx.entries.get(&PathBuf::from("src/main.rs")).unwrap().symbols.len(), 1);
        assert_eq!(idx.entries.get(&PathBuf::from("src/lib.rs")).unwrap().symbols.len(), 1);

        // DB file should exist in cache dir
        assert!(cache_path_for(dir.path()).exists());
    }

    #[test]
    fn test_full_crawl_indexes_many_files() {
        let files: Vec<_> = (0..64)
            .map(|i| {
                (
                    format!("src/module_{i}.rs"),
                    format!("pub fn function_{i}() -> usize {{ {i} }}\n"),
                )
            })
            .collect();
        let borrowed_files: Vec<_> = files
            .iter()
            .map(|(path, content)| (path.as_str(), content.as_str()))
            .collect();

        let (_dir, idx) = build_temp_index(&borrowed_files);

        assert_eq!(idx.entries.len(), 64);
        for i in 0..64 {
            let path = PathBuf::from(format!("src/module_{i}.rs"));
            let symbols = &idx.entries.get(&path).unwrap().symbols;
            assert!(
                symbols.iter().any(|symbol| symbol.name == format!("function_{i}")),
                "missing function_{i} in {path:?}"
            );
        }
    }

    #[test]
    fn test_load_or_build_reloads_from_existing_db() {
        let (dir, idx) = build_temp_index(&[
            ("src/main.rs", "fn main() {}\nfn helper() {}\n"),
        ]);

        let file_count = idx.entries.len();
        let sym_count = idx.entries.get(&PathBuf::from("src/main.rs")).unwrap().symbols.len();
        assert!(sym_count >= 2, "should have at least 2 symbols: {sym_count}");

        // Drop and reload — should get same data from redb
        drop(idx);
        let idx2 = Index::load_or_build(dir.path());
        assert_eq!(idx2.entries.len(), file_count);
        assert_eq!(
            idx2.entries.get(&PathBuf::from("src/main.rs")).unwrap().symbols.len(),
            sym_count,
        );
    }

    #[test]
    fn test_save_all_clears_stale_entries() {
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir(dir.path().join(".git")).unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        fs::write(dir.path().join("src/a.rs"), "fn a() {}\n").unwrap();
        fs::write(dir.path().join("src/b.rs"), "fn b() {}\n").unwrap();

        // Build index with both files
        let idx = Index::load_or_build(dir.path());
        assert!(idx.entries.contains_key(&PathBuf::from("src/a.rs")));
        assert!(idx.entries.contains_key(&PathBuf::from("src/b.rs")));
        drop(idx);

        // Remove b.rs, rebuild
        fs::remove_file(dir.path().join("src/b.rs")).unwrap();
        let idx2 = Index::load_or_build(dir.path());
        assert!(idx2.entries.contains_key(&PathBuf::from("src/a.rs")));
        assert!(!idx2.entries.contains_key(&PathBuf::from("src/b.rs")));

        // Reload again — b.rs should still be gone from redb
        drop(idx2);
        let idx3 = Index::load_or_build(dir.path());
        assert!(!idx3.entries.contains_key(&PathBuf::from("src/b.rs")));
    }

    #[test]
    fn test_incremental_update_detects_new_file() {
        init_grammar_cache();
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir(dir.path().join(".git")).unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        fs::write(dir.path().join("src/a.rs"), "fn a() {}\n").unwrap();

        let idx = Index::load_or_build(dir.path());
        assert_eq!(idx.entries.len(), 1);
        drop(idx);

        // Set mtime in the future so the incremental update detects the new file
        // even on filesystems with coarse (1-second) timestamp granularity.
        let b_path = dir.path().join("src/b.rs");
        fs::write(&b_path, "fn b() {}\n").unwrap();
        let future = SystemTime::now() + Duration::from_secs(2);
        fs::File::options().write(true).open(&b_path).unwrap()
            .set_times(fs::FileTimes::new().set_modified(future)).unwrap();

        let idx2 = Index::load_or_build(dir.path());
        assert_eq!(idx2.entries.len(), 2);
        assert!(idx2.entries.contains_key(&PathBuf::from("src/b.rs")));
        assert_eq!(idx2.entries.get(&PathBuf::from("src/b.rs")).unwrap().symbols.len(), 1);
    }

    #[test]
    fn test_incremental_update_detects_modified_file() {
        init_grammar_cache();
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir(dir.path().join(".git")).unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        fs::write(dir.path().join("src/a.rs"), "fn a() {}\n").unwrap();

        let idx = Index::load_or_build(dir.path());
        assert_eq!(idx.entries.get(&PathBuf::from("src/a.rs")).unwrap().symbols.len(), 1);
        drop(idx);

        // Modify the file — add a second function.
        // Set mtime in the future to avoid coarse-granularity timestamp ties.
        let a_path = dir.path().join("src/a.rs");
        fs::write(&a_path, "fn a() {}\nfn b() {}\n").unwrap();
        let future = SystemTime::now() + Duration::from_secs(2);
        fs::File::options().write(true).open(&a_path).unwrap()
            .set_times(fs::FileTimes::new().set_modified(future)).unwrap();

        let idx2 = Index::load_or_build(dir.path());
        assert_eq!(
            idx2.entries.get(&PathBuf::from("src/a.rs")).unwrap().symbols.len(),
            2,
            "should detect modified file and re-parse symbols"
        );
    }

    #[test]
    fn test_incremental_update_detects_deleted_file() {
        init_grammar_cache();
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir(dir.path().join(".git")).unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        fs::write(dir.path().join("src/a.rs"), "fn a() {}\n").unwrap();
        fs::write(dir.path().join("src/b.rs"), "fn b() {}\n").unwrap();

        let idx = Index::load_or_build(dir.path());
        assert_eq!(idx.entries.len(), 2);
        drop(idx);

        // Delete one file
        fs::remove_file(dir.path().join("src/b.rs")).unwrap();

        let idx2 = Index::load_or_build(dir.path());
        assert_eq!(idx2.entries.len(), 1);
        assert!(idx2.entries.contains_key(&PathBuf::from("src/a.rs")));
        assert!(!idx2.entries.contains_key(&PathBuf::from("src/b.rs")));
    }

    #[test]
    fn test_version_mismatch_triggers_rebuild() {
        init_grammar_cache();
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir(dir.path().join(".git")).unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        fs::write(dir.path().join("src/a.rs"), "fn a() {}\n").unwrap();

        // Build normally
        let idx = Index::load_or_build(dir.path());
        assert!(idx.entries.contains_key(&PathBuf::from("src/a.rs")));
        drop(idx);

        // Corrupt the version in the db
        let db = Database::create(cache_path_for(dir.path())).unwrap();
        {
            let write_txn = db.begin_write().unwrap();
            {
                let mut table = write_txn.open_table(META_TABLE).unwrap();
                let _ = table.insert("version", 999u32.to_le_bytes().as_slice());
            }
            write_txn.commit().unwrap();
        }
        drop(db);

        // Reload — should detect version mismatch and rebuild
        let idx2 = Index::load_or_build(dir.path());
        assert!(idx2.entries.contains_key(&PathBuf::from("src/a.rs")));
    }

    #[test]
    fn test_symbols_persisted_to_redb() {
        let (dir, idx) = build_temp_index(&[
            ("src/main.rs", "pub fn foo(x: i32) -> bool { true }\nstruct Bar;\n"),
        ]);

        let syms = &idx.entries.get(&PathBuf::from("src/main.rs")).unwrap().symbols;
        assert!(syms.iter().any(|s| s.name == "foo" && s.kind == SymbolKind::Fn));
        assert!(syms.iter().any(|s| s.name == "Bar" && s.kind == SymbolKind::Struct));
        drop(idx);

        // Reload and verify symbols survive the roundtrip through redb + bincode
        let idx2 = Index::load_or_build(dir.path());
        let syms2 = &idx2.entries.get(&PathBuf::from("src/main.rs")).unwrap().symbols;
        assert!(syms2.iter().any(|s| s.name == "foo" && s.kind == SymbolKind::Fn));
        assert!(syms2.iter().any(|s| s.name == "Bar" && s.kind == SymbolKind::Struct));
    }
}