sessionwiki 0.34.4

Find, search, and read every AI coding session you've ever had - across Claude Code, Codex, Gemini CLI, OpenCode, Cline, and more.
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
//! Golden-file tests for the session adapters.
//!
//! These guard the most fragile part of the project: parsing three different
//! JSONL/JSON schemas that drift between tool versions. Each fixture under
//! `tests/fixtures/<tool>/` is a small, realistic session including the edge
//! cases the parsers are supposed to handle (boilerplate dropping, subagent
//! detection, malformed lines, multi-block content, skipped roles).
//!
//! When a tool changes its format, a fixture from the new version plus an
//! assertion here is the cleanest possible bug report and regression test.

use sessionwiki::adapters;
use sessionwiki::model::Session;
use std::path::PathBuf;

fn fixture(rel: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(rel)
}

fn parse(tool: &str, rel: &str) -> Session {
    let adapter = adapters::by_name(tool).expect("adapter exists");
    adapters::parse_session(adapter.as_ref(), &fixture(rel)).expect("parse succeeds")
}

fn roles(s: &Session) -> Vec<&'static str> {
    s.messages.iter().map(|m| m.role.label()).collect()
}

#[test]
fn claude_main_session() {
    let s = parse(
        "claude-code",
        "claude-code/proj-a/0a000000-0000-4000-8000-000000000001.jsonl",
    );

    // Title comes from the summary line, not the first user message.
    assert_eq!(s.title, "Fix CORS preflight failing on /auth routes");
    assert_eq!(s.tool, "claude-code");
    assert_eq!(s.project, "/home/dev/proj-a");
    assert!(!s.subagent);

    // A malformed line and the isMeta:true boilerplate user turn are dropped;
    // the shared pass folds each tool call and result into one Tool message.
    assert_eq!(
        roles(&s),
        [
            "user",
            "assistant",
            "tool",
            "tool",
            "tool",
            "tool",
            "assistant"
        ]
    );
    assert_eq!(s.messages[2].text, "→ Bash(rg -n cors src/) ⇒ ok · 1 line");
    assert_eq!(
        s.messages[3].text,
        "→ Edit(/home/dev/proj-a/src/middleware/mod.rs) ⇒ error · 2 lines — Edit failed"
    );
    assert_eq!(
        s.messages[4].text,
        "→ Edit(/home/dev/proj-a/src/middleware/mod.rs) ⇒ pending"
    );
    assert_eq!(
        s.messages[5].text,
        "→ Write(/home/dev/proj-a/tests/cors_preflight.rs) ⇒ ok · 5 lines"
    );
    assert!(matches!(
        &s.messages[5].tool,
        Some(sessionwiki::model::ToolEvent::Summary(summary))
            if summary.output.as_deref().is_some_and(|output| output.lines().count() == 5)
    ));

    // The dropped boilerplate must not leak into any message.
    assert!(s
        .messages
        .iter()
        .all(|m| !m.text.contains("harness boilerplate")));

    // First user prompt and final assistant message survive intact.
    assert!(s.messages[0].text.contains("Preflight requests"));
    assert!(s.messages.iter().any(|m| m.text.contains("14 tests pass")));

    // Provenance: Edit/Write file_path is extracted, the repeated edit to
    // mod.rs is de-duplicated, and the read-only Bash call contributes nothing.
    assert_eq!(
        s.touched,
        [
            "/home/dev/proj-a/src/middleware/mod.rs",
            "/home/dev/proj-a/tests/cors_preflight.rs"
        ]
    );

    assert_eq!(
        s.started.map(|t| t.to_rfc3339()),
        Some("2026-06-09T14:01:00+00:00".to_string())
    );
}

#[test]
fn claude_subagent_is_flagged() {
    let s = parse(
        "claude-code",
        "claude-code/proj-a/0a000000-0000-4000-8000-000000000001/subagents/agent-deadbeef.jsonl",
    );
    assert!(s.subagent, "files under /subagents/ must be flagged");
    assert_eq!(roles(&s), ["user", "assistant"]);
    assert_eq!(s.title, "Search the codebase for all CORS references.");
}

