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 = match server_url {
139        Some(url) => url,
140        None => {
141            return Err("No server URL configured. Run 'tracevault login' first.".into());
142        }
143    };
144
145    if token.is_none() {
146        return Err("Not logged in. Run 'tracevault login' to check policies.".into());
147    }
148
149    let org_slug = TracevaultConfig::load(project_root)
150        .and_then(|c| c.org_slug)
151        .ok_or("No org_slug in config. Run 'tracevault init' first.")?;
152
153    let client = ApiClient::new(&server_url, token.as_deref());
154
155    // Resolve repo_id by name
156    let repo_name = git_repo_name(project_root);
157    let repos = client.list_repos(&org_slug).await?;
158    let repo = repos.iter().find(|r| r.name == repo_name).ok_or_else(|| {
159        format!(
160            "Repo '{}' not found on server. Run 'tracevault sync' first.",
161            repo_name
162        )
163    })?;
164
165    // Collect session data from unpushed sessions
166    let sessions_dir = project_root.join(".tracevault").join("sessions");
167    let mut sessions = Vec::new();
168
169    if sessions_dir.exists() {
170        for entry in fs::read_dir(&sessions_dir)? {
171            let entry = entry?;
172            if !entry.file_type()?.is_dir() {
173                continue;
174            }
175            let session_dir = entry.path();
176            let pushed_marker = session_dir.join(".pushed");
177            if pushed_marker.exists() {
178                continue;
179            }
180            if let Some(data) = collect_session_data(&session_dir) {
181                sessions.push(data);
182            }
183        }
184    }
185
186    if sessions.is_empty() {
187        println!("No unpushed sessions to check.");
188        return Ok(());
189    }
190
191    println!("Checking {} session(s) against policies...", sessions.len());
192
193    let commit_sha = git_head_sha(project_root);
194    let result = client
195        .check_policies(
196            &org_slug,
197            &repo.id,
198            CheckPoliciesRequest {
199                sessions,
200                commit_sha,
201            },
202        )
203        .await?;
204
205    // Print results
206    for r in &result.results {
207        let icon = match r.result.as_str() {
208            "pass" => "\x1b[32m✓\x1b[0m",                             // green
209            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
210            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
211            _ => " ",
212        };
213        println!(
214            "  {} [{}] {} — {}",
215            icon, r.severity, r.rule_name, r.details
216        );
217    }
218
219    if result.blocked {
220        eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
221        std::process::exit(1);
222    } else if result.passed {
223        println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
224    } else {
225        println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
226    }
227
228    Ok(())
229}