voom 0.2.0

Fast, safe, parallel build-artifact pruning across every major language ecosystem
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
//! Marker anchoring: candidate + markers -> verdict.
//!
//! This is the rail the whole tool rests on. A directory is an artifact **only** when a marker
//! file proves its ecosystem at the position that ecosystem declares. The name alone is never
//! enough — a survey of one workspace found 41 directories named `bin`, 20 named `vendor` and
//! 12 named `obj`, each build output in one ecosystem and hand-written source in another.
//! See `adrs/0002-marker-anchored-classification.md`.
//!
//! Two things make this cheap enough to run over `$HOME`:
//!
//! - **Candidates are rejected by name first.** [`NameMatcher`] answers "could this entry be an
//!   artifact at all?" with a hash lookup over the entry's raw bytes. The overwhelming majority
//!   of entries stop there, having allocated nothing.
//! - **Directory facts are probed once and memoized.** A single `read_dir` of an anchor
//!   directory answers the marker question for *every* ecosystem at once, packed into a `u32`
//!   bitmask, and answers `voom.toml` discovery (ADR 0004) from the same pass. Only anchor
//!   directories are ever probed, and each is probed at most once per run — so an `Ancestor(n)`
//!   lookup in a deep tree does not re-check the same parents for every sibling.

use std::collections::HashMap;
use std::ffi::OsStr;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::RwLock;
use std::sync::atomic::{AtomicUsize, Ordering};

use crate::catalog::{self, Artifact, CATALOG, Ecosystem};
use crate::error::Result;
use crate::names::NameMatcher;

/// The per-directory configuration file discovered during the walk (ADR 0004).
pub const CONFIG_FILE_NAME: &str = "voom.toml";

/// Identifies one artifact declaration: an index into [`CATALOG`] and into that entry's
/// `artifacts`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ArtifactId {
    ecosystem: u8,
    artifact: u8,
}

impl ArtifactId {
    /// The catalog entry this artifact belongs to.
    ///
    /// # Panics
    ///
    /// Never in practice: ids are only minted by [`Classifier::new`] from the catalog itself.
    #[must_use]
    pub fn ecosystem(self) -> &'static Ecosystem {
        &CATALOG[self.ecosystem as usize]
    }

    /// The artifact declaration.
    #[must_use]
    pub fn artifact(self) -> &'static Artifact {
        &self.ecosystem().artifacts[self.artifact as usize]
    }

    /// The `<ecosystem>.<artifact>` spelling used in configuration and in `voom catalog`.
    #[must_use]
    pub fn spec(self) -> String {
        format!("{}.{}", self.ecosystem().id, self.artifact().slug())
    }

    /// Resolves an `<ecosystem>.<artifact>` spec back to a declaration.
    ///
    /// Returns `None` for anything the catalog does not answer to, so a typo in configuration
    /// surfaces as a rejected key rather than a rule that silently matches nothing.
    #[must_use]
    pub fn from_spec(spec: &str) -> Option<Self> {
        let (ecosystem_id, artifact_slug) = spec.split_once('.')?;
        let index = CATALOG.iter().position(|ecosystem| ecosystem.id == ecosystem_id)?;
        let offset = CATALOG[index]
            .artifacts
            .iter()
            .position(|artifact| artifact.slug() == artifact_slug)?;
        Some(Self {
            ecosystem: u8::try_from(index).ok()?,
            artifact: u8::try_from(offset).ok()?,
        })
    }
}

/// Which catalog entries participate in a run.
///
/// Starts from the catalog's own `default_on` flags and is narrowed or widened by
/// configuration and flags. Kept separate from the catalog so the table stays pure data.
#[derive(Debug, Clone)]
pub struct Selection {
    ecosystems: u32,
    overrides: HashMap<ArtifactId, bool>,
    permissive: bool,
}

impl Default for Selection {
    fn default() -> Self {
        Self::all()
    }
}

impl Selection {
    /// Every ecosystem participating, each artifact at its catalog default.
    #[must_use]
    pub fn all() -> Self {
        let ecosystems = if CATALOG.len() >= u32::BITS as usize {
            u32::MAX
        } else {
            (1 << CATALOG.len()) - 1
        };
        Self {
            ecosystems,
            overrides: HashMap::new(),
            permissive: false,
        }
    }

