mati 0.1.2

An enforcement layer for codebase knowledge: confirmed gotchas gate what AI agents read and edit at the hook level. Not a passive memory store.
Documentation
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
//! Parallel file walker for Layer 0 static analysis.
//!
//! Uses `ignore::WalkParallel` (same engine as ripgrep) for parallel,
//! gitignore-aware directory traversal. Results stream to the caller via an
//! `mpsc` channel so downstream parsing can start before the walk completes.
//!
//! # Architecture
//!
//! ```text
//! Walker::walk_channel()
//!//!     ├── spawns std::thread (WalkParallel::visit is blocking/sync)
//!     │       │
//!     │       ├── VisitorBuilder::build() — one FileVisitor per worker thread
//!     │       │
//!     │       └── FileVisitor::visit() — per-entry filtering + local buffering
//!     │               │
//!     │               └── flush every FLUSH_THRESHOLD entries → mpsc::Sender
//!     │                   Drop flush handles tail entries
//!//!     └── returns mpsc::Receiver<WalkedFile>  (parser consumes while walk runs)
//!
//! Walker::walk() — thin wrapper: collect channel → sort → Vec<WalkedFile>
//! ```
//!
//! ## Why thread-local buffering?
//!
//! `mpsc::Sender::send()` acquires an internal lock on every call. With 8
//! threads and 80k files, 80k individual sends ≈ 16ms of contention overhead.
//! Flushing every `FLUSH_THRESHOLD` entries reduces sends to ~2 500,
//! cutting that overhead to ~500µs while still giving the receiver batches
//! early enough for meaningful parse pipelining.

use std::path::{Path, PathBuf};
use std::sync::{mpsc, Arc, Mutex};

use anyhow::Result;
use ignore::{DirEntry, ParallelVisitor, ParallelVisitorBuilder, WalkBuilder, WalkState};

// ── Constants ─────────────────────────────────────────────────────────────────

/// Default maximum file size accepted by the walker (bytes).
/// Files larger than this are silently skipped — they are almost always
/// generated artefacts (minified JS, compiled output) not worth parsing.
pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024; // 1 MiB

/// Number of [`WalkedFile`] entries a [`FileVisitor`] accumulates locally
/// before flushing to the shared channel. Balances streaming latency against
/// `mpsc` lock contention on large repos.
const FLUSH_THRESHOLD: usize = 32;

// ── Public types ──────────────────────────────────────────────────────────────

/// Programming language detected from file extension.
///
/// All variants with a corresponding tree-sitter grammar are explicitly named.
/// Everything else — config files, markdown, shell scripts, etc. — maps to
/// [`Language::Unknown`] and is still walked but not parsed by tree-sitter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Language {
    Rust,
    TypeScript,
    JavaScript,
    Python,
    Go,
    Java,
    C,
    Cpp,
    Ruby,
    Scala,
    Elixir,
    Haskell,
    Unknown,
}

/// A single file discovered by the walker.
#[derive(Debug, Clone)]
pub struct WalkedFile {
    /// Absolute path — used for opening the file for parsing.
    pub abs_path: PathBuf,
    /// Repo-relative path with forward slashes — used as the mati store key
    /// suffix: `file:<rel_path>`.
    pub rel_path: String,
    pub language: Language,
    pub size_bytes: u64,
    /// File modification time as seconds since Unix epoch (0 if unavailable).
    /// Used as a cheap pre-filter in incremental init: if mtime matches the
    /// stored value, skip disk read + parse entirely.
    pub mtime_secs: u64,
}

// ── Walker ────────────────────────────────────────────────────────────────────

