goosedump 0.6.4

Coding agent context data browser
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
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2026 Jarkko Sakkinen

//! Data-driven integration tests. A single fixture tree stages one store per
//! provider (see [`Fixture`]); each line of `tests/data.txt` then drives one
//! `goosedump` invocation and matches the exit status and captured stdout
//! against the expectations. See `tests/data.txt` for the field syntax.

use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use rusqlite::{Connection, params};

const DATA: &str = include_str!("data.txt");
const CODEX_ID: &str = "019eb466-8e72-7dd0-8a10-9c8963f7d86c";

fn main() {
    let fixture = Fixture::build();
    let mut failed = 0u32;
    let mut ran = 0u32;

    for raw in DATA.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        ran += 1;
        let case = Case::parse(line);
        print!("Test {} ... ", case.name);
        std::io::stdout().flush().expect("flush stdout");
        match case.run(&fixture) {
            Ok(()) => println!("ok"),
            Err(reason) => {
                println!("FAILED");
                eprintln!("  {}: {reason}", case.name);
                failed += 1;
            }
        }
    }

    for (name, result) in roundtrip_cases(&fixture) {
        ran += 1;
        print!("Test {name} ... ");
        std::io::stdout().flush().expect("flush stdout");
        match result {
            Ok(()) => println!("ok"),
            Err(reason) => {
                println!("FAILED");
                eprintln!("  {name}: {reason}");
                failed += 1;
            }
        }
    }

    for (name, result) in delete_cases(&fixture) {
        ran += 1;
        print!("Test {name} ... ");
        std::io::stdout().flush().expect("flush stdout");
        match result {
            Ok(()) => println!("ok"),
            Err(reason) => {
                println!("FAILED");
                eprintln!("  {name}: {reason}");
                failed += 1;
            }
        }
    }

    for (name, result) in import_cases(&fixture) {
        ran += 1;
        print!("Test {name} ... ");
        std::io::stdout().flush().expect("flush stdout");
        match result {
            Ok(()) => println!("ok"),
            Err(reason) => {
                println!("FAILED");
                eprintln!("  {name}: {reason}");
                failed += 1;
            }
        }
    }

    let _ = std::fs::remove_dir_all(&fixture.root);

    eprintln!("\n{ran} tests run.");
    if failed > 0 {
        eprintln!("{failed} test(s) failed.");
        std::process::exit(1);
    }
    eprintln!("All tests passed.");
}

#[derive(Clone, Copy, PartialEq)]
enum Status {
    Zero,
    NonZero,
    Eq(i32),
}

struct Case {
    name: String,
    args: Vec<String>,
    cwd: bool,
    status: Status,
    contains: Vec<String>,
    excludes: Vec<String>,
}

impl Case {
    fn parse(line: &str) -> Self {
        let mut case = Case {
            name: String::new(),
            args: Vec::new(),
            cwd: false,
            status: Status::Zero,
            contains: Vec::new(),
            excludes: Vec::new(),
        };
        for field in line.split(" | ") {
            let (key, value) = field.split_once('=').unwrap_or((field, ""));
            match key {
                "name" => case.name = value.to_owned(),
                "args" => case.args = tokenize(value),
                "cwd" => case.cwd = true,
                "status" => case.status = parse_status(value),
                "out" => case.contains.push(unescape(value)),
                "out!" => case.excludes.push(unescape(value)),
                other => panic!("{}: unknown field `{other}`", case.name),
            }
        }
        case
    }

    fn run(&self, fixture: &Fixture) -> Result<(), String> {
        let mut command = Command::new(&fixture.bin);
        command.args(&self.args);
        for (key, value) in &fixture.env {
            command.env(key, value);
        }
        if self.cwd {
            command.current_dir(&fixture.root);
        }
        command.stdin(Stdio::null());
        command.stdout(Stdio::piped()).stderr(Stdio::piped());

        let output = command
            .output()
            .map_err(|e| format!("spawn goosedump: {e}"))?;
        let code = output.status.code().unwrap_or(-1);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);

        let ok = match self.status {
            Status::Zero => code == 0,
            Status::NonZero => code != 0,
            Status::Eq(expected) => code == expected,
        };
        if !ok {
            return Err(format!("exit {code}; stderr={}", stderr.trim()));
        }

