tracevault-cli 0.21.0

CLI tool for Visdom Trace - AI code tracing and attribution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! `tracevault status` — surface every piece of state a user might need to
//! debug "why doesn't it work". The command runs read-only checks across
//! credentials, the project tree, and the server, and prints a grouped
//! report with ✓ / ✗ / ! markers. Exits non-zero if anything actionable is
//! broken.

use crate::api_client::{ApiClient, GetMeError};
use crate::config::TracevaultConfig;
use crate::credentials::Credentials;
use std::fs;
use std::path::Path;
use std::process::Command;

const ANSI_GREEN: &str = "\x1b[32m";
const ANSI_RED: &str = "\x1b[31m";
const ANSI_YELLOW: &str = "\x1b[33m";
const ANSI_DIM: &str = "\x1b[2m";
const ANSI_RESET: &str = "\x1b[0m";

/// Severity classification of a single check. Anything at `Error` level
/// bumps the final exit code to 1.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Level {
    Ok,
    Warn,
    Error,
    /// Check skipped because a prerequisite failed (e.g. can't validate
    /// token if no token was found). Does not affect exit code.
    Skip,
}

#[derive(Debug)]
struct Check {
    label: String,
    level: Level,
    detail: String,
}

impl Check {
    fn ok(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            level: Level::Ok,
            detail: detail.into(),
        }
    }
    fn warn(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            level: Level::Warn,
            detail: detail.into(),
        }
    }
    fn err(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            level: Level::Error,
            detail: detail.into(),
        }
    }
    fn skip(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            level: Level::Skip,
            detail: detail.into(),
        }
    }
}

fn marker(l: Level) -> &'static str {
    match l {
        Level::Ok => "\x1b[32m✓\x1b[0m",
        Level::Warn => "\x1b[33m!\x1b[0m",
        Level::Error => "\x1b[31m✗\x1b[0m",
        Level::Skip => "\x1b[2m·\x1b[0m",
    }
}

fn print_section(title: &str, checks: &[Check]) {
    println!("{ANSI_DIM}──{ANSI_RESET} {title}");
    for c in checks {
        if c.detail.is_empty() {
            println!("  {} {}", marker(c.level), c.label);
        } else {
            println!(
                "  {} {:<32} {ANSI_DIM}{}{ANSI_RESET}",
                marker(c.level),
                c.label,
                c.detail
            );
        }
    }
    println!();
}

// --- Authentication ---

struct AuthContext {
    server_url: Option<String>,
    token: Option<String>,
    source: &'static str, // "env", "credentials", or "none"
    email_from_creds: Option<String>,
}

fn resolve_auth() -> AuthContext {
    // Env var wins. Match the server-side resolution order in
    // resolve_credentials (env > creds), except we treat the env var as
    // authoritative without looking at the credentials file email.
    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
    let env_url = std::env::var("TRACEVAULT_SERVER_URL").ok();

    if let Some(token) = env_key {
        return AuthContext {
            server_url: env_url,
            token: Some(token),
            source: "env (TRACEVAULT_API_KEY)",
            email_from_creds: None,
        };
    }

    let creds = Credentials::load();
    if let Some(c) = creds {
        return AuthContext {
            server_url: Some(c.server_url),
            token: Some(c.token),
            source: "credentials file",
            email_from_creds: Some(c.email),
        };
    }

    AuthContext {
        server_url: env_url,
        token: None,
        source: "none",
        email_from_creds: None,
    }
}

