mise 2026.9.3

Dev tools, env vars, and tasks in one CLI
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
//! Plugin-declared system dependencies with capability detection.
//!
//! Source-compiling plugins (php, erlang, postgres, ...) need system
//! prerequisites — build tools, libraries, headers. Historically these lived
//! as README prose, so users only discovered them when a build failed halfway
//! through. A plugin can instead declare them as structured *capability
//! checks* (see [`SystemDepCheck`]) plus per-package-manager remediation hints.
//!
//! Detection is the source of truth: a check that passes is satisfied,
//! full stop — mise never asks *how* the capability got there, so nix,
//! MacPorts, and from-source installs all pass without ceremony. The package
//! hints are consulted only to *offer* installing the missing subset via the
//! existing [`crate::system::packages`] engine.

use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex};

use indexmap::IndexMap;
use once_cell::sync::Lazy;
use versions::Versioning;

use crate::config::Settings;
use crate::system::packages::{self, PackageRequest, SystemPackageManager};

/// A single capability a plugin requires before it can install.
#[derive(Debug, Clone)]
pub(crate) struct SystemDep {
    pub check: SystemDepCheck,
    /// Optional version constraint (only meaningful for `Bin`/`PkgConfig`).
    pub version: Option<VersionConstraint>,
    /// If set, this dependency is optional and this string is the reason it
    /// might be wanted (e.g. "observer GUI"). Missing optional deps never
    /// prompt or fail — they surface as a single informational line.
    pub optional: Option<String>,
    /// manager name -> candidate package names, used only for remediation
    /// hints. More than one candidate means the same capability is packaged
    /// under different names across distro releases (apt's `libaio1` became
    /// `libaio1t64` in the 64-bit time_t transition); the first candidate the
    /// manager actually has wins, resolved lazily at remediation time.
    pub packages: IndexMap<String, Vec<String>>,
}

/// How to detect whether a [`SystemDep`] is satisfied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SystemDepCheck {
    /// executable resolvable on `PATH`
    Bin(String),
    /// `pkg-config --exists <name>` (a `.pc` module)
    PkgConfig(String),
    /// dynamic linker can resolve a soname, e.g. `libaio.so.1` (Linux only)
    SharedLib(String),
    /// escape hatch: a shell command whose exit status 0 means satisfied
    Command(String),
}

impl SystemDepCheck {
    fn kind(&self) -> &'static str {
        match self {
            SystemDepCheck::Bin(_) => "bin",
            SystemDepCheck::PkgConfig(_) => "pkgconfig",
            SystemDepCheck::SharedLib(_) => "sharedlib",
            SystemDepCheck::Command(_) => "command",
        }
    }

    fn value(&self) -> &str {
        match self {
            SystemDepCheck::Bin(s)
            | SystemDepCheck::PkgConfig(s)
            | SystemDepCheck::SharedLib(s)
            | SystemDepCheck::Command(s) => s,
        }
    }
}

/// A version comparison operator for [`VersionConstraint`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VersionOp {
    AtLeast,
    Greater,
    AtMost,
    Less,
    Exact,
}

impl VersionOp {
    fn symbol(self) -> &'static str {
        match self {
            VersionOp::AtLeast => ">=",
            VersionOp::Greater => ">",
            VersionOp::AtMost => "<=",
            VersionOp::Less => "<",
            VersionOp::Exact => "=",
        }
    }
}

/// A parsed version constraint like `>=3.0`. A bare version (`3.0`) means
/// `>=3.0` — the common "at least this" case.
///
/// Note: this compares versions of *system binaries/libraries* declared by a
/// plugin author against what is installed on the machine. It is NOT used to
/// resolve or order mise tool versions (see the semver rules in CLAUDE.md);
/// it is the same class of comparison as [`crate::config::config_file::min_version`].
#[derive(Debug, Clone)]
pub(crate) struct VersionConstraint {
    pub op: VersionOp,
    pub version: Versioning,
}

