Skip to main content

tracevault_cli/commands/
status.rs

1//! `tracevault status` — surface every piece of state a user might need to
2//! debug "why doesn't it work". The command runs read-only checks across
3//! credentials, the project tree, and the server, and prints a grouped
4//! report with ✓ / ✗ / ! markers. Exits non-zero if anything actionable is
5//! broken.
6
7use crate::api_client::{ApiClient, GetMeError};
8use crate::config::TracevaultConfig;
9use crate::credentials::Credentials;
10use std::fs;
11use std::path::Path;
12use std::process::Command;
13
14const ANSI_GREEN: &str = "\x1b[32m";
15const ANSI_RED: &str = "\x1b[31m";
16const ANSI_YELLOW: &str = "\x1b[33m";
17const ANSI_DIM: &str = "\x1b[2m";
18const ANSI_RESET: &str = "\x1b[0m";
19
20/// Severity classification of a single check. Anything at `Error` level
21/// bumps the final exit code to 1.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23enum Level {
24    Ok,
25    Warn,
26    Error,
27    /// Check skipped because a prerequisite failed (e.g. can't validate
28    /// token if no token was found). Does not affect exit code.
29    Skip,
30}
31
32#[derive(Debug)]
33struct Check {
34    label: String,
35    level: Level,
36    detail: String,
37}
38
39impl Check {
40    fn ok(label: impl Into<String>, detail: impl Into<String>) -> Self {
41        Self {
42            label: label.into(),
43            level: Level::Ok,
44            detail: detail.into(),
45        }
46    }
47    fn warn(label: impl Into<String>, detail: impl Into<String>) -> Self {
48        Self {
49            label: label.into(),
50            level: Level::Warn,
51            detail: detail.into(),
52        }
53    }
54    fn err(label: impl Into<String>, detail: impl Into<String>) -> Self {
55        Self {
56            label: label.into(),
57            level: Level::Error,
58            detail: detail.into(),
59        }
60    }
61    fn skip(label: impl Into<String>, detail: impl Into<String>) -> Self {
62        Self {
63            label: label.into(),
64            level: Level::Skip,
65            detail: detail.into(),
66        }
67    }
68}
69
70fn marker(l: Level) -> &'static str {
71    match l {
72        Level::Ok => "\x1b[32m✓\x1b[0m",
73        Level::Warn => "\x1b[33m!\x1b[0m",
74        Level::Error => "\x1b[31m✗\x1b[0m",
75        Level::Skip => "\x1b[2m·\x1b[0m",
76    }
77}
78
79fn print_section(title: &str, checks: &[Check]) {
80    println!("{ANSI_DIM}──{ANSI_RESET} {title}");
81    for c in checks {
82        if c.detail.is_empty() {
83            println!("  {} {}", marker(c.level), c.label);
84        } else {
85            println!(
86                "  {} {:<32} {ANSI_DIM}{}{ANSI_RESET}",
87                marker(c.level),
88                c.label,
89                c.detail
90            );
91        }
92    }
93    println!();
94}
95
96// --- Authentication ---
97
98struct AuthContext {
99    server_url: Option<String>,
100    token: Option<String>,
101    source: &'static str, // "env", "credentials", or "none"
102    email_from_creds: Option<String>,
103}
104
105fn resolve_auth() -> AuthContext {
106    // Env var wins. Match the server-side resolution order in
107    // resolve_credentials (env > creds), except we treat the env var as
108    // authoritative without looking at the credentials file email.
109    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
110    let env_url = std::env::var("TRACEVAULT_SERVER_URL").ok();
111
112    if let Some(token) = env_key {
113        return AuthContext {
114            server_url: env_url,
115            token: Some(token),
116            source: "env (TRACEVAULT_API_KEY)",
117            email_from_creds: None,
118        };
119    }
120
121    let creds = Credentials::load();
122    if let Some(c) = creds {
123        return AuthContext {
124            server_url: Some(c.server_url),
125            token: Some(c.token),
126            source: "credentials file",
127            email_from_creds: Some(c.email),
128        };
129    }
130
131    AuthContext {
132        server_url: env_url,
133        token: None,
134        source: "none",
135        email_from_creds: None,
136    }
137}
138
139async fn auth_checks(auth: &AuthContext) -> Vec<Check> {
140    let mut out = Vec::new();
141
142    match (auth.token.as_ref(), auth.server_url.as_ref()) {
143        (None, _) => {
144            out.push(Check::err(
145                "Logged in",
146                "no credentials found. Run `tracevault login --server-url <URL>`.",
147            ));
148            out.push(Check::skip("Token valid", "no token to check"));
149            return out;
150        }
151        (Some(_), None) => {
152            out.push(Check::err(
153                "Logged in",
154                "token found but no server URL (set TRACEVAULT_SERVER_URL)",
155            ));
156            out.push(Check::skip("Token valid", "no server URL to call"));
157            return out;
158        }
159        (Some(_), Some(url)) => {
160            out.push(Check::ok("Logged in", format!("{url} via {}", auth.source)));
161        }
162    }
163
164    let server_url = auth.server_url.as_ref().unwrap();
165    let token = auth.token.as_ref().unwrap();
166    let client = ApiClient::new(server_url, Some(token));
167    match client.get_me().await {
168        Ok(me) => {
169            let who = me.name.unwrap_or_else(|| me.email.clone());
170            out.push(Check::ok("Token valid", format!("{who} <{}>", me.email)));
171
172            if let Some(cached) = &auth.email_from_creds {
173                if cached != &me.email {
174                    out.push(Check::warn(
175                        "Credentials cache",
176                        format!(
177                            "cached email '{cached}' differs from server '{}' — re-run login",
178                            me.email
179                        ),
180                    ));
181                }
182            }
183        }
184        Err(GetMeError::Unauthorized) => {
185            out.push(Check::err(
186                "Token valid",
187                "rejected by server (expired or revoked). Run `tracevault login` again.",
188            ));
189        }
190        Err(GetMeError::Network(msg)) => {
191            out.push(Check::warn(
192                "Server reachable",
193                format!("{msg} — cannot confirm token validity"),
194            ));
195        }
196        Err(GetMeError::Server(msg)) => {
197            out.push(Check::warn("Token valid", format!("server error: {msg}")));
198        }
199    }
200    out
201}
202
203// --- Project ---
204
205/// Subset of project checks that don't need network. Returns the loaded
206/// config if present so later sections can reuse it.
207fn project_checks(project_root: &Path) -> (Vec<Check>, Option<TracevaultConfig>) {
208    let mut out = Vec::new();
209
210    let is_git = project_root.join(".git").exists();
211    if is_git {
212        out.push(Check::ok(
213            "Git repository",
214            project_root.display().to_string(),
215        ));
216    } else {
217        out.push(Check::err(
218            "Git repository",
219            "current directory is not a git repo",
220        ));
221    }
222
223    let tv_dir = project_root.join(".tracevault");
224    if !tv_dir.exists() {
225        out.push(Check::err(
226            "TraceVault initialized",
227            "no .tracevault/ directory. Run `tracevault init`.",
228        ));
229        return (out, None);
230    }
231    out.push(Check::ok("TraceVault initialized", ".tracevault/ present"));
232
233    let config = TracevaultConfig::load(project_root);
234    match &config {
235        Some(c) => {
236            let slug = c.org_slug.as_deref().unwrap_or("<unset>");
237            let url = c.server_url.as_deref().unwrap_or("<unset>");
238            out.push(Check::ok(
239                "Project config",
240                format!("org={slug}, server={url}"),
241            ));
242        }
243        None => {
244            out.push(Check::err(
245                "Project config",
246                ".tracevault/config.toml missing or unreadable",
247            ));
248        }
249    }
250
251    // Hooks — presence of our markers, not just existence of the hook file.
252    out.push(git_hook_check(
253        project_root,
254        "pre-push",
255        "# tracevault:enforce",
256    ));
257    out.push(git_hook_check(
258        project_root,
259        "post-commit",
260        "# tracevault:post-commit",
261    ));
262    out.push(claude_hook_check(project_root));
263
264    (out, config)
265}
266
267fn git_hook_check(project_root: &Path, name: &str, marker: &str) -> Check {
268    let path = project_root.join(".git/hooks").join(name);
269    let label = format!("Git hook: {name}");
270    if !path.exists() {
271        return Check::warn(
272            label,
273            format!(".git/hooks/{name} missing — rerun `tracevault init`"),
274        );
275    }
276    match fs::read_to_string(&path) {
277        Ok(s) if s.contains(marker) => Check::ok(label, "installed"),
278        Ok(_) => Check::warn(
279            label,
280            format!("{name} exists but no tracevault block — rerun `tracevault init`"),
281        ),
282        Err(e) => Check::warn(label, format!("cannot read hook: {e}")),
283    }
284}
285
286fn claude_hook_check(project_root: &Path) -> Check {
287    let settings = project_root.join(".claude/settings.json");
288    if !settings.exists() {
289        // Not installed is a warning, not an error: tracevault still works
290        // without Claude Code hooks (just with less rich capture).
291        return Check::warn(
292            "Claude Code hooks",
293            ".claude/settings.json missing (capture will miss some events)",
294        );
295    }
296    match fs::read_to_string(&settings) {
297        Ok(s) if s.contains("tracevault stream") => {
298            Check::ok("Claude Code hooks", "registered in .claude/settings.json")
299        }
300        Ok(_) => Check::warn(
301            "Claude Code hooks",
302            "settings.json has no tracevault stream commands",
303        ),
304        Err(e) => Check::warn(
305            "Claude Code hooks",
306            format!("cannot read settings.json: {e}"),
307        ),
308    }
309}
310
311// --- Server repo ---
312
313async fn server_repo_checks(
314    project_root: &Path,
315    auth: &AuthContext,
316    config: Option<&TracevaultConfig>,
317) -> Vec<Check> {
318    let mut out = Vec::new();
319
320    let (Some(token), Some(server_url)) = (auth.token.as_ref(), auth.server_url.as_ref()) else {
321        out.push(Check::skip(
322            "Repo registered on server",
323            "not authenticated",
324        ));
325        return out;
326    };
327    let Some(slug) = config.and_then(|c| c.org_slug.as_deref()) else {
328        out.push(Check::skip(
329            "Repo registered on server",
330            "no org_slug in config",
331        ));
332        return out;
333    };
334
335    let client = ApiClient::new(server_url, Some(token));
336    let repos = match client.list_repos(slug).await {
337        Ok(r) => r,
338        Err(e) => {
339            out.push(Check::warn(
340                "Repo registered on server",
341                format!("failed to list repos: {e}"),
342            ));
343            return out;
344        }
345    };
346
347    let repo_name = git_repo_name(project_root);
348    let found = repos.iter().find(|r| r.name == repo_name);
349
350    match found {
351        None => {
352            out.push(Check::err(
353                "Repo registered on server",
354                format!("'{repo_name}' not found in org '{slug}'. Run `tracevault init` while logged in, or `tracevault sync`."),
355            ));
356            return out;
357        }
358        Some(r) => {
359            out.push(Check::ok(
360                "Repo registered on server",
361                format!("id={}", r.id),
362            ));
363            match r.clone_status.as_deref() {
364                Some("ready") => out.push(Check::ok("Server-side clone", "ready")),
365                Some(other @ ("cloning" | "pending")) => out.push(Check::warn(
366                    "Server-side clone",
367                    format!("{other} — analytics and code browser unavailable until it finishes"),
368                )),
369                Some("error") => out.push(Check::err(
370                    "Server-side clone",
371                    "error — check the repo settings page on the dashboard",
372                )),
373                Some(other) => out.push(Check::warn(
374                    "Server-side clone",
375                    format!("unknown status '{other}'"),
376                )),
377                None => out.push(Check::skip(
378                    "Server-side clone",
379                    "server did not report clone status",
380                )),
381            }
382
383            let local_remote = git_remote_url(project_root);
384            match (local_remote.as_deref(), r.github_url.as_deref()) {
385                (Some(local), Some(remote))
386                    if normalize_remote(local) == normalize_remote(remote) =>
387                {
388                    out.push(Check::ok("Remote URL matches", remote.to_string()));
389                }
390                (Some(local), Some(remote)) => out.push(Check::warn(
391                    "Remote URL matches",
392                    format!("local={local} vs server={remote} — run `tracevault sync`"),
393                )),
394                (Some(local), None) => out.push(Check::warn(
395                    "Remote URL matches",
396                    format!("server has no github_url; local={local}"),
397                )),
398                (None, _) => out.push(Check::warn(
399                    "Remote URL matches",
400                    "no local `origin` remote configured",
401                )),
402            }
403        }
404    }
405
406    out
407}
408
409// --- Sessions ---
410
411fn session_checks(project_root: &Path) -> Vec<Check> {
412    let sessions_dir = project_root.join(".tracevault/sessions");
413    if !sessions_dir.exists() {
414        return vec![Check::skip(
415            "Pending events",
416            "no .tracevault/sessions/ yet (no captures recorded)",
417        )];
418    }
419
420    let mut total_sessions = 0usize;
421    let mut sessions_with_pending = 0usize;
422    let mut pending_event_count = 0usize;
423
424    if let Ok(read) = fs::read_dir(&sessions_dir) {
425        for entry in read.flatten() {
426            if !entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
427                continue;
428            }
429            total_sessions += 1;
430            let pending_path = entry.path().join("pending.jsonl");
431            if pending_path.exists() {
432                let count = fs::read_to_string(&pending_path)
433                    .unwrap_or_default()
434                    .lines()
435                    .filter(|l| !l.trim().is_empty())
436                    .count();
437                if count > 0 {
438                    sessions_with_pending += 1;
439                    pending_event_count += count;
440                }
441            }
442        }
443    }
444
445    vec![if sessions_with_pending == 0 {
446        Check::ok(
447            "Pending events",
448            format!("{total_sessions} session(s), all synced"),
449        )
450    } else {
451        Check::warn(
452            "Pending events",
453            format!(
454                "{pending_event_count} event(s) in {sessions_with_pending}/{total_sessions} session(s) — run `tracevault flush`"
455            ),
456        )
457    }]
458}
459
460// --- Git helpers ---
461
462fn git_repo_name(project_root: &Path) -> String {
463    Command::new("git")
464        .args(["rev-parse", "--show-toplevel"])
465        .current_dir(project_root)
466        .output()
467        .ok()
468        .filter(|o| o.status.success())
469        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
470        .as_deref()
471        .and_then(|p| p.rsplit('/').next())
472        .map(String::from)
473        .unwrap_or_else(|| "unknown".into())
474}
475
476fn git_remote_url(project_root: &Path) -> Option<String> {
477    Command::new("git")
478        .args(["remote", "get-url", "origin"])
479        .current_dir(project_root)
480        .output()
481        .ok()
482        .filter(|o| o.status.success())
483        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
484        .filter(|s| !s.is_empty())
485}
486
487/// Make two remote URLs comparable by dropping `.git`, trailing slash, and
488/// collapsing SSH ↔ HTTPS differences for github.com specifically.
489fn normalize_remote(url: &str) -> String {
490    let trimmed = url
491        .trim()
492        .trim_end_matches('/')
493        .trim_end_matches(".git")
494        .to_string();
495
496    // git@github.com:org/repo  ->  github.com/org/repo
497    if let Some(rest) = trimmed.strip_prefix("git@github.com:") {
498        return format!("github.com/{rest}");
499    }
500    // https://github.com/org/repo -> github.com/org/repo
501    for p in ["https://", "http://"] {
502        if let Some(rest) = trimmed.strip_prefix(p) {
503            return rest.to_string();
504        }
505    }
506    trimmed
507}
508
509// --- Entry point ---
510
511pub async fn run_status(project_root: &Path) -> i32 {
512    let auth = resolve_auth();
513
514    let auth_checks_v = auth_checks(&auth).await;
515    let (proj_checks_v, config) = project_checks(project_root);
516    let server_checks_v = server_repo_checks(project_root, &auth, config.as_ref()).await;
517    let session_checks_v = session_checks(project_root);
518
519    print_section("Authentication", &auth_checks_v);
520    print_section("Project", &proj_checks_v);
521    print_section("Server repo", &server_checks_v);
522    print_section("Sessions", &session_checks_v);
523
524    let all: Vec<&Check> = auth_checks_v
525        .iter()
526        .chain(proj_checks_v.iter())
527        .chain(server_checks_v.iter())
528        .chain(session_checks_v.iter())
529        .collect();
530
531    let errors = all.iter().filter(|c| c.level == Level::Error).count();
532    let warns = all.iter().filter(|c| c.level == Level::Warn).count();
533
534    match (errors, warns) {
535        (0, 0) => println!("{ANSI_GREEN}All good.{ANSI_RESET}"),
536        (0, w) => println!(
537            "{ANSI_YELLOW}{w} warning{} — no blocking issues.{ANSI_RESET}",
538            if w == 1 { "" } else { "s" }
539        ),
540        (e, 0) => println!(
541            "{ANSI_RED}{e} problem{} found.{ANSI_RESET}",
542            if e == 1 { "" } else { "s" }
543        ),
544        (e, w) => println!(
545            "{ANSI_RED}{e} problem{}, {w} warning{}.{ANSI_RESET}",
546            if e == 1 { "" } else { "s" },
547            if w == 1 { "" } else { "s" }
548        ),
549    }
550
551    if errors > 0 {
552        1
553    } else {
554        0
555    }
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561
562    #[test]
563    fn normalize_remote_ssh_https_equal() {
564        assert_eq!(
565            normalize_remote("git@github.com:VirtusLab/visdom-ai-tracing.git"),
566            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing")
567        );
568        assert_eq!(
569            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing.git/"),
570            "github.com/VirtusLab/visdom-ai-tracing"
571        );
572    }
573
574    #[test]
575    fn normalize_remote_preserves_non_github() {
576        assert_eq!(
577            normalize_remote("git@gitlab.com:foo/bar.git"),
578            "git@gitlab.com:foo/bar"
579        );
580    }
581
582    #[test]
583    fn git_hook_check_missing_file_is_warning() {
584        let dir = tempfile::tempdir().unwrap();
585        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
586        assert_eq!(check.level, Level::Warn);
587    }
588
589    #[test]
590    fn git_hook_check_with_marker_is_ok() {
591        let dir = tempfile::tempdir().unwrap();
592        let hooks = dir.path().join(".git/hooks");
593        std::fs::create_dir_all(&hooks).unwrap();
594        std::fs::write(
595            hooks.join("pre-push"),
596            "#!/bin/sh\n# tracevault:enforce\ntracevault check\n",
597        )
598        .unwrap();
599        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
600        assert_eq!(check.level, Level::Ok);
601    }
602
603    #[test]
604    fn git_hook_check_without_marker_is_warning() {
605        let dir = tempfile::tempdir().unwrap();
606        let hooks = dir.path().join(".git/hooks");
607        std::fs::create_dir_all(&hooks).unwrap();
608        std::fs::write(hooks.join("pre-push"), "#!/bin/sh\necho hi\n").unwrap();
609        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
610        assert_eq!(check.level, Level::Warn);
611    }
612
613    #[test]
614    fn project_checks_errors_without_tracevault_dir() {
615        let dir = tempfile::tempdir().unwrap();
616        // Create .git so the git-repo check passes, isolate the assertion.
617        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
618        let (checks, cfg) = project_checks(dir.path());
619        assert!(cfg.is_none());
620        assert!(checks
621            .iter()
622            .any(|c| c.level == Level::Error && c.label == "TraceVault initialized"));
623    }
624}