async fn auth_checks(auth: &AuthContext) -> Vec<Check> {
    let mut out = Vec::new();

    match (auth.token.as_ref(), auth.server_url.as_ref()) {
        (None, _) => {
            out.push(Check::err(
                "Logged in",
                "no credentials found. Run `tracevault login --server-url <URL>`.",
            ));
            out.push(Check::skip("Token valid", "no token to check"));
            return out;
        }
        (Some(_), None) => {
            out.push(Check::err(
                "Logged in",
                "token found but no server URL (set TRACEVAULT_SERVER_URL)",
            ));
            out.push(Check::skip("Token valid", "no server URL to call"));
            return out;
        }
        (Some(_), Some(url)) => {
            out.push(Check::ok("Logged in", format!("{url} via {}", auth.source)));
        }
    }

    let server_url = auth.server_url.as_ref().unwrap();
    let token = auth.token.as_ref().unwrap();
    let client = ApiClient::new(server_url, Some(token));
    match client.get_me().await {
        Ok(me) => {
            let who = me.name.unwrap_or_else(|| me.email.clone());
            out.push(Check::ok("Token valid", format!("{who} <{}>", me.email)));

            if let Some(cached) = &auth.email_from_creds {
                if cached != &me.email {
                    out.push(Check::warn(
                        "Credentials cache",
                        format!(
                            "cached email '{cached}' differs from server '{}' — re-run login",
                            me.email
                        ),
                    ));
                }
            }
        }
        Err(GetMeError::Unauthorized) => {
            out.push(Check::err(
                "Token valid",
                "rejected by server (expired or revoked). Run `tracevault login` again.",
            ));
        }
        Err(GetMeError::Network(msg)) => {
            out.push(Check::warn(
                "Server reachable",
                format!("{msg} — cannot confirm token validity"),
            ));
        }
        Err(GetMeError::Server(msg)) => {
            out.push(Check::warn("Token valid", format!("server error: {msg}")));
        }
    }
    out
}

// --- Project ---

/// Subset of project checks that don't need network. Returns the loaded
/// config if present so later sections can reuse it.
fn project_checks(project_root: &Path) -> (Vec<Check>, Option<TracevaultConfig>) {
    let mut out = Vec::new();

    let is_git = project_root.join(".git").exists();
    if is_git {
        out.push(Check::ok(
            "Git repository",
            project_root.display().to_string(),
        ));
    } else {
        out.push(Check::err(
            "Git repository",
            "current directory is not a git repo",
        ));
    }

    let tv_dir = project_root.join(".tracevault");
    if !tv_dir.exists() {
        out.push(Check::err(
            "TraceVault initialized",
            "no .tracevault/ directory. Run `tracevault init`.",
        ));
        return (out, None);
    }
    out.push(Check::ok("TraceVault initialized", ".tracevault/ present"));

    // Distinguish "no config.toml" (expected in workspace/detached mode —
    // just a warning) from "config.toml present but malformed" (a genuine
    // error) via `try_load`, rather than the lenient `load` which collapses
    // both cases to `None`.
    let config = match TracevaultConfig::try_load(project_root) {
        Ok(Some(c)) => {
            let slug = c.org_slug.as_deref().unwrap_or("<unset>");
            let url = c.server_url.as_deref().unwrap_or("<unset>");
            out.push(Check::ok(
                "Project config",
                format!("org={slug}, server={url}"),
            ));
            Some(c)
        }
        Ok(None) => {
            out.push(Check::warn(
                "Project config",
                "No .tracevault/config.toml. Bound mode: run `tracevault init`. Workspace/detached mode: this is expected — use `tracevault repo status` to see the session binding.",
            ));
            None
        }
        Err(e) => {
            out.push(Check::err(
                "Project config",
                format!(".tracevault/config.toml malformed: {e}"),
            ));
            None
        }
    };

    // Hooks — presence of our markers, not just existence of the hook file.
    out.push(git_hook_check(
        project_root,
        "pre-push",
        "# tracevault:enforce",
    ));
    out.push(git_hook_check(
        project_root,
        "post-commit",
        "# tracevault:post-commit",
    ));
    out.push(claude_hook_check(project_root));

    (out, config)
}

fn git_hook_check(project_root: &Path, name: &str, marker: &str) -> Check {
    let path = project_root.join(".git/hooks").join(name);
    let label = format!("Git hook: {name}");
    if !path.exists() {
        return Check::warn(
            label,
            format!(".git/hooks/{name} missing — rerun `tracevault init`"),
        );
    }
    match fs::read_to_string(&path) {
        Ok(s) if s.contains(marker) => Check::ok(label, "installed"),
        Ok(_) => Check::warn(
            label,
            format!("{name} exists but no tracevault block — rerun `tracevault init`"),
        ),
        Err(e) => Check::warn(label, format!("cannot read hook: {e}")),
    }
}

