supercode-core 0.1.0

A lightweight, fully-customizable AI coding agent SDK in Rust. Talks to any model via OpenRouter or any OpenAI-compatible endpoint.
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
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
//! Fidelity tests driven by ROADMAP.md items — each proves that content the
//! loader previously dropped is now preserved, ideally against the real corpus.

use std::path::PathBuf;

use supercode::session::Session;
use supercode::Role;

// ---- P0: toolUseResult + multimodal tool results --------------------------

#[test]
fn claude_tool_results_preserve_nontext_and_recover_from_tooluseresult() {
    // An image-only tool_result must not become a blank tool message.
    let image_only = r#"
{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Screenshot","input":{}}]},"sessionId":"s"}
{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":[{"type":"image","source":{"type":"base64","data":"x"}}]}]},"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(image_only).unwrap();
    let tool = s.messages.iter().find(|m| m.role == Role::Tool).unwrap();
    assert_eq!(
        tool.content.as_deref(),
        Some("[image]"),
        "image-only result"
    );

    // A tool_reference block is preserved with its tool name.
    let ref_only = r#"
{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t2","name":"X","input":{}}]},"sessionId":"s"}
{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t2","content":[{"type":"tool_reference","tool_name":"mcp__playwright__browser_navigate"}]}]},"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(ref_only).unwrap();
    let tool = s.messages.iter().find(|m| m.role == Role::Tool).unwrap();
    assert!(
        tool.content
            .as_deref()
            .unwrap_or("")
            .contains("browser_navigate"),
        "tool_reference name preserved"
    );

    // An empty tool_result text falls back to toolUseResult (structured).
    let empty_with_tur = r#"
{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t3","name":"Edit","input":{}}]},"sessionId":"s"}
{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t3","content":""}]},"toolUseResult":{"filePath":"/p/x.rs","oldString":"a","newString":"b"},"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(empty_with_tur).unwrap();
    let tool = s.messages.iter().find(|m| m.role == Role::Tool).unwrap();
    let c = tool.content.as_deref().unwrap_or("");
    assert!(
        c.contains("x.rs") && c.contains("newString"),
        "recovered from toolUseResult: {c}"
    );
}

/// Corpus proof: real Claude tool results that used to normalize to blank now
/// carry content (image marker, tool_reference, or recovered toolUseResult).
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn claude_empty_tool_results_recovered_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let root = PathBuf::from(&home).join(".claude/projects");
    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&root)
        .standard_filters(false)
        .build();
    for entry in walker.flatten().take(40_000) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        // A user record with toolUseResult and an empty tool_result text body.
        let mut target: Option<String> = None;
        for line in text.lines() {
            let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
                continue;
            };
            if v.get("type").and_then(|x| x.as_str()) != Some("user")
                || v.get("toolUseResult").is_none()
            {
                continue;
            }
            let tr_text: String = v
                .get("message")
                .and_then(|m| m.get("content"))
                .and_then(|c| c.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter(|b| b.get("type").and_then(|x| x.as_str()) == Some("tool_result"))
                        .map(|b| match b.get("content") {
                            Some(serde_json::Value::String(s)) => s.clone(),
                            Some(serde_json::Value::Array(a)) => a
                                .iter()
                                .filter_map(|i| i.get("text").and_then(|x| x.as_str()))
                                .collect::<Vec<_>>()
                                .join(""),
                            _ => String::new(),
                        })
                        .collect::<String>()
                })
                .unwrap_or_default();
            if tr_text.trim().is_empty() {
                target = v
                    .get("message")
                    .and_then(|m| m.get("content"))
                    .and_then(|c| c.as_array())
                    .and_then(|a| {
                        a.iter()
                            .find(|b| b.get("type").and_then(|x| x.as_str()) == Some("tool_result"))
                    })
                    .and_then(|b| b.get("tool_use_id"))
                    .and_then(|x| x.as_str())
                    .map(str::to_string);
                if target.is_some() {
                    break;
                }
            }
        }
        let Some(tid) = target else { continue };
        let s = Session::from_claude_code_str(&text).unwrap();
        let tool = s
            .messages
            .iter()
            .find(|m| m.role == Role::Tool && m.tool_call_id.as_deref() == Some(&tid));
        if let Some(tool) = tool {
            assert!(
                !tool.content.as_deref().unwrap_or("").trim().is_empty(),
                "{}: tool result {tid} still blank after recovery",
                path.display()
            );
            proven = true;
            eprintln!(
                "proven on {}: previously-blank tool result now has content",
                path.display()
            );
            break;
        }
    }
    assert!(
        proven,
        "no Claude session with an empty tool_result + toolUseResult found"
    );
}

// ---- P0: Claude attachment content ----------------------------------------

#[test]
fn claude_content_attachments_are_folded_in() {
    let jsonl = r#"
{"type":"user","message":{"role":"user","content":"start"},"sessionId":"s","cwd":"/tmp"}
{"type":"attachment","attachment":{"type":"queued_command","commandMode":"prompt","prompt":"QUEUED user prompt text"}}
{"type":"attachment","attachment":{"type":"file","filename":"/p/notes.md","content":"FILE BODY here"}}
{"type":"attachment","attachment":{"type":"edited_text_file","filename":"/p/edit.rs","snippet":"EDITED SNIPPET"}}
{"type":"attachment","attachment":{"type":"nested_memory","path":"/p/CLAUDE.md","content":"MEMORY CONTENT"}}
{"type":"attachment","attachment":{"type":"skill_listing","skills":["x"]}}
{"type":"attachment","attachment":{"type":"task_reminder","text":"noise"}}
"#;
    let s = Session::from_claude_code_str(jsonl).unwrap();
    let all: String = s
        .messages
        .iter()
        .filter_map(|m| m.content.clone())
        .collect::<Vec<_>>()
        .join("\n");
    // The four content-bearing subtypes are present…
    assert!(all.contains("QUEUED user prompt text"), "{all}");
    assert!(
        all.contains("FILE BODY here") && all.contains("notes.md"),
        "{all}"
    );
    assert!(all.contains("EDITED SNIPPET"), "{all}");
    assert!(all.contains("MEMORY CONTENT"), "{all}");
    // …and the regenerable system injections are not.
    assert!(!all.contains("noise"), "{all}");
}

/// Corpus proof: a real Claude session containing a content-bearing attachment
/// now surfaces that content in the conversation.
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn claude_attachments_recovered_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let root = PathBuf::from(&home).join(".claude/projects");
    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&root)
        .standard_filters(false)
        .build();
    for entry in walker.flatten().take(40_000) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        if !text.contains("\"attachment\"") {
            continue;
        }
        // Extract a real string body from any of the four content-bearing
        // subtypes and confirm it now appears in the normalized session.
        let mut needle: Option<String> = None;
        for line in text.lines() {
            let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
                continue;
            };
            if v.get("type").and_then(|x| x.as_str()) != Some("attachment") {
                continue;
            }
            let Some(att) = v.get("attachment") else {
                continue;
            };
            let body = match att.get("type").and_then(|x| x.as_str()) {
                Some("queued_command") => att.get("prompt"),
                Some("file") | Some("nested_memory") => att.get("content"),
                Some("edited_text_file") => att.get("snippet"),
                _ => None,
            }
            .and_then(|x| x.as_str());
            if let Some(b) = body {
                // A contiguous run of non-control chars, so it appears verbatim
                // in the folded message text.
                let snippet: String = b
                    .trim_start()
                    .chars()
                    .take_while(|c| !c.is_control())
                    .take(40)
                    .collect();
                if snippet.trim().len() > 12 {
                    needle = Some(snippet.trim().to_string());
                    break;
                }
            }
        }
        let Some(needle) = needle else { continue };
        let s = Session::from_claude_code_str(&text).unwrap();
        let blob: String = s
            .messages
            .iter()
            .filter_map(|m| m.content.clone())
            .collect();
        assert!(
            blob.contains(needle.trim()),
            "{}: file attachment content not folded into the conversation",
            path.display()
        );
        proven = true;
        eprintln!(
            "proven on {}: file attachment content now in conversation",
            path.display()
        );
        break;
    }
    assert!(proven, "no Claude session with a file attachment found");
}

