Skip to main content

visdom_cli/
finding.rs

1//! What a check found, and the change that would fix it.
2
3use std::path::PathBuf;
4
5use serde::{Serialize, Serializer};
6use tracevault_cli::agent::Agent;
7
8#[derive(Serialize, Clone, Copy, PartialEq, Eq, Debug)]
9#[serde(rename_all = "snake_case")]
10pub enum Severity {
11    Ok,
12    /// Worth knowing, nothing to do.
13    Info,
14    Warn,
15    /// The component does not work for this project as it is.
16    Error,
17    /// Could not be verified (unreadable file, unreachable service).
18    Unknown,
19}
20
21#[derive(Serialize, Clone, Debug)]
22pub struct Finding {
23    pub component: &'static str,
24    pub id: &'static str,
25    pub severity: Severity,
26    pub message: String,
27    pub fix: Option<Fix>,
28}
29
30impl Finding {
31    pub fn new(
32        component: &'static str,
33        id: &'static str,
34        severity: Severity,
35        message: impl Into<String>,
36    ) -> Self {
37        Finding {
38            component,
39            id,
40            severity,
41            message: message.into(),
42            fix: None,
43        }
44    }
45
46    pub fn with_fix(mut self, fix: Fix) -> Self {
47        self.fix = Some(fix);
48        self
49    }
50}
51
52/// A change `visdom` can make. `description` is what the user is shown before
53/// agreeing to it: the command that will run and where.
54#[derive(Serialize, Clone, Debug)]
55pub struct Fix {
56    pub description: String,
57    pub action: FixAction,
58}
59
60#[derive(Serialize, Clone, Debug, PartialEq)]
61#[serde(tag = "kind", rename_all = "snake_case")]
62pub enum FixAction {
63    /// `visdom trace init --agent <agent>` in `dir`.
64    TracingInit {
65        #[serde(serialize_with = "ser_agent")]
66        agent: Agent,
67        dir: PathBuf,
68    },
69    /// `visdom login --server-url <server_url>`.
70    Login { server_url: String },
71    /// Any other command, e.g. the agent's own `mcp add`.
72    RunCommand {
73        program: String,
74        args: Vec<String>,
75        #[serde(skip_serializing_if = "Option::is_none")]
76        cwd: Option<PathBuf>,
77    },
78    /// Steps run in order; the first failure stops the rest.
79    Sequence { steps: Vec<FixAction> },
80}
81
82fn ser_agent<S: Serializer>(agent: &Agent, s: S) -> Result<S::Ok, S::Error> {
83    s.serialize_str(agent.tool_name())
84}
85
86/// The command line of a `RunCommand`, for display.
87pub fn command_line(program: &str, args: &[String]) -> String {
88    std::iter::once(program)
89        .chain(args.iter().map(String::as_str))
90        .map(|word| {
91            if word.is_empty() || word.contains(char::is_whitespace) {
92                format!("'{word}'")
93            } else {
94                word.to_string()
95            }
96        })
97        .collect::<Vec<_>>()
98        .join(" ")
99}
100
101fn marker(severity: Severity) -> char {
102    match severity {
103        Severity::Ok => '✓',
104        Severity::Info => '-',
105        Severity::Warn => '!',
106        Severity::Error => '✗',
107        Severity::Unknown => '?',
108    }
109}
110
111fn title(component: &str) -> String {
112    let mut chars = component.chars();
113    match chars.next() {
114        Some(first) => first.to_uppercase().chain(chars).collect(),
115        None => String::new(),
116    }
117}
118
119/// The findings as text, grouped by component in first-seen order.
120pub fn render_text(findings: &[Finding]) -> String {
121    let mut components: Vec<&str> = Vec::new();
122    for finding in findings {
123        if !components.contains(&finding.component) {
124            components.push(finding.component);
125        }
126    }
127    let mut out = String::new();
128    for component in components {
129        out.push_str(&title(component));
130        out.push('\n');
131        for finding in findings.iter().filter(|f| f.component == component) {
132            out.push_str(&format!(
133                "  {} {}\n",
134                marker(finding.severity),
135                finding.message
136            ));
137            if let Some(fix) = &finding.fix {
138                out.push_str(&format!("      fix: {}\n", fix.description));
139            }
140        }
141    }
142    out
143}
144
145/// `{"findings":[…]}`, pretty-printed.
146pub fn render_json(findings: &[Finding]) -> String {
147    serde_json::to_string_pretty(&serde_json::json!({ "findings": findings }))
148        .unwrap_or_else(|e| format!("{{\"error\":\"{e}\"}}"))
149}
150
151/// 1 when any finding is an error, else 0.
152pub fn exit_code(findings: &[Finding]) -> i32 {
153    i32::from(findings.iter().any(|f| f.severity == Severity::Error))
154}
155
156/// The findings a developer starting an agent should see: everything that is
157/// neither fine nor merely informational.
158pub fn needs_attention(findings: &[Finding]) -> Vec<Finding> {
159    findings
160        .iter()
161        .filter(|f| !matches!(f.severity, Severity::Ok | Severity::Info))
162        .cloned()
163        .collect()
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    fn run_fix() -> Fix {
171        Fix {
172            description: "run `claude mcp add …`".to_string(),
173            action: FixAction::RunCommand {
174                program: "claude".to_string(),
175                args: vec!["mcp".to_string(), "add".to_string()],
176                cwd: None,
177            },
178        }
179    }
180
181    #[test]
182    fn json_shape_is_stable() {
183        let findings = [
184            Finding::new("bazaar", "bazaar.mcp", Severity::Error, "not registered")
185                .with_fix(run_fix()),
186            Finding::new("tracing", "tracing.repo", Severity::Error, "no config").with_fix(Fix {
187                description: "init".to_string(),
188                action: FixAction::TracingInit {
189                    agent: Agent::ClaudeCode,
190                    dir: PathBuf::from("/repo"),
191                },
192            }),
193        ];
194        let v: serde_json::Value = serde_json::from_str(&render_json(&findings)).unwrap();
195        let first = &v["findings"][0];
196        let keys: Vec<&str> = first
197            .as_object()
198            .unwrap()
199            .keys()
200            .map(String::as_str)
201            .collect();
202        assert_eq!(keys, ["component", "id", "severity", "message", "fix"]);
203        assert_eq!(first["severity"], "error");
204        assert_eq!(first["fix"]["action"]["kind"], "run_command");
205        assert_eq!(first["fix"]["action"]["program"], "claude");
206        assert!(first["fix"]["action"].get("cwd").is_none());
207        let init = &v["findings"][1]["fix"]["action"];
208        assert_eq!(init["kind"], "tracing_init");
209        assert_eq!(init["agent"], "claude-code");
210    }
211
212    #[test]
213    fn exit_code_only_on_error() {
214        let mk = |s| Finding::new("tracing", "x", s, "m");
215        assert_eq!(exit_code(&[]), 0);
216        assert_eq!(
217            exit_code(&[
218                mk(Severity::Ok),
219                mk(Severity::Info),
220                mk(Severity::Warn),
221                mk(Severity::Unknown)
222            ]),
223            0
224        );
225        assert_eq!(exit_code(&[mk(Severity::Ok), mk(Severity::Error)]), 1);
226    }
227
228    #[test]
229    fn text_groups_by_component_and_shows_fixes() {
230        let text = render_text(&[
231            Finding::new("tracing", "tracing.auth", Severity::Ok, "logged in"),
232            Finding::new("bazaar", "bazaar.mcp", Severity::Error, "not registered")
233                .with_fix(run_fix()),
234            Finding::new(
235                "tracing",
236                "tracing.git_hooks",
237                Severity::Warn,
238                "no git hooks",
239            ),
240        ]);
241        assert_eq!(
242            text,
243            "Tracing\n  ✓ logged in\n  ! no git hooks\nBazaar\n  ✗ not registered\n      fix: run \
244             `claude mcp add …`\n"
245        );
246    }
247
248    #[test]
249    fn needs_attention_drops_ok_and_info() {
250        let mk = |s| Finding::new("tracing", "x", s, "m");
251        let kept = needs_attention(&[
252            mk(Severity::Ok),
253            mk(Severity::Info),
254            mk(Severity::Warn),
255            mk(Severity::Error),
256            mk(Severity::Unknown),
257        ]);
258        let severities: Vec<Severity> = kept.iter().map(|f| f.severity).collect();
259        assert_eq!(
260            severities,
261            [Severity::Warn, Severity::Error, Severity::Unknown]
262        );
263    }
264
265    #[test]
266    fn command_line_quotes_words_with_spaces() {
267        assert_eq!(
268            command_line("claude", &["mcp".to_string(), "my server".to_string()]),
269            "claude mcp 'my server'"
270        );
271    }
272}