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;
9use tracevault_cli::credentials::Credential;
10
11use crate::agents::{adapter_for, AgentAdapter, AgentPaths, McpScope, Workdir};
12use crate::billing::{self, billing_use, Billing, BillingUse, ResolvedBilling};
13use crate::components::gateway::GatewayPlan;
14use crate::components::{
15    bazaar, gateway as gateway_checks, tracing, CheckContext, CredentialState,
16};
17use crate::config::{self, RepoConfig, UserConfig};
18use crate::finding::{command_line, needs_attention, render_text, Finding, Fix, FixAction};
19use crate::fixes::{apply_fixes, FixExecutor, FixOutcome, FixPolicy};
20use crate::gateway;
21use crate::instructions::{self, Facts, Told};
22use crate::mode::{configured_mode, effective_mode, ResolvedMode, TracingMode, MODE_ENV};
23use crate::subscription::{self, KeyState};
24use crate::suite::{self, PolicyState, SuiteMap};
25
26/// The first of `candidates` that is set to something.
27fn first_set(candidates: [Option<String>; 3]) -> Option<String> {
28    candidates
29        .into_iter()
30        .flatten()
31        .map(|v| v.trim().trim_end_matches('/').to_string())
32        .find(|v| !v.is_empty())
33}
34
35/// The canonical top level of the git checkout containing `from`.
36pub fn git_toplevel(from: &Path) -> Option<PathBuf> {
37    let output = Command::new("git")
38        .args(["rev-parse", "--show-toplevel"])
39        .current_dir(from)
40        .stderr(Stdio::null())
41        .output()
42        .ok()
43        .filter(|o| o.status.success())?;
44    let path = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
45    Some(path.canonicalize().unwrap_or(path))
46}
47
48/// The directory whose `.visdom/config.toml` applies in `cwd`: the top of the
49/// git checkout, else — outside any checkout, in a folder of checkouts set up
50/// as a workspace — the nearest directory above that has the file.
51pub fn settings_dir(cwd: &Path) -> Option<PathBuf> {
52    git_toplevel(cwd).or_else(|| {
53        cwd.ancestors()
54            .find(|dir| config::repo_config_path_in(dir).is_file())
55            .map(Path::to_path_buf)
56    })
57}
58
59pub const GATEWAY_URL_ENV: &str = "VISDOM_GATEWAY_URL";
60pub const GATEWAY_PROJECT_ENV: &str = "VISDOM_GATEWAY_PROJECT";
61pub const GATEWAY_MODEL_ENV: &str = "VISDOM_GATEWAY_MODEL";
62
63/// Where the gateway settings of a session come from, each said as a person
64/// would read it (`VISDOM_GATEWAY_URL in the environment`, a config file's
65/// key, `published by the tracing server`). `None`: nobody set it.
66#[derive(Clone, Debug, Default, PartialEq, Eq)]
67pub struct GatewaySources {
68    pub console_url: Option<String>,
69    pub project: Option<String>,
70    pub model: Option<String>,
71}
72
73/// The first value that is set, and where it was found.
74fn first_from<const N: usize>(
75    candidates: [(Option<String>, String); N],
76) -> (Option<String>, Option<String>) {
77    candidates
78        .into_iter()
79        .find_map(|(value, source)| {
80            value
81                .filter(|v| !v.trim().is_empty())
82                .map(|v| (Some(v), Some(source)))
83        })
84        .unwrap_or((None, None))
85}
86
87/// The process environment a [`Session`] is gathered from.
88pub struct Environment {
89    pub cwd: PathBuf,
90    pub home: PathBuf,
91    /// The platform config directory (`~/.config` on Linux).
92    pub config_root: PathBuf,
93    pub codex_home: PathBuf,
94    /// `VISDOM_AGENT`.
95    pub agent: Option<String>,
96    /// `VISDOM_BAZAAR_URL`.
97    pub bazaar_url: Option<String>,
98    /// `VISDOM_TRACING_MODE`.
99    pub mode: Option<String>,
100    /// `VISDOM_GATEWAY_URL`: the AI Gateway console.
101    pub gateway_url: Option<String>,
102    /// `VISDOM_CONTROL_PLANE_URL`.
103    pub control_plane_url: Option<String>,
104    /// `VISDOM_GATEWAY_PROJECT`: the gateway project (slug, id or name).
105    pub gateway_project: Option<String>,
106    /// `VISDOM_GATEWAY_MODEL`: the model alias the agent asks the gateway for.
107    pub gateway_model: Option<String>,
108    /// `VISDOM_GATEWAY_BILLING`: who pays for the calls through the gateway.
109    pub gateway_billing: Option<String>,
110}
111
112impl Environment {
113    pub fn current() -> Self {
114        let home = dirs::home_dir().unwrap_or_default();
115        let set = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
116        Environment {
117            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
118            config_root: dirs::config_dir().unwrap_or_else(|| home.join(".config")),
119            codex_home: set("CODEX_HOME")
120                .map(PathBuf::from)
121                .unwrap_or_else(|| home.join(".codex")),
122            agent: set("VISDOM_AGENT"),
123            bazaar_url: set("VISDOM_BAZAAR_URL"),
124            mode: set(MODE_ENV),
125            gateway_url: set("VISDOM_GATEWAY_URL"),
126            control_plane_url: set("VISDOM_CONTROL_PLANE_URL"),
127            gateway_project: set(GATEWAY_PROJECT_ENV),
128            gateway_model: set(GATEWAY_MODEL_ENV),
129            gateway_billing: set(billing::BILLING_ENV),
130            home,
131        }
132    }
133}
134
135/// One run's view of the project: which agent, and everything the checks read.
136pub struct Session {
137    pub ctx: CheckContext,
138    pub adapter: Box<dyn AgentAdapter>,
139    /// `Err`: the server that should know it could not be asked (the reason).
140    pub bazaar_url: Result<Option<String>, String>,
141    pub user_config_path: PathBuf,
142    /// Problems reading visdom's own config files; the run goes on without them.
143    pub warnings: Vec<String>,
144    /// How this session is traced, and who decided.
145    pub mode: ResolvedMode,
146    pub policy: PolicyState,
147    /// In gateway mode: what the session will use, or why it cannot.
148    pub gateway: Option<Result<GatewayPlan, String>>,
149    /// The suite's other products, as far as the tracing server says.
150    pub suite: SuiteMap,
151    /// The developer's Keycloak access token, for the suite's other products.
152    /// Never an API key: that is the tracing server's alone.
153    pub token: Option<String>,
154    /// The model alias configured for this agent through the gateway.
155    pub gateway_model: Option<String>,
156    /// Where a missing bazaar registration is made: for this project
157    /// directory, or (a machine-wide setup) for all of the user's.
158    pub mcp_scope: McpScope,
159    /// The gateway console's address, as far as anybody names one.
160    pub console_url: Option<String>,
161    /// Who set the gateway's address, project and model.
162    pub gateway_sources: GatewaySources,
163    /// Where visdom keeps its own state (`<config dir>`).
164    pub config_root: PathBuf,
165    /// Whether the agent is told about Visdom's tools (`agent_instructions`
166    /// in the user config; yes unless that says no).
167    pub agent_instructions: bool,
168    /// Who pays for the agent's calls through the gateway, and who said so.
169    pub billing: ResolvedBilling,
170    /// Whether that can be used in this session's mode with this agent.
171    pub billing_use: BillingUse,
172    /// What [`Session::check_subscription`] found; empty until it runs.
173    pub subscription: Vec<Finding>,
174}
175
176impl Session {
177    /// Read the config files, choose the agent and gather the check context.
178    /// The errors are an agent that cannot be chosen or launched, and a mode
179    /// or billing in the environment that names none.
180    pub fn gather(
181        env: &Environment,
182        agent_flag: Option<Agent>,
183        mode_flag: Option<TracingMode>,
184        billing_flag: Option<Billing>,
185        runtime: &tokio::runtime::Runtime,
186    ) -> Result<Session, String> {
187        let mut warnings = Vec::new();
188        let project_dir = git_toplevel(&env.cwd);
189        let user: UserConfig = config::load_user_config_in(&env.config_root).unwrap_or_else(|e| {
190            warnings.push(e);
191            UserConfig::default()
192        });
193        let repo = settings_dir(&env.cwd)
194            .as_deref()
195            .map(config::load_repo_config_in)
196            .transpose()
197            .unwrap_or_else(|e| {
198                warnings.push(e);
199                None
200            })
201            .unwrap_or_default();
202        let repo: RepoConfig = repo;
203        let agent = config::resolve_agent(agent_flag, env.agent.as_deref(), &repo, &user)?;
204        let chosen = configured_mode(
205            mode_flag,
206            env.mode.as_deref(),
207            repo.tracing_mode,
208            user.tracing_mode,
209        )?;
210        let billing = billing::configured_billing(
211            billing_flag,
212            env.gateway_billing.as_deref(),
213            repo.gateway.billing,
214            user.gateway.billing,
215            &config::user_config_path_in(&env.config_root)
216                .display()
217                .to_string(),
218        )?;
219
220        let tracing_root = project_dir
221            .as_deref()
222            .map(|dir| tracevault_cli::paths::resolve_project_root(dir).root);
223        let credential_root = tracing_root.as_deref().unwrap_or(&env.cwd);
224        let (server_url, credential, session) =
225            match tracevault_cli::credentials::resolve_credentials_quiet(credential_root) {
226                Ok((url, Some(credential))) => {
227                    let session = match credential {
228                        Credential::Keycloak(_) => Some(credential),
229                        Credential::ApiKey(_) => None,
230                    };
231                    (url, CredentialState::Present, session)
232                }
233                Ok((url, None)) => (url, missing_or_unreadable(), None),
234                Err(e) => (None, CredentialState::Unusable(e.to_string()), None),
235            };
236
237        let http = http_client();
238        // One question to the tracing server tells where everything else is.
239        let published = match &server_url {
240            Some(url) => runtime.block_on(suite::fetch_suite_map(&http, url)),
241            None => Ok(SuiteMap::default()),
242        };
243        let bazaar_url = bazaar::resolve_bazaar_url(env.bazaar_url.clone(), &user, &published);
244        // While that server is away, the rest of the suite is where it last
245        // said: a policy that requires the gateway must not lapse with it.
246        let suite_map = match &server_url {
247            Some(url) => suite::suite_map_or_remembered(
248                &published,
249                url,
250                &suite::suite_cache_path_in(&env.config_root),
251            ),
252            None => SuiteMap::default(),
253        };
254
255        // The developer's own token opens the suite's other products. Only a
256        // Keycloak login has one; an API key is never sent anywhere else.
257        let token = match (&server_url, session) {
258            (Some(url), Some(session)) => runtime
259                .block_on(
260                    tracevault_cli::api_client::ApiClient::with_credential(url, Some(session))
261                        .bearer_valid_for(MIN_TOKEN_SECONDS),
262                )
263                .ok()
264                .flatten(),
265            _ => None,
266        };
267        let control_plane_url = first_set([
268            env.control_plane_url.clone(),
269            user.control_plane_url.clone(),
270            suite_map.control_plane_url.clone(),
271        ]);
272        let policy = runtime.block_on(suite::resolve_policy(
273            &http,
274            control_plane_url.as_deref(),
275            token.as_deref(),
276            &suite::policy_cache_path_in(&env.config_root),
277        ));
278        let mode = effective_mode(chosen, policy.policy());
279        let billing_use = billing_use(&billing, &mode, agent);
280        // The environment first, then the files, then what the server says:
281        // a setting left out of the config is taken from the environment.
282        let user_file = config::user_config_path_in(&env.config_root);
283        let in_env = |name: &str| format!("{name} in the environment");
284        let in_user = |key: &str| format!("{key} in {}", user_file.display());
285        let (console_url, console_source) = first_from([
286            (env.gateway_url.clone(), in_env(GATEWAY_URL_ENV)),
287            (user.gateway.url.clone(), in_user("url under [gateway]")),
288            (
289                suite_map.ai_gateway_url.clone(),
290                "published by the tracing server".to_string(),
291            ),
292        ]);
293        let (project, project_source) = first_from([
294            (env.gateway_project.clone(), in_env(GATEWAY_PROJECT_ENV)),
295            (
296                repo.gateway.project.clone(),
297                "project under [gateway] in .visdom/config.toml".to_string(),
298            ),
299            (
300                user.gateway.project.clone(),
301                in_user("project under [gateway]"),
302            ),
303        ]);
304        let (gateway_model, model_source) = first_from([
305            (env.gateway_model.clone(), in_env(GATEWAY_MODEL_ENV)),
306            (
307                user.gateway.model_for(agent),
308                in_user(&format!(
309                    "{}_model under [gateway]",
310                    config::agent_config_key(agent)
311                )),
312            ),
313        ]);
314        let gateway = (mode.mode == TracingMode::Gateway).then(|| {
315            runtime.block_on(plan_gateway(
316                &http,
317                console_url.clone(),
318                token.as_deref(),
319                project.as_deref(),
320            ))
321        });
322
323        let paths = AgentPaths {
324            home: env.home.clone(),
325            codex_home: env.codex_home.clone(),
326        };
327        let adapter = adapter_for(agent, paths, user.agents.program_for(agent))
328            .ok_or_else(|| format!("visdom cannot launch {}", agent.tool_name()))?;
329        Ok(Session {
330            ctx: CheckContext {
331                mode: mode.mode,
332                workdir: Workdir {
333                    start_dir: env.cwd.clone(),
334                    checkout: project_dir,
335                    primary: tracing_root,
336                },
337                home: env.home.clone(),
338                codex_home: env.codex_home.clone(),
339                agent,
340                server_url,
341                credential,
342            },
343            adapter,
344            bazaar_url,
345            user_config_path: config::user_config_path_in(&env.config_root),
346            warnings,
347            mode,
348            policy,
349            gateway,
350            suite: suite_map,
351            token,
352            gateway_model,
353            mcp_scope: McpScope::Local,
354            console_url,
355            gateway_sources: GatewaySources {
356                console_url: console_source,
357                project: project_source,
358                model: model_source,
359            },
360            config_root: env.config_root.clone(),
361            agent_instructions: user.agent_instructions.unwrap_or(true),
362            billing,
363            billing_use,
364            subscription: Vec::new(),
365        })
366    }
367
368    /// Whether the agent is to be started through the gateway on the
369    /// developer's own Claude subscription.
370    pub fn on_subscription(&self) -> bool {
371        self.mode.mode == TracingMode::Gateway
372            && self.billing_use == BillingUse::Applies
373            && self.billing.billing == Billing::Subscription
374    }
375
376    /// The model alias a subscription session would ask for: the configured
377    /// one, else the first one named for the agent among those the gateway
378    /// takes a subscription call on.
379    pub fn subscription_model(&self) -> Option<String> {
380        let eligible = match &self.gateway {
381            Some(Ok(plan)) => plan.project.subscription_aliases().unwrap_or_default(),
382            _ => Vec::new(),
383        };
384        gateway::pick_model(self.ctx.agent, self.gateway_model.as_deref(), &eligible)
385    }
386
387    /// Check that a subscription session can work here (see
388    /// [`crate::subscription`]); [`Session::collect`] then reports it.
389    /// `model` is the alias it would ask for, and `key` what is known of its
390    /// key (`None`: not checked here). Nothing when the session is not one.
391    /// `agent_args` are the caller's own options for the agent, which may
392    /// name another model.
393    pub fn check_subscription(
394        &mut self,
395        model: Option<&str>,
396        agent_args: &[String],
397        key: Option<&KeyState>,
398    ) {
399        self.subscription.clear();
400        if !self.on_subscription() {
401            return;
402        }
403        if let Some(Ok(plan)) = &self.gateway {
404            self.subscription
405                .push(subscription::traffic_finding(plan.subscription_traffic));
406        }
407        self.subscription
408            .push(subscription::login_finding(&subscription::claude_login(
409                self.adapter.program(),
410                agent_args,
411                &crate::launch::private_dir(&self.config_root),
412            )));
413        // Claude Code reads a project's `.claude/` settings in the checkout,
414        // or, outside one, where it is started.
415        let project_dir = self
416            .ctx
417            .workdir
418            .checkout
419            .clone()
420            .unwrap_or_else(|| self.ctx.workdir.start_dir.clone());
421        if let Some(Ok(plan)) = &self.gateway {
422            // What the launch keeps of the environment, Claude Code's
423            // settings and the caller's options wins over visdom's alias:
424            // each is checked.
425            let claude_env = subscription::ClaudeEnv::read(
426                &subscription::managed_settings_path(),
427                &self.ctx.home,
428                Some(&project_dir),
429                agent_args,
430            );
431            let uses = subscription::models_in_use(model, agent_args, &|name| {
432                claude_env.get(name, &|name| std::env::var(name).ok())
433            });
434            self.subscription.push(subscription::model_finding(
435                &uses,
436                self.gateway_sources.model.as_deref(),
437                &plan.project,
438                &format!("{}_model", config::agent_config_key(self.ctx.agent)),
439            ));
440        }
441        if let Some(key) = key {
442            self.subscription.push(subscription::key_finding(key));
443        }
444        self.subscription.push(subscription::settings_finding(
445            &subscription::managed_settings_path(),
446            &self.ctx.home,
447            Some(&project_dir),
448        ));
449    }
450
451    /// The kept subscription key, tried on the LLM gateway; none is issued
452    /// (`visdom doctor` changes nothing at the gateway). Any key that has not
453    /// expired is tried, also one close enough to its end that the next
454    /// launch replaces it.
455    pub fn kept_subscription_key(&self, runtime: &tokio::runtime::Runtime, now: i64) -> KeyState {
456        let (Some(Ok(plan)), Some(token)) = (&self.gateway, &self.token) else {
457            return KeyState::NoneKept;
458        };
459        let store = gateway::KeyStore::at(gateway::key_store_path_in(&self.config_root));
460        let kept = store.unexpired(
461            &plan.console_url,
462            &plan.project.id,
463            &gateway::account_of(token),
464            Billing::Subscription,
465            now,
466        );
467        let Some(key) = kept else {
468            return KeyState::NoneKept;
469        };
470        match runtime.block_on(gateway::models(&http_client(), &plan.llm_url, &key.secret)) {
471            Ok(_) => KeyState::Accepted {
472                expires_at: key.expires_at,
473            },
474            Err(refusal) if refusal.rejected => KeyState::KeptRefused,
475            Err(refusal) => KeyState::Failed(refusal.why),
476        }
477    }
478
479    /// Whether a subscription session cannot work here, as far as
480    /// [`Session::check_subscription`] found.
481    pub fn subscription_blocked(&self) -> bool {
482        self.subscription
483            .iter()
484            .any(|f| f.severity == crate::finding::Severity::Error)
485    }
486
487    /// What an agent started now would have of Visdom's, `through_gateway`
488    /// saying whether its LLM traffic goes through the AI Gateway.
489    pub fn facts(&self, through_gateway: bool) -> Facts {
490        Facts {
491            tracing: tracing::working(&self.ctx),
492            bazaar: bazaar::registered_name(
493                self.bazaar_url.as_ref().ok().and_then(|url| url.as_deref()),
494                self.adapter.as_ref(),
495                &self.ctx.workdir,
496            ),
497            gateway: through_gateway,
498        }
499    }
500
501    /// `args` for the agent, with what it is told about Visdom's tools, if
502    /// it is told anything.
503    pub fn agent_args(&self, args: &[String], through_gateway: bool) -> Told {
504        if !self.agent_instructions {
505            return Told::Nothing(args.to_vec());
506        }
507        let mut facts = self.facts(through_gateway);
508        // The caller's own options may take the registered servers away from
509        // this one session.
510        let agent = self.ctx.agent;
511        // What was found is of the directory `visdom` was run in: a Codex
512        // sent to work in another one is told nothing of it.
513        if agent == Agent::Codex && instructions::codex_works_elsewhere(args) {
514            return Told::Nothing(args.to_vec());
515        }
516        facts.tracing &= !instructions::without_hooks(agent, args);
517        let profile_changes_mcp = agent == Agent::Codex
518            && instructions::codex_profile_changes_mcp(args, &self.ctx.codex_home);
519        facts.bazaar = facts.bazaar.filter(|name| {
520            !profile_changes_mcp && !instructions::without_registered_mcp(agent, args, name)
521        });
522        match instructions::compose(&facts) {
523            Some(text) => instructions::agent_args(
524                self.ctx.agent,
525                &text,
526                args,
527                &self.ctx.codex_home,
528                &self.ctx.workdir.start_dir,
529            ),
530            None => Told::Nothing(args.to_vec()),
531        }
532    }
533
534    /// Tracing, then the mode and the gateway, then bazaar.
535    pub fn collect(&self) -> Vec<Finding> {
536        let mut findings = tracing::check(&self.ctx);
537        findings.extend(gateway_checks::check(
538            &self.mode,
539            &self.policy,
540            self.gateway.as_ref(),
541            self.ctx.agent,
542        ));
543        findings.extend(gateway_checks::billing_finding(
544            &self.billing,
545            &self.billing_use,
546        ));
547        findings.extend(self.subscription.iter().cloned());
548        findings.extend(bazaar::check(
549            self.bazaar_url
550                .as_ref()
551                .map(|url| url.as_deref())
552                .map_err(String::as_str),
553            self.adapter.as_ref(),
554            &self.ctx.workdir,
555            &self.user_config_path,
556            self.mcp_scope,
557        ));
558        findings
559    }
560}
561
562/// The developer's Keycloak access token for the project containing
563/// `start`, refreshed if needed. An error says why there is none.
564pub fn person_token(start: &Path, runtime: &tokio::runtime::Runtime) -> Result<String, String> {
565    let root = git_toplevel(start)
566        .map(|dir| tracevault_cli::paths::resolve_project_root(&dir).root)
567        .unwrap_or_else(|| start.to_path_buf());
568    let login = "the AI Gateway needs a Visdom account login: run `visdom login`";
569    match tracevault_cli::credentials::resolve_credentials_quiet(&root) {
570        Ok((Some(url), Some(session @ Credential::Keycloak(_)))) => runtime
571            .block_on(
572                tracevault_cli::api_client::ApiClient::with_credential(&url, Some(session))
573                    .bearer_valid_for(MIN_TOKEN_SECONDS),
574            )
575            .map_err(|e| format!("your Visdom login could not be used ({e}): run `visdom login`"))?
576            .ok_or_else(|| login.to_string()),
577        Ok(_) => Err(login.to_string()),
578        Err(e) => Err(e.to_string()),
579    }
580}
581
582/// The account of the login stored for the project containing `start`, read
583/// from the token as it is on disk: nobody is asked. `None` without a Visdom
584/// account login.
585pub fn stored_account(start: &Path) -> Option<String> {
586    let root = git_toplevel(start)
587        .map(|dir| tracevault_cli::paths::resolve_project_root(&dir).root)
588        .unwrap_or_else(|| start.to_path_buf());
589    match tracevault_cli::credentials::resolve_credentials_quiet(&root) {
590        Ok((_, Some(Credential::Keycloak(session)))) => {
591            Some(gateway::account_of(&session.access_token))
592        }
593        _ => None,
594    }
595}
596
597/// How long the token handed to the suite's other products must still be
598/// valid: enough for the few calls of one run.
599const MIN_TOKEN_SECONDS: i64 = 60;
600
601/// The HTTP client for the questions asked before an agent starts: nothing
602/// here may hold the developer up for long.
603pub fn http_client() -> reqwest::Client {
604    reqwest::Client::builder()
605        .timeout(std::time::Duration::from_secs(3))
606        .build()
607        .unwrap_or_default()
608}
609
610/// What a session through the gateway will use: the console, the LLM gateway
611/// behind it and the project whose key the agent gets. Nothing is issued.
612pub async fn plan_gateway(
613    http: &reqwest::Client,
614    console_url: Option<String>,
615    token: Option<&str>,
616    project: Option<&str>,
617) -> Result<GatewayPlan, String> {
618    let console_url = console_url.ok_or(
619        "this installation names no AI Gateway: set url under [gateway] in your visdom config, \
620         or VISDOM_GATEWAY_URL, to the gateway console's address",
621    )?;
622    if !bazaar::is_http_url(&console_url) {
623        return Err(format!(
624            "the AI Gateway address `{console_url}` is not an http(s) URL"
625        ));
626    }
627    let token = token.ok_or(
628        "the AI Gateway needs a Visdom account login (an API key does not work there): run \
629         `visdom login`",
630    )?;
631    let settings = gateway::console_settings(http, &console_url, token).await?;
632    let open = gateway::open_projects(http, &console_url, token).await?;
633    let project = gateway::pick_project(project, &open)?;
634    Ok(GatewayPlan {
635        console_url,
636        llm_url: settings.llm_url,
637        project,
638        subscription_traffic: settings.subscription_traffic,
639    })
640}
641
642/// No credential was resolved: either there is none, or the credential file
643/// is there and cannot be read or parsed (the library treats both alike).
644fn missing_or_unreadable() -> CredentialState {
645    use tracevault_cli::credentials::Credentials;
646    match Credentials::existing_path() {
647        Ok(path) if path.exists() && Credentials::load().is_none() => {
648            CredentialState::Unreadable(path.display().to_string())
649        }
650        _ => CredentialState::Missing,
651    }
652}
653
654/// Carries out fixes by running commands: `visdom` itself for tracing and
655/// login, the agent's own CLI for its MCP configuration.
656pub struct RealExecutor {
657    /// This executable.
658    pub visdom: PathBuf,
659    /// Send the commands' stdout to stderr (when stdout carries JSON).
660    pub stdout_to_stderr: bool,
661    /// Give the commands no stdin, so none of them can stop to ask anything:
662    /// with `--yes` the fix shown is applied with its defaults.
663    pub no_questions: bool,
664}
665
666impl RealExecutor {
667    pub fn new(stdout_to_stderr: bool, policy: FixPolicy) -> Self {
668        RealExecutor {
669            visdom: std::env::current_exe().unwrap_or_else(|_| PathBuf::from("visdom")),
670            stdout_to_stderr,
671            no_questions: policy == FixPolicy::All,
672        }
673    }
674
675    fn run(&self, program: &str, args: &[String], cwd: Option<&Path>) -> Result<(), String> {
676        let line = command_line(program, args);
677        let mut cmd = Command::new(program);
678        cmd.args(args);
679        if let Some(dir) = cwd {
680            cmd.current_dir(dir);
681        }
682        if self.stdout_to_stderr {
683            cmd.stdout(Stdio::from(std::io::stderr()));
684        }
685        if self.no_questions {
686            cmd.stdin(Stdio::null());
687        }
688        match cmd.status() {
689            Ok(status) if status.success() => Ok(()),
690            Ok(status) => Err(format!("`{line}` failed ({status})")),
691            Err(e) => Err(format!("cannot run `{line}`: {e}")),
692        }
693    }
694}
695
696impl FixExecutor for RealExecutor {
697    fn execute(&mut self, action: &FixAction) -> Result<(), String> {
698        let visdom = self.visdom.to_string_lossy().into_owned();
699        match action {
700            FixAction::TracingInit { agent, dir } => self.run(
701                &visdom,
702                &["trace", "init", "--agent", agent.tool_name()].map(String::from),
703                Some(dir),
704            ),
705            FixAction::Login { server_url } => self.run(
706                &visdom,
707                &["login", "--server-url", server_url].map(String::from),
708                None,
709            ),
710            FixAction::RunCommand { program, args, cwd } => self.run(program, args, cwd.as_deref()),
711            FixAction::Sequence { steps } => steps.iter().try_for_each(|step| self.execute(step)),
712        }
713    }
714}
715
716/// Whether a line read at the prompt is a yes. Enter alone is; end of input
717/// (nothing read, not even a newline) and a read error are not.
718pub fn is_yes(read: std::io::Result<usize>, line: &str) -> bool {
719    match read {
720        Ok(0) | Err(_) => false,
721        Ok(_) => matches!(line.trim(), "" | "y" | "Y" | "yes"),
722    }
723}
724
725/// Show one fix on the terminal and read the answer.
726pub fn ask_on_terminal(fix: &Fix) -> bool {
727    eprint!("Apply: {}? [Y/n] ", fix.description);
728    let _ = std::io::stderr().flush();
729    let mut answer = String::new();
730    let read = std::io::stdin().lock().read_line(&mut answer);
731    is_yes(read, &answer)
732}
733
734/// How a round of fixes went.
735#[derive(Clone, Copy, Debug, PartialEq, Eq)]
736pub struct FixSummary {
737    /// Something was changed, so the checks are worth running again.
738    pub applied: bool,
739    /// A fix that was meant to be applied failed.
740    pub failed: bool,
741}
742
743/// Offer the fixes of `findings` under `policy`, reporting each failure on
744/// stderr. A fix applied without asking is still shown first.
745pub fn fix(findings: &[Finding], policy: FixPolicy, exec: &mut dyn FixExecutor) -> FixSummary {
746    if policy == FixPolicy::All {
747        let mut shown: Vec<&str> = Vec::new();
748        for fix in findings.iter().filter_map(|f| f.fix.as_ref()) {
749            if !shown.contains(&fix.description.as_str()) {
750                eprintln!("visdom: applying: {}", fix.description);
751                shown.push(&fix.description);
752            }
753        }
754    }
755    let outcomes: Vec<FixOutcome> = apply_fixes(findings, policy, &mut ask_on_terminal, exec);
756    let mut reported: Vec<&str> = Vec::new();
757    for error in outcomes.iter().filter_map(|o| o.error.as_deref()) {
758        if !reported.contains(&error) {
759            eprintln!("visdom: fix failed: {error}");
760            reported.push(error);
761        }
762    }
763    FixSummary {
764        applied: outcomes.iter().any(|o| o.applied),
765        failed: outcomes.iter().any(|o| o.error.is_some()),
766    }
767}
768
769/// What a developer sees before the agent starts (or after `init`): the
770/// findings that need attention, on stderr. Nothing when all is well.
771pub fn print_attention(findings: &[Finding]) {
772    let attention = needs_attention(findings);
773    if !attention.is_empty() {
774        eprint!("{}", render_text(&attention));
775    }
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781
782    #[test]
783    fn end_of_input_at_the_prompt_is_a_no() {
784        assert!(is_yes(Ok(1), "\n"));
785        assert!(is_yes(Ok(2), "y\n"));
786        assert!(is_yes(Ok(4), "yes\n"));
787        assert!(!is_yes(Ok(2), "n\n"));
788        assert!(!is_yes(Ok(6), "maybe\n"));
789        // Ctrl-D: nothing was read.
790        assert!(!is_yes(Ok(0), ""));
791        assert!(!is_yes(Err(std::io::Error::other("closed")), ""));
792    }
793
794    /// With `--yes` a fix must not stop to ask: its command gets no stdin.
795    #[test]
796    fn no_questions_gives_commands_an_empty_stdin() {
797        let tmp = tempfile::tempdir().unwrap();
798        let out = tmp.path().join("read");
799        let mut exec = RealExecutor {
800            visdom: PathBuf::from("visdom"),
801            stdout_to_stderr: true,
802            no_questions: true,
803        };
804        let script = format!("cat > '{}'", out.display());
805        let result = exec.execute(&FixAction::RunCommand {
806            program: "sh".to_string(),
807            args: vec!["-c".to_string(), script],
808            cwd: None,
809        });
810        assert_eq!(result, Ok(()));
811        assert_eq!(std::fs::read(&out).unwrap(), b"");
812        assert!(RealExecutor::new(false, FixPolicy::All).no_questions);
813        assert!(!RealExecutor::new(false, FixPolicy::Ask).no_questions);
814    }
815
816    #[test]
817    fn settings_outside_a_checkout_are_the_nearest_folders_above() {
818        let tmp = tempfile::tempdir().unwrap();
819        let below = tmp.path().join("a").join("b");
820        std::fs::create_dir_all(&below).unwrap();
821        assert_eq!(settings_dir(&below), None);
822        std::fs::create_dir_all(tmp.path().join(".visdom")).unwrap();
823        std::fs::write(config::repo_config_path_in(tmp.path()), "").unwrap();
824        assert_eq!(settings_dir(&below).as_deref(), Some(tmp.path()));
825        // A checkout's own top level wins, with or without the file.
826        let status = Command::new("git")
827            .args(["init", "-q"])
828            .current_dir(&below)
829            .status()
830            .unwrap();
831        assert!(status.success());
832        assert_eq!(settings_dir(&below), git_toplevel(&below));
833    }
834
835    #[test]
836    fn git_toplevel_is_none_outside_a_repository() {
837        let tmp = tempfile::tempdir().unwrap();
838        assert_eq!(git_toplevel(tmp.path()), None);
839    }
840
841    #[test]
842    fn git_toplevel_from_a_subdirectory() {
843        let tmp = tempfile::tempdir().unwrap();
844        let status = Command::new("git")
845            .args(["init", "-q"])
846            .current_dir(tmp.path())
847            .status()
848            .unwrap();
849        assert!(status.success());
850        let sub = tmp.path().join("a/b");
851        std::fs::create_dir_all(&sub).unwrap();
852        assert_eq!(git_toplevel(&sub), Some(tmp.path().canonicalize().unwrap()));
853    }
854
855    #[test]
856    fn executor_reports_a_failing_and_a_missing_command() {
857        let mut exec = RealExecutor {
858            visdom: PathBuf::from("visdom"),
859            stdout_to_stderr: true,
860            no_questions: false,
861        };
862        let run = |program: &str, args: &[&str]| FixAction::RunCommand {
863            program: program.to_string(),
864            args: args.iter().map(|a| a.to_string()).collect(),
865            cwd: None,
866        };
867        assert_eq!(exec.execute(&run("true", &[])), Ok(()));
868        let err = exec.execute(&run("false", &[])).unwrap_err();
869        assert!(err.contains("`false` failed"), "{err}");
870        let err = exec
871            .execute(&run("/nonexistent/visdom-test-program", &["x"]))
872            .unwrap_err();
873        assert!(err.contains("cannot run"), "{err}");
874    }
875
876    #[test]
877    fn sequence_stops_at_the_first_failure() {
878        let tmp = tempfile::tempdir().unwrap();
879        let marker = tmp.path().join("ran");
880        let mut exec = RealExecutor {
881            visdom: PathBuf::from("visdom"),
882            stdout_to_stderr: true,
883            no_questions: false,
884        };
885        let step = |program: &str, args: Vec<String>| FixAction::RunCommand {
886            program: program.to_string(),
887            args,
888            cwd: None,
889        };
890        let result = exec.execute(&FixAction::Sequence {
891            steps: vec![
892                step("false", vec![]),
893                step("touch", vec![marker.to_string_lossy().into_owned()]),
894            ],
895        });
896        assert!(result.is_err());
897        assert!(!marker.exists(), "the step after a failure must not run");
898    }
899
900    #[test]
901    fn run_command_uses_its_directory() {
902        let tmp = tempfile::tempdir().unwrap();
903        let mut exec = RealExecutor {
904            visdom: PathBuf::from("visdom"),
905            stdout_to_stderr: true,
906            no_questions: false,
907        };
908        let result = exec.execute(&FixAction::RunCommand {
909            program: "touch".to_string(),
910            args: vec!["here".to_string()],
911            cwd: Some(tmp.path().to_path_buf()),
912        });
913        assert_eq!(result, Ok(()));
914        assert!(tmp.path().join("here").exists());
915    }
916}