// ---- P0: Codex compacted records + thread_rolled_back ---------------------

#[test]
fn codex_compacted_replaces_history() {
    // Pre-compaction turns, then a `compacted` record whose replacement_history
    // is the summarized conversation that should REPLACE them, then a later turn.
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"ORIGINAL long question one"}]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ORIGINAL long answer one"}]}}
{"type":"compacted","payload":{"message":"","replacement_history":[{"type":"message","role":"user","content":[{"type":"input_text","text":"SUMMARY of the conversation so far"}]}]}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"follow-up after compaction"}]}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let texts: Vec<String> = s
        .messages
        .iter()
        .filter_map(|m| m.content.clone())
        .collect();
    // The original pre-compaction turns are gone…
    assert!(!texts.iter().any(|t| t.contains("ORIGINAL")), "{texts:?}");
    // …replaced by the summary, with the post-compaction turn retained.
    assert!(texts.iter().any(|t| t.contains("SUMMARY")), "{texts:?}");
    assert!(
        texts
            .iter()
            .any(|t| t.contains("follow-up after compaction")),
        "{texts:?}"
    );
}

#[test]
fn codex_thread_rolled_back_drops_last_turn() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"keep me"}]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"kept answer"}]}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"undo this turn"}]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"answer to be undone"}]}}
{"type":"event_msg","payload":{"type":"thread_rolled_back","num_turns":1}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let texts: Vec<String> = s
        .messages
        .iter()
        .filter_map(|m| m.content.clone())
        .collect();
    assert!(texts.iter().any(|t| t.contains("keep me")), "{texts:?}");
    assert!(texts.iter().any(|t| t.contains("kept answer")), "{texts:?}");
    // The rolled-back turn (user + assistant) is removed.
    assert!(
        !texts.iter().any(|t| t.contains("undo this turn")),
        "{texts:?}"
    );
    assert!(
        !texts.iter().any(|t| t.contains("to be undone")),
        "{texts:?}"
    );
}

