stable-which 0.5.0

Evaluate binary path stability and find stable PATH candidates
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
//! Durability judging: can a path be pinned into a service definition?
//!
//! See `DR-016` (durable-to-pin model) in the repository's `docs/decisions/`.
//! This module is internal; the public surface is [`crate::Durability`] and
//! [`crate::Candidate::durability`]. (The DR reference is an in-repo document,
//! not a docs.rs link.)

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

use crate::path_analysis;

/// Whether a path string keeps pointing at the same (logical) target across
/// rebuild / upgrade / reboot.
///
/// This is a *durable-to-pin* judgement: a [`Durable`](Durability::Durable)
/// path may be baked into a launchd plist / systemd unit and is expected to
/// survive upgrades and reboots. Judgement is **per candidate** — for the same
/// binary, the reference path (`/opt/homebrew/bin/git`) can be
/// [`Durable`](Durability::Durable) while its canonical realpath
/// (`/opt/homebrew/Cellar/git/2.44.0/bin/git`) is
/// [`NotDurable`](Durability::NotDurable).
///
/// # Judging model (allow-list)
///
/// 1. `NotDurable` is decided first: versioned-install / ephemeral /
///    build-output / project-local patterns.
/// 2. Otherwise, if the path is under a known durable location (the
///    "environment-wide reference surfaces": standard system bins, profile
///    bins matched by their exact structure, shims at standard HOME-anchored
///    locations, and HOME-anchored direct-install dirs such as
///    `~/.cargo/bin`), it is `Durable`.
/// 3. Otherwise `Unknown` (treated as not-durable by
///    [`Candidate::is_stable`](crate::Candidate::is_stable)).
///
/// User dropbox directories (`~/bin`, `~/.local/bin`) are deliberately *not*
/// in the durable allow-list: they mix shebang-embedded scripts and versioned
/// symlinks, so they fall through to `Unknown`. `~/.cargo/bin` is not such a
/// dropbox: `cargo install` overwrites the binary in place at the same path
/// on every install/upgrade (no per-tool versioned symlink), so it is
/// included in the allow-list.
///
/// # Platform support
///
/// The durable location allow-list (step 2) is Unix-only: all entries in
/// [`DURABLE_DIRECT_DIRS`] and the `/etc/profiles/per-user/<user>/bin/<file>`
/// shape are Unix absolute paths (`/usr/bin`, `/opt/homebrew/bin`, etc.).
/// On Windows, [`Path::is_absolute`] returns `false` for these Unix paths
/// (no drive letter), so [`is_durable_direct_dir`] and
/// [`is_etc_profiles_per_user_bin`] always return `false`.
/// As a result, **on Windows all paths that do not match a `NotDurable`
/// pattern fall through to `Unknown`** (the safe side).
/// Windows-native durable surfaces (`C:\Windows\System32`, scoop/chocolatey/
/// winget `bin` directories, PowerShell profile paths, etc.) are not yet in
/// the allow-list and are planned for 0.5.x. See `docs/issue/` for the
/// tracking issue.
///
/// # Known limitations
///
/// Judgement is path-string based and cannot detect:
///
/// - **shebang-embedded versioned dependencies**: e.g. a script in a standard
///   reference surface whose shebang points at a versioned interpreter
///   (`cpython@<ver>`). Such a path may be judged `Durable` yet break on
///   upgrade. This is why shebang-prone user dropboxes are excluded from the
///   allow-list (see above), but the case cannot be ruled out entirely.
/// - **environment-dependent paths**: e.g. `~/.nix-profile` is alive in some
///   environments and dead in others; durability cannot be confirmed without
///   inspecting the realpath.
/// - **non-UTF-8 paths**: pattern matching goes through
///   [`Path::to_string_lossy`], so a path containing non-UTF-8 bytes in a
///   matched segment may compare unexpectedly; such paths typically fall
///   through to `Unknown` (safe side).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Durability {
    /// The path string keeps pointing at the same entity (or same logical
    /// target) across rebuild / upgrade / reboot.
    Durable,
    /// Versioned-install / ephemeral / build-output / project-local etc.;
    /// baking this path into a service definition can break it.
    NotDurable,
    /// Matched neither a known durable nor a known not-durable pattern; cannot
    /// decide (safe side = treated as not-durable).
    Unknown,
}