#[test]
fn claude_ai_title_precedes_first_user_message() {
    let s = parse(
        "claude-code",
        "claude-code/proj-a/0a000000-0000-4000-8000-000000000002.jsonl",
    );

    assert_eq!(s.title, "Repair synthetic schema drift");
    assert_eq!(roles(&s), ["user"]);
}

#[test]
fn codex_session_with_schema_variants() {
    let s = parse(
        "codex",
        "codex/rollout-2026-06-11T13-00-00-019eb9b2-1466-7e93-8b85-5b596295e96b.jsonl",
    );

    assert_eq!(s.tool, "codex");
    assert_eq!(s.project, "/home/dev/api-server");
    assert_eq!(s.title, "Write property-based tests for the rate limiter.");

    // environment_context boilerplate and reasoning are dropped; function
    // calls and their outputs become one compact Tool message each, while both
    // response_item and event_msg message shapes parse.
    assert_eq!(
        roles(&s),
        ["user", "tool", "tool", "assistant", "user", "assistant"]
    );
    assert!(s
        .messages
        .iter()
        .all(|m| !m.text.contains("environment_context")));
    assert_eq!(s.messages[1].text, "→ shell(cargo test) ⇒ pending");
    assert!(s.messages[2]
        .text
        .starts_with("→ shell(apply_patch *** Begin Patch"));
    assert!(s.messages[2].text.ends_with(" ⇒ ok · 1 line"));
    assert!(s
        .messages
        .iter()
        .all(|message| !message.text.contains("10000 cases passed")));
    let Some(sessionwiki::model::ToolEvent::Summary(summary)) = &s.messages[2].tool else {
        panic!("the apply_patch call should retain the anonymous structured result");
    };
    assert_eq!(summary.output.as_deref(), Some("10000 cases passed"));
    assert_eq!(
        sessionwiki::tool_summary::render_output(summary, 8 * 1024, 80).as_deref(),
        Some("```text\n10000 cases passed\n```")
    );
    assert!(s.messages.iter().any(|m| m.text.contains("2.1M ops/sec")));

    // Provenance: apply_patch file headers (Update File / Add File) are pulled
    // from the call arguments even though the patch is double-JSON-escaped.
    assert_eq!(
        s.touched,
        ["src/rate_limiter.rs", "tests/rate_limiter_props.rs"]
    );
}

#[test]
fn codex_deduplicates_user_message_schema_variants() {
    let s = parse(
        "codex",
        "codex/rollout-2026-07-13T07-05-40-duplicate-user.jsonl",
    );

    assert_eq!(roles(&s), ["user"]);
    assert_eq!(s.messages[0].text, "Explain the synthetic parser failure.");
}

#[test]
fn codex_drops_current_agents_instructions_boilerplate() {
    let s = parse(
        "codex",
        "codex/rollout-2026-07-13T16-06-13-agents-instructions.jsonl",
    );

    assert_eq!(s.title, "Fix the synthetic parser.");
    assert_eq!(roles(&s), ["user"]);
    assert!(s
        .messages
        .iter()
        .all(|message| !message.text.starts_with("# AGENTS.md instructions")));
}

#[test]
fn codex_keeps_genuinely_repeated_prompts() {
    // Each prompt arrives in BOTH shapes (event_msg + response_item); the
    // dedup must cancel per PAIR, so a user who sends "continue" twice still
    // indexes two user messages - not one.
    let s = parse(
        "codex",
        "codex/rollout-2026-07-13T08-00-00-repeated-prompt.jsonl",
    );

    assert_eq!(roles(&s), ["user", "assistant", "user"]);
    assert_eq!(s.messages[0].text, "continue");
    assert_eq!(s.messages[2].text, "continue");
}

#[test]
fn codex_parses_legacy_bare_messages() {
    let s = parse(
        "codex",
        "codex/rollout-2025-08-25T00-04-27-bare-message.jsonl",
    );

    assert_eq!(roles(&s), ["user", "assistant"]);
    assert_eq!(s.title, "Parse the legacy synthetic rollout.");
}