    /// Only the named ecosystems participate. Unknown ids are returned rather than ignored,
    /// because a typo in `--ecosystem` should fail loudly rather than silently sweep nothing.
    #[must_use]
    pub fn only<'a>(ids: impl IntoIterator<Item = &'a str>) -> (Self, Vec<String>) {
        let mut selection = Self {
            ecosystems: 0,
            overrides: HashMap::new(),
            permissive: false,
        };
        let mut unknown = Vec::new();
        for id in ids {
            match CATALOG.iter().position(|ecosystem| ecosystem.id == id) {
                Some(index) => selection.ecosystems |= 1 << index,
                None => unknown.push(id.to_owned()),
            }
        }
        (selection, unknown)
    }

    /// Treats every artifact as on unless something turns it off.
    ///
    /// Classification runs permissively so that a `voom.toml` deeper in the tree can still
    /// enable an off-by-default artifact — the final decision is made per artifact against the
    /// configuration resolved at its own location (ADR 0004). It never widens what the command
    /// line allowed, because flags are applied above every configuration layer.
    #[must_use]
    pub fn permissive(mut self) -> Self {
        self.permissive = true;
        self
    }

    /// Overrides one artifact's participation, by `<ecosystem>.<artifact>` spec or by bare
    /// ecosystem id (which sets every artifact of that ecosystem). Returns `false` if nothing
    /// in the catalog answers to the spec.
    ///
    /// **A bare ecosystem id never widens to a dependency directory.** `--enable node` means
    /// "turn on node's off-by-default build output", and before ADR 0001's amendment there was
    /// nothing else it could mean. Letting it now also reach `node_modules/` would make a
    /// `voom.toml` written against 0.1.0 — `[ecosystems] enable = ["go"]`, to get `go.bin` —
    /// start deleting a checked-in `vendor/` on upgrade, silently and in the delete direction.
    /// Those five artifacts are reachable only by their own `<ecosystem>.<artifact>` spec, or
    /// by `--clean-dependencies`, which expands to exactly those specs.
    ///
    /// The restriction is on widening only. A bare id still turns an ecosystem *off* whole,
    /// because narrowing is always safe.
    pub fn set(&mut self, spec: &str, enabled: bool) -> bool {
        let (ecosystem_id, artifact_slug) = match spec.split_once('.') {
            Some((ecosystem_id, artifact_slug)) => (ecosystem_id, Some(artifact_slug)),
            None => (spec, None),
        };
        let Some(index) = CATALOG.iter().position(|ecosystem| ecosystem.id == ecosystem_id) else {
            return false;
        };
        let ecosystem = &CATALOG[index];
        let mut matched = false;
        for (offset, artifact) in ecosystem.artifacts.iter().enumerate() {
            if artifact_slug.is_some_and(|slug| artifact.slug() != slug) {
                continue;
            }
            if artifact_slug.is_none()
                && enabled
                && crate::catalog::is_dependency_artifact(&format!("{ecosystem_id}.{}", artifact.slug()))
            {
                continue;
            }
            let Ok(ecosystem_index) = u8::try_from(index) else {
                continue;
            };
            let Ok(artifact_index) = u8::try_from(offset) else {
                continue;
            };
            self.overrides.insert(
                ArtifactId {
                    ecosystem: ecosystem_index,
                    artifact: artifact_index,
                },
                enabled,
            );
            matched = true;
        }
        if matched && enabled {
            self.ecosystems |= 1 << index;
        }
        matched
    }

    /// Whether this artifact's ecosystem participates at all.
    ///
    /// Checked before marker resolution so a deselected ecosystem never costs a `read_dir`.
    #[must_use]
    pub fn ecosystem_enabled(&self, id: ArtifactId) -> bool {
        self.ecosystems & (1 << id.ecosystem) != 0
    }

    /// Whether this artifact participates.
    #[must_use]
    pub fn is_enabled(&self, id: ArtifactId) -> bool {
        if !self.ecosystem_enabled(id) {
            return false;
        }
        self.overrides
            .get(&id)
            .copied()
            .unwrap_or_else(|| self.permissive || id.artifact().default_on)
    }
}

/// What one `read_dir` of a directory told us, cached for the rest of the run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DirFacts {
    /// Bit `i` set means `CATALOG[i]`'s marker glob matched a name in this directory.
    markers: u32,
    /// Whether the directory could be listed at all. An unreadable directory proves nothing,
    /// which means its candidates survive — the safe direction.
    readable: bool,
}

impl DirFacts {
    const UNREADABLE: Self = Self {
        markers: 0,
        readable: false,
    };
}