/// Parallel, gitignore-aware file walker.
///
/// # Example
/// ```no_run
/// use mati_core::analysis::Walker;
///
/// let walker = Walker::new("/path/to/repo");
///
/// // Streaming — parser can consume while walk is still in progress.
/// for file in walker.walk_channel().unwrap() {
///     println!("{} ({:?})", file.rel_path, file.language);
/// }
///
/// // Batch — sorted Vec, useful when you need the full set before proceeding.
/// let files = walker.walk().unwrap();
/// ```
pub struct Walker {
    root: PathBuf,
    max_file_size: u64,
    follow_symlinks: bool,
}

impl Walker {
    /// Create a walker rooted at `root` with default settings.
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            max_file_size: DEFAULT_MAX_FILE_SIZE,
            follow_symlinks: false,
        }
    }

    /// Override the maximum file size. Files larger than `bytes` are skipped.
    pub fn max_file_size(mut self, bytes: u64) -> Self {
        self.max_file_size = bytes;
        self
    }

    /// Whether to follow symbolic links. Default: `false` (avoids cycles).
    pub fn follow_symlinks(mut self, yes: bool) -> Self {
        self.follow_symlinks = yes;
        self
    }

    /// Primary interface: start the walk and return a channel receiver.
    ///
    /// The walk runs on a background thread; the caller can begin consuming
    /// [`WalkedFile`] items immediately while traversal is still in progress.
    /// The channel closes automatically when the walk finishes.
    ///
    /// Returns `Err` if `root` is not an accessible directory.
    pub fn walk_channel(&self) -> Result<mpsc::Receiver<WalkedFile>> {
        if !self.root.is_dir() {
            anyhow::bail!("walk root is not a directory: {}", self.root.display());
        }

        let (tx, rx) = mpsc::channel::<WalkedFile>();

        // One clone, used for both WalkBuilder::new and as the root reference
        // passed to every FileVisitor via VisitorBuilder.
        let root_arc = Arc::new(self.root.clone());
        let max_file_size = self.max_file_size;
        let follow_symlinks = self.follow_symlinks;

        // Spawn a dedicated thread: WalkParallel::visit is blocking and spawns
        // its own worker threads internally. We must not block the async
        // runtime (tokio) — always call walk_channel from a spawn_blocking
        // context when used from async code.
        std::thread::spawn(move || {
            let walk = WalkBuilder::new(root_arc.as_path())
                // Include hidden files — .gitignore is the authority on what
                // to skip; hiding .github/, .claude/ etc. would lose coverage.
                .hidden(false)
                .follow_links(follow_symlinks)
                // All git-related ignore rules enabled (default, stated for clarity).
                .git_ignore(true)
                .git_global(true)
                .git_exclude(true)
                .build_parallel();

            let mut builder = VisitorBuilder {
                // Arc<Mutex<Sender>> satisfies the Send + Sync bound required
                // by ParallelVisitorBuilder. Each FileVisitor clones the
                // Sender out of the Mutex exactly once in build().
                tx: Arc::new(Mutex::new(tx)),
                root: root_arc,
                max_file_size,
            };

            walk.visit(&mut builder);
            // builder drops here → Arc<Mutex<Sender>> drops → all Sender
            // clones held by FileVisitors have already been dropped when their
            // threads finished → channel closes → receiver exhausts cleanly.
        });

        Ok(rx)
    }

    /// Batch interface: collect the full walk into a sorted `Vec`.
    ///
    /// Useful for callers that need the complete file list before proceeding
    /// (tests, dep parsing, one-shot reporting). Prefer [`walk_channel`] when
    /// results will be piped into a parallel processing stage.
    ///
    /// [`walk_channel`]: Walker::walk_channel
    pub fn walk(&self) -> Result<Vec<WalkedFile>> {
        let mut files: Vec<WalkedFile> = self.walk_channel()?.into_iter().collect();
        // Deterministic order: sort by repo-relative path so downstream
        // consumers (store writes, tests) produce repeatable output.
        files.sort_unstable_by(|a, b| a.rel_path.cmp(&b.rel_path));
        Ok(files)
    }
}

// ── Internal visitor types ────────────────────────────────────────────────────