fn claude_hook_check(project_root: &Path) -> Check {
    let settings = project_root.join(".claude/settings.json");
    if !settings.exists() {
        // Not installed is a warning, not an error: tracevault still works
        // without Claude Code hooks (just with less rich capture).
        return Check::warn(
            "Claude Code hooks",
            ".claude/settings.json missing (capture will miss some events)",
        );
    }
    match fs::read_to_string(&settings) {
        Ok(s) if s.contains("tracevault stream") => {
            Check::ok("Claude Code hooks", "registered in .claude/settings.json")
        }
        Ok(_) => Check::warn(
            "Claude Code hooks",
            "settings.json has no tracevault stream commands",
        ),
        Err(e) => Check::warn(
            "Claude Code hooks",
            format!("cannot read settings.json: {e}"),
        ),
    }
}

// --- Server repo ---

async fn server_repo_checks(
    project_root: &Path,
    auth: &AuthContext,
    config: Option<&TracevaultConfig>,
) -> Vec<Check> {
    let mut out = Vec::new();

    let (Some(token), Some(server_url)) = (auth.token.as_ref(), auth.server_url.as_ref()) else {
        out.push(Check::skip(
            "Repo registered on server",
            "not authenticated",
        ));
        return out;
    };
    let Some(slug) = config.and_then(|c| c.org_slug.as_deref()) else {
        out.push(Check::skip(
            "Repo registered on server",
            "no org_slug in config",
        ));
        return out;
    };

    let client = ApiClient::new(server_url, Some(token));
    let repos = match client.list_repos(slug).await {
        Ok(r) => r,
        Err(e) => {
            out.push(Check::warn(
                "Repo registered on server",
                format!("failed to list repos: {e}"),
            ));
            return out;
        }
    };

    let repo_name = git_repo_name(project_root);
    let found = repos.iter().find(|r| r.name == repo_name);

    match found {
        None => {
            out.push(Check::err(
                "Repo registered on server",
                format!("'{repo_name}' not found in org '{slug}'. Run `tracevault init` while logged in, or `tracevault sync`."),
            ));
            return out;
        }
        Some(r) => {
            out.push(Check::ok(
                "Repo registered on server",
                format!("id={}", r.id),
            ));
            match r.clone_status.as_deref() {
                Some("ready") => out.push(Check::ok("Server-side clone", "ready")),
                Some(other @ ("cloning" | "pending")) => out.push(Check::warn(
                    "Server-side clone",
                    format!("{other} — analytics and code browser unavailable until it finishes"),
                )),
                Some("error") => out.push(Check::err(
                    "Server-side clone",
                    "error — check the repo settings page on the dashboard",
                )),
                Some(other) => out.push(Check::warn(
                    "Server-side clone",
                    format!("unknown status '{other}'"),
                )),
                None => out.push(Check::skip(
                    "Server-side clone",
                    "server did not report clone status",
                )),
            }

            let local_remote = git_remote_url(project_root);
            match (local_remote.as_deref(), r.github_url.as_deref()) {
                (Some(local), Some(remote))
                    if normalize_remote(local) == normalize_remote(remote) =>
                {
                    out.push(Check::ok("Remote URL matches", remote.to_string()));
                }
                (Some(local), Some(remote)) => out.push(Check::warn(
                    "Remote URL matches",
                    format!("local={local} vs server={remote} — run `tracevault sync`"),
                )),
                (Some(local), None) => out.push(Check::warn(
                    "Remote URL matches",
                    format!("server has no github_url; local={local}"),
                )),
                (None, _) => out.push(Check::warn(
                    "Remote URL matches",
                    "no local `origin` remote configured",
                )),
            }
        }
    }

    out
}

// --- Sessions ---

/// True for a per-repo `pending-<id>.jsonl` (nonempty id) queue file —
/// tighter than a bare `starts_with("pending") && ends_with(".jsonl")`
/// check, which would also match e.g. `pendingfoo.jsonl` or `pending-.jsonl`.
/// The legacy `pending.jsonl` name is handled separately by callers, since
/// whether it counts depends on whether there's a bound `repo_id` to
/// attribute it to (see `count_pending_events`).
fn is_pending_queue_filename(name: &str) -> bool {
    crate::commands::flush::repo_id_from_pending_filename(name).is_some()
}

