vct-core 2.3.1

Vibe Coding Tracker core library - parse local AI coding assistant session data into CodeAnalysis results
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
use crate::constants::FastHashSet;
use crate::models::TimeRange;
use anyhow::Result;
use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

/// A file matched during directory traversal, paired with its modification date.
pub struct FileInfo {
    /// Absolute path to the matched file.
    pub path: PathBuf,
    /// Local modification date formatted as `YYYY-MM-DD`, used for grouping.
    pub modified_date: String,
}

/// One directory traversal or metadata error encountered during discovery.
#[derive(Debug)]
pub(crate) struct FileDiscoveryFailure {
    /// Path whose directory entry or metadata could not be read.
    pub path: PathBuf,
    /// Content-safe error summary.
    pub error: String,
}

/// Files discovered successfully plus any partial traversal failures.
pub(crate) struct FileDiscovery {
    /// Matched files that could be inspected successfully.
    pub files: Vec<FileInfo>,
    /// Traversal, metadata, or mtime failures in deterministic path order.
    pub failures: Vec<FileDiscoveryFailure>,
}

/// Recursively collects the files under `dir` that pass `filter_fn`, tagging
/// each with its modification date.
///
/// `filter_fn` decides whether a given path is included; `time_range` drops
/// files whose modification date falls before its cutoff. Equivalent to
/// [`collect_files_with_max_depth`] with no depth cap.
///
/// # Errors
///
/// Returns `Result` for caller ergonomics, but the current implementation
/// never produces an error: a missing directory yields an empty list, and
/// per-entry traversal or metadata failures are silently skipped.
pub fn collect_files_with_dates<P, F>(
    dir: P,
    filter_fn: F,
    time_range: TimeRange,
) -> Result<Vec<FileInfo>>
where
    P: AsRef<Path>,
    F: Fn(&Path) -> bool,
{
    collect_files_with_max_depth(dir, filter_fn, time_range, None)
}

/// Same as [`collect_files_with_dates`] but with an optional traversal depth cap.
///
/// `max_depth` is counted from the root directory: `None` walks the whole
/// tree, `Some(2)` only descends two levels. Callers that know the exact
/// nesting of the file they want (e.g. Copilot's
/// `session-state/<sessionId>/events.jsonl` is always at depth 2) can use
/// this to avoid paying the cost of `WalkDir` visiting large sibling
/// subtrees such as `rewind-snapshots/backups/` that never contain a
/// match but can hold hundreds of files per session.
///
/// # Errors
///
/// Returns `Result` for caller ergonomics, but the current implementation
/// never produces an error: a missing directory yields an empty list, and
/// per-entry traversal or metadata failures are silently skipped.
pub fn collect_files_with_max_depth<P, F>(
    dir: P,
    filter_fn: F,
    time_range: TimeRange,
    max_depth: Option<usize>,
) -> Result<Vec<FileInfo>>
where
    P: AsRef<Path>,
    F: Fn(&Path) -> bool,
{
    Ok(collect_files_with_max_depth_diagnostics(dir, filter_fn, time_range, max_depth).files)
}

/// Discovers matching files while retaining partial traversal failures.
pub(crate) fn collect_files_with_max_depth_diagnostics<P, F>(
    dir: P,
    filter_fn: F,
    time_range: TimeRange,
    max_depth: Option<usize>,
) -> FileDiscovery
where
    P: AsRef<Path>,
    F: Fn(&Path) -> bool,
{
    let dir = dir.as_ref();
    match fs::metadata(dir) {
        Ok(_) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return FileDiscovery {
                files: Vec::new(),
                failures: Vec::new(),
            };
        }
        Err(error) => {
            return FileDiscovery {
                files: Vec::new(),
                failures: vec![FileDiscoveryFailure {
                    path: dir.to_path_buf(),
                    error: error.to_string(),
                }],
            };
        }
    }

    let cutoff = time_range
        .cutoff_date()
        .map(|d| d.format("%Y-%m-%d").to_string());

    // Pre-allocate Vec with estimated capacity (typical: 10-50 session files)
    let mut results = Vec::with_capacity(20);
    let mut failures = Vec::new();

    let mut walker = WalkDir::new(dir);
    if let Some(depth) = max_depth {
        walker = walker.max_depth(depth);
    }

    for entry in walker {
        let entry = match entry {
            Ok(entry) => entry,
            Err(error) => {
                failures.push(FileDiscoveryFailure {
                    path: error.path().unwrap_or(dir).to_path_buf(),
                    error: error.to_string(),
                });
                continue;
            }
        };
        if !entry.file_type().is_file() {
            continue;
        }

        let path = entry.path();

        // Apply filter
        if !filter_fn(path) {
            continue;
        }

        // Get file modification time for date grouping
        let metadata = match entry.metadata() {
            Ok(metadata) => metadata,
            Err(error) => {
                failures.push(FileDiscoveryFailure {
                    path: path.to_path_buf(),
                    error: error.to_string(),
                });
                continue;
            }
        };

        let modified = match metadata.modified() {
            Ok(modified) => modified,
            Err(error) => {
                failures.push(FileDiscoveryFailure {
                    path: path.to_path_buf(),
                    error: error.to_string(),
                });
                continue;
            }
        };
        let datetime: chrono::DateTime<chrono::Local> = modified.into();
        let date_key = datetime.format("%Y-%m-%d").to_string();

        // Apply time range filter
        if let Some(ref cutoff_str) = cutoff
            && date_key.as_str() < cutoff_str.as_str()
        {
            continue;
        }

        results.push(FileInfo {
            path: path.to_path_buf(),
            modified_date: date_key,
        });
    }

    failures.sort_by(|left, right| {
        left.path
            .cmp(&right.path)
            .then_with(|| left.error.cmp(&right.error))
    });
    FileDiscovery {
        files: results,
        failures,
    }
}

