openlatch-client 0.6.19

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! The user `Path` (`HKCU\Environment\Path`): where the Windows launcher shims' folder is put first
//! (`hooks::cli_shims_install`), and the half of the search path a long-running daemon cannot see
//! change — its own `PATH` froze when it started, so a CLI installed later is found only through a
//! fresh read of this value ([`effective_path`]).
//!
//! Written as `REG_EXPAND_SZ` so the developer's `%USERPROFILE%`-style entries keep expanding, and
//! only by the daemon's wiring pass and `uninstall`, both behind the machine-supervision gate. Every
//! edit is a pure string function here; the OS write sits behind [`PathSink`] so tests record it.
//!
//! It also answers which executable a command resolves to on Windows ([`SearchPath`]): the machine
//! `Path` (`HKLM\...\Session Manager\Environment`), then the user `Path`, each directory tried
//! with every `PATHEXT` extension — so doctor can tell a launcher shim shadowed by a machine-wide
//! install (AGT-6 C-9). Read only: nothing here ever writes the machine `Path` or runs a candidate.

use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};

/// The value's name under `HKCU\Environment`.
pub const NAME: &str = "Path";

/// The user `Path`, read and written whole. `read` answers `Ok(None)` when the value is unset.
pub trait PathSink {
    fn read(&self) -> Result<Option<String>, String>;
    fn write(&self, value: &str) -> Result<(), String>;
}

/// The real `HKCU\Environment\Path`, followed by a `WM_SETTINGCHANGE` broadcast on write.
#[cfg(windows)]
pub struct RegistryPath;

#[cfg(windows)]
impl PathSink for RegistryPath {
    fn read(&self) -> Result<Option<String>, String> {
        crate::core::login_env::registry::read(NAME)
    }
    fn write(&self, value: &str) -> Result<(), String> {
        crate::core::login_env::registry::apply_expand(NAME, value)
    }
}

/// This OS's user `Path`, when it has one (Windows only).
pub fn os_sink() -> Option<Box<dyn PathSink>> {
    #[cfg(windows)]
    {
        Some(Box::new(RegistryPath))
    }
    #[cfg(not(windows))]
    {
        None
    }
}

/// `%NAME%` references replaced through `lookup`; an unknown or unterminated one stays verbatim,
/// as Windows leaves it.
fn expand_with(raw: &str, lookup: &dyn Fn(&str) -> Option<String>) -> String {
    let mut out = String::with_capacity(raw.len());
    let mut rest = raw;
    while let Some(start) = rest.find('%') {
        out.push_str(&rest[..start]);
        let after = &rest[start + 1..];
        match after.find('%') {
            Some(end) if end > 0 => match lookup(&after[..end]) {
                Some(value) => {
                    out.push_str(&value);
                    rest = &after[end + 1..];
                }
                None => {
                    out.push('%');
                    rest = after;
                }
            },
            _ => {
                out.push('%');
                rest = after;
            }
        }
    }
    out.push_str(rest);
    out
}

fn env_lookup(name: &str) -> Option<String> {
    std::env::var(name).ok()
}

/// An entry as Windows compares it: expanded, trimmed, one separator, no trailing separator,
/// case-folded.
fn normalize(entry: &str, lookup: &dyn Fn(&str) -> Option<String>) -> String {
    expand_with(entry.trim(), lookup)
        .replace('/', "\\")
        .trim_end_matches('\\')
        .to_lowercase()
}

fn same(a: &str, b: &str, lookup: &dyn Fn(&str) -> Option<String>) -> bool {
    let a = normalize(a, lookup);
    !a.is_empty() && a == normalize(b, lookup)
}

/// Whether `entry` is the first non-empty entry of `path`.
pub fn is_first(path: &str, entry: &str) -> bool {
    path.split(';')
        .find(|e| !e.trim().is_empty())
        .is_some_and(|first| same(first, entry, &env_lookup))
}

/// Whether `path` names `entry` anywhere.
pub fn contains(path: &str, entry: &str) -> bool {
    path.split(';').any(|e| same(e, entry, &env_lookup))
}