/// What the classifier concluded about one directory entry.
///
/// `#[non_exhaustive]` because a new verdict is a change this design expects to make, and after
/// 0.1.0 adding one to a bare enum would break every downstream `match` that has no wildcard.
/// [`Error`](crate::error::Error) and [`SkipReason`] carry it for the same reason.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Verdict {
    /// A marker proved it. This is the only verdict that can lead to a deletion.
    Artifact(Finding),
    /// It looked like an artifact but something held it back, with the reason.
    Skip(SkipReason),
    /// Its name matches nothing in the catalog. The common case, and the cheap one.
    NotACandidate,
}

/// What entitles voom to remove a path.
///
/// An enum rather than an optional [`ArtifactId`] so that the two cases cannot be confused at a
/// call site. Every reporter has to match on it, which means no output path can be added that
/// forgets to say a deletion was never proved by a marker.
///
/// `#[non_exhaustive]` because a third route to removal is plausible — ADR 0004 already
/// separates the two that exist — and adding one after 0.1.0 would otherwise be a breaking
/// change for every downstream matcher.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Provenance {
    /// A marker file proved the ecosystem at the declared anchor — ADR 0002's central rule, and
    /// the only route voom ever takes on its own.
    Anchored {
        /// Which catalog declaration proved it.
        artifact: ArtifactId,
        /// The directory whose marker did the proving, for `--verbose` and for JSON.
        marker_dir: PathBuf,
    },
    /// A configured `include` named it, so no marker was required.
    ///
    /// ADR 0004 makes this the only route to unanchored deletion and calls it a loaded foot-gun
    /// by design: the user has said what they mean and owns the result. Reports label it, which
    /// is why the pattern is carried here rather than discarded.
    Included {
        /// The `include` pattern that matched.
        pattern: String,
    },
}

/// An artifact voom is entitled to remove.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    /// The path to remove.
    pub path: PathBuf,
    /// What entitles voom to remove it.
    pub provenance: Provenance,
}

impl Finding {
    /// The catalog declaration that proved it, if a marker did.
    #[must_use]
    pub fn artifact(&self) -> Option<ArtifactId> {
        match &self.provenance {
            Provenance::Anchored { artifact, .. } => Some(*artifact),
            Provenance::Included { .. } => None,
        }
    }

    /// The ecosystem that claimed it, if one did.
    #[must_use]
    pub fn ecosystem(&self) -> Option<&'static str> {
        self.artifact().map(|id| id.ecosystem().id)
    }
}

/// Why a candidate was not removed.
///
/// Variants are the machine-readable reason codes ADR 0007 puts in JSON, so they are defined
/// once here and rendered by both reporters rather than restated in either.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SkipReason {
    /// No marker proved the ecosystem — ADR 0002's central rule doing its job.
    NoMarker {
        /// The ecosystem that would have claimed it.
        ecosystem: &'static str,
        /// The markers that would have proved it.
        markers: &'static [&'static str],
    },
    /// The artifact is off by default, or the ecosystem was not selected.
    NotEnabled {
        /// The `<ecosystem>.<artifact>` spec that would enable it.
        spec: String,
        /// Why it is off by default, when the catalog says.
        note: Option<&'static str>,
    },
    /// It is a machine-global tool cache or an installed toolchain (ADR 0001).
    ToolCache,
    /// A configured `exclude` matched.
    Excluded {
        /// The pattern that matched.
        pattern: String,
    },
    /// A keep policy held it.
    KeptByPolicy {
        /// Which rule — `min_age`, `min_size`, `max_size`.
        rule: &'static str,
        /// The comparison in human terms.
        detail: String,
    },
    /// It sits on a different filesystem than the scan root.
    FilesystemBoundary,
    /// It is a symlink, which is never followed and never deleted through.
    Symlink,
    /// Another artifact that is being removed already contains it.
    ///
    /// Only the opt-in dependency artifacts can produce this. The catalog declares build output
    /// *inside* two dependency directories (Ruby's `vendor/bundle/`, Julia's `deps/build/`), so
    /// enabling the outer directory as well makes the inner one redundant — and removing both
    /// would count its bytes twice and then refuse the second as `Vanished`.
    Covered {
        /// The artifact that contains it.
        by: PathBuf,
    },
    /// Its anchor directory could not be listed, so nothing could prove it.
    Unreadable,
}

impl SkipReason {
    /// The stable, enum-like code emitted in JSON so hooks can branch without parsing prose.
    #[must_use]
    pub fn code(&self) -> &'static str {
        match self {
            Self::NoMarker { .. } => "no_marker",
            Self::NotEnabled { .. } => "not_enabled",
            Self::ToolCache => "tool_cache",
            Self::Excluded { .. } => "excluded",
            Self::KeptByPolicy { .. } => "kept_by_policy",
            Self::FilesystemBoundary => "filesystem_boundary",
            Self::Symlink => "symlink",
            Self::Covered { .. } => "covered",
            Self::Unreadable => "unreadable",
        }
    }
}

