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