impl VersionConstraint {
    pub(crate) fn parse(s: &str) -> eyre::Result<Self> {
        let s = s.trim();
        let (op, rest) = if let Some(r) = s.strip_prefix(">=") {
            (VersionOp::AtLeast, r)
        } else if let Some(r) = s.strip_prefix("<=") {
            (VersionOp::AtMost, r)
        } else if let Some(r) = s.strip_prefix('>') {
            (VersionOp::Greater, r)
        } else if let Some(r) = s.strip_prefix('<') {
            (VersionOp::Less, r)
        } else if let Some(r) = s.strip_prefix('=') {
            (VersionOp::Exact, r)
        } else {
            (VersionOp::AtLeast, s)
        };
        let version = Versioning::new(rest.trim())
            .ok_or_else(|| eyre::eyre!("invalid version constraint '{s}'"))?;
        Ok(Self { op, version })
    }

    pub(crate) fn satisfied_by(&self, current: &Versioning) -> bool {
        match self.op {
            VersionOp::AtLeast => current >= &self.version,
            VersionOp::Greater => current > &self.version,
            VersionOp::AtMost => current <= &self.version,
            VersionOp::Less => current < &self.version,
            VersionOp::Exact => current == &self.version,
        }
    }
}

impl fmt::Display for VersionConstraint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.op.symbol(), self.version)
    }
}

impl SystemDep {
    /// Human-readable capability label, e.g. `bison >=3.0`, `pkg-config libxml-2.0`.
    pub(crate) fn label(&self) -> String {
        let base = match &self.check {
            SystemDepCheck::Bin(name) => name.clone(),
            SystemDepCheck::PkgConfig(name) => format!("pkg-config {name}"),
            SystemDepCheck::SharedLib(name) => format!("shared library {name}"),
            SystemDepCheck::Command(cmd) => format!("`{cmd}`"),
        };
        match &self.version {
            Some(v) => format!("{base} {v}"),
            None => base,
        }
    }

    /// Stable fingerprint used to memoize detection across tools that declare
    /// the same dependency (php + postgres both needing bison probe once).
    fn fingerprint(&self) -> String {
        match &self.version {
            Some(v) => format!("{}:{}:{v}", self.check.kind(), self.check.value()),
            None => format!("{}:{}", self.check.kind(), self.check.value()),
        }
    }
}

impl fmt::Display for SystemDep {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.label())
    }
}

/// The result of probing one [`SystemDep`] on the host.
#[derive(Debug, Clone)]
pub(crate) struct DepStatus {
    pub dep: SystemDep,
    /// detected version, if a version was extracted
    pub found: Option<String>,
    pub satisfied: bool,
    /// why it is unsatisfied (or a note when satisfied)
    pub reason: Option<String>,
}

impl TryFrom<vfox::SystemDependency> for SystemDep {
    type Error = eyre::Error;

    fn try_from(d: vfox::SystemDependency) -> eyre::Result<Self> {
        let check = match (&d.bin, &d.pkgconfig, &d.sharedlib, &d.command) {
            (Some(b), None, None, None) => SystemDepCheck::Bin(b.clone()),
            (None, Some(p), None, None) => SystemDepCheck::PkgConfig(p.clone()),
            (None, None, Some(s), None) => SystemDepCheck::SharedLib(s.clone()),
            (None, None, None, Some(c)) => SystemDepCheck::Command(c.clone()),
            _ => eyre::bail!(
                "systemDependencies entry must set exactly one of bin/pkgconfig/sharedlib/command"
            ),
        };
        // A version constraint is only meaningful for bin/pkgconfig (we probe
        // `--version` / `--modversion`). If declared on sharedlib/command,
        // keep the check but drop the version with a warning rather than
        // silently honoring a constraint that is never enforced.
        let version = match (&check, &d.version) {
            (_, None) => None,
            (SystemDepCheck::Bin(_) | SystemDepCheck::PkgConfig(_), Some(v)) => {
                Some(VersionConstraint::parse(v)?)
            }
            (check, Some(_)) => {
                warn!(
                    "systemDependencies: `version` is only supported for bin/pkgconfig checks, ignoring it for the {} check",
                    check.kind()
                );
                None
            }
        };
        // Normalize candidate names here so nothing downstream can pass a
        // package manager a padded or empty operand, and a hint left with no
        // usable name at all reports as unremediable rather than as a nameless
        // install.
        let packages = d
            .packages
            .into_iter()
            .map(|(mgr, candidates)| {
                let candidates: Vec<String> = candidates
                    .into_iter()
                    .map(|c| c.trim().to_string())
                    .filter(|c| !c.is_empty())
                    .collect();
                (mgr, candidates)
            })
            .filter(|(_, candidates)| !candidates.is_empty())
            .collect();
        Ok(SystemDep {
            check,
            version,
            optional: d.optional.clone(),
            packages,
        })
    }
}