/// Internal scope of a path. Not exposed publicly (DR-016 Decision 2):
/// project-local is folded into [`Durability::NotDurable`].
///
/// Kept as an enum (rather than a bool) as a deliberate placeholder for the
/// future: if DR-016 Decision 2's "expose scope" option is ever taken, the
/// public `Scope` enum can grow from this internal one without a churny
/// bool→enum migration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
    /// Scoped to a single project (`.direnv/`, `venv/`, `node_modules/.bin/`).
    /// A global service must not reference it.
    ProjectLocal,
    /// Not project-scoped (the common case).
    Global,
}

/// Project-local path fragments. A global service should never reference these.
const PROJECT_LOCAL_PATTERNS: &[&str] = &[
    "/.direnv/",
    "/node_modules/.bin/",
    "/.venv/",
    "/venv/bin/",
    "/.tox/",
];

/// Versioned-install path fragments: the path embeds a version identifier, so
/// it changes on upgrade. These are NotDurable.
const VERSIONED_INSTALL_PATTERNS: &[&str] = &[
    // Homebrew Cellar / Caskroom
    "/Cellar/",
    "/Caskroom/",
    // mise / asdf installs
    "/mise/installs/",
    "/.mise/installs/",
    "/asdf/installs/",
    "/.asdf/installs/",
    // nix store (hash + version in first segment)
    "/nix/store/",
    // version-manager versions/ trees
    "/.nvm/versions/",
    "/.fnm/node-versions/",
    "/.rustup/toolchains/",
    "/.volta/tools/",
    "/.sdkman/candidates/",
    "/.pyenv/versions/",
    "/.rbenv/versions/",
    "/.goenv/versions/",
    "/.proto/tools/",
    "/scoop/apps/",
    "/chocolatey/lib/",
    "/WinGet/Packages/",
    // aqua internal packages
    "/aquaproj-aqua/internal/pkgs/",
    // app-specific versioned trees, anchored to the specific tool name to avoid
    // false positives from an unrelated generic `/versions/` segment (findings:
    // claude / cursor-agent each keep a `versions/<ver>/` tree).
    "/claude/versions/",
    "/cursor-agent/versions/",
    // rye cpython interpreters
    "/cpython@",
];

/// Durable directory surfaces where the binary lives **directly** in the dir
/// (`<dir>/<file>`). These are matched by exact parent-directory equality, not
/// substring, so `/usr/local/binutils/foo` or `/opt/homebrew/binfoo/git` do
/// not match.
///
/// Design rationale: `/usr/local/bin` is included because it is a standard,
/// environment-wide reference surface populated by `make install`, distro
/// packages, and `brew link` symlinks — the reference path is stable across
/// upgrades. The residual risk is a tool that itself places a *versioned
/// symlink* directly in `/usr/local/bin` (rare); that case is a known
/// limitation of path-string judgement (a `Durable` verdict that could still
/// break) and is documented on [`Durability`].
const DURABLE_DIRECT_DIRS: &[&str] = &[
    // standard system bins
    "/usr/bin",
    "/bin",
    "/usr/local/bin",
    "/usr/sbin",
    "/sbin",
    // homebrew profile bins (the symlink surface, not Cellar)
    "/opt/homebrew/bin",
    "/opt/homebrew/sbin",
    // nix-darwin / Determinate Nix profile surfaces
    "/run/current-system/sw/bin",
    "/nix/var/nix/profiles/default/bin",
];

/// Standard shim directory suffixes (HOME-anchored). A shim path is treated as
/// durable only when it both matches one of these and is anchored under the
/// resolved HOME, so a project-local `/repo/.mise/shims/tool` does not qualify.
const STANDARD_SHIM_SUFFIXES: &[&str] = &[
    "/.local/share/mise/shims",
    "/.mise/shims",
    "/.asdf/shims",
    "/.pyenv/shims",
    "/.rbenv/shims",
    "/.goenv/shims",
    "/.proto/shims",
];

