Skip to main content

visdom_cli/
doctor.rs

1//! Gathering what the checks need from this machine, running them, and
2//! carrying out the fixes the user agreed to.
3
4use std::io::{BufRead, Write};
5use std::path::{Path, PathBuf};
6use std::process::{Command, Stdio};
7
8use tracevault_cli::agent::Agent;
9
10use crate::agents::{adapter_for, AgentAdapter, AgentPaths, Workdir};
11use crate::components::{bazaar, tracing, CheckContext, CredentialState};
12use crate::config::{self, UserConfig};
13use crate::finding::{command_line, needs_attention, render_text, Finding, Fix, FixAction};
14use crate::fixes::{apply_fixes, FixExecutor, FixOutcome, FixPolicy};
15use crate::mode::resolve_tracing_mode;
16
17/// Tracing first, then bazaar.
18pub fn collect(
19    ctx: &CheckContext,
20    adapter: &dyn AgentAdapter,
21    bazaar_url: Result<Option<&str>, &str>,
22    user_config_path: &Path,
23) -> Vec<Finding> {
24    let mut findings = tracing::check(ctx);
25    findings.extend(bazaar::check(
26        bazaar_url,
27        adapter,
28        &ctx.workdir,
29        user_config_path,
30    ));
31    findings
32}
33
34/// The canonical top level of the git checkout containing `from`.
35pub fn git_toplevel(from: &Path) -> Option<PathBuf> {
36    let output = Command::new("git")
37        .args(["rev-parse", "--show-toplevel"])
38        .current_dir(from)
39        .stderr(Stdio::null())
40        .output()
41        .ok()
42        .filter(|o| o.status.success())?;
43    let path = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
44    Some(path.canonicalize().unwrap_or(path))
45}
46
47/// The process environment a [`Session`] is gathered from.
48pub struct Environment {
49    pub cwd: PathBuf,
50    pub home: PathBuf,
51    /// The platform config directory (`~/.config` on Linux).
52    pub config_root: PathBuf,
53    pub codex_home: PathBuf,
54    /// `VISDOM_AGENT`.
55    pub agent: Option<String>,
56    /// `VISDOM_BAZAAR_URL`.
57    pub bazaar_url: Option<String>,
58}
59
60impl Environment {
61    pub fn current() -> Self {
62        let home = dirs::home_dir().unwrap_or_default();
63        let set = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
64        Environment {
65            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
66            config_root: dirs::config_dir().unwrap_or_else(|| home.join(".config")),
67            codex_home: set("CODEX_HOME")
68                .map(PathBuf::from)
69                .unwrap_or_else(|| home.join(".codex")),
70            agent: set("VISDOM_AGENT"),
71            bazaar_url: set("VISDOM_BAZAAR_URL"),
72            home,
73        }
74    }
75}
76
77/// One run's view of the project: which agent, and everything the checks read.
78pub struct Session {
79    pub ctx: CheckContext,
80    pub adapter: Box<dyn AgentAdapter>,
81    /// `Err`: the server that should know it could not be asked (the reason).
82    pub bazaar_url: Result<Option<String>, String>,
83    pub user_config_path: PathBuf,
84    /// Problems reading visdom's own config files; the run goes on without them.
85    pub warnings: Vec<String>,
86}
87
88impl Session {
89    /// Read the config files, choose the agent and gather the check context.
90    /// The only error is an agent that cannot be chosen or launched.
91    pub fn gather(
92        env: &Environment,
93        agent_flag: Option<Agent>,
94        runtime: &tokio::runtime::Runtime,
95    ) -> Result<Session, String> {
96        let mut warnings = Vec::new();
97        let project_dir = git_toplevel(&env.cwd);
98        let user: UserConfig = config::load_user_config_in(&env.config_root).unwrap_or_else(|e| {
99            warnings.push(e);
100            UserConfig::default()
101        });
102        let repo = project_dir
103            .as_deref()
104            .map(config::load_repo_config_in)
105            .transpose()
106            .unwrap_or_else(|e| {
107                warnings.push(e);
108                None
109            })
110            .unwrap_or_default();
111        let agent = config::resolve_agent(agent_flag, env.agent.as_deref(), &repo, &user)?;
112
113        let tracing_root = project_dir
114            .as_deref()
115            .map(|dir| tracevault_cli::paths::resolve_project_root(dir).root);
116        let credential_root = tracing_root.as_deref().unwrap_or(&env.cwd);
117        let (server_url, credential) =
118            match tracevault_cli::credentials::resolve_credentials_quiet(credential_root) {
119                Ok((url, Some(_))) => (url, CredentialState::Present),
120                Ok((url, None)) => (url, missing_or_unreadable()),
121                Err(e) => (None, CredentialState::Unusable(e.to_string())),
122            };
123
124        let http = reqwest::Client::builder()
125            .timeout(std::time::Duration::from_secs(3))
126            .build()
127            .unwrap_or_default();
128        let bazaar_url = runtime.block_on(bazaar::resolve_bazaar_url(
129            env.bazaar_url.clone(),
130            &user,
131            server_url.as_deref(),
132            &http,
133        ));
134
135        let paths = AgentPaths {
136            home: env.home.clone(),
137            codex_home: env.codex_home.clone(),
138        };
139        let adapter = adapter_for(agent, paths, user.agents.program_for(agent))
140            .ok_or_else(|| format!("visdom cannot launch {}", agent.tool_name()))?;
141        Ok(Session {
142            ctx: CheckContext {
143                mode: resolve_tracing_mode(project_dir.as_deref()),
144                workdir: Workdir {
145                    start_dir: env.cwd.clone(),
146                    checkout: project_dir,
147                    primary: tracing_root,
148                },
149                home: env.home.clone(),
150                codex_home: env.codex_home.clone(),
151                agent,
152                server_url,
153                credential,
154            },
155            adapter,
156            bazaar_url,
157            user_config_path: config::user_config_path_in(&env.config_root),
158            warnings,
159        })
160    }
161
162    pub fn collect(&self) -> Vec<Finding> {
163        collect(
164            &self.ctx,
165            self.adapter.as_ref(),
166            self.bazaar_url
167                .as_ref()
168                .map(|url| url.as_deref())
169                .map_err(String::as_str),
170            &self.user_config_path,
171        )
172    }
173}
174
175/// No credential was resolved: either there is none, or the credential file
176/// is there and cannot be read or parsed (the library treats both alike).
177fn missing_or_unreadable() -> CredentialState {
178    use tracevault_cli::credentials::Credentials;
179    match Credentials::path() {
180        Ok(path) if path.exists() && Credentials::load().is_none() => {
181            CredentialState::Unreadable(path.display().to_string())
182        }
183        _ => CredentialState::Missing,
184    }
185}
186
187/// Carries out fixes by running commands: `visdom` itself for tracing and
188/// login, the agent's own CLI for its MCP configuration.
189pub struct RealExecutor {
190    /// This executable.
191    pub visdom: PathBuf,
192    /// Send the commands' stdout to stderr (when stdout carries JSON).
193    pub stdout_to_stderr: bool,
194    /// Give the commands no stdin, so none of them can stop to ask anything:
195    /// with `--yes` the fix shown is applied with its defaults.
196    pub no_questions: bool,
197}
198
199impl RealExecutor {
200    pub fn new(stdout_to_stderr: bool, policy: FixPolicy) -> Self {
201        RealExecutor {
202            visdom: std::env::current_exe().unwrap_or_else(|_| PathBuf::from("visdom")),
203            stdout_to_stderr,
204            no_questions: policy == FixPolicy::All,
205        }
206    }
207
208    fn run(&self, program: &str, args: &[String], cwd: Option<&Path>) -> Result<(), String> {
209        let line = command_line(program, args);
210        let mut cmd = Command::new(program);
211        cmd.args(args);
212        if let Some(dir) = cwd {
213            cmd.current_dir(dir);
214        }
215        if self.stdout_to_stderr {
216            cmd.stdout(Stdio::from(std::io::stderr()));
217        }
218        if self.no_questions {
219            cmd.stdin(Stdio::null());
220        }
221        match cmd.status() {
222            Ok(status) if status.success() => Ok(()),
223            Ok(status) => Err(format!("`{line}` failed ({status})")),
224            Err(e) => Err(format!("cannot run `{line}`: {e}")),
225        }
226    }
227}
228
229impl FixExecutor for RealExecutor {
230    fn execute(&mut self, action: &FixAction) -> Result<(), String> {
231        let visdom = self.visdom.to_string_lossy().into_owned();
232        match action {
233            FixAction::TracingInit { agent, dir } => self.run(
234                &visdom,
235                &["trace", "init", "--agent", agent.tool_name()].map(String::from),
236                Some(dir),
237            ),
238            FixAction::Login { server_url } => self.run(
239                &visdom,
240                &["login", "--server-url", server_url].map(String::from),
241                None,
242            ),
243            FixAction::RunCommand { program, args, cwd } => self.run(program, args, cwd.as_deref()),
244            FixAction::Sequence { steps } => steps.iter().try_for_each(|step| self.execute(step)),
245        }
246    }
247}
248
249/// Whether a line read at the prompt is a yes. Enter alone is; end of input
250/// (nothing read, not even a newline) and a read error are not.
251pub fn is_yes(read: std::io::Result<usize>, line: &str) -> bool {
252    match read {
253        Ok(0) | Err(_) => false,
254        Ok(_) => matches!(line.trim(), "" | "y" | "Y" | "yes"),
255    }
256}
257
258/// Show one fix on the terminal and read the answer.
259pub fn ask_on_terminal(fix: &Fix) -> bool {
260    eprint!("Apply: {}? [Y/n] ", fix.description);
261    let _ = std::io::stderr().flush();
262    let mut answer = String::new();
263    let read = std::io::stdin().lock().read_line(&mut answer);
264    is_yes(read, &answer)
265}
266
267/// How a round of fixes went.
268#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269pub struct FixSummary {
270    /// Something was changed, so the checks are worth running again.
271    pub applied: bool,
272    /// A fix that was meant to be applied failed.
273    pub failed: bool,
274}
275
276/// Offer the fixes of `findings` under `policy`, reporting each failure on
277/// stderr. A fix applied without asking is still shown first.
278pub fn fix(findings: &[Finding], policy: FixPolicy, exec: &mut dyn FixExecutor) -> FixSummary {
279    if policy == FixPolicy::All {
280        let mut shown: Vec<&str> = Vec::new();
281        for fix in findings.iter().filter_map(|f| f.fix.as_ref()) {
282            if !shown.contains(&fix.description.as_str()) {
283                eprintln!("visdom: applying: {}", fix.description);
284                shown.push(&fix.description);
285            }
286        }
287    }
288    let outcomes: Vec<FixOutcome> = apply_fixes(findings, policy, &mut ask_on_terminal, exec);
289    let mut reported: Vec<&str> = Vec::new();
290    for error in outcomes.iter().filter_map(|o| o.error.as_deref()) {
291        if !reported.contains(&error) {
292            eprintln!("visdom: fix failed: {error}");
293            reported.push(error);
294        }
295    }
296    FixSummary {
297        applied: outcomes.iter().any(|o| o.applied),
298        failed: outcomes.iter().any(|o| o.error.is_some()),
299    }
300}
301
302/// What a developer sees before the agent starts (or after `init`): the
303/// findings that need attention, on stderr. Nothing when all is well.
304pub fn print_attention(findings: &[Finding]) {
305    let attention = needs_attention(findings);
306    if !attention.is_empty() {
307        eprint!("{}", render_text(&attention));
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    #[test]
316    fn end_of_input_at_the_prompt_is_a_no() {
317        assert!(is_yes(Ok(1), "\n"));
318        assert!(is_yes(Ok(2), "y\n"));
319        assert!(is_yes(Ok(4), "yes\n"));
320        assert!(!is_yes(Ok(2), "n\n"));
321        assert!(!is_yes(Ok(6), "maybe\n"));
322        // Ctrl-D: nothing was read.
323        assert!(!is_yes(Ok(0), ""));
324        assert!(!is_yes(Err(std::io::Error::other("closed")), ""));
325    }
326
327    /// With `--yes` a fix must not stop to ask: its command gets no stdin.
328    #[test]
329    fn no_questions_gives_commands_an_empty_stdin() {
330        let tmp = tempfile::tempdir().unwrap();
331        let out = tmp.path().join("read");
332        let mut exec = RealExecutor {
333            visdom: PathBuf::from("visdom"),
334            stdout_to_stderr: true,
335            no_questions: true,
336        };
337        let script = format!("cat > '{}'", out.display());
338        let result = exec.execute(&FixAction::RunCommand {
339            program: "sh".to_string(),
340            args: vec!["-c".to_string(), script],
341            cwd: None,
342        });
343        assert_eq!(result, Ok(()));
344        assert_eq!(std::fs::read(&out).unwrap(), b"");
345        assert!(RealExecutor::new(false, FixPolicy::All).no_questions);
346        assert!(!RealExecutor::new(false, FixPolicy::Ask).no_questions);
347    }
348
349    #[test]
350    fn git_toplevel_is_none_outside_a_repository() {
351        let tmp = tempfile::tempdir().unwrap();
352        assert_eq!(git_toplevel(tmp.path()), None);
353    }
354
355    #[test]
356    fn git_toplevel_from_a_subdirectory() {
357        let tmp = tempfile::tempdir().unwrap();
358        let status = Command::new("git")
359            .args(["init", "-q"])
360            .current_dir(tmp.path())
361            .status()
362            .unwrap();
363        assert!(status.success());
364        let sub = tmp.path().join("a/b");
365        std::fs::create_dir_all(&sub).unwrap();
366        assert_eq!(git_toplevel(&sub), Some(tmp.path().canonicalize().unwrap()));
367    }
368
369    #[test]
370    fn executor_reports_a_failing_and_a_missing_command() {
371        let mut exec = RealExecutor {
372            visdom: PathBuf::from("visdom"),
373            stdout_to_stderr: true,
374            no_questions: false,
375        };
376        let run = |program: &str, args: &[&str]| FixAction::RunCommand {
377            program: program.to_string(),
378            args: args.iter().map(|a| a.to_string()).collect(),
379            cwd: None,
380        };
381        assert_eq!(exec.execute(&run("true", &[])), Ok(()));
382        let err = exec.execute(&run("false", &[])).unwrap_err();
383        assert!(err.contains("`false` failed"), "{err}");
384        let err = exec
385            .execute(&run("/nonexistent/visdom-test-program", &["x"]))
386            .unwrap_err();
387        assert!(err.contains("cannot run"), "{err}");
388    }
389
390    #[test]
391    fn sequence_stops_at_the_first_failure() {
392        let tmp = tempfile::tempdir().unwrap();
393        let marker = tmp.path().join("ran");
394        let mut exec = RealExecutor {
395            visdom: PathBuf::from("visdom"),
396            stdout_to_stderr: true,
397            no_questions: false,
398        };
399        let step = |program: &str, args: Vec<String>| FixAction::RunCommand {
400            program: program.to_string(),
401            args,
402            cwd: None,
403        };
404        let result = exec.execute(&FixAction::Sequence {
405            steps: vec![
406                step("false", vec![]),
407                step("touch", vec![marker.to_string_lossy().into_owned()]),
408            ],
409        });
410        assert!(result.is_err());
411        assert!(!marker.exists(), "the step after a failure must not run");
412    }
413
414    #[test]
415    fn run_command_uses_its_directory() {
416        let tmp = tempfile::tempdir().unwrap();
417        let mut exec = RealExecutor {
418            visdom: PathBuf::from("visdom"),
419            stdout_to_stderr: true,
420            no_questions: false,
421        };
422        let result = exec.execute(&FixAction::RunCommand {
423            program: "touch".to_string(),
424            args: vec!["here".to_string()],
425            cwd: Some(tmp.path().to_path_buf()),
426        });
427        assert_eq!(result, Ok(()));
428        assert!(tmp.path().join("here").exists());
429    }
430}