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
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
//! Merging the layers, and resolving what applies at one point in the tree.
//!
//! Two rules carry the semantics:
//!
//! - **Keep policies compose by narrowing, not replacing.** An override sets only the keys it
//!   names; the rest inherit. Replacement would mean a user who sets one key silently loses
//!   every other guard, which for a safety setting is the wrong failure.
//! - **Flags always win.** Configuration layers accumulate as an ordered list of operations,
//!   and the command line is applied after all of them at every point in the tree — so a
//!   `voom.toml` deep in the tree cannot override what the invocation asked for.

use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

use globset::{Glob, GlobMatcher};

use super::load::{Layer, Sources, read_in};
use super::schema::{EcosystemsSection, KeepTable};
use crate::catalog;
use crate::classify::{ArtifactId, Selection};
use crate::error::{Error, Result};
use crate::policy::{KeepPolicy, parse_duration, parse_size};

/// Command-line overrides, which sit above every configuration layer.
#[derive(Debug, Default, Clone)]
pub struct Flags {
    /// `--ecosystem`: when set, only these participate at all.
    pub ecosystems: Option<Vec<String>>,
    /// `--enable` specs.
    pub enable: Vec<String>,
    /// `--disable` specs.
    pub disable: Vec<String>,
    /// `--min-age`, `--min-size`, `--max-size`.
    pub keep: KeepPolicy,
    /// `--exclude` globs.
    pub exclude: Vec<String>,
    /// `--include` globs.
    pub include: Vec<String>,
    /// `--clean-caches` ids.
    pub clean_caches: Vec<String>,
    /// `--no-git`, as `Some(false)`. `None` leaves the decision to configuration.
    pub git: Option<bool>,
    /// `--no-bazel`, as `Some(false)`. `None` leaves the decision to configuration.
    pub bazel: Option<bool>,
    /// `--bazel-max-age`. `None` leaves the age to configuration.
    pub bazel_max_age: Option<std::time::Duration>,
    /// `--docker`, as `Some(true)`. `None` leaves the decision to configuration.
    pub docker: Option<bool>,
    /// `--docker-max-age`. `None` leaves the age to configuration.
    pub docker_max_age: Option<std::time::Duration>,
    /// `--clean-tagged`, as `Some(true)`. `None` leaves the decision to configuration.
    pub clean_tagged: Option<bool>,
}

/// One compiled `[[paths]]` rule.
#[derive(Debug, Clone)]
struct Rule {
    pattern: String,
    glob: GlobMatcher,
    keep: KeepPolicy,
    ops: Vec<(String, bool)>,
}

/// The configuration layers accumulated down to one directory, before flags.
#[derive(Debug, Default, Clone)]
struct Accumulated {
    /// Enable/disable operations in precedence order; later wins.
    ops: Vec<(String, bool)>,
    keep: KeepPolicy,
    keep_by_ecosystem: BTreeMap<String, KeepPolicy>,
    rules: Vec<Rule>,
    exclude: Vec<String>,
    include: Vec<String>,
    clean_caches: Vec<String>,
    git: Option<bool>,
    bazel: Option<bool>,
    bazel_max_age: Option<std::time::Duration>,
    docker: Option<bool>,
    docker_max_age: Option<std::time::Duration>,
    clean_tagged: Option<bool>,
    sources: Vec<PathBuf>,
}