/// Host-only detection result: `(satisfied, found_version, reason)`.
type DetectOutcome = (bool, Option<String>, Option<String>);

static CACHE: Lazy<Mutex<HashMap<String, DetectOutcome>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Detect all `deps`, memoized. Concurrency-safe; two calls with the same
/// fingerprint reuse the first result.
pub(crate) async fn detect(deps: &[SystemDep]) -> Vec<DepStatus> {
    detect_inner(deps, true).await
}

/// Detect all `deps`, bypassing (and refreshing) the memo cache. Used to
/// re-verify after remediation, since a package we just installed changes the
/// answer.
pub(crate) async fn detect_fresh(deps: &[SystemDep]) -> Vec<DepStatus> {
    detect_inner(deps, false).await
}

async fn detect_inner(deps: &[SystemDep], use_cache: bool) -> Vec<DepStatus> {
    let mut out = Vec::with_capacity(deps.len());
    for dep in deps {
        // The cache keys on the check + version only (the fingerprint), so it
        // must store just the detection *outcome* — not the whole DepStatus.
        // The `dep` (its `optional`/`packages`) belongs to the current caller;
        // reusing the first caller's dep would misclassify a required dep as
        // optional when two tools share the same check.
        let fp = dep.fingerprint();
        let (satisfied, found, reason) =
            if use_cache && let Some(cached) = CACHE.lock().unwrap().get(&fp).cloned() {
                cached
            } else {
                let outcome = detect_outcome(dep).await;
                CACHE.lock().unwrap().insert(fp, outcome.clone());
                outcome
            };
        out.push(DepStatus {
            dep: dep.clone(),
            found,
            satisfied,
            reason,
        });
    }
    out
}

/// Probe a single dep, returning `(satisfied, found_version, reason)` — the
/// part of the result that depends only on the host, not on which tool
/// declared the dep.
async fn detect_outcome(dep: &SystemDep) -> DetectOutcome {
    match &dep.check {
        SystemDepCheck::Bin(name) => check_bin(name, dep.version.as_ref()).await,
        SystemDepCheck::PkgConfig(name) => check_pkgconfig(name, dep.version.as_ref()).await,
        SystemDepCheck::SharedLib(name) => check_sharedlib(name).await,
        SystemDepCheck::Command(cmd) => check_command(cmd).await,
    }
}

async fn check_bin(
    name: &str,
    constraint: Option<&VersionConstraint>,
) -> (bool, Option<String>, Option<String>) {
    let Some(path) = crate::file::which_spawnable(name) else {
        return (false, None, Some(format!("`{name}` not found on PATH")));
    };
    let Some(constraint) = constraint else {
        return (true, None, None);
    };
    match run_capture(&path, &["--version"]).await {
        Some((_, output)) => match extract_version(&output) {
            Some(v) => {
                let versioning = Versioning::new(&v);
                match versioning {
                    Some(versioning) => {
                        let ok = constraint.satisfied_by(&versioning);
                        (ok, Some(v), None)
                    }
                    // unparseable — do not block; presence is enough
                    None => {
                        debug!(
                            "system dep: `{name}` version '{v}' unparseable, treating as satisfied"
                        );
                        (true, Some(v), None)
                    }
                }
            }
            None => {
                debug!(
                    "system dep: could not extract version from `{name} --version`, treating as satisfied"
                );
                (true, None, None)
            }
        },
        None => {
            debug!("system dep: `{name} --version` failed to run, treating as satisfied");
            (true, None, None)
        }
    }
}