#[test]
fn codex_indexes_custom_tool_calls_and_their_patched_paths() {
    let s = parse(
        "codex",
        "codex/rollout-2026-07-13T16-05-05-custom-tool-call.jsonl",
    );

    assert_eq!(roles(&s), ["user", "tool"]);
    assert_eq!(
        s.messages[1].text,
        "→ apply_patch(src/synthetic.rs) ⇒ pending"
    );
    assert_eq!(s.touched, ["src/synthetic.rs"]);
}

#[test]
fn codex_structured_tool_calls_and_results_are_summarized() {
    let s = parse(
        "codex",
        "codex/rollout-2026-10-06T12-00-00-structured-tools.jsonl",
    );

    let tool_lines: Vec<_> = s
        .messages
        .iter()
        .filter(|message| message.role.label() == "tool")
        .map(|message| message.text.as_str())
        .collect();
    assert_eq!(
        tool_lines,
        [
            "→ shell(cargo check) ⇒ ok · 1 line",
            "→ shell(cargo test) ⇒ error · 2 lines — error[E0425]: unresolved synthetic name",
            "→ shell(print-many) ⇒ ok · 10 lines",
            "→ apply_patch(src/codex_synthetic.rs) ⇒ ok · 2 lines",
            "→ shell(printf block output) ⇒ ok · 2 lines",
            "→ shell(older-result) ⇒ ok · 1 line",
            "→ shell(echo pending) ⇒ pending",
            "→ exec_command(git status --short && echo \"done\") ⇒ ok · 2 lines",
            "→ exec_command(pwd; rg -n needle missing.rs) ⇒ error · 3 lines — /home/dev/proj",
        ]
    );
    assert!(tool_lines.iter().all(|line| !line.contains(" {")));
    assert_eq!(s.touched, ["src/codex_synthetic.rs"]);
}

#[test]
fn codex_plain_text_command_results_carry_their_exit_codes() {
    let s = parse(
        "codex",
        "codex/rollout-2026-05-06T12-00-00-text-results.jsonl",
    );

    let tool_lines: Vec<_> = s
        .messages
        .iter()
        .filter(|message| message.role.label() == "tool")
        .map(|message| message.text.as_str())
        .collect();
    assert_eq!(
        tool_lines,
        [
            "→ exec_command(cargo test) ⇒ error · 2 lines — error[E0425]: unresolved synthetic name",
            "→ exec_command(cargo check) ⇒ ok · 1 line",
            "→ exec_command(sleep 30) ⇒ error · 1 line — timed out after 10s",
            "→ exec_command(pwd) ⇒ ok · 1 line",
        ]
    );
}

/// An MCP tool's failure is stated only in the `mcp_tool_call_end` event
/// (`isError`, or an `Err` result); the `function_call_output` beside it is
/// plain text, so the call read as ok.
#[test]
fn codex_mcp_tool_failures_are_marked_as_errors() {
    let s = parse(
        "codex",
        "codex/rollout-2026-05-07T12-00-00-mcp-errors.jsonl",
    );
    let tool_lines: Vec<_> = s
        .messages
        .iter()
        .filter(|message| message.role.label() == "tool")
        .map(|message| message.text.as_str())
        .collect();
    assert_eq!(tool_lines.len(), 3, "{tool_lines:?}");
    assert!(tool_lines[0].contains("⇒ error"), "{}", tool_lines[0]);
    assert!(tool_lines[1].contains("⇒ ok"), "{}", tool_lines[1]);
    assert!(tool_lines[2].contains("⇒ error"), "{}", tool_lines[2]);
}