/// Corpus proof: a real Codex session with a `compacted` record loads its
/// replacement_history (previously the whole record was dropped).
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn codex_compacted_recovered_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let root = PathBuf::from(&home).join(".codex/sessions");
    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&root)
        .standard_filters(false)
        .build();
    for entry in walker.flatten().take(40_000) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        if !text.contains("\"type\":\"compacted\"") {
            continue;
        }
        // The replacement_history has real messages.
        let rep_msgs = text.matches("replacement_history").count();
        if rep_msgs == 0 {
            continue;
        }
        let s = Session::from_codex_str(&text).unwrap();
        assert!(
            !s.messages.is_empty(),
            "{}: compacted session normalized to zero messages",
            path.display()
        );
        proven = true;
        eprintln!(
            "proven on {}: compacted session → {} messages (replacement_history applied)",
            path.display(),
            s.messages.len()
        );
        break;
    }
    assert!(proven, "no Codex file with a compacted record found");
}

// ---- P0: Codex collab event_msg assistant content -------------------------

#[test]
fn codex_collab_agent_messages_recovered_but_normal_deduped() {
    // Normal session: the agent_message event duplicates the response_item
    // assistant message → must NOT be added twice.
    let normal = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}}
{"type":"event_msg","payload":{"type":"agent_message","phase":"final_answer","message":"the answer is 42"}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"the answer is 42"}]}}
"#;
    let s = Session::from_codex_str(normal).unwrap();
    let assistants = s
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .count();
    assert_eq!(assistants, 1, "duplicate agent_message must be deduped");

    // Collab/worker session: assistant narration exists ONLY as agent_message
    // events (no response_item copy) → must be recovered.
    let collab = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"do the task"}]}}
{"type":"event_msg","payload":{"type":"agent_message","phase":"commentary","message":"I'll inspect the repo first."}}
{"type":"event_msg","payload":{"type":"agent_message","phase":"commentary","message":"Now running the tests."}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"All done."}]}}
"#;
    let s = Session::from_codex_str(collab).unwrap();
    let texts: Vec<String> = s
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .filter_map(|m| m.content.clone())
        .collect();
    assert!(
        texts.iter().any(|t| t.contains("inspect the repo")),
        "{texts:?}"
    );
    assert!(
        texts.iter().any(|t| t.contains("running the tests")),
        "{texts:?}"
    );
    assert!(texts.iter().any(|t| t.contains("All done")), "{texts:?}");
    assert_eq!(
        texts.len(),
        3,
        "two recovered narration turns + one final answer"
    );
}

/// Corpus proof: a real collab/worker Codex session (agent_message >> assistant
/// response_items) now recovers the narration the loader used to drop entirely.
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn codex_collab_narration_recovered_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let root = PathBuf::from(&home).join(".codex/sessions");

    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&root)
        .standard_filters(false)
        .build();
    for entry in walker.flatten().take(40_000) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        // Heuristic for a collab session: many agent_message events, few
        // assistant response_items.
        let agent_msgs = text.matches("\"type\":\"agent_message\"").count();
        let assistant_ri = text.matches("\"role\":\"assistant\"").count();
        if agent_msgs < 50 || agent_msgs < assistant_ri * 3 + 10 {
            continue;
        }
        let session = Session::from_codex_str(&text).unwrap();
        let assistant_count = session
            .messages
            .iter()
            .filter(|m| m.role == Role::Assistant)
            .count();
        // The recovered transcript must contain far more assistant turns than
        // the handful of response_item assistant messages.
        assert!(
            assistant_count > assistant_ri + 20,
            "{}: only {assistant_count} assistant msgs recovered from {agent_msgs} agent_message events",
            path.display()
        );
        proven = true;
        eprintln!(
            "proven on {}: {agent_msgs} agent_message events, {assistant_ri} response_item assistants → {assistant_count} assistant turns recovered",
            path.display()
        );
        break;
    }
    assert!(proven, "no collab-pattern Codex file found to prove on");
}

// ---- P4: Claude attribution + content-bearing system subtypes -------------