/// Discovers matching files across every root one provider's sessions live in.
///
/// Roots are walked in order and their results concatenated, so a provider with
/// a single root behaves exactly as [`collect_files_with_max_depth_diagnostics`]
/// does. With more than one root, a file name already found in an **earlier**
/// root is dropped from a later one: Codex archives a session by moving its
/// rollout log from `sessions/` to `archived_sessions/`, and a scan that races
/// that move would otherwise fold the same session twice.
///
/// Declaring more than one root therefore asserts that a repeated file name means
/// a repeated session. Codex satisfies that: its rollout logs are named
/// `rollout-<timestamp>-<uuid>.jsonl` and keep that name across the move. Names
/// are compared only across roots, never within one, because a provider may
/// legitimately give every session the same file name (Copilot writes
/// `events.jsonl` for all of them) — such a provider has to stay single-root.
/// Each drop is logged at debug level so a wrong assertion is diagnosable rather
/// than a silently missing session.
pub(crate) fn collect_provider_files_diagnostics<F>(
    dirs: &[&Path],
    filter_fn: F,
    time_range: TimeRange,
    max_depth: Option<usize>,
) -> FileDiscovery
where
    F: Fn(&Path) -> bool,
{
    let Some((first, rest)) = dirs.split_first() else {
        return FileDiscovery {
            files: Vec::new(),
            failures: Vec::new(),
        };
    };
    let mut discovery =
        collect_files_with_max_depth_diagnostics(first, &filter_fn, time_range, max_depth);
    if rest.is_empty() {
        return discovery;
    }

    for dir in rest {
        let mut found =
            collect_files_with_max_depth_diagnostics(dir, &filter_fn, time_range, max_depth);
        discovery.failures.append(&mut found.failures);
        // The overwhelmingly common shape is an absent or empty later root (no
        // session has been archived yet), so skip building the name index for it.
        if found.files.is_empty() {
            continue;
        }
        // Scoped so the borrow of the already-merged names ends before the append.
        {
            let seen: FastHashSet<&OsStr> = discovery
                .files
                .iter()
                .filter_map(|file| file.path.file_name())
                .collect();
            found.files.retain(|file| {
                let duplicate = file
                    .path
                    .file_name()
                    .is_some_and(|name| seen.contains(name));
                if duplicate {
                    log::debug!(
                        "skipping {}: already discovered under an earlier session root",
                        file.path.display()
                    );
                }
                !duplicate
            });
        }
        discovery.files.append(&mut found.files);
    }

    discovery.failures.sort_by(|left, right| {
        left.path
            .cmp(&right.path)
            .then_with(|| left.error.cmp(&right.error))
    });
    discovery
}

/// Maximum traversal depth for Copilot CLI session scans.
///
/// Copilot writes `~/.copilot/session-state/<sessionId>/events.jsonl`, so
/// the event log is always exactly two directory levels below
/// `session-state/`. Anything deeper belongs to companion subtrees we
/// intentionally ignore (`rewind-snapshots/backups/`, `checkpoints/`,
/// `files/`, `research/`) — some of which can hold dozens of files per
/// session and would otherwise make `WalkDir` visit hundreds of entries
/// per session just to have `is_copilot_session_file` reject them.
pub const COPILOT_SESSION_MAX_DEPTH: usize = 2;

