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, PathBuf};
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(
208    project_root: &Path,
209    global_settings: Option<&Path>,
210    has_global: bool,
211    has_binding: bool,
212) -> (Vec<Check>, Option<TracevaultConfig>) {
213    let mut out = Vec::new();
214
215    let is_git = project_root.join(".git").exists();
216    if is_git {
217        out.push(Check::ok(
218            "Git repository",
219            project_root.display().to_string(),
220        ));
221    } else if has_global || has_binding {
222        out.push(Check::skip(
223            "Git repository",
224            "not a git repo (global/workspace mode)",
225        ));
226    } else {
227        out.push(Check::err(
228            "Git repository",
229            "current directory is not a git repo",
230        ));
231    }
232
233    let tv_present = project_root.join(".tracevault").exists();
234    out.push(tracevault_init_check(tv_present, has_global, has_binding));
235
236    // Distinguish "no config.toml" (expected in workspace/detached mode —
237    // just a warning) from "config.toml present but malformed" (a genuine
238    // error) via `try_load`, rather than the lenient `load` which collapses
239    // both cases to `None`.
240    let config = match TracevaultConfig::try_load(project_root) {
241        Ok(Some(c)) => {
242            let slug = c.org_slug.as_deref().unwrap_or("<unset>");
243            let url = c.server_url.as_deref().unwrap_or("<unset>");
244            out.push(Check::ok(
245                "Project config",
246                format!("org={slug}, server={url}"),
247            ));
248            Some(c)
249        }
250        Ok(None) => {
251            if tv_present {
252                out.push(Check::warn(
253                    "Project config",
254                    "No .tracevault/config.toml — run `tracevault init`, or use workspace mode (`tracevault repo status`).",
255                ));
256            }
257            None
258        }
259        Err(e) => {
260            out.push(Check::err(
261                "Project config",
262                format!(".tracevault/config.toml malformed: {e}"),
263            ));
264            None
265        }
266    };
267
268    if tv_present {
269        // Hooks — presence of our markers, not just existence of the hook file.
270        out.push(git_hook_check(
271            project_root,
272            "pre-push",
273            "# tracevault:enforce",
274        ));
275        out.push(git_hook_check(
276            project_root,
277            "post-commit",
278            "# tracevault:post-commit",
279        ));
280    } else if has_global || has_binding {
281        out.push(Check::skip(
282            "Git hooks",
283            "not used in global/workspace mode",
284        ));
285    } else {
286        out.push(Check::skip(
287            "Git hooks",
288            "not installed (no .tracevault/ — run `tracevault init`)",
289        ));
290    }
291
292    out.push(claude_hook_check_in(
293        &project_root.join(".claude/settings.json"),
294        global_settings,
295    ));
296
297    (out, config)
298}
299
300fn git_hook_check(project_root: &Path, name: &str, marker: &str) -> Check {
301    let path = project_root.join(".git/hooks").join(name);
302    let label = format!("Git hook: {name}");
303    if !path.exists() {
304        return Check::warn(
305            label,
306            format!(".git/hooks/{name} missing — rerun `tracevault init`"),
307        );
308    }
309    match fs::read_to_string(&path) {
310        Ok(s) if s.contains(marker) => Check::ok(label, "installed"),
311        Ok(_) => Check::warn(
312            label,
313            format!("{name} exists but no tracevault block — rerun `tracevault init`"),
314        ),
315        Err(e) => Check::warn(label, format!("cannot read hook: {e}")),
316    }
317}
318
319/// True if a Claude settings.json body wires any tracevault hook command.
320fn settings_has_tracevault_hooks(contents: &str) -> bool {
321    contents.contains("tracevault stream")
322        || contents.contains("tracevault session-start")
323        || contents.contains("tracevault user-prompt")
324}
325
326/// Whether a Claude `settings.json` wires tracevault hooks — distinguishing a
327/// genuinely-absent file from one that exists but can't be read, so an
328/// IO/permission error isn't silently reported as "not installed".
329enum SettingsHooks {
330    Present,
331    NoHooks,
332    Missing,
333    Unreadable(String),
334}
335
336fn read_settings_hooks(path: &Path) -> SettingsHooks {
337    match fs::read_to_string(path) {
338        Ok(s) if settings_has_tracevault_hooks(&s) => SettingsHooks::Present,
339        Ok(_) => SettingsHooks::NoHooks,
340        Err(e) if e.kind() == std::io::ErrorKind::NotFound => SettingsHooks::Missing,
341        Err(e) => SettingsHooks::Unreadable(e.to_string()),
342    }
343}
344
345/// Check a global `~/.claude/settings.json` for the `init --global` install.
346/// Absent / no tracevault hooks → Skip (a global install is optional); an
347/// existing-but-unreadable file → Warn (don't hide a permission/IO problem).
348fn global_hook_check_in(settings_path: &Path) -> Check {
349    match read_settings_hooks(settings_path) {
350        SettingsHooks::Present => Check::ok(
351            "Global install",
352            "hooks installed in ~/.claude/settings.json",
353        ),
354        SettingsHooks::NoHooks => Check::skip(
355            "Global install",
356            "~/.claude/settings.json has no tracevault hooks",
357        ),
358        SettingsHooks::Missing => Check::skip("Global install", "no ~/.claude/settings.json"),
359        SettingsHooks::Unreadable(e) => Check::warn(
360            "Global install",
361            format!("cannot read ~/.claude/settings.json: {e}"),
362        ),
363    }
364}
365
366/// Claude Code hooks may live per-repo (`<repo>/.claude/settings.json`) OR
367/// globally (`~/.claude/settings.json`, `init --global`). Ok if EITHER wires
368/// tracevault; an existing-but-unreadable settings file is surfaced as a Warn
369/// with the path (not a generic "not registered"); Warn if neither wires it.
370fn claude_hook_check_in(repo_settings: &Path, global_settings: Option<&Path>) -> Check {
371    let repo = read_settings_hooks(repo_settings);
372    if matches!(repo, SettingsHooks::Present) {
373        return Check::ok("Claude Code hooks", "registered in .claude/settings.json");
374    }
375    let global = global_settings.map(read_settings_hooks);
376    if matches!(global, Some(SettingsHooks::Present)) {
377        return Check::ok("Claude Code hooks", "via global install (see Installation)");
378    }
379    if let SettingsHooks::Unreadable(e) = &repo {
380        return Check::warn(
381            "Claude Code hooks",
382            format!("cannot read <repo>/.claude/settings.json: {e}"),
383        );
384    }
385    if let Some(SettingsHooks::Unreadable(e)) = &global {
386        return Check::warn(
387            "Claude Code hooks",
388            format!("cannot read ~/.claude/settings.json: {e}"),
389        );
390    }
391    Check::warn(
392        "Claude Code hooks",
393        "not registered in <repo>/.claude/settings.json or ~/.claude/settings.json (capture will miss some events)",
394    )
395}
396
397/// Severity of the "TraceVault initialized" check. A per-repo `.tracevault/`
398/// present is always Ok. Absent is EXPECTED (Skip) when the user has a global
399/// install or an active workspace binding; only a truly-unconfigured setup
400/// (none of the three) is an Error.
401fn tracevault_init_check(tv_dir_present: bool, has_global: bool, has_binding: bool) -> Check {
402    if tv_dir_present {
403        Check::ok("TraceVault initialized", ".tracevault/ present")
404    } else if has_global || has_binding {
405        Check::skip(
406            "TraceVault initialized",
407            "no per-repo .tracevault/ — global/workspace mode",
408        )
409    } else {
410        Check::err(
411            "TraceVault initialized",
412            "not set up: run `tracevault init` (per-repo) or `tracevault init --global`",
413        )
414    }
415}
416
417/// The most-recently-modified session in `sessions_dir` that HAS an active
418/// binding, as `(session_id, binding)`. Scans ALL session files (newest first)
419/// rather than only the newest file, so a real binding isn't missed when the
420/// most-recently-touched session happens to have none. `None` if no session
421/// carries an active binding.
422fn latest_active_binding_in(
423    sessions_dir: &Path,
424) -> Option<(String, crate::session_state::RepoBinding)> {
425    let mut sessions: Vec<(std::time::SystemTime, String)> = Vec::new();
426    for entry in fs::read_dir(sessions_dir).ok()?.flatten() {
427        let name = entry.file_name();
428        let name = name.to_str().unwrap_or("");
429        let Some(id) = name.strip_suffix(".toml") else {
430            continue;
431        };
432        if id.is_empty() {
433            continue;
434        }
435        let Ok(mtime) = entry.metadata().and_then(|m| m.modified()) else {
436            continue;
437        };
438        sessions.push((mtime, id.to_string()));
439    }
440    sessions.sort_by_key(|(mtime, _)| std::cmp::Reverse(*mtime)); // newest first
441    for (_, id) in sessions {
442        if let Some(b) = crate::session_state::load_from(sessions_dir, &id).active {
443            return Some((id, b));
444        }
445    }
446    None
447}
448
449/// Resolve the workspace binding for `status`. With an explicit session id the
450/// user named a target, so a missing binding is a Warn. Without one, best-effort
451/// scan across all sessions (state is global): show the most recent that HAS a
452/// binding, and stay quiet (Skip) when none does — so a bound-mode user with a
453/// stray empty session file isn't warned. Returns the Check AND the resolved
454/// binding (reused by the caller as the `has_binding` mode signal).
455fn workspace_binding_check_in(
456    sessions_dir: &Path,
457    explicit_session_id: Option<&str>,
458) -> (Check, Option<crate::session_state::RepoBinding>) {
459    match explicit_session_id {
460        Some(id) => {
461            let state = crate::session_state::load_from(sessions_dir, id);
462            match state.active {
463                Some(b) => (
464                    Check::ok(
465                        "Workspace binding",
466                        format!(
467                            "repo {} (org {}) via repo switch (session {id})",
468                            b.repo_id, b.org_slug
469                        ),
470                    ),
471                    Some(b),
472                ),
473                None => (
474                    Check::warn(
475                        "Workspace binding",
476                        format!(
477                            "session {id} has no active binding — run `tracevault repo switch …`"
478                        ),
479                    ),
480                    None,
481                ),
482            }
483        }
484        None => match latest_active_binding_in(sessions_dir) {
485            Some((id, b)) => (
486                Check::ok(
487                    "Workspace binding",
488                    format!(
489                        "repo {} (org {}) via repo switch — most recent session with a binding: {id} (may be another repo; pass --session-id to target one)",
490                        b.repo_id, b.org_slug
491                    ),
492                ),
493                Some(b),
494            ),
495            None => (
496                Check::skip("Workspace binding", "no active workspace binding found"),
497                None,
498            ),
499        },
500    }
501}
502
503// --- Server repo ---
504
505/// How `status` should locate the repo on the server.
506#[derive(Debug, PartialEq)]
507enum RepoMatch {
508    ByName(String),
509    ById(String),
510}
511
512/// Bound mode (config `org_slug`, match by git repo NAME) takes precedence;
513/// otherwise workspace mode (the authoritative binding's `org_slug`, match by
514/// `repo_id`). `None` when neither is available. Pure — `repo_name` is passed
515/// in so this is unit-testable without invoking git.
516fn server_repo_lookup(
517    config_org_slug: Option<&str>,
518    repo_name: &str,
519    binding: Option<&crate::session_state::RepoBinding>,
520) -> Option<(String, RepoMatch)> {
521    if let Some(slug) = config_org_slug {
522        return Some((slug.to_string(), RepoMatch::ByName(repo_name.to_string())));
523    }
524    if let Some(b) = binding {
525        return Some((b.org_slug.clone(), RepoMatch::ById(b.repo_id.clone())));
526    }
527    None
528}
529
530async fn server_repo_checks(
531    project_root: &Path,
532    auth: &AuthContext,
533    config: Option<&TracevaultConfig>,
534    binding: Option<&crate::session_state::RepoBinding>,
535) -> Vec<Check> {
536    let mut out = Vec::new();
537
538    let (Some(token), Some(server_url)) = (auth.token.as_ref(), auth.server_url.as_ref()) else {
539        out.push(Check::skip(
540            "Repo registered on server",
541            "not authenticated",
542        ));
543        return out;
544    };
545
546    let repo_name = git_repo_name(project_root);
547    let Some((slug, want)) = server_repo_lookup(
548        config.and_then(|c| c.org_slug.as_deref()),
549        &repo_name,
550        binding,
551    ) else {
552        out.push(Check::skip(
553            "Repo registered on server",
554            "no org (need a bound config.toml or a --session-id workspace binding)",
555        ));
556        return out;
557    };
558
559    let client = ApiClient::new(server_url, Some(token));
560    let repos = match client.list_repos(&slug).await {
561        Ok(r) => r,
562        Err(e) => {
563            out.push(Check::warn(
564                "Repo registered on server",
565                format!("failed to list repos: {e}"),
566            ));
567            return out;
568        }
569    };
570
571    let found = repos.iter().find(|r| match &want {
572        RepoMatch::ByName(name) => &r.name == name,
573        RepoMatch::ById(id) => &r.id.to_string() == id,
574    });
575
576    match found {
577        None => {
578            let what = match &want {
579                RepoMatch::ByName(n) => format!("'{n}'"),
580                RepoMatch::ById(id) => format!("repo id {id}"),
581            };
582            out.push(Check::err(
583                "Repo registered on server",
584                format!("{what} not found in org '{slug}'. Run `tracevault init` while logged in, or `tracevault sync`."),
585            ));
586            return out;
587        }
588        Some(r) => {
589            out.push(Check::ok(
590                "Repo registered on server",
591                format!("id={}", r.id),
592            ));
593            match r.clone_status.as_deref() {
594                Some("ready") => out.push(Check::ok("Server-side clone", "ready")),
595                Some(other @ ("cloning" | "pending")) => out.push(Check::warn(
596                    "Server-side clone",
597                    format!("{other} — analytics and code browser unavailable until it finishes"),
598                )),
599                Some("error") => out.push(Check::err(
600                    "Server-side clone",
601                    "error — check the repo settings page on the dashboard",
602                )),
603                Some(other) => out.push(Check::warn(
604                    "Server-side clone",
605                    format!("unknown status '{other}'"),
606                )),
607                None => out.push(Check::skip(
608                    "Server-side clone",
609                    "server did not report clone status",
610                )),
611            }
612
613            match &want {
614                RepoMatch::ByName(_) => {
615                    let local_remote = git_remote_url(project_root);
616                    match (local_remote.as_deref(), r.github_url.as_deref()) {
617                        (Some(local), Some(remote))
618                            if normalize_remote(local) == normalize_remote(remote) =>
619                        {
620                            out.push(Check::ok("Remote URL matches", remote.to_string()));
621                        }
622                        (Some(local), Some(remote)) => out.push(Check::warn(
623                            "Remote URL matches",
624                            format!("local={local} vs server={remote} — run `tracevault sync`"),
625                        )),
626                        (Some(local), None) => out.push(Check::warn(
627                            "Remote URL matches",
628                            format!("server has no github_url; local={local}"),
629                        )),
630                        (None, _) => out.push(Check::warn(
631                            "Remote URL matches",
632                            "no local `origin` remote configured",
633                        )),
634                    }
635                }
636                RepoMatch::ById(_) => {
637                    out.push(Check::skip(
638                        "Remote URL matches",
639                        "n/a in workspace mode (bound by name/id)",
640                    ));
641                }
642            }
643        }
644    }
645
646    out
647}
648
649// --- Sessions ---
650
651/// True for a per-repo `pending-<id>.jsonl` (nonempty id) queue file —
652/// tighter than a bare `starts_with("pending") && ends_with(".jsonl")`
653/// check, which would also match e.g. `pendingfoo.jsonl` or `pending-.jsonl`.
654/// The legacy `pending.jsonl` name is handled separately by callers, since
655/// whether it counts depends on whether there's a bound `repo_id` to
656/// attribute it to (see `count_pending_events`).
657fn is_pending_queue_filename(name: &str) -> bool {
658    crate::commands::flush::repo_id_from_pending_filename(name).is_some()
659}
660
661/// Sum the non-empty lines across every per-repo (and, if `include_legacy`,
662/// legacy) pending queue file in a session directory: `pending.jsonl` and
663/// `pending-<repo_id>.jsonl`.
664///
665/// `include_legacy` should be true only when the project has a bound
666/// `repo_id` (config.toml), since `flush` only drains the legacy
667/// `pending.jsonl` in that case (best-effort attribution). Otherwise a
668/// stray `pending.jsonl` would be counted here but never cleared by
669/// `flush`, leaving `status` permanently reporting stuck events.
670fn count_pending_events(session_dir: &Path, include_legacy: bool) -> usize {
671    let Ok(read) = fs::read_dir(session_dir) else {
672        return 0;
673    };
674
675    read.flatten()
676        .filter(|entry| {
677            entry
678                .file_name()
679                .to_str()
680                .map(|name| {
681                    is_pending_queue_filename(name) || (include_legacy && name == "pending.jsonl")
682                })
683                .unwrap_or(false)
684        })
685        .map(|entry| {
686            fs::read_to_string(entry.path())
687                .unwrap_or_default()
688                .lines()
689                .filter(|l| !l.trim().is_empty())
690                .count()
691        })
692        .sum()
693}
694
695fn session_checks(project_root: &Path) -> Vec<Check> {
696    let sessions_dir = project_root.join(".tracevault/sessions");
697    if !sessions_dir.exists() {
698        return vec![Check::skip(
699            "Pending events",
700            "no .tracevault/sessions/ here (project-local check; a detached worker's queue may live under its own working dir)",
701        )];
702    }
703
704    // The legacy `pending.jsonl` is only drainable by `flush` when there's a
705    // bound `repo_id` to attribute it to (best-effort attribution). Counting
706    // it here otherwise would report events that `flush` can never clear.
707    let include_legacy = TracevaultConfig::load(project_root)
708        .and_then(|c| c.repo_id)
709        .is_some();
710
711    let mut total_sessions = 0usize;
712    let mut sessions_with_pending = 0usize;
713    let mut pending_event_count = 0usize;
714
715    if let Ok(read) = fs::read_dir(&sessions_dir) {
716        for entry in read.flatten() {
717            if !entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
718                continue;
719            }
720            total_sessions += 1;
721            let count = count_pending_events(&entry.path(), include_legacy);
722            if count > 0 {
723                sessions_with_pending += 1;
724                pending_event_count += count;
725            }
726        }
727    }
728
729    vec![if sessions_with_pending == 0 {
730        Check::ok(
731            "Pending events",
732            format!("{total_sessions} session(s), all synced (project-local)"),
733        )
734    } else {
735        Check::warn(
736            "Pending events",
737            format!(
738                "{pending_event_count} event(s) in {sessions_with_pending}/{total_sessions} session(s) — run `tracevault flush`"
739            ),
740        )
741    }]
742}
743
744// --- Git helpers ---
745
746fn git_repo_name(project_root: &Path) -> String {
747    Command::new("git")
748        .args(["rev-parse", "--show-toplevel"])
749        .current_dir(project_root)
750        .output()
751        .ok()
752        .filter(|o| o.status.success())
753        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
754        .as_deref()
755        .and_then(|p| p.rsplit('/').next())
756        .map(String::from)
757        .unwrap_or_else(|| "unknown".into())
758}
759
760fn git_remote_url(project_root: &Path) -> Option<String> {
761    Command::new("git")
762        .args(["remote", "get-url", "origin"])
763        .current_dir(project_root)
764        .output()
765        .ok()
766        .filter(|o| o.status.success())
767        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
768        .filter(|s| !s.is_empty())
769}
770
771/// Make two remote URLs comparable by dropping `.git`, trailing slash, and
772/// collapsing SSH ↔ HTTPS differences for github.com specifically.
773fn normalize_remote(url: &str) -> String {
774    let trimmed = url
775        .trim()
776        .trim_end_matches('/')
777        .trim_end_matches(".git")
778        .to_string();
779
780    // git@github.com:org/repo  ->  github.com/org/repo
781    if let Some(rest) = trimmed.strip_prefix("git@github.com:") {
782        return format!("github.com/{rest}");
783    }
784    // https://github.com/org/repo -> github.com/org/repo
785    for p in ["https://", "http://"] {
786        if let Some(rest) = trimmed.strip_prefix(p) {
787            return rest.to_string();
788        }
789    }
790    trimmed
791}
792
793// --- Entry point ---
794
795/// Resolve the session id for `status`: an explicit `--session-id` wins, else
796/// `$TRACEVAULT_SESSION_ID`; empty strings are ignored (fall through).
797pub fn effective_session_id(arg: Option<String>, env: Option<String>) -> Option<String> {
798    arg.filter(|s| !s.is_empty())
799        .or_else(|| env.filter(|s| !s.is_empty()))
800}
801
802pub async fn run_status(project_root: &Path, session_id: Option<&str>) -> i32 {
803    let auth = resolve_auth();
804
805    // ~/.claude/settings.json — None when the home dir can't be resolved. Do
806    // NOT fall back to a relative `.claude/settings.json`: that would read the
807    // repo's own settings and could report a false "Global install".
808    let global_settings: Option<PathBuf> =
809        dirs::home_dir().map(|h| h.join(".claude").join("settings.json"));
810    let sessions_dir = crate::session_state::sessions_dir();
811
812    let global_check = match global_settings.as_deref() {
813        Some(p) => global_hook_check_in(p),
814        None => Check::skip("Global install", "cannot determine home directory"),
815    };
816    let has_global = global_check.level == Level::Ok;
817
818    // Resolve the workspace binding ONCE: it drives both the section and the
819    // `has_binding` mode signal used by project_checks.
820    let (binding_check, binding) = match sessions_dir.as_deref() {
821        Some(dir) => workspace_binding_check_in(dir, session_id),
822        None => (
823            Check::skip("Workspace binding", "cannot determine session state dir"),
824            None,
825        ),
826    };
827    // A binding only counts as a mode signal when the session was named
828    // explicitly (--session-id / $TRACEVAULT_SESSION_ID). A *scanned* binding
829    // (no session id) is cwd-agnostic and may belong to another repo, so it is
830    // shown for information but must NOT downgrade "not set up" severity nor
831    // drive the server-repo check.
832    let explicit_session = session_id.is_some();
833    let has_binding = binding.is_some() && explicit_session;
834    let authoritative_binding = if explicit_session {
835        binding.as_ref()
836    } else {
837        None
838    };
839
840    let auth_checks_v = auth_checks(&auth).await;
841    let install_v = vec![global_check];
842    let (proj_checks_v, config) = project_checks(
843        project_root,
844        global_settings.as_deref(),
845        has_global,
846        has_binding,
847    );
848    let binding_v = vec![binding_check];
849    let server_checks_v =
850        server_repo_checks(project_root, &auth, config.as_ref(), authoritative_binding).await;
851    let session_checks_v = session_checks(project_root);
852
853    let sections: Vec<(&str, Vec<Check>)> = vec![
854        ("Authentication", auth_checks_v),
855        ("Installation", install_v),
856        ("Project", proj_checks_v),
857        ("Workspace binding", binding_v),
858        ("Server repo", server_checks_v),
859        ("Sessions", session_checks_v),
860    ];
861    for (title, checks) in &sections {
862        print_section(title, checks);
863    }
864    let all: Vec<&Check> = sections.iter().flat_map(|(_, v)| v.iter()).collect();
865
866    let errors = all.iter().filter(|c| c.level == Level::Error).count();
867    let warns = all.iter().filter(|c| c.level == Level::Warn).count();
868
869    match (errors, warns) {
870        (0, 0) => println!("{ANSI_GREEN}All good.{ANSI_RESET}"),
871        (0, w) => println!(
872            "{ANSI_YELLOW}{w} warning{} — no blocking issues.{ANSI_RESET}",
873            if w == 1 { "" } else { "s" }
874        ),
875        (e, 0) => println!(
876            "{ANSI_RED}{e} problem{} found.{ANSI_RESET}",
877            if e == 1 { "" } else { "s" }
878        ),
879        (e, w) => println!(
880            "{ANSI_RED}{e} problem{}, {w} warning{}.{ANSI_RESET}",
881            if e == 1 { "" } else { "s" },
882            if w == 1 { "" } else { "s" }
883        ),
884    }
885
886    exit_code_for(&all)
887}
888
889/// Only `Level::Error` checks force a non-zero exit; `Warn` and `Skip` are
890/// surfaced to the user but don't fail the command. Pulled out as a pure
891/// function so the severity→exit-code mapping is unit-testable independent
892/// of the network-calling `run_status`.
893fn exit_code_for(checks: &[&Check]) -> i32 {
894    if checks.iter().any(|c| c.level == Level::Error) {
895        1
896    } else {
897        0
898    }
899}
900
901#[cfg(test)]
902mod tests {
903    use super::*;
904
905    #[test]
906    fn normalize_remote_ssh_https_equal() {
907        assert_eq!(
908            normalize_remote("git@github.com:VirtusLab/visdom-ai-tracing.git"),
909            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing")
910        );
911        assert_eq!(
912            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing.git/"),
913            "github.com/VirtusLab/visdom-ai-tracing"
914        );
915    }
916
917    #[test]
918    fn normalize_remote_preserves_non_github() {
919        assert_eq!(
920            normalize_remote("git@gitlab.com:foo/bar.git"),
921            "git@gitlab.com:foo/bar"
922        );
923    }
924
925    #[test]
926    fn git_hook_check_missing_file_is_warning() {
927        let dir = tempfile::tempdir().unwrap();
928        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
929        assert_eq!(check.level, Level::Warn);
930    }
931
932    #[test]
933    fn git_hook_check_with_marker_is_ok() {
934        let dir = tempfile::tempdir().unwrap();
935        let hooks = dir.path().join(".git/hooks");
936        std::fs::create_dir_all(&hooks).unwrap();
937        std::fs::write(
938            hooks.join("pre-push"),
939            "#!/bin/sh\n# tracevault:enforce\ntracevault check\n",
940        )
941        .unwrap();
942        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
943        assert_eq!(check.level, Level::Ok);
944    }
945
946    #[test]
947    fn git_hook_check_without_marker_is_warning() {
948        let dir = tempfile::tempdir().unwrap();
949        let hooks = dir.path().join(".git/hooks");
950        std::fs::create_dir_all(&hooks).unwrap();
951        std::fs::write(hooks.join("pre-push"), "#!/bin/sh\necho hi\n").unwrap();
952        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
953        assert_eq!(check.level, Level::Warn);
954    }
955
956    #[test]
957    fn project_checks_errors_without_tracevault_dir_and_no_global_or_binding() {
958        let dir = tempfile::tempdir().unwrap();
959        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
960        let missing_global = dir.path().join("no-global.json");
961        let (checks, cfg) =
962            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
963        assert!(cfg.is_none());
964        assert!(checks
965            .iter()
966            .any(|c| c.level == Level::Error && c.label == "TraceVault initialized"));
967        // The Git-hooks Skip must NOT claim "global/workspace mode" when the
968        // user is truly unconfigured (no global install, no binding).
969        let git_hooks = checks
970            .iter()
971            .find(|c| c.label == "Git hooks")
972            .expect("Git hooks check present");
973        assert_eq!(git_hooks.level, Level::Skip);
974        assert!(
975            !git_hooks.detail.contains("global/workspace mode"),
976            "unconfigured git-hooks detail must not claim global/workspace mode: {}",
977            git_hooks.detail
978        );
979    }
980
981    #[test]
982    fn project_checks_no_tracevault_dir_is_not_error_in_global_mode() {
983        let dir = tempfile::tempdir().unwrap();
984        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
985        let missing_global = dir.path().join("no-global.json");
986        let (checks, _) = project_checks(dir.path(), Some(missing_global.as_path()), true, false);
987        let refs: Vec<&Check> = checks.iter().collect();
988        assert_eq!(
989            exit_code_for(&refs),
990            0,
991            "global mode must not force exit 1 on missing .tracevault/"
992        );
993        assert!(checks
994            .iter()
995            .any(|c| c.label == "TraceVault initialized" && c.level == Level::Skip));
996    }
997
998    #[test]
999    fn project_checks_warns_when_config_toml_missing() {
1000        // Pure workspace/detached-mode user: .tracevault/ exists (or not,
1001        // doesn't matter for this check) but there's no config.toml because
1002        // `tracevault init` was never run. This must be a Warn, not an
1003        // Error, and therefore must not force the process exit code to 1.
1004        let dir = tempfile::tempdir().unwrap();
1005        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1006        std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
1007        let missing_global = dir.path().join("no-global.json");
1008        let (checks, cfg) =
1009            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1010        assert!(cfg.is_none());
1011        let project_config_check = checks
1012            .iter()
1013            .find(|c| c.label == "Project config")
1014            .expect("Project config check present");
1015        assert_eq!(project_config_check.level, Level::Warn);
1016
1017        let refs: Vec<&Check> = checks.iter().collect();
1018        assert_eq!(
1019            exit_code_for(&refs),
1020            0,
1021            "a missing config.toml alone must not force a non-zero exit code"
1022        );
1023    }
1024
1025    #[test]
1026    fn project_checks_errors_on_malformed_config_toml() {
1027        // A config.toml that exists but fails to parse is a genuine error,
1028        // distinct from "no config.toml at all" — it should stay Check::err
1029        // and keep forcing a non-zero exit code.
1030        let dir = tempfile::tempdir().unwrap();
1031        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1032        std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
1033        std::fs::write(
1034            dir.path().join(".tracevault/config.toml"),
1035            "not valid toml {{{",
1036        )
1037        .unwrap();
1038        let missing_global = dir.path().join("no-global.json");
1039        let (checks, cfg) =
1040            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1041        assert!(cfg.is_none());
1042        let project_config_check = checks
1043            .iter()
1044            .find(|c| c.label == "Project config")
1045            .expect("Project config check present");
1046        assert_eq!(project_config_check.level, Level::Error);
1047
1048        let refs: Vec<&Check> = checks.iter().collect();
1049        assert_eq!(exit_code_for(&refs), 1);
1050    }
1051
1052    #[test]
1053    fn exit_code_for_warn_only_is_zero() {
1054        let checks = [
1055            Check::warn("a", ""),
1056            Check::ok("b", ""),
1057            Check::skip("c", ""),
1058        ];
1059        let refs: Vec<&Check> = checks.iter().collect();
1060        assert_eq!(exit_code_for(&refs), 0);
1061    }
1062
1063    #[test]
1064    fn exit_code_for_any_error_is_one() {
1065        let checks = [
1066            Check::ok("a", ""),
1067            Check::err("b", ""),
1068            Check::warn("c", ""),
1069        ];
1070        let refs: Vec<&Check> = checks.iter().collect();
1071        assert_eq!(exit_code_for(&refs), 1);
1072    }
1073
1074    #[test]
1075    fn count_pending_events_sums_across_per_repo_queues() {
1076        let dir = tempfile::tempdir().unwrap();
1077        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1078        std::fs::write(dir.path().join("pending-b.jsonl"), "line1\n").unwrap();
1079        std::fs::write(dir.path().join("pending-c.jsonl"), "").unwrap();
1080        assert_eq!(count_pending_events(dir.path(), false), 3);
1081        assert_eq!(count_pending_events(dir.path(), true), 3);
1082    }
1083
1084    #[test]
1085    fn count_pending_events_ignores_unrelated_files() {
1086        let dir = tempfile::tempdir().unwrap();
1087        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\n").unwrap();
1088        std::fs::write(dir.path().join("notes.txt"), "line1\nline2\n").unwrap();
1089        assert_eq!(count_pending_events(dir.path(), false), 1);
1090    }
1091
1092    #[test]
1093    fn count_pending_events_zero_for_empty_dir() {
1094        let dir = tempfile::tempdir().unwrap();
1095        assert_eq!(count_pending_events(dir.path(), false), 0);
1096        assert_eq!(count_pending_events(dir.path(), true), 0);
1097    }
1098
1099    #[test]
1100    fn is_pending_queue_filename_matches_per_repo_only() {
1101        assert!(!is_pending_queue_filename("pending.jsonl"));
1102        assert!(is_pending_queue_filename("pending-a.jsonl"));
1103    }
1104
1105    #[test]
1106    fn is_pending_queue_filename_rejects_lookalikes() {
1107        assert!(!is_pending_queue_filename("pendingfoo.jsonl"));
1108        assert!(!is_pending_queue_filename("pending-.jsonl"));
1109    }
1110
1111    #[test]
1112    fn count_pending_events_legacy_pending_jsonl_requires_include_legacy() {
1113        let dir = tempfile::tempdir().unwrap();
1114        std::fs::write(dir.path().join("pending.jsonl"), "line1\nline2\n").unwrap();
1115        assert_eq!(
1116            count_pending_events(dir.path(), false),
1117            0,
1118            "legacy pending.jsonl must not be counted when there's no bound repo_id"
1119        );
1120        assert_eq!(
1121            count_pending_events(dir.path(), true),
1122            2,
1123            "legacy pending.jsonl counts once a repo_id is bound"
1124        );
1125    }
1126
1127    #[test]
1128    fn count_pending_events_legacy_and_per_repo_both_count_when_included() {
1129        let dir = tempfile::tempdir().unwrap();
1130        std::fs::write(dir.path().join("pending.jsonl"), "line1\n").unwrap();
1131        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1132        assert_eq!(count_pending_events(dir.path(), false), 2);
1133        assert_eq!(count_pending_events(dir.path(), true), 3);
1134    }
1135
1136    #[test]
1137    fn count_pending_events_ignores_lookalike_filenames() {
1138        let dir = tempfile::tempdir().unwrap();
1139        std::fs::write(dir.path().join("pendingfoo.jsonl"), "line1\n").unwrap();
1140        std::fs::write(dir.path().join("pending-.jsonl"), "line1\n").unwrap();
1141        assert_eq!(count_pending_events(dir.path(), false), 0);
1142        assert_eq!(count_pending_events(dir.path(), true), 0);
1143    }
1144
1145    #[test]
1146    fn settings_has_tracevault_hooks_detects_commands() {
1147        assert!(settings_has_tracevault_hooks(
1148            r#"{"hooks":{"PreToolUse":[{"hooks":[{"command":"tracevault stream --event pre"}]}]}}"#
1149        ));
1150        assert!(settings_has_tracevault_hooks(
1151            r#"{"command":"tracevault session-start"}"#
1152        ));
1153        assert!(settings_has_tracevault_hooks(
1154            r#"{"command":"tracevault user-prompt"}"#
1155        ));
1156        assert!(!settings_has_tracevault_hooks(
1157            r#"{"hooks":{"PreToolUse":[]}}"#
1158        ));
1159        assert!(!settings_has_tracevault_hooks("{}"));
1160    }
1161
1162    #[test]
1163    fn global_hook_check_ok_when_present() {
1164        let dir = tempfile::tempdir().unwrap();
1165        let p = dir.path().join("settings.json");
1166        std::fs::write(
1167            &p,
1168            r#"{"hooks":{"SessionStart":[{"hooks":[{"command":"tracevault session-start"}]}]}}"#,
1169        )
1170        .unwrap();
1171        assert_eq!(global_hook_check_in(&p).level, Level::Ok);
1172    }
1173
1174    #[test]
1175    fn global_hook_check_skip_when_absent_or_no_hooks() {
1176        let dir = tempfile::tempdir().unwrap();
1177        let missing = dir.path().join("settings.json");
1178        assert_eq!(global_hook_check_in(&missing).level, Level::Skip);
1179        let empty = dir.path().join("empty.json");
1180        std::fs::write(&empty, "{}").unwrap();
1181        assert_eq!(global_hook_check_in(&empty).level, Level::Skip);
1182    }
1183
1184    #[test]
1185    fn global_hook_check_warns_when_unreadable() {
1186        // A path that exists but isn't a readable file (a directory) yields a
1187        // non-NotFound read error → Warn, not a false "no settings.json" Skip.
1188        let dir = tempfile::tempdir().unwrap();
1189        let as_dir = dir.path().join("settings.json");
1190        std::fs::create_dir(&as_dir).unwrap();
1191        let check = global_hook_check_in(&as_dir);
1192        assert_eq!(check.level, Level::Warn);
1193        assert!(
1194            check.detail.contains("cannot read"),
1195            "detail: {}",
1196            check.detail
1197        );
1198    }
1199
1200    #[test]
1201    fn claude_hook_check_ok_from_global_only() {
1202        let dir = tempfile::tempdir().unwrap();
1203        let repo = dir.path().join("repo-settings.json"); // does not exist
1204        let global = dir.path().join("global-settings.json");
1205        std::fs::write(&global, r#"{"command":"tracevault stream"}"#).unwrap();
1206        let c = claude_hook_check_in(&repo, Some(global.as_path()));
1207        assert_eq!(c.level, Level::Ok);
1208        assert!(
1209            c.detail.to_lowercase().contains("global") || c.detail.contains("~/.claude"),
1210            "detail: {}",
1211            c.detail
1212        );
1213    }
1214
1215    #[test]
1216    fn claude_hook_check_ok_from_repo() {
1217        let dir = tempfile::tempdir().unwrap();
1218        let repo = dir.path().join("repo-settings.json");
1219        std::fs::write(&repo, r#"{"command":"tracevault stream"}"#).unwrap();
1220        let global = dir.path().join("global-settings.json"); // does not exist
1221        assert_eq!(
1222            claude_hook_check_in(&repo, Some(global.as_path())).level,
1223            Level::Ok
1224        );
1225    }
1226
1227    #[test]
1228    fn claude_hook_check_no_global_path_uses_repo_only() {
1229        // When the home dir can't be resolved (global_settings = None), only the
1230        // repo settings are consulted — never a relative fallback.
1231        let dir = tempfile::tempdir().unwrap();
1232        let repo = dir.path().join("repo-settings.json");
1233        std::fs::write(&repo, r#"{"command":"tracevault stream"}"#).unwrap();
1234        assert_eq!(claude_hook_check_in(&repo, None).level, Level::Ok);
1235
1236        let missing = dir.path().join("nope.json");
1237        assert_eq!(claude_hook_check_in(&missing, None).level, Level::Warn);
1238    }
1239
1240    #[test]
1241    fn claude_hook_check_warn_when_neither() {
1242        let dir = tempfile::tempdir().unwrap();
1243        let c = claude_hook_check_in(
1244            &dir.path().join("a.json"),
1245            Some(dir.path().join("b.json").as_path()),
1246        );
1247        assert_eq!(c.level, Level::Warn);
1248    }
1249
1250    #[test]
1251    fn claude_hook_check_warns_when_repo_settings_unreadable() {
1252        let dir = tempfile::tempdir().unwrap();
1253        let repo = dir.path().join("repo-settings.json");
1254        std::fs::create_dir(&repo).unwrap(); // directory-as-file → non-NotFound read error
1255        let global = dir.path().join("global.json"); // missing
1256        let c = claude_hook_check_in(&repo, Some(global.as_path()));
1257        assert_eq!(c.level, Level::Warn);
1258        assert!(c.detail.contains("cannot read"), "detail: {}", c.detail);
1259    }
1260
1261    #[test]
1262    fn tracevault_init_check_severity_matrix() {
1263        assert_eq!(tracevault_init_check(true, false, false).level, Level::Ok); // present → Ok
1264        assert_eq!(tracevault_init_check(false, true, false).level, Level::Skip); // absent + global → Skip
1265        assert_eq!(tracevault_init_check(false, false, true).level, Level::Skip); // absent + binding → Skip
1266        assert_eq!(tracevault_init_check(false, true, true).level, Level::Skip);
1267        assert_eq!(
1268            tracevault_init_check(false, false, false).level,
1269            Level::Error
1270        ); // nothing → Error
1271    }
1272
1273    #[test]
1274    fn workspace_binding_explicit_id_with_binding_is_ok() {
1275        let dir = tempfile::tempdir().unwrap();
1276        let st = crate::session_state::SessionState {
1277            active: Some(crate::session_state::RepoBinding {
1278                org_slug: "acme".into(),
1279                repo_id: "11111111-1111-4111-8111-111111111111".into(),
1280                git_url: None,
1281                updated_at: "t".into(),
1282            }),
1283            ..Default::default()
1284        };
1285        std::fs::write(
1286            dir.path().join("sess-9.toml"),
1287            toml::to_string(&st).unwrap(),
1288        )
1289        .unwrap();
1290        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-9"));
1291        assert_eq!(check.level, Level::Ok);
1292        assert!(check.detail.contains("acme"), "detail: {}", check.detail);
1293        assert_eq!(
1294            binding.unwrap().repo_id,
1295            "11111111-1111-4111-8111-111111111111"
1296        );
1297    }
1298
1299    #[test]
1300    fn workspace_binding_explicit_id_without_binding_is_warn() {
1301        let dir = tempfile::tempdir().unwrap();
1302        std::fs::write(
1303            dir.path().join("sess-empty.toml"),
1304            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
1305        )
1306        .unwrap();
1307        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-empty"));
1308        assert_eq!(check.level, Level::Warn);
1309        assert!(binding.is_none());
1310    }
1311
1312    #[test]
1313    fn workspace_binding_no_id_empty_dir_is_skip() {
1314        let dir = tempfile::tempdir().unwrap();
1315        let (check, binding) = workspace_binding_check_in(dir.path(), None);
1316        assert_eq!(check.level, Level::Skip);
1317        assert!(binding.is_none());
1318    }
1319
1320    #[test]
1321    fn workspace_binding_no_id_scans_latest() {
1322        let dir = tempfile::tempdir().unwrap();
1323        // Two sessions; the one written LAST should be picked by the mtime scan.
1324        let older = crate::session_state::SessionState {
1325            active: Some(crate::session_state::RepoBinding {
1326                org_slug: "o1".into(),
1327                repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
1328                git_url: None,
1329                updated_at: "t".into(),
1330            }),
1331            ..Default::default()
1332        };
1333        std::fs::write(
1334            dir.path().join("old.toml"),
1335            toml::to_string(&older).unwrap(),
1336        )
1337        .unwrap();
1338        // Ensure a distinct, later mtime for the second file.
1339        std::thread::sleep(std::time::Duration::from_millis(20));
1340        let newer = crate::session_state::SessionState {
1341            active: Some(crate::session_state::RepoBinding {
1342                org_slug: "o2".into(),
1343                repo_id: "bbbbbbbb-2222-4222-8222-222222222222".into(),
1344                git_url: None,
1345                updated_at: "t".into(),
1346            }),
1347            ..Default::default()
1348        };
1349        std::fs::write(
1350            dir.path().join("new.toml"),
1351            toml::to_string(&newer).unwrap(),
1352        )
1353        .unwrap();
1354        let (check, binding) = workspace_binding_check_in(dir.path(), None);
1355        assert_eq!(check.level, Level::Ok);
1356        assert_eq!(
1357            binding.unwrap().org_slug,
1358            "o2",
1359            "must pick the most-recently-modified session"
1360        );
1361    }
1362
1363    #[test]
1364    fn workspace_binding_scan_skips_newest_without_binding() {
1365        // The most-recently-touched session has NO active binding, but an older
1366        // one does — the scan must find the older binding, not stop at the newest.
1367        let dir = tempfile::tempdir().unwrap();
1368        let with_binding = crate::session_state::SessionState {
1369            active: Some(crate::session_state::RepoBinding {
1370                org_slug: "has-it".into(),
1371                repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
1372                git_url: None,
1373                updated_at: "t".into(),
1374            }),
1375            ..Default::default()
1376        };
1377        std::fs::write(
1378            dir.path().join("older.toml"),
1379            toml::to_string(&with_binding).unwrap(),
1380        )
1381        .unwrap();
1382        std::thread::sleep(std::time::Duration::from_millis(20));
1383        // Newest file: no active binding.
1384        std::fs::write(
1385            dir.path().join("newest.toml"),
1386            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
1387        )
1388        .unwrap();
1389        let (check, binding) = workspace_binding_check_in(dir.path(), None);
1390        assert_eq!(check.level, Level::Ok);
1391        assert_eq!(binding.unwrap().org_slug, "has-it");
1392    }
1393
1394    #[test]
1395    fn workspace_binding_scan_no_active_binding_is_skip_not_warn() {
1396        // A session file exists but has no active binding (e.g. a bound-mode
1397        // user with a stray session). Scan mode must Skip, not Warn.
1398        let dir = tempfile::tempdir().unwrap();
1399        std::fs::write(
1400            dir.path().join("stray.toml"),
1401            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
1402        )
1403        .unwrap();
1404        let (check, binding) = workspace_binding_check_in(dir.path(), None);
1405        assert_eq!(check.level, Level::Skip);
1406        assert!(binding.is_none());
1407    }
1408
1409    #[test]
1410    fn server_repo_lookup_prefers_config_by_name() {
1411        let m = server_repo_lookup(Some("acme"), "myrepo", None).unwrap();
1412        assert_eq!(
1413            m,
1414            ("acme".to_string(), RepoMatch::ByName("myrepo".to_string()))
1415        );
1416    }
1417
1418    #[test]
1419    fn server_repo_lookup_falls_back_to_binding_by_id() {
1420        let b = crate::session_state::RepoBinding {
1421            org_slug: "visdom".into(),
1422            repo_id: "rid-1".into(),
1423            git_url: None,
1424            updated_at: "t".into(),
1425        };
1426        let m = server_repo_lookup(None, "ignored", Some(&b)).unwrap();
1427        assert_eq!(
1428            m,
1429            ("visdom".to_string(), RepoMatch::ById("rid-1".to_string()))
1430        );
1431    }
1432
1433    #[test]
1434    fn server_repo_lookup_none_when_neither() {
1435        assert!(server_repo_lookup(None, "x", None).is_none());
1436    }
1437
1438    #[test]
1439    fn effective_session_id_arg_wins_and_filters_empty() {
1440        assert_eq!(
1441            effective_session_id(Some("a".into()), Some("b".into())),
1442            Some("a".into())
1443        );
1444        assert_eq!(
1445            effective_session_id(Some("".into()), Some("b".into())),
1446            Some("b".into())
1447        );
1448        assert_eq!(
1449            effective_session_id(Some("   ".into()), None).as_deref(),
1450            Some("   ")
1451        ); // non-empty whitespace is a real (if odd) id — NOT filtered
1452        assert_eq!(effective_session_id(None, Some("".into())), None);
1453        assert_eq!(effective_session_id(None, None), None);
1454    }
1455}