/// HOME-anchored direct-install directory suffixes: individual tools install
/// their binary directly here (`<home><suffix>/<file>`), overwriting the same
/// path on every install/upgrade rather than writing a versioned tree, so the
/// path string stays durable across upgrades.
///
/// Design rationale: each entry is a directory whose owning installer
/// (`cargo install` / `go install` / `moon upgrade`) writes the binary in
/// place at the same path on every install/upgrade — no versioned tree, so
/// the path string keeps pointing at the current binary (findings
/// `2026-06-13-binary-path-durability-matrix` fact 7; promoted per DR-016
/// Decision 5's `Unknown → Durable` refinement path). rustup's
/// toolchain-proxy binaries (`rustc`, `cargo`, `rustfmt`, ...) also live in
/// `~/.cargo/bin` and redirect internally to the active toolchain without
/// moving this path. Unlike `~/.local/bin` (Decision 3 of DR-016), these
/// directories are populated by a single, well-known installer rather than an
/// ad-hoc mix of shebang scripts and versioned symlinks.
///
/// Residual risk (same class as the `/usr/local/bin` note on
/// [`DURABLE_DIRECT_DIRS`]): these are user-writable directories on PATH, so
/// an unrelated tool or a manual `ln -s` can place a *versioned symlink* here
/// (e.g. via `cargo-binstall` or a curl-pipe installer). Such a path would be
/// judged `Durable` yet break on upgrade — a known limitation of path-string
/// judgement, documented on [`Durability`].
const HOME_ANCHORED_DIRECT_DIRS: &[&str] = &[
    "/.cargo/bin", // cargo install / rustup proxies
    "/go/bin",     // go install (default GOPATH)
    "/.moon/bin",  // moon (MoonBit toolchain)
];