/// The configuration in effect at one point in the tree, with flags applied.
#[expect(
    clippy::struct_excessive_bools,
    reason = "these mirror command-line flags, which are bools by nature"
)]
#[derive(Debug, Clone)]
pub struct Resolved {
    selection: Selection,
    keep: KeepPolicy,
    /// The keep policy the command line asked for, kept apart from the merged configuration so
    /// that [`Resolved::keep_for`] can apply it last. Folding it into `keep` alone is not
    /// enough: the per-ecosystem and `[[paths]]` overrides narrow that value afterwards, and
    /// narrowing lets the later value win — so a committed `voom.toml` could release an
    /// artifact that `--min-age` was holding.
    flags_keep: KeepPolicy,
    keep_by_ecosystem: BTreeMap<String, KeepPolicy>,
    rules: Vec<Rule>,
    /// Paths never scanned, absolute where the source made them so.
    pub exclude: Vec<String>,
    /// Paths swept without a marker — explicit user intent (ADR 0002).
    pub include: Vec<String>,
    /// Machine-global caches this run may remove, by id (ADR 0012). Empty unless asked.
    pub clean_caches: Vec<String>,
    /// Whether an ordinary sweep runs git housekeeping here (ADR 0011). On unless something
    /// turned it off.
    pub git: bool,
    /// Whether an ordinary sweep runs Bazel housekeeping (ADR 0014). On unless something turned
    /// it off.
    pub bazel: bool,
    /// How long an output base may go unbuilt in before the sweep treats it as stale. `None`
    /// means [`crate::bazel::DEFAULT_MAX_AGE`].
    pub bazel_max_age: Option<std::time::Duration>,
    /// Whether an ordinary sweep prunes Docker (ADR 0017). Off unless something turned it on.
    pub docker: bool,
    /// How old an unused Docker image or idle build-cache record must be. `None` means
    /// [`crate::docker::DEFAULT_MAX_AGE`].
    pub docker_max_age: Option<std::time::Duration>,
    /// Whether a `CACHEDIR.TAG` alone proves an artifact here (ADR 0013). Off unless asked.
    pub clean_tagged: bool,
    /// The files that contributed, in ascending precedence.
    pub sources: Vec<PathBuf>,
}

impl Resolved {
    /// Whether an artifact participates at this path.
    #[must_use]
    pub fn is_enabled(&self, path: &Path, id: ArtifactId) -> bool {
        let mut selection = None;
        for rule in &self.rules {
            if rule.ops.is_empty() || !rule.glob.is_match(path) {
                continue;
            }
            let selection = selection.get_or_insert_with(|| self.selection.clone());
            for (spec, enabled) in &rule.ops {
                selection.set(spec, *enabled);
            }
        }
        selection.as_ref().unwrap_or(&self.selection).is_enabled(id)
    }

    /// The keep policy for one artifact: the base, narrowed by its ecosystem's override, then
    /// by every matching `[[paths]]` rule in order — and finally by the command line, which
    /// outranks all of them.
    ///
    /// The flags go last because [`KeepPolicy::narrow`] lets the *later* value win, so applying
    /// them to the base alone would leave any config layer named after it free to overrule
    /// them. A repository that ships `[keep.rust] min_age = "0s"` could then release an
    /// artifact that the operator's `--min-age 30d` was holding, which inverts the precedence
    /// this module promises and does it in the unsafe direction.
    #[must_use]
    pub fn keep_for(&self, path: &Path, ecosystem: Option<&str>) -> KeepPolicy {
        let mut keep = self.keep;
        if let Some(per_ecosystem) = ecosystem.and_then(|id| self.keep_by_ecosystem.get(id)) {
            keep = keep.narrow(*per_ecosystem);
        }
        for rule in &self.rules {
            if rule.glob.is_match(path) {
                keep = keep.narrow(rule.keep);
            }
        }
        keep.narrow(self.flags_keep)
    }

    /// The base keep policy, for `voom config show`.
    #[must_use]
    pub fn keep(&self) -> KeepPolicy {
        self.keep
    }

    /// The base selection, for `voom config show`.
    #[must_use]
    pub fn selection(&self) -> &Selection {
        &self.selection
    }

    /// The per-ecosystem keep overrides, for `voom config show`.
    pub fn keep_overrides(&self) -> impl Iterator<Item = (&str, KeepPolicy)> {
        self.keep_by_ecosystem.iter().map(|(id, keep)| (id.as_str(), *keep))
    }

    /// The `[[paths]]` rules in precedence order, for `voom config show`.
    pub fn rules(&self) -> impl Iterator<Item = (&str, KeepPolicy, &[(String, bool)])> {
        self.rules
            .iter()
            .map(|rule| (rule.pattern.as_str(), rule.keep, rule.ops.as_slice()))
    }
}

