Skip to main content

tracevault_cli/commands/
check.rs

1use crate::api_client::{resolve_credentials, ApiClient, CheckPoliciesRequest, SessionCheckData};
2use crate::resolution::{resolve_repo_by_name, ResolveRepoByNameError};
3use std::collections::HashSet;
4use std::fs;
5use std::path::Path;
6use std::process::Command;
7
8fn git_head_sha(project_root: &Path) -> Option<String> {
9    let out = Command::new("git")
10        .args(["rev-parse", "HEAD"])
11        .current_dir(project_root)
12        .output()
13        .ok()?;
14    if !out.status.success() {
15        return None;
16    }
17    let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
18    if sha.is_empty() {
19        None
20    } else {
21        Some(sha)
22    }
23}
24
25fn collect_session_data(session_dir: &Path) -> Option<SessionCheckData> {
26    let session_id = session_dir.file_name()?.to_string_lossy().to_string();
27
28    // Read events.jsonl for files_modified
29    let events_path = session_dir.join("events.jsonl");
30    let mut files_modified = Vec::new();
31    let mut files_seen = HashSet::new();
32
33    if events_path.exists() {
34        if let Ok(content) = fs::read_to_string(&events_path) {
35            for line in content.lines() {
36                let event: serde_json::Value = match serde_json::from_str(line) {
37                    Ok(v) => v,
38                    Err(_) => continue,
39                };
40                if let Some(path) = event
41                    .get("tool_input")
42                    .and_then(|v| v.get("file_path"))
43                    .and_then(|v| v.as_str())
44                {
45                    if files_seen.insert(path.to_string()) {
46                        files_modified.push(path.to_string());
47                    }
48                }
49            }
50        }
51    }
52
53    // Read transcript for tool_calls
54    let meta_path = session_dir.join("metadata.json");
55    let metadata: Option<serde_json::Value> = meta_path
56        .exists()
57        .then(|| fs::read_to_string(&meta_path).ok())
58        .flatten()
59        .and_then(|c| serde_json::from_str(&c).ok());
60
61    let transcript_path = metadata
62        .as_ref()
63        .and_then(|m| m.get("transcript_path"))
64        .and_then(|v| v.as_str())
65        .map(|s| s.to_string());
66
67    let mut tool_calls_map: std::collections::HashMap<String, i32> =
68        std::collections::HashMap::new();
69    let mut total_tool_calls: i32 = 0;
70
71    if let Some(path) = &transcript_path {
72        if let Ok(content) = fs::read_to_string(path) {
73            for line in content.lines() {
74                let entry: serde_json::Value = match serde_json::from_str(line) {
75                    Ok(v) => v,
76                    Err(_) => continue,
77                };
78
79                if entry.get("type").and_then(|v| v.as_str()) == Some("assistant") {
80                    if let Some(content_arr) = entry
81                        .get("message")
82                        .and_then(|m| m.get("content"))
83                        .and_then(|c| c.as_array())
84                    {
85                        for block in content_arr {
86                            if block.get("type").and_then(|v| v.as_str()) == Some("tool_use") {
87                                if let Some(name) = block.get("name").and_then(|v| v.as_str()) {
88                                    *tool_calls_map.entry(name.to_string()).or_insert(0) += 1;
89                                    total_tool_calls += 1;
90                                }
91                            }
92                        }
93                    }
94                }
95            }
96        }
97    }
98
99    let tool_calls = if tool_calls_map.is_empty() {
100        None
101    } else {
102        serde_json::to_value(&tool_calls_map).ok()
103    };
104
105    Some(SessionCheckData {
106        session_id,
107        tool_calls,
108        files_modified: if files_modified.is_empty() {
109            None
110        } else {
111            Some(files_modified)
112        },
113        total_tool_calls: if total_tool_calls > 0 {
114            Some(total_tool_calls)
115        } else {
116            None
117        },
118    })
119}
120
121/// Select the session directories that belong to the current worktree.
122/// Keeps sessions whose `origin` marker == `worktree_top` OR that have no
123/// marker (legacy/unmarked — kept conservatively). Marked sessions from other
124/// worktrees are excluded.
125///
126/// Safety rail: if filtering would drop EVERY session while sessions exist,
127/// return all of them with `fell_back = true` — never under-enforce by sending
128/// zero sessions for a push that has unpushed work.
129///
130/// `pub` so the integration test in Task 7 can drive it.
131pub fn select_worktree_sessions(
132    session_dirs: Vec<std::path::PathBuf>,
133    worktree_top: &str,
134) -> (Vec<std::path::PathBuf>, bool) {
135    let belongs = |dir: &std::path::Path| -> bool {
136        match fs::read_to_string(dir.join("origin")) {
137            Ok(s) => s.trim() == worktree_top, // marked: keep only if mine
138            // Only a genuinely-absent marker counts as unmarked/legacy (keep).
139            Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
140            // Marker present but unreadable (permissions/IO): we can't prove it's
141            // ours, so exclude it rather than risk cross-worktree interference.
142            // The safety rail below still prevents under-enforcement if this
143            // drops everything.
144            Err(_) => false,
145        }
146    };
147    let filtered: Vec<_> = session_dirs
148        .iter()
149        .filter(|d| belongs(d))
150        .cloned()
151        .collect();
152    if filtered.is_empty() && !session_dirs.is_empty() {
153        (session_dirs, true)
154    } else {
155        (filtered, false)
156    }
157}
158
159/// Check unpushed sessions against server policies.
160///
161/// `project_root` — the git-resolved PRIMARY worktree root (from
162///   `paths::resolve_project_root`). Used to load config/credentials, locate
163///   `.tracevault/sessions/`, and resolve the server-registered repo name
164///   (the primary checkout's basename; a sibling worktree's own directory
165///   basename would not match the registered repo).
166/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used for
167///   git *state* (`HEAD`) so the reported `commit_sha` is the commit being
168///   pushed from the invoking worktree, not the primary's unrelated HEAD.
169pub async fn check_policies(
170    project_root: &Path,
171    cwd: &Path,
172) -> Result<(), Box<dyn std::error::Error>> {
173    let (server_url, token) = resolve_credentials(project_root);
174
175    let server_url = server_url
176        .ok_or("No server URL configured. Run `tracevault login --server-url=<url>` to set one.")?;
177
178    if token.is_none() {
179        return Err(
180            "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate."
181                .into(),
182        );
183    }
184
185    let client = ApiClient::new(&server_url, token.as_deref());
186
187    // Resolve repo_id by name.
188    //
189    // Connectivity errors here (auth expired, server down, network
190    // unreachable) propagate so the pre-push hook exits non-zero — if a
191    // repo is opted into TraceVault, every push must be evaluated, full
192    // stop. Letting pushes slip when TV is unreachable would defeat the
193    // point of enforcement. We attach an actionable next step to each
194    // error so the user (or agent) knows the recovery command without
195    // guessing — see `connectivity_message` below.
196    let repo = match resolve_repo_by_name(&client, project_root).await {
197        Ok(r) => r,
198        Err(ResolveRepoByNameError::ListFailed(e)) => {
199            return Err(connectivity_message(&e.to_string()).into());
200        }
201        Err(ResolveRepoByNameError::NotFound { repo_name }) => {
202            return Err(format!(
203                "Repo '{repo_name}' not found on server. Run `tracevault sync` first."
204            )
205            .into());
206        }
207    };
208
209    // Collect unpushed session dirs from the shared primary .tracevault/.
210    let sessions_dir = project_root.join(".tracevault").join("sessions");
211    let mut unpushed_dirs: Vec<std::path::PathBuf> = Vec::new();
212    if sessions_dir.exists() {
213        for entry in fs::read_dir(&sessions_dir)? {
214            let entry = entry?;
215            if !entry.file_type()?.is_dir() {
216                continue;
217            }
218            let session_dir = entry.path();
219            if session_dir.join(".pushed").exists() {
220                continue;
221            }
222            unpushed_dirs.push(session_dir);
223        }
224    }
225
226    // Filter to the worktree that is actually pushing, so a push is not
227    // evaluated against sessions belonging to other worktrees.
228    let worktree_top = crate::paths::worktree_toplevel(cwd);
229    let (selected_dirs, fell_back) = select_worktree_sessions(unpushed_dirs, &worktree_top);
230    if fell_back {
231        eprintln!(
232            "Warning: no unpushed session matched this worktree by origin marker — \
233             checking all unpushed sessions to avoid skipping policy enforcement."
234        );
235    }
236
237    let mut sessions = Vec::new();
238    for session_dir in &selected_dirs {
239        if let Some(data) = collect_session_data(session_dir) {
240            sessions.push(data);
241        }
242    }
243
244    if sessions.is_empty() {
245        println!("No unpushed sessions to check.");
246        return Ok(());
247    }
248
249    println!("Checking {} session(s) against policies...", sessions.len());
250
251    // HEAD comes from the invoking worktree (`cwd`), not the primary root —
252    // the commit being pushed lives on the current worktree's branch.
253    let commit_sha = git_head_sha(cwd);
254    let result = client
255        .check_policies(
256            &repo.id,
257            CheckPoliciesRequest {
258                sessions,
259                commit_sha,
260            },
261        )
262        .await
263        .map_err(|e| connectivity_message(&e.to_string()))?;
264
265    // Print results
266    for r in &result.results {
267        let icon = match r.result.as_str() {
268            "pass" => "\x1b[32m✓\x1b[0m",                             // green
269            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
270            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
271            _ => " ",
272        };
273        println!(
274            "  {} [{}] {} — {}",
275            icon, r.severity, r.rule_name, r.details
276        );
277    }
278
279    if result.blocked {
280        eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
281        std::process::exit(1);
282    } else if result.passed {
283        println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
284    } else {
285        println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
286    }
287
288    Ok(())
289}
290
291/// Wrap an opaque API-client error string with the most useful next step.
292/// Today the api_client surfaces errors as `"Stream failed (401 ...)"` or
293/// `"Server returned 500 Internal Server Error: ..."` strings; we sniff for
294/// the common shapes and surface a one-line action. A 404 gets its own
295/// version-mismatch hint rather than the generic fallback, since the calls
296/// that route through here have no legitimate domain reason to 404 — see
297/// the 404 branch below.
298fn connectivity_message(raw: &str) -> String {
299    let lower = raw.to_ascii_lowercase();
300
301    // 401 — token rejected. An expired session is the most common cause of
302    // a surprise blocked push, so point straight at the refresh command.
303    if lower.contains("401") || lower.contains("unauthorized") {
304        return with_action(
305            raw,
306            "Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh.",
307        );
308    }
309    // 403 — authenticated but not allowed. Re-login won't help; the token
310    // itself is not authorized for this repo's policies.
311    if lower.contains("403") || lower.contains("forbidden") {
312        return with_action(
313            raw,
314            "Your token is not authorized for this repo's policies. Confirm the token/service account has access and rerun `tracevault login`.",
315        );
316    }
317    // 404 — the route itself wasn't found. Neither call that reaches this
318    // function (`list_repos`, `check_policies`) has a legitimate domain
319    // reason to 404 — a missing repo is already turned into its own message
320    // by `resolve_repo_by_name`'s `NotFound` variant before it gets here —
321    // so a 404 this far down most plausibly means this server build doesn't
322    // recognize the route at all: a CLI/server version mismatch (e.g. this
323    // CLI shipped ahead of a server still on the old routes).
324    if lower.contains("404") {
325        return with_action(
326            raw,
327            "This server may not recognize this endpoint yet — this can happen when the CLI is newer than the server. Confirm the server has been upgraded, or downgrade the CLI to match it.",
328        );
329    }
330    // 5xx — server-side fault. Checked before the transport keywords below
331    // so a `504 Gateway Timeout` reads as a server issue, not a local one.
332    if is_server_error(&lower) {
333        return with_action(
334            raw,
335            "TraceVault server returned an error. The team has likely been paged; retry shortly.",
336        );
337    }
338    // Transport-level failure with no HTTP status — DNS, refused, timeout.
339    // ("connect" also covers "connection refused"/"connection reset".)
340    if lower.contains("dns")
341        || lower.contains("connect")
342        || lower.contains("timed out")
343        || lower.contains("timeout")
344    {
345        return with_action(
346            raw,
347            "Could not reach the TraceVault server. Check network and `server_url` in .tracevault/config.toml.",
348        );
349    }
350    // Unrecognized — surface the raw error verbatim, no invented advice.
351    format!("Policy check could not run: {raw}.")
352}
353
354/// Format the standard "could not run" line with an actionable next step.
355fn with_action(raw: &str, action: &str) -> String {
356    format!("Policy check could not run: {raw}.\n  → {action}")
357}
358
359/// Heuristic for a 5xx server-side failure. Matches the textual status
360/// (`internal`, `server error`) and the concrete 5xx codes so a bare
361/// `503 Service Unavailable` — which carries neither phrase — is still
362/// recognized.
363fn is_server_error(lower: &str) -> bool {
364    lower.contains("internal")
365        || lower.contains("server error")
366        || ["500", "501", "502", "503", "504"]
367            .iter()
368            .any(|code| lower.contains(code))
369}
370
371#[cfg(test)]
372mod worktree_tests {
373    use super::select_worktree_sessions;
374    use std::path::PathBuf;
375
376    fn seed(tmp: &std::path::Path, id: &str, origin: Option<&str>) -> PathBuf {
377        let d = tmp.join(id);
378        std::fs::create_dir_all(&d).unwrap();
379        if let Some(o) = origin {
380            std::fs::write(d.join("origin"), o).unwrap();
381        }
382        d
383    }
384
385    #[test]
386    fn keeps_current_worktree_and_unmarked_excludes_other() {
387        let tmp = tempfile::tempdir().unwrap();
388        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
389        let other = seed(tmp.path(), "other", Some("/wt/there"));
390        let legacy = seed(tmp.path(), "legacy", None);
391
392        let (kept, fell_back) = select_worktree_sessions(
393            vec![mine.clone(), other.clone(), legacy.clone()],
394            "/wt/here",
395        );
396
397        assert!(!fell_back);
398        assert!(kept.contains(&mine), "current worktree session kept");
399        assert!(
400            kept.contains(&legacy),
401            "unmarked legacy session kept (conservative)"
402        );
403        assert!(
404            !kept.contains(&other),
405            "other worktree's marked session excluded"
406        );
407    }
408
409    #[test]
410    fn excludes_session_with_unreadable_marker() {
411        let tmp = tempfile::tempdir().unwrap();
412        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
413        // A present-but-unreadable marker: make `origin` a directory so
414        // read_to_string fails with a non-NotFound error.
415        let bad = tmp.path().join("bad");
416        std::fs::create_dir_all(bad.join("origin")).unwrap();
417
418        let (kept, fell_back) =
419            select_worktree_sessions(vec![mine.clone(), bad.clone()], "/wt/here");
420
421        assert!(!fell_back);
422        assert!(kept.contains(&mine), "current worktree session kept");
423        assert!(
424            !kept.contains(&bad),
425            "session with a present-but-unreadable marker must be excluded, not kept as legacy"
426        );
427    }
428
429    #[test]
430    fn falls_back_to_all_when_nothing_matches() {
431        let tmp = tempfile::tempdir().unwrap();
432        let a = seed(tmp.path(), "a", Some("/wt/there"));
433        let b = seed(tmp.path(), "b", Some("/wt/elsewhere"));
434
435        let (kept, fell_back) = select_worktree_sessions(vec![a.clone(), b.clone()], "/wt/here");
436
437        assert!(fell_back, "must flag fallback when filter matches nothing");
438        assert_eq!(
439            kept.len(),
440            2,
441            "never under-enforce: send all rather than zero"
442        );
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::connectivity_message;
449
450    #[test]
451    fn connectivity_message_suggests_login_on_401() {
452        let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
453        assert!(
454            m.contains("tracevault login"),
455            "401 errors must surface the login hint; got: {m}"
456        );
457    }
458
459    #[test]
460    fn connectivity_message_suggests_login_on_unauthorized_text() {
461        let m = connectivity_message("Server returned: unauthorized request");
462        assert!(m.contains("tracevault login"));
463    }
464
465    #[test]
466    fn connectivity_message_suggests_network_check_on_dns_error() {
467        let m = connectivity_message("error sending request for url: dns error");
468        assert!(
469            m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
470            "DNS errors must surface a network hint; got: {m}"
471        );
472    }
473
474    #[test]
475    fn connectivity_message_suggests_network_check_on_connection_refused() {
476        let m = connectivity_message("connection refused");
477        assert!(m.to_lowercase().contains("network"));
478    }
479
480    #[test]
481    fn connectivity_message_falls_back_when_unrecognized() {
482        let m = connectivity_message("some weird new error shape we have not seen before");
483        // No suggestion — but the raw error must still be in the message so
484        // the user can debug.
485        assert!(m.contains("some weird new error shape"));
486        assert!(!m.contains("→")); // no action arrow
487    }
488
489    #[test]
490    fn connectivity_message_does_not_collide_on_403() {
491        let m = connectivity_message("403 Forbidden");
492        // 403 should point at token authorization, NOT a re-login.
493        assert!(
494            m.to_lowercase().contains("authorized"),
495            "403 should mention authorization; got: {m}"
496        );
497    }
498
499    #[test]
500    fn connectivity_message_flags_404_as_version_mismatch() {
501        // Simulates an old-server-404 skew: a route the CLI expects to exist
502        // (e.g. `Failed to list repos (404 Not Found)`) doesn't exist yet on
503        // this server build. Must hint at a version mismatch, not just
504        // report a bare 404 with no next step.
505        let m = connectivity_message("Failed to list repos (404 Not Found): ");
506        assert!(
507            m.to_lowercase().contains("newer than the server")
508                || m.to_lowercase().contains("version mismatch"),
509            "404 should hint at a possible CLI/server version mismatch; got: {m}"
510        );
511    }
512
513    #[test]
514    fn connectivity_message_flags_500_as_server_error() {
515        let m = connectivity_message("Server returned 500 Internal Server Error: oops");
516        assert!(
517            m.to_lowercase().contains("server returned an error"),
518            "500 should surface the server-error hint; got: {m}"
519        );
520    }
521
522    #[test]
523    fn connectivity_message_flags_503_without_internal_text() {
524        // `503 Service Unavailable` carries neither "internal" nor
525        // "server error" — the bare code must still be recognized.
526        let m = connectivity_message("Server returned 503 Service Unavailable: ");
527        assert!(
528            m.to_lowercase().contains("server returned an error"),
529            "503 should surface the server-error hint; got: {m}"
530        );
531    }
532
533    #[test]
534    fn connectivity_message_treats_504_as_server_not_network() {
535        // A gateway timeout is a server-side fault even though it contains
536        // the word "timeout"; it must not be misreported as a local network
537        // problem.
538        let m = connectivity_message("Server returned 504 Gateway Timeout: ");
539        assert!(
540            m.to_lowercase().contains("server returned an error"),
541            "504 should be treated as a server error; got: {m}"
542        );
543    }
544}