/// Normalize a path string to forward slashes for pattern matching.
fn norm(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

/// Detect whether a path is project-local (scoped to a single project).
fn scope_of(path: &Path) -> Scope {
    let s = norm(path);
    if PROJECT_LOCAL_PATTERNS.iter().any(|p| s.contains(p)) {
        Scope::ProjectLocal
    } else {
        Scope::Global
    }
}

/// Detect whether a path embeds a version identifier (versioned install).
fn is_versioned_install(path: &Path) -> bool {
    let s = norm(path);
    VERSIONED_INSTALL_PATTERNS.iter().any(|p| s.contains(p))
}

/// Collect the normal (named) path components of `path` as strings.
///
/// Only [`Component::Normal`] segments are kept; root / prefix / `.` / `..`
/// are dropped. A path with any `..` is considered un-normalized by callers and
/// will not match the strict structural checks below.
fn normal_components(path: &Path) -> Vec<String> {
    path.components()
        .filter_map(|c| match c {
            Component::Normal(os) => Some(os.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect()
}

/// `/etc/profiles/per-user/<user>/bin/<file>` (home-manager profile surface).
///
/// Strictly require the exact structure: components `etc`, `profiles`,
/// `per-user`, `<user>`, `bin`, `<file>` with nothing in between and the file
/// as the last component. This rejects
/// `/etc/profiles/per-user/alice/lib/python/bin/foo` and a non-absolute
/// `home/u/etc/profiles/per-user/alice/bin/foo`.
fn is_etc_profiles_per_user_bin(path: &Path) -> bool {
    if !path.is_absolute() {
        return false;
    }
    let c = normal_components(path);
    c.len() == 6
        && c[0] == "etc"
        && c[1] == "profiles"
        && c[2] == "per-user"
        // c[3] is the user name (any single segment)
        && c[4] == "bin"
    // c[5] is the file name (last component); len()==6 guarantees terminal.
}

/// Whether the binary lives directly in one of [`DURABLE_DIRECT_DIRS`]
/// (`<dir>/<file>`), matched by exact parent equality on an absolute path.
fn is_durable_direct_dir(path: &Path) -> bool {
    if !path.is_absolute() {
        return false;
    }
    let Some(parent) = path.parent() else {
        return false;
    };
    // file_name() must exist (so `path` is `<dir>/<file>`, not `<dir>/`).
    if path.file_name().is_none() {
        return false;
    }
    let parent_s = norm(parent);
    DURABLE_DIRECT_DIRS.iter().any(|&d| parent_s == d)
}

/// Whether `path` is `<home><suffix>/<file>` for one of `suffixes`:
/// HOME-anchored, with exactly one of the given suffix directories, then a
/// single file segment (no further `/`). Shared by [`is_standard_shim`] and
/// [`is_home_anchored_direct_dir`].
///
/// `home` is the resolved HOME directory; when `None`, HOME-anchoring cannot
/// be confirmed and the function returns `false` (→ `Unknown`).
fn is_home_anchored_suffix_dir(path: &Path, home: Option<&Path>, suffixes: &[&str]) -> bool {
    let Some(home) = home else {
        return false;
    };
    if !path.is_absolute() {
        return false;
    }
    let home_s = {
        let mut h = norm(home);
        while h.ends_with('/') {
            h.pop();
        }
        h
    };
    if home_s.is_empty() {
        return false;
    }
    let s = norm(path);
    suffixes.iter().any(|suffix| {
        let with_sep = format!("{home_s}{suffix}/");
        // `s` starts with `<home><suffix>/` and the remainder is a single file
        // segment (no further `/`).
        s.strip_prefix(&with_sep)
            .is_some_and(|rest| !rest.is_empty() && !rest.contains('/'))
    })
}

/// Whether `path` is a shim at a standard HOME-anchored location.
fn is_standard_shim(path: &Path, home: Option<&Path>) -> bool {
    // The shim must be recognized as a shim by the shared detector first.
    path_analysis::is_shim_path(path)
        && is_home_anchored_suffix_dir(path, home, STANDARD_SHIM_SUFFIXES)
}

/// Whether `path` is a direct install destination at a standard HOME-anchored
/// location (`~/.cargo/bin` etc; see [`HOME_ANCHORED_DIRECT_DIRS`]).
fn is_home_anchored_direct_dir(path: &Path, home: Option<&Path>) -> bool {
    is_home_anchored_suffix_dir(path, home, HOME_ANCHORED_DIRECT_DIRS)
}

/// Detect whether a path lives at a known durable reference surface.
///
/// Each surface is matched by its exact structure (direct-dir parent equality,
/// the strict per-user profile shape, or a HOME-anchored standard shim or
/// direct-install dir), never by loose substring. Unrecognized locations fall
/// through to `Unknown`.
fn is_durable_location(path: &Path, home: Option<&Path>) -> bool {
    is_durable_direct_dir(path)
        || is_etc_profiles_per_user_bin(path)
        || is_standard_shim(path, home)
        || is_home_anchored_direct_dir(path, home)
}

/// Judge the durability of a candidate path, resolving HOME from the process
/// environment. See [`Durability`] for the judging model and platform notes.
///
/// On Windows, the durable location allow-list is not populated (all entries
/// are Unix absolute paths), so paths that do not match a `NotDurable` pattern
/// fall through to `Unknown` (safe side). Windows-native durable surfaces are
/// planned for 0.5.x.
pub fn judge(path: &Path) -> Durability {
    let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
    judge_with_home(path, home.as_deref())
}

/// Judge durability with an explicit HOME (for testability). See [`Durability`].
fn judge_with_home(path: &Path, home: Option<&Path>) -> Durability {
    // 1. NotDurable is decided first.
    if is_versioned_install(path)
        || path_analysis::is_ephemeral(path)
        || path_analysis::is_build_output(path)
        || scope_of(path) == Scope::ProjectLocal
    {
        return Durability::NotDurable;
    }

    // 2. Known durable reference surfaces.
    if is_durable_location(path, home) {
        return Durability::Durable;
    }

    // 3. Fall through: cannot decide.
    Durability::Unknown
}

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

    const HOME: &str = "/home/u";

    fn judge_str(s: &str) -> Durability {
        // Most tests anchor shims under "/home/u".
        judge_with_home(Path::new(s), Some(Path::new(HOME)))
    }

    // --- NotDurable: versioned-install (findings real examples) ---

    #[test]
    fn homebrew_cellar_is_not_durable() {
        assert_eq!(
            judge_str("/opt/homebrew/Cellar/node/26.0.0/bin/node"),
            Durability::NotDurable
        );
    }

    #[test]
    fn nix_store_is_not_durable() {
        assert_eq!(
            judge_str("/nix/store/abc123hash-git-2.54.0/bin/git"),
            Durability::NotDurable
        );
    }

    #[test]
    fn mise_installs_is_not_durable() {
        assert_eq!(
            judge_str("/home/u/.local/share/mise/installs/node/22.22.0/bin/node"),
            Durability::NotDurable
        );
    }

    #[test]
    fn claude_versions_is_not_durable() {
        assert_eq!(
            judge_str("/home/u/.local/share/claude/versions/2.1.177/bin/claude"),
            Durability::NotDurable
        );
    }

    #[test]
    fn cursor_agent_versions_is_not_durable() {
        assert_eq!(
            judge_str(
                "/home/u/.local/share/cursor-agent/versions/2025.09.17-25b418f/bin/cursor-agent"
            ),
            Durability::NotDurable
        );
    }

    #[test]
    fn generic_versions_segment_is_not_versioned_install() {
        // H: the generic `/versions/` pattern was removed. An unrelated dir
        // named "versions" should NOT be classified as a versioned install
        // (falls through to Unknown here, not NotDurable-by-versioned).
        assert_eq!(
            judge_str("/home/u/myapp/versions/data/tool"),
            Durability::Unknown
        );
    }

    #[test]
    fn rye_cpython_is_not_durable() {
        assert_eq!(
            judge_str("/home/u/.dotfiles/cache/rye/py/cpython@3.12.8/bin/python"),
            Durability::NotDurable
        );
    }

    #[test]
    fn aqua_internal_pkgs_is_not_durable() {
        assert_eq!(
            judge_str("/home/u/.local/share/aquaproj-aqua/internal/pkgs/foo/v2.56.2/bin/aqua"),
            Durability::NotDurable
        );
    }

    // --- NotDurable: ephemeral / build-output / project-local ---

    #[test]
    fn cache_dir_is_not_durable() {
        assert_eq!(
            judge_str("/home/u/.cache/jj-worktree/bin/git"),
            Durability::NotDurable
        );
    }

    #[test]
    fn build_output_is_not_durable() {
        assert_eq!(
            judge_str("/home/u/project/target/release/myapp"),
            Durability::NotDurable
        );
    }

    #[test]
    fn direnv_is_not_durable() {
        assert_eq!(
            judge_str("/home/u/project/.direnv/python-3.12/bin/python"),
            Durability::NotDurable
        );
    }

    #[test]
    fn venv_is_not_durable() {
        assert_eq!(
            judge_str("/home/u/project/.venv/bin/python"),
            Durability::NotDurable
        );
    }

    #[test]
    fn node_modules_bin_is_not_durable() {
        assert_eq!(
            judge_str("/home/u/project/node_modules/.bin/eslint"),
            Durability::NotDurable
        );
    }

    // --- Durable: environment-wide reference surfaces ---
    // These tests use Unix absolute paths (/usr/bin, /opt/homebrew/bin, etc.)
    // and expect Durable.  On Windows, Path::is_absolute() returns false for
    // paths without a drive letter, so is_durable_direct_dir() and
    // is_etc_profiles_per_user_bin() always return false and these paths would
    // fall through to Unknown.  Guard with #[cfg(unix)].

    #[cfg(unix)]
    #[test]
    fn homebrew_bin_is_durable() {
        assert_eq!(judge_str("/opt/homebrew/bin/node"), Durability::Durable);
    }

    #[cfg(unix)]
    #[test]
    fn homebrew_sbin_is_durable() {
        assert_eq!(judge_str("/opt/homebrew/sbin/foo"), Durability::Durable);
    }

    #[cfg(unix)]
    #[test]
    fn usr_bin_is_durable() {
        assert_eq!(judge_str("/usr/bin/git"), Durability::Durable);
    }

    #[cfg(unix)]
    #[test]
    fn usr_sbin_is_durable() {
        assert_eq!(judge_str("/usr/sbin/foo"), Durability::Durable);
    }

    #[cfg(unix)]
    #[test]
    fn sbin_is_durable() {
        assert_eq!(judge_str("/sbin/init"), Durability::Durable);
    }

    #[cfg(unix)]
    #[test]
    fn bin_is_durable() {
        assert_eq!(judge_str("/bin/sh"), Durability::Durable);
    }

    #[cfg(unix)]
    #[test]
    fn usr_local_bin_is_durable() {
        assert_eq!(judge_str("/usr/local/bin/node"), Durability::Durable);
    }

    #[cfg(unix)]
    #[test]
    fn mise_shim_is_durable() {
        assert_eq!(
            judge_str("/home/u/.local/share/mise/shims/node"),
            Durability::Durable
        );
    }

    #[cfg(unix)]
    #[test]
    fn run_current_system_is_durable() {
        assert_eq!(
            judge_str("/run/current-system/sw/bin/git"),
            Durability::Durable
        );
    }

    #[cfg(unix)]
    #[test]
    fn etc_profiles_per_user_is_durable() {
        assert_eq!(
            judge_str("/etc/profiles/per-user/alice/bin/curl"),
            Durability::Durable
        );
    }

    #[cfg(unix)]
    #[test]
    fn nix_default_profile_is_durable() {
        assert_eq!(
            judge_str("/nix/var/nix/profiles/default/bin/nix"),
            Durability::Durable
        );
    }

    // `cargo install` overwrites the binary in place at the same path on
    // every install/upgrade (no versioned tree), so ~/.cargo/bin is a durable
    // reference surface (promoted from Unknown; see HOME_ANCHORED_DIRECT_DIRS).
    #[cfg(unix)]
    #[test]
    fn cargo_bin_is_durable() {
        assert_eq!(judge_str("/home/u/.cargo/bin/ripgrep"), Durability::Durable);
    }

    // `go install` writes to $GOPATH/bin (default ~/go/bin), overwriting the
    // same path on every install — same in-place model as cargo (findings
    // fact 7), so the default location is a durable reference surface.
    #[cfg(unix)]
    #[test]
    fn go_bin_is_durable() {
        assert_eq!(judge_str("/home/u/go/bin/gopls"), Durability::Durable);
    }

    // moon (MoonBit) installs its toolchain binaries at ~/.moon/bin and
    // upgrades in place at the same path — same in-place model (findings
    // fact 7), so it is a durable reference surface.
    #[cfg(unix)]
    #[test]
    fn moon_bin_is_durable() {
        assert_eq!(judge_str("/home/u/.moon/bin/moon"), Durability::Durable);
    }

    // --- A: strict per-user profile structure (false-positive regression) ---

    #[test]
    fn etc_profiles_per_user_deep_is_not_durable() {
        // Deeper than `<user>/bin/<file>`: must NOT be Durable.
        assert_eq!(
            judge_with_home(
                Path::new("/etc/profiles/per-user/alice/lib/python/bin/foo"),
                Some(Path::new(HOME))
            ),
            Durability::Unknown
        );
    }

    #[test]
    fn etc_profiles_per_user_relative_is_not_durable() {
        // Non-absolute lookalike must NOT match.
        assert_eq!(
            judge_with_home(
                Path::new("home/u/etc/profiles/per-user/alice/bin/foo"),
                Some(Path::new(HOME))
            ),
            Durability::Unknown
        );
    }

    // --- A/E: direct-dir exact match (substring false-positive regression) ---

    #[test]
    fn usr_local_binutils_is_unknown() {
        // `/usr/local/binutils/foo` must NOT match `/usr/local/bin`.
        assert_eq!(judge_str("/usr/local/binutils/foo"), Durability::Unknown);
    }

    #[test]
    fn opt_homebrew_binfoo_is_unknown() {
        // `/opt/homebrew/binfoo/git` must NOT match `/opt/homebrew/bin`.
        assert_eq!(judge_str("/opt/homebrew/binfoo/git"), Durability::Unknown);
    }

    #[test]
    fn usr_bin_nested_is_unknown() {
        // A file nested below /usr/bin (not direct child) must NOT match.
        assert_eq!(judge_str("/usr/bin/subdir/foo"), Durability::Unknown);
    }

    // --- B: project/user-local shim must not be Durable ---

    #[test]
    fn project_local_mise_shim_is_unknown() {
        // `/repo/.mise/shims/tool` is shim-shaped but NOT HOME-anchored.
        assert_eq!(
            judge_with_home(Path::new("/repo/.mise/shims/tool"), Some(Path::new(HOME))),
            Durability::Unknown
        );
    }

    #[test]
    fn shim_without_home_is_unknown() {
        // HOME unknown → cannot confirm standard shim → Unknown.
        assert_eq!(
            judge_with_home(Path::new("/home/u/.local/share/mise/shims/node"), None),
            Durability::Unknown
        );
    }

    // Unix absolute path + Durable expected → guard with #[cfg(unix)].
    #[cfg(unix)]
    #[test]
    fn shim_anchored_under_home_is_durable() {
        assert_eq!(
            judge_with_home(Path::new("/home/u/.asdf/shims/ruby"), Some(Path::new(HOME))),
            Durability::Durable
        );
    }

    // --- C: HOME-anchored direct dir false-positive regression ---
    // Exercised via ~/.cargo/bin; the anchoring/structure mechanism
    // (is_home_anchored_suffix_dir) is shared by all HOME_ANCHORED_DIRECT_DIRS
    // entries (go/bin, .moon/bin), so per-entry duplicates add no coverage.

    #[test]
    fn project_local_cargo_bin_is_unknown() {
        // `/repo/.cargo/bin/tool` is directly under a dir named `.cargo/bin`
        // but is NOT anchored under the resolved HOME (project-local
        // lookalike); must not be promoted to Durable.
        assert_eq!(
            judge_with_home(Path::new("/repo/.cargo/bin/tool"), Some(Path::new(HOME))),
            Durability::Unknown
        );
    }

    #[test]
    fn cargo_bin_without_home_is_unknown() {
        // HOME unknown → cannot confirm HOME-anchoring → Unknown, even though
        // the path shape matches `.cargo/bin`.
        assert_eq!(
            judge_with_home(Path::new("/home/u/.cargo/bin/ripgrep"), None),
            Durability::Unknown
        );
    }

    #[test]
    fn cargo_bin_nested_is_unknown() {
        // `<home>/.cargo/bin/sub/tool` is not a direct child of `.cargo/bin`
        // (extra `sub/` segment); the strict "single file segment" structural
        // match must reject it.
        assert_eq!(
            judge_with_home(
                Path::new("/home/u/.cargo/bin/sub/tool"),
                Some(Path::new(HOME))
            ),
            Durability::Unknown
        );
    }

    #[test]
    fn cargo_binx_lookalike_is_unknown() {
        // `.cargo/binx` is a similar-looking but distinct directory name; the
        // exact-suffix match must not treat it as `.cargo/bin`.
        assert_eq!(
            judge_with_home(Path::new("/home/u/.cargo/binx/tool"), Some(Path::new(HOME))),
            Durability::Unknown
        );
    }

    // --- Unknown: user dropbox and unrecognized locations ---

    #[test]
    fn local_bin_jupyter_is_unknown() {
        // ~/.local/bin mixes shebang/versioned, deliberately excluded.
        assert_eq!(judge_str("/home/u/.local/bin/jupyter"), Durability::Unknown);
    }

    #[test]
    fn home_bin_is_unknown() {
        assert_eq!(judge_str("/home/u/bin/mytool"), Durability::Unknown);
    }

    #[test]
    fn unrecognized_dir_is_unknown() {
        assert_eq!(judge_str("/some/random/dir/tool"), Durability::Unknown);
    }

    // --- ordering: NotDurable wins over a durable-looking surface ---

    #[test]
    fn ephemeral_shim_is_not_durable_despite_shim() {
        // jj-worktree cache: ephemeral + shim. NotDurable must win (decided first).
        assert_eq!(
            judge_str("/home/u/.cache/jj-worktree/.mise/shims/git"),
            Durability::NotDurable
        );
    }

    // --- O: Windows backslash normalization ---

    #[test]
    fn windows_chocolatey_lib_is_not_durable() {
        assert_eq!(
            judge_str(r"C:\ProgramData\chocolatey\lib\foo\bin\foo.exe"),
            Durability::NotDurable
        );
    }

    #[test]
    fn windows_winget_packages_is_not_durable() {
        assert_eq!(
            judge_str(r"C:\Users\u\AppData\Local\Microsoft\WinGet\Packages\Foo\bin\foo.exe"),
            Durability::NotDurable
        );
    }

    #[test]
    fn windows_scoop_apps_is_not_durable() {
        assert_eq!(
            judge_str(r"C:\Users\u\scoop\apps\foo\1.2.3\foo.exe"),
            Durability::NotDurable
        );
    }

    // --- helper-level direct tests ---

    // The first assertion uses a Unix absolute path and expects true.
    // On Windows, Path::is_absolute() returns false for paths without a drive
    // letter, so is_durable_direct_dir() returns false → guard with #[cfg(unix)].
    #[cfg(unix)]
    #[test]
    fn is_durable_direct_dir_exact_only() {
        assert!(is_durable_direct_dir(&PathBuf::from("/usr/bin/git")));
        assert!(!is_durable_direct_dir(&PathBuf::from("/usr/bin/sub/git")));
        assert!(!is_durable_direct_dir(&PathBuf::from("usr/bin/git")));
    }
}