/// Some Codex rollouts record an MCP call only as its `mcp_tool_call_end`
/// event, with no `function_call` or output beside it. Those calls were not
/// indexed at all. A call that also has a `function_call` is not repeated.
#[test]
fn codex_mcp_calls_recorded_only_as_events_are_indexed() {
    let s = parse(
        "codex",
        "codex/rollout-2026-07-08T12-00-00-mcp-events-only.jsonl",
    );
    let tool_lines: Vec<_> = s
        .messages
        .iter()
        .filter(|message| message.role.label() == "tool")
        .map(|message| message.text.as_str())
        .collect();
    assert_eq!(
        tool_lines,
        [
            "→ navigate(https://example.invalid/a) ⇒ ok · 2 lines",
            "→ navigate(https://example.invalid/b) ⇒ error · 1 line — tool call failed: timeout",
            "→ navigate(https://example.invalid/c) ⇒ ok · 1 line",
        ]
    );
}

#[test]
fn gemini_session() {
    let s = parse(
        "gemini",
        "gemini/myproject/chats/session-2026-06-08T10-00-abcd1234.json",
    );

    assert_eq!(s.tool, "gemini");
    assert_eq!(s.project, "myproject");
    // String content and array-of-blocks content both parse; unknown role
    // ("system") is skipped.
    assert_eq!(roles(&s), ["user", "assistant"]);
    assert!(s.messages[0].text.contains("iframe"));
    assert!(s.messages[1].text.contains("1급 스코프")); // CJK survives intact
    assert_eq!(
        s.ended.map(|t| t.to_rfc3339()),
        Some("2026-06-08T10:00:30+00:00".to_string())
    );
}

#[test]
fn gemini_tool_calls_and_results_are_summarized() {
    let s = parse(
        "gemini",
        "gemini/myproject/chats/session-2026-06-08T11-00-tools.json",
    );

    let tool_lines: Vec<_> = s
        .messages
        .iter()
        .filter(|message| message.role.label() == "tool")
        .map(|message| message.text.as_str())
        .collect();
    assert_eq!(
        tool_lines,
        [
            "→ run_shell_command(cargo test) ⇒ ok · 1 line",
            "→ run_shell_command(cargo test --broken) ⇒ error · 1 line — permission denied",
            "→ read_file(src/lib.rs) ⇒ ok · 12 lines",
            "→ list_files(src) ⇒ ok · 1 line",
        ]
    );
    assert_eq!(
        roles(&s),
        [
            "user",
            "assistant",
            "tool",
            "tool",
            "tool",
            "tool",
            "assistant"
        ]
    );
}

#[test]
fn opencode_multi_file_session() {
    // OpenCode splits a session across session/message/part JSON files; the
    // adapter is handed the session file and joins the rest from the store.
    let s = parse("opencode", "opencode/storage/session/proj1/ses_aaa.json");

    assert_eq!(s.tool, "opencode");
    assert_eq!(s.title, "Add retry to the HTTP client"); // from session.title
    assert_eq!(s.project, "/home/dev/myapp"); // session.directory
    assert!(!s.subagent);

    // reasoning parts are dropped; text parts and tool parts are folded into
    // compact summaries in id order; the malformed part file is skipped; the
    // patch part contributes no message (only provenance).
    assert_eq!(
        roles(&s),
        ["user", "assistant", "tool", "tool", "tool", "tool"]
    );
    assert!(s.messages[0]
        .text
        .contains("retry with exponential backoff"));
    assert!(s
        .messages
        .iter()
        .any(|m| m.text.contains("3-attempt retry")));
    assert!(s
        .messages
        .iter()
        .all(|m| !m.text.contains("thinking about"))); // reasoning dropped
    let tool_lines: Vec<_> = s
        .messages
        .iter()
        .filter(|m| m.text.starts_with("→ "))
        .map(|m| m.text.as_str())
        .collect();
    assert_eq!(
        tool_lines,
        [
            "→ edit(/home/dev/myapp/src/http/client.ts) ⇒ ok · 1 line",
            "→ bash(false) ⇒ error · 2 lines — Command failed: exit 1",
            "→ read(README.md) ⇒ ok · 10 lines",
            "→ read(config.json) ⇒ pending"
        ]
    );

    // Provenance: edit tool's state.input.filePath + the patch's files list.
    assert_eq!(
        s.touched,
        [
            "/home/dev/myapp/src/http/client.ts",
            "/home/dev/myapp/src/util.ts"
        ]
    );

    // epoch-millis timestamp is parsed (not an RFC3339 string).
    assert_eq!(
        s.started,
        chrono::DateTime::from_timestamp_millis(1718630400000)
    );
}