#[test]
fn claude_attribution_and_system_content() {
    let jsonl = r#"
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"done by skill"}]},"attributionSkill":"pm","slug":"my-slug","sessionId":"s"}
{"type":"system","subtype":"scheduled_task_fire","content":"Claude resuming /loop wakeup","sessionId":"s"}
{"type":"system","subtype":"local_command","content":"<command-name>/model</command-name>","sessionId":"s"}
{"type":"system","subtype":"turn_duration","durationMs":1234,"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(jsonl).unwrap();

    // Attribution captured on the assistant message metadata.
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .unwrap();
    assert_eq!(
        a.metadata.get("attributionSkill").map(String::as_str),
        Some("pm")
    );
    assert_eq!(a.metadata.get("slug").map(String::as_str), Some("my-slug"));

    // Content-bearing system subtypes folded in; marker subtypes skipped.
    let blob: String = s
        .messages
        .iter()
        .filter(|m| m.role == Role::System)
        .filter_map(|m| m.content.clone())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(blob.contains("resuming /loop wakeup"), "{blob}");
    assert!(blob.contains("<command-name>/model"), "{blob}");
    // turn_duration is a marker — not folded.
    assert!(!blob.contains("1234"), "{blob}");

    // None of the metadata leaks to the wire format.
    let wire = serde_json::to_string(&s.messages).unwrap();
    assert!(!wire.contains("attributionSkill") && !wire.contains("systemSubtype"));
}

/// Corpus proof: a real Claude session with a content-bearing system subtype
/// now surfaces that content.
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn claude_system_content_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let root = PathBuf::from(&home).join(".claude/projects");
    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&root)
        .standard_filters(false)
        .build();
    for entry in walker.flatten().take(40_000) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        // Find a content-bearing system line and a needle from it.
        let mut needle: Option<String> = None;
        for line in text.lines() {
            let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
                continue;
            };
            if v.get("type").and_then(|x| x.as_str()) != Some("system") {
                continue;
            }
            let sub = v.get("subtype").and_then(|x| x.as_str()).unwrap_or("");
            if matches!(
                sub,
                "scheduled_task_fire" | "local_command" | "away_summary"
            ) {
                if let Some(c) = v.get("content").and_then(|x| x.as_str()) {
                    let snip: String = c
                        .trim_start()
                        .chars()
                        .take_while(|c| !c.is_control())
                        .take(30)
                        .collect();
                    if snip.trim().len() > 10 {
                        needle = Some(snip.trim().to_string());
                        break;
                    }
                }
            }
        }
        let Some(needle) = needle else { continue };
        let s = Session::from_claude_code_str(&text).unwrap();
        let blob: String = s
            .messages
            .iter()
            .filter_map(|m| m.content.clone())
            .collect();
        assert!(
            blob.contains(&needle),
            "{}: system content not folded",
            path.display()
        );
        proven = true;
        eprintln!(
            "proven on {}: system subtype content folded",
            path.display()
        );
        break;
    }
    assert!(
        proven,
        "no Claude session with a content-bearing system subtype found"
    );
}

// ---- P3: reasoning preservation -------------------------------------------

#[test]
fn reasoning_retained_in_metadata_not_on_wire() {
    // Codex: a reasoning item precedes an assistant turn.
    let codex = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"reasoning","encrypted_content":"OPAQUE","summary":[{"type":"summary_text","text":"weighed options A and B"}]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"go with A"}]}}
"#;
    let s = Session::from_codex_str(codex).unwrap();
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .unwrap();
    assert!(a
        .metadata
        .get("reasoning")
        .map(String::as_str)
        .unwrap_or("")
        .contains("options A and B"));
    assert_eq!(
        a.metadata.get("reasoning_encrypted").map(String::as_str),
        Some("true")
    );

    // Claude: a thinking block on the assistant turn.
    let claude = r#"
{"type":"assistant","message":{"role":"assistant","content":[{"type":"thinking","thinking":"let me reason","signature":"sig-1"},{"type":"text","text":"answer"}]},"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(claude).unwrap();
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .unwrap();
    assert_eq!(
        a.metadata.get("thinking").map(String::as_str),
        Some("let me reason")
    );
    assert_eq!(
        a.metadata.get("thinking_signature").map(String::as_str),
        Some("sig-1")
    );
    assert_eq!(
        a.content.as_deref(),
        Some("answer"),
        "thinking is not mixed into content"
    );

    // Retained reasoning never reaches the OpenAI wire format.
    let wire = serde_json::to_string(&s.messages).unwrap();
    assert!(!wire.contains("thinking") && !wire.contains("reason"));
}

// ---- P2: multi-file subagent lineage --------------------------------------

#[test]
fn codex_lineage_capture_and_tree_reconstruction() {
    // Parent session A.
    let parent = Session::from_codex_str(
        r#"{"type":"session_meta","payload":{"id":"A","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"delegate"}]}}"#,
    )
    .unwrap();
    // Child rollout whose lineage points at A.
    let child = Session::from_codex_str(
        r#"{"type":"session_meta","payload":{"id":"B","cwd":"/tmp","thread_source":"subagent","source":{"subagent":{"thread_spawn":{"parent_thread_id":"A","depth":1,"agent_nickname":"Gauss","agent_role":"worker"}}}}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"sub work"}]}}"#,
    )
    .unwrap();

    // Lineage captured.
    assert_eq!(
        child
            .meta
            .lineage
            .get("parent_thread_id")
            .map(String::as_str),
        Some("A")
    );
    assert_eq!(
        child.meta.lineage.get("agent_nickname").map(String::as_str),
        Some("Gauss")
    );
    assert_eq!(
        child.meta.lineage.get("thread_source").map(String::as_str),
        Some("subagent")
    );

    // Reconstruct the tree: child nests under parent A; one root remains.
    let roots = Session::reconstruct_tree(vec![parent, child]);
    assert_eq!(roots.len(), 1, "only the parent is a root");
    assert_eq!(roots[0].meta.session_id.as_deref(), Some("A"));
    assert_eq!(roots[0].subagents.len(), 1, "child attached under parent");
    assert_eq!(roots[0].subagents[0].meta.session_id.as_deref(), Some("B"));
}