/// Resolves configuration for any directory under a scan root, memoized.
#[derive(Debug)]
pub struct Resolver {
    root: PathBuf,
    flags: Flags,
    base: Accumulated,
    /// Set when `--config` named a file. The hierarchy is then off entirely — one file and no
    /// surprises is what an explicit flag should mean.
    explicit: bool,
    cache: RwLock<HashMap<PathBuf, Arc<Cached>>>,
}

#[derive(Debug)]
struct Cached {
    accumulated: Accumulated,
    effective: Arc<Resolved>,
}

impl Resolver {
    /// Builds the base layers for a root and validates everything they contain.
    ///
    /// # Errors
    ///
    /// [`Error::Config`] for an unparseable duration or size, an ecosystem id the catalog does
    /// not know, or an uncompilable glob — each naming the file it came from.
    pub fn new(root: &Path, sources: &Sources, flags: Flags) -> Result<Self> {
        let mut base = Accumulated::default();
        for layer in &sources.layers {
            apply(&mut base, layer)?;
        }
        Ok(Self {
            root: root.to_path_buf(),
            flags,
            base,
            explicit: sources.explicit,
            cache: RwLock::new(HashMap::new()),
        })
    }

    /// The configuration in effect at the scan root.
    ///
    /// # Errors
    ///
    /// Whatever [`Self::for_dir`] rejects.
    pub fn root_config(&self) -> Result<Arc<Resolved>> {
        let root = self.root.clone();
        self.for_dir(&root)
    }

    /// The configuration in effect in a directory: every `voom.toml` from the scan root down to
    /// it, nearest wins, with flags on top.
    ///
    /// Memoized per directory and derived from the parent's result, so a wide tree resolves in
    /// one pass rather than re-reading the same ancestors for every sibling.
    ///
    /// # Errors
    ///
    /// [`Error::Config`] if a `voom.toml` on the way down is broken.
    pub fn for_dir(&self, dir: &Path) -> Result<Arc<Resolved>> {
        Ok(self.cached(dir)?.effective.clone())
    }

    fn cached(&self, dir: &Path) -> Result<Arc<Cached>> {
        if let Ok(cache) = self.cache.read()
            && let Some(cached) = cache.get(dir)
        {
            return Ok(cached.clone());
        }

        let mut accumulated = if dir == self.root {
            self.base.clone()
        } else {
            match dir.parent() {
                // Stop at the scan root: a `voom.toml` above the tree voom was pointed at is
                // not part of this run.
                Some(parent) if dir.starts_with(&self.root) => self.cached(parent)?.accumulated.clone(),
                _ => self.base.clone(),
            }
        };

        if !self.explicit
            && let Some(layer) = read_in(dir)?
        {
            apply(&mut accumulated, &layer)?;
        }

        let effective = Arc::new(self.effective(&accumulated)?);
        let cached = Arc::new(Cached { accumulated, effective });
        if let Ok(mut cache) = self.cache.write() {
            cache.insert(dir.to_path_buf(), cached.clone());
        }
        Ok(cached)
    }

