sephera_scan 0.7.1

Fast line-of-code counting with language-aware comment detection.
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
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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{Context, Result, bail};
use rayon::prelude::*;

use sephera_core::language_data::{LanguageMatch, language_for_path};
use sephera_ignore::{
    Decision, IGNORE_FILE_NAMES, IgnoreMatcher, IgnoreRules,
    normalize_relative_path, read_directory_rules,
};

#[derive(Debug, Clone)]
pub struct ProjectFile {
    pub absolute_path: PathBuf,
    pub relative_path: PathBuf,
    pub normalized_relative_path: String,
    pub size_bytes: u64,
    pub language_match: Option<LanguageMatch>,
}

/// # Errors
///
/// Returns an error when the target path is invalid, traversal fails, or file
/// metadata cannot be read.
pub fn collect_project_files(
    base_path: &Path,
    ignore: &IgnoreMatcher,
) -> Result<Vec<ProjectFile>> {
    collect_project_files_inner(base_path, ignore, true)
}

/// Collect project files, optionally skipping nested checkout directories.
///
/// # Errors
///
/// Returns an error when the target path is invalid, traversal fails, or file
/// metadata cannot be read.
///
/// # Parameters
///
/// * `skip_nested_checkouts` — when true, directories that hold parallel
///   checkouts of the same repository (agent worktrees, `.git`) are pruned.
///   Callers that build a context pack set this to false, because a pack may
///   legitimately be focused inside such a tree.
pub fn collect_project_files_with(
    base_path: &Path,
    ignore: &IgnoreMatcher,
    skip_nested_checkouts: bool,
) -> Result<Vec<ProjectFile>> {
    collect_project_files_inner(base_path, ignore, skip_nested_checkouts)
}

/// Collect project files with control over both kinds of exclusion.
///
/// # Errors
///
/// Returns an error when the target path is invalid, traversal fails, or file
/// metadata cannot be read.
///
/// # Parameters
///
/// * `skip_nested_checkouts` — as [`collect_project_files_with`].
/// * `read_ignore_files` — when false, `.gitignore` and `.sepheraignore` are
///   not consulted. Callers do not pass this: it lives on
///   [`IgnoreMatcher`](sephera_scan::IgnoreMatcher), so that it cannot
///   be dropped on one path and kept on another. This entry point exists for
///   tests, which need to compare the two settings directly.
#[cfg(test)]
pub fn collect_project_files_with_options(
    base_path: &Path,
    ignore: &IgnoreMatcher,
    skip_nested_checkouts: bool,
    read_ignore_files: bool,
) -> Result<Vec<ProjectFile>> {
    collect_project_files_inner(
        base_path,
        &ignore.with_reads_ignore_files(read_ignore_files),
        skip_nested_checkouts,
    )
}

fn collect_project_files_inner(
    base_path: &Path,
    ignore: &IgnoreMatcher,
    skip_nested_checkouts: bool,
) -> Result<Vec<ProjectFile>> {
    if !base_path.exists() {
        bail!("path `{}` does not exist", base_path.display());
    }
    if !base_path.is_dir() {
        bail!("path `{}` is not a directory", base_path.display());
    }

    let walker = Walker {
        base_path,
        ignore,
        skip_nested_checkouts,
        read_ignore_files: ignore.reads_ignore_files(),
    };

    let mut files = Vec::new();
    walker.walk(base_path, &mut files)?;
    files.sort_by(|left, right| {
        left.normalized_relative_path
            .cmp(&right.normalized_relative_path)
    });

    Ok(files)
}

/// Directories that are never part of a project's own source.
///
/// These are skipped regardless of `.gitignore` so that build output and
/// vendored trees are not analysed as first-party source. The analysis root
/// itself is never skipped, so pointing Sephera straight at a directory called
/// `target` still works.
const ALWAYS_SKIPPED_DIRECTORIES: &[&str] = &[
    "target",
    "node_modules",
    "__pycache__",
    "vendor",
    "dist",
    "build",
    "site-packages",
    "Pods",
];

/// Whether a directory name holds a nested checkout or agent worktree copy.
///
/// Tooling keeps parallel checkouts under dot-directories (`.kilo/worktrees`,
/// `.git/worktrees`, `.claude`). Analysing one alongside the real tree
/// duplicates every count and reports cycles that exist only in the copy, so
/// these are skipped. Dot-directories that hold real content — `.github`,
/// `.venv` when explicitly focused — are left to the caller, which is why this
/// is opt-in per caller rather than a blanket traversal rule.
fn is_nested_checkout_name(name: &str) -> bool {
    name.ends_with("worktrees") || name == ".git"
}

