supercode-harness 0.4.3

The optional native Supercode agent and tool harness
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
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
//! 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_harness::session::{Session, SessionFormat};
use supercode_harness::{ChatMessage, 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.
    // PARITY-11: this source has no `media_type` — the same "genuinely
    // unconvertible" shape `claude_image_block_to_part` already rejects for a
    // TOP-LEVEL `image` block (missing mime/data) — so `extract_tool_result_content`
    // now folds in `UNCONVERTIBLE_IMAGE_MARKER`, not the old bare `[image]`
    // (which used to collapse EVERY nested image, convertible or not, to the
    // same uninformative marker and silently discarded the bytes even for a
    // well-formed base64 source — see
    // `claude_tool_result_nested_image_survives_load_and_round_trip` below for
    // the well-formed, now-actually-captured case).
    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!(
        tool.content
            .as_deref()
            .unwrap_or("")
            .contains("unconvertible"),
        "unconvertible (no media_type) image-only result must fold in the honest \
         marker, not the old uninformative bare `[image]`: {:?}",
        tool.content
    );
    assert!(
        tool.content_parts.is_none(),
        "no convertible image source exists to synthesize content_parts from: {tool:?}"
    );

    // 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}");

    // Folded in is not the same as spoken by the user, and once the record is
    // flattened to text the only surviving answer is the metadata: the
    // subtype, plus `commandMode` on a queued command. A frontend classifies
    // from these (`isContextMessage`, sdk/client/client.mjs) instead of
    // re-deriving authorship from the text it just read.
    let meta_of = |needle: &str, key: &str| -> Option<Option<String>> {
        s.messages
            .iter()
            .find(|m| {
                m.content
                    .as_deref()
                    .is_some_and(|body| body.contains(needle))
            })
            .map(|m| m.metadata.get(key).cloned())
    };
    for (needle, kind) in [
        ("QUEUED user prompt text", "queued_command"),
        ("FILE BODY here", "file"),
        ("EDITED SNIPPET", "edited_text_file"),
        ("MEMORY CONTENT", "nested_memory"),
    ] {
        assert_eq!(
            meta_of(needle, "attachmentType"),
            Some(Some(kind.to_string())),
            "{needle}: the attachment subtype must survive the flattening"
        );
    }
    assert_eq!(
        meta_of("QUEUED user prompt text", "commandMode"),
        Some(Some("prompt".to_string())),
        "a queued command records whose text it is; keep it verbatim"
    );
    assert_eq!(
        meta_of("FILE BODY here", "commandMode"),
        Some(None),
        "`commandMode` is a queued-command field — never invented elsewhere"
    );
}

/// A `queued_command` attachment is NOT proof a person typed something. Claude
/// Code delivers a finished background task the same way, and says so in
/// `commandMode` — the field this loader used to drop, leaving the frame
/// indistinguishable from the reader's own queued prompt.
#[test]
fn claude_queued_command_attachment_keeps_its_command_mode() {
    let jsonl = r#"
{"type":"user","message":{"role":"user","content":"start"},"sessionId":"s","cwd":"/tmp"}
{"type":"attachment","attachment":{"type":"queued_command","commandMode":"task-notification","prompt":"<task-notification>\n<task-id>bf9yzcpf1</task-id>\n<status>completed</status>\n</task-notification>"}}
{"type":"attachment","attachment":{"type":"queued_command","commandMode":"prompt","prompt":"and now run the tests"}}
"#;
    let s = Session::from_claude_code_str(jsonl).unwrap();
    let modes: Vec<(Option<&str>, Option<&str>)> = s
        .messages
        .iter()
        .filter(|m| m.role == Role::User)
        .map(|m| {
            (
                m.metadata.get("attachmentType").map(String::as_str),
                m.metadata.get("commandMode").map(String::as_str),
            )
        })
        .collect();
    assert_eq!(
        modes,
        vec![
            (None, None), // the person's own turn — not an attachment at all
            (Some("queued_command"), Some("task-notification")),
            (Some("queued_command"), Some("prompt")),
        ]
    );

    // Where the attachment metadata goes on the wire, stated rather than
    // assumed. Claude's own writer projects named fields only, so nothing new
    // appears in a re-emitted Claude transcript. Grok is the portability
    // intermediate: `set_grok_target_message_extension` serializes the WHOLE
    // metadata map into the namespaced `_supercode_grok_message` envelope, so
    // these two DO travel there — which is the point of that envelope, and is
    // the same treatment `claude_uuid`/`systemSubtype`/`promptSource` already
    // get. They are the producer's own fields, so carrying them through a
    // translation is fidelity, not leakage.
    let claude = s.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    assert!(
        !claude.contains("attachmentType") && !claude.contains("commandMode"),
        "{claude}"
    );
    let grok = s.to_jsonl(SessionFormat::Grok).unwrap();
    assert!(
        grok.contains(r#""commandMode":"task-notification""#)
            && grok.contains(r#""attachmentType":"queued_command""#),
        "{grok}"
    );
}

/// 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, non-compacted collab/worker Codex session
/// (`agent_message` >> assistant response_items) now recovers the narration
/// the loader used to drop entirely. Compacted sessions are deliberately
/// excluded: their `replacement_history` supersedes events from before the
/// last compaction, so comparing the final transcript with every lifetime
/// `agent_message` would assert the opposite of Codex's compaction semantics.
#[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;
        };
        if text.contains("\"type\":\"compacted\"") {
            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":"away_summary","content":"Recapping: we split the treatment into four episodes.","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");
    // All three keep-listed subtypes, so dropping any ONE of them from the
    // keep list fails here — in the default gate, without the corpus.
    assert!(blob.contains("resuming /loop wakeup"), "{blob}");
    assert!(blob.contains("<command-name>/model"), "{blob}");
    assert!(blob.contains("split the treatment into four"), "{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: in a real Claude session, every content-bearing `system`
/// record the loader KEEPS surfaces its content verbatim, as a system message
/// tagged with the source subtype.
///
/// "Keeps" is the load-bearing word, and it is read from the loaded session
/// rather than assumed. `from_claude_code_str` projects the single active,
/// post-compaction branch Claude Code would itself resume, so a real
/// transcript's earlier `away_summary`/`local_command` records are routinely
/// (and correctly) *absent* from the normalized messages — measured on this
/// corpus, the FIRST content-bearing system record in file order is dropped by
/// that projection in half the files that have one, and in the most heavily
/// compacted sessions every one of them is. `claude_uuid` provenance is what
/// makes the distinction observable here: a record whose uuid reached the
/// messages was kept, and only those are asserted on. Folding is proved by
/// full-content equality, not a substring, and the run fails if the corpus
/// yielded no kept record to check. Which subtypes are keep-listed is a
/// constant, not a corpus shape, so that half is guarded without a corpus by
/// `claude_attribution_and_system_content` above.
#[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");
    // Records offered by the corpus vs. records the loader kept and this test
    // therefore checked. Both are reported so a zero can never read as a pass.
    let mut candidates = 0usize;
    let mut checked = 0usize;
    let mut files_proven = 0usize;
    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;
        };
        // Every content-bearing system record in the file, keyed by uuid.
        // The non-empty-content filter mirrors the loader's own condition —
        // a blank `content` legitimately produces no message.
        let mut want: Vec<(String, String, String)> = Vec::new();
        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"
            ) {
                continue;
            }
            let (Some(uuid), Some(content)) = (
                v.get("uuid").and_then(|x| x.as_str()),
                v.get("content").and_then(|x| x.as_str()),
            ) else {
                continue;
            };
            if content.trim().is_empty() {
                continue;
            }
            want.push((uuid.to_string(), sub.to_string(), content.to_string()));
        }
        if want.is_empty() {
            continue;
        }
        candidates += want.len();
        let s = Session::from_claude_code_str(&text).unwrap();
        let by_uuid: std::collections::HashMap<&str, &ChatMessage> = s
            .messages
            .iter()
            .filter_map(|m| Some((m.metadata.get("claude_uuid")?.as_str(), m)))
            .collect();
        let mut checked_here = 0usize;
        for (uuid, subtype, content) in &want {
            // Not in the loaded session: the active-branch/compaction
            // projection dropped this record, exactly as Claude Code would
            // when resuming. Nothing to prove about it here.
            let Some(msg) = by_uuid.get(uuid.as_str()) else {
                continue;
            };
            checked_here += 1;
            assert_eq!(
                msg.role,
                Role::System,
                "{}: kept `{subtype}` record {uuid} is not a system message",
                path.display()
            );
            assert_eq!(
                msg.content.as_deref(),
                Some(content.as_str()),
                "{}: kept `{subtype}` record {uuid} did not fold its content verbatim",
                path.display()
            );
            assert_eq!(
                msg.metadata.get("systemSubtype").map(String::as_str),
                Some(subtype.as_str()),
                "{}: kept `{subtype}` record {uuid} lost its systemSubtype tag",
                path.display()
            );
        }
        if checked_here > 0 {
            checked += checked_here;
            files_proven += 1;
            eprintln!(
                "proven on {}: {checked_here}/{} content-bearing system records kept and folded",
                path.display(),
                want.len()
            );
            // A handful of real files is proof; walking the whole corpus only
            // costs minutes.
            if files_proven >= 5 {
                break;
            }
        }
    }
    assert!(
        checked > 0,
        "no kept content-bearing Claude system record to prove on \
         ({candidates} offered by the corpus, {checked} kept by the loader)"
    );
}

// ---- 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"));
}

/// N1: on a REAL Codex rollout, `encrypted_content` is a present-but-`null`
/// key on the vast majority of reasoning items (upstream always serializes
/// the field, `codex-rs/protocol/src/models.rs:970-983`, no
/// `skip_serializing_if`). `serde_json` returns `Some(&Value::Null)` for a
/// present-but-null key, so the pre-fix code
/// (`payload.get("encrypted_content").is_some()`) false-flagged
/// `reasoning_encrypted` on every single following assistant turn in a real
/// corpus — exactly the false positive `Coverage::Retained`'s label implied
/// was never happening. This test fails against the pre-fix `.is_some()`
/// check (it would assert `Some("true")` is `None`) and passes with the
/// `.is_some_and(|v| !v.is_null())` fix. The genuinely-encrypted case (a
/// real, non-null opaque blob) must still set the flag — asserted in the
/// same test so a regression that just stops setting the flag entirely
/// can't sneak through either.
#[test]
fn reasoning_encrypted_flag_is_gated_on_genuinely_non_null_content() {
    // Real shape: `encrypted_content` key present, value `null`.
    let null_case = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"reasoning","content":null,"encrypted_content":null,"summary":[{"type":"summary_text","text":"thinking it through"}]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"answer one"}]}}