/// Builds a [`FileVisitor`] for each worker thread spawned by `WalkParallel`.
///
/// Must implement `Send + Sync`:
/// - `Arc<Mutex<mpsc::Sender<_>>>`: Send (Arc<T>: Send when T: Send+Sync) +
///   Sync (Mutex<T>: Sync when T: Send, mpsc::Sender<T>: Send) ✓
/// - `Arc<PathBuf>`: Send + Sync ✓
/// - `u64`: Send + Sync ✓
struct VisitorBuilder {
    tx: Arc<Mutex<mpsc::Sender<WalkedFile>>>,
    root: Arc<PathBuf>,
    max_file_size: u64,
}

impl<'s> ParallelVisitorBuilder<'s> for VisitorBuilder {
    fn build(&mut self) -> Box<dyn ParallelVisitor + 's> {
        // Clone the Sender once per thread. The Mutex is held only for the
        // duration of clone() — essentially free.
        let tx = self
            .tx
            .lock()
            .expect("VisitorBuilder mutex poisoned")
            .clone();
        Box::new(FileVisitor {
            local: Vec::with_capacity(FLUSH_THRESHOLD),
            tx,
            root: Arc::clone(&self.root),
            max_file_size: self.max_file_size,
        })
    }
}

/// Per-thread visitor. Accumulates entries locally and flushes in batches to
/// reduce `mpsc` lock contention on high-file-count repos.
struct FileVisitor {
    /// Thread-local accumulator — flushed every FLUSH_THRESHOLD entries and
    /// on Drop (tail flush for the final partial batch).
    local: Vec<WalkedFile>,
    tx: mpsc::Sender<WalkedFile>,
    root: Arc<PathBuf>,
    max_file_size: u64,
}

impl FileVisitor {
    /// Send all buffered entries to the channel.
    ///
    /// Returns `false` if the receiver was dropped — the caller should return
    /// [`WalkState::Quit`] to stop the walk early.
    fn flush(&mut self) -> bool {
        // mem::take swaps self.local with an empty Vec, giving us owned
        // iteration without holding a borrow on self.local. Any remaining
        // items are dropped when `batch` goes out of scope.
        for file in std::mem::take(&mut self.local) {
            if self.tx.send(file).is_err() {
                return false;
            }
        }
        true
    }
}

impl Drop for FileVisitor {
    fn drop(&mut self) {
        // Tail flush: send any entries accumulated since the last threshold flush.
        self.flush();
    }
}

impl ParallelVisitor for FileVisitor {
    fn visit(&mut self, entry: Result<DirEntry, ignore::Error>) -> WalkState {
        let entry = match entry {
            Ok(e) => e,
            Err(e) => {
                tracing::warn!("walker: entry error: {e}");
                return WalkState::Continue;
            }
        };

        // DirEntry::file_type() is free on Linux (returned by readdir).
        // On macOS it may require a stat; ignore handles the caching.
        let file_type = match entry.file_type() {
            Some(ft) => ft,
            None => return WalkState::Continue, // stdin / unknown — skip
        };

        // Only process regular files. This explicitly skips:
        //   • directories (walk nodes — the ignore crate descends them)
        //   • symlinks — even with follow_links(false), ignore still yields
        //     symlink entries; opening a symlink path follows it implicitly,
        //     which violates the follow_symlinks=false contract
        //   • device files, pipes, sockets
        if !file_type.is_file() {
            return WalkState::Continue;
        }

        let path = entry.path();

        // Skip .git/ internals. .hidden(false) is needed to include .github/,
        // .claude/, etc., but the .git directory itself contains no project
        // knowledge — only git object/ref data. Check via path components so
        // we don't accidentally skip a legitimate ".git"-named user directory.
        if path.components().any(|c| c.as_os_str() == ".git") {
            return WalkState::Continue;
        }

        // Extension-based binary filter: checked before metadata() to avoid
        // unnecessary syscalls on clearly unanalysable files.
        if is_binary_extension(path) {
            return WalkState::Continue;
        }

        // DirEntry::metadata() reuses cached data where available (inode
        // info from readdir on Linux). Unavoidable for size filtering.
        let meta = match entry.metadata() {
            Ok(m) => m,
            Err(e) => {
                tracing::warn!("walker: cannot read metadata for {}: {e}", path.display());
                return WalkState::Continue;
            }
        };
        let size_bytes = meta.len();
        let mtime_secs = meta
            .modified()
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs())
            .unwrap_or(0);