#[test]
fn cline_xml_and_native_tool_edits() {
    // Cline keeps each task as api_conversation_history.json (the Anthropic
    // Messages array) plus ui_messages.json (timestamps + the title).
    let s = parse(
        "cline",
        "cline/tasks/1749477660000/api_conversation_history.json",
    );

    assert_eq!(s.tool, "cline");
    assert_eq!(s.title, "Add a hello function to src/main.py"); // ui_messages say:"task"
    assert_eq!(s.project, "/home/dev/app"); // from <environment_details>
    assert!(!s.subagent);

    // The <task>/<environment_details> wrappers are stripped; legacy XML and
    // native calls/results become compact Tool messages.
    assert_eq!(
        roles(&s),
        [
            "user",
            "assistant",
            "tool",
            "assistant",
            "tool",
            "tool",
            "tool",
            "assistant"
        ]
    );
    assert_eq!(
        s.messages[2].text,
        "→ write_to_file(src/main.py) ⇒ ok · 1 line"
    );
    assert_eq!(
        s.messages[4].text,
        "→ write_to_file(tests/test_main.py) ⇒ ok · 1 line"
    );
    assert_eq!(
        s.messages[5].text,
        "→ execute_command(cargo test) ⇒ error · 2 lines — Error: cargo test failed"
    );
    assert_eq!(
        s.messages[6].text,
        "→ read_file(src/output.txt) ⇒ ok · 10 lines"
    );
    assert_eq!(s.messages[0].text, "Add a hello function to src/main.py");
    assert!(s
        .messages
        .iter()
        .all(|m| !m.text.contains("environment_details")));
    assert!(s.messages.iter().all(|m| !m.text.contains("] Result:")));
    assert!(s
        .messages
        .iter()
        .all(|m| !m.text.contains("successfully saved")));

    // Provenance from BOTH the XML <write_to_file><path> and the native
    // tool_use input.path.
    assert_eq!(s.touched, ["src/main.py", "tests/test_main.py"]);

    assert_eq!(
        s.started,
        chrono::DateTime::from_timestamp_millis(1749477660000)
    );
    assert_eq!(
        s.ended,
        chrono::DateTime::from_timestamp_millis(1749477700000)
    );
}

#[test]
fn gajae_jsonl_session() {
    // gajae-code (and upstream Pi) store one JSONL transcript per session: a
    // header line then message lines, with toolCall/arguments content blocks.
    let s = parse(
        "gajae-code",
        "gajae-code/--home--dev--proj--/2025-12-09T00-53-29-825Z_ffae836b-9420-4060-ac13-7745215f90ff.jsonl",
    );

    assert_eq!(s.tool, "gajae-code");
    assert_eq!(s.title, "refactor the parser"); // header title
    assert_eq!(s.project, "/home/dev/proj"); // header cwd
    assert!(!s.subagent);

    // thinking blocks dropped; tool calls/results fold into compact summaries;
    // the malformed line is skipped without panicking.
    assert_eq!(
        roles(&s),
        [
            "user",
            "assistant",
            "tool",
            "assistant",
            "tool",
            "assistant",
            "tool",
            "assistant",
            "tool",
            "assistant"
        ]
    );
    assert!(s
        .messages
        .iter()
        .all(|m| !m.text.contains("considering the structure")));
    let tool_lines: Vec<_> = s
        .messages
        .iter()
        .filter(|m| m.text.starts_with("→ "))
        .map(|m| m.text.as_str())
        .collect();
    assert_eq!(
        tool_lines,
        [
            "→ write(src/parse.ts) ⇒ ok · 1 line",
            "→ read(config.ts) ⇒ pending",
            "→ ast_edit({\"paths\":[\"src/parse.ts\",\"src/helper.ts\"]}) ⇒ ok · 10 lines",
            "→ edit(src/parse.ts) ⇒ error · 2 lines — Edit failed"
        ]
    );

    // Provenance: write (arguments.path) + ast_edit (arguments.paths[]) with the
    // repeat de-duplicated; read is excluded.
    assert_eq!(s.touched, ["src/parse.ts", "src/helper.ts"]);

    // started = header RFC3339; ended = last entry's RFC3339.
    assert_eq!(
        s.started.map(|t| t.to_rfc3339()),
        Some("2025-12-09T00:53:29.825+00:00".to_string())
    );
    assert_eq!(
        s.ended.map(|t| t.to_rfc3339()),
        Some("2025-12-09T00:53:40+00:00".to_string())
    );
}