/// Corpus proof: a real Codex subagent rollout carries the parent_thread_id
/// lineage key needed to reconstruct cross-file trees.
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn codex_subagent_lineage_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let root = PathBuf::from(&home).join(".codex/sessions");
    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&root)
        .standard_filters(false)
        .build();
    for entry in walker.flatten().take(40_000) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        if !text.contains("\"thread_source\":\"subagent\"") {
            continue;
        }
        let s = Session::from_codex_str(&text).unwrap();
        if s.meta.lineage.contains_key("parent_thread_id") {
            proven = true;
            eprintln!(
                "proven on {}: parent_thread_id={:?}",
                path.display(),
                s.meta.lineage.get("parent_thread_id")
            );
            break;
        }
    }
    assert!(proven, "no Codex subagent rollout with lineage found");
}

// ---- P2: Codex thread_goal_updated + review_mode --------------------------

#[test]
fn codex_thread_goal_and_review_recovered() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"event_msg","payload":{"type":"thread_goal_updated","goal":{"objective":"Stabilize the orchestrator"}}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"start review"}]}}
{"type":"event_msg","payload":{"type":"entered_review_mode"}}
{"type":"event_msg","payload":{"type":"exited_review_mode","review_output":{"findings":[],"overall_correctness":"patch is correct","overall_explanation":"All good; no issues found."}}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let blob: String = s
        .messages
        .iter()
        .filter_map(|m| m.content.clone())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        blob.contains("[thread goal] Stabilize the orchestrator"),
        "{blob}"
    );
    assert!(
        blob.contains("[code review]") && blob.contains("no issues found"),
        "{blob}"
    );
}

// ---- P2 / P2.5: turn-grouping + provenance fields -------------------------

#[test]
fn claude_user_provenance_and_tool_pairing_edge() {
    let jsonl = r#"
{"type":"user","message":{"role":"user","content":"real prompt"},"promptSource":"typed","sessionId":"s"}
{"type":"user","message":{"role":"user","content":"injected"},"promptSource":"system","isMeta":true,"origin":{"kind":"task-notification"},"sessionId":"s"}
{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Read","input":{}}]},"sessionId":"s"}
{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"data"}]},"sourceToolAssistantUUID":"asst-uuid-9","sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(jsonl).unwrap();
    let users: Vec<&supercode::ChatMessage> =
        s.messages.iter().filter(|m| m.role == Role::User).collect();
    assert_eq!(
        users[0].metadata.get("promptSource").map(String::as_str),
        Some("typed")
    );
    assert_eq!(
        users[1].metadata.get("promptSource").map(String::as_str),
        Some("system")
    );
    assert_eq!(
        users[1].metadata.get("isMeta").map(String::as_str),
        Some("true")
    );
    assert_eq!(
        users[1].metadata.get("origin").map(String::as_str),
        Some("task-notification")
    );

    // The tool result records which assistant turn issued the call.
    let tool = s.messages.iter().find(|m| m.role == Role::Tool).unwrap();
    assert_eq!(
        tool.metadata
            .get("sourceToolAssistantUUID")
            .map(String::as_str),
        Some("asst-uuid-9")
    );

    // None of this metadata leaks to the wire format.
    let wire = serde_json::to_string(&s.messages).unwrap();
    assert!(!wire.contains("promptSource") && !wire.contains("sourceToolAssistantUUID"));
}

#[test]
fn claude_compaction_summary_is_marked() {
    // Claude keeps full history in the log; the compaction summary is an
    // isCompactSummary "user" message. Tag it so a consumer continuing the
    // session knows it's a summary, not human input.
    let jsonl = r#"
{"type":"user","message":{"role":"user","content":"real turn"},"promptSource":"typed","sessionId":"s"}
{"type":"system","subtype":"compact_boundary","content":"Conversation compacted","sessionId":"s"}
{"type":"user","message":{"role":"user","content":"<summary of earlier conversation>"},"isCompactSummary":true,"isVisibleInTranscriptOnly":true,"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(jsonl).unwrap();
    let summary = s
        .messages
        .iter()
        .find(|m| m.metadata.get("isCompactSummary").map(String::as_str) == Some("true"))
        .expect("compaction summary tagged");
    assert!(summary
        .content
        .as_deref()
        .unwrap_or("")
        .contains("summary of earlier"));
    assert_eq!(
        summary
            .metadata
            .get("isVisibleInTranscriptOnly")
            .map(String::as_str),
        Some("true")
    );
    // The real human turn is not tagged as a summary.
    let real = s
        .messages
        .iter()
        .find(|m| m.content.as_deref() == Some("real turn"))
        .unwrap();
    assert!(!real.metadata.contains_key("isCompactSummary"));
}

#[test]
fn codex_turn_id_preserved() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}],"metadata":{"turn_id":"turn-7"}}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .unwrap();
    assert_eq!(
        a.metadata.get("turn_id").map(String::as_str),
        Some("turn-7")
    );
}