    /// Applies the command line on top of the accumulated layers.
    fn effective(&self, accumulated: &Accumulated) -> Result<Resolved> {
        let selection = self.selection(accumulated)?;

        // Appended, not layered above: `include` and `exclude` are sets whose members are
        // independent, and a flag naming one more directory does not contradict a config file
        // naming another. Precedence between the two lists is settled in the walker, where
        // `exclude` wins, and is unchanged by where either pattern came from.
        let mut exclude = accumulated.exclude.clone();
        exclude.extend(expand_flag_patterns(&self.flags.exclude, &self.root));
        let mut include = accumulated.include.clone();
        include.extend(expand_flag_patterns(&self.flags.include, &self.root));

        let (clean_caches, clear_all) = self.clean_caches(accumulated)?;

        Ok(Resolved {
            selection,
            keep: accumulated.keep.narrow(self.flags.keep),
            flags_keep: self.flags.keep,
            keep_by_ecosystem: accumulated.keep_by_ecosystem.clone(),
            rules: accumulated.rules.clone(),
            exclude,
            include,
            clean_caches,
            // Flags last, on the same principle as the selection above: no `voom.toml` below a
            // scan root may turn housekeeping back on for a run that was invoked with
            // `--no-git`. On by default, which is what makes it ordinary behaviour.
            git: self.flags.git.or(accumulated.git).unwrap_or(true),
            bazel: self.flags.bazel.or(accumulated.bazel).unwrap_or(true),
            bazel_max_age: self.flags.bazel_max_age.or(accumulated.bazel_max_age),
            docker: self.flags.docker.or(accumulated.docker).unwrap_or(false),
            docker_max_age: self.flags.docker_max_age.or(accumulated.docker_max_age),
            // A full cache clear includes relocated tagged build output. Named cache ids do
            // not widen the scan; an ordinary run still leaves tagged directories alone.
            clean_tagged: self
                .flags
                .clean_tagged
                .or_else(|| self.flags.clean_caches.iter().any(|id| id == "all").then_some(true))
                .or(accumulated.clean_tagged)
                .unwrap_or(clear_all),
            sources: accumulated.sources.clone(),
        })
    }

    /// The ecosystem selection: the `--only` base, then configuration operations, then flags.
    fn selection(&self, accumulated: &Accumulated) -> Result<Selection> {
        let mut selection = match &self.flags.ecosystems {
            Some(ids) => {
                let (selection, unknown) = Selection::only(ids.iter().map(String::as_str));
                if let Some(name) = unknown.first() {
                    return Err(Error::UnknownEcosystem { name: name.clone() });
                }
                selection
            }
            None => Selection::all(),
        };

        for (spec, enabled) in &accumulated.ops {
            selection.set(spec, *enabled);
        }
        // Flags last, so no configuration file can override the invocation — and within them,
        // `--disable` last, so the flag that says "not this" beats the flag that says "this".
        // The order used to be the other way round, which meant
        // `voom --clean-dependencies --disable node` still removed `node_modules/`: the group
        // flag expands to `--enable node.node_modules`, and enabling ran afterwards. For a tool
        // that deletes, the narrowing instruction has to be the one that wins.
        for spec in &self.flags.enable {
            if !selection.set(spec, true) {
                return Err(Error::UnknownEcosystem { name: spec.clone() });
            }
        }
        for spec in &self.flags.disable {
            if !selection.set(spec, false) {
                return Err(Error::UnknownEcosystem { name: spec.clone() });
            }
        }

        Ok(selection)
    }

    /// The cache ids to clear, with `all` expanded and exclusions applied, and whether `all` was named.
    fn clean_caches(&self, accumulated: &Accumulated) -> Result<(Vec<String>, bool)> {
        let mut clean_caches = accumulated.clean_caches.clone();
        clean_caches.extend(self.flags.clean_caches.iter().cloned());
        let clear_all = clean_caches.iter().any(|id| id == "all");
        if clear_all {
            clean_caches.retain(|id| id != "all");
            clean_caches.extend(
                crate::caches::CACHES
                    .iter()
                    .filter(|cache| cache.in_all)
                    .map(|cache| cache.id.to_owned()),
            );
            clean_caches.push(crate::caches::BAZEL_ID.to_owned());
        }
        // `-id` takes one back out, so `all,-bazel` is every cache without the machine-wide Bazel
        // clear — which stops running servers and so is the wrong half of `all` on a machine
        // where other work is building.
        let excluded: Vec<String> = clean_caches
            .iter()
            .filter_map(|id| id.strip_prefix('-').map(str::to_owned))
            .collect();
        // An exclusion subtracts from a set; with no positive id anywhere (neither a config
        // `enable` nor `all`), it subtracts from nothing, and the run would clear no cache while
        // reporting success. Rejected rather than treated as `all,-id`: a flag that names a cache
        // to take back out is not a request to clear the whole table.
        if !excluded.is_empty() && !clean_caches.iter().any(|id| !id.starts_with('-')) {
            return Err(Error::LoneCacheExclusion {
                id: excluded.first().cloned().unwrap_or_default(),
            });
        }
        clean_caches.retain(|id| !id.starts_with('-') && !excluded.contains(id));
        clean_caches.sort_unstable();
        clean_caches.dedup();
        let unknown = crate::caches::unknown_ids(&clean_caches)
            .into_iter()
            .chain(crate::caches::unknown_ids(&excluded))
            .collect::<Vec<_>>();
        if let Some(id) = unknown.first() {
            return Err(Error::UnknownCache { id: id.clone() });
        }

        Ok((clean_caches, clear_all))
    }
}

