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