apexe 0.4.0

Outside-In CLI-to-Agent Bridge
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
//! Loading and selection of curated tool overlays.
//!
//! This is the OS-facing half of the overlay mechanism: it reads overlay
//! documents off disk (or out of the binary, for the curated built-ins) and
//! decides which one applies to a scanned binary. The data model, the match
//! rules and the merge semantics live in [`crate::adapter::overlay`] and stay
//! free of any filesystem or subprocess dependency.
//!
//! # Unified override path
//!
//! `--overlay <PATH>` is the single operator-facing override. It replaces the
//! former `ParserPipeline::parse(.., user_override)` hook, which sat below the
//! layer where variant information exists and was never wired to the CLI.

use std::path::{Path, PathBuf};

use thiserror::Error;
use tracing::{debug, warn};

use crate::adapter::overlay::{
    validate_overlay, MatchContext, MatchStrength, OverlayDefect, ToolOverlay,
    OVERLAY_SCHEMA_VERSION,
};

/// Curated overlays compiled into the binary.
///
/// Deliberately a short list: it exists to prove the mechanism end to end, not
/// to be a library of every CLI in existence.
const BUILTIN_OVERLAYS: &[(&str, &str)] = &[
    ("cat@bsd", include_str!("../../overlays/cat@bsd.json")),
    ("cat@gnu", include_str!("../../overlays/cat@gnu.json")),
    ("chmod@bsd", include_str!("../../overlays/chmod@bsd.json")),
    ("chmod@gnu", include_str!("../../overlays/chmod@gnu.json")),
    ("cp@bsd", include_str!("../../overlays/cp@bsd.json")),
    ("cp@gnu", include_str!("../../overlays/cp@gnu.json")),
    ("cut@bsd", include_str!("../../overlays/cut@bsd.json")),
    ("cut@gnu", include_str!("../../overlays/cut@gnu.json")),
    ("df@bsd", include_str!("../../overlays/df@bsd.json")),
    ("df@gnu", include_str!("../../overlays/df@gnu.json")),
    ("diff@bsd", include_str!("../../overlays/diff@bsd.json")),
    ("diff@gnu", include_str!("../../overlays/diff@gnu.json")),
    ("du@bsd", include_str!("../../overlays/du@bsd.json")),
    ("du@gnu", include_str!("../../overlays/du@gnu.json")),
    ("find@bsd", include_str!("../../overlays/find@bsd.json")),
    ("find@gnu", include_str!("../../overlays/find@gnu.json")),
    ("grep@bsd", include_str!("../../overlays/grep@bsd.json")),
    ("grep@gnu", include_str!("../../overlays/grep@gnu.json")),
    ("head@bsd", include_str!("../../overlays/head@bsd.json")),
    ("head@gnu", include_str!("../../overlays/head@gnu.json")),
    ("ln@bsd", include_str!("../../overlays/ln@bsd.json")),
    ("ln@gnu", include_str!("../../overlays/ln@gnu.json")),
    ("ls@bsd", include_str!("../../overlays/ls@bsd.json")),
    ("ls@gnu", include_str!("../../overlays/ls@gnu.json")),
    ("mkdir@bsd", include_str!("../../overlays/mkdir@bsd.json")),
    ("mkdir@gnu", include_str!("../../overlays/mkdir@gnu.json")),
    ("mv@bsd", include_str!("../../overlays/mv@bsd.json")),
    ("mv@gnu", include_str!("../../overlays/mv@gnu.json")),
    ("rm@bsd", include_str!("../../overlays/rm@bsd.json")),
    ("rm@gnu", include_str!("../../overlays/rm@gnu.json")),
    ("sort@apple", include_str!("../../overlays/sort@apple.json")),
    ("sort@gnu", include_str!("../../overlays/sort@gnu.json")),
    ("tail@bsd", include_str!("../../overlays/tail@bsd.json")),
    ("tail@gnu", include_str!("../../overlays/tail@gnu.json")),
    ("touch@bsd", include_str!("../../overlays/touch@bsd.json")),
    ("touch@gnu", include_str!("../../overlays/touch@gnu.json")),
    ("uniq@bsd", include_str!("../../overlays/uniq@bsd.json")),
    ("uniq@gnu", include_str!("../../overlays/uniq@gnu.json")),
    ("wc@bsd", include_str!("../../overlays/wc@bsd.json")),
    ("wc@gnu", include_str!("../../overlays/wc@gnu.json")),
    ("xargs@bsd", include_str!("../../overlays/xargs@bsd.json")),
    ("xargs@gnu", include_str!("../../overlays/xargs@gnu.json")),
];