/// Sum the non-empty lines across every per-repo (and, if `include_legacy`,
/// legacy) pending queue file in a session directory: `pending.jsonl` and
/// `pending-<repo_id>.jsonl`.
///
/// `include_legacy` should be true only when the project has a bound
/// `repo_id` (config.toml), since `flush` only drains the legacy
/// `pending.jsonl` in that case (best-effort attribution). Otherwise a
/// stray `pending.jsonl` would be counted here but never cleared by
/// `flush`, leaving `status` permanently reporting stuck events.
fn count_pending_events(session_dir: &Path, include_legacy: bool) -> usize {
    let Ok(read) = fs::read_dir(session_dir) else {
        return 0;
    };

    read.flatten()
        .filter(|entry| {
            entry
                .file_name()
                .to_str()
                .map(|name| {
                    is_pending_queue_filename(name) || (include_legacy && name == "pending.jsonl")
                })
                .unwrap_or(false)
        })
        .map(|entry| {
            fs::read_to_string(entry.path())
                .unwrap_or_default()
                .lines()
                .filter(|l| !l.trim().is_empty())
                .count()
        })
        .sum()
}

fn session_checks(project_root: &Path) -> Vec<Check> {
    let sessions_dir = project_root.join(".tracevault/sessions");
    if !sessions_dir.exists() {
        return vec![Check::skip(
            "Pending events",
            "no .tracevault/sessions/ yet (no captures recorded)",
        )];
    }

    // The legacy `pending.jsonl` is only drainable by `flush` when there's a
    // bound `repo_id` to attribute it to (best-effort attribution). Counting
    // it here otherwise would report events that `flush` can never clear.
    let include_legacy = TracevaultConfig::load(project_root)
        .and_then(|c| c.repo_id)
        .is_some();

    let mut total_sessions = 0usize;
    let mut sessions_with_pending = 0usize;
    let mut pending_event_count = 0usize;

    if let Ok(read) = fs::read_dir(&sessions_dir) {
        for entry in read.flatten() {
            if !entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                continue;
            }
            total_sessions += 1;
            let count = count_pending_events(&entry.path(), include_legacy);
            if count > 0 {
                sessions_with_pending += 1;
                pending_event_count += count;
            }
        }
    }

    vec![if sessions_with_pending == 0 {
        Check::ok(
            "Pending events",
            format!("{total_sessions} session(s), all synced"),
        )
    } else {
        Check::warn(
            "Pending events",
            format!(
                "{pending_event_count} event(s) in {sessions_with_pending}/{total_sessions} session(s) — run `tracevault flush`"
            ),
        )
    }]
}

// --- Git helpers ---

fn git_repo_name(project_root: &Path) -> String {
    Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(project_root)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .as_deref()
        .and_then(|p| p.rsplit('/').next())
        .map(String::from)
        .unwrap_or_else(|| "unknown".into())
}

fn git_remote_url(project_root: &Path) -> Option<String> {
    Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(project_root)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .filter(|s| !s.is_empty())
}

/// Make two remote URLs comparable by dropping `.git`, trailing slash, and
/// collapsing SSH ↔ HTTPS differences for github.com specifically.
fn normalize_remote(url: &str) -> String {
    let trimmed = url
        .trim()
        .trim_end_matches('/')
        .trim_end_matches(".git")
        .to_string();

    // git@github.com:org/repo  ->  github.com/org/repo
    if let Some(rest) = trimmed.strip_prefix("git@github.com:") {
        return format!("github.com/{rest}");
    }
    // https://github.com/org/repo -> github.com/org/repo
    for p in ["https://", "http://"] {
        if let Some(rest) = trimmed.strip_prefix(p) {
            return rest.to_string();
        }
    }
    trimmed
}

// --- Entry point ---