/// `path` without any spelling of `entry`; every other entry is kept verbatim, in order.
pub fn remove_entry(path: &str, entry: &str) -> String {
    path.split(';')
        .filter(|e| !same(e, entry, &env_lookup))
        .collect::<Vec<_>>()
        .join(";")
}

/// `entry` first, then `path` without it. Idempotent; an entry later in the list is moved back to
/// the front, and every other entry is kept verbatim.
pub fn prepend_entry(path: &str, entry: &str) -> String {
    let rest = remove_entry(path, entry);
    if rest.trim_matches(';').is_empty() {
        entry.to_string()
    } else {
        format!("{entry};{}", rest.trim_start_matches(';'))
    }
}

/// Put `entry` first in the user `Path`. `Ok(true)` when the value was written.
pub fn ensure_first(sink: &dyn PathSink, entry: &Path) -> Result<bool, String> {
    let entry = entry.display().to_string();
    let current = sink.read()?.unwrap_or_default();
    if is_first(&current, &entry) {
        return Ok(false);
    }
    sink.write(&prepend_entry(&current, &entry))?;
    Ok(true)
}

/// Take `entry` out of the user `Path`. `Ok(true)` when the value was written.
pub fn remove(sink: &dyn PathSink, entry: &Path) -> Result<bool, String> {
    let entry = entry.display().to_string();
    let Some(current) = sink.read()? else {
        return Ok(false);
    };
    if !contains(&current, &entry) {
        return Ok(false);
    }
    sink.write(&remove_entry(&current, &entry))?;
    Ok(true)
}

/// Whether `entry` is first in this OS's user `Path`, read fresh. `false` off Windows.
pub fn os_is_first(entry: &Path) -> bool {
    os_sink()
        .and_then(|s| s.read().ok().flatten())
        .is_some_and(|p| is_first(&p, &entry.display().to_string()))
}

/// Pure [`effective_path`]: `process` then the expanded `user` entries, de-duplicated as Windows
/// compares them, with `skip` (the shims folder) left out.
pub fn effective_path_from(process: &OsStr, user: Option<&str>, skip: &Path) -> OsString {
    let skip = skip.display().to_string();
    let mut seen: Vec<String> = Vec::new();
    let mut out: Vec<PathBuf> = Vec::new();
    let user_dirs = user
        .into_iter()
        .flat_map(|u| u.split(';'))
        .map(|e| PathBuf::from(expand_with(e.trim(), &env_lookup)));
    for dir in std::env::split_paths(process).chain(user_dirs) {
        let text = dir.display().to_string();
        let key = normalize(&text, &env_lookup);
        if key.is_empty() || same(&text, &skip, &env_lookup) || seen.contains(&key) {
            continue;
        }
        seen.push(key);
        out.push(dir);
    }
    std::env::join_paths(out).unwrap_or_default()
}

/// The search path detection walks: this process's `PATH`, plus — on Windows — the user `Path`
/// read fresh from the registry, so a CLI installed after the daemon started is still found.
/// The launcher shims' folder is never part of it: a shim is not an installed CLI.
pub fn effective_path() -> OsString {
    let process = std::env::var_os("PATH").unwrap_or_default();
    let user = os_sink().and_then(|s| s.read().ok().flatten());
    let skip = crate::hooks::cli_shims_install::shims_dir(&crate::config::openlatch_dir());
    effective_path_from(&process, user.as_deref(), &skip)
}

/// `PATHEXT` when neither the machine value nor this process has one: Windows' own default order
/// for the executable kinds a CLI ships as.
pub const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";

/// The registry key holding the machine environment, under `HKEY_LOCAL_MACHINE`.
#[cfg(windows)]
const MACHINE_ENV_KEY: &str = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";