/// Failures while loading overlay documents.
#[derive(Debug, Error)]
pub enum OverlayError {
    #[error("Failed to read overlay '{path}': {source}")]
    Read {
        path: String,
        #[source]
        source: std::io::Error,
    },

    #[error("Overlay '{path}' is not valid JSON or YAML: {message}")]
    Malformed { path: String, message: String },

    #[error(
        "Overlay '{path}' declares schema_version '{found}', but this build supports '{expected}'"
    )]
    UnsupportedVersion {
        path: String,
        found: String,
        expected: String,
    },

    /// The document parsed, but asserts something it is not allowed to assert —
    /// most importantly `confidence: verified` with no provenance to back it.
    #[error("Overlay '{path}' is invalid:\n{}", format_defects(.defects))]
    Invalid {
        path: String,
        defects: Vec<OverlayDefect>,
    },
}

/// Render a defect list as one indented bullet per line.
fn format_defects(defects: &[OverlayDefect]) -> String {
    defects
        .iter()
        .map(|defect| format!("  - {defect}"))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Where an overlay came from, which sets its baseline precedence.
#[derive(Debug, Clone, PartialEq, Eq)]
enum OverlayOrigin {
    /// Compiled into this build.
    Builtin,
    /// Discovered in an overlay directory.
    UserDir,
    /// Named on the command line by the operator.
    Explicit,
}

/// One loaded overlay plus its provenance.
#[derive(Debug, Clone)]
struct StoredOverlay {
    overlay: ToolOverlay,
    origin: OverlayOrigin,
}

/// A resolved overlay selection.
#[derive(Debug, Clone)]
pub struct OverlaySelection<'a> {
    pub overlay: &'a ToolOverlay,
    pub strength: MatchStrength,
}

/// Collection of overlays available to a scan.
#[derive(Debug, Default)]
pub struct OverlayStore {
    entries: Vec<StoredOverlay>,
}

impl OverlayStore {
    /// An empty store, for tests and for callers that opt out of overlays.
    pub fn empty() -> Self {
        Self::default()
    }

    /// Load the curated built-in overlays.
    ///
    /// A malformed built-in is a build defect, not a user problem, so it is
    /// logged and skipped rather than failing every scan.
    pub fn with_builtins() -> Self {
        let mut store = Self::default();
        for (id, document) in BUILTIN_OVERLAYS {
            match parse_overlay(id, document) {
                Ok(overlay) => store.entries.push(StoredOverlay {
                    overlay,
                    origin: OverlayOrigin::Builtin,
                }),
                Err(e) => warn!(overlay = id, "Built-in overlay is invalid, skipping: {e}"),
            }
        }
        store
    }