#[test]
fn continue_session_with_tool_edit() {
    let s = parse(
        "continue",
        "continue/sessions/5f1d2c9a-8b34-4e21-9d6e-7a0c1b2e3f44.json",
    );

    assert_eq!(s.tool, "continue");
    assert_eq!(s.title, "Add retry to the HTTP client");
    assert_eq!(s.project, "/home/alex/projects/acme-api");
    assert!(!s.subagent);

    assert_eq!(
        roles(&s),
        [
            "user",
            "assistant",
            "tool",
            "assistant",
            "tool",
            "assistant",
            "tool"
        ]
    );
    assert_eq!(
        s.messages[2].text,
        "→ edit_existing_file(src/http.ts) ⇒ ok · 1 line"
    );
    assert_eq!(
        s.messages[4].text,
        "→ run_command(cargo test) ⇒ error · 2 lines — Error: cargo test failed"
    );
    assert_eq!(
        s.messages[6].text,
        "→ read_file(logs/test-output.txt) ⇒ ok · 10 lines"
    );

    // Provenance from toolCallStates[].parsedArgs.filepath.
    assert_eq!(s.touched, ["src/http.ts"]);

    // The session file has no timestamps; started comes from sessions.json's
    // dateCreated (epoch-ms as a string); there is no reliable ended.
    assert_eq!(
        s.started,
        chrono::DateTime::from_timestamp_millis(1718600000000)
    );
    assert_eq!(s.ended, None);
}

#[test]
fn gptme_session() {
    let s = parse(
        "gptme",
        "gptme/fix-cors-bug-20260608-abcd/conversation.jsonl",
    );

    assert_eq!(s.tool, "gptme");
    // Project label is the session directory name (the slug), not a cwd.
    assert_eq!(s.project, "fix-cors-bug-20260608-abcd");

    // Pinned system-prompt line and bare system role are both dropped;
    // the malformed JSON line is silently skipped.
    assert_eq!(roles(&s), ["user", "assistant", "user", "assistant"]);

    // Naive timestamp fallback (no UTC offset) is parsed and assumed UTC.
    assert_eq!(
        s.started,
        chrono::DateTime::parse_from_rfc3339("2026-06-08T10:00:01Z")
            .ok()
            .map(|t| t.with_timezone(&chrono::Utc))
    );

    // Title comes from first user message.
    assert!(s.messages[0].text.contains("CORS preflight"));
}

#[test]
fn gptme_markdown_tool_calls_are_summarized_without_inferred_error_status() {
    let s = parse("gptme", "gptme/tool-summary/conversation.jsonl");

    let tool_lines: Vec<_> = s
        .messages
        .iter()
        .filter(|message| message.role.label() == "tool")
        .map(|message| message.text.as_str())
        .collect();
    assert_eq!(
        tool_lines,
        [
            "→ shell(cargo test) ⇒ ok · 1 line",
            // gptme stores this failure as ordinary system text, without an
            // explicit result status; keep is_error=false instead of guessing.
            "→ shell(cargo test --broken) ⇒ ok · 1 line",
            "→ shell(seq 1 12) ⇒ ok · 12 lines",
        ]
    );
    assert_eq!(roles(&s), ["user", "tool", "tool", "tool", "assistant"]);
}

