Skip to main content

ragfs_index/
exclude.rs

1//! Shared default exclusion lists and matcher (ADR-010).
2//!
3//! One source of truth for CLI, FUSE/mount, library `IndexerConfig`, and docs.
4//! Hidden files *and* hidden directories under the index root are excluded by
5//! default. A separate secret-file denylist is always applied unless the user
6//! sets `include_secret_files`. Gitignore `!` rules cannot re-include a secret
7//! or hidden path.
8//!
9//! Built-in secret patterns follow gitleaks / TruffleHog-style filename
10//! denylists (`*.pem`, `*.key`, `id_rsa` / `id_ed25519`, credentials files,
11//! `.netrc`, `.npmrc`, `.pypirc`, `.env*`, kube config). A bare `id_*` is
12//! intentionally not used (false positive on `id_mapping.md`).
13//!
14//! Hidden/secret path exclusion is adapted from [sophie4869/ragfs](https://github.com/sophie4869/ragfs)
15//! onto the `ignore` crate (`WalkBuilder` + `OverrideBuilder`) as specified
16//! by ADR-010. Nested `.ragfsignore` files are supported under the index root.
17
18use ignore::WalkBuilder;
19use ignore::gitignore::Gitignore;
20use ignore::overrides::{Override, OverrideBuilder};
21use std::path::{Component, Path, PathBuf};
22use tracing::warn;
23
24use crate::indexer::path_matches_pattern;
25
26/// Noise / build-artifact globs used as the default `[index].exclude` list.
27///
28/// Secrets and hidden paths are *not* in this list so replacing `exclude` in
29/// config cannot disable the denylist or hidden-path rule.
30pub const DEFAULT_NOISE_PATTERNS: &[&str] = &[
31    "**/node_modules/**",
32    "**/.git/**",
33    "**/target/**",
34    "**/__pycache__/**",
35    "**/*.pyc",
36    "**/.venv/**",
37    "**/venv/**",
38    "**/*.lock",
39];
40
41/// Secret-file denylist (ADR-010). Always applied unless `include_secret_files`.
42///
43/// Public keys (`id_*.pub`) are not listed and stay eligible when hidden
44/// opt-in is on. Case-sensitive on Linux; case-insensitive on macOS/Windows
45/// (same as the `ignore` crate / git on that host).
46pub const DEFAULT_SECRET_PATTERNS: &[&str] = &[
47    "**/.env",
48    "**/.env.*",
49    "**/*.env",
50    "**/.netrc",
51    "**/.npmrc",
52    "**/.pypirc",
53    "**/.git-credentials",
54    "**/*.key",
55    "**/*.pem",
56    "**/*.p12",
57    "**/*.pfx",
58    "**/*.kdbx",
59    "**/*.jks",
60    "**/*.keystore",
61    "**/*.ppk",
62    "**/id_rsa",
63    "**/id_dsa",
64    "**/id_ecdsa",
65    "**/id_ed25519",
66    "**/secrets.*",
67    "**/credentials.*",
68    "**/.aws/credentials",
69    "**/.kube/config",
70];
71
72/// Default `[index].exclude` / `IndexerConfig.exclude_patterns` (noise only).
73#[must_use]
74pub fn default_exclude_patterns() -> Vec<String> {
75    DEFAULT_NOISE_PATTERNS
76        .iter()
77        .map(|pattern| (*pattern).to_string())
78        .collect()
79}
80
81/// Options for [`ExclusionMatcher`].
82#[derive(Debug, Clone)]
83pub struct ExclusionOptions {
84    /// Index hidden descendants of the root (`--include-hidden`).
85    pub include_hidden: bool,
86    /// Index secret-named files (does not affect hidden unless also set).
87    pub include_secret_files: bool,
88    /// Honour `.gitignore` / `.ignore` under the index root only.
89    pub honor_gitignore: bool,
90    /// Additional ignore globs (`[index].exclude`).
91    pub extra_excludes: Vec<String>,
92    /// Include globs; empty means “all non-excluded”.
93    pub include_patterns: Vec<String>,
94}
95
96impl Default for ExclusionOptions {
97    fn default() -> Self {
98        Self {
99            include_hidden: false,
100            include_secret_files: false,
101            honor_gitignore: true,
102            extra_excludes: default_exclude_patterns(),
103            include_patterns: vec!["**/*".to_string()],
104        }
105    }
106}
107
108/// Matcher bound to one index root.
109#[derive(Debug, Clone)]
110pub struct ExclusionMatcher {
111    root: PathBuf,
112    options: ExclusionOptions,
113    overrides: Override,
114}
115
116impl ExclusionMatcher {
117    /// Build a matcher for `root`. Invalid override globs are skipped.
118    #[must_use]
119    pub fn new(root: impl Into<PathBuf>, options: ExclusionOptions) -> Self {
120        let root = root.into();
121        let overrides = build_overrides(&root, &options);
122        Self {
123            root,
124            options,
125            overrides,
126        }
127    }
128
129    /// Index root this matcher is bound to.
130    #[must_use]
131    pub fn root(&self) -> &Path {
132        &self.root
133    }
134
135    /// Options used to build this matcher.
136    #[must_use]
137    pub fn options(&self) -> &ExclusionOptions {
138        &self.options
139    }
140
141    /// Whether `path` is excluded by hidden / secret / noise / gitignore rules.
142    ///
143    /// Include globs are not applied here; see [`Self::should_process`].
144    #[must_use]
145    pub fn is_excluded(&self, path: &Path) -> bool {
146        if !self.options.include_hidden && self.is_hidden_under_root(path) {
147            return true;
148        }
149        let Ok(relative) = path.strip_prefix(&self.root) else {
150            return true;
151        };
152        let mut candidate = self.root.clone();
153        let components: Vec<_> = relative.components().collect();
154        for (index, component) in components.iter().enumerate() {
155            candidate.push(component.as_os_str());
156            if override_ignores(
157                &self.overrides,
158                &candidate,
159                index + 1 < components.len() || path.is_dir(),
160            ) {
161                return true;
162            }
163        }
164        self.options.honor_gitignore && gitignore_excludes(&self.root, path)
165    }
166
167    /// Whether a file should be indexed (not excluded and matches include globs).
168    #[must_use]
169    pub fn should_process(&self, path: &Path) -> bool {
170        if self.is_excluded(path) {
171            return false;
172        }
173        matches_include(&self.options.include_patterns, path)
174    }
175
176    /// Whether a directory should be descended into during a hand-rolled walk.
177    #[must_use]
178    pub fn should_descend(&self, path: &Path) -> bool {
179        if path == self.root {
180            return true;
181        }
182        !self.is_excluded(path)
183    }
184
185    /// Walk the index root with the `ignore` crate (`WalkBuilder`).
186    ///
187    /// Hidden opt-in, secret/noise overrides, and gitignore (no parents, no
188    /// global gitignore) are applied here. Include globs are applied after.
189    #[must_use]
190    pub fn collect_files(&self) -> Vec<PathBuf> {
191        self.collect_files_with_status().0
192    }
193
194    /// Return eligible files and whether every visited entry was readable.
195    /// An incomplete walk must never be used to infer deletions.
196    pub fn collect_files_with_status(&self) -> (Vec<PathBuf>, bool) {
197        let mut complete = true;
198        let mut builder = WalkBuilder::new(&self.root);
199        let matcher = self.clone();
200        builder
201            .standard_filters(false)
202            .follow_links(false)
203            .filter_entry(move |entry| entry.depth() == 0 || !matcher.is_excluded(entry.path()));
204
205        let files = builder
206            .build()
207            .filter_map(|entry| match entry {
208                Ok(entry) => Some(entry),
209                Err(error) => {
210                    complete = false;
211                    warn!("Cannot read index entry: {error}");
212                    None
213                }
214            })
215            .filter(|entry| entry.file_type().is_some_and(|kind| kind.is_file()))
216            .map(ignore::DirEntry::into_path)
217            .filter(|path| matches_include(&self.options.include_patterns, path))
218            .collect();
219        (files, complete)
220    }
221
222    fn is_hidden_under_root(&self, path: &Path) -> bool {
223        is_hidden_under_root(&self.root, path)
224    }
225}
226
227fn build_overrides(root: &Path, options: &ExclusionOptions) -> Override {
228    let mut builder = OverrideBuilder::new(root);
229    builder
230        .case_insensitive(cfg!(any(target_os = "macos", target_os = "windows")))
231        .expect("case policy configured before adding globs");
232    if !options.include_secret_files {
233        for pattern in DEFAULT_SECRET_PATTERNS {
234            add_ignore_override(&mut builder, pattern);
235        }
236    }
237    for pattern in &options.extra_excludes {
238        add_ignore_override(&mut builder, pattern);
239    }
240    match builder.build() {
241        Ok(overrides) => overrides,
242        Err(error) => {
243            warn!("Failed to build exclusion overrides ({error}); using empty set");
244            OverrideBuilder::new(root)
245                .build()
246                .expect("empty OverrideBuilder")
247        }
248    }
249}
250
251/// Add an *ignore* override (`!glob`).
252///
253/// `OverrideBuilder` polarity is the inverse of gitignore: a bare glob is a
254/// whitelist, and a `!` prefix is an ignore. ADR-010 uses ignore overrides so
255/// gitignore `!` cannot re-include a secret or noise path.
256fn add_ignore_override(builder: &mut OverrideBuilder, pattern: &str) {
257    let pattern = pattern.trim();
258    if pattern.is_empty() || pattern == "!" {
259        return;
260    }
261    // `[index].exclude` always adds excludes, even if the user wrote `!`.
262    let stripped = pattern.strip_prefix('!').unwrap_or(pattern);
263    let ignore_glob = format!("!{stripped}");
264    if let Err(error) = builder.add(&ignore_glob) {
265        warn!("Ignoring invalid exclude pattern {pattern:?}: {error}");
266    }
267}
268
269fn override_ignores(overrides: &Override, path: &Path, is_dir: bool) -> bool {
270    overrides.matched(path, is_dir).is_ignore()
271        || overrides
272            .matched(path_for_override(path), is_dir)
273            .is_ignore()
274}
275
276fn path_for_override(path: &Path) -> &Path {
277    path.strip_prefix("/").unwrap_or(path)
278}
279
280fn is_hidden_under_root(root: &Path, path: &Path) -> bool {
281    let relative = match path.strip_prefix(root) {
282        Ok(relative) => relative,
283        Err(_) => return path.components().any(is_hidden_component),
284    };
285    relative.components().any(is_hidden_component)
286}
287
288fn is_hidden_component(component: Component<'_>) -> bool {
289    match component {
290        Component::Normal(name) => {
291            let name = name.to_string_lossy();
292            name.starts_with('.') && name != "." && name != ".."
293        }
294        _ => false,
295    }
296}
297
298fn matches_include(include_patterns: &[String], path: &Path) -> bool {
299    if include_patterns.is_empty() {
300        return true;
301    }
302    let path_str = path.to_string_lossy();
303    include_patterns
304        .iter()
305        .any(|pattern| path_matches_pattern(&path_str, pattern))
306}
307
308/// Honour `.gitignore` / `.ignore` from the index root down to `path`.
309///
310/// Never reads a file above `root`. A `!` whitelist in those files cannot
311/// undo [`ExclusionMatcher::is_excluded`] secret/hidden decisions because
312/// those run first.
313fn gitignore_excludes(root: &Path, path: &Path) -> bool {
314    let Ok(relative) = path.strip_prefix(root) else {
315        return true;
316    };
317    let mut candidate = root.to_path_buf();
318    let components: Vec<_> = relative.components().collect();
319    // An ignored parent cannot be resurrected by a child negation. Evaluate
320    // each ancestor as a directory, even for a deleted watcher path.
321    for (index, component) in components.iter().enumerate() {
322        candidate.push(component.as_os_str());
323        let is_dir = index + 1 < components.len() || path.is_dir();
324        let mut dirs = Vec::new();
325        let mut parent = candidate.parent();
326        while let Some(dir) = parent {
327            if !dir.starts_with(root) {
328                break;
329            }
330            dirs.push(dir);
331            if dir == root {
332                break;
333            }
334            parent = dir.parent();
335        }
336        dirs.reverse();
337        let mut ignored = false;
338        // File kind takes precedence over depth; the nearest file of the
339        // same kind wins. All evaluation stays inside the index root.
340        for name in [".gitignore", ".ignore", ".ragfsignore"] {
341            for dir in &dirs {
342                let ignore_path = dir.join(name);
343                if !ignore_path.is_file() {
344                    continue;
345                }
346                let (rules, error) = Gitignore::new(&ignore_path);
347                if let Some(error) = error {
348                    warn!("Failed to parse {}: {error}", ignore_path.display());
349                }
350                let matched = rules.matched(&candidate, is_dir);
351                if matched.is_ignore() {
352                    ignored = true;
353                } else if matched.is_whitelist() {
354                    ignored = false;
355                }
356            }
357        }
358        if ignored {
359            return true;
360        }
361    }
362    false
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use std::fs;
369    use tempfile::tempdir;
370
371    fn matcher_at(root: &Path) -> ExclusionMatcher {
372        ExclusionMatcher::new(root, ExclusionOptions::default())
373    }
374
375    fn write(root: &Path, relative: &str, body: &str) {
376        let path = root.join(relative);
377        if let Some(parent) = path.parent() {
378            fs::create_dir_all(parent).unwrap();
379        }
380        fs::write(path, body).unwrap();
381    }
382
383    #[test]
384    fn override_builder_bang_is_an_ignore_not_a_whitelist() {
385        // Guard the ignore-crate polarity: bare globs whitelist, `!` ignores.
386        let root = tempdir().unwrap();
387        let root = root.path();
388        write(root, "notes/keyboard.md", "kept");
389        write(root, "server.pem", "secret");
390        write(root, "node_modules/pkg/index.js", "noise");
391
392        let matcher = matcher_at(root);
393        assert!(
394            matcher.should_process(&root.join("notes/keyboard.md")),
395            "ignore-only overrides must not treat unmatched files as ignored"
396        );
397        assert!(matcher.is_excluded(&root.join("server.pem")));
398        assert!(matcher.is_excluded(&root.join("node_modules/pkg/index.js")));
399        let collected = matcher.collect_files();
400        assert_eq!(
401            collected.len(),
402            1,
403            "walk must keep the note and drop noise/secrets: {collected:?}"
404        );
405    }
406
407    #[test]
408    fn default_exclude_lists_are_the_shared_noise_patterns() {
409        assert_eq!(
410            default_exclude_patterns(),
411            DEFAULT_NOISE_PATTERNS
412                .iter()
413                .map(|p| (*p).to_string())
414                .collect::<Vec<_>>()
415        );
416        assert!(
417            !DEFAULT_NOISE_PATTERNS.contains(&"**/.*"),
418            "hidden paths are a separate rule, not a **/.* glob"
419        );
420        assert!(
421            !DEFAULT_SECRET_PATTERNS.contains(&"**/id_*"),
422            "bare id_* is a false positive on id_mapping.md"
423        );
424    }
425
426    #[test]
427    fn hidden_file_and_hidden_dir_are_excluded() {
428        let root = tempdir().unwrap();
429        let root = root.path();
430        write(root, "notes/keyboard.md", "kept");
431        write(root, ".hidden.md", "hidden file");
432        write(root, ".obsidian/x.md", "hidden dir");
433        write(root, ".ssh/id_rsa", "ssh key");
434        let matcher = matcher_at(root);
435
436        assert!(matcher.should_process(&root.join("notes/keyboard.md")));
437        assert!(matcher.is_excluded(&root.join(".hidden.md")));
438        assert!(matcher.is_excluded(&root.join(".obsidian/x.md")));
439        assert!(matcher.is_excluded(&root.join(".ssh/id_rsa")));
440        assert!(!matcher.should_descend(&root.join(".obsidian")));
441        assert!(matcher.should_descend(root));
442    }
443
444    #[test]
445    fn hidden_index_root_keeps_visible_descendants() {
446        let tmp = tempdir().unwrap();
447        let root = tmp.path().join(".notes");
448        fs::create_dir_all(&root).unwrap();
449        write(&root, "todo.md", "visible in hidden root");
450        write(&root, "sub/deep.md", "also visible");
451        write(&root, ".obsidian/app.json", "hidden inside");
452        let matcher = matcher_at(&root);
453
454        assert!(
455            matcher.should_process(&root.join("todo.md")),
456            "index root may itself be hidden"
457        );
458        assert!(matcher.should_process(&root.join("sub/deep.md")));
459        assert!(matcher.is_excluded(&root.join(".obsidian/app.json")));
460    }
461
462    #[test]
463    fn secret_denylist_matches_adr_examples() {
464        let root = tempdir().unwrap();
465        let root = root.path();
466        let matcher = matcher_at(root);
467
468        assert!(matcher.is_excluded(&root.join("server.pem")));
469        assert!(matcher.is_excluded(&root.join("certs/server.pem")));
470        assert!(matcher.is_excluded(&root.join("deploy.key")));
471        assert!(matcher.is_excluded(&root.join("passwords.kdbx")));
472        assert!(matcher.is_excluded(&root.join(".env")));
473        assert!(matcher.is_excluded(&root.join(".env.local")));
474        assert!(matcher.is_excluded(&root.join("prod.env")));
475        assert!(matcher.is_excluded(&root.join(".netrc")));
476        assert!(matcher.is_excluded(&root.join(".npmrc")));
477        assert!(matcher.is_excluded(&root.join(".pypirc")));
478        assert!(matcher.is_excluded(&root.join(".git-credentials")));
479        assert!(matcher.is_excluded(&root.join("id_rsa")));
480        assert!(matcher.is_excluded(&root.join("id_ed25519")));
481        assert!(matcher.is_excluded(&root.join(".aws/credentials")));
482        assert!(matcher.is_excluded(&root.join(".kube/config")));
483        assert!(matcher.is_excluded(&root.join("secrets.yaml")));
484        assert!(matcher.is_excluded(&root.join("credentials.json")));
485        assert!(
486            !matcher.is_excluded(&root.join("notes/keyboard.md")),
487            "ordinary notes stay eligible"
488        );
489        assert!(
490            !matcher.is_excluded(&root.join("id_mapping.md")),
491            "bare id_* must not exclude id_mapping.md"
492        );
493        assert!(
494            !matcher.is_excluded(&root.join("id_rsa.pub")),
495            "public keys are not secrets"
496        );
497    }
498
499    #[test]
500    fn include_hidden_does_not_disable_secret_denylist() {
501        let root = tempdir().unwrap();
502        let root = root.path();
503        write(root, ".notes.md", "dotfile");
504        write(root, ".ssh/id_rsa", "private");
505        write(root, ".ssh/id_rsa.pub", "public");
506        write(root, "server.pem", "cert");
507        write(root, "notes/keyboard.md", "kept");
508
509        let matcher = ExclusionMatcher::new(
510            root,
511            ExclusionOptions {
512                include_hidden: true,
513                ..ExclusionOptions::default()
514            },
515        );
516
517        assert!(
518            matcher.should_process(&root.join(".notes.md")),
519            "hidden opt-in indexes a visible-named file in a hidden basename"
520        );
521        assert!(
522            matcher.should_process(&root.join(".ssh/id_rsa.pub")),
523            "public key is eligible once hidden dirs are included"
524        );
525        assert!(
526            matcher.is_excluded(&root.join(".ssh/id_rsa")),
527            "include-hidden must not disable the secret denylist"
528        );
529        assert!(matcher.is_excluded(&root.join("server.pem")));
530        assert!(matcher.should_process(&root.join("notes/keyboard.md")));
531    }
532
533    #[test]
534    fn gitignore_under_root_is_honoured_without_parents() {
535        let tmp = tempdir().unwrap();
536        let root = tmp.path().join("proj");
537        fs::create_dir_all(&root).unwrap();
538        write(&root, "kept.md", "keep");
539        write(&root, "skip.log", "noise");
540        write(&root, ".gitignore", "*.log\n");
541        // Parent gitignore must not apply (parents off).
542        write(tmp.path(), ".gitignore", "*.md\n");
543
544        let matcher = matcher_at(&root);
545        assert!(matcher.should_process(&root.join("kept.md")));
546        assert!(
547            matcher.is_excluded(&root.join("skip.log")),
548            "root .gitignore applies"
549        );
550    }
551
552    #[test]
553    fn gitignore_bang_cannot_reinclude_secrets() {
554        let root = tempdir().unwrap();
555        let root = root.path();
556        write(root, ".env", "SECRET=1");
557        write(root, "server.pem", "cert");
558        write(root, ".gitignore", "!.env\n!*.pem\n");
559
560        let hidden_on = ExclusionMatcher::new(
561            root,
562            ExclusionOptions {
563                include_hidden: true,
564                ..ExclusionOptions::default()
565            },
566        );
567        assert!(
568            hidden_on.is_excluded(&root.join(".env")),
569            "!.env in gitignore must not re-include a secret"
570        );
571        assert!(hidden_on.is_excluded(&root.join("server.pem")));
572    }
573
574    #[test]
575    fn honor_gitignore_false_skips_gitignore() {
576        let root = tempdir().unwrap();
577        let root = root.path();
578        write(root, "skip.log", "noise");
579        write(root, ".gitignore", "*.log\n");
580        let matcher = ExclusionMatcher::new(
581            root,
582            ExclusionOptions {
583                honor_gitignore: false,
584                ..ExclusionOptions::default()
585            },
586        );
587        assert!(matcher.should_process(&root.join("skip.log")));
588    }
589
590    #[test]
591    fn walkbuilder_collect_agrees_with_should_process() {
592        let root = tempdir().unwrap();
593        let root = root.path();
594        write(root, "notes/keyboard.md", "kept");
595        write(root, ".obsidian/x.md", "hidden dir");
596        write(root, "server.pem", "secret");
597        write(root, "node_modules/pkg/index.js", "noise");
598        write(root, ".hidden.md", "hidden file");
599
600        let matcher = matcher_at(root);
601        let collected = matcher.collect_files();
602        assert_eq!(
603            collected.len(),
604            1,
605            "only the visible note is walked: {collected:?}"
606        );
607        assert!(collected[0].ends_with("keyboard.md"));
608        assert!(matcher.should_process(&root.join("notes/keyboard.md")));
609    }
610
611    #[test]
612    fn include_patterns_filter_after_excludes() {
613        let root = tempdir().unwrap();
614        let root = root.path();
615        write(root, "src/lib.rs", "fn x() {}");
616        write(root, "readme.md", "docs");
617        let matcher = ExclusionMatcher::new(
618            root,
619            ExclusionOptions {
620                include_patterns: vec!["**/*.rs".to_string()],
621                ..ExclusionOptions::default()
622            },
623        );
624        assert!(matcher.should_process(&root.join("src/lib.rs")));
625        assert!(!matcher.should_process(&root.join("readme.md")));
626        let collected = matcher.collect_files();
627        assert_eq!(collected.len(), 1);
628        assert!(collected[0].ends_with("lib.rs"));
629    }
630    #[test]
631    fn scan_and_direct_match_agree_for_ignored_ancestors() {
632        let tmp = tempdir().unwrap();
633        let root = tmp.path();
634        write(root, ".gitignore", "private/\n");
635        write(root, "private/.gitignore", "!note.md\n");
636        write(root, "private/note.md", "private");
637        write(root, "public.md", "public");
638        let matcher = matcher_at(root);
639        assert!(matcher.is_excluded(&root.join("private/note.md")));
640        assert_eq!(matcher.collect_files(), vec![root.join("public.md")]);
641    }
642
643    #[test]
644    fn ignore_kind_precedence_beats_nested_gitignore() {
645        let tmp = tempdir().unwrap();
646        let root = tmp.path();
647        write(root, ".ignore", "*.md\n");
648        write(root, "sub/.gitignore", "!note.md\n");
649        write(root, "sub/note.md", "private");
650        let matcher = matcher_at(root);
651        assert!(matcher.is_excluded(&root.join("sub/note.md")));
652        assert!(matcher.collect_files().is_empty());
653    }
654
655    #[test]
656    fn secret_case_policy_is_explicit() {
657        let tmp = tempdir().unwrap();
658        let matcher = matcher_at(tmp.path());
659        assert_eq!(
660            matcher.is_excluded(&tmp.path().join("SERVER.PEM")),
661            cfg!(any(target_os = "macos", target_os = "windows"))
662        );
663    }
664    #[test]
665    fn nested_ragfsignore_is_bounded_and_has_highest_priority() {
666        let tmp = tempdir().unwrap();
667        let root = tmp.path().join("root");
668        fs::create_dir_all(&root).unwrap();
669        write(tmp.path(), ".ragfsignore", "*.md\n");
670        write(&root, ".ignore", "*.md\n");
671        write(&root, ".ragfsignore", "# keep notes\n!*.md\ncache/\n");
672        write(&root, "sub/.ragfsignore", "drop.md\n!secrets.md\n");
673        write(&root, "sub/keep.md", "keep");
674        write(&root, "sub/drop.md", "drop");
675        write(&root, "sub/secrets.md", "secret");
676        write(&root, "cache/note.md", "cached");
677        let matcher = matcher_at(&root);
678        assert_eq!(matcher.collect_files(), vec![root.join("sub/keep.md")]);
679        for name in ["sub/drop.md", "sub/secrets.md", "cache/note.md"] {
680            assert!(matcher.is_excluded(&root.join(name)));
681        }
682        fs::remove_file(root.join(".ignore")).unwrap();
683        fs::remove_file(root.join(".ragfsignore")).unwrap();
684        assert!(matcher.should_process(&root.join("sub/keep.md")));
685    }
686    #[test]
687    fn unreadable_walk_entry_emits_warning() {
688        use std::io::Write;
689        use std::sync::{Arc, Mutex};
690        #[derive(Clone)]
691        struct Capture(Arc<Mutex<Vec<u8>>>);
692        impl Write for Capture {
693            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
694                self.0.lock().unwrap().extend_from_slice(bytes);
695                Ok(bytes.len())
696            }
697            fn flush(&mut self) -> std::io::Result<()> {
698                Ok(())
699            }
700        }
701        let bytes = Arc::new(Mutex::new(Vec::new()));
702        let capture = Capture(bytes.clone());
703        let subscriber = tracing_subscriber::fmt()
704            .without_time()
705            .with_ansi(false)
706            .with_writer(move || capture.clone())
707            .finish();
708        let temp = tempdir().unwrap();
709        // A missing entry is deterministic even when tests run as root.
710        let matcher = matcher_at(&temp.path().join("missing"));
711        tracing::subscriber::with_default(subscriber, || {
712            assert!(matcher.collect_files().is_empty());
713        });
714        let log = String::from_utf8(bytes.lock().unwrap().clone()).unwrap();
715        assert!(log.contains("Cannot read index entry"), "{log}");
716    }
717    #[test]
718    fn directory_override_also_excludes_direct_child_events() {
719        let temp = tempdir().unwrap();
720        write(temp.path(), "cache/note.md", "cached");
721        let matcher = ExclusionMatcher::new(
722            temp.path(),
723            ExclusionOptions {
724                extra_excludes: vec!["cache/".into()],
725                ..ExclusionOptions::default()
726            },
727        );
728        assert!(matcher.is_excluded(&temp.path().join("cache/note.md")));
729        assert!(matcher.collect_files().is_empty());
730    }
731}