/// Folds one file into the accumulated layers, validating as it goes.
fn apply(accumulated: &mut Accumulated, layer: &Layer) -> Result<()> {
    let source = &layer.source;
    let dir = source.parent().unwrap_or(Path::new("."));

    for spec in &layer.file.ecosystems.disable {
        validate_spec(spec, source)?;
        accumulated.ops.push((spec.clone(), false));
    }
    for spec in &layer.file.ecosystems.enable {
        validate_spec(spec, source)?;
        accumulated.ops.push((spec.clone(), true));
    }

    // Later layer wins, matching every other scalar key: a repository's committed `voom.toml`
    // decides for its own subtree.
    if let Some(enabled) = layer.file.tagged.enabled {
        accumulated.clean_tagged = Some(enabled);
    }
    if let Some(enabled) = layer.file.git.enabled {
        accumulated.git = Some(enabled);
    }

    apply_machine_global(accumulated, layer)?;

    apply_keep(accumulated, layer)?;

    for pattern in &layer.file.exclude {
        accumulated.exclude.push(expand(pattern, dir));
    }
    for pattern in &layer.file.include {
        accumulated.include.push(expand(pattern, dir));
    }

    apply_rules(accumulated, layer, dir)?;

    accumulated.sources.push(source.clone());
    Ok(())
}

/// Folds the machine-global tables (`[bazel]`, `[docker]`, `[caches]`) of one file into the accumulated layers.
fn apply_machine_global(accumulated: &mut Accumulated, layer: &Layer) -> Result<()> {
    let source = &layer.source;

    // `[bazel]`, `[docker]` and `[caches]` drive removal outside the swept tree — machine-global
    // Bazel output bases, Docker state and tool caches. Only the user's own configuration or an explicit `--config`
    // may set them; a repository's committed `voom.toml` cannot, so cloning a repository can
    // never let it clear the machine's caches or Bazel state. A repository that tries is a hard
    // error rather than a silent no-op, so the file and the behaviour never disagree.
    if layer.user_level {
        if let Some(enabled) = layer.file.bazel.enabled {
            accumulated.bazel = Some(enabled);
        }
        if let Some(age) = &layer.file.bazel.max_age {
            accumulated.bazel_max_age = Some(crate::policy::parse_duration(age).map_err(|error| Error::Config {
                path: source.clone(),
                reason: format!("`[bazel] max_age`: {error}"),
            })?);
        }
        if let Some(enabled) = layer.file.docker.enabled {
            accumulated.docker = Some(enabled);
        }
        if let Some(age) = &layer.file.docker.max_age {
            accumulated.docker_max_age = Some(crate::policy::parse_duration(age).map_err(|error| Error::Config {
                path: source.clone(),
                reason: format!("`[docker] max_age`: {error}"),
            })?);
        }
        // Ids rather than paths, so nothing is expanded and nothing is per-directory: a cache is
        // machine-global and its location comes from the table, not from where the file sits.
        for id in &layer.file.caches.enable {
            accumulated.clean_caches.push(id.clone());
        }
    } else if layer.file.bazel.enabled.is_some()
        || layer.file.bazel.max_age.is_some()
        || layer.file.docker.enabled.is_some()
        || layer.file.docker.max_age.is_some()
        || !layer.file.caches.enable.is_empty()
    {
        return Err(Error::Config {
            path: source.clone(),
            reason: "`[bazel]`, `[docker]` and `[caches]` are machine-global and are read only from the user \
                     configuration or `--config`, never from a repository's `voom.toml`"
                .to_owned(),
        });
    }
    Ok(())
}