impl fmt::Display for SkipReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoMarker { ecosystem, markers } => {
                write!(f, "no {ecosystem} marker ({}) proves it", markers.join(", "))
            }
            // Deliberately not "off by default": this fires both for a catalog default and
            // for an artifact configuration turned off, and claiming the former when it was
            // the latter sends the user to the wrong file.
            Self::NotEnabled { spec, note } => match note {
                Some(note) => write!(f, "not enabled — {note} Enable with `{spec}`"),
                None => write!(f, "not enabled — enable with `{spec}`"),
            },
            Self::ToolCache => write!(f, "a tool cache, not build output — `--caches` sweeps these too"),
            Self::Excluded { pattern } => write!(f, "excluded by `{pattern}`"),
            Self::KeptByPolicy { rule, detail } => write!(f, "kept by {rule} ({detail})"),
            Self::FilesystemBoundary => write!(f, "on a different filesystem than the scan root"),
            Self::Symlink => write!(f, "is a symlink"),
            // The final component only: the covering artifact is always an ancestor of the path
            // this line already names, and the renderer prints that one relative to the scan
            // root — repeating the absolute path here would be the longest string on the line
            // and would say nothing the reader cannot see.
            Self::Covered { by } => {
                write!(
                    f,
                    "already inside {}",
                    by.file_name().unwrap_or(by.as_os_str()).display()
                )
            }
            Self::Unreadable => write!(f, "its anchor directory could not be read"),
        }
    }
}

/// Resolves candidates against markers, memoizing what it learns about each directory.
#[derive(Debug)]
pub struct Classifier {
    artifacts: NameMatcher<ArtifactId>,
    markers: NameMatcher<u8>,
    selection: Selection,
    /// `(dependency directory name, artifact declared inside it)`.
    nested_in_dependencies: Vec<(&'static str, ArtifactId)>,
    facts: RwLock<HashMap<PathBuf, DirFacts>>,
    probes: AtomicUsize,
}

impl Classifier {
    /// Indexes the catalog for the given selection.
    ///
    /// # Errors
    ///
    /// [`crate::error::Error::CatalogPattern`] if a catalog pattern will not compile. That is a
    /// bug in voom rather than in the user's tree, and the catalog tests exist to prevent it.
    pub fn new(selection: Selection) -> Result<Self> {
        let mut artifact_patterns = Vec::new();
        let mut marker_patterns = Vec::new();
        let mut nested_in_dependencies = Vec::new();

        for (index, ecosystem) in CATALOG.iter().enumerate() {
            let Ok(ecosystem_index) = u8::try_from(index) else {
                continue;
            };
            for marker in ecosystem.markers {
                marker_patterns.push((*marker, ecosystem_index));
            }
            for (offset, artifact) in ecosystem.artifacts.iter().enumerate() {
                let Ok(artifact_index) = u8::try_from(offset) else {
                    continue;
                };
                // Candidates are keyed on the artifact's *last* segment; any leading segments
                // are verified against the entry's ancestors once a name matches.
                let last = artifact
                    .path
                    .trim_end_matches('/')
                    .rsplit('/')
                    .next()
                    .unwrap_or(artifact.path);
                let id = ArtifactId {
                    ecosystem: ecosystem_index,
                    artifact: artifact_index,
                };
                artifact_patterns.push((last, id));

                if artifact.depth() > 1
                    && let Some(first) = artifact.segments().next()
                    && let Some(dependency) = catalog::DEPENDENCY_DIRS.iter().find(|dir| **dir == first)
                {
                    nested_in_dependencies.push((*dependency, id));
                }
            }
        }

        Ok(Self {
            artifacts: NameMatcher::build(artifact_patterns)?,
            markers: NameMatcher::build(marker_patterns)?,
            selection,
            nested_in_dependencies,
            facts: RwLock::new(HashMap::new()),
            probes: AtomicUsize::new(0),
        })
    }

    /// How many directories have actually been listed.
    ///
    /// Marker resolution is the one place classification touches the filesystem, so this is
    /// the number that says whether memoization is working: it must stay proportional to the
    /// number of *anchor* directories, not to the number of candidates or entries.
    #[must_use]
    pub fn probe_count(&self) -> usize {
        self.probes.load(Ordering::Relaxed)
    }

    /// The selection this classifier was built with.
    #[must_use]
    pub fn selection(&self) -> &Selection {
        &self.selection
    }

