pathlint 0.0.9

Lint the PATH environment variable against declarative ordering rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
//! Evaluate `[[expect]]` entries against the resolved PATH.
//!
//! Pure: takes the merged catalog, the OS, the PATH entries, and a
//! resolver function, then returns one `Outcome` per expectation.
//! Tests can swap the resolver for a deterministic stub.

use std::collections::BTreeMap;
use std::path::PathBuf;

use crate::config::{Expectation, Kind, Severity, SourceDef};
use crate::expand::normalize;
use crate::os_detect::Os;
use crate::resolve::Resolution;
use crate::source_match;

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
    Ok,
    NgWrongSource,
    NgUnknownSource,
    NgNotFound,
    /// R2 — resolved path failed `kind` shape check (directory,
    /// broken symlink, missing exec bit, etc.). Carries a short
    /// human-readable reason.
    #[serde(rename = "ng_not_executable")]
    NgNotExecutable(String),
    Skip, // optional + not on PATH
    NotApplicable,
    ConfigError(String),
}

#[derive(Debug, Clone)]
pub struct Outcome {
    pub command: String,
    pub status: Status,
    pub resolved: Option<PathBuf>,
    pub matched_sources: Vec<String>,
    pub prefer: Vec<String>,
    pub avoid: Vec<String>,
    /// Per-rule severity copied from `Expectation.severity`. Pure
    /// policy: it does not affect `Status` (the domain fact) but
    /// `lint::exit_code` reads it to decide whether an NG escalates
    /// to exit 1 or stays at exit 0.
    pub severity: Severity,
}

impl Default for Outcome {
    fn default() -> Self {
        Outcome {
            command: String::new(),
            status: Status::Ok,
            resolved: None,
            matched_sources: Vec::new(),
            prefer: Vec::new(),
            avoid: Vec::new(),
            severity: Severity::Error,
        }
    }
}

impl Outcome {
    /// Smart constructor: build an `Outcome` skeleton from an
    /// `Expectation`, copying the rule's name and prefer/avoid sets
    /// and starting with `Status::Ok`, no resolved path, and no
    /// matched sources. Callers refine the skeleton via the builder
    /// methods (`with_status`, `with_resolved`, …) as they learn
    /// more about the resolution.
    ///
    /// Centralising the field-by-field initialization keeps every
    /// `evaluate` early-return path consistent — previously the
    /// same five-line struct literal was repeated four times.
    pub fn initial(expect: &Expectation) -> Self {
        Outcome {
            command: expect.command.clone(),
            status: Status::Ok,
            resolved: None,
            matched_sources: Vec::new(),
            prefer: expect.prefer.clone(),
            avoid: expect.avoid.clone(),
            severity: expect.severity,
        }
    }

    /// Builder: set the status. Useful in expression-style flow.
    pub fn with_status(mut self, status: Status) -> Self {
        self.status = status;
        self
    }

    /// Builder: set the resolved path.
    pub fn with_resolved(mut self, resolved: PathBuf) -> Self {
        self.resolved = Some(resolved);
        self
    }

    /// Builder: set the matched-source list.
    pub fn with_matched_sources(mut self, matched: Vec<String>) -> Self {
        self.matched_sources = matched;
        self
    }
}

/// Pure-data view of *why* an outcome failed. Derived from
/// `Outcome` by `diagnose`; kept separate so the presentation
/// layer renders strings from a structured value rather than from
/// raw `Outcome` fields. `serde::Serialize` so the same value can
/// drive `check --json`.
///
/// Variants name the failure mode; the fields are the load-bearing
/// facts callers need: which sources were missed (`prefer_missed`),
/// which `avoid` names were hit (`avoid_hits`), the reason the
/// shape check rejected the file, etc. The struct does *not*
/// carry `command` / `resolved` — those live on `Outcome` and the
/// caller pairs them up.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Diagnosis {
    /// Resolved path matched some sources, but none of the
    /// `prefer` set — or it matched a source listed under `avoid`.
    /// `avoid_hits` is the intersection of `matched ∩ avoid`;
    /// non-empty means the rule explicitly forbids this source.
    /// `prefer_missed` is `prefer` itself (every name the user
    /// hoped for); rendering decides whether to show it.
    WrongSource {
        matched: Vec<String>,
        prefer_missed: Vec<String>,
        avoid_hits: Vec<String>,
    },
    /// Path lies outside every defined `[source.<name>]`. No
    /// source name matched at all.
    UnknownSource { prefer: Vec<String> },
    /// Command was not on PATH, and the rule was not optional.
    NotFound { prefer: Vec<String> },
    /// `kind = "executable"` shape check rejected the resolved file.
    /// `reason` is the short human-readable cause from `lint`
    /// (`"is a directory"`, `"broken symlink"`, …).
    NotExecutable {
        reason: String,
        matched: Vec<String>,
    },
    /// `[[expect]]` referenced a source name that is not defined.
    Config { message: String },
}

