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