"#;
    let s = Session::from_codex_str(null_case).unwrap();
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .unwrap();
    assert_eq!(
        a.metadata.get("reasoning_encrypted"),
        None,
        "encrypted_content:null must NOT set reasoning_encrypted (N1) -- \
         got {:?}",
        a.metadata.get("reasoning_encrypted")
    );
    assert_eq!(
        a.metadata.get("reasoning").map(String::as_str),
        Some("thinking it through"),
        "summary text must still be captured even when encrypted_content is null"
    );

    // Real shape: `encrypted_content` key present, genuinely non-null blob.
    let encrypted_case = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"reasoning","content":null,"encrypted_content":"gAAAAABOPAQUEBLOB==","summary":[]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"answer two"}]}}
"#;
    let s = Session::from_codex_str(encrypted_case).unwrap();
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .unwrap();
    assert_eq!(
        a.metadata.get("reasoning_encrypted").map(String::as_str),
        Some("true"),
        "a genuinely non-null encrypted_content MUST still set reasoning_encrypted"
    );
}

/// N2: `response_item/reasoning` is labeled `Coverage::Retained`, but the
/// pre-fix loader only ever captured `summary` + the encrypted flag -- the
/// raw `content` field (the actual chain-of-thought text, distinct from the
/// `summary` synopsis) was silently dropped despite the label. This test
/// fails against the pre-fix loader (metadata key `reasoning_content` is
/// never populated there) and passes now that `content` is captured
/// alongside `summary`.
#[test]
fn reasoning_raw_content_is_captured_not_silently_dropped() {
    let codex = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"reasoning","content":[{"type":"reasoning_text","text":"first I considered X, then Y, chose Y because it's simpler"}],"encrypted_content":null,"summary":[{"type":"summary_text","text":"weighed X vs Y"}]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"went with Y"}]}}
"#;
    let s = Session::from_codex_str(codex).unwrap();
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .unwrap();
    assert_eq!(
        a.metadata.get("reasoning").map(String::as_str),
        Some("weighed X vs Y"),
        "summary must still be captured"
    );
    assert_eq!(
        a.metadata.get("reasoning_content").map(String::as_str),
        Some("first I considered X, then Y, chose Y because it's simpler"),
        "raw reasoning `content` must be captured, not silently dropped (N2) \
         despite Coverage::Retained claiming it survives"
    );
    assert_eq!(a.metadata.get("reasoning_encrypted"), None);

    // `content: null` (the common real-world case) must NOT stringify to
    // the literal text "null" via a naive `extract_text_content` call.
    let null_content = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"reasoning","content":null,"encrypted_content":null,"summary":[]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"answer"}]}}
"#;
    let s = Session::from_codex_str(null_content).unwrap();
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .unwrap();
    assert_eq!(
        a.metadata.get("reasoning_content"),
        None,
        "content:null must never surface as the literal text \"null\""
    );
}

/// N3: pending reasoning used to be unconditionally cleared as soon as the
/// NEXT `response_item` was processed, even when that item wasn't the
/// assistant turn the reasoning was for (e.g. a user message interrupts an
/// aborted turn) -- and trailing reasoning dangling at EOF (another
/// aborted-turn shape) was never flushed at all, silently discarded despite
/// `Coverage::Retained`. Both cases now surface as their own synthesized
/// `[reasoning] (turn ended without a reply)` message. This test fails
/// against the pre-fix code (no such message is ever produced; the
/// `reasoning`/`reasoning_encrypted` text disappears with no trace).
#[test]
fn orphaned_reasoning_is_flushed_not_discarded() {
    // Case A: reasoning immediately followed by a USER message (no
    // assistant turn ever claims it) -- an aborted-turn interruption shape.
    let interrupted = 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":"reasoning","content":null,"encrypted_content":"gAAAAABORPHANED==","summary":[{"type":"summary_text","text":"orphaned by interruption"}]}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"actually stop"}]}}
"#;
    let s = Session::from_codex_str(interrupted).unwrap();
    let orphan = s
        .messages
        .iter()
        .find(|m| {
            m.metadata.get("reasoning").map(String::as_str) == Some("orphaned by interruption")
        })
        .unwrap_or_else(|| {
            panic!(
                "orphaned reasoning interrupted by a user message must survive \
                 as its own message, not be silently discarded: {:?}",
                s.messages
            )
        });
    assert_eq!(
        orphan
            .metadata
            .get("reasoning_encrypted")
            .map(String::as_str),
        Some("true")
    );
    // And it must appear BEFORE the interrupting "actually stop" user turn,
    // preserving chronological order.
    let orphan_idx = s
        .messages
        .iter()
        .position(|m| std::ptr::eq(m, orphan))
        .unwrap();
    let stop_idx = s
        .messages
        .iter()
        .position(|m| m.content.as_deref() == Some("actually stop"))
        .unwrap();
    assert!(
        orphan_idx < stop_idx,
        "orphaned reasoning must be inserted before the interrupting message, \
         not appended after"
    );

    // Case B: reasoning dangling at EOF -- the turn was aborted before any
    // reply arrived at all.
    let trailing_eof = 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":"reasoning","content":null,"encrypted_content":null,"summary":[{"type":"summary_text","text":"dangling at eof"}]}}
"#;
    let s = Session::from_codex_str(trailing_eof).unwrap();
    let orphan = s
        .messages
        .iter()
        .find(|m| m.metadata.get("reasoning").map(String::as_str) == Some("dangling at eof"))
        .unwrap_or_else(|| {
            panic!(
                "reasoning left pending at EOF must be flushed as its own \
                 trailing message, not silently discarded: {:?}",
                s.messages
            )
        });
    assert_eq!(orphan.metadata.get("reasoning_encrypted"), None);
    assert_eq!(
        s.messages.last().map(|m| std::ptr::eq(m, orphan)),
        Some(true),
        "the trailing orphaned-reasoning message must be the LAST message"
    );
}

/// N4: `review_output.overall_correctness`/`overall_confidence_score` are
/// the review's actual verdict -- unique content distinct from `findings`
/// and `overall_explanation`, both already captured. The pre-fix loader
/// captured neither, and the audit doc stayed silent about them as residue
/// while `event_msg/exited_review_mode` was labeled `Coverage::Retained`.
/// This test fails against the pre-fix loader (neither metadata key is ever
/// populated).
#[test]
fn review_verdict_fields_are_captured_onto_review_message_metadata() {
    let codex = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"event_msg","payload":{"type":"exited_review_mode","review_output":{"findings":[],"overall_correctness":"needs_changes","overall_explanation":"one issue found","overall_confidence_score":0.83}}}
"#;
    let s = Session::from_codex_str(codex).unwrap();
    let review = s
        .messages
        .iter()
        .find(|m| {
            m.content
                .as_deref()
                .unwrap_or("")
                .starts_with("[code review]")
        })
        .expect("exited_review_mode must synthesize a [code review] message");
    assert_eq!(
        review
            .metadata
            .get("review_overall_correctness")
            .map(String::as_str),
        Some("needs_changes"),
        "overall_correctness must be captured (N4)"
    );
    assert_eq!(
        review
            .metadata
            .get("review_overall_confidence_score")
            .map(String::as_str),
        Some("0.83"),
        "overall_confidence_score must be captured (N4)"
    );
}

/// D8 (Fable-5 review, confirmed): a message with MULTIPLE `thinking`
/// blocks used to collapse to a single concatenated `thinking` string with
/// only the LAST block's `signature` retained — a real Anthropic signature
/// cryptographically covers only its own block's text, so re-emitting block
/// 1's text under block 2's signature (or dropping block 1's signature
/// entirely) produces a signature that will never verify. This is a
/// genuinely reasoning-only turn (no text/tool_use — matches the PARITY-11
/// standalone-thinking-turn shape) so the Claude Code semantic writer's
/// re-emission path is exercised, not just the loader. Fails against the
/// pre-fix loader/writer, which produced only ONE `thinking` block (with
/// `sig-2`, silently losing `sig-1`) on the round trip.
#[test]
fn claude_multiple_thinking_blocks_preserve_each_signature_separately() {
    let claude = r#"
{"type":"assistant","message":{"role":"assistant","content":[{"type":"thinking","thinking":"first thought","signature":"sig-1"},{"type":"thinking","thinking":"second thought","signature":"sig-2"}]},"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(claude).unwrap();
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .expect("the reasoning-only turn must survive as a message, not vanish");

    let blocks: serde_json::Value = a
        .metadata
        .get("thinking_blocks")
        .map(|s| serde_json::from_str(s).unwrap())
        .expect("multi-block messages must carry the exact per-block list");
    let blocks = blocks.as_array().expect("thinking_blocks must be an array");
    assert_eq!(
        blocks.len(),
        2,
        "both thinking blocks must be preserved: {blocks:#?}"
    );
    assert_eq!(blocks[0]["thinking"], serde_json::json!("first thought"));
    assert_eq!(blocks[0]["signature"], serde_json::json!("sig-1"));
    assert_eq!(blocks[1]["thinking"], serde_json::json!("second thought"));
    assert_eq!(
        blocks[1]["signature"],
        serde_json::json!("sig-2"),
        "sig-1 must NOT have been overwritten by sig-2: {blocks:#?}"
    );

    // Full round trip through the Claude Code semantic writer/loader: both
    // blocks, and BOTH signatures, must survive intact.
    let exported = s.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    let reloaded = Session::from_claude_code_str(&exported).unwrap();
    let a2 = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .expect("the reasoning-only turn must survive the writer round trip");
    let blocks2: serde_json::Value = a2
        .metadata
        .get("thinking_blocks")
        .map(|s| serde_json::from_str(s).unwrap())
        .expect("the reloaded message must still carry the exact per-block list");
    assert_eq!(
        blocks2.as_array(),
        Some(blocks),
        "both thinking blocks (and both signatures) must round-trip byte-for-byte: {blocks2:#?}"
    );

    // The exported wire line itself must literally contain BOTH signatures,
    // not just the last one.
    assert!(
        exported.contains("\"signature\":\"sig-1\"")
            && exported.contains("\"signature\":\"sig-2\""),
        "the exported Claude Code record must carry both signatures: {exported}"
    );
}

/// D8, redacted_thinking half: no `data` field on the source block must
/// never be re-emitted as a fabricated placeholder (the pre-fix code
/// defaulted a missing `data` to the literal string `"<redacted>"`, which
/// looks exactly like a real opaque payload to any downstream consumer).
#[test]
fn claude_redacted_thinking_without_data_is_not_fabricated() {
    let claude = r#"
{"type":"assistant","message":{"role":"assistant","content":[{"type":"redacted_thinking"}]},"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(claude).unwrap();
    let a = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .expect("a data-less redacted_thinking-only turn must still survive as a message");
    assert_ne!(
        a.metadata.get("redacted_thinking").map(String::as_str),
        Some("<redacted>"),
        "missing `data` must never be reported as the literal fabricated placeholder"
    );
    let blocks: serde_json::Value = a
        .metadata
        .get("thinking_blocks")
        .map(|s| serde_json::from_str(s).unwrap())
        .expect("the block must still be recorded in thinking_blocks");
    let block = &blocks.as_array().unwrap()[0];
    assert_eq!(block["type"], serde_json::json!("redacted_thinking"));
    assert!(
        block.get("data").is_none(),
        "a data-less block must have NO `data` key at all, not a fabricated one: {block:?}"
    );
}

// ---- 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 --------------------------

/// D3: `thread_goal_updated`/`entered_review_mode` use the REAL wire shapes
/// (camelCase, `threadId`, a full `ThreadGoal`; `target: {"type":
/// "uncommittedChanges"}`) — cross-checked against upstream `openai/codex`'s
/// `codex-rs/protocol/src/protocol.rs` (`ThreadGoalUpdatedEvent`,
/// `ThreadGoal`, `ThreadGoalStatus`, `ReviewTarget`). D4: `goal.status` and
/// `review_output.findings` (not just `objective`/`overall_explanation`) are
/// captured onto the synthesized messages' metadata, so
/// `crate::audit::Coverage::Retained` is no longer an over-claim for either
/// record type.
#[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","threadId":"019ec7e4-904f-76f0-91ff-76496e81237b","turnId":"019ec7e4-9050-76f0-91ff-000000000001","goal":{"threadId":"019ec7e4-904f-76f0-91ff-76496e81237b","objective":"Stabilize the orchestrator","status":"active","tokenBudget":50000,"tokensUsed":1200,"timeUsedSeconds":30,"createdAt":1781455700,"updatedAt":1781455724}}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"start review"}]}}
{"type":"event_msg","payload":{"type":"entered_review_mode","target":{"type":"uncommittedChanges"},"user_facing_hint":"start review"}}
{"type":"event_msg","payload":{"type":"exited_review_mode","review_output":{"findings":[{"title":"Nit","body":"Consider a comment here.","confidence_score":0.4,"priority":3,"code_location":{"absolute_file_path":"/tmp/src/lib.rs","line_range":{"start":1,"end":2}}}],"overall_correctness":"patch is correct","overall_explanation":"All good; no issues found.","overall_confidence_score":0.9}}}
"#;
    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}"
    );

    // D4: `goal.status`/`goal.tokenBudget` are captured onto the synthesized
    // system message's metadata, not just `objective`.
    let goal_msg = s
        .messages
        .iter()
        .find(|m| {
            m.content
                .as_deref()
                .is_some_and(|c| c.contains("[thread goal]"))
        })
        .expect("thread goal message");
    assert_eq!(
        goal_msg.metadata.get("goal_status").map(String::as_str),
        Some("active")
    );
    assert_eq!(
        goal_msg
            .metadata
            .get("goal_token_budget")
            .map(String::as_str),
        Some("50000")
    );

    // D4: `review_output.findings` are captured (verbatim JSON) onto the
    // synthesized code-review message's metadata, not just
    // `overall_explanation`.
    let review_msg = s
        .messages
        .iter()
        .find(|m| {
            m.content
                .as_deref()
                .is_some_and(|c| c.contains("[code review]"))
        })
        .expect("code review message");
    let findings_json = review_msg
        .metadata
        .get("review_findings")
        .expect("review_findings metadata");
    assert!(findings_json.contains("Nit") && findings_json.contains("confidence_score"));
}