/// Maximum traversal depth for Grok CLI session scans.
///
/// Grok writes `$GROK_HOME/sessions/<workspace>/<session>/signals.json`, so
/// each signals file is exactly three levels below the sessions root.
pub const GROK_SESSION_MAX_DEPTH: usize = 3;

/// Filter for Codex session files under `~/.codex/sessions/YYYY/MM/DD/`.
///
/// Codex writes `rollout-*.jsonl` files directly into the dated sub-folders.
/// We also accept `.json` defensively in case an older dump ever gets dropped
/// into the tree, but reject Claude Code's `*.meta.json` / `*.meta.jsonl`
/// subagent sidecar files (those live under `~/.claude/projects/` in
/// practice, but the filter still guards against the unlikely collision).
///
/// Intentionally separated from the other per-provider filters
/// (`is_claude_session_file`, `is_copilot_session_file`,
/// `is_gemini_session_file`) even though the body is currently trivial:
/// keeping one filter per provider means future format changes on one
/// provider do not require teasing apart a shared implementation.
pub fn is_codex_session_file(path: &Path) -> bool {
    if is_meta_sidecar_file(path) {
        return false;
    }
    if let Some(ext) = path.extension() {
        ext == "jsonl" || ext == "json"
    } else {
        false
    }
}

/// Filter for Claude Code session files (`.jsonl` only).
///
/// Matches both top-level sessions (`~/.claude/projects/<project>/<session>.jsonl`)
/// and subagent sessions (`~/.claude/projects/<project>/<session>/subagents/agent-*.jsonl`).
/// Rejects meta sidecars (`*.meta.json` / `*.meta.jsonl`) and any non-JSONL artifact
/// that ends up under the projects directory (e.g. screenshots pasted into prompts).
pub fn is_claude_session_file(path: &Path) -> bool {
    if is_meta_sidecar_file(path) {
        return false;
    }
    path.extension().is_some_and(|ext| ext == "jsonl")
}

/// Filter for Gemini CLI session files.
///
/// Current Gemini CLI stores each chat as a line-delimited event stream at
/// `~/.gemini/tmp/<project>/chats/session-*.jsonl`. Subagent sessions sit one
/// level deeper at `chats/<parent-session>/<subagent>.jsonl`. Sibling artifacts
/// (`discordbot/logs.json`, the `bin/rg` binary, `.project_root`) are rejected.
///
/// Legacy single-object exports (`chats/<session>.json`) are intentionally
/// not matched: the JSONL format is the only shape the analyzer understands
/// today, and silently scanning `.json` files we can no longer parse just
/// yields `Warning: Failed to analyze ...` noise on every run.
pub fn is_gemini_session_file(path: &Path) -> bool {
    if path.extension() != Some(std::ffi::OsStr::new("jsonl")) {
        false
    } else {
        path.parent().is_some_and(|parent| {
            parent.file_name() == Some(std::ffi::OsStr::new("chats"))
                || parent.parent().is_some_and(|grandparent| {
                    grandparent.file_name() == Some(std::ffi::OsStr::new("chats"))
                })
        })
    }
}

/// Filter for Copilot CLI session files.
///
/// Copilot CLI stores each session as a directory under
/// `~/.copilot/session-state/<sessionId>/` containing the event log
/// (`events.jsonl`) plus sibling subdirectories for file snapshots
/// (`rewind-snapshots/`, `files/`, `research/`, `checkpoints/`) and a
/// per-workspace YAML file. Only `events.jsonl` carries the conversation
/// stream we want to analyze — if we fell back to the generic JSON filter,
/// `rewind-snapshots/index.json` would be mis-picked up as a session log
/// and fail to parse.
///
/// The historical single-file layout
/// (`~/.copilot/history-session-state/<sessionId>.json`) is not matched
/// and no longer supported by the analyzer at all.
pub fn is_copilot_session_file(path: &Path) -> bool {
    // Compare raw `OsStr` rather than going through `to_str()` so paths with
    // non-UTF-8 bytes elsewhere in the tree do not silently reject the file.
    // The chosen constants (`events.jsonl`, `session-state`) are pure ASCII,
    // so the comparison is safe on every platform we care about and keeps
    // the style consistent with `is_gemini_session_file`'s `OsStr::new("chats")`
    // check above.
    if path.file_name() != Some(std::ffi::OsStr::new("events.jsonl")) {
        return false;
    }

    // Must sit one level under `session-state/<sessionId>/events.jsonl` —
    // reject anything that just happens to be called `events.jsonl` in a
    // nested subfolder (e.g. `rewind-snapshots/events.jsonl`).
    path.parent()
        .and_then(|p| p.parent())
        .map(|pp| pp.file_name() == Some(std::ffi::OsStr::new("session-state")))
        .unwrap_or(false)
}