        for needle in &self.contains {
            if !stdout.contains(needle.as_str()) {
                return Err(format!("missing `{needle}`; stdout={}", stdout.trim()));
            }
        }
        for needle in &self.excludes {
            if stdout.contains(needle.as_str()) {
                return Err(format!("unexpected `{needle}`; stdout={}", stdout.trim()));
            }
        }
        Ok(())
    }
}

fn parse_status(value: &str) -> Status {
    match value {
        "0" => Status::Zero,
        "!0" => Status::NonZero,
        other => Status::Eq(other.parse().expect("status must be 0, !0 or an integer")),
    }
}

/// Tokenizes a command line, honoring single and double quotes so a grep
/// pattern that contains spaces survives as a single argument.
fn tokenize(input: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut current: Option<String> = None;
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            ' ' | '\t' => {
                if let Some(token) = current.take() {
                    tokens.push(token);
                }
            }
            '\'' | '"' => {
                let quote = c;
                let buf = current.get_or_insert_with(String::new);
                for inner in chars.by_ref() {
                    if inner == quote {
                        break;
                    }
                    buf.push(inner);
                }
            }
            _ => current.get_or_insert_with(String::new).push(c),
        }
    }
    if let Some(token) = current {
        tokens.push(token);
    }
    tokens
}

fn unescape(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some('\\') => out.push('\\'),
            Some(other) => {
                out.push('\\');
                out.push(other);
            }
            None => out.push('\\'),
        }
    }
    out
}

/// Capture stdout of a goosedump invocation against the shared fixture.
fn capture(fixture: &Fixture, args: &[&str]) -> String {
    let mut command = Command::new(&fixture.bin);
    command.args(args);
    for (key, value) in &fixture.env {
        command.env(key, value);
    }
    command.stdin(Stdio::null());
    command.stdout(Stdio::piped()).stderr(Stdio::piped());
    let output = command.output().expect("spawn goosedump");
    String::from_utf8_lossy(&output.stdout).into_owned()
}

/// Round-trip checks: render a context into its own native format, stage that
/// output as a fresh session, read it back, and re-render. The two renders must
/// be identical once the session id differs, which proves the native output
/// re-parses to the same IR (entry uuids, tool-call correlation ids, content).
fn roundtrip_cases(fixture: &Fixture) -> Vec<(String, Result<(), String>)> {
    vec![
        (
            "roundtrip: claude".to_string(),
            roundtrip(
                fixture,
                "claude",
                "sesh-claude",
                "rt-claude",
                &fixture
                    .root
                    .join("claude-home/projects/project-claude/rt-claude.jsonl"),
            ),
        ),
        (
            "roundtrip: pi".to_string(),
            roundtrip(
                fixture,
                "pi",
                "sesh-pi",
                "rt-pi",
                &fixture.root.join("pi-sessions/rt-pi.jsonl"),
            ),
        ),
    ]
}

fn roundtrip(
    fixture: &Fixture,
    provider: &str,
    orig_id: &str,
    rt_id: &str,
    rt_path: &Path,
) -> Result<(), String> {
    let original = capture(
        fixture,
        &[
            "show",
            &format!("{provider}:{orig_id}"),
            "--output-format",
            provider,
        ],
    );
    if original.trim().is_empty() {
        return Err("original render was empty".to_string());
    }

    if let Some(parent) = rt_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    std::fs::write(rt_path, &original).map_err(|e| e.to_string())?;

    let reparsed = capture(
        fixture,
        &[
            "show",
            &format!("{provider}:{rt_id}"),
            "--output-format",
            provider,
        ],
    );

    // The session id is the only field that legitimately changes (it is the
    // file stem); normalise it before comparing.
    let first = original.replace(orig_id, "RTID");
    let second = reparsed.replace(rt_id, "RTID");
    if first == second {
        Ok(())
    } else {
        Err(format!(
            "re-render differs after round-trip:\n--- first ---\n{first}\n--- second ---\n{second}"
        ))
    }
}

/// Real deletion checks. Each stages an isolated throwaway context, deletes it,
/// and asserts it is gone while a sibling survives — so the canonical fixture
/// data the other cases rely on is never disturbed. Covers a file-based
/// provider (pi) and a DB-based provider (opencode).
fn delete_cases(fixture: &Fixture) -> Vec<(String, Result<(), String>)> {
    vec![
        ("delete: pi file-based".to_string(), delete_pi_case(fixture)),
        (
            "delete: opencode db-based".to_string(),
            delete_opencode_case(fixture),
        ),
    ]
}