    /// Add every `*.json` / `*.yaml` overlay found directly under `dir`.
    ///
    /// A missing directory is not an error: most installs never create one.
    /// A malformed file *is* reported, so a typo in a hand-written overlay does
    /// not silently degrade the scan back to heuristics.
    pub fn load_dir(&mut self, dir: &Path) -> Result<usize, OverlayError> {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return Ok(0);
        };
        let mut loaded = 0;
        for entry in entries.flatten() {
            let path = entry.path();
            if !has_overlay_extension(&path) {
                continue;
            }
            self.push_from_path(&path, OverlayOrigin::UserDir)?;
            loaded += 1;
        }
        Ok(loaded)
    }

    /// Add an overlay named explicitly by the operator.
    ///
    /// Explicit overlays outrank everything else and skip variant, platform and
    /// probe conditions: naming the file is the operator's own assertion that it
    /// applies. Only the command name still has to agree, so a mistyped path
    /// cannot silently reshape an unrelated tool.
    pub fn load_explicit(&mut self, path: &Path) -> Result<(), OverlayError> {
        self.push_from_path(path, OverlayOrigin::Explicit)
    }

    fn push_from_path(&mut self, path: &Path, origin: OverlayOrigin) -> Result<(), OverlayError> {
        let path_text = path.display().to_string();
        let document = std::fs::read_to_string(path).map_err(|source| OverlayError::Read {
            path: path_text.clone(),
            source,
        })?;
        let overlay = parse_overlay(&path_text, &document)?;
        debug!(overlay = %overlay.id(), path = %path_text, "Loaded overlay");
        self.entries.push(StoredOverlay { overlay, origin });
        Ok(())
    }

    /// Distinct probe argument sets any overlay for `command` may need run.
    ///
    /// The scanner runs these once per binary and hands the outcomes back in a
    /// [`MatchContext`], so probing stays outside the pure matching code.
    pub fn probe_arg_sets(&self, command: &str) -> Vec<Vec<String>> {
        let mut sets: Vec<Vec<String>> = vec![super::variant::version_probe_args()];
        for entry in &self.entries {
            if entry.overlay.command != command {
                continue;
            }
            let Some(ref probe) = entry.overlay.match_rules.probe else {
                continue;
            };
            if !sets.contains(&probe.args) {
                sets.push(probe.args.clone());
            }
        }
        sets
    }

    /// Pick the overlay that best describes `context`, if any.
    ///
    /// Explicit overlays win outright. Otherwise the strongest match wins:
    /// probe > platform + binary_globs > platform alone. Ties are broken toward
    /// user-supplied overlays so a local file can shadow a built-in.
    pub fn select(&self, context: &MatchContext) -> Option<OverlaySelection<'_>> {
        self.entries
            .iter()
            .filter_map(|entry| self.evaluate(entry, context))
            .max_by_key(|(strength, prefer_user, _)| (*strength, *prefer_user))
            .map(|(strength, _, overlay)| OverlaySelection { overlay, strength })
    }

    fn evaluate<'a>(
        &self,
        entry: &'a StoredOverlay,
        context: &MatchContext,
    ) -> Option<(MatchStrength, u8, &'a ToolOverlay)> {
        let prefer_user = u8::from(entry.origin != OverlayOrigin::Builtin);
        if entry.origin == OverlayOrigin::Explicit {
            return (entry.overlay.command == context.command).then_some((
                MatchStrength::Explicit,
                prefer_user,
                &entry.overlay,
            ));
        }
        entry
            .overlay
            .evaluate(context)
            .map(|strength| (strength, prefer_user, &entry.overlay))
    }

    /// Number of loaded overlays.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether no overlay is loaded.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// Whether `path` looks like an overlay document.
fn has_overlay_extension(path: &Path) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .is_some_and(|ext| matches!(ext, "json" | "yaml" | "yml"))
}

/// Parse an overlay document, accepting JSON or YAML.
///
/// `serde_yaml` parses JSON too, so one pass covers both; the JSON error is
/// reported when the text looks like JSON, because it points at the real
/// mistake far better than a YAML indentation complaint would.
fn parse_overlay(path: &str, document: &str) -> Result<ToolOverlay, OverlayError> {
    let overlay: ToolOverlay = if document.trim_start().starts_with('{') {
        serde_json::from_str(document).map_err(|e| OverlayError::Malformed {
            path: path.to_string(),
            message: e.to_string(),
        })?
    } else {
        serde_yaml::from_str(document).map_err(|e| OverlayError::Malformed {
            path: path.to_string(),
            message: e.to_string(),
        })?
    };

    if !overlay.is_supported_version() {
        return Err(OverlayError::UnsupportedVersion {
            path: path.to_string(),
            found: overlay.schema_version.clone(),
            expected: OVERLAY_SCHEMA_VERSION.to_string(),
        });
    }

    // Content invariants are enforced here rather than only in `overlay verify`
    // so a `verified` claim can never reach a scan without provenance backing
    // it: an authoritative overlay replaces the scan result wholesale, and an
    // unbacked one would launder a guess into a fact an agent then acts on.
    let defects = validate_overlay(&overlay);
    if !defects.is_empty() {
        return Err(OverlayError::Invalid {
            path: path.to_string(),
            defects,
        });
    }
    Ok(overlay)
}