/// Folds the `[keep]` tables of one file into the accumulated layers.
fn apply_keep(accumulated: &mut Accumulated, layer: &Layer) -> Result<()> {
    let source = &layer.source;

    accumulated.keep = accumulated.keep.narrow(keep_from(&layer.file.keep.scalars(), source)?);
    for (id, table) in &layer.file.keep.per_ecosystem {
        if catalog::find(id).is_none() {
            return Err(Error::Config {
                path: source.clone(),
                reason: format!("`[keep.{id}]` is not a known ecosystem"),
            });
        }
        let policy = keep_from(table, source)?;
        let entry = accumulated.keep_by_ecosystem.entry(id.clone()).or_default();
        *entry = entry.narrow(policy);
    }
    Ok(())
}

/// Folds the `[[paths]]` rules of one file into the accumulated layers.
fn apply_rules(accumulated: &mut Accumulated, layer: &Layer, dir: &Path) -> Result<()> {
    let source = &layer.source;

    for rule in &layer.file.paths {
        let pattern = expand(&rule.pattern, dir);
        let glob = Glob::new(&pattern)
            .map_err(|error| Error::Config {
                path: source.clone(),
                reason: format!("`[[paths]] match = \"{pattern}\"` is not a valid glob: {error}"),
            })?
            .compile_matcher();
        let keep = match &rule.keep {
            Some(table) => keep_from(table, source)?,
            None => KeepPolicy::default(),
        };
        accumulated.rules.push(Rule {
            pattern,
            glob,
            keep,
            ops: rule_ops(rule.ecosystems.as_ref(), source)?,
        });
    }
    Ok(())
}

fn rule_ops(section: Option<&EcosystemsSection>, source: &Path) -> Result<Vec<(String, bool)>> {
    let Some(section) = section else { return Ok(Vec::new()) };
    let mut ops = Vec::new();
    for spec in &section.disable {
        validate_spec(spec, source)?;
        ops.push((spec.clone(), false));
    }
    for spec in &section.enable {
        validate_spec(spec, source)?;
        ops.push((spec.clone(), true));
    }
    Ok(ops)
}

/// Rejects a spec the catalog does not answer to, naming the file it came from.
fn validate_spec(spec: &str, source: &Path) -> Result<()> {
    let known = match spec.split_once('.') {
        Some((ecosystem, _)) => ArtifactId::from_spec(spec).is_some() && catalog::find(ecosystem).is_some(),
        None => catalog::find(spec).is_some(),
    };
    if known {
        return Ok(());
    }
    Err(Error::Config {
        path: source.to_path_buf(),
        reason: format!("`{spec}` is not a known ecosystem or artifact — run `voom catalog` to see the table"),
    })
}

/// Parses a keep table strictly, attributing any failure to the file it came from.
fn keep_from(table: &KeepTable, source: &Path) -> Result<KeepPolicy> {
    let attribute = |error: Error| Error::Config {
        path: source.to_path_buf(),
        reason: error.to_string(),
    };
    Ok(KeepPolicy {
        min_age: table
            .min_age
            .as_deref()
            .map(parse_duration)
            .transpose()
            .map_err(attribute)?,
        min_size: table
            .min_size
            .as_deref()
            .map(parse_size)
            .transpose()
            .map_err(attribute)?,
        max_size: table
            .max_size
            .as_deref()
            .map(parse_size)
            .transpose()
            .map_err(attribute)?,
    })
}