/// Whether a collected file is one of the ignore files themselves.
///
/// Read, never analysed. Reporting `.gitignore` as a line of project code would
/// mean the line count changes because an exclusion rule was added, which is
/// backwards: the rule describes files that should not be counted, so counting
/// it adds work for every file the rule omits.
fn is_ignore_file(normalized_path: &str) -> bool {
    Path::new(normalized_path)
        .file_name()
        .and_then(std::ffi::OsStr::to_str)
        .is_some_and(|name| IGNORE_FILE_NAMES.contains(&name))
}

/// One directory still to visit, carrying the ignore rules that apply inside
/// it.
///
/// `inherited` is the accumulated stack from the root down to and including this
/// directory's own ignore files. It has to be carried rather than re-read: a
/// rule in the root's `.gitignore` applies to every file in the tree, and a
/// traversal that consults only each directory's own rules would exempt
/// `src/notes.md` from a root `*.md` while still honouring `coverage`.
#[derive(Debug)]
struct Pending {
    directory: PathBuf,
    inherited: Arc<IgnoreRules>,
}

/// What visiting one directory produced.
///
/// Returned by value rather than appended into a shared list so that the
/// directories of a level can be visited in parallel and still concatenated in
/// a fixed order.
#[derive(Debug, Default)]
struct DirectoryVisit {
    files: Vec<ProjectFile>,
    subdirectories: Vec<Pending>,
}

/// Depth-first traversal that prunes excluded subtrees and reads each
/// directory's own ignore files.
///
/// An explicit stack rather than `WalkDir` plus `filter_entry`, for two
/// reasons. Ignore files are scoped to the directory holding them:
/// `frontend/.gitignore` containing `dist` excludes `frontend/dist` and must
/// not exclude `backend/dist`, and matching one flattened list of every pattern
/// in the tree would exclude both — a wrong answer delivered confidently.
/// And `filter_entry` cannot be handed the per-directory stack, because
/// `walkdir` requires its closure to be `Send`.
struct Walker<'a> {
    base_path: &'a Path,
    ignore: &'a IgnoreMatcher,
    skip_nested_checkouts: bool,
    read_ignore_files: bool,
}