/// Reads `name` from the machine environment, raw (`RRF_NOEXPAND`), with whether it is a
/// `REG_EXPAND_SZ`. `Ok(None)` when unset.
#[cfg(windows)]
fn read_machine_env(name: &str) -> Result<Option<(String, bool)>, String> {
    crate::core::login_env::registry::read_value(
        windows_sys::Win32::System::Registry::HKEY_LOCAL_MACHINE,
        MACHINE_ENV_KEY,
        name,
    )
    .map_err(|e| format!("HKLM: {e}"))
}

/// The machine `Path`, read fresh from the registry — a daemon's own `PATH` froze when it started.
/// Only a `REG_EXPAND_SZ` value has its `%NAME%` references expanded; a `REG_SZ` is taken
/// verbatim, as Windows takes it. `Ok(None)` when unset.
#[cfg(windows)]
pub fn machine_path() -> Result<Option<String>, String> {
    Ok(read_machine_env(NAME)?.map(|(raw, expand)| {
        if expand {
            expand_with(&raw, &env_lookup)
        } else {
            raw
        }
    }))
}

/// The directories Windows searches for a command typed in a new shell: the machine `Path`, then
/// the user `Path` with its `%NAME%` references expanded, de-duplicated as Windows compares
/// entries (as [`effective_path_from`] does). An unreadable machine value is passed as `None`.
pub fn combined_dirs(machine: Option<&str>, user: Option<&str>) -> Vec<PathBuf> {
    combined_dirs_with(machine, user, &env_lookup)
}

fn combined_dirs_with(
    machine: Option<&str>,
    user: Option<&str>,
    lookup: &dyn Fn(&str) -> Option<String>,
) -> Vec<PathBuf> {
    let machine_dirs = machine
        .into_iter()
        .flat_map(|m| m.split(';'))
        .map(str::to_string);
    let user_dirs = user
        .into_iter()
        .flat_map(|u| u.split(';'))
        .map(|e| expand_with(e.trim(), lookup));
    let mut seen: Vec<String> = Vec::new();
    let mut out: Vec<PathBuf> = Vec::new();
    for entry in machine_dirs.chain(user_dirs) {
        let entry = entry.trim().trim_matches('"').to_string();
        // Compared as resolved, never expanded again: a `REG_SZ` machine entry keeps a literal
        // `%NAME%`, which Windows searches as written and which names no real directory.
        let key = normalize(&entry, &|_| None);
        if key.is_empty() || seen.contains(&key) {
            continue;
        }
        seen.push(key);
        out.push(PathBuf::from(entry));
    }
    out
}

/// Whether `path` names something on disk Windows could run. `symlink_metadata`, not `exists`:
/// an App Execution Alias under `WindowsApps` is a reparse point that `metadata` cannot follow,
/// and Windows still runs it. A directory named like an executable is not one.
pub fn present(path: &Path) -> bool {
    std::fs::symlink_metadata(path).is_ok_and(|m| !m.is_dir())
}

/// The file `name` resolves to: for each directory in order, each `PATHEXT` extension in order.
/// Extensions are tried lower-cased. A bare, extensionless `name` is never a hit — Windows does not run one (the launcher's `sh`
/// sibling is one). `stat` answers whether a candidate exists; it is never executed.
pub fn first_hit(
    dirs: &[PathBuf],
    name: &str,
    pathext: &str,
    stat: &dyn Fn(&Path) -> bool,
) -> Option<PathBuf> {
    // Lower-cased: Windows matches names case-insensitively, `PATHEXT` is upper-case and the files
    // a CLI installs are not — so the hit reads as the file on disk does.
    let exts: Vec<String> = pathext
        .split(';')
        .map(|e| e.trim().to_lowercase())
        .filter(|e| !e.is_empty())
        .collect();
    dirs.iter().find_map(|dir| {
        exts.iter()
            .map(|ext| dir.join(format!("{name}{ext}")))
            .find(|candidate| stat(candidate))
    })
}

/// The executable shadowing the launcher in `shims_dir`: the first hit for `name` when it is not in
/// the shims folder. `None` when the shim wins, or when nothing resolves at all.
pub fn shadowing_in(
    dirs: &[PathBuf],
    name: &str,
    pathext: &str,
    shims_dir: &Path,
    stat: &dyn Fn(&Path) -> bool,
) -> Option<PathBuf> {
    let hit = first_hit(dirs, name, pathext, stat)?;
    let dir = hit.parent()?.display().to_string();
    (!same(&dir, &shims_dir.display().to_string(), &env_lookup)).then_some(hit)
}