/// Expands a flag's patterns against the scan root, exactly as a file's are expanded against
/// the directory that declared it.
///
/// Without this a relative `--exclude build` matched nothing at all. The walker offers the paths
/// it produces in the root's own spelling and `globset` compares against the whole of one, so a
/// bare `build` could only ever have matched a path that was literally `build`. The flag
/// reported success and swept the directory anyway — a silent failure on the flag whose entire
/// job is to protect a path, which is why this is a fix and not a documentation note.
///
/// The root rather than the working directory, for two reasons: it is the same rule ADR 0004
/// already states for config files, so there is one thing to learn; and it is the spelling the
/// walker will actually produce, so `voom --exclude proj .` and `voom --exclude proj /abs/path`
/// both work instead of only the second.
fn expand_flag_patterns(patterns: &[String], root: &Path) -> Vec<String> {
    patterns.iter().map(|pattern| expand(pattern, root)).collect()
}

/// Expands `~` and makes a relative pattern relative to the file that declared it.
///
/// ADR 0004 says paths are "relative to this file or absolute", which is what makes a committed
/// `voom.toml` portable between checkouts.
fn expand(pattern: &str, dir: &Path) -> String {
    // `~\` as well as `~/`: a Windows user types the separator their shell shows them, and a
    // home prefix that silently became a relative path would point the pattern somewhere else
    // entirely rather than fail.
    if let Some(rest) = pattern.strip_prefix("~/").or_else(|| pattern.strip_prefix("~\\"))
        && let Some(home) = dirs::home_dir()
    {
        return as_glob(&home.join(rest));
    }
    if Path::new(pattern).is_absolute() || pattern.starts_with("**") {
        return pattern.to_owned();
    }
    as_glob(&dir.join(pattern))
}