pub async fn run_status(project_root: &Path) -> i32 {
    let auth = resolve_auth();

    let auth_checks_v = auth_checks(&auth).await;
    let (proj_checks_v, config) = project_checks(project_root);
    let server_checks_v = server_repo_checks(project_root, &auth, config.as_ref()).await;
    let session_checks_v = session_checks(project_root);

    print_section("Authentication", &auth_checks_v);
    print_section("Project", &proj_checks_v);
    print_section("Server repo", &server_checks_v);
    print_section("Sessions", &session_checks_v);

    let all: Vec<&Check> = auth_checks_v
        .iter()
        .chain(proj_checks_v.iter())
        .chain(server_checks_v.iter())
        .chain(session_checks_v.iter())
        .collect();

    let errors = all.iter().filter(|c| c.level == Level::Error).count();
    let warns = all.iter().filter(|c| c.level == Level::Warn).count();

    match (errors, warns) {
        (0, 0) => println!("{ANSI_GREEN}All good.{ANSI_RESET}"),
        (0, w) => println!(
            "{ANSI_YELLOW}{w} warning{} — no blocking issues.{ANSI_RESET}",
            if w == 1 { "" } else { "s" }
        ),
        (e, 0) => println!(
            "{ANSI_RED}{e} problem{} found.{ANSI_RESET}",
            if e == 1 { "" } else { "s" }
        ),
        (e, w) => println!(
            "{ANSI_RED}{e} problem{}, {w} warning{}.{ANSI_RESET}",
            if e == 1 { "" } else { "s" },
            if w == 1 { "" } else { "s" }
        ),
    }

    exit_code_for(&all)
}

