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::{Credential, Credentials};
10use crate::program::{CLI, ENV, TOP};
11use crate::resolution::{
12    effective_project, git_remote_url, resolve_effective_project, ProjectResolveInputs,
13    ProjectSource,
14};
15use std::fs;
16use std::path::{Path, PathBuf};
17
18const ANSI_GREEN: &str = "\x1b[32m";
19const ANSI_RED: &str = "\x1b[31m";
20const ANSI_YELLOW: &str = "\x1b[33m";
21const ANSI_DIM: &str = "\x1b[2m";
22const ANSI_RESET: &str = "\x1b[0m";
23
24/// Severity classification of a single check. Anything at `Error` level
25/// bumps the final exit code to 1.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27enum Level {
28    Ok,
29    Warn,
30    Error,
31    /// Check skipped because a prerequisite failed (e.g. can't validate
32    /// token if no token was found). Does not affect exit code.
33    Skip,
34}
35
36#[derive(Debug)]
37struct Check {
38    label: String,
39    level: Level,
40    detail: String,
41}
42
43impl Check {
44    fn ok(label: impl Into<String>, detail: impl Into<String>) -> Self {
45        Self {
46            label: label.into(),
47            level: Level::Ok,
48            detail: detail.into(),
49        }
50    }
51    fn warn(label: impl Into<String>, detail: impl Into<String>) -> Self {
52        Self {
53            label: label.into(),
54            level: Level::Warn,
55            detail: detail.into(),
56        }
57    }
58    fn err(label: impl Into<String>, detail: impl Into<String>) -> Self {
59        Self {
60            label: label.into(),
61            level: Level::Error,
62            detail: detail.into(),
63        }
64    }
65    fn skip(label: impl Into<String>, detail: impl Into<String>) -> Self {
66        Self {
67            label: label.into(),
68            level: Level::Skip,
69            detail: detail.into(),
70        }
71    }
72}
73
74fn marker(l: Level) -> &'static str {
75    match l {
76        Level::Ok => "\x1b[32m✓\x1b[0m",
77        Level::Warn => "\x1b[33m!\x1b[0m",
78        Level::Error => "\x1b[31m✗\x1b[0m",
79        Level::Skip => "\x1b[2m·\x1b[0m",
80    }
81}
82
83fn print_section(title: &str, checks: &[Check]) {
84    println!("{ANSI_DIM}──{ANSI_RESET} {title}");
85    for c in checks {
86        if c.detail.is_empty() {
87            println!("  {} {}", marker(c.level), c.label);
88        } else {
89            println!(
90                "  {} {:<32} {ANSI_DIM}{}{ANSI_RESET}",
91                marker(c.level),
92                c.label,
93                c.detail
94            );
95        }
96    }
97    println!();
98}
99
100// --- Authentication ---
101
102struct AuthContext {
103    server_url: Option<String>,
104    /// The resolved credential, if any. Cloned per client construction
105    /// because a Keycloak session may be refreshed by the checks below.
106    credential: Option<Credential>,
107    source: &'static str, // "env", "credentials", or "none"
108    email_from_creds: Option<String>,
109    /// `(file's server_url, TRACEVAULT_SERVER_URL)` when the saved credential
110    /// is for a different instance than the env var targets.
111    ///
112    /// This inspector deliberately reports the FILE's URL (that is the
113    /// credential it validates), so without this field `status` would print a
114    /// green "Logged in" while every other command refuses to run — the exact
115    /// situation someone runs `status` to diagnose.
116    url_override_mismatch: Option<(String, String)>,
117}
118
119/// `config_server_url`/`config_api_key` are the lowest rung, mirroring
120/// `credentials::resolve_credentials`. Without them this inspector reported a
121/// repo authenticated purely through `.visdom/tracing.toml` as "no
122/// credentials found" and exited non-zero, while every command using that same
123/// config worked — the inspector called a working setup broken.
124fn resolve_auth(config_server_url: Option<&str>, config_api_key: Option<&str>) -> AuthContext {
125    // Env var wins. Match the server-side resolution order in
126    // resolve_credentials (env > creds), except we treat the env var as
127    // authoritative without looking at the credentials file email.
128    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
129    let env_url = std::env::var("TRACEVAULT_SERVER_URL").ok();
130
131    if let Some(token) = env_key {
132        return AuthContext {
133            // `.or(config)` because `resolve_credentials` resolves the URL and
134            // the credential independently: an env key with the URL pinned only
135            // in the config is a working setup, not "no server URL".
136            server_url: env_url.or_else(|| config_server_url.map(str::to_string)),
137            credential: Some(Credential::ApiKey(token)),
138            source: if crate::program::is_visdom() {
139                "env (VISDOM_API_KEY)"
140            } else {
141                "env (TRACEVAULT_API_KEY)"
142            },
143            email_from_creds: None,
144            // An explicitly supplied API key may target any URL by design.
145            url_override_mismatch: None,
146        };
147    }
148
149    let creds = Credentials::load();
150    if let Some(c) = creds {
151        let source = match &c.auth {
152            Some(_) => "credentials file (Keycloak session)",
153            None => "credentials file (API key)",
154        };
155        // Any credential read from the FILE is instance-bound — a `tvk_` key as
156        // much as a Keycloak session (see `api_client::resolve_credentials`,
157        // which refuses this pairing for both).
158        let url_override_mismatch = env_url.filter(|env| {
159            c.credential().is_some() && !crate::credentials::same_server(&c.server_url, env)
160        });
161        return AuthContext {
162            server_url: Some(c.server_url.clone()),
163            credential: c.credential(),
164            source,
165            // An empty email means a login saved credentials before
166            // `/auth/me` could resolve the identity (e.g. the account lacks
167            // a `tracevault` grant); there is nothing to compare against.
168            email_from_creds: Some(c.email).filter(|e| !e.is_empty()),
169            url_override_mismatch: url_override_mismatch.map(|env| (c.server_url, env)),
170        };
171    }
172
173    // Lowest rung: a hand-authored `config.toml` may carry `api_key` and
174    // `server_url`. Only reached when the env and the credentials file yielded
175    // nothing, exactly as in `resolve_credentials`.
176    AuthContext {
177        server_url: env_url.or_else(|| config_server_url.map(str::to_string)),
178        credential: config_api_key.map(|k| Credential::ApiKey(k.to_string())),
179        source: if config_api_key.is_some() {
180            "project config (.visdom/tracing.toml)"
181        } else {
182            "none"
183        },
184        email_from_creds: None,
185        url_override_mismatch: None,
186    }
187}
188
189async fn auth_checks(auth: &AuthContext, config_server_url: Option<&str>) -> Vec<Check> {
190    let mut out = Vec::new();
191
192    match (auth.credential.as_ref(), auth.server_url.as_ref()) {
193        (None, _) => {
194            out.push(Check::err(
195                "Logged in",
196                crate::program::say(
197                    "no credentials found. Run `tracevault login --server-url <URL>`.",
198                ),
199            ));
200            out.push(Check::skip("Token valid", "no token to check"));
201            return out;
202        }
203        (Some(_), None) => {
204            out.push(Check::err(
205                "Logged in",
206                crate::program::say("token found but no server URL (set TRACEVAULT_SERVER_URL)"),
207            ));
208            out.push(Check::skip("Token valid", "no server URL to call"));
209            return out;
210        }
211        (Some(_), Some(url)) => {
212            out.push(Check::ok("Logged in", format!("{url} via {}", auth.source)));
213        }
214    }
215
216    // Reported as an ERROR, not a warning: in this state every command that
217    // needs auth refuses to run (see `api_client::resolve_credentials`), so
218    // "everything is fine except this note" would be misleading.
219    if let Some((file_url, env_url)) = &auth.url_override_mismatch {
220        out.push(Check::err(
221            "Server URL",
222            format!(
223                "{ENV}_SERVER_URL is '{env_url}' but the saved login is for '{file_url}'. \
224                 Commands will refuse to run rather than send that session's token to another \
225                 instance. Unset {ENV}_SERVER_URL, or run `{TOP} login --server-url \
226                 {env_url}`."
227            ),
228        ));
229    }
230
231    // Reported as a WARNING, not an error: unlike the override above, commands
232    // still run — they just use the login's instance while the repo's config
233    // says otherwise. Without this the inspector is actively misleading: it
234    // reads only the credentials file, so it would print a green "Logged in"
235    // against a URL the repo never asked for. Shares
236    // `credentials::config_url_conflict` with the resolution itself so the two
237    // cannot drift apart.
238    if let Some((file_url, config_url)) = crate::credentials::config_url_conflict(
239        config_server_url,
240        auth.server_url.as_deref(),
241        std::env::var("TRACEVAULT_SERVER_URL").is_ok(),
242    ) {
243        out.push(Check::warn(
244            "Server URL",
245            format!(
246                ".visdom/tracing.toml pins '{config_url}' but the saved login is for \
247                 '{file_url}'. The config URL is ignored — commands use '{file_url}'. Run \
248                 `{TOP} login --server-url {config_url}` to use the repo's instance, or \
249                 remove `server_url` from .visdom/tracing.toml."
250            ),
251        ));
252    }
253
254    let server_url = auth.server_url.as_ref().unwrap();
255    let client = ApiClient::with_credential(server_url, auth.credential.clone());
256    match client.get_me().await {
257        Ok(me) => {
258            let who = me.name.unwrap_or_else(|| me.email.clone());
259            let detail = match &me.role {
260                Some(role) => format!("{who} <{}> (role: {role})", me.email),
261                None => format!("{who} <{}>", me.email),
262            };
263            out.push(Check::ok("Token valid", detail));
264
265            if let Some(cached) = &auth.email_from_creds {
266                if cached != &me.email {
267                    out.push(Check::warn(
268                        "Credentials cache",
269                        format!(
270                            "cached email '{cached}' differs from server '{}' — re-run login",
271                            me.email
272                        ),
273                    ));
274                }
275            }
276        }
277        Err(GetMeError::Unauthorized) => {
278            out.push(Check::err(
279                "Token valid",
280                crate::program::say(
281                    "rejected by server (expired or revoked). Run `tracevault login` again.",
282                ),
283            ));
284        }
285        // A valid token whose account isn't authorized. Re-running login
286        // would NOT help, so this must not say "log in again".
287        Err(GetMeError::Forbidden(_)) => {
288            out.push(Check::err(
289                "Account authorized",
290                "the token is valid but this account has no `tracevault` grant in Control Plane — \
291                 ask an administrator to grant it (or the `ai-tracing-admin` realm role).",
292            ));
293        }
294        Err(GetMeError::Network(msg)) => {
295            out.push(Check::warn(
296                "Server reachable",
297                format!("{msg} — cannot confirm token validity"),
298            ));
299        }
300        Err(GetMeError::Server(msg)) => {
301            out.push(Check::warn("Token valid", format!("server error: {msg}")));
302        }
303    }
304    out
305}
306
307// --- Project ---
308
309/// Subset of project checks that don't need network. Returns the loaded
310/// config if present so later sections can reuse it.
311fn project_checks(
312    project_root: &Path,
313    global_settings: Option<&Path>,
314    has_global: bool,
315    has_binding: bool,
316) -> (Vec<Check>, Option<TracevaultConfig>) {
317    let mut out = Vec::new();
318
319    let is_git = project_root.join(".git").exists();
320    if is_git {
321        out.push(Check::ok(
322            "Git repository",
323            project_root.display().to_string(),
324        ));
325    } else if has_global || has_binding {
326        out.push(Check::skip(
327            "Git repository",
328            "not a git repo (global/workspace mode)",
329        ));
330    } else {
331        out.push(Check::err(
332            "Git repository",
333            "current directory is not a git repo",
334        ));
335    }
336
337    let tv_present = crate::layout::is_set_up(project_root);
338    out.push(tracevault_init_check(tv_present, has_global, has_binding));
339
340    // Distinguish "no config.toml" (expected in workspace/detached mode —
341    // just a warning) from "config.toml present but malformed" (a genuine
342    // error) via `try_load`, rather than the lenient `load` which collapses
343    // both cases to `None`.
344    let config = match TracevaultConfig::try_load(project_root) {
345        Ok(Some(c)) => {
346            let url = c.server_url.as_deref().unwrap_or("<unset>");
347            out.push(Check::ok("Project config", format!("server={url}")));
348            Some(c)
349        }
350        Ok(None) => {
351            if tv_present {
352                out.push(Check::warn(
353                    "Project config",
354                    crate::program::say("No .visdom/tracing.toml — run `tracevault init`, or use workspace mode (`tracevault repo status`)."),
355                ));
356            }
357            None
358        }
359        Err(e) => {
360            out.push(Check::err(
361                "Project config",
362                format!(".visdom/tracing.toml malformed: {e}"),
363            ));
364            None
365        }
366    };
367
368    if tv_present {
369        // Hooks — presence of our markers, not just existence of the hook file.
370        out.push(git_hook_check(
371            project_root,
372            "pre-push",
373            "# tracevault:enforce",
374        ));
375        out.push(git_hook_check(
376            project_root,
377            "post-commit",
378            "# tracevault:post-commit",
379        ));
380    } else if has_global || has_binding {
381        out.push(Check::skip(
382            "Git hooks",
383            "not used in global/workspace mode",
384        ));
385    } else {
386        out.push(Check::skip(
387            "Git hooks",
388            crate::program::say("not installed (no .visdom/ — run `tracevault init`)"),
389        ));
390    }
391
392    out.push(claude_hook_check_in(
393        &project_root.join(".claude"),
394        global_settings,
395    ));
396
397    (out, config)
398}
399
400fn git_hook_check(project_root: &Path, name: &str, marker: &str) -> Check {
401    let path = project_root.join(".git/hooks").join(name);
402    let label = format!("Git hook: {name}");
403    if !path.exists() {
404        return Check::warn(
405            label,
406            format!(".git/hooks/{name} missing — rerun `{TOP} init`"),
407        );
408    }
409    match fs::read_to_string(&path) {
410        Ok(s) if crate::commands::init::has_marker(&s, marker) => Check::ok(label, "installed"),
411        Ok(_) => Check::warn(
412            label,
413            format!("{name} exists but has no Visdom block — rerun `{TOP} init`"),
414        ),
415        Err(e) => Check::warn(label, format!("cannot read hook: {e}")),
416    }
417}
418
419/// True if a Claude settings.json body wires any tracevault hook command.
420fn settings_has_tracevault_hooks(contents: &str) -> bool {
421    [crate::program::TRACEVAULT, crate::program::VISDOM_TRACE]
422        .iter()
423        .any(|cli| {
424            ["stream", "session-start", "user-prompt"]
425                .iter()
426                .any(|sub| contents.contains(&format!("{cli} {sub}")))
427        })
428}
429
430/// Whether a Claude `settings.json` wires tracevault hooks — distinguishing a
431/// genuinely-absent file from one that exists but can't be read, so an
432/// IO/permission error isn't silently reported as "not installed".
433enum SettingsHooks {
434    Present,
435    NoHooks,
436    Missing,
437    Unreadable(String),
438}
439
440fn read_settings_hooks(path: &Path) -> SettingsHooks {
441    match fs::read_to_string(path) {
442        Ok(s) if settings_has_tracevault_hooks(&s) => SettingsHooks::Present,
443        Ok(_) => SettingsHooks::NoHooks,
444        Err(e) if e.kind() == std::io::ErrorKind::NotFound => SettingsHooks::Missing,
445        Err(e) => SettingsHooks::Unreadable(e.to_string()),
446    }
447}
448
449/// Check a global `~/.claude/settings.json` for the `init --global` install.
450/// Absent / no tracevault hooks → Skip (a global install is optional); an
451/// existing-but-unreadable file → Warn (don't hide a permission/IO problem).
452fn global_hook_check_in(settings_path: &Path) -> Check {
453    match read_settings_hooks(settings_path) {
454        SettingsHooks::Present => Check::ok(
455            "Global install",
456            "hooks installed in ~/.claude/settings.json",
457        ),
458        SettingsHooks::NoHooks => Check::skip(
459            "Global install",
460            crate::program::say("~/.claude/settings.json has no tracevault hooks"),
461        ),
462        SettingsHooks::Missing => Check::skip("Global install", "no ~/.claude/settings.json"),
463        SettingsHooks::Unreadable(e) => Check::warn(
464            "Global install",
465            format!("cannot read ~/.claude/settings.json: {e}"),
466        ),
467    }
468}
469
470/// Whether Claude Code's cost reaches Visdom over OpenTelemetry
471/// (`init --claude-telemetry`), read from `~/.claude/settings.json` and this
472/// process's `OTEL_*` environment. Off or exported elsewhere → Skip (both are
473/// legitimate); an incomplete install, one for another server than the login,
474/// or our token also going to someone else's exporter → Warn.
475fn claude_telemetry_check_in(
476    settings_path: &Path,
477    server_url: Option<&str>,
478    env: &crate::commands::claude_telemetry::Environment,
479) -> Check {
480    use crate::commands::claude_telemetry::{inspect, logs_endpoint, TelemetryState};
481    const LABEL: &str = "Claude Code telemetry";
482    let settings = match fs::read_to_string(settings_path) {
483        Ok(s) => match serde_json::from_str::<serde_json::Value>(&s) {
484            Ok(v) => v,
485            Err(e) => {
486                return Check::warn(LABEL, format!("cannot parse ~/.claude/settings.json: {e}"))
487            }
488        },
489        Err(e) if e.kind() == std::io::ErrorKind::NotFound => serde_json::json!({}),
490        Err(e) => return Check::warn(LABEL, format!("cannot read ~/.claude/settings.json: {e}")),
491    };
492    let expected = server_url.map(logs_endpoint);
493    match inspect(&settings, env, expected.as_deref()) {
494        TelemetryState::Off => Check::skip(
495            LABEL,
496            crate::program::say("off (enable with `tracevault telemetry on`)"),
497        ),
498        TelemetryState::Foreign { reasons, ours_too } => {
499            let detail = format!("exported elsewhere: {}", reasons.join("; "));
500            if ours_too {
501                Check::warn(
502                    LABEL,
503                    format!(
504                        "{detail} — these exporters also receive Visdom's otel-headers \
505                         token; remove them or Visdom's otelHeadersHelper"
506                    ),
507                )
508            } else {
509                Check::skip(LABEL, format!("{detail} (see README: collector route)"))
510            }
511        }
512        TelemetryState::Ours { missing, .. } if !missing.is_empty() => Check::warn(
513            LABEL,
514            format!(
515                "incomplete ({} missing or changed): re-run `{TOP} init --claude-telemetry`",
516                missing.join(", ")
517            ),
518        ),
519        TelemetryState::Ours { endpoint, .. } => {
520            let endpoint = endpoint.unwrap_or_default();
521            match expected {
522                Some(expected) if expected != endpoint => Check::warn(
523                    LABEL,
524                    format!(
525                        "exports to {endpoint}, but you are logged in to {}: re-run \
526                         `{TOP} init --claude-telemetry`",
527                        server_url.unwrap_or_default()
528                    ),
529                ),
530                _ => Check::ok(LABEL, format!("exports cost to {endpoint}")),
531            }
532        }
533    }
534}
535
536/// Add what the install state knows to the telemetry check (VIS-1109): that
537/// the user opted out (so it stays off across upgrades), or that an upgrade
538/// turned it on without being asked.
539fn with_telemetry_choice(mut check: Check, state: &crate::install_state::InstallState) -> Check {
540    match check.level {
541        Level::Skip if state.claude_telemetry_opt_out && check.detail.starts_with("off") => {
542            check.detail = crate::program::say(
543                "off — you opted out, upgrades keep it off (`tracevault telemetry on` to enable)",
544            )
545            .to_string();
546        }
547        Level::Ok => {
548            if let Some(version) = &state.telemetry_auto_enabled {
549                check.detail.push_str(&format!(
550                    " — turned on automatically by the upgrade to {version} \
551                     (`{CLI} telemetry off` to disable)"
552                ));
553            }
554        }
555        _ => {}
556    }
557    check
558}
559
560/// The telemetry check as `status` shows it, on one line, for `tracevault
561/// telemetry status`.
562pub fn telemetry_status_line(server_url: Option<&str>) -> String {
563    let Some(settings) = dirs::home_dir().map(|h| h.join(".claude").join("settings.json")) else {
564        return "Claude Code telemetry: cannot determine home directory".to_string();
565    };
566    let check = with_telemetry_choice(
567        claude_telemetry_check_in(
568            &settings,
569            server_url,
570            &crate::commands::claude_telemetry::Environment::current(
571                settings.parent().unwrap_or(&settings),
572            ),
573        ),
574        &crate::install_state::load_in(&crate::config::tv_config_root()),
575    );
576    format!("{}: {}", check.label, check.detail)
577}
578
579/// The per-repo Claude settings files `init` can write hooks into
580/// (`--claude-settings shared|local`), in the order they are reported.
581const REPO_CLAUDE_SETTINGS: [&str; 2] = ["settings.json", "settings.local.json"];
582
583/// Claude Code hooks may live per-repo (`<repo>/.claude/settings.json` or
584/// `settings.local.json`, per `init --claude-settings`) OR globally
585/// (`~/.claude/settings.json`, `init --global`). Ok if ANY of them wires
586/// tracevault; an existing-but-unreadable settings file is surfaced as a Warn
587/// with the path (not a generic "not registered"); Warn if none wires it.
588fn claude_hook_check_in(repo_claude_dir: &Path, global_settings: Option<&Path>) -> Check {
589    let repo: Vec<(&str, SettingsHooks)> = REPO_CLAUDE_SETTINGS
590        .iter()
591        .map(|name| (*name, read_settings_hooks(&repo_claude_dir.join(name))))
592        .collect();
593    if let Some((name, _)) = repo
594        .iter()
595        .find(|(_, h)| matches!(h, SettingsHooks::Present))
596    {
597        return Check::ok("Claude Code hooks", format!("registered in .claude/{name}"));
598    }
599    let global = global_settings.map(read_settings_hooks);
600    if matches!(global, Some(SettingsHooks::Present)) {
601        return Check::ok("Claude Code hooks", "via global install (see Installation)");
602    }
603    for (name, hooks) in &repo {
604        if let SettingsHooks::Unreadable(e) = hooks {
605            return Check::warn(
606                "Claude Code hooks",
607                format!("cannot read <repo>/.claude/{name}: {e}"),
608            );
609        }
610    }
611    if let Some(SettingsHooks::Unreadable(e)) = &global {
612        return Check::warn(
613            "Claude Code hooks",
614            format!("cannot read ~/.claude/settings.json: {e}"),
615        );
616    }
617    Check::warn(
618        "Claude Code hooks",
619        "not registered in <repo>/.claude/settings.json, <repo>/.claude/settings.local.json or ~/.claude/settings.json (capture will miss some events)",
620    )
621}
622
623/// Severity of the "Visdom initialized" check. A per-repo `.visdom/`
624/// present is always Ok. Absent is EXPECTED (Skip) when the user has a global
625/// install or an active workspace binding; only a truly-unconfigured setup
626/// (none of the three) is an Error.
627fn tracevault_init_check(tv_dir_present: bool, has_global: bool, has_binding: bool) -> Check {
628    if tv_dir_present {
629        Check::ok("Visdom initialized", ".visdom/ present")
630    } else if has_global || has_binding {
631        Check::skip(
632            "Visdom initialized",
633            "no per-repo .visdom/ — global/workspace mode",
634        )
635    } else {
636        Check::err(
637            "Visdom initialized",
638            crate::program::say(
639                "not set up: run `tracevault init` (per-repo) or `tracevault init --global`",
640            ),
641        )
642    }
643}
644
645/// The most-recently-modified session in `sessions_dir` that HAS an active
646/// binding, as `(session_id, binding)`. Scans ALL session files (newest first)
647/// rather than only the newest file, so a real binding isn't missed when the
648/// most-recently-touched session happens to have none. `None` if no session
649/// carries an active binding.
650fn latest_active_binding_in(
651    sessions_dir: &Path,
652) -> Option<(String, crate::session_state::RepoBinding)> {
653    let mut sessions: Vec<(std::time::SystemTime, String)> = Vec::new();
654    for entry in fs::read_dir(sessions_dir).ok()?.flatten() {
655        let name = entry.file_name();
656        let name = name.to_str().unwrap_or("");
657        let Some(id) = name.strip_suffix(".toml") else {
658            continue;
659        };
660        if id.is_empty() {
661            continue;
662        }
663        let Ok(mtime) = entry.metadata().and_then(|m| m.modified()) else {
664            continue;
665        };
666        sessions.push((mtime, id.to_string()));
667    }
668    sessions.sort_by_key(|(mtime, _)| std::cmp::Reverse(*mtime)); // newest first
669    for (_, id) in sessions {
670        if let Some(b) = crate::session_state::load_from(sessions_dir, &id).active {
671            return Some((id, b));
672        }
673    }
674    None
675}
676
677/// One clear rule for the "Workspace repo" check, shared by both arms of
678/// [`workspace_binding_check_in`] below: `Ok` only when
679/// `binding_repo_id_is_valid` — the SAME predicate `attribution_for` filters
680/// through before honoring a repo binding — passes. A corrupted/hand-edited
681/// session-state file can carry a `repo_id` that isn't a real UUID;
682/// `attribution_for` silently drops such a binding, so showing it as `Ok`
683/// here would be green for something the hook will not honor.
684/// `detail_suffix` carries the arm-specific "(session {id})" / "most recent
685/// session..." wording; the base "repo {id} via repo switch" text stays
686/// identical to before this check existed.
687fn workspace_repo_binding_check(
688    b: &crate::session_state::RepoBinding,
689    detail_suffix: &str,
690) -> Check {
691    let base = format!("repo {} via repo switch{detail_suffix}", b.repo_id);
692    if crate::commands::stream::binding_repo_id_is_valid(&b.repo_id) {
693        Check::ok("Workspace repo", base)
694    } else {
695        Check::warn(
696            "Workspace repo",
697            format!(
698                "{base} — this repo_id is not a valid id and will be dropped at capture time; run `{CLI} repo switch <path>` to rewrite it"
699            ),
700        )
701    }
702}
703
704/// Resolve the workspace binding for `status` — the repo axis of
705/// attribution. With an explicit session id the user named a target, but a
706/// missing binding is only a Skip here: this check sees the repo axis alone,
707/// so it cannot tell a genuinely unbound machine (nothing will record) from
708/// one that's fully attributed via the project axis (`project switch
709/// --user`). Only [`recording_check`], which sees both axes, can make that
710/// call — so it also owns the escalation and the remediation hint; this
711/// check states the bare fact and stops (in particular, it does NOT suggest
712/// `tracevault repo switch …`: since v0.28.0 that command takes a checkout
713/// path and rejects binding by session name, which is exactly the situation
714/// on the repo-less machine this check is describing).
715///
716/// Without an explicit id, best-effort scan across all sessions (state is
717/// global): show the most recent that HAS a binding, and stay quiet (Skip)
718/// when none does — so a bound-mode user with a stray empty session file
719/// isn't warned. Returns the Check AND the resolved binding (reused by the
720/// caller as the `has_binding` mode signal).
721fn workspace_binding_check_in(
722    sessions_dir: &Path,
723    explicit_session_id: Option<&str>,
724) -> (Check, Option<crate::session_state::RepoBinding>) {
725    match explicit_session_id {
726        Some(id) => {
727            let state = crate::session_state::load_from(sessions_dir, id);
728            match state.active {
729                Some(b) => {
730                    let check = workspace_repo_binding_check(&b, &format!(" (session {id})"));
731                    (check, Some(b))
732                }
733                None => (
734                    Check::skip(
735                        "Workspace repo",
736                        format!("session {id} has no active binding"),
737                    ),
738                    None,
739                ),
740            }
741        }
742        None => match latest_active_binding_in(sessions_dir) {
743            Some((id, b)) => {
744                let suffix = format!(
745                    " — most recent session with a binding: {id} (may be another repo; pass --session-id to target one)"
746                );
747                let check = workspace_repo_binding_check(&b, &suffix);
748                (check, Some(b))
749            }
750            None => (
751                Check::skip("Workspace repo", "no active workspace binding found"),
752                None,
753            ),
754        },
755    }
756}
757
758// --- Attribution: project axis + the combined recording verdict ---
759
760/// The already-resolved project-attribution outcome consumed by
761/// [`project_binding_check`]: either the full server-aware chain
762/// (`resolve_effective_project`) or, when no API client is available, the
763/// pure local tiers (`effective_project`) wrapped in `Ok` so both code paths
764/// in `run_status` produce the same shape. Reuses `resolution.rs`'s own
765/// `Option<(ProjectBinding, ProjectSource)>`/`Box<dyn Error>` types rather
766/// than introducing a parallel enum, so `ProjectSource`'s tier labels (and
767/// its `Display` impl) stay the single source of truth.
768type ProjectOutcome = Result<
769    Option<(crate::session_state::ProjectBinding, ProjectSource)>,
770    Box<dyn std::error::Error>,
771>;
772
773/// Display label for a project binding: the friendly name, falling back to
774/// the id when unset. A `Deduced` binding carries an empty `project_name`
775/// (`resolve_effective_project` doesn't enrich it) and is shown by id rather
776/// than name: the credentialed arm below only ever calls `list_projects`
777/// when a config `default_project` is set, so a name lookup for `Deduced` is
778/// not reliably available — falling back to the id keeps this consistent
779/// across both cases rather than sometimes showing a name and sometimes an
780/// id depending on unrelated config state.
781fn project_label(binding: &crate::session_state::ProjectBinding) -> &str {
782    if binding.project_name.is_empty() {
783        &binding.project_id
784    } else {
785        &binding.project_name
786    }
787}
788
789/// Maps the resolved project-attribution outcome to the "Project" check.
790/// Network-free — the resolution already happened in `run_status`. It does
791/// read `TRACEVAULT_PROJECT` (via `env_project_binding`) for the `Env` arm;
792/// see the rule below for why that read is the point.
793/// DISPLAY ONLY: this outcome never feeds [`recording_check`]'s verdict — see
794/// that function's doc comment for why.
795///
796/// One rule decides `Ok`: the tier must be one `capture_project` itself
797/// honors (flag/subagent/`Env`/session-active/user-default — NOT
798/// `ConfigDefault` or `Deduced`, which it excludes/never produces), AND the
799/// binding must be one `capture_project` would not then drop. It drops a
800/// `project_id` that fails `.parse::<uuid::Uuid>()` (its own last act before
801/// returning the binding), and — at the `Env` rung specifically — it never
802/// forms a binding at all unless the RAW `TRACEVAULT_PROJECT` value is a
803/// UUID, because `env_project_binding` is UUID-only by design (a name would
804/// need a per-event `list_projects` round trip).
805///
806/// That last condition is why the `Env` arm consults
807/// [`crate::commands::stream::env_project_binding`] rather than testing the
808/// RESOLVED binding's id: a NAME in `TRACEVAULT_PROJECT` is resolved here for
809/// display (this command has a client; the hook does not), so its resolved id
810/// IS a valid UUID and would sail through an id-only test — reporting green
811/// for a tier the wire silently ignores. Asking the capture path's own reader
812/// is what makes the two unable to drift.
813///
814/// Any of those failures renders `Warn`, not `Ok` — showing green for a
815/// binding the capture path will not honor is the exact confusion this
816/// command exists to eliminate (a hand-edited or corrupted
817/// `user_project.toml` with a garbage `project_id` is a real way to hit the
818/// id-validity half of this).
819///
820/// `Err` — the ambiguous "this repo belongs to multiple projects" case, or
821/// any transport/5xx failure of the deduction call (`resolve_effective_project`
822/// propagates both the same way via `?`) — is also at most a `Warn`, never an
823/// `Error`: this axis is display-only, so a network blip must never be able
824/// to redden the exit code on its own. Matches how the rest of `status`
825/// treats transport failure (`GetMeError::Network`, a failed `list_repos`) as
826/// Warn, not Error.
827///
828/// `None` (nothing bound on this axis) is a `Skip` — severity for "nothing
829/// will be recorded" is [`recording_check`]'s job, since only it consults the
830/// actual recording gate.
831///
832/// DELIBERATE GAP — this reports WHICH project and WHICH tier, and whether
833/// ingest honours that tier. It does not report the attribution MODE
834/// (`derived`/`explicit`) or any persisted-force detail, and it is not meant
835/// to: `commands::project`'s `status` owns that, via the one function that
836/// decides the header (`commands::stream::attribution_mode`) plus
837/// `format_force_line`. Reproducing either here would mean a second surface
838/// that has to keep agreeing with the wire, and the whole shape of VIS-305's
839/// attribution reporting is that exactly one place answers "derived or
840/// explicit?" — the bugs this branch fixed were all second answers drifting
841/// from the first. The README says the same split rather than promising
842/// parity, the way `online_project_outcome`'s unresolvable-name case is
843/// documented as a gap instead of claimed as coverage. If the mode ever does
844/// belong in the full diagnostic, it must arrive by CALLING
845/// `attribution_mode` — never by re-deriving the verdict here.
846fn project_binding_check(outcome: &ProjectOutcome) -> Check {
847    match outcome {
848        Err(e) => Check::warn("Project", e.to_string()),
849        Ok(None) => Check::skip(
850            "Project",
851            crate::program::say("not bound — run `tracevault project switch --user \"<name>\"`, or `tracevault repo switch <path>` inside a checkout"),
852        ),
853        Ok(Some((binding, source))) => {
854            // `Env` (`TRACEVAULT_PROJECT`) joined this list once
855            // `commands::stream::capture_project` started passing
856            // `env_project_binding()` into `effective_project` — it is now
857            // one of the tiers capture time actually resolves, same as
858            // Subagent/SessionActive/UserDefault, so it must read Ok here
859            // too or this Check would warn "not used for attribution at
860            // capture time" about a tier that is, in fact, used.
861            let honored_tier = matches!(
862                source,
863                ProjectSource::ProjectFlag
864                    | ProjectSource::Subagent
865                    | ProjectSource::Env
866                    | ProjectSource::SessionActive
867                    | ProjectSource::Workspace
868                    | ProjectSource::UserDefault
869            );
870            // ...but only for the form the capture path can actually use. A
871            // NAME resolves here (a client is in scope) and nowhere on the
872            // wire, so asking `env_project_binding` — the hook's own reader
873            // of this same var — is the only test that can't go green on a
874            // tier the hook ignores.
875            let env_name_form = *source == ProjectSource::Env
876                && crate::commands::stream::env_project_binding().is_none();
877            let label = project_label(binding);
878            if env_name_form {
879                Check::warn(
880                    "Project",
881                    format!(
882                        "{label} — {source}, resolved for display only: the capture path honours only the UUID form of {ENV}_PROJECT, so a NAME is ignored there and attribution falls through to the next tier — export {ENV}_PROJECT={} instead, or bind it with `{CLI} project switch <name>`",
883                        binding.project_id
884                    ),
885                )
886            } else if !honored_tier {
887                Check::warn(
888                    "Project",
889                    format!(
890                        "{label} — {source}, not used for attribution at capture time; set one explicitly with `{CLI} project switch <name>` or --project"
891                    ),
892                )
893            } else if binding.project_id.parse::<uuid::Uuid>().is_err() {
894                Check::warn(
895                    "Project",
896                    format!(
897                        "{label} — {source}, but the saved project_id is not a valid id and will be dropped at capture time; run `{}` to rewrite it",
898                        source.rewrite_command()
899                    ),
900                )
901            } else {
902                Check::ok("Project", format!("{label} — {source}"))
903            }
904        }
905    }
906}
907
908/// Surfaces a `.visdom/tracing.toml` that still carries the legacy
909/// `default_project` NAME (VIS-1256). Ingest never resolves names, so the
910/// name contributes nothing to attribution until `init`/`sync` migrate it to
911/// `project_id`; this command therefore does not resolve it either (that
912/// would report a project ingest never attributes to — VIS-316) and says so
913/// instead. `None` when there is nothing legacy in the config. Shares its
914/// wording with `commands::project`'s `status` via
915/// [`crate::commands::migrate::legacy_default_project_notice`].
916fn legacy_default_project_check(config: Option<&TracevaultConfig>) -> Option<Check> {
917    let notice = crate::commands::migrate::legacy_default_project_notice(config?)?;
918    Some(Check::warn("Project default", notice))
919}
920
921/// The one check that reflects whether anything will record this session at
922/// all. Takes the ALREADY-RESOLVED [`crate::commands::stream::Attribution`] —
923/// the exact same value `attribution_for(resolve_stream_binding(...),
924/// capture_project(...))` the `stream` hook itself computes before deciding
925/// to no-op — rather than a hand-built approximation of the two axes. Coupling
926/// to the hook's own gate this way is load-bearing: the repo axis has tiers
927/// (`repo switch --user`, a config with no `repo_id`) and the project axis has
928/// tiers (`project switch --user` with no credential, `Deduced`/`ConfigDefault`
929/// display values `capture_project` doesn't honor) that a hand-rolled
930/// `repo_bound`/`project_bound` pair would have to re-derive and could get
931/// wrong; calling the real functions means the two can't drift apart.
932///
933/// Only fires for an explicitly named session (`--session-id` /
934/// `$TRACEVAULT_SESSION_ID`, i.e. `session_id.is_some()`); without one,
935/// [`checkout_recording_check`] answers the session-independent question
936/// instead. Pure and
937/// network-free: `attribution` is computed by the caller from purely local
938/// tiers (mirroring the hook), so this check — and the verdict it drives —
939/// can never be swayed by a network hiccup.
940fn recording_check(
941    session_id: Option<&str>,
942    attribution: Option<&crate::commands::stream::Attribution>,
943) -> Option<Check> {
944    let id = session_id?;
945    if attribution.is_some() {
946        return None;
947    }
948    Some(Check::err(
949        "Recording",
950        format!(
951            "nothing will be recorded — session {id} is bound on neither the repo nor the \
952             project axis; run `{CLI} project switch --user \"<name>\"` on a repo-less \
953             machine, or `{CLI} repo switch <path>` inside a checkout"
954        ),
955    ))
956}
957
958/// The session-independent half of the recording verdict: will a NEW session
959/// started in this checkout record anything, before it runs `repo switch` or
960/// `project switch`? Answers the question a plain terminal right after `init`
961/// needs, where [`recording_check`] stays silent for lack of a session.
962///
963/// `attribution` must come from [`recording_attribution`] with NO session —
964/// i.e. the hook's own gate fed only the tiers that exist before a session
965/// does (bound config, `repo switch --user`, `TRACEVAULT_PROJECT`,
966/// `project switch --user`). `config` only picks the wording and severity:
967///
968/// - a repo resolved → `Ok`;
969/// - a `config.toml` is present (bound mode) but did not yield a usable repo
970///   (`repo_id` missing or not a UUID) → `Error` when nothing resolved at all,
971///   `Warn` when a project still catches the events (they ship, but not to
972///   this repo) — the bound-mode user asked for repo attribution;
973/// - no config and nothing resolved → `Warn`, not `Error`: in workspace mode
974///   each session is bound by its hooks from the checkout's origin remote
975///   (`auto_bind`) or by `repo switch`, so this is the expected state of a
976///   plain terminal, but the user should still be told.
977fn checkout_recording_check(
978    attribution: Option<&crate::commands::stream::Attribution>,
979    config: Option<&TracevaultConfig>,
980) -> Check {
981    use crate::commands::stream::Attribution;
982    const LABEL: &str = "Recording";
983    let repo_id_problem = config.and_then(|c| match c.repo_id.as_deref() {
984        None => Some(".visdom/tracing.toml has no repo_id".to_string()),
985        Some(id) if !crate::commands::stream::binding_repo_id_is_valid(id) => Some(format!(
986            ".visdom/tracing.toml repo_id '{id}' is not a valid id"
987        )),
988        Some(_) => None,
989    });
990    match (attribution, repo_id_problem) {
991        (Some(Attribution::Repo { repo_id, .. }), _) => Check::ok(
992            LABEL,
993            format!("new sessions in this checkout record to repo {repo_id}"),
994        ),
995        (Some(Attribution::ProjectOnly { project_id }), Some(problem)) => Check::warn(
996            LABEL,
997            format!(
998                "{problem}: new sessions here record to project {project_id} only, not to this repo — run `{CLI} sync` while logged in"
999            ),
1000        ),
1001        (Some(Attribution::ProjectOnly { project_id }), None) => Check::ok(
1002            LABEL,
1003            format!("new sessions in this checkout record to project {project_id}"),
1004        ),
1005        (None, Some(problem)) => Check::err(
1006            LABEL,
1007            format!(
1008                "nothing will be recorded — {problem} and nothing else binds this checkout; run `{CLI} sync` while logged in"
1009            ),
1010        ),
1011        (None, None) => Check::warn(
1012            LABEL,
1013            crate::program::say("no session named and nothing binds this checkout locally — a new session here is bound by its hooks to the repo of this checkout's origin remote if the server has it registered (otherwise run `tracevault sync` while logged in), or by `tracevault repo switch <path>`"),
1014        ),
1015    }
1016}
1017
1018/// Compose the "will this session record anything" gate exactly as
1019/// `run_status` and the `stream` hook do: load the session state, derive the
1020/// worktree key from `cwd`, extract a bound-config `RepoBinding` (if any),
1021/// and call `resolve_stream_binding` -> `capture_project` -> `attribution_for`
1022/// with those inputs. Pure and synchronous — network-free, matching the two
1023/// functions it calls. Returns the worktree key alongside the attribution so
1024/// callers that also need it (the project-display resolution in `run_status`)
1025/// don't re-shell out to git for the same value.
1026///
1027/// Deliberately derives its OWN worktree key from `cwd` (via
1028/// `crate::paths::worktree_toplevel`) rather than taking a pre-computed key as
1029/// a parameter: `cwd` is the toplevel a `stream` hook invocation actually runs
1030/// from, which for a LINKED worktree is NOT the same string as `project_root`
1031/// (the PRIMARY worktree's root, from `resolve_project_root`'s
1032/// `git rev-parse --git-common-dir`) — subagent overrides are keyed by the
1033/// former. Keeping the derivation INSIDE this function, with every attribution
1034/// test calling it directly rather than re-deriving the key by hand, is what
1035/// makes `recording_attribution_finds_subagent_override_via_linked_worktree_cwd`
1036/// able to catch a regression back to a primary-root path.
1037#[cfg(test)]
1038fn recording_attribution(
1039    sessions_dir: Option<&Path>,
1040    session_id: Option<&str>,
1041    cwd: &Path,
1042    config: Option<&TracevaultConfig>,
1043) -> (Option<crate::commands::stream::Attribution>, String) {
1044    let (recording, worktree) = recording_for(sessions_dir, session_id, cwd, config);
1045    (recording.attribution, worktree)
1046}
1047
1048/// [`recording_attribution`] with whether its repo was inferred from the
1049/// checkout (VIS-1258) rather than bound — what `run_status` reports.
1050fn recording_for(
1051    sessions_dir: Option<&Path>,
1052    session_id: Option<&str>,
1053    cwd: &Path,
1054    config: Option<&TracevaultConfig>,
1055) -> (crate::commands::stream::Recording, String) {
1056    let session = match (sessions_dir, session_id) {
1057        (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
1058        _ => crate::session_state::SessionState::default(),
1059    };
1060    let worktree = crate::paths::worktree_toplevel(cwd);
1061    let bound = config.and_then(crate::resolution::binding_from_config);
1062    let user_default_repo = crate::user_default::load();
1063    let recording = crate::commands::stream::recording_attribution_for(
1064        &session,
1065        &worktree,
1066        bound,
1067        user_default_repo,
1068        config.and_then(crate::resolution::project_from_config),
1069    );
1070    (recording, worktree)
1071}
1072
1073/// The `Recording` line for a named session whose repo is inferred from this
1074/// checkout (VIS-1258), so `status` says it is inferred and not bound.
1075/// `None` when the repo is not inferred.
1076fn inferred_recording_check(recording: &crate::commands::stream::Recording) -> Option<Check> {
1077    use crate::commands::stream::Attribution;
1078    let (
1079        Some(Attribution::Repo {
1080            repo_id,
1081            project: Some(pid),
1082        }),
1083        Some(checkout),
1084    ) = (&recording.attribution, &recording.inferred_from)
1085    else {
1086        return None;
1087    };
1088    Some(Check::ok(
1089        "Recording",
1090        format!(
1091            "repo {repo_id} (inferred from the checkout {checkout}) in project {pid} — no repo \
1092             is bound, so each event is sent to the repo of the checkout it touches when that \
1093             repo is in the project, else to the project only"
1094        ),
1095    ))
1096}
1097
1098/// The project axis's client-backed resolution: `TRACEVAULT_PROJECT` (UUID
1099/// or NAME, mirroring `commands::project`'s `status`) gets to consult
1100/// `list_projects` here, then the full server-aware precedence chain
1101/// (`resolve_effective_project`) runs. The workspace config tier is its
1102/// `project_id` only (`config_project`, read locally exactly as ingest reads
1103/// it); a legacy `default_project` NAME is never resolved here — the caller
1104/// reports it via `legacy_default_project_check`. Pulled out analogously to
1105/// [`offline_project_outcome`] so this branch is unit-testable without
1106/// driving all of `run_status`.
1107///
1108/// An unresolved `TRACEVAULT_PROJECT` NAME still gets no equivalent surfacing
1109/// here; it is silently dropped. That is now a real (if narrow) gap rather
1110/// than a matter of parity: `commands::project`'s `status` DOES warn for it
1111/// (as it already did for an unresolved `--project` and `default_project`).
1112/// It is survivable because the capture path drops a name too, so nothing
1113/// this command reports contradicts what the hook does — the operator is
1114/// simply not told why their variable had no effect. Closing it means a
1115/// `Check` of its own, deliberately left for a follow-up.
1116/// One project NAME looked up in the server's project list, as a binding.
1117///
1118/// Used for the NAME form of `TRACEVAULT_PROJECT` — a client is in scope
1119/// here, unlike on the capture path.
1120async fn resolve_name_via_client(
1121    client: &ApiClient,
1122    name: &str,
1123) -> Option<crate::session_state::ProjectBinding> {
1124    client.list_projects().await.ok().and_then(|items| {
1125        items
1126            .into_iter()
1127            .find(|p| p.name == name)
1128            .map(|p| crate::session_state::ProjectBinding {
1129                project_id: p.id.to_string(),
1130                project_name: p.name,
1131                updated_at: chrono::Utc::now().to_rfc3339(),
1132                forced_until: None,
1133            })
1134    })
1135}
1136
1137async fn online_project_outcome(
1138    client: &ApiClient,
1139    config_project: Option<crate::session_state::ProjectBinding>,
1140    project_session: &crate::session_state::SessionState,
1141    worktree: &str,
1142    user_default_project: Option<crate::session_state::ProjectBinding>,
1143    project_git_url: Option<&str>,
1144) -> ProjectOutcome {
1145    // `TRACEVAULT_PROJECT`: a UUID or a NAME — a client is in scope here, so
1146    // both forms are honoured (unlike the capture path, which is UUID-only).
1147    //
1148    // The UUID form is whatever the HOOK reads, so it comes from
1149    // `env_project_binding` — the hook's own reader — rather than a fourth
1150    // hand-rolled copy of the same parse (the reason `offline_project_outcome`
1151    // already calls it). A non-empty value it declines is a name, which only
1152    // this command can resolve.
1153    let env_project = match crate::commands::stream::env_project_binding() {
1154        Some(binding) => Some(binding),
1155        None => match std::env::var("TRACEVAULT_PROJECT").ok() {
1156            Some(raw) if !raw.trim().is_empty() => {
1157                resolve_name_via_client(client, raw.trim()).await
1158            }
1159            _ => None,
1160        },
1161    };
1162    let inputs = ProjectResolveInputs {
1163        project_flag: None,
1164        env_project,
1165        session: project_session,
1166        worktree_path: Some(worktree),
1167        config_project,
1168    };
1169    resolve_effective_project(&inputs, user_default_project, project_git_url, client).await
1170}
1171
1172/// The project axis's offline/no-client display fallback: the pure local
1173/// tiers (`effective_project`) plus the user-level project default as the
1174/// lowest tier. `effective_project` alone never consults the user default —
1175/// only `resolve_effective_project` (the networked chain) does — so without
1176/// this, a repo-less pod attributed solely via `project switch --user`, with
1177/// no credential/server URL configured, would show "not bound" on the
1178/// "Project" line while `recording_attribution` (which reads this same tier
1179/// independently via `capture_project`) correctly shows the session as
1180/// recording. Pulled out as its own pure function so this fallback is
1181/// unit-testable without driving all of `run_status`.
1182fn offline_project_outcome(
1183    inputs: &ProjectResolveInputs,
1184    user_default_project: Option<crate::session_state::ProjectBinding>,
1185) -> ProjectOutcome {
1186    Ok(effective_project(inputs)
1187        .or_else(|| user_default_project.map(|b| (b, ProjectSource::UserDefault))))
1188}
1189
1190// --- Server repo ---
1191
1192/// Which repo id `status` looks up on the server, and where it came from.
1193/// Always an id — never the checkout's directory name: a name match finds
1194/// whatever repo of that name someone registered, which says nothing about
1195/// whether THIS checkout carries an id the stream hook can attribute to.
1196#[derive(Debug, Clone, PartialEq)]
1197enum RepoLookup {
1198    /// The explicitly named session's repo binding for this worktree (a
1199    /// subagent override or the `repo switch` binding).
1200    Workspace(String),
1201    /// The `repo_id` in `.visdom/tracing.toml` (bound mode).
1202    Bound(String),
1203    /// A `config.toml` exists but has no `repo_id`, and no session binding
1204    /// supplies one — the state in which the stream hook drops every event
1205    /// of a repo-only setup.
1206    MissingRepoId,
1207}
1208
1209/// Mirrors the hook's precedence (`effective_binding`: session bindings
1210/// before bound config): the explicitly named session's binding — from
1211/// [`session_repo_binding`], so a subagent's worktree override wins exactly as
1212/// it does in the hook — else the config's `repo_id`. `None` when there is
1213/// neither a binding nor a config. Pure, so the precedence is unit-testable
1214/// without a server.
1215fn server_repo_lookup(
1216    config: Option<&TracevaultConfig>,
1217    binding: Option<&crate::session_state::RepoBinding>,
1218) -> Option<RepoLookup> {
1219    if let Some(b) = binding {
1220        return Some(RepoLookup::Workspace(b.repo_id.clone()));
1221    }
1222    let config = config?;
1223    Some(match &config.repo_id {
1224        Some(id) => RepoLookup::Bound(id.clone()),
1225        None => RepoLookup::MissingRepoId,
1226    })
1227}
1228
1229/// The session-scoped tiers of the hook's repo chain for `worktree`: a
1230/// subagent's worktree override, else the session's active binding. Calls
1231/// `resolve_stream_binding` with the config and user-default tiers left out —
1232/// [`server_repo_lookup`] handles the config tier itself, and reports a
1233/// missing `repo_id` there rather than letting a lower tier mask it.
1234fn session_repo_binding(
1235    session: &crate::session_state::SessionState,
1236    worktree: &str,
1237) -> Option<crate::session_state::RepoBinding> {
1238    crate::commands::stream::resolve_stream_binding(session, worktree, None, None)
1239}
1240
1241/// The server repo whose id is `id`. Compared as UUIDs, so case or
1242/// formatting differences in a hand-edited id don't produce a false miss; an
1243/// id that is not a UUID matches nothing (the hook would drop it too).
1244fn find_repo_by_id<'a>(
1245    repos: &'a [crate::api_client::RepoListItem],
1246    id: &str,
1247) -> Option<&'a crate::api_client::RepoListItem> {
1248    let id: uuid::Uuid = id.trim().parse().ok()?;
1249    repos.iter().find(|r| r.id == id)
1250}
1251
1252async fn server_repo_checks(
1253    project_root: &Path,
1254    auth: &AuthContext,
1255    config: Option<&TracevaultConfig>,
1256    binding: Option<&crate::session_state::RepoBinding>,
1257) -> Vec<Check> {
1258    let mut out = Vec::new();
1259
1260    // The local half first: a missing `repo_id` is an error whether or not
1261    // the user is logged in (init-before-login is exactly that state).
1262    // `bound_mode`: the id came from config.toml, so the checkout's own
1263    // `origin` is expected to match the server record (checked below).
1264    let (id, source, bound_mode) = match server_repo_lookup(config, binding) {
1265        None => {
1266            out.push(Check::skip(
1267                "Repo registered on server",
1268                "not bound (need a project config.toml or a --session-id workspace binding)",
1269            ));
1270            return out;
1271        }
1272        Some(RepoLookup::MissingRepoId) => {
1273            out.push(Check::err(
1274                "Repo registered on server",
1275                crate::program::say(".visdom/tracing.toml has no repo_id, so sessions here are not attributed to this repo — run `tracevault sync` while logged in to register the repo and write it"),
1276            ));
1277            return out;
1278        }
1279        Some(RepoLookup::Workspace(id)) => (id, "session binding", false),
1280        Some(RepoLookup::Bound(id)) => (id, ".visdom/tracing.toml", true),
1281    };
1282
1283    let (Some(credential), Some(server_url)) = (auth.credential.clone(), auth.server_url.as_ref())
1284    else {
1285        out.push(Check::skip(
1286            "Repo registered on server",
1287            format!("not authenticated (would look up repo id {id} from {source})"),
1288        ));
1289        return out;
1290    };
1291
1292    let client = ApiClient::with_credential(server_url, Some(credential));
1293    let repos = match client.list_repos().await {
1294        Ok(r) => r,
1295        Err(e) => {
1296            out.push(Check::warn(
1297                "Repo registered on server",
1298                format!("failed to list repos: {e}"),
1299            ));
1300            return out;
1301        }
1302    };
1303
1304    match find_repo_by_id(&repos, &id) {
1305        None => {
1306            out.push(Check::err(
1307                "Repo registered on server",
1308                format!("repo id {id} (from {source}) not found on the server. Run `{CLI} sync` while logged in."),
1309            ));
1310            return out;
1311        }
1312        Some(r) => {
1313            out.push(Check::ok(
1314                "Repo registered on server",
1315                format!("id={} (from {source})", r.id),
1316            ));
1317            match r.clone_status.as_deref() {
1318                Some("ready") => out.push(Check::ok("Server-side clone", "ready")),
1319                Some(other @ ("cloning" | "pending")) => out.push(Check::warn(
1320                    "Server-side clone",
1321                    format!("{other} — analytics and code browser unavailable until it finishes"),
1322                )),
1323                Some("error") => out.push(Check::err(
1324                    "Server-side clone",
1325                    "error — check the repo settings page on the dashboard",
1326                )),
1327                Some(other) => out.push(Check::warn(
1328                    "Server-side clone",
1329                    format!("unknown status '{other}'"),
1330                )),
1331                None => out.push(Check::skip(
1332                    "Server-side clone",
1333                    "server did not report clone status",
1334                )),
1335            }
1336
1337            if bound_mode {
1338                let local_remote = git_remote_url(project_root);
1339                match (local_remote.as_deref(), r.github_url.as_deref()) {
1340                    (Some(local), Some(remote))
1341                        if normalize_remote(local) == normalize_remote(remote) =>
1342                    {
1343                        out.push(Check::ok("Remote URL matches", remote.to_string()));
1344                    }
1345                    (Some(local), Some(remote)) => out.push(Check::warn(
1346                        "Remote URL matches",
1347                        format!("local={local} vs server={remote} — run `{CLI} sync`"),
1348                    )),
1349                    (Some(local), None) => out.push(Check::warn(
1350                        "Remote URL matches",
1351                        format!("server has no github_url; local={local}"),
1352                    )),
1353                    (None, _) => out.push(Check::warn(
1354                        "Remote URL matches",
1355                        "no local `origin` remote configured",
1356                    )),
1357                }
1358            } else {
1359                out.push(Check::skip(
1360                    "Remote URL matches",
1361                    "n/a in workspace mode (bound by id)",
1362                ));
1363            }
1364        }
1365    }
1366
1367    out
1368}
1369
1370// --- Sessions ---
1371
1372/// True for a per-repo `pending-<id>.jsonl` (nonempty id) queue file —
1373/// tighter than a bare `starts_with("pending") && ends_with(".jsonl")`
1374/// check, which would also match e.g. `pendingfoo.jsonl` or `pending-.jsonl`.
1375/// The legacy `pending.jsonl` name is handled separately by callers, since
1376/// whether it counts depends on whether there's a bound `repo_id` to
1377/// attribute it to (see `count_pending_events`).
1378fn is_pending_queue_filename(name: &str) -> bool {
1379    crate::commands::flush::repo_id_from_pending_filename(name).is_some()
1380}
1381
1382/// Sum the non-empty lines across every per-repo (and, if `include_legacy`,
1383/// legacy) pending queue file in a session directory: `pending.jsonl` and
1384/// `pending-<repo_id>.jsonl`.
1385///
1386/// `include_legacy` should be true only when the project has a bound
1387/// `repo_id` (config.toml), since `flush` only drains the legacy
1388/// `pending.jsonl` in that case (best-effort attribution). Otherwise a
1389/// stray `pending.jsonl` would be counted here but never cleared by
1390/// `flush`, leaving `status` permanently reporting stuck events.
1391fn count_pending_events(session_dir: &Path, include_legacy: bool) -> usize {
1392    let Ok(read) = fs::read_dir(session_dir) else {
1393        return 0;
1394    };
1395
1396    read.flatten()
1397        .filter(|entry| {
1398            entry
1399                .file_name()
1400                .to_str()
1401                .map(|name| {
1402                    is_pending_queue_filename(name) || (include_legacy && name == "pending.jsonl")
1403                })
1404                .unwrap_or(false)
1405        })
1406        .map(|entry| {
1407            fs::read_to_string(entry.path())
1408                .unwrap_or_default()
1409                .lines()
1410                .filter(|l| !l.trim().is_empty())
1411                .count()
1412        })
1413        .sum()
1414}
1415
1416fn session_checks(project_root: &Path) -> Vec<Check> {
1417    // Sessions an earlier release started are still in `.tracevault/`.
1418    let sessions_dirs = crate::layout::existing_sessions_dirs(project_root);
1419    if sessions_dirs.is_empty() {
1420        return vec![Check::skip(
1421            "Pending events",
1422            "no .visdom/sessions/ here (project-local check; a detached worker's queue may live under its own working dir)",
1423        )];
1424    }
1425
1426    // The legacy `pending.jsonl` is only drainable by `flush` when there's a
1427    // bound `repo_id` to attribute it to (best-effort attribution). Counting
1428    // it here otherwise would report events that `flush` can never clear.
1429    let include_legacy = TracevaultConfig::load(project_root)
1430        .and_then(|c| c.repo_id)
1431        .is_some();
1432
1433    let mut total_sessions = 0usize;
1434    let mut sessions_with_pending = 0usize;
1435    let mut pending_event_count = 0usize;
1436
1437    let entries = sessions_dirs
1438        .iter()
1439        .filter_map(|dir| fs::read_dir(dir).ok())
1440        .flatten();
1441    for entry in entries.flatten() {
1442        if !entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
1443            continue;
1444        }
1445        total_sessions += 1;
1446        let count = count_pending_events(&entry.path(), include_legacy);
1447        if count > 0 {
1448            sessions_with_pending += 1;
1449            pending_event_count += count;
1450        }
1451    }
1452
1453    vec![if sessions_with_pending == 0 {
1454        Check::ok(
1455            "Pending events",
1456            format!("{total_sessions} session(s), all synced (project-local)"),
1457        )
1458    } else {
1459        Check::warn(
1460            "Pending events",
1461            format!(
1462                "{pending_event_count} event(s) in {sessions_with_pending}/{total_sessions} session(s) — run `{CLI} flush`"
1463            ),
1464        )
1465    }]
1466}
1467
1468// --- Git helpers ---
1469
1470/// Make two remote URLs comparable by dropping `.git`, trailing slash, and
1471/// collapsing SSH ↔ HTTPS differences for github.com specifically.
1472fn normalize_remote(url: &str) -> String {
1473    let trimmed = url
1474        .trim()
1475        .trim_end_matches('/')
1476        .trim_end_matches(".git")
1477        .to_string();
1478
1479    // git@github.com:org/repo  ->  github.com/org/repo
1480    if let Some(rest) = trimmed.strip_prefix("git@github.com:") {
1481        return format!("github.com/{rest}");
1482    }
1483    // https://github.com/org/repo -> github.com/org/repo
1484    for p in ["https://", "http://"] {
1485        if let Some(rest) = trimmed.strip_prefix(p) {
1486            return rest.to_string();
1487        }
1488    }
1489    trimmed
1490}
1491
1492// --- Entry point ---
1493
1494/// Resolve the session id for `status`: an explicit `--session-id` wins, else
1495/// the environment's ([`crate::session_state::env_session_id`]); empty strings
1496/// are ignored (fall through).
1497pub fn effective_session_id(arg: Option<String>, env: Option<String>) -> Option<String> {
1498    arg.filter(|s| !s.is_empty())
1499        .or_else(|| env.filter(|s| !s.is_empty()))
1500}
1501
1502pub async fn run_status(project_root: &Path, cwd: &Path, session_id: Option<&str>) -> i32 {
1503    // Loaded here rather than reused from `project_checks` below, which runs
1504    // later and owns its own load. `try_load`, not `load`: `load` prints its own
1505    // stderr line on malformed TOML, which would pre-empt (and duplicate) the
1506    // structured parse error `project_checks` reports. A config that will not
1507    // parse simply contributes nothing here.
1508    let auth_config = TracevaultConfig::try_load(project_root).ok().flatten();
1509    let config_server_url = auth_config.as_ref().and_then(|c| c.server_url.as_deref());
1510    let auth = resolve_auth(
1511        config_server_url,
1512        auth_config.as_ref().and_then(|c| c.api_key.as_deref()),
1513    );
1514
1515    // ~/.claude/settings.json — None when the home dir can't be resolved. Do
1516    // NOT fall back to a relative `.claude/settings.json`: that would read the
1517    // repo's own settings and could report a false "Global install".
1518    let global_settings: Option<PathBuf> =
1519        dirs::home_dir().map(|h| h.join(".claude").join("settings.json"));
1520    let sessions_dir = crate::session_state::sessions_dir();
1521
1522    let global_check = match global_settings.as_deref() {
1523        Some(p) => global_hook_check_in(p),
1524        None => Check::skip("Global install", "cannot determine home directory"),
1525    };
1526    let has_global = global_check.level == Level::Ok;
1527
1528    // Resolve the workspace binding ONCE: it drives both the section and the
1529    // `has_binding` mode signal used by project_checks.
1530    let (binding_check, binding) = match sessions_dir.as_deref() {
1531        Some(dir) => workspace_binding_check_in(dir, session_id),
1532        None => (
1533            Check::skip("Workspace repo", "cannot determine session state dir"),
1534            None,
1535        ),
1536    };
1537    // A binding only counts as a mode signal when the session was named
1538    // explicitly (--session-id / $TRACEVAULT_SESSION_ID). A *scanned* binding
1539    // (no session id) is cwd-agnostic and may belong to another repo, so it is
1540    // shown for information but must NOT downgrade "not set up" severity nor
1541    // drive the server-repo check.
1542    let explicit_session = session_id.is_some();
1543    let has_binding = binding.is_some() && explicit_session;
1544
1545    let auth_checks_v = auth_checks(&auth, config_server_url).await;
1546    let telemetry_check = match global_settings.as_deref() {
1547        Some(p) => with_telemetry_choice(
1548            claude_telemetry_check_in(
1549                p,
1550                auth.server_url.as_deref(),
1551                &crate::commands::claude_telemetry::Environment::current(p.parent().unwrap_or(p)),
1552            ),
1553            &crate::install_state::load_in(&crate::config::tv_config_root()),
1554        ),
1555        None => Check::skip("Claude Code telemetry", "cannot determine home directory"),
1556    };
1557    let install_v = vec![global_check, telemetry_check];
1558    let (proj_checks_v, config) = project_checks(
1559        project_root,
1560        global_settings.as_deref(),
1561        has_global,
1562        has_binding,
1563    );
1564
1565    // The recording verdict: call the hook's own gate (stream.rs) via
1566    // `recording_attribution` — see that function's doc comment for why its
1567    // composition, including the worktree-key derivation, lives there rather
1568    // than inline here. Its worktree key is reused below for the project
1569    // display resolution, which needs the same value.
1570    let (recording, worktree) =
1571        recording_for(sessions_dir.as_deref(), session_id, cwd, config.as_ref());
1572    let attribution = recording.attribution.clone();
1573
1574    // The project axis for DISPLAY needs its own full `SessionState` (more
1575    // than `workspace_binding_check_in`'s bare `RepoBinding`, e.g.
1576    // `active_project`/`subagent_projects`) — unlike the verdict above, which
1577    // lives entirely inside `recording_attribution`. Loaded separately
1578    // (rather than sharing `recording_attribution`'s internal session load)
1579    // so that function's session load stays self-contained.
1580    let project_session = match (sessions_dir.as_deref(), session_id) {
1581        (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
1582        _ => crate::session_state::SessionState::default(),
1583    };
1584
1585    // --- The project axis for DISPLAY only, mirroring `commands::project`'s
1586    // `status` path (project.rs:228-334): read the worktree-relative
1587    // default_project + the user-level default, and run the full precedence
1588    // chain (including server-side deduction) if a client can be built from
1589    // the existing `auth`. Best-effort like that path: no credential/client
1590    // degrades to the pure local tiers via `effective_project`, which need no
1591    // network. Whatever this resolves to (including a deduction failure) is
1592    // shown to the user but — unlike the verdict above — can never affect the
1593    // exit code beyond a Warn; see `project_binding_check`.
1594    // The workspace tier, read exactly as ingest reads it: the config's
1595    // `project_id`, never the legacy `default_project` name (VIS-1256).
1596    let config_project = config
1597        .as_ref()
1598        .and_then(crate::resolution::project_from_config);
1599    let user_default_project = crate::user_project_default::load();
1600    let project_git_url = git_remote_url(cwd);
1601    let project_outcome: ProjectOutcome = match (auth.credential.clone(), auth.server_url.as_ref())
1602    {
1603        (Some(credential), Some(server_url)) => {
1604            let client = ApiClient::with_credential(server_url, Some(credential));
1605            online_project_outcome(
1606                &client,
1607                config_project,
1608                &project_session,
1609                &worktree,
1610                user_default_project,
1611                project_git_url.as_deref(),
1612            )
1613            .await
1614        }
1615        _ => {
1616            // Offline (no client): only the UUID form of
1617            // `TRACEVAULT_PROJECT` can be honoured — a name would need
1618            // `list_projects`, which needs a client this arm doesn't
1619            // have. Reuses `commands::stream`'s capture-time helper
1620            // rather than duplicating the same UUID-only parse a third
1621            // time (the `project.rs` inline version stays separate: it
1622            // must distinguish "not a UUID" from "absent" so it can fall
1623            // through to name resolution, which this `Option`-returning
1624            // helper can't express).
1625            let inputs = ProjectResolveInputs {
1626                project_flag: None,
1627                env_project: crate::commands::stream::env_project_binding(),
1628                session: &project_session,
1629                worktree_path: Some(&worktree),
1630                config_project,
1631            };
1632            offline_project_outcome(&inputs, user_default_project)
1633        }
1634    };
1635
1636    let mut attribution_v = Vec::new();
1637    match session_id {
1638        Some(_) => attribution_v.extend(
1639            recording_check(session_id, attribution.as_ref())
1640                .or_else(|| inferred_recording_check(&recording)),
1641        ),
1642        // No session named: `attribution` was resolved with an empty session,
1643        // i.e. exactly what the hook sees for a new session in this checkout.
1644        None => attribution_v.push(checkout_recording_check(
1645            attribution.as_ref(),
1646            config.as_ref(),
1647        )),
1648    }
1649    attribution_v.push(binding_check);
1650    attribution_v.push(project_binding_check(&project_outcome));
1651    attribution_v.extend(legacy_default_project_check(config.as_ref()));
1652
1653    // The server target is the repo the hook would attribute this worktree's
1654    // events to — including a subagent override — not just the session's
1655    // `active` binding shown in "Workspace repo".
1656    let server_binding = if explicit_session {
1657        session_repo_binding(&project_session, &worktree)
1658    } else {
1659        None
1660    };
1661    let server_checks_v = server_repo_checks(
1662        project_root,
1663        &auth,
1664        config.as_ref(),
1665        server_binding.as_ref(),
1666    )
1667    .await;
1668    let session_checks_v = session_checks(project_root);
1669
1670    let sections: Vec<(&str, Vec<Check>)> = vec![
1671        ("Authentication", auth_checks_v),
1672        ("Installation", install_v),
1673        ("Project", proj_checks_v),
1674        ("Attribution", attribution_v),
1675        ("Server repo", server_checks_v),
1676        ("Sessions", session_checks_v),
1677    ];
1678    for (title, checks) in &sections {
1679        print_section(title, checks);
1680    }
1681    let all: Vec<&Check> = sections.iter().flat_map(|(_, v)| v.iter()).collect();
1682
1683    let errors = all.iter().filter(|c| c.level == Level::Error).count();
1684    let warns = all.iter().filter(|c| c.level == Level::Warn).count();
1685
1686    match (errors, warns) {
1687        (0, 0) => println!("{ANSI_GREEN}All good.{ANSI_RESET}"),
1688        (0, w) => println!(
1689            "{ANSI_YELLOW}{w} warning{} — no blocking issues.{ANSI_RESET}",
1690            if w == 1 { "" } else { "s" }
1691        ),
1692        (e, 0) => println!(
1693            "{ANSI_RED}{e} problem{} found.{ANSI_RESET}",
1694            if e == 1 { "" } else { "s" }
1695        ),
1696        (e, w) => println!(
1697            "{ANSI_RED}{e} problem{}, {w} warning{}.{ANSI_RESET}",
1698            if e == 1 { "" } else { "s" },
1699            if w == 1 { "" } else { "s" }
1700        ),
1701    }
1702
1703    exit_code_for(&all)
1704}
1705
1706/// Only `Level::Error` checks force a non-zero exit; `Warn` and `Skip` are
1707/// surfaced to the user but don't fail the command. Pulled out as a pure
1708/// function so the severity→exit-code mapping is unit-testable independent
1709/// of the network-calling `run_status`.
1710fn exit_code_for(checks: &[&Check]) -> i32 {
1711    if checks.iter().any(|c| c.level == Level::Error) {
1712        1
1713    } else {
1714        0
1715    }
1716}
1717
1718#[cfg(test)]
1719mod tests {
1720    use super::*;
1721
1722    #[test]
1723    fn normalize_remote_ssh_https_equal() {
1724        assert_eq!(
1725            normalize_remote("git@github.com:VirtusLab/visdom-ai-tracing.git"),
1726            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing")
1727        );
1728        assert_eq!(
1729            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing.git/"),
1730            "github.com/VirtusLab/visdom-ai-tracing"
1731        );
1732    }
1733
1734    #[test]
1735    fn normalize_remote_preserves_non_github() {
1736        assert_eq!(
1737            normalize_remote("git@gitlab.com:foo/bar.git"),
1738            "git@gitlab.com:foo/bar"
1739        );
1740    }
1741
1742    #[test]
1743    fn git_hook_check_missing_file_is_warning() {
1744        let dir = tempfile::tempdir().unwrap();
1745        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1746        assert_eq!(check.level, Level::Warn);
1747    }
1748
1749    #[test]
1750    fn git_hook_check_with_marker_is_ok() {
1751        let dir = tempfile::tempdir().unwrap();
1752        let hooks = dir.path().join(".git/hooks");
1753        std::fs::create_dir_all(&hooks).unwrap();
1754        std::fs::write(
1755            hooks.join("pre-push"),
1756            "#!/bin/sh\n# tracevault:enforce\ntracevault check\n",
1757        )
1758        .unwrap();
1759        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1760        assert_eq!(check.level, Level::Ok);
1761    }
1762
1763    #[test]
1764    fn git_hook_check_without_marker_is_warning() {
1765        let dir = tempfile::tempdir().unwrap();
1766        let hooks = dir.path().join(".git/hooks");
1767        std::fs::create_dir_all(&hooks).unwrap();
1768        std::fs::write(hooks.join("pre-push"), "#!/bin/sh\necho hi\n").unwrap();
1769        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1770        assert_eq!(check.level, Level::Warn);
1771    }
1772
1773    #[test]
1774    fn project_checks_errors_without_tracevault_dir_and_no_global_or_binding() {
1775        let dir = tempfile::tempdir().unwrap();
1776        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1777        let missing_global = dir.path().join("no-global.json");
1778        let (checks, cfg) =
1779            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1780        assert!(cfg.is_none());
1781        assert!(checks
1782            .iter()
1783            .any(|c| c.level == Level::Error && c.label == "Visdom initialized"));
1784        // The Git-hooks Skip must NOT claim "global/workspace mode" when the
1785        // user is truly unconfigured (no global install, no binding).
1786        let git_hooks = checks
1787            .iter()
1788            .find(|c| c.label == "Git hooks")
1789            .expect("Git hooks check present");
1790        assert_eq!(git_hooks.level, Level::Skip);
1791        assert!(
1792            !git_hooks.detail.contains("global/workspace mode"),
1793            "unconfigured git-hooks detail must not claim global/workspace mode: {}",
1794            git_hooks.detail
1795        );
1796    }
1797
1798    #[test]
1799    fn project_checks_no_tracevault_dir_is_not_error_in_global_mode() {
1800        let dir = tempfile::tempdir().unwrap();
1801        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1802        let missing_global = dir.path().join("no-global.json");
1803        let (checks, _) = project_checks(dir.path(), Some(missing_global.as_path()), true, false);
1804        let refs: Vec<&Check> = checks.iter().collect();
1805        assert_eq!(
1806            exit_code_for(&refs),
1807            0,
1808            "global mode must not force exit 1 on missing .visdom/"
1809        );
1810        assert!(checks
1811            .iter()
1812            .any(|c| c.label == "Visdom initialized" && c.level == Level::Skip));
1813    }
1814
1815    #[test]
1816    fn project_checks_warns_when_config_toml_missing() {
1817        // Pure workspace/detached-mode user: .visdom/ exists (or not,
1818        // doesn't matter for this check) but there's no config.toml because
1819        // `tracevault init` was never run. This must be a Warn, not an
1820        // Error, and therefore must not force the process exit code to 1.
1821        let dir = tempfile::tempdir().unwrap();
1822        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1823        std::fs::create_dir_all(dir.path().join(".visdom/sessions")).unwrap();
1824        let missing_global = dir.path().join("no-global.json");
1825        let (checks, cfg) =
1826            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1827        assert!(cfg.is_none());
1828        let project_config_check = checks
1829            .iter()
1830            .find(|c| c.label == "Project config")
1831            .expect("Project config check present");
1832        assert_eq!(project_config_check.level, Level::Warn);
1833
1834        let refs: Vec<&Check> = checks.iter().collect();
1835        assert_eq!(
1836            exit_code_for(&refs),
1837            0,
1838            "a missing config.toml alone must not force a non-zero exit code"
1839        );
1840    }
1841
1842    #[test]
1843    fn project_checks_errors_on_malformed_config_toml() {
1844        // A config.toml that exists but fails to parse is a genuine error,
1845        // distinct from "no config.toml at all" — it should stay Check::err
1846        // and keep forcing a non-zero exit code.
1847        let dir = tempfile::tempdir().unwrap();
1848        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1849        std::fs::create_dir_all(dir.path().join(".visdom")).unwrap();
1850        std::fs::write(
1851            dir.path().join(".visdom/tracing.toml"),
1852            "not valid toml {{{",
1853        )
1854        .unwrap();
1855        let missing_global = dir.path().join("no-global.json");
1856        let (checks, cfg) =
1857            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1858        assert!(cfg.is_none());
1859        let project_config_check = checks
1860            .iter()
1861            .find(|c| c.label == "Project config")
1862            .expect("Project config check present");
1863        assert_eq!(project_config_check.level, Level::Error);
1864
1865        let refs: Vec<&Check> = checks.iter().collect();
1866        assert_eq!(exit_code_for(&refs), 1);
1867    }
1868
1869    #[test]
1870    fn exit_code_for_warn_only_is_zero() {
1871        let checks = [
1872            Check::warn("a", ""),
1873            Check::ok("b", ""),
1874            Check::skip("c", ""),
1875        ];
1876        let refs: Vec<&Check> = checks.iter().collect();
1877        assert_eq!(exit_code_for(&refs), 0);
1878    }
1879
1880    #[test]
1881    fn exit_code_for_any_error_is_one() {
1882        let checks = [
1883            Check::ok("a", ""),
1884            Check::err("b", ""),
1885            Check::warn("c", ""),
1886        ];
1887        let refs: Vec<&Check> = checks.iter().collect();
1888        assert_eq!(exit_code_for(&refs), 1);
1889    }
1890
1891    #[test]
1892    fn count_pending_events_sums_across_per_repo_queues() {
1893        let dir = tempfile::tempdir().unwrap();
1894        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1895        std::fs::write(dir.path().join("pending-b.jsonl"), "line1\n").unwrap();
1896        std::fs::write(dir.path().join("pending-c.jsonl"), "").unwrap();
1897        assert_eq!(count_pending_events(dir.path(), false), 3);
1898        assert_eq!(count_pending_events(dir.path(), true), 3);
1899    }
1900
1901    #[test]
1902    fn count_pending_events_ignores_unrelated_files() {
1903        let dir = tempfile::tempdir().unwrap();
1904        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\n").unwrap();
1905        std::fs::write(dir.path().join("notes.txt"), "line1\nline2\n").unwrap();
1906        assert_eq!(count_pending_events(dir.path(), false), 1);
1907    }
1908
1909    #[test]
1910    fn count_pending_events_zero_for_empty_dir() {
1911        let dir = tempfile::tempdir().unwrap();
1912        assert_eq!(count_pending_events(dir.path(), false), 0);
1913        assert_eq!(count_pending_events(dir.path(), true), 0);
1914    }
1915
1916    #[test]
1917    fn is_pending_queue_filename_matches_per_repo_only() {
1918        assert!(!is_pending_queue_filename("pending.jsonl"));
1919        // Repo-less queues must be counted too. This holds today only
1920        // because `repo_id_from_pending_filename` matches the shared
1921        // `pending-` prefix and `status` never validates the id — i.e. by
1922        // accident. Pin it, so tightening that helper to reject the project
1923        // shape (which its name invites) cannot silently make `status` report
1924        // "0 pending" over a non-empty queue that `flush` still drains.
1925        assert!(is_pending_queue_filename(
1926            "pending-project-018f0000-0000-7000-8000-000000000abc.jsonl"
1927        ));
1928        assert!(is_pending_queue_filename("pending-a.jsonl"));
1929    }
1930
1931    #[test]
1932    fn is_pending_queue_filename_rejects_lookalikes() {
1933        assert!(!is_pending_queue_filename("pendingfoo.jsonl"));
1934        assert!(!is_pending_queue_filename("pending-.jsonl"));
1935    }
1936
1937    #[test]
1938    fn count_pending_events_legacy_pending_jsonl_requires_include_legacy() {
1939        let dir = tempfile::tempdir().unwrap();
1940        std::fs::write(dir.path().join("pending.jsonl"), "line1\nline2\n").unwrap();
1941        assert_eq!(
1942            count_pending_events(dir.path(), false),
1943            0,
1944            "legacy pending.jsonl must not be counted when there's no bound repo_id"
1945        );
1946        assert_eq!(
1947            count_pending_events(dir.path(), true),
1948            2,
1949            "legacy pending.jsonl counts once a repo_id is bound"
1950        );
1951    }
1952
1953    #[test]
1954    fn count_pending_events_legacy_and_per_repo_both_count_when_included() {
1955        let dir = tempfile::tempdir().unwrap();
1956        std::fs::write(dir.path().join("pending.jsonl"), "line1\n").unwrap();
1957        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1958        assert_eq!(count_pending_events(dir.path(), false), 2);
1959        assert_eq!(count_pending_events(dir.path(), true), 3);
1960    }
1961
1962    #[test]
1963    fn count_pending_events_ignores_lookalike_filenames() {
1964        let dir = tempfile::tempdir().unwrap();
1965        std::fs::write(dir.path().join("pendingfoo.jsonl"), "line1\n").unwrap();
1966        std::fs::write(dir.path().join("pending-.jsonl"), "line1\n").unwrap();
1967        assert_eq!(count_pending_events(dir.path(), false), 0);
1968        assert_eq!(count_pending_events(dir.path(), true), 0);
1969    }
1970
1971    #[test]
1972    fn settings_has_tracevault_hooks_detects_commands() {
1973        assert!(settings_has_tracevault_hooks(
1974            r#"{"hooks":{"PreToolUse":[{"hooks":[{"command":"tracevault stream --event pre"}]}]}}"#
1975        ));
1976        assert!(settings_has_tracevault_hooks(
1977            r#"{"command":"tracevault session-start"}"#
1978        ));
1979        assert!(settings_has_tracevault_hooks(
1980            r#"{"command":"tracevault user-prompt"}"#
1981        ));
1982        assert!(!settings_has_tracevault_hooks(
1983            r#"{"hooks":{"PreToolUse":[]}}"#
1984        ));
1985        assert!(!settings_has_tracevault_hooks("{}"));
1986    }
1987
1988    #[test]
1989    fn claude_telemetry_check_levels() {
1990        let dir = tempfile::tempdir().unwrap();
1991        let p = dir.path().join("settings.json");
1992        let server = Some("https://tv.example.com");
1993
1994        // No settings file: off.
1995        let c = claude_telemetry_check_in(
1996            &p,
1997            server,
1998            &crate::commands::claude_telemetry::Environment::default(),
1999        );
2000        assert_eq!(c.level, Level::Skip, "{c:?}");
2001
2002        crate::commands::claude_telemetry::install(
2003            dir.path(),
2004            "https://tv.example.com",
2005            &crate::commands::claude_telemetry::Environment::default(),
2006        )
2007        .unwrap();
2008        let c = claude_telemetry_check_in(
2009            &p,
2010            server,
2011            &crate::commands::claude_telemetry::Environment::default(),
2012        );
2013        assert_eq!(c.level, Level::Ok, "{c:?}");
2014        assert!(
2015            c.detail.contains("https://tv.example.com/otlp/v1/logs"),
2016            "{c:?}"
2017        );
2018
2019        // Logged in to another server than the one telemetry goes to.
2020        let c = claude_telemetry_check_in(
2021            &p,
2022            Some("https://other.example.com"),
2023            &crate::commands::claude_telemetry::Environment::default(),
2024        );
2025        assert_eq!(c.level, Level::Warn, "{c:?}");
2026
2027        // Our helper plus someone else's exporter: our token leaks there.
2028        let env = crate::commands::claude_telemetry::tests::shell("OTEL_METRICS_EXPORTER", "otlp");
2029        let c = claude_telemetry_check_in(&p, server, &env);
2030        assert_eq!(c.level, Level::Warn, "{c:?}");
2031
2032        // Only someone else's exporter: legitimate, just not ours.
2033        std::fs::write(&p, r#"{"env":{"OTEL_LOGS_EXPORTER":"console"}}"#).unwrap();
2034        let c = claude_telemetry_check_in(
2035            &p,
2036            server,
2037            &crate::commands::claude_telemetry::Environment::default(),
2038        );
2039        assert_eq!(c.level, Level::Skip, "{c:?}");
2040        assert!(c.detail.contains("exported elsewhere"), "{c:?}");
2041
2042        std::fs::write(&p, "{not json").unwrap();
2043        assert_eq!(
2044            claude_telemetry_check_in(
2045                &p,
2046                server,
2047                &crate::commands::claude_telemetry::Environment::default()
2048            )
2049            .level,
2050            Level::Warn
2051        );
2052    }
2053
2054    #[test]
2055    fn global_hook_check_ok_when_present() {
2056        let dir = tempfile::tempdir().unwrap();
2057        let p = dir.path().join("settings.json");
2058        std::fs::write(
2059            &p,
2060            r#"{"hooks":{"SessionStart":[{"hooks":[{"command":"tracevault session-start"}]}]}}"#,
2061        )
2062        .unwrap();
2063        assert_eq!(global_hook_check_in(&p).level, Level::Ok);
2064    }
2065
2066    #[test]
2067    fn global_hook_check_skip_when_absent_or_no_hooks() {
2068        let dir = tempfile::tempdir().unwrap();
2069        let missing = dir.path().join("settings.json");
2070        assert_eq!(global_hook_check_in(&missing).level, Level::Skip);
2071        let empty = dir.path().join("empty.json");
2072        std::fs::write(&empty, "{}").unwrap();
2073        assert_eq!(global_hook_check_in(&empty).level, Level::Skip);
2074    }
2075
2076    #[test]
2077    fn global_hook_check_warns_when_unreadable() {
2078        // A path that exists but isn't a readable file (a directory) yields a
2079        // non-NotFound read error → Warn, not a false "no settings.json" Skip.
2080        let dir = tempfile::tempdir().unwrap();
2081        let as_dir = dir.path().join("settings.json");
2082        std::fs::create_dir(&as_dir).unwrap();
2083        let check = global_hook_check_in(&as_dir);
2084        assert_eq!(check.level, Level::Warn);
2085        assert!(
2086            check.detail.contains("cannot read"),
2087            "detail: {}",
2088            check.detail
2089        );
2090    }
2091
2092    #[test]
2093    fn claude_hook_check_ok_from_global_only() {
2094        let dir = tempfile::tempdir().unwrap();
2095        let repo = dir.path().join(".claude"); // does not exist
2096        let global = dir.path().join("global-settings.json");
2097        std::fs::write(&global, r#"{"command":"tracevault stream"}"#).unwrap();
2098        let c = claude_hook_check_in(&repo, Some(global.as_path()));
2099        assert_eq!(c.level, Level::Ok);
2100        assert!(
2101            c.detail.to_lowercase().contains("global") || c.detail.contains("~/.claude"),
2102            "detail: {}",
2103            c.detail
2104        );
2105    }
2106
2107    #[test]
2108    fn claude_hook_check_ok_from_repo() {
2109        let dir = tempfile::tempdir().unwrap();
2110        let repo = dir.path().join(".claude");
2111        std::fs::create_dir(&repo).unwrap();
2112        std::fs::write(
2113            repo.join("settings.json"),
2114            r#"{"command":"tracevault stream"}"#,
2115        )
2116        .unwrap();
2117        let global = dir.path().join("global-settings.json"); // does not exist
2118        let c = claude_hook_check_in(&repo, Some(global.as_path()));
2119        assert_eq!(c.level, Level::Ok);
2120        assert!(
2121            c.detail.contains(".claude/settings.json"),
2122            "detail: {}",
2123            c.detail
2124        );
2125    }
2126
2127    #[test]
2128    fn claude_hook_check_ok_from_repo_local_settings() {
2129        // `init --claude-settings local` writes only settings.local.json; the
2130        // check must not warn "not registered" for it (VIS-1047).
2131        let dir = tempfile::tempdir().unwrap();
2132        let repo = dir.path().join(".claude");
2133        std::fs::create_dir(&repo).unwrap();
2134        std::fs::write(
2135            repo.join("settings.local.json"),
2136            r#"{"command":"tracevault stream"}"#,
2137        )
2138        .unwrap();
2139        let global = dir.path().join("global-settings.json"); // does not exist
2140        let c = claude_hook_check_in(&repo, Some(global.as_path()));
2141        assert_eq!(c.level, Level::Ok);
2142        assert!(
2143            c.detail.contains(".claude/settings.local.json"),
2144            "detail: {}",
2145            c.detail
2146        );
2147    }
2148
2149    #[test]
2150    fn claude_hook_check_local_settings_win_over_hookless_shared() {
2151        // A shared settings.json without our hooks (team settings) next to a
2152        // local file that has them is the usual `--claude-settings local` shape.
2153        let dir = tempfile::tempdir().unwrap();
2154        let repo = dir.path().join(".claude");
2155        std::fs::create_dir(&repo).unwrap();
2156        std::fs::write(repo.join("settings.json"), r#"{"permissions":{}}"#).unwrap();
2157        std::fs::write(
2158            repo.join("settings.local.json"),
2159            r#"{"command":"tracevault session-start"}"#,
2160        )
2161        .unwrap();
2162        assert_eq!(claude_hook_check_in(&repo, None).level, Level::Ok);
2163    }
2164
2165    #[test]
2166    fn claude_hook_check_no_global_path_uses_repo_only() {
2167        // When the home dir can't be resolved (global_settings = None), only the
2168        // repo settings are consulted — never a relative fallback.
2169        let dir = tempfile::tempdir().unwrap();
2170        let repo = dir.path().join(".claude");
2171        std::fs::create_dir(&repo).unwrap();
2172        std::fs::write(
2173            repo.join("settings.json"),
2174            r#"{"command":"tracevault stream"}"#,
2175        )
2176        .unwrap();
2177        assert_eq!(claude_hook_check_in(&repo, None).level, Level::Ok);
2178
2179        let missing = dir.path().join("nope");
2180        assert_eq!(claude_hook_check_in(&missing, None).level, Level::Warn);
2181    }
2182
2183    #[test]
2184    fn claude_hook_check_warn_when_neither() {
2185        let dir = tempfile::tempdir().unwrap();
2186        let c = claude_hook_check_in(
2187            &dir.path().join(".claude"),
2188            Some(dir.path().join("b.json").as_path()),
2189        );
2190        assert_eq!(c.level, Level::Warn);
2191        assert!(
2192            c.detail.contains("settings.local.json"),
2193            "detail: {}",
2194            c.detail
2195        );
2196    }
2197
2198    #[test]
2199    fn claude_hook_check_warns_when_repo_settings_unreadable() {
2200        let dir = tempfile::tempdir().unwrap();
2201        let repo = dir.path().join(".claude");
2202        // directory-as-file → non-NotFound read error
2203        std::fs::create_dir_all(repo.join("settings.local.json")).unwrap();
2204        let global = dir.path().join("global.json"); // missing
2205        let c = claude_hook_check_in(&repo, Some(global.as_path()));
2206        assert_eq!(c.level, Level::Warn);
2207        assert!(c.detail.contains("cannot read"), "detail: {}", c.detail);
2208        assert!(
2209            c.detail.contains("settings.local.json"),
2210            "detail: {}",
2211            c.detail
2212        );
2213    }
2214
2215    #[test]
2216    fn tracevault_init_check_severity_matrix() {
2217        assert_eq!(tracevault_init_check(true, false, false).level, Level::Ok); // present → Ok
2218        assert_eq!(tracevault_init_check(false, true, false).level, Level::Skip); // absent + global → Skip
2219        assert_eq!(tracevault_init_check(false, false, true).level, Level::Skip); // absent + binding → Skip
2220        assert_eq!(tracevault_init_check(false, true, true).level, Level::Skip);
2221        assert_eq!(
2222            tracevault_init_check(false, false, false).level,
2223            Level::Error
2224        ); // nothing → Error
2225    }
2226
2227    #[test]
2228    fn workspace_binding_explicit_id_with_binding_is_ok() {
2229        let dir = tempfile::tempdir().unwrap();
2230        let st = crate::session_state::SessionState {
2231            active: Some(crate::session_state::RepoBinding {
2232                repo_id: "11111111-1111-4111-8111-111111111111".into(),
2233                git_url: None,
2234                remote_id: None,
2235                codebase_name: None,
2236                updated_at: "t".into(),
2237            }),
2238            ..Default::default()
2239        };
2240        std::fs::write(
2241            dir.path().join("sess-9.toml"),
2242            toml::to_string(&st).unwrap(),
2243        )
2244        .unwrap();
2245        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-9"));
2246        assert_eq!(check.level, Level::Ok);
2247        assert!(
2248            check
2249                .detail
2250                .contains("11111111-1111-4111-8111-111111111111"),
2251            "detail: {}",
2252            check.detail
2253        );
2254        assert_eq!(
2255            binding.unwrap().repo_id,
2256            "11111111-1111-4111-8111-111111111111"
2257        );
2258    }
2259
2260    #[test]
2261    fn workspace_binding_explicit_id_without_binding_is_skip() {
2262        // Severity moved to `recording_check`, which is the only place that
2263        // sees both attribution axes — this check alone can't tell a
2264        // genuinely unbound machine from one attributed via the project axis.
2265        let dir = tempfile::tempdir().unwrap();
2266        std::fs::write(
2267            dir.path().join("sess-empty.toml"),
2268            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
2269        )
2270        .unwrap();
2271        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-empty"));
2272        assert_eq!(check.level, Level::Skip);
2273        assert!(binding.is_none());
2274    }
2275
2276    #[test]
2277    fn workspace_binding_no_id_empty_dir_is_skip() {
2278        let dir = tempfile::tempdir().unwrap();
2279        let (check, binding) = workspace_binding_check_in(dir.path(), None);
2280        assert_eq!(check.level, Level::Skip);
2281        assert!(binding.is_none());
2282    }
2283
2284    #[test]
2285    fn workspace_binding_no_id_scans_latest() {
2286        let dir = tempfile::tempdir().unwrap();
2287        // Two sessions; the one written LAST should be picked by the mtime scan.
2288        let older = crate::session_state::SessionState {
2289            active: Some(crate::session_state::RepoBinding {
2290                repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
2291                git_url: None,
2292                remote_id: None,
2293                codebase_name: None,
2294                updated_at: "t".into(),
2295            }),
2296            ..Default::default()
2297        };
2298        std::fs::write(
2299            dir.path().join("old.toml"),
2300            toml::to_string(&older).unwrap(),
2301        )
2302        .unwrap();
2303        // Ensure a distinct, later mtime for the second file.
2304        std::thread::sleep(std::time::Duration::from_millis(20));
2305        let newer = crate::session_state::SessionState {
2306            active: Some(crate::session_state::RepoBinding {
2307                repo_id: "bbbbbbbb-2222-4222-8222-222222222222".into(),
2308                git_url: None,
2309                remote_id: None,
2310                codebase_name: None,
2311                updated_at: "t".into(),
2312            }),
2313            ..Default::default()
2314        };
2315        std::fs::write(
2316            dir.path().join("new.toml"),
2317            toml::to_string(&newer).unwrap(),
2318        )
2319        .unwrap();
2320        let (check, binding) = workspace_binding_check_in(dir.path(), None);
2321        assert_eq!(check.level, Level::Ok);
2322        assert_eq!(
2323            binding.unwrap().repo_id,
2324            "bbbbbbbb-2222-4222-8222-222222222222",
2325            "must pick the most-recently-modified session"
2326        );
2327    }
2328
2329    #[test]
2330    fn workspace_binding_scan_skips_newest_without_binding() {
2331        // The most-recently-touched session has NO active binding, but an older
2332        // one does — the scan must find the older binding, not stop at the newest.
2333        let dir = tempfile::tempdir().unwrap();
2334        let with_binding = crate::session_state::SessionState {
2335            active: Some(crate::session_state::RepoBinding {
2336                repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
2337                git_url: None,
2338                remote_id: None,
2339                codebase_name: None,
2340                updated_at: "t".into(),
2341            }),
2342            ..Default::default()
2343        };
2344        std::fs::write(
2345            dir.path().join("older.toml"),
2346            toml::to_string(&with_binding).unwrap(),
2347        )
2348        .unwrap();
2349        std::thread::sleep(std::time::Duration::from_millis(20));
2350        // Newest file: no active binding.
2351        std::fs::write(
2352            dir.path().join("newest.toml"),
2353            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
2354        )
2355        .unwrap();
2356        let (check, binding) = workspace_binding_check_in(dir.path(), None);
2357        assert_eq!(check.level, Level::Ok);
2358        assert_eq!(
2359            binding.unwrap().repo_id,
2360            "aaaaaaaa-1111-4111-8111-111111111111"
2361        );
2362    }
2363
2364    #[test]
2365    fn workspace_binding_scan_no_active_binding_is_skip_not_warn() {
2366        // A session file exists but has no active binding (e.g. a bound-mode
2367        // user with a stray session). Scan mode must Skip, not Warn.
2368        let dir = tempfile::tempdir().unwrap();
2369        std::fs::write(
2370            dir.path().join("stray.toml"),
2371            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
2372        )
2373        .unwrap();
2374        let (check, binding) = workspace_binding_check_in(dir.path(), None);
2375        assert_eq!(check.level, Level::Skip);
2376        assert!(binding.is_none());
2377    }
2378
2379    #[test]
2380    fn workspace_binding_explicit_id_malformed_repo_id_is_warn_not_ok() {
2381        // `attribution_for` filters a resolved binding through
2382        // `binding_repo_id_is_valid` and drops it if the check fails; a
2383        // corrupted session-state file with a non-UUID `repo_id` must not
2384        // read Ok here either.
2385        let dir = tempfile::tempdir().unwrap();
2386        let st = crate::session_state::SessionState {
2387            active: Some(crate::session_state::RepoBinding {
2388                repo_id: "not-a-uuid".into(),
2389                git_url: None,
2390                remote_id: None,
2391                codebase_name: None,
2392                updated_at: "t".into(),
2393            }),
2394            ..Default::default()
2395        };
2396        std::fs::write(
2397            dir.path().join("sess-bad.toml"),
2398            toml::to_string(&st).unwrap(),
2399        )
2400        .unwrap();
2401        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-bad"));
2402        assert_eq!(check.level, Level::Warn);
2403        assert!(
2404            check.detail.contains("not a valid id"),
2405            "detail: {}",
2406            check.detail
2407        );
2408        // The raw binding is still returned (unchanged mode signal for
2409        // callers) — only this check's OWN severity changes.
2410        assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
2411    }
2412
2413    #[test]
2414    fn workspace_binding_scan_malformed_repo_id_is_warn_not_ok() {
2415        // Same rule, scan arm: `latest_active_binding_in` doesn't validate
2416        // either, so the same corrupted binding could surface via a scan.
2417        let dir = tempfile::tempdir().unwrap();
2418        let st = crate::session_state::SessionState {
2419            active: Some(crate::session_state::RepoBinding {
2420                repo_id: "not-a-uuid".into(),
2421                git_url: None,
2422                remote_id: None,
2423                codebase_name: None,
2424                updated_at: "t".into(),
2425            }),
2426            ..Default::default()
2427        };
2428        std::fs::write(
2429            dir.path().join("sess-bad.toml"),
2430            toml::to_string(&st).unwrap(),
2431        )
2432        .unwrap();
2433        let (check, binding) = workspace_binding_check_in(dir.path(), None);
2434        assert_eq!(check.level, Level::Warn);
2435        assert!(
2436            check.detail.contains("not a valid id"),
2437            "detail: {}",
2438            check.detail
2439        );
2440        assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
2441    }
2442
2443    fn repo_item(id: &str, name: &str) -> crate::api_client::RepoListItem {
2444        crate::api_client::RepoListItem {
2445            id: id.parse().unwrap(),
2446            name: name.to_string(),
2447            github_url: None,
2448            clone_status: None,
2449        }
2450    }
2451
2452    fn workspace_binding(id: &str) -> crate::session_state::RepoBinding {
2453        crate::session_state::RepoBinding {
2454            repo_id: id.into(),
2455            git_url: None,
2456            remote_id: None,
2457            codebase_name: None,
2458            updated_at: "t".into(),
2459        }
2460    }
2461
2462    #[test]
2463    fn find_repo_by_id_hits_by_id_not_name() {
2464        let id = "11111111-1111-4111-8111-111111111111";
2465        let repos = vec![repo_item(id, "myrepo")];
2466        assert_eq!(find_repo_by_id(&repos, id).unwrap().name, "myrepo");
2467        // Compared as UUIDs: an upper-cased, hand-edited id still matches.
2468        assert!(find_repo_by_id(&repos, &id.to_uppercase()).is_some());
2469    }
2470
2471    #[test]
2472    fn find_repo_by_id_ignores_same_named_repo() {
2473        // VIS-1047: someone else registered a repo with this checkout's
2474        // directory name. A name match used to show ✓ here; the id must not.
2475        let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
2476        assert!(find_repo_by_id(&repos, "22222222-2222-4222-8222-222222222222").is_none());
2477        assert!(find_repo_by_id(&repos, "myrepo").is_none());
2478    }
2479
2480    #[test]
2481    fn server_repo_lookup_uses_config_repo_id() {
2482        let config = TracevaultConfig {
2483            repo_id: Some("rid-config".into()),
2484            ..Default::default()
2485        };
2486        assert_eq!(
2487            server_repo_lookup(Some(&config), None),
2488            Some(RepoLookup::Bound("rid-config".into()))
2489        );
2490    }
2491
2492    #[test]
2493    fn server_repo_lookup_config_without_repo_id_is_missing() {
2494        // VIS-1047: the state in which the hook drops every event must not be
2495        // looked up by directory name and reported as registered.
2496        let config = TracevaultConfig::default();
2497        assert_eq!(
2498            server_repo_lookup(Some(&config), None),
2499            Some(RepoLookup::MissingRepoId)
2500        );
2501    }
2502
2503    #[test]
2504    fn server_repo_lookup_session_binding_wins_over_config() {
2505        // Same precedence as `effective_binding`: a session's active binding
2506        // outranks the bound config, so it is the repo the hook attributes to.
2507        let config = TracevaultConfig::default();
2508        let b = workspace_binding("rid-session");
2509        assert_eq!(
2510            server_repo_lookup(Some(&config), Some(&b)),
2511            Some(RepoLookup::Workspace("rid-session".into()))
2512        );
2513        assert_eq!(
2514            server_repo_lookup(None, Some(&b)),
2515            Some(RepoLookup::Workspace("rid-session".into()))
2516        );
2517    }
2518
2519    #[test]
2520    fn server_repo_lookup_none_when_neither() {
2521        assert!(server_repo_lookup(None, None).is_none());
2522    }
2523
2524    fn unauthenticated() -> AuthContext {
2525        AuthContext {
2526            server_url: None,
2527            credential: None,
2528            source: "none",
2529            email_from_creds: None,
2530            url_override_mismatch: None,
2531        }
2532    }
2533
2534    #[tokio::test]
2535    async fn server_repo_checks_missing_repo_id_is_error_before_login() {
2536        // Init-before-login: the missing repo_id is a local fact and must be
2537        // reported even though the server cannot be asked.
2538        let dir = tempfile::tempdir().unwrap();
2539        let config = TracevaultConfig::default();
2540        let checks = server_repo_checks(dir.path(), &unauthenticated(), Some(&config), None).await;
2541        assert_eq!(checks.len(), 1);
2542        assert_eq!(checks[0].level, Level::Error);
2543        assert!(
2544            checks[0].detail.contains("no repo_id"),
2545            "detail: {}",
2546            checks[0].detail
2547        );
2548    }
2549
2550    #[tokio::test]
2551    async fn server_repo_checks_with_repo_id_but_no_login_is_skip() {
2552        let dir = tempfile::tempdir().unwrap();
2553        let config = TracevaultConfig {
2554            repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
2555            ..Default::default()
2556        };
2557        let checks = server_repo_checks(dir.path(), &unauthenticated(), Some(&config), None).await;
2558        assert_eq!(checks.len(), 1);
2559        assert_eq!(checks[0].level, Level::Skip);
2560        assert!(
2561            checks[0]
2562                .detail
2563                .contains("22222222-2222-4222-8222-222222222222"),
2564            "detail: {}",
2565            checks[0].detail
2566        );
2567    }
2568
2569    #[test]
2570    fn session_repo_binding_prefers_subagent_override_like_the_hook() {
2571        // Codex R1: the server target must be the repo the hook attributes
2572        // this worktree to — a subagent override beats the active binding.
2573        let mut session = crate::session_state::SessionState {
2574            active: Some(workspace_binding("11111111-1111-4111-8111-111111111111")),
2575            ..Default::default()
2576        };
2577        session.subagents.insert(
2578            "/wt/sub".into(),
2579            workspace_binding("33333333-3333-4333-8333-333333333333"),
2580        );
2581        assert_eq!(
2582            session_repo_binding(&session, "/wt/sub").unwrap().repo_id,
2583            "33333333-3333-4333-8333-333333333333"
2584        );
2585        assert_eq!(
2586            session_repo_binding(&session, "/wt/other").unwrap().repo_id,
2587            "11111111-1111-4111-8111-111111111111"
2588        );
2589        assert!(session_repo_binding(&Default::default(), "/wt/sub").is_none());
2590    }
2591
2592    /// Runs `recording_attribution` the way `run_status` does without a named
2593    /// session, then `checkout_recording_check` on the result — in an isolated
2594    /// config home so no real user-level default leaks in.
2595    fn checkout_verdict(config: Option<&TracevaultConfig>) -> Check {
2596        let cwd = tempfile::tempdir().unwrap();
2597        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), config);
2598        checkout_recording_check(attribution.as_ref(), config)
2599    }
2600
2601    #[test]
2602    fn checkout_recording_config_without_repo_id_is_error() {
2603        // VIS-1047 case 3: right after an init-before-login, a plain terminal
2604        // must say capture is off.
2605        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2606        let cfg_tmp = tempfile::tempdir().unwrap();
2607        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2608        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2609        _guard.set("HOME", cfg_tmp.path());
2610        _guard.remove("TRACEVAULT_PROJECT");
2611
2612        let check = checkout_verdict(Some(&TracevaultConfig::default()));
2613        assert_eq!(check.level, Level::Error);
2614        assert!(
2615            check.detail.contains("no repo_id"),
2616            "detail: {}",
2617            check.detail
2618        );
2619        assert!(
2620            check.detail.contains("tracevault sync"),
2621            "detail: {}",
2622            check.detail
2623        );
2624    }
2625
2626    #[test]
2627    fn checkout_recording_config_with_invalid_repo_id_is_error() {
2628        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2629        let cfg_tmp = tempfile::tempdir().unwrap();
2630        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2631        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2632        _guard.set("HOME", cfg_tmp.path());
2633        _guard.remove("TRACEVAULT_PROJECT");
2634
2635        let config = TracevaultConfig {
2636            repo_id: Some("not-a-uuid".into()),
2637            ..Default::default()
2638        };
2639        let check = checkout_verdict(Some(&config));
2640        assert_eq!(check.level, Level::Error);
2641        assert!(
2642            check.detail.contains("not a valid id"),
2643            "detail: {}",
2644            check.detail
2645        );
2646    }
2647
2648    #[test]
2649    fn checkout_recording_config_with_repo_id_is_ok() {
2650        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2651        let cfg_tmp = tempfile::tempdir().unwrap();
2652        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2653        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2654        _guard.set("HOME", cfg_tmp.path());
2655        _guard.remove("TRACEVAULT_PROJECT");
2656
2657        let config = TracevaultConfig {
2658            repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
2659            ..Default::default()
2660        };
2661        let check = checkout_verdict(Some(&config));
2662        assert_eq!(check.level, Level::Ok);
2663        assert!(
2664            check
2665                .detail
2666                .contains("22222222-2222-4222-8222-222222222222"),
2667            "detail: {}",
2668            check.detail
2669        );
2670    }
2671
2672    #[test]
2673    fn checkout_recording_config_without_repo_id_but_user_project_is_warn() {
2674        // Events still ship (project-only), but not to this repo, which is
2675        // what a bound-mode checkout asked for.
2676        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2677        let cfg_tmp = tempfile::tempdir().unwrap();
2678        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2679        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2680        _guard.set("HOME", cfg_tmp.path());
2681        _guard.remove("TRACEVAULT_PROJECT");
2682        crate::user_project_default::save(&project_binding(
2683            &uuid::Uuid::from_u128(7).to_string(),
2684            "p",
2685        ))
2686        .unwrap();
2687
2688        let check = checkout_verdict(Some(&TracevaultConfig::default()));
2689        assert_eq!(check.level, Level::Warn);
2690        assert!(check.detail.contains("project"), "detail: {}", check.detail);
2691    }
2692
2693    #[test]
2694    fn checkout_recording_user_default_repo_without_config_is_ok() {
2695        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2696        let cfg_tmp = tempfile::tempdir().unwrap();
2697        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2698        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2699        _guard.set("HOME", cfg_tmp.path());
2700        _guard.remove("TRACEVAULT_PROJECT");
2701        crate::user_default::save(&workspace_binding("11111111-1111-4111-8111-111111111111"))
2702            .unwrap();
2703
2704        assert_eq!(checkout_verdict(None).level, Level::Ok);
2705    }
2706
2707    #[test]
2708    fn checkout_recording_nothing_bound_without_config_is_warn() {
2709        // Workspace mode binds per session, so an unbound plain terminal is
2710        // expected — but it is said out loud, not left green.
2711        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2712        let cfg_tmp = tempfile::tempdir().unwrap();
2713        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2714        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2715        _guard.set("HOME", cfg_tmp.path());
2716        _guard.remove("TRACEVAULT_PROJECT");
2717
2718        let check = checkout_verdict(None);
2719        assert_eq!(check.level, Level::Warn);
2720        // Says what will bind a new session: its checkout's remote (VIS-1048).
2721        assert!(
2722            check.detail.contains("origin remote") && check.detail.contains("tracevault sync"),
2723            "detail: {}",
2724            check.detail
2725        );
2726    }
2727
2728    #[test]
2729    fn effective_session_id_arg_wins_and_filters_empty() {
2730        assert_eq!(
2731            effective_session_id(Some("a".into()), Some("b".into())),
2732            Some("a".into())
2733        );
2734        assert_eq!(
2735            effective_session_id(Some("".into()), Some("b".into())),
2736            Some("b".into())
2737        );
2738        assert_eq!(
2739            effective_session_id(Some("   ".into()), None).as_deref(),
2740            Some("   ")
2741        ); // non-empty whitespace is a real (if odd) id — NOT filtered
2742        assert_eq!(effective_session_id(None, Some("".into())), None);
2743        assert_eq!(effective_session_id(None, None), None);
2744    }
2745
2746    fn project_binding(id: &str, name: &str) -> crate::session_state::ProjectBinding {
2747        crate::session_state::ProjectBinding {
2748            project_id: id.into(),
2749            project_name: name.into(),
2750            updated_at: "t".into(),
2751            forced_until: None,
2752        }
2753    }
2754
2755    /// `id` must be a real UUID string — `attribution_for` only accepts a
2756    /// repo binding whose `repo_id` parses as one (`binding_repo_id_is_valid`
2757    /// in stream.rs); a non-UUID id degrades to `ProjectOnly`/`None` instead.
2758    fn repo_binding_for_attribution(id: &str) -> crate::session_state::RepoBinding {
2759        crate::session_state::RepoBinding {
2760            repo_id: id.into(),
2761            git_url: None,
2762            remote_id: None,
2763            codebase_name: None,
2764            updated_at: "t".into(),
2765        }
2766    }
2767
2768    #[test]
2769    fn recording_check_truth_table() {
2770        // Literal expected outcomes, NOT a restatement of `recording_check`'s
2771        // own condition (a computed `expect_error` formula could pass even if
2772        // the implementation's condition drifted, since both would drift
2773        // together).
2774        let repo_attr = crate::commands::stream::Attribution::Repo {
2775            repo_id: "11111111-1111-4111-8111-111111111111".into(),
2776            project: None,
2777        };
2778        let project_attr = crate::commands::stream::Attribution::ProjectOnly {
2779            project_id: uuid::Uuid::from_u128(1),
2780        };
2781
2782        // session_id: None (no explicit session — a bare scan): never fires,
2783        // no matter what attribution is.
2784        assert!(recording_check(None, None).is_none());
2785        assert!(recording_check(None, Some(&repo_attr)).is_none());
2786        assert!(recording_check(None, Some(&project_attr)).is_none());
2787
2788        // session_id: Some, something resolved (either shape): no check.
2789        assert!(recording_check(Some("s"), Some(&repo_attr)).is_none());
2790        assert!(recording_check(Some("s"), Some(&project_attr)).is_none());
2791
2792        // session_id: Some, nothing resolved: the ONLY firing cell.
2793        assert_eq!(
2794            recording_check(Some("s"), None).map(|c| c.level),
2795            Some(Level::Error)
2796        );
2797    }
2798
2799    #[test]
2800    fn recording_check_error_names_project_switch_and_session() {
2801        // Defect (2): the stale `repo switch <name>` hint has to be gone and
2802        // the repo-less remediation (`project switch --user`) has to be
2803        // present, or a regression to the old text wouldn't be caught by a
2804        // plain level assertion.
2805        let check = recording_check(Some("3f27a336-abcd"), None).expect("expected an Error check");
2806        assert_eq!(check.level, Level::Error);
2807        assert!(
2808            check.detail.contains("project switch"),
2809            "detail: {}",
2810            check.detail
2811        );
2812        assert!(
2813            check.detail.contains("3f27a336-abcd"),
2814            "detail: {}",
2815            check.detail
2816        );
2817    }
2818
2819    #[test]
2820    fn project_binding_check_tiers_capture_project_honors_are_ok() {
2821        // Only the tiers `capture_project` itself resolves at capture time
2822        // read Ok: a `--project`-equivalent flag, the subagent/session-active
2823        // overrides, `TRACEVAULT_PROJECT` (`Env`, since A2 wired
2824        // `env_project_binding()` into `capture_project`'s inputs), and the
2825        // user-level default. `ConfigDefault` and `Deduced` are covered
2826        // separately — they must NOT appear here. Uses a well-formed UUID
2827        // id: an honored tier still needs a parseable `project_id` to read
2828        // Ok (see the malformed-id tests below).
2829        //
2830        // `TRACEVAULT_PROJECT` is pinned to that same UUID for the duration:
2831        // an `Env`-sourced binding can only ever exist when that var is set,
2832        // and the check now asks `env_project_binding()` whether the RAW
2833        // value is the UUID form the capture path honours (see
2834        // `project_binding_check_env_name_form_is_warn_not_ok`). Leaving the
2835        // var unset here would assert on a state that cannot occur.
2836        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2837        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2838        _guard.set("TRACEVAULT_PROJECT", "33333333-3333-4333-8333-333333333333");
2839
2840        use crate::resolution::ProjectSource::*;
2841        for source in [ProjectFlag, Subagent, Env, SessionActive, UserDefault] {
2842            let outcome: ProjectOutcome = Ok(Some((
2843                project_binding("33333333-3333-4333-8333-333333333333", "My Project"),
2844                source,
2845            )));
2846            let check = project_binding_check(&outcome);
2847            assert_eq!(check.level, Level::Ok, "source={source} should read Ok");
2848            assert!(
2849                check.detail.contains("My Project"),
2850                "source={source} detail: {}",
2851                check.detail
2852            );
2853        }
2854    }
2855
2856    /// VIS-305 whole-branch review, Important finding 2: the false green.
2857    /// `env_project_binding` is UUID-only, but `project status` and
2858    /// `run_status` both resolve a project NAME in `TRACEVAULT_PROJECT` via
2859    /// `list_projects` and report the tier as `Env`. The resolved binding's
2860    /// id then IS a valid UUID, so an id-only check reads `Ok` — whose
2861    /// documented contract is "this tier IS honoured at capture time" —
2862    /// while the hook ignores the name entirely and attributes elsewhere.
2863    ///
2864    /// The condition `capture_project` actually applies is to the RAW env
2865    /// value, so this pins that: same well-formed resolved binding, same
2866    /// `Env` tier, but `TRACEVAULT_PROJECT` holding a NAME must render
2867    /// `Warn`, worded like `unresolved_config_default_check` — resolves for
2868    /// display, not honoured on the wire.
2869    #[test]
2870    fn project_binding_check_env_name_form_is_warn_not_ok() {
2871        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2872        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2873        _guard.set("TRACEVAULT_PROJECT", "payments");
2874
2875        // Exactly what `online_project_outcome`/`resolve_status_effective`
2876        // hand back for `TRACEVAULT_PROJECT=payments`: the NAME resolved
2877        // against `list_projects`, so the id is a perfectly valid UUID.
2878        let outcome: ProjectOutcome = Ok(Some((
2879            project_binding("33333333-3333-4333-8333-333333333333", "payments"),
2880            crate::resolution::ProjectSource::Env,
2881        )));
2882        let check = project_binding_check(&outcome);
2883        assert_eq!(
2884            check.level,
2885            Level::Warn,
2886            "a NAME in TRACEVAULT_PROJECT is ignored by the capture path, so it must never read Ok: {}",
2887            check.detail
2888        );
2889        assert!(
2890            check.detail.contains("UUID form"),
2891            "the warning must say WHICH form is honoured: {}",
2892            check.detail
2893        );
2894        assert!(
2895            check.detail.contains("display only"),
2896            "worded like unresolved_config_default_check's precedent: {}",
2897            check.detail
2898        );
2899
2900        // Discrimination: the SAME binding under the UUID form still reads
2901        // Ok, so this pins the raw-value rule and not merely "Env warns".
2902        _guard.set("TRACEVAULT_PROJECT", "33333333-3333-4333-8333-333333333333");
2903        let outcome: ProjectOutcome = Ok(Some((
2904            project_binding("33333333-3333-4333-8333-333333333333", "payments"),
2905            crate::resolution::ProjectSource::Env,
2906        )));
2907        assert_eq!(project_binding_check(&outcome).level, Level::Ok);
2908    }
2909
2910    #[test]
2911    fn project_binding_check_workspace_config_is_ok() {
2912        // VIS-1256: the workspace config's `project_id` IS a capture tier,
2913        // so a valid one reads Ok, labelled with its source.
2914        let outcome: ProjectOutcome = Ok(Some((
2915            project_binding("00000000-0000-4000-8000-0000000000aa", "visdom"),
2916            crate::resolution::ProjectSource::Workspace,
2917        )));
2918        let check = project_binding_check(&outcome);
2919        assert_eq!(check.level, Level::Ok, "detail: {}", check.detail);
2920        assert_eq!(check.detail, "visdom — workspace .visdom/tracing.toml");
2921    }
2922
2923    /// A legacy `default_project` is reported as unmigrated, never resolved
2924    /// (status must match ingest, which ignores it).
2925    #[test]
2926    fn legacy_default_project_check_says_unmigrated() {
2927        let cfg = TracevaultConfig {
2928            default_project: Some("payments".into()),
2929            ..Default::default()
2930        };
2931        let check = legacy_default_project_check(Some(&cfg)).unwrap();
2932        assert_eq!(check.level, Level::Warn);
2933        assert_eq!(
2934            check.detail,
2935            "default_project \"payments\" is not used for capture until migrated; run `tracevault sync`"
2936        );
2937        assert!(legacy_default_project_check(Some(&TracevaultConfig::default())).is_none());
2938        assert!(legacy_default_project_check(None).is_none());
2939    }
2940
2941    #[test]
2942    fn project_binding_check_deduced_is_warn() {
2943        // `capture_project` never deduces server-side, so this tier can't
2944        // read Ok either — same reasoning as `ConfigDefault` above.
2945        let outcome: ProjectOutcome = Ok(Some((
2946            project_binding("pid-2", ""),
2947            crate::resolution::ProjectSource::Deduced,
2948        )));
2949        let check = project_binding_check(&outcome);
2950        assert_eq!(check.level, Level::Warn);
2951        assert!(
2952            check
2953                .detail
2954                .contains("not used for attribution at capture time"),
2955            "detail: {}",
2956            check.detail
2957        );
2958    }
2959
2960    #[test]
2961    fn project_binding_check_malformed_project_id_is_warn_not_ok() {
2962        // Aikido's finding: `capture_project` ends with
2963        // `.parse::<uuid::Uuid>().ok()?`, so a saved binding with a
2964        // non-UUID `project_id` (a hand-edited or corrupted
2965        // `user_project.toml`, or a corrupted session-state file) is
2966        // silently dropped at capture time. An honored tier with such an id
2967        // must not read Ok. Covers SessionActive and UserDefault.
2968        use crate::resolution::ProjectSource::{SessionActive, UserDefault};
2969        for source in [SessionActive, UserDefault] {
2970            let outcome: ProjectOutcome =
2971                Ok(Some((project_binding("not-a-uuid", "My Project"), source)));
2972            let check = project_binding_check(&outcome);
2973            assert_eq!(check.level, Level::Warn, "source={source}");
2974            assert!(
2975                check.detail.contains("not a valid id"),
2976                "source={source} detail: {}",
2977                check.detail
2978            );
2979        }
2980    }
2981
2982    #[test]
2983    fn project_binding_check_ambiguous_err_is_warn_not_error() {
2984        // This axis is display-only — the verdict comes from
2985        // `recording_check`'s real gate, which never deduces — so ANY failure
2986        // of the deduction call (genuinely ambiguous, or a transport/5xx
2987        // error propagated the same way) must read as Warn, never Error: a
2988        // network blip on this axis must not be able to redden the exit code.
2989        let outcome: ProjectOutcome =
2990            Err("this repo belongs to multiple projects; select one with `tracevault project switch <name>`".into());
2991        let check = project_binding_check(&outcome);
2992        assert_eq!(check.level, Level::Warn);
2993        assert!(
2994            check.detail.contains("multiple projects"),
2995            "detail: {}",
2996            check.detail
2997        );
2998    }
2999
3000    #[test]
3001    fn project_binding_check_none_is_skip() {
3002        let outcome: ProjectOutcome = Ok(None);
3003        let check = project_binding_check(&outcome);
3004        assert_eq!(check.level, Level::Skip);
3005    }
3006
3007    // --- Verdict composition: every test below drives `recording_attribution`
3008    // directly (rather than re-deriving its session-load/worktree-key/bound-
3009    // config composition by hand), so a regression in that composition —
3010    // e.g. the worktree key coming from the wrong path — fails a test instead
3011    // of only a full end-to-end run (see `recording_attribution_finds_
3012    // subagent_override_via_linked_worktree_cwd` below).
3013    //
3014    // ISOLATION: `recording_attribution` -> `capture_project` always
3015    // consults `user_project_default::load()` once its local tiers miss, and
3016    // `recording_attribution` itself calls `user_default::load()`
3017    // unconditionally — both are backed by `dirs::config_dir()`/
3018    // `dirs::home_dir()`, which read the REAL developer config on the machine
3019    // running the test unless overridden. EVERY test below therefore
3020    // redirects both `XDG_CONFIG_HOME` (the path on Linux) and `HOME` (the
3021    // path `dirs` actually uses on macOS, and `home_dir()`'s own first
3022    // choice) to the same empty temp dir — even tests that don't care about
3023    // either default, since a developer machine that has ever run
3024    // `project switch --user` or `repo switch --user` would otherwise inject
3025    // a real, non-deterministic tier and flip the test's outcome. Three of
3026    // these tests call the public `save()` (not just `load()`), so getting
3027    // this isolation wrong doesn't just make a test flaky — it overwrites
3028    // that developer's real config file.
3029    //
3030    // Every test below ALSO pins `TRACEVAULT_PROJECT` unset. Since the A2
3031    // fix, `capture_project` reads it at a rung ABOVE `session.active_
3032    // project`, so a developer who has exported it in their shell — or a
3033    // concurrently-running test in this same binary that sets it — would
3034    // otherwise silently change which project these verdicts resolve. The
3035    // crate lock serializes mutators against each other, but only holding
3036    // the lock AND declaring the var's value makes a reader safe.
3037
3038    // ---- resolve_auth: `.visdom/tracing.toml` is the lowest credential
3039    // ---- rung in `resolve_credentials`, so the inspector must know it too.
3040
3041    /// Isolate the env and the credentials file so nothing on the developer's
3042    /// machine can supply a credential these tests are asserting the absence of.
3043    fn auth_fixture() -> (
3044        tempfile::TempDir,
3045        tokio::sync::MutexGuard<'static, ()>,
3046        crate::test_helpers::EnvVarGuard,
3047    ) {
3048        let env_lock = crate::test_helpers::lock_env_mutation_sync();
3049        let dir = tempfile::tempdir().unwrap();
3050        let mut guard = crate::test_helpers::EnvVarGuard::new();
3051        guard.set("XDG_CONFIG_HOME", dir.path());
3052        guard.set("HOME", dir.path());
3053        guard.remove("TRACEVAULT_API_KEY");
3054        guard.remove("TRACEVAULT_SERVER_URL");
3055        (dir, env_lock, guard)
3056    }
3057
3058    /// The reported bug: a repo authenticated purely through `config.toml`
3059    /// works for every command, but `status` called it "no credentials found"
3060    /// and exited non-zero.
3061    #[test]
3062    fn a_config_only_setup_reads_as_logged_in() {
3063        let (_dir, _lock, _guard) = auth_fixture();
3064
3065        let auth = resolve_auth(Some("http://localhost:8080"), Some("tvk_from_config"));
3066
3067        assert_eq!(auth.server_url.as_deref(), Some("http://localhost:8080"));
3068        assert!(
3069            matches!(auth.credential, Some(Credential::ApiKey(ref k)) if k == "tvk_from_config"),
3070            "the config's key is the credential every command resolves"
3071        );
3072        assert_eq!(auth.source, "project config (.visdom/tracing.toml)");
3073    }
3074
3075    /// `resolve_credentials` resolves the URL and the credential independently,
3076    /// so an env key with the URL pinned only in the config is a working setup
3077    /// — it used to report "token found but no server URL".
3078    #[test]
3079    fn an_env_key_takes_its_url_from_the_config_when_the_env_has_none() {
3080        let (_dir, _lock, mut guard) = auth_fixture();
3081        guard.set("TRACEVAULT_API_KEY", "tvk_from_env");
3082
3083        let auth = resolve_auth(Some("http://localhost:8080"), None);
3084
3085        assert_eq!(auth.server_url.as_deref(), Some("http://localhost:8080"));
3086        assert!(matches!(auth.credential, Some(Credential::ApiKey(ref k)) if k == "tvk_from_env"));
3087        assert_eq!(auth.source, "env (TRACEVAULT_API_KEY)");
3088    }
3089
3090    /// The config is the LOWEST rung: a credentials file still outranks it, and
3091    /// its URL still wins, which is what the conflict warning then reports on.
3092    #[test]
3093    fn the_credentials_file_still_outranks_the_config() {
3094        let (dir, _lock, _guard) = auth_fixture();
3095        let creds_dir = dir.path().join("visdom");
3096        std::fs::create_dir_all(&creds_dir).unwrap();
3097        std::fs::write(
3098            creds_dir.join("credentials.json"),
3099            r#"{"server_url":"https://dev.example.com","token":"tvk_from_file","email":"a@b.com"}"#,
3100        )
3101        .unwrap();
3102
3103        let auth = resolve_auth(Some("http://localhost:8080"), Some("tvk_from_config"));
3104
3105        assert_eq!(auth.server_url.as_deref(), Some("https://dev.example.com"));
3106        assert!(matches!(auth.credential, Some(Credential::ApiKey(ref k)) if k == "tvk_from_file"));
3107        assert_eq!(auth.source, "credentials file (API key)");
3108    }
3109
3110    /// Nothing anywhere is still "none" — the fallback must not start claiming
3111    /// a credential just because a config exists without one.
3112    #[test]
3113    fn a_config_without_a_key_is_still_not_logged_in() {
3114        let (_dir, _lock, _guard) = auth_fixture();
3115
3116        let auth = resolve_auth(Some("http://localhost:8080"), None);
3117
3118        assert!(auth.credential.is_none());
3119        assert_eq!(auth.source, "none");
3120        assert_eq!(
3121            auth.server_url.as_deref(),
3122            Some("http://localhost:8080"),
3123            "the pin is still worth reporting"
3124        );
3125    }
3126
3127    #[test]
3128    fn verdict_repo_user_default_alone_is_not_an_error() {
3129        // `repo switch --user` is `resolve_stream_binding`'s lowest tier.
3130        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3131        let cfg_tmp = tempfile::tempdir().unwrap();
3132        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3133        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3134        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3135        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above
3136
3137        crate::user_default::save(&repo_binding_for_attribution(
3138            "11111111-1111-4111-8111-111111111111",
3139        ))
3140        .unwrap();
3141
3142        let cwd = tempfile::tempdir().unwrap();
3143        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
3144        assert_eq!(
3145            attribution,
3146            Some(crate::commands::stream::Attribution::Repo {
3147                repo_id: "11111111-1111-4111-8111-111111111111".into(),
3148                project: None,
3149            })
3150        );
3151        assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
3152    }
3153
3154    #[test]
3155    fn verdict_project_user_default_alone_is_not_an_error() {
3156        // `project switch --user` with no credential configured: the display
3157        // half of this same fallback is pinned separately by
3158        // `offline_project_outcome_falls_back_to_saved_user_default`.
3159        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3160        let cfg_tmp = tempfile::tempdir().unwrap();
3161        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3162        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3163        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3164        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above
3165
3166        let pb = crate::session_state::ProjectBinding {
3167            project_id: uuid::Uuid::from_u128(7).to_string(),
3168            project_name: "p".into(),
3169            updated_at: "".into(),
3170            forced_until: None,
3171        };
3172        crate::user_project_default::save(&pb).unwrap();
3173
3174        let cwd = tempfile::tempdir().unwrap();
3175        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
3176        assert_eq!(
3177            attribution,
3178            Some(crate::commands::stream::Attribution::ProjectOnly {
3179                project_id: uuid::Uuid::from_u128(7)
3180            })
3181        );
3182        assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
3183    }
3184
3185    #[test]
3186    fn verdict_config_without_repo_id_and_nothing_else_is_error() {
3187        // A loaded `config.toml` with no `repo_id` must not count as bound —
3188        // `binding_from_config` returns `None` for it.
3189        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3190        let cfg_tmp = tempfile::tempdir().unwrap();
3191        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3192        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3193        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3194        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above
3195
3196        let config = crate::config::TracevaultConfig::default();
3197        assert!(
3198            crate::resolution::binding_from_config(&config).is_none(),
3199            "a repo_id-less config must not bind"
3200        );
3201
3202        let cwd = tempfile::tempdir().unwrap();
3203        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
3204        assert_eq!(
3205            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3206            Some(Level::Error)
3207        );
3208    }
3209
3210    #[test]
3211    fn verdict_nothing_anywhere_is_error() {
3212        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3213        let cfg_tmp = tempfile::tempdir().unwrap();
3214        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3215        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3216        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3217        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above
3218
3219        let cwd = tempfile::tempdir().unwrap();
3220        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
3221        assert_eq!(
3222            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3223            Some(Level::Error)
3224        );
3225    }
3226
3227    #[test]
3228    fn verdict_deduced_project_display_does_not_suppress_recording_error() {
3229        // A `Deduced` DISPLAY value must not make the project axis count as
3230        // bound for the verdict — `capture_project` never deduces.
3231        let outcome: ProjectOutcome = Ok(Some((
3232            project_binding("pid", ""),
3233            crate::resolution::ProjectSource::Deduced,
3234        )));
3235        assert_eq!(project_binding_check(&outcome).level, Level::Warn);
3236
3237        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3238        let cfg_tmp = tempfile::tempdir().unwrap();
3239        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3240        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3241        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3242        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above
3243
3244        let cwd = tempfile::tempdir().unwrap();
3245        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
3246        assert_eq!(
3247            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3248            Some(Level::Error),
3249            "a Deduced display value must not suppress the Recording error"
3250        );
3251    }
3252
3253    #[test]
3254    fn verdict_deduction_failure_is_warn_and_does_not_affect_recording() {
3255        // A deduction failure (network blip, 5xx, or genuinely Ambiguous)
3256        // must render at most Warn, and — since `recording_check` never even
3257        // sees `project_outcome` — cannot suppress or trigger the Recording
3258        // verdict either way.
3259        let outcome: ProjectOutcome = Err("this repo belongs to multiple projects".into());
3260        assert_eq!(project_binding_check(&outcome).level, Level::Warn);
3261
3262        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3263        let cfg_tmp = tempfile::tempdir().unwrap();
3264        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3265        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3266        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3267        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above
3268
3269        let config = crate::config::TracevaultConfig {
3270            repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
3271            ..Default::default()
3272        };
3273        let cwd = tempfile::tempdir().unwrap();
3274        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
3275        // Repo bound (via config) independently of the deduction failure
3276        // above -> no error, and nothing about the `Err` outcome forced one.
3277        assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
3278    }
3279
3280    #[test]
3281    fn offline_project_outcome_falls_back_to_saved_user_default() {
3282        // A saved `project switch --user` default must surface as Ok, not
3283        // Skip, in the credential-less path — not just the pure local tiers,
3284        // which `effective_project` alone covers.
3285        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3286        let cfg_tmp = tempfile::tempdir().unwrap();
3287        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3288        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3289        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3290
3291        let pb = crate::session_state::ProjectBinding {
3292            project_id: uuid::Uuid::from_u128(9).to_string(),
3293            project_name: "My Project".into(),
3294            updated_at: "".into(),
3295            forced_until: None,
3296        };
3297        crate::user_project_default::save(&pb).unwrap();
3298
3299        let session = crate::session_state::SessionState::default();
3300        let inputs = ProjectResolveInputs {
3301            project_flag: None,
3302            env_project: None,
3303            session: &session,
3304            worktree_path: None,
3305            config_project: None,
3306        };
3307        // Same call `run_status`'s credential-less arm makes.
3308        let user_default_project = crate::user_project_default::load();
3309        let outcome = offline_project_outcome(&inputs, user_default_project);
3310        let check = project_binding_check(&outcome);
3311        assert_eq!(check.level, Level::Ok, "detail: {}", check.detail);
3312        assert!(
3313            check.detail.contains("My Project"),
3314            "detail: {}",
3315            check.detail
3316        );
3317    }
3318
3319    /// VIS-305 Part A fix: `run_status`'s client-backed arm must resolve
3320    /// `TRACEVAULT_PROJECT`'s UUID form at the `Env` rung, and the resulting
3321    /// `Check` must read Ok (not the "not used for attribution at capture
3322    /// time" Warn) — `capture_project` genuinely honours this tier as of the
3323    /// A2 fix, so the diagnostic disagreeing with real behaviour would be
3324    /// exactly the bug this batch closes.
3325    #[tokio::test]
3326    async fn online_project_outcome_resolves_env_uuid_and_reads_ok() {
3327        let _env_lock = crate::test_helpers::lock_env_mutation().await;
3328        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3329        let uuid = "55555555-5555-4555-8555-555555555555";
3330        _guard.set("TRACEVAULT_PROJECT", uuid);
3331
3332        // No `list_projects` mock: the UUID form must resolve without one.
3333        let client = ApiClient::new("http://127.0.0.1:0", Some("tok"));
3334        let session = crate::session_state::SessionState::default();
3335        let outcome = online_project_outcome(&client, None, &session, "/wt", None, None).await;
3336        let (b, source) = outcome
3337            .unwrap()
3338            .expect("TRACEVAULT_PROJECT must resolve to a binding");
3339        assert_eq!(source, ProjectSource::Env);
3340        assert_eq!(b.project_id, uuid);
3341
3342        let check = project_binding_check(&Ok(Some((b, source))));
3343        assert_eq!(
3344            check.level,
3345            Level::Ok,
3346            "an Env-sourced binding is honoured by capture_project and must read Ok: {}",
3347            check.detail
3348        );
3349    }
3350
3351    /// VIS-305 Part A fix, name form: with a client in scope,
3352    /// `TRACEVAULT_PROJECT` set to a NAME must resolve via `list_projects`,
3353    /// mirroring `commands::project`'s `status`.
3354    #[tokio::test]
3355    async fn online_project_outcome_resolves_env_name_via_the_client() {
3356        let _env_lock = crate::test_helpers::lock_env_mutation().await;
3357        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3358        _guard.set("TRACEVAULT_PROJECT", "payments");
3359
3360        let list =
3361            r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
3362        let (base, _rx) =
3363            crate::test_helpers::spawn_seq(vec![crate::test_helpers::http_json("200 OK", &list)]);
3364        let client = ApiClient::new(&base, Some("tok"));
3365        let session = crate::session_state::SessionState::default();
3366        let outcome = online_project_outcome(&client, None, &session, "/wt", None, None).await;
3367        let (b, source) = outcome
3368            .unwrap()
3369            .expect("a name should resolve via list_projects");
3370        assert_eq!(source, ProjectSource::Env);
3371        assert_eq!(b.project_name, "payments");
3372        assert_eq!(b.project_id, "11111111-1111-4111-8111-111111111111");
3373    }
3374
3375    #[test]
3376    fn recording_attribution_finds_subagent_override_via_linked_worktree_cwd() {
3377        // The subagent override is keyed by the LINKED worktree's own
3378        // toplevel, not the primary repo's — resolving from the wrong one
3379        // must miss it.
3380        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3381        let cfg_tmp = tempfile::tempdir().unwrap();
3382        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3383        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3384        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3385        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above
3386
3387        let base = tempfile::tempdir().unwrap();
3388        let repo_dir = base.path().join("repo");
3389        let wt_dir = base.path().join("wt");
3390        std::fs::create_dir_all(&repo_dir).unwrap();
3391        crate::test_helpers::init_git_repo(&repo_dir);
3392        crate::test_helpers::add_worktree(&repo_dir, &wt_dir);
3393
3394        let wt_key = crate::paths::worktree_toplevel(&wt_dir);
3395        let project_id = uuid::Uuid::from_u128(42);
3396        let mut subagent_projects = std::collections::HashMap::new();
3397        subagent_projects.insert(
3398            wt_key,
3399            crate::session_state::ProjectBinding {
3400                project_id: project_id.to_string(),
3401                project_name: "linked".into(),
3402                updated_at: "t".into(),
3403                forced_until: None,
3404            },
3405        );
3406        let state = crate::session_state::SessionState {
3407            subagent_projects,
3408            ..Default::default()
3409        };
3410        let sessions_dir = tempfile::tempdir().unwrap();
3411        std::fs::write(
3412            sessions_dir.path().join("sess-linked.toml"),
3413            toml::to_string(&state).unwrap(),
3414        )
3415        .unwrap();
3416
3417        // From the LINKED worktree cwd, the subagent override resolves.
3418        let (found, _worktree) = recording_attribution(
3419            Some(sessions_dir.path()),
3420            Some("sess-linked"),
3421            &wt_dir,
3422            None,
3423        );
3424        assert_eq!(
3425            found,
3426            Some(crate::commands::stream::Attribution::ProjectOnly { project_id })
3427        );
3428
3429        // From the PRIMARY worktree root instead, the key doesn't match, so
3430        // nothing resolves.
3431        let (missed, _worktree) = recording_attribution(
3432            Some(sessions_dir.path()),
3433            Some("sess-linked"),
3434            &repo_dir,
3435            None,
3436        );
3437        assert_eq!(missed, None);
3438    }
3439
3440    #[test]
3441    fn verdict_malformed_project_id_leaves_project_axis_unbound() {
3442        // Pins that the display fix (`project_binding_check`) and the real
3443        // verdict (`recording_attribution` -> `capture_project`) cannot
3444        // diverge: a malformed `project_id` must be dropped by both.
3445        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3446        let cfg_tmp = tempfile::tempdir().unwrap();
3447        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3448        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3449        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3450        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above
3451
3452        let state = crate::session_state::SessionState {
3453            active_project: Some(project_binding("not-a-uuid", "My Project")),
3454            ..Default::default()
3455        };
3456        let sessions_dir = tempfile::tempdir().unwrap();
3457        std::fs::write(
3458            sessions_dir.path().join("sess-bad-project.toml"),
3459            toml::to_string(&state).unwrap(),
3460        )
3461        .unwrap();
3462
3463        let cwd = tempfile::tempdir().unwrap();
3464        let (attribution, _worktree) = recording_attribution(
3465            Some(sessions_dir.path()),
3466            Some("sess-bad-project"),
3467            cwd.path(),
3468            None,
3469        );
3470        assert_eq!(
3471            attribution, None,
3472            "a malformed project_id must not resolve an attribution"
3473        );
3474        assert_eq!(
3475            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3476            Some(Level::Error)
3477        );
3478    }
3479
3480    #[test]
3481    fn verdict_malformed_repo_id_with_nothing_else_bound_is_error() {
3482        // Same principle, repo axis: `attribution_for` drops a binding whose
3483        // `repo_id` fails `binding_repo_id_is_valid`, so nothing else bound
3484        // must still error, matching `workspace_binding_*_malformed_repo_id_*`.
3485        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
3486        let cfg_tmp = tempfile::tempdir().unwrap();
3487        let mut _guard = crate::test_helpers::EnvVarGuard::new();
3488        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
3489        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
3490        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above
3491
3492        let state = crate::session_state::SessionState {
3493            active: Some(crate::session_state::RepoBinding {
3494                repo_id: "not-a-uuid".into(),
3495                git_url: None,
3496                remote_id: None,
3497                codebase_name: None,
3498                updated_at: "t".into(),
3499            }),
3500            ..Default::default()
3501        };
3502        let sessions_dir = tempfile::tempdir().unwrap();
3503        std::fs::write(
3504            sessions_dir.path().join("sess-bad-repo.toml"),
3505            toml::to_string(&state).unwrap(),
3506        )
3507        .unwrap();
3508
3509        let cwd = tempfile::tempdir().unwrap();
3510        let (attribution, _worktree) = recording_attribution(
3511            Some(sessions_dir.path()),
3512            Some("sess-bad-repo"),
3513            cwd.path(),
3514            None,
3515        );
3516        assert_eq!(
3517            attribution, None,
3518            "a malformed repo_id must not resolve an attribution"
3519        );
3520        assert_eq!(
3521            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
3522            Some(Level::Error)
3523        );
3524    }
3525
3526    #[test]
3527    fn pending_events_in_a_legacy_session_are_reported() {
3528        let dir = tempfile::tempdir().unwrap();
3529        let legacy = dir.path().join(".tracevault/sessions/old");
3530        std::fs::create_dir_all(&legacy).unwrap();
3531        std::fs::write(legacy.join("pending-a.jsonl"), "line1\nline2\n").unwrap();
3532        std::fs::create_dir_all(dir.path().join(".visdom/sessions/new")).unwrap();
3533
3534        let checks = session_checks(dir.path());
3535
3536        assert_eq!(checks.len(), 1);
3537        assert_eq!(checks[0].level, Level::Warn, "{}", checks[0].detail);
3538        assert!(
3539            checks[0].detail.contains("2 event(s) in 1/2 session(s)"),
3540            "{}",
3541            checks[0].detail
3542        );
3543    }
3544}