// ---- 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_harness::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")
    );
}

/// D3 (Fable-5 review, confirmed): `write_codex_records` used to ALWAYS
/// fabricate a fresh `"sc-grp-N"` value for `metadata.turn_id` on export,
/// discarding whatever REAL `turn_id` a native-Codex-loaded message already
/// carried (loaded above, `codex_turn_id_preserved`). A native-Codex ->
/// load -> export-Codex hop therefore silently replaced the source tool's
/// own turn grouping id with a supercode-internal one — a real round-trip
/// fidelity loss, and a foot-gun for anything downstream keying off
/// `turn_id`. Fails against the pre-fix writer, which emits `"sc-grp-0"`
/// instead of `"turn-7"` here.
#[test]
fn codex_turn_id_preserved_through_export_round_trip() {
    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 exported = s.to_jsonl(SessionFormat::Codex).unwrap();
    assert!(
        exported.contains(r#""turn_id":"turn-7""#),
        "export must reuse the message's REAL turn_id verbatim, not drop it: {exported}"
    );
    assert!(
        !exported.contains("sc-grp-"),
        "export must NOT fabricate a synthetic turn_id when a real one is already present: {exported}"
    );

    let reloaded = Session::from_codex_str(&exported).unwrap();
    let a = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .unwrap();
    assert_eq!(
        a.metadata.get("turn_id").map(String::as_str),
        Some("turn-7"),
        "the original turn_id must survive a full load -> export -> reload hop"
    );
}

/// 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"
    );
}

/// CI-run, non-corpus-gated pin of the subagent linkage on the committed
/// fixture (SUP-21). Proves the full `attach_claude_subagents` path — file
/// discovery, agent-id recovery, and single-pass parent lookup — still
/// produces the same linkage the old per-subagent `parent_tool_use_for_agent`
/// rescan produced: fixture line 8 has a `tool_result` with
/// `tool_use_id = "toolu_01SYjhg9qRCzUWY2GTa3iazQ"` whose text mentions agent
/// id `ad8dc6cf98b49eea6`.
#[test]
fn claude_subagent_linked_to_pinned_tool_use_id() {
    let fixture_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
    let main_text = std::fs::read_to_string(fixture_dir.join("claude_code_session.jsonl")).unwrap();

    let tmp = std::env::temp_dir().join(format!("supercode-sup21-linkage-{}", std::process::id()));
    let subagents_dir = tmp.join("claude_code_session").join("subagents");
    std::fs::create_dir_all(&subagents_dir).unwrap();

    let main_path = tmp.join("claude_code_session.jsonl");
    std::fs::write(&main_path, &main_text).unwrap();

    // Minimal Claude-Code subagent line carrying its own agentId.
    let sub_line = r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"hi"}]},"agentId":"ad8dc6cf98b49eea6","sessionId":"sub"}"#;
    std::fs::write(
        subagents_dir.join("agent-ad8dc6cf98b49eea6.jsonl"),
        sub_line,
    )
    .unwrap();

    let session = Session::load(&main_path).unwrap();
    let _ = std::fs::remove_dir_all(&tmp);

    assert_eq!(session.subagents.len(), 1, "one subagent attached");
    let sub = &session.subagents[0];
    assert_eq!(
        sub.meta.agent_id.as_deref(),
        Some("ad8dc6cf98b49eea6"),
        "agent id recovered from the subagent file"
    );
    assert_eq!(
        sub.meta.parent_tool_use_id.as_deref(),
        Some("toolu_01SYjhg9qRCzUWY2GTa3iazQ"),
        "linked to the pinned parent Task tool_use_id"
    );
}

// ---- 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"));
    assert_eq!(
        call.function.parsed_arguments().unwrap(),
        serde_json::Value::String("*** Begin Patch ***".to_string()),
        "free-form custom-tool input must remain typed data, not invalid JSON"
    );

    let exported = s.to_jsonl(SessionFormat::Codex).unwrap();
    let exported_call = exported
        .lines()
        .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
        .find(|line| {
            line.pointer("/payload/type")
                .and_then(serde_json::Value::as_str)
                == Some("custom_tool_call")
        })
        .expect("Codex semantic export retains the custom-tool record type");
    assert_eq!(
        exported_call.pointer("/payload/input"),
        Some(&serde_json::Value::String(
            "*** Begin Patch ***".to_string()
        ))
    );

    for intermediate in [
        SessionFormat::ClaudeCode,
        SessionFormat::OpenCode,
        SessionFormat::Goose,
        SessionFormat::Pi,
        SessionFormat::Grok,
    ] {
        let foreign = s.to_jsonl(intermediate).unwrap();
        let foreign_session = Session::load_str(&foreign, intermediate).unwrap();
        let returned = foreign_session.to_jsonl(SessionFormat::Codex).unwrap();
        let returned_call = returned
            .lines()
            .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
            .find(|line| {
                line.pointer("/payload/type")
                    .and_then(serde_json::Value::as_str)
                    == Some("custom_tool_call")
            })
            .unwrap_or_else(|| panic!("{intermediate:?} hop lost the Codex custom-tool kind"));
        assert_eq!(
            returned_call.pointer("/payload/input"),
            Some(&serde_json::Value::String(
                "*** Begin Patch ***".to_string()
            )),
            "{intermediate:?} hop changed the free-form custom-tool input"
        );
    }

    // 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"
    );
}

// ---- D5: Files-API (unconvertible-source) image-only records must not ----
// ---- vanish (Fable-5 review, PARITY-11-class bug) --------------------------

/// D5 (confirmed): `image` is audited as `Coverage::Normalized`, but
/// `claude_image_block_to_part` only converts `base64`/`url` sources —
/// anything else (most notably the real Anthropic Files-API shape,
/// `{"type":"image","source":{"type":"file","file_id":"file_abc123"}}`)
/// returns `None`. Before this fix, an image-ONLY user record (no text
/// alongside it) therefore vanished ENTIRELY on load: `images` stayed empty
/// (nothing convertible), `text` stayed empty, and neither branch of
/// `push_claude_user`'s `if !images.is_empty() { .. } else if
/// !text.trim().is_empty() { .. }` fired — same failure shape as the
/// PARITY-11 reasoning-only-turn bug. Fails against the pre-fix loader
/// (which produced zero messages for this record).
#[test]
fn claude_user_files_api_image_only_does_not_vanish() {
    let jsonl = r#"
{"type":"user","message":{"role":"user","content":[{"type":"image","source":{"type":"file","file_id":"file_abc123"}}]},"sessionId":"s"}
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"got it"}]},"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(jsonl).unwrap();
    let user = s
        .messages
        .iter()
        .find(|m| m.role == Role::User)
        .expect("a Files-API image-only user record must survive as a message, not vanish");
    // No convertible image content: neither a data: URI content_parts entry
    // (the source was never base64/url) nor a silently-fabricated one.
    assert!(
        user.content_parts.is_none(),
        "no convertible image source exists to synthesize content_parts from: {user:?}"
    );
    assert!(
        user.content
            .as_deref()
            .is_some_and(|t| !t.trim().is_empty()),
        "the record must carry SOME visible marker instead of blank/absent content: {user:?}"
    );
    assert_eq!(
        user.metadata.get("image_source_unconvertible").map(String::as_str),
        Some("true"),
        "the audit-honesty flag must be set so callers know the image itself wasn't captured: {user:?}"
    );

    // Round-trips through Claude Code's own writer/loader without vanishing
    // again (the marker text takes the ordinary plain-string content path).
    let exported = s.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    let reloaded = Session::from_claude_code_str(&exported).unwrap();
    assert!(
        reloaded.messages.iter().any(|m| m.role == Role::User),
        "the placeholder user message must survive a full export/reload round trip: {reloaded:#?}"
    );
}