/// `PATHEXT` in the order Windows takes it: the machine value, else this process's, else
/// [`DEFAULT_PATHEXT`] — a blank value counts as unset at every step.
pub fn pathext_of(machine: Option<String>, process: Option<String>) -> String {
    let set = |v: Option<String>| v.filter(|p| !p.trim().is_empty());
    set(machine)
        .or_else(|| set(process))
        .unwrap_or_else(|| DEFAULT_PATHEXT.to_string())
}

/// The Windows command search path, read fresh: the machine `Path`, the user `Path` and
/// `PATHEXT`. Not modeled, and named in doctor's remedy instead: PowerShell aliases and
/// functions, and `cmd`'s current directory.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SearchPath {
    pub dirs: Vec<PathBuf>,
    pub pathext: String,
    /// Why the machine `Path` could not be read; it is then treated as empty.
    pub machine_unreadable: Option<String>,
}

impl SearchPath {
    /// This OS's search path. Off Windows it is empty: there is no launcher to shadow.
    pub fn read() -> Self {
        #[cfg(windows)]
        {
            let (machine, machine_unreadable) = match machine_path() {
                Ok(m) => (m, None),
                Err(e) => (None, Some(e)),
            };
            let user = os_sink().and_then(|s| s.read().ok().flatten());
            let pathext = pathext_of(
                read_machine_env("PATHEXT")
                    .ok()
                    .flatten()
                    .map(|(raw, _)| raw),
                std::env::var("PATHEXT").ok(),
            );
            Self {
                dirs: combined_dirs(machine.as_deref(), user.as_deref()),
                pathext,
                machine_unreadable,
            }
        }
        #[cfg(not(windows))]
        {
            Self {
                pathext: DEFAULT_PATHEXT.to_string(),
                ..Self::default()
            }
        }
    }

