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