/// Renders a path as a glob pattern, which is always `/`-separated.
///
/// `Path::display` emits the platform's separator, and on Windows that is `\`, which glob syntax
/// reads as an escape rather than a separator — an `exclude` built out of a rendered path is one
/// escape away from quietly matching nothing, and an exclusion that stops working silently is
/// what ADR 0004 exists to prevent. `globset` matches against a candidate it has already
/// normalized to `/`, so `/` is the separator both sides agree on. Only [`MAIN_SEPARATOR`] is
/// rewritten, which leaves a unix filename that genuinely contains a backslash alone.
///
/// [`MAIN_SEPARATOR`]: std::path::MAIN_SEPARATOR
fn as_glob(path: &Path) -> String {
    path.display().to_string().replace(std::path::MAIN_SEPARATOR, "/")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::load::read_in;
    use crate::scan::PatternSet;
    use crate::testing::tree;

    fn home() -> PathBuf {
        dirs::home_dir().expect("a home directory")
    }

    #[test]
    fn should_expand_a_home_pattern_to_a_slash_separated_glob() {
        let expanded = expand("~/work/client-x/**", Path::new("/anywhere"));
        assert!(
            !expanded.contains('\\'),
            "a backslash escapes in glob syntax: {expanded}"
        );
        assert!(expanded.ends_with("/work/client-x/**"), "{expanded}");
        assert_ne!(expanded, "~/work/client-x/**", "the home prefix must be expanded");
    }

    /// A Windows user types the separator their shell shows them, so `~\` has to mean `~/`.
    #[test]
    fn should_expand_a_backslash_home_prefix_the_same_way() {
        let dir = Path::new("/anywhere");
        assert_eq!(expand("~\\scratch/**", dir), expand("~/scratch/**", dir));
    }

    #[test]
    fn should_expand_a_relative_pattern_to_a_slash_separated_glob() {
        let fixture = tree(&["project/voom.toml"]);
        let expanded = expand("build/**", &fixture.path().join("project"));
        assert!(
            !expanded.contains('\\'),
            "a backslash escapes in glob syntax: {expanded}"
        );
        assert!(expanded.ends_with("/project/build/**"), "{expanded}");
    }

    /// A `**`-prefixed pattern is already root-relative, so it is passed through untouched.
    #[test]
    fn should_pass_a_double_star_pattern_through_unchanged() {
        let expanded = expand("**/fixtures/**", Path::new("/anywhere"));
        assert_eq!(expanded, "**/fixtures/**");
        assert!(!expanded.contains('\\'), "{expanded}");
    }

    #[test]
    fn should_pass_an_absolute_pattern_through_unchanged() {
        let absolute = home().join("work").display().to_string();
        let pattern = format!("{absolute}/**");
        assert_eq!(expand(&pattern, Path::new("/anywhere")), pattern);
    }

    /// The property that silently breaks when the pattern carries platform separators: an
    /// `exclude` written in a `voom.toml` must still match the path it names.
    #[test]
    fn should_produce_an_exclude_that_matches_the_path_it_names() {
        let fixture = tree(&["project/voom.toml", "project/build/output.o"]);
        let dir = fixture.path().join("project");
        std::fs::write(dir.join("voom.toml"), "exclude = [\"build/**\"]\n").unwrap();

        let layer = read_in(&dir).expect("it parses").expect("a layer");
        let mut accumulated = Accumulated::default();
        apply(&mut accumulated, &layer).expect("the layer applies");

        let excludes = PatternSet::new(accumulated.exclude.clone()).expect("the exclude compiles");
        assert_eq!(
            excludes.matched(&dir.join("build").join("output.o")),
            Some(accumulated.exclude[0].as_str())
        );
    }

    /// The same property for a `~`-rooted exclude, where the expansion is a real system path and
    /// therefore carries whatever separator the platform renders.
    #[test]
    fn should_produce_a_home_exclude_that_matches_the_path_it_names() {
        let pattern = expand("~/work/client-x/**", Path::new("/anywhere"));
        let excludes = PatternSet::new([pattern]).expect("the exclude compiles");
        let candidate = home().join("work").join("client-x").join("target");
        assert!(excludes.matched(&candidate).is_some(), "{}", candidate.display());
    }

    /// The regression test for a flag that reported success and did nothing. The walker offers
    /// paths in the root's own spelling, so a bare `--exclude build` compiled to a glob that
    /// could never match one — a silent failure on the flag whose job is to protect a path.
    #[test]
    fn should_anchor_a_relative_flag_pattern_to_the_scan_root() {
        assert_eq!(
            expand_flag_patterns(&["build".to_owned()], Path::new("/srv/tree")),
            vec!["/srv/tree/build".to_owned()],
            "a bare pattern must be anchored, or it matches nothing the walker produces"
        );
    }

    /// And anchored in the root's *spelling*, not its canonical form: the walker deliberately
    /// keeps whatever the user typed, so `voom --exclude proj .` has to work too.
    #[test]
    fn should_keep_the_roots_spelling_when_anchoring_a_flag_pattern() {
        assert_eq!(
            expand_flag_patterns(&["proj".to_owned()], Path::new(".")),
            vec!["./proj".to_owned()]
        );
    }

    /// An absolute pattern is already anchored and must survive untouched, or every documented
    /// `--exclude /abs/path` invocation changes meaning.
    #[test]
    fn should_leave_an_absolute_flag_pattern_alone() {
        let absolute = if cfg!(windows) {
            r"C:\builds\**"
        } else {
            "/var/builds/**"
        };

        assert_eq!(
            expand_flag_patterns(&[absolute.to_owned()], Path::new("/srv/tree")),
            vec![absolute.to_owned()]
        );
    }

    /// A `[[paths]]` rule compiles its pattern the same way, and must match the same path.
    #[test]
    fn should_produce_a_path_rule_that_matches_the_path_it_names() {
        let fixture = tree(&["project/voom.toml"]);
        let dir = fixture.path().join("project");
        std::fs::write(
            dir.join("voom.toml"),
            "[[paths]]\nmatch = \"vendor/**\"\n[paths.keep]\nmin_age = \"7d\"\n",
        )
        .unwrap();

        let layer = read_in(&dir).expect("it parses").expect("a layer");
        let mut accumulated = Accumulated::default();
        apply(&mut accumulated, &layer).expect("the layer applies");

        let rule = accumulated.rules.first().expect("one rule");
        assert!(!rule.pattern.contains('\\'), "{}", rule.pattern);
        assert!(rule.glob.is_match(dir.join("vendor").join("target")));
    }
}