supercode-interchange 0.4.10

Canonical, provider-neutral session interchange primitives for Supercode
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
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
//! Natively load — and continue — real Claude Code and Codex sessions.
//!
//! Both tools persist their conversations as JSONL on disk:
//!
//! - **Claude Code**: `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl`,
//!   one line per event in the Anthropic message format, linked by
//!   `uuid`/`parentUuid`.
//! - **Codex**: `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`, where each line
//!   is a `{timestamp, type, payload}` envelope and the `response_item` lines
//!   form the canonical conversation.
//!
//! [`Session::load`] auto-detects the format and normalizes either one into a
//! provider-neutral [`Vec<ChatMessage>`] that can be handed straight back to a
//! model (via OpenRouter or any OpenAI-compatible endpoint) to continue.
//!
//! Provider-internal artifacts that don't replay across vendors — Anthropic
//! `thinking` blocks, Codex `reasoning` items — are dropped during
//! normalization.
//!
//! # Where this sits in supercode's priorities
//!
//! This module is the home of **feature 1 (translate between session formats)**
//! and half of **feature 2 (emulate-to-continue)** — the load/emit surface for
//! each harness ([`SessionFormat`], `from_*_str` loaders, `to_*_jsonl`
//! emitters). See [`AGENTS.md`](../../../AGENTS.md) for the three ranked
//! feature-priorities and the glue-tool positioning; the top priority is
//! **feature 3 (continue losslessly *with massive token reduction*)**, which
//! this fidelity work exists to make trustworthy. `opencode` + `pi` loaders
//! are built against the frozen `docs/interop/opencode-pi-spec.md` contract
//! — OpenCode additionally reads its native SQLite store (`opencode*.db`,
//! PARITY-3/PARITY-16) via `rusqlite`, reconstructing the same envelope form
//! [`Session::from_opencode_str`] already parses for the JSON-tree surfaces.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

use rusqlite::Connection;
use serde_json::Value;

use crate::{
    ChatMessage, Fidelity, FunctionCall, InterchangeError as Error, Result, Role, ToolCall,
};

/// Which tool produced a session log.
///
/// This is **read-provenance**: a fact recovered when a log is loaded (stored
/// in [`SessionMeta::source`], filled in by auto-detection in
/// `detect_source`), describing which tool originally wrote the file on
/// disk. It answers "where did this session come from?" — e.g. for
/// `inspect`/`convert` display in the CLI.
///
/// It is deliberately distinct from [`SessionFormat`], even though the two
/// enums' variant lists currently coincide: [`SessionFormat`] selects a
/// serialization codec (what to parse/export *as*), while `SessionSource`
/// records history (what wrote the file). The pair is intentionally kept
/// separate rather than merged — a session loaded from one tool's log can
/// still be exported in the other tool's format, and the two concepts could
/// diverge further (e.g. a format that is readable but not attributable, or
/// multiple versioned formats sharing one source).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionSource {
    /// A `~/.claude/projects/.../<id>.jsonl` transcript.
    ClaudeCode,
    /// A `~/.codex/sessions/.../rollout-*.jsonl` file.
    Codex,
    /// An OpenCode session — multi-file JSON tree(s) or SQLite `opencode*.db`
    /// (`docs/interop/opencode-pi-spec.md` §1.2). Detection and loading are
    /// wave B; this variant exists now so `SessionSource`/`SessionFormat` stay
    /// 1:1 per the frozen interop spec (§0).
    OpenCode,
    /// A `~/.pi/agent/sessions/--<enc-cwd>--/<iso>_<sessionId>.jsonl`
    /// transcript (`docs/interop/opencode-pi-spec.md` §1.1) — line-oriented
    /// JSONL like Claude Code/Codex, so it shares their byte-lossless native
    /// round-trip property.
    Pi,
    /// A Grok session transcript stored as
    /// `~/.grok/sessions/<percent-encoded-cwd>/<session-id>/chat_history.jsonl`.
    Grok,
    /// A Gemini CLI transcript stored under
    /// `~/.gemini/tmp/<project>/chats/session-*.jsonl`.
    Gemini,
    /// A Goose session exported through `_goose/unstable/session/export`, or
    /// reconstructed from Goose's `sessions/sessions.db` native store.
    Goose,
    /// P5-3 safety-hardening fix (Fable-5 review, LOW "translation-fidelity
    /// cosmetic"): a session that was never imported from ANY foreign
    /// tool's log at all — authored directly by supercode's own agent loop,
    /// with no foreign-tool prefix (`Session.raw` starts empty). Currently
    /// only `crate::agent::Agent`'s `persist_subagent_transcript` (P5-3,
    /// natively-spawned `spawn_subagent` children) uses this — before this
    /// variant existed, that call site built its blank `Session` via
    /// `Session::from_claude_code_str("")` purely as an "empty parser to
    /// get a blank skeleton" trick, which left `meta.source ==
    /// SessionSource::ClaudeCode` even though nothing Claude-Code-shaped
    /// was ever involved, mislabeling a native supercode spawn as an
    /// imported CC session on disk (and in any `inspect`/`convert` reading
    /// it back). Never produced by auto-detection (`detect_source`) or any
    /// `from_<tool>_str` loader — only by code that explicitly constructs
    /// a `SessionMeta` with this source, so no existing imported-session
    /// path can ever observe this variant appearing where it didn't before.
    Native,
}

/// An on-disk session format supercode can both read and write.
///
/// Like an image editor that opens and exports several file formats, supercode
/// keeps one canonical in-memory model ([`Session`]) and converts to/from each
/// supported format on the edges.
///
/// This is a **write-target** / codec selector: a caller's request, passed to
/// [`Session::load_str`], [`Session::to_jsonl`], and [`Session::save`],
/// choosing which on-disk dialect to parse or emit. It answers "what format
/// should I read/write?" — as opposed to [`SessionSource`], which records the
/// provenance fact of what actually produced a loaded file. The two enums are
/// intentionally kept separate (provenance fact vs. serialization choice) and
/// should not be unified, even though their variants currently match
/// one-to-one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionFormat {
    /// Claude Code transcript JSONL.
    ClaudeCode,
    /// Codex rollout JSONL.
    Codex,
    /// OpenCode export-document / envelope JSONL (wave B; see
    /// [`SessionSource::OpenCode`]).
    OpenCode,
    /// Pi session JSONL (see [`SessionSource::Pi`]).
    Pi,
    /// Grok `chat_history.jsonl` transcript.
    Grok,
    /// Gemini CLI session JSONL.
    Gemini,
    /// Goose native session-export JSON.
    Goose,
}

impl SessionFormat {
    /// The [`SessionSource`] a file of this format reports.
    ///
    /// This is the deliberate one-way bridge between the two concepts: a file
    /// saved in this format will, when reloaded, report this provenance (see
    /// `crates/harness/tests/session_saving.rs`), making the relationship
    /// discoverable from the method itself.
    pub fn source(self) -> SessionSource {
        match self {
            SessionFormat::ClaudeCode => SessionSource::ClaudeCode,
            SessionFormat::Codex => SessionSource::Codex,
            SessionFormat::OpenCode => SessionSource::OpenCode,
            SessionFormat::Pi => SessionSource::Pi,
            SessionFormat::Grok => SessionSource::Grok,
            SessionFormat::Gemini => SessionSource::Gemini,
            SessionFormat::Goose => SessionSource::Goose,
        }
    }
}

/// Metadata recovered from a session log.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SessionMeta {
    /// The tool that wrote the log.
    pub source: SessionSource,
    /// The session/rollout id.
    pub session_id: Option<String>,
    /// The model the session was running.
    pub model: Option<String>,
    /// The working directory the session ran in.
    pub cwd: Option<PathBuf>,
    /// The system / base-instructions prompt, when the log records it.
    pub system_prompt: Option<String>,
    /// Verbatim source-format header records (the Codex `session_meta` /
    /// `turn_context` lines), preserved so re-export can replay the exact header
    /// the original tool expects rather than guessing its required fields.
    pub codex_headers: Vec<Value>,
    /// Exact source lines for Codex execution/provenance records that affect
    /// continuation semantics but must not be replayed as active events after
    /// a foreign-format hop. Each entry records its original physical-line
    /// index, discriminant, and verbatim JSONL text. Foreign writers carry the
    /// list in a namespaced extension; a later Codex export restores headers
    /// from it while keeping compaction/rollback/review records non-operative,
    /// avoiding a second rollback or compaction of the already-normalized view.
    pub codex_provenance: Vec<Value>,
    /// The OpenCode analogue of [`Self::codex_headers`]
    /// (`docs/interop/opencode-pi-spec.md` §1.2/§2.1): the verbatim
    /// `SessionInfo` record (always element 0, or `Value::Null` if somehow
    /// absent), plus any captured `session_diff`/`todo` side-records — each
    /// wrapped as `{"key": [...], "value": ...}`, mirroring the envelope
    /// shape `raw` uses, so a consumer can tell which storage key a header
    /// record belongs to. These replay only via the direct-write fallback
    /// (`Session::to_opencode_direct_write`); `opencode import` has no
    /// ingestion path for `session_diff`/`todo` (S5).
    pub opencode_headers: Vec<Value>,
    /// Goose's native session-export object with `conversation` removed.
    /// Goose stores sessions in SQLite but defines this JSON object as its
    /// official import/export boundary. Keeping the shell lets an unchanged
    /// direct round-trip remain byte exact while appended turns are spliced
    /// into a stock-importable artifact without guessing native metadata.
    pub goose_header: Option<Value>,
    /// For a Claude Code subagent session: its `agentId` (the `agent-<id>` file
    /// stem). `None` for top-level sessions.
    pub agent_id: Option<String>,
    /// For a subagent session: the `tool_use_id` of the parent `Task` call that
    /// spawned it, recovered from the parent transcript's tool result. Best
    /// effort — `None` if the link could not be established.
    pub parent_tool_use_id: Option<String>,
    /// Cross-file lineage keys for multi-file/multi-agent sessions (Codex
    /// `parent_thread_id`, `forked_from_id`, `thread_source`, and the
    /// `source.subagent.thread_spawn` fields `agent_role` / `agent_nickname` /
    /// `depth`). Empty for a plain top-level session. Used by
    /// [`Session::reconstruct_tree`] to nest children under their parents.
    pub lineage: std::collections::BTreeMap<String, String>,
}

impl SessionMeta {
    fn new(source: SessionSource) -> Self {
        SessionMeta {
            source,
            session_id: None,
            model: None,
            cwd: None,
            system_prompt: None,
            codex_headers: Vec::new(),
            codex_provenance: Vec::new(),
            opencode_headers: Vec::new(),
            goose_header: None,
            agent_id: None,
            parent_tool_use_id: None,
            lineage: std::collections::BTreeMap::new(),
        }
    }
}

/// A normalized, replayable conversation loaded from a tool's session log.
#[derive(Debug, Clone)]
pub struct Session {
    /// Recovered metadata.
    pub meta: SessionMeta,
    /// The conversation, normalized to the OpenAI chat-completions shape.
    pub messages: Vec<ChatMessage>,
    /// Subagent (Task) sub-conversations. Claude Code stores these as separate
    /// `<session>/subagents/agent-*.jsonl` files; loading a session by path now
    /// discovers and attaches them here (each is a full [`Session`] whose
    /// `meta.agent_id` / `meta.parent_tool_use_id` link it back to its spawn).
    pub subagents: Vec<Session>,
    /// Every original JSONL line of the source log, STRICT-VERBATIM (IX-1):
    /// captured via `split_lines_verbatim`, not the blank-skipping/trimming
    /// `non_empty_lines` parse view, so a blank line, a CRLF (`\r\n`)
    /// terminator, or trailing whitespace on a line all survive bit-for-bit
    /// rather than being dropped/normalized away. Normalization into
    /// `messages` is still lossy by design (it targets the OpenAI replay
    /// shape), but these raw lines retain *everything* — including records
    /// with no canonical representation (e.g. Claude `file-history-snapshot`)
    /// — so a round-trip through the supercode-native format
    /// ([`Session::to_native_jsonl`]) is byte-lossless for the line-oriented
    /// formats (Claude Code/Codex/Pi), for ANY input (see
    /// [`Self::raw_trailing_newline`] for the one piece of information a line
    /// list alone can't carry).
    pub raw: Vec<String>,
    /// Whether the source text `raw` was captured from ended with a trailing
    /// `\n`. `raw`'s line list alone can't distinguish a source ending with a
    /// trailing newline from one that doesn't (both split into the same
    /// lines) — this flag carries that fact out-of-band so
    /// [`Self::to_native_jsonl`]/[`Self::from_native_str`] can reproduce the
    /// original source bytes exactly, including the presence/absence of a
    /// final newline. `true` for a `Session` whose `raw` isn't captured
    /// verbatim from real source text (e.g. OpenCode's re-synthesized
    /// export-document `raw`, or a `Session` assembled programmatically) —
    /// matching the historical always-terminated-by-newline behavior for
    /// those cases.
    pub raw_trailing_newline: bool,
    /// How many of `messages` (and, symmetrically, of `raw` — see below) came
    /// from parsing the imported log, as opposed to being appended after
    /// import. Set once, at the end of [`Self::from_claude_code_str`] /
    /// [`Self::from_codex_str`], to `messages.len()` at that moment — i.e.
    /// before [`Self::from_native_str`]'s subsequent loop reattaches any
    /// appended [`crate::sidecar::NativeTurn`] records onto `messages`/`raw`.
    /// That loop pushes exactly one `raw` line and one message per appended
    /// turn, so the two lists grow in lockstep from here on: the raw-prefix
    /// boundary A12's [`Self::to_jsonl_spliced`] needs is always recoverable
    /// as `raw.len() - (messages.len() - imported_message_count)`, without a
    /// second counter. `None` only when a `Session` is constructed some other
    /// way than through those two loaders — splicing then has no boundary to
    /// honor and treats every message as imported (equivalent to
    /// `Some(messages.len())`).
    /// A bounded display-history projection uses this field for the total
    /// number of normalized messages observed before its in-memory window was
    /// applied. Such a semantic view is never a continuation source, and all
    /// splice callers clamp the value to `messages.len()`.
    pub imported_message_count: Option<usize>,
    /// Whether `raw` was captured strict-verbatim from real source text
    /// (`true`) or re-synthesized by this crate (`false`) — the fact
    /// [`Self::raw_verbatim`]'s callers need to know before claiming a
    /// same-format `convert` is byte-identical (PARITY-AUDIT.md P006/P007).
    /// `true` for every line-oriented loader (`from_claude_code_str`,
    /// `from_codex_str`, `from_pi_str`) and OpenCode's own ENVELOPE read
    /// surface (`from_opencode_str`'s per-line loop) — each of those splits
    /// `raw` directly out of the source text via `split_lines_verbatim`, so
    /// replaying it reproduces the original bytes exactly. `false` for
    /// OpenCode's EXPORT-DOCUMENT read surface
    /// (`Session::from_opencode_export_doc`): a pretty-printed
    /// `{info, messages:[...]}` document has no per-line envelope structure
    /// of its own, so `raw` there is one envelope line RE-SYNTHESIZED per
    /// record — faithful in value, but not the original document's bytes.
    /// A `Session` assembled programmatically (not through a `from_*_str`
    /// loader) also defaults to `false` — no real source text was captured
    /// at all.
    pub raw_is_verbatim: bool,
    /// PARITY-15: how many non-empty lines of the source text FAILED to
    /// deserialize at all (a genuinely malformed/truncated JSON line — not
    /// a well-formed-but-unmodeled record type, which is a normal,
    /// intentional "skip", tracked separately by `crate::audit`). Every
    /// line-oriented loader tolerates a stray corrupt line rather than
    /// hard-failing the whole load (a single bad line must not make an
    /// otherwise-healthy multi-thousand-line session unloadable) — but that
    /// tolerance used to be completely invisible: `Session::load` returned
    /// `Ok` either way, with no signal that anything was skipped. This
    /// count is what lets a caller (the CLI, `inspect`/`convert`) surface
    /// that loss loudly instead of silently. `0` for a cleanly-parsed file,
    /// and for a `Session` assembled programmatically.
    pub parse_error_lines: usize,
    /// Named degradations a [`Fidelity::Semantic`] load accepted instead of
    /// failing — the same "say exactly what was given up" residue list
    /// `harness.v1.sessions.export` already reports for artifacts.
    ///
    /// ALWAYS empty for a lossless load: every stricter fidelity refuses a
    /// transcript it cannot reconstruct exactly, which is what keeps
    /// continuation/transfer/export guarantees intact. A non-empty list means
    /// this session is a read-only VIEW ([`Session::load_with_fidelity`] with
    /// [`Fidelity::Semantic`]) and must not be used as a continuation source.
    pub load_residue: Vec<String>,
}

impl Session {
    /// The fidelity this reconstruction actually achieved.
    ///
    /// Same rule the export path applies to an artifact: named residue means
    /// [`Fidelity::Semantic`]; otherwise a verbatim source capture is
    /// [`Fidelity::ByteLossless`] and a re-synthesized one is
    /// [`Fidelity::ValueLossless`]. A subagent's residue counts as this
    /// session's: the whole reconstruction is only as faithful as its least
    /// faithful part, and each child still reports its own residue where it
    /// was measured.
    pub fn load_fidelity(&self) -> Fidelity {
        let own = if !self.load_residue.is_empty() {
            Fidelity::Semantic
        } else if self.raw_is_verbatim {
            Fidelity::ByteLossless
        } else {
            Fidelity::ValueLossless
        };
        if own != Fidelity::Semantic
            && self
                .subagents
                .iter()
                .any(|subagent| subagent.load_fidelity() == Fidelity::Semantic)
        {
            return Fidelity::Semantic;
        }
        own
    }

    /// Assemble a session from supercode's own flat store transcript (one
    /// [`ChatMessage`] per JSONL line). These files are the native working
    /// format written by Supercode's native session store, not a foreign
    /// harness log, so routing them through format auto-detection would
    /// misclassify them as an empty Claude Code session.
    pub fn from_native_messages(messages: Vec<ChatMessage>) -> Session {
        Session {
            meta: SessionMeta::new(SessionSource::Native),
            messages,
            subagents: Vec::new(),
            raw: Vec::new(),
            raw_trailing_newline: true,
            imported_message_count: None,
            raw_is_verbatim: false,
            parse_error_lines: 0,
            load_residue: Vec::new(),
        }
    }

    /// Load a session, auto-detecting whether it's a Claude Code or Codex log
    /// — or, when `path` looks like a SQLite database, a real OpenCode
    /// `opencode*.db` store (PARITY-3/PARITY-16): that check runs BEFORE any
    /// UTF-8 text read, so a binary `.db` file is routed to
    /// [`Self::from_opencode_sqlite`] instead of failing on a raw "stream
    /// did not contain valid UTF-8" error (the confirmed footgun these items
    /// close — see [`looks_like_sqlite`] and the UTF-8 diagnostic reader).
    ///
    /// A DIRECTORY is also accepted directly: `path` is probed with
    /// [`detect_opencode_storage_surface`] BEFORE the SQLite/UTF-8 file
    /// checks below (both of which assume a file and would otherwise surface
    /// a cryptic "Is a directory" `io::Error` — the confirmed footgun this
    /// closes). This lets `inspect`/`convert`/`resume` accept an OpenCode
    /// DATA-ROOT directly (e.g. `~/.local/share/opencode`), matching what
    /// `audit --format opencode` already does. A resolved `Sqlite` surface
    /// loads exactly like pointing `load` at that `opencode*.db` file
    /// directly (most-recently-updated top-level session). The legacy
    /// `JsonTreeA`/`JsonTreeB` surfaces are classifier-only (see
    /// [`OpenCodeStorageSurface`]) — there's no direct-JSON-tree loader, so
    /// that case returns a clear error naming the `.db` file / `audit` as the
    /// way in, rather than silently doing nothing or crashing.
    pub fn load(path: impl AsRef<Path>) -> Result<Session> {
        Self::load_with_fidelity(path, Fidelity::ByteLossless)
    }

    /// Load a session at a declared [`Fidelity`].
    ///
    /// [`Fidelity::Semantic`] is the READ-ONLY VIEW mode: a transcript whose
    /// record graph cannot be reconstructed exactly (the everyday case for a
    /// Claude Code session that has been compacted or resumed across files,
    /// where a live record's `parentUuid` names a record that was pruned)
    /// still loads, stitched best-effort in transcript order, and names what
    /// it gave up in [`Session::load_residue`]. Every stricter level keeps
    /// the historical behavior — refuse loudly — because a continuation,
    /// transfer or export built on a guessed graph is exactly the loss
    /// supercode exists to prevent. Callers that go on to RESUME a session
    /// must therefore use [`Session::load`].
    pub fn load_with_fidelity(path: impl AsRef<Path>, fidelity: Fidelity) -> Result<Session> {
        Self::load_with_fidelity_and_subagents(path, fidelity, true)
    }

    /// Load only the selected session's own transcript at a declared fidelity.
    ///
    /// This is the read-only frontend path: Claude Code can place hundreds of
    /// child transcripts beside a parent, but a chat viewport displaying the
    /// parent must not eagerly parse and transport that entire child tree.
    /// Translation, continuation, export, and the ordinary [`Self::load`]
    /// path keep attaching every subagent unchanged.
    #[doc(hidden)]
    pub fn load_parent_with_fidelity(
        path: impl AsRef<Path>,
        fidelity: Fidelity,
    ) -> Result<Session> {
        Self::load_with_fidelity_and_subagents(path, fidelity, false)
    }

    /// Load a bounded, parent-only transcript for human display.
    ///
    /// Unlike the continuation loader, Codex compaction records do not erase
    /// earlier visible assistant turns here: the native rollout still holds
    /// those records, and a scrollback view should show what the human saw,
    /// not only the compacted context the next model call will receive.
    #[doc(hidden)]
    pub fn load_display_view(
        path: impl AsRef<Path>,
        fidelity: Fidelity,
        message_limit: usize,
    ) -> Result<Session> {
        let path = path.as_ref();
        if path.is_dir() || looks_like_sqlite(path) {
            let mut session = Self::load_parent_with_fidelity(path, fidelity)?;
            truncate_session_messages(&mut session, message_limit);
            return Ok(session);
        }
        let mut read_limit = message_limit.max(1);
        let mut previous_window_len = 0usize;
        let (mut session, omitted_prefix) = loop {
            let (source, text, omitted_prefix) = read_display_jsonl(path, read_limit)?;
            let mut candidate = match source {
                Some(SessionSource::Codex) => Self::from_codex_display_str(&text, message_limit)?,
                Some(SessionSource::Gemini) => {
                    let mut session = Self::from_gemini_str(&text)?;
                    session.raw_is_verbatim = false;
                    session.load_residue.push(
                        "display history is a bounded native-record projection, not a complete Gemini artifact"
                            .to_string(),
                    );
                    session
                }
                Some(SessionSource::Pi) => Self::from_pi_str(&text)?,
                Some(SessionSource::Grok) => {
                    let mut session = Self::from_grok_str(&text)?;
                    session.capture_grok_path_metadata(path);
                    session
                }
                Some(SessionSource::OpenCode) => Self::from_opencode_str(&text)?,
                _ => Self::from_claude_code_str_with_fidelity(&text, fidelity)?,
            };
            let observed_messages = candidate
                .imported_message_count
                .unwrap_or(candidate.messages.len())
                .max(candidate.messages.len());
            let human_turns = candidate
                .messages
                .iter()
                .filter(|message| message.role == Role::User)
                .count();
            let window_len = text.len();
            let sufficient =
                !omitted_prefix || (observed_messages > message_limit.max(1) && human_turns >= 2);
            // 16 KiB/message with a 64 MiB ceiling means 4096 is the first
            // read limit that cannot grow the native byte window further.
            // Smaller repeated lengths can be the intentional 4 MiB floor;
            // keep doubling through that plateau instead of declaring a
            // false pagination end.
            let byte_window_exhausted = window_len <= previous_window_len && read_limit >= 4096;
            if sufficient || byte_window_exhausted {
                if omitted_prefix {
                    // The prefix is known to contain more native history even
                    // when this bounded window cannot cheaply normalize its
                    // exact size. Never turn that into a false end-of-history.
                    candidate.imported_message_count =
                        Some(observed_messages.max(message_limit.max(1).saturating_add(1)));
                }
                break (candidate, omitted_prefix);
            }
            previous_window_len = window_len;
            read_limit = read_limit.saturating_mul(2);
        };
        if omitted_prefix {
            session.load_residue.push(
                "older native records remain outside this bounded display window".to_string(),
            );
        }
        truncate_session_messages(&mut session, message_limit);
        Ok(session)
    }

    fn load_with_fidelity_and_subagents(
        path: impl AsRef<Path>,
        fidelity: Fidelity,
        include_subagents: bool,
    ) -> Result<Session> {
        let path = path.as_ref();
        if path.is_dir() {
            return match detect_opencode_storage_surface(path) {
                Some((OpenCodeStorageSurface::Sqlite, db_path)) => {
                    Self::from_opencode_sqlite(&db_path, None)
                }
                Some((
                    OpenCodeStorageSurface::JsonTreeA | OpenCodeStorageSurface::JsonTreeB,
                    _,
                )) => Err(crate::Error::Other(format!(
                    "{} is an OpenCode data root using a legacy JSON storage tree, which \
                         supercode does not load directly — point `inspect`/`convert`/`resume` \
                         at the store's `opencode*.db` SQLite file if this install has one, or \
                         use `audit --format opencode {}` instead",
                    path.display(),
                    path.display()
                ))),
                None => Err(crate::Error::Other(format!(
                    "{} is a directory, but no session file or OpenCode store was found in it \
                     (expected an `opencode*.db` SQLite file, or an OpenCode legacy JSON storage \
                     tree)",
                    path.display()
                ))),
            };
        }
        if looks_like_sqlite(path) {
            return Self::from_opencode_sqlite(path, None);
        }
        let text = read_utf8_or_diagnose(path)?;
        match detect_source(&text) {
            Some(SessionSource::Codex) => Self::from_codex_str(&text),
            Some(SessionSource::Pi) => Self::from_pi_str(&text),
            Some(SessionSource::Grok) => {
                let mut session = Self::from_grok_str(&text)?;
                session.capture_grok_path_metadata(path);
                Ok(session)
            }
            Some(SessionSource::Gemini) => Self::from_gemini_str(&text),
            Some(SessionSource::Goose) => Self::from_goose_str(&text),
            // IX-3: a detected OpenCode session must route to its own
            // loader, not the Claude Code fallback below
            // (`docs/interop/build-followups.md`).
            Some(SessionSource::OpenCode) => Self::from_opencode_str(&text),
            _ => {
                let mut session = Self::from_claude_code_str_with_fidelity(&text, fidelity)?;
                if include_subagents {
                    session.attach_claude_subagents(path, &text, fidelity)?;
                }
                Ok(session)
            }
        }
    }

    /// Load a Claude Code transcript from a file, attaching any subagent
    /// (`Task`) sub-conversations stored alongside it.
    pub fn from_claude_code(path: impl AsRef<Path>) -> Result<Session> {
        Self::from_claude_code_with_fidelity(path, Fidelity::ByteLossless)
    }

    /// [`Session::from_claude_code`] at a declared [`Fidelity`] — see
    /// [`Session::load_with_fidelity`] for what [`Fidelity::Semantic`] buys.
    pub fn from_claude_code_with_fidelity(
        path: impl AsRef<Path>,
        fidelity: Fidelity,
    ) -> Result<Session> {
        let text = std::fs::read_to_string(path.as_ref())?;
        let mut session = Self::from_claude_code_str_with_fidelity(&text, fidelity)?;
        session.attach_claude_subagents(path.as_ref(), &text, fidelity)?;
        Ok(session)
    }

    /// Discover and load `<session>/subagents/agent-*.jsonl` files for a
    /// Claude Code transcript at `main_path`, linking each back to the parent
    /// `Task` tool call via the agent id embedded in the parent's tool result.
    fn attach_claude_subagents(
        &mut self,
        main_path: &Path,
        main_text: &str,
        fidelity: Fidelity,
    ) -> Result<()> {
        let Some(dir) = subagents_dir_for(main_path) else {
            return Ok(());
        };
        let entries = std::fs::read_dir(&dir).map_err(|error| {
            crate::Error::Other(format!(
                "failed to enumerate Claude subagents at {}: {error}",
                dir.display()
            ))
        })?;
        let mut files = Vec::new();
        for entry in entries {
            let entry = entry.map_err(|error| {
                crate::Error::Other(format!(
                    "failed to enumerate Claude subagents at {}: {error}",
                    dir.display()
                ))
            })?;
            let path = entry.path();
            if path.extension().and_then(|extension| extension.to_str()) == Some("jsonl") {
                files.push(path);
            }
        }
        files.sort();

        // Phase 1 — collect each subagent + its recovered agent id, without
        // touching the main transcript yet.
        let mut collected: Vec<(Session, Option<String>)> = Vec::with_capacity(files.len());
        for file in files {
            let text = read_utf8_or_diagnose(&file).map_err(|error| {
                crate::Error::Other(format!(
                    "failed to read Claude subagent {}: {error}",
                    file.display()
                ))
            })?;
            let sub = match Self::from_claude_code_str_with_fidelity(&text, fidelity) {
                Ok(sub) => sub,
                // A read-only VIEW keeps the main conversation rather than
                // losing the whole session to one unreconstructable child;
                // the skip is named, not silent. Every stricter fidelity
                // still propagates the child's failure.
                Err(error) if fidelity.tolerates_residue() => {
                    self.load_residue.push(format!(
                        "Claude subagent {} could not be reconstructed ({error}); it was omitted from this view",
                        file.display()
                    ));
                    continue;
                }
                Err(error) => {
                    return Err(crate::Error::Other(format!(
                        "failed to reconstruct Claude subagent {}: {error}",
                        file.display()
                    )))
                }
            };
            // agentId: prefer the file's own record, fall back to the filename stem.
            let agent_id = first_agent_id(&text).or_else(|| {
                file.file_stem()
                    .and_then(|s| s.to_str())
                    .map(|s| s.trim_start_matches("agent-").to_string())
            });
            collected.push((sub, agent_id));
        }

        // Phase 2 — single pass over the main transcript to index every
        // requested agent id at once, then assign each subagent's parent by
        // an O(1) lookup.
        let agent_ids: Vec<String> = collected.iter().filter_map(|(_, id)| id.clone()).collect();
        let index = parent_tool_use_index(main_text, &agent_ids);

        for (mut sub, agent_id) in collected {
            sub.meta.parent_tool_use_id = agent_id.as_ref().and_then(|id| index.get(id).cloned());
            sub.meta.agent_id = agent_id;
            self.subagents.push(sub);
        }
        Ok(())
    }

    /// Load a Codex rollout from a file.
    pub fn from_codex(path: impl AsRef<Path>) -> Result<Session> {
        Self::from_codex_str(&std::fs::read_to_string(path.as_ref())?)
    }

    /// Parse a Claude Code transcript from an in-memory JSONL string.
    pub fn from_claude_code_str(jsonl: &str) -> Result<Session> {
        Self::from_claude_code_str_with_fidelity(jsonl, Fidelity::ByteLossless)
    }

    /// [`Session::from_claude_code_str`] at a declared [`Fidelity`] — see
    /// [`Session::load_with_fidelity`] for what [`Fidelity::Semantic`] buys.
    pub fn from_claude_code_str_with_fidelity(jsonl: &str, fidelity: Fidelity) -> Result<Session> {
        let mut meta = SessionMeta::new(SessionSource::ClaudeCode);
        let mut messages = Vec::new();
        // IX-1: `raw` is captured STRICT-VERBATIM (blank lines, CRLF, trailing
        // whitespace all preserved) — separate from the blank-skipping
        // `non_empty_lines` walk just below, which still parses records only
        // (a blank line is not a JSON record and must not become one).
        let (raw_lines, raw_trailing_newline) = split_lines_verbatim(jsonl);
        let raw: Vec<String> = raw_lines.iter().map(|l| l.to_string()).collect();
        // PARITY-15: a malformed/truncated line is still tolerated (a
        // single bad line must not make an otherwise-healthy multi-
        // thousand-line session unloadable) — but it's no longer INVISIBLE.
        let mut parse_error_lines = 0usize;
        let mut index = ClaudeReplayIndex::default();

        // Claude transcripts are append-only trees, not linear chat logs.
        // Build a lightweight graph index first so normalization sees the
        // same single active, post-compaction branch Claude Code would
        // resume. `raw` above deliberately remains the complete source.
        for (line_index, line) in raw_lines.iter().enumerate() {
            if line.trim().is_empty() {
                continue;
            }
            let v: Value = match serde_json::from_str(line) {
                Ok(v) => v,
                Err(_) => {
                    parse_error_lines += 1; // tolerate stray/corrupt lines
                    continue;
                }
            };
            capture_claude_meta(&v, &mut meta, line)?;
            index.observe(line_index, &v)?;
        }

        let ClaudeReplaySelection {
            lines: replay_lines,
            residue: load_residue,
        } = index.select_lines(fidelity)?;
        let mut pending_assistant: Option<Value> = None;

        for line_index in replay_lines {
            let line = raw_lines[line_index];
            let v: Value = serde_json::from_str(line).map_err(crate::Error::Decode)?;

            if v.get("type").and_then(Value::as_str) == Some("assistant") {
                if v.get("isApiErrorMessage").and_then(Value::as_bool) == Some(true) {
                    flush_claude_assistant(&mut pending_assistant, &mut messages);
                    continue;
                }
                if let Some(pending) = pending_assistant.as_mut() {
                    if claude_assistant_message_id(pending).is_some_and(|message_id| {
                        claude_assistant_message_id(&v) == Some(message_id)
                    }) {
                        merge_claude_assistant_chunk(pending, &v);
                        continue;
                    }
                    flush_claude_assistant(&mut pending_assistant, &mut messages);
                }
                pending_assistant = Some(v);
                continue;
            }

            flush_claude_assistant(&mut pending_assistant, &mut messages);

            // WAVE-2 item 1: every Claude Code record carries a real
            // top-level `timestamp` (ISO-8601) — provenance stamping below
            // attaches it to every canonical `ChatMessage` this line
            // produces, together with the record UUID and assistant model.
            // `entry(...).or_insert_with` preserves any more-precise value a
            // role-specific loader already supplied.
            let before = messages.len();
            match v.get("type").and_then(Value::as_str) {
                Some("user") => push_claude_user(&v, &mut messages),
                Some("assistant") => push_claude_assistant(&v, &mut messages),
                Some("attachment") => push_claude_attachment(&v, &mut messages),
                Some("system") => push_claude_system(&v, &mut messages),
                _ => {} // mode, queue-operation, ... — skip
            }
            // UUID/model provenance remains meaningful even for legacy
            // records that predate Claude Code's timestamp field.
            capture_claude_record_provenance(&v, &mut messages[before..]);
            restore_single_grok_message(&v, &mut messages[before..]);
        }
        flush_claude_assistant(&mut pending_assistant, &mut messages);

        reorder_tool_results_after_calls(&mut messages);
        ensure_tool_results_paired(&mut messages);
        let imported_message_count = Some(messages.len());
        Ok(Session {
            meta,
            messages,
            subagents: Vec::new(),
            raw,
            raw_trailing_newline,
            imported_message_count,
            // Claude Code is line-oriented: `raw` is split directly out of
            // the source text (strict-verbatim, IX-1).
            raw_is_verbatim: true,
            parse_error_lines,
            load_residue,
        })
    }

    /// Reconstruct multi-file subagent trees from a flat set of loaded sessions.
    ///
    /// Codex stores subagents as separate rollout files linked to their parent
    /// by `lineage["parent_thread_id"]` (→ the parent's `session_id`). Given a
    /// collection of sessions, this nests each child into its parent's
    /// [`Session::subagents`] and returns only the roots. Children whose parent
    /// isn't in the set are returned as roots themselves (best effort).
    pub fn reconstruct_tree(sessions: Vec<Session>) -> Vec<Session> {
        use std::collections::HashMap;
        // Index each session's position by its session_id.
        let mut idx: HashMap<String, usize> = HashMap::new();
        for (i, s) in sessions.iter().enumerate() {
            if let Some(id) = &s.meta.session_id {
                idx.insert(id.clone(), i);
            }
        }
        // Determine each session's parent (by index), if present in the set.
        let parent_of: Vec<Option<usize>> = sessions
            .iter()
            .map(|s| {
                s.meta
                    .lineage
                    .get("parent_thread_id")
                    .and_then(|p| idx.get(p).copied())
            })
            .collect();

        // Move children into parents, deepest-first so chains nest correctly.
        let mut slots: Vec<Option<Session>> = sessions.into_iter().map(Some).collect();
        let mut order: Vec<usize> = (0..slots.len()).collect();
        order.sort_by_key(|&i| std::cmp::Reverse(depth_of(i, &parent_of)));
        for i in order {
            if let Some(p) = parent_of[i] {
                if p != i {
                    if let Some(child) = slots[i].take() {
                        if let Some(parent) = slots[p].as_mut() {
                            parent.subagents.push(child);
                        } else {
                            slots[i] = Some(child); // parent already moved; keep as root
                        }
                    }
                }
            }
        }
        slots.into_iter().flatten().collect()
    }

    /// Parse a session of a known format from an in-memory JSONL string.
    pub fn load_str(jsonl: &str, format: SessionFormat) -> Result<Session> {
        match format {
            SessionFormat::ClaudeCode => Self::from_claude_code_str(jsonl),
            SessionFormat::Codex => Self::from_codex_str(jsonl),
            SessionFormat::Pi => Self::from_pi_str(jsonl),
            SessionFormat::OpenCode => Self::from_opencode_str(jsonl),
            SessionFormat::Grok => Self::from_grok_str(jsonl),
            SessionFormat::Gemini => Self::from_gemini_str(jsonl),
            SessionFormat::Goose => Self::from_goose_str(jsonl),
        }
    }

    /// Serialize this session to JSONL in the given format.
    ///
    /// The conversation is synthesized from the canonical messages, so this
    /// works for sessions loaded from *either* tool as well as ones supercode
    /// built itself. Converting between formats (e.g. Codex → Claude Code) is an
    /// "export": format-specific framing that has no slot in the target may be
    /// dropped, but the user/assistant/tool conversation is preserved.
    pub fn to_jsonl(&self, format: SessionFormat) -> Result<String> {
        match format {
            SessionFormat::ClaudeCode => Ok(self.to_claude_code_jsonl()),
            SessionFormat::Codex => Ok(self.to_codex_jsonl()),
            SessionFormat::Pi => Ok(self.to_pi_jsonl()),
            SessionFormat::OpenCode => self.to_opencode_jsonl(),
            SessionFormat::Grok => Ok(self.to_grok_jsonl()),
            SessionFormat::Gemini => Ok(self.to_gemini_jsonl()),
            SessionFormat::Goose => Ok(self.to_goose_json()),
        }
    }

    /// Export back to `format`, replaying the imported `raw` prefix
    /// **verbatim** — original uuids/ids, real timestamps, and
    /// loader-skipped records (e.g. Claude Code `file-history-snapshot`) that
    /// [`Self::to_jsonl`]'s full synthesis discards or fakes — when `format`
    /// is the session's own origin (`format.source() == self.meta.source`,
    /// see [`SessionFormat::source`]) and there is a `raw` prefix to replay.
    /// Only messages appended *after* import (tracked by
    /// [`Self::imported_message_count`]) are synthesized, chained onto the
    /// last original record found in the raw prefix.
    ///
    /// `session_id` of `Some(new)` rewrites the session id on every emitted
    /// line, raw and synthesized alike (`sessionId` for Claude Code,
    /// `session_meta.payload.id` for Codex); `None` leaves ids as recorded.
    ///
    /// Cross-format export (no verbatim prefix exists in the target dialect,
    /// by definition) and a session with no `raw` lines both fall back
    /// unchanged to [`Self::to_jsonl`] — full synthesis, same output as
    /// today. A12 (SPEC.md §6): this turns "export back to origin" from
    /// *semantic* to *near-byte* fidelity for the dominant hop-back case;
    /// cross-format stays at the documented semantic tier.
    pub fn to_jsonl_spliced(
        &self,
        format: SessionFormat,
        session_id: Option<&str>,
    ) -> Result<String> {
        if self.parse_error_lines > 0
            || self
                .subagents
                .iter()
                .any(|subagent| subagent.parse_error_lines > 0)
        {
            return Err(Error::InvalidSession(
                "refusing spliced export because the loaded session contains parse loss"
                    .to_string(),
            ));
        }
        if self.raw.is_empty() || format.source() != self.meta.source {
            if let Some(session_id) = session_id {
                let mut rewritten = self.clone();
                rewritten.meta.session_id = Some(session_id.to_string());
                return rewritten.to_jsonl(format);
            }
            return self.to_jsonl(format);
        }
        match format {
            SessionFormat::ClaudeCode => Ok(self.to_claude_code_jsonl_spliced(session_id)),
            SessionFormat::Codex => Ok(self.to_codex_jsonl_spliced(session_id)),
            SessionFormat::Pi => self.to_pi_jsonl_spliced(session_id),
            SessionFormat::OpenCode => self.to_opencode_jsonl_spliced(session_id),
            SessionFormat::Grok => Ok(self.to_grok_jsonl_spliced()),
            SessionFormat::Gemini => Ok(self.to_gemini_jsonl_spliced(session_id)),
            SessionFormat::Goose => Ok(self.to_goose_json_spliced(session_id)),
        }
    }

    /// Write this session to `path` in the given format.
    pub fn save(&self, path: impl AsRef<Path>, format: SessionFormat) -> Result<()> {
        std::fs::write(path.as_ref(), self.to_jsonl(format)?)?;
        Ok(())
    }

    /// Reconstruct the exact source bytes this `Session` was loaded from,
    /// out of [`Self::raw`] + [`Self::raw_trailing_newline`] (the exact
    /// inverse of the strict-verbatim capture those two fields record — see
    /// `join_lines_verbatim`).
    ///
    /// For a genuinely line-oriented source (Claude Code, Codex, Pi, and an
    /// OpenCode *envelope*-form JSONL), `raw` is captured verbatim from the
    /// original text, so this reproduces the original file byte-for-byte —
    /// the P008/P009 diagonal-convert fix (`convert <file> --to
    /// <same-format>` is byte-identical to `<file>`) is built on exactly
    /// this. The one documented exception is an OpenCode **export-document**
    /// source (a single pretty-printed JSON value, not JSONL): `raw` there
    /// is RE-SYNTHESIZED as one envelope line per record (see
    /// `from_opencode_export_doc`'s contract), so this returns a
    /// verbatim reproduction of THAT captured representation rather than the
    /// original pretty-printed document — a known, narrow residue, not a
    /// silent loss (the same records are all still present).
    pub fn raw_verbatim(&self) -> String {
        join_lines_verbatim(&self.raw, self.raw_trailing_newline)
    }

    /// Serialize to the **supercode-native** lossless format: a header line
    /// recording the original source, followed by every original JSONL line
    /// verbatim. Unlike [`Self::to_jsonl`] (which targets a foreign tool's
    /// schema and is necessarily lossy), this preserves *everything* — including
    /// records with no canonical representation — so [`Self::from_native_str`]
    /// reconstructs the session with full fidelity.
    pub fn to_native_jsonl(&self) -> String {
        let source = match self.meta.source {
            SessionSource::ClaudeCode => "claude_code",
            SessionSource::Codex => "codex",
            SessionSource::Pi => "pi",
            SessionSource::OpenCode => "opencode",
            SessionSource::Grok => "grok",
            SessionSource::Gemini => "gemini",
            SessionSource::Goose => "goose",
            // P5-3 safety-hardening fix: a natively-spawned session must
            // never be written to disk labeled as an imported CC session.
            SessionSource::Native => "native",
        };
        let header = serde_json::json!({
            "supercode_native": 1,
            "source": source,
            // IX-1: carries whether the ORIGINAL imported source text ended
            // with a trailing newline — `from_native_str` needs this to
            // reconstruct the exact source bytes (not just the `raw` line
            // list) when re-parsing the body with the per-source loader.
            "raw_trailing_newline": self.raw_trailing_newline,
        })
        .to_string();
        let mut out =
            String::with_capacity(self.raw.iter().map(|l| l.len() + 1).sum::<usize>() + 64);
        out.push_str(&header);
        out.push('\n');
        for line in &self.raw {
            out.push_str(line);
            out.push('\n');
        }
        out
    }

    /// Serialize to the **supercode-native v2** format: the same imported-body
    /// mechanism as [`Self::to_native_jsonl`] (a versioned header line
    /// followed by every `Session.raw` line verbatim), plus one
    /// [`crate::sidecar::NativeTurn`] record per message in `appended` — turns
    /// produced after import, which have no backing `raw` line of their own.
    /// `NativeTurn` carries `metadata` in full (unlike `ChatMessage`'s wire
    /// serde), so nothing the live agent loop records is lost to disk.
    ///
    /// `appended` is caller-supplied rather than inferred from
    /// `self.messages`: A1 doesn't track which of `self.messages` came from
    /// import vs. the live loop — that bookkeeping belongs to the live writer
    /// built on top of this (A2/A3).
    pub fn to_native_jsonl_v2(&self, appended: &[ChatMessage]) -> String {
        self.to_native_jsonl_v2_with_timestamp(appended, None)
    }

    pub(crate) fn to_native_jsonl_v2_with_timestamp(
        &self,
        appended: &[ChatMessage],
        fixed_timestamp: Option<&str>,
    ) -> String {
        let source = match self.meta.source {
            SessionSource::ClaudeCode => "claude_code",
            SessionSource::Codex => "codex",
            SessionSource::Pi => "pi",
            SessionSource::OpenCode => "opencode",
            SessionSource::Grok => "grok",
            SessionSource::Gemini => "gemini",
            SessionSource::Goose => "goose",
            // P5-3 safety-hardening fix: a natively-spawned session must
            // never be written to disk labeled as an imported CC session.
            SessionSource::Native => "native",
        };
        // P5-3 (§2 module 9, §5.2 P5 row 3 "native write side — store
        // already parses CC sidechains + CX lineage on import"): a
        // natively-spawned subagent's own `Session` carries its lineage on
        // `SessionMeta` (`agent_id`/`parent_tool_use_id`/`lineage`) — before
        // this, `to_native_jsonl_v2` never wrote any of the three to disk at
        // all, so a native-spawned child's lineage was lost the instant it
        // round-tripped through a sidecar. Emitted only when non-empty/`Some`
        // (`skip_serializing_if`-equivalent via manual omission below) so a
        // plain top-level session's header is byte-identical to before this
        // change.
        let mut header_obj = serde_json::json!({
            "supercode_native": 2,
            "source": source,
            "session_id": self.meta.session_id,
            "created": fixed_timestamp
                .map(ToOwned::to_owned)
                .unwrap_or_else(crate::sidecar::now_rfc3339),
            // IX-1: see `to_native_jsonl`'s header field of the same name.
            "raw_trailing_newline": self.raw_trailing_newline,
        });
        if let Some(obj) = header_obj.as_object_mut() {
            if let Some(agent_id) = &self.meta.agent_id {
                obj.insert("agent_id".to_string(), Value::String(agent_id.clone()));
            }
            if let Some(parent_tool_use_id) = &self.meta.parent_tool_use_id {
                obj.insert(
                    "parent_tool_use_id".to_string(),
                    Value::String(parent_tool_use_id.clone()),
                );
            }
            if !self.meta.lineage.is_empty() {
                obj.insert(
                    "lineage".to_string(),
                    serde_json::to_value(&self.meta.lineage).unwrap_or(Value::Null),
                );
            }
        }
        let header = header_obj.to_string();
        let mut out =
            String::with_capacity(self.raw.iter().map(|l| l.len() + 1).sum::<usize>() + 64);
        out.push_str(&header);
        out.push('\n');
        for line in &self.raw {
            out.push_str(line);
            out.push('\n');
        }
        for (turn_index, msg) in appended.iter().enumerate() {
            let turn = match fixed_timestamp {
                Some(timestamp) => crate::sidecar::NativeTurn::from_with_timestamp_and_index(
                    msg,
                    timestamp.to_string(),
                    turn_index as u64,
                ),
                None => crate::sidecar::NativeTurn::from_with_timestamp_and_index(
                    msg,
                    crate::sidecar::now_rfc3339(),
                    turn_index as u64,
                ),
            };
            out.push_str(&serde_json::to_string(&turn).unwrap_or_default());
            out.push('\n');
        }
        out
    }

    /// Parse the supercode-native format produced by [`Self::to_native_jsonl`]
    /// / [`Self::to_native_jsonl_v2`]. A v1 file (no appended turns) parses
    /// exactly as before. A v2 file's appended `NativeTurn` records —
    /// discriminated by the `supercode_turn` key, which never appears in a v1
    /// body — are split out before the imported body is handed to the
    /// per-source loader, then reattached in file order: to `messages` (via
    /// [`crate::sidecar::NativeTurn::into_message`]) and to `raw` (verbatim),
    /// so a v2 file round-trips byte-for-byte through
    /// [`Self::to_native_jsonl_v2`] again.
    pub fn from_native_str(jsonl: &str) -> Result<Session> {
        // IX-1: the native WRAPPER's own lines are split verbatim (not via
        // the blank-skipping `non_empty_lines`) so that any `raw` line it
        // carries — which can itself be blank, CRLF-terminated, or
        // whitespace-padded, now that raw-capture is strict-verbatim —
        // survives being embedded in (and re-extracted from) this wrapper
        // bit-for-bit. The wrapper we ourselves emit never has a blank line
        // of its own (`to_native_jsonl(_v2)` always writes one well-formed
        // record per line), so this is a behavior-preserving switch for any
        // native text this crate produced; it also makes a hand-fed/legacy
        // native string tolerated exactly as `non_empty_lines` used to.
        let (all_lines, _wrapper_trailing_newline) = split_lines_verbatim(jsonl);
        let mut lines = all_lines.into_iter();
        let header = lines.next().unwrap_or("");
        let hv: Value = serde_json::from_str(header).unwrap_or(Value::Null);
        let source = hv.get("source").and_then(Value::as_str);
        // IX-1: whether the ORIGINAL imported source (before it was wrapped
        // in this native format) ended with a trailing newline — a property
        // of the pre-wrap source, not of this wrapper (which always
        // LF-terminates every line it writes, regardless). Missing on a
        // native file written before IX-1 (or a hand-built header in an
        // older test/sidecar) — default `true`, the historical
        // always-newline-terminated assumption.
        let raw_trailing_newline = hv
            .get("raw_trailing_newline")
            .and_then(Value::as_bool)
            .unwrap_or(true);

        // Split appended NativeTurn records (v2) out of the imported body. A
        // v1 body never carries a `supercode_turn` key, so this is a no-op
        // there — one code path serves both versions.
        let mut body_lines: Vec<String> = Vec::new();
        let mut turn_lines: Vec<&str> = Vec::new();
        for line in lines {
            let is_turn = serde_json::from_str::<Value>(line)
                .ok()
                .is_some_and(|v| v.get("supercode_turn").is_some());
            if is_turn {
                turn_lines.push(line);
            } else {
                body_lines.push(line.to_string());
            }
        }
        // IX-1: reconstruct the ORIGINAL imported source bytes exactly —
        // `body_lines.join("\n")` alone would silently gain a trailing
        // newline the original source never had (or lose one it did have).
        let body = join_lines_verbatim(&body_lines, raw_trailing_newline);

        // The remaining lines are the original log; re-parse with the right loader.
        let mut session = match source {
            Some("codex") => Self::from_codex_str(&body)?,
            Some("claude_code") => Self::from_claude_code_str(&body)?,
            Some("pi") => Self::from_pi_str(&body)?,
            Some("opencode") => Self::from_opencode_str(&body)?,
            Some("grok") => Self::from_grok_str(&body)?,
            Some("gemini") => Self::from_gemini_str(&body)?,
            Some("goose") => Self::from_goose_str(&body)?,
            // P5-3 safety-hardening fix: a natively-spawned session's body
            // is always empty (it never had any foreign-tool prefix to
            // begin with — see `SessionSource::Native`'s doc comment), so
            // any loader would parse it identically; `from_claude_code_str`
            // is reused purely as a blank-skeleton builder (empty
            // `raw`/`messages`), then its `meta.source` is corrected to
            // `Native` — never left mislabeled as `ClaudeCode`.
            Some("native") => {
                let mut s = Self::from_claude_code_str(&body)?;
                s.meta.source = SessionSource::Native;
                s
            }
            // No/unknown header — auto-detect the body.
            _ => match detect_source(&body) {
                Some(SessionSource::Codex) => Self::from_codex_str(&body)?,
                Some(SessionSource::Pi) => Self::from_pi_str(&body)?,
                Some(SessionSource::OpenCode) => Self::from_opencode_str(&body)?,
                Some(SessionSource::Grok) => Self::from_grok_str(&body)?,
                Some(SessionSource::Gemini) => Self::from_gemini_str(&body)?,
                Some(SessionSource::Goose) => Self::from_goose_str(&body)?,
                _ => Self::from_claude_code_str(&body)?,
            },
        };

        for line in turn_lines {
            match serde_json::from_str::<crate::sidecar::NativeTurn>(line) {
                Ok(turn) => {
                    session.raw.push(line.to_string());
                    session.messages.push(turn.into_message());
                }
                Err(_) => {
                    // A valid JSON object carrying the native-turn
                    // discriminator belongs to this wrapper, not to the
                    // imported body. If its required fields are malformed,
                    // count it as parse loss so every fail-loud caller can
                    // refuse continuation instead of silently dropping a
                    // native history record. Keep the rejected source line
                    // in `raw` as well: diagnostics must count it in their
                    // denominator, and even corrupt input must not disappear
                    // merely because it reached the parser.
                    session.raw.push(line.to_string());
                    session.parse_error_lines += 1;
                }
            }
        }

        // P5-3 (native write side, see `Self::to_native_jsonl_v2`'s matching
        // header block): recover a natively-spawned subagent's own lineage
        // from the v2 header, when present. Overlays (rather than merges
        // into) whatever the per-source body loader may have already set on
        // `session.meta` — these three keys are ONLY ever written by
        // `to_native_jsonl_v2` itself (never by a CC/CX/OC/Pi body), so a
        // header that carries them is authoritative for a file this crate
        // produced.
        if let Some(agent_id) = hv.get("agent_id").and_then(Value::as_str) {
            session.meta.agent_id = Some(agent_id.to_string());
        }
        if let Some(parent_tool_use_id) = hv.get("parent_tool_use_id").and_then(Value::as_str) {
            session.meta.parent_tool_use_id = Some(parent_tool_use_id.to_string());
        }
        if let Some(lineage) = hv.get("lineage").and_then(Value::as_object) {
            for (k, v) in lineage {
                if let Some(s) = v.as_str() {
                    session.meta.lineage.insert(k.clone(), s.to_string());
                }
            }
        }

        Ok(session)
    }

    /// The full-fidelity [`Session`] a sidecar denotes.
    ///
    /// The sidecar (native-v2 format, D1) is the imported body plus every
    /// appended [`crate::sidecar::NativeTurn`]. Unlike the deliberately
    /// tolerant lower-level native parser, this persisted-store entry point
    /// validates its framing header before loading anything: a missing,
    /// malformed, or unsupported header must never become a zero-message
    /// session that callers could continue as if it were complete.
    pub fn from_sidecar_str(s: &str) -> Result<Session> {
        let header = s.lines().next().ok_or_else(|| {
            Error::InvalidSession("sidecar header is missing from an empty artifact".to_string())
        })?;
        let value: Value = serde_json::from_str(header).map_err(|error| {
            Error::InvalidSession(format!("sidecar header is not valid JSON: {error}"))
        })?;
        let version = value.get("supercode_native").and_then(Value::as_u64);
        if !matches!(version, Some(1 | 2)) {
            return Err(Error::InvalidSession(
                "sidecar header must declare supported `supercode_native` version 1 or 2"
                    .to_string(),
            ));
        }
        let source = value.get("source").and_then(Value::as_str);
        if !matches!(
            source,
            Some(
                "native"
                    | "claude_code"
                    | "codex"
                    | "gemini"
                    | "goose"
                    | "opencode"
                    | "pi"
                    | "grok"
            )
        ) {
            return Err(Error::InvalidSession(
                "sidecar header must declare a supported `source`".to_string(),
            ));
        }
        Self::from_native_str(s)
    }

    /// Parse a Codex rollout from an in-memory JSONL string.
    pub fn from_codex_str(jsonl: &str) -> Result<Session> {
        let mut meta = SessionMeta::new(SessionSource::Codex);
        let mut messages = Vec::new();

        // First pass: collect the text of every assistant message that exists as
        // a canonical `response_item`. In normal sessions the streamed
        // `event_msg/agent_message` events duplicate these and are safely
        // skipped; in collab/multi-agent sessions the assistant narration lives
        // ONLY as `agent_message` events, so we recover the ones with no
        // response_item counterpart (deduping by exact text).
        let assistant_texts = collect_codex_assistant_texts(jsonl);
        // IX-1: strict-verbatim raw capture — see `from_claude_code_str`.
        let (raw_lines, raw_trailing_newline) = split_lines_verbatim(jsonl);
        let raw: Vec<String> = raw_lines.iter().map(|l| l.to_string()).collect();
        let mut pending_reasoning = String::new();
        let mut pending_reasoning_content = String::new();
        let mut pending_reasoning_encrypted = false;
        // PARITY-15: see `from_claude_code_str`'s identical counter.
        let mut parse_error_lines = 0usize;
        let mut restored_embedded_codex_provenance = false;

        for (record_index, raw_line) in raw_lines.iter().enumerate() {
            let line = raw_line.trim();
            if line.is_empty() {
                continue;
            }
            let v: Value = match serde_json::from_str(line) {
                Ok(v) => v,
                Err(_) => {
                    parse_error_lines += 1;
                    continue;
                }
            };
            let payload = v.get("payload").unwrap_or(&Value::Null);
            if !restored_embedded_codex_provenance
                && v.get("type").and_then(Value::as_str) == Some("session_meta")
                && payload
                    .get(SUPERCODE_CODEX_PROVENANCE_KEY)
                    .map(|extension| restore_codex_provenance(extension, &mut meta))
                    .transpose()?
                    .unwrap_or(false)
            {
                restored_embedded_codex_provenance = true;
            }
            if !restored_embedded_codex_provenance {
                capture_codex_provenance_record(&mut meta, record_index, raw_line, &v);
            }
            // WAVE-2 item 1: every Codex record carries a real top-level
            // `timestamp` (ISO-8601) — threaded onto each `ChatMessage` a
            // line produces via `stamp_new_codex_messages` below, at each
            // arm that pushes messages.
            let line_ts = v.get("timestamp").and_then(Value::as_str);

            match v.get("type").and_then(Value::as_str) {
                Some("session_meta") => {
                    capture_codex_session_meta(payload, &mut meta);
                    if !restored_embedded_codex_provenance {
                        meta.codex_headers.push(v.clone());
                    }
                }
                Some("turn_context") => {
                    if meta.model.is_none() {
                        meta.model = payload
                            .get("model")
                            .and_then(Value::as_str)
                            .map(str::to_string);
                    }
                    if !restored_embedded_codex_provenance {
                        meta.codex_headers.push(v.clone());
                    }
                }
                Some("response_item")
                    if payload.get("type").and_then(Value::as_str) == Some("reasoning") =>
                {
                    // Retain reasoning (P3): summary text if any, the raw
                    // `content` chain-of-thought text if any (N2 — this used
                    // to be dropped despite `Coverage::Retained` claiming the
                    // whole item survived; see `crate::audit`'s doc comment),
                    // plus a flag for the opaque encrypted_content a
                    // same-model continuation can replay. Stashed onto the
                    // next assistant message below.
                    let summary = extract_text_content(payload.get("summary"));
                    if !summary.trim().is_empty() {
                        push_str_field(&mut pending_reasoning, &summary);
                    }
                    // N2: `content` is `null` on the vast majority of real
                    // turns (raw reasoning text is only ever populated for
                    // certain reasoning-transcript configurations) — guard
                    // on non-null BEFORE calling `extract_text_content`,
                    // since `Some(&Value::Null)` would otherwise fall into
                    // its `Some(other) => other.to_string()` arm and
                    // stringify to the literal text `"null"`.
                    if let Some(raw_content) = payload.get("content").filter(|v| !v.is_null()) {
                        let text = extract_text_content(Some(raw_content));
                        if !text.trim().is_empty() {
                            push_str_field(&mut pending_reasoning_content, &text);
                        }
                    }
                    // N1: `serde_json` returns `Some(&Value::Null)` for a
                    // present-but-null `encrypted_content` key — which is
                    // what EVERY real rollout's reasoning item carries
                    // (upstream always serializes the field, never
                    // `skip_serializing_if`, `codex-rs/protocol/src/
                    // models.rs:970-983`). The old `.is_some()` check
                    // false-flagged every single reasoning item as
                    // "encrypted" on real data; only a genuinely non-null
                    // value means the model actually returned an opaque
                    // blob that a same-model continuation could replay.
                    if payload
                        .get("encrypted_content")
                        .is_some_and(|v| !v.is_null())
                    {
                        pending_reasoning_encrypted = true;
                    }
                }
                Some("response_item") => {
                    let before = messages.len();
                    push_codex_item(payload, &mut messages);
                    // Attach any pending reasoning to a newly produced assistant turn.
                    if messages.len() > before
                        && (!pending_reasoning.is_empty()
                            || !pending_reasoning_content.is_empty()
                            || pending_reasoning_encrypted)
                    {
                        let is_assistant = messages
                            .last()
                            .map(|m| m.role == Role::Assistant)
                            .unwrap_or(false);
                        if is_assistant {
                            let last = messages.last_mut().expect("checked above");
                            if !pending_reasoning.is_empty() {
                                last.metadata.insert(
                                    "reasoning".to_string(),
                                    std::mem::take(&mut pending_reasoning),
                                );
                            }
                            if !pending_reasoning_content.is_empty() {
                                last.metadata.insert(
                                    "reasoning_content".to_string(),
                                    std::mem::take(&mut pending_reasoning_content),
                                );
                            }
                            if pending_reasoning_encrypted {
                                last.metadata
                                    .insert("reasoning_encrypted".to_string(), "true".to_string());
                                pending_reasoning_encrypted = false;
                            }
                        } else {
                            // N3: the item that just landed is NOT the
                            // assistant turn the pending reasoning was for
                            // (e.g. an aborted turn's reasoning directly
                            // followed by a user message) — the old code
                            // unconditionally cleared the pending state
                            // here, silently discarding it. Flush it as its
                            // own message instead, inserted just before the
                            // interrupting item so replay order stays
                            // chronological, keeping `Coverage::Retained`
                            // honest for this shape too.
                            let orphan = orphaned_reasoning_message(
                                &mut pending_reasoning,
                                &mut pending_reasoning_content,
                                &mut pending_reasoning_encrypted,
                            );
                            messages.insert(before, orphan);
                        }
                    }
                    stamp_new_codex_messages(&mut messages, before, line_ts);
                    restore_single_grok_message(payload, &mut messages[before..]);
                }
                // A compaction record replaces all prior turns with its
                // summarized `replacement_history` — exactly how Codex itself
                // resumes a compacted session.
                Some("compacted") => {
                    messages.clear();
                    if let Some(Value::Array(history)) = payload.get("replacement_history") {
                        for item in history {
                            push_codex_item(item, &mut messages);
                        }
                    }
                    // `replacement_history` items carry no per-item
                    // timestamp of their own (observed corpora) — the
                    // `compacted` record's own timestamp (when it happened)
                    // is the best-effort real source for every message it
                    // synthesizes, so it stamps the whole rebuilt vec (index
                    // 0, since `clear()` reset it above).
                    stamp_new_codex_messages(&mut messages, 0, line_ts);
                    // IX-6 fix: replaying `replacement_history` through
                    // `push_codex_item` can leave the LAST replayed message
                    // marked `__codex_open_turn` (if it's an assistant
                    // `message`, per the combined-turn merge below). That
                    // marker must not survive past the compaction boundary —
                    // a live `function_call` arriving after this record is a
                    // NEW turn, not a continuation of the compaction
                    // summary's synthetic turn, so it must not merge into it.
                    if let Some(last) = messages.last_mut() {
                        last.metadata.remove("__codex_open_turn");
                    }
                }
                Some("event_msg")
                    if payload.get("type").and_then(Value::as_str) == Some("agent_message") =>
                {
                    let before = messages.len();
                    let text = agent_message_text(payload);
                    if !text.trim().is_empty() && !assistant_texts.contains(text.trim()) {
                        push_assistant(&mut messages, text, Vec::new());
                        if let Some(last) = messages.last_mut() {
                            if let Some(phase) = payload.get("phase").and_then(Value::as_str) {
                                last.metadata.insert("phase".to_string(), phase.to_string());
                            }
                        }
                    }
                    stamp_new_codex_messages(&mut messages, before, line_ts);
                }
                // The user rolled back (undid) the last N turns — replay must
                // drop them so the reloaded conversation matches what the user
                // actually kept.
                Some("event_msg")
                    if payload.get("type").and_then(Value::as_str)
                        == Some("thread_rolled_back") =>
                {
                    let n = payload
                        .get("num_turns")
                        .and_then(Value::as_u64)
                        .unwrap_or(1);
                    for _ in 0..n {
                        remove_last_turn(&mut messages);
                    }
                }
                // The natural-language goal assigned to this thread (sometimes
                // the only place the objective text is recorded).
                Some("event_msg")
                    if payload.get("type").and_then(Value::as_str)
                        == Some("thread_goal_updated") =>
                {
                    let before = messages.len();
                    let goal = payload.get("goal");
                    if let Some(obj) = goal
                        .and_then(|g| g.get("objective"))
                        .and_then(Value::as_str)
                    {
                        if !obj.trim().is_empty() {
                            messages.push(ChatMessage::system(format!("[thread goal] {obj}")));
                            // D4: `goal.objective` alone used to be the ONLY
                            // captured field, but the audit labeled this
                            // `Retained` as if the whole record survived.
                            // `goal.status`/`goal.tokenBudget` (real
                            // `ThreadGoal` wire fields, camelCase) are
                            // captured too so that label is honest — see
                            // `crate::audit::event_msg_coverage`'s doc
                            // comment.
                            if let Some(last) = messages.last_mut() {
                                if let Some(status) =
                                    goal.and_then(|g| g.get("status")).and_then(Value::as_str)
                                {
                                    last.metadata
                                        .insert("goal_status".to_string(), status.to_string());
                                }
                                if let Some(budget) = goal
                                    .and_then(|g| g.get("tokenBudget"))
                                    .and_then(Value::as_i64)
                                {
                                    last.metadata.insert(
                                        "goal_token_budget".to_string(),
                                        budget.to_string(),
                                    );
                                }
                            }
                        }
                    }
                    stamp_new_codex_messages(&mut messages, before, line_ts);
                }
                // Code-review output — unique assistant-generated content with no
                // `message` counterpart.
                Some("event_msg")
                    if payload.get("type").and_then(Value::as_str)
                        == Some("exited_review_mode") =>
                {
                    let before = messages.len();
                    if let Some(review) = payload.get("review_output") {
                        let text = review
                            .get("overall_explanation")
                            .and_then(Value::as_str)
                            .map(str::to_string)
                            .unwrap_or_else(|| review.to_string());
                        push_assistant(&mut messages, format!("[code review] {text}"), Vec::new());
                        // D4: `overall_explanation` alone used to be the ONLY
                        // captured field, but the audit labeled this
                        // `Retained` as if `review_output.findings` survived
                        // too. Capture `findings` verbatim (as JSON, onto
                        // metadata) so that label is honest — this is the
                        // only place review-mode findings (title/body/
                        // confidence_score/priority/code_location) live.
                        if let Some(findings) = review.get("findings") {
                            if findings.as_array().is_some_and(|a| !a.is_empty()) {
                                if let Some(last) = messages.last_mut() {
                                    if let Ok(s) = serde_json::to_string(findings) {
                                        last.metadata.insert("review_findings".to_string(), s);
                                    }
                                }
                            }
                        }
                        // N4: `overall_correctness`/`overall_confidence_score`
                        // are the review's actual verdict — distinct from the
                        // findings list and the explanation prose already
                        // captured above — and were neither captured nor
                        // disclosed as residue while the audit doc stayed
                        // silent about them. Capture both onto the same
                        // message's metadata, same pattern as `findings`.
                        if let Some(last) = messages.last_mut() {
                            if let Some(correctness) =
                                review.get("overall_correctness").and_then(Value::as_str)
                            {
                                last.metadata.insert(
                                    "review_overall_correctness".to_string(),
                                    correctness.to_string(),
                                );
                            }
                            if let Some(score) = review
                                .get("overall_confidence_score")
                                .and_then(Value::as_f64)
                            {
                                last.metadata.insert(
                                    "review_overall_confidence_score".to_string(),
                                    score.to_string(),
                                );
                            }
                        }
                    }
                    stamp_new_codex_messages(&mut messages, before, line_ts);
                }
                _ => {} // other event_msg, token_count, ... — UI events, skip
            }
        }

        // N3/PARITY-11: reasoning still pending at EOF is an aborted-turn
        // shape a real rollout can leave behind (the process was
        // interrupted mid-turn, after the model reasoned but before it
        // replied — end of file, or a rollback/compaction boundary that
        // clears the pending state some other way) — the old code silently
        // dropped it here (nothing ever consumed the pending buffers once
        // the loop ended). Flush it as its own trailing message instead, so
        // `Coverage::Retained` holds for this shape too. Superset of the
        // independently-discovered PARITY-11 fix: also folds in
        // `pending_reasoning_content` (the raw chain-of-thought, distinct
        // from `summary`/`reasoning`) via the shared `orphaned_reasoning_
        // message` helper, which the interrupted-by-a-user-message shape
        // (`orphaned_reasoning_is_flushed_not_discarded`, case A) also
        // relies on — a trailing-EOF-only flush here would miss that case.
        if !pending_reasoning.is_empty()
            || !pending_reasoning_content.is_empty()
            || pending_reasoning_encrypted
        {
            let orphan = orphaned_reasoning_message(
                &mut pending_reasoning,
                &mut pending_reasoning_content,
                &mut pending_reasoning_encrypted,
            );
            messages.push(orphan);
        }

        ensure_tool_results_paired(&mut messages);
        // IX-6: `__codex_open_turn` is an internal bookkeeping marker for the
        // combined-turn merge above — strip it so it never leaks out as
        // visible `ChatMessage` metadata.
        for m in &mut messages {
            m.metadata.remove("__codex_open_turn");
            if m.metadata
                .remove("__grok_remove_synthetic_turn_id")
                .is_some()
            {
                m.metadata.remove("turn_id");
            }
        }
        let imported_message_count = Some(messages.len());
        Ok(Session {
            meta,
            messages,
            subagents: Vec::new(),
            raw,
            raw_trailing_newline,
            imported_message_count,
            // Codex is line-oriented: `raw` is split directly out of the
            // source text (strict-verbatim, IX-1).
            raw_is_verbatim: true,
            parse_error_lines,
            load_residue: Vec::new(),
        })
    }

    /// Parse a Codex rollout as bounded human-visible history rather than as
    /// resumable model context. This deliberately ignores outer `compacted`
    /// replacement semantics: the original `response_item` records remain in
    /// the rollout and are the authoritative UI history.
    fn from_codex_display_str(jsonl: &str, message_limit: usize) -> Result<Session> {
        let mut meta = SessionMeta::new(SessionSource::Codex);
        let mut messages: Vec<ChatMessage> = Vec::new();
        let mut preceding_users = Vec::new();
        let mut parse_error_lines = 0usize;
        let mut record_count = 0usize;
        let mut total_message_count = 0usize;
        let retain = message_limit.max(1).saturating_add(64);
        let mut canonical_assistant_texts = HashSet::new();

        for raw_line in non_empty_lines(jsonl) {
            record_count += 1;
            let value: Value = match serde_json::from_str(raw_line) {
                Ok(value) => value,
                Err(_) => {
                    parse_error_lines += 1;
                    continue;
                }
            };
            let payload = value.get("payload").unwrap_or(&Value::Null);
            let line_ts = value.get("timestamp").and_then(Value::as_str);
            match value.get("type").and_then(Value::as_str) {
                Some("session_meta") => capture_codex_session_meta(payload, &mut meta),
                Some("turn_context") if meta.model.is_none() => {
                    meta.model = payload
                        .get("model")
                        .and_then(Value::as_str)
                        .map(str::to_string);
                }
                Some("response_item")
                    if payload.get("type").and_then(Value::as_str) != Some("reasoning") =>
                {
                    let assistant_text = (payload.get("type").and_then(Value::as_str)
                        == Some("message")
                        && payload.get("role").and_then(Value::as_str) == Some("assistant"))
                    .then(|| extract_text_content(payload.get("content")))
                    .filter(|text| !text.trim().is_empty());
                    if let Some(text) = assistant_text.as_deref() {
                        if let Some(index) = messages.iter().rposition(|message| {
                            message.metadata.contains_key("codex_event_message")
                                && message.content.as_deref() == Some(text)
                        }) {
                            messages.remove(index);
                            total_message_count = total_message_count.saturating_sub(1);
                        }
                        canonical_assistant_texts.insert(text.trim().to_string());
                    }
                    let before = messages.len();
                    push_codex_item(payload, &mut messages);
                    total_message_count += messages.len().saturating_sub(before);
                    stamp_new_codex_messages(&mut messages, before, line_ts);
                    restore_single_grok_message(payload, &mut messages[before..]);
                }
                Some("event_msg")
                    if payload.get("type").and_then(Value::as_str) == Some("agent_message") =>
                {
                    let text = agent_message_text(payload);
                    if !text.trim().is_empty() && !canonical_assistant_texts.contains(text.trim()) {
                        let before = messages.len();
                        push_assistant(&mut messages, text, Vec::new());
                        total_message_count += 1;
                        if let Some(last) = messages.last_mut() {
                            last.metadata
                                .insert("codex_event_message".to_string(), "true".to_string());
                            if let Some(phase) = payload.get("phase").and_then(Value::as_str) {
                                last.metadata.insert("phase".to_string(), phase.to_string());
                            }
                        }
                        stamp_new_codex_messages(&mut messages, before, line_ts);
                    }
                }
                // `compacted` changes continuation context, not what was
                // already visible in scrollback. Other event records are UI
                // lifecycle noise or duplicate canonical response items.
                _ => {}
            }
            if messages.len() > retain {
                let remove = messages.len() - retain;
                for message in messages.drain(..remove) {
                    if message.role == Role::User {
                        preceding_users.push(message);
                        if preceding_users.len() > 2 {
                            preceding_users.remove(0);
                        }
                    }
                }
            }
        }

        for message in &mut messages {
            message.metadata.remove("__codex_open_turn");
            message.metadata.remove("codex_event_message");
            if message
                .metadata
                .remove("__grok_remove_synthetic_turn_id")
                .is_some()
            {
                message.metadata.remove("turn_id");
            }
        }
        truncate_messages_with_anchor(&mut messages, message_limit, preceding_users);
        let imported_message_count = Some(total_message_count);
        Ok(Session {
            meta,
            messages,
            subagents: Vec::new(),
            // Preserve the cheap count without retaining hundreds of
            // megabytes of source lines in a display-only value.
            raw: vec![String::new(); record_count],
            raw_trailing_newline: jsonl.ends_with('\n'),
            imported_message_count,
            raw_is_verbatim: false,
            parse_error_lines,
            load_residue: vec![
                "display history is a bounded native-record projection, not resumable model context"
                    .to_string(),
            ],
        })
    }

    /// Load a Pi session from a file.
    pub fn from_pi(path: impl AsRef<Path>) -> Result<Session> {
        Self::from_pi_str(&std::fs::read_to_string(path.as_ref())?)
    }

    /// Parse a Pi session (`docs/interop/opencode-pi-spec.md` §1.1,
    /// `docs/interop/research/pi-fields.md`) from an in-memory JSONL string.
    ///
    /// Line 1 is the `session` header; every other line is one `SessionEntry`
    /// in a tree keyed by `id`/`parentId` — file order is append order, not
    /// tree order. `raw` captures every line verbatim (byte-lossless T1,
    /// exactly like Claude Code/Codex). `messages` is the **active path
    /// only**: pi's own leaf rule is "the last entry in file order"
    /// (`pi-fields.md` `sm:897`), so this walks `parentId` from there back to
    /// the root and linearizes root→leaf. Non-active branches, `label`s, and
    /// state records (`thinking_level_change`/`model_change`/`custom`/
    /// `session_info`) are never visited by that walk — they survive in
    /// `raw` only, pi's defining residue (§1.1).
    ///
    /// `message.role` is an OPEN union upstream (§1.1 S6): a role outside the
    /// five modeled here (`user`/`assistant`/`toolResult`/`bashExecution`/
    /// `custom`) produces no canonical message — raw-only survival, never a
    /// panic — and the Pi corpus audit turns that into a
    /// visible coverage failure rather than a silent drop.
    ///
    /// Same fail-loud discipline applies to `ImageContent` blocks
    /// (`user`/`toolResult`/`custom*` content, see `pi_image_shape`): the
    /// assumed `{mimeType, data}` shape is UNVERIFIED against real pi output
    /// (`pi-fields.md` doesn't enumerate `ImageContent`'s own fields, only
    /// cites the containing union) — a follow-up TR tracks confirming it
    /// against a real corpus. Until then, an image block that doesn't match
    /// that shape never gets silently synthesized as an empty/corrupt
    /// `image_url` part; the containing message survives in `raw` only and
    /// trips `crate::audit::Corpus::Pi`'s `message/UnknownImageShape` bucket.
    pub fn from_pi_str(jsonl: &str) -> Result<Session> {
        let mut meta = SessionMeta::new(SessionSource::Pi);
        // IX-1: `raw` is captured STRICT-VERBATIM — separate from the
        // blank-skipping PARSE walk (`lines_v`) below, which must keep
        // skipping blank/whitespace-only lines when it looks for `SessionEntry`
        // records (a blank line is never a record, on either view).
        let (raw_lines, raw_trailing_newline) = split_lines_verbatim(jsonl);
        let raw: Vec<String> = raw_lines.iter().map(|l| l.to_string()).collect();
        let non_empty_line_count = non_empty_lines(jsonl).count();
        let lines_v: Vec<Value> = non_empty_lines(jsonl)
            .filter_map(|l| serde_json::from_str(l).ok())
            .collect();
        // PARITY-15: every line that failed to even deserialize as JSON at
        // all (never mind whether it then parsed as a recognized
        // `SessionEntry` shape) — see `from_claude_code_str`'s identical
        // counter.
        let parse_error_lines = non_empty_line_count.saturating_sub(lines_v.len());

        if let Some(header) = lines_v.first() {
            capture_pi_header(header, &mut meta)?;
        }

        // Every non-header entry that parses as an object carrying an `id`.
        // (A line that fails to parse, or a header re-parsed as an entry,
        // simply never enters `by_id` — it survives in `raw` only, exactly
        // like a malformed/non-conversational line in the other loaders.)
        struct PiEntry {
            id: String,
            parent_id: Option<String>,
            value: Value,
        }
        let mut entries: Vec<PiEntry> = Vec::new();
        let mut by_id: HashMap<String, usize> = HashMap::new();
        for v in lines_v.iter().skip(1) {
            let Some(id) = v.get("id").and_then(Value::as_str) else {
                continue;
            };
            let parent_id = v
                .get("parentId")
                .and_then(Value::as_str)
                .map(str::to_string);
            by_id.insert(id.to_string(), entries.len());
            entries.push(PiEntry {
                id: id.to_string(),
                parent_id,
                value: v.clone(),
            });
        }

        if entries.is_empty() {
            return Ok(Session {
                meta,
                messages: Vec::new(),
                subagents: Vec::new(),
                raw,
                raw_trailing_newline,
                imported_message_count: Some(0),
                // Pi is line-oriented: `raw` is split directly out of the
                // source text (strict-verbatim, IX-1), even for this
                // no-entries early return.
                raw_is_verbatim: true,
                parse_error_lines,
                load_residue: Vec::new(),
            });
        }

        // Leaf = the last entry in file order (pi's own rule, `sm:897`), NOT
        // necessarily a `message` entry — a trailing `label`/`session_info`
        // still anchors the walk correctly since the walk just follows
        // `parentId` regardless of the leaf's own type.
        let leaf_idx = entries.len() - 1;
        let mut chain_rev: Vec<usize> = Vec::new();
        let mut cur: Option<String> = Some(entries[leaf_idx].id.clone());
        let mut guard = 0usize;
        while let Some(id) = cur {
            let Some(&idx) = by_id.get(&id) else { break };
            chain_rev.push(idx);
            cur = entries[idx].parent_id.clone();
            guard += 1;
            if guard > entries.len() + 1 {
                break; // cycle guard — malformed parentId chain
            }
        }
        chain_rev.reverse();
        let active = chain_rev; // indices into `entries`, root..leaf order

        let pos_in_active: HashMap<&str, usize> = active
            .iter()
            .enumerate()
            .map(|(pos, &idx)| (entries[idx].id.as_str(), pos))
            .collect();

        // First pass: compaction discipline (§2.1 S3) — every message from an
        // entry before the LATEST `firstKeptEntryId` on the active path is
        // excluded from replay (`compacted_out`), mirroring pi's own
        // `buildContextEntries` slice (`sm:414-450`).
        let mut kept_from_pos = 0usize;
        for &idx in &active {
            let e = &entries[idx];
            if e.value.get("type").and_then(Value::as_str) == Some("compaction") {
                if let Some(fk) = e.value.get("firstKeptEntryId").and_then(Value::as_str) {
                    if let Some(&p) = pos_in_active.get(fk) {
                        kept_from_pos = kept_from_pos.max(p);
                    }
                }
            }
        }

        let mut messages = Vec::new();
        let mut current_model: Option<String> = None;
        for (pos, &idx) in active.iter().enumerate() {
            let e = &entries[idx];
            let v = &e.value;
            let entry_ts = v
                .get("timestamp")
                .and_then(Value::as_str)
                .map(str::to_string);
            let before = messages.len();
            match v.get("type").and_then(Value::as_str) {
                Some("message") => {
                    let msg_v = v.get("message").cloned().unwrap_or(Value::Null);
                    match msg_v.get("role").and_then(Value::as_str) {
                        Some("user") => push_pi_user(&msg_v, &mut messages),
                        Some("assistant") => {
                            push_pi_assistant(&msg_v, &mut messages);
                            if let Some(m) = msg_v.get("model").and_then(Value::as_str) {
                                current_model = Some(m.to_string());
                            }
                        }
                        Some("toolResult") => push_pi_tool_result(&msg_v, &mut messages),
                        Some("bashExecution") => push_pi_bash(&msg_v, &mut messages),
                        Some("custom") => push_pi_custom_common(&msg_v, &mut messages),
                        // OPEN UNION (S6): any other role — raw-only survival.
                        _ => {}
                    }
                }
                Some("custom_message") => push_pi_custom_common(v, &mut messages),
                Some("compaction") => push_pi_compaction(v, &mut messages),
                Some("branch_summary") => push_pi_branch_summary(v, &mut messages),
                Some("model_change") => {
                    if let Some(m) = v.get("modelId").and_then(Value::as_str) {
                        current_model = Some(m.to_string());
                    }
                }
                Some("session_info") => {
                    if let Some(name) = v.get("name").and_then(Value::as_str) {
                        if !name.is_empty() {
                            meta.lineage
                                .insert("session_name".to_string(), name.to_string());
                        }
                    }
                }
                // thinking_level_change, custom (entry-level state), label —
                // no clean home, raw-only (§2.3).
                _ => {}
            }
            let is_summary = matches!(
                v.get("type").and_then(Value::as_str),
                Some("compaction") | Some("branch_summary")
            );
            for m in &mut messages[before..] {
                m.metadata.insert("pi_entry_id".to_string(), e.id.clone());
                if let Some(p) = &e.parent_id {
                    m.metadata.insert("pi_parent_id".to_string(), p.clone());
                }
                if let Some(ts) = &entry_ts {
                    m.metadata
                        .entry("timestamp".to_string())
                        .or_insert_with(|| ts.clone());
                }
                // WAVE-2 item 1 fallback: the entry-level `timestamp` above
                // is pi's authoritative, always-monotonic-in-file-order
                // wall-clock (mandatory on every entry) and wins whenever
                // present. The nested `message.timestamp` (unix-ms) is only
                // reached here — via `entry(...).or_insert_with`, so it
                // never overwrites the entry-level value — in the rare case
                // an entry lacks its own `timestamp`. This intentionally
                // does NOT prefer the msg-level field even though it LOOKS
                // more precise: unlike the entry-level timestamp, it is not
                // guaranteed monotonic with this loader's root->leaf
                // linearization (e.g. a rewound-branch entry can carry an
                // earlier msg-level clock reading than its file-order
                // neighbors), and OpenCode's own loader re-sorts messages by
                // this canonical timestamp — a non-monotonic source would
                // silently scramble replay order on a pi->opencode hop.
                if let Some(ms) = v
                    .get("message")
                    .and_then(|mm| mm.get("timestamp"))
                    .and_then(Value::as_u64)
                {
                    m.metadata
                        .entry("timestamp".to_string())
                        .or_insert_with(|| crate::sidecar::ms_to_rfc3339(ms as i64));
                }
                // A compaction/branch-summary message IS the retained marker
                // — never mark it excluded, regardless of its own position.
                if !is_summary && pos < kept_from_pos {
                    m.metadata
                        .insert("compacted_out".to_string(), "true".to_string());
                }
            }
            restore_single_grok_message(v, &mut messages[before..]);
            for message in &mut messages[before..] {
                restore_tool_outcome_extension(v, message);
            }
        }

        meta.model = current_model;
        ensure_tool_results_paired(&mut messages);
        let imported_message_count = Some(messages.len());
        Ok(Session {
            meta,
            messages,
            subagents: Vec::new(),
            raw,
            raw_trailing_newline,
            imported_message_count,
            // Pi is line-oriented: `raw` is split directly out of the
            // source text (strict-verbatim, IX-1).
            raw_is_verbatim: true,
            parse_error_lines,
            load_residue: Vec::new(),
        })
    }

    /// Load Grok's resumable `chat_history.jsonl` transcript.
    ///
    /// The surrounding session directory carries the session id, workspace,
    /// and `summary.json`; [`Self::from_grok_str`] handles the transcript
    /// itself while this path-aware entry point overlays that directory
    /// metadata.
    pub fn from_grok(path: impl AsRef<Path>) -> Result<Session> {
        let path = path.as_ref();
        let mut session = Self::from_grok_str(&std::fs::read_to_string(path)?)?;
        session.capture_grok_path_metadata(path);
        Ok(session)
    }

    /// Parse Grok's line-oriented `chat_history.jsonl` format.
    ///
    /// Conversational records are `user`, `assistant`, and `tool_result`.
    /// `system` is the regenerated base prompt and is retained in
    /// [`SessionMeta::system_prompt`]; encrypted reasoning and backend-only
    /// state remain byte-exact in [`Session::raw`] but are intentionally not
    /// replayed as chat turns.
    pub fn from_grok_str(jsonl: &str) -> Result<Session> {
        let mut meta = SessionMeta::new(SessionSource::Grok);
        let (raw_lines, raw_trailing_newline) = split_lines_verbatim(jsonl);
        let raw: Vec<String> = raw_lines.iter().map(|line| line.to_string()).collect();
        let mut messages = Vec::new();
        let mut parse_error_lines = 0usize;
        let mut tool_names: HashMap<String, String> = HashMap::new();

        for line in non_empty_lines(jsonl) {
            let value: Value = match serde_json::from_str(line) {
                Ok(value) => value,
                Err(_) => {
                    parse_error_lines += 1;
                    continue;
                }
            };
            restore_codex_provenance_from_top_level(&value, &mut meta)?;
            match value.get("type").and_then(Value::as_str) {
                Some("system") => {
                    if meta.system_prompt.is_none() {
                        meta.system_prompt = value
                            .get("content")
                            .and_then(Value::as_str)
                            .map(str::to_string);
                    }
                }
                Some("user") => {
                    let content = extract_text_content(value.get("content"));
                    let role = if value.get("synthetic_reason").and_then(Value::as_str)
                        == Some("supercode_system_event")
                    {
                        Role::System
                    } else {
                        Role::User
                    };
                    let content = if role == Role::User {
                        match grok_human_user_text(&content) {
                            Some(content) => content,
                            None if value.get(SUPERCODE_GROK_MESSAGE_KEY).is_some() => {
                                String::new()
                            }
                            None => continue,
                        }
                    } else {
                        content
                    };
                    let mut message = ChatMessage {
                        role,
                        content: Some(content),
                        content_parts: None,
                        tool_calls: None,
                        tool_call_id: None,
                        name: None,
                        metadata: Default::default(),
                    };
                    capture_grok_scalar_metadata(
                        &value,
                        &mut message,
                        &["prompt_index", "prior_turn_interrupt", "synthetic_reason"],
                    );
                    restore_grok_message_extension(&value, &mut message);
                    messages.push(message);
                }
                Some("assistant") => {
                    let calls: Vec<ToolCall> = value
                        .get("tool_calls")
                        .and_then(Value::as_array)
                        .into_iter()
                        .flatten()
                        .filter_map(|call| {
                            let id = call.get("id")?.as_str()?.to_string();
                            let name = call.get("name")?.as_str()?.to_string();
                            let arguments = call
                                .get("arguments")
                                .map(value_to_arg_string)
                                .unwrap_or_else(|| "{}".to_string());
                            tool_names.insert(id.clone(), name.clone());
                            Some(function_call(&id, &name, arguments))
                        })
                        .collect();
                    let content = value
                        .get("content")
                        .and_then(Value::as_str)
                        .filter(|content| !content.is_empty())
                        .map(str::to_string);
                    let mut message = ChatMessage {
                        role: Role::Assistant,
                        content,
                        content_parts: None,
                        tool_calls: (!calls.is_empty()).then_some(calls),
                        tool_call_id: None,
                        name: None,
                        metadata: Default::default(),
                    };
                    capture_grok_scalar_metadata(
                        &value,
                        &mut message,
                        &["model_id", "model_fingerprint", "reasoning_effort"],
                    );
                    if let Some(model) = value.get("model_id").and_then(Value::as_str) {
                        meta.model = Some(model.to_string());
                    }
                    restore_grok_message_extension(&value, &mut message);
                    messages.push(message);
                }
                Some("tool_result") => {
                    let id = value
                        .get("tool_call_id")
                        .and_then(Value::as_str)
                        .unwrap_or_default();
                    let content = value
                        .get("content")
                        .map(|value| match value {
                            Value::String(text) => text.clone(),
                            other => extract_text_content(Some(other)),
                        })
                        .unwrap_or_default();
                    let mut message = tool_message(id, content);
                    message.name = tool_names.get(id).cloned();
                    restore_grok_message_extension(&value, &mut message);
                    messages.push(message);
                }
                // `reasoning` contains encrypted chain-of-thought and
                // `backend_tool_call` is execution bookkeeping. Both survive
                // verbatim in raw without being replayed to another model.
                _ => {}
            }
        }

        ensure_tool_results_paired(&mut messages);
        let imported_message_count = Some(messages.len());
        Ok(Session {
            meta,
            messages,
            subagents: Vec::new(),
            raw,
            raw_trailing_newline,
            imported_message_count,
            raw_is_verbatim: true,
            parse_error_lines,
            load_residue: Vec::new(),
        })
    }

    fn capture_grok_path_metadata(&mut self, transcript: &Path) {
        let Some(session_dir) = transcript.parent() else {
            return;
        };
        self.meta.session_id = session_dir
            .file_name()
            .and_then(|name| name.to_str())
            .map(str::to_string);
        self.meta.cwd = session_dir
            .parent()
            .and_then(Path::file_name)
            .and_then(|name| name.to_str())
            .and_then(percent_decode_path)
            .map(PathBuf::from);

        let Ok(summary_text) = std::fs::read_to_string(session_dir.join("summary.json")) else {
            return;
        };
        let Ok(summary) = serde_json::from_str::<Value>(&summary_text) else {
            return;
        };
        if let Some(model) = summary.get("current_model_id").and_then(Value::as_str) {
            self.meta.model = Some(model.to_string());
        }
        for (source, target) in [
            ("generated_title", "session_name"),
            ("created_at", "created_at"),
            ("updated_at", "updated_at"),
            ("chat_format_version", "grok_chat_format_version"),
        ] {
            if let Some(value) = summary.get(source) {
                self.meta.lineage.insert(
                    target.to_string(),
                    value
                        .as_str()
                        .map(str::to_string)
                        .unwrap_or_else(|| value.to_string()),
                );
            }
        }
    }

    /// Load a Gemini CLI transcript from disk.
    pub fn from_gemini(path: impl AsRef<Path>) -> Result<Session> {
        Self::from_gemini_str(&std::fs::read_to_string(path.as_ref())?)
    }

    /// Parse Gemini CLI's line-oriented session format.
    ///
    /// Gemini stores a header without a `type`, followed by `user` and
    /// `gemini` records. Function calls are embedded in assistant content
    /// parts and function responses in user content parts. Unknown records
    /// remain byte-exact in [`Session::raw`] instead of silently entering the
    /// replay conversation.
    pub fn from_gemini_str(jsonl: &str) -> Result<Session> {
        let mut meta = SessionMeta::new(SessionSource::Gemini);
        let (raw_lines, raw_trailing_newline) = split_lines_verbatim(jsonl);
        let raw = raw_lines.iter().map(|line| line.to_string()).collect();
        let mut messages = Vec::new();
        let mut parse_error_lines = 0usize;
        let mut pending_by_name: HashMap<String, Vec<String>> = HashMap::new();

        for (line_index, line) in non_empty_lines(jsonl).enumerate() {
            let value: Value = match serde_json::from_str(line) {
                Ok(value) => value,
                Err(_) => {
                    parse_error_lines += 1;
                    continue;
                }
            };
            let kind = value.get("type").and_then(Value::as_str);
            if kind.is_none() {
                if meta.session_id.is_none() {
                    meta.session_id = value
                        .get("sessionId")
                        .and_then(Value::as_str)
                        .map(str::to_string);
                }
                for (source, target) in [
                    ("projectHash", "gemini_project_hash"),
                    ("startTime", "created_at"),
                    ("lastUpdated", "updated_at"),
                    ("kind", "gemini_session_kind"),
                ] {
                    if let Some(raw) = value.get(source) {
                        meta.lineage.insert(
                            target.to_string(),
                            raw.as_str()
                                .map(str::to_string)
                                .unwrap_or_else(|| raw.to_string()),
                        );
                    }
                }
                continue;
            }
            if kind != Some("user") && kind != Some("gemini") {
                continue;
            }

            let timestamp = value.get("timestamp").and_then(Value::as_str);
            let model = value.get("model").and_then(Value::as_str);
            if let Some(model) = model {
                meta.model = Some(model.to_string());
            }
            let content = value.get("content").unwrap_or(&Value::Null);
            let parts = content.as_array();
            let text = match content {
                Value::String(text) => text.clone(),
                Value::Array(parts) => parts
                    .iter()
                    .filter_map(|part| part.get("text").and_then(Value::as_str))
                    .collect::<Vec<_>>()
                    .join(" ")
                    .trim()
                    .to_string(),
                _ => String::new(),
            };

            if kind == Some("gemini") {
                let legacy_calls = parts
                    .into_iter()
                    .flatten()
                    .filter_map(|part| part.get("functionCall"));
                let native_calls = value
                    .get("toolCalls")
                    .and_then(Value::as_array)
                    .into_iter()
                    .flatten();
                let calls = native_calls
                    .chain(legacy_calls)
                    .enumerate()
                    .filter_map(|(call_index, call)| {
                        let name = call.get("name")?.as_str()?.to_string();
                        let id = call
                            .get("id")
                            .and_then(Value::as_str)
                            .map(str::to_string)
                            .unwrap_or_else(|| format!("gemini-{line_index}-{call_index}"));
                        pending_by_name
                            .entry(name.clone())
                            .or_default()
                            .push(id.clone());
                        let arguments = call
                            .get("args")
                            .map(value_to_arg_string)
                            .unwrap_or_else(|| "{}".to_string());
                        Some(function_call(&id, &name, arguments))
                    })
                    .collect::<Vec<_>>();
                let mut message = ChatMessage {
                    role: Role::Assistant,
                    content: (!text.is_empty()).then_some(text),
                    content_parts: None,
                    tool_calls: (!calls.is_empty()).then_some(calls),
                    tool_call_id: None,
                    name: None,
                    metadata: Default::default(),
                };
                if let Some(timestamp) = timestamp {
                    message
                        .metadata
                        .insert("timestamp".into(), timestamp.into());
                }
                if let Some(model) = model {
                    message.metadata.insert("gemini_model".into(), model.into());
                }
                if let Some(thoughts) = value.get("thoughts").filter(|value| !value.is_null()) {
                    message
                        .metadata
                        .insert("gemini_thoughts".into(), thoughts.to_string());
                }
                restore_gemini_message_extension(&value, &mut message);
                if message.content.is_some() || message.tool_calls.is_some() {
                    messages.push(message);
                }
                continue;
            }

            let mut user_parts = Vec::new();
            if let Some(parts) = parts {
                for part in parts {
                    if let Some(response) = part.get("functionResponse") {
                        push_gemini_user_parts(
                            &mut messages,
                            std::mem::take(&mut user_parts),
                            timestamp,
                            &value,
                        );
                        let name = response
                            .get("name")
                            .and_then(Value::as_str)
                            .unwrap_or("tool")
                            .to_string();
                        let explicit_id = response
                            .get("id")
                            .and_then(Value::as_str)
                            .map(str::to_string);
                        if let Some(id) = explicit_id.as_deref() {
                            if let Some(ids) = pending_by_name.get_mut(&name) {
                                if let Some(position) = ids.iter().position(|pending| pending == id)
                                {
                                    ids.remove(position);
                                }
                            }
                        }
                        let id = explicit_id
                            .or_else(|| {
                                pending_by_name
                                    .get_mut(&name)
                                    .and_then(|ids| (!ids.is_empty()).then(|| ids.remove(0)))
                            })
                            .unwrap_or_else(|| format!("gemini-{line_index}-response"));
                        let output = response
                            .get("response")
                            .and_then(|response| response.get("output"))
                            .map(|output| {
                                output
                                    .as_str()
                                    .map(str::to_string)
                                    .unwrap_or_else(|| output.to_string())
                            })
                            .or_else(|| response.get("response").map(Value::to_string))
                            .unwrap_or_default();
                        let mut message = tool_message(&id, output);
                        message.name = Some(name);
                        if let Some(timestamp) = timestamp {
                            message
                                .metadata
                                .insert("timestamp".into(), timestamp.into());
                        }
                        restore_gemini_message_extension(&value, &mut message);
                        messages.push(message);
                        continue;
                    }
                    if let Some(text) = part.get("text").and_then(Value::as_str) {
                        user_parts.push(serde_json::json!({"type": "text", "text": text}));
                        continue;
                    }
                    if let Some(inline) = part.get("inlineData") {
                        let Some(data) = inline.get("data").and_then(Value::as_str) else {
                            continue;
                        };
                        let media_type = inline
                            .get("mimeType")
                            .and_then(Value::as_str)
                            .unwrap_or("application/octet-stream");
                        user_parts.push(serde_json::json!({
                            "type": "image_url",
                            "image_url": {"url": format!("data:{media_type};base64,{data}")},
                        }));
                    }
                }
            } else if !text.is_empty() {
                user_parts.push(serde_json::json!({"type": "text", "text": text}));
            }
            push_gemini_user_parts(&mut messages, user_parts, timestamp, &value);
        }

        ensure_tool_results_paired(&mut messages);
        let imported_message_count = Some(messages.len());
        Ok(Session {
            meta,
            messages,
            subagents: Vec::new(),
            raw,
            raw_trailing_newline,
            imported_message_count,
            raw_is_verbatim: true,
            parse_error_lines,
            load_residue: Vec::new(),
        })
    }

    /// Load a Goose session-export JSON document from disk.
    pub fn from_goose(path: impl AsRef<Path>) -> Result<Session> {
        Self::from_goose_str(&std::fs::read_to_string(path.as_ref())?)
    }

    /// Parse Goose's official native import/export document.
    ///
    /// Goose's durable store is SQLite, but its own
    /// `_goose/unstable/session/export` and `/session/import` boundary is one
    /// JSON object containing a `conversation` array. Unknown native content
    /// blocks are retained on the first canonical message in a namespaced
    /// portability envelope; unchanged same-format exports replay the exact
    /// source bytes.
    pub fn from_goose_str(json: &str) -> Result<Session> {
        let document: Value = serde_json::from_str(json).map_err(crate::Error::Decode)?;
        let object = document.as_object().ok_or_else(|| {
            Error::InvalidSession("Goose session export must be a JSON object".to_string())
        })?;
        let conversation = object
            .get("conversation")
            .and_then(Value::as_array)
            .ok_or_else(|| {
                Error::InvalidSession(
                    "Goose session export must contain a conversation array".to_string(),
                )
            })?;

        let mut meta = SessionMeta::new(SessionSource::Goose);
        meta.session_id = object.get("id").and_then(Value::as_str).map(str::to_string);
        meta.cwd = object
            .get("working_dir")
            .or_else(|| object.get("workingDir"))
            .and_then(Value::as_str)
            .map(PathBuf::from);
        meta.model = object
            .get("model_config")
            .or_else(|| object.get("modelConfig"))
            .and_then(|model| model.get("model_name").or_else(|| model.get("modelName")))
            .and_then(Value::as_str)
            .map(str::to_string);
        for (source, target) in [
            ("name", "session_name"),
            ("created_at", "created_at"),
            ("updated_at", "updated_at"),
            ("session_type", "goose_session_type"),
            ("goose_mode", "goose_mode"),
            ("provider_name", "goose_provider_name"),
            ("parent_session_id", "parent_session_id"),
        ] {
            if let Some(value) = object.get(source) {
                meta.lineage.insert(
                    target.to_string(),
                    value
                        .as_str()
                        .map(str::to_string)
                        .unwrap_or_else(|| value.to_string()),
                );
            }
        }
        let mut header = document.clone();
        if let Some(header) = header.as_object_mut() {
            header.remove("conversation");
        }
        meta.goose_header = Some(header.clone());

        let mut messages = Vec::new();
        for (native_index, native) in conversation.iter().enumerate() {
            let before = messages.len();
            normalize_goose_message(native, native_index, &mut messages);
            if let Some(first) = messages.get_mut(before) {
                first
                    .metadata
                    .insert("goose_native_message".to_string(), native.to_string());
                first
                    .metadata
                    .insert("goose_native_index".to_string(), native_index.to_string());
                if native_index == 0 {
                    first
                        .metadata
                        .insert("goose_session_header".to_string(), header.to_string());
                }
                restore_grok_message_extension(native, first);
            }
            for message in messages.iter_mut().skip(before + 1) {
                message
                    .metadata
                    .insert("goose_native_index".to_string(), native_index.to_string());
            }
        }
        ensure_tool_results_paired(&mut messages);

        let (raw_lines, raw_trailing_newline) = split_lines_verbatim(json);
        let raw = raw_lines.iter().map(|line| line.to_string()).collect();
        let imported_message_count = Some(messages.len());
        Ok(Session {
            meta,
            messages,
            subagents: Vec::new(),
            raw,
            raw_trailing_newline,
            imported_message_count,
            raw_is_verbatim: true,
            parse_error_lines: 0,
            load_residue: Vec::new(),
        })
    }

    /// Load one Goose session directly from its native SQLite store.
    ///
    /// The selector is Goose's stable `sessions.id`. The reconstructed JSON
    /// uses Goose's own public export shape, so the ordinary Goose codec is
    /// the single normalization boundary for both files and the live store.
    pub fn from_goose_sqlite(db_path: &Path, session_id: &str) -> Result<Session> {
        Self::from_goose_sqlite_with_limit(db_path, session_id, None)
    }

    /// Bounded Goose store read for transcript UI surfaces. The inner query
    /// selects only the newest native rows; the outer query restores their
    /// chronological order. Export/continue callers deliberately use the
    /// unbounded public loader above.
    #[doc(hidden)]
    pub fn from_goose_sqlite_display(
        db_path: &Path,
        session_id: &str,
        message_limit: usize,
    ) -> Result<Session> {
        Self::from_goose_sqlite_with_limit(db_path, session_id, Some(message_limit.max(1)))
    }

    fn from_goose_sqlite_with_limit(
        db_path: &Path,
        session_id: &str,
        message_limit: Option<usize>,
    ) -> Result<Session> {
        let connection = Connection::open_with_flags(
            db_path,
            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
        )
        .map_err(|error| Error::Other(format!("failed to open Goose SQLite store: {error}")))?;
        let mut statement = connection
            .prepare(
                "SELECT id, name, working_dir, created_at, updated_at, session_type, \
                    extension_data, goose_mode, provider_name, model_config_json \
             FROM sessions WHERE id = ?1",
            )
            .map_err(|error| Error::Other(format!("failed to query Goose sessions: {error}")))?;
        let mut document = statement
            .query_row([session_id], |row| {
                let extension_data: Option<String> = row.get(6)?;
                let model_config: Option<String> = row.get(9)?;
                Ok(serde_json::json!({
                    "id": row.get::<_, String>(0)?,
                    "working_dir": row.get::<_, String>(2)?,
                    "name": row.get::<_, String>(1)?,
                    "user_set_name": false,
                    "session_type": row.get::<_, String>(5)?,
                    "created_at": row.get::<_, String>(3)?,
                    "updated_at": row.get::<_, String>(4)?,
                    "extension_data": extension_data
                        .as_deref()
                        .and_then(|value| serde_json::from_str::<Value>(value).ok())
                        .unwrap_or_else(|| serde_json::json!({})),
                    "usage": {},
                    "accumulated_usage": {},
                    "accumulated_cost": Value::Null,
                    "schedule_id": Value::Null,
                    "recipe": Value::Null,
                    "user_recipe_values": Value::Null,
                    "conversation": [],
                    "message_count": 0,
                    "last_message_at": Value::Null,
                    "provider_name": row.get::<_, Option<String>>(8)?,
                    "model_config": model_config
                        .as_deref()
                        .and_then(|value| serde_json::from_str::<Value>(value).ok()),
                    "goose_mode": row.get::<_, String>(7)?,
                    "archived_at": Value::Null,
                    "project_id": Value::Null,
                    "parent_session_id": Value::Null,
                    "last_message_snippet": Value::Null,
                }))
            })
            .map_err(|error| Error::Other(format!("failed to load Goose session: {error}")))?;

        let message_query = message_limit.map_or_else(
            || {
                "SELECT message_id, role, content_json, created_timestamp, metadata_json \
                 FROM messages WHERE session_id = ?1 ORDER BY created_timestamp, id"
                    .to_string()
            },
            |limit| {
                format!(
                    "SELECT message_id, role, content_json, created_timestamp, metadata_json \
                     FROM (SELECT id AS native_row_id, message_id, role, content_json, \
                                  created_timestamp, metadata_json \
                           FROM messages WHERE session_id = ?1 \
                           ORDER BY created_timestamp DESC, id DESC LIMIT {limit}) \
                     ORDER BY created_timestamp, native_row_id"
                )
            },
        );
        let mut message_statement = connection
            .prepare(&message_query)
            .map_err(|error| Error::Other(format!("failed to query Goose messages: {error}")))?;
        let rows = message_statement
            .query_map([session_id], |row| {
                let content: String = row.get(2)?;
                let metadata: Option<String> = row.get(4)?;
                Ok(serde_json::json!({
                    "id": row.get::<_, Option<String>>(0)?,
                    "role": row.get::<_, String>(1)?,
                    "created": row.get::<_, i64>(3)?,
                    "content": serde_json::from_str::<Value>(&content)
                        .unwrap_or_else(|_| Value::Array(Vec::new())),
                    "metadata": metadata
                        .as_deref()
                        .and_then(|value| serde_json::from_str::<Value>(value).ok())
                        .unwrap_or_else(|| serde_json::json!({
                            "userVisible": true,
                            "agentVisible": true
                        })),
                }))
            })
            .map_err(|error| Error::Other(format!("failed to load Goose messages: {error}")))?;
        let conversation = rows
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|error| Error::Other(format!("failed to decode Goose messages: {error}")))?;
        document["message_count"] = Value::from(conversation.len());
        document["conversation"] = Value::Array(conversation);
        let json = serde_json::to_string_pretty(&document).map_err(crate::Error::Decode)?;
        let mut session = Self::from_goose_str(&json)?;
        // SQLite was reconstructed through values, not captured byte-for-byte.
        session.raw_is_verbatim = false;
        Ok(session)
    }

    /// Load an OpenCode session from a file — either read surface, see
    /// [`Self::from_opencode_str`].
    pub fn from_opencode(path: impl AsRef<Path>) -> Result<Session> {
        Self::from_opencode_str(&std::fs::read_to_string(path.as_ref())?)
    }

    /// Load an OpenCode session from a real SQLite store (PARITY-3): opens
    /// `db_path`, resolves `session_id` (explicit, or — when `None` — the
    /// most-recently-updated top-level session, see
    /// `opencode_sqlite_primary_session_id`) and reconstructs the SAME
    /// envelope form [`Self::from_opencode_str`] already parses for the
    /// JSON-tree surfaces — so canonicalization (§2.1 mapping, compaction
    /// discipline, S1 tool-output masking, …) is shared code, not
    /// reimplemented here. See `docs/interop/opencode-pi-spec.md` §1.2/S9c
    /// for the envelope-construction rules this follows (all-columns rule,
    /// raw `revert` column carried verbatim).
    pub fn from_opencode_sqlite(db_path: &Path, session_id: Option<&str>) -> Result<Session> {
        let conn = opencode_sqlite_open(db_path)?;
        let id = match session_id {
            Some(id) => id.to_string(),
            None => opencode_sqlite_primary_session_id(&conn)?,
        };
        let lines = opencode_sqlite_session_envelope_lines(&conn, db_path, &id)?;
        let mut text = lines.join("\n");
        text.push('\n');
        let mut session = Self::from_opencode_str(&text)?;
        // D4: `text` above is a SYNTHESIZED reconstruction from SQL rows —
        // not the original source bytes (a binary `.db` file has no
        // "verbatim" line-oriented form to begin with). `from_opencode_str`
        // defaults `raw_is_verbatim` to `true` because for its OTHER two
        // callers (an actual envelope-form file's own text, an actual
        // export-document's text) that really is the source. It is NEVER
        // true for this diagonal — mirrors the export-document fix just
        // above for the same reason (`from_opencode_export_doc`, `false`).
        // `convert opencode.db --to opencode` must not claim byte-identical.
        session.raw_is_verbatim = false;
        Ok(session)
    }

    /// Parse an OpenCode session from either of its two frozen **read
    /// surfaces** (`docs/interop/opencode-pi-spec.md` §1.2, `S9a`,
    /// `opencode-fields.md`):
    ///
    /// - the **envelope form**: each line is
    ///   `{"key":[<storage key path>],"value":<record>}`, minified — the
    ///   synthesized raw-capture unit for the JSON-tree/SQLite storage
    ///   generations;
    /// - the **export-document form**: a single pretty-printed JSON document
    ///   `{info: SessionInfo, messages:[{info: Message, parts:[Part]}, …]}`
    ///   — the `opencode export`/`import` interchange shape, and EXACTLY
    ///   what the OpenCode writer emits.
    ///
    /// Both forms are parsed into the same `(session_info, side_records,
    /// Vec<OcMsg>)` shape and funnel through the SAME shared canonicalizer,
    /// `opencode_session_from_records` — so the same underlying records
    /// produce identical `messages` regardless of which surface carried
    /// them in. This is what makes `load(to_opencode_jsonl(S))` round-trip
    /// (§4.1's OpenCode diagonal, the exact circuit the fidelity matrix
    /// exercises): previously this function parsed the envelope form only
    /// and silently returned an empty-but-`Ok` `Session` for an export
    /// document — the confirmed footgun this now closes.
    ///
    /// Record classification (envelope form) is driven by the envelope
    /// `key`'s first component (`"session"` / `"message"` / `"part"` /
    /// `"session_diff"` / `"todo"`) — the frozen key scheme for all three
    /// storage generations plus SQLite rows (§1.2 S9c: a SQLite row's
    /// envelope synthesizes `key:["<table>","<ses>",...ids]` and MUST carry
    /// every column, `data` and non-`data` alike — e.g. the `session` row's
    /// `revert` column under the V2 `Revert.State` schema, whose extra
    /// `files` field the CLI's own row→V1 reconstruction drops; the
    /// envelope's `raw` capture keeps that raw column value regardless of
    /// what this loader's canonicalization understands).
    ///
    /// Mapping to canonical `messages` (§2.1, shared by both forms via
    /// `push_opencode_user`/`push_opencode_assistant`): `User`/`Assistant`
    /// text parts → `content`; a `User` `file` part whose `mime` is an image
    /// and whose `url` is a `data:` URI → an `image_url` `content_parts`
    /// entry; an `Assistant` `tool` part's `callID` + `state.*.input` → a
    /// `ToolCall`, and the SAME part's `state.completed.output` /
    /// `state.error.error` → a paired `Tool` message split by `callID`
    /// (opencode keeps call+result on one record; this loader splits it
    /// into the two OpenAI-shape messages the other loaders already
    /// produce).
    ///
    /// **S1 (`time.compacted`):** when a `tool` part's
    /// `state.completed.time.compacted` is set, the emitted `Tool`
    /// message's `content` is the placeholder
    /// [`OPENCODE_COMPACTED_TOOL_PLACEHOLDER`] — mirroring what opencode's
    /// own `toModelMessage` replays — while the REAL output survives in
    /// `raw` (always) and in `metadata["oc_tool_output_compacted"]` (full
    /// text) + `metadata["oc_tool_time_compacted"]` (the mask timestamp), so
    /// it is reversible, never actually lost.
    ///
    /// **Compaction boundary:** a `compaction` part's `tail_start_id` marks
    /// every message strictly before that message id
    /// `metadata["compacted_out"]="true"` (honored uniformly by
    /// `is_replay_excluded`) — except a `summary:true` `Assistant`
    /// message, which opencode itself hoists in FRONT of the retained tail
    /// on replay (`message-v2.ts:521-572`) and so must never be excluded
    /// regardless of its position, mirroring pi's identical exemption for
    /// its own compaction/branch-summary entries.
    ///
    /// **Unknown part `type` or unknown `tool.state.status`:** never
    /// canonicalized — raw-only survival, exactly like an unmodeled Pi
    /// `message.role` (S6-style fail-loud). The OpenCode corpus audit
    /// is what turns that into a visible coverage failure rather than a
    /// silent drop.
    ///
    /// **Export-document `raw`:** an export document is a single
    /// pretty-printed JSON value with no per-line envelope structure of its
    /// own to capture verbatim, so `raw` here is RE-SYNTHESIZED — one
    /// envelope line per `session`/`message`/`part` record found in the
    /// document, in the exact `{"key":[...],"value":...}` shape the native
    /// envelope form uses — so every native/T1-value-tier path
    /// (`to_native_jsonl`, `opencode_records_from_raw`, the
    /// splice/direct-write writers) stays consistent regardless of which
    /// read surface produced this `Session`.
    ///
    /// **Malformed input:** input that reaches this function non-empty but
    /// yields zero session/message/part records under EITHER form returns a
    /// clear `Err` rather than a silently-empty `Ok(Session)` — the
    /// confirmed footgun (`supercode resume`/`convert`/`inspect` on such
    /// input must not silently succeed with an empty session). A
    /// legitimately-empty session — a real `session` record with zero
    /// messages, or a valid export document with an empty `messages` array
    /// — is not an error.
    pub fn from_opencode_str(text: &str) -> Result<Session> {
        let trimmed = text.trim();

        // Export-document form first (§1.2/S9a) — mirrors `detect_source`'s
        // own precedence: try the whole-text parse before the per-line
        // envelope loop below, since a pretty-printed multi-line document
        // has no individually-valid-JSON lines for that loop to match.
        if let Ok(doc) = serde_json::from_str::<Value>(trimmed) {
            if doc.get("info").is_some() && doc.get("messages").and_then(Value::as_array).is_some()
            {
                return Self::from_opencode_export_doc(&doc);
            }
        }

        // Envelope form: each line `{"key":[<storage key path>],"value":<record>}`.
        // IX-1: `raw` is captured STRICT-VERBATIM — separate from the
        // blank-skipping PARSE walk just below, which keeps skipping
        // blank/whitespace-only lines when it looks for envelope records.
        let (raw_lines, raw_trailing_newline) = split_lines_verbatim(text);
        let raw: Vec<String> = raw_lines.iter().map(|l| l.to_string()).collect();
        let mut session_info: Option<Value> = None;
        let mut side_records: Vec<Value> = Vec::new();
        let mut msgs: Vec<OcMsg> = Vec::new();
        let mut msg_index: HashMap<String, usize> = HashMap::new();
        // PARITY-15: see `from_claude_code_str`'s identical counter — only
        // a genuinely malformed line (fails to deserialize as JSON at all),
        // not a well-formed envelope this loader simply doesn't recognize.
        let mut parse_error_lines = 0usize;

        for line in non_empty_lines(text) {
            let Ok(env) = serde_json::from_str::<Value>(line) else {
                parse_error_lines += 1;
                continue; // malformed line — raw-only, exactly like the other loaders
            };
            let Some(key) = env.get("key").and_then(Value::as_array) else {
                continue; // not an envelope record — raw-only
            };
            let value = env.get("value").cloned().unwrap_or(Value::Null);
            match key.first().and_then(Value::as_str) {
                Some("session") => session_info = Some(value),
                Some("message") => {
                    let Some(id) = value.get("id").and_then(Value::as_str) else {
                        continue;
                    };
                    let time_created = value
                        .get("time")
                        .and_then(|t| t.get("created"))
                        .and_then(Value::as_i64)
                        .unwrap_or(0);
                    msg_index.insert(id.to_string(), msgs.len());
                    msgs.push(OcMsg {
                        id: id.to_string(),
                        time_created,
                        value,
                        parts: Vec::new(),
                    });
                }
                Some("part") => {
                    if let Some(msg_id) = value.get("messageID").and_then(Value::as_str) {
                        if let Some(&idx) = msg_index.get(msg_id) {
                            msgs[idx].parts.push(value);
                        }
                        // A part whose message wasn't captured (out-of-order
                        // envelope) — still fully present in `raw`, just not
                        // attached to a canonical message.
                    }
                }
                Some("session_diff") | Some("todo") => {
                    side_records.push(serde_json::json!({"key": key, "value": value}));
                }
                _ => {} // unrecognized top-level key — raw-only
            }
        }

        opencode_guard_against_silent_empty(
            !trimmed.is_empty(),
            &session_info,
            &msgs,
            &side_records,
        )?;
        opencode_session_from_records(
            session_info,
            side_records,
            msgs,
            raw,
            raw_trailing_newline,
            // Envelope form: `raw` is split directly out of the source text
            // (strict-verbatim, IX-1) — genuinely reproduces the original
            // bytes on replay.
            true,
            parse_error_lines,
        )
    }

    /// The **export-document** read surface of [`Self::from_opencode_str`]
    /// — see that function's doc comment for the shared canonicalization
    /// and the `raw` re-synthesis this performs. `doc` is already known to
    /// have the `{info, messages:[...]}` shape (the caller checks this,
    /// matching `detect_source`'s own S9a check) before calling this.
    fn from_opencode_export_doc(doc: &Value) -> Result<Session> {
        let session_info = doc.get("info").cloned().filter(|v| !v.is_null());
        let messages_arr = doc
            .get("messages")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();

        let session_id = session_info
            .as_ref()
            .and_then(|si| si.get("id"))
            .and_then(Value::as_str)
            .unwrap_or("ses_unknown")
            .to_string();
        let project_id = session_info
            .as_ref()
            .and_then(|si| si.get("projectID"))
            .and_then(Value::as_str)
            .unwrap_or("global")
            .to_string();

        // Re-synthesize one envelope line per record — see the doc comment
        // on `from_opencode_str` ("Export-document `raw`").
        let mut raw: Vec<String> = Vec::new();
        if let Some(si) = &session_info {
            raw.push(
                serde_json::json!({"key": ["session", project_id, session_id], "value": si})
                    .to_string(),
            );
        }

        let mut msgs: Vec<OcMsg> = Vec::new();
        for entry in &messages_arr {
            let Some(info) = entry.get("info") else {
                continue; // malformed message entry — no clean home, raw-only
            };
            let Some(id) = info.get("id").and_then(Value::as_str) else {
                continue;
            };
            let time_created = info
                .get("time")
                .and_then(|t| t.get("created"))
                .and_then(Value::as_i64)
                .unwrap_or(0);
            let parts: Vec<Value> = entry
                .get("parts")
                .and_then(Value::as_array)
                .cloned()
                .unwrap_or_default();

            raw.push(
                serde_json::json!({"key": ["message", session_id, id], "value": info}).to_string(),
            );
            for p in &parts {
                let part_id = p.get("id").and_then(Value::as_str).unwrap_or("");
                raw.push(serde_json::json!({"key": ["part", id, part_id], "value": p}).to_string());
            }

            msgs.push(OcMsg {
                id: id.to_string(),
                time_created,
                value: info.clone(),
                parts,
            });
        }

        opencode_guard_against_silent_empty(true, &session_info, &msgs, &[])?;
        opencode_session_from_records(
            session_info,
            Vec::new(),
            msgs,
            raw,
            // Synthesized `raw` (§1.2's "Export-document raw" — one envelope
            // line re-derived per record, no real per-line source bytes to
            // measure) — matches the historical always-newline-terminated
            // behavior; see `Session::raw_trailing_newline`'s doc comment.
            true,
            // Export-document form: `raw` above is RE-SYNTHESIZED, one
            // envelope line derived per record — not the original document's
            // bytes (see this function's doc comment). `convert`'s
            // byte-identical claim must not fire on this diagonal.
            false,
            // PARITY-15: a pretty-printed export document is parsed WHOLE
            // (the caller's `if let Ok(doc) = serde_json::from_str(...)`) —
            // there's no per-line parse-loss concept here; a malformed
            // document fails that top-level parse and never reaches this
            // function at all.
            0,
        )
    }

    /// P5-5 (design §2 module 21 `session.tree`, §2.1 D-6 "session.tree →
    /// core.session(tree-addressable transcript)"): materialize this
    /// session's linear [`Self::messages`] into a native in-place
    /// [`crate::session_tree::SessionTree`] — the bridge a caller uses the
    /// FIRST time it wants to run a tree operation (rewind/branch/label)
    /// against an otherwise-linear [`Session`]. `created_at_ms` stamps every
    /// synthesized node (see
    /// [`crate::session_tree::SessionTree::from_linear`]'s doc comment for
    /// why a single timestamp is used: the source linear messages carry no
    /// per-turn timestamp of their own here).
    ///
    /// This does not mutate `self` or persist anything — see
    /// the composition layer's session-store tree writer for persistence, and
    /// [`Self::apply_session_tree`] for the inverse bridge.
    pub fn to_session_tree(&self, created_at_ms: i64) -> crate::session_tree::SessionTree {
        crate::session_tree::SessionTree::from_linear(&self.messages, created_at_ms)
    }

    /// P5-5: the inverse of [`Self::to_session_tree`] — overwrite
    /// [`Self::messages`] with `tree`'s ACTIVE branch's linear projection
    /// (C7's "tree-with-linear-projection": this is exactly what keeps every
    /// existing linear consumer — the agent loop, exporters — working
    /// unchanged after a tree operation runs). Nothing else on `self`
    /// (`meta`, `raw`, ...) is touched.
    ///
    /// **Fail-closed.** Propagates [`crate::session_tree::SessionTree::linear_projection`]'s
    /// `Err` rather than applying anything — a structurally-corrupt tree
    /// (a cycle, a dangling leaf, an active branch pointing at nothing) must
    /// error, not silently overwrite [`Self::messages`] with an empty `Vec`.
    /// `self` is left untouched on `Err` (the assignment only happens after
    /// the projection has already succeeded).
    pub fn apply_session_tree(&mut self, tree: &crate::session_tree::SessionTree) -> Result<()> {
        self.messages = tree.linear_projection()?;
        Ok(())
    }
}

/// One opencode `message` record plus its `part` children, gathered from
/// EITHER read surface (envelope-form records or export-document
/// `{info, parts}` entries) before the shared per-record canonicalization
/// in [`opencode_session_from_records`].
struct OcMsg {
    id: String,
    time_created: i64,
    value: Value,
    parts: Vec<Value>,
}

const OPENCODE_SUPERCODE_MESSAGE_POSITION: &str = "_supercode_message_position";
const OPENCODE_SUPERCODE_RESULT_POSITION: &str = "_supercode_result_position";
const OPENCODE_INTERNAL_ORIGINAL_POSITION: &str = "__supercode_original_position";

/// Guard against the confirmed footgun: input that reached
/// [`Session::from_opencode_str`] non-empty but produced no
/// session/message/part record under either read surface returns `Err`
/// instead of a silently-empty `Ok(Session)`. A legitimately-empty session
/// (a real session record with zero messages, or a valid empty `messages`
/// array) is not an error — only genuinely unparseable content is.
fn opencode_guard_against_silent_empty(
    non_empty_input: bool,
    session_info: &Option<Value>,
    msgs: &[OcMsg],
    side_records: &[Value],
) -> Result<()> {
    let has_any_record = session_info.as_ref().is_some_and(|v| !v.is_null())
        || !msgs.is_empty()
        || !side_records.is_empty();
    if non_empty_input && !has_any_record {
        return Err(crate::Error::Other(
            "opencode input was recognized as an OpenCode source (envelope or \
             export-document form) but no session/message/part record could be parsed from \
             it — refusing to silently return an empty session"
                .to_string(),
        ));
    }
    Ok(())
}

/// The shared per-record canonicalization for BOTH of
/// [`Session::from_opencode_str`]'s read surfaces (envelope form and
/// export-document form): frozen ordering, `SessionMeta` capture, the
/// compaction boundary pass, and the `User`/`Assistant` → `messages`
/// mapping via [`push_opencode_user`]/[`push_opencode_assistant`]. Fed the
/// same underlying `(session_info, side_records, msgs)` regardless of which
/// surface produced them, this produces byte-for-byte identical `messages`
/// — the invariant that makes `load(to_opencode_jsonl(S))` round-trip.
fn opencode_session_from_records(
    session_info: Option<Value>,
    side_records: Vec<Value>,
    mut msgs: Vec<OcMsg>,
    raw: Vec<String>,
    raw_trailing_newline: bool,
    raw_is_verbatim: bool,
    parse_error_lines: usize,
) -> Result<Session> {
    let mut meta = SessionMeta::new(SessionSource::OpenCode);

    // `msg_index` is captured BEFORE the frozen-order sort below, mapping
    // each message id to its PRE-sort position — used only to resolve a
    // `tail_start_id` reference in the compaction-boundary pass further
    // down. In every real opencode session (either surface) records
    // already arrive/are listed in creation order, so pre- and post-sort
    // positions coincide; this mirrors the original envelope-only
    // implementation's behavior exactly (not a new invariant introduced by
    // sharing this code across both surfaces).
    let msg_index: HashMap<String, usize> = msgs
        .iter()
        .enumerate()
        .map(|(i, m)| (m.id.clone(), i))
        .collect();

    // Frozen order (§1.2): messages by (time.created, id); each
    // message's parts by id.
    msgs.sort_by(|a, b| {
        a.time_created
            .cmp(&b.time_created)
            .then_with(|| a.id.cmp(&b.id))
    });
    for m in &mut msgs {
        m.parts.sort_by(|a, b| {
            let ai = a.get("id").and_then(Value::as_str).unwrap_or("");
            let bi = b.get("id").and_then(Value::as_str).unwrap_or("");
            ai.cmp(bi)
        });
    }

    meta.opencode_headers
        .push(session_info.clone().unwrap_or(Value::Null));
    meta.opencode_headers.extend(side_records);
    if let Some(si) = &session_info {
        capture_opencode_session_info(si, &mut meta)?;
    }

    // Compaction boundary (§2.1/§2.2 S3): the LATEST `tail_start_id`
    // seen — mirrors pi's `kept_from_pos` discipline (there is only one
    // active path in opencode's own linear message list, so no branch
    // walk is needed the way pi's tree requires).
    let mut tail_start_pos: Option<usize> = None;
    for m in &msgs {
        for p in &m.parts {
            if p.get("type").and_then(Value::as_str) == Some("compaction") {
                if let Some(t) = p.get("tail_start_id").and_then(Value::as_str) {
                    if let Some(&tp) = msg_index.get(t) {
                        tail_start_pos = Some(tail_start_pos.map_or(tp, |cur| cur.max(tp)));
                    }
                }
            }
        }
    }

    let mut messages = Vec::new();
    let mut first_system_seen = false;
    for (pos, m) in msgs.iter().enumerate() {
        let before = messages.len();
        match m.value.get("role").and_then(Value::as_str) {
            // B4: a `User` message that's actually
            // `append_synthesized_opencode_messages`'s own re-materialized
            // Claude `system` record (one `synthetic: true` text part
            // carrying the supercode marker key — see
            // `opencode_claude_system_subtype`'s doc comment) restores
            // `Role::System`, not a genuine user turn.
            Some("user") => match opencode_claude_system_subtype(&m.parts) {
                Some(subtype) => {
                    push_opencode_claude_system(&m.value, &m.parts, subtype, &mut messages)
                }
                None => push_opencode_user(
                    &m.value,
                    &m.parts,
                    &mut messages,
                    &mut meta,
                    &mut first_system_seen,
                ),
            },
            Some("assistant") => {
                push_opencode_assistant(&m.value, &m.parts, &mut messages, &mut meta)
            }
            // Unrecognized/missing role — raw-only survival;
            // `audit::Corpus::OpenCode` scores this as Unmodeled.
            _ => {}
        }
        if let Some(original_position) = m
            .value
            .get(OPENCODE_SUPERCODE_MESSAGE_POSITION)
            .and_then(Value::as_u64)
        {
            if let Some(message) = messages[before..]
                .iter_mut()
                .find(|message| message.role != Role::Tool)
            {
                message.metadata.insert(
                    OPENCODE_INTERNAL_ORIGINAL_POSITION.to_string(),
                    original_position.to_string(),
                );
            }
        }
        for msg in &mut messages[before..] {
            let is_summary = msg.metadata.get("is_summary").map(String::as_str) == Some("true");
            if !is_summary {
                if let Some(tsp) = tail_start_pos {
                    if pos < tsp {
                        msg.metadata
                            .insert("compacted_out".to_string(), "true".to_string());
                    }
                }
            }
        }
    }

    let marked_slots = messages
        .iter()
        .enumerate()
        .filter_map(|(index, message)| {
            message
                .metadata
                .contains_key(OPENCODE_INTERNAL_ORIGINAL_POSITION)
                .then_some(index)
        })
        .collect::<Vec<_>>();
    if !marked_slots.is_empty() {
        // A spliced OpenCode export can contain an unmarked native prefix
        // followed by a marked synthesized tail. Reorder only among the
        // marked slots so the tail never jumps in front of its raw prefix.
        let mut marked_messages = marked_slots
            .iter()
            .map(|index| messages[*index].clone())
            .collect::<Vec<_>>();
        marked_messages.sort_by_key(|message| {
            message
                .metadata
                .get(OPENCODE_INTERNAL_ORIGINAL_POSITION)
                .and_then(|position| position.parse::<usize>().ok())
                .unwrap_or(usize::MAX)
        });
        for (slot, message) in marked_slots.into_iter().zip(marked_messages) {
            messages[slot] = message;
        }
        for message in &mut messages {
            message.metadata.remove(OPENCODE_INTERNAL_ORIGINAL_POSITION);
        }
    }
    ensure_tool_results_paired(&mut messages);
    let imported_message_count = Some(messages.len());
    Ok(Session {
        meta,
        messages,
        subagents: Vec::new(),
        raw,
        raw_trailing_newline,
        imported_message_count,
        raw_is_verbatim,
        parse_error_lines,
        load_residue: Vec::new(),
    })
}

/// Resolve each opencode subagent (`task`) child session's
/// `meta.parent_tool_use_id` from its parent's own `task` tool part
/// `callID` (`docs/interop/opencode-pi-spec.md` §2.1 — the analogue of
/// Claude Code's `agentId`/`parent_tool_use_id` linkage,
/// `opencode-fields.md` `task.ts:145,171-176`).
///
/// Nesting itself needs no opencode-specific pass:
/// `capture_opencode_session_info` already mirrors `SessionInfo.parentID`
/// into `lineage["parent_thread_id"]` (the same key Codex subagents use),
/// so the existing generic [`Session::reconstruct_tree`] nests these
/// sessions correctly on its own. Call this FIRST — it only reads
/// `session_id`/`messages`/metadata, never reorders `sessions` — then feed
/// the same `Vec` to `reconstruct_tree`.
pub fn resolve_opencode_parent_tool_use_ids(sessions: &mut [Session]) {
    let ids: Vec<Option<String>> = sessions.iter().map(|s| s.meta.session_id.clone()).collect();
    for i in 0..sessions.len() {
        let child_id = sessions[i].meta.session_id.clone();
        let parent_id = sessions[i].meta.lineage.get("parent_session_id").cloned();
        let (Some(child_id), Some(parent_id)) = (child_id, parent_id) else {
            continue;
        };
        let Some(parent_idx) = ids
            .iter()
            .position(|id| id.as_deref() == Some(parent_id.as_str()))
        else {
            continue;
        };
        for m in &sessions[parent_idx].messages {
            for (k, v) in &m.metadata {
                if let Some(call_id) = k.strip_prefix("oc_task_child_session_id__") {
                    if v == &child_id {
                        sessions[i].meta.parent_tool_use_id = Some(call_id.to_string());
                    }
                }
            }
        }
    }
}

/// D7: repair tool-result/tool-call ORDERING for the Claude Code loader.
///
/// Real Claude Code transcripts are well-formed by `uuid`/`parentUuid` tree
/// structure but are NOT guaranteed to be well-formed in raw file order: async
/// tool-result delivery (or an edited turn) can write a `tool_result` `user`
/// line BEFORE the assistant `tool_use` line that owns it, even though the
/// parent/child tree itself is fine. The active-branch projection restores
/// parent-before-child order, but a result can still trail a later assistant
/// turn instead of sitting next to the assistant that owns it. Both OpenAI-
/// and Anthropic-shaped wire APIs reject either shape on `resume`. Measured
/// on a real corpus: 21/450 sessions (4.7%), 89 inverted pairs.
///
/// This reorders `messages` so every OWNED `Role::Tool` result (its
/// `tool_call_id` matches a `tool_calls` entry on some `Role::Assistant`
/// message anywhere in the list) sits immediately after the `Role::Assistant`
/// message that owns it, while leaving every other message's relative order
/// untouched. Orphan tool results — no matching call anywhere in the list —
/// are left in their ORIGINAL position, untouched; they are never moved. It
/// is a pure reorder: same message count, same multiset of messages, in/out.
///
/// Tool-call ids (`toolu_*`) are globally unique within a Claude Code session
/// — each appears exactly once as a call and once as its result — so a
/// simple id -> owning-assistant map is sufficient; no special-casing is
/// needed for sidechain (`isSidechain`) messages, since `push_claude_*`
/// already pushes those inline with their own distinct ids.
///
/// Results whose matching call is missing entirely (no owner found) are left
/// in place untouched — `ensure_tool_results_paired` (which runs right after
/// this) is responsible for synthesizing a placeholder result for any call
/// that ends up unanswered; this pass never drops or fabricates anything.
fn reorder_tool_results_after_calls(messages: &mut Vec<ChatMessage>) {
    // 0. First pass: which tool_call_ids are actually "owned" — emitted by
    //    some assistant message anywhere in the list — and the position of
    //    that owning assistant. Owned as `String` (not borrowed) so this map
    //    can outlive the later `messages.drain(..)`.
    let mut owner_positions: HashMap<String, usize> = HashMap::new();
    for (index, m) in messages.iter().enumerate() {
        if m.role == Role::Assistant {
            for c in m.tool_calls() {
                if !c.id.is_empty() {
                    owner_positions.entry(c.id.clone()).or_insert(index);
                }
            }
        }
    }

    // Fast, cheap detection of "nothing to do": every owned result must be
    // in the contiguous tool-result block immediately following its owning
    // assistant. Checking only result-before-owner inversions is insufficient
    // after Claude's active-branch projection: that projection can put the
    // owner first while leaving its result behind a later assistant turn.
    // Mere orphans never set this flag. A canonical session returns with
    // `messages` byte-for-byte unchanged, mirroring
    // `ensure_tool_results_paired`'s own no-op guard.
    let mut contiguous_owner = None;
    let needs_reorder =
        messages
            .iter()
            .enumerate()
            .any(|(message_index, message)| match message.role {
                Role::Assistant => {
                    contiguous_owner = Some(message_index);
                    false
                }
                Role::Tool => match message
                    .tool_call_id
                    .as_deref()
                    .and_then(|id| owner_positions.get(id))
                    .copied()
                {
                    Some(owner) => Some(owner) != contiguous_owner,
                    None => {
                        // An orphan or unlinked tool message interrupts the
                        // owner's contiguous result block but never moves by
                        // itself.
                        contiguous_owner = None;
                        false
                    }
                },
                _ => {
                    contiguous_owner = None;
                    false
                }
            });
    if !needs_reorder {
        return;
    }

    // 1. Second pass: route messages into the "spine" (everything that stays
    //    at its own position — non-tool messages AND orphan tool results)
    //    versus owned tool results (pulled out, to be reattached right after
    //    their owner). Record, for each spine index that's an assistant, the
    //    set of tool_call_ids it owns.
    let mut spine: Vec<ChatMessage> = Vec::with_capacity(messages.len());
    let mut call_owner: HashMap<String, usize> = HashMap::new();
    // Buffer of (original_position, message) for every OWNED tool result,
    // built alongside the spine; a result can reference a call emitted later
    // in file order, so owner spine-index is resolved in a later step once
    // `call_owner` is complete.
    let mut owned_results: Vec<(usize, ChatMessage)> = Vec::new();

    let drained: Vec<ChatMessage> = std::mem::take(messages);
    for (orig_pos, msg) in drained.into_iter().enumerate() {
        if msg.role == Role::Tool {
            let is_owned = msg
                .tool_call_id
                .as_deref()
                .map(|id| !id.is_empty() && owner_positions.contains_key(id))
                .unwrap_or(false);
            if is_owned {
                owned_results.push((orig_pos, msg));
                continue;
            }
            // Orphan: no matching call anywhere. Treat exactly like a
            // non-tool message for placement — it joins the spine at its
            // current position and is never moved.
            spine.push(msg);
            continue;
        }
        if msg.role == Role::Assistant {
            let spine_idx = spine.len();
            for c in msg.tool_calls() {
                if !c.id.is_empty() {
                    call_owner.entry(c.id.clone()).or_insert(spine_idx);
                }
            }
        }
        spine.push(msg);
    }

    // 2. Resolve each owned result's owner spine-index now that `call_owner`
    //    is complete, then bucket results by owner spine-index. Every result
    //    here was routed as "owned" because its id was found in `owned_ids`,
    //    which was built from the exact same `tool_calls()` scan that
    //    populates `call_owner` below, so the lookup is guaranteed to hit.
    let mut buckets: HashMap<usize, Vec<(usize, ChatMessage)>> = HashMap::new();
    for (orig_pos, msg) in owned_results.into_iter() {
        let id = msg
            .tool_call_id
            .as_deref()
            .filter(|id| !id.is_empty())
            .expect("routed as owned, so tool_call_id must be a non-empty owned id");
        let idx = *call_owner
            .get(id)
            .expect("owned id must have an owning assistant in call_owner");
        buckets.entry(idx).or_default().push((orig_pos, msg));
    }
    // Keep each bucket's results in their original relative file order.
    for v in buckets.values_mut() {
        v.sort_by_key(|(pos, _)| *pos);
    }

    // 3. Rebuild: emit each spine message (which now includes orphans at
    //    their original position, untouched) in order; immediately after
    //    emitting an assistant message that owns one or more tool results,
    //    emit its owned results, in original relative order.
    let mut out: Vec<ChatMessage> = Vec::with_capacity(spine.len() + buckets.len());
    for (idx, msg) in spine.into_iter().enumerate() {
        out.push(msg);
        if let Some(results) = buckets.remove(&idx) {
            for (_, r) in results {
                out.push(r);
            }
        }
    }
    *messages = out;
}

/// Guarantee every assistant `tool_calls` entry is answered by a following tool
/// result. Interrupted/aborted turns leave a tool call with no result, which
/// many chat-completions endpoints reject when the conversation is replayed.
/// We insert a synthetic placeholder result immediately after the assistant
/// turn so the transcript stays valid for continuation. (Orphan results — a
/// tool message with no preceding call — do not occur in practice and are left
/// untouched.)
fn ensure_tool_results_paired(messages: &mut Vec<ChatMessage>) {
    let answered: HashSet<String> = messages
        .iter()
        .filter(|m| m.role == Role::Tool)
        .filter_map(|m| m.tool_call_id.clone())
        .collect();

    // Nothing missing? Leave the vector byte-for-byte unchanged.
    let any_missing = messages.iter().any(|m| {
        m.tool_calls()
            .iter()
            .any(|c| !c.id.is_empty() && !answered.contains(&c.id))
    });
    if !any_missing {
        return;
    }

    let mut out: Vec<ChatMessage> = Vec::with_capacity(messages.len() + 4);
    for msg in messages.drain(..) {
        let synth: Vec<ChatMessage> = msg
            .tool_calls()
            .iter()
            .filter(|c| !c.id.is_empty() && !answered.contains(&c.id))
            .map(|c| {
                let mut m = ChatMessage::tool_result(
                    c.id.clone(),
                    c.function.name.clone(),
                    "[no tool result recorded — turn interrupted]".to_string(),
                );
                // TR-10: an interrupted call never executed to completion —
                // never a candidate for `ReductionKind::ToolInputElided`
                // (the "still-pending calls are never input-elided"
                // boundary).
                crate::mark_tool_error(&mut m);
                m
            })
            .collect();
        out.push(msg);
        out.extend(synth);
    }
    *messages = out;
}

/// Whether `msg` is excluded from every replay/export path — the frozen
/// cross-format discipline (`docs/interop/opencode-pi-spec.md` §2.1/§2.2/§6):
/// a message marked `compacted_out` (pre-compaction history a source harness
/// itself no longer replays) or `pi_exclude_from_context` (a pi `!!` bash
/// escape) must never reach `to_jsonl`/`to_jsonl_spliced` for ANY target
/// format, not just the one that produced the marker — so a translated
/// compacted session replays the same sliced context the source harness
/// would, instead of double-including history plus its own summary.
fn is_replay_excluded(msg: &ChatMessage) -> bool {
    msg.metadata.get("compacted_out").map(String::as_str) == Some("true")
        || msg
            .metadata
            .get("pi_exclude_from_context")
            .map(String::as_str)
            == Some("true")
}

// ---- detection ------------------------------------------------------------

fn detect_source(text: &str) -> Option<SessionSource> {
    // OpenCode export-document form (`docs/interop/opencode-pi-spec.md`
    // §1.2/S9a): `{info: SessionInfo, messages: [...]}` — a single
    // pretty-printed, MULTI-LINE JSON document, unlike every other format
    // this crate reads. It cannot be recognized by the per-line loop below
    // (no individual line of a pretty-printed document is itself valid
    // JSON), so it gets its own whole-text parse attempt up front. Cheap to
    // attempt: a real JSONL file (many newline-separated objects) fails this
    // parse immediately (trailing-data error) and falls through unaffected.
    if let Ok(v) = serde_json::from_str::<Value>(text.trim()) {
        if v.get("conversation").and_then(Value::as_array).is_some()
            && (v.get("working_dir").is_some() || v.get("workingDir").is_some())
        {
            return Some(SessionSource::Goose);
        }
        if v.get("info").is_some() && v.get("messages").and_then(Value::as_array).is_some() {
            return Some(SessionSource::OpenCode);
        }
    }
    for line in non_empty_lines(text) {
        // Tolerate a corrupt/truncated line (e.g. a partial first line) rather
        // than abandoning detection — the loaders themselves skip bad lines, so
        // bailing here would silently misroute an otherwise-valid Codex file.
        let Ok(v) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        // OpenCode's frozen envelope form (§1.2): `{"key":[...],"value":...}`,
        // one record per line — the synthesized raw-capture unit for the
        // JSON-tree/SQLite generations alike. No other format's lines carry
        // both a top-level `key` ARRAY and a `value` field, so this is
        // unambiguous against Codex/Pi/Claude Code.
        if v.get("key").and_then(Value::as_array).is_some() && v.get("value").is_some() {
            return Some(SessionSource::OpenCode);
        }
        // Codex envelopes always carry a `payload`; Claude Code lines never do.
        if v.get("payload").is_some() {
            return Some(SessionSource::Codex);
        }
        // Gemini CLI starts with an untyped session header. Its project hash
        // and timestamps distinguish it from Claude Code records that also
        // carry `sessionId`.
        if v.get("sessionId").and_then(Value::as_str).is_some()
            && (v.get("projectHash").is_some()
                || v.get("startTime").is_some()
                || v.get("lastUpdated").is_some())
            && v.get("type").is_none()
        {
            return Some(SessionSource::Gemini);
        }
        // Grok's resumable `chat_history.jsonl` stores the role/type and
        // content directly on each record. Claude Code uses a nested
        // `message` envelope for the overlapping `user`/`assistant` tags.
        let tag = v.get("type").and_then(Value::as_str);
        if tag == Some("gemini") && v.get("content").is_some() {
            return Some(SessionSource::Gemini);
        }
        if v.get("message").is_none()
            && v.get("uuid").is_none()
            && v.get("sessionId").is_none()
            && matches!(
                tag,
                Some(
                    "system"
                        | "user"
                        | "assistant"
                        | "tool_result"
                        | "reasoning"
                        | "backend_tool_call"
                )
            )
            && (v.get("content").is_some()
                || v.get("tool_calls").is_some()
                || v.get("tool_call_id").is_some()
                || v.get("encrypted_content").is_some()
                || v.get("kind").is_some())
        {
            return Some(SessionSource::Grok);
        }
        // Pi's `SessionHeader` (line 1, always `type:"session"`): a bare `id`
        // (the session id) with no `message`/`uuid` — Claude Code's own
        // `type`-bearing lines always carry one or the other, never a
        // `type:"session"` header shape (`docs/interop/research/pi-fields.md`
        // §1).
        if v.get("type").and_then(Value::as_str) == Some("session")
            && v.get("id").and_then(Value::as_str).is_some()
            && v.get("message").is_none()
            && v.get("uuid").is_none()
        {
            return Some(SessionSource::Pi);
        }
        if v.get("type").is_some() || v.get("message").is_some() {
            return Some(SessionSource::ClaudeCode);
        }
    }
    None
}

/// Which on-disk OpenCode storage surface is present under a data root
/// (`docs/interop/opencode-pi-spec.md` §1.2/S9a): SQLite `opencode*.db` (or
/// `$OPENCODE_DB`), legacy JSON tree generation B, or legacy JSON tree
/// generation A. This is a **filesystem classifier only** — it answers
/// "which generation is this?" for a corpus-discovery tool; it does not
/// itself read/parse the surface. See [`Session::from_opencode_str`]'s docs
/// for the envelope form any of these three surfaces synthesizes into, and
/// [`Session::from_opencode_sqlite`] (PARITY-3/PARITY-16) for the `rusqlite`
/// reader that reconstructs that same envelope form from `Sqlite`'s rows —
/// `JsonTreeA`/`JsonTreeB` remain classifier-only (their `session_diff`
/// round-trips via the JSON store per upstream's own behavior even on a
/// SQLite install, so nothing is silently lost by not reading the legacy
/// trees directly).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenCodeStorageSurface {
    /// SQLite `<data>/opencode*.db` (or `$OPENCODE_DB` override). Read by
    /// [`Session::from_opencode_sqlite`] / [`opencode_sqlite_store_stats`] /
    /// [`opencode_sqlite_corpus_envelope_text`].
    Sqlite,
    /// Legacy JSON tree, generation B: `<data>/storage/{session,message,part,session_diff}/…`,
    /// marker file `storage/migration`.
    JsonTreeB,
    /// Legacy JSON tree, generation A: `<data>/project/<slug>/storage/session/{info,message,part}/…`.
    JsonTreeA,
}

/// Probe `data_root` (e.g. `~/.local/share/opencode`) for the OpenCode
/// storage surface present, per the discovery rules frozen in
/// `docs/interop/opencode-pi-spec.md` §1.2/S9a: `$OPENCODE_DB` wins outright;
/// otherwise glob `opencode*.db` (not just `opencode.db` — dev/beta channels
/// suffix the filename, `database.ts:43-55`); otherwise look for the JSON
/// tree generation-B marker (`storage/migration`); otherwise generation-A's
/// `project/` subtree. Returns `None` if nothing is found.
pub fn detect_opencode_storage_surface(
    data_root: &Path,
) -> Option<(OpenCodeStorageSurface, PathBuf)> {
    if let Ok(p) = std::env::var("OPENCODE_DB") {
        let pb = PathBuf::from(p);
        if pb.is_file() {
            return Some((OpenCodeStorageSurface::Sqlite, pb));
        }
    }
    if let Ok(entries) = std::fs::read_dir(data_root) {
        // D8: `std::fs::read_dir`'s iteration order is filesystem-dependent,
        // NOT deterministic — a store with both a default-channel
        // `opencode.db` and a channel-suffixed `opencode-dev.db` (S9a: both
        // are legal, e.g. after switching install channels) previously
        // returned "whichever the OS happened to list first", which could
        // differ between two `inspect`/`audit`/`convert` runs against the
        // exact same directory. Collect every `opencode*.db` candidate and
        // pick deterministically: the exact `opencode.db` name wins if
        // present (the default/most-common channel); otherwise the
        // lexicographically-smallest match, so repeated runs always agree.
        let mut candidates: Vec<PathBuf> = entries
            .flatten()
            .map(|entry| entry.path())
            .filter(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|name| name.starts_with("opencode") && name.ends_with(".db"))
            })
            .collect();
        candidates.sort();
        if let Some(exact) = candidates
            .iter()
            .find(|p| p.file_name().and_then(|n| n.to_str()) == Some("opencode.db"))
        {
            return Some((OpenCodeStorageSurface::Sqlite, exact.clone()));
        }
        if let Some(first) = candidates.into_iter().next() {
            return Some((OpenCodeStorageSurface::Sqlite, first));
        }
    }
    let storage = data_root.join("storage");
    if storage.join("migration").is_file() {
        return Some((OpenCodeStorageSurface::JsonTreeB, storage));
    }
    let project_dir = data_root.join("project");
    if project_dir.is_dir() {
        return Some((OpenCodeStorageSurface::JsonTreeA, project_dir));
    }
    None
}

/// STRICT-VERBATIM line split for `raw` capture (IX-1) — the counterpart to
/// [`non_empty_lines`]'s blank-skipping/trimming PARSE view.
///
/// Splits only on `\n` (never treats `\r\n` specially), so a CRLF source's
/// `\r` survives as part of the returned line's own content; blank lines and
/// trailing-whitespace-only lines are kept verbatim rather than dropped or
/// trimmed. This is what makes `Session.raw` — populated from this at every
/// raw-capture site — byte-for-byte faithful to the source for ANY input, not
/// just well-formed LF JSONL with no blank lines.
///
/// Returns `(lines, ends_with_newline)`. `lines.join("\n")` alone cannot
/// distinguish a source that ended with a trailing newline from one that
/// didn't (both split into the same line list), so `ends_with_newline`
/// records that fact out-of-band — [`join_lines_verbatim`] is the exact
/// inverse, given both. `text == ""` yields `(vec![], false)`: an empty
/// source has zero lines, not one blank line.
fn split_lines_verbatim(text: &str) -> (Vec<&str>, bool) {
    if text.is_empty() {
        return (Vec::new(), false);
    }
    let ends_with_newline = text.ends_with('\n');
    let body = if ends_with_newline {
        &text[..text.len() - 1]
    } else {
        text
    };
    (body.split('\n').collect(), ends_with_newline)
}

/// The exact inverse of [`split_lines_verbatim`]: reconstruct the original
/// source bytes from its verbatim lines plus the trailing-newline flag.
fn join_lines_verbatim(lines: &[String], ends_with_newline: bool) -> String {
    let mut out = lines.join("\n");
    if ends_with_newline {
        out.push('\n');
    }
    out
}

// ---- OpenCode SQLite (PARITY-3/PARITY-4/PARITY-16) -------------------------
//
// Reads a real `opencode*.db` store directly with `rusqlite` (bundled
// SQLite — no system library dependency) and reconstructs the SAME envelope
// form `{"key":[...],"value":...}` that `Session::from_opencode_str` already
// parses for the JSON-tree surfaces (`docs/interop/opencode-pi-spec.md`
// §1.2/S9c). Row -> envelope reconstruction mirrors the real app's own
// `session.ts` `fromRow` (session table: columnar fields recombined into the
// camelCase `SessionInfo` shape) with ONE deliberate divergence: `revert` is
// carried as the RAW column value, not upstream's own `fromRow`
// reconstruction — which silently drops the V2 `Revert.State` schema's extra
// `files` field (`session.ts:70-76`, `revert.ts:18-24`, spec finding S9c).
// `message`/`part` rows are simpler: their `data` column is already the V1
// `Info`/`Part` JSON minus the id columns hoisted out by the schema
// (`session/sql.ts:68-98`), so reconstruction is just re-injecting
// `id`/`sessionID`(/`messageID`).

/// First 16 bytes of every SQLite database file — the format's own magic,
/// independent of file extension.
const SQLITE_MAGIC: &[u8; 16] = b"SQLite format 3\0";

/// Whether `path` should be routed to the OpenCode SQLite loader instead of
/// the UTF-8 text path (PARITY-16): true when the file's first 16 bytes are
/// the SQLite magic, OR its extension is `.db` — the latter so a
/// corrupted/truncated `opencode*.db` still gets `rusqlite`'s own "not a
/// database" diagnostic (PARITY-3 AC03) instead of a confusing UTF-8 error.
/// A non-existent path is NOT considered SQLite here — the missing-file
/// diagnostic in that case comes from the normal load path (`with_context`
/// at the CLI call sites), which already names the path clearly.
pub fn looks_like_sqlite(path: &Path) -> bool {
    if !path.is_file() {
        return false;
    }
    if path.extension().and_then(|e| e.to_str()) == Some("db") {
        return true;
    }
    use std::io::Read;
    let Ok(mut f) = std::fs::File::open(path) else {
        return false;
    };
    let mut buf = [0u8; 16];
    f.read_exact(&mut buf).is_ok() && &buf == SQLITE_MAGIC
}

/// Read `path` as UTF-8 text, translating a non-UTF-8 failure into a clear,
/// format-aware diagnostic (PARITY-16) instead of the raw "stream did not
/// contain valid UTF-8" `io::Error` — named path, and what supercode DOES
/// accept there. Binary SQLite input never reaches this function: callers
/// check [`looks_like_sqlite`] first and route to
/// [`Session::from_opencode_sqlite`] instead.
fn read_utf8_or_diagnose(path: &Path) -> Result<String> {
    let bytes = std::fs::read(path)?;
    String::from_utf8(bytes).map_err(|_| {
        crate::Error::Other(format!(
            "{} is not valid UTF-8 text, and is not a recognized OpenCode SQLite store \
             (no `SQLite format 3` header) — supercode reads Claude Code / Codex / Pi / \
             OpenCode session logs as UTF-8 JSONL, or an OpenCode `opencode*.db` SQLite file",
            path.display()
        ))
    })
}

/// Read only the portion of a JSONL transcript a bounded scrollback can use.
///
/// The first record carries durable session metadata (especially for Codex),
/// while the trailing window carries the messages the viewport will render.
/// Full lossless loaders intentionally continue to read every byte.
fn read_display_jsonl(
    path: &Path,
    message_limit: usize,
) -> Result<(Option<SessionSource>, String, bool)> {
    const MIN_TAIL_BYTES: u64 = 4 * 1024 * 1024;
    const MAX_TAIL_BYTES: u64 = 64 * 1024 * 1024;
    const BYTES_PER_MESSAGE: u64 = 16 * 1024;

    let mut first = String::new();
    BufReader::new(std::fs::File::open(path)?).read_line(&mut first)?;
    let source = detect_source(&first);
    if !matches!(
        source,
        Some(SessionSource::ClaudeCode | SessionSource::Codex | SessionSource::Gemini)
    ) {
        let text = read_utf8_or_diagnose(path)?;
        return Ok((detect_source(&text), text, false));
    }

    let mut file = std::fs::File::open(path)?;
    let file_len = file.metadata()?.len();
    let requested = (message_limit.max(1) as u64)
        .saturating_mul(BYTES_PER_MESSAGE)
        .clamp(MIN_TAIL_BYTES, MAX_TAIL_BYTES);
    if file_len <= requested {
        let text = read_utf8_or_diagnose(path)?;
        return Ok((source, text, false));
    }

    let start = file_len - requested;
    file.seek(SeekFrom::Start(start))?;
    let mut bytes = Vec::with_capacity(requested as usize);
    file.read_to_end(&mut bytes)?;
    // The window normally starts in the middle of a JSON record. Discard that
    // partial prefix so every line passed to the existing parsers is valid.
    if let Some(newline) = bytes.iter().position(|byte| *byte == b'\n') {
        bytes.drain(..=newline);
    }
    let mut tail = String::from_utf8(bytes).map_err(|_| {
        crate::Error::Other(format!(
            "{} contains non-UTF-8 data in its display window",
            path.display()
        ))
    })?;
    if !tail
        .lines()
        .any(|line| native_display_human_line(line, source))
    {
        // A single tool-heavy turn can exceed the ordinary byte window. Search backward through a
        // separately bounded native slice for only its nearest human record, then prepend that one
        // line to the cheap tail. The skipped megabytes are never normalized or sent over RPC.
        let search_bytes = file_len.min(requested.saturating_mul(2).min(MAX_TAIL_BYTES));
        let search_start = file_len - search_bytes;
        file.seek(SeekFrom::Start(search_start))?;
        let mut search = Vec::with_capacity(search_bytes as usize);
        file.read_to_end(&mut search)?;
        if search_start > 0 {
            if let Some(newline) = search.iter().position(|byte| *byte == b'\n') {
                search.drain(..=newline);
            }
        }
        if let Ok(search) = std::str::from_utf8(&search) {
            if let Some(anchor) = search
                .lines()
                .rev()
                .find(|line| native_display_human_line(line, source))
            {
                tail = format!("{anchor}\n{tail}");
            }
        }
    }
    let text = if matches!(source, Some(SessionSource::Codex | SessionSource::Gemini)) {
        format!("{first}{tail}")
    } else {
        tail
    };
    Ok((source, text, true))
}

fn native_display_human_line(line: &str, source: Option<SessionSource>) -> bool {
    if !line
        .as_bytes()
        .windows(6)
        .any(|window| window == b"\"user\"")
    {
        return false;
    }
    let Ok(value) = serde_json::from_str::<Value>(line) else {
        return false;
    };
    match source {
        Some(SessionSource::Codex) => {
            value.get("type").and_then(Value::as_str) == Some("response_item")
                && value
                    .get("payload")
                    .and_then(|payload| payload.get("type"))
                    .and_then(Value::as_str)
                    == Some("message")
                && value
                    .get("payload")
                    .and_then(|payload| payload.get("role"))
                    .and_then(Value::as_str)
                    == Some("user")
        }
        Some(SessionSource::ClaudeCode) => {
            value.get("type").and_then(Value::as_str) == Some("user")
                && value
                    .get("message")
                    .and_then(|message| message.get("content"))
                    .is_some_and(|content| match content {
                        Value::String(text) => !text.trim().is_empty(),
                        Value::Array(parts) => parts.iter().any(|part| {
                            part.get("type").and_then(Value::as_str) == Some("text")
                                && part
                                    .get("text")
                                    .and_then(Value::as_str)
                                    .is_some_and(|text| !text.trim().is_empty())
                        }),
                        _ => false,
                    })
        }
        Some(SessionSource::Gemini) => {
            value.get("type").and_then(Value::as_str) == Some("user")
                && value.get("content").is_some_and(|content| match content {
                    Value::String(text) => !text.trim().is_empty(),
                    Value::Array(parts) => parts.iter().any(|part| {
                        part.get("text")
                            .and_then(Value::as_str)
                            .is_some_and(|text| !text.trim().is_empty())
                    }),
                    _ => false,
                })
        }
        _ => false,
    }
}

fn opencode_sql_err(e: rusqlite::Error, context: &str) -> crate::Error {
    crate::Error::Other(format!("OpenCode SQLite error while {context}: {e}"))
}

/// Open `db_path` read-only and confirm it carries the expected V1 schema
/// (a `session` table) — the shared entry point for every SQLite read below,
/// so every caller gets the SAME clear diagnostics (PARITY-3 AC03): missing
/// path, not-a-database, and wrong/unsupported schema are each named
/// distinctly rather than surfacing later as "zero sessions" or a generic
/// parse failure.
fn opencode_sqlite_open(db_path: &Path) -> Result<Connection> {
    if !db_path.is_file() {
        return Err(crate::Error::Other(format!(
            "OpenCode SQLite store not found at {} — expected an `opencode*.db` file \
             (see `docs/interop/opencode-pi-spec.md` §1.2)",
            db_path.display()
        )));
    }
    let conn = Connection::open_with_flags(
        db_path,
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )
    .map_err(|e| {
        crate::Error::Other(format!(
            "{} does not look like a valid OpenCode SQLite database: {e}",
            db_path.display()
        ))
    })?;
    let has_session_table: i64 = conn
        .query_row(
            "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='session'",
            [],
            |r| r.get(0),
        )
        .map_err(|e| {
            crate::Error::Other(format!(
                "failed to read the OpenCode SQLite schema at {}: {e}",
                db_path.display()
            ))
        })?;
    if has_session_table == 0 {
        return Err(crate::Error::Other(format!(
            "{} is a SQLite database but has no `session` table — not a recognized \
             OpenCode store (wrong file, or an unsupported/pre-SQLite OpenCode version)",
            db_path.display()
        )));
    }
    Ok(conn)
}

/// Parse a nullable JSON-typed SQLite column (`metadata`, `revert`, `model`,
/// …). D7: an unparseable non-empty column previously degraded to
/// `Value::Null` with NO diagnostic — indistinguishable from a genuinely
/// absent/NULL column, so a corrupt `data`/`metadata` value silently
/// vanished (e.g. a message whose `data` fails to parse loses its entire
/// canonical content with no trace). A `tracing::warn!` now surfaces the
/// column name and context (session/record id) whenever this happens, so
/// the failure is diagnosable — `Value::Null` is kept as the parsed VALUE
/// (still the least-wrong placeholder for a broken column; changing it to a
/// sentinel would risk misleading every legitimate `.is_null()` check
/// elsewhere) but the frontend/log now knows it happened.
fn opencode_json_col(s: Option<String>, col: &str, context: &str) -> Value {
    match s.as_deref() {
        None => Value::Null,
        Some(t) => match serde_json::from_str::<Value>(t) {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!(
                    column = col,
                    context,
                    error = %e,
                    "opencode SQLite column failed to parse as JSON — treating as absent (D7)"
                );
                Value::Null
            }
        },
    }
}

/// Columns the `session` table has in a GIVEN store, read once per session
/// load via `PRAGMA table_info` (D3: real-world stores vary — a lean/older
/// `opencode` generation may lack columns the newest schema added, e.g.
/// `workspace_id`; rusqlite's `Row::get(name)` hard-errors
/// "Invalid column name" on an absent column, so callers must check
/// membership before reading a not-guaranteed column instead of reading it
/// unconditionally).
fn opencode_session_columns(
    conn: &Connection,
) -> rusqlite::Result<std::collections::HashSet<String>> {
    let mut stmt = conn.prepare("PRAGMA table_info(session)")?;
    let names = stmt.query_map([], |r| r.get::<_, String>(1))?; // column 1 = name
    names.collect()
}

/// Reconstruct one `session` row into the camelCase `SessionInfo` envelope
/// value [`Session::from_opencode_str`]'s `capture_opencode_session_info`
/// already parses — mirrors upstream's own `session.ts` `fromRow`, EXCEPT
/// `revert` carries the raw column value verbatim rather than upstream's
/// field-selecting reconstruction (spec S9c: that reconstruction silently
/// drops the V2 `Revert.State` schema's extra `files` field).
///
/// D3: not every column this loader would like to read is guaranteed to
/// exist — a real, older/leaner `opencode` install's `session` table (e.g.
/// v1.2.15) lacks `workspace_id`/`path`/`metadata`/`cost`/`tokens_*`/
/// `agent`/`model` entirely. Those are read defensively (guarded by
/// [`opencode_session_columns`]); columns present in EVERY `opencode`
/// generation this loader has ever targeted are still read unconditionally.
fn opencode_row_session_info(conn: &Connection, session_id: &str) -> Result<Value> {
    let cols = opencode_session_columns(conn)
        .map_err(|e| opencode_sql_err(e, &format!("reading session `{session_id}` schema")))?;
    let has = |name: &str| cols.contains(name);

    conn.query_row("SELECT * FROM session WHERE id = ?1", [session_id], |r| {
        let id: String = r.get("id")?;
        let project_id: String = r.get("project_id")?;
        let workspace_id: Option<String> = if has("workspace_id") {
            r.get("workspace_id")?
        } else {
            None
        };
        let parent_id: Option<String> = r.get("parent_id")?;
        let slug: String = r.get("slug")?;
        let directory: String = r.get("directory")?;
        let path: Option<String> = if has("path") { r.get("path")? } else { None };
        let title: String = r.get("title")?;
        let version: String = r.get("version")?;
        let share_url: Option<String> = r.get("share_url")?;
        let summary_additions: Option<i64> = r.get("summary_additions")?;
        let summary_deletions: Option<i64> = r.get("summary_deletions")?;
        let summary_files: Option<i64> = r.get("summary_files")?;
        let summary_diffs: Option<String> = r.get("summary_diffs")?;
        let metadata: Option<String> = if has("metadata") {
            r.get("metadata")?
        } else {
            None
        };
        let cost: f64 = if has("cost") { r.get("cost")? } else { 0.0 };
        let tokens_input: i64 = if has("tokens_input") {
            r.get("tokens_input")?
        } else {
            0
        };
        let tokens_output: i64 = if has("tokens_output") {
            r.get("tokens_output")?
        } else {
            0
        };
        let tokens_reasoning: i64 = if has("tokens_reasoning") {
            r.get("tokens_reasoning")?
        } else {
            0
        };
        let tokens_cache_read: i64 = if has("tokens_cache_read") {
            r.get("tokens_cache_read")?
        } else {
            0
        };
        let tokens_cache_write: i64 = if has("tokens_cache_write") {
            r.get("tokens_cache_write")?
        } else {
            0
        };
        let revert: Option<String> = r.get("revert")?;
        let permission: Option<String> = if has("permission") {
            r.get("permission")?
        } else {
            None
        };
        let agent: Option<String> = if has("agent") { r.get("agent")? } else { None };
        let model: Option<String> = if has("model") { r.get("model")? } else { None };
        let time_created: i64 = r.get("time_created")?;
        let time_updated: i64 = r.get("time_updated")?;
        let time_compacting: Option<i64> = if has("time_compacting") {
            r.get("time_compacting")?
        } else {
            None
        };
        let time_archived: Option<i64> = if has("time_archived") {
            r.get("time_archived")?
        } else {
            None
        };

        let summary =
            (summary_additions.is_some() || summary_deletions.is_some() || summary_files.is_some())
                .then(|| {
                    serde_json::json!({
                        "additions": summary_additions.unwrap_or(0),
                        "deletions": summary_deletions.unwrap_or(0),
                        "files": summary_files.unwrap_or(0),
                        "diffs": opencode_json_col(summary_diffs, "summary_diffs", session_id),
                    })
                });
        let share = share_url.map(|u| serde_json::json!({"url": u}));

        Ok(serde_json::json!({
            "id": id,
            "slug": slug,
            "projectID": project_id,
            "workspaceID": workspace_id,
            "directory": directory,
            "path": path,
            "parentID": parent_id,
            "summary": summary,
            "cost": cost,
            "tokens": {
                "input": tokens_input,
                "output": tokens_output,
                "reasoning": tokens_reasoning,
                "cache": {"read": tokens_cache_read, "write": tokens_cache_write},
            },
            "share": share,
            "title": title,
            "agent": agent,
            "model": opencode_json_col(model, "model", session_id),
            "version": version,
            "metadata": opencode_json_col(metadata, "metadata", session_id),
            "time": {
                "created": time_created,
                "updated": time_updated,
                "compacting": time_compacting,
                "archived": time_archived,
            },
            "permission": opencode_json_col(permission, "permission", session_id),
            // S9c: raw column value, not a field-selecting reconstruction —
            // see this function's doc comment.
            "revert": opencode_json_col(revert, "revert", session_id),
        }))
    })
    .map_err(|e| match e {
        rusqlite::Error::QueryReturnedNoRows => crate::Error::Other(format!(
            "OpenCode session `{session_id}` not found in this SQLite store"
        )),
        e => opencode_sql_err(e, &format!("reading session `{session_id}`")),
    })
}

/// `message.data` / `part.data` already ARE the V1 `Info`/`Part` JSON minus
/// the id columns the schema hoists out (`session/sql.ts:68-98`) — just
/// re-inject them, matching what a JSON-tree file (or the export document)
/// carries at this same key. Also re-injects the row's own `time_created`/
/// `time_updated` columns (D2/S9c: these live OUTSIDE `data` in the real
/// schema — `Timestamps` in `database/schema.sql.ts` — and MUST be carried
/// in the envelope so `raw` is value-complete and re-writable without
/// re-minting timestamps; distinct keys from `data`'s own `"time"` object,
/// which is a different, in-schema field with different semantics).
fn opencode_row_message_value(
    id: &str,
    session_id: &str,
    data_json: &str,
    time_created: i64,
    time_updated: i64,
) -> Value {
    let mut v = opencode_json_col(Some(data_json.to_string()), "message.data", id);
    if let Value::Object(map) = &mut v {
        map.insert("id".to_string(), Value::String(id.to_string()));
        map.insert(
            "sessionID".to_string(),
            Value::String(session_id.to_string()),
        );
        map.insert("time_created".to_string(), Value::from(time_created));
        map.insert("time_updated".to_string(), Value::from(time_updated));
    }
    v
}

fn opencode_row_part_value(
    id: &str,
    session_id: &str,
    message_id: &str,
    data_json: &str,
    time_created: i64,
    time_updated: i64,
) -> Value {
    let mut v = opencode_json_col(Some(data_json.to_string()), "part.data", id);
    if let Value::Object(map) = &mut v {
        map.insert("id".to_string(), Value::String(id.to_string()));
        map.insert(
            "sessionID".to_string(),
            Value::String(session_id.to_string()),
        );
        map.insert(
            "messageID".to_string(),
            Value::String(message_id.to_string()),
        );
        map.insert("time_created".to_string(), Value::from(time_created));
        map.insert("time_updated".to_string(), Value::from(time_updated));
    }
    v
}

/// Ordered envelope lines for one session's `session`/`message`/`part`/`todo`
/// records (`docs/interop/opencode-pi-spec.md` §1.2's frozen order): session
/// info first, then each message (by `time_created, id`) immediately
/// followed by its own parts (by `id`) — parts MUST directly follow their
/// owning message line, since `Session::from_opencode_str`'s envelope parser
/// attaches a `part` line to whichever message id is already in its index
/// and silently leaves an out-of-order part `raw`-only otherwise — then
/// `todo` side-records, then a `session_diff` side-record if the JSON
/// sidecar file for this session exists (order-independent).
///
/// `db_path` is needed only for the `session_diff` sidecar (D3): §1.3 says
/// it "is still JSON-written even on SQLite installs" — verified against
/// `packages/opencode/src/session/revert.ts:76` /
/// `packages/opencode/src/storage/storage.ts:192` at the pinned schema
/// commit, which write it to `<data>/storage/session_diff/<session>.json`
/// (`<data>` being `db_path`'s parent directory) on every revert, entirely
/// separate from the `session.revert` DB column this loader already
/// captures. Without this, revert diffs vanish from `raw` and audit
/// under-counts `session_diff` records for real reverted sessions.
fn opencode_sqlite_session_envelope_lines(
    conn: &Connection,
    db_path: &Path,
    session_id: &str,
) -> Result<Vec<String>> {
    let mut lines = Vec::new();

    let session_info = opencode_row_session_info(conn, session_id)?;
    let project_id = session_info
        .get("projectID")
        .and_then(Value::as_str)
        .unwrap_or("global")
        .to_string();
    lines.push(
        serde_json::json!({"key": ["session", project_id, session_id], "value": session_info})
            .to_string(),
    );

    let mut msg_stmt = conn
        .prepare(
            "SELECT id, data, time_created, time_updated FROM message \
             WHERE session_id = ?1 ORDER BY time_created, id",
        )
        .map_err(|e| opencode_sql_err(e, "preparing the message query"))?;
    let msg_rows = msg_stmt
        .query_map([session_id], |r| {
            let id: String = r.get("id")?;
            let data: String = r.get("data")?;
            let time_created: i64 = r.get("time_created")?;
            let time_updated: i64 = r.get("time_updated")?;
            Ok((id, data, time_created, time_updated))
        })
        .map_err(|e| opencode_sql_err(e, "querying messages"))?;

    let mut part_stmt = conn
        .prepare(
            "SELECT id, data, time_created, time_updated FROM part \
             WHERE message_id = ?1 ORDER BY id",
        )
        .map_err(|e| opencode_sql_err(e, "preparing the part query"))?;

    for row in msg_rows {
        let (msg_id, data, msg_time_created, msg_time_updated) =
            row.map_err(|e| opencode_sql_err(e, "reading a message row"))?;
        let msg_value = opencode_row_message_value(
            &msg_id,
            session_id,
            &data,
            msg_time_created,
            msg_time_updated,
        );
        lines.push(
            serde_json::json!({"key": ["message", session_id, msg_id], "value": msg_value})
                .to_string(),
        );

        let part_rows = part_stmt
            .query_map([&msg_id], |r| {
                let id: String = r.get("id")?;
                let data: String = r.get("data")?;
                let time_created: i64 = r.get("time_created")?;
                let time_updated: i64 = r.get("time_updated")?;
                Ok((id, data, time_created, time_updated))
            })
            .map_err(|e| opencode_sql_err(e, "querying parts"))?;
        for prow in part_rows {
            let (part_id, pdata, part_time_created, part_time_updated) =
                prow.map_err(|e| opencode_sql_err(e, "reading a part row"))?;
            let part_value = opencode_row_part_value(
                &part_id,
                session_id,
                &msg_id,
                &pdata,
                part_time_created,
                part_time_updated,
            );
            lines.push(
                serde_json::json!({"key": ["part", msg_id, part_id], "value": part_value})
                    .to_string(),
            );
        }
    }

    let mut todo_stmt = conn
        .prepare(
            "SELECT content, status, priority, position, time_created, time_updated \
             FROM todo WHERE session_id = ?1 ORDER BY position",
        )
        .map_err(|e| opencode_sql_err(e, "preparing the todo query"))?;
    let todo_rows = todo_stmt
        .query_map([session_id], |r| {
            let content: String = r.get("content")?;
            let status: String = r.get("status")?;
            let priority: String = r.get("priority")?;
            let position: i64 = r.get("position")?;
            let time_created: i64 = r.get("time_created")?;
            let time_updated: i64 = r.get("time_updated")?;
            Ok(serde_json::json!({
                "sessionID": session_id,
                "content": content,
                "status": status,
                "priority": priority,
                "position": position,
                "time": {"created": time_created, "updated": time_updated},
            }))
        })
        .map_err(|e| opencode_sql_err(e, "querying todos"))?;
    for trow in todo_rows {
        let tv = trow.map_err(|e| opencode_sql_err(e, "reading a todo row"))?;
        let position = tv.get("position").cloned().unwrap_or(Value::Null);
        lines.push(
            serde_json::json!({"key": ["todo", session_id, position], "value": tv}).to_string(),
        );
    }

    if let Some(diff_value) = opencode_read_session_diff_sidecar(db_path, session_id) {
        lines.push(
            serde_json::json!({"key": ["session_diff", session_id], "value": diff_value})
                .to_string(),
        );
    }

    Ok(lines)
}

/// D3: read the `session_diff` JSON sidecar file for `session_id`, if
/// present, from `<db_path's parent>/storage/session_diff/<session_id>.json`
/// — the real on-disk location (`storage.ts`'s `Global.Path.data` +
/// `"storage"`, with `db_path` itself living at `Global.Path.data/opencode.db`
/// or `opencode-<channel>.db`). Best-effort: a missing file is the common
/// case (most sessions never revert) and is not an error; an existing-but-
/// unparseable file surfaces a diagnostic (D7-style) rather than silently
/// vanishing.
fn opencode_read_session_diff_sidecar(db_path: &Path, session_id: &str) -> Option<Value> {
    let dir = db_path.parent()?;
    let sidecar = dir
        .join("storage")
        .join("session_diff")
        .join(format!("{session_id}.json"));
    let text = std::fs::read_to_string(&sidecar).ok()?;
    match serde_json::from_str::<Value>(&text) {
        Ok(v) => Some(v),
        Err(e) => {
            tracing::warn!(
                path = %sidecar.display(),
                error = %e,
                "opencode session_diff sidecar failed to parse as JSON — skipping (D7)"
            );
            None
        }
    }
}

/// Pick the "primary" session for a bare `.db` path with no explicit session
/// id (`Session::load`'s auto-detect entry point): the most-recently-updated
/// TOP-LEVEL session (`parent_id IS NULL` sorts first, then `time_updated`
/// descending) — a subagent/task child session is never picked over an
/// available root session, mirroring `most_recent_session`'s "latest wins"
/// convention used elsewhere in this crate for supercode's own store.
fn opencode_sqlite_primary_session_id(conn: &Connection) -> Result<String> {
    conn.query_row(
        "SELECT id FROM session ORDER BY (parent_id IS NULL) DESC, time_updated DESC LIMIT 1",
        [],
        |r| r.get::<_, String>(0),
    )
    .map_err(|e| match e {
        rusqlite::Error::QueryReturnedNoRows => {
            crate::Error::Other("OpenCode SQLite store contains no sessions".to_string())
        }
        e => opencode_sql_err(e, "selecting the primary session"),
    })
}

fn opencode_sqlite_all_session_ids(conn: &Connection, limit: Option<usize>) -> Result<Vec<String>> {
    let mut stmt = conn
        .prepare("SELECT id FROM session ORDER BY time_created, id")
        .map_err(|e| opencode_sql_err(e, "listing sessions"))?;
    let rows = stmt
        .query_map([], |r| r.get::<_, String>(0))
        .map_err(|e| opencode_sql_err(e, "listing sessions"))?;
    let mut ids = Vec::new();
    for row in rows {
        ids.push(row.map_err(|e| opencode_sql_err(e, "reading a session id"))?);
        if limit.is_some_and(|n| ids.len() >= n) {
            break;
        }
    }
    Ok(ids)
}

/// D6: list every session id in an OpenCode SQLite store (oldest first) —
/// exposed so CLI callers (`convert`, `inspect`) can detect a multi-session
/// store and warn before [`Session::load`]/[`Session::from_opencode_sqlite`]
/// silently picks just the primary one. Previously nothing surfaced this:
/// `convert opencode.db --to X` converted 1-of-N sessions with no warning
/// and no way to name a different one.
pub fn opencode_sqlite_session_ids(db_path: &Path) -> Result<Vec<String>> {
    let conn = opencode_sqlite_open(db_path)?;
    opencode_sqlite_all_session_ids(&conn, None)
}

/// D6: the same "most-recently-updated top-level session" selection
/// [`Session::load`]/[`Session::from_opencode_sqlite`] make by default when
/// no explicit session id is given — exposed so a CLI-level warning can name
/// which one was chosen.
pub fn opencode_sqlite_primary_id(db_path: &Path) -> Result<String> {
    let conn = opencode_sqlite_open(db_path)?;
    opencode_sqlite_primary_session_id(&conn)
}

/// Cheap store-level counts — `COUNT(*)` only, no row hydration — for
/// `inspect`'s "reports the audited real store's sessions, messages, and
/// parts" summary (PARITY-3 AC01).
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct OpenCodeSqliteStoreStats {
    /// Row count of the `session` table.
    pub sessions: u64,
    /// Row count of the `message` table.
    pub messages: u64,
    /// Row count of the `part` table.
    pub parts: u64,
    /// Row count of the `todo` table.
    pub todos: u64,
}

/// Count sessions/messages/parts/todos in a real OpenCode SQLite store
/// without loading any of them (PARITY-3 AC01).
pub fn opencode_sqlite_store_stats(db_path: &Path) -> Result<OpenCodeSqliteStoreStats> {
    let conn = opencode_sqlite_open(db_path)?;
    let count = |table: &str| -> Result<u64> {
        let sql = format!("SELECT count(*) FROM {table}");
        conn.query_row(&sql, [], |r| r.get::<_, i64>(0))
            .map(|n| n.max(0) as u64)
            .map_err(|e| opencode_sql_err(e, &format!("counting `{table}` rows")))
    };
    Ok(OpenCodeSqliteStoreStats {
        sessions: count("session")?,
        messages: count("message")?,
        parts: count("part")?,
        todos: count("todo")?,
    })
}

/// Combined envelope text spanning every session in `db_path` (or up to
/// `limit_sessions`) — for corpus-style scanning
/// (the OpenCode SQLite corpus-audit path, PARITY-4).
/// Safe to concatenate multiple sessions' records into one text even though
/// [`Session::from_opencode_str`] itself only keeps the LAST `session` line
/// (single-session semantics) — the audit line-classifier
/// (`audit_opencode_line`) scores each line independently and doesn't care
/// about session boundaries. Use [`Session::from_opencode_sqlite`] to load
/// one session as a real [`Session`].
pub fn opencode_sqlite_corpus_envelope_text(
    db_path: &Path,
    limit_sessions: Option<usize>,
) -> Result<String> {
    let conn = opencode_sqlite_open(db_path)?;
    let ids = opencode_sqlite_all_session_ids(&conn, limit_sessions)?;
    let mut out = String::new();
    for id in ids {
        for line in opencode_sqlite_session_envelope_lines(&conn, db_path, &id)? {
            out.push_str(&line);
            out.push('\n');
        }
    }
    Ok(out)
}

/// PARSE-iteration view (blank/whitespace-only lines skipped, each line
/// trimmed, `\r` line endings normalized away by [`str::lines`]) — used
/// everywhere a loader walks lines looking for JSON *records*, where a blank
/// line is simply not a record and must not become a spurious parse
/// failure/empty entry. Deliberately NOT used for `raw` capture any more
/// (IX-1) — see [`split_lines_verbatim`] for that.
fn non_empty_lines(text: &str) -> impl Iterator<Item = &str> {
    text.lines().map(str::trim).filter(|l| !l.is_empty())
}

// ---- Claude Code ----------------------------------------------------------

/// The `subagents/` directory for a Claude Code transcript at `<dir>/<stem>.jsonl`
/// is `<dir>/<stem>/subagents/`. Returns it only if it exists.
fn subagents_dir_for(main_path: &Path) -> Option<PathBuf> {
    let dir = main_path.parent()?;
    let stem = main_path.file_stem()?.to_str()?;
    let candidate = dir.join(stem).join("subagents");
    candidate.is_dir().then_some(candidate)
}

/// The first `agentId` recorded in a subagent transcript.
fn first_agent_id(jsonl: &str) -> Option<String> {
    for line in non_empty_lines(jsonl) {
        if let Ok(v) = serde_json::from_str::<Value>(line) {
            if let Some(id) = v.get("agentId").and_then(Value::as_str) {
                return Some(id.to_string());
            }
        }
    }
    None
}

/// Find the `tool_use_id` of each parent `Task` call that spawned one of
/// `agent_ids`, by locating the parent transcript's `tool_result` whose
/// serialized content mentions the agent id. Best effort: an id with no
/// qualifying match is simply absent from the returned map.
///
/// Single pass over `main_text` — each line is parsed at most once,
/// regardless of how many agent ids are being sought — with each id's result
/// reproducing exactly what a per-id scan-and-parse-per-hit-line search would
/// return: the first line (in file order) whose raw text contains the id and
/// which — the first qualifying `tool_result` block in that line, in block
/// order — has a string `tool_use_id` and a serialized form that also
/// contains the id. A `tool_result` block matching on raw-line/serialized
/// containment but lacking a `tool_use_id` yields nothing for that id and
/// does not shadow a later match.
fn parent_tool_use_index(main_text: &str, agent_ids: &[String]) -> HashMap<String, String> {
    let mut index: HashMap<String, String> = HashMap::new();
    if agent_ids.is_empty() {
        return index;
    }

    for line in non_empty_lines(main_text) {
        if index.len() == agent_ids.len() {
            break;
        }
        // Cheap prefilter: every match this function can ever return comes
        // from a block whose raw line carries the literal JSON string value
        // `tool_result` (no JSON-escape variants of that ASCII literal).
        if !line.contains("tool_result") {
            continue;
        }
        let still_unmapped: Vec<&String> = agent_ids
            .iter()
            .filter(|id| !index.contains_key(id.as_str()))
            .collect();
        if still_unmapped.is_empty() {
            break;
        }
        let Ok(v) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        let content = v.get("message").and_then(|m| m.get("content"));
        let Some(Value::Array(blocks)) = content else {
            continue;
        };
        for b in blocks {
            if b.get("type").and_then(Value::as_str) != Some("tool_result") {
                continue;
            }
            let Some(tool_use_id) = b.get("tool_use_id").and_then(Value::as_str) else {
                continue;
            };
            let block_str = b.to_string();
            for id in &still_unmapped {
                if index.contains_key(id.as_str()) {
                    continue;
                }
                if line.contains(id.as_str()) && block_str.contains(id.as_str()) {
                    index.insert((*id).clone(), tool_use_id.to_string());
                }
            }
        }
    }

    index
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ClaudeReplayKind {
    User,
    Assistant,
    Attachment,
    System,
}

impl ClaudeReplayKind {
    fn is_conversation(self) -> bool {
        matches!(self, Self::User | Self::Assistant)
    }
}

#[derive(Debug, Clone)]
struct ClaudeReplayNode {
    line_index: usize,
    uuid: String,
    parent_uuid: Option<String>,
    kind: ClaudeReplayKind,
    is_sidechain: bool,
    assistant_message_id: Option<String>,
    is_tool_result: bool,
    compact: Option<ClaudeCompactBoundary>,
}

#[derive(Debug, Clone)]
struct ClaudeCompactBoundary {
    anchor_uuid: Option<String>,
    preserved_uuids: Vec<String>,
    preserved_segment: Option<(String, String)>,
}

/// One projection of a Claude transcript graph: the source lines to replay,
/// plus whatever the projection had to give up to produce them (always empty
/// below [`Fidelity::Semantic`], which is the only level that degrades
/// instead of failing).
#[derive(Debug, Default)]
struct ClaudeReplaySelection {
    lines: Vec<usize>,
    residue: Vec<String>,
}

#[derive(Debug, Default)]
struct ClaudeReplayIndex {
    nodes: Vec<ClaudeReplayNode>,
    by_uuid: HashMap<String, usize>,
    segment_anchors: HashSet<String>,
    last_prompt: Option<(String, bool)>,
    linear_lines: Vec<usize>,
}

impl ClaudeReplayIndex {
    fn observe(&mut self, line_index: usize, v: &Value) -> Result<()> {
        if v.get("type").and_then(Value::as_str) == Some("last-prompt") {
            if let Some(leaf) = v.get("leafUuid").and_then(Value::as_str) {
                self.last_prompt = Some((
                    leaf.to_string(),
                    v.get("explicit").and_then(Value::as_bool) == Some(true),
                ));
            }
            return Ok(());
        }

        // A fork-context-ref is a real Claude graph anchor, but not a replay
        // message. Its child is the first conversational record in the
        // exported fork, so reaching this UUID terminates the locally
        // replayable segment rather than indicating a broken parent edge.
        if v.get("type").and_then(Value::as_str) == Some("fork-context-ref") {
            if let Some(uuid) = v.get("uuid").and_then(Value::as_str) {
                self.segment_anchors.insert(uuid.to_string());
            }
            return Ok(());
        }

        let kind = match v.get("type").and_then(Value::as_str) {
            Some("user") => ClaudeReplayKind::User,
            Some("assistant") => ClaudeReplayKind::Assistant,
            Some("attachment") => ClaudeReplayKind::Attachment,
            Some("system") => ClaudeReplayKind::System,
            _ => return Ok(()),
        };
        self.linear_lines.push(line_index);
        let Some(uuid) = v.get("uuid").and_then(Value::as_str) else {
            return Ok(());
        };
        if self.by_uuid.contains_key(uuid) {
            return Err(claude_replay_error(format!(
                "duplicate uuid `{uuid}` in Claude transcript"
            )));
        }

        let compact = (kind == ClaudeReplayKind::System
            && v.get("subtype").and_then(Value::as_str) == Some("compact_boundary"))
        .then(|| ClaudeCompactBoundary::from_value(v));
        let assistant_message_id = (kind == ClaudeReplayKind::Assistant)
            .then(|| claude_assistant_message_id(v).map(str::to_string))
            .flatten();
        let is_tool_result = kind == ClaudeReplayKind::User
            && v.get("message")
                .and_then(|m| m.get("content"))
                .and_then(Value::as_array)
                .is_some_and(|blocks| {
                    blocks
                        .iter()
                        .any(|b| b.get("type").and_then(Value::as_str) == Some("tool_result"))
                });
        let node = ClaudeReplayNode {
            line_index,
            uuid: uuid.to_string(),
            parent_uuid: v
                .get("parentUuid")
                .and_then(Value::as_str)
                .map(str::to_string),
            kind,
            is_sidechain: v.get("isSidechain").and_then(Value::as_bool) == Some(true),
            assistant_message_id,
            is_tool_result,
            compact,
        };
        self.by_uuid.insert(uuid.to_string(), self.nodes.len());
        self.nodes.push(node);
        Ok(())
    }

    /// Project the transcript at `fidelity`.
    ///
    /// Below [`Fidelity::Semantic`] this is the STRICT projection every
    /// continuation, transfer and export path depends on: reconstruct
    /// Claude's own single active post-compaction branch, or fail naming what
    /// could not be reconstructed.
    ///
    /// [`Fidelity::Semantic`] is the read-only VIEW mode. A Claude transcript
    /// that has been compacted, summarized, or resumed across files routinely
    /// contains a live record whose `parentUuid` names a record that is no
    /// longer on disk. Strict projection rightly refuses — a continuation
    /// built on a guessed graph is silent loss — but a VIEW does not need a
    /// continuation, so this mode anchors each dangling edge as a segment
    /// root, projects every severed segment exactly as the active branch is
    /// projected, splices them back together in transcript order, and names
    /// every degradation in the returned residue instead of erroring.
    fn select_lines(mut self, fidelity: Fidelity) -> Result<ClaudeReplaySelection> {
        let lenient = fidelity.tolerates_residue();
        let mut residue = Vec::new();
        if self.nodes.is_empty() {
            // Older exports and many hand-authored compatibility fixtures do
            // not carry Claude's `uuid`/`parentUuid` graph fields. There is no
            // branch information to project in that shape, so preserve the
            // historical linear normalization behavior. Native graph-bearing
            // transcripts always take the projection below.
            return Ok(ClaudeReplaySelection {
                lines: self.linear_lines,
                residue,
            });
        }
        if lenient {
            self.anchor_dangling_parents(&mut residue);
        }
        // Last resort for a VIEW: a transcript whose graph is unprojectable
        // for some OTHER reason (a cycle, an unresolvable compact boundary)
        // still renders as the file's own record order. A read-only mirror
        // that cannot open a session at all is the defect this mode exists
        // to remove, so `Semantic` never returns an error.
        let fallback = lenient.then(|| self.linear_lines.clone());
        match self.project(lenient, &mut residue) {
            Ok(lines) => Ok(ClaudeReplaySelection { lines, residue }),
            Err(error) => match fallback {
                Some(lines) => {
                    residue.push(format!(
                        "the Claude record graph could not be projected ({error}); \
                         every record was stitched in transcript order instead"
                    ));
                    Ok(ClaudeReplaySelection { lines, residue })
                }
                None => Err(error),
            },
        }
    }

    /// Turn every edge that points outside the transcript into a segment
    /// root, naming the dangling uuids as residue.
    ///
    /// A `fork-context-ref` anchor is already a declared segment boundary,
    /// not a break, so it is left alone.
    fn anchor_dangling_parents(&mut self, residue: &mut Vec<String>) {
        let mut dangling = Vec::new();
        for idx in 0..self.nodes.len() {
            let Some(parent) = self.nodes[idx].parent_uuid.as_deref() else {
                continue;
            };
            if self.by_uuid.contains_key(parent) || self.segment_anchors.contains(parent) {
                continue;
            }
            dangling.push(format!("`{}` → `{parent}`", self.nodes[idx].uuid));
            self.nodes[idx].parent_uuid = None;
        }
        if dangling.is_empty() {
            return;
        }
        const NAMED: usize = 8;
        let total = dangling.len();
        let overflow = total.saturating_sub(NAMED);
        dangling.truncate(NAMED);
        let mut listed = dangling.join(", ");
        if overflow > 0 {
            listed.push_str(&format!(", and {overflow} more"));
        }
        residue.push(format!(
            "{total} Claude record(s) reference a parentUuid absent from the transcript and were \
             anchored as segment roots: {listed}"
        ));
    }

    fn project(&mut self, lenient: bool, residue: &mut Vec<String>) -> Result<Vec<usize>> {
        let mut retained = vec![true; self.nodes.len()];
        if let Some(boundary_index) = self.nodes.iter().rposition(|n| n.compact.is_some()) {
            let parents: Option<Vec<Option<String>>> = lenient.then(|| {
                self.nodes
                    .iter()
                    .map(|node| node.parent_uuid.clone())
                    .collect()
            });
            if let Err(error) = self.apply_latest_compaction(boundary_index, &mut retained) {
                let Some(parents) = parents else {
                    return Err(error);
                };
                // The boundary rewrites parents as it goes, so restore the
                // graph it half-edited before continuing without it.
                for (node, parent) in self.nodes.iter_mut().zip(parents) {
                    node.parent_uuid = parent;
                }
                retained.iter_mut().for_each(|keep| *keep = true);
                residue.push(format!(
                    "the latest Claude compact boundary could not be projected ({error}); \
                     no pre-compaction record was pruned from this view"
                ));
            }
        }
        let sidechain_only = self
            .nodes
            .iter()
            .enumerate()
            .filter(|(idx, node)| retained[*idx] && node.kind.is_conversation())
            .all(|(_, node)| node.is_sidechain);

        let explicit_leaf = self
            .last_prompt
            .as_ref()
            .filter(|(_, explicit)| *explicit)
            .and_then(|(uuid, _)| self.by_uuid.get(uuid).copied())
            .filter(|idx| retained[*idx]);
        let newest_non_sidechain = self
            .nodes
            .iter()
            .enumerate()
            .rev()
            .find(|(idx, node)| retained[*idx] && !node.is_sidechain)
            .map(|(idx, _)| idx);
        // Dedicated Claude subagent transcripts are sidechains by design:
        // every record, including their root user prompt, has
        // `isSidechain:true`. When there is no main-chain candidate, resume
        // the newest retained sidechain leaf instead of rejecting the child.
        let newest_sidechain = self
            .nodes
            .iter()
            .enumerate()
            .rev()
            .find(|(idx, node)| retained[*idx] && node.is_sidechain && node.kind.is_conversation())
            .map(|(idx, _)| idx);
        let mut active = explicit_leaf
            .or(newest_non_sidechain)
            .or(newest_sidechain)
            .ok_or_else(|| claude_replay_error("no Claude record remains after compaction"))?;

        // Metadata descendants such as turn_duration are leaves in the raw
        // graph. Claude resumes from their nearest user/assistant ancestor,
        // then appends those descendants to the reconstructed chain.
        let mut seeking = HashSet::new();
        while !self.nodes[active].kind.is_conversation() {
            if !seeking.insert(active) {
                return Err(claude_replay_error(
                    "cycle while resolving active Claude leaf",
                ));
            }
            active = self.parent_index(active, &retained)?;
        }

        let mut segments =
            vec![self.project_segment(active, &retained, sidechain_only, lenient)?];
        if lenient {
            for leaf in self.severed_segment_leaves(active, &retained) {
                segments.push(self.project_segment(leaf, &retained, sidechain_only, lenient)?);
            }
            if segments.len() > 1 {
                residue.push(format!(
                    "{} conversation segments were stitched in transcript order because the \
                     Claude record graph is severed",
                    segments.len()
                ));
            }
        }
        // Each segment keeps its own reconstructed order; the segments
        // themselves are spliced by where they start in the file.
        segments.retain(|segment| !segment.is_empty());
        segments.sort_by_key(|segment| {
            segment
                .iter()
                .map(|idx| self.nodes[*idx].line_index)
                .min()
                .unwrap_or(usize::MAX)
        });
        let mut ordered = Vec::new();
        let mut placed = HashSet::new();
        for idx in segments.into_iter().flatten() {
            if placed.insert(idx) {
                ordered.push(idx);
            }
        }

        self.recover_parallel_assistant_chunks(ordered, &retained)
            .map(|indices| {
                indices
                    .into_iter()
                    .map(|idx| self.nodes[idx].line_index)
                    .collect()
            })
    }

    /// Reconstruct one segment: `leaf`'s parent chain, oldest-first, plus the
    /// non-conversation descendants rooted at it.
    fn project_segment(
        &self,
        leaf: usize,
        retained: &[bool],
        sidechain_only: bool,
        lenient: bool,
    ) -> Result<Vec<usize>> {
        let mut reversed = Vec::new();
        let mut seen = HashSet::new();
        let mut cursor = Some(leaf);
        while let Some(idx) = cursor {
            if !seen.insert(idx) {
                return Err(claude_replay_error(format!(
                    "cycle in active Claude parentUuid chain at `{}`",
                    self.nodes[idx].uuid
                )));
            }
            reversed.push(idx);
            cursor = match self.nodes[idx].parent_uuid.as_deref() {
                Some(parent) => match self.by_uuid.get(parent).copied() {
                    Some(parent) => Some(parent),
                    None if self.segment_anchors.contains(parent) => None,
                    // Claude can resume a background child in-place while
                    // retaining only the new segment in that child's JSONL.
                    // Its first record then points to a UUID not present in
                    // the sidechain file. That external edge is a segment
                    // boundary, not corruption; the complete source remains
                    // available byte-for-byte in `raw`.
                    None if sidechain_only => None,
                    None => {
                        return Err(claude_replay_error(format!(
                            "active Claude record `{}` has missing parentUuid `{parent}`",
                            self.nodes[idx].uuid
                        )));
                    }
                },
                None => None,
            };
            if cursor.is_some_and(|parent| !retained[parent]) {
                if lenient {
                    // A compaction boundary is where this segment ends; the
                    // records it pruned stay pruned.
                    break;
                }
                return Err(claude_replay_error(format!(
                    "active Claude chain crosses an excluded compaction record from `{}`",
                    self.nodes[idx].uuid
                )));
            }
        }
        reversed.reverse();

        // Include non-conversation descendants rooted at the segment's leaf
        // (turn_duration, attachments, etc.), matching Claude's QYH/n1T.
        let mut descendants = Vec::new();
        let mut frontier = vec![leaf];
        let mut head = 0;
        while head < frontier.len() {
            let parent = frontier[head];
            head += 1;
            for (idx, node) in self.nodes.iter().enumerate() {
                if !retained[idx]
                    || node.kind.is_conversation()
                    || seen.contains(&idx)
                    || node.parent_uuid.as_deref() != Some(self.nodes[parent].uuid.as_str())
                {
                    continue;
                }
                seen.insert(idx);
                descendants.push(idx);
                frontier.push(idx);
            }
        }
        descendants.sort_by_key(|idx| self.nodes[*idx].line_index);
        reversed.extend(descendants);
        Ok(reversed)
    }

    /// The newest retained conversation record of every component the active
    /// leaf's own component cannot reach.
    ///
    /// Only a severed graph produces any: a healthy transcript is one
    /// component, so the abandoned branches a rewind left behind stay
    /// abandoned here exactly as they do under strict projection.
    fn severed_segment_leaves(&self, active: usize, retained: &[bool]) -> Vec<usize> {
        let active_root = self.component_root(active, retained);
        let mut newest_by_root: BTreeMap<usize, usize> = BTreeMap::new();
        for idx in 0..self.nodes.len() {
            if !retained[idx] || !self.nodes[idx].kind.is_conversation() {
                continue;
            }
            let Some(root) = self.component_root(idx, retained) else {
                continue;
            };
            if Some(root) == active_root {
                continue;
            }
            let newest = newest_by_root.entry(root).or_insert(idx);
            if self.nodes[idx].line_index > self.nodes[*newest].line_index {
                *newest = idx;
            }
        }
        newest_by_root.into_values().collect()
    }

    /// Walk `idx` up to the record that anchors its component, stopping at a
    /// root, an edge that leaves the transcript, or a pruned parent. `None`
    /// when the walk cycles.
    fn component_root(&self, idx: usize, retained: &[bool]) -> Option<usize> {
        let mut cursor = idx;
        let mut seen = HashSet::new();
        loop {
            if !seen.insert(cursor) {
                return None;
            }
            let next = self.nodes[cursor]
                .parent_uuid
                .as_deref()
                .and_then(|parent| self.by_uuid.get(parent).copied())
                .filter(|parent| retained[*parent]);
            match next {
                Some(parent) => cursor = parent,
                None => return Some(cursor),
            }
        }
    }

    fn apply_latest_compaction(
        &mut self,
        boundary_index: usize,
        retained: &mut [bool],
    ) -> Result<()> {
        let compact = self.nodes[boundary_index]
            .compact
            .clone()
            .expect("called with compact boundary");
        let mut preserved = compact.preserved_uuids;
        if preserved.is_empty() {
            if let Some((head, tail)) = compact.preserved_segment {
                preserved = self.walk_preserved_segment(&head, &tail)?;
            }
        }

        let preserved_set: HashSet<String> = preserved.iter().cloned().collect();
        for uuid in &preserved {
            if !self.by_uuid.contains_key(uuid) {
                return Err(claude_replay_error(format!(
                    "latest compact boundary references missing preserved uuid `{uuid}`"
                )));
            }
        }

        let removed_uuids: HashSet<String> = self
            .nodes
            .iter()
            .enumerate()
            .filter(|(idx, node)| *idx < boundary_index && !preserved_set.contains(&node.uuid))
            .map(|(_, node)| node.uuid.clone())
            .collect();
        for (idx, node) in self.nodes.iter().enumerate() {
            if idx < boundary_index && !preserved_set.contains(&node.uuid) {
                retained[idx] = false;
            }
        }

        if preserved.is_empty() {
            return Ok(());
        }
        let anchor = compact.anchor_uuid.ok_or_else(|| {
            claude_replay_error("preserved compact boundary is missing anchorUuid")
        })?;
        if !self.by_uuid.contains_key(&anchor) {
            return Err(claude_replay_error(format!(
                "latest compact boundary references missing anchor uuid `{anchor}`"
            )));
        }
        let tail = preserved.last().cloned().expect("non-empty preserved list");
        let mut parent = anchor.clone();
        for uuid in &preserved {
            let idx = self.by_uuid[uuid];
            self.nodes[idx].parent_uuid = Some(parent);
            parent = uuid.clone();
        }
        let first = &preserved[0];
        for node in &mut self.nodes {
            if node.parent_uuid.as_deref() == Some(anchor.as_str()) && node.uuid != *first {
                node.parent_uuid = Some(tail.clone());
            }
        }
        for node in &mut self.nodes {
            if node.kind.is_conversation()
                && node
                    .parent_uuid
                    .as_ref()
                    .is_some_and(|parent| removed_uuids.contains(parent))
            {
                node.parent_uuid = Some(tail.clone());
            }
        }
        Ok(())
    }

    fn walk_preserved_segment(&self, head: &str, tail: &str) -> Result<Vec<String>> {
        let mut reversed = Vec::new();
        let mut seen = HashSet::new();
        let mut cursor = tail;
        loop {
            if !seen.insert(cursor.to_string()) {
                return Err(claude_replay_error("cycle in compact preservedSegment"));
            }
            let idx = *self.by_uuid.get(cursor).ok_or_else(|| {
                claude_replay_error(format!(
                    "compact preservedSegment references missing uuid `{cursor}`"
                ))
            })?;
            reversed.push(cursor.to_string());
            if cursor == head {
                reversed.reverse();
                return Ok(reversed);
            }
            cursor = self.nodes[idx].parent_uuid.as_deref().ok_or_else(|| {
                claude_replay_error(format!(
                    "compact preservedSegment tail `{tail}` does not reach head `{head}`"
                ))
            })?;
        }
    }

    fn parent_index(&self, idx: usize, retained: &[bool]) -> Result<usize> {
        let parent = self.nodes[idx].parent_uuid.as_deref().ok_or_else(|| {
            claude_replay_error(format!(
                "Claude record `{}` has no conversational ancestor",
                self.nodes[idx].uuid
            ))
        })?;
        let parent_idx = *self.by_uuid.get(parent).ok_or_else(|| {
            claude_replay_error(format!(
                "Claude record `{}` has missing parentUuid `{parent}`",
                self.nodes[idx].uuid
            ))
        })?;
        if !retained[parent_idx] {
            return Err(claude_replay_error(format!(
                "Claude record `{}` points into compacted-out history",
                self.nodes[idx].uuid
            )));
        }
        Ok(parent_idx)
    }

    fn recover_parallel_assistant_chunks(
        &self,
        base: Vec<usize>,
        retained: &[bool],
    ) -> Result<Vec<usize>> {
        let selected: HashSet<usize> = base.iter().copied().collect();
        let mut replacements: HashMap<usize, Vec<usize>> = HashMap::new();
        let mut skipped_positions = HashSet::new();
        let mut handled_ids = HashSet::new();

        for (base_pos, idx) in base.iter().copied().enumerate() {
            let Some(message_id) = self.nodes[idx].assistant_message_id.as_deref() else {
                continue;
            };
            if !handled_ids.insert(message_id.to_string()) {
                continue;
            }
            let base_positions: Vec<usize> = base
                .iter()
                .enumerate()
                .filter(|(_, candidate)| {
                    self.nodes[**candidate].assistant_message_id.as_deref() == Some(message_id)
                })
                .map(|(pos, _)| pos)
                .collect();
            let anchor_pos = base_positions.first().copied().unwrap_or(base_pos);
            skipped_positions.extend(base_positions.iter().copied().skip(1));

            // A streamed Anthropic response can be stored as sibling records
            // rather than a literal parent chain. Reassemble every chunk at
            // the first active occurrence and restore raw chunk order before
            // the normalizer coalesces their content blocks.
            let mut chunks: Vec<usize> = self
                .nodes
                .iter()
                .enumerate()
                .filter(|(candidate, node)| {
                    retained[*candidate] && node.assistant_message_id.as_deref() == Some(message_id)
                })
                .map(|(candidate, _)| candidate)
                .collect();
            chunks.sort_by_key(|candidate| self.nodes[*candidate].line_index);

            let assistant_uuids: HashSet<&str> = self
                .nodes
                .iter()
                .filter(|node| node.assistant_message_id.as_deref() == Some(message_id))
                .map(|node| node.uuid.as_str())
                .collect();
            let mut results: Vec<usize> = self
                .nodes
                .iter()
                .enumerate()
                .filter(|(candidate, node)| {
                    retained[*candidate]
                        && !selected.contains(candidate)
                        && node.is_tool_result
                        && node
                            .parent_uuid
                            .as_deref()
                            .is_some_and(|parent| assistant_uuids.contains(parent))
                })
                .map(|(candidate, _)| candidate)
                .collect();
            results.sort_by_key(|candidate| self.nodes[*candidate].line_index);
            chunks.extend(results);
            replacements.insert(anchor_pos, chunks);
        }

        let mut out = Vec::with_capacity(selected.len());
        for (pos, idx) in base.into_iter().enumerate() {
            if let Some(replacement) = replacements.remove(&pos) {
                out.extend(replacement);
            } else if !skipped_positions.contains(&pos) {
                out.push(idx);
            }
        }
        Ok(out)
    }
}

impl ClaudeCompactBoundary {
    fn from_value(v: &Value) -> Self {
        let metadata = v.get("compactMetadata");
        let preserved_messages = metadata.and_then(|m| m.get("preservedMessages"));
        let anchor_uuid = preserved_messages
            .and_then(|p| p.get("anchorUuid"))
            .and_then(Value::as_str)
            .or_else(|| {
                metadata
                    .and_then(|m| m.get("preservedSegment"))
                    .and_then(|p| p.get("anchorUuid"))
                    .and_then(Value::as_str)
            })
            .map(str::to_string);
        let preserved_uuids = preserved_messages
            .and_then(|p| p.get("uuids"))
            .and_then(Value::as_array)
            .map(|uuids| {
                uuids
                    .iter()
                    .filter_map(Value::as_str)
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default();
        let preserved_segment =
            metadata
                .and_then(|m| m.get("preservedSegment"))
                .and_then(|segment| {
                    Some((
                        segment.get("headUuid")?.as_str()?.to_string(),
                        segment.get("tailUuid")?.as_str()?.to_string(),
                    ))
                });
        Self {
            anchor_uuid,
            preserved_uuids,
            preserved_segment,
        }
    }
}

fn claude_replay_error(message: impl Into<String>) -> crate::Error {
    crate::Error::Other(format!(
        "cannot reconstruct lossless Claude continuation: {}",
        message.into()
    ))
}

fn claude_assistant_message_id(v: &Value) -> Option<&str> {
    v.get("message")
        .and_then(|message| message.get("id"))
        .and_then(Value::as_str)
}

fn merge_claude_assistant_chunk(target: &mut Value, chunk: &Value) {
    let Some(target_message) = target.get_mut("message") else {
        return;
    };
    let Some(chunk_message) = chunk.get("message") else {
        return;
    };
    let mut content = target_message
        .get("content")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    if let Some(blocks) = chunk_message.get("content").and_then(Value::as_array) {
        content.extend(blocks.iter().cloned());
    }
    let mut merged_message = chunk_message.clone();
    merged_message["content"] = Value::Array(content);
    *target_message = merged_message;
}

fn flush_claude_assistant(pending: &mut Option<Value>, out: &mut Vec<ChatMessage>) {
    let Some(v) = pending.take() else {
        return;
    };
    let reasoning_only = claude_assistant_message_id(&v).is_some()
        && v.get("message")
            .and_then(|message| message.get("content"))
            .and_then(Value::as_array)
            .is_some_and(|blocks| {
                !blocks.is_empty()
                    && blocks.iter().all(|block| {
                        matches!(
                            block.get("type").and_then(Value::as_str),
                            Some("thinking" | "redacted_thinking")
                        )
                    })
            });
    if reasoning_only {
        return;
    }
    let before = out.len();
    push_claude_assistant(&v, out);
    capture_claude_record_provenance(&v, &mut out[before..]);
    restore_single_grok_message(&v, &mut out[before..]);
}

/// Attach the record identity, clock, and actual assistant model to every
/// canonical message produced from one Claude JSONL record. These fields are
/// deliberately per-message: a continued transcript can cross a provider
/// boundary, so the session-level source model is not authoritative for its
/// appended tail.
fn capture_claude_record_provenance(v: &Value, messages: &mut [ChatMessage]) {
    let timestamp = v.get("timestamp").and_then(Value::as_str);
    let uuid = v.get("uuid").and_then(Value::as_str);
    let model = v
        .get("message")
        .and_then(|message| message.get("model"))
        .and_then(Value::as_str);
    for message in messages {
        if let Some(timestamp) = timestamp {
            message
                .metadata
                .entry("timestamp".to_string())
                .or_insert_with(|| timestamp.to_string());
        }
        if let Some(uuid) = uuid {
            message
                .metadata
                .entry("claude_uuid".to_string())
                .or_insert_with(|| uuid.to_string());
        }
        if let Some(model) = model {
            message
                .metadata
                .entry("model".to_string())
                .or_insert_with(|| model.to_string());
        }
    }
}

fn capture_claude_meta(v: &Value, meta: &mut SessionMeta, raw_line: &str) -> Result<()> {
    restore_codex_provenance_from_top_level(v, meta)?;
    if meta.session_id.is_none() {
        if let Some(id) = v.get("sessionId").and_then(Value::as_str) {
            meta.session_id = Some(id.to_string());
        }
    }
    if meta.cwd.is_none() {
        if let Some(cwd) = v.get("cwd").and_then(Value::as_str) {
            meta.cwd = Some(PathBuf::from(cwd));
        }
    }
    if meta.model.is_none() {
        if let Some(model) = v
            .get("message")
            .and_then(|m| m.get("model"))
            .and_then(Value::as_str)
        {
            meta.model = Some(model.to_string());
        }
    }
    // PARITY-10 (provenance P010): `fork-context-ref` is an extremely rare
    // real Claude Code record with no confirmed field shape (see
    // `ClaudeRecord::ForkContextRef`'s doc comment) — rather than guess at
    // named fields and risk silently mis-modeling it, stash the WHOLE raw
    // line verbatim under a lineage key. `write_claude_code_records` (below)
    // re-emits it byte-for-byte, so the record survives the Claude Code
    // semantic writer (not just the CLI's raw-passthrough diagonal path) —
    // and `to_codex_jsonl`'s synthesized header carries a namespaced copy
    // so a Claude -> Codex -> Claude round trip can still reconstruct it
    // (dev/03). A session can only fork from one context, so the first one
    // seen wins, matching every other "first wins" field above.
    //
    // D4 (Fable-5 review, confirmed): this used to store `v.to_string()` —
    // a RE-SERIALIZATION of the parsed `Value`, not the original source
    // text. `serde_json::Value` here has no `preserve_order` feature (see
    // `Cargo.toml`), so its object keys are a `BTreeMap` and get silently
    // REORDERED (alphabetized) on re-emit — the "byte-for-byte" claim in
    // this very comment was false. Fixed the cheap+honest way: store the
    // caller's own already-verbatim source `raw_line` text instead of
    // re-serializing `v` at all, so this is now ACTUALLY byte-for-byte
    // (key order, spacing, everything) rather than merely
    // structurally-equivalent JSON.
    if v.get("type").and_then(Value::as_str) == Some("fork-context-ref")
        && !meta.lineage.contains_key("claude_fork_context_ref_raw")
    {
        meta.lineage.insert(
            "claude_fork_context_ref_raw".to_string(),
            raw_line.to_string(),
        );
    }
    Ok(())
}

fn push_claude_user(v: &Value, out: &mut Vec<ChatMessage>) {
    let content = v.get("message").and_then(|m| m.get("content"));
    let provenance = claude_user_provenance(v);
    match content {
        Some(Value::String(s)) => {
            if !s.trim().is_empty() {
                out.push(ChatMessage::user(s.clone()).with_metas(&provenance));
            }
        }
        Some(Value::Array(blocks)) => {
            let mut text = String::new();
            // IX-5: image blocks alongside/instead of text — collected
            // separately (never synthesized on a malformed shape, see
            // `claude_image_block_to_part`) so a multimodal user turn
            // survives as `content_parts` instead of the image silently
            // vanishing.
            let mut images: Vec<Value> = Vec::new();
            // D5: an `image` block whose `source` isn't base64/url (e.g. a
            // Files-API `{"source":{"type":"file","file_id":..}}`
            // reference) makes `claude_image_block_to_part` return `None` —
            // track that it was SEEN even though it couldn't be converted,
            // so an image-ONLY record (no text, no convertible image) isn't
            // silently dropped below (the same vanishing-record bug-class
            // PARITY-11 fixed for reasoning-only turns).
            let mut saw_unconvertible_image = false;
            for b in blocks {
                match b.get("type").and_then(Value::as_str) {
                    Some("text") => push_text(&mut text, b.get("text")),
                    Some("tool_result") => {
                        let id = b
                            .get("tool_use_id")
                            .and_then(Value::as_str)
                            .unwrap_or_default();
                        // PARITY-11 (nested images): `extract_tool_result_content`
                        // captures any `image` blocks nested inside this
                        // `tool_result` into `content_parts` (via
                        // `claude_image_block_to_part`, the same conversion the
                        // top-level `image` block path already uses) instead of
                        // flattening them to the bare `[image]` marker text the
                        // old `extract_tool_result` emitted — the everyday
                        // "Read a PNG / screenshot tool output" shape.
                        let (result, images) =
                            extract_tool_result_content(b.get("content"), v.get("toolUseResult"));
                        let mut msg = tool_message(id, result);
                        if !images.is_empty() {
                            // D-mix (Fable review, must-fix): `content_parts`
                            // is a self-contained contract — the pi writer
                            // (`pi_content_value`) reads ONLY `content_parts`
                            // for a `Role::Tool` message and never falls back
                            // to `msg.content`, so on a MIXED text+image
                            // tool_result a bare `content_parts: [image]`
                            // silently drops the sibling text on `convert
                            // --to pi` (a regression vs. the pre-PARITY-11
                            // baseline, which at least preserved the text).
                            // Prepend the text as part 0, exactly mirroring
                            // `pi_content_to_text_and_parts` and
                            // `push_opencode_user`'s identical
                            // self-contained-parts construction. `msg.content`
                            // keeps the text too (unchanged) for the writers
                            // that read text from `msg.content` and only scan
                            // `content_parts` for `image_url` entries
                            // (`claude_tool_result_content_value`,
                            // `codex_tool_output_text`, the opencode
                            // assistant writer) — those already filter
                            // strictly on `image_url`/text-typed lookups, so
                            // this text part is never double-counted.
                            let mut parts = Vec::new();
                            if let Some(t) = &msg.content {
                                if !t.is_empty() {
                                    parts.push(serde_json::json!({"type": "text", "text": t}));
                                }
                            }
                            parts.extend(images);
                            msg.content_parts = Some(parts);
                        }
                        // The assistant turn that issued this tool call — the
                        // tool-pairing graph edge (parallel to parentUuid).
                        if let Some(src) = v.get("sourceToolAssistantUUID").and_then(Value::as_str)
                        {
                            msg.metadata
                                .insert("sourceToolAssistantUUID".to_string(), src.to_string());
                        }
                        // TR-10: preserve the Claude wire `is_error` flag so
                        // the reduction layer's success/failure boundary
                        // (`ReductionKind::ToolInputElided` must never target
                        // an errored call) survives import — `ChatMessage`
                        // otherwise has no structural slot for it.
                        if b.get("is_error").and_then(Value::as_bool) == Some(true) {
                            crate::mark_tool_error(&mut msg);
                        } else {
                            restore_tool_outcome_extension(v, &mut msg);
                        }
                        out.push(msg);
                    }
                    Some("image") => match claude_image_block_to_part(b) {
                        Some(part) => images.push(part),
                        None => saw_unconvertible_image = true,
                    },
                    _ => {} // document / unknown — skip
                }
            }
            // D5: nothing convertible landed in `text`/`images` but an
            // image block WAS present — fold in the same short bracketed
            // marker convention already used for `[web_search]`/`[model
            // fallback: ...]` rather than letting the record vanish.
            if images.is_empty() && text.trim().is_empty() && saw_unconvertible_image {
                push_str_field(&mut text, UNCONVERTIBLE_IMAGE_MARKER);
            }
            let before = out.len();
            if !images.is_empty() {
                let mut parts = Vec::new();
                if !text.trim().is_empty() {
                    parts.push(serde_json::json!({"type": "text", "text": text.clone()}));
                }
                parts.extend(images);
                out.push(
                    ChatMessage {
                        role: Role::User,
                        content: None,
                        content_parts: Some(parts),
                        tool_calls: None,
                        tool_call_id: None,
                        name: None,
                        metadata: Default::default(),
                    }
                    .with_metas(&provenance),
                );
            } else if !text.trim().is_empty() {
                out.push(ChatMessage::user(text).with_metas(&provenance));
            }
            if saw_unconvertible_image && out.len() > before {
                if let Some(msg) = out.last_mut() {
                    msg.metadata
                        .insert("image_source_unconvertible".to_string(), "true".to_string());
                }
            }
        }
        _ => {}
    }
}

/// D5 (Fable-5 review): the bracketed marker folded into `text` when an
/// `image` block is SEEN but [`claude_image_block_to_part`] can't convert it
/// (e.g. a Files-API `{"source":{"type":"file",...}}` reference) and nothing
/// else in the record survives either — matches the existing
/// `[web_search]`/`[model fallback: ...]` convention rather than letting the
/// whole record vanish (`push_claude_user`/`push_claude_assistant`).
const UNCONVERTIBLE_IMAGE_MARKER: &str =
    "[image: source not captured — unsupported/unconvertible image reference]";

/// Parse a Claude Code user-turn `image` content block
/// (`{"type":"image","source":{"type":"base64","media_type":..,"data":..}}`
/// or `{"type":"image","source":{"type":"url","url":..}}`) into a
/// `content_parts` `image_url` entry (a `data:` URI for the base64 form, the
/// bare URL for the url form) — the inverse of
/// [`claude_user_content_value`]'s emission. Only a well-formed source
/// (non-empty `media_type`/`data`, or non-empty `url`) is recognized;
/// anything else — including a well-formed but unconvertible source like a
/// Files-API `{"type":"file",...}` reference (D5) — is left as raw-only
/// residue rather than synthesizing a corrupt/empty part (mirrors the
/// pi/opencode loaders' `pi_image_shape`/`opencode_file_image_part`
/// discipline). Callers must not let that turn the record invisible though:
/// see [`UNCONVERTIBLE_IMAGE_MARKER`].
fn claude_image_block_to_part(b: &Value) -> Option<Value> {
    let source = b.get("source")?;
    match source.get("type").and_then(Value::as_str) {
        Some("base64") => {
            let mime = source.get("media_type").and_then(Value::as_str)?;
            let data = source.get("data").and_then(Value::as_str)?;
            if mime.is_empty() || data.is_empty() {
                return None;
            }
            Some(serde_json::json!({
                "type": "image_url",
                "image_url": {"url": format!("data:{mime};base64,{data}")},
            }))
        }
        Some("url") => {
            let url = source.get("url").and_then(Value::as_str)?;
            if url.is_empty() {
                return None;
            }
            Some(serde_json::json!({"type": "image_url", "image_url": {"url": url}}))
        }
        _ => None,
    }
}

/// Rebuild a Claude Code user-turn `message.content` value from a
/// `ChatMessage` — the inverse of `push_claude_user`'s parse (text blocks +
/// [`claude_image_block_to_part`]). When `content_parts` is absent this
/// MUST reproduce the historical plain-string `content` exactly (IX-5's
/// overriding constraint: a text-only message's export stays byte-identical)
/// — only a multimodal message (`content_parts` present, e.g. imported from
/// Pi/OpenCode or a real Claude Code image turn) gets the Anthropic
/// content-array shape, one `text` block (if any non-empty text part) plus
/// one `image` block per `image_url` part (`data:` URI → `source.base64`;
/// any other URL → `source.url`).
fn claude_user_content_value(msg: &ChatMessage) -> Value {
    match &msg.content_parts {
        Some(parts) => {
            let mut blocks = Vec::new();
            for p in parts {
                match p.get("type").and_then(Value::as_str) {
                    Some("text") => {
                        if let Some(t) = p.get("text").and_then(Value::as_str) {
                            if !t.is_empty() {
                                blocks.push(serde_json::json!({"type": "text", "text": t}));
                            }
                        }
                    }
                    Some("image_url") => {
                        if let Some(url) = p
                            .get("image_url")
                            .and_then(|u| u.get("url"))
                            .and_then(Value::as_str)
                        {
                            blocks.push(match parse_data_uri(url) {
                                Some((mime, data)) => serde_json::json!({
                                    "type": "image",
                                    "source": {"type": "base64", "media_type": mime, "data": data},
                                }),
                                None => serde_json::json!({
                                    "type": "image",
                                    "source": {"type": "url", "url": url},
                                }),
                            });
                        }
                    }
                    _ => {}
                }
            }
            Value::Array(blocks)
        }
        None => Value::String(msg.content.clone().unwrap_or_default()),
    }
}

/// Rebuild a Claude Code `tool_result` block's `content` value from a `Tool`
/// `ChatMessage` — the inverse of [`extract_tool_result_content`]'s parse
/// (PARITY-11). When `content_parts` is absent (or empty) this MUST reproduce
/// the historical plain-string `content` exactly (same IX-5-style constraint
/// `claude_user_content_value` follows) — only a `tool_result` that actually
/// carries a captured nested image gets the Anthropic content-array shape,
/// one `text` block (the existing `msg.content`, if any) plus one `image`
/// block per `image_url` part (mirrors `claude_user_content_value`'s
/// `data:` URI -> `source.base64` / other URL -> `source.url` mapping).
fn claude_tool_result_content_value(msg: &ChatMessage) -> Value {
    match &msg.content_parts {
        Some(parts) if !parts.is_empty() => {
            let mut blocks = Vec::new();
            if let Some(t) = &msg.content {
                if !t.is_empty() {
                    blocks.push(serde_json::json!({"type": "text", "text": t}));
                }
            }
            for p in parts {
                if p.get("type").and_then(Value::as_str) == Some("image_url") {
                    if let Some(url) = p
                        .get("image_url")
                        .and_then(|u| u.get("url"))
                        .and_then(Value::as_str)
                    {
                        blocks.push(match parse_data_uri(url) {
                            Some((mime, data)) => serde_json::json!({
                                "type": "image",
                                "source": {"type": "base64", "media_type": mime, "data": data},
                            }),
                            None => serde_json::json!({
                                "type": "image",
                                "source": {"type": "url", "url": url},
                            }),
                        });
                    }
                }
            }
            Value::Array(blocks)
        }
        _ => Value::String(msg.content.clone().unwrap_or_default()),
    }
}

/// Collect the Claude Code user-turn provenance fields that distinguish real
/// human input from system-injected turns and record replay-relevant state.
pub(crate) fn claude_user_provenance(v: &Value) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut take_str = |key: &str| {
        if let Some(s) = v.get(key).and_then(Value::as_str) {
            out.push((key.to_string(), s.to_string()));
        }
    };
    take_str("promptSource"); // typed | queued | system | sdk
    take_str("interruptedMessageId");
    take_str("sourceToolUseID");
    for flag in ["isMeta", "isCompactSummary", "isVisibleInTranscriptOnly"] {
        if v.get(flag).and_then(Value::as_bool) == Some(true) {
            out.push((flag.to_string(), "true".to_string()));
        }
    }
    if let Some(n) = v.get("queuePriority").and_then(Value::as_i64) {
        out.push(("queuePriority".to_string(), n.to_string()));
    }
    // `origin` is an object like {"kind":"task-notification"} — keep its kind.
    if let Some(kind) = v
        .get("origin")
        .and_then(|o| o.get("kind"))
        .and_then(Value::as_str)
    {
        out.push(("origin".to_string(), kind.to_string()));
    }
    out
}

/// Content-bearing Claude `system` events (`scheduled_task_fire`,
/// `local_command`, `away_summary`) carry real text that's part of the
/// interaction; fold them in as system context. Marker/metric subtypes
/// (`turn_duration`, `compact_boundary`, `api_error`, `stop_hook_summary`) carry
/// no conversational content and are skipped.
fn push_claude_system(v: &Value, out: &mut Vec<ChatMessage>) {
    let keep = matches!(
        v.get("subtype").and_then(Value::as_str),
        Some("scheduled_task_fire") | Some("local_command") | Some("away_summary")
    );
    if !keep {
        return;
    }
    if let Some(content) = v.get("content").and_then(Value::as_str) {
        if !content.trim().is_empty() {
            let subtype = v.get("subtype").and_then(Value::as_str).unwrap_or("system");
            out.push(ChatMessage::system(content.to_string()).with_meta("systemSubtype", subtype));
        }
    }
}

/// Fold content-bearing Claude Code `attachment` records into the conversation
/// as user-role messages. Most attachment subtypes (`task_reminder`,
/// `deferred_tools_delta`, `skill_listing`, `hook_*`, `command_permissions`, …)
/// are regenerable system injections and are skipped; only the four that carry
/// non-regenerable user/external content are kept.
fn push_claude_attachment(v: &Value, out: &mut Vec<ChatMessage>) {
    let att = match v.get("attachment") {
        Some(a) => a,
        None => return,
    };
    let kind = match att.get("type").and_then(Value::as_str) {
        Some(kind) => kind,
        None => return,
    };
    let text = match kind {
        // A queued prompt. `commandMode` says whose: `prompt` is the person's
        // own text, `task-notification` is the runtime reporting a finished
        // background task. Kept verbatim below.
        "queued_command" => att
            .get("prompt")
            .and_then(Value::as_str)
            .map(str::to_string),
        // A file the user attached: header + contents.
        "file" => attachment_with_path(att, "attached file", "filename", "content"),
        // A user-edited file snippet.
        "edited_text_file" => attachment_with_path(att, "edited file", "filename", "snippet"),
        // Injected project memory (CLAUDE.md), point-in-time.
        "nested_memory" => attachment_with_path(att, "project memory", "path", "content"),
        _ => None, // regenerable system injection — skip
    };
    let Some(text) = text else { return };
    if text.trim().is_empty() {
        return;
    }
    // An attachment record wears the user's ROLE, but the record itself says
    // who actually spoke — and that fact is lost the moment the attachment is
    // flattened to `[label: path]` text, so carry it as metadata the way
    // `push_claude_system` carries `systemSubtype`. Two fields, both verbatim:
    //
    //   `attachmentType`  the subtype. `file` / `edited_text_file` /
    //                     `nested_memory` are envelopes the runtime built
    //                     around a file body; a frontend that trusts the role
    //                     shows the reader a numbered source listing in a
    //                     chat bubble apparently sent by themselves.
    //   `commandMode`     present on `queued_command` only, and the whole
    //                     story for it. Measured over the local Claude Code
    //                     corpus (2,512 `queued_command` attachments): 926
    //                     `prompt`, every one of them plain human text, and
    //                     1,586 `task-notification`, every one of them a
    //                     `<task-notification>` frame — the same text Claude
    //                     Code also writes as a `type:"user"` record stamped
    //                     `origin.kind = "task-notification"`.
    //
    // Presentation policy (which of these a frontend hides) belongs to the
    // frontend — `isContextMessage` in `sdk/client/client.mjs`. The loader's
    // job is to stop discarding the producer's own answer.
    let mut message = ChatMessage::user(text).with_meta("attachmentType", kind);
    if let Some(mode) = att.get("commandMode").and_then(Value::as_str) {
        message = message.with_meta("commandMode", mode);
    }
    out.push(message);
}

/// Format an attachment as `[<label>: <path>]\n<body>`.
fn attachment_with_path(
    att: &Value,
    label: &str,
    path_key: &str,
    body_key: &str,
) -> Option<String> {
    let body = att.get(body_key).and_then(Value::as_str)?;
    let path = att
        .get(path_key)
        .or_else(|| att.get("displayPath"))
        .and_then(Value::as_str)
        .unwrap_or("");
    Some(format!("[{label}: {path}]\n{body}"))
}

fn push_str_field(buf: &mut String, s: &str) {
    if !buf.is_empty() {
        buf.push('\n');
    }
    buf.push_str(s);
}

/// N3: build a synthesized message for reasoning that could not attach to a
/// following assistant turn — either interrupted mid-stream by a
/// non-assistant item, or dangling at EOF (an aborted-turn shape). Drains
/// the three pending buffers (all empty/`false` afterward) so callers don't
/// separately have to remember to clear them.
fn orphaned_reasoning_message(
    reasoning: &mut String,
    reasoning_content: &mut String,
    encrypted: &mut bool,
) -> ChatMessage {
    let mut msg = ChatMessage::system("[reasoning] (turn ended without a reply)".to_string());
    if !reasoning.is_empty() {
        msg = msg.with_meta("reasoning", std::mem::take(reasoning));
    }
    if !reasoning_content.is_empty() {
        msg = msg.with_meta("reasoning_content", std::mem::take(reasoning_content));
    }
    if *encrypted {
        msg = msg.with_meta("reasoning_encrypted", "true");
        *encrypted = false;
    }
    msg
}

fn push_claude_assistant(v: &Value, out: &mut Vec<ChatMessage>) {
    let content = v.get("message").and_then(|m| m.get("content"));
    let mut text = String::new();
    let mut calls: Vec<ToolCall> = Vec::new();
    // Legacy singular fields — kept for backward compatibility with every
    // existing consumer of `metadata["thinking"]`/`["thinking_signature"]`/
    // `["redacted_thinking"]` (a concatenation of all thinking text, and the
    // LAST block's signature/data). D8 (Fable-5 review, confirmed): when a
    // message carries MULTIPLE `thinking` blocks, collapsing them down to
    // these singular fields silently drops every signature but the last
    // one's — a real Anthropic `thinking` block's `signature` cryptographically
    // covers ONLY that block's own text, so re-emitting block 1's text under
    // block 2's signature (or vice versa) produces a signature that will
    // never verify. `thinking_blocks` below is the fix: every block
    // preserved SEPARATELY, in order, each with its own (optional)
    // signature/data — the writer prefers it over the legacy fields
    // whenever present.
    let mut thinking = String::new();
    let mut signature: Option<String> = None;
    // PARITY-11: real Claude corpora also carry `redacted_thinking` and
    // `image` assistant blocks, and (rarely) a `fallback` model-routing
    // marker — none handled before, all silently vanishing (audit's own
    // census: 132,927 `thinking` / 67 `redacted_thinking` / 9 `image` / 4
    // `fallback` blocks in the reference corpus).
    //
    // D8: `redacted_thinking` is real data ONLY — never a fabricated
    // placeholder. The pre-fix code defaulted a missing `data` field to the
    // literal string `"<redacted>"`, which is indistinguishable from an
    // actual (if oddly-named) opaque payload on re-emit — a caller reading
    // it back has no way to tell "no data was ever captured" from "the
    // provider's own opaque blob happens to be the string `<redacted>`".
    // `redacted_thinking_seen` tracks block PRESENCE independently of
    // whether it had real data, so the reasoning-only-turn rescue below
    // still fires even when no block had a `data` field at all.
    let mut redacted_thinking: Option<String> = None;
    let mut redacted_thinking_seen = false;
    let mut images: Vec<Value> = Vec::new();
    // Real Anthropic `thinking` blocks very commonly carry an EMPTY
    // `thinking` string alongside a real `signature` (the summarized/
    // redacted-in-the-clear-but-replayable case) — `thinking.trim()` alone
    // would miss those, so track "a thinking block existed at all"
    // separately from whether it had visible text.
    let mut thinking_block_seen = false;
    // D8: every `thinking`/`redacted_thinking` block, preserved SEPARATELY
    // and IN ORDER — see the comment on `thinking`/`redacted_thinking`
    // above. Serialized as a single JSON-array metadata string
    // (`ChatMessage::metadata` is a flat string map) under
    // `"thinking_blocks"`.
    let mut thinking_blocks: Vec<Value> = Vec::new();
    // D5: mirrors `push_claude_user`'s tracking — an `image` block whose
    // source isn't base64/url (e.g. Files-API `{"type":"file",...}`) must
    // not silently vanish the whole record when nothing else survives.
    let mut saw_unconvertible_image = false;

    match content {
        Some(Value::String(s)) => push_text(&mut text, Some(&Value::String(s.clone()))),
        Some(Value::Array(blocks)) => {
            for b in blocks {
                match b.get("type").and_then(Value::as_str) {
                    Some("text") => push_text(&mut text, b.get("text")),
                    Some("tool_use") => {
                        let id = b.get("id").and_then(Value::as_str).unwrap_or_default();
                        let name = b.get("name").and_then(Value::as_str).unwrap_or_default();
                        let args = b
                            .get("input")
                            .map(|i| i.to_string())
                            .unwrap_or_else(|| "{}".to_string());
                        calls.push(function_call(id, name, args));
                    }
                    // Thinking is not replayed across providers, but retain it in
                    // (skip-serialized) metadata so a same-model continuation can
                    // re-inject it. See P3.
                    Some("thinking") => {
                        thinking_block_seen = true;
                        let t = b.get("thinking").and_then(Value::as_str).unwrap_or("");
                        if !t.is_empty() {
                            push_str_field(&mut thinking, t); // legacy concatenated field
                        }
                        let sig = b.get("signature").and_then(Value::as_str);
                        if let Some(s) = sig {
                            signature = Some(s.to_string()); // legacy last-wins field
                        }
                        // D8: this block's OWN text + signature, not folded
                        // into the running concatenation above.
                        let mut block = serde_json::json!({"type": "thinking", "thinking": t});
                        if let Some(s) = sig {
                            block["signature"] = Value::String(s.to_string());
                        }
                        thinking_blocks.push(block);
                    }
                    // Anthropic's redacted reasoning: an opaque, provider-private
                    // payload (flagged content the API declines to show in the
                    // clear). Like `thinking`, it's not replayable, but the raw
                    // `data` is retained in metadata rather than silently
                    // vanishing — a same-model continuation can still replay it
                    // verbatim even though supercode never renders it.
                    Some("redacted_thinking") => {
                        redacted_thinking_seen = true;
                        let data = b.get("data").and_then(Value::as_str);
                        // D8: no fabricated fallback — `data` is only ever
                        // the real captured payload, or genuinely absent.
                        if let Some(d) = data {
                            redacted_thinking = Some(d.to_string()); // legacy last-wins field
                        }
                        let mut block = serde_json::json!({"type": "redacted_thinking"});
                        if let Some(d) = data {
                            block["data"] = Value::String(d.to_string());
                        }
                        thinking_blocks.push(block);
                    }
                    // An assistant-emitted image block (e.g. a generated
                    // image) — collected exactly like `push_claude_user`'s
                    // user-turn image handling (`claude_image_block_to_part`
                    // is role-general), so it survives as `content_parts`
                    // instead of vanishing.
                    Some("image") => match claude_image_block_to_part(b) {
                        Some(part) => images.push(part),
                        None => saw_unconvertible_image = true,
                    },
                    // A provider-routing note (real shape:
                    // `{"type":"fallback","from":{"model":..},"to":{"model":..}}`
                    // — a mid-generation model swap, e.g. an overloaded model
                    // falling back to another). Carries no replayable
                    // conversational content, but folding it into `text` as a
                    // short bracketed marker — the same convention the Codex
                    // loader already uses for `[web_search]`/
                    // `[image_generation] ...` — keeps it visible instead of
                    // silently vanishing, including the case where it's the
                    // ONLY block in the turn (see the reasoning-only-turn fix
                    // below: before this, that shape dropped the entire
                    // message).
                    Some("fallback") => {
                        let from = b
                            .get("from")
                            .and_then(|f| f.get("model"))
                            .and_then(Value::as_str)
                            .unwrap_or("?");
                        let to = b
                            .get("to")
                            .and_then(|t| t.get("model"))
                            .and_then(Value::as_str)
                            .unwrap_or("?");
                        push_str_field(&mut text, &format!("[model fallback: {from} -> {to}]"));
                    }
                    _ => {}
                }
            }
        }
        _ => {}
    }

    // D5: nothing convertible landed in `text`/`images` but an image block
    // WAS present — fold in the same bracketed-marker convention `fallback`
    // uses above, so a genuinely image-only (unconvertible source) turn
    // doesn't vanish (mirrors `push_claude_user`'s identical fix).
    if images.is_empty() && text.trim().is_empty() && saw_unconvertible_image {
        push_str_field(&mut text, UNCONVERTIBLE_IMAGE_MARKER);
    }

    let before = out.len();
    if !images.is_empty() {
        let mut parts = Vec::new();
        if !text.trim().is_empty() {
            parts.push(serde_json::json!({"type": "text", "text": text.clone()}));
        }
        parts.extend(images);
        out.push(ChatMessage {
            role: Role::Assistant,
            content: None,
            content_parts: Some(parts),
            tool_calls: (!calls.is_empty()).then_some(calls),
            tool_call_id: None,
            name: None,
            metadata: Default::default(),
        });
    } else {
        push_assistant(out, text, calls);
        // A recognized native assistant record remains transcript state even
        // when its content array is empty (for example, an interrupted model
        // turn). Force a bare message whenever `push_assistant` had nothing
        // to emit. This includes the reasoning-only case and also preserves
        // genuinely part-less records instead of silently changing turn
        // count/order during translation.
        if out.len() == before {
            let mut empty = ChatMessage {
                role: Role::Assistant,
                content: None,
                content_parts: None,
                tool_calls: None,
                tool_call_id: None,
                name: None,
                metadata: Default::default(),
            };
            if !thinking_block_seen && !redacted_thinking_seen {
                empty
                    .metadata
                    .insert("empty_assistant_record".to_string(), "true".to_string());
            }
            out.push(empty);
        }
    }
    // Attach retained reasoning + attribution to the message we just produced.
    if out.len() > before {
        if let Some(msg) = out.last_mut() {
            // Insert "thinking" (even as an empty string) whenever a
            // `thinking` block was actually seen, not just when it had
            // visible text — a real `thinking` block commonly carries an
            // empty `thinking` string alongside a real `signature` (the
            // summarized-away-but-still-replayable case), and the writer
            // below keys its re-emission decision off this metadata key's
            // PRESENCE, not its content.
            if thinking_block_seen {
                msg.metadata.insert("thinking".to_string(), thinking);
            }
            if let Some(sig) = signature {
                msg.metadata.insert("thinking_signature".to_string(), sig);
            }
            if let Some(rt) = redacted_thinking {
                msg.metadata.insert("redacted_thinking".to_string(), rt);
            }
            // D8: exact per-block re-emission list — every `thinking`/
            // `redacted_thinking` block preserved separately, in order, each
            // with its own (optional) signature/data. The writer prefers
            // this over the legacy singular fields above whenever present,
            // so a multi-block message round-trips losslessly instead of
            // collapsing to one block under one (now-unverifiable)
            // signature.
            if !thinking_blocks.is_empty() {
                msg.metadata.insert(
                    "thinking_blocks".to_string(),
                    Value::Array(thinking_blocks).to_string(),
                );
            }
            // D5: honest signal that this message contained an image block
            // whose source this loader couldn't convert — the actual image
            // content is NOT captured, only a marker/partial record.
            if saw_unconvertible_image {
                msg.metadata
                    .insert("image_source_unconvertible".to_string(), "true".to_string());
            }
            // Attribution: which skill / subagent / MCP server+tool produced
            // this turn, plus the model `slug`.
            for key in [
                "attributionSkill",
                "attributionAgent",
                "attributionMcpServer",
                "attributionMcpTool",
                "slug",
            ] {
                if let Some(s) = v.get(key).and_then(Value::as_str) {
                    msg.metadata.insert(key.to_string(), s.to_string());
                }
            }
        }
    }
}

// ---- Codex ----------------------------------------------------------------

const SUPERCODE_CODEX_PROVENANCE_KEY: &str = "_supercode_codex_provenance";

fn codex_provenance_kind(record: &Value) -> Option<&str> {
    match record.get("type").and_then(Value::as_str) {
        Some("session_meta") => Some("session_meta"),
        Some("turn_context") => Some("turn_context"),
        Some("compacted") => Some("compacted"),
        Some("event_msg") => match record
            .get("payload")
            .and_then(|payload| payload.get("type"))
            .and_then(Value::as_str)
        {
            Some("thread_rolled_back") => Some("event_msg/thread_rolled_back"),
            Some("thread_goal_updated") => Some("event_msg/thread_goal_updated"),
            Some("entered_review_mode") => Some("event_msg/entered_review_mode"),
            Some("exited_review_mode") => Some("event_msg/exited_review_mode"),
            _ => None,
        },
        _ => None,
    }
}

fn capture_codex_provenance_record(
    meta: &mut SessionMeta,
    record_index: usize,
    raw_line: &str,
    record: &Value,
) {
    let Some(kind) = codex_provenance_kind(record) else {
        return;
    };
    meta.codex_provenance.push(serde_json::json!({
        "record_index": record_index,
        "kind": kind,
        "raw": raw_line,
    }));
}

fn codex_provenance_envelope(meta: &SessionMeta) -> Option<Value> {
    (!meta.codex_provenance.is_empty()).then(|| {
        serde_json::json!({
            "version": 1,
            "records": &meta.codex_provenance,
        })
    })
}

fn restore_codex_provenance(extension: &Value, meta: &mut SessionMeta) -> Result<bool> {
    if extension.get("version").and_then(Value::as_u64) != Some(1) {
        return Err(Error::InvalidSession(
            "invalid portable Codex provenance: expected version 1".to_string(),
        ));
    }
    let Some(records) = extension.get("records").and_then(Value::as_array) else {
        return Err(Error::InvalidSession(
            "invalid portable Codex provenance: `records` must be an array".to_string(),
        ));
    };
    if records.is_empty() {
        return Err(Error::InvalidSession(
            "invalid portable Codex provenance: `records` must not be empty".to_string(),
        ));
    }
    let mut restored = Vec::with_capacity(records.len());
    for entry in records {
        let Some(_record_index) = entry.get("record_index").and_then(Value::as_u64) else {
            return Err(Error::InvalidSession(
                "invalid portable Codex provenance: record_index must be an integer".to_string(),
            ));
        };
        let Some(kind) = entry.get("kind").and_then(Value::as_str) else {
            return Err(Error::InvalidSession(
                "invalid portable Codex provenance: kind must be a string".to_string(),
            ));
        };
        let Some(raw) = entry.get("raw").and_then(Value::as_str) else {
            return Err(Error::InvalidSession(
                "invalid portable Codex provenance: raw must be a string".to_string(),
            ));
        };
        let Ok(record) = serde_json::from_str::<Value>(raw) else {
            return Err(Error::InvalidSession(
                "invalid portable Codex provenance: raw is not valid JSON".to_string(),
            ));
        };
        if codex_provenance_kind(&record) != Some(kind) {
            return Err(Error::InvalidSession(format!(
                "invalid portable Codex provenance: kind `{kind}` does not match raw record"
            )));
        }
        restored.push(entry.clone());
    }
    meta.codex_provenance = restored;
    meta.codex_headers.clear();
    for entry in &meta.codex_provenance {
        let Some(raw) = entry.get("raw").and_then(Value::as_str) else {
            continue;
        };
        let Ok(record) = serde_json::from_str::<Value>(raw) else {
            continue;
        };
        if matches!(
            record.get("type").and_then(Value::as_str),
            Some("session_meta") | Some("turn_context")
        ) {
            meta.codex_headers.push(record);
        }
    }
    Ok(true)
}

fn restore_codex_provenance_from_top_level(record: &Value, meta: &mut SessionMeta) -> Result<bool> {
    match record.get(SUPERCODE_CODEX_PROVENANCE_KEY) {
        Some(extension) => restore_codex_provenance(extension, meta),
        None => Ok(false),
    }
}

fn inject_first_jsonl_top_level(out: &mut String, key: &str, extension: Value) {
    let Some(line_end) = out.find('\n') else {
        return;
    };
    let Ok(mut record) = serde_json::from_str::<Value>(&out[..line_end]) else {
        return;
    };
    let Some(object) = record.as_object_mut() else {
        return;
    };
    object.insert(key.to_string(), extension);
    out.replace_range(..line_end, &record.to_string());
}

fn inject_codex_provenance(out: &mut String, extension: Value) {
    let Some(line_end) = out.find('\n') else {
        return;
    };
    let Ok(mut record) = serde_json::from_str::<Value>(&out[..line_end]) else {
        return;
    };
    if record.get("type").and_then(Value::as_str) != Some("session_meta") {
        return;
    }
    let Some(payload) = record.get_mut("payload").and_then(Value::as_object_mut) else {
        return;
    };
    payload.insert(SUPERCODE_CODEX_PROVENANCE_KEY.to_string(), extension);
    out.replace_range(..line_end, &record.to_string());
}

/// Remove the last conversational turn from `messages`: everything from the
/// last `user` message to the end (the user prompt plus the assistant's
/// response and any tool calls/results it triggered).
fn remove_last_turn(messages: &mut Vec<ChatMessage>) {
    if let Some(idx) = messages.iter().rposition(|m| m.role == Role::User) {
        messages.truncate(idx);
    } else {
        messages.clear();
    }
    // IX-6 fix: the new tail exposed by `truncate` may still carry
    // `__codex_open_turn` from when it was marked (it was NOT the last
    // message at that time — items after it, now removed by the rollback,
    // intervened). A bare `function_call` arriving after the rollback is a
    // genuinely NEW turn and must get its own message, not merge into this
    // stale marked tail — close it out here so `push_codex_item`'s
    // adjacency check (`out.last()` + marker) can't be fooled by the
    // truncation re-exposing it.
    if let Some(last) = messages.last_mut() {
        last.metadata.remove("__codex_open_turn");
    }
}

fn truncate_messages(messages: &mut Vec<ChatMessage>, message_limit: usize) {
    truncate_messages_with_anchor(messages, message_limit, Vec::new());
}

fn truncate_messages_with_anchor(
    messages: &mut Vec<ChatMessage>,
    message_limit: usize,
    preceding_users: Vec<ChatMessage>,
) {
    let limit = message_limit.max(1);
    // Keep two recent human turn anchors. One anchor is insufficient once a
    // tool-heavy current turn grows beyond the numeric tail: the newest prompt
    // itself becomes that sole anchor, leaving a follower no overlap with the
    // transcript it already rendered. Two anchors preserve the previous turn
    // across a send and let overlap merging remain monotonic.
    let anchor_limit = limit.min(2);
    let mut anchor_indices = messages
        .iter()
        .enumerate()
        .rev()
        .filter_map(|(index, message)| (message.role == Role::User).then_some(index))
        .take(anchor_limit)
        .collect::<Vec<_>>();
    anchor_indices.reverse();
    let needed_preceding = anchor_limit.saturating_sub(anchor_indices.len());
    let mut preceding_anchors = preceding_users
        .into_iter()
        .rev()
        .take(needed_preceding)
        .collect::<Vec<_>>();
    preceding_anchors.reverse();
    if messages.len() + preceding_anchors.len() <= limit {
        preceding_anchors.append(messages);
        *messages = preceding_anchors;
        return;
    }
    if messages.len() <= limit && preceding_anchors.is_empty() {
        return;
    }
    let anchor_count = anchor_indices.len() + preceding_anchors.len();
    let target_index_count = limit.saturating_sub(preceding_anchors.len());
    let mut selected_indices = anchor_indices.clone();
    for index in (0..messages.len()).rev() {
        if selected_indices.len() >= target_index_count || anchor_indices.contains(&index) {
            continue;
        }
        selected_indices.push(index);
    }
    selected_indices.sort_unstable();
    let mut selected = Vec::with_capacity(limit);
    selected.append(&mut preceding_anchors);
    selected.extend(
        selected_indices
            .into_iter()
            .map(|index| messages[index].clone()),
    );
    debug_assert_eq!(selected.len(), limit.max(anchor_count));
    *messages = selected;
}

fn truncate_session_messages(session: &mut Session, message_limit: usize) {
    truncate_messages(&mut session.messages, message_limit);
}

/// The text of a Codex `agent_message` event. `message` is usually a string but
/// can be a structured object (e.g. review output) — fall back to its JSON.
fn agent_message_text(payload: &Value) -> String {
    match payload.get("message") {
        Some(Value::String(s)) => s.clone(),
        Some(other) => extract_text_content(Some(other)),
        None => String::new(),
    }
}

/// Trimmed texts of all assistant messages present as `response_item` — the
/// dedup set for recovering collab-only `agent_message` narration.
fn collect_codex_assistant_texts(jsonl: &str) -> std::collections::HashSet<String> {
    let mut set = std::collections::HashSet::new();
    for line in non_empty_lines(jsonl) {
        let Ok(v) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        if v.get("type").and_then(Value::as_str) != Some("response_item") {
            continue;
        }
        let payload = v.get("payload").unwrap_or(&Value::Null);
        if payload.get("type").and_then(Value::as_str) == Some("message")
            && payload.get("role").and_then(Value::as_str) == Some("assistant")
        {
            let text = extract_text_content(payload.get("content"));
            if !text.trim().is_empty() {
                set.insert(text.trim().to_string());
            }
        }
    }
    set
}

fn capture_codex_session_meta(payload: &Value, meta: &mut SessionMeta) {
    if meta.session_id.is_none() {
        if let Some(id) = payload.get("id").and_then(Value::as_str) {
            meta.session_id = Some(id.to_string());
        }
    }
    if meta.cwd.is_none() {
        if let Some(cwd) = payload.get("cwd").and_then(Value::as_str) {
            meta.cwd = Some(PathBuf::from(cwd));
        }
    }
    if meta.system_prompt.is_none() {
        // `base_instructions` may be a string or `{ "text": "..." }`.
        let bi = payload.get("base_instructions");
        let text = match bi {
            Some(Value::String(s)) => Some(s.clone()),
            Some(Value::Object(_)) => bi
                .and_then(|b| b.get("text"))
                .and_then(Value::as_str)
                .map(str::to_string),
            _ => None,
        };
        meta.system_prompt = text;
    }
    if meta.model.is_none() {
        if let Some(m) = payload.get("model").and_then(Value::as_str) {
            meta.model = Some(m.to_string());
        }
    }
    // Cross-file lineage keys for multi-agent / forked sessions.
    let mut put = |key: &str, v: Option<&Value>| {
        if let Some(s) = v.and_then(Value::as_str) {
            meta.lineage.insert(key.to_string(), s.to_string());
        }
    };
    put("parent_thread_id", payload.get("parent_thread_id"));
    put("forked_from_id", payload.get("forked_from_id"));
    put("thread_source", payload.get("thread_source"));
    // PARITY-10 dev/03: the other half of `write_synthesized_codex_header`'s
    // passthrough — restores a captured Claude `fork-context-ref` so a
    // Claude -> Codex -> Claude round trip reconstructs the original record
    // (`to_claude_code_jsonl` re-emits whatever lands in this lineage key).
    if !meta.lineage.contains_key("claude_fork_context_ref_raw") {
        if let Some(v) = payload.get("claude_fork_context_ref") {
            meta.lineage
                .insert("claude_fork_context_ref_raw".to_string(), v.to_string());
        }
    }
    if let Some(spawn) = payload
        .get("source")
        .and_then(|s| s.get("subagent"))
        .and_then(|s| s.get("thread_spawn"))
    {
        // parent_thread_id can also live here (preferred when both present).
        if let Some(p) = spawn.get("parent_thread_id").and_then(Value::as_str) {
            meta.lineage
                .insert("parent_thread_id".to_string(), p.to_string());
        }
        for k in ["agent_role", "agent_nickname"] {
            if let Some(s) = spawn.get(k).and_then(Value::as_str) {
                meta.lineage.insert(k.to_string(), s.to_string());
            }
        }
        if let Some(d) = spawn.get("depth").and_then(Value::as_i64) {
            meta.lineage.insert("depth".to_string(), d.to_string());
        }
    }
}

/// Depth of a node in the parent forest (root = 0), bounded against cycles.
fn depth_of(mut i: usize, parent_of: &[Option<usize>]) -> usize {
    let mut d = 0;
    let mut guard = 0;
    while let Some(p) = parent_of[i] {
        if p == i || guard > parent_of.len() {
            break;
        }
        i = p;
        d += 1;
        guard += 1;
    }
    d
}

/// Codex per-turn grouping id, stored under `payload.metadata.turn_id`.
fn codex_turn_id(payload: &Value) -> Option<&str> {
    payload
        .get("metadata")
        .and_then(|m| m.get("turn_id"))
        .and_then(Value::as_str)
}

/// N2 (spliced-export hardening): every Codex group id already present in
/// `raw_prefix` — the verbatim RAW lines [`Session::to_codex_jsonl_spliced`]
/// replays ahead of the appended tail it synthesizes via
/// `Session::write_codex_records`. This is the GROUND TRUTH of what
/// physically lands in the exported `out` string for the prefix: each line
/// is parsed as a Codex envelope and its own `payload.metadata.turn_id` (the
/// exact field `codex_turn_id` reads, whether it's a real native `turn_id`
/// or one of OUR OWN fabricated `sc-grp-N`/`<real>~dupN` ids from a prior
/// export) is extracted directly — no re-derivation from `self.messages`
/// needed (that would have to reconstruct which ids the ORIGINAL export
/// happened to assign, which this sidesteps entirely by reading them back
/// out of the bytes themselves). A line that fails to parse, isn't a
/// `response_item`, or carries no `turn_id` contributes nothing — headers
/// and non-message/call records (e.g. `session_meta`, `function_call_output`)
/// never carry this field to begin with.
fn collect_codex_group_ids_from_raw(raw_prefix: &[String]) -> HashSet<String> {
    let mut ids = HashSet::new();
    for line in raw_prefix {
        if let Ok(v) = serde_json::from_str::<Value>(line) {
            if let Some(payload) = v.get("payload") {
                if let Some(tid) = codex_turn_id(payload) {
                    ids.insert(tid.to_string());
                }
            }
        }
    }
    ids
}

/// Stamp every `ChatMessage` appended to `messages` since index `from` with
/// `ts` (a Codex record's own top-level `timestamp`, ISO-8601) as the
/// canonical `metadata["timestamp"]` (WAVE-2 item 1) — the same
/// `entry(...).or_insert_with` discipline the pi/Claude loaders use, so a
/// message that already carries a more specific timestamp of its own is
/// never overwritten (none currently do on the Codex side, but this keeps
/// every loader consistent). A no-op when `ts` is `None` (a line with no
/// `timestamp` field) or `from >= messages.len()` (nothing new was pushed).
fn stamp_new_codex_messages(messages: &mut [ChatMessage], from: usize, ts: Option<&str>) {
    let Some(ts) = ts else { return };
    let Some(slice) = messages.get_mut(from..) else {
        return;
    };
    for m in slice {
        m.metadata
            .entry("timestamp".to_string())
            .or_insert_with(|| ts.to_string());
    }
}

fn push_codex_item(payload: &Value, out: &mut Vec<ChatMessage>) {
    match payload.get("type").and_then(Value::as_str) {
        Some("message") => {
            let role = match payload.get("role").and_then(Value::as_str) {
                Some("user") => Role::User,
                Some("assistant") => Role::Assistant,
                // "developer" and "system" both carry operator instructions.
                _ => Role::System,
            };
            let content = payload.get("content");
            let text = extract_text_content(content);
            // IX-5: `input_image` blocks alongside/instead of text — see
            // `codex_extract_images`. A text-only message (no image blocks)
            // takes the historical `content: Some(text)` shape unchanged.
            let images = codex_extract_images(content);
            let is_empty_assistant =
                role == Role::Assistant && text.trim().is_empty() && images.is_empty();
            if !text.trim().is_empty() || !images.is_empty() || is_empty_assistant {
                let content_parts = if images.is_empty() {
                    None
                } else {
                    let mut parts = Vec::new();
                    if !text.trim().is_empty() {
                        parts.push(serde_json::json!({"type": "text", "text": text.clone()}));
                    }
                    parts.extend(images);
                    Some(parts)
                };
                let mut msg = ChatMessage {
                    role,
                    content: if content_parts.is_some() || text.is_empty() {
                        None
                    } else {
                        Some(text)
                    },
                    content_parts,
                    tool_calls: None,
                    tool_call_id: None,
                    name: None,
                    metadata: Default::default(),
                };
                // Preserve the assistant `phase` (commentary vs final_answer) so
                // a reloaded transcript can distinguish narration from the answer.
                if role == Role::Assistant {
                    if let Some(phase) = payload.get("phase").and_then(Value::as_str) {
                        msg.metadata.insert("phase".to_string(), phase.to_string());
                    }
                    // IX-6: mark this as an open, mergeable combined-turn
                    // candidate — a `function_call` response_item found
                    // immediately after (still `out.last()` when reached,
                    // i.e. no other item intervened) merges into this SAME
                    // `ChatMessage` instead of splitting into a second one,
                    // matching how Claude's parser keeps a text+tool_use
                    // turn together. Stripped again before the loaded
                    // `Session` is returned (`from_codex_str`), so it never
                    // leaks as visible metadata.
                    msg.metadata
                        .insert("__codex_open_turn".to_string(), "true".to_string());
                }
                // The per-turn grouping key (Codex batches items by turn_id).
                if let Some(tid) = codex_turn_id(payload) {
                    msg.metadata.insert("turn_id".to_string(), tid.to_string());
                }
                // PARITY-6 dev/02: restore the original Claude
                // `systemSubtype` for a `developer`/`system` message that
                // was itself synthesized FROM a real Claude system record
                // (`write_codex_records`'s `Role::System` arm stamps
                // `claude_system_subtype`) — the exact inverse, so
                // `write_claude_code_records`'s `Role::System` arm can
                // re-materialize the real Claude `type: "system"` record
                // faithfully on a Codex -> Claude Code hop instead of
                // guessing a fallback subtype.
                if role == Role::System {
                    if let Some(subtype) = payload
                        .get("metadata")
                        .and_then(|m| m.get("claude_system_subtype"))
                        .and_then(Value::as_str)
                    {
                        msg.metadata
                            .insert("systemSubtype".to_string(), subtype.to_string());
                    }
                }
                if is_empty_assistant {
                    msg.metadata
                        .insert("empty_assistant_record".to_string(), "true".to_string());
                }
                out.push(msg);
            }
        }
        Some("function_call") => {
            let id = payload
                .get("call_id")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let raw_name = payload
                .get("name")
                .and_then(Value::as_str)
                .unwrap_or_default();
            // Preserve the MCP `namespace` by qualifying the tool name
            // (`<namespace>__<name>`, matching the mcp__server__tool convention),
            // so the tool identity isn't ambiguous on round-trip.
            let qualified;
            let name = match payload.get("namespace").and_then(Value::as_str) {
                Some(ns) if !ns.is_empty() && !raw_name.starts_with(ns) => {
                    qualified = format!("{ns}__{raw_name}");
                    qualified.as_str()
                }
                _ => raw_name,
            };
            let args = payload
                .get("arguments")
                .map(value_to_arg_string)
                .unwrap_or_else(|| "{}".to_string());
            let call = function_call(id, name, args);
            // IX-6: a `function_call` immediately after an assistant `message`
            // in the SAME turn (still `out.last()`, marked `__codex_open_turn`
            // by the "message" arm above, and not yet closed by anything else)
            // merges into that ONE `ChatMessage` — text→`content`,
            // call→`tool_calls` — instead of splitting into a second message.
            // A bare `function_call` with no such preceding turn (the marker
            // absent, or `out.last()` not an assistant message) is unaffected:
            // it still gets its own synthesized message, exactly as before.
            //
            // Belt-and-suspenders (PARITY-6/7 tightened): if this
            // `function_call` response_item itself carries a `turn_id` (rare
            // in observed real-native-Codex corpora — Codex usually only
            // stamps it on `message` payloads — but ALWAYS present on OUR
            // OWN synthesized export whenever a `ChatMessage`'s own tool
            // calls need merge disambiguation, see `write_codex_records`),
            // it must match the marked assistant message's recorded
            // `turn_id` EXACTLY — including "the marked message has none at
            // all" counting as a mismatch. That's exactly the shape of two
            // genuinely separate, adjacent `ChatMessage`s (an unrelated
            // text-only turn immediately followed by a different,
            // tool-call-only turn): the tool-only turn's own `function_call`s
            // carry a synthetic id while the unrelated preceding text
            // message carries none, so this correctly refuses the merge
            // instead of falling through to a permissive default. Only when
            // this `function_call` carries NO `turn_id` at all (the ordinary
            // real-native-Codex shape) does this fall back to the original
            // permissive "adjacency + open marker is enough" rule —
            // unchanged from before for the vast majority of real Codex
            // data. The truncation/clear strip above is what actually closes
            // the marker across rollback/compaction boundaries; this is only
            // an extra guard for the case where a stale-but-unstripped
            // marker and a turn_id mismatch coincide.
            let can_merge = out.last().is_some_and(|last| {
                last.role == Role::Assistant
                    && last.metadata.contains_key("__codex_open_turn")
                    && match codex_turn_id(payload) {
                        Some(fc_tid) => {
                            last.metadata.get("turn_id").map(String::as_str) == Some(fc_tid)
                        }
                        None => true,
                    }
            });
            if can_merge {
                out.last_mut()
                    .expect("can_merge implies out.last() is Some")
                    .tool_calls
                    .get_or_insert_with(Vec::new)
                    .push(call);
            } else {
                push_assistant(out, String::new(), vec![call]);
                // PARITY-6/7: a BARE tool-call turn (no preceding `message`
                // in this turn, so nothing set `__codex_open_turn` above) can
                // still be the FIRST of several tool calls that all belong to
                // the SAME original `ChatMessage` (`write_codex_records`
                // stamps every one of a message's own tool calls with the
                // identical synthetic `turn_id`). Re-open THIS freshly
                // created message — but ONLY when a real `turn_id` is
                // present — so the NEXT `function_call` in the same group
                // merges into it instead of becoming its own message too.
                // Gated on `codex_turn_id(payload).is_some()` (not the bare
                // default `true` the belt-and-suspenders check above uses)
                // so real native Codex data — which almost never carries
                // this field on `function_call` payloads (see the comment
                // above) — keeps its existing "every bare tool call is its
                // own turn" behavior exactly as before.
                if let Some(tid) = codex_turn_id(payload) {
                    if let Some(last) = out.last_mut() {
                        last.metadata
                            .insert("__codex_open_turn".to_string(), "true".to_string());
                        last.metadata.insert("turn_id".to_string(), tid.to_string());
                    }
                }
            }
        }
        Some("function_call_output") => {
            let id = payload
                .get("call_id")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let result = match payload.get("output") {
                Some(Value::String(s)) => s.clone(),
                Some(v) => extract_text_content(Some(v)),
                None => String::new(),
            };
            let mut message = tool_message(id, result);
            // TR-13: Codex v1 exposes no structured success/error field on
            // this record. Free-text output is not a safe classifier, so the
            // reduction engine must treat the outcome as explicitly unknown
            // and fail closed on both success-only and error-only pruning.
            crate::mark_tool_outcome_unknown(&mut message);
            out.push(message);
        }
        // Custom / MCP tool calls are shaped like function calls but carry their
        // arguments under `input` (a JSON-encoded string). Normalize them the
        // same way so MCP-using sessions don't lose those turns.
        Some("custom_tool_call") => {
            let id = payload
                .get("call_id")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let name = payload
                .get("name")
                .and_then(Value::as_str)
                .unwrap_or_default();
            // Unlike `function_call.arguments`, Codex custom tools accept a
            // free-form `input` string (apply_patch is the common case).
            // Canonical `FunctionCall::arguments` must remain valid JSON, so
            // retain the input's JSON type instead of treating a free-form
            // string as if it were already a JSON document. This lets every
            // target harness carry the value rather than silently replacing
            // it with `{}` when `parsed_arguments()` fails.
            let args = payload
                .get("input")
                .map(Value::to_string)
                .unwrap_or_else(|| "{}".to_string());
            push_assistant(out, String::new(), vec![function_call(id, name, args)]);
            if let Some(message) = out.last_mut() {
                message.metadata.insert(
                    "codex_custom_tool_call_ids".to_string(),
                    serde_json::json!([id]).to_string(),
                );
            }
        }
        Some("custom_tool_call_output") => {
            let id = payload
                .get("call_id")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let result = match payload.get("output") {
                Some(Value::String(s)) => s.clone(),
                Some(v) => extract_text_content(Some(v)),
                None => String::new(),
            };
            let mut message = tool_message(id, result);
            crate::mark_tool_outcome_unknown(&mut message);
            out.push(message);
        }
        // Tool-search is a clean call/output pair keyed by call_id.
        //
        // D1: this arm used to ALWAYS start a brand-new `ChatMessage`,
        // ignoring the `turn_id` merge stamps `write_codex_records` puts on
        // its own synthesized `tool_search_call` records (see the PARITY-6/7
        // comment there and on `codex_turn_id`/the `function_call` arm
        // above). That left the same bug-class the turn_id work fixed for
        // `function_call` half-done here: a single Claude assistant message
        // containing text + a `tool_search` block reloaded as 2 messages
        // (1 -> 2 inflation), and a message with 2 `tool_search` blocks
        // reloaded as 3. Mirror the `function_call` arm's merge check
        // exactly so a `tool_search_call` immediately following an open
        // assistant turn (or another tool call sharing the same `turn_id`)
        // merges into that SAME `ChatMessage` instead of splitting.
        Some("tool_search_call") => {
            let id = payload
                .get("call_id")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let args = payload
                .get("arguments")
                .map(value_to_arg_string)
                .unwrap_or_else(|| "{}".to_string());
            let call = function_call(id, "tool_search", args);
            let can_merge = out.last().is_some_and(|last| {
                last.role == Role::Assistant
                    && last.metadata.contains_key("__codex_open_turn")
                    && match codex_turn_id(payload) {
                        Some(fc_tid) => {
                            last.metadata.get("turn_id").map(String::as_str) == Some(fc_tid)
                        }
                        None => true,
                    }
            });
            if can_merge {
                out.last_mut()
                    .expect("can_merge implies out.last() is Some")
                    .tool_calls
                    .get_or_insert_with(Vec::new)
                    .push(call);
            } else {
                push_assistant(out, String::new(), vec![call]);
                // Re-open the freshly created message so a FOLLOWING
                // `function_call`/`tool_search_call` sharing this same
                // `turn_id` merges into it too — matching the bare
                // `function_call` case's own re-open logic above.
                if let Some(tid) = codex_turn_id(payload) {
                    if let Some(last) = out.last_mut() {
                        last.metadata
                            .insert("__codex_open_turn".to_string(), "true".to_string());
                        last.metadata.insert("turn_id".to_string(), tid.to_string());
                    }
                }
            }
        }
        Some("tool_search_output") => {
            let id = payload
                .get("call_id")
                .and_then(Value::as_str)
                .unwrap_or_default();
            let result = payload
                .get("tools")
                .map(value_to_arg_string)
                .unwrap_or_default();
            out.push(tool_message(id, result));
        }
        // Web-search / image-generation response_items carry no paired output
        // here (results live in event_msg), so emit an assistant marker rather
        // than a dangling unanswered tool call.
        Some("web_search_call") => {
            push_assistant(out, "[web_search]".to_string(), Vec::new());
        }
        Some("image_generation_call") => {
            let prompt = payload
                .get("revised_prompt")
                .and_then(Value::as_str)
                .unwrap_or("");
            push_assistant(
                out,
                format!("[image_generation] {prompt}").trim().to_string(),
                Vec::new(),
            );
        }
        // "reasoning" and anything else — dropped.
        _ => {}
    }
}

// ---- Grok -------------------------------------------------------------

const SUPERCODE_GEMINI_MESSAGE_KEY: &str = "_supercode_gemini_message";

fn set_gemini_message_extension(value: &mut Value, message: &ChatMessage) {
    value[SUPERCODE_GEMINI_MESSAGE_KEY] = serde_json::json!({
        "schema": 1,
        "role": message.role,
        "content": message.content,
        "content_parts": message.content_parts,
        "tool_calls": message.tool_calls,
        "tool_call_id": message.tool_call_id,
        "name": message.name,
        "metadata": message.metadata,
    });
}

fn restore_gemini_message_extension(value: &Value, message: &mut ChatMessage) {
    let Some(extension) = value.get(SUPERCODE_GEMINI_MESSAGE_KEY) else {
        return;
    };
    if extension.get("schema").and_then(Value::as_u64) != Some(1) {
        return;
    }
    if let Some(role) = extension
        .get("role")
        .and_then(|value| serde_json::from_value(value.clone()).ok())
    {
        message.role = role;
    }
    message.content = extension
        .get("content")
        .and_then(Value::as_str)
        .map(str::to_string);
    message.content_parts = extension
        .get("content_parts")
        .and_then(|value| serde_json::from_value(value.clone()).ok());
    message.tool_calls = extension
        .get("tool_calls")
        .and_then(|value| serde_json::from_value(value.clone()).ok());
    message.tool_call_id = extension
        .get("tool_call_id")
        .and_then(Value::as_str)
        .map(str::to_string);
    message.name = extension
        .get("name")
        .and_then(Value::as_str)
        .map(str::to_string);
    message.metadata.clear();
    if let Some(metadata) = extension.get("metadata").and_then(Value::as_object) {
        for (key, value) in metadata {
            if let Some(value) = value.as_str() {
                message.metadata.insert(key.clone(), value.to_string());
            }
        }
    }
}

fn capture_grok_scalar_metadata(value: &Value, message: &mut ChatMessage, keys: &[&str]) {
    for key in keys {
        if let Some(value) = value.get(*key) {
            message.metadata.insert(
                format!("grok_{key}"),
                value
                    .as_str()
                    .map(str::to_string)
                    .unwrap_or_else(|| value.to_string()),
            );
        }
    }
}

fn grok_human_user_text(raw: &str) -> Option<String> {
    let text = raw.trim();
    if text.is_empty() || text.starts_with("<user_info>") || text.starts_with("<system-reminder>") {
        return None;
    }
    let unwrapped = text
        .strip_prefix("<user_query>")
        .and_then(|value| value.strip_suffix("</user_query>"))
        .map(str::trim)
        .unwrap_or(text);
    (!unwrapped.is_empty()).then(|| unwrapped.to_string())
}

/// Portable extension for messages whose canonical fields cannot be expressed
/// by the target's stock schema. It was introduced for Grok and retains that
/// on-disk key for compatibility. Gemini has the same need: Claude Code and
/// Codex have no native slot for a tool-result name or Gemini-only metadata.
/// Their readers tolerate unknown namespaced fields, so forwarding this
/// adapter-owned envelope keeps those cross-format hops reversible without
/// pretending the stock schemas represent the fields directly.
const SUPERCODE_GROK_MESSAGE_KEY: &str = "_supercode_grok_message";

/// Namespaced line-level extension carrying the one tool-result outcome state
/// Claude cannot represent natively. Keeping this narrower than the full Grok
/// portability envelope avoids changing unrelated target-message projection.
const SUPERCODE_TOOL_OUTCOME_KEY: &str = "_supercode_tool_outcome";

fn restore_tool_outcome_extension(value: &Value, message: &mut ChatMessage) {
    if !crate::is_tool_error(message)
        && value
            .get(SUPERCODE_TOOL_OUTCOME_KEY)
            .and_then(Value::as_str)
            == Some("unknown")
    {
        crate::mark_tool_outcome_unknown(message);
    }
}

fn grok_message_extension(source: SessionSource, message: &ChatMessage) -> Option<Value> {
    let metadata = message
        .metadata
        .iter()
        .filter(|(key, _)| {
            key.starts_with("gemini_") || key.starts_with("grok_") || key.starts_with("goose_")
        })
        .map(|(key, value)| (key.clone(), Value::String(value.clone())))
        .collect::<serde_json::Map<_, _>>();

    // `meta.source` changes after every reload. Keying portability only on
    // the immediate source therefore made Grok metadata survive one hop but
    // disappear on A -> B -> C translations. Once Grok-owned fields are
    // present, keep forwarding them regardless of the current container.
    let has_portable_fields =
        !metadata.is_empty() || message.metadata.contains_key("codex_custom_tool_call_ids");
    (matches!(
        source,
        SessionSource::Gemini | SessionSource::Grok | SessionSource::Goose
    ) || has_portable_fields
        || message.content_parts.is_some())
    .then(|| {
        serde_json::json!({
            "schema": 2,
            "role": message.role,
            "content": message.content,
            "content_parts": message.content_parts,
            "tool_calls": message.tool_calls,
            "tool_call_id": message.tool_call_id,
            "name": message.name,
            "metadata": message.metadata,
        })
    })
}

fn set_grok_target_message_extension(value: &mut Value, message: &ChatMessage) {
    value[SUPERCODE_GROK_MESSAGE_KEY] = serde_json::json!({
        "schema": 2,
        "role": message.role,
        "content": message.content,
        "content_parts": message.content_parts,
        "tool_calls": message.tool_calls,
        "tool_call_id": message.tool_call_id,
        "name": message.name,
        "metadata": message.metadata,
    });
}

fn set_grok_message_extension(value: &mut Value, source: SessionSource, message: &ChatMessage) {
    if let Some(extension) = grok_message_extension(source, message) {
        value[SUPERCODE_GROK_MESSAGE_KEY] = extension;
    }
}

fn restore_grok_message_extension(value: &Value, message: &mut ChatMessage) {
    let Some(extension) = value.get(SUPERCODE_GROK_MESSAGE_KEY) else {
        return;
    };
    // Codex temporarily marks a text assistant item so immediately-following
    // function-call items can merge back into the same canonical turn. The
    // portable envelope must not erase that loader-private marker before the
    // merge happens; `from_codex_str` removes it before returning.
    let codex_open_turn = message.metadata.get("__codex_open_turn").cloned();
    let codex_turn_id = message.metadata.get("turn_id").cloned();
    let extension_has_turn_id = extension
        .get("metadata")
        .and_then(Value::as_object)
        .is_some_and(|metadata| metadata.contains_key("turn_id"));
    if extension.get("schema").and_then(Value::as_u64) == Some(2) {
        if let Some(role) = extension
            .get("role")
            .and_then(|value| serde_json::from_value(value.clone()).ok())
        {
            message.role = role;
        }
        message.content = extension
            .get("content")
            .and_then(Value::as_str)
            .map(str::to_string);
        message.content_parts = extension
            .get("content_parts")
            .and_then(|value| serde_json::from_value(value.clone()).ok());
        // Tool calls are shared native structure in every supported format.
        // Keep the loader's reconstruction instead of restoring this copy:
        // Codex stores a combined text+tool turn across multiple records, so
        // eagerly restoring calls on its text record would duplicate them
        // when the following function-call records merge.
        message.tool_call_id = extension
            .get("tool_call_id")
            .and_then(Value::as_str)
            .map(str::to_string);
        message.name = extension
            .get("name")
            .and_then(Value::as_str)
            .map(str::to_string);
        message.metadata.clear();
    }
    if let Some(metadata) = extension.get("metadata").and_then(Value::as_object) {
        for (key, value) in metadata {
            if let Some(value) = value.as_str() {
                message.metadata.insert(key.clone(), value.to_string());
            }
        }
    }
    if let Some(name) = extension.get("name").and_then(Value::as_str) {
        message.name = Some(name.to_string());
    }
    if let Some(marker) = codex_open_turn {
        message
            .metadata
            .insert("__codex_open_turn".to_string(), marker);
    }
    if let Some(turn_id) = codex_turn_id {
        message.metadata.insert("turn_id".to_string(), turn_id);
        if !extension_has_turn_id {
            message.metadata.insert(
                "__grok_remove_synthetic_turn_id".to_string(),
                "true".to_string(),
            );
        }
    }
}

fn restore_single_grok_message(value: &Value, messages: &mut [ChatMessage]) {
    if let [message] = messages {
        restore_grok_message_extension(value, message);
    }
}

fn normalize_goose_message(native: &Value, native_index: usize, out: &mut Vec<ChatMessage>) {
    let role = match native.get("role").and_then(Value::as_str) {
        Some("assistant") => Role::Assistant,
        _ => Role::User,
    };
    let created = native.get("created").and_then(Value::as_i64);
    let native_id = native.get("id").and_then(Value::as_str);
    let mut text = Vec::new();
    let mut content_parts = Vec::new();
    let mut tool_calls = Vec::new();
    let mut tool_results = Vec::new();

    for (block_index, block) in native
        .get("content")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .enumerate()
    {
        match block.get("type").and_then(Value::as_str) {
            Some("text") => {
                if let Some(value) = block.get("text").and_then(Value::as_str) {
                    text.push(value.to_string());
                    content_parts.push(serde_json::json!({"type": "text", "text": value}));
                }
            }
            Some("image") => {
                let data = block
                    .get("data")
                    .and_then(Value::as_str)
                    .unwrap_or_default();
                let media_type = block
                    .get("mimeType")
                    .or_else(|| block.get("mime_type"))
                    .and_then(Value::as_str)
                    .unwrap_or("application/octet-stream");
                content_parts.push(serde_json::json!({
                    "type": "image_url",
                    "image_url": {"url": format!("data:{media_type};base64,{data}")},
                }));
            }
            Some("toolRequest" | "frontendToolRequest") => {
                let id = block
                    .get("id")
                    .and_then(Value::as_str)
                    .map(str::to_string)
                    .unwrap_or_else(|| format!("goose-{native_index}-{block_index}"));
                let call = block
                    .get("toolCall")
                    .and_then(|call| {
                        (call.get("status").and_then(Value::as_str) == Some("success"))
                            .then(|| call.get("value"))
                            .flatten()
                    })
                    .or_else(|| block.get("toolCall"));
                let Some(call) = call else { continue };
                let name = call.get("name").and_then(Value::as_str).unwrap_or("tool");
                let arguments = call
                    .get("arguments")
                    .map(value_to_arg_string)
                    .unwrap_or_else(|| "{}".to_string());
                tool_calls.push(function_call(&id, name, arguments));
            }
            Some("toolResponse") => tool_results.push(block.clone()),
            _ => {}
        }
    }

    if !text.is_empty() || !content_parts.is_empty() || !tool_calls.is_empty() {
        let has_non_text = content_parts
            .iter()
            .any(|part| part.get("type").and_then(Value::as_str) != Some("text"));
        let mut message = ChatMessage {
            role,
            content: (!text.is_empty()).then(|| text.join("\n")),
            content_parts: has_non_text.then_some(content_parts),
            tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
            tool_call_id: None,
            name: None,
            metadata: Default::default(),
        };
        capture_goose_message_metadata(native, created, native_id, &mut message);
        out.push(message);
    }

    for (result_index, block) in tool_results.into_iter().enumerate() {
        let id = block
            .get("id")
            .and_then(Value::as_str)
            .map(str::to_string)
            .unwrap_or_else(|| format!("goose-{native_index}-result-{result_index}"));
        let result = block.get("toolResult").unwrap_or(&Value::Null);
        let status_error = result.get("status").and_then(Value::as_str) == Some("error");
        let value = result.get("value").unwrap_or(result);
        let is_error = status_error || value.get("isError").and_then(Value::as_bool) == Some(true);
        let output = if status_error {
            result
                .get("error")
                .and_then(Value::as_str)
                .unwrap_or("Goose tool call failed")
                .to_string()
        } else {
            value
                .get("content")
                .and_then(Value::as_array)
                .map(|content| {
                    content
                        .iter()
                        .filter_map(|part| {
                            part.get("text")
                                .and_then(Value::as_str)
                                .map(str::to_string)
                                .or_else(|| Some(part.to_string()))
                        })
                        .collect::<Vec<_>>()
                        .join("\n")
                })
                .unwrap_or_else(|| value.to_string())
        };
        let mut message = tool_message(&id, output);
        if is_error {
            crate::mark_tool_error(&mut message);
        }
        capture_goose_message_metadata(native, created, native_id, &mut message);
        out.push(message);
    }
}

fn capture_goose_message_metadata(
    native: &Value,
    created: Option<i64>,
    native_id: Option<&str>,
    message: &mut ChatMessage,
) {
    if let Some(created) = created {
        message
            .metadata
            .insert("goose_created".to_string(), created.to_string());
    }
    if let Some(native_id) = native_id {
        message
            .metadata
            .insert("goose_message_id".to_string(), native_id.to_string());
    }
    if let Some(metadata) = native.get("metadata") {
        message
            .metadata
            .insert("goose_metadata".to_string(), metadata.to_string());
    }
}

#[doc(hidden)]
pub fn percent_decode_path(encoded: &str) -> Option<String> {
    fn hex(byte: u8) -> Option<u8> {
        match byte {
            b'0'..=b'9' => Some(byte - b'0'),
            b'a'..=b'f' => Some(byte - b'a' + 10),
            b'A'..=b'F' => Some(byte - b'A' + 10),
            _ => None,
        }
    }

    let bytes = encoded.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut index = 0usize;
    while index < bytes.len() {
        if bytes[index] == b'%' {
            let high = *bytes.get(index + 1)?;
            let low = *bytes.get(index + 2)?;
            decoded.push(hex(high)? * 16 + hex(low)?);
            index += 3;
        } else {
            decoded.push(bytes[index]);
            index += 1;
        }
    }
    String::from_utf8(decoded).ok()
}

// ---- Pi ---------------------------------------------------------------

fn capture_pi_header(v: &Value, meta: &mut SessionMeta) -> Result<()> {
    restore_codex_provenance_from_top_level(v, meta)?;
    if let Some(id) = v.get("id").and_then(Value::as_str) {
        meta.session_id = Some(id.to_string());
    }
    if let Some(cwd) = v.get("cwd").and_then(Value::as_str) {
        meta.cwd = Some(PathBuf::from(cwd));
    }
    // Absent `version` means a pre-v3 file (`pi-fields.md` §1: "absent = v1").
    let version = v
        .get("version")
        .and_then(Value::as_u64)
        .map(|n| n.to_string())
        .unwrap_or_else(|| "1".to_string());
    meta.lineage.insert("pi_version".to_string(), version);
    if let Some(ts) = v.get("timestamp").and_then(Value::as_str) {
        meta.lineage
            .insert("created_at".to_string(), ts.to_string());
    }
    if let Some(ps) = v.get("parentSession").and_then(Value::as_str) {
        meta.lineage
            .insert("parent_session_path".to_string(), ps.to_string());
    }
    // D7: the other half of `push_pi_header`'s passthrough — restores a
    // captured Claude `fork-context-ref` so a Claude -> Pi -> Claude round
    // trip reconstructs the original record (mirrors
    // `capture_codex_session_meta`'s identical `claude_fork_context_ref`
    // restore for the Codex hop).
    if !meta.lineage.contains_key("claude_fork_context_ref_raw") {
        if let Some(v) = v.get("claude_fork_context_ref") {
            meta.lineage
                .insert("claude_fork_context_ref_raw".to_string(), v.to_string());
        }
    }
    Ok(())
}

/// Validate one `ImageContent` block's `{mimeType, data}` shape and return
/// `(mime, data)` when it looks like a real image payload.
///
/// **This shape is UNVERIFIED against real pi output**: `pi-fields.md` cites
/// `ai:316-350` for the `ImageContent` content-block union but does not
/// enumerate `ImageContent`'s own fields (only `TextContent`/`ThinkingContent`/
/// `ToolCall` are itemized there) — `{mimeType, data}` (mirroring the OpenAI/
/// Anthropic multimodal wire shape) is this loader's best guess, not a
/// frozen-spec fact. A follow-up TR tracks confirming/correcting this shape
/// against a real pi corpus. Until then this function VALIDATES rather than
/// assumes: both fields must be present, non-empty strings, and `data` must
/// look like base64 (only the base64 alphabet, incl. `=` padding) — anything
/// else is an unknown/unexpected image shape, and the caller must route the
/// whole message to raw-only survival (S6-style fail loud) instead of
/// silently synthesizing a corrupt/empty `image_url` part.
fn pi_image_shape(item: &Value) -> Option<(String, String)> {
    let mime = item.get("mimeType").and_then(Value::as_str)?;
    let data = item.get("data").and_then(Value::as_str)?;
    if mime.is_empty() || data.is_empty() {
        return None;
    }
    if !data
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'='))
    {
        return None;
    }
    Some((mime.to_string(), data.to_string()))
}

/// True if `content` (a pi content value: bare string or
/// `(TextContent|ImageContent)[]`) contains at least one `type:"image"` block
/// that does not match [`pi_image_shape`] — shared by the loader (which
/// routes such a message to raw-only survival, never a synthesized-empty
/// part) and the coverage audit (`audit::Corpus::Pi`), which scores it as
/// `message/UnknownImageShape` instead of silently `Normalized`, so the shape
/// mismatch surfaces as a coverage FAILURE rather than vanishing.
#[doc(hidden)]
pub fn pi_content_has_unknown_image_shape(content: Option<&Value>) -> bool {
    let Some(Value::Array(items)) = content else {
        return false;
    };
    items.iter().any(|item| {
        item.get("type").and_then(Value::as_str) == Some("image") && pi_image_shape(item).is_none()
    })
}

/// Split a pi `(TextContent|ImageContent)[]` (or bare string) content value
/// into concatenated text plus, when a WELL-FORMED image block is present,
/// the full `content_parts` array (leading text block + one `image_url` part
/// per image, its `data:` URI carrying the exact `mimeType`/`data` bytes pi
/// stored) — shared by `user`/`toolResult`/`custom*` content, which all use
/// the identical union (`pi-fields.md` §3a/§3c/§3e).
///
/// Returns `(text, parts, unknown_image_shape)`. When an image block does NOT
/// match [`pi_image_shape`] (missing/empty `data`/`mimeType`, or a `data`
/// value that isn't recognizable base64), this NEVER synthesizes an empty/
/// corrupt `image_url` part — it reports `unknown_image_shape = true` and
/// every caller must treat that as raw-only survival for the whole message
/// (mirroring the unknown-`message.role` rule, S6), so a shape this loader
/// guessed wrong fails loud instead of silently dropping/corrupting the
/// image.
fn pi_content_to_text_and_parts(content: Option<&Value>) -> (String, Option<Vec<Value>>, bool) {
    match content {
        Some(Value::String(s)) => (s.clone(), None, false),
        Some(Value::Array(items)) => {
            let mut text = String::new();
            let mut parts: Vec<Value> = Vec::new();
            let mut has_image = false;
            let mut unknown_image_shape = false;
            for item in items {
                match item.get("type").and_then(Value::as_str) {
                    Some("text") => {
                        if let Some(t) = item.get("text").and_then(Value::as_str) {
                            push_str_field(&mut text, t);
                        }
                    }
                    Some("image") => {
                        has_image = true;
                        match pi_image_shape(item) {
                            Some((mime, data)) => {
                                parts.push(serde_json::json!({
                                    "type": "image_url",
                                    "image_url": {"url": format!("data:{mime};base64,{data}")},
                                }));
                            }
                            None => unknown_image_shape = true,
                        }
                    }
                    _ => {}
                }
            }
            if unknown_image_shape {
                // Never synthesize an empty/corrupt part for a shape we
                // don't recognize — raw-only survival for the whole message;
                // the coverage guard is what turns this into a visible
                // failure (S6-style).
                return (String::new(), None, true);
            }
            if has_image {
                if !text.trim().is_empty() {
                    parts.insert(0, serde_json::json!({"type": "text", "text": text.clone()}));
                }
                (text, Some(parts), false)
            } else {
                (text, None, false)
            }
        }
        _ => (String::new(), None, false),
    }
}

fn push_pi_user(msg_v: &Value, out: &mut Vec<ChatMessage>) {
    let (text, parts, unknown_image_shape) = pi_content_to_text_and_parts(msg_v.get("content"));
    // Unrecognized image shape (S6-style fail loud, FIX #2): raw-only
    // survival, never a synthesized-empty part. `audit::Corpus::Pi`'s
    // `message/UnknownImageShape` bucket is what turns this into a visible
    // coverage failure.
    if unknown_image_shape {
        return;
    }
    if text.trim().is_empty() && parts.is_none() {
        return;
    }
    let mut msg = match parts {
        Some(parts) => ChatMessage {
            role: Role::User,
            content: None,
            content_parts: Some(parts),
            tool_calls: None,
            tool_call_id: None,
            name: None,
            metadata: Default::default(),
        },
        None => ChatMessage::user(text),
    };
    // WAVE-2 fidelity fix: pi's message-level unix-ms clock
    // (`message.timestamp`) is a DISTINCT field from the canonical
    // entry-level ISO `metadata["timestamp"]` WAVE-2 item 1 wires — the two
    // carry genuinely different values in real corpora (the fixture's are
    // ~6 months apart). Preserve it separately so it isn't silently lost for
    // every pi session; see `msg_pi_native_timestamp_ms` (the pi writer's
    // native round-trip consumer) and the INHERENT residue note on
    // `pi_dropped_keys_cross` in `interop_fidelity_matrix.rs`.
    if let Some(ts) = msg_v.get("timestamp").and_then(Value::as_u64) {
        msg.metadata
            .insert("pi_msg_timestamp".to_string(), ts.to_string());
    }
    out.push(msg);
}

fn push_pi_assistant(msg_v: &Value, out: &mut Vec<ChatMessage>) {
    let mut text = String::new();
    let mut calls: Vec<ToolCall> = Vec::new();
    let mut thinking = String::new();
    let mut thinking_seen = false;
    let mut thinking_sig: Option<String> = None;
    let mut thinking_redacted = false;
    let mut text_sig: Option<String> = None;
    let mut thought_sig: Option<String> = None;

    if let Some(Value::Array(blocks)) = msg_v.get("content") {
        for b in blocks {
            match b.get("type").and_then(Value::as_str) {
                Some("text") => {
                    if let Some(t) = b.get("text").and_then(Value::as_str) {
                        push_str_field(&mut text, t);
                    }
                    if let Some(sig) = b.get("textSignature") {
                        text_sig = Some(match sig {
                            Value::String(s) => s.clone(),
                            other => other.to_string(),
                        });
                    }
                }
                Some("thinking") => {
                    thinking_seen = true;
                    if let Some(t) = b.get("thinking").and_then(Value::as_str) {
                        push_str_field(&mut thinking, t);
                    }
                    if let Some(sig) = b.get("thinkingSignature").and_then(Value::as_str) {
                        thinking_sig = Some(sig.to_string());
                    }
                    if b.get("redacted").and_then(Value::as_bool) == Some(true) {
                        thinking_redacted = true;
                    }
                }
                Some("toolCall") => {
                    let id = b.get("id").and_then(Value::as_str).unwrap_or_default();
                    let name = b.get("name").and_then(Value::as_str).unwrap_or_default();
                    // `arguments` is a JSON OBJECT on pi's wire, not a string
                    // (`pi-fields.md` §3b open question 4) — serialize to the
                    // string `FunctionCall::arguments` expects.
                    let args = b
                        .get("arguments")
                        .cloned()
                        .unwrap_or_else(|| Value::Object(Default::default()));
                    calls.push(function_call(id, name, args.to_string()));
                    if let Some(sig) = b.get("thoughtSignature").and_then(Value::as_str) {
                        thought_sig = Some(sig.to_string());
                    }
                }
                _ => {}
            }
        }
    }

    let before = out.len();
    push_assistant(out, text, calls);
    // A recognized native assistant entry remains transcript state even
    // when its content array is empty, except Pi's explicit empty error
    // response: that record has no replayable content and is established
    // raw-only residue (`pi_real_corpus_error_retry`). Preserve empty
    // non-error turns and Pi's standalone thinking-block shape.
    let is_empty_error =
        !thinking_seen && msg_v.get("stopReason").and_then(Value::as_str) == Some("error");
    if out.len() == before && !is_empty_error {
        let mut empty = ChatMessage {
            role: Role::Assistant,
            content: None,
            content_parts: None,
            tool_calls: None,
            tool_call_id: None,
            name: None,
            metadata: Default::default(),
        };
        if !thinking_seen {
            empty
                .metadata
                .insert("empty_assistant_record".to_string(), "true".to_string());
        }
        out.push(empty);
    }
    if out.len() > before {
        let msg = out.last_mut().expect("just pushed");
        if thinking_seen {
            msg.metadata.insert("thinking".to_string(), thinking);
        }
        if let Some(s) = thinking_sig {
            msg.metadata.insert("thinking_signature".to_string(), s);
        }
        if thinking_redacted {
            msg.metadata
                .insert("pi_thinking_redacted".to_string(), "true".to_string());
        }
        if let Some(s) = text_sig {
            msg.metadata.insert("pi_text_signature".to_string(), s);
        }
        if let Some(s) = thought_sig {
            msg.metadata.insert("pi_thought_signature".to_string(), s);
        }
        for (key, field) in [
            ("pi_api", "api"),
            ("pi_provider", "provider"),
            ("pi_response_model", "responseModel"),
            ("pi_response_id", "responseId"),
            ("pi_stop_reason", "stopReason"),
            ("pi_error_message", "errorMessage"),
        ] {
            if let Some(s) = msg_v.get(field).and_then(Value::as_str) {
                msg.metadata.insert(key.to_string(), s.to_string());
            }
        }
        if let Some(diag) = msg_v.get("diagnostics") {
            if !diag.is_null() {
                msg.metadata
                    .insert("pi_diagnostics".to_string(), diag.to_string());
            }
        }
        if let Some(usage) = msg_v.get("usage") {
            if !usage.is_null() {
                msg.metadata
                    .insert("pi_usage".to_string(), usage.to_string());
            }
        }
        // WAVE-2 fidelity fix: preserve pi's message-level unix-ms clock
        // separately from the canonical entry-level ISO `timestamp` — see
        // `push_pi_user`.
        if let Some(ts) = msg_v.get("timestamp").and_then(Value::as_u64) {
            msg.metadata
                .insert("pi_msg_timestamp".to_string(), ts.to_string());
        }
    }
}

fn push_pi_tool_result(msg_v: &Value, out: &mut Vec<ChatMessage>) {
    let id = msg_v
        .get("toolCallId")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let name = msg_v
        .get("toolName")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let (text, parts, unknown_image_shape) = pi_content_to_text_and_parts(msg_v.get("content"));
    // Unrecognized image shape (S6-style fail loud, FIX #2): raw-only
    // survival, never a synthesized-empty part. Dropping the toolResult
    // message here leaves its `toolCallId` unanswered, which
    // `ensure_tool_results_paired` already turns into a visible
    // "[no tool result recorded — turn interrupted]" placeholder — a loud
    // failure mode, not a silent one.
    if unknown_image_shape {
        return;
    }
    let mut msg = ChatMessage {
        role: Role::Tool,
        content: Some(text),
        content_parts: parts,
        tool_calls: None,
        tool_call_id: Some(id.to_string()),
        name: Some(name.to_string()),
        metadata: Default::default(),
    };
    if let Some(details) = msg_v.get("details") {
        if !details.is_null() {
            msg.metadata
                .insert("pi_tool_details".to_string(), details.to_string());
        }
    }
    let is_error = msg_v
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    msg.metadata
        .insert("pi_is_error".to_string(), is_error.to_string());
    if is_error {
        crate::mark_tool_error(&mut msg);
    }
    // WAVE-2 fidelity fix: preserve pi's message-level unix-ms clock
    // separately from the canonical entry-level ISO `timestamp` — see
    // `push_pi_user`.
    if let Some(ts) = msg_v.get("timestamp").and_then(Value::as_u64) {
        msg.metadata
            .insert("pi_msg_timestamp".to_string(), ts.to_string());
    }
    out.push(msg);
}

/// Render a pi `bashExecution` message (`!`/`!!` shell escape) to the text
/// pi itself sends the model, mirroring `bashExecutionToText`
/// (`pi-fields.md` §3d, `msg:82-98`). The exact upstream string constants
/// aren't reproduced in the frozen research doc (only cited by file:line),
/// so this is a faithful, clearly-labeled reconstruction — every structured
/// field is additionally preserved verbatim in `metadata`/`raw` regardless.
fn push_pi_bash(msg_v: &Value, out: &mut Vec<ChatMessage>) {
    let command = msg_v.get("command").and_then(Value::as_str).unwrap_or("");
    let output = msg_v.get("output").and_then(Value::as_str).unwrap_or("");
    let exit_code = msg_v.get("exitCode").and_then(Value::as_i64);
    let cancelled = msg_v
        .get("cancelled")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let truncated = msg_v
        .get("truncated")
        .and_then(Value::as_bool)
        .unwrap_or(false);

    let mut text = format!("$ {command}\n{output}");
    if let Some(code) = exit_code {
        if code != 0 {
            text.push_str(&format!("\n[exit code: {code}]"));
        }
    }
    if cancelled {
        text.push_str("\n[cancelled]");
    }
    if truncated {
        text.push_str("\n[truncated]");
    }

    let mut msg = ChatMessage::user(text);
    msg.metadata
        .insert("pi_bash_command".to_string(), command.to_string());
    msg.metadata
        .insert("pi_bash_output".to_string(), output.to_string());
    if let Some(code) = exit_code {
        msg.metadata
            .insert("pi_bash_exit_code".to_string(), code.to_string());
    }
    msg.metadata
        .insert("pi_bash_cancelled".to_string(), cancelled.to_string());
    msg.metadata
        .insert("pi_bash_truncated".to_string(), truncated.to_string());
    if let Some(p) = msg_v.get("fullOutputPath").and_then(Value::as_str) {
        msg.metadata
            .insert("pi_bash_full_output_path".to_string(), p.to_string());
    }
    // `!!` — hidden from the model context; honored by `is_replay_excluded`
    // on every writer, not just pi's own (§2.2).
    if msg_v.get("excludeFromContext").and_then(Value::as_bool) == Some(true) {
        msg.metadata
            .insert("pi_exclude_from_context".to_string(), "true".to_string());
    }
    // WAVE-2 fidelity fix: preserve pi's message-level unix-ms clock
    // separately from the canonical entry-level ISO `timestamp` — see
    // `push_pi_user`.
    if let Some(ts) = msg_v.get("timestamp").and_then(Value::as_u64) {
        msg.metadata
            .insert("pi_msg_timestamp".to_string(), ts.to_string());
    }
    out.push(msg);
}

/// B4: the `customType` marker `write_pi_entries`'s `Role::System` arm
/// stamps on a re-materialized content-bearing Claude `system` record (see
/// that arm's doc comment). Namespaced (`supercode_`-prefixed) so it can
/// never collide with a real pi `CustomMessage.customType` — pi's own
/// hook-injected custom types are hook/extension names (e.g. `hookMessage`
/// migration targets), never this literal string.
const PI_CLAUDE_SYSTEM_CUSTOM_TYPE: &str = "supercode_claude_system";

/// Shared mapping for pi's `role:"custom"` message (§3e) and top-level
/// `custom_message` entries (§9) — both enter context as a `User` message
/// with the same `customType`/`display`/`details` residue.
///
/// B4 exception: when `customType` is [`PI_CLAUDE_SYSTEM_CUSTOM_TYPE`] (our
/// own marker — see `write_pi_entries`'s `Role::System` arm), this is
/// actually a re-materialized content-bearing Claude `system` record round-
/// tripping through pi, not a genuine pi extension message — restore
/// `Role::System` + `metadata["systemSubtype"]` (from `details.
/// claude_system_subtype`, falling back to `local_command` — still one of
/// `push_claude_system`'s own keep subtypes — exactly like
/// `write_codex_records`'s Codex-leg fallback) instead of the generic
/// `Role::User` path below, so a Claude -> Pi -> Claude round trip restores
/// the exact original role, not just the text.
fn push_pi_custom_common(v: &Value, out: &mut Vec<ChatMessage>) {
    if v.get("customType").and_then(Value::as_str) == Some(PI_CLAUDE_SYSTEM_CUSTOM_TYPE) {
        let content = v.get("content").and_then(Value::as_str).unwrap_or("");
        if content.trim().is_empty() {
            return;
        }
        let subtype = v
            .get("details")
            .and_then(|d| d.get("claude_system_subtype"))
            .and_then(Value::as_str)
            .unwrap_or("local_command");
        out.push(ChatMessage::system(content.to_string()).with_meta("systemSubtype", subtype));
        return;
    }
    let (text, parts, unknown_image_shape) = pi_content_to_text_and_parts(v.get("content"));
    // Unrecognized image shape (S6-style fail loud, FIX #2): raw-only
    // survival, never a synthesized-empty part.
    if unknown_image_shape {
        return;
    }
    if text.trim().is_empty() && parts.is_none() {
        return;
    }
    let mut msg = match parts {
        Some(parts) => ChatMessage {
            role: Role::User,
            content: None,
            content_parts: Some(parts),
            tool_calls: None,
            tool_call_id: None,
            name: None,
            metadata: Default::default(),
        },
        None => ChatMessage::user(text),
    };
    if let Some(ct) = v.get("customType").and_then(Value::as_str) {
        msg.metadata
            .insert("pi_custom_type".to_string(), ct.to_string());
    }
    if let Some(d) = v.get("display").and_then(Value::as_bool) {
        msg.metadata.insert("pi_display".to_string(), d.to_string());
    }
    if let Some(details) = v.get("details") {
        if !details.is_null() {
            msg.metadata
                .insert("pi_details".to_string(), details.to_string());
        }
    }
    // WAVE-2 fidelity fix: preserve pi's message-level unix-ms clock
    // separately from the canonical entry-level ISO `timestamp` — see
    // `push_pi_user`. `v` here is the `message` object for the `role:
    // "custom"` case; for the top-level `custom_message` case `v` is the
    // entry itself, whose `timestamp` is the entry-level ISO string (not a
    // u64), so this is a no-op there — matching pre-WAVE-2 behavior.
    if let Some(ts) = v.get("timestamp").and_then(Value::as_u64) {
        msg.metadata
            .insert("pi_msg_timestamp".to_string(), ts.to_string());
    }
    out.push(msg);
}

/// pi's own prefix-wrapped user text for a `compaction` entry summary
/// (§2.1: "compaction/branch summaries (pi's own prefix-wrapped user text)").
/// The exact upstream wrapper string is cited (`msg:11-17`) but not
/// reproduced in the frozen research doc; this is a clearly-labeled
/// reconstruction, not pi's literal bytes — see build-report ambiguity note.
fn push_pi_compaction(entry_v: &Value, out: &mut Vec<ChatMessage>) {
    let summary = entry_v.get("summary").and_then(Value::as_str).unwrap_or("");
    if summary.trim().is_empty() {
        return;
    }
    let mut msg = ChatMessage::user(format!("[compaction summary]\n{summary}"));
    msg.metadata
        .insert("pi_type".to_string(), "compaction".to_string());
    if let Some(fk) = entry_v.get("firstKeptEntryId").and_then(Value::as_str) {
        msg.metadata
            .insert("pi_first_kept_entry_id".to_string(), fk.to_string());
    }
    if let Some(tb) = entry_v.get("tokensBefore").and_then(Value::as_u64) {
        msg.metadata
            .insert("pi_tokens_before".to_string(), tb.to_string());
    }
    if let Some(d) = entry_v.get("details") {
        if !d.is_null() {
            msg.metadata.insert("pi_details".to_string(), d.to_string());
        }
    }
    if entry_v.get("fromHook").and_then(Value::as_bool) == Some(true) {
        msg.metadata
            .insert("pi_from_hook".to_string(), "true".to_string());
    }
    out.push(msg);
}

/// pi's own prefix-wrapped user text for a `branch_summary` entry (a
/// rewind-with-summary) — same reconstruction caveat as
/// [`push_pi_compaction`].
fn push_pi_branch_summary(entry_v: &Value, out: &mut Vec<ChatMessage>) {
    let summary = entry_v.get("summary").and_then(Value::as_str).unwrap_or("");
    if summary.trim().is_empty() {
        return;
    }
    let mut msg = ChatMessage::user(format!("[branch summary]\n{summary}"));
    msg.metadata
        .insert("pi_type".to_string(), "branch_summary".to_string());
    if let Some(f) = entry_v.get("fromId").and_then(Value::as_str) {
        msg.metadata.insert("pi_from_id".to_string(), f.to_string());
    }
    if let Some(d) = entry_v.get("details") {
        if !d.is_null() {
            msg.metadata.insert("pi_details".to_string(), d.to_string());
        }
    }
    if entry_v.get("fromHook").and_then(Value::as_bool) == Some(true) {
        msg.metadata
            .insert("pi_from_hook".to_string(), "true".to_string());
    }
    out.push(msg);
}

// ---- OpenCode ---------------------------------------------------------

/// The placeholder opencode's own replay substitutes for a `tool` part's
/// output once `state.completed.time.compacted` is set
/// (`message-v2.ts:293-296 @fd9ee43`) — the REAL output is never actually
/// erased from the record (S1); it survives in `raw` and in this loader's
/// `metadata["oc_tool_output_compacted"]`.
pub const OPENCODE_COMPACTED_TOOL_PLACEHOLDER: &str = "[Old tool result content cleared]";

fn capture_opencode_session_info(si: &Value, meta: &mut SessionMeta) -> Result<()> {
    restore_codex_provenance_from_top_level(si, meta)?;
    if let Some(id) = si.get("id").and_then(Value::as_str) {
        meta.session_id = Some(id.to_string());
    }
    if let Some(dir) = si.get("directory").and_then(Value::as_str) {
        meta.cwd = Some(PathBuf::from(dir));
    }
    if let Some(agent) = si.get("agent").and_then(Value::as_str) {
        meta.agent_id = Some(agent.to_string());
    }
    if let Some(model) = si.get("model") {
        let provider = model.get("providerID").and_then(Value::as_str);
        let id = model.get("id").and_then(Value::as_str);
        if let (Some(p), Some(i)) = (provider, id) {
            meta.model = Some(format!("{p}/{i}"));
        }
    }
    if let Some(project_id) = si.get("projectID").and_then(Value::as_str) {
        meta.lineage
            .insert("projectID".to_string(), project_id.to_string());
    }
    if let Some(slug) = si.get("slug").and_then(Value::as_str) {
        meta.lineage.insert("slug".to_string(), slug.to_string());
    }
    if let Some(ws) = si.get("workspaceID").and_then(Value::as_str) {
        meta.lineage
            .insert("workspaceID".to_string(), ws.to_string());
    }
    if let Some(parent) = si.get("parentID").and_then(Value::as_str) {
        meta.lineage
            .insert("parent_session_id".to_string(), parent.to_string());
        // Mirrored under the Codex-originated lineage key so the existing
        // generic `Session::reconstruct_tree` nests opencode subagent
        // sessions too, with no format-specific nesting pass (§2.1: "child
        // session's parentID ... → drives reconstruct_tree").
        meta.lineage
            .insert("parent_thread_id".to_string(), parent.to_string());
    }
    // D7: the other half of `synthesized_opencode_info`'s passthrough —
    // restores a captured Claude `fork-context-ref` so a Claude -> OpenCode
    // -> Claude round trip reconstructs the original record (mirrors
    // `capture_codex_session_meta`/`capture_pi_header`'s identical
    // `claude_fork_context_ref` restore for the Codex/Pi hops).
    if !meta.lineage.contains_key("claude_fork_context_ref_raw") {
        if let Some(v) = si.get("claude_fork_context_ref") {
            meta.lineage
                .insert("claude_fork_context_ref_raw".to_string(), v.to_string());
        }
    }
    Ok(())
}

/// An opencode `User`/`Assistant` `file` part's image data-URI →
/// `content_parts` `image_url` entry (§2.1). Only `data:` URIs with an
/// `image/*` mime are mapped ("T3 clean for images; non-media residue") —
/// a bare filesystem path, an `https:` link, or a non-image mime is left as
/// raw-only residue (§2.3), never a corrupt/guessed `image_url`. `pub(crate)`
/// so [`crate::audit::audit_opencode_line`] can classify a `file` part's
/// coverage with the SAME test this loader uses to canonicalize it (D5) —
/// one definition of "is this file part actually replayed", not two.
#[doc(hidden)]
pub fn opencode_file_image_part(part: &Value) -> Option<Value> {
    let mime = part.get("mime").and_then(Value::as_str)?;
    let url = part.get("url").and_then(Value::as_str)?;
    if !mime.starts_with("image/") || !url.starts_with("data:") {
        return None;
    }
    Some(serde_json::json!({"type": "image_url", "image_url": {"url": url}}))
}

/// B4: the part-`metadata` key `append_synthesized_opencode_messages`'s
/// `Role::System` arm stamps on the one `synthetic: true` text part of a
/// re-materialized content-bearing Claude `system` record (see that arm's
/// doc comment). Namespaced (`supercode_`-prefixed) so it can never collide
/// with real opencode/provider part metadata (e.g. `anthropic.signature`).
const OPENCODE_CLAUDE_SYSTEM_SUBTYPE_KEY: &str = "supercode_claude_system_subtype";

/// Detect `append_synthesized_opencode_messages`'s own marker shape: a
/// `User` message with EXACTLY one `synthetic: true` text part carrying
/// [`OPENCODE_CLAUDE_SYSTEM_SUBTYPE_KEY`] in its part-level `metadata`. Real
/// opencode data is never misclassified — a genuine opencode `synthetic`
/// text part never carries this supercode-namespaced key, and a real
/// multi-part user message (text + an attached file, say) never matches
/// (`parts.len() != 1` bails). Returns the original Claude `systemSubtype`
/// (e.g. `local_command`) on a match.
fn opencode_claude_system_subtype(parts: &[Value]) -> Option<String> {
    let [part] = parts else { return None };
    if part.get("type").and_then(Value::as_str) != Some("text") {
        return None;
    }
    if part.get("synthetic").and_then(Value::as_bool) != Some(true) {
        return None;
    }
    part.get("metadata")
        .and_then(|m| m.get(OPENCODE_CLAUDE_SYSTEM_SUBTYPE_KEY))
        .and_then(Value::as_str)
        .map(str::to_string)
}

/// The [`opencode_claude_system_subtype`] match arm: restores `Role::System`
/// and `metadata["systemSubtype"]` from the marked text part instead of
/// `push_opencode_user`'s generic `Role::User` path, so a Claude ->
/// OpenCode -> Claude round trip restores the exact original role, not just
/// the text. Content is never fabricated — only emitted when non-empty.
fn push_opencode_claude_system(
    msg_value: &Value,
    parts: &[Value],
    subtype: String,
    out: &mut Vec<ChatMessage>,
) {
    let Some(text) = parts
        .first()
        .and_then(|p| p.get("text"))
        .and_then(Value::as_str)
    else {
        return;
    };
    if text.trim().is_empty() {
        return;
    }
    let mut msg = ChatMessage::system(text.to_string()).with_meta("systemSubtype", subtype);
    set_opencode_msg_timestamp(&mut msg, msg_value);
    out.push(msg);
}

/// Map an opencode `User` message (`msg_value`) + its parts to zero or one
/// canonical `Role::User` `ChatMessage` (§2.1). `text` parts concatenate
/// (an `ignored` one is never included — §2.2, "must not be re-emitted to
/// the model"); `file` parts with a recognized image shape become
/// `content_parts`. `System` (opencode's per-turn `User.system`) fills
/// `SessionMeta.system_prompt` on the first turn that carries it, and
/// `metadata["system"]` on every turn that does (§2.1: "System prompt is
/// per-user-message, not per-session").
/// Fold an opencode message envelope's `time.created` (unix-ms) into the
/// canonical `metadata["timestamp"]` (ISO-8601, WAVE-2 item 1) — the same
/// field claude/codex/pi loaders populate. Lossless to millisecond precision
/// (opencode's own wire granularity); a `None`/malformed `time.created`
/// leaves `metadata["timestamp"]` unset, so the writer falls back to
/// `SYNTH_TS`/`SYNTH_TS_MS`.
fn set_opencode_msg_timestamp(msg: &mut ChatMessage, msg_value: &Value) {
    if let Some(ms) = msg_value
        .get("time")
        .and_then(|t| t.get("created"))
        .and_then(Value::as_i64)
    {
        msg.metadata
            .insert("timestamp".to_string(), crate::sidecar::ms_to_rfc3339(ms));
    }
}

fn push_opencode_user(
    msg_value: &Value,
    parts: &[Value],
    out: &mut Vec<ChatMessage>,
    meta: &mut SessionMeta,
    first_system_seen: &mut bool,
) {
    let mut text = String::new();
    let mut image_parts: Vec<Value> = Vec::new();
    let mut has_ignored = false;
    for p in parts {
        match p.get("type").and_then(Value::as_str) {
            Some("text") => {
                if p.get("ignored").and_then(Value::as_bool) == Some(true) {
                    has_ignored = true;
                    continue; // must never be replayed (§2.2)
                }
                if let Some(t) = p.get("text").and_then(Value::as_str) {
                    push_str_field(&mut text, t);
                }
            }
            Some("file") => {
                if let Some(img) = opencode_file_image_part(p) {
                    image_parts.push(img);
                }
            }
            // reasoning/tool never appear on a User message; step-start,
            // step-finish, snapshot, patch, agent, subtask, retry have no
            // clean home (§2.3); compaction is read separately by the
            // caller (tail_start_id) and tagged onto the message below.
            _ => {}
        }
    }

    let has_images = !image_parts.is_empty();
    if text.trim().is_empty() && !has_images {
        return;
    }
    let mut msg = if has_images {
        let mut all = Vec::new();
        if !text.trim().is_empty() {
            all.push(serde_json::json!({"type": "text", "text": text.clone()}));
        }
        all.extend(image_parts);
        ChatMessage {
            role: Role::User,
            content: None,
            content_parts: Some(all),
            tool_calls: None,
            tool_call_id: None,
            name: None,
            metadata: Default::default(),
        }
    } else {
        ChatMessage::user(text)
    };

    if has_ignored {
        msg.metadata
            .insert("oc_has_ignored_part".to_string(), "true".to_string());
    }
    if let Some(id) = msg_value.get("id").and_then(Value::as_str) {
        msg.metadata
            .insert("oc_message_id".to_string(), id.to_string());
    }
    if let Some(agent) = msg_value.get("agent").and_then(Value::as_str) {
        msg.metadata.insert("agent".to_string(), agent.to_string());
    }
    if let Some(model) = msg_value.get("model") {
        if !model.is_null() {
            msg.metadata.insert("model".to_string(), model.to_string());
        }
    }
    if let Some(system) = msg_value.get("system").and_then(Value::as_str) {
        if !*first_system_seen {
            meta.system_prompt = Some(system.to_string());
            *first_system_seen = true;
        }
        msg.metadata
            .insert("system".to_string(), system.to_string());
    }
    for p in parts {
        if p.get("type").and_then(Value::as_str) == Some("compaction") {
            msg.metadata
                .insert("phase".to_string(), "compaction".to_string());
            if let Some(t) = p.get("tail_start_id").and_then(Value::as_str) {
                msg.metadata
                    .insert("tail_start_id".to_string(), t.to_string());
            }
        }
    }
    set_opencode_msg_timestamp(&mut msg, msg_value);
    restore_grok_message_extension(msg_value, &mut msg);
    out.push(msg);
}

/// Map an opencode `Assistant` message + its parts to a canonical
/// `Role::Assistant` `ChatMessage` (text + `tool_calls`), followed
/// immediately by one `Role::Tool` `ChatMessage` per `tool` part that
/// reached `completed`/`error` — the split-by-`callID` opencode's single
/// part→two-messages mapping (§2.1). `pending`/`running` calls (an
/// interrupted turn) synthesize no tool call/result of their own here; the
/// shared [`ensure_tool_results_paired`] fills that gap uniformly, exactly
/// like the other three loaders. A `tool` part whose `state.status` is none
/// of the four known values is skipped entirely — raw-only survival, never
/// guessed — so [`crate::audit::Corpus::OpenCode`] can flag it.
fn push_opencode_assistant(
    msg_value: &Value,
    parts: &[Value],
    out: &mut Vec<ChatMessage>,
    meta: &mut SessionMeta,
) {
    let mut text = String::new();
    let mut calls: Vec<ToolCall> = Vec::new();
    let mut thinking = String::new();
    let mut reasoning_seen = false;
    let mut thinking_sig: Option<String> = None;
    // (call_id, tool_name, the tool part itself) — deferred so the
    // assistant message (carrying `tool_calls`) is pushed FIRST, matching
    // every other loader's message ordering (call, then result).
    let mut tool_results: Vec<(String, String, Value)> = Vec::new();

    for p in parts {
        match p.get("type").and_then(Value::as_str) {
            Some("text") => {
                if p.get("ignored").and_then(Value::as_bool) == Some(true) {
                    continue;
                }
                if let Some(t) = p.get("text").and_then(Value::as_str) {
                    push_str_field(&mut text, t);
                }
            }
            Some("reasoning") => {
                reasoning_seen = true;
                if let Some(t) = p.get("text").and_then(Value::as_str) {
                    push_str_field(&mut thinking, t);
                }
                if let Some(sig) = p
                    .get("metadata")
                    .and_then(|m| m.get("anthropic"))
                    .and_then(|a| a.get("signature"))
                    .and_then(Value::as_str)
                {
                    thinking_sig = Some(sig.to_string());
                }
            }
            Some("tool") => {
                let call_id = p.get("callID").and_then(Value::as_str).unwrap_or_default();
                let tool_name = p.get("tool").and_then(Value::as_str).unwrap_or_default();
                let status = p
                    .get("state")
                    .and_then(|s| s.get("status"))
                    .and_then(Value::as_str);
                let known_status = matches!(
                    status,
                    Some("pending") | Some("running") | Some("completed") | Some("error")
                );
                if call_id.is_empty() || !known_status {
                    // Unknown/unrecognized status, or a malformed part with
                    // no callID — raw-only survival, never synthesized.
                    continue;
                }
                let input = p
                    .get("state")
                    .and_then(|s| s.get("input"))
                    .cloned()
                    .unwrap_or_else(|| Value::Object(Default::default()));
                calls.push(function_call(call_id, tool_name, input.to_string()));
                if matches!(status, Some("completed") | Some("error")) {
                    tool_results.push((call_id.to_string(), tool_name.to_string(), p.clone()));
                }
            }
            // file/step-start/step-finish/snapshot/patch/agent/subtask/retry
            // — no clean home on an Assistant turn (§2.3).
            _ => {}
        }
    }

    let before = out.len();
    push_assistant(out, text, calls);
    // A native OpenCode assistant record is transcript state even when it
    // has no parts. Real stores contain these after an interrupted/empty
    // model turn; dropping the record here loses its id, timestamp, model,
    // token/cost metadata, and shifts the conversation on every export.
    // Keep one empty canonical assistant message so all target writers can
    // preserve the turn. This also covers reasoning-only records (whose
    // reasoning payload is attached as metadata just below).
    if out.len() == before {
        let mut empty = ChatMessage {
            role: Role::Assistant,
            content: None,
            content_parts: None,
            tool_calls: None,
            tool_call_id: None,
            name: None,
            metadata: Default::default(),
        };
        if !reasoning_seen {
            empty
                .metadata
                .insert("empty_assistant_record".to_string(), "true".to_string());
        }
        out.push(empty);
    }
    if out.len() > before {
        let msg = out.last_mut().expect("just pushed");
        if reasoning_seen {
            msg.metadata.insert("thinking".to_string(), thinking);
        }
        if let Some(sig) = thinking_sig {
            msg.metadata.insert("thinking_signature".to_string(), sig);
        }
        if let Some(id) = msg_value.get("id").and_then(Value::as_str) {
            msg.metadata
                .insert("oc_message_id".to_string(), id.to_string());
        }
        if let Some(agent) = msg_value.get("agent").and_then(Value::as_str) {
            msg.metadata.insert("agent".to_string(), agent.to_string());
            if meta.agent_id.is_none() {
                meta.agent_id = Some(agent.to_string());
            }
        }
        let provider = msg_value.get("providerID").and_then(Value::as_str);
        let model_id = msg_value.get("modelID").and_then(Value::as_str);
        if let (Some(p), Some(i)) = (provider, model_id) {
            let full = format!("{p}/{i}");
            msg.metadata.insert("model".to_string(), full.clone());
            if meta.model.is_none() {
                meta.model = Some(full);
            }
        }
        if let Some(cwd) = msg_value
            .get("path")
            .and_then(|p| p.get("cwd"))
            .and_then(Value::as_str)
        {
            if meta.cwd.is_none() {
                meta.cwd = Some(PathBuf::from(cwd));
            }
        }
        if msg_value.get("summary").and_then(Value::as_bool) == Some(true) {
            msg.metadata
                .insert("is_summary".to_string(), "true".to_string());
        }
        for (key, field) in [
            ("finish", "finish"),
            ("variant", "variant"),
            ("mode", "mode"),
        ] {
            if let Some(s) = msg_value.get(field).and_then(Value::as_str) {
                msg.metadata.insert(key.to_string(), s.to_string());
            }
        }
        for (key, field) in [
            ("cost", "cost"),
            ("tokens", "tokens"),
            ("error", "error"),
            ("structured", "structured"),
        ] {
            if let Some(v) = msg_value.get(field) {
                if !v.is_null() {
                    msg.metadata.insert(key.to_string(), v.to_string());
                }
            }
        }
        // Subagent linkage (§2.1): a `task` tool's own `metadata` carries
        // the spawned child session id — keyed by callID so multiple `task`
        // calls in one message never collide.
        // `resolve_opencode_parent_tool_use_ids` reads these back once a
        // whole session set is loaded.
        for p in parts {
            if p.get("type").and_then(Value::as_str) == Some("tool")
                && p.get("tool").and_then(Value::as_str) == Some("task")
            {
                if let (Some(call_id), Some(child)) = (
                    p.get("callID").and_then(Value::as_str),
                    p.get("metadata")
                        .and_then(|m| m.get("sessionId"))
                        .and_then(Value::as_str),
                ) {
                    msg.metadata.insert(
                        format!("oc_task_child_session_id__{call_id}"),
                        child.to_string(),
                    );
                }
            }
        }
        set_opencode_msg_timestamp(msg, msg_value);
        restore_grok_message_extension(msg_value, msg);
    }

    // Second pass: the paired Tool-role message for each completed/error
    // tool part, split by callID (§2.1 — "the SAME part carries call and
    // result").
    for (call_id, tool_name, part) in tool_results {
        let status = part
            .get("state")
            .and_then(|s| s.get("status"))
            .and_then(Value::as_str);
        let compacted_at = part
            .get("state")
            .and_then(|s| s.get("time"))
            .and_then(|t| t.get("compacted"))
            .and_then(Value::as_i64);
        let real_output = part
            .get("state")
            .and_then(|s| s.get("output"))
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let (content, is_error) = match status {
            Some("completed") => {
                if compacted_at.is_some() {
                    (OPENCODE_COMPACTED_TOOL_PLACEHOLDER.to_string(), false)
                } else {
                    (real_output.clone(), false)
                }
            }
            Some("error") => {
                let err = part
                    .get("state")
                    .and_then(|s| s.get("error"))
                    .and_then(Value::as_str)
                    .unwrap_or("")
                    .to_string();
                (err, true)
            }
            _ => (String::new(), false),
        };
        let mut tmsg = ChatMessage {
            role: Role::Tool,
            content: Some(content),
            content_parts: None,
            tool_calls: None,
            tool_call_id: Some(call_id),
            name: Some(tool_name),
            metadata: Default::default(),
        };
        if let Some(original_position) = part
            .get(OPENCODE_SUPERCODE_RESULT_POSITION)
            .and_then(Value::as_u64)
        {
            tmsg.metadata.insert(
                OPENCODE_INTERNAL_ORIGINAL_POSITION.to_string(),
                original_position.to_string(),
            );
        }
        if is_error {
            crate::mark_tool_error(&mut tmsg);
        }
        restore_tool_outcome_extension(&part, &mut tmsg);
        if let Some(ts) = compacted_at {
            // S1: the real output is preserved — reversible, never erased.
            tmsg.metadata
                .insert("oc_tool_output_compacted".to_string(), real_output);
            tmsg.metadata
                .insert("oc_tool_time_compacted".to_string(), ts.to_string());
        }
        if status == Some("completed") {
            if let Some(atts) = part
                .get("state")
                .and_then(|s| s.get("attachments"))
                .and_then(Value::as_array)
            {
                let images: Vec<Value> = atts.iter().filter_map(opencode_file_image_part).collect();
                if !images.is_empty() {
                    // D-mix consistency fix (Fable-recommended, same
                    // pattern as `push_claude_user`'s tool_result arm above):
                    // a completed opencode tool part with BOTH `state.output`
                    // text and `state.attachments` images is the same
                    // non-self-contained hybrid shape — `content_parts` here
                    // used to hold images only, so opencode -> pi silently
                    // dropped the output text (`pi_content_value` reads
                    // `content_parts` exclusively for `Role::Tool`). Prepend
                    // the text as part 0 so `content_parts` is
                    // self-contained; `tmsg.content` keeps the text too,
                    // unchanged, for writers that read it from there and
                    // only scan `content_parts` for `image_url` entries.
                    let mut parts = Vec::new();
                    if let Some(t) = &tmsg.content {
                        if !t.is_empty() {
                            parts.push(serde_json::json!({"type": "text", "text": t}));
                        }
                    }
                    parts.extend(images);
                    tmsg.content_parts = Some(parts);
                }
            }
        }
        if let Some(id) = part.get("id").and_then(Value::as_str) {
            tmsg.metadata
                .insert("oc_part_id".to_string(), id.to_string());
        }
        // WAVE-2 item 1: a tool part's own `state.time.{end,start}` (unix-ms,
        // real opencode wire shape — `pi-fields.md`/`opencode-pi-spec.md`
        // cite `state.time.compacted`, but the SAME object also carries
        // `start`/`end` on every completed/error call) is this Tool
        // message's real source timestamp; prefer `end` (completion, closer
        // to when the RESULT — this message's content — was produced) and
        // fall back to `start` when only that is present.
        let tool_ts = part
            .get("state")
            .and_then(|s| s.get("time"))
            .and_then(|t| t.get("end").or_else(|| t.get("start")))
            .and_then(Value::as_i64);
        if let Some(ms) = tool_ts {
            tmsg.metadata
                .insert("timestamp".to_string(), crate::sidecar::ms_to_rfc3339(ms));
        }
        // OpenCode folds a canonical tool result into the assistant's tool
        // part. Restore the portable envelope from that part after native
        // fields have been captured so A -> OpenCode -> A retains fields
        // OpenCode does not model independently (for example Goose's
        // message-level metadata and an intentionally absent tool name).
        restore_grok_message_extension(&part, &mut tmsg);
        out.push(tmsg);
    }
}

// ---- shared helpers -------------------------------------------------------

fn push_text(buf: &mut String, v: Option<&Value>) {
    if let Some(Value::String(s)) = v {
        if !buf.is_empty() {
            buf.push('\n');
        }
        buf.push_str(s);
    }
}

/// Extract a Claude `tool_result` block's content, preserving non-text items
/// instead of silently dropping them:
///
/// - text blocks are concatenated;
/// - PARITY-11 (nested images, real-session-confirmed — the everyday "Read a
///   PNG / screenshot tool output" shape): `image` blocks are captured into
///   the returned `content_parts`-shaped `Vec<Value>` via
///   [`claude_image_block_to_part`] — the SAME base64/url conversion the
///   top-level `image` content-block path (`push_claude_user`) already uses
///   — instead of being flattened to the bare `[image]` marker text that used
///   to make the data unrecoverable from every writer. An unconvertible
///   source (D5 discipline — a Files-API `{"type":"file",...}` reference,
///   etc.) folds [`UNCONVERTIBLE_IMAGE_MARKER`] into the text instead of
///   vanishing, exactly like the top-level path;
/// - `tool_reference` blocks become `[tool_reference: <name>]`;
///
/// and if the block yields no text/images at all, fall back to the record's
/// `toolUseResult` field (string used directly, structured value serialized),
/// which is where Claude Code stores the actual result in many cases.
///
/// Returns `(text, images)`; callers that only need the old text-only
/// behavior can ignore the second element — every caller MUST fold non-empty
/// `images` into the resulting `ChatMessage.content_parts` themselves (this
/// function has no `ChatMessage` to attach to).
fn extract_tool_result_content(
    content: Option<&Value>,
    tool_use_result: Option<&Value>,
) -> (String, Vec<Value>) {
    let mut parts: Vec<String> = Vec::new();
    let mut images: Vec<Value> = Vec::new();
    match content {
        Some(Value::String(s)) => {
            if !s.is_empty() {
                parts.push(s.clone());
            }
        }
        Some(Value::Array(items)) => {
            for item in items {
                match item.get("type").and_then(Value::as_str) {
                    Some("text") => {
                        if let Some(t) = item.get("text").and_then(Value::as_str) {
                            parts.push(t.to_string());
                        }
                    }
                    Some("image") => match claude_image_block_to_part(item) {
                        Some(part) => images.push(part),
                        None => parts.push(UNCONVERTIBLE_IMAGE_MARKER.to_string()),
                    },
                    Some("tool_reference") => {
                        let name = item.get("tool_name").and_then(Value::as_str).unwrap_or("?");
                        parts.push(format!("[tool_reference: {name}]"));
                    }
                    _ => {
                        if let Some(s) = item.as_str() {
                            parts.push(s.to_string());
                        }
                    }
                }
            }
        }
        Some(other) => parts.push(other.to_string()),
        None => {}
    }

    let joined = parts.join("\n");
    if !joined.trim().is_empty() || !images.is_empty() {
        return (joined, images);
    }
    // Empty tool_result content — recover from toolUseResult.
    match tool_use_result {
        Some(Value::String(s)) => (s.clone(), images),
        Some(v) => (v.to_string(), images),
        None => (joined, images),
    }
}

/// Pull readable text out of a content value that may be a plain string or an
/// array of `{ "text": "..." }`-bearing blocks (any block type).
fn extract_text_content(v: Option<&Value>) -> String {
    match v {
        Some(Value::String(s)) => s.clone(),
        Some(Value::Array(items)) => {
            let mut parts = Vec::new();
            for item in items {
                if let Some(t) = item.get("text").and_then(Value::as_str) {
                    parts.push(t.to_string());
                } else if let Some(s) = item.as_str() {
                    parts.push(s.to_string());
                }
            }
            parts.join("\n")
        }
        Some(other) => other.to_string(),
        None => String::new(),
    }
}

/// Extract Codex `input_image` content blocks from a `message` response_item's
/// `content` value into `content_parts` `image_url` entries — the inverse of
/// [`codex_message_content_blocks`]'s `input_image` emission (IX-5). Only a
/// block whose `image_url` is a non-empty string is recognized; anything else
/// (a missing/malformed `image_url`, a `file_id`-only reference) is left as
/// raw-only residue rather than synthesizing a corrupt/empty part — mirroring
/// the pi/opencode/Claude loaders' image-shape discipline.
fn codex_extract_images(content: Option<&Value>) -> Vec<Value> {
    let Some(Value::Array(items)) = content else {
        return Vec::new();
    };
    items
        .iter()
        .filter(|item| item.get("type").and_then(Value::as_str) == Some("input_image"))
        .filter_map(|item| {
            let url = item.get("image_url").and_then(Value::as_str)?;
            if url.is_empty() {
                return None;
            }
            Some(serde_json::json!({"type": "image_url", "image_url": {"url": url}}))
        })
        .collect()
}

fn value_to_arg_string(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

fn push_gemini_user_parts(
    messages: &mut Vec<ChatMessage>,
    content_parts: Vec<Value>,
    timestamp: Option<&str>,
    source: &Value,
) {
    if content_parts.is_empty() {
        return;
    }
    let mut message = ChatMessage {
        role: Role::User,
        content: None,
        content_parts: Some(content_parts),
        tool_calls: None,
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    };
    if let Some(timestamp) = timestamp {
        message
            .metadata
            .insert("timestamp".into(), timestamp.into());
    }
    restore_gemini_message_extension(source, &mut message);
    messages.push(message);
}

fn function_call(id: &str, name: &str, arguments: String) -> ToolCall {
    ToolCall {
        id: id.to_string(),
        kind: "function".to_string(),
        function: FunctionCall {
            name: name.to_string(),
            arguments,
        },
    }
}

fn tool_message(tool_call_id: &str, content: String) -> ChatMessage {
    ChatMessage {
        role: Role::Tool,
        content: Some(content),
        content_parts: None,
        tool_calls: None,
        tool_call_id: Some(tool_call_id.to_string()),
        name: None,
        metadata: Default::default(),
    }
}

/// Emit a single assistant message combining accumulated text and tool calls.
/// A turn with neither (e.g. thinking-only) produces nothing.
fn push_assistant(out: &mut Vec<ChatMessage>, text: String, calls: Vec<ToolCall>) {
    let has_text = !text.trim().is_empty();
    if !has_text && calls.is_empty() {
        return;
    }
    out.push(ChatMessage {
        role: Role::Assistant,
        content: has_text.then_some(text),
        content_parts: None,
        tool_calls: (!calls.is_empty()).then_some(calls),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    });
}

// ---- writers --------------------------------------------------------------

/// A placeholder timestamp for SYNTHESIZED records only — WAVE-2 item 1's
/// fallback (`docs/interop` build brief): every writer now emits a message's
/// REAL source timestamp (`metadata["timestamp"]`, the canonical ISO-8601
/// field every loader populates) when one is present. `SYNTH_TS` fires only
/// for a message with no source timestamp at all — a turn synthesized/
/// appended after import (the live agent loop, a splice's appended tail,
/// ...), which was never loaded from a real per-message timestamp to begin
/// with. Both tools tolerate identical timestamps; callers that need real
/// ones for a synthesized turn can post-process.
const SYNTH_TS: &str = "2026-01-01T00:00:00.000Z";

/// The unix-millisecond twin of [`SYNTH_TS`], for OpenCode's numeric
/// `time.created`/`time.updated` fields.
const SYNTH_TS_MS: i64 = 1_767_225_600_000;

/// `msg`'s real source timestamp (`metadata["timestamp"]`, canonical
/// ISO-8601 — WAVE-2 item 1) when present AND well-formed, else the
/// [`SYNTH_TS`] fallback. Validated via [`crate::sidecar::rfc3339_to_ms`] (a
/// parse, not just a presence check) so an absent, empty, or malformed
/// source value all degrade to the same documented fallback rather than
/// propagating garbage verbatim. Used by every writer that emits an
/// ISO-8601 timestamp field
/// (Claude Code, Codex, pi's entry-level `timestamp`).
fn msg_timestamp_or_synth(msg: &ChatMessage) -> &str {
    match msg.metadata.get("timestamp") {
        Some(ts) if crate::sidecar::rfc3339_to_ms(ts).is_some() => ts.as_str(),
        _ => SYNTH_TS,
    }
}

/// OpenCode reloads an export document by sorting messages on
/// `time.created`, so a timestamp-less appended continuation cannot reuse
/// the fixed historical [`SYNTH_TS_MS`] fallback when its imported prefix is
/// newer. Advance a deterministic cursor for synthesized clocks while still
/// preserving every real source timestamp verbatim.
fn opencode_message_timestamp(msg: &ChatMessage, cursor: &mut i64) -> Result<i64> {
    if let Some(real) = msg
        .metadata
        .get("timestamp")
        .and_then(|s| crate::sidecar::rfc3339_to_ms(s))
    {
        // A NativeTurn timestamp is durable provenance minted by supercode,
        // not an OpenCode source clock that must be replayed verbatim.
        // Multiple turns may be recorded in the same millisecond, while
        // OpenCode sorts solely by `time.created`; allocate such turns after
        // the existing cursor so their persisted order cannot collapse. This
        // also preserves the fail-closed i64::MAX exhaustion behavior.
        if msg.metadata.contains_key("supercode_native_uuid") && real <= *cursor {
            *cursor = cursor.checked_add(1).ok_or_else(|| {
                crate::Error::Other(
                    "cannot synthesize an OpenCode continuation timestamp after i64::MAX"
                        .to_string(),
                )
            })?;
            return Ok(*cursor);
        }
        *cursor = (*cursor).max(real);
        return Ok(real);
    }
    let next = cursor.checked_add(1).ok_or_else(|| {
        crate::Error::Other(
            "cannot synthesize an OpenCode continuation timestamp after i64::MAX".to_string(),
        )
    })?;
    *cursor = next.max(SYNTH_TS_MS);
    Ok(*cursor)
}

/// Largest integer nested under any OpenCode `time` object. Imported
/// prefixes carry more clocks than `message.time.created` (assistant
/// completion, tool start/end, session updated); a synthesized continuation
/// must follow all of them, not merely sort after message creation times.
fn opencode_max_timestamp(value: &Value) -> Option<i64> {
    fn max_number(value: &Value) -> Option<i64> {
        match value {
            Value::Number(n) => n.as_i64(),
            Value::Array(values) => values.iter().filter_map(max_number).max(),
            Value::Object(fields) => fields.values().filter_map(max_number).max(),
            _ => None,
        }
    }

    match value {
        Value::Array(values) => values.iter().filter_map(opencode_max_timestamp).max(),
        Value::Object(fields) => fields
            .iter()
            .filter_map(|(key, value)| {
                if key == "time" {
                    max_number(value)
                } else {
                    opencode_max_timestamp(value)
                }
            })
            .max(),
        _ => None,
    }
}

/// pi's own message-level unix-ms clock (`metadata["pi_msg_timestamp"]`,
/// restored by the pi loader's `push_pi_*` helpers) — DISTINCT from the
/// canonical entry-level ISO `metadata["timestamp"]` [`msg_timestamp_or_synth`]
/// reads. The two carry genuinely different values in real pi corpora (a
/// message-level clock reading vs. the entry's own wall-clock stamp), so this
/// is intentionally its own accessor. Used ONLY by [`Session::write_pi_entries`]'s
/// nested `message.timestamp` field, so a pi -> pi native round-trip
/// preserves the source message-level clock value-exact instead of deriving
/// it from the (distinct) entry-level timestamp. Falls back to
/// [`SYNTH_TS_MS`] for a message that never carried a pi message-level clock
/// reading (non-pi-sourced, or a synthesized/appended turn).
fn msg_pi_native_timestamp_ms(msg: &ChatMessage) -> i64 {
    msg.metadata
        .get("pi_msg_timestamp")
        .and_then(|s| s.parse::<i64>().ok())
        .unwrap_or(SYNTH_TS_MS)
}

/// A format-valid (v4-shaped) but deterministic uuid, derived from a counter.
fn synth_uuid(n: usize) -> String {
    format!("00000000-0000-4000-8000-{n:012x}")
}

/// R1 (Skeptic B, spliced-export uuid-collision hardening — the same bug
/// class N2 closed for the Codex spliced path's group ids, see
/// `collect_codex_group_ids_from_raw`/`write_codex_records`): mint the next
/// `synth_uuid`, skipping any value already present in `seed_used_ids` — the
/// uuids [`collect_claude_uuids_from_raw`] found already sitting in the
/// verbatim raw prefix [`Session::to_claude_code_jsonl_spliced`] replays
/// ahead of the tail this counter mints. Without this, re-splicing a
/// previously-exported-then-reimported session (export -> reimport -> append
/// -> export again) restarts `counter` at 1 with no memory of the prior
/// export's tail uuids now sitting in the prefix, so the second tail
/// fabricates the SAME `00000000-0000-4000-8000-…` values the first one did
/// — a uuid collision across prefix and tail that can mis-link any
/// uuid-keyed consumer (fork/tree lineage, `parentUuid`). `counter` keeps
/// climbing monotonically even across skips. `used_ids` is also updated for
/// each minted or metadata-backed identity, so collisions are prevented both
/// against the replayed prefix and within the appended tail.
fn next_claude_uuid(counter: &mut usize, used_ids: &mut HashSet<String>) -> String {
    loop {
        let candidate = synth_uuid(*counter);
        *counter += 1;
        if used_ids.insert(candidate.clone()) {
            return candidate;
        }
    }
}

/// Reuse a message's durable native/source UUID when available, falling back
/// to the deterministic synthesized sequence only for hand-built or legacy
/// messages that never carried identity metadata.
fn claude_message_uuid(
    msg: &ChatMessage,
    counter: &mut usize,
    used_ids: &mut HashSet<String>,
) -> String {
    for key in ["claude_uuid", "supercode_native_uuid"] {
        if let Some(candidate) = msg.metadata.get(key) {
            if !candidate.is_empty() && used_ids.insert(candidate.clone()) {
                return candidate.clone();
            }
        }
    }
    next_claude_uuid(counter, used_ids)
}

/// Companion to [`next_claude_uuid`]: every `uuid` already present in
/// `raw_prefix` — the verbatim RAW lines
/// [`Session::to_claude_code_jsonl_spliced`] replays ahead of the appended
/// tail it synthesizes via [`Session::write_claude_code_records`]. This is
/// the GROUND TRUTH of what physically lands in the exported `out` string
/// for the prefix (mirrors `collect_codex_group_ids_from_raw`'s approach on
/// the Codex side): each line is parsed as a Claude Code JSONL record and
/// its own top-level `uuid` field is read back out of the bytes directly, no
/// re-derivation from `self.messages` needed. A line that fails to parse, or
/// parses but carries no `uuid` (e.g. a trailing `file-history-snapshot`
/// record), contributes nothing.
fn collect_claude_uuids_from_raw(raw_prefix: &[String]) -> HashSet<String> {
    let mut ids = HashSet::new();
    for line in raw_prefix {
        if let Ok(v) = serde_json::from_str::<Value>(line) {
            if let Some(uuid) = v.get("uuid").and_then(Value::as_str) {
                ids.insert(uuid.to_string());
            }
        }
    }
    ids
}

fn push_jsonl(out: &mut String, value: &Value) {
    out.push_str(&value.to_string());
    out.push('\n');
}

/// Replay a raw (verbatim) JSONL `line` into `out`, rewriting `key` to
/// `new_id` when the line parses as a JSON object carrying that key — used
/// by A12's Claude Code splice, where the session id lives at the top level
/// of (almost) every record under `key = "sessionId"`. A line that fails to
/// parse, or parses but lacks `key`, is copied through byte-for-byte
/// (nothing to patch, so nothing is reserialized).
fn push_spliced_line(out: &mut String, line: &str, new_id: Option<&str>, key: &str) {
    if let Some(new_id) = new_id {
        if let Ok(mut v) = serde_json::from_str::<Value>(line) {
            if v.get(key).is_some() {
                v[key] = Value::String(new_id.to_string());
                out.push_str(&v.to_string());
                out.push('\n');
                return;
            }
        }
    }
    out.push_str(line);
    out.push('\n');
}

impl Session {
    fn cwd_string(&self) -> String {
        self.meta
            .cwd
            .as_ref()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|| ".".to_string())
    }

    /// `(raw_prefix_len, message_prefix_len)` for A12 splicing: how many
    /// leading `raw` lines / `messages` came from the imported log, as
    /// opposed to being appended after import.
    ///
    /// `imported_message_count` (see its doc comment) pins the message-side
    /// boundary directly. The raw-side boundary isn't separately tracked —
    /// [`Self::from_native_str`]'s turn-appending loop pushes exactly one
    /// `raw` line per appended message, so the two lists grow by the same
    /// `appended_count` from the same starting point, and
    /// `raw.len() - appended_count` recovers it without a second counter.
    fn spliced_prefix_lens(&self) -> (usize, usize) {
        let message_prefix_len = self
            .imported_message_count
            .unwrap_or(self.messages.len())
            .min(self.messages.len());
        let appended_count = self.messages.len() - message_prefix_len;
        let raw_prefix_len = self.raw.len().saturating_sub(appended_count);
        (raw_prefix_len, message_prefix_len)
    }

    /// Synthesize a Claude Code transcript.
    ///
    /// Claude Code transcripts have no slot for the *session-level system
    /// prompt* (that lives in the CLI, not the log) — but PARITY-6 dev/02
    /// (Fable-5 corpus audit) surfaced that content-bearing `System`
    /// `ChatMessage`s (Claude's own `type: "system"` records with a
    /// content-bearing `subtype` like `local_command`/`scheduled_task_fire`/
    /// `away_summary` — see `push_claude_system`, the exact inverse of what
    /// this writer now does) DO have a first-class slot: the real `type:
    /// "system"` record itself. This function used to unconditionally drop
    /// every `System` message, silently losing e.g. a real
    /// `<local-command-stdout>` record on any format -> Claude Code hop
    /// (confirmed on a real 2,982-message corpus session: Codex -> Claude
    /// Code dropped its one surviving `system` message, 2215 -> 2214, with
    /// no loss manifest). `write_claude_code_records`'s `Role::System` arm
    /// now re-materializes it instead.
    fn to_claude_code_jsonl(&self) -> String {
        let session_id = self
            .meta
            .session_id
            .clone()
            .unwrap_or_else(|| synth_uuid(0));
        let cwd = self.cwd_string();
        let mut out = String::new();
        // PARITY-10: a captured `fork-context-ref` (see `capture_claude_meta`)
        // re-emitted byte-for-byte, ahead of the conversation it applies to —
        // this is what makes the record survive the SEMANTIC Claude Code
        // writer (the raw-passthrough diagonal in `crates/cli` already
        // preserves it by construction; this covers the library `to_jsonl`
        // path too, e.g. a `--session-id` override that forces the semantic
        // writer).
        if let Some(raw) = self.meta.lineage.get("claude_fork_context_ref_raw") {
            out.push_str(raw);
            out.push('\n');
        }
        // Full synthesis: `out` at this point has no raw prefix ahead of it
        // (unlike the A12 splice below), so there are no uuids yet in play
        // to seed against — see `next_claude_uuid`'s doc comment.
        self.write_claude_code_records(
            &mut out,
            &self.messages,
            &session_id,
            &cwd,
            None,
            1,
            &HashSet::new(),
        );
        if let Some(extension) = codex_provenance_envelope(&self.meta) {
            if out.is_empty() {
                push_jsonl(
                    &mut out,
                    &serde_json::json!({
                        "type": "file-history-snapshot",
                        "messageId": synth_uuid(1),
                        "snapshot": {},
                        "sessionId": session_id,
                        "cwd": cwd,
                        "timestamp": SYNTH_TS,
                    }),
                );
            }
            inject_first_jsonl_top_level(&mut out, SUPERCODE_CODEX_PROVENANCE_KEY, extension);
        }
        out
    }

    /// Synthesize Claude Code records for `messages` (a full session or an
    /// appended tail — A12's [`Self::to_jsonl_spliced`] reuses this for just
    /// the latter), starting the `parentUuid` chain at `parent` and the
    /// `synth_uuid` counter at `counter`. Factored out of
    /// [`Self::to_claude_code_jsonl`] so the record shape is defined once.
    ///
    /// `seed_used_ids` primes [`next_claude_uuid`]'s collision guard with
    /// every uuid that will ALREADY be present in `out` before this call
    /// ever runs — see that function's doc comment for why the A12 splice
    /// path needs this and full synthesis doesn't.
    // R1: this was already at clippy's `too_many_arguments` threshold (7,
    // including `&self`) before the fix; the added `seed_used_ids` param
    // pushes it to 8. Every argument here is independently meaningful (two
    // record-shape inputs, two id/parent-chain threading values, and now
    // the collision seed) — bundling them into a params struct is a larger
    // refactor of this already-widely-called private helper than the R1 fix
    // warrants, so this is allowed rather than restructured.
    #[allow(clippy::too_many_arguments)]
    fn write_claude_code_records(
        &self,
        out: &mut String,
        messages: &[ChatMessage],
        session_id: &str,
        cwd: &str,
        mut parent: Option<String>,
        mut counter: usize,
        seed_used_ids: &HashSet<String>,
    ) {
        let mut used_ids = seed_used_ids.clone();
        for msg in messages {
            if is_replay_excluded(msg) {
                continue;
            }
            let blocks: Vec<Value> = match msg.role {
                // PARITY-6 dev/02: re-materialize a content-bearing System
                // `ChatMessage` as a real Claude Code `type: "system"`
                // record — the exact inverse of `push_claude_system`, which
                // is what produced it in the first place for a message
                // loaded FROM a real Claude Code transcript. `subtype`
                // prefers the original `systemSubtype` metadata
                // (`push_claude_system`'s `.with_meta`, round-tripped
                // through the Codex hop via `write_codex_records`'s
                // `claude_system_subtype` metadata channel and restored by
                // `push_codex_item`); when that channel didn't carry it
                // (e.g. a genuinely native, non-Claude-origin developer
                // message), fall back to `local_command` — the observed
                // common case, and still one of `push_claude_system`'s own
                // `keep` subtypes, so the record survives a *subsequent*
                // reload rather than being silently re-dropped. This never
                // fabricates content: the real text is always carried
                // verbatim, only the subtype label is a best-effort guess
                // when the true one wasn't recoverable.
                Role::System => {
                    let content = msg.content.clone().unwrap_or_default();
                    if content.trim().is_empty() {
                        continue;
                    }
                    let subtype = msg
                        .metadata
                        .get("systemSubtype")
                        .cloned()
                        .unwrap_or_else(|| "local_command".to_string());
                    // R1/B3 union: this mint must ALSO route through
                    // `next_claude_uuid` + `seed_used_ids` like the other
                    // three arms below — otherwise this System arm (added by
                    // B3 after R1 landed) mints a raw `synth_uuid` that can
                    // collide with a uuid already sitting in the A12 splice's
                    // raw prefix (see `next_claude_uuid`'s doc comment).
                    let uuid = claude_message_uuid(msg, &mut counter, &mut used_ids);
                    let mut line = serde_json::json!({
                        "parentUuid": parent,
                        "type": "system",
                        "subtype": subtype,
                        "content": content,
                        "uuid": uuid,
                        "sessionId": session_id,
                        "cwd": cwd,
                        "timestamp": msg_timestamp_or_synth(msg),
                    });
                    set_grok_message_extension(&mut line, self.meta.source, msg);
                    push_jsonl(out, &line);
                    parent = Some(uuid);
                    continue;
                }
                Role::User => {
                    let uuid = claude_message_uuid(msg, &mut counter, &mut used_ids);
                    let mut line = serde_json::json!({
                        "parentUuid": parent,
                        "type": "user",
                        "message": {
                            "role": "user",
                            "content": claude_user_content_value(msg),
                        },
                        "uuid": uuid,
                        "sessionId": session_id,
                        "cwd": cwd,
                        "timestamp": msg_timestamp_or_synth(msg),
                    });
                    set_grok_message_extension(&mut line, self.meta.source, msg);
                    push_jsonl(out, &line);
                    parent = Some(uuid);
                    continue;
                }
                Role::Tool => {
                    let uuid = claude_message_uuid(msg, &mut counter, &mut used_ids);
                    let mut line = serde_json::json!({
                        "parentUuid": parent,
                        "type": "user",
                        "message": {
                            "role": "user",
                            "content": [{
                                "type": "tool_result",
                                "tool_use_id": msg.tool_call_id.clone().unwrap_or_default(),
                                "content": claude_tool_result_content_value(msg),
                            }],
                        },
                        "uuid": uuid,
                        "sessionId": session_id,
                        "cwd": cwd,
                        "timestamp": msg_timestamp_or_synth(msg),
                    });
                    if crate::tool_outcome(msg) == crate::ToolOutcome::Unknown {
                        line[SUPERCODE_TOOL_OUTCOME_KEY] = Value::String("unknown".to_string());
                    }
                    set_grok_message_extension(&mut line, self.meta.source, msg);
                    push_jsonl(out, &line);
                    parent = Some(uuid);
                    continue;
                }
                Role::Assistant => {
                    let mut blocks = Vec::new();
                    // PARITY-16 (found via the REAL pi corpus, PARITY-5
                    // dev/01): thinking/redacted_thinking must be re-emitted
                    // BEFORE text/tool_use, unconditionally whenever
                    // retained metadata is present — not only when `blocks`
                    // is otherwise empty. The previous `if blocks.is_empty()`
                    // gate (now below, applied unconditionally instead)
                    // meant a turn that thinks AND THEN answers/calls a tool
                    // in the SAME turn — pi's own default emission shape,
                    // and the overwhelmingly common real-world case for any
                    // reasoning model, not the rare reasoning-only edge case
                    // this gate's comment described — silently dropped its
                    // entire `thinking` block on Pi -> Claude Code export. A
                    // genuine multi-turn pi session driven through pi's own
                    // real Agent loop (faux provider, see
                    // `pi_interop.rs`'s live-corpus tests) exposed this: its
                    // thinking+text turns lost the thinking block entirely.
                    // D8: prefer the exact per-block list when present —
                    // every `thinking`/`redacted_thinking` block re-emitted
                    // SEPARATELY with its own signature/data, exactly as
                    // captured (`push_claude_assistant`), instead of the
                    // legacy singular fields' lossy collapse (which drops
                    // every signature but the last one's on a multi-block
                    // message). Falls back to the legacy fields only for a
                    // `Session` that never populated `thinking_blocks` (e.g.
                    // hand-constructed in another loader/test, or loaded
                    // from a non-Claude-Code source like Pi).
                    match msg
                        .metadata
                        .get("thinking_blocks")
                        .and_then(|s| serde_json::from_str::<Value>(s).ok())
                        .and_then(|v| v.as_array().cloned())
                    {
                        Some(saved_blocks) => blocks.extend(saved_blocks),
                        None => {
                            if let Some(t) = msg.metadata.get("thinking") {
                                let mut block =
                                    serde_json::json!({"type": "thinking", "thinking": t});
                                if let Some(sig) = msg.metadata.get("thinking_signature") {
                                    block["signature"] = Value::String(sig.clone());
                                }
                                blocks.push(block);
                            }
                            if let Some(rt) = msg.metadata.get("redacted_thinking") {
                                blocks.push(
                                    serde_json::json!({"type": "redacted_thinking", "data": rt}),
                                );
                            }
                        }
                    }
                    if let Some(t) = &msg.content {
                        if !t.is_empty() {
                            blocks.push(serde_json::json!({"type": "text", "text": t}));
                        }
                    }
                    // PARITY-11: an assistant-emitted image (`content_parts`,
                    // e.g. a generated image — `push_claude_assistant`'s
                    // load-side counterpart) has no slot in `msg.content`;
                    // without this, `blocks` stayed empty for an image-only
                    // turn and the whole message vanished on Claude Code
                    // semantic export, same failure mode the IX-6 Codex
                    // writer fix already closed on that side.
                    if let Some(parts) = &msg.content_parts {
                        for p in parts {
                            if p.get("type").and_then(Value::as_str) == Some("image_url") {
                                if let Some(url) = p
                                    .get("image_url")
                                    .and_then(|u| u.get("url"))
                                    .and_then(Value::as_str)
                                {
                                    blocks.push(match parse_data_uri(url) {
                                        Some((mime, data)) => serde_json::json!({
                                            "type": "image",
                                            "source": {"type": "base64", "media_type": mime, "data": data},
                                        }),
                                        None => serde_json::json!({
                                            "type": "image",
                                            "source": {"type": "url", "url": url},
                                        }),
                                    });
                                }
                            }
                        }
                    }
                    for tc in msg.tool_calls() {
                        let input = tc
                            .function
                            .parsed_arguments()
                            .unwrap_or_else(|_| Value::Object(Default::default()));
                        blocks.push(serde_json::json!({
                            "type": "tool_use",
                            "id": tc.id,
                            "name": tc.function.name,
                            "input": input,
                        }));
                    }
                    // PARITY-11 / PARITY-16: a genuinely reasoning-only turn
                    // (no text, no tool_use, no image) still doesn't vanish
                    // — the thinking/redacted_thinking prepend above already
                    // ran unconditionally, so `blocks` is non-empty here
                    // whenever any of those were present.
                    blocks
                }
            };

            // An empty assistant content array is a valid native interrupted
            // turn and must remain a record. Every non-assistant arm above
            // already `continue`s after writing its own shape, so an empty
            // `blocks` value here belongs specifically to that assistant.
            let uuid = claude_message_uuid(msg, &mut counter, &mut used_ids);
            let mut message = serde_json::json!({"role": "assistant", "content": blocks});
            if let Some(model) = msg.metadata.get("model").or(self.meta.model.as_ref()) {
                message["model"] = Value::String(model.clone());
            }
            let mut line = serde_json::json!({
                "parentUuid": parent,
                "type": "assistant",
                "message": message,
                "uuid": uuid,
                "sessionId": session_id,
                "cwd": cwd,
                "timestamp": msg_timestamp_or_synth(msg),
            });
            set_grok_message_extension(&mut line, self.meta.source, msg);
            push_jsonl(out, &line);
            parent = Some(uuid);
        }
    }

    /// A12 splice: replay the imported Claude Code `raw` prefix verbatim
    /// (patching `sessionId` on each line when `session_id` is `Some`), then
    /// synthesize records only for the appended tail, via
    /// [`Self::write_claude_code_records`] — chaining `parentUuid` from the
    /// last original `uuid` found anywhere in the raw prefix (not just its
    /// final line: a trailing loader-skipped record, e.g.
    /// `file-history-snapshot`, may carry no `uuid` of its own).
    fn to_claude_code_jsonl_spliced(&self, session_id: Option<&str>) -> String {
        let (raw_prefix_len, message_prefix_len) = self.spliced_prefix_lens();
        let sid = session_id
            .map(str::to_string)
            .or_else(|| self.meta.session_id.clone())
            .unwrap_or_else(|| synth_uuid(0));
        let cwd = self.cwd_string();

        let mut out = String::new();
        let mut parent: Option<String> = None;
        for line in &self.raw[..raw_prefix_len] {
            push_spliced_line(&mut out, line, session_id, "sessionId");
            if let Ok(v) = serde_json::from_str::<Value>(line) {
                if let Some(uuid) = v.get("uuid").and_then(Value::as_str) {
                    parent = Some(uuid.to_string());
                }
            }
        }

        // R1 (spliced-path hardening, mirrors the Codex N2 fix above): seed
        // the tail's collision guard with every uuid the just-replayed RAW
        // prefix already carries, so `write_claude_code_records` never
        // fabricates a `synth_uuid` for the appended tail that collides with
        // one already sitting in the prefix (see `next_claude_uuid`'s and
        // `collect_claude_uuids_from_raw`'s doc comments).
        let seed_used_ids = collect_claude_uuids_from_raw(&self.raw[..raw_prefix_len]);
        self.write_claude_code_records(
            &mut out,
            &self.messages[message_prefix_len..],
            &sid,
            &cwd,
            parent,
            1,
            &seed_used_ids,
        );
        out
    }

    /// Synthesize a Codex rollout.
    fn to_codex_jsonl(&self) -> String {
        let mut out = String::new();

        if self.meta.codex_headers.is_empty() {
            self.write_synthesized_codex_header(&mut out);
        } else {
            // Replay the exact header records the original tool wrote — Codex's
            // reader validates the header shape strictly — overriding only the
            // session id when the caller changed it.
            for header in &self.meta.codex_headers {
                let mut header = header.clone();
                if header.get("type").and_then(Value::as_str) == Some("session_meta") {
                    if let Some(id) = &self.meta.session_id {
                        if let Some(payload) = header.get_mut("payload") {
                            payload["id"] = Value::String(id.clone());
                        }
                    }
                }
                push_jsonl(&mut out, &header);
            }
        }

        // Full synthesis: `out` at this point is only the header, so there
        // are no group ids yet in play to seed against (see
        // `write_codex_records`'s doc comment).
        self.write_codex_records(&mut out, &self.messages, &std::collections::HashSet::new());
        if let Some(extension) = codex_provenance_envelope(&self.meta) {
            inject_codex_provenance(&mut out, extension);
        }
        out
    }

    /// Synthesize Codex `response_item` records for `messages` (a full
    /// session or an appended tail — A12's [`Self::to_jsonl_spliced`] reuses
    /// this for just the latter). Factored out of [`Self::to_codex_jsonl`] so
    /// the record shape is defined once; `tool_search_call_ids` pairing is
    /// scoped to this call's `messages`, matching the header-replay
    /// contract that only appended records need synthesizing.
    ///
    /// `seed_used_ids` primes the N2 collision guard below with every group
    /// id that will ALREADY be present in `out` before this call ever runs —
    /// [`Self::to_codex_jsonl`] (full synthesis, `out` starts as just the
    /// header) passes an empty set, since every group id in that case is
    /// assigned by this very loop. [`Self::to_codex_jsonl_spliced`] (the A12
    /// splice) passes the ids already used by the verbatim RAW prefix it
    /// replayed into `out` just before calling this for the appended tail —
    /// without that seed, the tail's own `used_group_ids`/`next_group_id`
    /// start blind to the prefix and can fabricate/reuse a group id that
    /// COLLIDES with one still "open" at the end of the prefix, letting
    /// reimport's merge check (`can_merge`, `push_codex_item`) wrongly splice
    /// an unrelated appended message into a historical one — the same
    /// bug-class N2 closed for full synthesis, reopened here because the
    /// spliced tail's tracking set used to always start empty regardless of
    /// what the replayed prefix already contained.
    fn write_codex_records(
        &self,
        out: &mut String,
        messages: &[ChatMessage],
        seed_used_ids: &std::collections::HashSet<String>,
    ) {
        // Call ids of assistant `tool_search` calls (B6 agent intrinsic), so
        // the matching tool result below can be emitted as the paired
        // `tool_search_output` record rather than a generic
        // `function_call_output` — the exact inverse of the importer's
        // `tool_search_call`/`tool_search_output` normalization
        // (`push_codex_item`, above).
        let mut tool_search_call_ids: std::collections::HashSet<String> = Default::default();
        // PARITY-6/7: two ADJACENT but genuinely SEPARATE Claude assistant
        // records (e.g. a text-only narration turn immediately followed by a
        // bare tool-call turn, no user turn between — a real, common Claude
        // Code shape) each become their own Codex `message`/`function_call`
        // response_item(s) here. Codex's own reader (`push_codex_item`, IX-6)
        // opportunistically RE-MERGES an assistant `message` immediately
        // followed by a `function_call` back into ONE `ChatMessage`, to match
        // how a genuinely single Claude turn (text+tool_use in the SAME
        // record) round-trips — but with no distinguishing signal, it can't
        // tell that case apart from two originally-separate records that
        // just happen to be adjacent, so it wrongly recombines them too,
        // silently shrinking the message count on every Claude -> Codex ->
        // (inspect) hop. Fix: stamp a synthetic `metadata.turn_id` — unique
        // per ORIGINAL `ChatMessage` — onto the `message` record AND every
        // `function_call`/`tool_search_call` record THAT SAME `ChatMessage`
        // itself emits. `push_codex_item`'s merge already treats a turn_id
        // mismatch as "different turn, do not merge" (the pre-existing
        // belt-and-suspenders check); real native Codex data almost never
        // carries this field (per that check's own comment), so this is a
        // no-op there and only sharpens fidelity for OUR OWN synthesized
        // export.
        let mut next_group_id: u64 = 0;
        // N2 (Fable-5 review, turn_id-collision hardening): every group id
        // this export has already assigned — whether REUSED from a real
        // `turn_id` or FABRICATED as `sc-grp-N` — so a later assistant
        // `ChatMessage` never emits one that's already in use. Two concrete
        // mis-merge scenarios motivate this:
        //
        // (a) Claude->Codex export fabricates `sc-grp-0` for msg A (msg A's
        //     own text+tool_use); reload makes A carry REAL turn_id
        //     `sc-grp-0`. A bare tool-call msg B (metadata has no turn_id of
        //     its own) is then appended. Re-export: A reuses its real
        //     `sc-grp-0`, but B independently fabricates a FRESH id starting
        //     from `next_group_id == 0` again (nothing bumped it when A's id
        //     was reused rather than fabricated) — also `sc-grp-0`.
        //     Collision. If A's call has no output (interrupted session),
        //     reimport sees message(sc-grp-0)+call(sc-grp-0)+call(sc-grp-0)
        //     adjacent with nothing to break the run and merges all three
        //     into ONE message (2 -> 1).
        // (b) Native Codex: `message(turn-7)` opens the merge marker, a
        //     truncation/clear event strips `__codex_open_turn` (closing the
        //     turn without changing the id), then `function_call(turn-7)`
        //     loads as a SECOND, separate `ChatMessage` that still carries
        //     the SAME real `turn_id` (the reopen step in `push_codex_item`
        //     restamps it). Full-synthesis export naively reuses `turn-7`
        //     verbatim for BOTH messages (they're two different loop
        //     iterations, each independently reusing its own `real_turn_id`)
        //     and emits them adjacent — reimport's merge check can't tell
        //     this apart from a single message's own multi-call turn and
        //     recombines them (2 -> 1).
        //
        // Fix: the fabricated-id counter is advanced (skipped) past any id
        // already in `used_group_ids`, AND a real id that's already been
        // used gets disambiguated (`<real>~dupN`) instead of reused verbatim
        // — never letting two DIFFERENT `ChatMessage`s in this export share
        // one group id, since `push_codex_item`'s merge check treats a
        // shared id as "same turn, merge". A single `ChatMessage`'s own
        // message record + its own tool call records still share ONE group
        // id (computed once per loop iteration below, before insertion), so
        // the D1 tool_search merge and ordinary same-turn multi-call
        // grouping are unaffected — this only stops REUSE across iterations.
        //
        // Seeded from `seed_used_ids` (see this fn's doc comment) so the
        // spliced-export tail is likewise blind-proof against the prefix it
        // doesn't itself write.
        let mut used_group_ids: std::collections::HashSet<String> = seed_used_ids.clone();

        for msg in messages {
            if is_replay_excluded(msg) {
                continue;
            }
            // D3 (Fable-5 review): a message loaded FROM real native Codex
            // carries its OWN real `turn_id` in `msg.metadata["turn_id"]`
            // (`push_codex_item`'s "message" arm stamps it whenever the
            // source record itself has one). The group-id logic below used
            // to ALWAYS fabricate a fresh `"sc-grp-N"` value regardless,
            // silently overwriting/discarding that real id on any
            // native-Codex -> load -> export-Codex hop. Reuse it verbatim
            // when present; only fabricate a synthetic id as a fallback for
            // our own merge-disambiguation need (PARITY-6/7) when the
            // message has no real one of its own.
            let real_turn_id = msg.metadata.get("turn_id").map(String::as_str);
            match msg.role {
                Role::System => {
                    // PARITY-6 dev/02: carry the original Claude
                    // `systemSubtype` (`push_claude_system`'s `.with_meta`)
                    // through as `metadata.claude_system_subtype`, so
                    // `push_codex_item`'s reverse load can restore it and
                    // `write_claude_code_records`'s `Role::System` arm can
                    // re-materialize the EXACT original subtype rather than
                    // guessing on a Codex -> Claude hop.
                    let subtype_meta = msg
                        .metadata
                        .get("systemSubtype")
                        .map(|s| ("claude_system_subtype", s.as_str()));
                    self.push_codex_message(
                        out,
                        "developer",
                        "input_text",
                        msg,
                        real_turn_id,
                        subtype_meta,
                    )
                }
                Role::User => {
                    self.push_codex_message(out, "user", "input_text", msg, real_turn_id, None)
                }
                Role::Assistant => {
                    // Emit the message record whenever there is text OR
                    // content_parts (IX-6 follow-up): an image-only assistant
                    // message has `content: None, content_parts:
                    // Some([image])` (the loader's `codex_extract_images` is
                    // role-general, so this shape can occur on the assistant
                    // side too) — gating on `msg.content` alone silently
                    // dropped the whole message, image included. A
                    // text-only message (content_parts: None) keeps taking
                    // the historical byte-identical path via
                    // `codex_message_content_blocks`'s `None` arm. A real
                    // empty native assistant record carries the
                    // loader's explicit marker and must also be emitted.
                    // Reasoning-only cross-provider turns deliberately lack
                    // that marker and keep the documented Codex residue.
                    let has_text = msg.content.as_deref().is_some_and(|t| !t.is_empty());
                    let has_message_record = has_text
                        || msg.content_parts.is_some()
                        || msg.metadata.contains_key("empty_assistant_record");
                    // Only assign a synthetic group id when there's actual
                    // merge ambiguity to resolve (a message AND its own tool
                    // calls, or 2+ of this message's own tool calls) — a
                    // pure-text message with no tool calls, or a lone tool
                    // call with nothing else from the same `ChatMessage`,
                    // has nothing to disambiguate, so it keeps the exact
                    // historical byte shape (no `metadata` key at all).
                    let group_id: Option<String> = if let Some(real) = real_turn_id {
                        if used_group_ids.contains(real) {
                            // N2: this real turn_id was already used by an
                            // earlier (now-closed) `ChatMessage` in this same
                            // export — reusing it verbatim would let the
                            // reimport merge check recombine two originally
                            // separate messages (see the doc comment above).
                            let mut n = 1u64;
                            let mut candidate = format!("{real}~dup{n}");
                            while used_group_ids.contains(&candidate) {
                                n += 1;
                                candidate = format!("{real}~dup{n}");
                            }
                            Some(candidate)
                        } else {
                            Some(real.to_string())
                        }
                    } else if !msg.tool_calls().is_empty() {
                        // N2: skip past any id already used (e.g. a REAL
                        // turn_id that happens to look like `sc-grp-N`, or an
                        // id an earlier reused-real case landed on).
                        let mut candidate = format!("sc-grp-{next_group_id}");
                        next_group_id += 1;
                        while used_group_ids.contains(&candidate) {
                            candidate = format!("sc-grp-{next_group_id}");
                            next_group_id += 1;
                        }
                        Some(candidate)
                    } else {
                        None
                    };
                    if let Some(g) = &group_id {
                        used_group_ids.insert(g.clone());
                    }
                    if has_message_record {
                        self.push_codex_message(
                            out,
                            "assistant",
                            "output_text",
                            msg,
                            group_id.as_deref(),
                            None,
                        );
                    }
                    for tc in msg.tool_calls() {
                        let custom_tool_call = msg
                            .metadata
                            .get("codex_custom_tool_call_ids")
                            .and_then(|raw| serde_json::from_str::<Vec<String>>(raw).ok())
                            .is_some_and(|ids| ids.iter().any(|id| id == &tc.id));
                        if custom_tool_call {
                            let input = tc
                                .function
                                .parsed_arguments()
                                .unwrap_or_else(|_| Value::String(tc.function.arguments.clone()));
                            let mut payload = with_turn_id(
                                serde_json::json!({
                                    "type": "custom_tool_call",
                                    "name": tc.function.name,
                                    "input": input,
                                    "call_id": tc.id,
                                }),
                                group_id.as_deref(),
                            );
                            set_grok_message_extension(&mut payload, self.meta.source, msg);
                            push_jsonl(
                                out,
                                &codex_response_item(payload, msg_timestamp_or_synth(msg)),
                            );
                        } else if tc.function.name == "tool_search" {
                            tool_search_call_ids.insert(tc.id.clone());
                            let mut payload = with_turn_id(
                                serde_json::json!({
                                    "type": "tool_search_call",
                                    "arguments": tc.function.arguments,
                                    "call_id": tc.id,
                                }),
                                group_id.as_deref(),
                            );
                            set_grok_message_extension(&mut payload, self.meta.source, msg);
                            push_jsonl(
                                out,
                                &codex_response_item(payload, msg_timestamp_or_synth(msg)),
                            );
                        } else {
                            let mut payload = with_turn_id(
                                serde_json::json!({
                                    "type": "function_call",
                                    "name": tc.function.name,
                                    "arguments": tc.function.arguments,
                                    "call_id": tc.id,
                                }),
                                group_id.as_deref(),
                            );
                            set_grok_message_extension(&mut payload, self.meta.source, msg);
                            push_jsonl(
                                out,
                                &codex_response_item(payload, msg_timestamp_or_synth(msg)),
                            );
                        }
                    }
                    // PARITY-11: a genuinely reasoning-only turn (Claude
                    // `thinking`/`redacted_thinking` with no text, tool_use,
                    // or image — `push_claude_assistant`'s load-side fix for
                    // the ~21% of real assistant records that are exactly
                    // this shape) has no message record and no tool calls,
                    // so nothing above writes anything for it. This is
                    // DELIBERATE, not a residual gap: Codex's `reasoning`
                    // response_item is understood on import (see the
                    // `response_item`/`"reasoning"` arm above), but its
                    // real-native semantics is "the reasoning immediately
                    // BEFORE the next turn" — the reader attaches it to
                    // whatever response_item comes next, unconditionally.
                    // For a genuinely standalone Claude reasoning-only turn
                    // (no related turn follows in Codex's export at all),
                    // emitting one here would get silently misattributed as
                    // belonging to some later, unrelated turn instead —
                    // strictly worse than the current honest, accounted-for
                    // absence (thinking/redacted_thinking is provider-
                    // private and "not replayed across providers" by
                    // original design; the audit correctly classifies it
                    // `Coverage::Dropped`, not `Unmodeled`). See the
                    // PARITY-6/7 corpus test's `is_replayable` filter for
                    // why this doesn't count as a message-count regression.
                }
                Role::Tool
                    if msg
                        .tool_call_id
                        .as_deref()
                        .is_some_and(|id| tool_search_call_ids.contains(id)) =>
                {
                    let content = msg.content.clone().unwrap_or_default();
                    let tools =
                        serde_json::from_str::<Value>(&content).unwrap_or(Value::String(content));
                    let mut payload = serde_json::json!({
                        "type": "tool_search_output",
                        "call_id": msg.tool_call_id.clone().unwrap_or_default(),
                        "tools": tools,
                    });
                    set_grok_message_extension(&mut payload, self.meta.source, msg);
                    push_jsonl(
                        out,
                        &codex_response_item(payload, msg_timestamp_or_synth(msg)),
                    );
                }
                Role::Tool => {
                    let mut payload = serde_json::json!({
                        "type": "function_call_output",
                        "call_id": msg.tool_call_id.clone().unwrap_or_default(),
                        "output": codex_tool_output_text(msg),
                    });
                    set_grok_message_extension(&mut payload, self.meta.source, msg);
                    push_jsonl(
                        out,
                        &codex_response_item(payload, msg_timestamp_or_synth(msg)),
                    );
                }
            }
        }
    }

    /// A12 splice: replay the imported Codex `raw` prefix verbatim — every
    /// line, not just the `session_meta`/`turn_context` headers
    /// [`Self::to_codex_jsonl`] replays — overriding only
    /// `session_meta.payload.id` when `session_id` is `Some` (every other
    /// line, including `response_item`s the stock synthesis would otherwise
    /// rebuild from scratch, is untouched byte-for-byte). Then synthesizes
    /// `response_item` records only for the appended tail, via
    /// [`Self::write_codex_records`].
    fn to_codex_jsonl_spliced(&self, session_id: Option<&str>) -> String {
        let (raw_prefix_len, message_prefix_len) = self.spliced_prefix_lens();

        let mut out = String::new();
        for line in &self.raw[..raw_prefix_len] {
            match session_id {
                Some(id) => {
                    let patched = serde_json::from_str::<Value>(line)
                        .ok()
                        .filter(|v| v.get("type").and_then(Value::as_str) == Some("session_meta"))
                        .map(|mut v| {
                            if let Some(payload) = v.get_mut("payload") {
                                payload["id"] = Value::String(id.to_string());
                            }
                            v.to_string()
                        });
                    out.push_str(patched.as_deref().unwrap_or(line));
                }
                None => out.push_str(line),
            }
            out.push('\n');
        }

        // N2 (spliced-path hardening): seed the tail's collision guard with
        // every group id the just-replayed RAW prefix already carries, so
        // `write_codex_records` never fabricates/reuses an id for the
        // appended tail that collides with one still open at the end of the
        // prefix (see that fn's doc comment, and
        // `collect_codex_group_ids_from_raw`'s).
        let mut seed_used_ids = collect_codex_group_ids_from_raw(&self.raw[..raw_prefix_len]);
        // Belt-and-suspenders: also union in the prefix `messages`' own
        // recorded `turn_id` metadata. In the ordinary case this is already
        // a subset of what the raw-line scan above found (the loader stamps
        // `metadata["turn_id"]` from the very same `payload.metadata.turn_id`
        // field the scan reads) — but scanning `messages` too costs nothing
        // and means this stays correct even if some future loader path ever
        // derives a message's `turn_id` by some means other than a literal
        // `payload.metadata.turn_id` copy.
        for msg in &self.messages[..message_prefix_len] {
            if let Some(tid) = msg.metadata.get("turn_id") {
                seed_used_ids.insert(tid.clone());
            }
        }
        self.write_codex_records(
            &mut out,
            &self.messages[message_prefix_len..],
            &seed_used_ids,
        );
        out
    }

    /// Build a Codex header from scratch (used when converting from another
    /// format, where no original Codex header exists to replay). Emits the
    /// fields Codex requires on `session_meta`.
    fn write_synthesized_codex_header(&self, out: &mut String) {
        let mut meta_payload = serde_json::json!({
            "id": self.meta.session_id.clone().unwrap_or_else(|| synth_uuid(0)),
            "timestamp": SYNTH_TS,
            "cwd": self.cwd_string(),
            "originator": "supercode",
            "cli_version": env!("CARGO_PKG_VERSION"),
            "source": "exec",
            "thread_source": "user",
            "model_provider": "openai",
        });
        if let Some(sp) = &self.meta.system_prompt {
            meta_payload["base_instructions"] = serde_json::json!({"text": sp});
        }
        // PARITY-10 dev/03: carry a captured Claude `fork-context-ref` (see
        // `capture_claude_meta`) through the Codex hop under a clearly
        // namespaced custom field — real Codex tooling ignores unknown
        // `session_meta.payload` keys, and `capture_codex_session_meta`
        // reads this same key back on import, so a Claude -> Codex -> Claude
        // round trip still reconstructs the original record instead of
        // silently losing the lineage note on the cross-format hop.
        if let Some(raw) = self.meta.lineage.get("claude_fork_context_ref_raw") {
            meta_payload["claude_fork_context_ref"] =
                serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.clone()));
        }
        push_jsonl(
            out,
            &serde_json::json!({"timestamp": SYNTH_TS, "type": "session_meta", "payload": meta_payload}),
        );
        if let Some(model) = &self.meta.model {
            push_jsonl(
                out,
                &serde_json::json!({
                    "timestamp": SYNTH_TS,
                    "type": "turn_context",
                    "payload": {"model": model, "cwd": self.cwd_string()},
                }),
            );
        }
    }

    /// `turn_id`: see the PARITY-6/7 (and D3) comment on
    /// [`Self::write_codex_records`] — `Some` when the source message
    /// carries its own REAL `turn_id` (a native-Codex round-trip), or
    /// (assistant only) a synthetic disambiguation id when it owns tool
    /// calls needing merge disambiguation and has no real id of its own;
    /// `None` reproduces the exact historical shape (no `metadata` key at
    /// all).
    /// `extra_metadata`: PARITY-6 dev/02 — an additional `(key, value)`
    /// pair folded into `payload.metadata` alongside `turn_id` (used by the
    /// `Role::System` case in [`Self::write_codex_records`] to carry
    /// `claude_system_subtype`, so a Claude `<local-command-stdout>`-style
    /// system record's subtype survives the Claude -> Codex -> Claude round
    /// trip instead of only its text; `None` for every other caller,
    /// preserving the exact historical shape).
    fn push_codex_message(
        &self,
        out: &mut String,
        role: &str,
        text_type: &str,
        msg: &ChatMessage,
        turn_id: Option<&str>,
        extra_metadata: Option<(&str, &str)>,
    ) {
        let mut payload = with_turn_id(
            serde_json::json!({
                "type": "message",
                "role": role,
                "content": codex_message_content_blocks(text_type, msg),
            }),
            turn_id,
        );
        if let Some((k, v)) = extra_metadata {
            if payload.get("metadata").is_none() {
                payload["metadata"] = serde_json::json!({});
            }
            payload["metadata"][k] = serde_json::json!(v);
        }
        set_grok_message_extension(&mut payload, self.meta.source, msg);
        push_jsonl(
            out,
            &codex_response_item(payload, msg_timestamp_or_synth(msg)),
        );
    }

    /// Synthesize a fresh pi v3 session from the canonical `messages`
    /// (T3 cross-format/full synthesis — `to_jsonl(other)`'s "view round-trip"
    /// tier, §3/§4.1: this is NOT the byte-lossless native path, which goes
    /// through `raw` + `to_native_jsonl(_v2)` instead).
    fn to_pi_jsonl(&self) -> String {
        let session_id = self
            .meta
            .session_id
            .clone()
            .unwrap_or_else(|| synth_uuid(0));
        let cwd = self.cwd_string();
        let mut out = String::new();
        push_pi_header(
            &mut out,
            &session_id,
            &cwd,
            self.meta
                .lineage
                .get("parent_session_path")
                .map(String::as_str),
            self.meta.lineage.get("created_at").map(String::as_str),
            // D7: carry a captured Claude `fork-context-ref` (see
            // `capture_claude_meta`) through the Pi hop too — mirrors the
            // Codex hop's `claude_fork_context_ref` passthrough
            // (`write_synthesized_codex_header`) so a Claude -> Pi -> Claude
            // round trip doesn't silently lose fork lineage just because Pi
            // has no native slot for it.
            self.meta
                .lineage
                .get("claude_fork_context_ref_raw")
                .map(String::as_str),
        );
        let mut used_ids: HashSet<String> = HashSet::new();
        let mut counter: u64 = 0;
        self.write_pi_entries(&mut out, &self.messages, None, &mut used_ids, &mut counter);
        if let Some(extension) = codex_provenance_envelope(&self.meta) {
            inject_first_jsonl_top_level(&mut out, SUPERCODE_CODEX_PROVENANCE_KEY, extension);
        }
        out
    }

    /// Synthesize pi `message` entries for `messages` (a full session, or —
    /// for [`Self::to_pi_jsonl_spliced`] — just the appended tail), chaining
    /// `parentId` from `parent` and drawing fresh ids from `used_ids`/
    /// `counter`. Skips [`is_replay_excluded`] messages (`compacted_out`,
    /// `pi_exclude_from_context`) exactly like the Claude/Codex writers.
    fn write_pi_entries(
        &self,
        out: &mut String,
        messages: &[ChatMessage],
        mut parent: Option<String>,
        used_ids: &mut HashSet<String>,
        counter: &mut u64,
    ) {
        // Claude Code and Codex do not repeat the tool name on their native
        // tool-result records. Recover that redundant Pi field from the
        // paired assistant call when a cross-format round trip therefore
        // returns a canonical Tool message with `name == None`.
        let mut paired_tool_names = HashMap::<String, String>::new();
        for msg in messages {
            if is_replay_excluded(msg) {
                continue;
            }
            for call in msg.tool_calls() {
                paired_tool_names.insert(call.id.clone(), call.function.name.clone());
            }
            let id = pi_fresh_id(used_ids, counter);
            let mut entry = match msg.role {
                // B4: pi has no session-level system/developer PROMPT slot
                // (§1.1: "no system-prompt... rebuilt at runtime"), but a
                // content-bearing `Role::System` message loaded from a real
                // Claude Code `type: "system"` record (`push_claude_system`'s
                // keep-listed subtypes: `local_command`, `scheduled_task_fire`,
                // `away_summary`) is NOT a system prompt — it's a real,
                // non-regenerable transcript event. Pi's own `role:"custom"`
                // `CustomMessage` (§3e: "extension-injected... sent to the LLM
                // as a user message") is the closest existing, non-fabricated
                // slot pi's own parser already understands, so this
                // re-materializes the record there instead of silently
                // dropping it — the exact allowance push_claude_system's own
                // doc comment describes in reverse. `customType` is a
                // supercode-namespaced marker (`push_pi_custom_common`
                // recognizes it on reload and restores `Role::System` +
                // `metadata["systemSubtype"]`, exactly like `push_claude_system`
                // produced in the first place); a real pi customType never
                // collides with this name. `details.claude_system_subtype`
                // carries the original subtype losslessly through the pi leg
                // (mirrors `write_codex_records`'s `claude_system_subtype`
                // metadata channel on the Codex leg, PARITY-6 dev/02). Content
                // is never fabricated — only emitted when non-empty.
                Role::System => {
                    let content = msg.content.clone().unwrap_or_default();
                    if content.trim().is_empty() {
                        continue;
                    }
                    let subtype = msg
                        .metadata
                        .get("systemSubtype")
                        .cloned()
                        .unwrap_or_else(|| "local_command".to_string());
                    serde_json::json!({
                        "type": "message",
                        "id": id,
                        "parentId": parent,
                        "timestamp": msg_timestamp_or_synth(msg),
                        "message": {
                            "role": "custom",
                            "customType": PI_CLAUDE_SYSTEM_CUSTOM_TYPE,
                            "content": content,
                            "display": true,
                            "details": {"claude_system_subtype": subtype},
                            "timestamp": msg_pi_native_timestamp_ms(msg),
                        },
                    })
                }
                Role::User => serde_json::json!({
                    "type": "message",
                    "id": id,
                    "parentId": parent,
                    "timestamp": msg_timestamp_or_synth(msg),
                    "message": {
                        "role": "user",
                        "content": pi_content_value(msg),
                        "timestamp": msg_pi_native_timestamp_ms(msg),
                    },
                }),
                Role::Assistant => {
                    let api = msg
                        .metadata
                        .get("pi_api")
                        .cloned()
                        .unwrap_or_else(|| "anthropic-messages".to_string());
                    let provider = msg
                        .metadata
                        .get("pi_provider")
                        .cloned()
                        .unwrap_or_else(|| "anthropic".to_string());
                    let model = self
                        .meta
                        .model
                        .clone()
                        .unwrap_or_else(|| "unknown".to_string());
                    let usage = msg
                        .metadata
                        .get("pi_usage")
                        .and_then(|s| serde_json::from_str::<Value>(s).ok())
                        .unwrap_or_else(default_pi_usage);
                    let stop_reason = msg
                        .metadata
                        .get("pi_stop_reason")
                        .cloned()
                        .unwrap_or_else(|| "stop".to_string());
                    serde_json::json!({
                        "type": "message",
                        "id": id,
                        "parentId": parent,
                        "timestamp": msg_timestamp_or_synth(msg),
                        "message": {
                            "role": "assistant",
                            "content": pi_assistant_content_value(msg),
                            "api": api,
                            "provider": provider,
                            "model": model,
                            "usage": usage,
                            "stopReason": stop_reason,
                            "timestamp": msg_pi_native_timestamp_ms(msg),
                        },
                    })
                }
                Role::Tool => serde_json::json!({
                    "type": "message",
                    "id": id,
                    "parentId": parent,
                    "timestamp": msg_timestamp_or_synth(msg),
                    "message": {
                        "role": "toolResult",
                        "toolCallId": msg.tool_call_id.clone().unwrap_or_default(),
                        "toolName": msg.name.as_deref().or_else(|| {
                            msg.tool_call_id
                                .as_deref()
                                .and_then(|id| paired_tool_names.get(id).map(String::as_str))
                        }).unwrap_or_default(),
                        "content": pi_content_value(msg),
                        "isError": is_tool_error_flag(msg),
                        "timestamp": msg_pi_native_timestamp_ms(msg),
                    },
                }),
            };
            if msg.role == Role::Tool && crate::tool_outcome(msg) == crate::ToolOutcome::Unknown {
                entry[SUPERCODE_TOOL_OUTCOME_KEY] = Value::String("unknown".to_string());
            }
            set_grok_message_extension(&mut entry, self.meta.source, msg);
            push_jsonl(out, &entry);
            parent = Some(id);
            if msg.role == Role::Tool {
                if let Some(call_id) = msg.tool_call_id.as_deref() {
                    paired_tool_names.remove(call_id);
                }
            }
        }
    }

    /// A12-style splice for pi (§1.1/§4.2): replay the imported `raw` prefix
    /// **verbatim** — the header line always has its `version` normalized to
    /// 3 (§1.3: pi rewrites any pre-v3 file in place on load, destroying
    /// byte-identity, so the writer never re-emits one; this intentionally
    /// breaks byte-identity for pre-v3 originals only, the accepted
    /// trade-off) and its `id` overridden when `session_id` is `Some`. Every
    /// other raw line — every entry — is untouched (pi repeats the session
    /// id on no other line, `pi-fields.md` §1). Then synthesizes `message`
    /// entries only for the appended tail via [`Self::write_pi_entries`],
    /// chaining from the last entry `id` found in the raw prefix.
    fn to_pi_jsonl_spliced(&self, session_id: Option<&str>) -> Result<String> {
        let (raw_prefix_len, message_prefix_len) = self.spliced_prefix_lens();
        if raw_prefix_len == 0 {
            return Ok(self.to_pi_jsonl());
        }

        let mut out = String::new();
        let mut used_ids: HashSet<String> = HashSet::new();
        let mut leaf: Option<String> = None;
        for (i, line) in self.raw[..raw_prefix_len].iter().enumerate() {
            if i == 0 {
                if let Ok(v) = serde_json::from_str::<Value>(line) {
                    if v.get("type").and_then(Value::as_str) == Some("session") {
                        let needs_v3 = v.get("version").and_then(Value::as_u64) != Some(3);
                        // Only reparse+reserialize the header when something
                        // actually needs to change — this crate doesn't
                        // enable serde_json's `preserve_order`, so a no-op
                        // round-trip through `Value` would reorder keys
                        // alphabetically and silently break the "prefix
                        // bytes unchanged" splice guarantee for the (common)
                        // already-v3, no-override case.
                        if needs_v3 || session_id.is_some() {
                            let mut v = v;
                            v["version"] = serde_json::json!(3);
                            if let Some(new_id) = session_id {
                                v["id"] = Value::String(new_id.to_string());
                            }
                            out.push_str(&v.to_string());
                            out.push('\n');
                            continue;
                        }
                    }
                }
            }
            out.push_str(line);
            out.push('\n');
            if let Ok(v) = serde_json::from_str::<Value>(line) {
                if let Some(id) = v.get("id").and_then(Value::as_str) {
                    used_ids.insert(id.to_string());
                    leaf = Some(id.to_string());
                }
            }
        }

        let mut counter: u64 = 0;
        self.write_pi_entries(
            &mut out,
            &self.messages[message_prefix_len..],
            leaf,
            &mut used_ids,
            &mut counter,
        );
        Ok(out)
    }

    // ---- Grok writers -----------------------------------------------

    /// Synthesize Grok's resumable `chat_history.jsonl` transcript.
    fn to_grok_jsonl(&self) -> String {
        let mut out = String::new();
        if let Some(prompt) = self
            .meta
            .system_prompt
            .as_deref()
            .filter(|prompt| !prompt.is_empty())
        {
            push_jsonl(
                &mut out,
                &serde_json::json!({
                    "type": "system",
                    "content": prompt,
                }),
            );
        }
        self.write_grok_records(&mut out, &self.messages);
        if let Some(extension) = codex_provenance_envelope(&self.meta) {
            if out.is_empty() {
                push_jsonl(
                    &mut out,
                    &serde_json::json!({"type": "system", "content": ""}),
                );
            }
            inject_first_jsonl_top_level(&mut out, SUPERCODE_CODEX_PROVENANCE_KEY, extension);
        }
        out
    }

    fn write_grok_records(&self, out: &mut String, messages: &[ChatMessage]) {
        for message in messages {
            if is_replay_excluded(message) {
                continue;
            }
            let mut value = match message.role {
                Role::System => serde_json::json!({
                    "type": "user",
                    "content": [{"type": "text", "text": message.content.clone().unwrap_or_default()}],
                    "synthetic_reason": "supercode_system_event",
                }),
                Role::User => {
                    let mut value = serde_json::json!({
                        "type": "user",
                        "content": [{"type": "text", "text": message.content.clone().unwrap_or_default()}],
                    });
                    if let Some(object) = value.as_object_mut() {
                        for (metadata, field) in [
                            ("grok_prompt_index", "prompt_index"),
                            ("grok_prior_turn_interrupt", "prior_turn_interrupt"),
                            ("grok_synthetic_reason", "synthetic_reason"),
                        ] {
                            if let Some(raw) = message.metadata.get(metadata) {
                                object.insert(
                                    field.to_string(),
                                    serde_json::from_str(raw)
                                        .unwrap_or_else(|_| Value::String(raw.clone())),
                                );
                            }
                        }
                    }
                    value
                }
                Role::Assistant => {
                    let calls = message
                        .tool_calls()
                        .iter()
                        .map(|call| {
                            serde_json::json!({
                                "id": call.id,
                                "name": call.function.name,
                                "arguments": call.function.arguments,
                            })
                        })
                        .collect::<Vec<_>>();
                    let mut value = serde_json::json!({
                        "type": "assistant",
                        "content": message.content.clone().unwrap_or_default(),
                        "tool_calls": calls,
                        "model_id": message.metadata.get("grok_model_id")
                            .or(self.meta.model.as_ref())
                            .cloned()
                            .unwrap_or_else(|| "unknown".to_string()),
                    });
                    if let Some(object) = value.as_object_mut() {
                        for (metadata, field) in [
                            ("grok_model_fingerprint", "model_fingerprint"),
                            ("grok_reasoning_effort", "reasoning_effort"),
                        ] {
                            if let Some(raw) = message.metadata.get(metadata) {
                                object.insert(field.to_string(), Value::String(raw.clone()));
                            }
                        }
                    }
                    value
                }
                Role::Tool => serde_json::json!({
                    "type": "tool_result",
                    "tool_call_id": message.tool_call_id.clone().unwrap_or_default(),
                    "content": message.content.clone().unwrap_or_default(),
                }),
            };
            set_grok_target_message_extension(&mut value, message);
            push_jsonl(out, &value);
        }
    }

    /// Replay a Grok imported prefix verbatim, then append newly-created
    /// canonical turns. Grok stores the session id in the directory name,
    /// not in transcript records, so there is no in-file id to rewrite.
    fn to_grok_jsonl_spliced(&self) -> String {
        let (raw_prefix_len, message_prefix_len) = self.spliced_prefix_lens();
        if raw_prefix_len == 0 {
            return self.to_grok_jsonl();
        }
        let mut out = String::new();
        for line in &self.raw[..raw_prefix_len] {
            out.push_str(line);
            out.push('\n');
        }
        self.write_grok_records(&mut out, &self.messages[message_prefix_len..]);
        out
    }

    // ---- Gemini writers ---------------------------------------------

    fn to_gemini_jsonl(&self) -> String {
        let mut out = String::new();
        self.write_gemini_header(&mut out, self.meta.session_id.as_deref());
        self.write_gemini_records(&mut out, &self.messages);
        push_jsonl(
            &mut out,
            &serde_json::json!({
                "$set": {"lastUpdated": SYNTH_TS}
            }),
        );
        out
    }

    fn write_gemini_header(&self, out: &mut String, session_id: Option<&str>) {
        push_jsonl(
            out,
            &serde_json::json!({
                "sessionId": session_id.unwrap_or("supercode-gemini-session"),
                "projectHash": self.meta.lineage.get("gemini_project_hash")
                    .cloned().unwrap_or_else(|| "supercode".to_string()),
                "startTime": self.meta.lineage.get("created_at")
                    .cloned().unwrap_or_else(|| SYNTH_TS.to_string()),
                "lastUpdated": self.meta.lineage.get("updated_at")
                    .cloned().unwrap_or_else(|| SYNTH_TS.to_string()),
                "kind": self.meta.lineage.get("gemini_session_kind")
                    .cloned().unwrap_or_else(|| "main".to_string()),
            }),
        );
    }

    fn write_gemini_records(&self, out: &mut String, messages: &[ChatMessage]) {
        let mut call_names = HashMap::new();
        for (index, message) in messages.iter().enumerate() {
            if is_replay_excluded(message) {
                continue;
            }
            let timestamp = message
                .metadata
                .get("timestamp")
                .cloned()
                .unwrap_or_else(|| SYNTH_TS.to_string());
            match message.role {
                Role::System | Role::User => {
                    let mut parts = Vec::new();
                    let text = message.content.clone().or_else(|| {
                        message.content_parts.as_ref().and_then(|parts| {
                            let text = parts
                                .iter()
                                .filter_map(|part| part.get("text").and_then(Value::as_str))
                                .collect::<Vec<_>>()
                                .join(" ");
                            (!text.is_empty()).then_some(text)
                        })
                    });
                    if let Some(text) = text {
                        let text = if message.role == Role::System {
                            format!("[System] {text}")
                        } else {
                            text
                        };
                        parts.push(serde_json::json!({"text": text}));
                    }
                    if let Some(content_parts) = &message.content_parts {
                        for part in content_parts {
                            let Some(url) = part
                                .get("image_url")
                                .and_then(|value| value.get("url"))
                                .and_then(Value::as_str)
                            else {
                                continue;
                            };
                            let Some(rest) = url.strip_prefix("data:") else {
                                continue;
                            };
                            let Some((media_type, data)) = rest.split_once(";base64,") else {
                                continue;
                            };
                            parts.push(serde_json::json!({
                                "inlineData": {"mimeType": media_type, "data": data}
                            }));
                        }
                    }
                    if !parts.is_empty() {
                        let mut value = serde_json::json!({
                            "id": format!("supercode-user-{index}"),
                            "timestamp": timestamp,
                            "type": "user",
                            "content": parts,
                        });
                        set_gemini_message_extension(&mut value, message);
                        push_jsonl(out, &value);
                    }
                }
                Role::Assistant => {
                    let mut tool_calls = Vec::new();
                    for call in message.tool_calls() {
                        call_names.insert(call.id.clone(), call.function.name.clone());
                        let args = serde_json::from_str::<Value>(&call.function.arguments)
                            .unwrap_or_else(|_| Value::String(call.function.arguments.clone()));
                        tool_calls.push(serde_json::json!({
                            "id": call.id,
                            "name": call.function.name,
                            "args": args,
                        }));
                    }
                    let mut value = serde_json::json!({
                        "id": format!("supercode-gemini-{index}"),
                        "timestamp": timestamp,
                        "type": "gemini",
                        "content": message.content.clone().unwrap_or_default(),
                        "model": message.metadata.get("gemini_model")
                            .or(self.meta.model.as_ref())
                            .cloned().unwrap_or_else(|| "unknown".to_string()),
                    });
                    if !tool_calls.is_empty() {
                        value["toolCalls"] = Value::Array(tool_calls);
                    }
                    if let Some(thoughts) = message.metadata.get("gemini_thoughts") {
                        value["thoughts"] = serde_json::from_str(thoughts)
                            .unwrap_or_else(|_| Value::String(thoughts.clone()));
                    }
                    set_gemini_message_extension(&mut value, message);
                    push_jsonl(out, &value);
                }
                Role::Tool => {
                    let id = message.tool_call_id.clone().unwrap_or_default();
                    let name = message
                        .name
                        .clone()
                        .or_else(|| call_names.get(&id).cloned())
                        .unwrap_or_else(|| "tool".to_string());
                    let output = message.content.clone().unwrap_or_else(|| {
                        message
                            .content_parts
                            .as_ref()
                            .map(|parts| Value::Array(parts.clone()))
                            .map(|value| value.to_string())
                            .unwrap_or_default()
                    });
                    let mut value = serde_json::json!({
                        "id": format!("supercode-tool-{index}"),
                        "timestamp": timestamp,
                        "type": "user",
                        "content": [{
                            "functionResponse": {
                                "id": id,
                                "name": name,
                                "response": {"output": output}
                            }
                        }],
                    });
                    set_gemini_message_extension(&mut value, message);
                    push_jsonl(out, &value);
                }
            }
        }
    }

    fn to_gemini_jsonl_spliced(&self, session_id: Option<&str>) -> String {
        let (raw_prefix_len, message_prefix_len) = self.spliced_prefix_lens();
        if raw_prefix_len == 0 {
            let mut out = String::new();
            self.write_gemini_header(&mut out, session_id.or(self.meta.session_id.as_deref()));
            self.write_gemini_records(&mut out, &self.messages);
            return out;
        }
        let mut out = String::new();
        for (index, line) in self.raw[..raw_prefix_len].iter().enumerate() {
            if index == 0 && session_id.is_some() {
                if let Ok(mut value) = serde_json::from_str::<Value>(line) {
                    if value.get("type").is_none() && value.get("sessionId").is_some() {
                        value["sessionId"] =
                            Value::String(session_id.unwrap_or_default().to_string());
                        push_jsonl(&mut out, &value);
                        continue;
                    }
                }
            }
            out.push_str(line);
            out.push('\n');
        }
        self.write_gemini_records(&mut out, &self.messages[message_prefix_len..]);
        out
    }

    // ---- Goose writers ----------------------------------------------

    fn to_goose_json(&self) -> String {
        if self.meta.source == SessionSource::Goose
            && !self.raw.is_empty()
            && self.imported_message_count == Some(self.messages.len())
        {
            return join_lines_verbatim(&self.raw, self.raw_trailing_newline);
        }
        self.synthesized_goose_document(None, &self.messages)
    }

    fn to_goose_json_spliced(&self, session_id: Option<&str>) -> String {
        let message_prefix_len = self
            .imported_message_count
            .unwrap_or(self.messages.len())
            .min(self.messages.len());
        if self.meta.source == SessionSource::Goose && !self.raw.is_empty() {
            if session_id.is_none() && message_prefix_len == self.messages.len() {
                return join_lines_verbatim(&self.raw, self.raw_trailing_newline);
            }
            let source = join_lines_verbatim(&self.raw, self.raw_trailing_newline);
            if let Ok(mut document) = serde_json::from_str::<Value>(&source) {
                if let Some(session_id) = session_id {
                    document["id"] = Value::String(session_id.to_string());
                }
                let appended = self.goose_conversation(&self.messages[message_prefix_len..]);
                if let Some(conversation) = document
                    .get_mut("conversation")
                    .and_then(Value::as_array_mut)
                {
                    conversation.extend(appended);
                    document["message_count"] = Value::from(conversation.len());
                }
                return serde_json::to_string_pretty(&document).unwrap_or_else(|_| {
                    self.synthesized_goose_document(session_id, &self.messages)
                });
            }
        }
        self.synthesized_goose_document(session_id, &self.messages)
    }

    fn synthesized_goose_document(
        &self,
        session_id: Option<&str>,
        messages: &[ChatMessage],
    ) -> String {
        let mut document = self
            .meta
            .goose_header
            .clone()
            .or_else(|| {
                self.messages.iter().find_map(|message| {
                    message
                        .metadata
                        .get("goose_session_header")
                        .and_then(|value| serde_json::from_str(value).ok())
                })
            })
            .unwrap_or_else(|| {
                serde_json::json!({
                    "id": "supercode-goose-session",
                    "working_dir": self.cwd_string(),
                    "name": "supercode export",
                    "user_set_name": false,
                    "session_type": "user",
                    "created_at": SYNTH_TS,
                    "updated_at": SYNTH_TS,
                    "extension_data": {},
                    "usage": {},
                    "accumulated_usage": {},
                    "accumulated_cost": Value::Null,
                    "schedule_id": Value::Null,
                    "recipe": Value::Null,
                    "user_recipe_values": Value::Null,
                    "message_count": 0,
                    "last_message_at": Value::Null,
                    "provider_name": Value::Null,
                    "model_config": Value::Null,
                    "goose_mode": "auto",
                    "archived_at": Value::Null,
                    "project_id": Value::Null,
                    "parent_session_id": Value::Null,
                    "last_message_snippet": Value::Null,
                })
            });
        document["id"] = Value::String(
            session_id
                .map(str::to_string)
                .or_else(|| self.meta.session_id.clone())
                .unwrap_or_else(|| "supercode-goose-session".to_string()),
        );
        document["working_dir"] = Value::String(self.cwd_string());
        let conversation = self.goose_conversation(messages);
        document["message_count"] = Value::from(conversation.len());
        document["conversation"] = Value::Array(conversation);
        serde_json::to_string_pretty(&document).unwrap_or_else(|_| "{}".to_string())
    }

    fn goose_conversation(&self, messages: &[ChatMessage]) -> Vec<Value> {
        let mut out = Vec::new();
        let mut last_native_index: Option<String> = None;
        let mut tool_names = HashMap::<String, String>::new();
        for (index, message) in messages.iter().enumerate() {
            if is_replay_excluded(message) {
                continue;
            }
            if let Some(native_index) = message.metadata.get("goose_native_index") {
                if last_native_index.as_ref() == Some(native_index) {
                    continue;
                }
                last_native_index = Some(native_index.clone());
                if let Some(native) = message
                    .metadata
                    .get("goose_native_message")
                    .and_then(|value| serde_json::from_str::<Value>(value).ok())
                {
                    out.push(native);
                    continue;
                }
            } else {
                last_native_index = None;
            }

            for call in message.tool_calls() {
                tool_names.insert(call.id.clone(), call.function.name.clone());
            }
            let created = message
                .metadata
                .get("goose_created")
                .and_then(|value| value.parse::<i64>().ok())
                .unwrap_or(SYNTH_TS_MS / 1000 + index as i64);
            let role = match message.role {
                Role::Assistant => "assistant",
                _ => "user",
            };
            let mut content = Vec::new();
            // A Goose tool response carries its output inside
            // `toolResult.value.content`; duplicating it as a sibling text
            // block makes the loader normalize one Tool message twice.
            if message.role != Role::Tool {
                if let Some(text) = &message.content {
                    let text = if message.role == Role::System {
                        format!("[System] {text}")
                    } else {
                        text.clone()
                    };
                    content.push(serde_json::json!({"type": "text", "text": text}));
                }
                if let Some(parts) = &message.content_parts {
                    for part in parts {
                        if let Some(text) = part.get("text").and_then(Value::as_str) {
                            if message.content.is_none() {
                                content.push(serde_json::json!({"type": "text", "text": text}));
                            }
                        }
                        let Some(url) = part
                            .get("image_url")
                            .and_then(|image| image.get("url"))
                            .and_then(Value::as_str)
                        else {
                            continue;
                        };
                        let Some(data) = url.strip_prefix("data:") else {
                            continue;
                        };
                        let Some((media_type, data)) = data.split_once(";base64,") else {
                            continue;
                        };
                        content.push(serde_json::json!({
                            "type": "image",
                            "data": data,
                            "mimeType": media_type,
                        }));
                    }
                }
            }
            for call in message.tool_calls() {
                let arguments = serde_json::from_str::<Value>(&call.function.arguments)
                    .unwrap_or_else(|_| Value::String(call.function.arguments.clone()));
                content.push(serde_json::json!({
                    "type": "toolRequest",
                    "id": call.id,
                    "toolCall": {
                        "status": "success",
                        "value": {"name": call.function.name, "arguments": arguments}
                    }
                }));
            }
            if message.role == Role::Tool {
                let id = message.tool_call_id.clone().unwrap_or_default();
                let output = message.content.clone().unwrap_or_else(|| {
                    message
                        .content_parts
                        .as_ref()
                        .map(|parts| Value::Array(parts.clone()).to_string())
                        .unwrap_or_default()
                });
                let tool_result = if crate::is_tool_error(message) {
                    serde_json::json!({"status": "error", "error": output})
                } else {
                    serde_json::json!({
                        "status": "success",
                        "value": {
                            "content": [{"type": "text", "text": output}],
                            "isError": false
                        }
                    })
                };
                content.push(serde_json::json!({
                    "type": "toolResponse",
                    "id": id,
                    "toolResult": tool_result,
                    "metadata": {
                        "toolName": message.name.as_ref()
                            .or_else(|| tool_names.get(&id))
                    }
                }));
            }
            if content.is_empty() {
                continue;
            }
            let metadata = message
                .metadata
                .get("goose_metadata")
                .and_then(|value| serde_json::from_str::<Value>(value).ok())
                .unwrap_or_else(|| {
                    serde_json::json!({
                        "userVisible": true,
                        "agentVisible": true
                    })
                });
            let mut native = serde_json::json!({
                "id": message.metadata.get("goose_message_id")
                    .cloned().unwrap_or_else(|| format!("supercode-goose-{index}")),
                "role": role,
                "created": created,
                "content": content,
                "metadata": metadata,
            });
            // Goose tolerates unknown top-level fields on a conversation
            // message. Always carry the canonical envelope when Goose is
            // the TARGET so metadata absent from Goose's stock schema can
            // make a later Goose -> source round trip without residue.
            set_grok_target_message_extension(&mut native, message);
            out.push(native);
        }
        out
    }

    // ---- OpenCode writers ---------------------------------------------

    /// Re-derive the structured OpenCode records (`SessionInfo`, an ordered
    /// `(message value, part values)` list) directly from `self.raw`'s
    /// envelope lines — the same classification
    /// [`Self::from_opencode_str`] performs, but returning the raw VALUES
    /// rather than canonical `ChatMessage`s. Used by
    /// [`Self::to_opencode_jsonl_spliced`] (§4.2 S5: the imported prefix
    /// must be VALUE-EQUAL at its position, not re-synthesized from lossy
    /// `messages`) and [`Self::to_opencode_direct_write`] (S5: the fidelity
    /// path for excess keys/timestamps/side-records `opencode import`
    /// cannot restore).
    fn opencode_records_from_raw(&self) -> (Option<Value>, Vec<(Value, Vec<Value>)>) {
        let mut session_info: Option<Value> = None;
        let mut msg_order: Vec<String> = Vec::new();
        let mut msg_values: HashMap<String, Value> = HashMap::new();
        let mut msg_parts: HashMap<String, Vec<Value>> = HashMap::new();
        for line in &self.raw {
            let Ok(env) = serde_json::from_str::<Value>(line) else {
                continue;
            };
            let Some(key) = env.get("key").and_then(Value::as_array) else {
                continue;
            };
            let value = env.get("value").cloned().unwrap_or(Value::Null);
            match key.first().and_then(Value::as_str) {
                Some("session") => session_info = Some(value),
                Some("message") => {
                    if let Some(id) = value.get("id").and_then(Value::as_str) {
                        if !msg_values.contains_key(id) {
                            msg_order.push(id.to_string());
                        }
                        msg_values.insert(id.to_string(), value);
                    }
                }
                Some("part") => {
                    if let Some(mid) = value.get("messageID").and_then(Value::as_str) {
                        msg_parts.entry(mid.to_string()).or_default().push(value);
                    }
                }
                _ => {}
            }
        }
        let mut ordered: Vec<(String, i64)> = msg_order
            .iter()
            .map(|id| {
                let tc = msg_values
                    .get(id)
                    .and_then(|v| v.get("time"))
                    .and_then(|t| t.get("created"))
                    .and_then(Value::as_i64)
                    .unwrap_or(0);
                (id.clone(), tc)
            })
            .collect();
        ordered.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
        let mut out = Vec::new();
        for (id, _) in ordered {
            let mut parts = msg_parts.remove(&id).unwrap_or_default();
            parts.sort_by(|a, b| {
                let ai = a.get("id").and_then(Value::as_str).unwrap_or("");
                let bi = b.get("id").and_then(Value::as_str).unwrap_or("");
                ai.cmp(bi)
            });
            if let Some(v) = msg_values.remove(&id) {
                out.push((v, parts));
            }
        }
        (session_info, out)
    }

    /// Best-effort `SessionInfo` synthesized from `self.meta` — used when no
    /// `raw` prefix exists to replay (a fresh/cross-format-converted
    /// session). T3 tier: only what `SessionMeta` carries survives.
    fn synthesized_opencode_info(&self) -> Value {
        let id = self
            .meta
            .session_id
            .clone()
            .unwrap_or_else(|| "ses_supercode00000000000001".to_string());
        let mut info = serde_json::json!({
            "id": id,
            "projectID": self.meta.lineage.get("projectID").cloned().unwrap_or_else(|| "global".to_string()),
            // OpenCode 1.2.15's import path writes this into a NOT NULL
            // SQLite column. Preserve a real source slug when available and
            // mint a stable, human-readable fallback for foreign sessions.
            "slug": self.meta.lineage.get("slug").cloned().unwrap_or_else(|| "supercode-export".to_string()),
            "directory": self.cwd_string(),
            "title": "supercode export",
            "version": env!("CARGO_PKG_VERSION"),
            "time": {"created": SYNTH_TS_MS, "updated": SYNTH_TS_MS},
        });
        if let Some(agent) = &self.meta.agent_id {
            info["agent"] = Value::String(agent.clone());
        }
        if let Some(model) = &self.meta.model {
            if let Some((provider, mid)) = model.split_once('/') {
                info["model"] = serde_json::json!({"providerID": provider, "id": mid});
            }
        }
        if let Some(parent) = self.meta.lineage.get("parent_session_id") {
            info["parentID"] = Value::String(parent.clone());
        }
        // D7: carry a captured Claude `fork-context-ref` through the
        // OpenCode hop too, exactly like the Codex (`claude_fork_context_ref`
        // on `session_meta.payload`) and Pi (`claude_fork_context_ref` on
        // the `session` header) hops already do — namespaced so real
        // OpenCode tooling ignores it, and `capture_opencode_session_info`
        // reads this same key back on import so a Claude -> OpenCode ->
        // Claude round trip doesn't silently lose fork lineage either.
        //
        // DOCUMENTED LIMITATION (D7 caveat, per the frozen interop spec —
        // `interop-research-spec@f168465`, `opencode-pi-spec.md` ~line 123):
        // this `claude_fork_context_ref` key on `SessionInfo` survives
        // supercode's OWN round-trip (write here, read back by
        // `capture_opencode_session_info` above) but NOT a real upstream
        // `opencode import` ingestion — that path decodes with
        // `Schema.decodeUnknownSync`, which strips any key its schema
        // doesn't declare. The direct-file/DB fallback (bypassing
        // `opencode import` entirely) is the per-spec fidelity path for
        // this lineage to actually reach real OpenCode.
        if let Some(raw) = self.meta.lineage.get("claude_fork_context_ref_raw") {
            info["claude_fork_context_ref"] =
                serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.clone()));
        }
        if let Some(extension) = codex_provenance_envelope(&self.meta) {
            info[SUPERCODE_CODEX_PROVENANCE_KEY] = extension;
        }
        info
    }

    /// OpenCode uses `SessionInfo.time.updated` for recency selection. Any
    /// synthesized continuation message therefore has to advance the
    /// session clock along with its own `time.created` value.
    fn touch_opencode_session_updated(info: &mut Value, timestamp: i64) {
        if !info.get("time").is_some_and(Value::is_object) {
            info["time"] = serde_json::json!({});
        }
        info["time"]["updated"] = serde_json::json!(timestamp);
    }

    /// Synthesize opencode `{info, parts}` message objects for `messages`
    /// (T3 tier — full synthesis from canonical `ChatMessage`s, the inverse
    /// of [`push_opencode_user`]/[`push_opencode_assistant`]), appending
    /// them to `out`. Every `Tool` message anywhere in `messages` is folded
    /// back into its call's assistant `tool` part (match by
    /// `tool_call_id`/`callID`, pairing repeated ids by occurrence over the
    /// whole slice)
    /// — the exact inverse of the loader's call/result split. This is a
    /// GLOBAL match, not a scan of the contiguous run of `Tool` messages
    /// immediately following each assistant: two-or-more consecutive
    /// assistant-with-tool-call messages before their results (streamed /
    /// parallel tool calls) otherwise strand the earlier call's real result
    /// behind a later assistant message, silently downgrading it to
    /// "pending" and losing the recorded output. Skips [`is_replay_excluded`]
    /// messages exactly like every other writer.
    fn append_synthesized_opencode_messages(
        &self,
        out: &mut Vec<Value>,
        messages: &[ChatMessage],
        session_id: &str,
        counter: &mut u64,
        timestamp_cursor: &mut i64,
    ) -> Result<()> {
        // Pair each Tool message to its call GLOBALLY by `tool_call_id`,
        // over the ENTIRE slice being processed, rather than by scanning
        // only the contiguous run of `Role::Tool` messages immediately
        // following a given assistant message. Two-or-more consecutive
        // assistant-with-tool-call messages before their results (streamed
        // / parallel tool calls — extremely common in real Claude Code and
        // Codex sessions) break the contiguous-run assumption: the first
        // assistant's own result(s) land AFTER a second assistant message,
        // not immediately after the first, so a contiguous scan starting
        // right after the first assistant finds nothing and silently drops
        // its real tool output into the `None => "pending"` branch below.
        // A single `id -> result` map is still insufficient: long real
        // sessions can reuse provider call ids. Last-write-wins then attaches
        // the final output to every earlier occurrence. Collect calls and
        // results independently and zip their occurrences in transcript
        // order, giving every concrete call position its own result.
        let mut calls_by_id: HashMap<&str, Vec<(usize, usize)>> = HashMap::new();
        let mut results_by_id: HashMap<&str, Vec<(usize, &ChatMessage)>> = HashMap::new();
        for (message_index, message) in messages.iter().enumerate() {
            if message.role == Role::Assistant {
                for (tool_index, call) in message.tool_calls().iter().enumerate() {
                    calls_by_id
                        .entry(call.id.as_str())
                        .or_default()
                        .push((message_index, tool_index));
                }
            } else if message.role == Role::Tool {
                if let Some(id) = &message.tool_call_id {
                    results_by_id
                        .entry(id.as_str())
                        .or_default()
                        .push((message_index, message));
                }
            }
        }
        let mut paired_results: HashMap<(usize, usize), (usize, &ChatMessage)> = HashMap::new();
        for (id, calls) in calls_by_id {
            let Some(results) = results_by_id.get(id) else {
                continue;
            };
            for (call_position, result) in calls.into_iter().zip(results.iter().copied()) {
                paired_results.insert(call_position, result);
            }
        }
        let mut i = 0;
        while i < messages.len() {
            let msg = &messages[i];
            if is_replay_excluded(msg) {
                i += 1;
                continue;
            }
            match msg.role {
                // B4: opencode V1 has no session-level system-PROMPT slot
                // either — `User.system` is a per-turn system-PROMPT
                // OVERRIDE (§2.1), a different thing from a content-bearing
                // `Role::System` message loaded from a real Claude `type:
                // "system"` record (`push_claude_system`'s keep-listed
                // subtypes). Stuffing real transcript content into
                // `User.system` would be a genuine misuse — it overrides the
                // replayed system prompt, not just annotates a turn — so
                // this instead reuses opencode's own `text` part `synthetic`
                // flag (§3.1: "injected by opencode, not typed by user"),
                // which is EXACTLY the right existing, non-fabricated
                // semantic for "system-originated content presented as a
                // user turn": a dedicated `User` message with one
                // `synthetic: true` text part, tagged with a
                // supercode-namespaced part-`metadata` key so
                // `opencode_claude_system_subtype`/`push_opencode_claude_system`
                // recognize it on reload and restore `Role::System` +
                // `metadata["systemSubtype"]` rather than treating it as a
                // real user turn. Content is never fabricated — only
                // emitted when non-empty.
                Role::System => {
                    let content = msg.content.clone().unwrap_or_default();
                    if content.trim().is_empty() {
                        i += 1;
                        continue;
                    }
                    let subtype = msg
                        .metadata
                        .get("systemSubtype")
                        .cloned()
                        .unwrap_or_else(|| "local_command".to_string());
                    let msg_id = opencode_fresh_id("msg", counter);
                    let part_id = opencode_fresh_id("prt", counter);
                    let timestamp = opencode_message_timestamp(msg, timestamp_cursor)?;
                    let mut info = serde_json::json!({
                        "id": msg_id,
                        "sessionID": session_id,
                        "role": "user",
                        "time": {"created": timestamp},
                    });
                    info[OPENCODE_SUPERCODE_MESSAGE_POSITION] = serde_json::json!(i);
                    let parts = vec![serde_json::json!({
                        "id": part_id,
                        "sessionID": session_id,
                        "messageID": msg_id,
                        "type": "text",
                        "text": content,
                        "synthetic": true,
                        "metadata": {OPENCODE_CLAUDE_SYSTEM_SUBTYPE_KEY: subtype},
                    })];
                    out.push(serde_json::json!({"info": info, "parts": parts}));
                    i += 1;
                }
                Role::User => {
                    let msg_id = opencode_fresh_id("msg", counter);
                    let parts = opencode_user_parts_from_message(msg, &msg_id, session_id, counter);
                    let timestamp = opencode_message_timestamp(msg, timestamp_cursor)?;
                    let mut info = serde_json::json!({
                        "id": msg_id,
                        "sessionID": session_id,
                        "role": "user",
                        "time": {"created": timestamp},
                    });
                    info[OPENCODE_SUPERCODE_MESSAGE_POSITION] = serde_json::json!(i);
                    opencode_restore_agent_model_fields(
                        &mut info, msg, /* is_assistant */ false,
                    );
                    set_grok_message_extension(&mut info, self.meta.source, msg);
                    out.push(serde_json::json!({
                        "info": info,
                        "parts": parts,
                    }));
                    i += 1;
                }
                Role::Assistant => {
                    let msg_id = opencode_fresh_id("msg", counter);
                    let timestamp = opencode_message_timestamp(msg, timestamp_cursor)?;
                    let mut parts = Vec::new();
                    if let Some(thinking) = msg.metadata.get("thinking") {
                        let mut part = serde_json::json!({
                            "id": opencode_fresh_id("prt", counter),
                            "sessionID": session_id,
                            "messageID": msg_id,
                            "type": "reasoning",
                            "text": thinking,
                            // Required by OpenCode V1's native reasoning
                            // schema. A synthesized part has no distinct
                            // stream start/end, so the source message clock
                            // is the honest zero-duration span.
                            "time": {"start": timestamp, "end": timestamp},
                        });
                        if let Some(signature) = msg.metadata.get("thinking_signature") {
                            part["metadata"] = serde_json::json!({
                                "anthropic": {"signature": signature},
                            });
                        }
                        parts.push(part);
                    }
                    if let Some(t) = &msg.content {
                        if !t.is_empty() {
                            parts.push(serde_json::json!({
                                "id": opencode_fresh_id("prt", counter),
                                "sessionID": session_id,
                                "messageID": msg_id,
                                "type": "text",
                                "text": t,
                            }));
                        }
                    }
                    // Fold each tool call's result back into ONE `tool`
                    // part, matched by tool_call_id via the GLOBAL
                    // `all_results` map built above (not a contiguous scan)
                    // — a result may be many messages away when other
                    // assistant turns with their own pending calls
                    // intervene before it appears.
                    for (tool_index, tc) in msg.tool_calls().iter().enumerate() {
                        let input = tc
                            .function
                            .parsed_arguments()
                            .unwrap_or_else(|_| Value::Object(Default::default()));
                        let paired_result = paired_results.get(&(i, tool_index)).copied();
                        let state = match paired_result {
                            Some((_, result)) if crate::is_tool_error(result) => {
                                let result_timestamp =
                                    opencode_message_timestamp(result, timestamp_cursor)?;
                                serde_json::json!({
                                    "status": "error",
                                    "input": input,
                                    "error": result.content.clone().unwrap_or_default(),
                                    "time": {"end": result_timestamp},
                                })
                            }
                            Some((_, result)) => {
                                let result_timestamp =
                                    opencode_message_timestamp(result, timestamp_cursor)?;
                                let mut s = serde_json::json!({
                                    "status": "completed",
                                    "input": input,
                                    "output": result.content.clone().unwrap_or_default(),
                                    "title": tc.function.name,
                                    "time": {"end": result_timestamp},
                                });
                                // PARITY-11 (nested images): the LOADER already
                                // reads a completed tool part's
                                // `state.attachments` back into `content_parts`
                                // (`opencode_file_image_part`, above) — this is
                                // the missing WRITE-side inverse. Without it, a
                                // Claude `tool_result`'s nested image (now
                                // captured into `content_parts` by
                                // `extract_tool_result_content`) reached
                                // `content_parts` on the canonical `ChatMessage`
                                // but was silently dropped again on re-export to
                                // OpenCode, because nothing ever read it back
                                // out. `mime`/`url` shape matches exactly what
                                // `opencode_file_image_part` expects on reload.
                                if let Some(cps) = &result.content_parts {
                                    let atts: Vec<Value> = cps
                                        .iter()
                                        .filter(|p| {
                                            p.get("type").and_then(Value::as_str)
                                                == Some("image_url")
                                        })
                                        .filter_map(|p| {
                                            let url = p
                                                .get("image_url")
                                                .and_then(|u| u.get("url"))
                                                .and_then(Value::as_str)?;
                                            let mime = url
                                                .strip_prefix("data:")
                                                .and_then(|r| r.split_once(','))
                                                .map(|(m, _)| m.trim_end_matches(";base64"))
                                                .unwrap_or("application/octet-stream");
                                            Some(serde_json::json!({
                                                "mime": mime,
                                                "url": url,
                                            }))
                                        })
                                        .collect();
                                    if !atts.is_empty() {
                                        s["attachments"] = Value::Array(atts);
                                    }
                                }
                                s
                            }
                            None => serde_json::json!({"status": "pending", "input": input}),
                        };
                        let mut part = serde_json::json!({
                            "id": opencode_fresh_id("prt", counter),
                            "sessionID": session_id,
                            "messageID": msg_id,
                            "type": "tool",
                            "callID": tc.id,
                            "tool": tc.function.name,
                            "state": state,
                        });
                        if let Some((result_position, _)) = paired_result {
                            part[OPENCODE_SUPERCODE_RESULT_POSITION] =
                                serde_json::json!(result_position);
                        }
                        if paired_result.is_some_and(|(_, result)| {
                            crate::tool_outcome(result) == crate::ToolOutcome::Unknown
                        }) {
                            part[SUPERCODE_TOOL_OUTCOME_KEY] = Value::String("unknown".to_string());
                        }
                        if let Some((_, result)) = paired_result {
                            set_grok_message_extension(&mut part, self.meta.source, result);
                        }
                        parts.push(part);
                    }
                    let mut info = serde_json::json!({
                        "id": msg_id,
                        "sessionID": session_id,
                        "role": "assistant",
                        "time": {"created": timestamp},
                    });
                    info[OPENCODE_SUPERCODE_MESSAGE_POSITION] = serde_json::json!(i);
                    opencode_restore_agent_model_fields(
                        &mut info, msg, /* is_assistant */ true,
                    );
                    set_grok_message_extension(&mut info, self.meta.source, msg);
                    out.push(serde_json::json!({
                        "info": info,
                        "parts": parts,
                    }));
                    i += 1;
                }
                // A Tool message is always folded into its call's assistant
                // `tool` part above (via occurrence-aware global pairing, not
                // positional adjacency), so it never needs its own entry
                // here — just advance past it.
                Role::Tool => i += 1,
            }
        }
        Ok(())
    }

    /// Synthesize a fresh OpenCode export DOCUMENT from the canonical
    /// `messages` (T3 cross-format/full synthesis tier — mirrors
    /// [`Self::to_pi_jsonl`]'s doc comment: this is NOT the value-lossless
    /// native path, which goes through `raw` + `to_native_jsonl(_v2)`
    /// instead). Shape: `{info: SessionInfo, messages: [{info, parts}, …]}`
    /// (§1.2 — the `opencode export`/`import` interchange shape).
    fn to_opencode_jsonl(&self) -> Result<String> {
        let mut info = self.synthesized_opencode_info();
        let ses_id = info
            .get("id")
            .and_then(Value::as_str)
            .unwrap_or("ses_new")
            .to_string();
        let mut messages_json: Vec<Value> = Vec::new();
        let mut counter: u64 = 0;
        let mut timestamp_cursor =
            opencode_max_timestamp(&info).unwrap_or_else(|| SYNTH_TS_MS.saturating_sub(1));
        self.append_synthesized_opencode_messages(
            &mut messages_json,
            &self.messages,
            &ses_id,
            &mut counter,
            &mut timestamp_cursor,
        )?;
        if !messages_json.is_empty() {
            Self::touch_opencode_session_updated(&mut info, timestamp_cursor);
        }
        let doc = serde_json::json!({"info": info, "messages": messages_json});
        Ok(serde_json::to_string_pretty(&doc).unwrap_or_default())
    }

    /// A12-style splice for OpenCode (§1.2/§4.2 point 1, S5): replay the
    /// imported records **value-equal at their position** in the export
    /// doc's `messages[]`/`parts[]` — reconstructed directly from `self.raw`
    /// via [`Self::opencode_records_from_raw`], never re-derived from the
    /// lossy canonical `messages` — then append freshly synthesized
    /// `{info, parts}` objects for the tail via
    /// [`Self::append_synthesized_opencode_messages`]. Unlike the
    /// line-oriented formats' splice, `out` here is a single export
    /// DOCUMENT, not a line stream (§4.2 restates the "prefix verbatim"
    /// assertion accordingly: value-equality at position, not byte
    /// equality of a line range).
    fn to_opencode_jsonl_spliced(&self, session_id: Option<&str>) -> Result<String> {
        if self.raw.is_empty() {
            return self.to_opencode_jsonl();
        }
        let (session_info, records) = self.opencode_records_from_raw();
        let (_, message_prefix_len) = self.spliced_prefix_lens();

        let mut info = session_info.unwrap_or_else(|| self.synthesized_opencode_info());
        if let Some(id) = session_id {
            info["id"] = Value::String(id.to_string());
        }
        let ses_id_for_new = info
            .get("id")
            .and_then(Value::as_str)
            .unwrap_or("ses_new")
            .to_string();

        let mut timestamp_cursor = std::iter::once(opencode_max_timestamp(&info))
            .chain(records.iter().flat_map(|(msg, parts)| {
                std::iter::once(opencode_max_timestamp(msg))
                    .chain(parts.iter().map(opencode_max_timestamp))
            }))
            .flatten()
            .max()
            .unwrap_or_else(|| SYNTH_TS_MS.saturating_sub(1));

        let mut messages_json: Vec<Value> = records
            .into_iter()
            .map(|(msg, parts)| serde_json::json!({"info": msg, "parts": parts}))
            .collect();
        let imported_len = messages_json.len();

        let mut counter: u64 = 0;
        self.append_synthesized_opencode_messages(
            &mut messages_json,
            &self.messages[message_prefix_len..],
            &ses_id_for_new,
            &mut counter,
            &mut timestamp_cursor,
        )?;
        if messages_json.len() > imported_len {
            Self::touch_opencode_session_updated(&mut info, timestamp_cursor);
        }

        let doc = serde_json::json!({"info": info, "messages": messages_json});
        Ok(serde_json::to_string_pretty(&doc).unwrap_or_default())
    }

    /// The **required** direct-write fallback (S5): write the imported
    /// OpenCode records **verbatim** — excess/unknown keys, part-row
    /// timestamps, and `session_diff`/`todo` side-records intact — to a
    /// generation-B JSON-file storage tree
    /// (`docs/interop/opencode-pi-spec.md` §1.2), the fidelity path
    /// `opencode import` cannot provide (S5: import re-decodes through a
    /// strict schema and STRIPS excess keys; inserts part rows without
    /// `time_created`/`time_updated`, so those reset to `Date.now()`; and
    /// has no ingestion path for `session_diff`/`todo` at all).
    ///
    /// Writes the JSON-FILE layout rather than a live SQLite write
    /// specifically to avoid a new `rusqlite`-class dependency on this
    /// build's memory-constrained box (see the build report); `session_diff`
    /// itself is still JSON-written by upstream even on SQLite installs
    /// (§1.3), so this is a real fidelity path, not a fictional one.
    ///
    /// Returns the `storage/session/<projectID>/` directory written to.
    pub fn to_opencode_direct_write(&self, data_root: &Path) -> Result<PathBuf> {
        let (session_info, mut records) = self.opencode_records_from_raw();
        let mut info = session_info.unwrap_or_else(|| self.synthesized_opencode_info());
        let ses_id = info
            .get("id")
            .and_then(Value::as_str)
            .unwrap_or("ses_new")
            .to_string();
        if info.get("id").is_none() {
            info["id"] = Value::String(ses_id.clone());
        }
        let project_id = info
            .get("projectID")
            .and_then(Value::as_str)
            .unwrap_or("global")
            .to_string();

        // Appended tail (messages produced after import): synthesize fresh
        // message/part VALUES via the same T3 synthesis the splice writer
        // uses, so continuation turns get files too. Do this BEFORE creating
        // any directories: timestamp exhaustion must fail atomically rather
        // than leave a partial direct-write tree behind.
        let (_, message_prefix_len) = self.spliced_prefix_lens();
        let mut counter: u64 = 0;
        let mut timestamp_cursor = std::iter::once(opencode_max_timestamp(&info))
            .chain(records.iter().flat_map(|(msg, parts)| {
                std::iter::once(opencode_max_timestamp(msg))
                    .chain(parts.iter().map(opencode_max_timestamp))
            }))
            .flatten()
            .max()
            .unwrap_or_else(|| SYNTH_TS_MS.saturating_sub(1));
        let mut appended_json: Vec<Value> = Vec::new();
        self.append_synthesized_opencode_messages(
            &mut appended_json,
            &self.messages[message_prefix_len..],
            &ses_id,
            &mut counter,
            &mut timestamp_cursor,
        )?;
        if !appended_json.is_empty() {
            Self::touch_opencode_session_updated(&mut info, timestamp_cursor);
        }
        for entry in appended_json {
            let msg = entry.get("info").cloned().unwrap_or(Value::Null);
            let parts = entry
                .get("parts")
                .and_then(Value::as_array)
                .cloned()
                .unwrap_or_default();
            records.push((msg, parts));
        }

        let storage = data_root.join("storage");
        let session_dir = storage.join("session").join(&project_id);
        std::fs::create_dir_all(&session_dir)?;
        std::fs::write(
            session_dir.join(format!("{ses_id}.json")),
            serde_json::to_string_pretty(&info).unwrap_or_default(),
        )?;

        let message_dir = storage.join("message").join(&ses_id);
        let part_dir = storage.join("part");
        std::fs::create_dir_all(&message_dir)?;

        for (msg, parts) in &records {
            let Some(msg_id) = msg.get("id").and_then(Value::as_str) else {
                continue;
            };
            std::fs::write(
                message_dir.join(format!("{msg_id}.json")),
                serde_json::to_string_pretty(msg).unwrap_or_default(),
            )?;
            let this_part_dir = part_dir.join(msg_id);
            std::fs::create_dir_all(&this_part_dir)?;
            for part in parts {
                let Some(part_id) = part.get("id").and_then(Value::as_str) else {
                    continue;
                };
                std::fs::write(
                    this_part_dir.join(format!("{part_id}.json")),
                    serde_json::to_string_pretty(part).unwrap_or_default(),
                )?;
            }
        }

        // Side-records (S5c): session_diff / todo have NO ingestion path via
        // `opencode import` at all — the direct write is their only
        // fidelity path.
        for header in &self.meta.opencode_headers {
            let Some(key) = header.get("key").and_then(Value::as_array) else {
                continue;
            };
            let Some(kind) = key.first().and_then(Value::as_str) else {
                continue;
            };
            let value = header.get("value").cloned().unwrap_or(Value::Null);
            if !matches!(kind, "session_diff" | "todo") {
                continue;
            }
            let dir = storage.join(kind);
            std::fs::create_dir_all(&dir)?;
            std::fs::write(
                dir.join(format!("{ses_id}.json")),
                serde_json::to_string_pretty(&value).unwrap_or_default(),
            )?;
        }

        Ok(session_dir)
    }
}

fn opencode_fresh_id(prefix: &str, counter: &mut u64) -> String {
    *counter += 1;
    format!("{prefix}_synth{counter:06}")
}

/// WAVE-2 fidelity item 2: restore the `agent`/`cost`/`finish`/`is_summary`/
/// `model`/`tokens` fields onto a synthesized OpenCode `info` record, in the
/// EXACT native shape opencode's own loaders (`push_opencode_user` /
/// `push_opencode_assistant`, above) parse back out — so an opencode->opencode
/// export-doc round-trip (write here, reload via [`Session::from_opencode_str`])
/// reconstructs value-identical `ChatMessage.metadata`. Each field is emitted
/// ONLY when its metadata key is present (a synthesized continuation turn, or
/// a User message that never carried `agent`, stays clean — no spurious
/// null/empty fields).
///
/// - `agent`: plain string on BOTH User (`v1/session.ts:346`) and Assistant
///   (`:465`) — `metadata["agent"]` is inserted verbatim by both loaders from
///   `msg_value.get("agent")`, so it's re-emitted verbatim here too.
/// - `model`: the loaders capture it in TWO DIFFERENT shapes depending on
///   role (`docs/interop/research/opencode-fields.md` §3 2a/2b), so the
///   inverse must match per-role:
///   - User: `push_opencode_user` stores `metadata["model"]` as the
///     STRINGIFIED `{providerID, modelID, variant?}` object
///     (`msg_value.get("model")...to_string()`) — re-parsed and re-emitted
///     as that same object under `"model"`.
///   - Assistant: `push_opencode_assistant` stores `metadata["model"]` as
///     `"{providerID}/{modelID}"` (from the top-level `providerID`/`modelID`
///     fields, joined) — split back on the FIRST `/` (matching `format!`'s
///     join; a `modelID` containing further `/`s round-trips correctly since
///     `split_once` only consumes the first) and re-emitted as the two
///     top-level `providerID`/`modelID` fields the loader actually reads.
/// - `is_summary`/`cost`/`finish`/`tokens`: Assistant-only concepts (no such
///   fields exist on opencode's `User` schema) — `is_summary` re-expands
///   `"true"` back to the native `summary: true` bool (the loader only ever
///   sets the metadata key on `Some(true)`, never on absent/false, so the
///   inverse never needs to emit `false`); `finish` is a plain string;
///   `cost`/`tokens` were captured via `v.to_string()` on the raw JSON
///   `Value` (a number and an object respectively), so they're re-parsed
///   from that stringified form and re-emitted as the native JSON value —
///   NOT as strings — matching `msg_value.get(field)` shape exactly.
fn opencode_restore_agent_model_fields(info: &mut Value, msg: &ChatMessage, is_assistant: bool) {
    if let Some(agent) = msg.metadata.get("agent") {
        info["agent"] = Value::String(agent.clone());
    }
    if let Some(model) = msg.metadata.get("model") {
        if is_assistant {
            if let Some((provider, model_id)) = model.split_once('/') {
                info["providerID"] = Value::String(provider.to_string());
                info["modelID"] = Value::String(model_id.to_string());
            }
        } else if let Ok(v) = serde_json::from_str::<Value>(model) {
            info["model"] = v;
        }
    }
    if !is_assistant {
        return;
    }
    if msg.metadata.get("is_summary").map(String::as_str) == Some("true") {
        info["summary"] = Value::Bool(true);
    }
    if let Some(finish) = msg.metadata.get("finish") {
        info["finish"] = Value::String(finish.clone());
    }
    if let Some(cost) = msg.metadata.get("cost") {
        if let Ok(v) = serde_json::from_str::<Value>(cost) {
            info["cost"] = v;
        }
    }
    if let Some(tokens) = msg.metadata.get("tokens") {
        if let Ok(v) = serde_json::from_str::<Value>(tokens) {
            info["tokens"] = v;
        }
    }
}

fn opencode_user_parts_from_message(
    msg: &ChatMessage,
    msg_id: &str,
    session_id: &str,
    counter: &mut u64,
) -> Vec<Value> {
    let mut parts = Vec::new();
    if let Some(cps) = &msg.content_parts {
        for p in cps {
            match p.get("type").and_then(Value::as_str) {
                Some("text") => {
                    if let Some(t) = p.get("text").and_then(Value::as_str) {
                        parts.push(serde_json::json!({
                            "id": opencode_fresh_id("prt", counter),
                            "sessionID": session_id,
                            "messageID": msg_id,
                            "type": "text",
                            "text": t,
                        }));
                    }
                }
                Some("image_url") => {
                    if let Some(url) = p
                        .get("image_url")
                        .and_then(|u| u.get("url"))
                        .and_then(Value::as_str)
                    {
                        let mime = url
                            .strip_prefix("data:")
                            .and_then(|r| r.split_once(','))
                            .map(|(m, _)| m.trim_end_matches(";base64"))
                            .unwrap_or("application/octet-stream");
                        parts.push(serde_json::json!({
                            "id": opencode_fresh_id("prt", counter),
                            "sessionID": session_id,
                            "messageID": msg_id,
                            "type": "file",
                            "mime": mime,
                            "url": url,
                        }));
                    }
                }
                _ => {}
            }
        }
    } else if let Some(t) = &msg.content {
        if !t.is_empty() {
            parts.push(serde_json::json!({
                "id": opencode_fresh_id("prt", counter),
                "sessionID": session_id,
                "messageID": msg_id,
                "type": "text",
                "text": t,
            }));
        }
    }
    parts
}

fn codex_response_item(payload: Value, ts: &str) -> Value {
    serde_json::json!({"timestamp": ts, "type": "response_item", "payload": payload})
}

/// Stamp `payload.metadata.turn_id` when `turn_id` is `Some` (PARITY-6/7,
/// see [`Session::write_codex_records`]); a no-op returning `payload`
/// untouched when `None`, so the historical byte shape is preserved for
/// every record that has no merge ambiguity to disambiguate.
fn with_turn_id(mut payload: Value, turn_id: Option<&str>) -> Value {
    if let Some(tid) = turn_id {
        payload["metadata"] = serde_json::json!({"turn_id": tid});
    }
    payload
}

/// Build a Codex `message` response_item's `content` block array from a
/// `ChatMessage` — the inverse of [`codex_extract_images`]/`extract_text_content`'s
/// parse. When `content_parts` is `None` this MUST reproduce the historical
/// single-block shape exactly (IX-5's overriding constraint: a text-only
/// message's export stays byte-identical) — only a multimodal message gets
/// one `{text_type}` block per non-empty text part plus one native Codex
/// `input_image` block (`{"type":"input_image","image_url":<data:URI or
/// URL>}` — the Responses-API-shaped image content Codex's own `input_text`/
/// `output_text` blocks already follow the family of) per `image_url` part.
fn codex_message_content_blocks(text_type: &str, msg: &ChatMessage) -> Value {
    match &msg.content_parts {
        Some(parts) => {
            let mut blocks = Vec::new();
            for p in parts {
                match p.get("type").and_then(Value::as_str) {
                    Some("text") => {
                        if let Some(t) = p.get("text").and_then(Value::as_str) {
                            if !t.is_empty() {
                                blocks.push(serde_json::json!({"type": text_type, "text": t}));
                            }
                        }
                    }
                    Some("image_url") => {
                        if let Some(url) = p
                            .get("image_url")
                            .and_then(|u| u.get("url"))
                            .and_then(Value::as_str)
                        {
                            blocks.push(serde_json::json!({
                                "type": "input_image",
                                "image_url": url,
                            }));
                        }
                    }
                    _ => {}
                }
            }
            Value::Array(blocks)
        }
        None => {
            let text = msg.content.clone().unwrap_or_default();
            Value::Array(vec![serde_json::json!({"type": text_type, "text": text})])
        }
    }
}

/// PARITY-11 (nested images, honest-residue side): a Codex
/// `function_call_output` response_item's `output` field is a BARE STRING
/// (real `codex-rs` protocol shape — unlike a `message` response_item, it has
/// no structured content array, so [`codex_message_content_blocks`]'s
/// `input_image` slot genuinely does not apply here). A nested image captured
/// off a Claude `tool_result` (`extract_tool_result_content`,
/// `content_parts`) therefore CANNOT be carried through this hop — but rather
/// than silently re-emitting the old bare `[image]` marker (indistinguishable
/// from a real, intentional annotation and impossible to tell apart from
/// "the data survived") or dropping it with zero trace, fold in an honest,
/// countable disclosure of exactly how many images were dropped and why —
/// same bracketed-note convention as [`UNCONVERTIBLE_IMAGE_MARKER`], applied
/// on the WRITE side instead of the read side. `content_parts` being `None`
/// (every pre-existing call site, and any tool result with no nested image)
/// reproduces the historical `msg.content` text byte-for-byte.
fn codex_tool_output_text(msg: &ChatMessage) -> String {
    let mut text = msg.content.clone().unwrap_or_default();
    if let Some(parts) = &msg.content_parts {
        let n = parts
            .iter()
            .filter(|p| p.get("type").and_then(Value::as_str) == Some("image_url"))
            .count();
        if n > 0 {
            if !text.is_empty() {
                text.push('\n');
            }
            text.push_str(&format!(
                "[image: {n} nested image(s) dropped — codex tool output has no \
                 structured content slot to carry them]"
            ));
        }
    }
    text
}

// ---- Pi writer helpers -----------------------------------------------------

/// Emit the pi v3 `session` header line. Frozen (§1.1/§1.3): `version` is
/// ALWAYS 3, never a lower value, so pi never rewrites a supercode-emitted
/// file in place on first resume (`pi-fields.md` sm:848-850).
fn push_pi_header(
    out: &mut String,
    id: &str,
    cwd: &str,
    parent_session: Option<&str>,
    created_at: Option<&str>,
    claude_fork_context_ref: Option<&str>,
) {
    let mut header = serde_json::json!({
        "type": "session",
        "version": 3,
        "id": id,
        "timestamp": created_at.unwrap_or(SYNTH_TS),
        "cwd": cwd,
    });
    if let Some(ps) = parent_session {
        header["parentSession"] = Value::String(ps.to_string());
    }
    // D7: namespaced passthrough field, exactly like the Codex writer's
    // `session_meta.payload.claude_fork_context_ref` — pi tolerates unknown
    // header keys, and `capture_pi_header` reads this same key back on
    // import, so a Claude -> Pi -> Claude round trip still reconstructs the
    // fork-context-ref record instead of silently losing it on this hop.
    if let Some(raw) = claude_fork_context_ref {
        header["claude_fork_context_ref"] =
            serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.to_string()));
    }
    push_jsonl(out, &header);
}

/// A fresh 8-hex entry id, collision-checked against `used` (mirrors pi's own
/// `randomUUID().slice(0,8)` + collision check, `pi-fields.md` sm:216-224 —
/// deterministic here rather than random, which still satisfies "fresh,
/// collision-free" without an extra RNG dependency).
fn pi_fresh_id(used: &mut HashSet<String>, counter: &mut u64) -> String {
    loop {
        *counter += 1;
        let h = counter.wrapping_mul(0x9E3779B97F4A7C15);
        let id = format!("{:08x}", (h >> 32) as u32);
        if used.insert(id.clone()) {
            return id;
        }
    }
}

/// Parse a `data:<mime>[;base64],<data>` URI back into `(mime, data)` — the
/// inverse of the loader's `data:{mime};base64,{data}` construction.
fn parse_data_uri(url: &str) -> Option<(String, String)> {
    let rest = url.strip_prefix("data:")?;
    let (meta, data) = rest.split_once(',')?;
    let mime = meta.strip_suffix(";base64").unwrap_or(meta);
    Some((mime.to_string(), data.to_string()))
}

/// Rebuild a pi `(TextContent|ImageContent)[]` (or bare string) content value
/// from a `ChatMessage`'s `content`/`content_parts` — shared by `user` and
/// `toolResult` entries (both use the identical union on the wire).
fn pi_content_value(msg: &ChatMessage) -> Value {
    if let Some(parts) = &msg.content_parts {
        let mut arr = Vec::new();
        for p in parts {
            match p.get("type").and_then(Value::as_str) {
                Some("text") => {
                    if let Some(t) = p.get("text").and_then(Value::as_str) {
                        arr.push(serde_json::json!({"type": "text", "text": t}));
                    }
                }
                Some("image_url") => {
                    if let Some(url) = p
                        .get("image_url")
                        .and_then(|u| u.get("url"))
                        .and_then(Value::as_str)
                    {
                        if let Some((mime, data)) = parse_data_uri(url) {
                            arr.push(
                                serde_json::json!({"type": "image", "mimeType": mime, "data": data}),
                            );
                        }
                    }
                }
                _ => {}
            }
        }
        Value::Array(arr)
    } else {
        Value::String(msg.content.clone().unwrap_or_default())
    }
}

fn pi_assistant_content_value(msg: &ChatMessage) -> Value {
    let mut arr = Vec::new();
    if let Some(thinking) = msg.metadata.get("thinking") {
        let mut block = serde_json::json!({"type": "thinking", "thinking": thinking});
        if let Some(sig) = msg.metadata.get("thinking_signature") {
            block["thinkingSignature"] = Value::String(sig.clone());
        }
        if msg.metadata.get("pi_thinking_redacted").map(String::as_str) == Some("true") {
            block["redacted"] = Value::Bool(true);
        }
        arr.push(block);
    }
    if let Some(text) = &msg.content {
        if !text.is_empty() {
            let mut block = serde_json::json!({"type": "text", "text": text});
            if let Some(sig) = msg.metadata.get("pi_text_signature") {
                block["textSignature"] = Value::String(sig.clone());
            }
            arr.push(block);
        }
    }
    for tc in msg.tool_calls() {
        let args = tc
            .function
            .parsed_arguments()
            .unwrap_or_else(|_| Value::Object(Default::default()));
        let mut block = serde_json::json!({
            "type": "toolCall",
            "id": tc.id,
            "name": tc.function.name,
            "arguments": args,
        });
        if let Some(sig) = msg.metadata.get("pi_thought_signature") {
            block["thoughtSignature"] = Value::String(sig.clone());
        }
        arr.push(block);
    }
    Value::Array(arr)
}

fn default_pi_usage() -> Value {
    serde_json::json!({
        "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 0,
        "cost": {"input": 0.0, "output": 0.0, "cacheRead": 0.0, "cacheWrite": 0.0, "total": 0.0},
    })
}

fn is_tool_error_flag(msg: &ChatMessage) -> bool {
    msg.metadata.get("pi_is_error").map(String::as_str) == Some("true") || crate::is_tool_error(msg)
}

#[cfg(test)]
mod tests {
    use super::{
        opencode_message_timestamp, parent_tool_use_index, truncate_messages_with_anchor, Session,
        SessionFormat,
    };
    use crate::message::ChatMessage;
    use crate::{Fidelity, Role};

    #[test]
    fn a_new_user_message_slides_the_display_tail_without_becoming_its_only_anchor() {
        let mut messages = vec![
            ChatMessage::user("original prompt"),
            ChatMessage::assistant("one"),
            ChatMessage::assistant("two"),
            ChatMessage::assistant("three"),
            ChatMessage::assistant("four"),
            ChatMessage::assistant("five"),
            ChatMessage::user("new prompt"),
        ];

        truncate_messages_with_anchor(&mut messages, 4, Vec::new());

        assert_eq!(messages.len(), 4);
        assert_eq!(messages[0].content.as_deref(), Some("original prompt"));
        assert_eq!(messages[3].content.as_deref(), Some("new prompt"));
    }

    #[test]
    fn a_tool_heavy_current_turn_keeps_the_previous_and_current_user_anchors() {
        let mut messages = vec![
            ChatMessage::user("previous prompt"),
            ChatMessage::assistant("previous answer"),
            ChatMessage::user("current prompt"),
            ChatMessage::assistant("tool one"),
            ChatMessage::assistant("tool two"),
            ChatMessage::assistant("tool three"),
            ChatMessage::assistant("tool four"),
            ChatMessage::assistant("tool five"),
        ];

        truncate_messages_with_anchor(&mut messages, 4, Vec::new());

        assert_eq!(messages.len(), 4);
        assert_eq!(messages[0].content.as_deref(), Some("previous prompt"));
        assert_eq!(messages[1].content.as_deref(), Some("current prompt"));
        assert_eq!(messages[3].content.as_deref(), Some("tool five"));
    }

    #[test]
    fn a_preceding_user_anchor_is_restored_when_dedup_shrinks_below_the_limit() {
        let mut messages = vec![
            ChatMessage::user("current prompt"),
            ChatMessage::assistant("tool one"),
            ChatMessage::assistant("tool two"),
        ];

        truncate_messages_with_anchor(&mut messages, 4, vec![ChatMessage::user("previous prompt")]);

        assert_eq!(messages.len(), 4);
        assert_eq!(messages[0].content.as_deref(), Some("previous prompt"));
        assert_eq!(messages[1].content.as_deref(), Some("current prompt"));
    }

    #[test]
    fn a_tool_heavy_turn_restores_two_users_that_both_left_the_retention_buffer() {
        let mut messages = vec![
            ChatMessage::assistant("tool one"),
            ChatMessage::assistant("tool two"),
            ChatMessage::assistant("tool three"),
            ChatMessage::assistant("tool four"),
        ];

        truncate_messages_with_anchor(
            &mut messages,
            4,
            vec![
                ChatMessage::user("previous prompt"),
                ChatMessage::user("current prompt"),
            ],
        );

        assert_eq!(messages.len(), 4);
        assert_eq!(messages[0].content.as_deref(), Some("previous prompt"));
        assert_eq!(messages[1].content.as_deref(), Some("current prompt"));
        assert_eq!(messages[3].content.as_deref(), Some("tool four"));
    }

    #[test]
    fn bounded_codex_file_expands_past_tool_noise_and_loads_real_earlier_history() {
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let path = std::env::temp_dir().join(format!(
            "supercode-display-history-{}-{nonce}.jsonl",
            std::process::id()
        ));
        let user = |text: &str| {
            format!(
                r#"{{"type":"response_item","payload":{{"type":"message","role":"user","content":[{{"type":"input_text","text":"{text}"}}]}}}}"#,
            )
        };
        let assistant = |index: usize| {
            format!(
                r#"{{"type":"response_item","payload":{{"type":"message","role":"assistant","content":[{{"type":"output_text","text":"answer-{index}"}}]}}}}"#,
            )
        };
        let mut lines = vec![
            r#"{"type":"session_meta","payload":{"id":"session-1"}}"#.to_string(),
            user("earlier prompt"),
            format!(
                r#"{{"type":"event_msg","payload":{{"type":"token_count","noise":"{}"}}}}"#,
                "x".repeat(5 * 1024 * 1024)
            ),
            user("latest prompt"),
        ];
        lines.extend((0..130).map(assistant));
        std::fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap();

        let initial = Session::load_display_view(&path, Fidelity::Semantic, 120).unwrap();
        let expanded = Session::load_display_view(&path, Fidelity::Semantic, 240).unwrap();
        std::fs::remove_file(&path).unwrap();

        let initial_users = initial
            .messages
            .iter()
            .filter(|message| message.role == Role::User)
            .filter_map(|message| message.content.as_deref())
            .collect::<Vec<_>>();
        assert_eq!(initial.messages.len(), 120);
        assert_eq!(initial_users, ["earlier prompt", "latest prompt"]);
        assert!(
            initial.imported_message_count.unwrap() > initial.messages.len(),
            "a bounded initial page must truthfully report earlier history"
        );
        assert_eq!(expanded.messages.len(), 132);
        assert_eq!(expanded.imported_message_count, Some(132));
    }

    #[test]
    fn bounded_codex_display_history_reports_the_unbounded_message_total() {
        let jsonl = (0..6)
            .map(|index| {
                let role = if index % 2 == 0 { "user" } else { "assistant" };
                format!(
                    r#"{{"type":"response_item","payload":{{"type":"message","role":"{role}","content":[{{"type":"input_text","text":"message-{index}"}}]}}}}"#,
                )
            })
            .collect::<Vec<_>>()
            .join("\n");

        let session = Session::from_codex_display_str(&jsonl, 2).unwrap();

        assert_eq!(session.messages.len(), 2);
        assert_eq!(session.imported_message_count, Some(6));
    }

    #[test]
    fn malformed_discriminated_native_turn_is_counted_as_parse_loss() {
        let base = Session::from_native_messages(Vec::new());
        let mut native = base.to_native_jsonl_v2(&[]);
        native.push_str("{\"supercode_turn\":1}\n");

        let parsed = Session::from_native_str(&native).unwrap();
        assert_eq!(parsed.parse_error_lines, 1);
        assert!(parsed.messages.is_empty());
        assert_eq!(
            parsed.raw.last().map(String::as_str),
            Some("{\"supercode_turn\":1}")
        );
    }

    #[test]
    fn spliced_export_refuses_a_native_wrapper_with_parse_loss() {
        let imported = Session::from_claude_code_str(
            r#"{"type":"user","sessionId":"s","cwd":"/tmp","message":{"role":"user","content":"hi"}}"#,
        )
        .unwrap();
        let mut native = imported.to_native_jsonl_v2(&[ChatMessage::assistant("continued")]);
        native.push_str("{\"supercode_turn\":1}\n");

        let parsed = Session::from_native_str(&native).unwrap();
        let error = parsed
            .to_jsonl_spliced(SessionFormat::ClaudeCode, None)
            .unwrap_err();
        assert!(error.to_string().contains("parse loss"), "{error}");
    }

    #[test]
    fn sidecar_loader_requires_a_supported_native_header() {
        for malformed in [
            "",
            "not-json\n",
            "{}\n",
            "{\"supercode_native\":2}\n",
            "{\"supercode_native\":99,\"source\":\"native\"}\n",
        ] {
            let error = Session::from_sidecar_str(malformed).unwrap_err();
            assert!(error.to_string().contains("sidecar header"), "{error}");
        }
    }

    #[test]
    fn gemini_user_parts_preserve_text_media_and_response_order() {
        let session = Session::from_gemini_str(
            r#"{"sessionId":"11111111-1111-4111-8111-111111111111","projectHash":"p"}
{"type":"gemini","content":"calling","toolCalls":[{"id":"a","name":"read","args":{}},{"id":"b","name":"read","args":{}}]}
{"type":"user","content":[{"text":"before"},{"functionResponse":{"id":"b","name":"read","response":{"output":"B"}}},{"inlineData":{"mimeType":"image/png","data":"YQ=="}},{"functionResponse":{"name":"read","response":{"output":"A"}}},{"text":"after"}]}
"#,
        )
        .unwrap();

        assert_eq!(session.messages.len(), 6);
        assert_eq!(
            session.messages[1].content_parts.as_ref().unwrap()[0]["text"],
            "before"
        );
        assert_eq!(session.messages[2].tool_call_id.as_deref(), Some("b"));
        assert!(
            session.messages[3].content_parts.as_ref().unwrap()[0]["image_url"]["url"]
                .as_str()
                .unwrap()
                .starts_with("data:image/png;base64,")
        );
        assert_eq!(session.messages[4].tool_call_id.as_deref(), Some("a"));
        assert_eq!(
            session.messages[5].content_parts.as_ref().unwrap()[0]["text"],
            "after"
        );
    }

    #[test]
    fn opencode_synthetic_timestamp_fails_closed_at_i64_max() {
        let msg = ChatMessage::user("continuation");
        let mut cursor = i64::MAX - 1;
        assert_eq!(
            opencode_message_timestamp(&msg, &mut cursor).unwrap(),
            i64::MAX
        );
        let err = opencode_message_timestamp(&msg, &mut cursor).unwrap_err();
        assert!(err.to_string().contains("after i64::MAX"));
        assert_eq!(cursor, i64::MAX, "overflow must not wrap or mutate state");
    }

    /// Pin of the single-pass indexer against the relevant Claude tool-result
    /// shape (SUP-21). An id absent from the transcript must map to nothing.
    #[test]
    fn parent_tool_use_index_matches_known_fixture_linkage() {
        let main_text = r#"{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01SYjhg9qRCzUWY2GTa3iazQ","type":"tool_result","content":[{"type":"text","text":"agentId: ad8dc6cf98b49eea6"}]}]},"toolUseResult":{"agentId":"ad8dc6cf98b49eea6"}}"#;

        let ids = vec![
            "ad8dc6cf98b49eea6".to_string(),
            "no-such-agent-id".to_string(),
        ];
        let index = parent_tool_use_index(main_text, &ids);

        assert_eq!(
            index.get("ad8dc6cf98b49eea6").map(String::as_str),
            Some("toolu_01SYjhg9qRCzUWY2GTa3iazQ"),
            "known agent id must resolve to the pinned parent tool_use_id"
        );
        assert_eq!(
            index.get("no-such-agent-id"),
            None,
            "unknown agent id must yield no entry (best-effort None)"
        );
    }

    #[test]
    fn parent_tool_use_index_empty_ids_returns_empty_map() {
        let index = parent_tool_use_index("irrelevant text", &[]);
        assert!(index.is_empty());
    }
}