async fn check_pkgconfig(
    name: &str,
    constraint: Option<&VersionConstraint>,
) -> (bool, Option<String>, Option<String>) {
    let Some(path) = crate::file::which_spawnable("pkg-config") else {
        return (
            false,
            None,
            Some("pkg-config is not installed (needed to detect this library)".to_string()),
        );
    };
    match run_capture(&path, &["--exists", name]).await {
        Some((true, _)) => {}
        Some((false, _)) => {
            return (
                false,
                None,
                Some(format!("pkg-config module `{name}` not found")),
            );
        }
        None => {
            // Timeout or spawn failure — inconclusive, so don't block (matches
            // the "presence is enough" fallback in check_bin).
            debug!(
                "system dep: `pkg-config --exists {name}` timed out or failed to spawn, treating as satisfied"
            );
            return (true, None, None);
        }
    }
    let Some(constraint) = constraint else {
        return (true, None, None);
    };
    match run_capture(&path, &["--modversion", name]).await {
        Some((true, output)) => {
            let v = output.trim().to_string();
            match Versioning::new(&v) {
                Some(versioning) => (constraint.satisfied_by(&versioning), Some(v), None),
                None => {
                    debug!(
                        "system dep: pkg-config modversion '{v}' unparseable, treating as satisfied"
                    );
                    (true, Some(v), None)
                }
            }
        }
        _ => (true, None, None),
    }
}

#[cfg(target_os = "linux")]
async fn check_sharedlib(soname: &str) -> (bool, Option<String>, Option<String>) {
    // Primary: ldconfig's cache lists every soname the dynamic linker knows.
    // Each entry looks like `	libaio.so.1 (libc6,x86-64) => /path/libaio.so.1`,
    // so match the advertised soname as the whole first token — a substring
    // check would let `libfoo.so.10` satisfy a request for `libfoo.so.1`.
    for ldconfig in ["ldconfig", "/sbin/ldconfig"] {
        if let Some((true, output)) = run_capture(ldconfig, &["-p"]).await {
            if output
                .lines()
                .any(|l| l.split_whitespace().next() == Some(soname))
            {
                return (true, None, None);
            }
            // ldconfig ran and did not list it; still check LD_LIBRARY_PATH below
            break;
        }
    }
    // Fallback: honor LD_LIBRARY_PATH dirs the cache doesn't cover.
    if let Ok(paths) = std::env::var("LD_LIBRARY_PATH") {
        for dir in std::env::split_paths(&paths) {
            if dir.join(soname).exists() {
                return (true, None, None);
            }
        }
    }
    (
        false,
        None,
        Some(format!(
            "shared library `{soname}` not found by the dynamic linker"
        )),
    )
}

#[cfg(not(target_os = "linux"))]
async fn check_sharedlib(soname: &str) -> (bool, Option<String>, Option<String>) {
    debug!("system dep: sharedlib check for `{soname}` is Linux-only, treating as satisfied");
    (true, None, None)
}

async fn check_command(cmd: &str) -> (bool, Option<String>, Option<String>) {
    let (program, args): (&str, Vec<&str>) = if cfg!(windows) {
        ("cmd", vec!["/C", cmd])
    } else {
        ("sh", vec!["-c", cmd])
    };
    let mut command = std::process::Command::new(program);
    command.args(&args);
    let command = crate::inline_command::direct_command(
        &command,
        true,
        cmd,
        &[],
        crate::config::Settings::get().implicit_inline_shell(),
    )
    .unwrap_or(command);
    match capture_command(command).await {
        Some((true, _)) => (true, None, None),
        _ => (
            false,
            None,
            Some(format!("command `{cmd}` did not succeed")),
        ),
    }
}

/// Run a short command, capturing combined stdout+stderr. Returns
/// `(success, output)` or `None` if it could not be spawned or timed out.
/// Silent and side-effect free — never elevates. A 5s wall-clock timeout keeps
/// a hanging binary (e.g. one that blocks on `--version`) from stalling the
/// whole install.
async fn run_capture(
    program: impl AsRef<std::ffi::OsStr>,
    args: &[&str],
) -> Option<(bool, String)> {
    let mut command = std::process::Command::new(program);
    command.args(args);
    capture_command(command).await
}

