Skip to main content

zeph_tools/
diagnostics.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::path::{Path, PathBuf};
5
6use schemars::JsonSchema;
7use serde::Deserialize;
8
9use crate::executor::{ToolCall, ToolError, ToolExecutor, ToolOutput, deserialize_params};
10use crate::registry::{InvocationHint, ToolDef};
11
12/// Cargo diagnostics level.
13#[derive(Debug, Default, Deserialize, JsonSchema, PartialEq, Eq)]
14#[serde(rename_all = "snake_case")]
15pub enum DiagnosticsLevel {
16    /// Run `cargo check`
17    #[default]
18    Check,
19    /// Run `cargo clippy`
20    Clippy,
21}
22
23#[derive(Debug, Deserialize, JsonSchema)]
24struct DiagnosticsParams {
25    /// Workspace path (defaults to current directory)
26    path: Option<String>,
27    /// Diagnostics level: check or clippy
28    #[serde(default)]
29    level: DiagnosticsLevel,
30}
31
32/// Runs `cargo check` or `cargo clippy` and returns structured diagnostics.
33#[derive(Debug)]
34pub struct DiagnosticsExecutor {
35    allowed_paths: Vec<PathBuf>,
36    /// Maximum number of diagnostics to return (default: 50)
37    max_diagnostics: usize,
38}
39
40impl DiagnosticsExecutor {
41    #[must_use]
42    pub fn new(allowed_paths: Vec<PathBuf>) -> Self {
43        let paths = if allowed_paths.is_empty() {
44            vec![std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))]
45        } else {
46            allowed_paths
47        };
48        Self {
49            allowed_paths: paths
50                .into_iter()
51                .map(|p| p.canonicalize().unwrap_or(p))
52                .collect(),
53            max_diagnostics: 50,
54        }
55    }
56
57    #[must_use]
58    pub fn with_max_diagnostics(mut self, max: usize) -> Self {
59        self.max_diagnostics = max;
60        self
61    }
62
63    fn validate_path(&self, path: &Path) -> Result<PathBuf, ToolError> {
64        let resolved = if path.is_absolute() {
65            path.to_path_buf()
66        } else {
67            std::env::current_dir()
68                .unwrap_or_else(|_| PathBuf::from("."))
69                .join(path)
70        };
71        let canonical = resolved.canonicalize().map_err(|e| {
72            ToolError::Execution(std::io::Error::new(
73                std::io::ErrorKind::NotFound,
74                format!("path not found: {}: {e}", resolved.display()),
75            ))
76        })?;
77        if !self.allowed_paths.iter().any(|a| canonical.starts_with(a)) {
78            return Err(ToolError::SandboxViolation {
79                path: canonical.display().to_string(),
80            });
81        }
82        Ok(canonical)
83    }
84}
85
86impl ToolExecutor for DiagnosticsExecutor {
87    async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
88        Ok(None)
89    }
90
91    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
92        if call.tool_id != "diagnostics" {
93            return Ok(None);
94        }
95        let p: DiagnosticsParams = deserialize_params(&call.params)?;
96        let work_dir = if let Some(path) = &p.path {
97            self.validate_path(Path::new(path))?
98        } else {
99            let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
100            self.validate_path(&cwd)?
101        };
102
103        let subcmd = match p.level {
104            DiagnosticsLevel::Check => "check",
105            DiagnosticsLevel::Clippy => "clippy",
106        };
107
108        let cargo = which_cargo()?;
109
110        let output = tokio::process::Command::new(&cargo)
111            .arg(subcmd)
112            .arg("--message-format=json")
113            .current_dir(&work_dir)
114            .output()
115            .await
116            .map_err(|e| {
117                ToolError::Execution(std::io::Error::new(
118                    std::io::ErrorKind::NotFound,
119                    format!("failed to run cargo: {e}"),
120                ))
121            })?;
122
123        let stdout = String::from_utf8_lossy(&output.stdout);
124        let diagnostics = parse_cargo_json(&stdout, self.max_diagnostics);
125
126        let summary = if diagnostics.is_empty() {
127            "No diagnostics".to_owned()
128        } else {
129            diagnostics.join("\n")
130        };
131
132        Ok(Some(ToolOutput {
133            tool_name: "diagnostics".to_owned(),
134            summary,
135            blocks_executed: 1,
136            filter_stats: None,
137            diff: None,
138            streamed: false,
139            terminal_id: None,
140            locations: None,
141            raw_response: None,
142        }))
143    }
144
145    fn tool_definitions(&self) -> Vec<ToolDef> {
146        vec![ToolDef {
147            id: "diagnostics".into(),
148            description: "Run cargo check/clippy and return compiler diagnostics".into(),
149            schema: schemars::schema_for!(DiagnosticsParams),
150            invocation: InvocationHint::ToolCall,
151        }]
152    }
153}
154
155/// Returns the path to the `cargo` binary, failing gracefully if not found.
156///
157/// Reads the `CARGO` environment variable (set by rustup/cargo during builds) or
158/// falls back to a PATH search. The process environment is assumed trusted — this
159/// function runs in the same process as the agent, not in an untrusted context.
160/// Canonicalization is applied as defence-in-depth to resolve any symlinks in the path.
161fn which_cargo() -> Result<PathBuf, ToolError> {
162    // Check CARGO env var first (set by rustup/cargo itself)
163    if let Ok(cargo) = std::env::var("CARGO") {
164        let p = PathBuf::from(&cargo);
165        if p.is_file() {
166            return Ok(p.canonicalize().unwrap_or(p));
167        }
168    }
169    // Fall back to PATH lookup
170    for dir in std::env::var("PATH").unwrap_or_default().split(':') {
171        let candidate = PathBuf::from(dir).join("cargo");
172        if candidate.is_file() {
173            return Ok(candidate.canonicalize().unwrap_or(candidate));
174        }
175    }
176    Err(ToolError::Execution(std::io::Error::new(
177        std::io::ErrorKind::NotFound,
178        "cargo not found in PATH",
179    )))
180}
181
182/// Parses cargo JSON output lines and extracts human-readable diagnostics.
183///
184/// Each JSON line from `--message-format=json` that represents a `compiler-message`
185/// with a span is formatted as `file:line:col: level: message`.
186pub(crate) fn parse_cargo_json(output: &str, max: usize) -> Vec<String> {
187    let mut results = Vec::new();
188    for line in output.lines() {
189        if results.len() >= max {
190            break;
191        }
192        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
193            continue;
194        };
195        if val.get("reason").and_then(|r| r.as_str()) != Some("compiler-message") {
196            continue;
197        }
198        let Some(msg) = val.get("message") else {
199            continue;
200        };
201        let level = msg
202            .get("level")
203            .and_then(|l| l.as_str())
204            .unwrap_or("unknown");
205        let text = msg
206            .get("message")
207            .and_then(|m| m.as_str())
208            .unwrap_or("")
209            .trim();
210        if text.is_empty() {
211            continue;
212        }
213
214        // Use the primary span if available for location info
215        let spans = msg
216            .get("spans")
217            .and_then(serde_json::Value::as_array)
218            .map_or(&[] as &[_], Vec::as_slice);
219
220        let primary = spans.iter().find(|s| {
221            s.get("is_primary")
222                .and_then(serde_json::Value::as_bool)
223                .unwrap_or(false)
224        });
225
226        if let Some(span) = primary {
227            let file = span
228                .get("file_name")
229                .and_then(|f| f.as_str())
230                .unwrap_or("?");
231            let line = span
232                .get("line_start")
233                .and_then(serde_json::Value::as_u64)
234                .unwrap_or(0);
235            let col = span
236                .get("column_start")
237                .and_then(serde_json::Value::as_u64)
238                .unwrap_or(0);
239            results.push(format!("{file}:{line}:{col}: {level}: {text}"));
240        } else {
241            results.push(format!("{level}: {text}"));
242        }
243    }
244    results
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    fn make_params(
252        pairs: &[(&str, serde_json::Value)],
253    ) -> serde_json::Map<String, serde_json::Value> {
254        pairs
255            .iter()
256            .map(|(k, v)| ((*k).to_owned(), v.clone()))
257            .collect()
258    }
259
260    // --- parse_cargo_json unit tests ---
261
262    #[test]
263    fn parse_cargo_json_empty_input() {
264        let result = parse_cargo_json("", 50);
265        assert!(result.is_empty());
266    }
267
268    #[test]
269    fn parse_cargo_json_non_compiler_message_ignored() {
270        let line = r#"{"reason":"build-script-executed","package_id":"foo"}"#;
271        let result = parse_cargo_json(line, 50);
272        assert!(result.is_empty());
273    }
274
275    #[test]
276    fn parse_cargo_json_compiler_message_with_span() {
277        let line = r#"{"reason":"compiler-message","message":{"level":"error","message":"cannot find value `foo` in this scope","spans":[{"file_name":"src/main.rs","line_start":10,"column_start":5,"is_primary":true}]}}"#;
278        let result = parse_cargo_json(line, 50);
279        assert_eq!(result.len(), 1);
280        assert!(result[0].contains("src/main.rs"));
281        assert!(result[0].contains("10"));
282        assert!(result[0].contains("error"));
283        assert!(result[0].contains("cannot find value"));
284    }
285
286    #[test]
287    fn parse_cargo_json_warning_with_span() {
288        let line = r#"{"reason":"compiler-message","message":{"level":"warning","message":"unused variable: `x`","spans":[{"file_name":"src/lib.rs","line_start":3,"column_start":9,"is_primary":true}]}}"#;
289        let result = parse_cargo_json(line, 50);
290        assert_eq!(result.len(), 1);
291        assert!(result[0].starts_with("src/lib.rs:3:9: warning:"));
292    }
293
294    #[test]
295    fn parse_cargo_json_no_primary_span_uses_message_only() {
296        let line = r#"{"reason":"compiler-message","message":{"level":"error","message":"aborting due to previous error","spans":[]}}"#;
297        let result = parse_cargo_json(line, 50);
298        assert_eq!(result.len(), 1);
299        assert_eq!(result[0], "error: aborting due to previous error");
300    }
301
302    #[test]
303    fn parse_cargo_json_max_cap_respected() {
304        let single = r#"{"reason":"compiler-message","message":{"level":"warning","message":"unused","spans":[]}}"#;
305        let input: String = (0..20).map(|_| single).collect::<Vec<_>>().join("\n");
306        let result = parse_cargo_json(&input, 5);
307        assert_eq!(result.len(), 5);
308    }
309
310    #[test]
311    fn parse_cargo_json_empty_message_skipped() {
312        let line = r#"{"reason":"compiler-message","message":{"level":"note","message":"   ","spans":[]}}"#;
313        let result = parse_cargo_json(line, 50);
314        assert!(result.is_empty());
315    }
316
317    #[test]
318    fn parse_cargo_json_non_primary_span_skipped_for_location() {
319        let line = r#"{"reason":"compiler-message","message":{"level":"warning","message":"some warning","spans":[{"file_name":"src/foo.rs","line_start":1,"column_start":1,"is_primary":false}]}}"#;
320        // No primary span → fall back to message-only format
321        let result = parse_cargo_json(line, 50);
322        assert_eq!(result.len(), 1);
323        assert_eq!(result[0], "warning: some warning");
324    }
325
326    #[test]
327    fn parse_cargo_json_invalid_json_line_skipped() {
328        let input = "not json\n{\"reason\":\"build-script-executed\"}";
329        let result = parse_cargo_json(input, 50);
330        assert!(result.is_empty());
331    }
332
333    // --- sandbox tests ---
334
335    #[tokio::test]
336    async fn diagnostics_sandbox_violation() {
337        let dir = tempfile::tempdir().unwrap();
338        let exec = DiagnosticsExecutor::new(vec![dir.path().to_path_buf()]);
339
340        let call = ToolCall {
341            tool_id: "diagnostics".to_owned(),
342            params: make_params(&[("path", serde_json::json!("/etc"))]),
343        };
344        let result = exec.execute_tool_call(&call).await;
345        assert!(result.is_err());
346    }
347
348    #[tokio::test]
349    async fn diagnostics_unknown_tool_returns_none() {
350        let exec = DiagnosticsExecutor::new(vec![]);
351        let call = ToolCall {
352            tool_id: "other".to_owned(),
353            params: serde_json::Map::new(),
354        };
355        let result = exec.execute_tool_call(&call).await.unwrap();
356        assert!(result.is_none());
357    }
358
359    #[test]
360    fn diagnostics_tool_definition() {
361        let exec = DiagnosticsExecutor::new(vec![]);
362        let defs = exec.tool_definitions();
363        assert_eq!(defs.len(), 1);
364        assert_eq!(defs[0].id, "diagnostics");
365        assert_eq!(defs[0].invocation, InvocationHint::ToolCall);
366    }
367
368    #[test]
369    fn diagnostics_level_default_is_check() {
370        assert_eq!(DiagnosticsLevel::default(), DiagnosticsLevel::Check);
371    }
372
373    #[test]
374    fn diagnostics_level_deserialize_check() {
375        let p: DiagnosticsParams = serde_json::from_str(r#"{"level":"check"}"#).unwrap();
376        assert_eq!(p.level, DiagnosticsLevel::Check);
377    }
378
379    #[test]
380    fn diagnostics_level_deserialize_clippy() {
381        let p: DiagnosticsParams = serde_json::from_str(r#"{"level":"clippy"}"#).unwrap();
382        assert_eq!(p.level, DiagnosticsLevel::Clippy);
383    }
384
385    #[test]
386    fn diagnostics_params_path_optional() {
387        let p: DiagnosticsParams = serde_json::from_str(r#"{}"#).unwrap();
388        assert!(p.path.is_none());
389        assert_eq!(p.level, DiagnosticsLevel::Check);
390    }
391
392    // CR-14: verify that level=clippy maps to "clippy" subcommand string
393    #[test]
394    fn diagnostics_clippy_subcmd_string() {
395        let subcmd = match DiagnosticsLevel::Clippy {
396            DiagnosticsLevel::Check => "check",
397            DiagnosticsLevel::Clippy => "clippy",
398        };
399        assert_eq!(subcmd, "clippy");
400    }
401
402    #[test]
403    fn diagnostics_check_subcmd_string() {
404        let subcmd = match DiagnosticsLevel::Check {
405            DiagnosticsLevel::Check => "check",
406            DiagnosticsLevel::Clippy => "clippy",
407        };
408        assert_eq!(subcmd, "check");
409    }
410}