    /// [`shadowing_in`] over this search path, against the files on disk.
    pub fn shadowing(&self, name: &str, shims_dir: &Path) -> Option<PathBuf> {
        shadowing_in(&self.dirs, name, &self.pathext, shims_dir, &present)
    }
}

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

    #[derive(Default)]
    struct Recording {
        value: Mutex<Option<String>>,
        writes: Mutex<Vec<String>>,
    }

    impl PathSink for Recording {
        fn read(&self) -> Result<Option<String>, String> {
            Ok(self.value.lock().unwrap().clone())
        }
        fn write(&self, value: &str) -> Result<(), String> {
            *self.value.lock().unwrap() = Some(value.to_string());
            self.writes.lock().unwrap().push(value.to_string());
            Ok(())
        }
    }

    fn no_vars(_: &str) -> Option<String> {
        None
    }

    #[test]
    fn expansion_replaces_known_names_and_keeps_the_rest() {
        let lookup = |n: &str| (n == "HOME_X").then(|| "C:\\Users\\a".to_string());
        assert_eq!(expand_with("%HOME_X%\\bin", &lookup), "C:\\Users\\a\\bin");
        assert_eq!(expand_with("%NOPE%\\bin", &lookup), "%NOPE%\\bin");
        assert_eq!(expand_with("50%", &lookup), "50%");
        assert_eq!(expand_with("%%", &no_vars), "%%");
    }

    #[test]
    fn entries_compare_case_insensitively_without_trailing_separator() {
        assert!(same("C:\\OL\\shims\\", "c:/ol/SHIMS", &no_vars));
        assert!(!same("", "", &no_vars));
        assert!(!same("C:\\a", "C:\\ab", &no_vars));
    }

    #[test]
    fn prepend_puts_the_entry_first_once() {
        assert_eq!(prepend_entry("", "C:\\s"), "C:\\s");
        assert_eq!(prepend_entry("C:\\a;C:\\b", "C:\\s"), "C:\\s;C:\\a;C:\\b");
        assert_eq!(
            prepend_entry("C:\\s;C:\\a", "C:\\s"),
            "C:\\s;C:\\a",
            "idempotent"
        );
        assert_eq!(
            prepend_entry("C:\\a;c:\\S\\;C:\\b", "C:\\s"),
            "C:\\s;C:\\a;C:\\b",
            "a later spelling moves back to the front"
        );
    }

    #[test]
    fn other_entries_are_kept_verbatim() {
        let path = "%USERPROFILE%\\AppData\\Local\\Microsoft\\WindowsApps;C:\\tools";
        assert_eq!(
            prepend_entry(path, "C:\\s"),
            format!("C:\\s;{path}"),
            "%VAR% entries are not expanded on write"
        );
        assert_eq!(remove_entry(&format!("C:\\s;{path}"), "C:\\s"), path);
    }

    #[test]
    fn is_first_skips_empty_entries() {
        assert!(is_first(";C:\\s;C:\\a", "C:\\s"));
        assert!(!is_first("C:\\a;C:\\s", "C:\\s"));
        assert!(!is_first("", "C:\\s"));
    }

    #[test]
    fn ensure_first_writes_only_when_needed() {
        let sink = Recording::default();
        assert!(ensure_first(&sink, Path::new("C:\\s")).unwrap());
        assert!(!ensure_first(&sink, Path::new("C:\\s")).unwrap());
        assert_eq!(sink.writes.lock().unwrap().len(), 1);

        *sink.value.lock().unwrap() = Some("C:\\installer;C:\\s".into());
        assert!(ensure_first(&sink, Path::new("C:\\s")).unwrap());
        assert_eq!(sink.read().unwrap().as_deref(), Some("C:\\s;C:\\installer"));
    }

    #[test]
    fn remove_drops_the_entry_and_nothing_else() {
        let sink = Recording::default();
        assert!(!remove(&sink, Path::new("C:\\s")).unwrap(), "unset value");
        *sink.value.lock().unwrap() = Some("C:\\a".into());
        assert!(!remove(&sink, Path::new("C:\\s")).unwrap(), "absent entry");
        *sink.value.lock().unwrap() = Some("C:\\s;C:\\a".into());
        assert!(remove(&sink, Path::new("C:\\s")).unwrap());
        assert_eq!(sink.read().unwrap().as_deref(), Some("C:\\a"));
    }

    #[test]
    fn effective_path_merges_dedups_and_skips_the_shims_folder() {
        let tmp = tempfile::tempdir().unwrap();
        let (a, b, shims) = (
            tmp.path().join("a"),
            tmp.path().join("b"),
            tmp.path().join("shims"),
        );
        let process = std::env::join_paths([&shims, &a]).unwrap();
        let user = format!("{};{}", a.display(), b.display());
        let merged: Vec<PathBuf> =
            std::env::split_paths(&effective_path_from(&process, Some(&user), &shims)).collect();
        assert_eq!(merged, vec![a, b]);
    }

    fn dirs(list: &[&str]) -> Vec<PathBuf> {
        list.iter().map(PathBuf::from).collect()
    }

    #[test]
    fn combined_dirs_put_the_machine_path_before_the_user_path() {
        let lookup =
            |n: &str| (n == "LOCALAPPDATA").then(|| "C:\\Users\\a\\AppData\\Local".to_string());
        assert_eq!(
            combined_dirs_with(
                Some("C:\\Windows\\system32;C:\\Program Files\\nodejs\\"),
                Some("%LOCALAPPDATA%\\OpenLatch\\shims;C:\\tools"),
                &lookup,
            ),
            dirs(&[
                "C:\\Windows\\system32",
                "C:\\Program Files\\nodejs\\",
                "C:\\Users\\a\\AppData\\Local\\OpenLatch\\shims",
                "C:\\tools",
            ])
        );
    }

    #[test]
    fn combined_dirs_drop_duplicates_and_empty_entries() {
        assert_eq!(
            combined_dirs_with(
                Some("C:\\a;;\"C:\\b\";C:\\A\\"),
                Some("c:/b;C:\\c; "),
                &no_vars
            ),
            dirs(&["C:\\a", "C:\\b", "C:\\c"]),
            "a later spelling of an earlier entry, quoted or not, is the same directory"
        );
    }

    #[test]
    fn an_unreadable_machine_path_is_treated_as_empty() {
        assert_eq!(
            combined_dirs_with(None, Some("C:\\s;C:\\a"), &no_vars),
            dirs(&["C:\\s", "C:\\a"])
        );
        assert!(combined_dirs_with(None, None, &no_vars).is_empty());
    }

    /// `dir\file` as `first_hit` builds it on this OS (`join` uses `/` off Windows).
    fn at(dir: &str, file: &str) -> PathBuf {
        Path::new(dir).join(file)
    }

    /// A fake disk that compares names case-insensitively, as Windows does (`PATHEXT` is
    /// upper-case, files on disk rarely are).
    fn on_disk(files: Vec<PathBuf>) -> impl Fn(&Path) -> bool {
        let lower = |p: &Path| p.display().to_string().to_lowercase();
        move |p: &Path| files.iter().any(|f| lower(f) == lower(p))
    }

    #[test]
    fn first_hit_walks_directories_before_extensions() {
        let stat = on_disk(vec![
            at("C:\\m", "opencode.cmd"),
            at("C:\\u", "opencode.exe"),
        ]);
        assert_eq!(
            first_hit(
                &dirs(&["C:\\m", "C:\\u"]),
                "opencode",
                DEFAULT_PATHEXT,
                &stat
            ),
            Some(at("C:\\m", "opencode.cmd")),
            "an earlier directory wins whatever its extension"
        );
    }

    #[test]
    fn first_hit_follows_pathext_order_within_a_directory() {
        let stat = on_disk(vec![at("C:\\d", "cline.cmd"), at("C:\\d", "cline.exe")]);
        let d = dirs(&["C:\\d"]);
        assert_eq!(
            first_hit(&d, "cline", DEFAULT_PATHEXT, &stat),
            Some(at("C:\\d", "cline.exe"))
        );
        assert_eq!(
            first_hit(&d, "cline", ".CMD; .EXE", &stat),
            Some(at("C:\\d", "cline.cmd"))
        );
        assert_eq!(
            first_hit(&d, "cline", "", &stat),
            None,
            "no extension, no hit"
        );
    }

    #[test]
    fn first_hit_skips_the_bare_extensionless_name() {
        let stat = on_disk(vec![
            at("C:\\shims", "opencode"),
            at("C:\\real", "opencode.exe"),
        ]);
        assert_eq!(
            first_hit(
                &dirs(&["C:\\shims", "C:\\real"]),
                "opencode",
                DEFAULT_PATHEXT,
                &stat
            ),
            Some(at("C:\\real", "opencode.exe"))
        );
    }

    #[test]
    fn a_reparse_point_alias_counts_as_a_hit() {
        // `metadata` fails on an App Execution Alias; `symlink_metadata` does not. A dangling
        // symlink stands in for it on any OS: it exists only as a link.
        let tmp = tempfile::tempdir().unwrap();
        let alias = tmp.path().join("cursor-agent.exe");
        #[cfg(unix)]
        std::os::unix::fs::symlink(tmp.path().join("gone"), &alias).unwrap();
        #[cfg(windows)]
        if let Err(e) = std::os::windows::fs::symlink_file(tmp.path().join("gone"), &alias) {
            // CI's Windows runner can create symlinks: there a setup failure fails the cell
            // instead of passing it unasserted. A developer machine without the privilege skips,
            // and says so.
            assert!(
                std::env::var_os("CI").is_none(),
                "the Windows CI runner must prove the alias cell: {e}"
            );
            eprintln!("skipped: no symlink privilege on this machine ({e})");
            return;
        }
        assert!(!alias.exists(), "the stand-in alias must not resolve");
        assert!(present(&alias));
        assert_eq!(
            first_hit(
                &[tmp.path().to_path_buf()],
                "cursor-agent",
                ".EXE",
                &present
            ),
            Some(alias)
        );
    }

    #[test]
    fn a_literal_machine_entry_never_hides_its_expanded_user_spelling() {
        let lookup = |n: &str| (n == "OL_SHIMS").then(|| "C:\\ol\\shims".to_string());
        assert_eq!(
            combined_dirs_with(Some("%OL_SHIMS%;C:\\m"), Some("C:\\ol\\shims"), &lookup),
            dirs(&["%OL_SHIMS%", "C:\\m", "C:\\ol\\shims"]),
            "a REG_SZ entry is searched as written: the real user entry stays"
        );
        // A user entry is expanded before it is compared, so two spellings of one user
        // directory are still one entry.
        assert_eq!(
            combined_dirs_with(None, Some("%OL_SHIMS%;C:\\ol\\shims\\"), &lookup),
            dirs(&["C:\\ol\\shims"])
        );
    }

    #[test]
    fn a_directory_named_like_the_cli_is_not_a_hit() {
        let tmp = tempfile::tempdir().unwrap();
        let (machine, shims) = (tmp.path().join("m"), tmp.path().join("shims"));
        std::fs::create_dir_all(machine.join("opencode.exe")).unwrap();
        std::fs::create_dir_all(&shims).unwrap();
        std::fs::write(shims.join("opencode.exe"), b"").unwrap();
        assert!(!present(&machine.join("opencode.exe")));
        assert_eq!(
            first_hit(&[machine, shims.clone()], "opencode", ".EXE", &present),
            Some(shims.join("opencode.exe"))
        );
    }

    #[test]
    fn pathext_falls_back_machine_then_process_then_default() {
        let s = |v: &str| Some(v.to_string());
        assert_eq!(pathext_of(s(".EXE"), s(".CMD")), ".EXE");
        assert_eq!(
            pathext_of(s("  "), s(".CMD")),
            ".CMD",
            "a blank machine value is unset"
        );
        assert_eq!(pathext_of(None, s(".CMD")), ".CMD");
        assert_eq!(pathext_of(s(""), s(" ")), DEFAULT_PATHEXT);
        assert_eq!(pathext_of(None, None), DEFAULT_PATHEXT);
    }

    #[test]
    fn shadowing_names_a_hit_outside_the_shims_folder_only() {
        let shims = Path::new("C:\\Users\\a\\.openlatch\\shims");
        let listed = "c:\\users\\A\\.openlatch\\shims\\";
        let search = dirs(&["C:\\m", listed, "C:\\u"]);
        let shim = at(listed, "opencode.exe");
        assert_eq!(
            shadowing_in(
                &search,
                "opencode",
                DEFAULT_PATHEXT,
                shims,
                &on_disk(vec![shim.clone()])
            ),
            None,
            "the shim is the first hit"
        );
        let machine_install = on_disk(vec![at("C:\\m", "opencode.exe"), shim.clone()]);
        assert_eq!(
            shadowing_in(
                &search,
                "opencode",
                DEFAULT_PATHEXT,
                shims,
                &machine_install
            ),
            Some(at("C:\\m", "opencode.exe"))
        );
        let user_install_after = on_disk(vec![at("C:\\u", "opencode.exe"), shim]);
        assert_eq!(
            shadowing_in(
                &search,
                "opencode",
                DEFAULT_PATHEXT,
                shims,
                &user_install_after
            ),
            None,
            "an install after the shims is what the shim runs"
        );
        assert_eq!(
            shadowing_in(
                &search,
                "opencode",
                DEFAULT_PATHEXT,
                shims,
                &on_disk(vec![])
            ),
            None,
            "nothing resolves"
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn the_search_path_is_empty_off_windows() {
        let search = SearchPath::read();
        assert!(search.dirs.is_empty());
        assert_eq!(search.machine_unreadable, None);
        assert_eq!(search.shadowing("opencode", Path::new("/x/shims")), None);
    }
}