    /// Artifacts the catalog declares *inside* a dependency directory of this name.
    ///
    /// ADR 0001 keeps dependency caches out of scope and ADR 0005 prunes them at the directory
    /// level, but two catalog entries name build output that lives inside one — Ruby's
    /// `vendor/bundle/` and Julia's `deps/build/`. Without this the walker would prune the
    /// parent and those two entries would be permanently unreachable. The scanner checks these
    /// specific paths and then prunes as usual, so nothing else below is ever walked.
    /// Returns an empty `Vec` — which does not allocate — for the overwhelming majority of
    /// dependency directories, which declare nothing.
    #[must_use]
    pub fn artifacts_inside(&self, name: &OsStr) -> Vec<ArtifactId> {
        self.nested_in_dependencies
            .iter()
            .filter(|(dir, _)| name == OsStr::new(*dir))
            .map(|(_, id)| *id)
            .collect()
    }

    /// Decides what one directory entry is.
    ///
    /// `root` bounds the search: a marker above the scan root never proves an artifact inside
    /// it, because voom must not justify a deletion with evidence from a tree it was not
    /// pointed at.
    pub fn classify(&self, root: &Path, path: &Path, is_dir: bool) -> Verdict {
        let Some(name) = path.file_name() else {
            return Verdict::NotACandidate;
        };

        // `Vec::new()` does not allocate; the first push only happens for a real candidate,
        // which is a small fraction of the entries the walker produces.
        let mut candidates: Vec<ArtifactId> = Vec::new();
        self.artifacts.for_each_match(name, |id| candidates.push(id));
        if candidates.is_empty() {
            return Verdict::NotACandidate;
        }
        candidates.sort_unstable();

        // A candidate name can belong to several ecosystems (`target/` is Rust's, Maven's and
        // sbt's; `bin/` is Go's and .NET's). Only one of them usually applies, so when none
        // proves out we report the *most useful* reason rather than the first: an artifact
        // whose ecosystem is genuinely present but which is off by default outranks a missing
        // marker for an ecosystem that was never plausible here.
        let mut best: Option<(u8, SkipReason)> = None;
        let mut record = |rank: u8, reason: SkipReason| {
            if best.as_ref().is_none_or(|(existing, _)| rank < *existing) {
                best = Some((rank, reason));
            }
        };

        for id in candidates {
            let artifact = id.artifact();
            if artifact.requires_dir() && !is_dir {
                continue;
            }
            let Some(anchor_dir) = anchor_dir(path, artifact) else {
                continue;
            };
            if !anchor_dir.starts_with(root) {
                continue;
            }
            // An ecosystem the user did not select is not worth a directory listing to
            // disprove, so this check comes before any probing.
            if !self.selection.ecosystem_enabled(id) {
                record(
                    RANK_ECOSYSTEM_OFF,
                    SkipReason::NotEnabled {
                        spec: id.spec(),
                        note: artifact.note,
                    },
                );
                continue;
            }

            match (self.prove(root, anchor_dir, id), self.selection.is_enabled(id)) {
                (Proof::Found(marker_dir), true) => {
                    return Verdict::Artifact(Finding {
                        path: path.to_path_buf(),
                        provenance: Provenance::Anchored {
                            artifact: id,
                            marker_dir,
                        },
                    });
                }
                (Proof::Found(_), false) => {
                    record(
                        RANK_PROVEN_OPT_IN,
                        SkipReason::NotEnabled {
                            spec: id.spec(),
                            note: artifact.note,
                        },
                    );
                }
                (Proof::Missing, true) => record(
                    RANK_NO_MARKER,
                    SkipReason::NoMarker {
                        ecosystem: id.ecosystem().id,
                        markers: id.ecosystem().markers,
                    },
                ),
                (Proof::Missing, false) => record(
                    RANK_UNPROVEN_OPT_IN,
                    SkipReason::NotEnabled {
                        spec: id.spec(),
                        note: artifact.note,
                    },
                ),
                (Proof::Unreadable, _) => record(RANK_UNREADABLE, SkipReason::Unreadable),
            }
        }

        best.map_or(Verdict::NotACandidate, |(_, reason)| Verdict::Skip(reason))
    }

    /// Looks for a marker at the artifact's declared anchor position.
    fn prove(&self, root: &Path, anchor_dir: &Path, id: ArtifactId) -> Proof {
        let bit = 1_u32 << id.ecosystem;
        let levels = id.artifact().anchor_in(id.ecosystem()).levels();
        let mut dir = anchor_dir;
        let mut unreadable = false;

        for _ in 0..=levels {
            let facts = self.facts(dir);
            if facts.markers & bit != 0 {
                return Proof::Found(dir.to_path_buf());
            }
            unreadable |= !facts.readable;
            if dir == root {
                break;
            }
            match dir.parent() {
                Some(parent) => dir = parent,
                None => break,
            }
        }

        if unreadable { Proof::Unreadable } else { Proof::Missing }
    }