/// Does this status indicate an expectation failure (NG)? Pure.
/// `ConfigError` is a *configuration* failure rather than a lint
/// failure — it deserves a different exit code, so it is not
/// considered a failure by this predicate. Use `is_config_error`
/// for that case.
pub fn is_failure(status: &Status) -> bool {
    matches!(
        status,
        Status::NgWrongSource
            | Status::NgUnknownSource
            | Status::NgNotFound
            | Status::NgNotExecutable(_)
    )
}

/// Is the outcome list polluted by at least one `ConfigError`?
/// Pure. Drives the exit-code-2 branch.
pub fn has_config_error(outcomes: &[Outcome]) -> bool {
    outcomes
        .iter()
        .any(|o| matches!(o.status, Status::ConfigError(_)))
}

/// Map a slice of outcomes to a process exit code. Pure.
///
/// - `2` — at least one `ConfigError` (rules file referenced an
///   undefined source, etc.). Wins over `1` because the rules
///   themselves are wrong; ignoring this would mask real bugs.
/// - `1` — at least one NG with `severity = "error"` (the default).
/// - `0` — every outcome is non-failure, or every failure carries
///   `severity = "warn"` (a CI-friendly nudge that should not
///   block the build).
///
/// The severity check happens *after* `is_failure`, so a `Warn`
/// outcome still appears in `--explain` / `--json` and still gets
/// the `[warn]` tag in the human view; only the exit code is
/// suppressed.
pub fn exit_code(outcomes: &[Outcome]) -> u8 {
    if has_config_error(outcomes) {
        return 2;
    }
    let any_error_failure = outcomes
        .iter()
        .any(|o| is_failure(&o.status) && o.severity == Severity::Error);
    if any_error_failure { 1 } else { 0 }
}

/// Derive the `Diagnosis` for an outcome — the *why* behind a
/// failing status. Pure: takes only the outcome.
///
/// Returns `None` for non-failure statuses (`Ok` / `Skip` /
/// `NotApplicable`). Callers typically render a `Diagnosis` into
/// human or JSON form; treating the value as the single source of
/// truth keeps the two views in sync.
pub fn diagnose(o: &Outcome) -> Option<Diagnosis> {
    match &o.status {
        Status::Ok | Status::Skip | Status::NotApplicable => None,
        Status::NgWrongSource => {
            let avoid_hits: Vec<String> = o
                .matched_sources
                .iter()
                .filter(|m| o.avoid.iter().any(|a| a == *m))
                .cloned()
                .collect();
            Some(Diagnosis::WrongSource {
                matched: o.matched_sources.clone(),
                prefer_missed: o.prefer.clone(),
                avoid_hits,
            })
        }
        Status::NgUnknownSource => Some(Diagnosis::UnknownSource {
            prefer: o.prefer.clone(),
        }),
        Status::NgNotFound => Some(Diagnosis::NotFound {
            prefer: o.prefer.clone(),
        }),
        Status::NgNotExecutable(reason) => Some(Diagnosis::NotExecutable {
            reason: reason.clone(),
            matched: o.matched_sources.clone(),
        }),
        Status::ConfigError(msg) => Some(Diagnosis::Config {
            message: msg.clone(),
        }),
    }
}

/// Evaluate every expectation. Both the resolver and the shape
/// checker are injected so `evaluate` itself stays pure — production
/// passes real PATH lookup and `std::fs::metadata` closures, tests
/// pass deterministic stubs.
///
/// `shape_check` is invoked only when an expectation declares
/// `kind` and the source check has already passed (R2 escalates
/// OK to NG, never the other way).
pub fn evaluate<R, S>(
    expectations: &[Expectation],
    sources: &BTreeMap<String, SourceDef>,
    os: Os,
    mut resolver: R,
    mut shape_check: S,
) -> Vec<Outcome>
where
    R: FnMut(&str) -> Option<Resolution>,
    S: FnMut(&std::path::Path, Kind) -> Result<(), String>,
{
    expectations
        .iter()
        .map(|e| evaluate_one(e, sources, os, &mut resolver, &mut shape_check))
        .collect()
}