        if size_bytes > self.max_file_size {
            tracing::debug!(
                "walker: skipping large file {} ({size_bytes} bytes)",
                path.display()
            );
            return WalkState::Continue;
        }

        self.local.push(WalkedFile {
            abs_path: path.to_path_buf(),
            rel_path: make_rel_path(&self.root, path),
            language: detect_language(path),
            size_bytes,
            mtime_secs,
        });

        if self.local.len() >= FLUSH_THRESHOLD && !self.flush() {
            return WalkState::Quit;
        }

        WalkState::Continue
    }
}

// ── Helper functions ──────────────────────────────────────────────────────────

/// Compute a forward-slash repo-relative path for use as the mati store key.
fn make_rel_path(root: &Path, abs: &Path) -> String {
    match abs.strip_prefix(root) {
        Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
        Err(_) => {
            // Should never happen — all entries come from walking root.
            tracing::debug!(
                "walker: {} is not under root {}; using absolute path",
                abs.display(),
                root.display()
            );
            abs.to_string_lossy().replace('\\', "/")
        }
    }
}

/// Detect programming language from file extension.
///
/// Only languages with a tree-sitter grammar in this project are explicitly
/// matched. Config files, markdown, shell scripts, etc. return
/// [`Language::Unknown`] — they are still walked and stored but not parsed.
pub fn detect_language(path: &Path) -> Language {
    match path.extension().and_then(|e| e.to_str()) {
        Some("rs") => Language::Rust,
        Some("ts" | "tsx") => Language::TypeScript,
        Some("js" | "jsx" | "mjs" | "cjs") => Language::JavaScript,
        Some("py" | "pyi") => Language::Python,
        Some("go") => Language::Go,
        Some("java") => Language::Java,
        Some("c") => Language::C,
        // .h is ambiguous (C vs C++ vs ObjC). Defaults to C — C++ headers
        // typically use .hpp/.hxx/.hh. This is a known, accepted heuristic.
        Some("h") => Language::C,
        Some("cpp" | "cc" | "cxx" | "hpp" | "hxx" | "hh") => Language::Cpp,
        Some("rb") => Language::Ruby,
        Some("scala" | "sc") => Language::Scala,
        Some("ex" | "exs") => Language::Elixir,
        Some("hs" | "lhs") => Language::Haskell,
        _ => Language::Unknown,
    }
}