/// Corpus proof: real Claude sessions preserve `promptSource` (distinguishing
/// typed human input from system-injected turns) on user messages.
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn claude_promptsource_preserved_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let root = PathBuf::from(&home).join(".claude/projects");
    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&root)
        .standard_filters(false)
        .build();
    for entry in walker.flatten().take(40_000) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        if !text.contains("\"promptSource\":\"typed\"") {
            continue;
        }
        let s = Session::from_claude_code_str(&text).unwrap();
        if s.messages
            .iter()
            .any(|m| m.metadata.get("promptSource").map(String::as_str) == Some("typed"))
        {
            proven = true;
            eprintln!("proven on {}: promptSource preserved", path.display());
            break;
        }
    }
    assert!(proven, "no Claude session with promptSource=typed found");
}

// ---- P2: Codex assistant phase (commentary vs final_answer) ---------------

#[test]
fn codex_assistant_phase_preserved() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"assistant","phase":"commentary","content":[{"type":"output_text","text":"thinking out loud"}]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","phase":"final_answer","content":[{"type":"output_text","text":"the answer"}]}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let phases: Vec<Option<&String>> = s
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .map(|m| m.metadata.get("phase"))
        .collect();
    assert_eq!(phases.len(), 2);
    assert_eq!(phases[0].map(String::as_str), Some("commentary"));
    assert_eq!(phases[1].map(String::as_str), Some("final_answer"));

    // Metadata must NOT leak onto the OpenAI wire format.
    let wire = serde_json::to_string(&s.messages).unwrap();
    assert!(!wire.contains("phase"), "metadata must be skip-serialized");
    assert!(
        !wire.contains("metadata"),
        "metadata must be skip-serialized"
    );
}

/// Corpus proof: a real Codex session preserves the commentary/final_answer
/// split on its assistant turns.
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn codex_phase_preserved_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let root = PathBuf::from(&home).join(".codex/sessions");
    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&root)
        .standard_filters(false)
        .build();
    for entry in walker.flatten().take(40_000) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        if !text.contains("\"phase\":\"final_answer\"")
            || !text.contains("\"phase\":\"commentary\"")
        {
            continue;
        }
        let s = Session::from_codex_str(&text).unwrap();
        let has_commentary = s
            .messages
            .iter()
            .any(|m| m.metadata.get("phase").map(String::as_str) == Some("commentary"));
        let has_final = s
            .messages
            .iter()
            .any(|m| m.metadata.get("phase").map(String::as_str) == Some("final_answer"));
        if has_commentary && has_final {
            proven = true;
            eprintln!("proven on {}: phase labels preserved", path.display());
            break;
        }
    }
    assert!(proven, "no Codex session with both phases found");
}

// ---- P2: interrupted turns / unanswered tool calls ------------------------

#[test]
fn unanswered_tool_calls_get_synthetic_results() {
    // An assistant tool call whose turn was interrupted (no output recorded).
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"go"}]}}
{"type":"response_item","payload":{"type":"function_call","call_id":"unanswered","name":"bash","arguments":"{}"}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    // Every tool call now has a matching tool result (valid for replay).
    let calls: Vec<String> = s
        .messages
        .iter()
        .flat_map(|m| m.tool_calls().iter().map(|c| c.id.clone()))
        .collect();
    let results: Vec<String> = s
        .messages
        .iter()
        .filter(|m| m.role == Role::Tool)
        .filter_map(|m| m.tool_call_id.clone())
        .collect();
    assert!(
        results.contains(&"unanswered".to_string()),
        "synthetic result added"
    );
    assert_eq!(calls.len(), results.len(), "every call answered");

    // And the synthetic result sits immediately after the call's turn.
    let call_idx = s
        .messages
        .iter()
        .position(|m| !m.tool_calls().is_empty())
        .unwrap();
    assert_eq!(s.messages[call_idx + 1].role, Role::Tool);
    assert_eq!(
        s.messages[call_idx + 1].tool_call_id.as_deref(),
        Some("unanswered")
    );
}

#[test]
fn paired_sessions_are_left_unchanged() {
    // A fully-paired session must not gain any synthetic results.
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"function_call","call_id":"c","name":"x","arguments":"{}"}}
{"type":"response_item","payload":{"type":"function_call_output","call_id":"c","output":"ok"}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    assert!(!s
        .messages
        .iter()
        .any(|m| m.content.as_deref() == Some("[no tool result recorded — turn interrupted]")));
}

