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/// Select the session directories that belong to the current worktree.
136/// Keeps sessions whose `origin` marker == `worktree_top` OR that have no
137/// marker (legacy/unmarked — kept conservatively). Marked sessions from other
138/// worktrees are excluded.
139///
140/// Safety rail: if filtering would drop EVERY session while sessions exist,
141/// return all of them with `fell_back = true` — never under-enforce by sending
142/// zero sessions for a push that has unpushed work.
143///
144/// `pub` so the integration test in Task 7 can drive it.
145pub fn select_worktree_sessions(
146    session_dirs: Vec<std::path::PathBuf>,
147    worktree_top: &str,
148) -> (Vec<std::path::PathBuf>, bool) {
149    let belongs = |dir: &std::path::Path| -> bool {
150        match fs::read_to_string(dir.join("origin")) {
151            Ok(s) => s.trim() == worktree_top, // marked: keep only if mine
152            // Only a genuinely-absent marker counts as unmarked/legacy (keep).
153            Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
154            // Marker present but unreadable (permissions/IO): we can't prove it's
155            // ours, so exclude it rather than risk cross-worktree interference.
156            // The safety rail below still prevents under-enforcement if this
157            // drops everything.
158            Err(_) => false,
159        }
160    };
161    let filtered: Vec<_> = session_dirs
162        .iter()
163        .filter(|d| belongs(d))
164        .cloned()
165        .collect();
166    if filtered.is_empty() && !session_dirs.is_empty() {
167        (session_dirs, true)
168    } else {
169        (filtered, false)
170    }
171}
172
173/// Check unpushed sessions against server policies.
174///
175/// `project_root` — the git-resolved PRIMARY worktree root (from
176///   `paths::resolve_project_root`). Used to load config/credentials, locate
177///   `.tracevault/sessions/`, and resolve the server-registered repo name
178///   (the primary checkout's basename; a sibling worktree's own directory
179///   basename would not match the registered repo).
180/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used for
181///   git *state* (`HEAD`) so the reported `commit_sha` is the commit being
182///   pushed from the invoking worktree, not the primary's unrelated HEAD.
183pub async fn check_policies(
184    project_root: &Path,
185    cwd: &Path,
186) -> Result<(), Box<dyn std::error::Error>> {
187    let (server_url, token) = resolve_credentials(project_root);
188
189    let server_url = server_url
190        .ok_or("No server URL configured. Run `tracevault login --server-url=<url>` to set one.")?;
191
192    if token.is_none() {
193        return Err(
194            "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate."
195                .into(),
196        );
197    }
198
199    let org_slug = TracevaultConfig::load(project_root)
200        .and_then(|c| c.org_slug)
201        .ok_or("No org_slug in config. Run `tracevault init` first.")?;
202
203    let client = ApiClient::new(&server_url, token.as_deref());
204
205    // Resolve repo_id by name.
206    //
207    // Connectivity errors here (auth expired, server down, network
208    // unreachable) propagate so the pre-push hook exits non-zero — if a
209    // repo is opted into TraceVault, every push must be evaluated, full
210    // stop. Letting pushes slip when TV is unreachable would defeat the
211    // point of enforcement. We attach an actionable next step to each
212    // error so the user (or agent) knows the recovery command without
213    // guessing — see `connectivity_message` below.
214    let repo_name = git_repo_name(project_root);
215    let repos = client
216        .list_repos(&org_slug)
217        .await
218        .map_err(|e| connectivity_message(&e.to_string()))?;
219    let repo = repos.iter().find(|r| r.name == repo_name).ok_or_else(|| {
220        format!("Repo '{repo_name}' not found on server. Run `tracevault sync` first.")
221    })?;
222
223    // Collect unpushed session dirs from the shared primary .tracevault/.
224    let sessions_dir = project_root.join(".tracevault").join("sessions");
225    let mut unpushed_dirs: Vec<std::path::PathBuf> = Vec::new();
226    if sessions_dir.exists() {
227        for entry in fs::read_dir(&sessions_dir)? {
228            let entry = entry?;
229            if !entry.file_type()?.is_dir() {
230                continue;
231            }
232            let session_dir = entry.path();
233            if session_dir.join(".pushed").exists() {
234                continue;
235            }
236            unpushed_dirs.push(session_dir);
237        }
238    }
239
240    // Filter to the worktree that is actually pushing, so a push is not
241    // evaluated against sessions belonging to other worktrees.
242    let worktree_top = crate::paths::worktree_toplevel(cwd);
243    let (selected_dirs, fell_back) = select_worktree_sessions(unpushed_dirs, &worktree_top);
244    if fell_back {
245        eprintln!(
246            "Warning: no unpushed session matched this worktree by origin marker — \
247             checking all unpushed sessions to avoid skipping policy enforcement."
248        );
249    }
250
251    let mut sessions = Vec::new();
252    for session_dir in &selected_dirs {
253        if let Some(data) = collect_session_data(session_dir) {
254            sessions.push(data);
255        }
256    }
257
258    if sessions.is_empty() {
259        println!("No unpushed sessions to check.");
260        return Ok(());
261    }
262
263    println!("Checking {} session(s) against policies...", sessions.len());
264
265    // HEAD comes from the invoking worktree (`cwd`), not the primary root —
266    // the commit being pushed lives on the current worktree's branch.
267    let commit_sha = git_head_sha(cwd);
268    let result = client
269        .check_policies(
270            &org_slug,
271            &repo.id,
272            CheckPoliciesRequest {
273                sessions,
274                commit_sha,
275            },
276        )
277        .await
278        .map_err(|e| connectivity_message(&e.to_string()))?;
279
280    // Print results
281    for r in &result.results {
282        let icon = match r.result.as_str() {
283            "pass" => "\x1b[32m✓\x1b[0m",                             // green
284            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
285            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
286            _ => " ",
287        };
288        println!(
289            "  {} [{}] {} — {}",
290            icon, r.severity, r.rule_name, r.details
291        );
292    }
293
294    if result.blocked {
295        eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
296        std::process::exit(1);
297    } else if result.passed {
298        println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
299    } else {
300        println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
301    }
302
303    Ok(())
304}
305
306/// Wrap an opaque API-client error string with the most useful next step.
307/// Today the api_client surfaces errors as `"Stream failed (401 ...)"` or
308/// `"Server returned 500 Internal Server Error: ..."` strings; we sniff for
309/// the common shapes and surface a one-line action.
310fn connectivity_message(raw: &str) -> String {
311    let lower = raw.to_ascii_lowercase();
312
313    // 401 — token rejected. An expired session is the most common cause of
314    // a surprise blocked push, so point straight at the refresh command.
315    if lower.contains("401") || lower.contains("unauthorized") {
316        return with_action(
317            raw,
318            "Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh.",
319        );
320    }
321    // 403 — authenticated but not allowed. Re-login won't help; this is an
322    // org-membership problem.
323    if lower.contains("403") || lower.contains("forbidden") {
324        return with_action(
325            raw,
326            "Your token lacks access to this repo's policies. Check your org membership and rerun `tracevault login`.",
327        );
328    }
329    // 5xx — server-side fault. Checked before the transport keywords below
330    // so a `504 Gateway Timeout` reads as a server issue, not a local one.
331    if is_server_error(&lower) {
332        return with_action(
333            raw,
334            "TraceVault server returned an error. The team has likely been paged; retry shortly.",
335        );
336    }
337    // Transport-level failure with no HTTP status — DNS, refused, timeout.
338    // ("connect" also covers "connection refused"/"connection reset".)
339    if lower.contains("dns")
340        || lower.contains("connect")
341        || lower.contains("timed out")
342        || lower.contains("timeout")
343    {
344        return with_action(
345            raw,
346            "Could not reach the TraceVault server. Check network and `server_url` in .tracevault/config.toml.",
347        );
348    }
349    // Unrecognized — surface the raw error verbatim, no invented advice.
350    format!("Policy check could not run: {raw}.")
351}
352
353/// Format the standard "could not run" line with an actionable next step.
354fn with_action(raw: &str, action: &str) -> String {
355    format!("Policy check could not run: {raw}.\n  → {action}")
356}
357
358/// Heuristic for a 5xx server-side failure. Matches the textual status
359/// (`internal`, `server error`) and the concrete 5xx codes so a bare
360/// `503 Service Unavailable` — which carries neither phrase — is still
361/// recognized.
362fn is_server_error(lower: &str) -> bool {
363    lower.contains("internal")
364        || lower.contains("server error")
365        || ["500", "501", "502", "503", "504"]
366            .iter()
367            .any(|code| lower.contains(code))
368}
369
370#[cfg(test)]
371mod worktree_tests {
372    use super::select_worktree_sessions;
373    use std::path::PathBuf;
374
375    fn seed(tmp: &std::path::Path, id: &str, origin: Option<&str>) -> PathBuf {
376        let d = tmp.join(id);
377        std::fs::create_dir_all(&d).unwrap();
378        if let Some(o) = origin {
379            std::fs::write(d.join("origin"), o).unwrap();
380        }
381        d
382    }
383
384    #[test]
385    fn keeps_current_worktree_and_unmarked_excludes_other() {
386        let tmp = tempfile::tempdir().unwrap();
387        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
388        let other = seed(tmp.path(), "other", Some("/wt/there"));
389        let legacy = seed(tmp.path(), "legacy", None);
390
391        let (kept, fell_back) = select_worktree_sessions(
392            vec![mine.clone(), other.clone(), legacy.clone()],
393            "/wt/here",
394        );
395
396        assert!(!fell_back);
397        assert!(kept.contains(&mine), "current worktree session kept");
398        assert!(
399            kept.contains(&legacy),
400            "unmarked legacy session kept (conservative)"
401        );
402        assert!(
403            !kept.contains(&other),
404            "other worktree's marked session excluded"
405        );
406    }
407
408    #[test]
409    fn excludes_session_with_unreadable_marker() {
410        let tmp = tempfile::tempdir().unwrap();
411        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
412        // A present-but-unreadable marker: make `origin` a directory so
413        // read_to_string fails with a non-NotFound error.
414        let bad = tmp.path().join("bad");
415        std::fs::create_dir_all(bad.join("origin")).unwrap();
416
417        let (kept, fell_back) =
418            select_worktree_sessions(vec![mine.clone(), bad.clone()], "/wt/here");
419
420        assert!(!fell_back);
421        assert!(kept.contains(&mine), "current worktree session kept");
422        assert!(
423            !kept.contains(&bad),
424            "session with a present-but-unreadable marker must be excluded, not kept as legacy"
425        );
426    }
427
428    #[test]
429    fn falls_back_to_all_when_nothing_matches() {
430        let tmp = tempfile::tempdir().unwrap();
431        let a = seed(tmp.path(), "a", Some("/wt/there"));
432        let b = seed(tmp.path(), "b", Some("/wt/elsewhere"));
433
434        let (kept, fell_back) = select_worktree_sessions(vec![a.clone(), b.clone()], "/wt/here");
435
436        assert!(fell_back, "must flag fallback when filter matches nothing");
437        assert_eq!(
438            kept.len(),
439            2,
440            "never under-enforce: send all rather than zero"
441        );
442    }
443}
444
445#[cfg(test)]
446mod tests {
447    use super::connectivity_message;
448
449    #[test]
450    fn connectivity_message_suggests_login_on_401() {
451        let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
452        assert!(
453            m.contains("tracevault login"),
454            "401 errors must surface the login hint; got: {m}"
455        );
456    }
457
458    #[test]
459    fn connectivity_message_suggests_login_on_unauthorized_text() {
460        let m = connectivity_message("Server returned: unauthorized request");
461        assert!(m.contains("tracevault login"));
462    }
463
464    #[test]
465    fn connectivity_message_suggests_network_check_on_dns_error() {
466        let m = connectivity_message("error sending request for url: dns error");
467        assert!(
468            m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
469            "DNS errors must surface a network hint; got: {m}"
470        );
471    }
472
473    #[test]
474    fn connectivity_message_suggests_network_check_on_connection_refused() {
475        let m = connectivity_message("connection refused");
476        assert!(m.to_lowercase().contains("network"));
477    }
478
479    #[test]
480    fn connectivity_message_falls_back_when_unrecognized() {
481        let m = connectivity_message("some weird new error shape we have not seen before");
482        // No suggestion — but the raw error must still be in the message so
483        // the user can debug.
484        assert!(m.contains("some weird new error shape"));
485        assert!(!m.contains("→")); // no action arrow
486    }
487
488    #[test]
489    fn connectivity_message_does_not_collide_on_403() {
490        let m = connectivity_message("403 Forbidden");
491        // 403 should suggest org membership, NOT a re-login.
492        assert!(
493            m.to_lowercase().contains("membership"),
494            "403 should mention membership; got: {m}"
495        );
496    }
497
498    #[test]
499    fn connectivity_message_flags_500_as_server_error() {
500        let m = connectivity_message("Server returned 500 Internal Server Error: oops");
501        assert!(
502            m.to_lowercase().contains("server returned an error"),
503            "500 should surface the server-error hint; got: {m}"
504        );
505    }
506
507    #[test]
508    fn connectivity_message_flags_503_without_internal_text() {
509        // `503 Service Unavailable` carries neither "internal" nor
510        // "server error" — the bare code must still be recognized.
511        let m = connectivity_message("Server returned 503 Service Unavailable: ");
512        assert!(
513            m.to_lowercase().contains("server returned an error"),
514            "503 should surface the server-error hint; got: {m}"
515        );
516    }
517
518    #[test]
519    fn connectivity_message_treats_504_as_server_not_network() {
520        // A gateway timeout is a server-side fault even though it contains
521        // the word "timeout"; it must not be misreported as a local network
522        // problem.
523        let m = connectivity_message("Server returned 504 Gateway Timeout: ");
524        assert!(
525            m.to_lowercase().contains("server returned an error"),
526            "504 should be treated as a server error; got: {m}"
527        );
528    }
529}