1use 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, Workdir};
12use crate::components::gateway::GatewayPlan;
13use crate::components::{
14 bazaar, gateway as gateway_checks, tracing, CheckContext, CredentialState,
15};
16use crate::config::{self, RepoConfig, UserConfig};
17use crate::finding::{command_line, needs_attention, render_text, Finding, Fix, FixAction};
18use crate::fixes::{apply_fixes, FixExecutor, FixOutcome, FixPolicy};
19use crate::gateway;
20use crate::mode::{configured_mode, effective_mode, ResolvedMode, TracingMode, MODE_ENV};
21use crate::suite::{self, PolicyState, SuiteMap};
22
23fn first_set(candidates: [Option<String>; 3]) -> Option<String> {
25 candidates
26 .into_iter()
27 .flatten()
28 .map(|v| v.trim().trim_end_matches('/').to_string())
29 .find(|v| !v.is_empty())
30}
31
32pub fn git_toplevel(from: &Path) -> Option<PathBuf> {
34 let output = Command::new("git")
35 .args(["rev-parse", "--show-toplevel"])
36 .current_dir(from)
37 .stderr(Stdio::null())
38 .output()
39 .ok()
40 .filter(|o| o.status.success())?;
41 let path = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
42 Some(path.canonicalize().unwrap_or(path))
43}
44
45pub struct Environment {
47 pub cwd: PathBuf,
48 pub home: PathBuf,
49 pub config_root: PathBuf,
51 pub codex_home: PathBuf,
52 pub agent: Option<String>,
54 pub bazaar_url: Option<String>,
56 pub mode: Option<String>,
58 pub gateway_url: Option<String>,
60 pub control_plane_url: Option<String>,
62}
63
64impl Environment {
65 pub fn current() -> Self {
66 let home = dirs::home_dir().unwrap_or_default();
67 let set = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
68 Environment {
69 cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
70 config_root: dirs::config_dir().unwrap_or_else(|| home.join(".config")),
71 codex_home: set("CODEX_HOME")
72 .map(PathBuf::from)
73 .unwrap_or_else(|| home.join(".codex")),
74 agent: set("VISDOM_AGENT"),
75 bazaar_url: set("VISDOM_BAZAAR_URL"),
76 mode: set(MODE_ENV),
77 gateway_url: set("VISDOM_GATEWAY_URL"),
78 control_plane_url: set("VISDOM_CONTROL_PLANE_URL"),
79 home,
80 }
81 }
82}
83
84pub struct Session {
86 pub ctx: CheckContext,
87 pub adapter: Box<dyn AgentAdapter>,
88 pub bazaar_url: Result<Option<String>, String>,
90 pub user_config_path: PathBuf,
91 pub warnings: Vec<String>,
93 pub mode: ResolvedMode,
95 pub policy: PolicyState,
96 pub gateway: Option<Result<GatewayPlan, String>>,
98 pub suite: SuiteMap,
100 pub token: Option<String>,
103 pub gateway_model: Option<String>,
105 pub config_root: PathBuf,
107}
108
109impl Session {
110 pub fn gather(
113 env: &Environment,
114 agent_flag: Option<Agent>,
115 mode_flag: Option<TracingMode>,
116 runtime: &tokio::runtime::Runtime,
117 ) -> Result<Session, String> {
118 let mut warnings = Vec::new();
119 let project_dir = git_toplevel(&env.cwd);
120 let user: UserConfig = config::load_user_config_in(&env.config_root).unwrap_or_else(|e| {
121 warnings.push(e);
122 UserConfig::default()
123 });
124 let repo = project_dir
125 .as_deref()
126 .map(config::load_repo_config_in)
127 .transpose()
128 .unwrap_or_else(|e| {
129 warnings.push(e);
130 None
131 })
132 .unwrap_or_default();
133 let repo: RepoConfig = repo;
134 let agent = config::resolve_agent(agent_flag, env.agent.as_deref(), &repo, &user)?;
135 let chosen = configured_mode(
136 mode_flag,
137 env.mode.as_deref(),
138 repo.tracing_mode,
139 user.tracing_mode,
140 )?;
141
142 let tracing_root = project_dir
143 .as_deref()
144 .map(|dir| tracevault_cli::paths::resolve_project_root(dir).root);
145 let credential_root = tracing_root.as_deref().unwrap_or(&env.cwd);
146 let (server_url, credential, session) =
147 match tracevault_cli::credentials::resolve_credentials_quiet(credential_root) {
148 Ok((url, Some(credential))) => {
149 let session = match credential {
150 Credential::Keycloak(_) => Some(credential),
151 Credential::ApiKey(_) => None,
152 };
153 (url, CredentialState::Present, session)
154 }
155 Ok((url, None)) => (url, missing_or_unreadable(), None),
156 Err(e) => (None, CredentialState::Unusable(e.to_string()), None),
157 };
158
159 let http = http_client();
160 let published = match &server_url {
162 Some(url) => runtime.block_on(suite::fetch_suite_map(&http, url)),
163 None => Ok(SuiteMap::default()),
164 };
165 let bazaar_url = bazaar::resolve_bazaar_url(env.bazaar_url.clone(), &user, &published);
166 let suite_map = match &server_url {
169 Some(url) => suite::suite_map_or_remembered(
170 &published,
171 url,
172 &suite::suite_cache_path_in(&env.config_root),
173 ),
174 None => SuiteMap::default(),
175 };
176
177 let token = match (&server_url, session) {
180 (Some(url), Some(session)) => runtime
181 .block_on(
182 tracevault_cli::api_client::ApiClient::with_credential(url, Some(session))
183 .bearer_valid_for(MIN_TOKEN_SECONDS),
184 )
185 .ok()
186 .flatten(),
187 _ => None,
188 };
189 let control_plane_url = first_set([
190 env.control_plane_url.clone(),
191 user.control_plane_url.clone(),
192 suite_map.control_plane_url.clone(),
193 ]);
194 let policy = runtime.block_on(suite::resolve_policy(
195 &http,
196 control_plane_url.as_deref(),
197 token.as_deref(),
198 &suite::policy_cache_path_in(&env.config_root),
199 ));
200 let mode = effective_mode(chosen, policy.policy());
201 let gateway = (mode.mode == TracingMode::Gateway).then(|| {
202 let console_url = first_set([
203 env.gateway_url.clone(),
204 user.gateway.url.clone(),
205 suite_map.ai_gateway_url.clone(),
206 ]);
207 let project = repo
208 .gateway
209 .project
210 .clone()
211 .or_else(|| user.gateway.project.clone());
212 runtime.block_on(plan_gateway(
213 &http,
214 console_url,
215 token.as_deref(),
216 project.as_deref(),
217 ))
218 });
219
220 let paths = AgentPaths {
221 home: env.home.clone(),
222 codex_home: env.codex_home.clone(),
223 };
224 let adapter = adapter_for(agent, paths, user.agents.program_for(agent))
225 .ok_or_else(|| format!("visdom cannot launch {}", agent.tool_name()))?;
226 Ok(Session {
227 ctx: CheckContext {
228 mode: mode.mode,
229 workdir: Workdir {
230 start_dir: env.cwd.clone(),
231 checkout: project_dir,
232 primary: tracing_root,
233 },
234 home: env.home.clone(),
235 codex_home: env.codex_home.clone(),
236 agent,
237 server_url,
238 credential,
239 },
240 adapter,
241 bazaar_url,
242 user_config_path: config::user_config_path_in(&env.config_root),
243 warnings,
244 mode,
245 policy,
246 gateway,
247 suite: suite_map,
248 token,
249 gateway_model: user.gateway.model_for(agent),
250 config_root: env.config_root.clone(),
251 })
252 }
253
254 pub fn collect(&self) -> Vec<Finding> {
256 let mut findings = tracing::check(&self.ctx);
257 findings.extend(gateway_checks::check(
258 &self.mode,
259 &self.policy,
260 self.gateway.as_ref(),
261 self.ctx.agent,
262 ));
263 findings.extend(bazaar::check(
264 self.bazaar_url
265 .as_ref()
266 .map(|url| url.as_deref())
267 .map_err(String::as_str),
268 self.adapter.as_ref(),
269 &self.ctx.workdir,
270 &self.user_config_path,
271 ));
272 findings
273 }
274}
275
276pub fn person_token(start: &Path, runtime: &tokio::runtime::Runtime) -> Result<String, String> {
279 let root = git_toplevel(start)
280 .map(|dir| tracevault_cli::paths::resolve_project_root(&dir).root)
281 .unwrap_or_else(|| start.to_path_buf());
282 let login = "the AI Gateway needs a Visdom account login: run `visdom login`";
283 match tracevault_cli::credentials::resolve_credentials_quiet(&root) {
284 Ok((Some(url), Some(session @ Credential::Keycloak(_)))) => runtime
285 .block_on(
286 tracevault_cli::api_client::ApiClient::with_credential(&url, Some(session))
287 .bearer_valid_for(MIN_TOKEN_SECONDS),
288 )
289 .map_err(|e| format!("your Visdom login could not be used ({e}): run `visdom login`"))?
290 .ok_or_else(|| login.to_string()),
291 Ok(_) => Err(login.to_string()),
292 Err(e) => Err(e.to_string()),
293 }
294}
295
296pub fn stored_account(start: &Path) -> Option<String> {
300 let root = git_toplevel(start)
301 .map(|dir| tracevault_cli::paths::resolve_project_root(&dir).root)
302 .unwrap_or_else(|| start.to_path_buf());
303 match tracevault_cli::credentials::resolve_credentials_quiet(&root) {
304 Ok((_, Some(Credential::Keycloak(session)))) => {
305 Some(gateway::account_of(&session.access_token))
306 }
307 _ => None,
308 }
309}
310
311const MIN_TOKEN_SECONDS: i64 = 60;
314
315pub fn http_client() -> reqwest::Client {
318 reqwest::Client::builder()
319 .timeout(std::time::Duration::from_secs(3))
320 .build()
321 .unwrap_or_default()
322}
323
324pub async fn plan_gateway(
327 http: &reqwest::Client,
328 console_url: Option<String>,
329 token: Option<&str>,
330 project: Option<&str>,
331) -> Result<GatewayPlan, String> {
332 let console_url = console_url.ok_or(
333 "this installation names no AI Gateway: set VISDOM_GATEWAY_URL, or url under [gateway] \
334 in your visdom config, to the gateway console's address",
335 )?;
336 if !bazaar::is_http_url(&console_url) {
337 return Err(format!(
338 "the AI Gateway address `{console_url}` is not an http(s) URL"
339 ));
340 }
341 let token = token.ok_or(
342 "the AI Gateway needs a Visdom account login (an API key does not work there): run \
343 `visdom login`",
344 )?;
345 let llm_url = gateway::llm_gateway_url(http, &console_url, token).await?;
346 let open = gateway::open_projects(http, &console_url, token).await?;
347 let project = gateway::pick_project(project, &open)?;
348 Ok(GatewayPlan {
349 console_url,
350 llm_url,
351 project,
352 })
353}
354
355fn missing_or_unreadable() -> CredentialState {
358 use tracevault_cli::credentials::Credentials;
359 match Credentials::path() {
360 Ok(path) if path.exists() && Credentials::load().is_none() => {
361 CredentialState::Unreadable(path.display().to_string())
362 }
363 _ => CredentialState::Missing,
364 }
365}
366
367pub struct RealExecutor {
370 pub visdom: PathBuf,
372 pub stdout_to_stderr: bool,
374 pub no_questions: bool,
377}
378
379impl RealExecutor {
380 pub fn new(stdout_to_stderr: bool, policy: FixPolicy) -> Self {
381 RealExecutor {
382 visdom: std::env::current_exe().unwrap_or_else(|_| PathBuf::from("visdom")),
383 stdout_to_stderr,
384 no_questions: policy == FixPolicy::All,
385 }
386 }
387
388 fn run(&self, program: &str, args: &[String], cwd: Option<&Path>) -> Result<(), String> {
389 let line = command_line(program, args);
390 let mut cmd = Command::new(program);
391 cmd.args(args);
392 if let Some(dir) = cwd {
393 cmd.current_dir(dir);
394 }
395 if self.stdout_to_stderr {
396 cmd.stdout(Stdio::from(std::io::stderr()));
397 }
398 if self.no_questions {
399 cmd.stdin(Stdio::null());
400 }
401 match cmd.status() {
402 Ok(status) if status.success() => Ok(()),
403 Ok(status) => Err(format!("`{line}` failed ({status})")),
404 Err(e) => Err(format!("cannot run `{line}`: {e}")),
405 }
406 }
407}
408
409impl FixExecutor for RealExecutor {
410 fn execute(&mut self, action: &FixAction) -> Result<(), String> {
411 let visdom = self.visdom.to_string_lossy().into_owned();
412 match action {
413 FixAction::TracingInit { agent, dir } => self.run(
414 &visdom,
415 &["trace", "init", "--agent", agent.tool_name()].map(String::from),
416 Some(dir),
417 ),
418 FixAction::Login { server_url } => self.run(
419 &visdom,
420 &["login", "--server-url", server_url].map(String::from),
421 None,
422 ),
423 FixAction::RunCommand { program, args, cwd } => self.run(program, args, cwd.as_deref()),
424 FixAction::Sequence { steps } => steps.iter().try_for_each(|step| self.execute(step)),
425 }
426 }
427}
428
429pub fn is_yes(read: std::io::Result<usize>, line: &str) -> bool {
432 match read {
433 Ok(0) | Err(_) => false,
434 Ok(_) => matches!(line.trim(), "" | "y" | "Y" | "yes"),
435 }
436}
437
438pub fn ask_on_terminal(fix: &Fix) -> bool {
440 eprint!("Apply: {}? [Y/n] ", fix.description);
441 let _ = std::io::stderr().flush();
442 let mut answer = String::new();
443 let read = std::io::stdin().lock().read_line(&mut answer);
444 is_yes(read, &answer)
445}
446
447#[derive(Clone, Copy, Debug, PartialEq, Eq)]
449pub struct FixSummary {
450 pub applied: bool,
452 pub failed: bool,
454}
455
456pub fn fix(findings: &[Finding], policy: FixPolicy, exec: &mut dyn FixExecutor) -> FixSummary {
459 if policy == FixPolicy::All {
460 let mut shown: Vec<&str> = Vec::new();
461 for fix in findings.iter().filter_map(|f| f.fix.as_ref()) {
462 if !shown.contains(&fix.description.as_str()) {
463 eprintln!("visdom: applying: {}", fix.description);
464 shown.push(&fix.description);
465 }
466 }
467 }
468 let outcomes: Vec<FixOutcome> = apply_fixes(findings, policy, &mut ask_on_terminal, exec);
469 let mut reported: Vec<&str> = Vec::new();
470 for error in outcomes.iter().filter_map(|o| o.error.as_deref()) {
471 if !reported.contains(&error) {
472 eprintln!("visdom: fix failed: {error}");
473 reported.push(error);
474 }
475 }
476 FixSummary {
477 applied: outcomes.iter().any(|o| o.applied),
478 failed: outcomes.iter().any(|o| o.error.is_some()),
479 }
480}
481
482pub fn print_attention(findings: &[Finding]) {
485 let attention = needs_attention(findings);
486 if !attention.is_empty() {
487 eprint!("{}", render_text(&attention));
488 }
489}
490
491#[cfg(test)]
492mod tests {
493 use super::*;
494
495 #[test]
496 fn end_of_input_at_the_prompt_is_a_no() {
497 assert!(is_yes(Ok(1), "\n"));
498 assert!(is_yes(Ok(2), "y\n"));
499 assert!(is_yes(Ok(4), "yes\n"));
500 assert!(!is_yes(Ok(2), "n\n"));
501 assert!(!is_yes(Ok(6), "maybe\n"));
502 assert!(!is_yes(Ok(0), ""));
504 assert!(!is_yes(Err(std::io::Error::other("closed")), ""));
505 }
506
507 #[test]
509 fn no_questions_gives_commands_an_empty_stdin() {
510 let tmp = tempfile::tempdir().unwrap();
511 let out = tmp.path().join("read");
512 let mut exec = RealExecutor {
513 visdom: PathBuf::from("visdom"),
514 stdout_to_stderr: true,
515 no_questions: true,
516 };
517 let script = format!("cat > '{}'", out.display());
518 let result = exec.execute(&FixAction::RunCommand {
519 program: "sh".to_string(),
520 args: vec!["-c".to_string(), script],
521 cwd: None,
522 });
523 assert_eq!(result, Ok(()));
524 assert_eq!(std::fs::read(&out).unwrap(), b"");
525 assert!(RealExecutor::new(false, FixPolicy::All).no_questions);
526 assert!(!RealExecutor::new(false, FixPolicy::Ask).no_questions);
527 }
528
529 #[test]
530 fn git_toplevel_is_none_outside_a_repository() {
531 let tmp = tempfile::tempdir().unwrap();
532 assert_eq!(git_toplevel(tmp.path()), None);
533 }
534
535 #[test]
536 fn git_toplevel_from_a_subdirectory() {
537 let tmp = tempfile::tempdir().unwrap();
538 let status = Command::new("git")
539 .args(["init", "-q"])
540 .current_dir(tmp.path())
541 .status()
542 .unwrap();
543 assert!(status.success());
544 let sub = tmp.path().join("a/b");
545 std::fs::create_dir_all(&sub).unwrap();
546 assert_eq!(git_toplevel(&sub), Some(tmp.path().canonicalize().unwrap()));
547 }
548
549 #[test]
550 fn executor_reports_a_failing_and_a_missing_command() {
551 let mut exec = RealExecutor {
552 visdom: PathBuf::from("visdom"),
553 stdout_to_stderr: true,
554 no_questions: false,
555 };
556 let run = |program: &str, args: &[&str]| FixAction::RunCommand {
557 program: program.to_string(),
558 args: args.iter().map(|a| a.to_string()).collect(),
559 cwd: None,
560 };
561 assert_eq!(exec.execute(&run("true", &[])), Ok(()));
562 let err = exec.execute(&run("false", &[])).unwrap_err();
563 assert!(err.contains("`false` failed"), "{err}");
564 let err = exec
565 .execute(&run("/nonexistent/visdom-test-program", &["x"]))
566 .unwrap_err();
567 assert!(err.contains("cannot run"), "{err}");
568 }
569
570 #[test]
571 fn sequence_stops_at_the_first_failure() {
572 let tmp = tempfile::tempdir().unwrap();
573 let marker = tmp.path().join("ran");
574 let mut exec = RealExecutor {
575 visdom: PathBuf::from("visdom"),
576 stdout_to_stderr: true,
577 no_questions: false,
578 };
579 let step = |program: &str, args: Vec<String>| FixAction::RunCommand {
580 program: program.to_string(),
581 args,
582 cwd: None,
583 };
584 let result = exec.execute(&FixAction::Sequence {
585 steps: vec![
586 step("false", vec![]),
587 step("touch", vec![marker.to_string_lossy().into_owned()]),
588 ],
589 });
590 assert!(result.is_err());
591 assert!(!marker.exists(), "the step after a failure must not run");
592 }
593
594 #[test]
595 fn run_command_uses_its_directory() {
596 let tmp = tempfile::tempdir().unwrap();
597 let mut exec = RealExecutor {
598 visdom: PathBuf::from("visdom"),
599 stdout_to_stderr: true,
600 no_questions: false,
601 };
602 let result = exec.execute(&FixAction::RunCommand {
603 program: "touch".to_string(),
604 args: vec!["here".to_string()],
605 cwd: Some(tmp.path().to_path_buf()),
606 });
607 assert_eq!(result, Ok(()));
608 assert!(tmp.path().join("here").exists());
609 }
610}