/// Corpus proof: a real session with an unanswered tool call now loads with
/// every assistant tool call answered (valid OpenAI-style replay).
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn unanswered_tool_calls_paired_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let mut proven = false;
    for sub in [".codex/sessions", ".claude/projects"] {
        let root = PathBuf::from(&home).join(sub);
        let walker = ignore::WalkBuilder::new(&root)
            .standard_filters(false)
            .build();
        for entry in walker.flatten().take(20_000) {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                continue;
            }
            let Ok(text) = std::fs::read_to_string(path) else {
                continue;
            };
            let s = Session::load(path).unwrap_or_else(|_| {
                Session::from_codex_str(&text)
                    .unwrap_or_else(|_| Session::from_claude_code_str(&text).unwrap())
            });
            let calls: std::collections::HashSet<String> = s
                .messages
                .iter()
                .flat_map(|m| m.tool_calls().iter().map(|c| c.id.clone()))
                .filter(|id| !id.is_empty())
                .collect();
            if calls.is_empty() {
                continue;
            }
            let results: std::collections::HashSet<String> = s
                .messages
                .iter()
                .filter(|m| m.role == Role::Tool)
                .filter_map(|m| m.tool_call_id.clone())
                .collect();
            // Invariant must hold for EVERY loaded session.
            assert!(
                calls.is_subset(&results),
                "{}: tool calls without results after pairing",
                path.display()
            );
            // Prove we actually exercised a session that needed synthesis.
            if s.messages.iter().any(|m| {
                m.content.as_deref() == Some("[no tool result recorded — turn interrupted]")
            }) {
                proven = true;
                eprintln!("proven on {}: unanswered tool call paired", path.display());
            }
            if proven {
                break;
            }
        }
        if proven {
            break;
        }
    }
    assert!(
        proven,
        "no session with an unanswered tool call found to prove on"
    );
}

// ---- P1: Codex server/agent tool coverage ---------------------------------

#[test]
fn codex_server_tools_and_namespace() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"tool_search_call","call_id":"ts1","arguments":{"query":"find tools"}}}
{"type":"response_item","payload":{"type":"tool_search_output","call_id":"ts1","tools":[{"type":"namespace","name":"multi_agent"}]}}
{"type":"response_item","payload":{"type":"web_search_call","status":"completed"}}
{"type":"response_item","payload":{"type":"image_generation_call","status":"completed","revised_prompt":"a blue circle"}}
{"type":"response_item","payload":{"type":"function_call","call_id":"f1","name":"create_issue","namespace":"linear","arguments":"{}"}}
{"type":"response_item","payload":{"type":"function_call_output","call_id":"f1","output":"ok"}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();

    // tool_search is a paired call/result.
    let ts_call = s.messages.iter().find_map(|m| {
        m.tool_calls()
            .iter()
            .find(|c| c.function.name == "tool_search")
            .cloned()
    });
    let ts_call = ts_call.expect("tool_search call present");
    assert_eq!(ts_call.id, "ts1");
    assert!(s.messages.iter().any(|m| m.role == Role::Tool
        && m.tool_call_id.as_deref() == Some("ts1")
        && m.content.as_deref().unwrap_or("").contains("multi_agent")));

    // web_search and image_generation are non-dropped markers.
    let blob: String = s
        .messages
        .iter()
        .filter_map(|m| m.content.clone())
        .collect();
    assert!(blob.contains("[web_search]"), "{blob}");
    assert!(blob.contains("[image_generation] a blue circle"), "{blob}");

    // namespace qualifies the function-call name.
    let fc = s
        .messages
        .iter()
        .find_map(|m| m.tool_calls().iter().find(|c| c.id == "f1").cloned())
        .expect("function call f1");
    assert_eq!(fc.function.name, "linear__create_issue");

    // No dangling unanswered tool call (web_search/image_gen are text, not calls).
    let calls: usize = s.messages.iter().map(|m| m.tool_calls().len()).sum();
    let results = s.messages.iter().filter(|m| m.role == Role::Tool).count();
    assert_eq!(calls, results, "every tool call has a matching result");
}

// ---- P0: Claude Code subagent files ---------------------------------------