fn delete_pi_case(fixture: &Fixture) -> Result<(), String> {
    let path = fixture.root.join("pi-sessions").join("del-pi.jsonl");
    write_lines(
        &path,
        &[
            r#"{"type":"session","id":"del-pi","cwd":"/tmp/project"}"#,
            r#"{"type":"message","id":"del-1","parentId":"","message":{"role":"user","content":[{"type":"text","text":"throwaway"}]}}"#,
        ],
    );

    let before = capture(fixture, &["list", "pi:*"]);
    if !before.contains("pi:del-pi") {
        return Err(format!("staged context not listed; list={}", before.trim()));
    }

    let out = capture(fixture, &["delete", "pi:del-pi"]);
    if !out.contains("pi:del-pi") {
        return Err(format!(
            "delete did not report the tag; stdout={}",
            out.trim()
        ));
    }
    if path.exists() {
        return Err("session file still present after delete".to_string());
    }

    let after = capture(fixture, &["list", "pi:*"]);
    if after.contains("pi:del-pi") {
        return Err(format!(
            "context still listed after delete; list={}",
            after.trim()
        ));
    }
    if !after.contains("pi:sesh-pi") {
        return Err(format!("sibling context removed; list={}", after.trim()));
    }
    Ok(())
}

fn delete_opencode_case(fixture: &Fixture) -> Result<(), String> {
    let db = fixture.root.join("opencode").join("opencode.db");
    {
        let conn = Connection::open(&db).map_err(|e| e.to_string())?;
        conn.execute(
            "INSERT INTO message VALUES(?1, ?2, ?3, ?4)",
            params![
                "sesh-del",
                "msg-del",
                r#"{"role":"user","id":"entry-del","parentID":""}"#,
                9000_i64
            ],
        )
        .map_err(|e| e.to_string())?;
        conn.execute(
            "INSERT INTO part VALUES(?1, ?2, ?3, ?4)",
            params![
                "sesh-del",
                "msg-del",
                r#"{"type":"text","text":"throwaway"}"#,
                9000_i64
            ],
        )
        .map_err(|e| e.to_string())?;
    }

    let before = capture(fixture, &["list", "opencode:*"]);
    if !before.contains("opencode:sesh-del") {
        return Err(format!("staged context not listed; list={}", before.trim()));
    }

    let out = capture(fixture, &["delete", "opencode:sesh-del"]);
    if !out.contains("opencode:sesh-del") {
        return Err(format!(
            "delete did not report the tag; stdout={}",
            out.trim()
        ));
    }

    let after = capture(fixture, &["list", "opencode:*"]);
    if after.contains("opencode:sesh-del") {
        return Err(format!(
            "context still listed after delete; list={}",
            after.trim()
        ));
    }
    if !after.contains("opencode:sesh-alpha") || !after.contains("opencode:sesh-bravo") {
        return Err(format!("sibling context removed; list={}", after.trim()));
    }

    let conn = Connection::open(&db).map_err(|e| e.to_string())?;
    let remaining: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM part WHERE session_id = ?1",
            params!["sesh-del"],
            |row| row.get::<_, i64>(0),
        )
        .map_err(|e| e.to_string())?;
    if remaining != 0 {
        return Err(format!("{remaining} orphan part rows remain"));
    }
    Ok(())
}

/// Import checks. Each stages an isolated source session and imports it into a
/// different provider, asserting the converted content lands, that a re-import
/// is a silent no-op, that same-provider matches are skipped, and that
/// `--dry-run` persists nothing. Mutations run last (after delete_cases) so the
/// canonical fixture data the other cases rely on is never disturbed.
fn import_cases(fixture: &Fixture) -> Vec<(String, Result<(), String>)> {
    vec![
        (
            "import: file to db lands and dedupes".to_string(),
            import_pi_to_goose_case(fixture),
        ),
        (
            "import: db to file".to_string(),
            import_goose_to_pi_case(fixture),
        ),
        (
            "import: same provider skipped".to_string(),
            import_same_provider_case(fixture),
        ),
        (
            "import: dry-run does not persist".to_string(),
            import_dry_run_case(fixture),
        ),
    ]
}

/// The session ids a provider exposes, parsed from a `list <glob>` capture.
fn provider_ids(
    fixture: &Fixture,
    glob: &str,
    provider: &str,
) -> std::collections::HashSet<String> {
    let prefix = format!("{provider}:");
    capture(fixture, &["list", glob])
        .lines()
        .filter_map(|line| line.strip_prefix(&prefix).map(str::to_string))
        .collect()
}

