supercode-interchange 0.4.17

Canonical, provider-neutral session interchange primitives for Supercode
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
//! OpenCode session codec: JSON/SQLite loaders, writers and helpers.

use super::*;

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

    pub fn from_opencode_sqlite(db_path: &Path, session_id: Option<&str>) -> Result<Session> {
        let conn = opencode_sqlite_open(db_path)?;
        let id = match session_id {
            Some(id) => id.to_string(),
            None => opencode_sqlite_primary_session_id(&conn)?,
        };
        let lines = opencode_sqlite_session_envelope_lines(&conn, db_path, &id)?;
        let mut text = lines.join("\n");
        text.push('\n');
        let mut session = Self::from_opencode_str(&text)?;
        // D4: `text` above is a SYNTHESIZED reconstruction from SQL rows —
        // not the original source bytes (a binary `.db` file has no
        // "verbatim" line-oriented form to begin with). `from_opencode_str`
        // defaults `raw_is_verbatim` to `true` because for its OTHER two
        // callers (an actual envelope-form file's own text, an actual
        // export-document's text) that really is the source. It is NEVER
        // true for this diagonal — mirrors the export-document fix just
        // above for the same reason (`from_opencode_export_doc`, `false`).
        // `convert opencode.db --to opencode` must not claim byte-identical.
        session.raw_is_verbatim = false;
        Ok(session)
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

fn opencode_sqlite_open(db_path: &Path) -> Result<Connection> {
    if !db_path.is_file() {
        return Err(crate::Error::Other(format!(
            "OpenCode SQLite store not found at {} — expected an `opencode*.db` file \
             (see `docs/interop/opencode-pi-spec.md` §1.2)",
            db_path.display()
        )));
    }
    let conn = Connection::open_with_flags(
        db_path,
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )
    .map_err(|e| {
        crate::Error::Other(format!(
            "{} does not look like a valid OpenCode SQLite database: {e}",
            db_path.display()
        ))
    })?;
    let has_session_table: i64 = conn
        .query_row(
            "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='session'",
            [],
            |r| r.get(0),
        )
        .map_err(|e| {
            crate::Error::Other(format!(
                "failed to read the OpenCode SQLite schema at {}: {e}",
                db_path.display()
            ))
        })?;
    if has_session_table == 0 {
        return Err(crate::Error::Other(format!(
            "{} is a SQLite database but has no `session` table — not a recognized \
             OpenCode store (wrong file, or an unsupported/pre-SQLite OpenCode version)",
            db_path.display()
        )));
    }
    Ok(conn)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Ok(lines)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

impl Session {
    // ---- OpenCode writers ---------------------------------------------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Ok(session_dir)
    }
}

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

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

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

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

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