voom 0.14.1

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
//! 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::path::{Path, PathBuf};
use std::sync::RwLock;
use std::sync::atomic::{AtomicUsize, Ordering};

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

mod selection;
mod verdict;

pub use selection::ArtifactId;
pub use selection::Selection;
pub use verdict::{Finding, Provenance, SkipReason, TAGGED_ID, Verdict};

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

/// 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,
    };
}

/// 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 weigh(
                id,
                self.prove(root, path, anchor_dir, id),
                self.selection.is_enabled(id),
            ) {
                Weighed::Proven(marker_dir) => {
                    return Verdict::Artifact(Finding {
                        path: path.to_path_buf(),
                        provenance: Provenance::Anchored {
                            artifact: id,
                            marker_dir,
                        },
                    });
                }
                Weighed::Skipped(rank, reason) => record(rank, reason),
            }
        }

        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, candidate: &Path, anchor_dir: &Path, id: ArtifactId) -> Proof {
        let bit = 1_u32 << id.ecosystem;
        let anchor = id.artifact().anchor_in(id.ecosystem());

        // `Inside` looks down rather than up: the directory that would prove the candidate is
        // the candidate. There is no climb and no ancestor to fall back on, so one probe
        // settles it — of a directory the walker prunes and never enumerates, which is why
        // this is affordable at all.
        if anchor.is_inside() {
            let facts = self.facts(candidate);
            return if facts.markers & bit != 0 {
                Proof::Found(candidate.to_path_buf())
            } else if facts.readable {
                Proof::Missing
            } else {
                Proof::Unreadable
            };
        }

        if anchor.is_workspace_root() {
            return self.prove_workspace_root(root, anchor_dir, bit);
        }

        let levels = anchor.levels();
        let mut dir = anchor_dir;
        let mut unreadable = false;
        // Whether the climb ran out of *tree* rather than out of *permission to climb*. The
        // difference is the whole point: one means nothing above proves it, the other means
        // voom stopped looking while there was still tree left.
        let mut exhausted_tree = 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 {
                exhausted_tree = true;
                break;
            }
            let Some(parent) = dir.parent() else {
                exhausted_tree = true;
                break;
            };
            dir = parent;
        }

        if unreadable {
            Proof::Unreadable
        } else if exhausted_tree || levels == 0 {
            Proof::Missing
        } else {
            // Climbed the full bound with the scan root still above. Reported apart from a
            // plain missing marker because the reader's situation is different and, until now,
            // indistinguishable: an artifact past the bound is not merely unswept, it looks
            // exactly like a directory that was never this ecosystem's at all.
            Proof::BoundReached(levels)
        }
    }

    /// Climbs from the anchor towards the scan root looking for a marker, with no level bound.
    fn prove_workspace_root(&self, root: &Path, anchor_dir: &Path, bit: u32) -> Proof {
        // `WorkspaceRoot` climbs with no level bound, all the way to the scan root. Unlike the
        // bounded loop below, running out of climb here always means the marker genuinely is
        // not above this candidate within the scanned tree — there is no bound left to report
        // as reached, because none was imposed. See `Anchor::WorkspaceRoot`'s doc comment.
        let mut dir = anchor_dir;
        let mut unreadable = false;
        loop {
            let facts = self.facts(dir);
            if facts.markers & bit != 0 {
                return Proof::Found(dir.to_path_buf());
            }
            unreadable |= !facts.readable;
            // Stop at the scan root, and never climb past it: a root spelling that does not
            // compare equal to `dir` must not let the climb walk above the scanned tree and
            // prove an artifact from a marker outside it.
            if dir == root || !dir.starts_with(root) {
                break;
            }
            let Some(parent) = dir.parent() else { break };
            dir = parent;
        }
        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,
    /// The `Ancestor(n)` climb used all `n` levels and the scan root was still above it.
    BoundReached(u8),
    Unreadable,
}