fn stage_pi_source(fixture: &Fixture, id: &str, marker: &str) {
    write_lines(
        &fixture.root.join("pi-sessions").join(format!("{id}.jsonl")),
        &[
            &format!(r#"{{"type":"session","id":"{id}","cwd":"/tmp/project"}}"#),
            &format!(
                r#"{{"type":"message","id":"{id}-1","parentId":"","message":{{"role":"user","content":[{{"type":"text","text":"{marker}"}}]}}}}"#
            ),
        ],
    );
}

fn import_pi_to_goose_case(fixture: &Fixture) -> Result<(), String> {
    stage_pi_source(fixture, "imp-alpha", "IMPORT-MARKER-ALPHA");

    let before = provider_ids(fixture, "goose:*", "goose");
    let out = capture(fixture, &["import", "goose", "pi:imp-alpha"]);
    if !out.contains("pi:imp-alpha") {
        return Err(format!(
            "import did not report the source tag; stdout={}",
            out.trim()
        ));
    }

    let after = provider_ids(fixture, "goose:*", "goose");
    let new_ids: Vec<&String> = after.difference(&before).collect();
    if new_ids.len() != 1 {
        return Err(format!(
            "expected exactly one new goose session, got {}",
            new_ids.len()
        ));
    }
    let shown = capture(fixture, &["show", &format!("goose:{}", new_ids[0])]);
    if !shown.contains("IMPORT-MARKER-ALPHA") {
        return Err(format!(
            "imported goose session missing content; show={}",
            shown.trim()
        ));
    }

    // Re-importing the same source must be a silent no-op (content dedup).
    let again = capture(fixture, &["import", "goose", "pi:imp-alpha"]);
    if again.contains("pi:imp-alpha") {
        return Err(format!(
            "re-import was not skipped; stdout={}",
            again.trim()
        ));
    }
    if provider_ids(fixture, "goose:*", "goose").len() != after.len() {
        return Err("re-import created a duplicate goose session".to_string());
    }
    Ok(())
}

fn import_goose_to_pi_case(fixture: &Fixture) -> Result<(), String> {
    let before = provider_ids(fixture, "pi:*", "pi");
    let out = capture(fixture, &["import", "pi", "goose:sesh-goose"]);
    if !out.contains("goose:sesh-goose") {
        return Err(format!(
            "import did not report the source tag; stdout={}",
            out.trim()
        ));
    }

    let after = provider_ids(fixture, "pi:*", "pi");
    let new_ids: Vec<&String> = after.difference(&before).collect();
    if new_ids.len() != 1 {
        return Err(format!(
            "expected one new pi session, got {}",
            new_ids.len()
        ));
    }
    let shown = capture(fixture, &["show", &format!("pi:{}", new_ids[0])]);
    if !shown.contains("YANKEE-ECHO") {
        return Err(format!(
            "imported pi session missing content; show={}",
            shown.trim()
        ));
    }
    Ok(())
}

fn import_same_provider_case(fixture: &Fixture) -> Result<(), String> {
    let before = provider_ids(fixture, "goose:*", "goose");
    let out = capture(fixture, &["import", "goose", "goose:*"]);
    if !out.trim().is_empty() {
        return Err(format!(
            "same-provider import printed output; stdout={}",
            out.trim()
        ));
    }
    if provider_ids(fixture, "goose:*", "goose").len() != before.len() {
        return Err("same-provider import changed goose sessions".to_string());
    }
    Ok(())
}

fn import_dry_run_case(fixture: &Fixture) -> Result<(), String> {
    stage_pi_source(fixture, "imp-dry", "IMPORT-MARKER-DRY");

    let before = provider_ids(fixture, "goose:*", "goose");
    let dry = capture(fixture, &["import", "goose", "pi:imp-dry", "--dry-run"]);
    if !dry.contains("pi:imp-dry") {
        return Err(format!(
            "dry-run did not list the match; stdout={}",
            dry.trim()
        ));
    }
    if provider_ids(fixture, "goose:*", "goose").len() != before.len() {
        return Err("dry-run created a goose session".to_string());
    }

    // A real import afterwards still proceeds — dry-run left nothing behind.
    let real = capture(fixture, &["import", "goose", "pi:imp-dry"]);
    if !real.contains("pi:imp-dry") {
        return Err(format!(
            "real import after dry-run was skipped; stdout={}",
            real.trim()
        ));
    }
    Ok(())
}

/// The staged store tree shared by every case, plus the environment overrides
/// that point each provider's resolver at it.
struct Fixture {
    bin: PathBuf,
    root: PathBuf,
    env: Vec<(String, String)>,
}

impl Fixture {
    fn build() -> Self {
        let root = std::env::temp_dir().join(format!("goosedump-data-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).expect("create fixture root");

        build_opencode(&root);
        build_crush(&root);
        build_pi(&root);
        build_codex(&root);
        build_goose(&root);
        build_claude(&root);
        build_gemini(&root);

        let env = vec![
            ("GOOSEDUMP_DATA_DIR".to_owned(), path(&root)),
            (
                "PI_CODING_AGENT_SESSION_DIR".to_owned(),
                path(&root.join("pi-sessions")),
            ),
            ("CODEX_HOME".to_owned(), path(&root.join("codex-home"))),
            (
                "CLAUDE_CONFIG_DIR".to_owned(),
                path(&root.join("claude-home")),
            ),
            ("GEMINI_DIR".to_owned(), path(&root.join("gemini-home"))),
            ("XDG_CACHE_HOME".to_owned(), path(&root.join("cache"))),
        ];

        Fixture {
            bin: PathBuf::from(env!("CARGO_BIN_EXE_goosedump")),
            root,
            env,
        }
    }
}

fn path(p: &Path) -> String {
    p.to_string_lossy().into_owned()
}

fn write_lines(path: &Path, lines: &[&str]) {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).expect("create parent");
    }
    let mut body = lines.join("\n");
    body.push('\n');
    std::fs::write(path, body).expect("write file");
}

fn build_opencode(root: &Path) {
    let dir = root.join("opencode");
    std::fs::create_dir_all(&dir).expect("create opencode dir");
    let conn = Connection::open(dir.join("opencode.db")).expect("open opencode.db");
    conn.execute_batch(
        "CREATE TABLE message(session_id TEXT, id TEXT, data TEXT, time_created INTEGER);
         CREATE TABLE part(session_id TEXT, message_id TEXT, data TEXT, time_created INTEGER);",
    )
    .expect("opencode schema");

    let messages: &[(&str, &str, &str, i64)] = &[
        (
            "sesh-alpha",
            "msg-a",
            r#"{"role":"user","id":"entry-alpha","parentID":""}"#,
            1000,
        ),
        (
            "sesh-alpha",
            "msg-b",
            r#"{"role":"assistant","id":"entry-bravo","parentID":"entry-alpha"}"#,
            2000,
        ),
        (
            "sesh-bravo",
            "msg-c",
            r#"{"role":"user","id":"entry-charlie","parentID":""}"#,
            3000,
        ),
    ];
    for (sid, id, data, time) in messages {
        conn.execute(
            "INSERT INTO message VALUES(?1, ?2, ?3, ?4)",
            params![sid, id, data, time],
        )
        .expect("insert message");
    }

    let parts: &[(&str, &str, &str, i64)] = &[
        (
            "sesh-alpha",
            "msg-a",
            r#"{"type":"text","text":"search keyword STARTREK-DISCO"}"#,
            1000,
        ),
        (
            "sesh-alpha",
            "msg-b",
            r#"{"type":"reasoning","text":"need to read a file"}"#,
            2000,
        ),
        (
            "sesh-alpha",
            "msg-b",
            r#"{"type":"text","text":"found STARTREK-DISCO in source"}"#,
            2001,
        ),
        (
            "sesh-alpha",
            "msg-b",
            r#"{"type":"tool","name":"read","arguments":{"filePath":"src/main.rs","description":"read tool"}}"#,
            2002,
        ),
        (
            "sesh-bravo",
            "msg-c",
            r#"{"type":"text","text":"query about TANGO-SIERRA"}"#,
            3000,
        ),
    ];
    for (sid, mid, data, time) in parts {
        conn.execute(
            "INSERT INTO part VALUES(?1, ?2, ?3, ?4)",
            params![sid, mid, data, time],
        )
        .expect("insert part");
    }
}

fn build_crush(root: &Path) {
    let conn = Connection::open(root.join("crush.db")).expect("open crush.db");
    conn.execute_batch(
        "CREATE TABLE messages(session_id TEXT, role TEXT, parts TEXT, created_at TEXT);",
    )
    .expect("crush schema");

    let rows: &[(&str, &str, &str, &str)] = &[
        (
            "sesh-crush",
            "user",
            r#"[{"type":"text","text":"explain ZULU-NOVEMBER"}]"#,
            "2026-01-01T00:00:00Z",
        ),
        (
            "sesh-crush",
            "assistant",
            r#"[{"type":"text","text":"ZULU-NOVEMBER is a code pattern"},{"type":"tool_use","name":"grep","input":{"pattern":"ZULU","filePath":"lib.rs"},"result":"lib.rs:9: ZULU-NOVEMBER"}]"#,
            "2026-01-01T00:00:01Z",
        ),
    ];
    for (sid, role, parts, created) in rows {
        conn.execute(
            "INSERT INTO messages VALUES(?1, ?2, ?3, ?4)",
            params![sid, role, parts, created],
        )
        .expect("insert crush message");
    }

    std::fs::write(root.join(".crush.json"), r#"{"data_directory":"."}"#)
        .expect("write .crush.json");
}

fn build_pi(root: &Path) {
    let dir = root.join("pi-sessions");
    std::fs::create_dir_all(&dir).expect("create pi dir");

    write_lines(
        &dir.join("sesh-pi.jsonl"),
        &[
            r#"{"type":"session","id":"sesh-pi","cwd":"/tmp/project"}"#,
            r#"{"type":"message","id":"pi-entry-1","parentId":"","message":{"role":"user","content":[{"type":"text","text":"find TRIPLA-ESPRESSO"}]}}"#,
            r#"{"type":"message","id":"pi-entry-2","parentId":"pi-entry-1","message":{"role":"assistant","content":[{"type":"thinking","text":"searching for TRIPLA-ESPRESSO"},{"type":"text","text":"found TRIPLA-ESPRESSO in file"},{"type":"toolCall","name":"bash","arguments":{"command":"grep TRIPLA src/*.rs"}},{"type":"toolCall","name":"todo","arguments":{"action":"update"}}]}}"#,
            r#"{"type":"message","id":"pi-entry-3","parentId":"pi-entry-2","message":{"role":"bashExecution","command":"grep TRIPLA src/*.rs","content":[{"type":"text","text":"src/main.rs:123: TRIPLA-ESPRESSO\ntest result: ok. 1 passed"}]}}"#,
            r#"{"type":"message","id":"pi-entry-4","parentId":"pi-entry-3","message":{"role":"toolResult","toolName":"todo","content":"Created #99: Review compact parity (pending)\nUpdated #99 (pending -> in_progress)\n1:928|// SPDX-License-Identifier\n.git/\nnode_modules/"}}"#,
            r#"{"type":"message","id":"pi-entry-5","parentId":"pi-entry-4","message":{"role":"assistant","content":[{"type":"text","text":"The earlier error is fixed; tests are passing."}]}}"#,
        ],
    );

    write_lines(
        &dir.join("sesh-pi-merge.jsonl"),
        &[
            r#"{"type":"session","id":"sesh-pi-merge","cwd":"/tmp/project"}"#,
            r#"{"type":"message","id":"pi-merge-1","parentId":"","message":{"role":"assistant","content":[{"type":"text","text":"[Session Goal]\n- Preserve durable context (#prior-goal)\n\n---\n\n[User Preferences]\n- Always run clippy (#prior-pref)\n\n---\n\n[assistant]\nold transcript line"}]}}"#,
        ],
    );

    let mut long: Vec<String> = Vec::new();
    long.push(r#"{"type":"session","id":"sesh-pi-long","cwd":"/tmp/project"}"#.to_owned());
    long.push(long_msg(
        1,
        "",
        "user",
        "establish the espresso machine baseline",
    ));
    long.push(long_msg(
        2,
        "long-1",
        "assistant",
        "OPENING-ASSISTANT-MARKER reviewing the initial layout",
    ));
    for n in 3..=142 {
        long.push(long_msg(
            n,
            &format!("long-{}", n - 1),
            "assistant",
            &format!("step {n} inspecting module {n}"),
        ));
    }
    long.push(long_msg(
        143,
        "long-142",
        "assistant",
        "TAIL-RECENT-MARKER final verification of the pipeline",
    ));
    let long_refs: Vec<&str> = long.iter().map(String::as_str).collect();
    write_lines(&dir.join("sesh-pi-long.jsonl"), &long_refs);
}

fn long_msg(idx: u32, parent: &str, role: &str, text: &str) -> String {
    format!(
        r#"{{"type":"message","id":"long-{idx}","parentId":"{parent}","message":{{"role":"{role}","content":[{{"type":"text","text":"{text}"}}]}}}}"#
    )
}

fn build_codex(root: &Path) {
    let file = root
        .join("codex-home")
        .join("sessions")
        .join("2026")
        .join("06")
        .join("11")
        .join(format!("rollout-2026-06-11T04-58-00-{CODEX_ID}.jsonl"));
    let meta = format!(
        r#"{{"timestamp":"2026-06-11T01:58:35.740Z","type":"session_meta","payload":{{"id":"{CODEX_ID}","timestamp":"2026-06-11T01:58:00.570Z","cwd":"/tmp/project","originator":"codex-tui"}}}}"#
    );
    write_lines(
        &file,
        &[
            &meta,
            r#"{"timestamp":"2026-06-11T01:58:35.777Z","type":"response_item","payload":{"type":"message","id":"codex-user-1","role":"user","content":[{"type":"input_text","text":"find DEADBEEF"}]}}"#,
            r#"{"timestamp":"2026-06-11T01:58:36.000Z","type":"response_item","payload":{"type":"message","id":"codex-assistant-1","role":"assistant","content":[{"type":"output_text","text":"I found DEADBEEF in source"}]}}"#,
            r#"{"timestamp":"2026-06-11T01:58:36.250Z","type":"response_item","payload":{"type":"function_call","call_id":"call-codex-grep","name":"grep","arguments":"{\"pattern\":\"DEADBEEF\",\"path\":\"src/main.rs\"}"}}"#,
            r#"{"timestamp":"2026-06-11T01:58:36.300Z","type":"response_item","payload":{"type":"reasoning","id":"codex-reasoning-1","summary":[{"type":"summary_text","text":"consider DEADBEEF search plan"}]}}"#,
            r#"{"timestamp":"2026-06-11T01:58:36.350Z","type":"response_item","payload":{"type":"custom_tool_call","call_id":"call-codex-custom","name":"lookup","input":{"query":"DEADBEEF custom"}}}"#,
            r#"{"timestamp":"2026-06-11T01:58:36.400Z","type":"response_item","payload":{"type":"local_shell_call","call_id":"call-codex-shell","action":{"command":"grep DEADBEEF src/main.rs"}}}"#,
            r#"{"timestamp":"2026-06-11T01:58:36.500Z","type":"response_item","payload":{"type":"function_call_output","call_id":"call-codex-grep","output":"src/main.rs:7: DEADBEEF"}}"#,
        ],
    );
}

fn build_goose(root: &Path) {
    let dir = root.join("goose").join("sessions");
    std::fs::create_dir_all(&dir).expect("create goose dir");
    let conn = Connection::open(dir.join("sessions.db")).expect("open sessions.db");
    conn.execute_batch(
        "CREATE TABLE sessions(id TEXT PRIMARY KEY, name TEXT, working_dir TEXT, updated_at TIMESTAMP);
         CREATE TABLE messages(id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT, session_id TEXT, role TEXT, content_json TEXT, created_timestamp INTEGER);",
    )
    .expect("goose schema");

    conn.execute(
        "INSERT INTO sessions VALUES(?1, ?2, ?3, ?4)",
        params![
            "sesh-goose",
            "Review Session",
            "/tmp/project",
            "2026-06-10T00:00:00Z"
        ],
    )
    .expect("insert goose session");

    let rows: &[(i64, &str, &str, &str, i64)] = &[
        (
            1,
            "msg-1",
            "user",
            r#"[{"type":"text","text":"find YANKEE-ECHO"}]"#,
            1000,
        ),
        (
            2,
            "msg-2",
            "assistant",
            r#"[{"type":"thinking","thinking":"searching for YANKEE-ECHO","signature":""},{"type":"text","text":"let me search for that"}]"#,
            2000,
        ),
        (
            3,
            "msg-3",
            "assistant",
            r#"[{"type":"toolRequest","id":"call_00","toolCall":{"status":"success","value":{"name":"grep","arguments":{"pattern":"YANKEE"}}}}]"#,
            3000,
        ),
        (
            4,
            "msg-4",
            "user",
            r#"[{"type":"toolResponse","id":"call_00","toolResult":{"status":"success","value":{"name":"grep","content":[{"type":"text","text":"src/main.rs:42: YANKEE-ECHO"}]}}}]"#,
            4000,
        ),
    ];
    for (id, mid, role, content, time) in rows {
        conn.execute(
            "INSERT INTO messages VALUES(?1, ?2, ?3, ?4, ?5, ?6)",
            params![id, mid, "sesh-goose", role, content, time],
        )
        .expect("insert goose message");
    }
}

fn build_claude(root: &Path) {
    let file = root
        .join("claude-home")
        .join("projects")
        .join("project-claude")
        .join("sesh-claude.jsonl");
    write_lines(
        &file,
        &[
            r#"{"type":"mode","mode":"normal","sessionId":"sesh-claude"}"#,
            r#"{"type":"user","uuid":"claude-user-1","parentUuid":null,"sessionId":"sesh-claude","cwd":"/tmp/project","gitBranch":"main","timestamp":"2026-06-11T01:58:35.777Z","message":{"role":"user","content":"find SLOP-STARS"}}"#,
            r#"{"type":"assistant","uuid":"claude-asst-1","parentUuid":"claude-user-1","sessionId":"sesh-claude","cwd":"/tmp/project","timestamp":"2026-06-11T01:58:36.000Z","message":{"role":"assistant","model":"claude-opus-4-8","content":[{"type":"thinking","thinking":"looking for SLOP-STARS","signature":"sig"},{"type":"text","text":"I found SLOP-STARS in source"},{"type":"tool_use","id":"toolu_grep","name":"Bash","input":{"command":"grep SLOP src/*.rs"}}]}}"#,
            r#"{"type":"user","uuid":"claude-tool-1","parentUuid":"claude-asst-1","sessionId":"sesh-claude","cwd":"/tmp/project","timestamp":"2026-06-11T01:58:36.100Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_grep","content":[{"type":"text","text":"src/main.rs:7: SLOP-STARS"}]}]}}"#,
            r#"{"type":"assistant","uuid":"claude-asst-2","parentUuid":"claude-tool-1","sessionId":"sesh-claude","cwd":"/tmp/project","timestamp":"2026-06-11T01:58:36.200Z","message":{"role":"assistant","model":"claude-opus-4-8","content":[{"type":"tool_use","id":"toolu_read","name":"Read","input":{"file_path":"/nope"}}]}}"#,
            r#"{"type":"user","uuid":"claude-tool-2","parentUuid":"claude-asst-2","sessionId":"sesh-claude","cwd":"/tmp/project","timestamp":"2026-06-11T01:58:36.300Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_read","content":"file not found","is_error":true}]}}"#,
        ],
    );
}

fn build_gemini(root: &Path) {
    let file = root
        .join("gemini-home")
        .join("tmp")
        .join("project-gemini")
        .join("chats")
        .join("session-gemini-1.json");
    if let Some(parent) = file.parent() {
        std::fs::create_dir_all(parent).expect("create gemini dir");
    }
    std::fs::write(
        &file,
        r#"{"sessionId":"11111111-1111-1111-1111-111111111111","projectHash":"project-gemini","startTime":"2026-06-11T02:00:00.000Z","lastUpdated":"2026-06-11T02:01:00.000Z","messages":[{"id":"gem-user-1","timestamp":"2026-06-11T02:00:00.000Z","type":"user","content":"find SLOP-STARS"},{"id":"gem-asst-1","timestamp":"2026-06-11T02:00:01.000Z","type":"gemini","model":"gemini-2.5-pro","thoughts":[{"subject":"Searching","description":"looking for SLOP-STARS","timestamp":"2026-06-11T02:00:01.000Z"}],"content":"I found SLOP-STARS in source","toolCalls":[{"id":"tc-grep","name":"grep_search","args":{"pattern":"SLOP"},"status":"success","timestamp":"2026-06-11T02:00:01.500Z","result":[{"functionResponse":{"id":"tc-grep","name":"grep_search","response":{"output":"src/main.rs:7: SLOP-STARS"}}}]},{"id":"tc-read","name":"read_file","args":{"path":"/nope"},"status":"error","timestamp":"2026-06-11T02:00:01.700Z","result":[{"functionResponse":{"id":"tc-read","name":"read_file","response":{"error":"file not found"}}}]}]}]}"#,
    )
    .expect("write gemini file");
}