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