/// Return `true` for extensions that indicate binary or generated files that
/// are never useful for tree-sitter analysis or mati knowledge records.
///
/// `.svg` is intentionally excluded from this list — it is XML text and may
/// appear in documentation or assets that are relevant to know about.
/// `.json` is also excluded — `package.json`, `tsconfig.json` etc. are
/// valuable for dependency analysis (M-06-E).
fn is_binary_extension(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|e| e.to_str()),
        Some(
            // Raster images
            "png" | "jpg" | "jpeg" | "gif" | "ico" | "webp" | "bmp" | "tiff"
            // Compiled / native artefacts
            | "o" | "a" | "so" | "dylib" | "dll" | "exe" | "wasm"
            | "class" | "jar"
            // Archives
            | "zip" | "tar" | "gz" | "bz2" | "xz" | "7z"
            // Media
            | "mp3" | "mp4" | "wav" | "avi" | "mkv" | "mov"
            // Fonts
            | "ttf" | "woff" | "woff2" | "otf" | "eot"
            // Generated lock / snapshot files — large, not useful for analysis
            | "lock" | "snap"
            // Databases
            | "db" | "sqlite" | "sqlite3"
            // Documents
            | "pdf"
        )
    )
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // ── Helpers ───────────────────────────────────────────────────────────────

    /// Write `content` to `dir/path`, creating intermediate directories.
    fn write(dir: &Path, rel: &str, content: &str) {
        let full = dir.join(rel);
        if let Some(parent) = full.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(full, content).unwrap();
    }

    /// Collect rel_paths from a walk result, sorted.
    fn rel_paths(files: &[WalkedFile]) -> Vec<&str> {
        let mut paths: Vec<&str> = files.iter().map(|f| f.rel_path.as_str()).collect();
        paths.sort_unstable();
        paths
    }

    // ── Walker behaviour ──────────────────────────────────────────────────────

    #[test]
    fn walk_returns_all_source_files() {
        let dir = TempDir::new().unwrap();
        write(dir.path(), "src/main.rs", "fn main() {}");
        write(dir.path(), "src/lib.py", "def foo(): pass");
        write(dir.path(), "app/index.ts", "export {}");

        let files = Walker::new(dir.path()).walk().unwrap();
        let paths = rel_paths(&files);

        assert!(paths.contains(&"app/index.ts"));
        assert!(paths.contains(&"src/lib.py"));
        assert!(paths.contains(&"src/main.rs"));
        assert_eq!(files.len(), 3);
    }

    #[test]
    fn walk_output_is_sorted_by_rel_path() {
        let dir = TempDir::new().unwrap();
        write(dir.path(), "z.rs", "");
        write(dir.path(), "a.rs", "");
        write(dir.path(), "m.rs", "");

        let files = Walker::new(dir.path()).walk().unwrap();
        let paths: Vec<&str> = files.iter().map(|f| f.rel_path.as_str()).collect();

        assert_eq!(paths, vec!["a.rs", "m.rs", "z.rs"]);
    }

    #[test]
    fn walk_empty_dir_returns_empty_vec() {
        let dir = TempDir::new().unwrap();
        let files = Walker::new(dir.path()).walk().unwrap();
        assert!(files.is_empty());
    }

    #[test]
    fn walk_nested_dirs_have_correct_rel_path() {
        let dir = TempDir::new().unwrap();
        write(dir.path(), "a/b/c/deep.rs", "");

        let files = Walker::new(dir.path()).walk().unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].rel_path, "a/b/c/deep.rs");
    }

    #[test]
    fn walk_rel_path_does_not_start_with_slash() {
        let dir = TempDir::new().unwrap();
        write(dir.path(), "src/foo.rs", "");

        let files = Walker::new(dir.path()).walk().unwrap();
        assert_eq!(files.len(), 1);
        assert!(!files[0].rel_path.starts_with('/'));
    }

    #[test]
    fn walk_respects_gitignore() {
        let dir = TempDir::new().unwrap();
        // ignore crate only reads .gitignore when it detects a git root.
        // A .git directory (even empty) is sufficient for detection.
        fs::create_dir(dir.path().join(".git")).unwrap();
        write(dir.path(), ".gitignore", "ignored.rs\ntarget/\n");
        write(dir.path(), "kept.rs", "");
        write(dir.path(), "ignored.rs", "");
        write(dir.path(), "target/debug/binary", "");

        let files = Walker::new(dir.path()).walk().unwrap();
        let paths = rel_paths(&files);

        // .gitignore itself is included (it's a text file)
        assert!(paths.contains(&"kept.rs"));
        assert!(
            !paths.contains(&"ignored.rs"),
            "ignored.rs should be excluded by .gitignore"
        );
        assert!(
            paths.iter().all(|p| !p.starts_with("target/")),
            "target/ should be excluded by .gitignore"
        );
    }

    #[test]
    fn walk_excludes_files_over_size_limit() {
        let dir = TempDir::new().unwrap();
        let big = dir.path().join("big.rs");
        // Write exactly max_file_size + 1 bytes
        fs::write(&big, vec![b'x'; 513]).unwrap();
        write(dir.path(), "small.rs", "fn main() {}");

        let files = Walker::new(dir.path()).max_file_size(512).walk().unwrap();

        let paths = rel_paths(&files);
        assert!(paths.contains(&"small.rs"));
        assert!(
            !paths.contains(&"big.rs"),
            "big.rs should be excluded by size limit"
        );
    }

    #[test]
    fn walk_includes_file_exactly_at_size_limit() {
        let dir = TempDir::new().unwrap();
        let exact = dir.path().join("exact.rs");
        fs::write(&exact, vec![b'x'; 512]).unwrap();

        let files = Walker::new(dir.path()).max_file_size(512).walk().unwrap();

        assert_eq!(
            files.len(),
            1,
            "file at exact size limit should be included"
        );
    }

    #[test]
    fn walk_excludes_binary_extensions() {
        let dir = TempDir::new().unwrap();
        write(dir.path(), "image.png", "not really a png");
        write(dir.path(), "archive.zip", "not really a zip");
        write(dir.path(), "lib.so", "");
        write(dir.path(), "Cargo.lock", "generated");
        write(dir.path(), "source.rs", "fn main() {}");

        let files = Walker::new(dir.path()).walk().unwrap();
        let paths = rel_paths(&files);

        assert!(paths.contains(&"source.rs"));
        assert!(!paths.contains(&"image.png"));
        assert!(!paths.contains(&"archive.zip"));
        assert!(!paths.contains(&"lib.so"));
        assert!(!paths.contains(&"Cargo.lock"));
    }

    #[test]
    fn walk_does_not_yield_directories() {
        let dir = TempDir::new().unwrap();
        fs::create_dir(dir.path().join("subdir")).unwrap();
        write(dir.path(), "subdir/file.rs", "");

        let files = Walker::new(dir.path()).walk().unwrap();

        for f in &files {
            assert!(
                f.abs_path.is_file(),
                "walker yielded a directory: {}",
                f.rel_path
            );
        }
    }

    #[test]
    fn walk_channel_and_walk_return_same_files() {
        let dir = TempDir::new().unwrap();
        write(dir.path(), "a.rs", "");
        write(dir.path(), "b.py", "");
        write(dir.path(), "c.ts", "");

        let walker = Walker::new(dir.path());

        // Collect channel output (unordered)
        let mut channel_paths: Vec<String> = walker
            .walk_channel()
            .unwrap()
            .into_iter()
            .map(|f| f.rel_path)
            .collect();
        channel_paths.sort_unstable();

        // Batch walk (sorted)
        let batch_paths: Vec<String> = walker
            .walk()
            .unwrap()
            .into_iter()
            .map(|f| f.rel_path)
            .collect();

        assert_eq!(channel_paths, batch_paths);
    }

    #[test]
    fn walk_errors_on_nonexistent_root() {
        let result = Walker::new("/nonexistent/path/that/does/not/exist").walk();
        assert!(result.is_err());
    }

    #[test]
    fn walk_size_bytes_is_accurate() {
        let dir = TempDir::new().unwrap();
        let content = "fn main() { println!(\"hello\"); }";
        write(dir.path(), "main.rs", content);

        let files = Walker::new(dir.path()).walk().unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].size_bytes, content.len() as u64);
    }

    // ── detect_language ───────────────────────────────────────────────────────

    #[test]
    fn detect_language_rust() {
        assert_eq!(detect_language(Path::new("foo.rs")), Language::Rust);
    }

    #[test]
    fn detect_language_typescript() {
        assert_eq!(detect_language(Path::new("app.ts")), Language::TypeScript);
        assert_eq!(detect_language(Path::new("comp.tsx")), Language::TypeScript);
    }

    #[test]
    fn detect_language_javascript() {
        assert_eq!(detect_language(Path::new("index.js")), Language::JavaScript);
        assert_eq!(detect_language(Path::new("mod.mjs")), Language::JavaScript);
        assert_eq!(detect_language(Path::new("cjs.cjs")), Language::JavaScript);
    }

    #[test]
    fn detect_language_python() {
        assert_eq!(detect_language(Path::new("main.py")), Language::Python);
        assert_eq!(detect_language(Path::new("types.pyi")), Language::Python);
    }

    #[test]
    fn detect_language_go() {
        assert_eq!(detect_language(Path::new("main.go")), Language::Go);
    }

    #[test]
    fn detect_language_java() {
        assert_eq!(detect_language(Path::new("Main.java")), Language::Java);
    }

    #[test]
    fn detect_language_c() {
        assert_eq!(detect_language(Path::new("main.c")), Language::C);
        assert_eq!(detect_language(Path::new("header.h")), Language::C);
    }

    #[test]
    fn detect_language_cpp() {
        assert_eq!(detect_language(Path::new("main.cpp")), Language::Cpp);
        assert_eq!(detect_language(Path::new("util.cc")), Language::Cpp);
        assert_eq!(detect_language(Path::new("lib.cxx")), Language::Cpp);
        assert_eq!(detect_language(Path::new("header.hpp")), Language::Cpp);
        assert_eq!(detect_language(Path::new("tmpl.hxx")), Language::Cpp);
        assert_eq!(detect_language(Path::new("types.hh")), Language::Cpp);
    }

    #[test]
    fn detect_language_ruby() {
        assert_eq!(detect_language(Path::new("app.rb")), Language::Ruby);
    }

    #[test]
    fn detect_language_scala() {
        assert_eq!(detect_language(Path::new("Main.scala")), Language::Scala);
        assert_eq!(detect_language(Path::new("script.sc")), Language::Scala);
    }

    #[test]
    fn detect_language_elixir() {
        assert_eq!(detect_language(Path::new("app.ex")), Language::Elixir);
        assert_eq!(detect_language(Path::new("test.exs")), Language::Elixir);
    }

    #[test]
    fn detect_language_haskell() {
        assert_eq!(detect_language(Path::new("Main.hs")), Language::Haskell);
        assert_eq!(
            detect_language(Path::new("Literate.lhs")),
            Language::Haskell
        );
    }

    #[test]
    fn detect_language_unknown_for_config_and_text() {
        assert_eq!(detect_language(Path::new("Cargo.toml")), Language::Unknown);
        assert_eq!(detect_language(Path::new("README.md")), Language::Unknown);
        assert_eq!(detect_language(Path::new("script.sh")), Language::Unknown);
        assert_eq!(detect_language(Path::new(".env")), Language::Unknown);
        assert_eq!(
            detect_language(Path::new("no_extension")),
            Language::Unknown
        );
    }

    // ── is_binary_extension ───────────────────────────────────────────────────

    #[test]
    fn binary_extensions_are_excluded() {
        let binaries = [
            "image.png",
            "photo.jpg",
            "archive.zip",
            "lib.so",
            "binary.exe",
            "module.wasm",
            "Cargo.lock",
            "yarn.lock",
            "snapshot.snap",
            "data.db",
            "doc.pdf",
        ];
        for name in binaries {
            assert!(
                is_binary_extension(Path::new(name)),
                "{name} should be detected as binary"
            );
        }
    }

    #[test]
    fn source_extensions_are_not_binary() {
        let sources = [
            "main.rs",
            "app.py",
            "index.ts",
            "main.go",
            "package.json",
            "Cargo.toml",
            "README.md",
            "style.css",
            "image.svg",
        ];
        for name in sources {
            assert!(
                !is_binary_extension(Path::new(name)),
                "{name} should not be detected as binary"
            );
        }
    }
}