async fn capture_command(command: std::process::Command) -> Option<(bool, String)> {
    let program = command.get_program().to_owned();
    let mut command = tokio::process::Command::from(command);
    let fut = command.stdin(std::process::Stdio::null()).output();
    let output = match tokio::time::timeout(std::time::Duration::from_secs(5), fut).await {
        Ok(Ok(output)) => output,
        Ok(Err(_)) => return None,
        Err(_) => {
            debug!(
                "system dep: `{}` timed out, treating check as inconclusive",
                program.to_string_lossy()
            );
            return None;
        }
    };
    let mut combined = String::from_utf8_lossy(&output.stdout).into_owned();
    combined.push_str(&String::from_utf8_lossy(&output.stderr));
    Some((output.status.success(), combined))
}

/// Extract the first version-like token (`3`, `3.0`, `3.12.1`) from text such
/// as `bison (GNU Bison) 3.8.2`.
fn extract_version(text: &str) -> Option<String> {
    static RE: Lazy<regex::Regex> = Lazy::new(|| regex::Regex::new(r"\d+(?:\.\d+)+").unwrap());
    RE.find(text).map(|m| m.as_str().to_string())
}

/// Pick the first available, settings-enabled package manager that has a hint
/// for `dep`. Mirrors the manager selection [`crate::system`] applies so we
/// never propose a manager the driver would reject.
pub(crate) async fn pick_manager(dep: &SystemDep) -> Option<Arc<dyn SystemPackageManager>> {
    let enabled = Settings::get().system_packages.managers.clone();
    for m in packages::all_managers() {
        let name = m.name();
        if enabled
            .as_ref()
            .is_some_and(|e| !e.iter().any(|x| x == name))
        {
            continue;
        }
        if m.unavailable_reason_async().await.is_some() {
            continue;
        }
        // An empty candidate list names no package, so this manager cannot
        // remediate the dep even though it has an entry.
        if dep.packages.get(name).is_some_and(|c| !c.is_empty()) {
            return Some(m);
        }
    }
    None
}

/// Resolve `dep`'s hint for `m` to a single package name.
///
/// With one candidate this is just that name — no query, so the common case
/// costs nothing. With several, ask the manager which ones it actually has and
/// take the first; managers that cannot answer (the default `available`
/// implementation) fall back to the first candidate, which is the behavior
/// before candidate lists existed. Reached only for deps that already failed
/// detection, i.e. when mise is about to install packages anyway.
async fn resolve_package(m: &Arc<dyn SystemPackageManager>, dep: &SystemDep) -> Option<String> {
    let candidates = dep.packages.get(m.name())?;
    match candidates.split_first()? {
        (first, []) => Some(first.clone()),
        (first, _) => match m.available(candidates).await {
            Ok(available) => Some(
                candidates
                    .iter()
                    .zip(available)
                    .find(|(_, exists)| *exists)
                    .map(|(name, _)| name)
                    .unwrap_or(first)
                    .clone(),
            ),
            Err(err) => {
                debug!(
                    "could not query {} for {}, using {first}: {err:#}",
                    m.name(),
                    dep.label()
                );
                Some(first.clone())
            }
        },
    }
}

/// Group missing deps into per-manager [`PackageRequest`]s for remediation.
/// Returns `(by_manager, unremediable)` where `unremediable` are deps with no
/// available manager hint.
pub(crate) async fn build_requests(
    missing: &[&SystemDep],
) -> (IndexMap<String, Vec<PackageRequest>>, Vec<SystemDep>) {
    let mut by_mgr: IndexMap<String, Vec<PackageRequest>> = IndexMap::new();
    let mut unremediable = vec![];
    for dep in missing {
        // A dep with no manager, or whose hint names no package, is reported as
        // unremediable rather than sent to a manager as an empty operand.
        let resolved = match pick_manager(dep).await {
            Some(m) => resolve_package(&m, dep).await.map(|pkg| (m, pkg)),
            None => None,
        };
        match resolved {
            Some((m, pkg)) => {
                let requests = by_mgr.entry(m.name().to_string()).or_default();
                if !requests.iter().any(|r| r.name == pkg) {
                    requests.push(PackageRequest {
                        name: pkg,
                        version: None,
                        tap_url: None,
                        desired: crate::system::packages::PackageDesiredState::Present,
                    });
                }
            }
            None => unremediable.push((*dep).clone()),
        }
    }
    (by_mgr, unremediable)
}