/// D5, assistant side: mirrors the user-side fix — an assistant record whose
/// ONLY content is an unconvertible-source image block (e.g. a generated
/// image referenced via the Files API) must not vanish either.
#[test]
fn claude_assistant_files_api_image_only_does_not_vanish() {
    let jsonl = r#"
{"type":"user","message":{"role":"user","content":"make an image"},"sessionId":"s"}
{"type":"assistant","message":{"role":"assistant","content":[{"type":"image","source":{"type":"file","file_id":"file_xyz789"}}]},"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(jsonl).unwrap();
    let assistant = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .expect("a Files-API image-only assistant record must survive as a message, not vanish");
    assert!(
        assistant
            .content
            .as_deref()
            .is_some_and(|t| !t.trim().is_empty()),
        "the record must carry SOME visible marker instead of blank/absent content: {assistant:?}"
    );
    assert_eq!(
        assistant
            .metadata
            .get("image_source_unconvertible")
            .map(String::as_str),
        Some("true"),
        "the audit-honesty flag must be set: {assistant:?}"
    );
}

// ---- IX-5: Claude Code / Codex serialize+parse content_parts (images) ----

/// A Claude Code user turn's own `image` content block (the exact native
/// shape Claude Code itself writes, `{"type":"image","source":{"type":
/// "base64",...}}`) must load into `content_parts`, not be silently skipped
/// — and survive a full export-then-reload through Claude Code's own writer.
/// Before the IX-5 fix, `push_claude_user`'s array match had no `"image"`
/// arm at all (`_ => {} // image / document / unknown — skip`), so the whole
/// message vanished whenever the leading text was empty, or the image was
/// silently dropped when text was present.
#[test]
fn claude_user_image_content_parts_survive_load_and_round_trip() {
    let jsonl = r#"
{"type":"user","message":{"role":"user","content":[{"type":"text","text":"look at this"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}]},"sessionId":"s"}
"#;
    let s = Session::from_claude_code_str(jsonl).unwrap();
    let msg = s
        .messages
        .iter()
        .find(|m| m.role == Role::User)
        .expect("user message must survive, not vanish");
    let parts = msg
        .content_parts
        .as_ref()
        .expect("image block must produce content_parts, not be dropped");
    assert!(
        parts.iter().any(
            |p| p.get("type").and_then(|v| v.as_str()) == Some("image_url")
                && p["image_url"]["url"] == "data:image/png;base64,aGVsbG8="
        ),
        "content_parts must carry the image as a data: URI with the exact mime/data: {parts:?}"
    );

    // Full export-then-reload through Claude Code's OWN writer/loader must
    // reproduce the same content_parts — the image survives a real resume.
    let exported = s.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    let reloaded = Session::from_claude_code_str(&exported).unwrap();
    let msg2 = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::User)
        .expect("reloaded user message");
    assert_eq!(
        msg.content_parts, msg2.content_parts,
        "content_parts must round-trip byte-identically through Claude Code's own writer/loader"
    );

    // A text-only user message (no content_parts) must still export the
    // historical plain-string `content` — the overriding IX-5 constraint.
    let text_only = Session::from_claude_code_str(
        r#"{"type":"user","message":{"role":"user","content":"just text"},"sessionId":"s"}"#,
    )
    .unwrap();
    let out = text_only.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    let line: serde_json::Value = serde_json::from_str(out.lines().next().unwrap()).unwrap();
    assert_eq!(
        line["message"]["content"],
        serde_json::json!("just text"),
        "text-only content must stay a plain string, not become a content array"
    );
}

/// Codex's native `input_image` message-content block must load into
/// `content_parts`, and a full export-then-reload through Codex's own
/// writer/loader must reproduce it — the loader/writer-side proof for IX-5's
/// second format. Before the fix, `push_codex_item`'s `"message"` arm only
/// called `extract_text_content` (never inspected `input_image` blocks) and
/// `push_codex_message` only ever wrote `msg.content` — a codex-native or
/// translated-in image was dropped in both directions.
#[test]
fn codex_user_image_content_parts_survive_load_and_round_trip() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"look at this"},{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let msg = s
        .messages
        .iter()
        .find(|m| m.role == Role::User)
        .expect("user message must survive, not vanish");
    let parts = msg
        .content_parts
        .as_ref()
        .expect("input_image block must produce content_parts, not be dropped");
    assert!(
        parts.iter().any(
            |p| p.get("type").and_then(|v| v.as_str()) == Some("image_url")
                && p["image_url"]["url"] == "data:image/png;base64,aGVsbG8="
        ),
        "content_parts must carry the image data: URI verbatim: {parts:?}"
    );

    let exported = s.to_jsonl(SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&exported).unwrap();
    let msg2 = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::User)
        .expect("reloaded user message");
    assert_eq!(
        msg.content_parts, msg2.content_parts,
        "content_parts must round-trip byte-identically through Codex's own writer/loader"
    );

    // Text-only stays exactly the historical single `{"type":"input_text",...}`
    // block — the overriding IX-5 constraint.
    let text_only = Session::from_codex_str(
        r#"{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"just text"}]}}"#,
    )
    .unwrap();
    let out = text_only.to_jsonl(SessionFormat::Codex).unwrap();
    let line = out
        .lines()
        .find(|l| l.contains("\"role\":\"user\""))
        .expect("exported user message line");
    let v: serde_json::Value = serde_json::from_str(line).unwrap();
    assert_eq!(
        v["payload"]["content"],
        serde_json::json!([{"type": "input_text", "text": "just text"}]),
        "text-only content must stay the single historical input_text block"
    );
}

// ---- PARITY-11: nested images inside a Claude `tool_result` ---------------
//
// The IX-5 tests above cover only TOP-LEVEL message images
// (`push_claude_user`'s own `image` content-block arm). A real, everyday
// Claude Code shape — "Read a PNG / screenshot tool output" — instead nests
// the `image` block INSIDE a `tool_result`'s own `content` array
// (`{"type":"tool_result","content":[{"type":"image",...}]}`), which the old
// `extract_tool_result` flattened to the bare, unrecoverable `[image]` marker
// text regardless of whether the source was a genuine, well-formed base64
// image — skeptic-confirmed on a real session
// (`~/.claude/projects/.../58cfec80-*.jsonl`, 4 real 295-565KB screenshots,
// all four reduced to `[image]` by `convert --to pi`/`--to opencode`/
// `--to codex` before this fix, INCLUDING pi/opencode which both have a real
// slot to carry image data). A genuine 1x1 PNG (not a placeholder string) so
// this proves real base64 round-trips, not just marker text.
const PARITY11_TINY_PNG_B64: &str =
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mNgAAACAAFVvzDOAAAAAElFTkSuQmCC";

fn parity11_nested_image_jsonl() -> String {
    format!(
        r#"
{{"type":"assistant","message":{{"role":"assistant","content":[{{"type":"tool_use","id":"toolu_01SHOT","name":"Read","input":{{"file_path":"/tmp/screenshot.png"}}}}]}},"sessionId":"s"}}
{{"type":"user","message":{{"role":"user","content":[{{"type":"tool_result","tool_use_id":"toolu_01SHOT","content":[{{"type":"text","text":"Here is the screenshot:"}},{{"type":"image","source":{{"type":"base64","media_type":"image/png","data":"{PARITY11_TINY_PNG_B64}"}}}}]}}]}},"sessionId":"s"}}
"#
    )
}

/// The loader must capture the nested image into `content_parts` (not the
/// old bare `[image]` marker), and a full export-then-reload through Claude
/// Code's OWN writer/loader (`claude_tool_result_content_value`, the
/// `write_claude_code_records`/`push_claude_user` pair) must reproduce it
/// byte-identically — the same "loader captures, writer/loader round-trips"
/// proof IX-5 established for top-level images, now extended to the nested
/// case. Fails against `parity/integrated-v3@e7b15fd`, where
/// `extract_tool_result`'s `Some("image") => parts.push("[image]")` arm had
/// no `content_parts` slot at all.
#[test]
fn claude_tool_result_nested_image_survives_load_and_round_trip() {
    let s = Session::from_claude_code_str(&parity11_nested_image_jsonl()).unwrap();
    let tool = s
        .messages
        .iter()
        .find(|m| m.role == Role::Tool)
        .expect("tool_result message must survive");
    assert_eq!(
        tool.content.as_deref(),
        Some("Here is the screenshot:"),
        "the sibling text block must still be captured as plain content"
    );
    let parts = tool
        .content_parts
        .as_ref()
        .expect("nested image must produce content_parts, not the old bare [image] marker");
    let expected_uri = format!("data:image/png;base64,{PARITY11_TINY_PNG_B64}");
    assert!(
        parts.iter().any(
            |p| p.get("type").and_then(|v| v.as_str()) == Some("image_url")
                && p["image_url"]["url"] == expected_uri
        ),
        "content_parts must carry the exact base64 payload as a data: URI, \
         recoverable — not a lossy marker: {parts:?}"
    );
    assert!(
        !tool.content.as_deref().unwrap_or("").contains("[image]"),
        "the old lossy bare marker must not appear once the image is captured: {:?}",
        tool.content
    );

    // Full export-then-reload through Claude Code's OWN writer/loader must
    // reproduce the same content_parts.
    let exported = s.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    let reloaded = Session::from_claude_code_str(&exported).unwrap();
    let tool2 = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::Tool)
        .expect("reloaded tool_result message");
    assert_eq!(
        tool.content_parts, tool2.content_parts,
        "content_parts (the nested image) must round-trip byte-identically \
         through Claude Code's own writer/loader"
    );

    // A tool_result with no image at all must still export the historical
    // plain-string `content` — the overriding IX-5-style constraint applied
    // to the writer's Tool arm (`claude_tool_result_content_value`).
    let text_only = Session::from_claude_code_str(
        r#"
{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t9","name":"Bash","input":{}}]},"sessionId":"s"}
{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t9","content":"ok"}]},"sessionId":"s"}
"#,
    )
    .unwrap();
    let out = text_only.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    let line = out
        .lines()
        .find(|l| l.contains("tool_result"))
        .expect("exported tool_result line");
    let v: serde_json::Value = serde_json::from_str(line).unwrap();
    assert_eq!(
        v["message"]["content"][0]["content"],
        serde_json::json!("ok"),
        "an image-free tool_result must stay a plain string, not become a content array"
    );
}

/// A nested tool_result image must survive a Claude -> Pi hop: pi's own
/// `toolResult` writer (`pi_content_value`, shared with `user`) already
/// re-emits `content_parts` as `ImageContent` blocks — this test proves the
/// LOADER side (`extract_tool_result_content` populating `content_parts` in
/// the first place) is what was actually missing, by exporting through
/// Session::to_jsonl(Pi) and reloading through pi's own loader
/// (`push_pi_tool_result`) to confirm the exact bytes survive an actual
/// cross-format hop, not just an in-memory `content_parts` check.
#[test]
fn claude_tool_result_nested_image_survives_claude_to_pi() {
    let s = Session::from_claude_code_str(&parity11_nested_image_jsonl()).unwrap();
    let exported = s.to_jsonl(SessionFormat::Pi).unwrap();
    assert!(
        !exported.contains("[image]"),
        "pi export must not contain the old lossy bare marker: {exported}"
    );
    // D-mix (Fable must-fix): the pi `toolResult` writer (`pi_content_value`)
    // reads ONLY `content_parts` — it never falls back to `msg.content` — so
    // the sibling TEXT of this mixed text+image tool_result must itself be
    // captured as a `content_parts` text part upstream (`push_claude_user`),
    // or it silently vanishes on this exact hop even though the image
    // survives. Assert the raw exported bytes carry the text before even
    // reloading, so a regression here fails loudly at the JSON level.
    assert!(
        exported.contains("Here is the screenshot:"),
        "pi export must still carry the sibling text of the mixed \
         text+image tool_result, not just the image: {exported}"
    );
    let reloaded = Session::from_pi_str(&exported).unwrap();
    let tool = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::Tool)
        .expect("pi toolResult message must survive reload");
    let parts = tool
        .content_parts
        .as_ref()
        .expect("image must survive the Claude -> Pi hop as content_parts");
    assert!(
        parts.iter().any(|p| {
            p.get("type").and_then(|v| v.as_str()) == Some("image_url")
                && p["image_url"]["url"]
                    == serde_json::json!(format!("data:image/png;base64,{PARITY11_TINY_PNG_B64}"))
        }),
        "the exact base64 payload must be recoverable after the Claude -> Pi hop: {parts:?}"
    );
    // BOTH the text and the image must be recoverable from the reloaded
    // message — this is the actual regression: base e7b15fd preserved the
    // text (it only lost the image); B2 flipped that, preserving the image
    // but losing the text on this exact hop.
    assert_eq!(
        tool.content.as_deref(),
        Some("Here is the screenshot:"),
        "the sibling text must survive the Claude -> Pi hop's own loader \
         (`push_pi_tool_result`), not just the image: {tool:?}"
    );
}

