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