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