/// The mixed text+image shape end-to-end, asserting BOTH halves survive in
/// one place: this is the exact fixture shape (`parity11_nested_image_jsonl`)
/// a real MCP screenshot tool / computer-use tool_result produces. Fails
/// against `parity/parity11-nested-images@71e9ba9` (B2), which built
/// `content_parts` as `[image]`-only (never prepending the text part), so
/// `pi_content_value` — which reads exclusively from `content_parts` for a
/// `Role::Tool` message — silently dropped the text on this hop even though
/// the image survived.
#[test]
fn claude_mixed_text_and_image_tool_result_survives_claude_to_pi() {
    let s = Session::from_claude_code_str(&parity11_nested_image_jsonl()).unwrap();
    let tool = s
        .messages
        .iter()
        .find(|m| m.role == Role::Tool)
        .expect("tool_result message must survive load");
    let parts = tool
        .content_parts
        .as_ref()
        .expect("mixed tool_result must produce content_parts");
    assert_eq!(
        parts
            .first()
            .and_then(|p| p.get("type"))
            .and_then(|t| t.as_str()),
        Some("text"),
        "content_parts must be self-contained: the text must be part 0, \
         mirroring `pi_content_to_text_and_parts`/`push_opencode_user`: {parts:?}"
    );
    assert_eq!(
        parts
            .first()
            .and_then(|p| p.get("text"))
            .and_then(|t| t.as_str()),
        Some("Here is the screenshot:"),
        "the leading content_parts text part must carry the exact sibling text: {parts:?}"
    );

    let exported = s.to_jsonl(SessionFormat::Pi).unwrap();
    let reloaded = Session::from_pi_str(&exported).unwrap();
    let reloaded_tool = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::Tool)
        .expect("pi toolResult message must survive reload");
    assert_eq!(
        reloaded_tool.content.as_deref(),
        Some("Here is the screenshot:"),
        "text must survive the full Claude -> Pi hop"
    );
    let reloaded_parts = reloaded_tool
        .content_parts
        .as_ref()
        .expect("image must survive the full Claude -> Pi hop");
    assert!(
        reloaded_parts.iter().any(|p| {
            p.get("type").and_then(|v| v.as_str()) == Some("image_url")
                && p["image_url"]["url"]
                    == serde_json::json!(format!("data:image/png;base64,{PARITY11_TINY_PNG_B64}"))
        }),
        "image must ALSO survive the full Claude -> Pi hop, alongside the text: {reloaded_parts:?}"
    );
}

/// A nested tool_result image must survive a Claude -> OpenCode hop: the
/// LOADER already read a completed tool part's `state.attachments` back into
/// `content_parts` (`opencode_file_image_part`) — what was missing is the
/// WRITE-side inverse in `append_synthesized_opencode_messages`'s `Role::Tool`
/// result handling, which never read `content_parts` back out onto
/// `state.attachments` at all before this fix. Proven end-to-end: export
/// through `Session::to_jsonl(OpenCode)`, parse the resulting export
/// document directly (opencode's synthesis is JSON-document shaped, not
/// line-oriented), and confirm the `mime`/`url` attachment carries the exact
/// base64 payload.
#[test]
fn claude_tool_result_nested_image_survives_claude_to_opencode() {
    let s = Session::from_claude_code_str(&parity11_nested_image_jsonl()).unwrap();
    let exported = s.to_jsonl(SessionFormat::OpenCode).unwrap();
    assert!(
        !exported.contains("[image]"),
        "opencode export must not contain the old lossy bare marker: {exported}"
    );
    // D-mix (Fable must-fix): the opencode writer's `Role::Tool` arm reads
    // the text from `msg.content` (unaffected by this fix) and only scans
    // `content_parts` for `image_url` entries, so the opencode WRITE side was
    // never the bug — but assert it explicitly here anyway so this test
    // covers the full mixed-shape claim end to end, symmetric with the pi
    // test above.
    assert!(
        exported.contains("Here is the screenshot:"),
        "opencode export must still carry the sibling text of the mixed \
         text+image tool_result, not just the image: {exported}"
    );
    let doc: serde_json::Value = serde_json::from_str(&exported).unwrap();
    let messages = doc["messages"].as_array().expect("messages array");
    let mut found = false;
    let mut found_text = false;
    for m in messages {
        let Some(parts) = m["parts"].as_array() else {
            continue;
        };
        for p in parts {
            if p.get("type").and_then(|v| v.as_str()) != Some("tool") {
                continue;
            }
            if p["state"]["output"].as_str() == Some("Here is the screenshot:") {
                found_text = true;
            }
            if let Some(atts) = p["state"]["attachments"].as_array() {
                for a in atts {
                    if a.get("mime").and_then(|v| v.as_str()) == Some("image/png")
                        && a.get("url").and_then(|v| v.as_str())
                            == Some(&format!("data:image/png;base64,{PARITY11_TINY_PNG_B64}"))
                    {
                        found = true;
                    }
                }
            }
        }
    }
    assert!(
        found,
        "the exact base64 payload must be recoverable as a `state.attachments` \
         entry after the Claude -> OpenCode hop: {exported}"
    );
    assert!(
        found_text,
        "the sibling text must be recoverable as `state.output` after the \
         Claude -> OpenCode hop, alongside the image attachment: {exported}"
    );
}

/// The opencode TOOL LOADER'S own hybrid shape (`state.output` text +
/// `state.attachments` images on a completed tool part, PRE-EXISTING — a
/// native opencode session, not one imported from Claude) must build a
/// self-contained `content_parts` (text prepended as part 0) the same way
/// `push_claude_user`'s tool_result arm now does, so an opencode -> pi hop
/// doesn't drop the text either (`pi_content_value` reads exclusively from
/// `content_parts` for a `Role::Tool` message). Fails against
/// `parity/parity11-nested-images@71e9ba9`, whose opencode tool loader built
/// `content_parts` as images-only.
#[test]
fn opencode_native_tool_result_mixed_text_and_image_survives_to_pi() {
    let session_json = serde_json::json!({
        "info": {"id": "s", "title": "t", "time": {"created": 1, "updated": 1}},
        "messages": [
            {
                "info": {"id": "m1", "sessionID": "s", "role": "assistant", "time": {"created": 1}},
                "parts": [
                    {
                        "id": "p1", "sessionID": "s", "messageID": "m1", "type": "tool",
                        "callID": "call_1", "tool": "screenshot",
                        "state": {
                            "status": "completed",
                            "input": {},
                            "output": "Here is the screenshot:",
                            "time": {"end": 1},
                            "attachments": [
                                {
                                    "mime": "image/png",
                                    "url": format!("data:image/png;base64,{PARITY11_TINY_PNG_B64}"),
                                }
                            ],
                        },
                    }
                ],
            }
        ],
    })
    .to_string();
    let s = Session::from_opencode_str(&session_json).unwrap();
    let tool = s
        .messages
        .iter()
        .find(|m| m.role == Role::Tool)
        .expect("native opencode tool_result message must survive load");
    let parts = tool
        .content_parts
        .as_ref()
        .expect("mixed output+attachments must produce content_parts");
    assert_eq!(
        parts
            .first()
            .and_then(|p| p.get("type"))
            .and_then(|t| t.as_str()),
        Some("text"),
        "content_parts must be self-contained: the text must be part 0: {parts:?}"
    );

    let exported = s.to_jsonl(SessionFormat::Pi).unwrap();
    assert!(
        exported.contains("Here is the screenshot:"),
        "pi export must carry the text from the native opencode tool part: {exported}"
    );
    let reloaded = Session::from_pi_str(&exported).unwrap();
    let reloaded_tool = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::Tool)
        .expect("pi toolResult message must survive reload");
    assert_eq!(
        reloaded_tool.content.as_deref(),
        Some("Here is the screenshot:"),
        "text must survive the full OpenCode -> Pi hop"
    );
    let reloaded_parts = reloaded_tool
        .content_parts
        .as_ref()
        .expect("image must survive the full OpenCode -> Pi hop");
    assert!(
        reloaded_parts.iter().any(|p| {
            p.get("type").and_then(|v| v.as_str()) == Some("image_url")
                && p["image_url"]["url"]
                    == serde_json::json!(format!("data:image/png;base64,{PARITY11_TINY_PNG_B64}"))
        }),
        "image must ALSO survive the full OpenCode -> Pi hop: {reloaded_parts:?}"
    );
}

/// Codex's `function_call_output` response_item has a BARE-STRING `output`
/// field, so the stock field carries an honest residue disclosure while the
/// existing namespaced portability envelope retains the structured image for
/// a reversible supercode round trip.
#[test]
fn claude_tool_result_nested_image_codex_reversible_residue() {
    let s = Session::from_claude_code_str(&parity11_nested_image_jsonl()).unwrap();
    let exported = s.to_jsonl(SessionFormat::Codex).unwrap();
    assert!(
        !exported.contains("\"output\":\"[image]\""),
        "must not silently re-emit the old ambiguous bare marker: {exported}"
    );
    let line = exported
        .lines()
        .find(|l| l.contains("function_call_output"))
        .expect("exported function_call_output line");
    let value: serde_json::Value = serde_json::from_str(line).unwrap();
    assert!(
        !value["payload"]["output"]
            .as_str()
            .unwrap_or_default()
            .contains(PARITY11_TINY_PNG_B64),
        "the stock Codex output string must remain text-only"
    );
    assert!(
        line.contains("nested image(s) dropped"),
        "the dropped image must be disclosed honestly, not silently: {line}"
    );
    // The sibling text is still carried alongside the disclosure.
    assert!(
        line.contains("Here is the screenshot:"),
        "the text portion of the tool_result must still be preserved: {line}"
    );
    let reloaded = Session::from_codex_str(&exported).unwrap();
    let reloaded_tool = reloaded
        .messages
        .iter()
        .find(|message| message.role == Role::Tool)
        .expect("tool result survives Codex reload");
    assert_eq!(reloaded_tool.content, s.messages[1].content);
    assert_eq!(reloaded_tool.content_parts, s.messages[1].content_parts);
}