fn evaluate_one<R, S>(
    expect: &Expectation,
    sources: &BTreeMap<String, SourceDef>,
    os: Os,
    resolver: &mut R,
    shape_check: &mut S,
) -> Outcome
where
    R: FnMut(&str) -> Option<Resolution>,
    S: FnMut(&std::path::Path, Kind) -> Result<(), String>,
{
    let base = Outcome::initial(expect);

    if !crate::os_detect::os_filter_applies(&expect.os, os) {
        return base.with_status(Status::NotApplicable);
    }

    if let Some(name) = first_undefined(&expect.prefer, &expect.avoid, sources) {
        return base.with_status(Status::ConfigError(format!(
            "undefined source name: {name}"
        )));
    }

    let Some(resolution) = resolver(&expect.command) else {
        let status = if expect.optional {
            Status::Skip
        } else {
            Status::NgNotFound
        };
        return base.with_status(status);
    };

    let haystack = normalize(&resolution.full_path.to_string_lossy());
    let matched = source_match::names_only(&haystack, sources, os);
    let source_status = decide(&matched, &expect.prefer, &expect.avoid);

    // R2 shape check. Only run when the source check already passed —
    // a `prefer` mismatch is a louder failure than a shape one and
    // we don't want to drown the user in two diagnostics for the
    // same expectation. The shape check only escalates an OK status
    // into a NG, never the other way around. Delegated to the
    // injected `shape_check` closure so this function stays pure.
    let final_status = match (&source_status, expect.kind) {
        (Status::Ok, Some(kind)) => match shape_check(&resolution.full_path, kind) {
            Ok(()) => Status::Ok,
            Err(reason) => Status::NgNotExecutable(reason),
        },
        _ => source_status,
    };

    base.with_resolved(resolution.full_path)
        .with_matched_sources(matched)
        .with_status(final_status)
}

/// Default shape-check implementation: hits the filesystem via
/// `std::fs::metadata`. The injected closure variant in `evaluate`
/// is what tests use; this is what `run.rs` wires for production.
///
/// Returns `Err` with a short human-readable reason on mismatch
/// (`"is a directory"` / `"broken symlink"` / `"not executable
/// (no +x bit)"` / `"cannot stat"` / `"not a regular file"`).
pub fn check_shape_filesystem(path: &std::path::Path, kind: Kind) -> Result<(), String> {
    match kind {
        Kind::Executable => check_executable(path),
    }
}

fn check_executable(path: &std::path::Path) -> Result<(), String> {
    // metadata() follows symlinks. If that fails, the symlink is
    // dangling or the file vanished between resolve and now.
    let md = match std::fs::metadata(path) {
        Ok(md) => md,
        Err(_) => {
            return Err(if path.is_symlink() {
                "broken symlink".into()
            } else {
                "cannot stat".into()
            });
        }
    };
    if md.is_dir() {
        return Err("is a directory".into());
    }
    if !md.is_file() {
        return Err("not a regular file".into());
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if md.permissions().mode() & 0o111 == 0 {
            return Err("not executable (no +x bit)".into());
        }
    }
    Ok(())
}

fn first_undefined<'a>(
    prefer: &'a [String],
    avoid: &'a [String],
    sources: &BTreeMap<String, SourceDef>,
) -> Option<&'a str> {
    for name in prefer.iter().chain(avoid.iter()) {
        if !sources.contains_key(name) {
            return Some(name.as_str());
        }
    }
    None
}

