supercode-interchange 0.4.20

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
//! Claude Code session codec: loaders, writers and native-record helpers.

use super::*;

mod read_index;
pub use read_index::ClaudeReadIndex;
mod append;
pub(crate) use append::ClaudeAppendState;

impl 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.
    pub(super) 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(())
    }

    /// 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();
        let mut residue_lines = Vec::new();

        // 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)?;
            if claude_residue_kind(&v).is_some() {
                residue_lines.push(line_index);
            }
        }

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

        // PARITY-23: candidates cover ALL raw records, not just the active
        // replay branch. Classify during the first decode to avoid decoding
        // every conversation/tool payload again merely to rule it out here.
        // Capture must still follow ALL metadata restoration: a later foreign
        // envelope suppresses local residue, while a same-source envelope is
        // restored before local records are appended. Retain indexes, not Values.
        for record_index in residue_lines {
            let line = raw_lines[record_index];
            if let Ok(record) = serde_json::from_str::<Value>(line) {
                capture_claude_residue(&mut meta, record_index, line, &record);
            }
        }

        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,
        })
    }
}

// ---- 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.
pub(super) 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, Clone)]
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`).
pub(super) 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`].
pub(super) 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}"))
}

pub(super) 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.
pub(super) 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());
                }
            }
        }
    }
}

/// PARITY-23: Claude Code records that affect replay or carry source-native
/// state but have no canonical home — the claude-code residue inventory
/// (design doc §per-format). `last-prompt` steers leaf selection,
/// `fork-context-ref` anchors the replay graph, `file-history-snapshot` /
/// `queue-operation` / `mode` are durable native state.
pub(super) fn claude_residue_kind(record: &Value) -> Option<&'static str> {
    match record.get("type").and_then(Value::as_str) {
        Some("file-history-snapshot") => Some("file-history-snapshot"),
        Some("queue-operation") => Some("queue-operation"),
        Some("last-prompt") => Some("last-prompt"),
        Some("mode") => Some("mode"),
        Some("fork-context-ref") => Some("fork-context-ref"),
        _ => None,
    }
}

/// Re-emit a claude residue record under the session's CURRENT metadata:
/// `sessionId`/`cwd` keys are rewritten only when they exist and differ (an
/// explicit `--session-id`/`--cwd` override is a deliberate rewrite request
/// that extends to residue). When nothing differs — the plain return
/// diagonal — the raw line is emitted byte-exact.
fn claude_residue_line_for_emit(raw: &str, session_id: &str, cwd: &str) -> String {
    let Ok(mut value) = serde_json::from_str::<Value>(raw) else {
        return raw.to_string();
    };
    let Some(object) = value.as_object_mut() else {
        return raw.to_string();
    };
    let mut changed = false;
    for (key, current) in [("sessionId", session_id), ("cwd", cwd)] {
        if object
            .get(key)
            .and_then(Value::as_str)
            .is_some_and(|existing| existing != current)
        {
            object.insert(key.to_string(), Value::String(current.to_string()));
            changed = true;
        }
    }
    if changed {
        value.to_string()
    } else {
        raw.to_string()
    }
}

fn capture_claude_residue(
    meta: &mut SessionMeta,
    record_index: usize,
    raw_line: &str,
    record: &Value,
) {
    let Some(kind) = claude_residue_kind(record) else {
        return;
    };
    capture_native_residue(meta, "claude_code", record_index, raw_line, record, kind);
}

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