// ---- IX-6: Codex loader merges a combined text+tool-call turn -------------

/// A `message`(assistant text) response_item directly followed by a
/// `function_call` response_item in the SAME turn — Codex's own equivalent
/// of a combined text+tool-call turn — must load as ONE `ChatMessage`
/// (text→`content`, call→`tool_calls`), matching how Claude's parser keeps a
/// multi-block turn together. Before the fix, `push_codex_item`'s
/// `"function_call"` arm always called `push_assistant` with a fresh
/// message, splitting this into two.
#[test]
fn codex_combined_text_and_tool_call_turn_merges_into_one_message() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Sure."}]}}
{"type":"response_item","payload":{"type":"function_call","call_id":"c1","name":"bash","arguments":"{}"}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let assistants: Vec<&supercode_harness::ChatMessage> = s
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .collect();
    assert_eq!(
        assistants.len(),
        1,
        "text+tool-call in one turn must merge into ONE message, not split: {:#?}",
        s.messages
    );
    assert_eq!(assistants[0].content.as_deref(), Some("Sure."));
    assert_eq!(assistants[0].tool_calls().len(), 1);
    assert_eq!(assistants[0].tool_calls()[0].id, "c1");
    assert_eq!(assistants[0].tool_calls()[0].function.name, "bash");

    // No `__codex_open_turn` (or any other internal-only) bookkeeping key
    // leaks into visible metadata.
    assert!(
        !assistants[0].metadata.contains_key("__codex_open_turn"),
        "internal merge marker must be stripped before the session is returned"
    );

    // The merge must survive Codex's own writer/loader round trip too — the
    // writer re-splits into the real two-item shape on export (Codex's
    // on-disk format genuinely has separate message+function_call items),
    // and the loader remerges them back on reload.
    let exported = s.to_jsonl(SessionFormat::Codex).unwrap();
    assert!(
        exported.contains("\"type\":\"message\"")
            && exported.contains("\"type\":\"function_call\""),
        "writer must still emit codex's real two-item shape: {exported}"
    );
    let reloaded = Session::from_codex_str(&exported).unwrap();
    let reloaded_assistants: Vec<&supercode_harness::ChatMessage> = reloaded
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .collect();
    assert_eq!(
        reloaded_assistants.len(),
        1,
        "round trip must still merge into ONE message: {:#?}",
        reloaded.messages
    );
    assert_eq!(reloaded_assistants[0].content.as_deref(), Some("Sure."));
    assert_eq!(reloaded_assistants[0].tool_calls().len(), 1);
}

/// A BARE `function_call` with no preceding same-turn assistant text (the
/// ordinary/majority shape in real Codex sessions) must NOT be affected by
/// the IX-6 merge — it still gets its own synthesized message, exactly as
/// before the fix.
#[test]
fn codex_bare_function_call_with_no_preceding_text_is_unaffected_by_ix6_merge() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"function_call","call_id":"c1","name":"bash","arguments":"{}"}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let assistants: Vec<&supercode_harness::ChatMessage> = s
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .collect();
    assert_eq!(assistants.len(), 1);
    assert_eq!(
        assistants[0].content, None,
        "a bare tool call carries no text"
    );
    assert_eq!(assistants[0].tool_calls().len(), 1);
}

/// A genuine turn boundary (a `user` message between the assistant text and
/// the later tool call) must NOT be merged across — IX-6's merge is scoped
/// to the SAME turn only.
#[test]
fn codex_function_call_does_not_merge_across_a_genuine_turn_boundary() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Sure."}]}}
{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"go"}]}}
{"type":"response_item","payload":{"type":"function_call","call_id":"c1","name":"bash","arguments":"{}"}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let assistant_text = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant && m.content.as_deref() == Some("Sure."))
        .expect("the earlier assistant text turn");
    assert!(
        assistant_text.tool_calls().is_empty(),
        "the tool call belongs to a LATER turn (separated by a user message) and must not merge \
         into the earlier text-only turn: {assistant_text:?}"
    );
    // The tool call still gets its own (bare) message.
    let call_msg = s
        .messages
        .iter()
        .find(|m| !m.tool_calls().is_empty())
        .expect("the function_call's own message");
    assert_eq!(call_msg.content, None);
}

/// Skeptic-confirmed negative (a): `thread_rolled_back` → `remove_last_turn`
/// truncates the vector, which can re-expose a PRIOR assistant text turn
/// (the predecessor of the rolled-back turn) as `out.last()` again — and
/// that prior turn is still carrying its `__codex_open_turn` marker from
/// when it was first created (it just wasn't `out.last()` at that time,
/// since the now-removed turn came after it). A bare `function_call`
/// arriving after the rollback is a genuinely NEW turn and must NOT merge
/// into that stale marked tail.
#[test]
fn codex_rollback_then_bare_function_call_does_not_merge_into_prior_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}}
{"type":"response_item","payload":{"type":"function_call","call_id":"c1","name":"bash","arguments":"{}"}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();

    let kept = s
        .messages
        .iter()
        .find(|m| m.content.as_deref() == Some("kept answer"))
        .expect("pre-rollback assistant turn survives the rollback");
    assert!(
        kept.tool_calls().is_empty(),
        "the post-rollback function_call must NOT merge into the \
         pre-rollback assistant turn just because truncation re-exposed it \
         as out.last(): {kept:?}"
    );

    // The rolled-back turn is gone.
    assert!(
        !s.messages
            .iter()
            .any(|m| m.content.as_deref() == Some("answer to be undone")),
        "{:#?}",
        s.messages
    );

    // The function_call gets its own independent (bare) message.
    let call_msg = s
        .messages
        .iter()
        .find(|m| !m.tool_calls().is_empty())
        .expect("the function_call's own message");
    assert_eq!(
        call_msg.content, None,
        "the new turn after rollback carries no text of its own"
    );
    assert_eq!(call_msg.tool_calls().len(), 1);
    assert_eq!(call_msg.tool_calls()[0].id, "c1");
}

/// Skeptic-confirmed negative (b): a `compacted` record replays
/// `replacement_history` through `push_codex_item`, which can leave the
/// LAST replayed message (the compaction summary, if it's an assistant
/// `message`) marked `__codex_open_turn`. A live `function_call` arriving
/// after the compaction boundary is a NEW turn (not a continuation of the
/// summary) and must NOT merge into it.
#[test]
fn codex_compacted_then_bare_function_call_does_not_merge_into_summary_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 question"}]}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ORIGINAL answer"}]}}
{"type":"compacted","payload":{"message":"","replacement_history":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"SUMMARY of the conversation so far"}]}]}}
{"type":"response_item","payload":{"type":"function_call","call_id":"c1","name":"bash","arguments":"{}"}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();

    let summary = s
        .messages
        .iter()
        .find(|m| m.content.as_deref() == Some("SUMMARY of the conversation so far"))
        .expect("the compaction summary turn is retained");
    assert!(
        summary.tool_calls().is_empty(),
        "the post-compaction function_call must NOT merge into the \
         compaction-summary assistant turn: {summary:?}"
    );

    // The pre-compaction turns are gone (existing `compacted` semantics).
    assert!(
        !s.messages
            .iter()
            .any(|m| m.content.as_deref() == Some("ORIGINAL answer")),
        "{:#?}",
        s.messages
    );

    // The function_call gets its own independent (bare) message.
    let call_msg = s
        .messages
        .iter()
        .find(|m| !m.tool_calls().is_empty())
        .expect("the function_call's own message");
    assert_eq!(
        call_msg.content, None,
        "the new turn after compaction carries no text of its own"
    );
    assert_eq!(call_msg.tool_calls().len(), 1);
    assert_eq!(call_msg.tool_calls()[0].id, "c1");
}

// ---- IX-5/IX-6 follow-up: Codex writer must not drop an image-only or ----
// ---- text+image ASSISTANT message ----------------------------------------

/// Confirmed defect: `write_codex_records`'s `Role::Assistant` arm gated the
/// message-record emission on `msg.content` alone (`if let Some(t) =
/// &msg.content { if !t.is_empty() { ... } }`). Since `codex_extract_images`
/// is role-general (IX-5), the LOADER can produce an assistant `ChatMessage`
/// with `content: None, content_parts: Some([image])` — and the writer's
/// content-only gate then emitted NO record at all for it, silently dropping
/// the whole assistant turn (image included) on export. This proves an
/// image-only assistant message now round-trips byte-exact through Codex's
/// own writer/loader.
#[test]
fn codex_assistant_image_only_message_survives_writer_round_trip() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let msg = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .expect("image-only assistant message must survive load, not vanish");
    assert_eq!(
        msg.content, None,
        "image-only assistant message carries no plain-text content"
    );
    let parts = msg
        .content_parts
        .as_ref()
        .expect("input_image block must produce content_parts");
    assert!(
        parts.iter().any(
            |p| p.get("type").and_then(|v| v.as_str()) == Some("image_url")
                && p["image_url"]["url"] == "data:image/png;base64,aGVsbG8="
        ),
        "content_parts must carry the image data: URI verbatim: {parts:?}"
    );

    // Before the fix, this export dropped the assistant message record
    // entirely (`write_codex_records` never called `push_codex_message` for
    // it), so reload produced ZERO assistant messages.
    let exported = s.to_jsonl(SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&exported).unwrap();
    let msg2 = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .expect(
            "the assistant image message must NOT vanish across the codex writer/loader round trip",
        );
    assert_eq!(
        msg.content_parts, msg2.content_parts,
        "content_parts (the image) must round-trip byte-identically"
    );
}

/// Same defect, text+image variant: an assistant message with BOTH a text
/// part and an image part must also round-trip (not just the image-only
/// case) — `codex_message_content_blocks` already emits both blocks once the
/// writer actually calls it.
#[test]
fn codex_assistant_text_and_image_message_survives_writer_round_trip() {
    let jsonl = r#"
{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"here you go"},{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]}}
"#;
    let s = Session::from_codex_str(jsonl).unwrap();
    let msg = s
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .expect("text+image assistant message must survive load");
    assert!(msg.content_parts.is_some());

    let exported = s.to_jsonl(SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&exported).unwrap();
    let msg2 = reloaded
        .messages
        .iter()
        .find(|m| m.role == Role::Assistant)
        .expect("the assistant text+image message must not vanish on round trip");
    assert_eq!(
        msg.content_parts, msg2.content_parts,
        "content_parts (text block + image block) must round-trip byte-identically"
    );
}

