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