/// Default directory an install keeps hand-written overlays in.
pub fn user_overlay_dir(config_dir: &Path) -> PathBuf {
    config_dir.join("overlays")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapter::overlay::{Platform, ProbeOutcome};
    use crate::models::ToolVariant;
    use tempfile::TempDir;

    const MINIMAL: &str = r#"{
      "schema_version": "1.0",
      "command": "widget",
      "variant": "bsd",
      "match": { "platform": ["macos"] },
      "mode": "merge",
      "confidence": "verified",
      "provenance": {
        "platform": "macos",
        "tool_version": "test",
        "source": "man-page",
        "checked_on": "2026-07-27"
      },
      "flags": []
    }"#;

    fn context(command: &str, variant: ToolVariant, platform: Platform) -> MatchContext {
        MatchContext {
            command: command.to_string(),
            variant,
            platform: Some(platform),
            binary_path: format!("/bin/{command}"),
            ..Default::default()
        }
    }

    /// An Apple-variant overlay must be *expressible*, not merely nameable:
    /// before `ToolVariant::Apple` existed, macOS `sort` classified `unknown`,
    /// so an overlay for it could never match on anything but a path. No such
    /// overlay ships — this asserts the mechanism, not a curated file.
    #[test]
    fn test_apple_variant_overlay_is_selectable() {
        let document = MINIMAL
            .replace("\"widget\"", "\"sort\"")
            .replace("\"variant\": \"bsd\"", "\"variant\": \"apple\"");
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("sort.json"), document).unwrap();

        let mut store = OverlayStore::empty();
        store.load_dir(tmp.path()).unwrap();

        let ctx = context("sort", ToolVariant::Apple, Platform::new("macos"));
        let selected = store.select(&ctx).expect("apple overlay must match");
        assert_eq!(selected.overlay.id(), "sort@apple");
    }

    #[test]
    fn test_builtin_overlays_all_parse() {
        // A malformed built-in would be silently skipped at runtime, so assert
        // the shipped count here instead.
        let store = OverlayStore::with_builtins();
        assert_eq!(store.len(), BUILTIN_OVERLAYS.len());
        assert!(!store.is_empty());
    }

    #[test]
    fn test_builtin_ls_bsd_selected_for_bsd_probe() {
        let store = OverlayStore::with_builtins();
        let mut ctx = context("ls", ToolVariant::Bsd, Platform::new("macos"));
        ctx.probes = vec![ProbeOutcome {
            args: super::super::variant::version_probe_args(),
            succeeded: false,
            output: "ls: unrecognized option `--version'".to_string(),
        }];
        let selected = store.select(&ctx).expect("bsd overlay must match");
        assert_eq!(selected.overlay.id(), "ls@bsd");
        assert_eq!(selected.strength, MatchStrength::Probe);
    }

    #[test]
    fn test_builtin_ls_gnu_selected_on_macos_when_probe_says_gnu() {
        // Homebrew coreutils on macOS: path heuristics would say BSD; the probe
        // is the only thing that gets this right.
        let store = OverlayStore::with_builtins();
        let mut ctx = context("ls", ToolVariant::Gnu, Platform::new("macos"));
        ctx.binary_path = "/opt/homebrew/opt/coreutils/libexec/gnubin/ls".to_string();
        ctx.version = Some("9.4".to_string());
        ctx.probes = vec![ProbeOutcome {
            args: super::super::variant::version_probe_args(),
            succeeded: true,
            output: "ls (GNU coreutils) 9.4".to_string(),
        }];
        let selected = store.select(&ctx).expect("gnu overlay must match");
        assert_eq!(selected.overlay.id(), "ls@gnu");
    }

    #[test]
    fn test_builtin_rm_bsd_selected_for_bsd_probe() {
        let store = OverlayStore::with_builtins();
        let mut ctx = context("rm", ToolVariant::Bsd, Platform::new("macos"));
        ctx.probes = vec![ProbeOutcome {
            args: super::super::variant::version_probe_args(),
            succeeded: false,
            output: "rm: illegal option -- -".to_string(),
        }];
        let selected = store.select(&ctx).expect("bsd rm overlay must match");
        assert_eq!(selected.overlay.id(), "rm@bsd");
        assert_eq!(selected.strength, MatchStrength::Probe);
    }

    #[test]
    fn test_builtin_rm_gnu_selected_when_probe_says_gnu() {
        let store = OverlayStore::with_builtins();
        let mut ctx = context("rm", ToolVariant::Gnu, Platform::new("linux"));
        ctx.binary_path = "/usr/bin/rm".to_string();
        ctx.version = Some("9.7".to_string());
        ctx.probes = vec![ProbeOutcome {
            args: super::super::variant::version_probe_args(),
            succeeded: true,
            output: "rm (GNU coreutils) 9.7".to_string(),
        }];
        let selected = store.select(&ctx).expect("gnu rm overlay must match");
        assert_eq!(selected.overlay.id(), "rm@gnu");
    }

    /// An under-classified `rm` would let an agent delete files without ever
    /// reaching the approval gate, so both variants are pinned here.
    #[test]
    fn test_builtin_rm_overlays_assert_destructive_and_require_approval() {
        let store = OverlayStore::with_builtins();
        let rm_overlays: Vec<_> = store
            .entries
            .iter()
            .filter(|entry| entry.overlay.command == "rm")
            .collect();
        assert_eq!(rm_overlays.len(), 2, "both rm variants must be registered");
        for entry in rm_overlays {
            let annotations = &entry.overlay.annotations;
            assert_eq!(annotations.destructive, Some(true));
            assert_eq!(annotations.requires_approval, Some(true));
            assert_eq!(annotations.readonly, Some(false));
        }
    }

    /// Every curated built-in claims `verified`, which the loader only accepts
    /// with provenance behind it. This asserts the intent rather than relying
    /// on a silent skip if someone strips a provenance block.
    #[test]
    fn test_builtin_overlays_are_verified_with_provenance() {
        let store = OverlayStore::with_builtins();
        for entry in &store.entries {
            assert_eq!(
                entry.overlay.confidence,
                crate::models::Confidence::Verified,
                "{} must be verified",
                entry.overlay.id()
            );
            let provenance = entry
                .overlay
                .provenance
                .as_ref()
                .unwrap_or_else(|| panic!("{} must carry provenance", entry.overlay.id()));
            assert!(!provenance.tool_version.trim().is_empty());
            assert_eq!(provenance.checked_on.len(), 10);
        }
    }

    /// `ToolVariant::Gnu` is the whole GNU family, so the variant alone says
    /// nothing about the package. Package identity has to be enforced where it
    /// actually bites — the probe — or a GNU `tar` could pick up a coreutils
    /// overlay. `provenance.package` records the same fact for an auditor, and
    /// the two must agree, which is what this asserts: the probe string is
    /// `GNU <package>` for whichever package the provenance names. It is
    /// deliberately not a fixed count or a fixed string, because coreutils,
    /// diffutils, grep and findutils are all `gnu` and all curated here.
    #[test]
    fn test_builtin_gnu_overlays_pin_their_own_package() {
        let store = OverlayStore::with_builtins();
        let gnu: Vec<_> = store
            .entries
            .iter()
            .filter(|entry| entry.overlay.variant == ToolVariant::Gnu)
            .collect();
        assert!(
            gnu.len() >= 14,
            "the curated GNU overlays must all be registered, found {}",
            gnu.len()
        );
        for entry in gnu {
            let provenance = entry
                .overlay
                .provenance
                .as_ref()
                .unwrap_or_else(|| panic!("{} must carry provenance", entry.overlay.id()));
            let package = provenance
                .package
                .as_deref()
                .unwrap_or_else(|| panic!("{} must name its upstream package", entry.overlay.id()));
            let probe = entry
                .overlay
                .match_rules
                .probe
                .as_ref()
                .unwrap_or_else(|| panic!("{} must declare a probe", entry.overlay.id()));
            assert_eq!(
                probe.output_contains.as_deref(),
                Some(format!("GNU {package}").as_str()),
                "{} must pin its package in the probe",
                entry.overlay.id()
            );
        }
    }

    /// The `gnu` variant covers the whole GNU family, so a non-coreutils
    /// package has to reach its own overlay. These three are the first ones
    /// that are not coreutils, and each is separated from the others only by
    /// `probe.output_contains`.
    #[test]
    fn test_builtin_non_coreutils_gnu_overlays_are_selected_by_their_banner() {
        let store = OverlayStore::with_builtins();
        for (command, banner, expected) in [
            ("grep", "grep (GNU grep) 3.11", "grep@gnu"),
            ("find", "find (GNU findutils) 4.10.0", "find@gnu"),
            ("xargs", "xargs (GNU findutils) 4.10.0", "xargs@gnu"),
            ("diff", "diff (GNU diffutils) 3.10", "diff@gnu"),
        ] {
            let mut ctx = context(command, ToolVariant::Gnu, Platform::new("linux"));
            ctx.binary_path = format!("/usr/bin/{command}");
            ctx.probes = vec![ProbeOutcome {
                args: super::super::variant::version_probe_args(),
                succeeded: true,
                output: banner.to_string(),
            }];
            let selected = store
                .select(&ctx)
                .unwrap_or_else(|| panic!("{expected} must match"));
            assert_eq!(selected.overlay.id(), expected);

            // A coreutils banner must not satisfy a diffutils/grep/findutils
            // probe, which is the whole reason the package is pinned there.
            ctx.probes = vec![ProbeOutcome {
                args: super::super::variant::version_probe_args(),
                succeeded: true,
                output: format!("{command} (GNU coreutils) 9.7"),
            }];
            assert!(
                store.select(&ctx).is_none(),
                "{expected} must not match a coreutils banner"
            );
        }
    }

    /// The `apple` variant exists so that Apple's own ports, whose banner names
    /// Apple rather than BSD, can carry an overlay at all. `sort` is the first
    /// one, and its probe must key on the banner: Homebrew coreutils can put a
    /// GNU `sort` at the same path, where every platform and path signal still
    /// says macOS.
    #[test]
    fn test_builtin_sort_apple_selected_only_on_the_apple_banner() {
        let store = OverlayStore::with_builtins();
        let mut ctx = context("sort", ToolVariant::Apple, Platform::new("macos"));
        ctx.binary_path = "/usr/bin/sort".to_string();
        ctx.probes = vec![ProbeOutcome {
            args: super::super::variant::version_probe_args(),
            succeeded: true,
            output: "2.3-Apple (197)".to_string(),
        }];
        let selected = store.select(&ctx).expect("apple overlay must match");
        assert_eq!(selected.overlay.id(), "sort@apple");
        assert_eq!(selected.strength, MatchStrength::Probe);

        // A GNU sort installed at the same path must not pick it up.
        ctx.probes = vec![ProbeOutcome {
            args: super::super::variant::version_probe_args(),
            succeeded: true,
            output: "sort (GNU coreutils) 9.7".to_string(),
        }];
        assert!(store.select(&ctx).is_none());
    }

    /// Prose in a description is not actionable; the boolean has to survive
    /// the trip from the shipped overlay into the scanned flag.
    #[test]
    fn test_builtin_tail_overlays_mark_follow_long_running() {
        let store = OverlayStore::with_builtins();
        let tails: Vec<_> = store
            .entries
            .iter()
            .filter(|entry| entry.overlay.command == "tail")
            .collect();
        assert_eq!(tails.len(), 2, "both tail variants must be registered");
        for entry in tails {
            let marked: Vec<&str> = entry
                .overlay
                .flags
                .iter()
                .filter(|flag| flag.long_running)
                .filter_map(|flag| flag.short.as_deref())
                .collect();
            assert_eq!(
                marked,
                vec!["-f", "-F"],
                "{}: only the following flags may claim it",
                entry.overlay.id()
            );
        }
    }

    #[test]
    fn test_select_returns_none_for_unknown_command() {
        let store = OverlayStore::with_builtins();
        let ctx = context(
            "definitely-not-a-real-tool",
            ToolVariant::Bsd,
            Platform::new("macos"),
        );
        assert!(store.select(&ctx).is_none());
    }

    #[test]
    fn test_probe_arg_sets_always_includes_version() {
        let store = OverlayStore::with_builtins();
        let sets = store.probe_arg_sets("ls");
        assert!(sets.contains(&vec!["--version".to_string()]));
    }

    #[test]
    fn test_probe_arg_sets_deduplicates() {
        // Both built-in ls overlays probe `--version`; it must appear once.
        let store = OverlayStore::with_builtins();
        let sets = store.probe_arg_sets("ls");
        let version_count = sets
            .iter()
            .filter(|args| *args == &vec!["--version".to_string()])
            .count();
        assert_eq!(version_count, 1);
    }

    #[test]
    fn test_load_dir_missing_directory_is_not_an_error() {
        let mut store = OverlayStore::empty();
        let loaded = store
            .load_dir(Path::new("/nonexistent/overlay/dir"))
            .unwrap();
        assert_eq!(loaded, 0);
    }

    #[test]
    fn test_load_dir_reads_json_overlay() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("widget.json"), MINIMAL).unwrap();
        std::fs::write(tmp.path().join("notes.txt"), "ignored").unwrap();

        let mut store = OverlayStore::empty();
        let loaded = store.load_dir(tmp.path()).unwrap();
        assert_eq!(loaded, 1);
        assert!(store
            .select(&context("widget", ToolVariant::Bsd, Platform::new("macos")))
            .is_some());
    }

    #[test]
    fn test_load_dir_reads_yaml_overlay() {
        let tmp = TempDir::new().unwrap();
        let yaml = "schema_version: '1.0'\ncommand: widget\nvariant: bsd\nmode: merge\n";
        std::fs::write(tmp.path().join("widget.yaml"), yaml).unwrap();

        let mut store = OverlayStore::empty();
        assert_eq!(store.load_dir(tmp.path()).unwrap(), 1);
    }

    #[test]
    fn test_load_dir_surfaces_malformed_overlay() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("bad.json"), "{ not json").unwrap();

        let mut store = OverlayStore::empty();
        let err = store.load_dir(tmp.path()).unwrap_err();
        assert!(matches!(err, OverlayError::Malformed { .. }));
    }

    #[test]
    fn test_load_rejects_unsupported_schema_version() {
        let tmp = TempDir::new().unwrap();
        let document = MINIMAL.replace("\"1.0\"", "\"99.0\"");
        std::fs::write(tmp.path().join("widget.json"), document).unwrap();

        let mut store = OverlayStore::empty();
        let err = store.load_dir(tmp.path()).unwrap_err();
        match err {
            OverlayError::UnsupportedVersion {
                found, expected, ..
            } => {
                assert_eq!(found, "99.0");
                assert_eq!(expected, OVERLAY_SCHEMA_VERSION);
            }
            other => panic!("expected UnsupportedVersion, got {other:?}"),
        }
    }

    #[test]
    fn test_load_explicit_missing_file_errors() {
        let mut store = OverlayStore::empty();
        let err = store
            .load_explicit(Path::new("/nonexistent/overlay.json"))
            .unwrap_err();
        assert!(matches!(err, OverlayError::Read { .. }));
    }

    #[test]
    fn test_explicit_overlay_outranks_builtin_and_skips_variant_match() {
        // The operator named the file, so a variant the probe could not confirm
        // must not stop it from applying.
        let tmp = TempDir::new().unwrap();
        let document = MINIMAL.replace("\"widget\"", "\"ls\"");
        let path = tmp.path().join("mine.json");
        std::fs::write(&path, document).unwrap();

        let mut store = OverlayStore::with_builtins();
        store.load_explicit(&path).unwrap();

        let ctx = context("ls", ToolVariant::Unknown, Platform::new("linux"));
        let selected = store.select(&ctx).expect("explicit overlay must apply");
        assert_eq!(selected.strength, MatchStrength::Explicit);
    }

    #[test]
    fn test_explicit_overlay_still_requires_matching_command() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("mine.json");
        std::fs::write(&path, MINIMAL).unwrap();

        let mut store = OverlayStore::empty();
        store.load_explicit(&path).unwrap();

        assert!(store
            .select(&context("cat", ToolVariant::Bsd, Platform::new("macos")))
            .is_none());
    }

    #[test]
    fn test_user_overlay_shadows_builtin_at_equal_strength() {
        let tmp = TempDir::new().unwrap();
        let document = MINIMAL
            .replace("\"widget\"", "\"ls\"")
            .replace("{ \"platform\": [\"macos\"] }", "{}");
        std::fs::write(tmp.path().join("ls.json"), document).unwrap();

        let mut store = OverlayStore::with_builtins();
        store.load_dir(tmp.path()).unwrap();

        // No probe outcomes recorded, so the built-in (probe-gated) overlays do
        // not match and only the user's platform-free overlay survives.
        let ctx = context("ls", ToolVariant::Bsd, Platform::new("macos"));
        let selected = store.select(&ctx).unwrap();
        assert_eq!(selected.strength, MatchStrength::Platform);
    }

    #[test]
    fn test_user_overlay_dir_is_under_config_dir() {
        let dir = user_overlay_dir(Path::new("/home/me/.apexe"));
        assert_eq!(dir, PathBuf::from("/home/me/.apexe/overlays"));
    }
}