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, git_repo_name, resolve_effective_project,
12    ProjectResolveInputs, 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
118fn resolve_auth() -> AuthContext {
119    // Env var wins. Match the server-side resolution order in
120    // resolve_credentials (env > creds), except we treat the env var as
121    // authoritative without looking at the credentials file email.
122    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
123    let env_url = std::env::var("TRACEVAULT_SERVER_URL").ok();
124
125    if let Some(token) = env_key {
126        return AuthContext {
127            server_url: env_url,
128            credential: Some(Credential::ApiKey(token)),
129            source: "env (TRACEVAULT_API_KEY)",
130            email_from_creds: None,
131            // An explicitly supplied API key may target any URL by design.
132            url_override_mismatch: None,
133        };
134    }
135
136    let creds = Credentials::load();
137    if let Some(c) = creds {
138        let source = match &c.auth {
139            Some(_) => "credentials file (Keycloak session)",
140            None => "credentials file (API key)",
141        };
142        // Any credential read from the FILE is instance-bound — a `tvk_` key as
143        // much as a Keycloak session (see `api_client::resolve_credentials`,
144        // which refuses this pairing for both).
145        let url_override_mismatch = env_url.filter(|env| {
146            c.credential().is_some() && !crate::credentials::same_server(&c.server_url, env)
147        });
148        return AuthContext {
149            server_url: Some(c.server_url.clone()),
150            credential: c.credential(),
151            source,
152            // An empty email means a login saved credentials before
153            // `/auth/me` could resolve the identity (e.g. the account lacks
154            // the `tracing` role); there is nothing to compare against.
155            email_from_creds: Some(c.email).filter(|e| !e.is_empty()),
156            url_override_mismatch: url_override_mismatch.map(|env| (c.server_url, env)),
157        };
158    }
159
160    AuthContext {
161        server_url: env_url,
162        credential: None,
163        source: "none",
164        email_from_creds: None,
165        url_override_mismatch: None,
166    }
167}
168
169async fn auth_checks(auth: &AuthContext) -> Vec<Check> {
170    let mut out = Vec::new();
171
172    match (auth.credential.as_ref(), auth.server_url.as_ref()) {
173        (None, _) => {
174            out.push(Check::err(
175                "Logged in",
176                "no credentials found. Run `tracevault login --server-url <URL>`.",
177            ));
178            out.push(Check::skip("Token valid", "no token to check"));
179            return out;
180        }
181        (Some(_), None) => {
182            out.push(Check::err(
183                "Logged in",
184                "token found but no server URL (set TRACEVAULT_SERVER_URL)",
185            ));
186            out.push(Check::skip("Token valid", "no server URL to call"));
187            return out;
188        }
189        (Some(_), Some(url)) => {
190            out.push(Check::ok("Logged in", format!("{url} via {}", auth.source)));
191        }
192    }
193
194    // Reported as an ERROR, not a warning: in this state every command that
195    // needs auth refuses to run (see `api_client::resolve_credentials`), so
196    // "everything is fine except this note" would be misleading.
197    if let Some((file_url, env_url)) = &auth.url_override_mismatch {
198        out.push(Check::err(
199            "Server URL",
200            format!(
201                "TRACEVAULT_SERVER_URL is '{env_url}' but the saved login is for '{file_url}'. \
202                 Commands will refuse to run rather than send that session's token to another \
203                 instance. Unset TRACEVAULT_SERVER_URL, or run `tracevault login --server-url \
204                 {env_url}`."
205            ),
206        ));
207    }
208
209    let server_url = auth.server_url.as_ref().unwrap();
210    let client = ApiClient::with_credential(server_url, auth.credential.clone());
211    match client.get_me().await {
212        Ok(me) => {
213            let who = me.name.unwrap_or_else(|| me.email.clone());
214            let detail = match &me.role {
215                Some(role) => format!("{who} <{}> (role: {role})", me.email),
216                None => format!("{who} <{}>", me.email),
217            };
218            out.push(Check::ok("Token valid", detail));
219
220            if let Some(cached) = &auth.email_from_creds {
221                if cached != &me.email {
222                    out.push(Check::warn(
223                        "Credentials cache",
224                        format!(
225                            "cached email '{cached}' differs from server '{}' — re-run login",
226                            me.email
227                        ),
228                    ));
229                }
230            }
231        }
232        Err(GetMeError::Unauthorized) => {
233            out.push(Check::err(
234                "Token valid",
235                "rejected by server (expired or revoked). Run `tracevault login` again.",
236            ));
237        }
238        // A valid token whose account isn't authorized. Re-running login
239        // would NOT help, so this must not say "log in again".
240        Err(GetMeError::Forbidden(_)) => {
241            out.push(Check::err(
242                "Account authorized",
243                "the token is valid but this account lacks the `tracing` Keycloak realm role — \
244                 ask an administrator to grant `tracing` (or `tracing-admin`).",
245            ));
246        }
247        Err(GetMeError::Network(msg)) => {
248            out.push(Check::warn(
249                "Server reachable",
250                format!("{msg} — cannot confirm token validity"),
251            ));
252        }
253        Err(GetMeError::Server(msg)) => {
254            out.push(Check::warn("Token valid", format!("server error: {msg}")));
255        }
256    }
257    out
258}
259
260// --- Project ---
261
262/// Subset of project checks that don't need network. Returns the loaded
263/// config if present so later sections can reuse it.
264fn project_checks(
265    project_root: &Path,
266    global_settings: Option<&Path>,
267    has_global: bool,
268    has_binding: bool,
269) -> (Vec<Check>, Option<TracevaultConfig>) {
270    let mut out = Vec::new();
271
272    let is_git = project_root.join(".git").exists();
273    if is_git {
274        out.push(Check::ok(
275            "Git repository",
276            project_root.display().to_string(),
277        ));
278    } else if has_global || has_binding {
279        out.push(Check::skip(
280            "Git repository",
281            "not a git repo (global/workspace mode)",
282        ));
283    } else {
284        out.push(Check::err(
285            "Git repository",
286            "current directory is not a git repo",
287        ));
288    }
289
290    let tv_present = project_root.join(".tracevault").exists();
291    out.push(tracevault_init_check(tv_present, has_global, has_binding));
292
293    // Distinguish "no config.toml" (expected in workspace/detached mode —
294    // just a warning) from "config.toml present but malformed" (a genuine
295    // error) via `try_load`, rather than the lenient `load` which collapses
296    // both cases to `None`.
297    let config = match TracevaultConfig::try_load(project_root) {
298        Ok(Some(c)) => {
299            let url = c.server_url.as_deref().unwrap_or("<unset>");
300            out.push(Check::ok("Project config", format!("server={url}")));
301            Some(c)
302        }
303        Ok(None) => {
304            if tv_present {
305                out.push(Check::warn(
306                    "Project config",
307                    "No .tracevault/config.toml — run `tracevault init`, or use workspace mode (`tracevault repo status`).",
308                ));
309            }
310            None
311        }
312        Err(e) => {
313            out.push(Check::err(
314                "Project config",
315                format!(".tracevault/config.toml malformed: {e}"),
316            ));
317            None
318        }
319    };
320
321    if tv_present {
322        // Hooks — presence of our markers, not just existence of the hook file.
323        out.push(git_hook_check(
324            project_root,
325            "pre-push",
326            "# tracevault:enforce",
327        ));
328        out.push(git_hook_check(
329            project_root,
330            "post-commit",
331            "# tracevault:post-commit",
332        ));
333    } else if has_global || has_binding {
334        out.push(Check::skip(
335            "Git hooks",
336            "not used in global/workspace mode",
337        ));
338    } else {
339        out.push(Check::skip(
340            "Git hooks",
341            "not installed (no .tracevault/ — run `tracevault init`)",
342        ));
343    }
344
345    out.push(claude_hook_check_in(
346        &project_root.join(".claude/settings.json"),
347        global_settings,
348    ));
349
350    (out, config)
351}
352
353fn git_hook_check(project_root: &Path, name: &str, marker: &str) -> Check {
354    let path = project_root.join(".git/hooks").join(name);
355    let label = format!("Git hook: {name}");
356    if !path.exists() {
357        return Check::warn(
358            label,
359            format!(".git/hooks/{name} missing — rerun `tracevault init`"),
360        );
361    }
362    match fs::read_to_string(&path) {
363        Ok(s) if s.contains(marker) => Check::ok(label, "installed"),
364        Ok(_) => Check::warn(
365            label,
366            format!("{name} exists but no tracevault block — rerun `tracevault init`"),
367        ),
368        Err(e) => Check::warn(label, format!("cannot read hook: {e}")),
369    }
370}
371
372/// True if a Claude settings.json body wires any tracevault hook command.
373fn settings_has_tracevault_hooks(contents: &str) -> bool {
374    contents.contains("tracevault stream")
375        || contents.contains("tracevault session-start")
376        || contents.contains("tracevault user-prompt")
377}
378
379/// Whether a Claude `settings.json` wires tracevault hooks — distinguishing a
380/// genuinely-absent file from one that exists but can't be read, so an
381/// IO/permission error isn't silently reported as "not installed".
382enum SettingsHooks {
383    Present,
384    NoHooks,
385    Missing,
386    Unreadable(String),
387}
388
389fn read_settings_hooks(path: &Path) -> SettingsHooks {
390    match fs::read_to_string(path) {
391        Ok(s) if settings_has_tracevault_hooks(&s) => SettingsHooks::Present,
392        Ok(_) => SettingsHooks::NoHooks,
393        Err(e) if e.kind() == std::io::ErrorKind::NotFound => SettingsHooks::Missing,
394        Err(e) => SettingsHooks::Unreadable(e.to_string()),
395    }
396}
397
398/// Check a global `~/.claude/settings.json` for the `init --global` install.
399/// Absent / no tracevault hooks → Skip (a global install is optional); an
400/// existing-but-unreadable file → Warn (don't hide a permission/IO problem).
401fn global_hook_check_in(settings_path: &Path) -> Check {
402    match read_settings_hooks(settings_path) {
403        SettingsHooks::Present => Check::ok(
404            "Global install",
405            "hooks installed in ~/.claude/settings.json",
406        ),
407        SettingsHooks::NoHooks => Check::skip(
408            "Global install",
409            "~/.claude/settings.json has no tracevault hooks",
410        ),
411        SettingsHooks::Missing => Check::skip("Global install", "no ~/.claude/settings.json"),
412        SettingsHooks::Unreadable(e) => Check::warn(
413            "Global install",
414            format!("cannot read ~/.claude/settings.json: {e}"),
415        ),
416    }
417}
418
419/// Claude Code hooks may live per-repo (`<repo>/.claude/settings.json`) OR
420/// globally (`~/.claude/settings.json`, `init --global`). Ok if EITHER wires
421/// tracevault; an existing-but-unreadable settings file is surfaced as a Warn
422/// with the path (not a generic "not registered"); Warn if neither wires it.
423fn claude_hook_check_in(repo_settings: &Path, global_settings: Option<&Path>) -> Check {
424    let repo = read_settings_hooks(repo_settings);
425    if matches!(repo, SettingsHooks::Present) {
426        return Check::ok("Claude Code hooks", "registered in .claude/settings.json");
427    }
428    let global = global_settings.map(read_settings_hooks);
429    if matches!(global, Some(SettingsHooks::Present)) {
430        return Check::ok("Claude Code hooks", "via global install (see Installation)");
431    }
432    if let SettingsHooks::Unreadable(e) = &repo {
433        return Check::warn(
434            "Claude Code hooks",
435            format!("cannot read <repo>/.claude/settings.json: {e}"),
436        );
437    }
438    if let Some(SettingsHooks::Unreadable(e)) = &global {
439        return Check::warn(
440            "Claude Code hooks",
441            format!("cannot read ~/.claude/settings.json: {e}"),
442        );
443    }
444    Check::warn(
445        "Claude Code hooks",
446        "not registered in <repo>/.claude/settings.json or ~/.claude/settings.json (capture will miss some events)",
447    )
448}
449
450/// Severity of the "TraceVault initialized" check. A per-repo `.tracevault/`
451/// present is always Ok. Absent is EXPECTED (Skip) when the user has a global
452/// install or an active workspace binding; only a truly-unconfigured setup
453/// (none of the three) is an Error.
454fn tracevault_init_check(tv_dir_present: bool, has_global: bool, has_binding: bool) -> Check {
455    if tv_dir_present {
456        Check::ok("TraceVault initialized", ".tracevault/ present")
457    } else if has_global || has_binding {
458        Check::skip(
459            "TraceVault initialized",
460            "no per-repo .tracevault/ — global/workspace mode",
461        )
462    } else {
463        Check::err(
464            "TraceVault initialized",
465            "not set up: run `tracevault init` (per-repo) or `tracevault init --global`",
466        )
467    }
468}
469
470/// The most-recently-modified session in `sessions_dir` that HAS an active
471/// binding, as `(session_id, binding)`. Scans ALL session files (newest first)
472/// rather than only the newest file, so a real binding isn't missed when the
473/// most-recently-touched session happens to have none. `None` if no session
474/// carries an active binding.
475fn latest_active_binding_in(
476    sessions_dir: &Path,
477) -> Option<(String, crate::session_state::RepoBinding)> {
478    let mut sessions: Vec<(std::time::SystemTime, String)> = Vec::new();
479    for entry in fs::read_dir(sessions_dir).ok()?.flatten() {
480        let name = entry.file_name();
481        let name = name.to_str().unwrap_or("");
482        let Some(id) = name.strip_suffix(".toml") else {
483            continue;
484        };
485        if id.is_empty() {
486            continue;
487        }
488        let Ok(mtime) = entry.metadata().and_then(|m| m.modified()) else {
489            continue;
490        };
491        sessions.push((mtime, id.to_string()));
492    }
493    sessions.sort_by_key(|(mtime, _)| std::cmp::Reverse(*mtime)); // newest first
494    for (_, id) in sessions {
495        if let Some(b) = crate::session_state::load_from(sessions_dir, &id).active {
496            return Some((id, b));
497        }
498    }
499    None
500}
501
502/// One clear rule for the "Workspace repo" check, shared by both arms of
503/// [`workspace_binding_check_in`] below: `Ok` only when
504/// `binding_repo_id_is_valid` — the SAME predicate `attribution_for` filters
505/// through before honoring a repo binding — passes. A corrupted/hand-edited
506/// session-state file can carry a `repo_id` that isn't a real UUID;
507/// `attribution_for` silently drops such a binding, so showing it as `Ok`
508/// here would be green for something the hook will not honor.
509/// `detail_suffix` carries the arm-specific "(session {id})" / "most recent
510/// session..." wording; the base "repo {id} via repo switch" text stays
511/// identical to before this check existed.
512fn workspace_repo_binding_check(
513    b: &crate::session_state::RepoBinding,
514    detail_suffix: &str,
515) -> Check {
516    let base = format!("repo {} via repo switch{detail_suffix}", b.repo_id);
517    if crate::commands::stream::binding_repo_id_is_valid(&b.repo_id) {
518        Check::ok("Workspace repo", base)
519    } else {
520        Check::warn(
521            "Workspace repo",
522            format!(
523                "{base} — this repo_id is not a valid id and will be dropped at capture time; run `tracevault repo switch <path>` to rewrite it"
524            ),
525        )
526    }
527}
528
529/// Resolve the workspace binding for `status` — the repo axis of
530/// attribution. With an explicit session id the user named a target, but a
531/// missing binding is only a Skip here: this check sees the repo axis alone,
532/// so it cannot tell a genuinely unbound machine (nothing will record) from
533/// one that's fully attributed via the project axis (`project switch
534/// --user`). Only [`recording_check`], which sees both axes, can make that
535/// call — so it also owns the escalation and the remediation hint; this
536/// check states the bare fact and stops (in particular, it does NOT suggest
537/// `tracevault repo switch …`: since v0.28.0 that command takes a checkout
538/// path and rejects binding by session name, which is exactly the situation
539/// on the repo-less machine this check is describing).
540///
541/// Without an explicit id, best-effort scan across all sessions (state is
542/// global): show the most recent that HAS a binding, and stay quiet (Skip)
543/// when none does — so a bound-mode user with a stray empty session file
544/// isn't warned. Returns the Check AND the resolved binding (reused by the
545/// caller as the `has_binding` mode signal).
546fn workspace_binding_check_in(
547    sessions_dir: &Path,
548    explicit_session_id: Option<&str>,
549) -> (Check, Option<crate::session_state::RepoBinding>) {
550    match explicit_session_id {
551        Some(id) => {
552            let state = crate::session_state::load_from(sessions_dir, id);
553            match state.active {
554                Some(b) => {
555                    let check = workspace_repo_binding_check(&b, &format!(" (session {id})"));
556                    (check, Some(b))
557                }
558                None => (
559                    Check::skip(
560                        "Workspace repo",
561                        format!("session {id} has no active binding"),
562                    ),
563                    None,
564                ),
565            }
566        }
567        None => match latest_active_binding_in(sessions_dir) {
568            Some((id, b)) => {
569                let suffix = format!(
570                    " — most recent session with a binding: {id} (may be another repo; pass --session-id to target one)"
571                );
572                let check = workspace_repo_binding_check(&b, &suffix);
573                (check, Some(b))
574            }
575            None => (
576                Check::skip("Workspace repo", "no active workspace binding found"),
577                None,
578            ),
579        },
580    }
581}
582
583// --- Attribution: project axis + the combined recording verdict ---
584
585/// The already-resolved project-attribution outcome consumed by
586/// [`project_binding_check`]: either the full server-aware chain
587/// (`resolve_effective_project`) or, when no API client is available, the
588/// pure local tiers (`effective_project`) wrapped in `Ok` so both code paths
589/// in `run_status` produce the same shape. Reuses `resolution.rs`'s own
590/// `Option<(ProjectBinding, ProjectSource)>`/`Box<dyn Error>` types rather
591/// than introducing a parallel enum, so `ProjectSource`'s tier labels (and
592/// its `Display` impl) stay the single source of truth.
593type ProjectOutcome = Result<
594    Option<(crate::session_state::ProjectBinding, ProjectSource)>,
595    Box<dyn std::error::Error>,
596>;
597
598/// Display label for a project binding: the friendly name, falling back to
599/// the id when unset. A `Deduced` binding carries an empty `project_name`
600/// (`resolve_effective_project` doesn't enrich it) and is shown by id rather
601/// than name: the credentialed arm below only ever calls `list_projects`
602/// when a config `default_project` is set, so a name lookup for `Deduced` is
603/// not reliably available — falling back to the id keeps this consistent
604/// across both cases rather than sometimes showing a name and sometimes an
605/// id depending on unrelated config state.
606fn project_label(binding: &crate::session_state::ProjectBinding) -> &str {
607    if binding.project_name.is_empty() {
608        &binding.project_id
609    } else {
610        &binding.project_name
611    }
612}
613
614/// Maps the resolved project-attribution outcome to the "Project" check.
615/// Pure and network-free — the resolution already happened in `run_status`.
616/// DISPLAY ONLY: this outcome never feeds [`recording_check`]'s verdict — see
617/// that function's doc comment for why.
618///
619/// One rule decides `Ok`: the tier must be one `capture_project` itself
620/// honors (flag/subagent/session-active/user-default — NOT `ConfigDefault`
621/// or `Deduced`, which it excludes/never produces), AND the binding's
622/// `project_id` must parse as a UUID, since `capture_project` ends with
623/// `.parse::<uuid::Uuid>().ok()?` and silently drops anything that doesn't.
624/// Either failure renders `Warn`, not `Ok` — showing green for a binding the
625/// capture path will not honor is the exact confusion this command exists to
626/// eliminate (a hand-edited or corrupted `user_project.toml` with a garbage
627/// `project_id` is a real way to hit the id-validity half of this).
628///
629/// `Err` — the ambiguous "this repo belongs to multiple projects" case, or
630/// any transport/5xx failure of the deduction call (`resolve_effective_project`
631/// propagates both the same way via `?`) — is also at most a `Warn`, never an
632/// `Error`: this axis is display-only, so a network blip must never be able
633/// to redden the exit code on its own. Matches how the rest of `status`
634/// treats transport failure (`GetMeError::Network`, a failed `list_repos`) as
635/// Warn, not Error.
636///
637/// `None` (nothing bound on this axis) is a `Skip` — severity for "nothing
638/// will be recorded" is [`recording_check`]'s job, since only it consults the
639/// actual recording gate.
640fn project_binding_check(outcome: &ProjectOutcome) -> Check {
641    match outcome {
642        Err(e) => Check::warn("Project", e.to_string()),
643        Ok(None) => Check::skip(
644            "Project",
645            "not bound — run `tracevault project switch --user \"<name>\"`, or `tracevault repo switch <path>` inside a checkout",
646        ),
647        Ok(Some((binding, source))) => {
648            let honored_tier = matches!(
649                source,
650                ProjectSource::ProjectFlag
651                    | ProjectSource::Subagent
652                    | ProjectSource::SessionActive
653                    | ProjectSource::UserDefault
654            );
655            let label = project_label(binding);
656            if !honored_tier {
657                Check::warn(
658                    "Project",
659                    format!(
660                        "{label} — {source}, not used for attribution at capture time; set one explicitly with `tracevault project switch <name>` or --project"
661                    ),
662                )
663            } else if binding.project_id.parse::<uuid::Uuid>().is_err() {
664                Check::warn(
665                    "Project",
666                    format!(
667                        "{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"
668                    ),
669                )
670            } else {
671                Check::ok("Project", format!("{label} — {source}"))
672            }
673        }
674    }
675}
676
677/// Surfaces a `.tracevault/config.toml` `default_project` NAME that failed
678/// to resolve to a real project (network failure, no matching name, or a
679/// case mismatch — names are matched case-sensitively). Without this, the
680/// tier is silently dropped: `commands::project`'s `status` warns for the
681/// same gap (project.rs:284-289) via a plain `eprintln!`, but `status` has
682/// no equivalent, so a stale/misspelled `default_project` is invisible here.
683///
684/// Always a `Warn`, and the wording says so explicitly: even a `default_project`
685/// that DOES resolve is a `ConfigDefault` tier `capture_project` excludes (see
686/// [`project_binding_check`]), so this unresolved case must not imply fixing
687/// the name would make attribution work at capture time — it would still need
688/// `tracevault project switch <name>` or `--project`.
689fn unresolved_config_default_check(name: &str) -> Check {
690    Check::warn(
691        "Project default",
692        format!(
693            "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"
694        ),
695    )
696}
697
698/// The one check that reflects whether anything will record this session at
699/// all. Takes the ALREADY-RESOLVED [`crate::commands::stream::Attribution`] —
700/// the exact same value `attribution_for(resolve_stream_binding(...),
701/// capture_project(...))` the `stream` hook itself computes before deciding
702/// to no-op — rather than a hand-built approximation of the two axes. Coupling
703/// to the hook's own gate this way is load-bearing: the repo axis has tiers
704/// (`repo switch --user`, a config with no `repo_id`) and the project axis has
705/// tiers (`project switch --user` with no credential, `Deduced`/`ConfigDefault`
706/// display values `capture_project` doesn't honor) that a hand-rolled
707/// `repo_bound`/`project_bound` pair would have to re-derive and could get
708/// wrong; calling the real functions means the two can't drift apart.
709///
710/// Only fires for an explicitly named session (`--session-id` /
711/// `$TRACEVAULT_SESSION_ID`, i.e. `session_id.is_some()`) — a bare scan has no
712/// committed target, so there's nothing to escalate about. Pure and
713/// network-free: `attribution` is computed by the caller from purely local
714/// tiers (mirroring the hook), so this check — and the verdict it drives —
715/// can never be swayed by a network hiccup.
716fn recording_check(
717    session_id: Option<&str>,
718    attribution: Option<&crate::commands::stream::Attribution>,
719) -> Option<Check> {
720    let id = session_id?;
721    if attribution.is_some() {
722        return None;
723    }
724    Some(Check::err(
725        "Recording",
726        format!(
727            "nothing will be recorded — session {id} is bound on neither the repo nor the \
728             project axis; run `tracevault project switch --user \"<name>\"` on a repo-less \
729             machine, or `tracevault repo switch <path>` inside a checkout"
730        ),
731    ))
732}
733
734/// Compose the "will this session record anything" gate exactly as
735/// `run_status` and the `stream` hook do: load the session state, derive the
736/// worktree key from `cwd`, extract a bound-config `RepoBinding` (if any),
737/// and call `resolve_stream_binding` -> `capture_project` -> `attribution_for`
738/// with those inputs. Pure and synchronous — network-free, matching the two
739/// functions it calls. Returns the worktree key alongside the attribution so
740/// callers that also need it (the project-display resolution in `run_status`)
741/// don't re-shell out to git for the same value.
742///
743/// Deliberately derives its OWN worktree key from `cwd` (via
744/// `crate::paths::worktree_toplevel`) rather than taking a pre-computed key as
745/// a parameter: `cwd` is the toplevel a `stream` hook invocation actually runs
746/// from, which for a LINKED worktree is NOT the same string as `project_root`
747/// (the PRIMARY worktree's root, from `resolve_project_root`'s
748/// `git rev-parse --git-common-dir`) — subagent overrides are keyed by the
749/// former. Keeping the derivation INSIDE this function, with every attribution
750/// test calling it directly rather than re-deriving the key by hand, is what
751/// makes `recording_attribution_finds_subagent_override_via_linked_worktree_cwd`
752/// able to catch a regression back to a primary-root path.
753fn recording_attribution(
754    sessions_dir: Option<&Path>,
755    session_id: Option<&str>,
756    cwd: &Path,
757    config: Option<&TracevaultConfig>,
758) -> (Option<crate::commands::stream::Attribution>, String) {
759    let session = match (sessions_dir, session_id) {
760        (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
761        _ => crate::session_state::SessionState::default(),
762    };
763    let worktree = crate::paths::worktree_toplevel(cwd);
764    let bound = config.and_then(crate::resolution::binding_from_config);
765    let user_default_repo = crate::user_default::load();
766    let stream_binding = crate::commands::stream::resolve_stream_binding(
767        &session,
768        &worktree,
769        bound,
770        user_default_repo,
771    );
772    let capture_pid = crate::commands::stream::capture_project(&session, Some(&worktree));
773    let attribution =
774        crate::commands::stream::attribution_for(stream_binding.as_ref(), capture_pid);
775    (attribution, worktree)
776}
777
778/// The project axis's offline/no-client display fallback: the pure local
779/// tiers (`effective_project`) plus the user-level project default as the
780/// lowest tier. `effective_project` alone never consults the user default —
781/// only `resolve_effective_project` (the networked chain) does — so without
782/// this, a repo-less pod attributed solely via `project switch --user`, with
783/// no credential/server URL configured, would show "not bound" on the
784/// "Project" line while `recording_attribution` (which reads this same tier
785/// independently via `capture_project`) correctly shows the session as
786/// recording. Pulled out as its own pure function so this fallback is
787/// unit-testable without driving all of `run_status`.
788fn offline_project_outcome(
789    inputs: &ProjectResolveInputs,
790    user_default_project: Option<crate::session_state::ProjectBinding>,
791) -> ProjectOutcome {
792    Ok(effective_project(inputs)
793        .or_else(|| user_default_project.map(|b| (b, ProjectSource::UserDefault))))
794}
795
796// --- Server repo ---
797
798/// How `status` should locate the repo on the server.
799#[derive(Debug, Clone, PartialEq)]
800enum RepoMatch {
801    ByName(String),
802    ById(String),
803}
804
805/// Bound mode (a loaded project config, match by git repo NAME) takes
806/// precedence; otherwise workspace mode (the authoritative binding, match by
807/// `repo_id`). `None` when neither is available. Pure — `repo_name` is passed
808/// in so this is unit-testable without invoking git.
809fn server_repo_lookup(
810    config_present: bool,
811    repo_name: &str,
812    binding: Option<&crate::session_state::RepoBinding>,
813) -> Option<RepoMatch> {
814    if config_present {
815        return Some(RepoMatch::ByName(repo_name.to_string()));
816    }
817    if let Some(b) = binding {
818        return Some(RepoMatch::ById(b.repo_id.clone()));
819    }
820    None
821}
822
823/// Find the repo matching `want`, retrying by workspace-binding id if a
824/// `ByName` lookup misses. A directory rename after `tracevault init`
825/// registered the repo would otherwise make the (name-based) bound-mode
826/// lookup miss even though the binding's `repo_id` still resolves — since this
827/// is a read-only inspector, a stale name should not produce a false "not
828/// found on server" negative when a binding is available to double-check
829/// against. Returns the matched repo plus the [`RepoMatch`] that actually
830/// found it, so the caller can tell a direct hit from a fallback hit (the
831/// fallback must not be treated as if the name-based lookup had succeeded —
832/// see the `RepoMatch::ById` arm of the "Remote URL matches" check below).
833/// `ById` lookups have already tried the only id available, so they are never
834/// retried.
835fn find_repo_with_fallback<'a>(
836    repos: &'a [crate::api_client::RepoListItem],
837    want: &RepoMatch,
838    binding: Option<&crate::session_state::RepoBinding>,
839) -> Option<(&'a crate::api_client::RepoListItem, RepoMatch)> {
840    if let Some(r) = repos.iter().find(|r| match want {
841        RepoMatch::ByName(name) => &r.name == name,
842        RepoMatch::ById(id) => &r.id.to_string() == id,
843    }) {
844        return Some((r, want.clone()));
845    }
846    if let RepoMatch::ByName(_) = want {
847        let b = binding?;
848        let r = repos.iter().find(|r| r.id.to_string() == b.repo_id)?;
849        return Some((r, RepoMatch::ById(b.repo_id.clone())));
850    }
851    None
852}
853
854async fn server_repo_checks(
855    project_root: &Path,
856    auth: &AuthContext,
857    config: Option<&TracevaultConfig>,
858    binding: Option<&crate::session_state::RepoBinding>,
859) -> Vec<Check> {
860    let mut out = Vec::new();
861
862    let (Some(credential), Some(server_url)) = (auth.credential.clone(), auth.server_url.as_ref())
863    else {
864        out.push(Check::skip(
865            "Repo registered on server",
866            "not authenticated",
867        ));
868        return out;
869    };
870
871    let repo_name = git_repo_name(project_root);
872    let Some(want) = server_repo_lookup(config.is_some(), &repo_name, binding) else {
873        out.push(Check::skip(
874            "Repo registered on server",
875            "not bound (need a project config.toml or a --session-id workspace binding)",
876        ));
877        return out;
878    };
879
880    let client = ApiClient::with_credential(server_url, Some(credential));
881    let repos = match client.list_repos().await {
882        Ok(r) => r,
883        Err(e) => {
884            out.push(Check::warn(
885                "Repo registered on server",
886                format!("failed to list repos: {e}"),
887            ));
888            return out;
889        }
890    };
891
892    let found = find_repo_with_fallback(&repos, &want, binding);
893
894    match found {
895        None => {
896            let what = match &want {
897                RepoMatch::ByName(n) => format!("'{n}'"),
898                RepoMatch::ById(id) => format!("repo id {id}"),
899            };
900            out.push(Check::err(
901                "Repo registered on server",
902                format!("{what} not found on the server. Run `tracevault init` while logged in, or `tracevault sync`."),
903            ));
904            return out;
905        }
906        Some((r, matched_via)) => {
907            out.push(Check::ok(
908                "Repo registered on server",
909                format!("id={}", r.id),
910            ));
911            match r.clone_status.as_deref() {
912                Some("ready") => out.push(Check::ok("Server-side clone", "ready")),
913                Some(other @ ("cloning" | "pending")) => out.push(Check::warn(
914                    "Server-side clone",
915                    format!("{other} — analytics and code browser unavailable until it finishes"),
916                )),
917                Some("error") => out.push(Check::err(
918                    "Server-side clone",
919                    "error — check the repo settings page on the dashboard",
920                )),
921                Some(other) => out.push(Check::warn(
922                    "Server-side clone",
923                    format!("unknown status '{other}'"),
924                )),
925                None => out.push(Check::skip(
926                    "Server-side clone",
927                    "server did not report clone status",
928                )),
929            }
930
931            match &matched_via {
932                RepoMatch::ByName(_) => {
933                    let local_remote = git_remote_url(project_root);
934                    match (local_remote.as_deref(), r.github_url.as_deref()) {
935                        (Some(local), Some(remote))
936                            if normalize_remote(local) == normalize_remote(remote) =>
937                        {
938                            out.push(Check::ok("Remote URL matches", remote.to_string()));
939                        }
940                        (Some(local), Some(remote)) => out.push(Check::warn(
941                            "Remote URL matches",
942                            format!("local={local} vs server={remote} — run `tracevault sync`"),
943                        )),
944                        (Some(local), None) => out.push(Check::warn(
945                            "Remote URL matches",
946                            format!("server has no github_url; local={local}"),
947                        )),
948                        (None, _) => out.push(Check::warn(
949                            "Remote URL matches",
950                            "no local `origin` remote configured",
951                        )),
952                    }
953                }
954                RepoMatch::ById(_) => {
955                    out.push(Check::skip(
956                        "Remote URL matches",
957                        "n/a in workspace mode (bound by name/id)",
958                    ));
959                }
960            }
961        }
962    }
963
964    out
965}
966
967// --- Sessions ---
968
969/// True for a per-repo `pending-<id>.jsonl` (nonempty id) queue file —
970/// tighter than a bare `starts_with("pending") && ends_with(".jsonl")`
971/// check, which would also match e.g. `pendingfoo.jsonl` or `pending-.jsonl`.
972/// The legacy `pending.jsonl` name is handled separately by callers, since
973/// whether it counts depends on whether there's a bound `repo_id` to
974/// attribute it to (see `count_pending_events`).
975fn is_pending_queue_filename(name: &str) -> bool {
976    crate::commands::flush::repo_id_from_pending_filename(name).is_some()
977}
978
979/// Sum the non-empty lines across every per-repo (and, if `include_legacy`,
980/// legacy) pending queue file in a session directory: `pending.jsonl` and
981/// `pending-<repo_id>.jsonl`.
982///
983/// `include_legacy` should be true only when the project has a bound
984/// `repo_id` (config.toml), since `flush` only drains the legacy
985/// `pending.jsonl` in that case (best-effort attribution). Otherwise a
986/// stray `pending.jsonl` would be counted here but never cleared by
987/// `flush`, leaving `status` permanently reporting stuck events.
988fn count_pending_events(session_dir: &Path, include_legacy: bool) -> usize {
989    let Ok(read) = fs::read_dir(session_dir) else {
990        return 0;
991    };
992
993    read.flatten()
994        .filter(|entry| {
995            entry
996                .file_name()
997                .to_str()
998                .map(|name| {
999                    is_pending_queue_filename(name) || (include_legacy && name == "pending.jsonl")
1000                })
1001                .unwrap_or(false)
1002        })
1003        .map(|entry| {
1004            fs::read_to_string(entry.path())
1005                .unwrap_or_default()
1006                .lines()
1007                .filter(|l| !l.trim().is_empty())
1008                .count()
1009        })
1010        .sum()
1011}
1012
1013fn session_checks(project_root: &Path) -> Vec<Check> {
1014    let sessions_dir = project_root.join(".tracevault/sessions");
1015    if !sessions_dir.exists() {
1016        return vec![Check::skip(
1017            "Pending events",
1018            "no .tracevault/sessions/ here (project-local check; a detached worker's queue may live under its own working dir)",
1019        )];
1020    }
1021
1022    // The legacy `pending.jsonl` is only drainable by `flush` when there's a
1023    // bound `repo_id` to attribute it to (best-effort attribution). Counting
1024    // it here otherwise would report events that `flush` can never clear.
1025    let include_legacy = TracevaultConfig::load(project_root)
1026        .and_then(|c| c.repo_id)
1027        .is_some();
1028
1029    let mut total_sessions = 0usize;
1030    let mut sessions_with_pending = 0usize;
1031    let mut pending_event_count = 0usize;
1032
1033    if let Ok(read) = fs::read_dir(&sessions_dir) {
1034        for entry in read.flatten() {
1035            if !entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
1036                continue;
1037            }
1038            total_sessions += 1;
1039            let count = count_pending_events(&entry.path(), include_legacy);
1040            if count > 0 {
1041                sessions_with_pending += 1;
1042                pending_event_count += count;
1043            }
1044        }
1045    }
1046
1047    vec![if sessions_with_pending == 0 {
1048        Check::ok(
1049            "Pending events",
1050            format!("{total_sessions} session(s), all synced (project-local)"),
1051        )
1052    } else {
1053        Check::warn(
1054            "Pending events",
1055            format!(
1056                "{pending_event_count} event(s) in {sessions_with_pending}/{total_sessions} session(s) — run `tracevault flush`"
1057            ),
1058        )
1059    }]
1060}
1061
1062// --- Git helpers ---
1063
1064/// Make two remote URLs comparable by dropping `.git`, trailing slash, and
1065/// collapsing SSH ↔ HTTPS differences for github.com specifically.
1066fn normalize_remote(url: &str) -> String {
1067    let trimmed = url
1068        .trim()
1069        .trim_end_matches('/')
1070        .trim_end_matches(".git")
1071        .to_string();
1072
1073    // git@github.com:org/repo  ->  github.com/org/repo
1074    if let Some(rest) = trimmed.strip_prefix("git@github.com:") {
1075        return format!("github.com/{rest}");
1076    }
1077    // https://github.com/org/repo -> github.com/org/repo
1078    for p in ["https://", "http://"] {
1079        if let Some(rest) = trimmed.strip_prefix(p) {
1080            return rest.to_string();
1081        }
1082    }
1083    trimmed
1084}
1085
1086// --- Entry point ---
1087
1088/// Resolve the session id for `status`: an explicit `--session-id` wins, else
1089/// `$TRACEVAULT_SESSION_ID`; empty strings are ignored (fall through).
1090pub fn effective_session_id(arg: Option<String>, env: Option<String>) -> Option<String> {
1091    arg.filter(|s| !s.is_empty())
1092        .or_else(|| env.filter(|s| !s.is_empty()))
1093}
1094
1095pub async fn run_status(project_root: &Path, cwd: &Path, session_id: Option<&str>) -> i32 {
1096    let auth = resolve_auth();
1097
1098    // ~/.claude/settings.json — None when the home dir can't be resolved. Do
1099    // NOT fall back to a relative `.claude/settings.json`: that would read the
1100    // repo's own settings and could report a false "Global install".
1101    let global_settings: Option<PathBuf> =
1102        dirs::home_dir().map(|h| h.join(".claude").join("settings.json"));
1103    let sessions_dir = crate::session_state::sessions_dir();
1104
1105    let global_check = match global_settings.as_deref() {
1106        Some(p) => global_hook_check_in(p),
1107        None => Check::skip("Global install", "cannot determine home directory"),
1108    };
1109    let has_global = global_check.level == Level::Ok;
1110
1111    // Resolve the workspace binding ONCE: it drives both the section and the
1112    // `has_binding` mode signal used by project_checks.
1113    let (binding_check, binding) = match sessions_dir.as_deref() {
1114        Some(dir) => workspace_binding_check_in(dir, session_id),
1115        None => (
1116            Check::skip("Workspace repo", "cannot determine session state dir"),
1117            None,
1118        ),
1119    };
1120    // A binding only counts as a mode signal when the session was named
1121    // explicitly (--session-id / $TRACEVAULT_SESSION_ID). A *scanned* binding
1122    // (no session id) is cwd-agnostic and may belong to another repo, so it is
1123    // shown for information but must NOT downgrade "not set up" severity nor
1124    // drive the server-repo check.
1125    let explicit_session = session_id.is_some();
1126    let has_binding = binding.is_some() && explicit_session;
1127    let authoritative_binding = if explicit_session {
1128        binding.as_ref()
1129    } else {
1130        None
1131    };
1132
1133    let auth_checks_v = auth_checks(&auth).await;
1134    let install_v = vec![global_check];
1135    let (proj_checks_v, config) = project_checks(
1136        project_root,
1137        global_settings.as_deref(),
1138        has_global,
1139        has_binding,
1140    );
1141
1142    // The recording verdict: call the hook's own gate (stream.rs) via
1143    // `recording_attribution` — see that function's doc comment for why its
1144    // composition, including the worktree-key derivation, lives there rather
1145    // than inline here. Its worktree key is reused below for the project
1146    // display resolution, which needs the same value.
1147    let (attribution, worktree) =
1148        recording_attribution(sessions_dir.as_deref(), session_id, cwd, config.as_ref());
1149
1150    // The project axis for DISPLAY needs its own full `SessionState` (more
1151    // than `workspace_binding_check_in`'s bare `RepoBinding`, e.g.
1152    // `active_project`/`subagent_projects`) — unlike the verdict above, which
1153    // lives entirely inside `recording_attribution`. Loaded separately
1154    // (rather than sharing `recording_attribution`'s internal session load)
1155    // so that function's session load stays self-contained.
1156    let project_session = match (sessions_dir.as_deref(), session_id) {
1157        (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
1158        _ => crate::session_state::SessionState::default(),
1159    };
1160
1161    // --- The project axis for DISPLAY only, mirroring `commands::project`'s
1162    // `status` path (project.rs:228-334): read the worktree-relative
1163    // default_project + the user-level default, and run the full precedence
1164    // chain (including server-side deduction) if a client can be built from
1165    // the existing `auth`. Best-effort like that path: no credential/client
1166    // degrades to the pure local tiers via `effective_project`, which need no
1167    // network. Whatever this resolves to (including a deduction failure) is
1168    // shown to the user but — unlike the verdict above — can never affect the
1169    // exit code beyond a Warn; see `project_binding_check`.
1170    let config_default_name = config.as_ref().and_then(|c| c.default_project.clone());
1171    let user_default_project = crate::user_project_default::load();
1172    let project_git_url = git_remote_url(cwd);
1173    // Set when a configured `default_project` NAME fails to resolve (network
1174    // error, or no matching/case-matching project) — surfaced below rather
1175    // than silently dropped, mirroring `commands::project`'s `status`
1176    // (project.rs:284-289). `None` in EITHER arm: the offline arm never
1177    // attempts resolution at all (no client to call `list_projects` with),
1178    // which is a different, already-visible gap (no credential -> an Error
1179    // from the Authentication section).
1180    let mut config_default_unresolved: Option<String> = None;
1181
1182    let project_outcome: ProjectOutcome = match (auth.credential.clone(), auth.server_url.as_ref())
1183    {
1184        (Some(credential), Some(server_url)) => {
1185            let client = ApiClient::with_credential(server_url, Some(credential));
1186            // A configured default_project is a NAME; resolving it into a
1187            // binding needs the project list, same as project.rs's status.
1188            let config_default = match config_default_name.as_deref() {
1189                Some(name) => {
1190                    let resolved = client.list_projects().await.ok().and_then(|items| {
1191                        items.into_iter().find(|p| p.name == name).map(|p| {
1192                            crate::session_state::ProjectBinding {
1193                                project_id: p.id.to_string(),
1194                                project_name: p.name,
1195                                updated_at: chrono::Utc::now().to_rfc3339(),
1196                            }
1197                        })
1198                    });
1199                    if resolved.is_none() {
1200                        config_default_unresolved = Some(name.to_string());
1201                    }
1202                    resolved
1203                }
1204                None => None,
1205            };
1206            let inputs = ProjectResolveInputs {
1207                project_flag: None,
1208                session: &project_session,
1209                worktree_path: Some(&worktree),
1210                config_default,
1211            };
1212            resolve_effective_project(
1213                &inputs,
1214                user_default_project,
1215                project_git_url.as_deref(),
1216                &client,
1217            )
1218            .await
1219        }
1220        _ => {
1221            let inputs = ProjectResolveInputs {
1222                project_flag: None,
1223                session: &project_session,
1224                worktree_path: Some(&worktree),
1225                config_default: None,
1226            };
1227            offline_project_outcome(&inputs, user_default_project)
1228        }
1229    };
1230
1231    let mut attribution_v = Vec::new();
1232    if let Some(c) = recording_check(session_id, attribution.as_ref()) {
1233        attribution_v.push(c);
1234    }
1235    attribution_v.push(binding_check);
1236    attribution_v.push(project_binding_check(&project_outcome));
1237    if let Some(name) = config_default_unresolved {
1238        attribution_v.push(unresolved_config_default_check(&name));
1239    }
1240
1241    let server_checks_v =
1242        server_repo_checks(project_root, &auth, config.as_ref(), authoritative_binding).await;
1243    let session_checks_v = session_checks(project_root);
1244
1245    let sections: Vec<(&str, Vec<Check>)> = vec![
1246        ("Authentication", auth_checks_v),
1247        ("Installation", install_v),
1248        ("Project", proj_checks_v),
1249        ("Attribution", attribution_v),
1250        ("Server repo", server_checks_v),
1251        ("Sessions", session_checks_v),
1252    ];
1253    for (title, checks) in &sections {
1254        print_section(title, checks);
1255    }
1256    let all: Vec<&Check> = sections.iter().flat_map(|(_, v)| v.iter()).collect();
1257
1258    let errors = all.iter().filter(|c| c.level == Level::Error).count();
1259    let warns = all.iter().filter(|c| c.level == Level::Warn).count();
1260
1261    match (errors, warns) {
1262        (0, 0) => println!("{ANSI_GREEN}All good.{ANSI_RESET}"),
1263        (0, w) => println!(
1264            "{ANSI_YELLOW}{w} warning{} — no blocking issues.{ANSI_RESET}",
1265            if w == 1 { "" } else { "s" }
1266        ),
1267        (e, 0) => println!(
1268            "{ANSI_RED}{e} problem{} found.{ANSI_RESET}",
1269            if e == 1 { "" } else { "s" }
1270        ),
1271        (e, w) => println!(
1272            "{ANSI_RED}{e} problem{}, {w} warning{}.{ANSI_RESET}",
1273            if e == 1 { "" } else { "s" },
1274            if w == 1 { "" } else { "s" }
1275        ),
1276    }
1277
1278    exit_code_for(&all)
1279}
1280
1281/// Only `Level::Error` checks force a non-zero exit; `Warn` and `Skip` are
1282/// surfaced to the user but don't fail the command. Pulled out as a pure
1283/// function so the severity→exit-code mapping is unit-testable independent
1284/// of the network-calling `run_status`.
1285fn exit_code_for(checks: &[&Check]) -> i32 {
1286    if checks.iter().any(|c| c.level == Level::Error) {
1287        1
1288    } else {
1289        0
1290    }
1291}
1292
1293#[cfg(test)]
1294mod tests {
1295    use super::*;
1296
1297    #[test]
1298    fn normalize_remote_ssh_https_equal() {
1299        assert_eq!(
1300            normalize_remote("git@github.com:VirtusLab/visdom-ai-tracing.git"),
1301            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing")
1302        );
1303        assert_eq!(
1304            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing.git/"),
1305            "github.com/VirtusLab/visdom-ai-tracing"
1306        );
1307    }
1308
1309    #[test]
1310    fn normalize_remote_preserves_non_github() {
1311        assert_eq!(
1312            normalize_remote("git@gitlab.com:foo/bar.git"),
1313            "git@gitlab.com:foo/bar"
1314        );
1315    }
1316
1317    #[test]
1318    fn git_hook_check_missing_file_is_warning() {
1319        let dir = tempfile::tempdir().unwrap();
1320        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1321        assert_eq!(check.level, Level::Warn);
1322    }
1323
1324    #[test]
1325    fn git_hook_check_with_marker_is_ok() {
1326        let dir = tempfile::tempdir().unwrap();
1327        let hooks = dir.path().join(".git/hooks");
1328        std::fs::create_dir_all(&hooks).unwrap();
1329        std::fs::write(
1330            hooks.join("pre-push"),
1331            "#!/bin/sh\n# tracevault:enforce\ntracevault check\n",
1332        )
1333        .unwrap();
1334        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1335        assert_eq!(check.level, Level::Ok);
1336    }
1337
1338    #[test]
1339    fn git_hook_check_without_marker_is_warning() {
1340        let dir = tempfile::tempdir().unwrap();
1341        let hooks = dir.path().join(".git/hooks");
1342        std::fs::create_dir_all(&hooks).unwrap();
1343        std::fs::write(hooks.join("pre-push"), "#!/bin/sh\necho hi\n").unwrap();
1344        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
1345        assert_eq!(check.level, Level::Warn);
1346    }
1347
1348    #[test]
1349    fn project_checks_errors_without_tracevault_dir_and_no_global_or_binding() {
1350        let dir = tempfile::tempdir().unwrap();
1351        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1352        let missing_global = dir.path().join("no-global.json");
1353        let (checks, cfg) =
1354            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1355        assert!(cfg.is_none());
1356        assert!(checks
1357            .iter()
1358            .any(|c| c.level == Level::Error && c.label == "TraceVault initialized"));
1359        // The Git-hooks Skip must NOT claim "global/workspace mode" when the
1360        // user is truly unconfigured (no global install, no binding).
1361        let git_hooks = checks
1362            .iter()
1363            .find(|c| c.label == "Git hooks")
1364            .expect("Git hooks check present");
1365        assert_eq!(git_hooks.level, Level::Skip);
1366        assert!(
1367            !git_hooks.detail.contains("global/workspace mode"),
1368            "unconfigured git-hooks detail must not claim global/workspace mode: {}",
1369            git_hooks.detail
1370        );
1371    }
1372
1373    #[test]
1374    fn project_checks_no_tracevault_dir_is_not_error_in_global_mode() {
1375        let dir = tempfile::tempdir().unwrap();
1376        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1377        let missing_global = dir.path().join("no-global.json");
1378        let (checks, _) = project_checks(dir.path(), Some(missing_global.as_path()), true, false);
1379        let refs: Vec<&Check> = checks.iter().collect();
1380        assert_eq!(
1381            exit_code_for(&refs),
1382            0,
1383            "global mode must not force exit 1 on missing .tracevault/"
1384        );
1385        assert!(checks
1386            .iter()
1387            .any(|c| c.label == "TraceVault initialized" && c.level == Level::Skip));
1388    }
1389
1390    #[test]
1391    fn project_checks_warns_when_config_toml_missing() {
1392        // Pure workspace/detached-mode user: .tracevault/ exists (or not,
1393        // doesn't matter for this check) but there's no config.toml because
1394        // `tracevault init` was never run. This must be a Warn, not an
1395        // Error, and therefore must not force the process exit code to 1.
1396        let dir = tempfile::tempdir().unwrap();
1397        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1398        std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
1399        let missing_global = dir.path().join("no-global.json");
1400        let (checks, cfg) =
1401            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1402        assert!(cfg.is_none());
1403        let project_config_check = checks
1404            .iter()
1405            .find(|c| c.label == "Project config")
1406            .expect("Project config check present");
1407        assert_eq!(project_config_check.level, Level::Warn);
1408
1409        let refs: Vec<&Check> = checks.iter().collect();
1410        assert_eq!(
1411            exit_code_for(&refs),
1412            0,
1413            "a missing config.toml alone must not force a non-zero exit code"
1414        );
1415    }
1416
1417    #[test]
1418    fn project_checks_errors_on_malformed_config_toml() {
1419        // A config.toml that exists but fails to parse is a genuine error,
1420        // distinct from "no config.toml at all" — it should stay Check::err
1421        // and keep forcing a non-zero exit code.
1422        let dir = tempfile::tempdir().unwrap();
1423        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1424        std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
1425        std::fs::write(
1426            dir.path().join(".tracevault/config.toml"),
1427            "not valid toml {{{",
1428        )
1429        .unwrap();
1430        let missing_global = dir.path().join("no-global.json");
1431        let (checks, cfg) =
1432            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
1433        assert!(cfg.is_none());
1434        let project_config_check = checks
1435            .iter()
1436            .find(|c| c.label == "Project config")
1437            .expect("Project config check present");
1438        assert_eq!(project_config_check.level, Level::Error);
1439
1440        let refs: Vec<&Check> = checks.iter().collect();
1441        assert_eq!(exit_code_for(&refs), 1);
1442    }
1443
1444    #[test]
1445    fn exit_code_for_warn_only_is_zero() {
1446        let checks = [
1447            Check::warn("a", ""),
1448            Check::ok("b", ""),
1449            Check::skip("c", ""),
1450        ];
1451        let refs: Vec<&Check> = checks.iter().collect();
1452        assert_eq!(exit_code_for(&refs), 0);
1453    }
1454
1455    #[test]
1456    fn exit_code_for_any_error_is_one() {
1457        let checks = [
1458            Check::ok("a", ""),
1459            Check::err("b", ""),
1460            Check::warn("c", ""),
1461        ];
1462        let refs: Vec<&Check> = checks.iter().collect();
1463        assert_eq!(exit_code_for(&refs), 1);
1464    }
1465
1466    #[test]
1467    fn count_pending_events_sums_across_per_repo_queues() {
1468        let dir = tempfile::tempdir().unwrap();
1469        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1470        std::fs::write(dir.path().join("pending-b.jsonl"), "line1\n").unwrap();
1471        std::fs::write(dir.path().join("pending-c.jsonl"), "").unwrap();
1472        assert_eq!(count_pending_events(dir.path(), false), 3);
1473        assert_eq!(count_pending_events(dir.path(), true), 3);
1474    }
1475
1476    #[test]
1477    fn count_pending_events_ignores_unrelated_files() {
1478        let dir = tempfile::tempdir().unwrap();
1479        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\n").unwrap();
1480        std::fs::write(dir.path().join("notes.txt"), "line1\nline2\n").unwrap();
1481        assert_eq!(count_pending_events(dir.path(), false), 1);
1482    }
1483
1484    #[test]
1485    fn count_pending_events_zero_for_empty_dir() {
1486        let dir = tempfile::tempdir().unwrap();
1487        assert_eq!(count_pending_events(dir.path(), false), 0);
1488        assert_eq!(count_pending_events(dir.path(), true), 0);
1489    }
1490
1491    #[test]
1492    fn is_pending_queue_filename_matches_per_repo_only() {
1493        assert!(!is_pending_queue_filename("pending.jsonl"));
1494        // Repo-less queues must be counted too. This holds today only
1495        // because `repo_id_from_pending_filename` matches the shared
1496        // `pending-` prefix and `status` never validates the id — i.e. by
1497        // accident. Pin it, so tightening that helper to reject the project
1498        // shape (which its name invites) cannot silently make `status` report
1499        // "0 pending" over a non-empty queue that `flush` still drains.
1500        assert!(is_pending_queue_filename(
1501            "pending-project-018f0000-0000-7000-8000-000000000abc.jsonl"
1502        ));
1503        assert!(is_pending_queue_filename("pending-a.jsonl"));
1504    }
1505
1506    #[test]
1507    fn is_pending_queue_filename_rejects_lookalikes() {
1508        assert!(!is_pending_queue_filename("pendingfoo.jsonl"));
1509        assert!(!is_pending_queue_filename("pending-.jsonl"));
1510    }
1511
1512    #[test]
1513    fn count_pending_events_legacy_pending_jsonl_requires_include_legacy() {
1514        let dir = tempfile::tempdir().unwrap();
1515        std::fs::write(dir.path().join("pending.jsonl"), "line1\nline2\n").unwrap();
1516        assert_eq!(
1517            count_pending_events(dir.path(), false),
1518            0,
1519            "legacy pending.jsonl must not be counted when there's no bound repo_id"
1520        );
1521        assert_eq!(
1522            count_pending_events(dir.path(), true),
1523            2,
1524            "legacy pending.jsonl counts once a repo_id is bound"
1525        );
1526    }
1527
1528    #[test]
1529    fn count_pending_events_legacy_and_per_repo_both_count_when_included() {
1530        let dir = tempfile::tempdir().unwrap();
1531        std::fs::write(dir.path().join("pending.jsonl"), "line1\n").unwrap();
1532        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
1533        assert_eq!(count_pending_events(dir.path(), false), 2);
1534        assert_eq!(count_pending_events(dir.path(), true), 3);
1535    }
1536
1537    #[test]
1538    fn count_pending_events_ignores_lookalike_filenames() {
1539        let dir = tempfile::tempdir().unwrap();
1540        std::fs::write(dir.path().join("pendingfoo.jsonl"), "line1\n").unwrap();
1541        std::fs::write(dir.path().join("pending-.jsonl"), "line1\n").unwrap();
1542        assert_eq!(count_pending_events(dir.path(), false), 0);
1543        assert_eq!(count_pending_events(dir.path(), true), 0);
1544    }
1545
1546    #[test]
1547    fn settings_has_tracevault_hooks_detects_commands() {
1548        assert!(settings_has_tracevault_hooks(
1549            r#"{"hooks":{"PreToolUse":[{"hooks":[{"command":"tracevault stream --event pre"}]}]}}"#
1550        ));
1551        assert!(settings_has_tracevault_hooks(
1552            r#"{"command":"tracevault session-start"}"#
1553        ));
1554        assert!(settings_has_tracevault_hooks(
1555            r#"{"command":"tracevault user-prompt"}"#
1556        ));
1557        assert!(!settings_has_tracevault_hooks(
1558            r#"{"hooks":{"PreToolUse":[]}}"#
1559        ));
1560        assert!(!settings_has_tracevault_hooks("{}"));
1561    }
1562
1563    #[test]
1564    fn global_hook_check_ok_when_present() {
1565        let dir = tempfile::tempdir().unwrap();
1566        let p = dir.path().join("settings.json");
1567        std::fs::write(
1568            &p,
1569            r#"{"hooks":{"SessionStart":[{"hooks":[{"command":"tracevault session-start"}]}]}}"#,
1570        )
1571        .unwrap();
1572        assert_eq!(global_hook_check_in(&p).level, Level::Ok);
1573    }
1574
1575    #[test]
1576    fn global_hook_check_skip_when_absent_or_no_hooks() {
1577        let dir = tempfile::tempdir().unwrap();
1578        let missing = dir.path().join("settings.json");
1579        assert_eq!(global_hook_check_in(&missing).level, Level::Skip);
1580        let empty = dir.path().join("empty.json");
1581        std::fs::write(&empty, "{}").unwrap();
1582        assert_eq!(global_hook_check_in(&empty).level, Level::Skip);
1583    }
1584
1585    #[test]
1586    fn global_hook_check_warns_when_unreadable() {
1587        // A path that exists but isn't a readable file (a directory) yields a
1588        // non-NotFound read error → Warn, not a false "no settings.json" Skip.
1589        let dir = tempfile::tempdir().unwrap();
1590        let as_dir = dir.path().join("settings.json");
1591        std::fs::create_dir(&as_dir).unwrap();
1592        let check = global_hook_check_in(&as_dir);
1593        assert_eq!(check.level, Level::Warn);
1594        assert!(
1595            check.detail.contains("cannot read"),
1596            "detail: {}",
1597            check.detail
1598        );
1599    }
1600
1601    #[test]
1602    fn claude_hook_check_ok_from_global_only() {
1603        let dir = tempfile::tempdir().unwrap();
1604        let repo = dir.path().join("repo-settings.json"); // does not exist
1605        let global = dir.path().join("global-settings.json");
1606        std::fs::write(&global, r#"{"command":"tracevault stream"}"#).unwrap();
1607        let c = claude_hook_check_in(&repo, Some(global.as_path()));
1608        assert_eq!(c.level, Level::Ok);
1609        assert!(
1610            c.detail.to_lowercase().contains("global") || c.detail.contains("~/.claude"),
1611            "detail: {}",
1612            c.detail
1613        );
1614    }
1615
1616    #[test]
1617    fn claude_hook_check_ok_from_repo() {
1618        let dir = tempfile::tempdir().unwrap();
1619        let repo = dir.path().join("repo-settings.json");
1620        std::fs::write(&repo, r#"{"command":"tracevault stream"}"#).unwrap();
1621        let global = dir.path().join("global-settings.json"); // does not exist
1622        assert_eq!(
1623            claude_hook_check_in(&repo, Some(global.as_path())).level,
1624            Level::Ok
1625        );
1626    }
1627
1628    #[test]
1629    fn claude_hook_check_no_global_path_uses_repo_only() {
1630        // When the home dir can't be resolved (global_settings = None), only the
1631        // repo settings are consulted — never a relative fallback.
1632        let dir = tempfile::tempdir().unwrap();
1633        let repo = dir.path().join("repo-settings.json");
1634        std::fs::write(&repo, r#"{"command":"tracevault stream"}"#).unwrap();
1635        assert_eq!(claude_hook_check_in(&repo, None).level, Level::Ok);
1636
1637        let missing = dir.path().join("nope.json");
1638        assert_eq!(claude_hook_check_in(&missing, None).level, Level::Warn);
1639    }
1640
1641    #[test]
1642    fn claude_hook_check_warn_when_neither() {
1643        let dir = tempfile::tempdir().unwrap();
1644        let c = claude_hook_check_in(
1645            &dir.path().join("a.json"),
1646            Some(dir.path().join("b.json").as_path()),
1647        );
1648        assert_eq!(c.level, Level::Warn);
1649    }
1650
1651    #[test]
1652    fn claude_hook_check_warns_when_repo_settings_unreadable() {
1653        let dir = tempfile::tempdir().unwrap();
1654        let repo = dir.path().join("repo-settings.json");
1655        std::fs::create_dir(&repo).unwrap(); // directory-as-file → non-NotFound read error
1656        let global = dir.path().join("global.json"); // missing
1657        let c = claude_hook_check_in(&repo, Some(global.as_path()));
1658        assert_eq!(c.level, Level::Warn);
1659        assert!(c.detail.contains("cannot read"), "detail: {}", c.detail);
1660    }
1661
1662    #[test]
1663    fn tracevault_init_check_severity_matrix() {
1664        assert_eq!(tracevault_init_check(true, false, false).level, Level::Ok); // present → Ok
1665        assert_eq!(tracevault_init_check(false, true, false).level, Level::Skip); // absent + global → Skip
1666        assert_eq!(tracevault_init_check(false, false, true).level, Level::Skip); // absent + binding → Skip
1667        assert_eq!(tracevault_init_check(false, true, true).level, Level::Skip);
1668        assert_eq!(
1669            tracevault_init_check(false, false, false).level,
1670            Level::Error
1671        ); // nothing → Error
1672    }
1673
1674    #[test]
1675    fn workspace_binding_explicit_id_with_binding_is_ok() {
1676        let dir = tempfile::tempdir().unwrap();
1677        let st = crate::session_state::SessionState {
1678            active: Some(crate::session_state::RepoBinding {
1679                repo_id: "11111111-1111-4111-8111-111111111111".into(),
1680                git_url: None,
1681                remote_id: None,
1682                codebase_name: None,
1683                updated_at: "t".into(),
1684            }),
1685            ..Default::default()
1686        };
1687        std::fs::write(
1688            dir.path().join("sess-9.toml"),
1689            toml::to_string(&st).unwrap(),
1690        )
1691        .unwrap();
1692        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-9"));
1693        assert_eq!(check.level, Level::Ok);
1694        assert!(
1695            check
1696                .detail
1697                .contains("11111111-1111-4111-8111-111111111111"),
1698            "detail: {}",
1699            check.detail
1700        );
1701        assert_eq!(
1702            binding.unwrap().repo_id,
1703            "11111111-1111-4111-8111-111111111111"
1704        );
1705    }
1706
1707    #[test]
1708    fn workspace_binding_explicit_id_without_binding_is_skip() {
1709        // Severity moved to `recording_check`, which is the only place that
1710        // sees both attribution axes — this check alone can't tell a
1711        // genuinely unbound machine from one attributed via the project axis.
1712        let dir = tempfile::tempdir().unwrap();
1713        std::fs::write(
1714            dir.path().join("sess-empty.toml"),
1715            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
1716        )
1717        .unwrap();
1718        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-empty"));
1719        assert_eq!(check.level, Level::Skip);
1720        assert!(binding.is_none());
1721    }
1722
1723    #[test]
1724    fn workspace_binding_no_id_empty_dir_is_skip() {
1725        let dir = tempfile::tempdir().unwrap();
1726        let (check, binding) = workspace_binding_check_in(dir.path(), None);
1727        assert_eq!(check.level, Level::Skip);
1728        assert!(binding.is_none());
1729    }
1730
1731    #[test]
1732    fn workspace_binding_no_id_scans_latest() {
1733        let dir = tempfile::tempdir().unwrap();
1734        // Two sessions; the one written LAST should be picked by the mtime scan.
1735        let older = crate::session_state::SessionState {
1736            active: Some(crate::session_state::RepoBinding {
1737                repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
1738                git_url: None,
1739                remote_id: None,
1740                codebase_name: None,
1741                updated_at: "t".into(),
1742            }),
1743            ..Default::default()
1744        };
1745        std::fs::write(
1746            dir.path().join("old.toml"),
1747            toml::to_string(&older).unwrap(),
1748        )
1749        .unwrap();
1750        // Ensure a distinct, later mtime for the second file.
1751        std::thread::sleep(std::time::Duration::from_millis(20));
1752        let newer = crate::session_state::SessionState {
1753            active: Some(crate::session_state::RepoBinding {
1754                repo_id: "bbbbbbbb-2222-4222-8222-222222222222".into(),
1755                git_url: None,
1756                remote_id: None,
1757                codebase_name: None,
1758                updated_at: "t".into(),
1759            }),
1760            ..Default::default()
1761        };
1762        std::fs::write(
1763            dir.path().join("new.toml"),
1764            toml::to_string(&newer).unwrap(),
1765        )
1766        .unwrap();
1767        let (check, binding) = workspace_binding_check_in(dir.path(), None);
1768        assert_eq!(check.level, Level::Ok);
1769        assert_eq!(
1770            binding.unwrap().repo_id,
1771            "bbbbbbbb-2222-4222-8222-222222222222",
1772            "must pick the most-recently-modified session"
1773        );
1774    }
1775
1776    #[test]
1777    fn workspace_binding_scan_skips_newest_without_binding() {
1778        // The most-recently-touched session has NO active binding, but an older
1779        // one does — the scan must find the older binding, not stop at the newest.
1780        let dir = tempfile::tempdir().unwrap();
1781        let with_binding = crate::session_state::SessionState {
1782            active: Some(crate::session_state::RepoBinding {
1783                repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
1784                git_url: None,
1785                remote_id: None,
1786                codebase_name: None,
1787                updated_at: "t".into(),
1788            }),
1789            ..Default::default()
1790        };
1791        std::fs::write(
1792            dir.path().join("older.toml"),
1793            toml::to_string(&with_binding).unwrap(),
1794        )
1795        .unwrap();
1796        std::thread::sleep(std::time::Duration::from_millis(20));
1797        // Newest file: no active binding.
1798        std::fs::write(
1799            dir.path().join("newest.toml"),
1800            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
1801        )
1802        .unwrap();
1803        let (check, binding) = workspace_binding_check_in(dir.path(), None);
1804        assert_eq!(check.level, Level::Ok);
1805        assert_eq!(
1806            binding.unwrap().repo_id,
1807            "aaaaaaaa-1111-4111-8111-111111111111"
1808        );
1809    }
1810
1811    #[test]
1812    fn workspace_binding_scan_no_active_binding_is_skip_not_warn() {
1813        // A session file exists but has no active binding (e.g. a bound-mode
1814        // user with a stray session). Scan mode must Skip, not Warn.
1815        let dir = tempfile::tempdir().unwrap();
1816        std::fs::write(
1817            dir.path().join("stray.toml"),
1818            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
1819        )
1820        .unwrap();
1821        let (check, binding) = workspace_binding_check_in(dir.path(), None);
1822        assert_eq!(check.level, Level::Skip);
1823        assert!(binding.is_none());
1824    }
1825
1826    #[test]
1827    fn workspace_binding_explicit_id_malformed_repo_id_is_warn_not_ok() {
1828        // `attribution_for` filters a resolved binding through
1829        // `binding_repo_id_is_valid` and drops it if the check fails; a
1830        // corrupted session-state file with a non-UUID `repo_id` must not
1831        // read Ok here either.
1832        let dir = tempfile::tempdir().unwrap();
1833        let st = crate::session_state::SessionState {
1834            active: Some(crate::session_state::RepoBinding {
1835                repo_id: "not-a-uuid".into(),
1836                git_url: None,
1837                remote_id: None,
1838                codebase_name: None,
1839                updated_at: "t".into(),
1840            }),
1841            ..Default::default()
1842        };
1843        std::fs::write(
1844            dir.path().join("sess-bad.toml"),
1845            toml::to_string(&st).unwrap(),
1846        )
1847        .unwrap();
1848        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-bad"));
1849        assert_eq!(check.level, Level::Warn);
1850        assert!(
1851            check.detail.contains("not a valid id"),
1852            "detail: {}",
1853            check.detail
1854        );
1855        // The raw binding is still returned (unchanged mode signal for
1856        // callers) — only this check's OWN severity changes.
1857        assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
1858    }
1859
1860    #[test]
1861    fn workspace_binding_scan_malformed_repo_id_is_warn_not_ok() {
1862        // Same rule, scan arm: `latest_active_binding_in` doesn't validate
1863        // either, so the same corrupted binding could surface via a scan.
1864        let dir = tempfile::tempdir().unwrap();
1865        let st = crate::session_state::SessionState {
1866            active: Some(crate::session_state::RepoBinding {
1867                repo_id: "not-a-uuid".into(),
1868                git_url: None,
1869                remote_id: None,
1870                codebase_name: None,
1871                updated_at: "t".into(),
1872            }),
1873            ..Default::default()
1874        };
1875        std::fs::write(
1876            dir.path().join("sess-bad.toml"),
1877            toml::to_string(&st).unwrap(),
1878        )
1879        .unwrap();
1880        let (check, binding) = workspace_binding_check_in(dir.path(), None);
1881        assert_eq!(check.level, Level::Warn);
1882        assert!(
1883            check.detail.contains("not a valid id"),
1884            "detail: {}",
1885            check.detail
1886        );
1887        assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
1888    }
1889
1890    fn repo_item(id: &str, name: &str) -> crate::api_client::RepoListItem {
1891        crate::api_client::RepoListItem {
1892            id: id.parse().unwrap(),
1893            name: name.to_string(),
1894            github_url: None,
1895            clone_status: None,
1896        }
1897    }
1898
1899    #[test]
1900    fn find_repo_with_fallback_direct_name_hit_no_fallback_needed() {
1901        let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
1902        let want = RepoMatch::ByName("myrepo".to_string());
1903        let (r, matched_via) = find_repo_with_fallback(&repos, &want, None).unwrap();
1904        assert_eq!(r.name, "myrepo");
1905        assert_eq!(matched_via, want);
1906    }
1907
1908    #[test]
1909    fn find_repo_with_fallback_falls_back_to_binding_id_on_name_miss() {
1910        // Local checkout directory was renamed after registration: the
1911        // git-derived name ("renamed") no longer matches the server's
1912        // registered name ("myrepo"), but the workspace binding still carries
1913        // the correct repo_id.
1914        let id = "11111111-1111-4111-8111-111111111111";
1915        let repos = vec![repo_item(id, "myrepo")];
1916        let binding = crate::session_state::RepoBinding {
1917            repo_id: id.to_string(),
1918            git_url: None,
1919            remote_id: None,
1920            codebase_name: None,
1921            updated_at: "t".into(),
1922        };
1923        let want = RepoMatch::ByName("renamed".to_string());
1924        let (r, matched_via) = find_repo_with_fallback(&repos, &want, Some(&binding))
1925            .expect("fallback by binding id must find the repo");
1926        assert_eq!(r.name, "myrepo");
1927        assert_eq!(matched_via, RepoMatch::ById(id.to_string()));
1928    }
1929
1930    #[test]
1931    fn find_repo_with_fallback_none_when_name_misses_and_no_binding() {
1932        let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
1933        let want = RepoMatch::ByName("renamed".to_string());
1934        assert!(find_repo_with_fallback(&repos, &want, None).is_none());
1935    }
1936
1937    #[test]
1938    fn find_repo_with_fallback_none_when_name_and_binding_both_miss() {
1939        let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
1940        let binding = crate::session_state::RepoBinding {
1941            repo_id: "22222222-2222-4222-8222-222222222222".to_string(),
1942            git_url: None,
1943            remote_id: None,
1944            codebase_name: None,
1945            updated_at: "t".into(),
1946        };
1947        let want = RepoMatch::ByName("renamed".to_string());
1948        assert!(find_repo_with_fallback(&repos, &want, Some(&binding)).is_none());
1949    }
1950
1951    #[test]
1952    fn find_repo_with_fallback_by_id_miss_is_never_retried() {
1953        // An ById lookup has already tried the only id available — a miss
1954        // stays a miss even with a (necessarily-matching-or-irrelevant)
1955        // binding present.
1956        let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
1957        let binding = crate::session_state::RepoBinding {
1958            repo_id: "99999999-9999-4999-8999-999999999999".to_string(),
1959            git_url: None,
1960            remote_id: None,
1961            codebase_name: None,
1962            updated_at: "t".into(),
1963        };
1964        let want = RepoMatch::ById("99999999-9999-4999-8999-999999999999".to_string());
1965        assert!(find_repo_with_fallback(&repos, &want, Some(&binding)).is_none());
1966    }
1967
1968    #[test]
1969    fn server_repo_lookup_prefers_config_by_name() {
1970        let m = server_repo_lookup(true, "myrepo", None).unwrap();
1971        assert_eq!(m, RepoMatch::ByName("myrepo".to_string()));
1972    }
1973
1974    #[test]
1975    fn server_repo_lookup_falls_back_to_binding_by_id() {
1976        let b = crate::session_state::RepoBinding {
1977            repo_id: "rid-1".into(),
1978            git_url: None,
1979            remote_id: None,
1980            codebase_name: None,
1981            updated_at: "t".into(),
1982        };
1983        let m = server_repo_lookup(false, "ignored", Some(&b)).unwrap();
1984        assert_eq!(m, RepoMatch::ById("rid-1".to_string()));
1985    }
1986
1987    #[test]
1988    fn server_repo_lookup_none_when_neither() {
1989        assert!(server_repo_lookup(false, "x", None).is_none());
1990    }
1991
1992    #[test]
1993    fn effective_session_id_arg_wins_and_filters_empty() {
1994        assert_eq!(
1995            effective_session_id(Some("a".into()), Some("b".into())),
1996            Some("a".into())
1997        );
1998        assert_eq!(
1999            effective_session_id(Some("".into()), Some("b".into())),
2000            Some("b".into())
2001        );
2002        assert_eq!(
2003            effective_session_id(Some("   ".into()), None).as_deref(),
2004            Some("   ")
2005        ); // non-empty whitespace is a real (if odd) id — NOT filtered
2006        assert_eq!(effective_session_id(None, Some("".into())), None);
2007        assert_eq!(effective_session_id(None, None), None);
2008    }
2009
2010    fn project_binding(id: &str, name: &str) -> crate::session_state::ProjectBinding {
2011        crate::session_state::ProjectBinding {
2012            project_id: id.into(),
2013            project_name: name.into(),
2014            updated_at: "t".into(),
2015        }
2016    }
2017
2018    /// `id` must be a real UUID string — `attribution_for` only accepts a
2019    /// repo binding whose `repo_id` parses as one (`binding_repo_id_is_valid`
2020    /// in stream.rs); a non-UUID id degrades to `ProjectOnly`/`None` instead.
2021    fn repo_binding_for_attribution(id: &str) -> crate::session_state::RepoBinding {
2022        crate::session_state::RepoBinding {
2023            repo_id: id.into(),
2024            git_url: None,
2025            remote_id: None,
2026            codebase_name: None,
2027            updated_at: "t".into(),
2028        }
2029    }
2030
2031    #[test]
2032    fn recording_check_truth_table() {
2033        // Literal expected outcomes, NOT a restatement of `recording_check`'s
2034        // own condition (a computed `expect_error` formula could pass even if
2035        // the implementation's condition drifted, since both would drift
2036        // together).
2037        let repo_attr = crate::commands::stream::Attribution::Repo {
2038            repo_id: "11111111-1111-4111-8111-111111111111".into(),
2039            project: None,
2040        };
2041        let project_attr = crate::commands::stream::Attribution::ProjectOnly {
2042            project_id: uuid::Uuid::from_u128(1),
2043        };
2044
2045        // session_id: None (no explicit session — a bare scan): never fires,
2046        // no matter what attribution is.
2047        assert!(recording_check(None, None).is_none());
2048        assert!(recording_check(None, Some(&repo_attr)).is_none());
2049        assert!(recording_check(None, Some(&project_attr)).is_none());
2050
2051        // session_id: Some, something resolved (either shape): no check.
2052        assert!(recording_check(Some("s"), Some(&repo_attr)).is_none());
2053        assert!(recording_check(Some("s"), Some(&project_attr)).is_none());
2054
2055        // session_id: Some, nothing resolved: the ONLY firing cell.
2056        assert_eq!(
2057            recording_check(Some("s"), None).map(|c| c.level),
2058            Some(Level::Error)
2059        );
2060    }
2061
2062    #[test]
2063    fn recording_check_error_names_project_switch_and_session() {
2064        // Defect (2): the stale `repo switch <name>` hint has to be gone and
2065        // the repo-less remediation (`project switch --user`) has to be
2066        // present, or a regression to the old text wouldn't be caught by a
2067        // plain level assertion.
2068        let check = recording_check(Some("3f27a336-abcd"), None).expect("expected an Error check");
2069        assert_eq!(check.level, Level::Error);
2070        assert!(
2071            check.detail.contains("project switch"),
2072            "detail: {}",
2073            check.detail
2074        );
2075        assert!(
2076            check.detail.contains("3f27a336-abcd"),
2077            "detail: {}",
2078            check.detail
2079        );
2080    }
2081
2082    #[test]
2083    fn project_binding_check_tiers_capture_project_honors_are_ok() {
2084        // Only the tiers `capture_project` itself resolves at capture time
2085        // read Ok: a `--project`-equivalent flag, the subagent/session-active
2086        // overrides, and the user-level default. `ConfigDefault` and
2087        // `Deduced` are covered separately — they must NOT appear here. Uses
2088        // a well-formed UUID id: an honored tier still needs a parseable
2089        // `project_id` to read Ok (see the malformed-id tests below).
2090        use crate::resolution::ProjectSource::*;
2091        for source in [ProjectFlag, Subagent, SessionActive, UserDefault] {
2092            let outcome: ProjectOutcome = Ok(Some((
2093                project_binding("33333333-3333-4333-8333-333333333333", "My Project"),
2094                source,
2095            )));
2096            let check = project_binding_check(&outcome);
2097            assert_eq!(check.level, Level::Ok, "source={source} should read Ok");
2098            assert!(
2099                check.detail.contains("My Project"),
2100                "source={source} detail: {}",
2101                check.detail
2102            );
2103        }
2104    }
2105
2106    #[test]
2107    fn project_binding_check_config_default_is_warn_not_ok() {
2108        // `capture_project` deliberately excludes the config `default_project`
2109        // tier, so displaying it as Ok would print a green Project line
2110        // directly above a red Recording line for the same session.
2111        let outcome: ProjectOutcome = Ok(Some((
2112            project_binding("pid-3", "My Project"),
2113            crate::resolution::ProjectSource::ConfigDefault,
2114        )));
2115        let check = project_binding_check(&outcome);
2116        assert_eq!(check.level, Level::Warn);
2117        assert!(
2118            check
2119                .detail
2120                .contains("not used for attribution at capture time"),
2121            "detail: {}",
2122            check.detail
2123        );
2124    }
2125
2126    #[test]
2127    fn project_binding_check_deduced_is_warn() {
2128        // `capture_project` never deduces server-side, so this tier can't
2129        // read Ok either — same reasoning as `ConfigDefault` above.
2130        let outcome: ProjectOutcome = Ok(Some((
2131            project_binding("pid-2", ""),
2132            crate::resolution::ProjectSource::Deduced,
2133        )));
2134        let check = project_binding_check(&outcome);
2135        assert_eq!(check.level, Level::Warn);
2136        assert!(
2137            check
2138                .detail
2139                .contains("not used for attribution at capture time"),
2140            "detail: {}",
2141            check.detail
2142        );
2143    }
2144
2145    #[test]
2146    fn project_binding_check_malformed_project_id_is_warn_not_ok() {
2147        // Aikido's finding: `capture_project` ends with
2148        // `.parse::<uuid::Uuid>().ok()?`, so a saved binding with a
2149        // non-UUID `project_id` (a hand-edited or corrupted
2150        // `user_project.toml`, or a corrupted session-state file) is
2151        // silently dropped at capture time. An honored tier with such an id
2152        // must not read Ok. Covers SessionActive and UserDefault.
2153        use crate::resolution::ProjectSource::{SessionActive, UserDefault};
2154        for source in [SessionActive, UserDefault] {
2155            let outcome: ProjectOutcome =
2156                Ok(Some((project_binding("not-a-uuid", "My Project"), source)));
2157            let check = project_binding_check(&outcome);
2158            assert_eq!(check.level, Level::Warn, "source={source}");
2159            assert!(
2160                check.detail.contains("not a valid id"),
2161                "source={source} detail: {}",
2162                check.detail
2163            );
2164        }
2165    }
2166
2167    #[test]
2168    fn project_binding_check_ambiguous_err_is_warn_not_error() {
2169        // This axis is display-only — the verdict comes from
2170        // `recording_check`'s real gate, which never deduces — so ANY failure
2171        // of the deduction call (genuinely ambiguous, or a transport/5xx
2172        // error propagated the same way) must read as Warn, never Error: a
2173        // network blip on this axis must not be able to redden the exit code.
2174        let outcome: ProjectOutcome =
2175            Err("this repo belongs to multiple projects; select one with `tracevault project switch <name>`".into());
2176        let check = project_binding_check(&outcome);
2177        assert_eq!(check.level, Level::Warn);
2178        assert!(
2179            check.detail.contains("multiple projects"),
2180            "detail: {}",
2181            check.detail
2182        );
2183    }
2184
2185    #[test]
2186    fn project_binding_check_none_is_skip() {
2187        let outcome: ProjectOutcome = Ok(None);
2188        let check = project_binding_check(&outcome);
2189        assert_eq!(check.level, Level::Skip);
2190    }
2191
2192    // --- Verdict composition: every test below drives `recording_attribution`
2193    // directly (rather than re-deriving its session-load/worktree-key/bound-
2194    // config composition by hand), so a regression in that composition —
2195    // e.g. the worktree key coming from the wrong path — fails a test instead
2196    // of only a full end-to-end run (see `recording_attribution_finds_
2197    // subagent_override_via_linked_worktree_cwd` below).
2198    //
2199    // ISOLATION: `recording_attribution` -> `capture_project` always
2200    // consults `user_project_default::load()` once its local tiers miss, and
2201    // `recording_attribution` itself calls `user_default::load()`
2202    // unconditionally — both are backed by `dirs::config_dir()`/
2203    // `dirs::home_dir()`, which read the REAL developer config on the machine
2204    // running the test unless overridden. EVERY test below therefore
2205    // redirects both `XDG_CONFIG_HOME` (the path on Linux) and `HOME` (the
2206    // path `dirs` actually uses on macOS, and `home_dir()`'s own first
2207    // choice) to the same empty temp dir — even tests that don't care about
2208    // either default, since a developer machine that has ever run
2209    // `project switch --user` or `repo switch --user` would otherwise inject
2210    // a real, non-deterministic tier and flip the test's outcome. Three of
2211    // these tests call the public `save()` (not just `load()`), so getting
2212    // this isolation wrong doesn't just make a test flaky — it overwrites
2213    // that developer's real config file.
2214
2215    #[test]
2216    fn verdict_repo_user_default_alone_is_not_an_error() {
2217        // `repo switch --user` is `resolve_stream_binding`'s lowest tier.
2218        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2219        let cfg_tmp = tempfile::tempdir().unwrap();
2220        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2221        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2222        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2223
2224        crate::user_default::save(&repo_binding_for_attribution(
2225            "11111111-1111-4111-8111-111111111111",
2226        ))
2227        .unwrap();
2228
2229        let cwd = tempfile::tempdir().unwrap();
2230        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
2231        assert_eq!(
2232            attribution,
2233            Some(crate::commands::stream::Attribution::Repo {
2234                repo_id: "11111111-1111-4111-8111-111111111111".into(),
2235                project: None,
2236            })
2237        );
2238        assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
2239    }
2240
2241    #[test]
2242    fn verdict_project_user_default_alone_is_not_an_error() {
2243        // `project switch --user` with no credential configured: the display
2244        // half of this same fallback is pinned separately by
2245        // `offline_project_outcome_falls_back_to_saved_user_default`.
2246        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2247        let cfg_tmp = tempfile::tempdir().unwrap();
2248        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2249        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2250        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2251
2252        let pb = crate::session_state::ProjectBinding {
2253            project_id: uuid::Uuid::from_u128(7).to_string(),
2254            project_name: "p".into(),
2255            updated_at: "".into(),
2256        };
2257        crate::user_project_default::save(&pb).unwrap();
2258
2259        let cwd = tempfile::tempdir().unwrap();
2260        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
2261        assert_eq!(
2262            attribution,
2263            Some(crate::commands::stream::Attribution::ProjectOnly {
2264                project_id: uuid::Uuid::from_u128(7)
2265            })
2266        );
2267        assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
2268    }
2269
2270    #[test]
2271    fn verdict_config_without_repo_id_and_nothing_else_is_error() {
2272        // A loaded `config.toml` with no `repo_id` must not count as bound —
2273        // `binding_from_config` returns `None` for it.
2274        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2275        let cfg_tmp = tempfile::tempdir().unwrap();
2276        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2277        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2278        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2279
2280        let config = crate::config::TracevaultConfig::default();
2281        assert!(
2282            crate::resolution::binding_from_config(&config).is_none(),
2283            "a repo_id-less config must not bind"
2284        );
2285
2286        let cwd = tempfile::tempdir().unwrap();
2287        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
2288        assert_eq!(
2289            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2290            Some(Level::Error)
2291        );
2292    }
2293
2294    #[test]
2295    fn verdict_nothing_anywhere_is_error() {
2296        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2297        let cfg_tmp = tempfile::tempdir().unwrap();
2298        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2299        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2300        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2301
2302        let cwd = tempfile::tempdir().unwrap();
2303        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
2304        assert_eq!(
2305            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2306            Some(Level::Error)
2307        );
2308    }
2309
2310    #[test]
2311    fn verdict_deduced_project_display_does_not_suppress_recording_error() {
2312        // A `Deduced` DISPLAY value must not make the project axis count as
2313        // bound for the verdict — `capture_project` never deduces.
2314        let outcome: ProjectOutcome = Ok(Some((
2315            project_binding("pid", ""),
2316            crate::resolution::ProjectSource::Deduced,
2317        )));
2318        assert_eq!(project_binding_check(&outcome).level, Level::Warn);
2319
2320        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2321        let cfg_tmp = tempfile::tempdir().unwrap();
2322        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2323        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2324        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2325
2326        let cwd = tempfile::tempdir().unwrap();
2327        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
2328        assert_eq!(
2329            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2330            Some(Level::Error),
2331            "a Deduced display value must not suppress the Recording error"
2332        );
2333    }
2334
2335    #[test]
2336    fn verdict_deduction_failure_is_warn_and_does_not_affect_recording() {
2337        // A deduction failure (network blip, 5xx, or genuinely Ambiguous)
2338        // must render at most Warn, and — since `recording_check` never even
2339        // sees `project_outcome` — cannot suppress or trigger the Recording
2340        // verdict either way.
2341        let outcome: ProjectOutcome = Err("this repo belongs to multiple projects".into());
2342        assert_eq!(project_binding_check(&outcome).level, Level::Warn);
2343
2344        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2345        let cfg_tmp = tempfile::tempdir().unwrap();
2346        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2347        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2348        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2349
2350        let config = crate::config::TracevaultConfig {
2351            repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
2352            ..Default::default()
2353        };
2354        let cwd = tempfile::tempdir().unwrap();
2355        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
2356        // Repo bound (via config) independently of the deduction failure
2357        // above -> no error, and nothing about the `Err` outcome forced one.
2358        assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
2359    }
2360
2361    #[test]
2362    fn offline_project_outcome_falls_back_to_saved_user_default() {
2363        // A saved `project switch --user` default must surface as Ok, not
2364        // Skip, in the credential-less path — not just the pure local tiers,
2365        // which `effective_project` alone covers.
2366        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2367        let cfg_tmp = tempfile::tempdir().unwrap();
2368        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2369        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2370        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2371
2372        let pb = crate::session_state::ProjectBinding {
2373            project_id: uuid::Uuid::from_u128(9).to_string(),
2374            project_name: "My Project".into(),
2375            updated_at: "".into(),
2376        };
2377        crate::user_project_default::save(&pb).unwrap();
2378
2379        let session = crate::session_state::SessionState::default();
2380        let inputs = ProjectResolveInputs {
2381            project_flag: None,
2382            session: &session,
2383            worktree_path: None,
2384            config_default: None,
2385        };
2386        // Same call `run_status`'s credential-less arm makes.
2387        let user_default_project = crate::user_project_default::load();
2388        let outcome = offline_project_outcome(&inputs, user_default_project);
2389        let check = project_binding_check(&outcome);
2390        assert_eq!(check.level, Level::Ok, "detail: {}", check.detail);
2391        assert!(
2392            check.detail.contains("My Project"),
2393            "detail: {}",
2394            check.detail
2395        );
2396    }
2397
2398    #[test]
2399    fn recording_attribution_finds_subagent_override_via_linked_worktree_cwd() {
2400        // The subagent override is keyed by the LINKED worktree's own
2401        // toplevel, not the primary repo's — resolving from the wrong one
2402        // must miss it.
2403        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2404        let cfg_tmp = tempfile::tempdir().unwrap();
2405        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2406        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2407        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2408
2409        let base = tempfile::tempdir().unwrap();
2410        let repo_dir = base.path().join("repo");
2411        let wt_dir = base.path().join("wt");
2412        std::fs::create_dir_all(&repo_dir).unwrap();
2413        crate::test_helpers::init_git_repo(&repo_dir);
2414        crate::test_helpers::add_worktree(&repo_dir, &wt_dir);
2415
2416        let wt_key = crate::paths::worktree_toplevel(&wt_dir);
2417        let project_id = uuid::Uuid::from_u128(42);
2418        let mut subagent_projects = std::collections::HashMap::new();
2419        subagent_projects.insert(
2420            wt_key,
2421            crate::session_state::ProjectBinding {
2422                project_id: project_id.to_string(),
2423                project_name: "linked".into(),
2424                updated_at: "t".into(),
2425            },
2426        );
2427        let state = crate::session_state::SessionState {
2428            subagent_projects,
2429            ..Default::default()
2430        };
2431        let sessions_dir = tempfile::tempdir().unwrap();
2432        std::fs::write(
2433            sessions_dir.path().join("sess-linked.toml"),
2434            toml::to_string(&state).unwrap(),
2435        )
2436        .unwrap();
2437
2438        // From the LINKED worktree cwd, the subagent override resolves.
2439        let (found, _worktree) = recording_attribution(
2440            Some(sessions_dir.path()),
2441            Some("sess-linked"),
2442            &wt_dir,
2443            None,
2444        );
2445        assert_eq!(
2446            found,
2447            Some(crate::commands::stream::Attribution::ProjectOnly { project_id })
2448        );
2449
2450        // From the PRIMARY worktree root instead, the key doesn't match, so
2451        // nothing resolves.
2452        let (missed, _worktree) = recording_attribution(
2453            Some(sessions_dir.path()),
2454            Some("sess-linked"),
2455            &repo_dir,
2456            None,
2457        );
2458        assert_eq!(missed, None);
2459    }
2460
2461    #[test]
2462    fn verdict_malformed_project_id_leaves_project_axis_unbound() {
2463        // Pins that the display fix (`project_binding_check`) and the real
2464        // verdict (`recording_attribution` -> `capture_project`) cannot
2465        // diverge: a malformed `project_id` must be dropped by both.
2466        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2467        let cfg_tmp = tempfile::tempdir().unwrap();
2468        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2469        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2470        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2471
2472        let state = crate::session_state::SessionState {
2473            active_project: Some(project_binding("not-a-uuid", "My Project")),
2474            ..Default::default()
2475        };
2476        let sessions_dir = tempfile::tempdir().unwrap();
2477        std::fs::write(
2478            sessions_dir.path().join("sess-bad-project.toml"),
2479            toml::to_string(&state).unwrap(),
2480        )
2481        .unwrap();
2482
2483        let cwd = tempfile::tempdir().unwrap();
2484        let (attribution, _worktree) = recording_attribution(
2485            Some(sessions_dir.path()),
2486            Some("sess-bad-project"),
2487            cwd.path(),
2488            None,
2489        );
2490        assert_eq!(
2491            attribution, None,
2492            "a malformed project_id must not resolve an attribution"
2493        );
2494        assert_eq!(
2495            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2496            Some(Level::Error)
2497        );
2498    }
2499
2500    #[test]
2501    fn verdict_malformed_repo_id_with_nothing_else_bound_is_error() {
2502        // Same principle, repo axis: `attribution_for` drops a binding whose
2503        // `repo_id` fails `binding_repo_id_is_valid`, so nothing else bound
2504        // must still error, matching `workspace_binding_*_malformed_repo_id_*`.
2505        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
2506        let cfg_tmp = tempfile::tempdir().unwrap();
2507        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2508        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
2509        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
2510
2511        let state = crate::session_state::SessionState {
2512            active: Some(crate::session_state::RepoBinding {
2513                repo_id: "not-a-uuid".into(),
2514                git_url: None,
2515                remote_id: None,
2516                codebase_name: None,
2517                updated_at: "t".into(),
2518            }),
2519            ..Default::default()
2520        };
2521        let sessions_dir = tempfile::tempdir().unwrap();
2522        std::fs::write(
2523            sessions_dir.path().join("sess-bad-repo.toml"),
2524            toml::to_string(&state).unwrap(),
2525        )
2526        .unwrap();
2527
2528        let cwd = tempfile::tempdir().unwrap();
2529        let (attribution, _worktree) = recording_attribution(
2530            Some(sessions_dir.path()),
2531            Some("sess-bad-repo"),
2532            cwd.path(),
2533            None,
2534        );
2535        assert_eq!(
2536            attribution, None,
2537            "a malformed repo_id must not resolve an attribution"
2538        );
2539        assert_eq!(
2540            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
2541            Some(Level::Error)
2542        );
2543    }
2544
2545    #[test]
2546    fn unresolved_config_default_check_names_it_and_is_warn() {
2547        let check = unresolved_config_default_check("payments-platform");
2548        assert_eq!(check.level, Level::Warn);
2549        assert!(
2550            check.detail.contains("payments-platform"),
2551            "detail: {}",
2552            check.detail
2553        );
2554        assert!(
2555            check
2556                .detail
2557                .contains("not used for attribution at capture time"),
2558            "detail should not imply resolving it would make capture-time \
2559             attribution work: {}",
2560            check.detail
2561        );
2562    }
2563}