    /// Everything we know about a directory, listing it exactly once per run.
    fn facts(&self, dir: &Path) -> DirFacts {
        if let Ok(cache) = self.facts.read()
            && let Some(facts) = cache.get(dir)
        {
            return *facts;
        }
        let facts = self.probe(dir);
        if let Ok(mut cache) = self.facts.write() {
            cache.insert(dir.to_path_buf(), facts);
        }
        facts
    }

    /// One `read_dir`, answering every marker question and `voom.toml` discovery at once.
    fn probe(&self, dir: &Path) -> DirFacts {
        self.probes.fetch_add(1, Ordering::Relaxed);
        let Ok(entries) = std::fs::read_dir(dir) else {
            return DirFacts::UNREADABLE;
        };
        let mut facts = DirFacts {
            markers: 0,
            readable: true,
        };
        for entry in entries.flatten() {
            self.markers
                .for_each_match(&entry.file_name(), |index| facts.markers |= 1_u32 << index);
        }
        facts
    }
}

/// Skip-reason precedence, lowest number reported. The ordering is the order of usefulness to
/// somebody asking "why didn't you take that?".
const RANK_PROVEN_OPT_IN: u8 = 0;
const RANK_NO_MARKER: u8 = 1;
const RANK_UNPROVEN_OPT_IN: u8 = 2;
const RANK_ECOSYSTEM_OFF: u8 = 3;
const RANK_UNREADABLE: u8 = 4;

/// The outcome of looking for a marker.
enum Proof {
    Found(PathBuf),
    Missing,
    Unreadable,
}

/// The directory an artifact anchors against: the candidate path with the artifact's own
/// relative path stripped off.
///
/// The artifact's last segment matched the entry's name, so this verifies the segments above it
/// and walks up. Leading segments are literals — `leading_artifact_segments_are_literal` in the
/// catalog tests keeps them that way, which is what lets this be a byte comparison.
fn anchor_dir<'p>(path: &'p Path, artifact: &Artifact) -> Option<&'p Path> {
    let mut dir = path.parent()?;
    for segment in artifact.path.trim_end_matches('/').rsplit('/').skip(1) {
        if dir.file_name()?.as_encoded_bytes() != segment.as_bytes() {
            return None;
        }
        dir = dir.parent()?;
    }
    Some(dir)
}

