Skip to main content

tracevault_cli/commands/
check.rs

1use crate::api_client::{resolve_credentials, ApiClient, CheckPoliciesRequest, SessionCheckData};
2use crate::config::TracevaultConfig;
3use std::collections::HashSet;
4use std::fs;
5use std::path::Path;
6use std::process::Command;
7
8fn git_repo_name(project_root: &Path) -> String {
9    Command::new("git")
10        .args(["rev-parse", "--show-toplevel"])
11        .current_dir(project_root)
12        .output()
13        .ok()
14        .filter(|o| o.status.success())
15        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
16        .as_deref()
17        .and_then(|p| p.rsplit('/').next())
18        .map(String::from)
19        .unwrap_or_else(|| "unknown".into())
20}
21
22fn git_head_sha(project_root: &Path) -> Option<String> {
23    let out = Command::new("git")
24        .args(["rev-parse", "HEAD"])
25        .current_dir(project_root)
26        .output()
27        .ok()?;
28    if !out.status.success() {
29        return None;
30    }
31    let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
32    if sha.is_empty() {
33        None
34    } else {
35        Some(sha)
36    }
37}
38
39fn collect_session_data(session_dir: &Path) -> Option<SessionCheckData> {
40    let session_id = session_dir.file_name()?.to_string_lossy().to_string();
41
42    // Read events.jsonl for files_modified
43    let events_path = session_dir.join("events.jsonl");
44    let mut files_modified = Vec::new();
45    let mut files_seen = HashSet::new();
46
47    if events_path.exists() {
48        if let Ok(content) = fs::read_to_string(&events_path) {
49            for line in content.lines() {
50                let event: serde_json::Value = match serde_json::from_str(line) {
51                    Ok(v) => v,
52                    Err(_) => continue,
53                };
54                if let Some(path) = event
55                    .get("tool_input")
56                    .and_then(|v| v.get("file_path"))
57                    .and_then(|v| v.as_str())
58                {
59                    if files_seen.insert(path.to_string()) {
60                        files_modified.push(path.to_string());
61                    }
62                }
63            }
64        }
65    }
66
67    // Read transcript for tool_calls
68    let meta_path = session_dir.join("metadata.json");
69    let metadata: Option<serde_json::Value> = meta_path
70        .exists()
71        .then(|| fs::read_to_string(&meta_path).ok())
72        .flatten()
73        .and_then(|c| serde_json::from_str(&c).ok());
74
75    let transcript_path = metadata
76        .as_ref()
77        .and_then(|m| m.get("transcript_path"))
78        .and_then(|v| v.as_str())
79        .map(|s| s.to_string());
80
81    let mut tool_calls_map: std::collections::HashMap<String, i32> =
82        std::collections::HashMap::new();
83    let mut total_tool_calls: i32 = 0;
84
85    if let Some(path) = &transcript_path {
86        if let Ok(content) = fs::read_to_string(path) {
87            for line in content.lines() {
88                let entry: serde_json::Value = match serde_json::from_str(line) {
89                    Ok(v) => v,
90                    Err(_) => continue,
91                };
92
93                if entry.get("type").and_then(|v| v.as_str()) == Some("assistant") {
94                    if let Some(content_arr) = entry
95                        .get("message")
96                        .and_then(|m| m.get("content"))
97                        .and_then(|c| c.as_array())
98                    {
99                        for block in content_arr {
100                            if block.get("type").and_then(|v| v.as_str()) == Some("tool_use") {
101                                if let Some(name) = block.get("name").and_then(|v| v.as_str()) {
102                                    *tool_calls_map.entry(name.to_string()).or_insert(0) += 1;
103                                    total_tool_calls += 1;
104                                }
105                            }
106                        }
107                    }
108                }
109            }
110        }
111    }
112
113    let tool_calls = if tool_calls_map.is_empty() {
114        None
115    } else {
116        serde_json::to_value(&tool_calls_map).ok()
117    };
118
119    Some(SessionCheckData {
120        session_id,
121        tool_calls,
122        files_modified: if files_modified.is_empty() {
123            None
124        } else {
125            Some(files_modified)
126        },
127        total_tool_calls: if total_tool_calls > 0 {
128            Some(total_tool_calls)
129        } else {
130            None
131        },
132    })
133}
134
135pub async fn check_policies(project_root: &Path) -> Result<(), Box<dyn std::error::Error>> {
136    let (server_url, token) = resolve_credentials(project_root);
137
138    let server_url = server_url
139        .ok_or("No server URL configured. Run `tracevault login --server-url=<url>` to set one.")?;
140
141    if token.is_none() {
142        return Err(
143            "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate."
144                .into(),
145        );
146    }
147
148    let org_slug = TracevaultConfig::load(project_root)
149        .and_then(|c| c.org_slug)
150        .ok_or("No org_slug in config. Run `tracevault init` first.")?;
151
152    let client = ApiClient::new(&server_url, token.as_deref());
153
154    // Resolve repo_id by name.
155    //
156    // Connectivity errors here (auth expired, server down, network
157    // unreachable) propagate so the pre-push hook exits non-zero — if a
158    // repo is opted into TraceVault, every push must be evaluated, full
159    // stop. Letting pushes slip when TV is unreachable would defeat the
160    // point of enforcement. We attach an actionable next step to each
161    // error so the user (or agent) knows the recovery command without
162    // guessing — see `connectivity_message` below.
163    let repo_name = git_repo_name(project_root);
164    let repos = client
165        .list_repos(&org_slug)
166        .await
167        .map_err(|e| connectivity_message(&e.to_string()))?;
168    let repo = repos.iter().find(|r| r.name == repo_name).ok_or_else(|| {
169        format!("Repo '{repo_name}' not found on server. Run `tracevault sync` first.")
170    })?;
171
172    // Collect session data from unpushed sessions
173    let sessions_dir = project_root.join(".tracevault").join("sessions");
174    let mut sessions = Vec::new();
175
176    if sessions_dir.exists() {
177        for entry in fs::read_dir(&sessions_dir)? {
178            let entry = entry?;
179            if !entry.file_type()?.is_dir() {
180                continue;
181            }
182            let session_dir = entry.path();
183            let pushed_marker = session_dir.join(".pushed");
184            if pushed_marker.exists() {
185                continue;
186            }
187            if let Some(data) = collect_session_data(&session_dir) {
188                sessions.push(data);
189            }
190        }
191    }
192
193    if sessions.is_empty() {
194        println!("No unpushed sessions to check.");
195        return Ok(());
196    }
197
198    println!("Checking {} session(s) against policies...", sessions.len());
199
200    let commit_sha = git_head_sha(project_root);
201    let result = client
202        .check_policies(
203            &org_slug,
204            &repo.id,
205            CheckPoliciesRequest {
206                sessions,
207                commit_sha,
208            },
209        )
210        .await
211        .map_err(|e| connectivity_message(&e.to_string()))?;
212
213    // Print results
214    for r in &result.results {
215        let icon = match r.result.as_str() {
216            "pass" => "\x1b[32m✓\x1b[0m",                             // green
217            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
218            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
219            _ => " ",
220        };
221        println!(
222            "  {} [{}] {} — {}",
223            icon, r.severity, r.rule_name, r.details
224        );
225    }
226
227    if result.blocked {
228        eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
229        std::process::exit(1);
230    } else if result.passed {
231        println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
232    } else {
233        println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
234    }
235
236    Ok(())
237}
238
239/// Wrap an opaque API-client error string with the most useful next step.
240/// Today the api_client surfaces errors as `"Stream failed (401 ...)"` or
241/// `"Server returned 500 Internal Server Error: ..."` strings; we sniff for
242/// the common shapes and surface a one-line action.
243fn connectivity_message(raw: &str) -> String {
244    let lower = raw.to_ascii_lowercase();
245
246    // 401 — token rejected. An expired session is the most common cause of
247    // a surprise blocked push, so point straight at the refresh command.
248    if lower.contains("401") || lower.contains("unauthorized") {
249        return with_action(
250            raw,
251            "Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh.",
252        );
253    }
254    // 403 — authenticated but not allowed. Re-login won't help; this is an
255    // org-membership problem.
256    if lower.contains("403") || lower.contains("forbidden") {
257        return with_action(
258            raw,
259            "Your token lacks access to this repo's policies. Check your org membership and rerun `tracevault login`.",
260        );
261    }
262    // 5xx — server-side fault. Checked before the transport keywords below
263    // so a `504 Gateway Timeout` reads as a server issue, not a local one.
264    if is_server_error(&lower) {
265        return with_action(
266            raw,
267            "TraceVault server returned an error. The team has likely been paged; retry shortly.",
268        );
269    }
270    // Transport-level failure with no HTTP status — DNS, refused, timeout.
271    // ("connect" also covers "connection refused"/"connection reset".)
272    if lower.contains("dns")
273        || lower.contains("connect")
274        || lower.contains("timed out")
275        || lower.contains("timeout")
276    {
277        return with_action(
278            raw,
279            "Could not reach the TraceVault server. Check network and `server_url` in .tracevault/config.toml.",
280        );
281    }
282    // Unrecognized — surface the raw error verbatim, no invented advice.
283    format!("Policy check could not run: {raw}.")
284}
285
286/// Format the standard "could not run" line with an actionable next step.
287fn with_action(raw: &str, action: &str) -> String {
288    format!("Policy check could not run: {raw}.\n  → {action}")
289}
290
291/// Heuristic for a 5xx server-side failure. Matches the textual status
292/// (`internal`, `server error`) and the concrete 5xx codes so a bare
293/// `503 Service Unavailable` — which carries neither phrase — is still
294/// recognized.
295fn is_server_error(lower: &str) -> bool {
296    lower.contains("internal")
297        || lower.contains("server error")
298        || ["500", "501", "502", "503", "504"]
299            .iter()
300            .any(|code| lower.contains(code))
301}
302
303#[cfg(test)]
304mod tests {
305    use super::connectivity_message;
306
307    #[test]
308    fn connectivity_message_suggests_login_on_401() {
309        let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
310        assert!(
311            m.contains("tracevault login"),
312            "401 errors must surface the login hint; got: {m}"
313        );
314    }
315
316    #[test]
317    fn connectivity_message_suggests_login_on_unauthorized_text() {
318        let m = connectivity_message("Server returned: unauthorized request");
319        assert!(m.contains("tracevault login"));
320    }
321
322    #[test]
323    fn connectivity_message_suggests_network_check_on_dns_error() {
324        let m = connectivity_message("error sending request for url: dns error");
325        assert!(
326            m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
327            "DNS errors must surface a network hint; got: {m}"
328        );
329    }
330
331    #[test]
332    fn connectivity_message_suggests_network_check_on_connection_refused() {
333        let m = connectivity_message("connection refused");
334        assert!(m.to_lowercase().contains("network"));
335    }
336
337    #[test]
338    fn connectivity_message_falls_back_when_unrecognized() {
339        let m = connectivity_message("some weird new error shape we have not seen before");
340        // No suggestion — but the raw error must still be in the message so
341        // the user can debug.
342        assert!(m.contains("some weird new error shape"));
343        assert!(!m.contains("→")); // no action arrow
344    }
345
346    #[test]
347    fn connectivity_message_does_not_collide_on_403() {
348        let m = connectivity_message("403 Forbidden");
349        // 403 should suggest org membership, NOT a re-login.
350        assert!(
351            m.to_lowercase().contains("membership"),
352            "403 should mention membership; got: {m}"
353        );
354    }
355
356    #[test]
357    fn connectivity_message_flags_500_as_server_error() {
358        let m = connectivity_message("Server returned 500 Internal Server Error: oops");
359        assert!(
360            m.to_lowercase().contains("server returned an error"),
361            "500 should surface the server-error hint; got: {m}"
362        );
363    }
364
365    #[test]
366    fn connectivity_message_flags_503_without_internal_text() {
367        // `503 Service Unavailable` carries neither "internal" nor
368        // "server error" — the bare code must still be recognized.
369        let m = connectivity_message("Server returned 503 Service Unavailable: ");
370        assert!(
371            m.to_lowercase().contains("server returned an error"),
372            "503 should surface the server-error hint; got: {m}"
373        );
374    }
375
376    #[test]
377    fn connectivity_message_treats_504_as_server_not_network() {
378        // A gateway timeout is a server-side fault even though it contains
379        // the word "timeout"; it must not be misreported as a local network
380        // problem.
381        let m = connectivity_message("Server returned 504 Gateway Timeout: ");
382        assert!(
383            m.to_lowercase().contains("server returned an error"),
384            "504 should be treated as a server error; got: {m}"
385        );
386    }
387}