Skip to main content

tracevault_cli/commands/
check.rs

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