/// Proof against the real corpus: loading a Claude Code session that spawned a
/// subagent now attaches the subagent's (previously omitted) conversation, with
/// best-effort linkage back to the spawning Task tool call.
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn claude_subagents_attached_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let projects = PathBuf::from(&home).join(".claude/projects");

    // Find a main transcript `<dir>/<stem>.jsonl` that has a sibling
    // `<dir>/<stem>/subagents/*.jsonl`.
    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&projects)
        .standard_filters(false)
        .build();
    for entry in walker.flatten() {
        let path = entry.path();
        if path.is_dir() && path.file_name().and_then(|n| n.to_str()) == Some("subagents") {
            // path = <dir>/<stem>/subagents ; main = <dir>/<stem>.jsonl
            let Some(session_dir) = path.parent() else {
                continue;
            };
            let Some(proj) = session_dir.parent() else {
                continue;
            };
            let Some(stem) = session_dir.file_name().and_then(|n| n.to_str()) else {
                continue;
            };
            let main = proj.join(format!("{stem}.jsonl"));
            if !main.is_file() {
                continue;
            }
            let has_agent_file = std::fs::read_dir(path)
                .map(|rd| {
                    rd.flatten()
                        .any(|e| e.path().extension().and_then(|x| x.to_str()) == Some("jsonl"))
                })
                .unwrap_or(false);
            if !has_agent_file {
                continue;
            }

            let session = Session::load(&main).unwrap();
            assert!(
                !session.subagents.is_empty(),
                "{}: has a subagents/ dir but no subagents attached",
                main.display()
            );
            // Each attached subagent is a real sub-conversation, not empty.
            let sub_msgs: usize = session.subagents.iter().map(|s| s.messages.len()).sum();
            assert!(
                sub_msgs > 0,
                "{}: subagents attached but carry no messages",
                main.display()
            );
            // agent_id is recovered for each.
            assert!(
                session.subagents.iter().all(|s| s.meta.agent_id.is_some()),
                "{}: a subagent is missing its agent_id",
                main.display()
            );
            proven = true;
            let linked = session
                .subagents
                .iter()
                .filter(|s| s.meta.parent_tool_use_id.is_some())
                .count();
            eprintln!(
                "proven on {}: {} subagent(s), {sub_msgs} sub-messages, {linked} linked to a Task call",
                main.display(),
                session.subagents.len()
            );
            break;
        }
    }
    assert!(
        proven,
        "no Claude Code session with both a main transcript and subagents/ found"
    );
}

// ---- P0: Codex custom / MCP tool calls ------------------------------------

#[test]
fn codex_custom_tool_calls_are_normalized() {
    // A minimal Codex rollout that uses a custom/MCP tool. Before this fix the
    // loader matched only `function_call`/`function_call_output`, so these two
    // turns vanished entirely.
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s1","cwd":"/tmp"}}
{"type":"turn_context","payload":{"model":"gpt-5.5"}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"patch the file"}]}}
{"type":"response_item","payload":{"type":"custom_tool_call","status":"completed","call_id":"call_abc","name":"apply_patch","input":"*** Begin Patch ***"}}
{"type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"call_abc","output":"Success. Updated 1 file."}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}}
"#;

    let s = Session::from_codex_str(jsonl).unwrap();

    // user, assistant(tool_call), tool(result), assistant(text)
    let roles: Vec<Role> = s.messages.iter().map(|m| m.role).collect();
    assert_eq!(
        roles,
        vec![Role::User, Role::Assistant, Role::Tool, Role::Assistant]
    );

    // The custom tool call is present with its name, id, and arguments.
    let call = &s.messages[1].tool_calls()[0];
    assert_eq!(call.id, "call_abc");
    assert_eq!(call.function.name, "apply_patch");
    assert!(call.function.arguments.contains("Begin Patch"));

    // The output is linked back by call_id.
    assert_eq!(s.messages[2].tool_call_id.as_deref(), Some("call_abc"));
    assert!(s.messages[2]
        .content
        .as_deref()
        .unwrap_or("")
        .contains("Success"));
}

/// Proof against the real corpus: a Codex session that actually used a custom /
/// MCP tool now yields the corresponding tool call/result instead of dropping
/// them. Opt-in (needs the local corpus).
#[test]
#[ignore = "requires local session corpus; set SUPERCODE_CORPUS=1"]
fn codex_custom_tool_calls_recovered_from_corpus() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without \
             the maintainer's local session logs; set SUPERCODE_CORPUS=1 to run it."
        );
    }
    let home = std::env::var("HOME").unwrap();
    let root = PathBuf::from(&home).join(".codex/sessions");

    // Find a real file containing a custom_tool_call.
    let mut proven = false;
    let walker = ignore::WalkBuilder::new(&root)
        .standard_filters(false)
        .build();
    for entry in walker.flatten().take(20_000) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        if !text.contains("\"custom_tool_call\"") {
            continue;
        }
        let Ok(session) = Session::from_codex_str(&text) else {
            continue;
        };
        // Count custom_tool_call lines in the raw file…
        let raw_calls = text
            .lines()
            .filter(|l| l.contains("\"type\":\"custom_tool_call\""))
            .count();
        if raw_calls == 0 {
            continue;
        }
        // …and assert the normalized session now carries tool calls (it dropped
        // them all before this fix).
        let normalized_calls: usize = session.messages.iter().map(|m| m.tool_calls().len()).sum();
        assert!(
            normalized_calls > 0,
            "{}: {raw_calls} custom_tool_calls but 0 normalized",
            path.display()
        );
        proven = true;
        eprintln!(
            "proven on {}: {raw_calls} raw custom_tool_calls → {normalized_calls} total tool calls",
            path.display()
        );
        break;
    }
    assert!(
        proven,
        "no Codex file with custom_tool_call found to prove on"
    );
}