/// What one candidate artifact came to once its proof and its enablement are both known.
enum Weighed {
    /// Proven and enabled: the marker directory that justifies removal.
    Proven(PathBuf),
    /// Not removable, with the rank of the reason and the reason itself.
    Skipped(u8, SkipReason),
}

/// Combines a proof with whether the artifact is enabled into either a finding or a ranked skip.
fn weigh(id: ArtifactId, proof: Proof, enabled: bool) -> Weighed {
    let artifact = id.artifact();
    let not_enabled = || SkipReason::NotEnabled {
        spec: id.spec(),
        note: artifact.note,
    };
    match (proof, enabled) {
        (Proof::Found(marker_dir), true) => Weighed::Proven(marker_dir),
        (Proof::Found(_), false) => Weighed::Skipped(RANK_PROVEN_OPT_IN, not_enabled()),
        (Proof::Missing, true) => Weighed::Skipped(RANK_NO_MARKER, unproven(id)),
        (Proof::BoundReached(levels), true) => Weighed::Skipped(
            RANK_NO_MARKER,
            SkipReason::MarkerOutOfReach {
                ecosystem: id.ecosystem().id,
                markers: id.ecosystem().markers,
                levels,
            },
        ),
        (Proof::BoundReached(_) | Proof::Missing, false) => Weighed::Skipped(RANK_UNPROVEN_OPT_IN, not_enabled()),
        (Proof::Unreadable, _) => Weighed::Skipped(RANK_UNREADABLE, SkipReason::Unreadable),
    }
}

/// The reason to report when a selected artifact's marker was looked for and not found.
///
/// Which sentence is right depends on *where* the search happened, so it is decided here rather
/// than at the two call sites that would otherwise both have to remember.
fn unproven(id: ArtifactId) -> SkipReason {
    let ecosystem = id.ecosystem().id;
    let markers = id.ecosystem().markers;
    if id.artifact().anchor_in(id.ecosystem()).is_inside() {
        SkipReason::NoInnerMarker { ecosystem, markers }
    } else {
        SkipReason::NoMarker { ecosystem, markers }
    }
}

/// 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::MarkerOutOfReach { ecosystem, levels, .. }) => {
                assert_eq!(ecosystem, "dotnet");
                assert_eq!(levels, 3, "and it names the bound it stopped at");
            }
            other => panic!("expected an out-of-reach skip four levels down, got {other:?}"),
        }
    }

    /// The distinction the previous test rests on: a climb that ran out of *tree* is a plain
    /// missing marker, and only one that ran out of *bound* is out of reach. Reporting both the
    /// same way is what made an artifact past the bound indistinguishable from a directory that
    /// was never this ecosystem's.
    #[test]
    fn should_report_a_plain_missing_marker_when_the_climb_reached_the_scan_root() {
        let fixture = tree(&["a/obj/"]);
        let classifier = classifier();

        match verdict(&classifier, fixture.path(), "a/obj") {
            Verdict::Skip(SkipReason::NoMarker { ecosystem, .. }) => assert_eq!(ecosystem, "dotnet"),
            other => panic!("the root was reached, so nothing above proves it: got {other:?}"),
        }
    }

    /// A `Sibling` anchor has no bound to reach — the marker is beside it or it is not.
    #[test]
    fn should_never_report_a_sibling_anchor_as_out_of_reach() {
        let fixture = tree(&["a/b/target/"]);
        let classifier = classifier();

        match verdict(&classifier, fixture.path(), "a/b/target") {
            Verdict::Skip(SkipReason::NoMarker { .. }) => {}
            other => panic!("expected a plain missing marker for a sibling anchor, 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/"]);
        // `vendor/bundle/` is opt-in — installed gems cost a `bundle install` to restore — so
        // the multi-segment path has to be asked for before it can be classified.
        let mut selection = Selection::all();
        assert!(selection.set("ruby.vendor-bundle", true), "the spec exists");
        let classifier = Classifier::new(selection).expect("the catalog compiles");
        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(), "a deselected ecosystem declares no unknown specs");
        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")));
    }
}