/// Copy-pasteable install hint commands for `missing`, grouped by the manager
/// that would satisfy each. Used by warn mode.
pub(crate) async fn hint_commands(missing: &[&SystemDep]) -> Vec<String> {
    let (by_mgr, _) = build_requests(missing).await;
    by_mgr
        .into_iter()
        .map(|(mgr, requests)| {
            if mgr == "winget" {
                return requests
                    .iter()
                    .map(|request| format!("winget install --id {} --exact", request.name))
                    .collect::<Vec<_>>()
                    .join("\n");
            }
            let pkgs = requests
                .iter()
                .map(|r| r.name.as_str())
                .collect::<Vec<_>>()
                .join(" ");
            format!("{}{pkgs}", install_prefix(&mgr))
        })
        .collect()
}

fn install_prefix(mgr: &str) -> &'static str {
    match mgr {
        "brew" => "brew install ",
        "brew-cask" => "brew install --cask ",
        "apt" => "sudo apt-get install -y ",
        "dnf" => "sudo dnf install -y ",
        "pacman" => "sudo pacman -S ",
        "apk" => "sudo apk add ",
        "mas" => "mas install ",
        _ => "",
    }
}

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

    #[test]
    fn test_version_constraint_parse_and_compare() {
        let c = VersionConstraint::parse(">=3.0").unwrap();
        assert_eq!(c.op, VersionOp::AtLeast);
        assert!(!c.satisfied_by(&Versioning::new("2.3").unwrap()));
        assert!(c.satisfied_by(&Versioning::new("3.0").unwrap()));
        assert!(c.satisfied_by(&Versioning::new("3.8.2").unwrap()));

        // bare version means >=
        let bare = VersionConstraint::parse("3.0").unwrap();
        assert_eq!(bare.op, VersionOp::AtLeast);
        assert!(bare.satisfied_by(&Versioning::new("3.1").unwrap()));
        assert!(!bare.satisfied_by(&Versioning::new("2.9").unwrap()));

        assert!(
            VersionConstraint::parse(">2")
                .unwrap()
                .satisfied_by(&Versioning::new("3").unwrap())
        );
        assert!(
            !VersionConstraint::parse(">3")
                .unwrap()
                .satisfied_by(&Versioning::new("3").unwrap())
        );
        assert!(
            VersionConstraint::parse("<=1.2")
                .unwrap()
                .satisfied_by(&Versioning::new("1.2").unwrap())
        );
        assert!(
            VersionConstraint::parse("=3.0")
                .unwrap()
                .satisfied_by(&Versioning::new("3.0").unwrap())
        );
        assert!(
            !VersionConstraint::parse("=3.0")
                .unwrap()
                .satisfied_by(&Versioning::new("3.0.1").unwrap())
        );
    }

    #[test]
    fn test_extract_version() {
        assert_eq!(
            extract_version("bison (GNU Bison) 2.3").as_deref(),
            Some("2.3")
        );
        assert_eq!(extract_version("GNU Make 3.81").as_deref(), Some("3.81"));
        assert_eq!(
            extract_version("OpenSSL 3.0.13 30 Jan 2024").as_deref(),
            Some("3.0.13")
        );
        assert_eq!(extract_version("no version here").as_deref(), None);
    }

    /// Reports only the names in `stock` as available, and records every query
    /// so a single-candidate hint can be shown to query nothing at all.
    struct StubManager {
        stock: Vec<String>,
        queries: Mutex<usize>,
    }

    #[async_trait::async_trait(?Send)]
    impl SystemPackageManager for StubManager {
        fn name(&self) -> &str {
            "stub"
        }
        fn is_available(&self) -> bool {
            true
        }
        fn unavailable_reason(&self) -> String {
            unreachable!()
        }
        async fn installed(
            &self,
            _pkgs: &[PackageRequest],
        ) -> crate::result::Result<Vec<crate::system::packages::PackageStatus>> {
            Ok(vec![])
        }
        async fn available(&self, names: &[String]) -> crate::result::Result<Vec<bool>> {
            *self.queries.lock().unwrap() += 1;
            Ok(names.iter().map(|n| self.stock.contains(n)).collect())
        }
        async fn install(
            &self,
            _pkgs: &[PackageRequest],
            _opts: &crate::system::packages::InstallOpts,
        ) -> crate::result::Result<()> {
            Ok(())
        }
    }

    fn dep_with_packages(candidates: Vec<&str>) -> SystemDep {
        SystemDep {
            check: SystemDepCheck::SharedLib("libaio.so.1".into()),
            version: None,
            optional: None,
            packages: [(
                "stub".to_string(),
                candidates.into_iter().map(str::to_string).collect(),
            )]
            .into_iter()
            .collect(),
        }
    }

    #[tokio::test]
    async fn test_resolve_package_picks_first_available_candidate() {
        let m: Arc<dyn SystemPackageManager> = Arc::new(StubManager {
            stock: vec!["libaio1".to_string()],
            queries: Mutex::new(0),
        });
        // the first candidate does not exist here, so the fallback wins
        let dep = dep_with_packages(vec!["libaio1t64", "libaio1"]);
        assert_eq!(resolve_package(&m, &dep).await.as_deref(), Some("libaio1"));

        // no candidate exists: keep the first so the user still sees a name
        let dep = dep_with_packages(vec!["nonexistent", "also-nonexistent"]);
        assert_eq!(
            resolve_package(&m, &dep).await.as_deref(),
            Some("nonexistent")
        );
    }

    #[tokio::test]
    async fn test_resolve_package_does_not_query_for_a_single_candidate() {
        let m = Arc::new(StubManager {
            stock: vec![],
            queries: Mutex::new(0),
        });
        let dyn_m: Arc<dyn SystemPackageManager> = m.clone();
        let dep = dep_with_packages(vec!["libaio1"]);
        // resolves to the only candidate even though the stub does not stock it
        assert_eq!(
            resolve_package(&dyn_m, &dep).await.as_deref(),
            Some("libaio1")
        );
        assert_eq!(*m.queries.lock().unwrap(), 0);
    }

    #[tokio::test]
    async fn test_resolve_package_returns_none_for_empty_candidates() {
        // `packages = { apt = {} }` names no package, so there is nothing to
        // install — resolution must yield None rather than an empty name.
        let m: Arc<dyn SystemPackageManager> = Arc::new(StubManager {
            stock: vec![],
            queries: Mutex::new(0),
        });
        let dep = dep_with_packages(vec![]);
        assert_eq!(resolve_package(&m, &dep).await, None);
    }

    /// Name of a package manager that can actually run here, or None. Tests
    /// that exercise `pick_manager` need one: it only ever considers managers
    /// from `all_managers()`, so a dep keyed on a fictional name is skipped for
    /// the wrong reason and proves nothing.
    async fn available_manager_name() -> Option<String> {
        for m in packages::all_managers() {
            if m.unavailable_reason_async().await.is_none() {
                return Some(m.name().to_string());
            }
        }
        None
    }

    fn dep_under_manager(mgr: &str, candidates: Vec<&str>) -> SystemDep {
        SystemDep {
            check: SystemDepCheck::SharedLib("libaio.so.1".into()),
            version: None,
            optional: None,
            packages: [(
                mgr.to_string(),
                candidates.into_iter().map(str::to_string).collect(),
            )]
            .into_iter()
            .collect(),
        }
    }

    #[tokio::test]
    async fn test_pick_manager_skips_empty_candidate_list() {
        let Some(mgr) = available_manager_name().await else {
            return; // no usable package manager on this host
        };
        // a real, available manager with a usable name is picked...
        let usable = dep_under_manager(&mgr, vec!["some-package"]);
        assert!(pick_manager(&usable).await.is_some());
        // ...but the same manager naming no package cannot remediate
        let empty = dep_under_manager(&mgr, vec![]);
        assert!(pick_manager(&empty).await.is_none());
        let (by_mgr, unremediable) = build_requests(&[&empty]).await;
        assert!(by_mgr.is_empty());
        assert_eq!(unremediable.len(), 1);
    }

    #[test]
    fn test_blank_candidate_names_are_dropped() {
        // A hint of only blank names must not survive as a nameless install,
        // and a padded name must reach the package manager trimmed rather than
        // as the invalid operand "  libaio  ".
        let d = vfox::SystemDependency {
            sharedlib: Some("libaio.so.1".into()),
            packages: [
                ("apt".to_string(), vec!["".to_string(), "  ".to_string()]),
                (
                    "dnf".to_string(),
                    vec!["".to_string(), "  libaio  ".to_string()],
                ),
            ]
            .into_iter()
            .collect(),
            ..Default::default()
        };
        let dep = SystemDep::try_from(d).unwrap();
        assert!(!dep.packages.contains_key("apt"));
        assert_eq!(dep.packages.get("dnf"), Some(&vec!["libaio".to_string()]));
    }

    #[tokio::test]
    async fn test_resolve_package_falls_back_when_manager_cannot_answer() {
        struct CannotAnswer;
        #[async_trait::async_trait(?Send)]
        impl SystemPackageManager for CannotAnswer {
            fn name(&self) -> &str {
                "stub"
            }
            fn is_available(&self) -> bool {
                true
            }
            fn unavailable_reason(&self) -> String {
                unreachable!()
            }
            async fn installed(
                &self,
                _pkgs: &[PackageRequest],
            ) -> crate::result::Result<Vec<crate::system::packages::PackageStatus>> {
                Ok(vec![])
            }
            async fn available(&self, _names: &[String]) -> crate::result::Result<Vec<bool>> {
                eyre::bail!("apt-cache not found")
            }
            async fn install(
                &self,
                _pkgs: &[PackageRequest],
                _opts: &crate::system::packages::InstallOpts,
            ) -> crate::result::Result<()> {
                Ok(())
            }
        }
        let m: Arc<dyn SystemPackageManager> = Arc::new(CannotAnswer);
        let dep = dep_with_packages(vec!["libaio1t64", "libaio1"]);
        assert_eq!(
            resolve_package(&m, &dep).await.as_deref(),
            Some("libaio1t64")
        );
    }

    #[test]
    fn test_label() {
        let dep = SystemDep {
            check: SystemDepCheck::Bin("bison".into()),
            version: Some(VersionConstraint::parse(">=3.0").unwrap()),
            optional: None,
            packages: Default::default(),
        };
        assert_eq!(dep.label(), "bison >=3.0");

        let dep = SystemDep {
            check: SystemDepCheck::PkgConfig("libxml-2.0".into()),
            version: None,
            optional: None,
            packages: Default::default(),
        };
        assert_eq!(dep.label(), "pkg-config libxml-2.0");
    }

    #[tokio::test]
    async fn test_check_bin_present_and_missing() {
        // The bare name resolves through configured executable extensions on Windows.
        let present = if cfg!(windows) { "cmd" } else { "sh" };
        let (ok, _, _) = check_bin(present, None).await;
        assert!(ok);

        let (ok, _, reason) = check_bin("definitely-not-a-real-binary-xyz", None).await;
        assert!(!ok);
        assert!(reason.is_some());
    }

    #[tokio::test]
    async fn test_check_command() {
        // `true`/`false` aren't cmd built-ins on Windows; use `exit N`, which
        // works in both `sh -c` and `cmd /C`.
        let (succeed, fail) = if cfg!(windows) {
            ("exit 0", "exit 1")
        } else {
            ("true", "false")
        };
        let (ok, _, _) = check_command(succeed).await;
        assert!(ok);
        let (ok, _, _) = check_command(fail).await;
        assert!(!ok);
    }

    #[test]
    fn test_version_only_applies_to_bin_and_pkgconfig() {
        // bin + version is honored
        let d = vfox::SystemDependency {
            bin: Some("bison".into()),
            version: Some(">=3.0".into()),
            ..Default::default()
        };
        let dep = SystemDep::try_from(d).unwrap();
        assert!(dep.version.is_some());

        // sharedlib + version: the check is kept, the version is dropped
        let d = vfox::SystemDependency {
            sharedlib: Some("libaio.so.1".into()),
            version: Some(">=1.0".into()),
            ..Default::default()
        };
        let dep = SystemDep::try_from(d).unwrap();
        assert!(matches!(dep.check, SystemDepCheck::SharedLib(_)));
        assert!(dep.version.is_none());
        // and label must not render a phantom version
        assert_eq!(dep.label(), "shared library libaio.so.1");
    }
}