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
135/// Check unpushed sessions against server policies.
136///
137/// `project_root` — the git-resolved PRIMARY worktree root (from
138///   `paths::resolve_project_root`). Used to load config/credentials, locate
139///   `.tracevault/sessions/`, and resolve the server-registered repo name
140///   (the primary checkout's basename; a sibling worktree's own directory
141///   basename would not match the registered repo).
142/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used for
143///   git *state* (`HEAD`) so the reported `commit_sha` is the commit being
144///   pushed from the invoking worktree, not the primary's unrelated HEAD.
145pub async fn check_policies(
146    project_root: &Path,
147    cwd: &Path,
148) -> Result<(), Box<dyn std::error::Error>> {
149    let (server_url, token) = resolve_credentials(project_root);
150
151    let server_url = server_url
152        .ok_or("No server URL configured. Run `tracevault login --server-url=<url>` to set one.")?;
153
154    if token.is_none() {
155        return Err(
156            "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate."
157                .into(),
158        );
159    }
160
161    let org_slug = TracevaultConfig::load(project_root)
162        .and_then(|c| c.org_slug)
163        .ok_or("No org_slug in config. Run `tracevault init` first.")?;
164
165    let client = ApiClient::new(&server_url, token.as_deref());
166
167    // Resolve repo_id by name.
168    //
169    // Connectivity errors here (auth expired, server down, network
170    // unreachable) propagate so the pre-push hook exits non-zero — if a
171    // repo is opted into TraceVault, every push must be evaluated, full
172    // stop. Letting pushes slip when TV is unreachable would defeat the
173    // point of enforcement. We attach an actionable next step to each
174    // error so the user (or agent) knows the recovery command without
175    // guessing — see `connectivity_message` below.
176    let repo_name = git_repo_name(project_root);
177    let repos = client
178        .list_repos(&org_slug)
179        .await
180        .map_err(|e| connectivity_message(&e.to_string()))?;
181    let repo = repos.iter().find(|r| r.name == repo_name).ok_or_else(|| {
182        format!("Repo '{repo_name}' not found on server. Run `tracevault sync` first.")
183    })?;
184
185    // Collect session data from unpushed sessions
186    let sessions_dir = project_root.join(".tracevault").join("sessions");
187    let mut sessions = Vec::new();
188
189    if sessions_dir.exists() {
190        for entry in fs::read_dir(&sessions_dir)? {
191            let entry = entry?;
192            if !entry.file_type()?.is_dir() {
193                continue;
194            }
195            let session_dir = entry.path();
196            let pushed_marker = session_dir.join(".pushed");
197            if pushed_marker.exists() {
198                continue;
199            }
200            if let Some(data) = collect_session_data(&session_dir) {
201                sessions.push(data);
202            }
203        }
204    }
205
206    if sessions.is_empty() {
207        println!("No unpushed sessions to check.");
208        return Ok(());
209    }
210
211    println!("Checking {} session(s) against policies...", sessions.len());
212
213    // HEAD comes from the invoking worktree (`cwd`), not the primary root —
214    // the commit being pushed lives on the current worktree's branch.
215    let commit_sha = git_head_sha(cwd);
216    let result = client
217        .check_policies(
218            &org_slug,
219            &repo.id,
220            CheckPoliciesRequest {
221                sessions,
222                commit_sha,
223            },
224        )
225        .await
226        .map_err(|e| connectivity_message(&e.to_string()))?;
227
228    // Print results
229    for r in &result.results {
230        let icon = match r.result.as_str() {
231            "pass" => "\x1b[32m✓\x1b[0m",                             // green
232            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
233            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
234            _ => " ",
235        };
236        println!(
237            "  {} [{}] {} — {}",
238            icon, r.severity, r.rule_name, r.details
239        );
240    }
241
242    if result.blocked {
243        eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
244        std::process::exit(1);
245    } else if result.passed {
246        println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
247    } else {
248        println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
249    }
250
251    Ok(())
252}
253
254/// Wrap an opaque API-client error string with the most useful next step.
255/// Today the api_client surfaces errors as `"Stream failed (401 ...)"` or
256/// `"Server returned 500 Internal Server Error: ..."` strings; we sniff for
257/// the common shapes and surface a one-line action.
258fn connectivity_message(raw: &str) -> String {
259    let lower = raw.to_ascii_lowercase();
260
261    // 401 — token rejected. An expired session is the most common cause of
262    // a surprise blocked push, so point straight at the refresh command.
263    if lower.contains("401") || lower.contains("unauthorized") {
264        return with_action(
265            raw,
266            "Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh.",
267        );
268    }
269    // 403 — authenticated but not allowed. Re-login won't help; this is an
270    // org-membership problem.
271    if lower.contains("403") || lower.contains("forbidden") {
272        return with_action(
273            raw,
274            "Your token lacks access to this repo's policies. Check your org membership and rerun `tracevault login`.",
275        );
276    }
277    // 5xx — server-side fault. Checked before the transport keywords below
278    // so a `504 Gateway Timeout` reads as a server issue, not a local one.
279    if is_server_error(&lower) {
280        return with_action(
281            raw,
282            "TraceVault server returned an error. The team has likely been paged; retry shortly.",
283        );
284    }
285    // Transport-level failure with no HTTP status — DNS, refused, timeout.
286    // ("connect" also covers "connection refused"/"connection reset".)
287    if lower.contains("dns")
288        || lower.contains("connect")
289        || lower.contains("timed out")
290        || lower.contains("timeout")
291    {
292        return with_action(
293            raw,
294            "Could not reach the TraceVault server. Check network and `server_url` in .tracevault/config.toml.",
295        );
296    }
297    // Unrecognized — surface the raw error verbatim, no invented advice.
298    format!("Policy check could not run: {raw}.")
299}
300
301/// Format the standard "could not run" line with an actionable next step.
302fn with_action(raw: &str, action: &str) -> String {
303    format!("Policy check could not run: {raw}.\n  → {action}")
304}
305
306/// Heuristic for a 5xx server-side failure. Matches the textual status
307/// (`internal`, `server error`) and the concrete 5xx codes so a bare
308/// `503 Service Unavailable` — which carries neither phrase — is still
309/// recognized.
310fn is_server_error(lower: &str) -> bool {
311    lower.contains("internal")
312        || lower.contains("server error")
313        || ["500", "501", "502", "503", "504"]
314            .iter()
315            .any(|code| lower.contains(code))
316}
317
318#[cfg(test)]
319mod tests {
320    use super::connectivity_message;
321
322    #[test]
323    fn connectivity_message_suggests_login_on_401() {
324        let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
325        assert!(
326            m.contains("tracevault login"),
327            "401 errors must surface the login hint; got: {m}"
328        );
329    }
330
331    #[test]
332    fn connectivity_message_suggests_login_on_unauthorized_text() {
333        let m = connectivity_message("Server returned: unauthorized request");
334        assert!(m.contains("tracevault login"));
335    }
336
337    #[test]
338    fn connectivity_message_suggests_network_check_on_dns_error() {
339        let m = connectivity_message("error sending request for url: dns error");
340        assert!(
341            m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
342            "DNS errors must surface a network hint; got: {m}"
343        );
344    }
345
346    #[test]
347    fn connectivity_message_suggests_network_check_on_connection_refused() {
348        let m = connectivity_message("connection refused");
349        assert!(m.to_lowercase().contains("network"));
350    }
351
352    #[test]
353    fn connectivity_message_falls_back_when_unrecognized() {
354        let m = connectivity_message("some weird new error shape we have not seen before");
355        // No suggestion — but the raw error must still be in the message so
356        // the user can debug.
357        assert!(m.contains("some weird new error shape"));
358        assert!(!m.contains("→")); // no action arrow
359    }
360
361    #[test]
362    fn connectivity_message_does_not_collide_on_403() {
363        let m = connectivity_message("403 Forbidden");
364        // 403 should suggest org membership, NOT a re-login.
365        assert!(
366            m.to_lowercase().contains("membership"),
367            "403 should mention membership; got: {m}"
368        );
369    }
370
371    #[test]
372    fn connectivity_message_flags_500_as_server_error() {
373        let m = connectivity_message("Server returned 500 Internal Server Error: oops");
374        assert!(
375            m.to_lowercase().contains("server returned an error"),
376            "500 should surface the server-error hint; got: {m}"
377        );
378    }
379
380    #[test]
381    fn connectivity_message_flags_503_without_internal_text() {
382        // `503 Service Unavailable` carries neither "internal" nor
383        // "server error" — the bare code must still be recognized.
384        let m = connectivity_message("Server returned 503 Service Unavailable: ");
385        assert!(
386            m.to_lowercase().contains("server returned an error"),
387            "503 should surface the server-error hint; got: {m}"
388        );
389    }
390
391    #[test]
392    fn connectivity_message_treats_504_as_server_not_network() {
393        // A gateway timeout is a server-side fault even though it contains
394        // the word "timeout"; it must not be misreported as a local network
395        // problem.
396        let m = connectivity_message("Server returned 504 Gateway Timeout: ");
397        assert!(
398            m.to_lowercase().contains("server returned an error"),
399            "504 should be treated as a server error; got: {m}"
400        );
401    }
402}