/// Overriding constraint check: the FIX #2 gate change (`has_text ||
/// content_parts.is_some()`) must NOT alter behavior for the two shapes that
/// already worked — a text-only assistant message stays byte-identical to
/// its historical single `output_text` block export, and a bare
/// tool-call-only assistant message (content: None, content_parts: None)
/// still emits ZERO message record (no spurious empty `"type":"message"`
/// line before its `function_call`).
#[test]
fn codex_assistant_text_only_and_tool_call_only_writer_output_unchanged() {
    // Text-only: exact historical single-block shape.
    let text_only = Session::from_codex_str(
        r#"{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"just text"}]}}"#,
    )
    .unwrap();
    let out = text_only.to_jsonl(SessionFormat::Codex).unwrap();
    let line = out
        .lines()
        .find(|l| l.contains("\"role\":\"assistant\""))
        .expect("exported assistant message line");
    let v: serde_json::Value = serde_json::from_str(line).unwrap();
    assert_eq!(
        v["payload"]["content"],
        serde_json::json!([{"type": "output_text", "text": "just text"}]),
        "text-only assistant content must stay the single historical output_text block"
    );

    // Tool-call-only: no message record at all, only the function_call.
    let tool_call_only = Session::from_codex_str(
        r#"{"type":"session_meta","payload":{"id":"s","cwd":"/tmp"}}
{"type":"response_item","payload":{"type":"function_call","call_id":"c1","name":"bash","arguments":"{}"}}"#,
    )
    .unwrap();
    let out = tool_call_only.to_jsonl(SessionFormat::Codex).unwrap();
    assert!(
        !out.contains("\"role\":\"assistant\""),
        "a bare tool-call-only assistant message must emit ZERO message \
         record (no spurious empty assistant message line): {out}"
    );
    assert!(
        out.contains("\"type\":\"function_call\""),
        "the function_call itself must still be emitted: {out}"
    );
}

// ---- WAVE-2 item 1: real per-message timestamps, SYNTH_TS fallback --------

/// A message with NO source timestamp at all (`metadata` carries no
/// `timestamp` key) is exactly what a synthesized/appended continuation turn
/// looks like — e.g. a fresh `ChatMessage::user`/`::assistant`/`::tool_result`
/// the live agent loop produces after import, never having been loaded from
/// any per-message timestamp field. Every writer's fallback for that case is
/// the frozen `SYNTH_TS`/`SYNTH_TS_MS` placeholder — asserted here, per
/// format, deterministic (byte-identical across two independent synthesis
/// calls) and panic-free, so this doesn't regress silently into some other
/// default (a real wall-clock read, an empty string, ...).
#[test]
fn synthesized_message_with_no_source_timestamp_falls_back_to_synth_ts() {
    let mut session = Session::from_claude_code_str("").unwrap();
    session.messages = vec![
        ChatMessage::user("hello"),
        ChatMessage::assistant("hi there"),
        ChatMessage::tool_result("t1", "some_tool", "tool output"),
    ];
    assert!(
        session
            .messages
            .iter()
            .all(|m| !m.metadata.contains_key("timestamp")),
        "sanity: none of these synthesized messages carry a source timestamp"
    );

    for format in [
        SessionFormat::ClaudeCode,
        SessionFormat::Codex,
        SessionFormat::Pi,
        SessionFormat::OpenCode,
    ] {
        let out1 = session.to_jsonl(format).unwrap();
        let out2 = session.to_jsonl(format).unwrap();
        assert_eq!(
            out1, out2,
            "{format:?}: SYNTH_TS fallback must be deterministic across runs"
        );
        match format {
            SessionFormat::ClaudeCode
            | SessionFormat::Codex
            | SessionFormat::Gemini
            | SessionFormat::Pi => {
                assert!(
                    out1.contains("2026-01-01T00:00:00.000Z"),
                    "{format:?}: a message with no source timestamp must fall back to \
                     the SYNTH_TS placeholder: {out1}"
                );
            }
            SessionFormat::OpenCode => {
                assert!(
                    out1.contains("1767225600000"),
                    "{format:?}: a message with no source timestamp must fall back to \
                     the SYNTH_TS_MS placeholder: {out1}"
                );
            }
            SessionFormat::Grok => {
                // Grok's chat_history records carry no per-message timestamp.
            }
            SessionFormat::Goose => {
                assert!(
                    out1.contains("1767225600"),
                    "{format:?}: missing deterministic synthesized timestamp: {out1}"
                );
            }
        }
        // The fallback path must never panic or emit malformed output.
        // OpenCode's writer emits one pretty-printed JSON document (not
        // JSONL like the other three), so it's parsed as a whole; the rest
        // are one JSON object per line.
        if matches!(format, SessionFormat::OpenCode | SessionFormat::Goose) {
            serde_json::from_str::<serde_json::Value>(&out1)
                .unwrap_or_else(|e| panic!("{format:?}: invalid JSON document ({e}): {out1}"));
        } else {
            for line in out1.lines().filter(|l| !l.trim().is_empty()) {
                serde_json::from_str::<serde_json::Value>(line)
                    .unwrap_or_else(|e| panic!("{format:?}: invalid JSON line ({e}): {line}"));
            }
        }
    }
}

/// The flip side: when a message DOES carry a real source `timestamp`
/// (exactly what every loader now populates, WAVE-2 item 1), the writer must
/// emit THAT value, not the `SYNTH_TS` fallback — proven directly against
/// `ChatMessage.metadata`, independent of any loader. Covers all 4 writers
/// (Claude Code, Codex, Pi's entry-level `timestamp`, OpenCode's ms
/// conversion) — a fidelity-regression build previously left Codex/Pi
/// untested here, letting the pi native round-trip corruption ship unnoticed.
#[test]
fn message_with_real_timestamp_metadata_is_not_synth_ts() {
    let mut session = Session::from_claude_code_str("").unwrap();
    let mut user = ChatMessage::user("hello");
    user.metadata.insert(
        "timestamp".to_string(),
        "2024-03-05T12:00:00.500Z".to_string(),
    );
    session.messages = vec![user];

    let out = session.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    assert!(
        out.contains("2024-03-05T12:00:00.500Z"),
        "the real source timestamp must be emitted verbatim: {out}"
    );
    assert!(
        !out.contains("2026-01-01T00:00:00.000Z"),
        "a message WITH a real source timestamp must never fall back to SYNTH_TS: {out}"
    );

    let out = session.to_jsonl(SessionFormat::Codex).unwrap();
    assert!(
        out.contains("2024-03-05T12:00:00.500Z"),
        "Codex: the real source timestamp must be emitted verbatim: {out}"
    );
    // NOTE: unlike Claude/Pi, Codex's writer always emits a synthesized
    // `session_meta` header `response_item` with the `SYNTH_TS` placeholder
    // (it's a thread-level header, not derived from any single message) —
    // so this asserts only the message's OWN `response_item` line, not
    // whole-output absence of SYNTH_TS.
    let message_line = out
        .lines()
        .find(|l| l.contains("\"type\":\"response_item\""))
        .unwrap_or_else(|| panic!("Codex: no response_item line in output: {out}"));
    assert!(
        !message_line.contains("2026-01-01T00:00:00.000Z"),
        "Codex: a message WITH a real source timestamp must never fall back to SYNTH_TS: {message_line}"
    );

    let out = session.to_jsonl(SessionFormat::Pi).unwrap();
    assert!(
        out.contains("2024-03-05T12:00:00.500Z"),
        "Pi: the real source entry-level (canonical) timestamp must be emitted verbatim: {out}"
    );
    // NOTE: like Codex, Pi's writer always emits a synthesized `"type":
    // "session"` header line with the `SYNTH_TS` placeholder (session
    // metadata, not derived from any single message) — so this asserts only
    // the `"type":"message"` entry line, not whole-output absence of
    // SYNTH_TS.
    let message_line = out
        .lines()
        .find(|l| l.contains("\"type\":\"message\""))
        .unwrap_or_else(|| panic!("Pi: no message-type line in output: {out}"));
    assert!(
        !message_line.contains("2026-01-01T00:00:00.000Z"),
        "Pi: a message WITH a real source timestamp must never fall back to SYNTH_TS: {message_line}"
    );

    let out = session.to_jsonl(SessionFormat::OpenCode).unwrap();
    // 2024-03-05T12:00:00.500Z == 1709640000500 ms.
    assert!(
        out.contains("1709640000500"),
        "the real source timestamp must be converted to the equivalent unix-ms: {out}"
    );
    // NOTE: like Codex/Pi, OpenCode's writer always emits a synthesized
    // session-level `info.time.created`/`updated` with the SYNTH_TS_MS
    // placeholder (session metadata, not derived from any single message) —
    // so this asserts only the message's own `info.time.created`, not
    // whole-output absence of SYNTH_TS_MS.
    let doc: serde_json::Value = serde_json::from_str(&out).unwrap();
    let msg_created = doc["messages"][0]["info"]["time"]["created"]
        .as_i64()
        .unwrap_or_else(|| panic!("OpenCode: no messages[0].info.time.created in output: {out}"));
    assert_ne!(
        msg_created, 1_767_225_600_000,
        "OpenCode: a message WITH a real source timestamp must never fall back to SYNTH_TS_MS: {out}"
    );
    assert_eq!(msg_created, 1_709_640_000_500);
}

/// A malformed or empty `metadata["timestamp"]` (garbage bytes, or a present
/// but empty string) must degrade to the `SYNTH_TS`/`SYNTH_TS_MS` fallback,
/// not propagate verbatim into the writer's output — the ISO-string writers
/// (Claude/Codex/Pi) previously trusted `metadata["timestamp"]` on mere
/// presence, unlike OpenCode's numeric path which already guarded via
/// `rfc3339_to_ms`. `msg_timestamp_or_synth` now validates format via the
/// same `rfc3339_to_ms` parse before trusting the value.
#[test]
fn malformed_or_empty_timestamp_metadata_falls_back_to_synth_ts() {
    let mut session = Session::from_claude_code_str("").unwrap();

    for bad_ts in ["", "not-a-timestamp", "2024-13-99T99:99:99Z"] {
        let mut user = ChatMessage::user("hello");
        user.metadata
            .insert("timestamp".to_string(), bad_ts.to_string());
        session.messages = vec![user];

        for format in [
            SessionFormat::ClaudeCode,
            SessionFormat::Codex,
            SessionFormat::Pi,
        ] {
            let out = session.to_jsonl(format).unwrap();
            assert!(
                out.contains("2026-01-01T00:00:00.000Z"),
                "{format:?}: malformed/empty timestamp {bad_ts:?} must fall back to \
                 SYNTH_TS, not propagate: {out}"
            );
            if !bad_ts.is_empty() {
                assert!(
                    !out.contains(bad_ts),
                    "{format:?}: the malformed value {bad_ts:?} must never appear verbatim \
                     in the output: {out}"
                );
            }
        }

        let out = session.to_jsonl(SessionFormat::OpenCode).unwrap();
        assert!(
            out.contains("1767225600000"),
            "OpenCode: malformed/empty timestamp {bad_ts:?} must fall back to SYNTH_TS_MS: {out}"
        );
    }
}