/// Filter for Grok CLI session signal files.
///
/// Only `$GROK_HOME/sessions/<workspace>/<session>/signals.json` is a session
/// entry point. Sibling files such as `summary.json` and `updates.jsonl` are
/// consumed by the Grok parser after the signals file has been selected.
pub fn is_grok_session_file(path: &Path) -> bool {
    if path.file_name() != Some(std::ffi::OsStr::new("signals.json")) {
        return false;
    }

    path.parent()
        .and_then(Path::parent)
        .and_then(Path::parent)
        .is_some_and(|sessions| sessions.file_name() == Some(std::ffi::OsStr::new("sessions")))
}

/// Returns true if the path is a Claude Code meta sidecar file.
///
/// Claude Code writes these next to subagent session logs with metadata like
/// `agentType` / `description`. Today they're `*.meta.json`; we also reject
/// `*.meta.jsonl` pre-emptively so the filter stays correct if the format
/// ever switches to line-delimited JSON.
fn is_meta_sidecar_file(path: &Path) -> bool {
    path.file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|name| name.ends_with(".meta.json") || name.ends_with(".meta.jsonl"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{self, File};
    use std::io::Write;
    use tempfile::tempdir;

    #[test]
    fn test_is_codex_session_file_jsonl() {
        // Test JSONL file extension
        let path = std::path::Path::new("test.jsonl");
        assert!(is_codex_session_file(path));
    }

    #[test]
    fn test_is_codex_session_file_json() {
        // Test JSON file extension
        let path = std::path::Path::new("test.json");
        assert!(is_codex_session_file(path));
    }

    #[test]
    fn test_is_codex_session_file_txt() {
        // Test non-JSON file extension
        let path = std::path::Path::new("test.txt");
        assert!(!is_codex_session_file(path));
    }

    #[test]
    fn test_is_codex_session_file_no_extension() {
        // Test file without extension
        let path = std::path::Path::new("test");
        assert!(!is_codex_session_file(path));
    }

    #[test]
    fn test_is_codex_session_file_uppercase() {
        // Test uppercase extension
        let path = std::path::Path::new("test.JSON");
        assert!(!is_codex_session_file(path)); // Case-sensitive
    }

    #[test]
    fn test_is_gemini_session_file_rejects_legacy_json() {
        // Legacy single-object exports (`chats/<session>.json`) are intentionally
        // no longer matched — the analyzer only handles the JSONL event stream.
        let path = std::path::Path::new("/home/user/.gemini/tmp/hash/chats/chat.json");
        assert!(!is_gemini_session_file(path));
    }

    #[test]
    fn test_is_gemini_session_file_accepts_jsonl() {
        // Current Gemini CLI writes each event as a JSONL line under `chats/`.
        let path = std::path::Path::new(
            "/home/user/.gemini/tmp/proj/chats/session-2026-04-23T12-52.jsonl",
        );
        assert!(is_gemini_session_file(path));
    }

    #[test]
    fn test_is_gemini_session_file_accepts_nested_subagent() {
        let path =
            std::path::Path::new("/home/user/.gemini/tmp/proj/chats/parent-session/subagent.jsonl");
        assert!(is_gemini_session_file(path));
    }

    #[test]
    fn test_is_gemini_session_file_rejects_deeper_jsonl() {
        let path = std::path::Path::new(
            "/home/user/.gemini/tmp/proj/chats/parent-session/artifacts/data.jsonl",
        );
        assert!(!is_gemini_session_file(path));
    }

    #[test]
    fn test_is_gemini_session_file_wrong_parent() {
        // Test file not in chats directory
        let path = std::path::Path::new("/home/user/.gemini/tmp/hash/other/file.json");
        assert!(!is_gemini_session_file(path));
    }

    #[test]
    fn test_is_gemini_session_file_wrong_extension() {
        // Test file in chats directory but wrong extension
        let path = std::path::Path::new("/home/user/.gemini/tmp/hash/chats/file.txt");
        assert!(!is_gemini_session_file(path));
    }

    #[test]
    fn test_is_gemini_session_file_no_parent() {
        // Test file without parent
        let path = std::path::Path::new("file.json");
        assert!(!is_gemini_session_file(path));
    }

    #[test]
    fn test_is_gemini_session_file_excludes_sibling_dirs() {
        // `tmp/discordbot/logs.json` lives next to the `chats/` folder but
        // must not be picked up because its parent is not `chats`.
        let sibling = std::path::Path::new("/home/user/.gemini/tmp/discordbot/logs.json");
        assert!(!is_gemini_session_file(sibling));

        // The `bin/rg` binary that Gemini CLI drops alongside session data has no
        // JSON extension at all.
        let binary = std::path::Path::new("/home/user/.gemini/tmp/bin/rg");
        assert!(!is_gemini_session_file(binary));
    }

    #[test]
    fn test_is_copilot_session_file_accepts_events_jsonl() {
        // Current layout: `session-state/<sessionId>/events.jsonl`
        let path = std::path::Path::new(
            "/home/user/.copilot/session-state/d2e098d0-e0d6-4d6b-914b-c4c5543b17e3/events.jsonl",
        );
        assert!(is_copilot_session_file(path));
    }

    #[test]
    fn test_is_copilot_session_file_rejects_snapshots() {
        // Rewind snapshots also emit JSON files; they must not be picked up as
        // session logs.
        let snapshot_index = std::path::Path::new(
            "/home/user/.copilot/session-state/d2e098d0/rewind-snapshots/index.json",
        );
        assert!(!is_copilot_session_file(snapshot_index));

        let snapshot_backup = std::path::Path::new(
            "/home/user/.copilot/session-state/d2e098d0/rewind-snapshots/backups/2ee575c19132c8bd-1776949007337",
        );
        assert!(!is_copilot_session_file(snapshot_backup));

        let workspace =
            std::path::Path::new("/home/user/.copilot/session-state/d2e098d0/workspace.yaml");
        assert!(!is_copilot_session_file(workspace));
    }

    #[test]
    fn test_is_copilot_session_file_rejects_nested_events_jsonl() {
        // A stray `events.jsonl` inside a rewind snapshot must not count as a
        // session log — the parent of the parent must be `session-state`.
        let nested = std::path::Path::new(
            "/home/user/.copilot/session-state/d2e098d0/rewind-snapshots/events.jsonl",
        );
        assert!(!is_copilot_session_file(nested));
    }

    #[test]
    fn test_is_copilot_session_file_rejects_other_files() {
        // Plain JSON / JSONL files outside the `session-state/<uuid>/` layout
        // should never pass.
        let path1 = std::path::Path::new("/tmp/events.jsonl");
        assert!(!is_copilot_session_file(path1));

        let path2 = std::path::Path::new("/home/user/.copilot/logs.json");
        assert!(!is_copilot_session_file(path2));
    }

    #[test]
    fn test_is_grok_session_file_accepts_exact_layout() {
        let path =
            std::path::Path::new("/home/user/.grok/sessions/workspace/session-id/signals.json");
        assert!(is_grok_session_file(path));
    }

    #[test]
    fn test_is_grok_session_file_rejects_siblings_and_nested_files() {
        let summary =
            std::path::Path::new("/home/user/.grok/sessions/workspace/session-id/summary.json");
        let nested = std::path::Path::new(
            "/home/user/.grok/sessions/workspace/session-id/snapshots/signals.json",
        );
        let shallow = std::path::Path::new("/home/user/.grok/sessions/session-id/signals.json");

        assert!(!is_grok_session_file(summary));
        assert!(!is_grok_session_file(nested));
        assert!(!is_grok_session_file(shallow));
    }

    #[test]
    fn test_grok_max_depth_collects_only_signals_entry_point() {
        let dir = tempdir().unwrap();
        let sessions = dir.path().join("sessions");
        let session = sessions.join("workspace").join("session-id");
        let nested = session.join("snapshots");
        fs::create_dir_all(&nested).unwrap();
        File::create(session.join("signals.json")).unwrap();
        File::create(session.join("summary.json")).unwrap();
        File::create(nested.join("signals.json")).unwrap();

        let files = collect_files_with_max_depth(
            &sessions,
            is_grok_session_file,
            TimeRange::All,
            Some(GROK_SESSION_MAX_DEPTH),
        )
        .unwrap();

        assert_eq!(files.len(), 1);
        assert!(files[0].path.ends_with("workspace/session-id/signals.json"));
    }

    #[test]
    fn test_collect_files_with_max_depth_respects_bound() {
        // Layout mirrors a real Copilot `session-state/` tree: `events.jsonl` sits
        // at depth 2 and must be collected, while snapshot artifacts deeper in
        // the tree (`rewind-snapshots/backups/<hash>`) must be skipped entirely
        // by a max_depth(2) walk so they never even hit `is_copilot_session_file`.
        let dir = tempdir().unwrap();
        let session = dir.path().join("session-state").join("sess-abc");
        let backups = session.join("rewind-snapshots").join("backups");
        fs::create_dir_all(&backups).unwrap();

        File::create(session.join("events.jsonl")).unwrap();
        File::create(backups.join("deadbeef-123")).unwrap();
        File::create(backups.join("events.jsonl")).unwrap(); // still valid JSONL
        File::create(session.join("workspace.yaml")).unwrap();

        // Unbounded walk picks up every file whose filter passes...
        let unbounded = collect_files_with_dates(
            dir.path().join("session-state"),
            is_copilot_session_file,
            TimeRange::All,
        )
        .unwrap();
        let unbounded_names: Vec<&str> = unbounded
            .iter()
            .filter_map(|f| f.path.file_name()?.to_str())
            .collect();
        // `rewind-snapshots/backups/events.jsonl` fails the filter (parent-of-parent
        // is `rewind-snapshots`, not `session-state`), so the filter already blocks
        // it. But we must have picked up the real one at depth 2.
        assert!(unbounded_names.contains(&"events.jsonl"));

        // Bounded walk (depth 2) must not even descend into backups/.
        let bounded = collect_files_with_max_depth(
            dir.path().join("session-state"),
            is_copilot_session_file,
            TimeRange::All,
            Some(2),
        )
        .unwrap();
        assert_eq!(bounded.len(), 1);
        assert!(bounded[0].path.ends_with("sess-abc/events.jsonl"));
    }

    #[test]
    fn test_collect_provider_files_deduplicates_only_across_roots() {
        // Mirrors Codex: a dated active root plus the flat archived root the
        // rollout log is moved into, with one session momentarily in both.
        let dir = tempdir().unwrap();
        let active = dir
            .path()
            .join("sessions")
            .join("2026")
            .join("06")
            .join("06");
        let archived = dir.path().join("archived_sessions");
        fs::create_dir_all(&active).unwrap();
        fs::create_dir_all(&archived).unwrap();
        File::create(active.join("rollout-live.jsonl")).unwrap();
        File::create(active.join("rollout-moving.jsonl")).unwrap();
        File::create(archived.join("rollout-moving.jsonl")).unwrap();
        File::create(archived.join("rollout-old.jsonl")).unwrap();

        let roots = [dir.path().join("sessions"), archived.clone()];
        let roots: Vec<&Path> = roots.iter().map(PathBuf::as_path).collect();
        let files =
            collect_provider_files_diagnostics(&roots, is_codex_session_file, TimeRange::All, None)
                .files;

        let mut found: Vec<PathBuf> = files.into_iter().map(|file| file.path).collect();
        found.sort();
        assert_eq!(found.len(), 3, "the moving session must be counted once");
        // The active copy wins, so the archived duplicate is the one dropped.
        assert!(found.contains(&active.join("rollout-moving.jsonl")));
        assert!(!found.contains(&archived.join("rollout-moving.jsonl")));
        assert!(found.contains(&archived.join("rollout-old.jsonl")));
    }

    #[test]
    fn test_collect_provider_files_keeps_same_named_files_in_one_root() {
        // Every Copilot session log is named `events.jsonl`; a single-root
        // provider must never have those collapsed into one.
        let dir = tempdir().unwrap();
        let sessions = dir.path().join("session-state");
        for session in ["sess-a", "sess-b"] {
            let path = sessions.join(session);
            fs::create_dir_all(&path).unwrap();
            File::create(path.join("events.jsonl")).unwrap();
        }

        let roots = [sessions.as_path()];
        let files = collect_provider_files_diagnostics(
            &roots,
            is_copilot_session_file,
            TimeRange::All,
            Some(COPILOT_SESSION_MAX_DEPTH),
        )
        .files;

        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_collect_provider_files_skips_missing_roots() {
        let dir = tempdir().unwrap();
        let archived = dir.path().join("archived_sessions");
        fs::create_dir_all(&archived).unwrap();
        File::create(archived.join("rollout-old.jsonl")).unwrap();

        // A Codex home that has only ever archived: the active root is absent.
        let roots = [dir.path().join("sessions"), archived];
        let roots: Vec<&Path> = roots.iter().map(PathBuf::as_path).collect();
        let discovery =
            collect_provider_files_diagnostics(&roots, is_codex_session_file, TimeRange::All, None);

        assert_eq!(discovery.files.len(), 1);
        assert!(discovery.failures.is_empty());
        assert!(
            collect_provider_files_diagnostics(&[], is_codex_session_file, TimeRange::All, None)
                .files
                .is_empty()
        );
    }

    #[test]
    fn test_collect_files_with_dates_empty_dir() {
        // Test collecting files from empty directory
        let dir = tempdir().unwrap();

        let results =
            collect_files_with_dates(dir.path(), is_codex_session_file, TimeRange::All).unwrap();
        assert_eq!(results.len(), 0);
    }

    #[test]
    fn test_collect_files_with_dates_nonexistent_dir() {
        // Test collecting files from non-existent directory
        let results =
            collect_files_with_dates("/nonexistent/path", is_codex_session_file, TimeRange::All)
                .unwrap();
        assert_eq!(results.len(), 0);
    }

    #[test]
    fn test_collect_files_with_dates_with_files() {
        // Test collecting JSON files from directory
        let dir = tempdir().unwrap();

        // Create some JSON files
        File::create(dir.path().join("file1.json")).unwrap();
        File::create(dir.path().join("file2.jsonl")).unwrap();
        File::create(dir.path().join("file3.txt")).unwrap(); // Should be filtered out

        let results =
            collect_files_with_dates(dir.path(), is_codex_session_file, TimeRange::All).unwrap();
        assert_eq!(results.len(), 2);

        // Check that date fields are set
        for file_info in &results {
            assert!(!file_info.modified_date.is_empty());
            assert!(file_info.modified_date.contains('-')); // Should be YYYY-MM-DD format
        }
    }

    #[test]
    fn test_collect_files_with_dates_nested_directories() {
        // Test collecting files from nested directories
        let dir = tempdir().unwrap();

        // Create nested structure
        fs::create_dir_all(dir.path().join("subdir1")).unwrap();
        fs::create_dir_all(dir.path().join("subdir2")).unwrap();

        File::create(dir.path().join("file1.json")).unwrap();
        File::create(dir.path().join("subdir1/file2.json")).unwrap();
        File::create(dir.path().join("subdir2/file3.jsonl")).unwrap();

        let results =
            collect_files_with_dates(dir.path(), is_codex_session_file, TimeRange::All).unwrap();
        assert_eq!(results.len(), 3);
    }

    #[test]
    fn test_collect_files_with_dates_filter_function() {
        // Test that filter function works correctly
        let dir = tempdir().unwrap();

        File::create(dir.path().join("file1.json")).unwrap();
        File::create(dir.path().join("file2.jsonl")).unwrap();
        File::create(dir.path().join("file3.txt")).unwrap();

        // Custom filter: only .txt files
        let results = collect_files_with_dates(
            dir.path(),
            |p| p.extension().is_some_and(|e| e == "txt"),
            TimeRange::All,
        )
        .unwrap();

        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_collect_files_with_dates_no_matching_files() {
        // Test when no files match filter
        let dir = tempdir().unwrap();

        File::create(dir.path().join("file1.txt")).unwrap();
        File::create(dir.path().join("file2.md")).unwrap();

        let results =
            collect_files_with_dates(dir.path(), is_codex_session_file, TimeRange::All).unwrap();
        assert_eq!(results.len(), 0);
    }

    #[test]
    fn test_file_info_path() {
        // Test that FileInfo contains correct paths
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.json");
        File::create(&file_path).unwrap();

        let results =
            collect_files_with_dates(dir.path(), is_codex_session_file, TimeRange::All).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].path, file_path);
    }

    #[test]
    fn test_file_info_date_format() {
        // Test that date format is YYYY-MM-DD
        let dir = tempdir().unwrap();
        File::create(dir.path().join("test.json")).unwrap();

        let results =
            collect_files_with_dates(dir.path(), is_codex_session_file, TimeRange::All).unwrap();
        assert_eq!(results.len(), 1);

        let date = &results[0].modified_date;
        assert_eq!(date.len(), 10); // YYYY-MM-DD is 10 chars
        assert_eq!(date.chars().filter(|&c| c == '-').count(), 2); // Two dashes
    }

    #[test]
    fn test_collect_files_ignores_directories() {
        // Test that directories are not included in results
        let dir = tempdir().unwrap();

        // Create a directory with .json in name
        fs::create_dir(dir.path().join("test.json")).unwrap();

        // Create an actual file
        File::create(dir.path().join("real.json")).unwrap();

        let results =
            collect_files_with_dates(dir.path(), is_codex_session_file, TimeRange::All).unwrap();
        assert_eq!(results.len(), 1); // Only the file, not the directory
    }

    #[test]
    fn test_is_codex_session_file_with_dots_in_name() {
        // Test files with dots in name
        let path = std::path::Path::new("my.test.file.json");
        assert!(is_codex_session_file(path));

        let path2 = std::path::Path::new("my.test.file.jsonl");
        assert!(is_codex_session_file(path2));
    }

    #[test]
    fn test_is_gemini_session_file_multiple_levels() {
        // Depth of the enclosing directory does not matter as long as the
        // *immediate* parent is `chats/` and the extension is `.jsonl`.
        let path = std::path::Path::new("/a/b/c/d/chats/file.jsonl");
        assert!(is_gemini_session_file(path));
    }

    #[test]
    fn test_collect_files_with_content() {
        // Test that files with content are collected
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.json");

        let mut file = File::create(&file_path).unwrap();
        writeln!(file, r#"{{"key": "value"}}"#).unwrap();

        let results =
            collect_files_with_dates(dir.path(), is_codex_session_file, TimeRange::All).unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].path.exists());
    }

    #[test]
    fn test_is_codex_session_file_excludes_meta_sidecars() {
        // *.meta.json sidecars live next to Claude Code subagent sessions and must not
        // be picked up by the generic json filter (they would otherwise be parsed and
        // mis-detected as Codex logs).
        let path = std::path::Path::new("agent-afda1991051a0eb93.meta.json");
        assert!(!is_codex_session_file(path));

        let nested = std::path::Path::new(
            "/home/user/.claude/projects/proj/sess/subagents/agent-x.meta.json",
        );
        assert!(!is_codex_session_file(nested));

        // Pre-emptive defense: reject `.meta.jsonl` too, in case Claude Code ever
        // switches the sidecar format to line-delimited JSON.
        let meta_jsonl = std::path::Path::new(
            "/home/user/.claude/projects/proj/sess/subagents/agent-x.meta.jsonl",
        );
        assert!(!is_codex_session_file(meta_jsonl));
    }

    #[test]
    fn test_is_claude_session_file_accepts_jsonl() {
        // Top-level Claude session logs
        let top_level = std::path::Path::new("/home/user/.claude/projects/proj/sess.jsonl");
        assert!(is_claude_session_file(top_level));

        // Subagent session logs sit one extra level deeper
        let subagent = std::path::Path::new(
            "/home/user/.claude/projects/proj/sess/subagents/agent-afda1991051a0eb93.jsonl",
        );
        assert!(is_claude_session_file(subagent));
    }

    #[test]
    fn test_is_claude_session_file_rejects_non_jsonl() {
        // Metadata sidecars — current format (`.meta.json`)
        let meta = std::path::Path::new(
            "/home/user/.claude/projects/proj/sess/subagents/agent-afda1991051a0eb93.meta.json",
        );
        assert!(!is_claude_session_file(meta));

        // Metadata sidecars — hypothetical future format (`.meta.jsonl`). Has `.jsonl`
        // extension, so without the sidecar check it would slip through.
        let meta_jsonl = std::path::Path::new(
            "/home/user/.claude/projects/proj/sess/subagents/agent-afda1991051a0eb93.meta.jsonl",
        );
        assert!(!is_claude_session_file(meta_jsonl));

        // Plain .json files (not something Claude Code writes in this tree)
        let plain_json = std::path::Path::new("/home/user/.claude/projects/proj/notes.json");
        assert!(!is_claude_session_file(plain_json));

        // Other pasted artifacts
        let image = std::path::Path::new("/home/user/.claude/projects/proj/sess/paste.png");
        assert!(!is_claude_session_file(image));
    }

    #[test]
    fn test_collect_claude_session_files_includes_subagents() {
        // Simulates the `~/.claude/projects/<project>/<session>/subagents/` layout:
        //   projects/<project>/
        //     sess-a.jsonl                          <- top-level session
        //     sess-a/subagents/agent-one.jsonl      <- subagent session
        //     sess-a/subagents/agent-one.meta.json  <- metadata sidecar (ignored)
        //     sess-a/screenshot.png                 <- pasted artifact (ignored)
        let dir = tempdir().unwrap();
        let project = dir.path().join("-home-user-repo");
        let session_subdir = project.join("sess-a");
        let subagents = session_subdir.join("subagents");
        fs::create_dir_all(&subagents).unwrap();

        File::create(project.join("sess-a.jsonl")).unwrap();
        File::create(subagents.join("agent-one.jsonl")).unwrap();
        File::create(subagents.join("agent-one.meta.json")).unwrap();
        File::create(subagents.join("agent-two.meta.jsonl")).unwrap();
        File::create(session_subdir.join("screenshot.png")).unwrap();

        let results =
            collect_files_with_dates(dir.path(), is_claude_session_file, TimeRange::All).unwrap();
        let names: Vec<String> = results
            .iter()
            .filter_map(|f| f.path.file_name()?.to_str().map(String::from))
            .collect();

        assert_eq!(results.len(), 2, "collected: {:?}", names);
        assert!(names.contains(&"sess-a.jsonl".to_string()));
        assert!(names.contains(&"agent-one.jsonl".to_string()));
        assert!(!names.iter().any(|n| n.contains(".meta.")));
        assert!(!names.iter().any(|n| n.ends_with(".png")));
    }
}