impl Walker<'_> {
    fn walk(&self, root: &Path, files: &mut Vec<ProjectFile>) -> Result<()> {
        let mut frontier = vec![Pending {
            directory: root.to_path_buf(),
            inherited: Arc::new(IgnoreRules::default()),
        }];

        // One level of the tree at a time, each level in parallel.
        //
        // This walk is almost entirely waiting on the filesystem: measured over
        // 8000 small files in 2001 directories, listing the directories and
        // stat-ing the files took 276 ms while reading and classifying every
        // byte took 43 ms. Done one directory at a time it was 87% of the
        // command, and none of that time was spent computing anything -- it was
        // a single thread blocked on syscalls the other thirteen were not
        // making.
        //
        // `par_iter` keeps index order in what it collects, and the results are
        // concatenated in that order, so the file list is still fully
        // determined by the directory contents. What changes is that directories
        // are visited breadth-first rather than depth-first, which is a
        // different fixed order rather than a different fixed order per run.
        while !frontier.is_empty() {
            let visits = frontier
                .par_iter()
                .map(|entry| self.visit(entry))
                .collect::<Result<Vec<_>>>()?;

            frontier.clear();
            for mut visit in visits {
                files.append(&mut visit.files);
                frontier.append(&mut visit.subdirectories);
            }
        }

        Ok(())
    }

    /// One directory's files, and the subdirectories still to visit.
    fn visit(&self, entry: &Pending) -> Result<DirectoryVisit> {
        let mut children = Vec::new();
        let read = std::fs::read_dir(&entry.directory).with_context(|| {
            format!("failed to read directory `{}`", entry.directory.display())
        })?;

        for item in read {
            let item = item.with_context(|| {
                format!(
                    "failed to traverse directory `{}`",
                    entry.directory.display()
                )
            })?;
            children.push(item);
        }

        // This directory's own rules, now that its listing is in hand. The
        // listing already names every file here, so finding `.gitignore` among
        // the entries costs a string comparison instead of an open that usually
        // fails. See `read_directory_rules`.
        let rules =
            self.rules_for(&entry.directory, &children, &entry.inherited);

        // Read order is whatever the filesystem hands back, which differs
        // between machines. Sorting keeps traversal deterministic, so
        // nothing that depends on visiting order can pass on one machine
        // and fail on another.
        children.sort_by_key(std::fs::DirEntry::file_name);

        let mut visit = DirectoryVisit::default();

        for item in children {
            let path = item.path();
            // One metadata call answers both "what kind of entry is this" and
            // "how big is it". Asking `file_type` and then `metadata` separately
            // means two trips to the filesystem for every file in the tree, and
            // `DirEntry::metadata` does not traverse symlinks either, so the
            // classification it reports is the same one.
            let metadata = match item.metadata() {
                Ok(metadata) => metadata,
                Err(error) => {
                    // A dangling symlink fails here while `file_type` still
                    // describes it. A link is not a file to read, so skip it
                    // rather than failing a whole traversal over one broken
                    // entry; anything that claims to be a real file and cannot
                    // be measured is still an error, as it was before.
                    let file_type = item.file_type().with_context(|| {
                        format!(
                            "failed to read the type of `{}`",
                            path.display()
                        )
                    })?;
                    if !file_type.is_file() {
                        continue;
                    }
                    return Err(error).with_context(|| {
                        format!(
                            "failed to read metadata for `{}`",
                            path.display()
                        )
                    });
                }
            };
            let file_type = metadata.file_type();

            let relative_path =
                path.strip_prefix(self.base_path).unwrap_or(&path);
            let normalized = normalize_relative_path(relative_path);

            if self.is_skipped(&normalized, file_type, &rules) {
                continue;
            }

            if file_type.is_file() && is_ignore_file(&normalized) {
                // Collected, it would become a node in the graph and a line
                // in the file count, for a file whose only content is
                // instructions about which files to ignore. Counting it
                // means the line count moves when an exclusion rule is
                // added, which is backwards.
                continue;
            }

            if file_type.is_dir() {
                visit.subdirectories.push(Pending {
                    inherited: Arc::clone(&rules),
                    directory: path,
                });
                continue;
            }

            if !file_type.is_file() {
                continue;
            }

            let size_bytes = metadata.len();

            visit.files.push(ProjectFile {
                language_match: language_for_path(&path),
                normalized_relative_path: normalized,
                relative_path: relative_path.to_path_buf(),
                absolute_path: path,
                size_bytes,
            });
        }

        Ok(visit)
    }

    /// The rules to apply inside one directory: its own ignore files stacked on
    /// everything inherited from above.
    ///
    /// Appending rather than prepending is what gives a deeper ignore file
    /// precedence, matching git. The shared handle is reused when a directory
    /// has no ignore file of its own, so the common case copies nothing -- and
    /// the common case is most directories, which is why the answer is one
    /// `Arc` clone rather than a rebuilt rule set per directory.
    fn rules_for(
        &self,
        directory: &Path,
        children: &[std::fs::DirEntry],
        inherited: &Arc<IgnoreRules>,
    ) -> Arc<IgnoreRules> {
        if !self.read_ignore_files {
            return Arc::clone(inherited);
        }

        let own = read_directory_rules(directory, children);
        if own.is_empty() {
            return Arc::clone(inherited);
        }

        let mut combined = IgnoreRules::default();
        combined.extend_clone(inherited);
        combined.extend(own);
        Arc::new(combined)
    }

    /// Whether an entry is excluded, and by which rule.
    ///
    /// The generated-tree and nested-checkout checks come first: they are not
    /// opinions about source, they are statements about what is not source at
    /// all. Then explicit `--ignore` patterns, so a pattern the user typed is
    /// never undone by a `!` rule in the repository's own ignore file. The
    /// ignore files have the last word among the rules, matching git, where a
    /// deeper file overrides a shallower one.
    fn is_skipped(
        &self,
        normalized: &str,
        file_type: std::fs::FileType,
        rules: &IgnoreRules,
    ) -> bool {
        let is_dir = file_type.is_dir();

        if is_dir {
            let name = Path::new(normalized)
                .file_name()
                .and_then(|name| name.to_str());
            if let Some(name) = name {
                if ALWAYS_SKIPPED_DIRECTORIES.contains(&name) {
                    return true;
                }
                if self.skip_nested_checkouts && is_nested_checkout_name(name) {
                    return true;
                }
            }
        }

        if self.ignore.is_ignored(Path::new(normalized)) {
            return true;
        }

        rules.matched(normalized, is_dir) == Some(Decision::Ignore)
    }
}

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

    /// The project-relative paths that survive traversal.
    fn collected(root: &Path) -> Vec<String> {
        collect_project_files(root, &IgnoreMatcher::empty())
            .unwrap()
            .into_iter()
            .map(|file| file.normalized_relative_path)
            .collect()
    }

    /// The project-relative paths, with the repository's ignore files ignored.
    fn collected_without_ignore_files(root: &Path) -> Vec<String> {
        collect_project_files_with_options(
            root,
            &IgnoreMatcher::empty(),
            true,
            false,
        )
        .unwrap()
        .into_iter()
        .map(|file| file.normalized_relative_path)
        .collect()
    }

    #[test]
    fn skips_generated_directories_without_gitignore() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::create_dir_all(root.join("target")).unwrap();
        fs::create_dir_all(root.join("node_modules/pkg")).unwrap();
        fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
        fs::write(root.join("target/built.rs"), "fn built() {}\n").unwrap();
        fs::write(
            root.join("node_modules/pkg/index.js"),
            "module.exports = {};\n",
        )
        .unwrap();

        let names = collected(root);

        assert!(
            names.iter().any(|n| n.ends_with("main.rs")),
            "real source must be collected, got {names:?}"
        );
        assert!(
            !names.iter().any(|n| n.contains("target")),
            "target/ must be skipped even unlisted, got {names:?}"
        );
        assert!(
            !names.iter().any(|n| n.contains("node_modules")),
            "node_modules/ must be skipped even unlisted, got {names:?}"
        );
    }

    #[test]
    fn honours_the_repository_gitignore() {
        // A tool that reports a vendored tree as project code is answering a
        // different question from the one asked, and does so without a word.
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::create_dir_all(root.join("coverage")).unwrap();
        fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
        fs::write(root.join("coverage/lcov.info"), "TN:\n").unwrap();
        fs::write(root.join("src/notes.md"), "# notes\n").unwrap();
        fs::write(root.join(".gitignore"), "coverage\n*.md\n").unwrap();

        let names = collected(root);

        assert_eq!(
            names,
            vec!["src/main.rs".to_owned()],
            "an unlisted generated tree and an ignored file must both go, \
             got {names:?}"
        );
    }

    #[test]
    fn a_nested_gitignore_applies_to_its_own_directory_only() {
        // The reason ignore files are read per directory rather than flattened.
        // Flattening `frontend/.gitignore` into one list would exclude
        // `backend/generated` too, which is not what the file says.
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join("frontend/generated")).unwrap();
        fs::create_dir_all(root.join("backend/generated")).unwrap();
        fs::write(root.join("frontend/generated/a.ts"), "export {};\n")
            .unwrap();
        fs::write(root.join("backend/generated/b.ts"), "export {};\n").unwrap();
        fs::write(root.join("frontend/.gitignore"), "generated\n").unwrap();

        let names = collected(root);

        assert!(
            !names.contains(&"frontend/generated/a.ts".to_owned()),
            "the file's own directory is excluded, got {names:?}"
        );
        assert!(
            names.contains(&"backend/generated/b.ts".to_owned()),
            "a same-named directory elsewhere is not, got {names:?}"
        );
    }

    #[test]
    fn no_gitignore_leaves_the_repository_rules_out() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
        fs::write(root.join("src/notes.md"), "# notes\n").unwrap();
        fs::write(root.join(".gitignore"), "*.md\n").unwrap();

        assert_eq!(collected(root), vec!["src/main.rs".to_owned()]);
        assert_eq!(
            collected_without_ignore_files(root),
            vec!["src/main.rs".to_owned(), "src/notes.md".to_owned()],
            "with the repository's rules switched off, its files come back"
        );
    }

    #[test]
    fn no_gitignore_still_skips_generated_trees_and_explicit_patterns() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join("target")).unwrap();
        fs::create_dir_all(root.join("scratch")).unwrap();
        fs::write(root.join("target/built.rs"), "fn built() {}\n").unwrap();
        fs::write(root.join("scratch/a.rs"), "fn a() {}\n").unwrap();
        fs::write(root.join("scratch/b.rs"), "fn b() {}\n").unwrap();
        fs::write(root.join(".gitignore"), "scratch\n").unwrap();

        let ignore =
            IgnoreMatcher::from_patterns(&["*.rs".to_owned()]).unwrap();
        // `scratch` is excluded twice over: by the repository's file and by the
        // explicit `scratch` pattern. Neither is a generated-tree rule, so
        // switching ignore files off must not bring it back.
        let scratch: &[String] = &["scratch".to_owned()];
        let names = collect_project_files_with_options(
            root,
            &IgnoreMatcher::from_patterns(scratch).unwrap(),
            true,
            false,
        )
        .unwrap()
        .into_iter()
        .map(|file| file.normalized_relative_path)
        .collect::<Vec<String>>();

        assert!(
            !names.iter().any(|n| n.contains("target")),
            "a generated tree is not source under any setting, got {names:?}"
        );
        assert!(
            !names.iter().any(|n| n.contains("scratch")),
            "an explicit pattern still applies, got {names:?}"
        );

        // And the explicit glob, which is the item-1 fix, still works here.
        assert!(
            ignore.is_ignored(Path::new("scratch/a.rs")),
            "the matcher itself is unchanged by traversal options"
        );
    }

    #[test]
    fn a_gitignore_negation_reinstates_a_file() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join("logs")).unwrap();
        fs::write(root.join("logs/debug.log"), "x\n").unwrap();
        fs::write(root.join("logs/keep.log"), "x\n").unwrap();
        fs::write(root.join(".gitignore"), "*.log\n!keep.log\n").unwrap();

        let names = collected(root);

        assert_eq!(names, vec!["logs/keep.log".to_owned()], "got {names:?}");
    }

    #[test]
    fn an_explicit_pattern_outranks_a_repository_negation() {
        // A pattern the user typed must not be undone by a `!` rule they did not
        // write for this invocation.
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
        fs::write(root.join("test.rs"), "#[test] fn t() {}\n").unwrap();
        fs::write(root.join(".gitignore"), "!*.rs\n").unwrap();

        let names: Vec<String> = collect_project_files_with_options(
            root,
            &IgnoreMatcher::from_patterns(&["test.rs".to_owned()]).unwrap(),
            true,
            true,
        )
        .unwrap()
        .into_iter()
        .map(|file| file.normalized_relative_path)
        .collect();

        assert_eq!(
            names,
            vec!["main.rs".to_owned()],
            "--ignore must win over `.gitignore`, got {names:?}"
        );
    }

    #[test]
    fn a_sepheraignore_overrides_the_repository_gitignore() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join("generated")).unwrap();
        fs::write(root.join("generated/schema.json"), "{}\n").unwrap();
        fs::write(root.join("generated/other.json"), "{}\n").unwrap();
        fs::write(root.join(".gitignore"), "*.json\n").unwrap();
        fs::write(root.join(".sepheraignore"), "!generated/schema.json\n")
            .unwrap();

        let names = collected(root);

        assert!(
            names.contains(&"generated/schema.json".to_owned()),
            "the file the user asked for must survive, got {names:?}"
        );
        assert!(
            !names.contains(&"generated/other.json".to_owned()),
            "and the rest of the repository's rule must still hold, got \
             {names:?}"
        );
    }

    #[test]
    fn a_negation_cannot_reach_inside_an_excluded_directory() {
        // git: "It is not possible to re-include a file if a parent directory
        // of that file is excluded." Traversal prunes `generated` before it ever
        // looks inside, so the file below it is unreachable.
        //
        // Asserted because the alternative is worse: a traversal that
        // descended anyway to honour the negation would be doing something git
        // does not, and would report files the repository says are not there.
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join("generated")).unwrap();
        fs::write(root.join("generated/schema.json"), "{}\n").unwrap();
        fs::write(root.join(".gitignore"), "generated\n").unwrap();
        fs::write(root.join(".sepheraignore"), "!generated/schema.json\n")
            .unwrap();

        assert_eq!(collected(root), Vec::<String>::new());
    }

    #[test]
    fn a_malformed_ignore_file_does_not_stop_the_walk() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
        fs::write(root.join(".gitignore"), "[unclosed\n").unwrap();

        // The valid part is unusable, but a file that cannot be parsed must not
        // turn into a failed analysis.
        assert_eq!(collected(root), vec!["main.rs".to_owned()]);
    }

    #[test]
    fn skips_agent_worktree_directories_by_default() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join("crates/core")).unwrap();
        fs::create_dir_all(root.join(".kilo/worktrees/arrow/crates/core"))
            .unwrap();
        fs::write(root.join("crates/core/a.rs"), "use crate::b;\n").unwrap();
        fs::write(root.join("crates/core/b.rs"), "pub fn b() {}\n").unwrap();
        fs::write(
            root.join(".kilo/worktrees/arrow/crates/core/a.rs"),
            "use crate::b;\n",
        )
        .unwrap();

        let names = collected(root);
        let nested = names.iter().filter(|n| n.contains(".kilo")).count();

        assert_eq!(
            nested, 0,
            "worktree copies must not be counted as project source, got {names:?}"
        );
    }

    #[test]
    fn worktrees_can_be_included_when_caller_opts_in() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join(".kilo/worktrees/arrow/src")).unwrap();
        fs::write(root.join(".kilo/worktrees/arrow/src/a.rs"), "fn a() {}\n")
            .unwrap();

        let files =
            collect_project_files_with(root, &IgnoreMatcher::empty(), false)
                .unwrap();

        assert!(
            files
                .iter()
                .any(|f| f.normalized_relative_path.contains(".kilo")),
            "opting in must reach worktree contents"
        );
    }

    #[test]
    fn dot_directories_that_hold_content_are_kept() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        fs::create_dir_all(root.join(".github/workflows")).unwrap();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(root.join(".github/workflows/ci.yml"), "name: CI\n").unwrap();
        fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();

        let paths = collected(root);

        assert!(
            paths.iter().any(|p| p.contains(".github")),
            "dot-directories with real content must be kept, got {paths:?}"
        );
    }

    #[test]
    fn root_analysis_target_is_never_skipped() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path().join("target");
        fs::create_dir_all(&root).unwrap();
        fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();

        let files =
            collect_project_files(&root, &IgnoreMatcher::empty()).unwrap();

        assert_eq!(
            files.len(),
            1,
            "the analysis root itself must be traversed"
        );
    }

    #[test]
    fn collects_files_from_empty_directory() {
        let temp_dir = tempdir().unwrap();
        let ignore = IgnoreMatcher::empty();

        let result = collect_project_files(temp_dir.path(), &ignore).unwrap();

        assert!(result.is_empty());
    }

    #[test]
    fn collects_files_recursively() {
        let temp_dir = tempdir().unwrap();
        fs::write(temp_dir.path().join("main.rs"), "fn main() {}").unwrap();
        fs::create_dir(temp_dir.path().join("src")).unwrap();
        fs::write(temp_dir.path().join("src/lib.rs"), "pub fn lib() {}")
            .unwrap();

        let ignore = IgnoreMatcher::empty();
        let result = collect_project_files(temp_dir.path(), &ignore).unwrap();

        assert_eq!(result.len(), 2);
        assert!(result.iter().any(|f| f.relative_path.ends_with("main.rs")));
        assert!(result.iter().any(|f| f.relative_path.ends_with("lib.rs")));
    }

    #[test]
    fn respects_ignore_patterns() {
        let temp_dir = tempdir().unwrap();
        fs::write(temp_dir.path().join("main.rs"), "fn main() {}").unwrap();
        fs::write(temp_dir.path().join("target.rs"), "fn target() {}").unwrap();
        fs::write(temp_dir.path().join("Cargo.lock"), "").unwrap();

        let ignore = IgnoreMatcher::from_patterns(&[
            "target.rs".to_string(),
            "*.lock".to_string(),
        ])
        .unwrap();

        let result = collect_project_files(temp_dir.path(), &ignore).unwrap();

        assert_eq!(result.len(), 1);
        assert!(
            result
                .iter()
                .all(|f| !f.relative_path.ends_with("target.rs"))
        );
        assert!(
            result
                .iter()
                .all(|f| !f.relative_path.ends_with("Cargo.lock"))
        );
    }

    #[test]
    fn returns_error_for_nonexistent_path() {
        let ignore = IgnoreMatcher::empty();
        let result =
            collect_project_files(Path::new("/nonexistent/path"), &ignore);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("does not exist"));
    }

    #[test]
    fn returns_error_for_file_instead_of_directory() {
        let temp_dir = tempdir().unwrap();
        let file_path = temp_dir.path().join("file.txt");
        fs::write(&file_path, "content").unwrap();

        let ignore = IgnoreMatcher::empty();
        let result = collect_project_files(&file_path, &ignore);

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("is not a directory")
        );
    }

    #[test]
    fn skips_symlinks_to_files() {
        let temp_dir = tempdir().unwrap();
        let real_file = temp_dir.path().join("real.rs");
        let symlink_file = temp_dir.path().join("link.rs");

        fs::write(&real_file, "fn real() {}").unwrap();

        // Create symlink (may fail on Windows without developer mode)
        let symlink_created = {
            #[cfg(unix)]
            {
                std::os::unix::fs::symlink(&real_file, &symlink_file).is_ok()
            }
            #[cfg(windows)]
            {
                match std::os::windows::fs::symlink_file(
                    &real_file,
                    &symlink_file,
                ) {
                    Ok(()) => true,
                    Err(err) => {
                        // Skip test if symlink creation fails (requires privilege on Windows)
                        eprintln!(
                            "Skipping symlink test: requires privilege on Windows ({err})"
                        );
                        false
                    }
                }
            }
        };

        if !symlink_created {
            return; // Skip test if symlink couldn't be created
        }

        let ignore = IgnoreMatcher::empty();
        let result = collect_project_files(temp_dir.path(), &ignore).unwrap();

        // Should only collect the real file, not the symlink
        assert_eq!(result.len(), 1);
        assert!(result.iter().any(|f| f.relative_path.ends_with("real.rs")));
    }

    #[test]
    fn normalizes_paths_correctly() {
        let temp_dir = tempdir().unwrap();
        fs::create_dir(temp_dir.path().join("src")).unwrap();
        fs::write(temp_dir.path().join("src/main.rs"), "fn main() {}").unwrap();

        let ignore = IgnoreMatcher::empty();
        let result = collect_project_files(temp_dir.path(), &ignore).unwrap();

        assert_eq!(result.len(), 1);
        let file = &result[0];

        // Check normalized path uses forward slashes
        assert!(!file.normalized_relative_path.contains('\\'));
        assert_eq!(file.normalized_relative_path, "src/main.rs");
    }

    #[test]
    fn sorts_files_by_normalized_path() {
        let temp_dir = tempdir().unwrap();
        fs::write(temp_dir.path().join("z.rs"), "").unwrap();
        fs::write(temp_dir.path().join("a.rs"), "").unwrap();
        fs::write(temp_dir.path().join("m.rs"), "").unwrap();

        let ignore = IgnoreMatcher::empty();
        let result = collect_project_files(temp_dir.path(), &ignore).unwrap();

        assert_eq!(result.len(), 3);
        assert_eq!(result[0].normalized_relative_path, "a.rs");
        assert_eq!(result[1].normalized_relative_path, "m.rs");
        assert_eq!(result[2].normalized_relative_path, "z.rs");
    }

    #[test]
    fn includes_file_size() {
        let temp_dir = tempdir().unwrap();
        let content = "fn main() {}";
        fs::write(temp_dir.path().join("main.rs"), content).unwrap();

        let ignore = IgnoreMatcher::empty();
        let result = collect_project_files(temp_dir.path(), &ignore).unwrap();

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].size_bytes, content.len() as u64);
    }

    #[test]
    fn detects_language_for_files() {
        let temp_dir = tempdir().unwrap();
        fs::write(temp_dir.path().join("main.rs"), "fn main() {}").unwrap();
        fs::write(temp_dir.path().join("lib.py"), "def lib(): pass").unwrap();

        let ignore = IgnoreMatcher::empty();
        let result = collect_project_files(temp_dir.path(), &ignore).unwrap();

        assert_eq!(result.len(), 2);

        let rust_file = result
            .iter()
            .find(|f| f.relative_path.ends_with("main.rs"))
            .unwrap();
        assert!(rust_file.language_match.is_some());

        let python_file = result
            .iter()
            .find(|f| f.relative_path.ends_with("lib.py"))
            .unwrap();
        assert!(python_file.language_match.is_some());
    }
}