// ---- WAVE-2 fidelity-regression fix: pi_msg_timestamp restored ------------

/// pi's message-level unix-ms clock (`message.timestamp` on the wire,
/// captured into `metadata["pi_msg_timestamp"]`) is a DISTINCT field from
/// the canonical entry-level ISO `metadata["timestamp"]` WAVE-2 item 1
/// wired — the fixture's own values are ~6 months apart (entry ~2026-01-01,
/// msg ~2025-07-07). A prior build wrongly deleted its capture entirely,
/// which silently lost pi's real per-message clock AND corrupted pi's own
/// native round-trip (the writer derived the nested `message.timestamp` from
/// the entry-level ISO instead of preserving the source value). This proves
/// the round-trip is now value-exact: load the pi fixture, write it back out
/// as pi, reload, and assert every message's nested `message.timestamp`
/// equals the ORIGINAL fixture's nested value — not merely "some number".
#[test]
fn pi_native_roundtrip_preserves_msg_level_timestamp_value_exact() {
    let fixture_path =
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/pi_session.jsonl");

    let session = Session::from_pi(&fixture_path).unwrap();
    // Every replay-eligible message loaded from pi must carry the restored
    // `pi_msg_timestamp` metadata field.
    let with_ts_count = session
        .messages
        .iter()
        .filter(|m| m.metadata.contains_key("pi_msg_timestamp"))
        .count();
    assert!(
        with_ts_count > 0,
        "pi_msg_timestamp must be captured by the loader"
    );

    let written = session.to_jsonl(SessionFormat::Pi).unwrap();

    // `write_pi_entries` walks `session.messages` in order, `continue`-ing
    // past `is_replay_excluded` messages (compacted-out / `!!`
    // exclude-from-context) and emitting exactly one JSONL line per
    // remaining message — so re-deriving that same skip here lets us match
    // each written line back to the exact source `ChatMessage` that
    // produced it, without needing round-trip id/entry bookkeeping.
    fn is_excluded(m: &ChatMessage) -> bool {
        m.metadata.get("compacted_out").map(String::as_str) == Some("true")
            || m.metadata
                .get("pi_exclude_from_context")
                .map(String::as_str)
                == Some("true")
    }

    // Skip the header line (`"type":"session"`) — only `"type":"message"`
    // entries correspond 1:1 with non-excluded `ChatMessage`s.
    let written_lines: Vec<serde_json::Value> = written
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .filter(|v| v.get("type").and_then(serde_json::Value::as_str) == Some("message"))
        .collect();
    let expected_written = session.messages.iter().filter(|m| !is_excluded(m)).count();
    assert_eq!(
        written_lines.len(),
        expected_written,
        "sanity: one written pi entry per non-excluded message"
    );

    let mut checked_real_ts = 0usize;
    for (msg, line) in session
        .messages
        .iter()
        .filter(|m| !is_excluded(m))
        .zip(written_lines.iter())
    {
        let written_ts = line
            .get("message")
            .and_then(|m| m.get("timestamp"))
            .and_then(serde_json::Value::as_u64)
            .unwrap_or_else(|| panic!("written pi entry missing nested message.timestamp: {line}"));
        if let Some(expected) = msg
            .metadata
            .get("pi_msg_timestamp")
            .and_then(|s| s.parse::<u64>().ok())
        {
            assert_eq!(
                written_ts, expected,
                "pi native round-trip: nested message.timestamp must preserve pi's real \
                 message-level clock ({expected}) VALUE-EXACT, not derive it from the \
                 (distinct) entry-level ISO timestamp — got {written_ts} for entry {line}"
            );
            // Must never silently coincide with the SYNTH_TS_MS placeholder
            // for a message that DID have a real source timestamp.
            assert_ne!(
                written_ts, 1_767_225_600_000,
                "pi native round-trip: a message WITH a real pi_msg_timestamp must never \
                 fall back to SYNTH_TS_MS: {line}"
            );
            checked_real_ts += 1;
        }
    }
    // `with_ts_count` counts ALL loaded messages carrying `pi_msg_timestamp`,
    // including ones legitimately excluded from replay (compacted-out) and
    // therefore never written at all — so `checked_real_ts` is a strict
    // subset, not necessarily equal. The real assertion is just that at
    // least one non-excluded, real-timestamped message was value-checked
    // above (proving the round-trip actually exercises the fix, not just
    // vacuously passing over an empty set).
    assert!(
        checked_real_ts > 0,
        "sanity: at least one non-excluded message with a real pi_msg_timestamp must have \
         been value-checked (loaded {with_ts_count} total)"
    );

    // And the reloaded session must have re-captured pi_msg_timestamp again
    // — the whole point of the round-trip.
    let reload = Session::load_str(&written, SessionFormat::Pi).unwrap();
    assert!(
        reload
            .messages
            .iter()
            .any(|m| m.metadata.contains_key("pi_msg_timestamp")),
        "pi_msg_timestamp must survive a pi -> pi native round-trip"
    );
}

// ---- IX-1: strict-verbatim raw capture (claude/codex) ---------------------
//
// `pi_interop.rs` carries the pi analogues of these two tests
// (`pi_raw_capture_is_strict_verbatim_for_pathological_input` and
// `pi_parsing_skips_blank_lines_between_records`) plus the `join_source`
// helper these mirror inline (duplicated per this test suite's
// standalone-file convention).

/// Reconstruct the ORIGINAL source bytes `session.raw` was captured from —
/// see `pi_interop.rs::join_source` for the full rationale.
fn ix1_join_source(session: &Session) -> String {
    let mut out = session.raw.join("\n");
    if session.raw_trailing_newline {
        out.push('\n');
    }
    out
}

/// IX-1: a Claude Code transcript with blank lines, a trailing-whitespace-padded
/// line, a CRLF line ending, AND no trailing newline at EOF must round-trip
/// BYTE-EXACT: load -> to_native_jsonl -> from_native_str -> reconstructed
/// source bytes == the original pathological bytes.
#[test]
fn claude_code_raw_capture_is_strict_verbatim_for_pathological_input() {
    let line1 =
        r#"{"type":"user","message":{"role":"user","content":"hi"},"sessionId":"s","cwd":"/tmp"}"#;
    let line2 = r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"ok"}]},"sessionId":"s"}"#;

    let pathological = format!("{line1}   \n\n\n{line2}\r\n\n{{\"type\":\"user\",\"message\":{{\"role\":\"user\",\"content\":\"bye\"}},\"sessionId\":\"s\"}}");
    assert!(
        !pathological.ends_with('\n'),
        "sanity: no trailing newline at EOF"
    );

    let session = Session::from_claude_code_str(&pathological).unwrap();
    let native = session.to_native_jsonl();
    let reloaded = Session::from_native_str(&native).unwrap();
    assert_eq!(
        ix1_join_source(&reloaded).as_bytes(),
        pathological.as_bytes(),
        "IX-1: Claude Code strict-verbatim raw capture must round-trip pathological input \
         (blank lines / CRLF / trailing whitespace / no trailing newline at EOF) byte-exact"
    );

    let native_v2 = session.to_native_jsonl_v2(&[]);
    let reloaded_v2 = Session::from_native_str(&native_v2).unwrap();
    assert_eq!(
        ix1_join_source(&reloaded_v2).as_bytes(),
        pathological.as_bytes(),
        "IX-1: v2/sidecar native round-trip must also be byte-exact for pathological input"
    );
}

/// IX-1 companion (dev/02): a blank line between two Claude Code records must
/// still be SKIPPED by parsing — no spurious empty message, no parse error —
/// even though `raw` now preserves it verbatim.
#[test]
fn claude_code_parsing_skips_blank_lines_between_records() {
    let line1 =
        r#"{"type":"user","message":{"role":"user","content":"hi"},"sessionId":"s","cwd":"/tmp"}"#;
    let line2 = r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"ok"}]},"sessionId":"s"}"#;
    let jsonl = format!("{line1}\n\n{line2}\n");

    let session = Session::from_claude_code_str(&jsonl).unwrap();
    assert_eq!(
        session.messages.len(),
        2,
        "the blank line between the two records must not produce a spurious empty message \
         or a parse error: {:?}",
        session.messages
    );
    assert_eq!(session.messages[0].content.as_deref(), Some("hi"));
    assert_eq!(
        session.messages[1].content.as_deref(),
        Some("ok"),
        "assistant text must round-trip"
    );

    // But `raw` (strict-verbatim, IX-1) retains the blank line.
    assert_eq!(
        session.raw.len(),
        3,
        "raw must retain all 3 lines verbatim, including the blank one"
    );
    assert_eq!(
        session.raw[1], "",
        "the blank line itself must survive in raw"
    );
}

/// IX-1: same byte-exact pathological-input round trip for Codex.
#[test]
fn codex_raw_capture_is_strict_verbatim_for_pathological_input() {
    let line1 = r#"{"type":"session_meta","payload":{"id":"sess-1","cwd":"/tmp","originator":"codex_exec","cli_version":"0.141.0"}}"#;
    let line2 = r#"{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}}"#;
    let line3 = r#"{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi there"}]}}"#;

    let pathological = format!("{line1}   \n\n\n{line2}\r\n\n{line3}");
    assert!(
        !pathological.ends_with('\n'),
        "sanity: no trailing newline at EOF"
    );

    let session = Session::from_codex_str(&pathological).unwrap();
    let native = session.to_native_jsonl();
    let reloaded = Session::from_native_str(&native).unwrap();
    assert_eq!(
        ix1_join_source(&reloaded).as_bytes(),
        pathological.as_bytes(),
        "IX-1: Codex strict-verbatim raw capture must round-trip pathological input (blank \
         lines / CRLF / trailing whitespace / no trailing newline at EOF) byte-exact"
    );

    let native_v2 = session.to_native_jsonl_v2(&[]);
    let reloaded_v2 = Session::from_native_str(&native_v2).unwrap();
    assert_eq!(
        ix1_join_source(&reloaded_v2).as_bytes(),
        pathological.as_bytes(),
        "IX-1: v2/sidecar native round-trip must also be byte-exact for pathological input"
    );
}

/// IX-1 companion (dev/02): a blank line between two Codex records must still
/// be SKIPPED by parsing.
#[test]
fn codex_parsing_skips_blank_lines_between_records() {
    let line1 = r#"{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}}"#;
    let line2 = r#"{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi there"}]}}"#;
    let jsonl = format!("{line1}\n\n{line2}\n");

    let session = Session::from_codex_str(&jsonl).unwrap();
    assert_eq!(
        session.messages.len(),
        2,
        "the blank line between the two records must not produce a spurious empty message \
         or a parse error: {:?}",
        session.messages
    );

    // But `raw` (strict-verbatim, IX-1) retains the blank line.
    assert_eq!(
        session.raw.len(),
        3,
        "raw must retain all 3 lines verbatim, including the blank one"
    );
    assert_eq!(
        session.raw[1], "",
        "the blank line itself must survive in raw"
    );
}