/// Whether a directory name is one of the dependency caches ADR 0001 puts out of scope.
#[must_use]
pub fn is_dependency_dir(name: &OsStr) -> bool {
    catalog::DEPENDENCY_DIRS.iter().any(|dir| name == OsStr::new(dir))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::tree;

    fn classifier() -> Classifier {
        Classifier::new(Selection::all()).unwrap()
    }

    /// Classifies a path inside the fixture, inferring whether it is a directory from disk.
    fn verdict(classifier: &Classifier, root: &Path, relative: &str) -> Verdict {
        let path = root.join(relative);
        let is_dir = path.is_dir();
        classifier.classify(root, &path, is_dir)
    }

    fn assert_artifact(verdict: &Verdict, ecosystem: &str, artifact: &str) {
        match verdict {
            Verdict::Artifact(finding) => {
                let id = finding.artifact().expect("a marker proved it");
                assert_eq!(id.ecosystem().id, ecosystem);
                assert_eq!(id.artifact().path, artifact);
            }
            other => panic!("expected an artifact verdict, got {other:?}"),
        }
    }

    #[test]
    fn should_classify_target_as_rust_when_cargo_toml_is_beside_it() {
        let fixture = tree(&["Cargo.toml", "target/"]);
        let classifier = classifier();
        let verdict = verdict(&classifier, fixture.path(), "target");
        assert_artifact(&verdict, "rust", "target/");
        match verdict {
            Verdict::Artifact(finding) => assert!(
                matches!(finding.provenance, Provenance::Anchored { marker_dir, .. } if marker_dir == fixture.path())
            ),
            other => panic!("expected an artifact verdict, got {other:?}"),
        }
    }

    /// The data-loss regression test. A `target/` with nothing proving it is somebody's data.
    #[test]
    fn should_not_classify_target_without_a_marker() {
        let fixture = tree(&["target/", "target/important.txt"]);
        let classifier = classifier();
        match verdict(&classifier, fixture.path(), "target") {
            Verdict::Skip(SkipReason::NoMarker { ecosystem, .. }) => {
                assert!(
                    ["rust", "maven", "scala"].contains(&ecosystem),
                    "unexpected ecosystem {ecosystem}"
                );
            }
            other => panic!("expected a no-marker skip, got {other:?}"),
        }
    }

    #[test]
    fn should_resolve_an_ambiguous_name_by_ecosystem_not_precedence() {
        let rust = tree(&["Cargo.toml", "target/"]);
        let maven = tree(&["pom.xml", "target/"]);
        let classifier = classifier();
        assert_artifact(&verdict(&classifier, rust.path(), "target"), "rust", "target/");
        assert_artifact(&verdict(&classifier, maven.path(), "target"), "maven", "target/");
    }

    #[test]
    fn should_report_a_missing_marker_rather_than_a_lesser_reason() {
        let fixture = tree(&["bin/"]);
        let classifier = classifier();
        // `bin/` is Go's (off by default) and .NET's (on). The .NET no-marker explanation is
        // more useful than Go's opt-in hint, so it wins.
        match verdict(&classifier, fixture.path(), "bin") {
            Verdict::Skip(SkipReason::NoMarker { ecosystem, .. }) => assert_eq!(ecosystem, "dotnet"),
            other => panic!("expected a no-marker skip, got {other:?}"),
        }
    }

    #[test]
    fn should_prove_dotnet_obj_through_an_ancestor_marker() {
        for depth in 0..=3 {
            let nesting = "src/".repeat(depth);
            let fixture = tree(&["App.csproj", &format!("{nesting}obj/")]);
            let classifier = classifier();
            let verdict = verdict(&classifier, fixture.path(), &format!("{nesting}obj"));
            assert_artifact(&verdict, "dotnet", "obj/");
        }
    }

    #[test]
    fn should_not_prove_dotnet_obj_beyond_the_ancestor_bound() {
        let fixture = tree(&["App.csproj", "a/b/c/d/obj/"]);
        let classifier = classifier();
        match verdict(&classifier, fixture.path(), "a/b/c/d/obj") {
            Verdict::Skip(SkipReason::NoMarker { ecosystem, .. }) => assert_eq!(ecosystem, "dotnet"),
            other => panic!("expected a no-marker skip four levels down, got {other:?}"),
        }
    }

    /// A marker outside the scanned tree must not justify a deletion inside it.
    #[test]
    fn should_not_climb_above_the_scan_root_for_a_marker() {
        let fixture = tree(&["App.csproj", "project/nested/obj/"]);
        let classifier = classifier();
        let root = fixture.path().join("project");
        let path = root.join("nested/obj");
        match classifier.classify(&root, &path, true) {
            Verdict::Skip(SkipReason::NoMarker { .. }) => {}
            other => panic!("expected the climb to stop at the scan root, got {other:?}"),
        }
    }

    #[test]
    fn should_prove_pycache_one_level_below_the_project_root() {
        let fixture = tree(&["pyproject.toml", "package/__pycache__/"]);
        let classifier = classifier();
        assert_artifact(
            &verdict(&classifier, fixture.path(), "package/__pycache__"),
            "python",
            "__pycache__/",
        );
    }

    #[test]
    fn should_verify_leading_segments_of_a_multi_segment_artifact() {
        let matching = tree(&["Gemfile", "vendor/bundle/"]);
        let classifier = classifier();
        assert_artifact(
            &verdict(&classifier, matching.path(), "vendor/bundle"),
            "ruby",
            "vendor/bundle/",
        );

        // The same trailing name in the wrong place is not the artifact.
        let elsewhere = tree(&["Gemfile", "lib/bundle/"]);
        assert_eq!(
            verdict(&classifier, elsewhere.path(), "lib/bundle"),
            Verdict::NotACandidate
        );
    }

    #[test]
    fn should_require_a_directory_for_a_slash_terminated_artifact() {
        let fixture = tree(&["Cargo.toml", "target"]);
        let classifier = classifier();
        assert_eq!(verdict(&classifier, fixture.path(), "target"), Verdict::NotACandidate);
    }

    #[test]
    fn should_match_a_file_artifact_that_is_not_slash_terminated() {
        let fixture = tree(&["package.json", "app.tsbuildinfo"]);
        let classifier = classifier();
        assert_artifact(
            &verdict(&classifier, fixture.path(), "app.tsbuildinfo"),
            "node",
            "*.tsbuildinfo",
        );
    }

    #[test]
    fn should_match_a_prefix_glob_artifact() {
        let fixture = tree(&["CMakeLists.txt", "cmake-build-debug/"]);
        let classifier = classifier();
        assert_artifact(
            &verdict(&classifier, fixture.path(), "cmake-build-debug"),
            "cmake",
            "cmake-build-*/",
        );
    }

    #[test]
    fn should_skip_an_off_by_default_artifact_and_say_how_to_enable_it() {
        let fixture = tree(&["go.mod", "bin/"]);
        let classifier = classifier();
        match verdict(&classifier, fixture.path(), "bin") {
            Verdict::Skip(SkipReason::NotEnabled { spec, note }) => {
                assert_eq!(spec, "go.bin");
                assert!(note.is_some(), "an opt-in artifact must explain itself");
            }
            other => panic!("expected an opt-in skip, got {other:?}"),
        }
    }

    #[test]
    fn should_remove_an_off_by_default_artifact_once_enabled() {
        let fixture = tree(&["go.mod", "bin/"]);
        let mut selection = Selection::all();
        assert!(selection.set("go.bin", true));
        let classifier = Classifier::new(selection).unwrap();
        assert_artifact(&verdict(&classifier, fixture.path(), "bin"), "go", "bin/");
    }

    #[test]
    fn should_not_classify_when_the_ecosystem_is_deselected() {
        let fixture = tree(&["Cargo.toml", "target/"]);
        let (selection, unknown) = Selection::only(["node"]);
        assert!(unknown.is_empty());
        let classifier = Classifier::new(selection).unwrap();
        match verdict(&classifier, fixture.path(), "target") {
            Verdict::Skip(SkipReason::NotEnabled { .. }) => {}
            other => panic!("expected a deselected skip, got {other:?}"),
        }
    }

    #[test]
    fn should_report_an_unknown_ecosystem_rather_than_ignoring_it() {
        let (_, unknown) = Selection::only(["rust", "rustlang"]);
        assert_eq!(unknown, vec!["rustlang".to_owned()]);
    }

    /// Memoization is the reason ADR 0002's safety costs almost nothing. Twenty siblings that
    /// all anchor on the same directory must list it once, not twenty times.
    #[test]
    fn should_list_each_anchor_directory_exactly_once() {
        let mut entries = vec!["Cargo.toml".to_owned()];
        for index in 0..20 {
            entries.push(format!("crate{index}/Cargo.toml"));
            entries.push(format!("crate{index}/target/"));
        }
        let refs: Vec<&str> = entries.iter().map(String::as_str).collect();
        let fixture = tree(&refs);
        let classifier = classifier();

        for index in 0..20 {
            assert_artifact(
                &verdict(&classifier, fixture.path(), &format!("crate{index}/target")),
                "rust",
                "target/",
            );
        }
        // One probe per crate directory, and none for the twenty `target/` directories
        // themselves — those are never anchors.
        assert_eq!(classifier.probe_count(), 20);
    }

    #[test]
    fn should_leave_an_unreadable_anchor_unproven() {
        let fixture = tree(&["Cargo.toml", "target/"]);
        let classifier = classifier();
        let missing = fixture.path().join("gone");
        // Classifying against an anchor that does not exist proves nothing, which means the
        // candidate survives — the safe direction when voom cannot tell.
        match classifier.classify(fixture.path(), &missing.join("target"), true) {
            Verdict::Skip(SkipReason::Unreadable) => {}
            other => panic!("expected an unreadable skip, got {other:?}"),
        }
    }

    #[test]
    fn should_treat_an_unrelated_name_as_not_a_candidate() {
        let fixture = tree(&["Cargo.toml", "src/"]);
        let classifier = classifier();
        assert_eq!(verdict(&classifier, fixture.path(), "src"), Verdict::NotACandidate);
        assert_eq!(
            classifier.probe_count(),
            0,
            "a non-candidate must not cost a directory listing"
        );
    }

    #[test]
    fn should_recognise_dependency_directories() {
        assert!(is_dependency_dir(OsStr::new("node_modules")));
        assert!(is_dependency_dir(OsStr::new("vendor")));
        assert!(!is_dependency_dir(OsStr::new("target")));
    }

    #[test]
    fn skip_reason_codes_are_stable() {
        assert_eq!(SkipReason::Symlink.code(), "symlink");
        assert_eq!(SkipReason::FilesystemBoundary.code(), "filesystem_boundary");
        assert_eq!(SkipReason::Unreadable.code(), "unreadable");
        assert_eq!(
            SkipReason::NoMarker {
                ecosystem: "rust",
                markers: &["Cargo.toml"]
            }
            .code(),
            "no_marker"
        );
    }
}