/// Only `Level::Error` checks force a non-zero exit; `Warn` and `Skip` are
/// surfaced to the user but don't fail the command. Pulled out as a pure
/// function so the severity→exit-code mapping is unit-testable independent
/// of the network-calling `run_status`.
fn exit_code_for(checks: &[&Check]) -> i32 {
    if checks.iter().any(|c| c.level == Level::Error) {
        1
    } else {
        0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn normalize_remote_ssh_https_equal() {
        assert_eq!(
            normalize_remote("git@github.com:VirtusLab/visdom-ai-tracing.git"),
            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing")
        );
        assert_eq!(
            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing.git/"),
            "github.com/VirtusLab/visdom-ai-tracing"
        );
    }

    #[test]
    fn normalize_remote_preserves_non_github() {
        assert_eq!(
            normalize_remote("git@gitlab.com:foo/bar.git"),
            "git@gitlab.com:foo/bar"
        );
    }

    #[test]
    fn git_hook_check_missing_file_is_warning() {
        let dir = tempfile::tempdir().unwrap();
        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
        assert_eq!(check.level, Level::Warn);
    }

    #[test]
    fn git_hook_check_with_marker_is_ok() {
        let dir = tempfile::tempdir().unwrap();
        let hooks = dir.path().join(".git/hooks");
        std::fs::create_dir_all(&hooks).unwrap();
        std::fs::write(
            hooks.join("pre-push"),
            "#!/bin/sh\n# tracevault:enforce\ntracevault check\n",
        )
        .unwrap();
        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
        assert_eq!(check.level, Level::Ok);
    }

    #[test]
    fn git_hook_check_without_marker_is_warning() {
        let dir = tempfile::tempdir().unwrap();
        let hooks = dir.path().join(".git/hooks");
        std::fs::create_dir_all(&hooks).unwrap();
        std::fs::write(hooks.join("pre-push"), "#!/bin/sh\necho hi\n").unwrap();
        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
        assert_eq!(check.level, Level::Warn);
    }

    #[test]
    fn project_checks_errors_without_tracevault_dir() {
        let dir = tempfile::tempdir().unwrap();
        // Create .git so the git-repo check passes, isolate the assertion.
        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
        let (checks, cfg) = project_checks(dir.path());
        assert!(cfg.is_none());
        assert!(checks
            .iter()
            .any(|c| c.level == Level::Error && c.label == "TraceVault initialized"));
    }

    #[test]
    fn project_checks_warns_when_config_toml_missing() {
        // Pure workspace/detached-mode user: .tracevault/ exists (or not,
        // doesn't matter for this check) but there's no config.toml because
        // `tracevault init` was never run. This must be a Warn, not an
        // Error, and therefore must not force the process exit code to 1.
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
        std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
        let (checks, cfg) = project_checks(dir.path());
        assert!(cfg.is_none());
        let project_config_check = checks
            .iter()
            .find(|c| c.label == "Project config")
            .expect("Project config check present");
        assert_eq!(project_config_check.level, Level::Warn);

        let refs: Vec<&Check> = checks.iter().collect();
        assert_eq!(
            exit_code_for(&refs),
            0,
            "a missing config.toml alone must not force a non-zero exit code"
        );
    }

    #[test]
    fn project_checks_errors_on_malformed_config_toml() {
        // A config.toml that exists but fails to parse is a genuine error,
        // distinct from "no config.toml at all" — it should stay Check::err
        // and keep forcing a non-zero exit code.
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
        std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
        std::fs::write(
            dir.path().join(".tracevault/config.toml"),
            "not valid toml {{{",
        )
        .unwrap();
        let (checks, cfg) = project_checks(dir.path());
        assert!(cfg.is_none());
        let project_config_check = checks
            .iter()
            .find(|c| c.label == "Project config")
            .expect("Project config check present");
        assert_eq!(project_config_check.level, Level::Error);

        let refs: Vec<&Check> = checks.iter().collect();
        assert_eq!(exit_code_for(&refs), 1);
    }

    #[test]
    fn exit_code_for_warn_only_is_zero() {
        let checks = [
            Check::warn("a", ""),
            Check::ok("b", ""),
            Check::skip("c", ""),
        ];
        let refs: Vec<&Check> = checks.iter().collect();
        assert_eq!(exit_code_for(&refs), 0);
    }

    #[test]
    fn exit_code_for_any_error_is_one() {
        let checks = [
            Check::ok("a", ""),
            Check::err("b", ""),
            Check::warn("c", ""),
        ];
        let refs: Vec<&Check> = checks.iter().collect();
        assert_eq!(exit_code_for(&refs), 1);
    }

    #[test]
    fn count_pending_events_sums_across_per_repo_queues() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
        std::fs::write(dir.path().join("pending-b.jsonl"), "line1\n").unwrap();
        std::fs::write(dir.path().join("pending-c.jsonl"), "").unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 3);
        assert_eq!(count_pending_events(dir.path(), true), 3);
    }

    #[test]
    fn count_pending_events_ignores_unrelated_files() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\n").unwrap();
        std::fs::write(dir.path().join("notes.txt"), "line1\nline2\n").unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 1);
    }

    #[test]
    fn count_pending_events_zero_for_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 0);
        assert_eq!(count_pending_events(dir.path(), true), 0);
    }

    #[test]
    fn is_pending_queue_filename_matches_per_repo_only() {
        assert!(!is_pending_queue_filename("pending.jsonl"));
        assert!(is_pending_queue_filename("pending-a.jsonl"));
    }

    #[test]
    fn is_pending_queue_filename_rejects_lookalikes() {
        assert!(!is_pending_queue_filename("pendingfoo.jsonl"));
        assert!(!is_pending_queue_filename("pending-.jsonl"));
    }

    #[test]
    fn count_pending_events_legacy_pending_jsonl_requires_include_legacy() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pending.jsonl"), "line1\nline2\n").unwrap();
        assert_eq!(
            count_pending_events(dir.path(), false),
            0,
            "legacy pending.jsonl must not be counted when there's no bound repo_id"
        );
        assert_eq!(
            count_pending_events(dir.path(), true),
            2,
            "legacy pending.jsonl counts once a repo_id is bound"
        );
    }

    #[test]
    fn count_pending_events_legacy_and_per_repo_both_count_when_included() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pending.jsonl"), "line1\n").unwrap();
        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 2);
        assert_eq!(count_pending_events(dir.path(), true), 3);
    }

    #[test]
    fn count_pending_events_ignores_lookalike_filenames() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pendingfoo.jsonl"), "line1\n").unwrap();
        std::fs::write(dir.path().join("pending-.jsonl"), "line1\n").unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 0);
        assert_eq!(count_pending_events(dir.path(), true), 0);
    }
}