#[test]
fn gptme_malformed_lines_do_not_panic() {
    // A fixture with a bad line must not panic — it is silently skipped.
    let adapter = adapters::by_name("gptme").unwrap();
    let result = adapter.parse(&fixture(
        "gptme/fix-cors-bug-20260608-abcd/conversation.jsonl",
    ));
    assert!(result.is_ok());
}

#[test]
fn missing_file_errors_without_panicking() {
    let adapter = adapters::by_name("codex").unwrap();
    assert!(adapter
        .parse(&fixture("codex/does-not-exist.jsonl"))
        .is_err());
}

#[test]
fn aider_golden() {
    // aider is a shared store: drive parse_key with `<path>\u{1f}<run-index>`.
    let path = fixture("aider/myrepo/.aider.chat.history.md");
    let adapter = adapters::by_name("aider").unwrap();
    let s = adapters::parse_session_key(
        adapter.as_ref(),
        &format!("{}\u{1f}0", path.to_string_lossy()),
    )
    .unwrap();
    assert_eq!(s.tool, "aider");
    assert_eq!(s.title, "add a retry to the webhook");
    let roles: Vec<&str> = s.messages.iter().map(|m| m.role.label()).collect();
    assert_eq!(roles, vec!["user", "assistant", "tool"]);
    assert_eq!(s.touched, vec!["src/webhook.py", "src/retry.py"]); // dry-run ignored
    assert!(s.started.is_some());
    assert!(s.messages.iter().all(|m| m.ts.is_none()));
    // a bad run index errors, never panics
    assert!(adapter
        .parse_key(&format!("{}\u{1f}99", path.to_string_lossy()))
        .is_err());
}

#[test]
fn every_adapter_is_addressable_by_name() {
    for tool in [
        "claude-code",
        "codex",
        "gemini",
        "opencode",
        "cline",
        "roo-code",
        "kilo-code",
        "gajae-code",
        "continue",
        "gptme",
        "aider",
    ] {
        assert!(adapters::by_name(tool).is_some(), "{tool} should resolve");
    }
    assert!(adapters::by_name("nonexistent").is_none());
}