impl Session {
    /// 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.
    pub(super) 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(),
        );
        // PARITY-23: claude-source residue restored from a foreign hop is
        // NATIVE here again — re-emit the exact source records (relative
        // order preserved) instead of wrapping them in an envelope.
        if self.meta.native_residue_source.as_deref() == Some("claude_code") {
            let mut records: Vec<&Value> = self.meta.native_residue.iter().collect();
            records.sort_by_key(|entry| {
                entry
                    .get("record_index")
                    .and_then(Value::as_u64)
                    .unwrap_or(u64::MAX)
            });
            for entry in records {
                if let Some(raw) = entry.get("raw").and_then(Value::as_str) {
                    out.push_str(&claude_residue_line_for_emit(raw, &session_id, &cwd));
                    out.push('\n');
                }
            }
        } else if let Some(extension) = native_residue_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_NATIVE_RESIDUE_SUMMARY_KEY,
                native_residue_summary(&extension),
            );
            inject_first_jsonl_top_level(&mut out, SUPERCODE_NATIVE_RESIDUE_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).
    pub(super) 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
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn residue_inventory_preserves_raw_indexes_and_all_native_kinds() {
        let lines = [
            "",
            r#" {"type":"mode","mode":"plan"} "#,
            r#"{"type":"file-history-snapshot","snapshot":{}}"#,
            r#"{"type":"queue-operation","operation":"dequeue"}"#,
            r#"{"type":"fork-context-ref","uuid":"root"}"#,
            r#"{"type":"user","uuid":"user","parentUuid":"root","message":{"role":"user","content":"hello"}}"#,
            r#"{"type":"last-prompt","leafUuid":"user","explicit":true}"#,
            r#"{"type":"progress","data":"not residue"}"#,
            "{truncated",
        ];
        let text = lines.join("\r\n");
        let session = Session::from_claude_code_str(&text).unwrap();
        assert_eq!(session.parse_error_lines, 1);
        assert_eq!(session.messages.len(), 1);
        let expected = [
            (1, "mode"),
            (2, "file-history-snapshot"),
            (3, "queue-operation"),
            (4, "fork-context-ref"),
            (6, "last-prompt"),
        ];
        assert_eq!(session.meta.native_residue.len(), expected.len());
        for (entry, (index, kind)) in session.meta.native_residue.iter().zip(expected) {
            assert_eq!(entry["record_index"], index);
            assert_eq!(entry["kind"], kind);
            assert_eq!(entry["raw"], format!("{}\r", lines[index]));
        }
        assert_eq!(session.raw.join("\n"), text);
    }

    #[test]
    fn residue_capture_waits_for_late_same_or_foreign_envelope_restore() {
        for source in ["claude_code", "grok"] {
            let restored_raw = r#"{"type":"mode","mode":"restored"}"#;
            let mut restored_meta = SessionMeta::new(SessionSource::ClaudeCode);
            capture_native_residue(
                &mut restored_meta,
                source,
                17,
                restored_raw,
                &serde_json::from_str::<Value>(restored_raw).unwrap(),
                "mode",
            );
            let carrier = serde_json::json!({
                "type": "mode",
                (SUPERCODE_NATIVE_RESIDUE_KEY): native_residue_envelope(&restored_meta).unwrap(),
            });
            let before = r#"{"type":"mode","mode":"before"}"#;
            let after = r#"{"type":"queue-operation","operation":"after"}"#;
            let text = format!(
                "{before}\n{carrier}\n{after}\n{}\n",
                r#"{"type":"user","message":{"role":"user","content":"hello"}}"#,
            );
            let session = Session::from_claude_code_str(&text).unwrap();
            assert_eq!(session.meta.native_residue_source.as_deref(), Some(source));
            assert_eq!(
                session.meta.native_residue[0],
                restored_meta.native_residue[0]
            );
            if source == "claude_code" {
                assert_eq!(session.meta.native_residue.len(), 3);
                assert_eq!(session.meta.native_residue[1]["raw"], before);
                assert_eq!(session.meta.native_residue[1]["record_index"], 0);
                assert_eq!(session.meta.native_residue[2]["raw"], after);
                assert_eq!(session.meta.native_residue[2]["record_index"], 2);
            } else {
                assert_eq!(session.meta.native_residue, restored_meta.native_residue);
            }
        }
    }

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