Skip to main content

rust_anything/
doctor.rs

1//! `doctor`: check the toolchains, the agent setup and the MCP server on this machine, and say
2//! the command that fixes each problem.
3//!
4//! Language runtimes are optional: each matters only for the languages being ported. Cargo, the
5//! MCP server and the setup of every agent found on the machine are required.
6
7use std::io::{BufRead, BufReader, Write};
8use std::path::{Path, PathBuf};
9use std::process::{Command, Stdio};
10use std::sync::mpsc;
11use std::time::{Duration, Instant};
12
13use serde::Serialize;
14use serde_json::{Value, json};
15
16use crate::setup::{self, Agent, NAME, SKILL_FILES};
17use crate::walk::Canonical;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "lowercase")]
21pub enum Status {
22    Ok,
23    Missing,
24    Outdated,
25    /// Something named rust-anything is there, but it is not ours.
26    Foreign,
27}
28
29impl Status {
30    fn label(self) -> &'static str {
31        match self {
32            Status::Ok => "ok",
33            Status::Missing => "missing",
34            Status::Outdated => "outdated",
35            Status::Foreign => "foreign",
36        }
37    }
38}
39
40#[derive(Debug, Serialize)]
41pub struct Check {
42    pub name: String,
43    pub status: Status,
44    /// A problem here makes `doctor` exit 1; optional checks only matter for some languages.
45    pub required: bool,
46    pub detail: String,
47    pub fix: Option<String>,
48}
49
50#[derive(Debug, Serialize)]
51pub struct Report {
52    pub checks: Vec<Check>,
53}
54
55impl Report {
56    /// Whether every required check passed.
57    pub fn ok(&self) -> bool {
58        self.checks
59            .iter()
60            .all(|c| !c.required || c.status == Status::Ok)
61    }
62}
63
64/// A version as `major.minor.patch`.
65#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
66pub struct Version(pub u32, pub u32, pub u32);
67
68impl std::fmt::Display for Version {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        write!(f, "{}.{}.{}", self.0, self.1, self.2)
71    }
72}
73
74/// The first `N[.N[.N]]` in a version banner (`v24.1.0`, `go version go1.22.3 ...`,
75/// `openjdk version "21.0.2"`, `ruby 2.6.10p210`).
76pub fn parse_version(text: &str) -> Option<Version> {
77    let start = text.find(|c: char| c.is_ascii_digit())?;
78    let mut parts = text[start..]
79        .split(|c: char| !c.is_ascii_digit() && c != '.')
80        .next()?
81        .split('.')
82        .map(|p| p.parse::<u32>().ok());
83    let major = parts.next()??;
84    let minor = parts.next().flatten().unwrap_or(0);
85    let patch = parts.next().flatten().unwrap_or(0);
86    Some(Version(major, minor, patch))
87}
88
89/// Java's version, reading the old `1.8.0` scheme as 8.
90pub fn parse_java_version(text: &str) -> Option<Version> {
91    parse_version(text).map(|v| match v {
92        Version(1, minor, patch) => Version(minor, patch, 0),
93        v => v,
94    })
95}
96
97/// A runtime's status from whether it ran, its version and the oldest version that works.
98pub fn grade(ran: bool, version: Option<Version>, minimum: Option<Version>) -> Status {
99    match (ran, version, minimum) {
100        (false, _, _) => Status::Missing,
101        (true, Some(v), Some(min)) if v < min => Status::Outdated,
102        _ => Status::Ok,
103    }
104}
105
106/// The state of something `setup` installs: an MCP entry or the skill.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum Install {
109    Missing,
110    Current,
111    Outdated,
112    Foreign,
113}
114
115impl From<Install> for Status {
116    fn from(i: Install) -> Status {
117        match i {
118            Install::Missing => Status::Missing,
119            Install::Current => Status::Ok,
120            Install::Outdated => Status::Outdated,
121            Install::Foreign => Status::Foreign,
122        }
123    }
124}
125
126/// An agent's `rust-anything` MCP server entry, as read from its settings.
127#[derive(Debug, Default)]
128pub struct Entry {
129    pub command: Option<String>,
130    pub args: Vec<String>,
131    pub url: bool,
132    /// OpenCode keeps a configured server out of the way with `disabled`; never set elsewhere.
133    pub disabled: bool,
134}
135
136/// Ours and current when it runs `<exe> mcp`; outdated when it runs `mcp` on another binary.
137pub fn entry_state(entry: Option<&Entry>, exe: &Path) -> Install {
138    let Some(entry) = entry else {
139        return Install::Missing;
140    };
141    let Some(command) = entry.command.as_deref() else {
142        return Install::Foreign;
143    };
144    if entry.url || entry.args != ["mcp"] {
145        return Install::Foreign;
146    }
147    if entry.disabled {
148        return Install::Outdated;
149    }
150    let path = Path::new(command);
151    if path == exe || path.canonical().is_ok_and(|p| p == exe) {
152        Install::Current
153    } else {
154        Install::Outdated
155    }
156}
157
158/// The installed skill files, in `SKILL_FILES` order, against the embedded copies.
159pub fn skill_state(installed: &[Option<String>]) -> Install {
160    let Some(main) = installed.first().and_then(Option::as_deref) else {
161        return if installed.iter().all(Option::is_none) {
162            Install::Missing
163        } else {
164            Install::Outdated
165        };
166    };
167    if installed
168        .iter()
169        .zip(SKILL_FILES)
170        .all(|(have, (_, want))| have.as_deref() == Some(*want))
171    {
172        Install::Current
173    } else if main
174        .lines()
175        .take_while(|l| !l.is_empty())
176        .any(|l| l.trim() == format!("name: {NAME}"))
177    {
178        Install::Outdated
179    } else {
180        Install::Foreign
181    }
182}
183
184pub fn run() -> Report {
185    let exe = std::env::current_exe()
186        .and_then(|p| p.canonical())
187        .unwrap_or_else(|_| PathBuf::from(NAME));
188    let mut checks: Vec<Check> = std::thread::scope(|s| {
189        let probes: Vec<_> = RUNTIMES.iter().map(|r| s.spawn(|| runtime(r))).collect();
190        let wasm = s.spawn(wasm_target);
191        let ndk = s.spawn(android_ndk);
192        let android_targets = s.spawn(android_targets);
193        let adb = s.spawn(android_adb);
194        let mcp = s.spawn(|| mcp_self_test(&exe));
195        let mut checks: Vec<Check> = probes
196            .into_iter()
197            .map(|p| p.join().expect("a runtime probe panicked"))
198            .collect();
199        checks.push(wasm.join().expect("the wasm probe panicked"));
200        checks.push(ndk.join().expect("the NDK probe panicked"));
201        checks.push(
202            android_targets
203                .join()
204                .expect("the Android targets probe panicked"),
205        );
206        checks.push(adb.join().expect("the adb probe panicked"));
207        checks.push(mcp.join().expect("the MCP self-test panicked"));
208        checks
209    });
210    checks.extend(agents(&exe));
211    Report { checks }
212}
213
214/// The command `doctor` gives on this platform to install or update a runtime, by its name.
215pub(crate) fn install_command(name: &str) -> Option<String> {
216    let r = RUNTIMES.iter().find(|r| r.name == name)?;
217    runtime_fix(r, Status::Outdated, Platform::HERE)
218}
219
220/// The command `doctor` gives on this platform when a runtime is missing, matched by its name or
221/// executable (`program`).
222pub(crate) fn missing_command(program: &str) -> Option<String> {
223    let lookup = program.strip_suffix(".exe").unwrap_or(program);
224    let r = RUNTIMES.iter().find(|r| {
225        r.program == program
226            || r.program == lookup
227            || r.name == lookup
228            || (lookup == "python" && r.name == "python3")
229    })?;
230    runtime_fix(r, Status::Missing, Platform::HERE)
231}
232
233/// The oldest version of a runtime that `doctor` accepts, by its name.
234pub(crate) fn minimum(name: &str) -> Option<Version> {
235    RUNTIMES.iter().find(|r| r.name == name)?.minimum
236}
237
238struct Runtime {
239    name: &'static str,
240    program: &'static str,
241    args: &'static [&'static str],
242    minimum: Option<Version>,
243    required: bool,
244    java: bool,
245    /// Fix commands: macOS, Windows, elsewhere.
246    fix: [&'static str; 3],
247}
248
249/// The C++ Build Tools, which Rust links with on Windows. Without `--add`, winget installs them
250/// with no workload: no compiler, linker or Windows SDK. The workload's recommended tools build for
251/// x64 and x86, so a build for Windows on ARM (npm has no binary for it) adds the ARM64 tools.
252const BUILD_TOOLS: &str = if cfg!(all(windows, target_arch = "aarch64")) {
253    BUILD_TOOLS_ARM64
254} else {
255    BUILD_TOOLS_X64
256};
257const BUILD_TOOLS_X64: &str = "winget install Microsoft.VisualStudio.2022.BuildTools --override \"--wait --passive --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended\"";
258const BUILD_TOOLS_ARM64: &str = "winget install Microsoft.VisualStudio.2022.BuildTools --override \"--wait --passive --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --add Microsoft.VisualStudio.Component.VC.Tools.ARM64\"";
259/// winget adds nothing to Build Tools that are already installed: an upgrade cannot add a workload.
260const BUILD_TOOLS_INSTALLED: &str = "(Build Tools already installed: add \"Desktop development with C++\" in Visual Studio Installer)";
261
262const RUNTIMES: &[Runtime] = &[
263    Runtime {
264        name: "cargo",
265        program: "cargo",
266        args: &["--version"],
267        minimum: Some(Version(1, 97, 0)),
268        required: true,
269        java: false,
270        fix: [
271            "rustup update stable",
272            "rustup update stable",
273            "rustup update stable",
274        ],
275    },
276    Runtime {
277        name: "node",
278        program: "node",
279        args: &["--version"],
280        minimum: Some(Version(22, 6, 0)),
281        required: false,
282        java: false,
283        fix: [
284            "brew install node@24",
285            "winget install OpenJS.NodeJS",
286            "fnm install 24 && fnm default 24",
287        ],
288    },
289    Runtime {
290        name: "python3",
291        program: if cfg!(windows) { "python" } else { "python3" },
292        args: &["--version"],
293        minimum: Some(Version(3, 9, 0)),
294        required: false,
295        java: false,
296        fix: [
297            "brew install python@3.13",
298            "winget install Python.Python.3.13",
299            "sudo apt install python3",
300        ],
301    },
302    Runtime {
303        name: "cc",
304        program: "cc",
305        args: &["--version"],
306        minimum: None,
307        required: false,
308        java: false,
309        fix: [
310            "xcode-select --install",
311            BUILD_TOOLS,
312            "sudo apt install build-essential",
313        ],
314    },
315    Runtime {
316        name: "go",
317        program: "go",
318        args: &["version"],
319        minimum: Some(Version(1, 22, 0)),
320        required: false,
321        java: false,
322        fix: [
323            "brew install go",
324            "winget install GoLang.Go",
325            "install Go 1.22+ from https://go.dev/dl",
326        ],
327    },
328    Runtime {
329        name: "ruby",
330        program: "ruby",
331        args: &["--version"],
332        minimum: Some(Version(3, 0, 0)),
333        required: false,
334        java: false,
335        fix: [
336            "brew install ruby && export PATH=\"$(brew --prefix ruby)/bin:$PATH\"",
337            "winget install RubyInstallerTeam.RubyWithDevKit.3.4",
338            "sudo apt install ruby-full",
339        ],
340    },
341    Runtime {
342        name: "java",
343        program: "java",
344        args: &["-version"],
345        minimum: Some(Version(17, 0, 0)),
346        required: false,
347        java: true,
348        fix: [
349            "brew install openjdk@21",
350            "winget install EclipseAdoptium.Temurin.21.JDK",
351            "sudo apt install openjdk-21-jdk",
352        ],
353    },
354    Runtime {
355        name: "javac",
356        program: "javac",
357        args: &["-version"],
358        minimum: Some(Version(17, 0, 0)),
359        required: false,
360        java: true,
361        fix: [
362            "brew install openjdk@21",
363            "winget install EclipseAdoptium.Temurin.21.JDK",
364            "sudo apt install openjdk-21-jdk",
365        ],
366    },
367    Runtime {
368        name: "kotlinc",
369        program: "kotlinc",
370        args: &["-version"],
371        minimum: None,
372        required: false,
373        java: false,
374        fix: [
375            "brew install kotlin",
376            "winget install JetBrains.Kotlin",
377            "sdk install kotlin",
378        ],
379    },
380    Runtime {
381        name: "php",
382        program: "php",
383        args: &["--version"],
384        minimum: Some(Version(8, 0, 0)),
385        required: false,
386        java: false,
387        fix: [
388            "brew install php",
389            "winget install PHP.PHP.8.4",
390            "sudo apt install php-cli",
391        ],
392    },
393    Runtime {
394        name: "dotnet",
395        program: "dotnet",
396        args: &["--version"],
397        minimum: None,
398        required: false,
399        java: false,
400        fix: [
401            "brew install --cask dotnet-sdk",
402            "winget install Microsoft.DotNet.SDK.8",
403            "install the .NET SDK from https://dotnet.microsoft.com/download",
404        ],
405    },
406    Runtime {
407        name: "pwsh",
408        program: "pwsh",
409        args: &["-NoProfile", "-NonInteractive", "-Version"],
410        minimum: Some(Version(7, 4, 0)),
411        required: false,
412        java: false,
413        fix: [
414            "brew install powershell",
415            "winget install Microsoft.PowerShell",
416            "install PowerShell 7.4+ from https://aka.ms/install-powershell",
417        ],
418    },
419    Runtime {
420        name: "wasm-bindgen",
421        program: "wasm-bindgen",
422        args: &["--version"],
423        minimum: None,
424        required: false,
425        java: false,
426        fix: [
427            "cargo install wasm-bindgen-cli --version <the crate's wasm-bindgen version> --locked",
428            "cargo install wasm-bindgen-cli --version <the crate's wasm-bindgen version> --locked",
429            "cargo install wasm-bindgen-cli --version <the crate's wasm-bindgen version> --locked",
430        ],
431    },
432];
433
434/// Where a fix runs: [`Runtime::fix`] has one command for each, in this order.
435#[derive(Clone, Copy, Debug, PartialEq, Eq)]
436enum Platform {
437    MacOs,
438    Windows,
439    Other,
440}
441
442impl Platform {
443    const HERE: Platform = if cfg!(target_os = "macos") {
444        Platform::MacOs
445    } else if cfg!(windows) {
446        Platform::Windows
447    } else {
448        Platform::Other
449    };
450
451    fn pick(self, fix: &[&'static str; 3]) -> &'static str {
452        fix[self as usize]
453    }
454}
455
456/// The commands that install or update `r` on `platform`, one per line, to run in order; `None`
457/// when it is fine.
458fn runtime_fix(r: &Runtime, status: Status, platform: Platform) -> Option<String> {
459    let fix = match (status, r.name) {
460        (Status::Ok, _) => return None,
461        (Status::Outdated, "cargo") => "rustup update stable".to_string(),
462        // rustup's script needs a Unix shell. winget runs `rustup-init -y`, which skips the Build
463        // Tools with a warning, so they come first, on a line of their own: `cmd` does not split
464        // commands at `;`.
465        (Status::Missing, "cargo") if platform == Platform::Windows => {
466            format!("{BUILD_TOOLS}\nwinget install Rustlang.Rustup")
467        }
468        (Status::Missing, "cargo") => {
469            "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh".to_string()
470        }
471        _ => platform.pick(&r.fix).to_string(),
472    };
473    Some(if fix.starts_with(BUILD_TOOLS) {
474        format!("{fix}\n{BUILD_TOOLS_INSTALLED}")
475    } else {
476        fix
477    })
478}
479
480/// The program's banner (stdout, else stderr), or `None` when it did not run.
481fn probe(program: &str, args: &[&str]) -> Option<String> {
482    let out =
483        crate::process::output(Command::new(program).args(args), crate::process::QUICK).ok()?;
484    if !out.success() {
485        return None;
486    }
487    let text = out.stdout_text();
488    let text = if text.trim().is_empty() {
489        out.stderr_text()
490    } else {
491        text
492    };
493    Some(text.lines().next().unwrap_or_default().trim().to_string())
494}
495
496fn which(program: &str) -> Option<PathBuf> {
497    std::env::split_paths(&std::env::var_os("PATH")?)
498        .map(|dir| dir.join(program))
499        .find(|p| p.is_file())
500}
501
502/// Whether `php -m` lists the `FFI` extension.
503pub fn php_has_ffi(modules: &str) -> bool {
504    modules
505        .lines()
506        .any(|l| l.trim().eq_ignore_ascii_case("ffi"))
507}
508
509fn php_modules(program: &str) -> Option<String> {
510    let out =
511        crate::process::output(Command::new(program).arg("-m"), crate::process::QUICK).ok()?;
512    out.success().then(|| out.stdout_text())
513}
514
515fn php_ffi_fix(platform: Platform) -> &'static str {
516    match platform {
517        Platform::MacOs => {
518            "brew install php  (or enable `extension=ffi` in the `php.ini` shown by `php --ini`)"
519        }
520        Platform::Windows => {
521            "enable `extension=ffi` (and `extension_dir=\"ext\"`) in the `php.ini` shown by `php --ini`"
522        }
523        Platform::Other => {
524            "enable `extension=ffi` in the `php.ini` shown by `php --ini` (or install `php-ffi`)"
525        }
526    }
527}
528
529fn runtime(r: &Runtime) -> Check {
530    let banner = probe(r.program, r.args);
531    let version = banner.as_deref().and_then(if r.java {
532        parse_java_version
533    } else {
534        parse_version
535    });
536    let modules = (r.name == "php" && grade(banner.is_some(), version, r.minimum) == Status::Ok)
537        .then(|| php_modules(r.program))
538        .flatten();
539    runtime_check(r, banner.as_deref(), modules.as_deref(), Platform::HERE)
540}
541
542fn runtime_check(
543    r: &Runtime,
544    banner: Option<&str>,
545    php_modules: Option<&str>,
546    platform: Platform,
547) -> Check {
548    let version = banner.and_then(if r.java {
549        parse_java_version
550    } else {
551        parse_version
552    });
553    let mut status = grade(banner.is_some(), version, r.minimum);
554    let mut detail = match (banner, r.minimum) {
555        (None, _) => format!("`{}` not found or did not run", r.program),
556        (Some(b), Some(min)) if status == Status::Outdated => {
557            format!("{b}; rust-anything needs {}.{}+", min.0, min.1)
558        }
559        (Some(b), _) => b.to_string(),
560    };
561    if r.name == "node" && status == Status::Ok && version.is_some_and(|v| v.0 < 24) {
562        detail.push_str("; works, but `profile` through `npx` or `npm run` may need Node 24");
563    }
564    if r.name == "ruby" && status == Status::Outdated {
565        detail.push_str("; magnus/rb-sys extensions do not build on Ruby 2");
566        if platform == Platform::MacOs && which("ruby").is_some_and(|p| p.starts_with("/usr/bin")) {
567            detail.push_str(" (this is macOS's system Ruby)");
568        }
569    }
570    let mut fix = runtime_fix(r, status, platform);
571    if r.name == "php" && status == Status::Ok {
572        match php_modules {
573            Some(m) if php_has_ffi(m) => detail.push_str(" (FFI loaded)"),
574            Some(_) => {
575                status = Status::Missing;
576                detail.push_str("; FFI extension not loaded");
577                fix = Some(php_ffi_fix(platform).to_string());
578            }
579            None => {
580                status = Status::Missing;
581                detail.push_str("; could not check the FFI extension (`php -m` failed)");
582                fix = Some(php_ffi_fix(platform).to_string());
583            }
584        }
585    }
586    Check {
587        name: r.name.to_string(),
588        status,
589        required: r.required,
590        detail,
591        fix,
592    }
593}
594
595fn wasm_target() -> Check {
596    const TARGET: &str = "wasm32-unknown-unknown";
597    let installed = crate::process::output(
598        Command::new("rustup").args(["target", "list", "--installed"]),
599        crate::process::QUICK,
600    )
601    .ok()
602    .filter(|o| o.success())
603    .map(|o| o.stdout_text());
604    let (status, detail) = match installed {
605        None => (Status::Missing, "`rustup` not found or did not run".into()),
606        Some(list) if list.lines().any(|l| l.trim() == TARGET) => {
607            (Status::Ok, format!("{TARGET} installed"))
608        }
609        Some(_) => (Status::Missing, format!("{TARGET} not installed")),
610    };
611    Check {
612        name: TARGET.into(),
613        status,
614        required: false,
615        detail,
616        fix: (status != Status::Ok).then(|| format!("rustup target add {TARGET}")),
617    }
618}
619
620/// The Android NDK `build --profile android` links with.
621fn android_ndk() -> Check {
622    let (status, detail) = match crate::android::ndk_root(None) {
623        Ok(path) => (Status::Ok, path.display().to_string()),
624        Err(e) => (Status::Missing, format!("{e:#}")),
625    };
626    Check {
627        name: "Android NDK".into(),
628        status,
629        required: false,
630        detail,
631        fix: (status != Status::Ok).then(|| {
632            "sdkmanager \"ndk;28.0.13004108\"  (or set ANDROID_NDK_HOME to an installed NDK)"
633                .to_string()
634        }),
635    }
636}
637
638/// `adb`, which `record`/`diff --profile android` use to reach a device.
639fn android_adb() -> Check {
640    let probe = probe("adb", &["version"]);
641    let (status, detail) = match probe.as_deref() {
642        Some(banner) => (
643            Status::Ok,
644            banner.lines().next().unwrap_or(banner).to_string(),
645        ),
646        None => (
647            Status::Missing,
648            "`adb` not found or did not run; recording and diffing on a device needs it".into(),
649        ),
650    };
651    Check {
652        name: "Android adb".into(),
653        status,
654        required: false,
655        detail,
656        fix: (status != Status::Ok).then(|| {
657            // The package alone is not enough: its folder has to be on PATH, or the next probe
658            // still cannot find `adb`.
659            "sdkmanager \"platform-tools\"  (or install Android Studio's SDK tools), then put its \
660             platform-tools folder on PATH"
661                .to_string()
662        }),
663    }
664}
665
666/// The Rust targets `build --profile android` needs.
667fn android_targets() -> Check {
668    let wanted: Vec<&str> = crate::android::DEFAULT_ABIS
669        .iter()
670        .map(|a| a.triple())
671        .collect();
672    let installed = crate::process::output(
673        Command::new("rustup").args(["target", "list", "--installed"]),
674        crate::process::QUICK,
675    )
676    .ok()
677    .filter(|o| o.success())
678    .map(|o| o.stdout_text());
679    let (status, detail, fix) = match installed {
680        None => (
681            Status::Missing,
682            "`rustup` not found or did not run".into(),
683            "install Rust with rustup (https://rustup.rs) to add Android targets".to_string(),
684        ),
685        Some(list) => {
686            let missing: Vec<&str> = wanted
687                .iter()
688                .copied()
689                .filter(|t| !list.lines().any(|l| l.trim() == *t))
690                .collect();
691            if missing.is_empty() {
692                (
693                    Status::Ok,
694                    format!("{} installed", wanted.join(", ")),
695                    String::new(),
696                )
697            } else {
698                (
699                    Status::Missing,
700                    format!("not installed: {}", missing.join(", ")),
701                    format!("rustup target add {}", missing.join(" ")),
702                )
703            }
704        }
705    };
706    Check {
707        name: "Android Rust targets".into(),
708        status,
709        required: false,
710        detail,
711        fix: (status != Status::Ok).then_some(fix),
712    }
713}
714
715/// Starts `<exe> mcp`, asks for `initialize` and `tools/list`, and expects both answers in 10 s.
716fn mcp_self_test(exe: &Path) -> Check {
717    let (status, detail) = match talk_to_mcp(exe, Duration::from_secs(10)) {
718        Ok(tools) => (
719            Status::Ok,
720            format!("`{} mcp` answered with {tools} tools", exe.display()),
721        ),
722        Err(e) => (Status::Missing, format!("`{} mcp`: {e}", exe.display())),
723    };
724    Check {
725        name: "mcp server".into(),
726        status,
727        required: true,
728        detail,
729        fix: (status != Status::Ok).then(|| {
730            format!(
731                "run `{} mcp` by hand and look at what it prints; reinstall with `cargo install rust-anything`",
732                quoted(exe)
733            )
734        }),
735    }
736}
737
738fn talk_to_mcp(exe: &Path, limit: Duration) -> Result<usize, String> {
739    let mut child = Command::new(exe)
740        .arg("mcp")
741        .stdin(Stdio::piped())
742        .stdout(Stdio::piped())
743        .stderr(Stdio::null())
744        .spawn()
745        .map_err(|e| format!("could not start: {e}"))?;
746    let requests = [
747        json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "rust-anything-doctor", "version": env!("CARGO_PKG_VERSION")}}}),
748        json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
749        json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
750    ];
751    if let Some(mut stdin) = child.stdin.take() {
752        for r in &requests {
753            let _ = writeln!(stdin, "{r}");
754        }
755    }
756    let (tx, rx) = mpsc::channel();
757    if let Some(stdout) = child.stdout.take() {
758        std::thread::spawn(move || {
759            for line in BufReader::new(stdout).lines() {
760                let Ok(line) = line else { break };
761                if tx.send(line).is_err() {
762                    break;
763                }
764            }
765        });
766    }
767    let deadline = Instant::now() + limit;
768    let mut init = None;
769    let mut list = None;
770    let outcome = loop {
771        if let (Some(_), Some(_)) = (&init, &list) {
772            break Ok(());
773        }
774        let left = deadline.saturating_duration_since(Instant::now());
775        match rx.recv_timeout(left) {
776            Ok(line) => {
777                let Ok(reply) = serde_json::from_str::<Value>(&line) else {
778                    break Err(format!("printed a line that is not JSON: {line}"));
779                };
780                match reply["id"].as_i64() {
781                    Some(1) => init = Some(reply),
782                    Some(2) => list = Some(reply),
783                    _ => {}
784                }
785            }
786            Err(mpsc::RecvTimeoutError::Timeout) => {
787                break Err(format!("no answer within {}s", limit.as_secs()));
788            }
789            Err(mpsc::RecvTimeoutError::Disconnected) => {
790                break Err("exited before answering".to_string());
791            }
792        }
793    };
794    let _ = child.kill();
795    let _ = child.wait();
796    outcome?;
797    let init = init.unwrap_or_default();
798    let list = list.unwrap_or_default();
799    if !init["result"]["protocolVersion"].is_string() {
800        return Err(format!("`initialize` gave no protocol version: {init}"));
801    }
802    match list["result"]["tools"].as_array() {
803        Some(tools) if !tools.is_empty() => Ok(tools.len()),
804        _ => Err(format!("`tools/list` listed no tools: {list}")),
805    }
806}
807
808fn quoted(path: &Path) -> String {
809    let text = path.display().to_string();
810    if text.contains(' ') {
811        format!("\"{text}\"")
812    } else {
813        text
814    }
815}
816
817fn slug(agent: Agent) -> &'static str {
818    match agent {
819        Agent::Claude => "claude",
820        Agent::Codex => "codex",
821        Agent::Cursor => "cursor",
822        Agent::Gemini => "gemini",
823        Agent::OpenCode => "opencode",
824    }
825}
826
827fn agents(exe: &Path) -> Vec<Check> {
828    let home = match setup::home() {
829        Ok(h) => h,
830        Err(e) => {
831            return vec![Check {
832                name: "agents".into(),
833                status: Status::Missing,
834                required: false,
835                detail: format!("{e:#}"),
836                fix: Some("set HOME".into()),
837            }];
838        }
839    };
840    let found: Vec<Agent> = Agent::ALL
841        .into_iter()
842        .filter(|a| a.present(&home))
843        .collect();
844    if found.is_empty() {
845        return vec![Check {
846            name: "agents".into(),
847            status: Status::Missing,
848            required: false,
849            detail: "no coding agent found (Claude Code, Codex, Cursor, Gemini CLI, OpenCode); the CLI works without one".into(),
850            fix: Some(format!("{} setup --agent claude", quoted(exe))),
851        }];
852    }
853    let setup_fix = |agent: Agent| format!("{} setup --agent {}", quoted(exe), slug(agent));
854    let mut checks = Vec::new();
855    for agent in found {
856        let config = agent.config(&home);
857        let (state, detail) = match read_entry(agent, &config) {
858            Err(e) => (Install::Foreign, e),
859            Ok(entry) => {
860                let state = entry_state(entry.as_ref(), exe);
861                let detail = match (state, &entry) {
862                    (Install::Missing, _) => format!("no `{NAME}` server in {}", config.display()),
863                    (_, Some(Entry { disabled: true, .. })) => {
864                        format!("`{NAME}` in {} is disabled", config.display())
865                    }
866                    (
867                        _,
868                        Some(Entry {
869                            command: Some(c), ..
870                        }),
871                    ) => {
872                        format!("{} runs `{c}`", config.display())
873                    }
874                    _ => format!(
875                        "`{NAME}` in {} is not `{} mcp`",
876                        config.display(),
877                        exe.display()
878                    ),
879                };
880                (state, detail)
881            }
882        };
883        checks.push(Check {
884            name: format!("{} mcp", agent.name()),
885            status: state.into(),
886            required: true,
887            detail,
888            fix: match state {
889                Install::Current => None,
890                Install::Missing | Install::Outdated => Some(setup_fix(agent)),
891                Install::Foreign => Some(format!(
892                    "fix or remove the `{NAME}` entry in {}, then run `{}`",
893                    config.display(),
894                    setup_fix(agent)
895                )),
896            },
897        });
898        if let Some(dir) = agent.skill_dir(&home) {
899            let installed: Vec<Option<String>> = SKILL_FILES
900                .iter()
901                .map(|(name, _)| std::fs::read_to_string(dir.join(name)).ok())
902                .collect();
903            let state = skill_state(&installed);
904            let skill_md = dir.join("SKILL.md");
905            checks.push(Check {
906                name: format!("{} skill", agent.name()),
907                status: state.into(),
908                required: true,
909                detail: match state {
910                    Install::Missing => format!("{} not installed", skill_md.display()),
911                    Install::Current => format!("{} matches this version", skill_md.display()),
912                    Install::Outdated => {
913                        format!("{} is from another version", skill_md.display())
914                    }
915                    Install::Foreign => {
916                        format!("{} is not rust-anything's skill", skill_md.display())
917                    }
918                },
919                fix: match state {
920                    Install::Current => None,
921                    Install::Missing | Install::Outdated => Some(setup_fix(agent)),
922                    Install::Foreign => Some(format!(
923                        "move {} aside, then run `{}`",
924                        dir.display(),
925                        setup_fix(agent)
926                    )),
927                },
928            });
929        }
930    }
931    checks
932}
933
934/// The agent's `rust-anything` entry; `Err` when the settings file cannot be read as settings.
935fn read_entry(agent: Agent, path: &Path) -> Result<Option<Entry>, String> {
936    let text = match std::fs::read_to_string(path) {
937        Ok(t) => t,
938        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
939        Err(e) => return Err(format!("reading {}: {e}", path.display())),
940    };
941    if text.trim().is_empty() {
942        return Ok(None);
943    }
944    if agent == Agent::Codex {
945        let doc: toml_edit::DocumentMut = text
946            .parse()
947            .map_err(|_| format!("{} is not valid TOML", path.display()))?;
948        let Some(server) = doc
949            .get("mcp_servers")
950            .and_then(|s| s.get(NAME))
951            .and_then(toml_edit::Item::as_table_like)
952        else {
953            return Ok(None);
954        };
955        return Ok(Some(Entry {
956            command: server
957                .get("command")
958                .and_then(|c| c.as_str())
959                .map(String::from),
960            args: server
961                .get("args")
962                .and_then(|a| a.as_array())
963                .map(|a| {
964                    a.iter()
965                        .filter_map(|v| v.as_str().map(String::from))
966                        .collect()
967                })
968                .unwrap_or_default(),
969            url: server.get("url").is_some(),
970            disabled: false,
971        }));
972    }
973    if agent == Agent::OpenCode {
974        let doc: Value = serde_json::from_str(&text)
975            .map_err(|_| format!("{} is not valid JSON", path.display()))?;
976        // Current OpenCode keeps servers under `mcp.servers`; older files list them in `mcp`.
977        let mcp = &doc["mcp"];
978        let servers = if mcp.get("servers").is_some() {
979            &mcp["servers"]
980        } else {
981            mcp
982        };
983        let Some(server) = servers.get(NAME) else {
984            return Ok(None);
985        };
986        // OpenCode's local server takes the whole argv in `command`.
987        let mut argv = server["command"]
988            .as_array()
989            .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)));
990        return Ok(Some(Entry {
991            command: argv.as_mut().and_then(|a| a.next()),
992            args: argv.into_iter().flatten().collect(),
993            url: server.get("url").is_some(),
994            disabled: server["disabled"].as_bool() == Some(true),
995        }));
996    }
997    let doc: Value =
998        serde_json::from_str(&text).map_err(|_| format!("{} is not valid JSON", path.display()))?;
999    let Some(server) = doc["mcpServers"].get(NAME) else {
1000        return Ok(None);
1001    };
1002    Ok(Some(Entry {
1003        command: server["command"].as_str().map(String::from),
1004        args: server["args"]
1005            .as_array()
1006            .map(|a| {
1007                a.iter()
1008                    .filter_map(|v| v.as_str().map(String::from))
1009                    .collect()
1010            })
1011            .unwrap_or_default(),
1012        url: server.get("url").is_some(),
1013        disabled: false,
1014    }))
1015}
1016
1017/// The report for people: one line per check, the fix under each problem.
1018pub fn text(r: &Report) -> String {
1019    let mut out = String::new();
1020    let width = r.checks.iter().map(|c| c.name.len()).max().unwrap_or(0);
1021    for c in &r.checks {
1022        let optional = if c.required || c.status == Status::Ok {
1023            ""
1024        } else {
1025            " (optional)"
1026        };
1027        out.push_str(&format!(
1028            "{:<9} {:<width$}  {}{optional}\n",
1029            c.status.label(),
1030            c.name,
1031            c.detail
1032        ));
1033        if let Some(fix) = &c.fix {
1034            // Further lines of a fix line up under the first.
1035            for (i, line) in fix.lines().enumerate() {
1036                let label = if i == 0 { "fix:" } else { "" };
1037                out.push_str(&format!("{:<9} {:<width$}  {label:<4} {line}\n", "", ""));
1038            }
1039        }
1040    }
1041    out.push_str(if r.ok() {
1042        "\nEverything required is in place. Language runtimes and wasm are optional: each matters only for the languages you port.\n"
1043    } else {
1044        "\nSomething required is missing: cargo, the MCP server, or the setup of an agent found here. Run the fix commands above.\n"
1045    });
1046    out
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051    use super::*;
1052
1053    #[test]
1054    fn install_command_is_doctor_fix_for_a_runtime() {
1055        let ruby = RUNTIMES.iter().find(|r| r.name == "ruby").unwrap();
1056        assert_eq!(
1057            install_command("ruby"),
1058            runtime_fix(ruby, Status::Outdated, Platform::HERE)
1059        );
1060        assert!(install_command("cobol").is_none());
1061        assert_eq!(minimum("ruby"), ruby.minimum);
1062        assert!(minimum("cobol").is_none());
1063
1064        let cargo = RUNTIMES.iter().find(|r| r.name == "cargo").unwrap();
1065        assert_eq!(
1066            missing_command("cargo"),
1067            runtime_fix(cargo, Status::Missing, Platform::HERE)
1068        );
1069        assert_ne!(
1070            missing_command("cargo").as_deref(),
1071            Some("rustup update stable")
1072        );
1073        assert!(missing_command("cobol").is_none());
1074    }
1075
1076    #[test]
1077    fn versions_are_read_from_every_banner() {
1078        let cases = [
1079            ("v24.1.0", Version(24, 1, 0)),
1080            ("Python 3.12.1", Version(3, 12, 1)),
1081            ("go version go1.22.3 darwin/arm64", Version(1, 22, 3)),
1082            (
1083                "ruby 2.6.10p210 (2022-04-12 revision 67958) [universal.arm64e-darwin26]",
1084                Version(2, 6, 10),
1085            ),
1086            ("openjdk version \"21.0.8\" 2025-07-15", Version(21, 0, 8)),
1087            ("javac 17", Version(17, 0, 0)),
1088            ("PHP 8.3.4 (cli) (built: Mar 12 2024)", Version(8, 3, 4)),
1089            ("PowerShell 7.7.0", Version(7, 7, 0)),
1090            ("cargo 1.97.0 (abcdef 2026-01-01)", Version(1, 97, 0)),
1091            ("8.0.100", Version(8, 0, 100)),
1092        ];
1093        for (text, want) in cases {
1094            assert_eq!(parse_version(text), Some(want), "{text}");
1095        }
1096        assert_eq!(parse_version("no digits"), None);
1097        assert_eq!(
1098            parse_java_version("java version \"1.8.0_281\""),
1099            Some(Version(8, 0, 0))
1100        );
1101        assert_eq!(
1102            parse_java_version("openjdk version \"17.0.2\""),
1103            Some(Version(17, 0, 2))
1104        );
1105    }
1106
1107    #[test]
1108    fn runtimes_are_graded_against_their_minimum() {
1109        let min = Some(Version(3, 0, 0));
1110        assert_eq!(grade(false, None, min), Status::Missing);
1111        assert_eq!(grade(true, Some(Version(2, 6, 10)), min), Status::Outdated);
1112        assert_eq!(grade(true, Some(Version(3, 0, 0)), min), Status::Ok);
1113        assert_eq!(grade(true, Some(Version(3, 4, 1)), min), Status::Ok);
1114        assert_eq!(grade(true, None, min), Status::Ok);
1115        assert_eq!(grade(true, Some(Version(1, 0, 0)), None), Status::Ok);
1116        assert!(Version(22, 6, 0) > Version(22, 5, 9));
1117    }
1118
1119    #[test]
1120    fn install_states_map_to_statuses() {
1121        assert_eq!(Status::from(Install::Missing), Status::Missing);
1122        assert_eq!(Status::from(Install::Current), Status::Ok);
1123        assert_eq!(Status::from(Install::Outdated), Status::Outdated);
1124        assert_eq!(Status::from(Install::Foreign), Status::Foreign);
1125        assert_eq!(
1126            serde_json::to_value(Status::Outdated).unwrap(),
1127            json!("outdated")
1128        );
1129    }
1130
1131    #[test]
1132    fn mcp_entries_are_ours_only_when_they_run_this_binary() {
1133        let exe = Path::new("/opt/bin/rust-anything");
1134        let entry = |command: &str, args: &[&str], url: bool| Entry {
1135            command: Some(command.into()),
1136            args: args.iter().map(|a| a.to_string()).collect(),
1137            url,
1138            disabled: false,
1139        };
1140        assert_eq!(entry_state(None, exe), Install::Missing);
1141        assert_eq!(
1142            entry_state(Some(&entry("/opt/bin/rust-anything", &["mcp"], false)), exe),
1143            Install::Current
1144        );
1145        assert_eq!(
1146            entry_state(Some(&entry("/old/rust-anything", &["mcp"], false)), exe),
1147            Install::Outdated
1148        );
1149        assert_eq!(
1150            entry_state(
1151                Some(&entry("/opt/bin/rust-anything", &["serve"], false)),
1152                exe
1153            ),
1154            Install::Foreign
1155        );
1156        assert_eq!(
1157            entry_state(Some(&entry("/opt/bin/rust-anything", &["mcp"], true)), exe),
1158            Install::Foreign
1159        );
1160        assert_eq!(entry_state(Some(&Entry::default()), exe), Install::Foreign);
1161        // A server OpenCode keeps disabled is not current.
1162        let mut disabled = entry("/opt/bin/rust-anything", &["mcp"], false);
1163        disabled.disabled = true;
1164        assert_eq!(entry_state(Some(&disabled), exe), Install::Outdated);
1165    }
1166
1167    #[test]
1168    fn opencode_entries_come_from_mcp_servers() {
1169        let home = std::env::temp_dir().join(format!(
1170            "rust-anything-doctor-opencode-{}",
1171            std::process::id()
1172        ));
1173        let _ = std::fs::remove_dir_all(&home);
1174        std::fs::create_dir_all(home.join(".config/opencode")).unwrap();
1175        let config = home.join(".config/opencode/opencode.json");
1176        std::fs::write(
1177            &config,
1178            r#"{"mcp":{"servers":{"rust-anything":{"type":"local","command":["/opt/bin/rust-anything","mcp"]}}}}"#,
1179        )
1180        .unwrap();
1181        let exe = Path::new("/opt/bin/rust-anything");
1182        let entry = read_entry(Agent::OpenCode, &config).unwrap();
1183        assert_eq!(entry_state(entry.as_ref(), exe), Install::Current);
1184        assert_eq!(
1185            entry_state(entry.as_ref(), Path::new("/elsewhere/rust-anything")),
1186            Install::Outdated
1187        );
1188        std::fs::write(
1189            &config,
1190            r#"{"mcp":{"servers":{"rust-anything":{"type":"local","command":["/opt/bin/rust-anything","mcp"],"disabled":true}}}}"#,
1191        )
1192        .unwrap();
1193        let entry = read_entry(Agent::OpenCode, &config).unwrap();
1194        assert_eq!(entry_state(entry.as_ref(), exe), Install::Outdated);
1195        // Older files list servers in `mcp` itself.
1196        std::fs::write(
1197            &config,
1198            r#"{"mcp":{"rust-anything":{"type":"local","command":["/opt/bin/rust-anything","mcp"]}}}"#,
1199        )
1200        .unwrap();
1201        let entry = read_entry(Agent::OpenCode, &config).unwrap();
1202        assert_eq!(entry_state(entry.as_ref(), exe), Install::Current);
1203        std::fs::remove_dir_all(&home).unwrap();
1204    }
1205
1206    #[test]
1207    fn skills_are_current_outdated_or_foreign() {
1208        let ours: Vec<Option<String>> = SKILL_FILES
1209            .iter()
1210            .map(|(_, t)| Some(t.to_string()))
1211            .collect();
1212        assert_eq!(skill_state(&ours), Install::Current);
1213        assert_eq!(
1214            skill_state(&vec![None; SKILL_FILES.len()]),
1215            Install::Missing
1216        );
1217        let mut old = ours.clone();
1218        old[0] = Some(format!(
1219            "---\nname: {NAME}\ndescription: old\n---\n\n# Old\n"
1220        ));
1221        assert_eq!(skill_state(&old), Install::Outdated);
1222        let mut partial = ours.clone();
1223        partial[1] = None;
1224        assert_eq!(skill_state(&partial), Install::Outdated);
1225        let mut foreign = ours;
1226        foreign[0] = Some("---\nname: something-else\n---\n".into());
1227        assert_eq!(skill_state(&foreign), Install::Foreign);
1228    }
1229
1230    #[test]
1231    fn only_required_problems_fail_the_report() {
1232        let check = |status, required| Check {
1233            name: "x".into(),
1234            status,
1235            required,
1236            detail: String::new(),
1237            fix: None,
1238        };
1239        let optional = Report {
1240            checks: vec![check(Status::Ok, true), check(Status::Missing, false)],
1241        };
1242        assert!(optional.ok());
1243        let required = Report {
1244            checks: vec![check(Status::Outdated, true)],
1245        };
1246        assert!(!required.ok());
1247    }
1248
1249    fn runtime_named(name: &str) -> &'static Runtime {
1250        RUNTIMES.iter().find(|r| r.name == name).unwrap()
1251    }
1252
1253    #[test]
1254    fn fixes_follow_the_platform() {
1255        let cc = runtime_named("cc");
1256        let fix = |platform| runtime_fix(cc, Status::Missing, platform);
1257        assert_eq!(
1258            fix(Platform::MacOs).as_deref(),
1259            Some("xcode-select --install")
1260        );
1261        assert_eq!(
1262            fix(Platform::Windows),
1263            Some(format!("{BUILD_TOOLS}\n{BUILD_TOOLS_INSTALLED}"))
1264        );
1265        assert_eq!(
1266            fix(Platform::Other).as_deref(),
1267            Some("sudo apt install build-essential")
1268        );
1269        assert_eq!(runtime_fix(cc, Status::Ok, Platform::Windows), None);
1270    }
1271
1272    #[test]
1273    fn windows_fixes_need_no_unix_shell() {
1274        for r in RUNTIMES {
1275            for status in [Status::Missing, Status::Outdated] {
1276                let fix = runtime_fix(r, status, Platform::Windows).unwrap();
1277                assert!(!fix.contains("| sh"), "{}: {fix}", r.name);
1278            }
1279        }
1280    }
1281
1282    #[test]
1283    fn windows_build_tools_fixes_add_the_cpp_workload() {
1284        for name in ["cargo", "cc"] {
1285            let fix = runtime_fix(runtime_named(name), Status::Missing, Platform::Windows).unwrap();
1286            assert!(
1287                fix.contains("--add Microsoft.VisualStudio.Workload.VCTools"),
1288                "{name}: {fix}"
1289            );
1290        }
1291    }
1292
1293    #[test]
1294    fn windows_cargo_fix_has_one_command_per_line() {
1295        let fix = runtime_fix(runtime_named("cargo"), Status::Missing, Platform::Windows).unwrap();
1296        assert_eq!(
1297            fix.lines().collect::<Vec<_>>(),
1298            [
1299                BUILD_TOOLS,
1300                "winget install Rustlang.Rustup",
1301                BUILD_TOOLS_INSTALLED
1302            ]
1303        );
1304    }
1305
1306    #[test]
1307    fn windows_on_arm_adds_the_arm64_tools() {
1308        let workload = "--add Microsoft.VisualStudio.Workload.VCTools --includeRecommended";
1309        assert!(BUILD_TOOLS_X64.contains(workload));
1310        assert!(!BUILD_TOOLS_X64.contains("ARM64"));
1311        assert!(BUILD_TOOLS_ARM64.contains(workload));
1312        assert!(
1313            BUILD_TOOLS_ARM64.ends_with(" --add Microsoft.VisualStudio.Component.VC.Tools.ARM64\"")
1314        );
1315        assert_eq!(
1316            BUILD_TOOLS == BUILD_TOOLS_ARM64,
1317            cfg!(all(windows, target_arch = "aarch64"))
1318        );
1319    }
1320
1321    #[test]
1322    fn fixes_of_several_lines_line_up() {
1323        let report = Report {
1324            checks: vec![Check {
1325                name: "cargo".into(),
1326                status: Status::Missing,
1327                required: true,
1328                detail: "not found".into(),
1329                fix: Some("first\nsecond".into()),
1330            }],
1331        };
1332        let out = text(&report);
1333        let lines: Vec<_> = out.lines().collect();
1334        assert!(lines[1].trim_start().starts_with("fix: first"), "{out}");
1335        assert_eq!(lines[1].find("first"), lines[2].find("second"), "{out}");
1336    }
1337
1338    #[test]
1339    fn adb_is_a_row_of_its_own_and_never_required() {
1340        // `record`/`diff --profile android` run `adb devices`, so a machine without it should hear
1341        // about it — but a device is optional, like the NDK and the Rust targets next to it.
1342        let check = android_adb();
1343        assert_eq!(check.name, "Android adb");
1344        assert!(!check.required);
1345        if check.status != Status::Ok {
1346            assert!(
1347                check
1348                    .fix
1349                    .as_deref()
1350                    .is_some_and(|f| f.contains("platform-tools")),
1351                "a missing adb names the package that installs it: {:?}",
1352                check.fix
1353            );
1354        }
1355    }
1356
1357    #[test]
1358    fn php_requires_the_ffi_extension_and_stays_optional() {
1359        let php = runtime_named("php");
1360        let banner = Some("PHP 8.3.4 (cli) (built: Mar 12 2024)");
1361        assert!(php_has_ffi("[PHP Modules]\nCore\nFFI\njson\n"));
1362        assert!(php_has_ffi("  ffi \n"));
1363        assert!(!php_has_ffi("[PHP Modules]\nCore\nfileinfo\njson\n"));
1364        assert!(!php_has_ffi(
1365            "PHP Warning: Unable to load dynamic library 'ffi'\n[PHP Modules]\nCore\n"
1366        ));
1367
1368        let loaded = runtime_check(
1369            php,
1370            banner,
1371            Some("[PHP Modules]\nCore\nFFI\n"),
1372            Platform::Other,
1373        );
1374        assert_eq!(loaded.status, Status::Ok);
1375        assert!(!loaded.required);
1376        assert!(loaded.detail.ends_with("(FFI loaded)"), "{}", loaded.detail);
1377        assert_eq!(loaded.fix, None);
1378
1379        for platform in [Platform::MacOs, Platform::Windows, Platform::Other] {
1380            let no_ffi = runtime_check(php, banner, Some("[PHP Modules]\nCore\n"), platform);
1381            assert_eq!(no_ffi.status, Status::Missing);
1382            assert!(!no_ffi.required);
1383            assert!(
1384                no_ffi.detail.contains("FFI extension not loaded"),
1385                "{}",
1386                no_ffi.detail
1387            );
1388            let fix = no_ffi.fix.as_deref().expect("a fix when FFI is missing");
1389            assert!(fix.contains("extension=ffi"), "{platform:?}: {fix}");
1390            assert!(!fix.contains("| sh"), "{platform:?}: {fix}");
1391            assert!(
1392                Report {
1393                    checks: vec![no_ffi]
1394                }
1395                .ok(),
1396                "missing FFI stays optional"
1397            );
1398        }
1399
1400        let probe_failed = runtime_check(php, banner, None, Platform::Other);
1401        assert_eq!(probe_failed.status, Status::Missing);
1402        assert!(probe_failed.detail.contains("`php -m` failed"));
1403        assert!(probe_failed.fix.is_some());
1404
1405        let old = runtime_check(php, Some("PHP 7.4.33 (cli)"), None, Platform::Other);
1406        assert_eq!(old.status, Status::Outdated);
1407        assert!(old.detail.contains("needs 8.0+"));
1408    }
1409    #[test]
1410    fn install_md_names_the_runtime_minimums_doctor_checks() {
1411        // docs/install.md lists the runtimes `record`, `diff` and `bench` run the original in; it
1412        // must not promise an older version than `doctor` accepts, or leave a checked one out.
1413        let doc = include_str!("../docs/install.md")
1414            .split_whitespace()
1415            .collect::<Vec<_>>()
1416            .join(" ");
1417        let named = [
1418            ("node", "Node"),
1419            ("python3", "Python"),
1420            ("go", "Go"),
1421            ("ruby", "Ruby"),
1422            ("javac", "JDK"),
1423            ("php", "PHP"),
1424            ("pwsh", "PowerShell"),
1425        ];
1426        for r in RUNTIMES.iter().filter(|r| r.minimum.is_some()) {
1427            assert!(
1428                matches!(r.name, "cargo" | "java") || named.iter().any(|(n, _)| *n == r.name),
1429                "add {} to this list and to docs/install.md",
1430                r.name
1431            );
1432        }
1433        for (name, label) in named {
1434            let Version(major, minor, _) = minimum(name).unwrap();
1435            let version = if minor == 0 {
1436                major.to_string()
1437            } else {
1438                format!("{major}.{minor}")
1439            };
1440            let text = format!("{label} {version}+");
1441            assert!(
1442                doc.contains(&text),
1443                "docs/install.md should say `{text}`, as doctor does"
1444            );
1445        }
1446        for runtime in ["`kotlinc`", ".NET SDK"] {
1447            assert!(
1448                doc.contains(runtime),
1449                "docs/install.md should name {runtime}"
1450            );
1451        }
1452    }
1453}