#[test]
fn gemini_project_is_the_recorded_root_not_the_store_slug() {
    // Gemini CLI names the store dir with a short slug and records the real
    // directory in `.project_root` next to `chats/`.
    let dir = tempfile::tempdir().unwrap();
    let store = dir.path().join("myproject");
    std::fs::create_dir_all(store.join("chats")).unwrap();
    let chat = store.join("chats/session-2026-06-08T10-00-abcd1234.json");
    std::fs::copy(
        fixture("gemini/myproject/chats/session-2026-06-08T10-00-abcd1234.json"),
        &chat,
    )
    .unwrap();
    std::fs::write(store.join(".project_root"), "/work/myproject\n").unwrap();

    let s = adapters::by_name("gemini").unwrap().parse(&chat).unwrap();
    assert_eq!(s.project, "/work/myproject");

    // A row an older version indexed with the slug is corrected on open.
    let data = tempfile::tempdir().unwrap();
    std::env::set_var("SESSIONWIKI_DATA", data.path());
    let conn = sessionwiki::index::open().unwrap();
    conn.execute(
        "INSERT INTO files(path, mtime, size, session_id, tool, project, title, started, msg_count, kind)
         VALUES (?1, 0, 0, 'g-1', 'gemini', 'myproject', 't', '2026-06-08T10:00:00+00:00', 2, 'main')",
        [chat.to_string_lossy()],
    )
    .unwrap();
    conn.execute("DELETE FROM meta WHERE key = 'gemini_project_upto'", [])
        .unwrap();
    drop(conn);
    let conn = sessionwiki::index::open().unwrap();
    let project: String = conn
        .query_row(
            "SELECT project FROM files WHERE session_id = 'g-1'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    std::env::remove_var("SESSIONWIKI_DATA");
    assert_eq!(project, "/work/myproject");
}

#[test]
fn prodex_consult_task_becomes_a_two_message_session() {
    let s = parse(
        "prodex",
        "prodex/repo-a/.bridge/tasks/task_20260707_090000_gpt-pro-consult.json",
    );
    assert_eq!(s.tool, "prodex");
    // sha256("task_20260707_090000_gpt-pro-consult")[..12] - the uniform
    // short-id shape every tool gets in the index.
    assert_eq!(s.id, "567f374d7a70");
    // The question is the title - prodex auto-titles every consult
    // "GPT Pro consult", which would make a list of them indistinguishable.
    assert!(s.title.starts_with("Should the retry loop"), "{}", s.title);
    assert_eq!(roles(&s), ["user", "assistant"]);
    assert!(s.messages[0].text.contains("exponential backoff"), "prompt");
    // The full pro-consult artifact wins over the truncated summary.
    assert!(
        s.messages[1].text.contains("thundering herds"),
        "artifact text used as the answer: {}",
        s.messages[1].text
    );
    assert!(s.started.is_some(), "claimed_at parsed");
    // Project = the repo that owns the .bridge.
    assert!(s.project.ends_with("repo-a"), "{}", s.project);
}

#[test]
fn prodex_pending_task_is_a_one_message_session() {
    let s = parse(
        "prodex",
        "prodex/repo-a/.bridge/tasks/task_20260707_100000_open-question.json",
    );
    assert_eq!(roles(&s), ["user"]);
    assert!(s.started.is_some(), "falls back to the id timestamp");
}

#[test]
fn prodex_thread_url_comes_from_the_bridge_session() {
    let task = fixture("prodex/repo-a/.bridge/tasks/task_20260707_090000_gpt-pro-consult.json");
    let url = sessionwiki::adapters::prodex_thread_url(&task);
    assert_eq!(
        url.as_deref(),
        Some("https://chatgpt.com/c/aaaa1111-2222-3333-4444-555566667777")
    );
    // A non-chatgpt URL in a tampered file is never surfaced.
    let dir = tempfile::tempdir().unwrap();
    let tasks = dir.path().join(".bridge/tasks");
    let sessions = dir.path().join(".bridge/sessions");
    std::fs::create_dir_all(&tasks).unwrap();
    std::fs::create_dir_all(&sessions).unwrap();
    let t = tasks.join("task_x.json");
    std::fs::write(&t, "{}").unwrap();
    std::fs::write(
        sessions.join("s.json"),
        r#"{"thread":"file:///etc/passwd"}"#,
    )
    .unwrap();
    assert_eq!(sessionwiki::adapters::prodex_thread_url(&t), None);
}

// The crash path the durable ledger exists for: the answer artifact was
// written but the result JSON was not. The answer must still be indexed.
#[test]
fn prodex_artifact_without_result_is_still_the_answer() {
    let s = parse(
        "prodex",
        "prodex/repo-a/.bridge/tasks/task_20260707_110000_crash-path.json",
    );
    assert_eq!(roles(&s), ["user", "assistant"]);
    assert!(
        s.messages[1].text.contains("logical shards"),
        "{}",
        s.messages[1].text
    );
}

// AUDIT-HIGH: a crafted/corrupt task id with a multibyte char at a slice
// boundary must not panic (an uncaught parse panic aborts the WHOLE indexer -
// one bad .bridge file would brick every list/search/scan).
#[test]
fn prodex_multibyte_task_id_never_panics() {
    let dir = tempfile::tempdir().unwrap();
    let tasks = dir.path().join(".bridge/tasks");
    std::fs::create_dir_all(&tasks).unwrap();
    let p = tasks.join("bad.json");
    std::fs::write(
        &p,
        r#"{"id":"task_12345é7_123456","title":"t","prompt":"p"}"#,
    )
    .unwrap();
    let adapter = sessionwiki::adapters::by_name("prodex").unwrap();
    let s = adapters::parse_session(adapter.as_ref(), &p).expect("parse must not panic");
    assert!(
        s.started.is_none(),
        "unparseable stamp -> None, not a crash"
    );
}