fn decide(matched: &[String], prefer: &[String], avoid: &[String]) -> Status {
    let in_avoid = matched.iter().any(|m| avoid.iter().any(|a| a == m));
    if in_avoid {
        return Status::NgWrongSource;
    }
    if prefer.is_empty() {
        return Status::Ok;
    }
    if matched.is_empty() {
        return Status::NgUnknownSource;
    }
    let in_prefer = matched.iter().any(|m| prefer.iter().any(|p| p == m));
    if in_prefer {
        Status::Ok
    } else {
        Status::NgWrongSource
    }
}

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

    fn src(unix: &str) -> SourceDef {
        SourceDef {
            unix: Some(unix.into()),
            ..Default::default()
        }
    }

    fn src_win(win: &str) -> SourceDef {
        SourceDef {
            windows: Some(win.into()),
            ..Default::default()
        }
    }

    fn cat(entries: &[(&str, SourceDef)]) -> BTreeMap<String, SourceDef> {
        entries
            .iter()
            .map(|(n, d)| (n.to_string(), d.clone()))
            .collect()
    }

    fn resolved(p: &str) -> Resolution {
        Resolution {
            full_path: PathBuf::from(p),
        }
    }

    /// Stub shape-check that always passes. Used by tests that
    /// don't exercise R2 — keeps `evaluate` calls terse.
    fn shape_ok(_: &std::path::Path, _: crate::config::Kind) -> Result<(), String> {
        Ok(())
    }

    #[test]
    fn ok_when_resolved_under_preferred_source() {
        let sources = cat(&[("cargo", src("/home/u/.cargo/bin"))]);
        let expectations = vec![Expectation {
            command: "runex".into(),
            prefer: vec!["cargo".into()],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| Some(resolved("/home/u/.cargo/bin/runex")),
            shape_ok,
        );
        assert_eq!(out[0].status, Status::Ok);
        assert_eq!(out[0].matched_sources, vec!["cargo".to_string()]);
    }

    #[test]
    fn ng_wrong_source_when_avoid_hits() {
        let sources = cat(&[
            ("cargo", src("/home/u/.cargo/bin")),
            ("winget", src_win("WinGet")),
        ]);
        let expectations = vec![Expectation {
            command: "runex".into(),
            prefer: vec!["cargo".into()],
            avoid: vec!["winget".into()],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Windows,
            |_| {
                Some(resolved(
                    r"C:\Users\u\AppData\Local\Microsoft\WinGet\Links\runex.exe",
                ))
            },
            shape_ok,
        );
        assert_eq!(out[0].status, Status::NgWrongSource);
        assert!(out[0].matched_sources.contains(&"winget".to_string()));
    }

    #[test]
    fn unknown_source_when_no_match_but_prefer_set() {
        let sources = cat(&[("cargo", src("/home/u/.cargo/bin"))]);
        let expectations = vec![Expectation {
            command: "runex".into(),
            prefer: vec!["cargo".into()],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| Some(resolved("/usr/local/bin/runex")),
            shape_ok,
        );
        assert_eq!(out[0].status, Status::NgUnknownSource);
    }

    #[test]
    fn not_found_unless_optional() {
        let expectations = vec![Expectation {
            command: "runex".into(),
            prefer: vec![],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &BTreeMap::new(),
            Os::Linux,
            |_| None,
            shape_ok,
        );
        assert_eq!(out[0].status, Status::NgNotFound);

        let optional = vec![Expectation {
            command: "runex".into(),
            prefer: vec![],
            avoid: vec![],
            os: None,
            optional: true,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(&optional, &BTreeMap::new(), Os::Linux, |_| None, shape_ok);
        assert_eq!(out[0].status, Status::Skip);
    }

    #[test]
    fn os_filter_excludes() {
        let expectations = vec![Expectation {
            command: "runex".into(),
            prefer: vec![],
            avoid: vec![],
            os: Some(vec!["windows".into()]),
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &BTreeMap::new(),
            Os::Linux,
            |_| panic!("resolver must not be called for n/a expectations"),
            shape_ok,
        );
        assert_eq!(out[0].status, Status::NotApplicable);
    }

    #[test]
    fn config_error_on_undefined_source() {
        let expectations = vec![Expectation {
            command: "runex".into(),
            prefer: vec!["nonexistent".into()],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &BTreeMap::new(),
            Os::Linux,
            |_| panic!("must not resolve when config is invalid"),
            shape_ok,
        );
        assert!(matches!(out[0].status, Status::ConfigError(_)));
    }

    #[test]
    fn empty_prefer_with_avoid_only_passes_when_avoid_misses() {
        let sources = cat(&[("winget", src_win("WinGet"))]);
        let expectations = vec![Expectation {
            command: "runex".into(),
            prefer: vec![],
            avoid: vec!["winget".into()],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Windows,
            |_| Some(resolved(r"C:\Users\u\.cargo\bin\runex.exe")),
            shape_ok,
        );
        assert_eq!(out[0].status, Status::Ok);
    }

    #[test]
    fn lazygit_any_of_three_preferred_is_ok() {
        // PRD §8.1: prefer is a set; matching any one is OK.
        let sources = cat(&[
            ("cargo", src("/home/u/.cargo/bin")),
            ("winget", src_win("WinGet")),
            ("mise", src("/home/u/.local/share/mise")),
        ]);
        let expectations = vec![Expectation {
            command: "lazygit".into(),
            prefer: vec!["cargo".into(), "winget".into(), "mise".into()],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        // Only the mise install path matches; cargo and winget do not.
        let out = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| {
                Some(resolved(
                    "/home/u/.local/share/mise/installs/lazygit/0.42/bin/lazygit",
                ))
            },
            shape_ok,
        );
        assert_eq!(out[0].status, Status::Ok);
        assert_eq!(out[0].matched_sources, vec!["mise".to_string()]);
    }

    #[test]
    fn multiple_sources_match_same_path_all_recorded() {
        // PRD §8.1 explicitly: a path may match many sources.
        let sources = cat(&[
            ("mise", src("/home/u/.local/share/mise")),
            ("python_install", src("/installs/python/")),
        ]);
        let expectations = vec![Expectation {
            command: "python".into(),
            prefer: vec!["mise".into()],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| {
                Some(resolved(
                    "/home/u/.local/share/mise/installs/python/3.12/bin/python",
                ))
            },
            shape_ok,
        );
        assert_eq!(out[0].status, Status::Ok);
        assert_eq!(out[0].matched_sources.len(), 2);
        assert!(out[0].matched_sources.contains(&"mise".to_string()));
        assert!(
            out[0]
                .matched_sources
                .contains(&"python_install".to_string())
        );
    }

    #[test]
    fn avoid_overrides_prefer_when_both_match() {
        // If the resolved path matches both a prefer source and an
        // avoid source, avoid wins (status NG).
        let sources = cat(&[
            ("mise", src("/home/u/.local/share/mise")),
            ("dangerous_subdir", src("/installs/python/3.10/")),
        ]);
        let expectations = vec![Expectation {
            command: "python".into(),
            prefer: vec!["mise".into()],
            avoid: vec!["dangerous_subdir".into()],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| {
                Some(resolved(
                    "/home/u/.local/share/mise/installs/python/3.10/bin/python",
                ))
            },
            shape_ok,
        );
        assert_eq!(out[0].status, Status::NgWrongSource);
    }

    #[test]
    fn mise_layered_match_shim_path_hits_mise_and_mise_shims() {
        // A binary served via mise's shim layer must match BOTH the
        // catch-all `mise` source and the more specific `mise_shims`,
        // never `mise_installs`. Tests rule co-existence after the
        // 0.0.3 split.
        let sources = cat(&[
            ("mise", src("/home/u/.local/share/mise")),
            ("mise_shims", src("/home/u/.local/share/mise/shims")),
            ("mise_installs", src("/home/u/.local/share/mise/installs")),
        ]);
        let expectations = vec![Expectation {
            command: "python".into(),
            prefer: vec!["mise_shims".into()],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| Some(resolved("/home/u/.local/share/mise/shims/python")),
            shape_ok,
        );
        assert_eq!(out[0].status, Status::Ok);
        assert!(out[0].matched_sources.contains(&"mise".to_string()));
        assert!(out[0].matched_sources.contains(&"mise_shims".to_string()));
        assert!(
            !out[0]
                .matched_sources
                .contains(&"mise_installs".to_string())
        );
    }

    #[test]
    fn mise_layered_match_install_path_hits_mise_and_mise_installs() {
        // The install layer (per-runtime bin dirs). Used when mise is
        // activated by PATH-rewriting, or when a plugin lives in
        // `installs/<plugin>/<ver>/bin`.
        let sources = cat(&[
            ("mise", src("/home/u/.local/share/mise")),
            ("mise_shims", src("/home/u/.local/share/mise/shims")),
            ("mise_installs", src("/home/u/.local/share/mise/installs")),
        ]);
        let expectations = vec![Expectation {
            command: "python".into(),
            prefer: vec!["mise_installs".into()],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| {
                Some(resolved(
                    "/home/u/.local/share/mise/installs/python/3.14/bin/python",
                ))
            },
            shape_ok,
        );
        assert_eq!(out[0].status, Status::Ok);
        assert!(out[0].matched_sources.contains(&"mise".to_string()));
        assert!(
            out[0]
                .matched_sources
                .contains(&"mise_installs".to_string())
        );
        assert!(!out[0].matched_sources.contains(&"mise_shims".to_string()));
    }

    #[test]
    fn mise_alias_remains_for_backwards_compat() {
        // Existing rules written with prefer = ["mise"] keep working
        // even though they don't know about mise_shims / mise_installs.
        let sources = cat(&[
            ("mise", src("/home/u/.local/share/mise")),
            ("mise_shims", src("/home/u/.local/share/mise/shims")),
            ("mise_installs", src("/home/u/.local/share/mise/installs")),
        ]);
        let expectations = vec![Expectation {
            command: "python".into(),
            prefer: vec!["mise".into()],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out_shim = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| Some(resolved("/home/u/.local/share/mise/shims/python")),
            shape_ok,
        );
        let out_install = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| {
                Some(resolved(
                    "/home/u/.local/share/mise/installs/python/3.14/bin/python",
                ))
            },
            shape_ok,
        );
        assert_eq!(out_shim[0].status, Status::Ok);
        assert_eq!(out_install[0].status, Status::Ok);
    }

    // ---- R2 kind = "executable" shape checks --------------------

    use crate::config::Kind;

    fn expect_with_kind(command: &str, source: &str, kind: Kind) -> Expectation {
        Expectation {
            command: command.into(),
            prefer: vec![source.into()],
            avoid: vec![],
            severity: crate::config::Severity::Error,
            os: None,
            optional: false,
            kind: Some(kind),
        }
    }

    /// Build a SourceDef whose path is set on every OS, so the
    /// kind tests work regardless of which OS the test host runs on.
    fn src_anywhere(p: &str) -> SourceDef {
        SourceDef {
            windows: Some(p.into()),
            unix: Some(p.into()),
            ..Default::default()
        }
    }

    /// Stub shape-check that always reports the given reason. Used
    /// to drive the R2 escalation path without touching the real
    /// filesystem — the unit-level concern is "does evaluate route
    /// the closure's Err into NgNotExecutable", not "does
    /// std::fs::metadata work". The real I/O variant is exercised
    /// by `tests/check.rs::kind_executable_flags_directory_shadow_in_real_run`.
    fn shape_err(reason: &'static str) -> impl Fn(&std::path::Path, Kind) -> Result<(), String> {
        move |_, _| Err(reason.into())
    }

    #[test]
    fn kind_executable_routes_shape_check_err_into_ng_not_executable() {
        // R1 says OK, but the (injected) shape check rejects the
        // path. evaluate must escalate to NgNotExecutable carrying
        // the closure's reason verbatim.
        let sources = cat(&[("rogue", src_anywhere("/some/dir"))]);
        let expectations = vec![expect_with_kind("rogue_bin", "rogue", Kind::Executable)];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| Some(resolved("/some/dir/rogue_bin")),
            shape_err("is a directory"),
        );
        match &out[0].status {
            Status::NgNotExecutable(reason) => assert_eq!(reason, "is a directory"),
            other => panic!("expected NgNotExecutable, got {other:?}"),
        }
    }

    #[test]
    fn kind_executable_passes_reason_through_for_each_failure_mode() {
        // Different shape-check failure reasons all surface
        // unchanged on the Outcome — evaluate is just a router.
        for reason in ["broken symlink", "cannot stat", "not a regular file"] {
            let sources = cat(&[("anywhere", src_anywhere("/no/such/place"))]);
            let expectations = vec![expect_with_kind("ghost", "anywhere", Kind::Executable)];
            let out = evaluate(
                &expectations,
                &sources,
                Os::Linux,
                |_| Some(resolved("/no/such/place/ghost")),
                shape_err(reason),
            );
            assert!(matches!(
                out[0].status,
                Status::NgNotExecutable(ref r) if r == reason
            ));
        }
    }

    #[test]
    fn kind_unset_skips_shape_check_entirely() {
        // Even when the resolved path is bogus, no shape check
        // means the source-only outcome stands.
        let sources = cat(&[("anywhere", src_anywhere("/no/such/place"))]);
        let expectations = vec![Expectation {
            command: "ghost".into(),
            prefer: vec!["anywhere".into()],
            avoid: vec![],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::current(),
            |_| Some(resolved("/no/such/place/ghost")),
            shape_ok,
        );
        assert_eq!(out[0].status, Status::Ok);
    }

    #[test]
    fn kind_executable_does_not_override_wrong_source() {
        // A source mismatch (NG already) must not be downgraded by
        // the shape check.
        let sources = cat(&[("good", src("/home/u/good")), ("bad", src("/home/u/bad"))]);
        let expectations = vec![Expectation {
            command: "x".into(),
            prefer: vec!["good".into()],
            avoid: vec!["bad".into()],
            os: None,
            optional: false,
            kind: Some(Kind::Executable),
            severity: crate::config::Severity::Error,
        }];
        let out = evaluate(
            &expectations,
            &sources,
            Os::Linux,
            |_| Some(resolved("/home/u/bad/x")),
            // Suppression of shape-check by source mismatch must
            // hold even when the shape closure would have passed.
            // shape_ok is fine here; check_shape_filesystem would
            // also fail (path doesn't exist) but the test would
            // still pass because the source check fires first.
            shape_ok,
        );
        // Stays NgWrongSource — the shape check is suppressed
        // because the source check already failed.
        assert!(matches!(out[0].status, Status::NgWrongSource));
    }

    // ---- diagnose() -------------------------------------------------

    fn outcome(status: Status, matched: &[&str], prefer: &[&str], avoid: &[&str]) -> Outcome {
        Outcome {
            command: "rg".into(),
            status,
            resolved: Some(PathBuf::from("/usr/local/bin/rg")),
            matched_sources: matched.iter().map(|s| s.to_string()).collect(),
            prefer: prefer.iter().map(|s| s.to_string()).collect(),
            avoid: avoid.iter().map(|s| s.to_string()).collect(),
            severity: Severity::Error,
        }
    }

    #[test]
    fn diagnose_returns_none_for_non_failure_statuses() {
        for status in [Status::Ok, Status::Skip, Status::NotApplicable] {
            let o = outcome(status, &["cargo"], &["cargo"], &[]);
            assert!(
                diagnose(&o).is_none(),
                "status should yield None: {:?}",
                o.status
            );
        }
    }

    #[test]
    fn diagnose_wrong_source_collects_avoid_hits_when_intersection_non_empty() {
        let o = outcome(
            Status::NgWrongSource,
            &["winget", "scoop"],
            &["cargo"],
            &["winget"],
        );
        let d = diagnose(&o).unwrap();
        match d {
            Diagnosis::WrongSource {
                matched,
                prefer_missed,
                avoid_hits,
            } => {
                assert_eq!(matched, vec!["winget", "scoop"]);
                assert_eq!(prefer_missed, vec!["cargo"]);
                assert_eq!(avoid_hits, vec!["winget"]);
            }
            other => panic!("expected WrongSource, got {other:?}"),
        }
    }

    #[test]
    fn diagnose_wrong_source_with_no_avoid_overlap_returns_empty_avoid_hits() {
        let o = outcome(Status::NgWrongSource, &["scoop"], &["cargo"], &[]);
        let d = diagnose(&o).unwrap();
        match d {
            Diagnosis::WrongSource { avoid_hits, .. } => assert!(avoid_hits.is_empty()),
            other => panic!("expected WrongSource, got {other:?}"),
        }
    }

    #[test]
    fn diagnose_unknown_source_carries_only_prefer() {
        let o = outcome(Status::NgUnknownSource, &[], &["cargo"], &[]);
        let d = diagnose(&o).unwrap();
        assert!(
            matches!(d, Diagnosis::UnknownSource { ref prefer } if prefer == &["cargo".to_string()])
        );
    }

    #[test]
    fn diagnose_not_found_carries_prefer() {
        let o = outcome(Status::NgNotFound, &[], &["cargo", "winget"], &[]);
        let d = diagnose(&o).unwrap();
        assert!(matches!(d, Diagnosis::NotFound { ref prefer } if prefer.len() == 2));
    }

    #[test]
    fn diagnose_not_executable_keeps_reason_and_matched() {
        let o = outcome(
            Status::NgNotExecutable("is a directory".into()),
            &["custom"],
            &["custom"],
            &[],
        );
        let d = diagnose(&o).unwrap();
        match d {
            Diagnosis::NotExecutable { reason, matched } => {
                assert_eq!(reason, "is a directory");
                assert_eq!(matched, vec!["custom"]);
            }
            other => panic!("expected NotExecutable, got {other:?}"),
        }
    }

    #[test]
    fn diagnose_config_error_propagates_message() {
        let o = outcome(
            Status::ConfigError("undefined source name: typo".into()),
            &[],
            &[],
            &[],
        );
        let d = diagnose(&o).unwrap();
        assert!(matches!(d, Diagnosis::Config { ref message } if message.contains("typo")));
    }

    #[test]
    fn diagnosis_serializes_with_kind_discriminator() {
        let d = Diagnosis::WrongSource {
            matched: vec!["scoop".into()],
            prefer_missed: vec!["cargo".into()],
            avoid_hits: vec![],
        };
        let json = serde_json::to_value(&d).unwrap();
        assert_eq!(json["kind"], "wrong_source");
        assert_eq!(json["matched"][0], "scoop");
    }

    // ---- exit_code ------------------------------------------------

    fn outcome_status(status: Status) -> Outcome {
        outcome(status, &[], &[], &[])
    }

    #[test]
    fn exit_code_zero_when_all_outcomes_pass() {
        let out = vec![
            outcome_status(Status::Ok),
            outcome_status(Status::Skip),
            outcome_status(Status::NotApplicable),
        ];
        assert_eq!(exit_code(&out), 0);
    }

    #[test]
    fn exit_code_one_when_any_failure_present() {
        let out = vec![
            outcome_status(Status::Ok),
            outcome_status(Status::NgNotFound),
        ];
        assert_eq!(exit_code(&out), 1);
    }

    #[test]
    fn exit_code_two_when_any_config_error_present() {
        let out = vec![
            outcome_status(Status::Ok),
            outcome_status(Status::ConfigError("typo".into())),
        ];
        assert_eq!(exit_code(&out), 2);
    }

    #[test]
    fn exit_code_two_wins_over_one_when_both_present() {
        // A rules-file error must mask plain NGs; otherwise users
        // patch the lint failure and re-run only to discover the
        // config error a second time.
        let out = vec![
            outcome_status(Status::NgWrongSource),
            outcome_status(Status::ConfigError("undefined".into())),
        ];
        assert_eq!(exit_code(&out), 2);
    }

    #[test]
    fn exit_code_zero_for_empty_outcome_list() {
        // No `[[expect]]` rules at all is a valid (if useless) state.
        let out: Vec<Outcome> = vec![];
        assert_eq!(exit_code(&out), 0);
    }

    fn outcome_with_severity(status: Status, severity: Severity) -> Outcome {
        Outcome {
            severity,
            ..outcome_status(status)
        }
    }

    #[test]
    fn exit_code_zero_when_only_warn_severity_failures() {
        // severity = "warn" demotes NG so CI doesn't block.
        let out = vec![
            outcome_with_severity(Status::NgWrongSource, Severity::Warn),
            outcome_with_severity(Status::Ok, Severity::Error),
        ];
        assert_eq!(exit_code(&out), 0);
    }

    #[test]
    fn exit_code_one_when_any_error_severity_failure_present() {
        // A single Error-severity NG escalates even if other NGs are Warn.
        let out = vec![
            outcome_with_severity(Status::NgWrongSource, Severity::Warn),
            outcome_with_severity(Status::NgNotFound, Severity::Error),
        ];
        assert_eq!(exit_code(&out), 1);
    }

    #[test]
    fn exit_code_two_still_wins_over_warn_severity() {
        // ConfigError is a config bug — severity policy must not
        // mask it.
        let out = vec![
            outcome_with_severity(Status::NgWrongSource, Severity::Warn),
            outcome_with_severity(Status::ConfigError("typo".into()), Severity::Warn),
        ];
        assert_eq!(exit_code(&out), 2);
    }

    #[test]
    fn is_failure_true_for_each_ng_variant() {
        assert!(is_failure(&Status::NgWrongSource));
        assert!(is_failure(&Status::NgUnknownSource));
        assert!(is_failure(&Status::NgNotFound));
        assert!(is_failure(&Status::NgNotExecutable("x".into())));
    }

    #[test]
    fn is_failure_false_for_non_ng_variants() {
        assert!(!is_failure(&Status::Ok));
        assert!(!is_failure(&Status::Skip));
        assert!(!is_failure(&Status::NotApplicable));
        // ConfigError is *not* a "failure" per is_failure — it gets
        // exit code 2 via has_config_error and exit_code instead.
        assert!(!is_failure(&Status::ConfigError("x".into())));
    }

    // ---- Outcome smart constructor + builders --------------------

    fn expect_simple() -> Expectation {
        Expectation {
            command: "rg".into(),
            prefer: vec!["cargo".into()],
            avoid: vec!["winget".into()],
            os: None,
            optional: false,
            kind: None,
            severity: crate::config::Severity::Error,
        }
    }

    #[test]
    fn outcome_initial_copies_command_prefer_avoid_from_expectation() {
        let e = expect_simple();
        let o = Outcome::initial(&e);
        assert_eq!(o.command, "rg");
        assert_eq!(o.prefer, vec!["cargo".to_string()]);
        assert_eq!(o.avoid, vec!["winget".to_string()]);
    }

    #[test]
    fn outcome_initial_starts_with_ok_status_and_no_resolution() {
        let o = Outcome::initial(&expect_simple());
        assert_eq!(o.status, Status::Ok);
        assert!(o.resolved.is_none());
        assert!(o.matched_sources.is_empty());
    }

    #[test]
    fn outcome_with_status_replaces_status_only() {
        let o = Outcome::initial(&expect_simple()).with_status(Status::NgNotFound);
        assert_eq!(o.status, Status::NgNotFound);
        // Other fields unchanged.
        assert_eq!(o.command, "rg");
        assert_eq!(o.prefer, vec!["cargo".to_string()]);
    }

    #[test]
    fn outcome_builders_chain() {
        let o = Outcome::initial(&expect_simple())
            .with_resolved(PathBuf::from("/usr/local/bin/rg"))
            .with_matched_sources(vec!["scoop".into()])
            .with_status(Status::NgWrongSource);
        assert_eq!(
            o.resolved.as_deref(),
            Some(std::path::Path::new("/usr/local/bin/rg"))
        );
        assert_eq!(o.matched_sources, vec!["scoop".to_string()]);
        assert_eq!(o.status, Status::NgWrongSource);
    }
}