pond-db 0.20.1

Lossless storage and search for sessions from any AI agent client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
//! opencode adapter (github.com/sst/opencode).
//!
//! opencode moved its storage from a JSON file tree to a Drizzle-managed SQLite
//! database in v1.2.0 (2026-02-14). This adapter reads BOTH, because a user who
//! upgraded past the format's death still has stranded pre-migration JSON that
//! never reached the DB (spec.md#session-movement-complete):
//!
//! - `<data-dir>/opencode*.db` (WAL) - `session`/`message`/`part` tables. The
//!   `message`/`part` `data` blob is the old per-file JSON minus its ids;
//!   opencode rehydrates it as `{...data, id, sessionID(, messageID)}`.
//! - `<data-dir>/storage/` - the legacy content-addressed split tree:
//!   `session/<projectID>/<sessionID>.json`, `message/<sessionID>/<messageID>.json`,
//!   `part/<messageID>/<partID>.json`.
//!
//! Sessions are deduped by id (DB wins, the tree fills gaps,
//! spec.md#adapter-integrity-dedup). Both feed the same
//! `build_message_events`/`map_part` pipeline, sorted by id (ids are lexically
//! time-sortable, so id order is creation order), emitting `Session -> Message
//! -> Parts` per session.
//!
//! OpenCode 2 writes the same DB through a second pair of tables:
//! `session_v2` (typed columns) and `session_message` (one row per typed
//! message, its parts inlined in `data`, ordered by `seq`). Its startup
//! migration copies every V1 session into them and leaves the V1 tables in
//! place, so one DB can hold V1-only, V2-only and migrated sessions. A migrated
//! session keeps its V1 rows (the originals, and what earlier pond versions
//! already stored, spec.md#adapter-integrity-additive-sync) and gains only the
//! V2 rows written after the migration; the migration's own lossy copies are
//! not re-ingested. docs/adapters/opencode.md is the decision record.
//!
//! opencode fuses a tool call and its result into one `tool` part on the
//! assistant message. Canonical keeps the two apart (a `tool_result` on an
//! assistant message is a category error, spec.md#model-part-provenance), so the
//! adapter splits it: a `ToolCall` Part stays on the assistant message and a
//! synthetic `Tool` message carries the `ToolResult`.
//!
//! Restore (native AND foreign) emits one `<session_id>.json` per session in the
//! `opencode import` shape - `{ info, messages: [ { info, parts } ] }` (see
//! `packages/opencode/src/cli/cmd/import.ts`). Native replays each real record's
//! stored `raw_record` (session/message/part) into that envelope and skips the
//! synthetic split records (the `Tool` carrier message + `ToolResult` part),
//! re-fusing into the single source `tool` part, so the split is
//! value-complete-lossless.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use async_stream::stream;
use chrono::{DateTime, Utc};
use rusqlite::{Connection, OptionalExtension};
use serde_json::{Value, json};
use tokio::sync::mpsc;

use crate::{
    sessions::IngestEvent,
    wire::{FileData, Message, Part, PartKind, Provenance, ProviderOptions, Session},
};

use super::{
    Adapter, AdapterError, AdapterFactory, AdapterYield, AdapterYieldStream, DiscoverFuture, Env,
    RestoreFidelity, RestoredFile, SkipOracle, SkipReason, by_timestamp_then_id, compact_json,
    config_path,
    extract::{Extracted, extract_str, json_or_string},
    jsonl::{RECORD_CAP, parse_bounded},
    part_id, part_ordinal, raw_record, source_options,
    sqlite::{self, CHANNEL_CAP, emit},
    validate_path_id,
};

const NAME: &str = "opencode";

/// Stateless factory: opens [`OpencodeAdapter`] instances and probes for the
/// canonical install location under `~/.local/share/opencode/storage`.
pub struct OpencodeFactory;

impl AdapterFactory for OpencodeFactory {
    fn name(&self) -> &'static str {
        NAME
    }

    fn open(&self, config: Value) -> Result<Box<dyn Adapter>, AdapterError> {
        Ok(Box::new(OpencodeAdapter::new(config_path(NAME, config)?)))
    }

    /// Windows needs no separate branch: opencode resolves its data dir through
    /// `xdg-basedir`, which has zero Windows special-casing. The standing gap is
    /// that pond ignores `XDG_DATA_HOME` here, on any platform.
    fn probe_default(&self, env: &Env) -> Option<Value> {
        // The configured root is the opencode DATA DIR (it holds both the
        // `opencode*.db` files and the legacy `storage/` tree). Only offer it
        // when it actually has one of those, so an empty `~/.local/share/opencode`
        // does not masquerade as a source.
        let data_dir = env.home.join(".local").join("share").join("opencode");
        if !data_dir.exists() {
            return None;
        }
        let has_db = db_paths(&data_dir).is_ok_and(|dbs| !dbs.is_empty());
        let has_tree = data_dir.join("storage").is_dir();
        (has_db || has_tree).then(|| json!({ "path": data_dir }))
    }

    fn serialize(
        &self,
        session: &crate::sessions::SessionWithMessages,
        fidelity: RestoreFidelity,
    ) -> Result<Vec<RestoredFile>, AdapterError> {
        match fidelity {
            RestoreFidelity::Native => serialize_native(session),
            RestoreFidelity::Foreign => serialize_foreign(session),
        }
    }
}

/// Configured opencode reader, rooted at the opencode DATA DIR (which holds the
/// `opencode*.db` files and the legacy `storage/` tree).
#[derive(Debug, Clone)]
pub struct OpencodeAdapter {
    root: PathBuf,
}

impl OpencodeAdapter {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        let root = root.into();
        // Legacy configs pointed `path` at `<data-dir>/storage`; the root is
        // the data dir, so a configured basename of `storage` resolves to its
        // parent and existing configs keep working.
        let root = if root.file_name().and_then(|name| name.to_str()) == Some("storage") {
            root.parent()
                .map_or_else(|| root.clone(), Path::to_path_buf)
        } else {
            root
        };
        Self { root }
    }
}

/// The legacy split-file tree lives at `<data-dir>/storage/`; a root that IS
/// itself a bare tree (`session/` directly under it) has no `storage/` subdir,
/// so fall back to the root. Resolved once per enumeration and carried through
/// to the read pass.
fn tree_base(root: &Path) -> PathBuf {
    let nested = root.join("storage");
    if nested.join("session").is_dir() {
        nested
    } else {
        root.to_path_buf()
    }
}

impl Adapter for OpencodeAdapter {
    fn discover(&self) -> DiscoverFuture<'_> {
        let root = self.root.clone();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || {
                // The TRUE deduped count: every DB session id plus each legacy-tree
                // session whose id no DB carries. Superseded tree copies are NOT
                // counted - the progress bar never ticks them (the bulk Superseded
                // skip leaves its length untouched).
                Ok(enumerate_and_peek(&root, false).entries.len())
            })
            .await
            .map_err(join_error)?
        })
    }

    fn plan<'a>(&'a self, oracle: &'a dyn SkipOracle) -> super::PlanFuture<'a> {
        let root = self.root.clone();
        Box::pin(async move {
            // The events_with freshness pre-pass run standalone: the same
            // per-session peek sync's gate pays every run, classified instead of
            // read. On an empty oracle the peeks are skipped - a first sync reads
            // everything. A message-less session stays Opaque (never Empty):
            // reading it still ingests its Session row. Degrades like the gate: a
            // source that failed to enumerate already warned and is counted as
            // whatever survived, never propagated.
            let peek = !oracle.is_empty();
            let peeked = tokio::task::spawn_blocking(move || enumerate_and_peek(&root, peek))
                .await
                .map_err(join_error)?;
            if !peek {
                return Ok(Some(super::SyncPlan::all_pending(peeked.entries.len())));
            }
            Ok(Some(super::SyncPlan::from_heads(
                oracle,
                peeked.entries.iter().map(|entry| {
                    let watermark = match entry.source_ts {
                        Some(ts) => super::SourceWatermark::At(ts),
                        None => super::SourceWatermark::Opaque,
                    };
                    (Some(entry.source.session_id()), watermark)
                }),
            )))
        })
    }

    fn events_with<'a>(&'a self, oracle: &'a dyn SkipOracle) -> AdapterYieldStream<'a> {
        let adapter = self.clone();
        Box::pin(stream! {
            let root = adapter.root.clone();
            let peek = !oracle.is_empty();
            // One blocking burst enumerates both sources, dedups, and (when the
            // oracle carries watermarks) peeks each session's newest-message
            // timestamp. It returns owned, Send data so the async gate below can
            // consult the borrowed oracle without dragging a rusqlite handle
            // across an await point.
            let peeked = tokio::task::spawn_blocking(move || enumerate_and_peek(&root, peek)).await;
            let Peeked { tree_base, entries, duplicates, errors } = match peeked {
                Ok(peeked) => peeked,
                Err(join) => { yield Err(join_error(join)); return; }
            };

            // Per-source enumeration failures surface as visible errors and the
            // run continues with the survivors (spec.md#adapter-integrity-no-silent-drops).
            // A failed DB's session ids are unknown this run, so its tree copies
            // (if any) ingest undeduped - additive and safe, self-correcting once
            // the DB opens again next run.
            for error in errors {
                yield Err(error);
            }

            // spec.md#adapter-integrity-dedup: a legacy-tree copy that shares a DB
            // session's id is a pre-1.2 migration artifact, superseded wholesale by
            // the DB copy. Content identity is deliberately NOT verified (locked
            // plan decision): the drop stays visible as a counted Superseded skip -
            // the spec's sanctioned terminal state for an unresolved collision -
            // never folded into Empty.
            if duplicates > 0 {
                yield Ok(AdapterYield::SkippedBatch {
                    reason: SkipReason::Superseded,
                    count: duplicates,
                });
            }

            let mut survivors = Vec::with_capacity(entries.len());
            for entry in entries {
                if crate::adapter::is_session_fresh(oracle, entry.source.session_id(), entry.source_ts) {
                    yield Ok(AdapterYield::Skipped {
                        session_id: Some(entry.source.session_id().to_owned()),
                        project: None,
                        reason: SkipReason::Fresh,
                    });
                    continue;
                }
                survivors.push(entry.source);
            }

            let (tx, mut rx) = mpsc::channel(CHANNEL_CAP);
            let handle =
                tokio::task::spawn_blocking(move || read_survivors(&tree_base, survivors, &tx));
            while let Some(item) = rx.recv().await {
                yield item;
            }
            if let Err(join) = handle.await {
                yield Err(join_error(join));
            }
        })
    }
}

/// Re-attribution for a composed opencode reader. A caller that runs opencode's
/// reader against a foreign root (nanoclaw's opencode-provider sessions) relabels
/// each yielded session: opencode still owns the main-vs-subagent decision from
/// its own taxonomy, and the caller supplies only the new `source_agent` root, the
/// `project` scope, and one `(key, value)` options entry mirrored onto every
/// session. opencode's own session/message/part ids stay canonical.
pub(crate) struct Attribution {
    pub source_agent_root: String,
    pub project: Extracted<String>,
    pub extra_options: (String, Value),
}

/// Stream opencode's `events_with` against `root`, applying `attribution` to every
/// emitted `Session`; every other yield (messages, parts, skips, errors) passes
/// through unchanged. Composition-only: the `opencode` adapter's own ingest does
/// not route through here (it emits its own stream). This seam keeps all opencode
/// format knowledge in this module so the foreign caller supplies only the
/// attribution; nanoclaw's provider composition is its one caller today.
pub(crate) fn composed_events_with<'a>(
    root: PathBuf,
    oracle: &'a dyn SkipOracle,
    attribution: Attribution,
) -> AdapterYieldStream<'a> {
    use tokio_stream::StreamExt;
    Box::pin(stream! {
        let adapter = OpencodeAdapter::new(root);
        let mut inner = adapter.events_with(oracle);
        while let Some(item) = inner.next().await {
            yield item.map(|yielded| reattribute(yielded, &attribution));
        }
    })
}

/// Apply an [`Attribution`] to one yield. opencode labels a main session bare
/// `opencode` and any subagent `opencode/<agent>` or `opencode/subagent`, so a
/// non-bare label is exactly opencode's "this is a subagent" signal.
fn reattribute(yielded: AdapterYield, attribution: &Attribution) -> AdapterYield {
    let AdapterYield::Event(IngestEvent::Session(mut session)) = yielded else {
        return yielded;
    };
    session.source_agent = if session.source_agent == NAME {
        attribution.source_agent_root.clone()
    } else {
        format!("{}/subagent", attribution.source_agent_root)
    };
    session.project = attribution.project.clone();
    let (key, value) = &attribution.extra_options;
    session.options.insert(key.clone(), value.clone());
    AdapterYield::Event(IngestEvent::Session(session))
}

/// A discovered session tagged by source, plus its freshness watermark peek in
/// micros (`None` = not peeked or unreadable -> re-read to be safe).
struct HeadEntry {
    source: SessionSource,
    source_ts: Option<i64>,
}

/// Where a session's records come from: a SQLite DB (identified by id, its full
/// row fetched at read time) or the legacy split tree.
enum SessionSource {
    Db(DbLight),
    Tree(SessionFile),
}

impl SessionSource {
    fn session_id(&self) -> &str {
        match self {
            SessionSource::Db(light) => &light.session_id,
            SessionSource::Tree(file) => &file.session_id,
        }
    }
}

/// A DB session located by the light enumeration SELECT: the DB it lives in, its
/// id, and which table generation carries it. The full session row is fetched by
/// primary key at read time so the freshness gate never materializes a row it
/// may skip.
struct DbLight {
    db_path: PathBuf,
    session_id: String,
    store: DbStore,
}

/// Which session tables of one DB carry a session.
enum DbStore {
    /// `session`/`message`/`part` only (OpenCode 1, or never migrated).
    V1,
    /// A V2 head in `head` (`session_v2`, or `session` in a pre-release
    /// OpenCode 2 DB) with its body in `session_message`.
    V2 { head: &'static str },
    /// Both: an OpenCode 1 session the V1->V2 migration copied forward.
    Migrated,
}

/// The enumerated (and optionally peeked) session set, plus the once-resolved
/// tree base carried through to the read pass and any per-source enumeration
/// failures collected for the gate to surface.
struct Peeked {
    tree_base: PathBuf,
    entries: Vec<HeadEntry>,
    /// Sessions an earlier source already carries (`opencode.db` over another
    /// DB, any DB over the tree); counted, not read.
    duplicates: usize,
    errors: Vec<AdapterError>,
}

/// Enumerate both sources into light entries, dedup by session id (every DB
/// session id, plus the legacy-tree sessions no DB carries,
/// `adapter-integrity-dedup`), and - when `peek` - compute each session's
/// freshness watermark. A single connection per DB is opened for the id SELECT
/// and reused for every one of that DB's session peeks (no double open). Tree
/// walks cache their listings on the `SessionFile` so the read pass does not
/// re-list.
///
/// Error resilience (spec.md#adapter-integrity-no-silent-drops), two levels:
/// - a per-session watermark peek that fails degrades to `source_ts = None`
///   (never fresh, so a safe re-read), not propagated;
/// - a per-source failure (a DB that won't open, its id SELECT fails, or an
///   unlistable tree) is `warn!`-logged naming the source and collected into
///   `errors`, and enumeration continues with the remaining sources.
fn enumerate_and_peek(root: &Path, peek: bool) -> Peeked {
    let tree_base = tree_base(root);
    let mut errors = Vec::new();
    let mut conns: HashMap<PathBuf, Connection> = HashMap::new();

    // DB side: light `(db_path, session_id)` per session, resilient per source.
    let mut db_entries: Vec<DbLight> = Vec::new();
    let mut db_ids: HashSet<String> = HashSet::new();
    let mut duplicates = 0usize;
    let paths = match db_paths(root) {
        Ok(paths) => paths,
        Err(error) => {
            tracing::warn!(path = %root.display(), %error, "opencode: listing DB files failed");
            errors.push(error);
            Vec::new()
        }
    };
    for db_path in paths {
        match db_session_ids(&mut conns, &db_path) {
            Ok(ids) => {
                for (id, store) in ids {
                    // OpenCode 2's migration imports a pre-release
                    // `opencode-next.db` into `opencode.db`, so the same session
                    // can sit in two DBs; the first DB (`opencode.db` leads)
                    // wins and the rest count as superseded.
                    if !db_ids.insert(id.clone()) {
                        duplicates += 1;
                        continue;
                    }
                    db_entries.push(DbLight {
                        db_path: db_path.clone(),
                        session_id: id,
                        store,
                    });
                }
            }
            Err(error) => {
                tracing::warn!(
                    path = %db_path.display(),
                    %error,
                    "opencode: enumerating DB sessions failed"
                );
                errors.push(error);
            }
        }
    }

    // Tree side: list session files and dedup against the DB ids.
    let mut tree_entries: Vec<SessionFile> = Vec::new();
    match collect_session_files(&tree_base) {
        Ok(files) => {
            for file in files {
                if db_ids.contains(&file.session_id) {
                    duplicates += 1;
                } else {
                    tree_entries.push(file);
                }
            }
        }
        Err(error) => {
            tracing::warn!(
                path = %tree_base.display(),
                %error,
                "opencode: listing tree sessions failed"
            );
            errors.push(error);
        }
    }

    let mut entries = Vec::with_capacity(db_entries.len() + tree_entries.len());
    for light in db_entries {
        let source_ts = if peek {
            match connection(&mut conns, &light.db_path) {
                Ok(conn) => db_store_watermark(conn, &light).unwrap_or(None),
                Err(_) => None,
            }
        } else {
            None
        };
        entries.push(HeadEntry {
            source: SessionSource::Db(light),
            source_ts,
        });
    }
    for mut file in tree_entries {
        let source_ts = if peek {
            match walk_session_subtree(&tree_base, &file.session_id) {
                Ok(walk) => {
                    let ts = newest_message_ts(&walk);
                    file.cached_subtree = Some(walk);
                    ts
                }
                Err(_) => None,
            }
        } else {
            None
        };
        entries.push(HeadEntry {
            source: SessionSource::Tree(file),
            source_ts,
        });
    }

    Peeked {
        tree_base,
        entries,
        duplicates,
        errors,
    }
}

/// Read every survivor session's body, streaming events through `tx`. Opens each
/// DB once (cached by path); tree sessions route through the legacy read path.
/// Keeps its OWN connection cache: the enumerate/peek pass's handles are dropped
/// before this runs, so no rusqlite handle is dragged across the await between
/// them.
fn read_survivors(
    tree_base: &Path,
    survivors: Vec<SessionSource>,
    tx: &mpsc::Sender<Result<AdapterYield, AdapterError>>,
) {
    let mut conns: HashMap<PathBuf, Connection> = HashMap::new();
    for source in survivors {
        let keep = match source {
            SessionSource::Db(light) => read_db_survivor(&mut conns, light, tx),
            SessionSource::Tree(file) => read_one_session(tree_base, file, tx),
        };
        if !keep {
            return;
        }
    }
}

/// Fetch one DB survivor's full `session` row by primary key (the peek carried
/// only the id), build its head, and stream its body. A row that vanished between
/// enumeration and read (opencode deleted the session; our separate statements
/// share no snapshot) yields a typed error for that session and continues
/// (spec.md#adapter-integrity-no-silent-drops).
fn read_db_survivor(
    conns: &mut HashMap<PathBuf, Connection>,
    light: DbLight,
    tx: &mpsc::Sender<Result<AdapterYield, AdapterError>>,
) -> bool {
    // DB session ids become restore filenames; a hostile id fails here at
    // ingest, typed and attributed, like the tree path's four gates.
    if let Err(error) = validate_path_id(
        NAME,
        "session id",
        &light.session_id,
        record_location(&light.db_path, &light.session_id, &light.session_id),
    ) {
        return tx.blocking_send(Err(error)).is_ok();
    }
    let conn = match connection(conns, &light.db_path) {
        Ok(conn) => conn,
        Err(error) => return tx.blocking_send(Err(error)).is_ok(),
    };
    let head = match light.store {
        DbStore::V1 | DbStore::Migrated => {
            fetch_db_session_head(conn, &light.db_path, &light.session_id)
        }
        DbStore::V2 { head } => {
            fetch_v2_session_head(conn, &light.db_path, &light.session_id, head)
        }
    };
    match head {
        Ok(Some(head)) => {
            let session_id = head.id.clone();
            let anchor = head.created_at;
            emit!(tx, Ok(AdapterYield::Event(IngestEvent::Session(head))));
            match light.store {
                DbStore::V1 => read_db_session(conn, &light.db_path, &session_id, anchor, tx),
                DbStore::V2 { .. } => {
                    read_v2_messages(conn, &light.db_path, &session_id, anchor, None, tx)
                }
                DbStore::Migrated => {
                    if !read_db_session(conn, &light.db_path, &session_id, anchor, tx) {
                        return false;
                    }
                    let copies = match migration_copies(conn, &light.db_path, &session_id) {
                        Ok(copies) => copies,
                        Err(error) => return tx.blocking_send(Err(error)).is_ok(),
                    };
                    read_v2_messages(conn, &light.db_path, &session_id, anchor, Some(&copies), tx)
                }
            }
        }
        Ok(None) => {
            let error = AdapterError::schema(
                NAME,
                record_location(&light.db_path, &light.session_id, &light.session_id),
                "session row vanished between enumeration and read",
            );
            tx.blocking_send(Err(error)).is_ok()
        }
        Err(error) => tx.blocking_send(Err(error)).is_ok(),
    }
}

/// `NAME`-bound view of the shared [`sqlite`] plumbing (one impl, two adapters).
fn join_error(join: tokio::task::JoinError) -> AdapterError {
    sqlite::join_error(NAME, join)
}

/// One session file located on disk. `cached_subtree` is populated only when
/// the freshness pre-walk happened (i.e. the oracle had a watermark for this
/// session); the read pass reuses the listings instead of re-walking.
struct SessionFile {
    session_id: String,
    path: PathBuf,
    cached_subtree: Option<SubtreeWalk>,
}

/// Result of one subtree walk: the message and part directory listings (so the
/// read pass doesn't redo them). The last `message_files` entry is the session's
/// latest message id for the freshness check.
struct SubtreeWalk {
    message_files: Vec<PathBuf>,
    /// One entry per message file, in the same order; each is the sorted list
    /// of part files for that message. Empty vec = message has no parts.
    part_files_by_message: Vec<Vec<PathBuf>>,
}

/// Walk `<root>/session/<projectID>/<sessionID>.json`, sorted for deterministic
/// ingest order. A missing `session/` dir means "no sessions yet", not an error.
fn collect_session_files(root: &Path) -> Result<Vec<SessionFile>, AdapterError> {
    let session_root = root.join("session");
    let io = |path: &Path, source| AdapterError::io(NAME, path.display().to_string(), source);
    let entries = match std::fs::read_dir(&session_root) {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => return Err(io(&session_root, error)),
    };
    let mut out = Vec::new();
    for project in entries {
        let project = project.map_err(|error| io(&session_root, error))?;
        if !project
            .file_type()
            .map_err(|error| io(&project.path(), error))?
            .is_dir()
        {
            continue;
        }
        let project_dir = project.path();
        for session in std::fs::read_dir(&project_dir).map_err(|error| io(&project_dir, error))? {
            let session = session.map_err(|error| io(&project_dir, error))?;
            let path = session.path();
            if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
                continue;
            }
            let Some(session_id) = path
                .file_stem()
                .and_then(|s| s.to_str())
                .map(ToOwned::to_owned)
            else {
                continue;
            };
            validate_path_id(
                NAME,
                "session file name",
                &session_id,
                path.display().to_string(),
            )?;
            out.push(SessionFile {
                session_id,
                path,
                cached_subtree: None,
            });
        }
    }
    out.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(out)
}

/// Walk one session's full subtree: the message files under `message/<sid>/` and
/// every part file under `part/<mid>/`, returning the listings so the read pass
/// can reuse them.
fn walk_session_subtree(tree_base: &Path, session_id: &str) -> Result<SubtreeWalk, AdapterError> {
    let message_dir = tree_base.join("message").join(session_id);
    let message_files = list_json_sorted(&message_dir)?;
    let mut part_files_by_message = Vec::with_capacity(message_files.len());
    for message_path in &message_files {
        let Some(message_id) = message_path.file_stem().and_then(|stem| stem.to_str()) else {
            part_files_by_message.push(Vec::new());
            continue;
        };
        validate_path_id(
            NAME,
            "message file name",
            message_id,
            message_path.display().to_string(),
        )?;
        let part_dir = tree_base.join("part").join(message_id);
        let parts = list_json_sorted(&part_dir)?;
        part_files_by_message.push(parts);
    }
    Ok(SubtreeWalk {
        message_files,
        part_files_by_message,
    })
}

/// Watermark for the freshness gate: the session's max stored message timestamp,
/// read from the last message's subtree (its `time.created` raised by any of its
/// tool parts' `state.time.end`, via [`watermark_micros`]). Earlier messages'
/// events all precede the last message, so its subtree suffices. `None` on an
/// empty session or unreadable last message -> safe re-read. Reads only the last
/// message and its parts (a handful of small files).
fn newest_message_ts(walk: &SubtreeWalk) -> Option<i64> {
    let message = read_json(walk.message_files.last()?).ok()?;
    let parts = walk
        .part_files_by_message
        .last()
        .into_iter()
        .flatten()
        .filter_map(|part_path| read_json(part_path).ok());
    watermark_micros(&message, parts)
}

/// The freshness-watermark kernel (micros): the message's `data.time.created`,
/// raised by each part's `state.time.end`; `.timestamp_micros()`. `None` (the
/// message carries no `time.created`) = safe re-read.
///
/// KNOWN RESIDUAL: the peek reads only the newest message's subtree, while pond's
/// stored watermark is a global max over ALL messages, including the synthetic
/// tool carrier messages stamped at their `state.time.end`. So an earlier
/// message's tool end outrunning a later message's `time.created` (clock skew,
/// out-of-order end) can over-skip. Accepted: ULID message ordering plus
/// opencode's turn protocol make it unreachable in practice, and `pond sync
/// --verify` is the full-re-read backstop (the same posture as the equal-micros
/// residual documented on `SkipOracle` in adapter/mod.rs).
fn watermark_micros(message: &Value, parts: impl IntoIterator<Item = Value>) -> Option<i64> {
    let mut newest = millis_at(message, &["time", "created"])?;
    for part in parts {
        if let Some(end) = millis_at(&part, &["state", "time", "end"]) {
            newest = newest.max(end);
        }
    }
    Some(newest.timestamp_micros())
}

/// Returns `false` when the consumer dropped the receiver and the read should stop.
fn read_one_session(
    tree_base: &Path,
    file: SessionFile,
    tx: &mpsc::Sender<Result<AdapterYield, AdapterError>>,
) -> bool {
    let session_value = match read_json(&file.path) {
        Ok(value) => value,
        Err(error) => {
            emit!(tx, Err(error));
            return true;
        }
    };
    let session = match session_from_value(&session_value, &file.path) {
        Ok(session) => session,
        Err(error) => {
            emit!(tx, Err(error));
            return true;
        }
    };
    let session_id = session.id.clone();
    if let Err(error) = validate_path_id(
        NAME,
        "session id",
        &session_id,
        file.path.display().to_string(),
    ) {
        emit!(tx, Err(error));
        return true;
    }
    let session_created_at = session.created_at;
    emit!(tx, Ok(AdapterYield::Event(IngestEvent::Session(session))));

    // Reuse the freshness pre-walk's listings when present; otherwise list now.
    let (message_files, mut part_files_by_message) = match file.cached_subtree {
        Some(walk) => (walk.message_files, walk.part_files_by_message),
        None => {
            let message_dir = tree_base.join("message").join(&session_id);
            let files = match list_json_sorted(&message_dir) {
                Ok(files) => files,
                Err(error) => {
                    emit!(tx, Err(error));
                    return true;
                }
            };
            (files, Vec::new())
        }
    };
    let use_cache = !part_files_by_message.is_empty();

    for (index, message_path) in message_files.iter().enumerate() {
        let message_value = match read_json(message_path) {
            Ok(value) => value,
            Err(error) => {
                emit!(tx, Err(error));
                continue;
            }
        };
        let Some(message_id) = message_value.get("id").and_then(Value::as_str) else {
            emit!(
                tx,
                Err(AdapterError::schema(
                    NAME,
                    message_path.display().to_string(),
                    "message file missing `id`",
                ))
            );
            continue;
        };
        if let Err(error) = validate_path_id(
            NAME,
            "message id",
            message_id,
            message_path.display().to_string(),
        ) {
            emit!(tx, Err(error));
            continue;
        }
        let part_files = if use_cache {
            std::mem::take(&mut part_files_by_message[index])
        } else {
            let part_dir = tree_base.join("part").join(message_id);
            match list_json_sorted(&part_dir) {
                Ok(files) => files,
                Err(error) => {
                    emit!(tx, Err(error));
                    continue;
                }
            }
        };
        let mut parts = Vec::with_capacity(part_files.len());
        for part_path in part_files {
            match read_json(&part_path) {
                Ok(value) => parts.push(value),
                Err(error) => emit!(tx, Err(error)),
            }
        }
        match build_message_events(&session_id, &message_value, &parts, session_created_at) {
            Ok(events) => {
                for event in events {
                    emit!(tx, Ok(AdapterYield::Event(event)));
                }
            }
            Err(error) => emit!(tx, Err(error)),
        }
    }
    true
}

/// The `session` table's columns as a SELECT list. Read by name in
/// [`session_info_from_row`], so this order is NOT load-bearing - it only fixes
/// the projected column set.
const SESSION_COLUMNS: &str = "id, project_id, workspace_id, parent_id, slug, directory, path, \
     title, version, share_url, summary_additions, summary_deletions, summary_files, \
     summary_diffs, metadata, cost, tokens_input, tokens_output, tokens_reasoning, \
     tokens_cache_read, tokens_cache_write, revert, permission, agent, model, time_created, \
     time_updated, time_compacting, time_archived";

/// List the `*.<extension>` files directly in `dir` whose file name passes
/// `name_filter`, sorted by path (= creation order, ids are time-sortable). A
/// missing dir is an empty list, not an error - a source dir may not exist yet.
fn list_files_sorted(
    dir: &Path,
    extension: &str,
    name_filter: impl Fn(&str) -> bool,
) -> Result<Vec<PathBuf>, AdapterError> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => return Err(AdapterError::io(NAME, dir.display().to_string(), error)),
    };
    let mut out = Vec::new();
    for entry in entries {
        let entry =
            entry.map_err(|error| AdapterError::io(NAME, dir.display().to_string(), error))?;
        let path = entry.path();
        if path.extension().and_then(|ext| ext.to_str()) != Some(extension) {
            continue;
        }
        if path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(&name_filter)
        {
            out.push(path);
        }
    }
    out.sort();
    Ok(out)
}

/// Every `opencode*.db` directly under `root` (WAL `-wal`/`-shm` sidecars are
/// excluded by the `.db` extension filter). A missing root is "no DB", not an
/// error - the adapter may be pointed at a bare legacy tree.
fn db_paths(root: &Path) -> Result<Vec<PathBuf>, AdapterError> {
    let mut paths = list_files_sorted(root, "db", |name| name.starts_with("opencode"))?;
    // The live DB leads, so it wins a session id another DB repeats.
    paths.sort_by_key(|path| path.file_name() != Some(std::ffi::OsStr::new("opencode.db")));
    Ok(paths)
}

/// Test-only direct open (the non-test path opens through [`connection`]).
#[cfg(test)]
fn open_db(path: &Path) -> Result<Connection, AdapterError> {
    sqlite::open_db(NAME, path)
}

/// DB-interaction failures route through [`sqlite::db_error`] as
/// [`AdapterError::io`]; genuine shape errors route through
/// [`reconstruct_record`]'s parse errors instead.
fn db_error(path: &Path, op: &str, error: &rusqlite::Error) -> AdapterError {
    sqlite::db_error(NAME, path, op, error)
}

/// Get-or-open a cached connection for `path`.
fn connection<'a>(
    conns: &'a mut HashMap<PathBuf, Connection>,
    path: &Path,
) -> Result<&'a Connection, AdapterError> {
    sqlite::connection(NAME, conns, path)
}

/// Every session id in one DB with the table generation(s) carrying it, ordered
/// by id for deterministic ingest. Each table is read only when it exists: a
/// fresh OpenCode 2 install has no V1 tables, an OpenCode 1 DB no `session_v2`.
/// A pre-release OpenCode 2 DB (the `opencode-next.db` its migration imports)
/// keeps V2 heads in a table still named `session`; those sessions are told
/// apart from V1 ones by having `session_message` rows, which OpenCode 1 never
/// writes, or - an empty one - by the DB having no V1 `message` table. Uses the shared connection cache so enumeration and the per-session
/// peeks share a single open per DB.
fn db_session_ids(
    conns: &mut HashMap<PathBuf, Connection>,
    db_path: &Path,
) -> Result<Vec<(String, DbStore)>, AdapterError> {
    let conn = connection(conns, db_path)?;
    let v1 = table_ids(conn, db_path, "session")?;
    let v2 = table_ids(conn, db_path, "session_v2")?;
    let v2_set: HashSet<&str> = v2.iter().map(String::as_str).collect();
    let has_v2_body = table_exists(conn, db_path, "session_message")?;
    let prerelease = has_v2_body && !table_exists(conn, db_path, "message")?;
    let with_v2_body: HashSet<String> = if has_v2_body {
        conn.prepare_cached("SELECT DISTINCT session_id FROM session_message")
            .and_then(|mut stmt| {
                stmt.query_map([], |row| row.get::<_, String>(0))?
                    .collect::<rusqlite::Result<_>>()
            })
            .map_err(|error| db_error(db_path, "list v2 message sessions", &error))?
    } else {
        HashSet::new()
    };
    let v1_set: HashSet<&str> = v1.iter().map(String::as_str).collect();
    let mut ids: Vec<(String, DbStore)> = v1
        .iter()
        .map(|id| {
            let store = if v2_set.contains(id.as_str()) {
                DbStore::Migrated
            } else if prerelease || with_v2_body.contains(id) {
                DbStore::V2 { head: "session" }
            } else {
                DbStore::V1
            };
            (id.clone(), store)
        })
        .chain(
            v2.iter()
                .filter(|id| !v1_set.contains(id.as_str()))
                .map(|id| (id.clone(), DbStore::V2 { head: "session_v2" })),
        )
        .collect();
    ids.sort_unstable_by(|a, b| a.0.cmp(&b.0));
    Ok(ids)
}

fn table_exists(conn: &Connection, db_path: &Path, table: &str) -> Result<bool, AdapterError> {
    sqlite::has_table(conn, table)
        .map_err(|error| db_error(db_path, &format!("probe {table} table"), &error))
}

/// Every `id` in `table`, or none when the DB has no such table.
fn table_ids(conn: &Connection, db_path: &Path, table: &str) -> Result<Vec<String>, AdapterError> {
    if !table_exists(conn, db_path, table)? {
        return Ok(Vec::new());
    }
    let mut stmt = conn
        .prepare_cached(&format!("SELECT id FROM {table}"))
        .map_err(|error| db_error(db_path, &format!("prepare {table} ids"), &error))?;
    let rows = stmt
        .query_map([], |row| row.get::<_, String>(0))
        .map_err(|error| db_error(db_path, &format!("query {table} ids"), &error))?;
    rows.collect::<rusqlite::Result<Vec<_>>>()
        .map_err(|error| db_error(db_path, &format!("read {table} id"), &error))
}

/// Fetch one `session` row by primary key and map it to a canonical [`Session`].
/// `Ok(None)` when no row matches (the session vanished between enumeration and
/// read - our separate statements share no snapshot).
fn fetch_db_session_head(
    conn: &Connection,
    db_path: &Path,
    session_id: &str,
) -> Result<Option<Session>, AdapterError> {
    let mut stmt = conn
        .prepare_cached(&format!(
            "SELECT {SESSION_COLUMNS} FROM session WHERE id = ?1"
        ))
        .map_err(|error| db_error(db_path, "prepare session by id", &error))?;
    let info = stmt
        .query_row([session_id], session_info_from_row)
        .optional()
        .map_err(|error| db_error(db_path, "query session by id", &error))?;
    info.map(|info| db_session_head(db_path, &info)).transpose()
}

/// Map one reconstructed `SessionInfo` to a canonical [`Session`]. Reusing
/// [`session_from_value`] threads `directory` through the sealed `Extracted` path
/// and derives `created_at` from the row `time.created`.
fn db_session_head(db_path: &Path, info: &Value) -> Result<Session, AdapterError> {
    let mut session = session_from_value(info, db_path)?;
    // spec.md#model-no-synthesis: a subagent session (`parentID` set) is labeled
    // `opencode/<agent>` so children leave default search, matching claude-code; a
    // null agent column degrades to the bare `opencode/subagent` label. Tree-era
    // child sessions carry no agent column and keep the plain `opencode` the tree
    // path assigns: `source_agent` is immutable after first write
    // (spec.md#adapter-integrity-additive-sync), so relabeling would fork history
    // against already-stored rows.
    if info.get("parentID").and_then(Value::as_str).is_some() {
        session.source_agent = match info.get("agent").and_then(Value::as_str) {
            Some(agent) => format!("{NAME}/{agent}"),
            None => format!("{NAME}/subagent"),
        };
    }
    Ok(session)
}

/// Rebuild the `fromRow` `SessionInfo` JSON from a `session` row by NAME
/// (`&str` implements `RowIndex`): camelCase keys, nested `time`/`tokens`/`summary`,
/// null columns omitted (spec.md#model-lossless-projection - every non-null column
/// is recoverable). JSON-mode columns (model, metadata, permission, revert,
/// summary diffs) go through [`json_or_string`]. This is the shape
/// [`session_from_value`] and the DB conformance test both consume.
fn session_info_from_row(row: &rusqlite::Row) -> rusqlite::Result<Value> {
    let mut info = serde_json::Map::new();
    info.insert("id".to_owned(), json!(row.get::<_, String>("id")?));
    info.insert("slug".to_owned(), json!(row.get::<_, String>("slug")?));
    info.insert(
        "projectID".to_owned(),
        json!(row.get::<_, String>("project_id")?),
    );
    if let Some(value) = row.get::<_, Option<String>>("workspace_id")? {
        info.insert("workspaceID".to_owned(), json!(value));
    }
    info.insert(
        "directory".to_owned(),
        json!(row.get::<_, String>("directory")?),
    );
    if let Some(value) = row.get::<_, Option<String>>("path")? {
        info.insert("path".to_owned(), json!(value));
    }
    if let Some(value) = row.get::<_, Option<String>>("parent_id")? {
        info.insert("parentID".to_owned(), json!(value));
    }
    info.insert("title".to_owned(), json!(row.get::<_, String>("title")?));
    if let Some(value) = row.get::<_, Option<String>>("agent")? {
        info.insert("agent".to_owned(), json!(value));
    }
    if let Some(value) = row.get::<_, Option<String>>("model")? {
        info.insert("model".to_owned(), json_or_string(&value));
    }
    info.insert(
        "version".to_owned(),
        json!(row.get::<_, String>("version")?),
    );
    let summary_additions = row.get::<_, Option<i64>>("summary_additions")?;
    let summary_deletions = row.get::<_, Option<i64>>("summary_deletions")?;
    let summary_files = row.get::<_, Option<i64>>("summary_files")?;
    let summary_diffs = row.get::<_, Option<String>>("summary_diffs")?;
    if summary_additions.is_some() || summary_deletions.is_some() || summary_files.is_some() {
        let mut summary = serde_json::Map::new();
        summary.insert(
            "additions".to_owned(),
            json!(summary_additions.unwrap_or(0)),
        );
        summary.insert(
            "deletions".to_owned(),
            json!(summary_deletions.unwrap_or(0)),
        );
        summary.insert("files".to_owned(), json!(summary_files.unwrap_or(0)));
        if let Some(value) = &summary_diffs {
            summary.insert("diffs".to_owned(), json_or_string(value));
        }
        info.insert("summary".to_owned(), Value::Object(summary));
    }
    info.insert("cost".to_owned(), json!(row.get::<_, f64>("cost")?));
    info.insert(
        "tokens".to_owned(),
        json!({
            "input": row.get::<_, i64>("tokens_input")?,
            "output": row.get::<_, i64>("tokens_output")?,
            "reasoning": row.get::<_, i64>("tokens_reasoning")?,
            "cache": {
                "read": row.get::<_, i64>("tokens_cache_read")?,
                "write": row.get::<_, i64>("tokens_cache_write")?,
            },
        }),
    );
    if let Some(value) = row.get::<_, Option<String>>("share_url")? {
        info.insert("share".to_owned(), json!({ "url": value }));
    }
    if let Some(value) = row.get::<_, Option<String>>("metadata")? {
        info.insert("metadata".to_owned(), json_or_string(&value));
    }
    if let Some(value) = row.get::<_, Option<String>>("revert")? {
        info.insert("revert".to_owned(), json_or_string(&value));
    }
    if let Some(value) = row.get::<_, Option<String>>("permission")? {
        info.insert("permission".to_owned(), json_or_string(&value));
    }
    let mut time = serde_json::Map::new();
    time.insert(
        "created".to_owned(),
        json!(row.get::<_, i64>("time_created")?),
    );
    time.insert(
        "updated".to_owned(),
        json!(row.get::<_, i64>("time_updated")?),
    );
    if let Some(value) = row.get::<_, Option<i64>>("time_compacting")? {
        time.insert("compacting".to_owned(), json!(value));
    }
    if let Some(value) = row.get::<_, Option<i64>>("time_archived")? {
        time.insert("archived".to_owned(), json!(value));
    }
    info.insert("time".to_owned(), Value::Object(time));
    Ok(Value::Object(info))
}

/// Freshness watermark for a DB session (micros): the newest message by id order,
/// its `data.time.created` raised by any of its tool parts' `state.time.end` (via
/// [`watermark_micros`]). NEVER the `time_created` COLUMN - migration-stamped rows
/// carry a future column value that would re-read forever.
/// `None` (empty or unreadable newest message) -> safe re-read.
///
/// The probe is two statements on purpose: the newest id comes from a covering
/// scan of the `(session_id, time_created, id)` index (ids only - the sort
/// discards every row but one, so materializing `data` per row would read the
/// session's whole `data` column just to keep one blob), then that single
/// row's `data` is fetched by primary key. The only streamable alternative
/// order is `time_created` (the poisoned migration column), so this MUST NOT
/// be "optimized" onto it.
fn db_session_watermark(
    conn: &Connection,
    db_path: &Path,
    session_id: &str,
) -> Result<Option<i64>, AdapterError> {
    let mut newest_stmt = conn
        .prepare_cached("SELECT id FROM message WHERE session_id = ?1 ORDER BY id DESC LIMIT 1")
        .map_err(|error| db_error(db_path, "prepare newest message id", &error))?;
    let newest = newest_stmt
        .query_row([session_id], |row| row.get::<_, String>(0))
        .optional()
        .map_err(|error| db_error(db_path, "query newest message id", &error))?;
    let Some(message_id) = newest else {
        return Ok(None);
    };
    let mut data_stmt = conn
        .prepare_cached("SELECT data FROM message WHERE id = ?1")
        .map_err(|error| db_error(db_path, "prepare newest message data", &error))?;
    let data = data_stmt
        .query_row([&message_id], |row| row.get::<_, String>(0))
        .optional()
        .map_err(|error| db_error(db_path, "query newest message data", &error))?;
    // A row vanishing between the two statements (live writer) is a safe
    // re-read, same as an unparseable one.
    let Some(data) = data else {
        return Ok(None);
    };
    let Ok(message) = serde_json::from_str::<Value>(&data) else {
        return Ok(None);
    };
    let mut stmt = conn
        .prepare_cached("SELECT data FROM part WHERE message_id = ?1 ORDER BY id")
        .map_err(|error| db_error(db_path, "prepare newest parts", &error))?;
    let rows = stmt
        .query_map([&message_id], |row| row.get::<_, String>(0))
        .map_err(|error| db_error(db_path, "query newest parts", &error))?;
    let datas = rows
        .collect::<rusqlite::Result<Vec<_>>>()
        .map_err(|error| db_error(db_path, "read newest part row", &error))?;
    let parts = datas
        .iter()
        .filter_map(|data| serde_json::from_str::<Value>(data).ok());
    Ok(watermark_micros(&message, parts))
}

/// Owned projection of one `message`/`part` row: its id (for ordering and id
/// injection) and its `data` blob. The row `time_created` column is deliberately
/// not projected (see the `default_ts` note in [`read_db_session`]).
struct RecordRow {
    id: String,
    data: String,
}

fn fetch_records(
    conn: &Connection,
    db_path: &Path,
    sql: &str,
    param: &str,
    kind: &str,
) -> Result<Vec<RecordRow>, AdapterError> {
    let mut stmt = conn
        .prepare_cached(sql)
        .map_err(|error| db_error(db_path, &format!("prepare {kind}"), &error))?;
    let rows = stmt
        .query_map([param], |row| {
            Ok(RecordRow {
                id: row.get(0)?,
                data: row.get(1)?,
            })
        })
        .map_err(|error| db_error(db_path, &format!("query {kind}"), &error))?;
    rows.collect::<rusqlite::Result<Vec<_>>>()
        .map_err(|error| db_error(db_path, &format!("read {kind} row"), &error))
}

/// Read one DB session's body in short bursts (messages, then per-message parts -
/// each query its own autocommit read, never one long transaction), feeding the
/// same `build_message_events` pipeline as the tree path. Returns `false` when
/// the consumer dropped the receiver.
fn read_db_session(
    conn: &Connection,
    db_path: &Path,
    session_id: &str,
    session_anchor: DateTime<Utc>,
    tx: &mpsc::Sender<Result<AdapterYield, AdapterError>>,
) -> bool {
    // No `ORDER BY id` in SQL: no index ends in bare `id`, so an SQL sort forces a
    // transient temp b-tree over the full rows (~2x memory), and chunked keyset
    // pagination would be O(N^2) re-sorts. The accepted bound is O(one session)
    // resident, sorted in Rust below (BINARY collation == Rust byte order,
    // verified no `COLLATE` on `id`).
    let mut messages = match fetch_records(
        conn,
        db_path,
        "SELECT id, data FROM message WHERE session_id = ?1",
        session_id,
        "message",
    ) {
        Ok(rows) => rows,
        Err(error) => {
            emit!(tx, Err(error));
            return true;
        }
    };
    messages.sort_unstable_by(|a, b| a.id.cmp(&b.id));

    for message in messages {
        let message_id = message.id;
        // spec.md#model-no-synthesis: `build_message_events` prefers the message's
        // own `data.time.created`; when it is absent the session anchor is the
        // spec-blessed fallback. The row `time_created` COLUMN is deliberately NOT
        // used: it is migration-stamped, and a future column value would become the
        // stored watermark and freshness-skip every later real message. Trade-off:
        // a non-migrated message genuinely lacking `data.time.created` takes the
        // coarser session anchor even though its column was accurate - accepted
        // because ordering still survives via the id tiebreaker.
        let default_ts = session_anchor;
        let message_value = match reconstruct_record(
            &message.data,
            [("id", json!(message_id)), ("sessionID", json!(session_id))],
            db_path,
            session_id,
            &message_id,
        ) {
            Ok(value) => value,
            Err(error) => {
                emit!(tx, Err(error));
                continue;
            }
        };

        // The part query KEEPS its `ORDER BY id`: it streams via the
        // (message_id, id) index (verified via EXPLAIN QUERY PLAN), no temp b-tree.
        let part_rows = match fetch_records(
            conn,
            db_path,
            "SELECT id, data FROM part WHERE message_id = ?1 ORDER BY id",
            &message_id,
            "part",
        ) {
            Ok(rows) => rows,
            Err(error) => {
                emit!(tx, Err(error));
                continue;
            }
        };
        let mut parts = Vec::with_capacity(part_rows.len());
        for part in part_rows {
            match reconstruct_record(
                &part.data,
                [
                    ("id", json!(part.id)),
                    ("sessionID", json!(session_id)),
                    ("messageID", json!(message_id)),
                ],
                db_path,
                session_id,
                &part.id,
            ) {
                Ok(value) => parts.push(value),
                Err(error) => emit!(tx, Err(error)),
            }
        }
        match build_message_events(session_id, &message_value, &parts, default_ts) {
            Ok(events) => {
                for event in events {
                    emit!(tx, Ok(AdapterYield::Event(event)));
                }
            }
            Err(error) => emit!(tx, Err(error)),
        }
    }
    true
}

/// Reconstruct a `message`/`part` value as `{...data, <injected>}`, delegating the
/// cap check, parse, and leaf bounding to [`parse_bounded`] before injecting the
/// row's ids. A malformed `data` JSON drops only that record, like a malformed
/// part file in the tree. `location` is formatted lazily (only on the error path).
fn reconstruct_record(
    data: &str,
    inject: impl IntoIterator<Item = (&'static str, Value)>,
    db_path: &Path,
    session_id: &str,
    record_id: &str,
) -> Result<Value, AdapterError> {
    let mut value = parse_bounded(NAME, data.as_bytes(), || {
        record_location(db_path, session_id, record_id)
    })?;
    if let Value::Object(map) = &mut value {
        for (key, injected) in inject {
            map.insert(key.to_owned(), injected);
        }
    }
    Ok(value)
}

/// Recognizes the rows OpenCode 2's V1->V2 migration wrote into a migrated
/// session: copies of records the V1 tables already hold. A copy keeps its V1
/// message id or carries the migration's deterministic `syntheticID` (the
/// user/synthetic split, the trailing legacy-tool notice). The migration writes
/// a session's copies as its `seq` prefix (`0..n`, before any live row, which
/// takes a later `seq`), so every row up to the last recognized copy is one too,
/// covering a salted id or the copy of a V1 message deleted since. Live rows
/// are never matched; the one miss is a copy of a V1 TAIL deleted after the
/// migration (an OpenCode 1.x revert after a downgrade), which re-ingests as a
/// duplicate of content already stored rather than being lost.
struct MigrationCopies {
    ids: HashSet<String>,
    through_seq: Option<i64>,
}

impl MigrationCopies {
    fn contains(&self, id: &str, seq: i64) -> bool {
        self.ids.contains(id) || self.through_seq.is_some_and(|through| seq <= through)
    }

    /// The first `seq` past the copy prefix. Every exact copy sits at or below
    /// `through_seq`, so reads start here and never fetch a copy's `data`.
    fn live_from(copies: Option<&Self>) -> i64 {
        copies
            .and_then(|copies| copies.through_seq)
            .map_or(i64::MIN, |through| through.saturating_add(1))
    }
}

fn migration_copies(
    conn: &Connection,
    db_path: &Path,
    session_id: &str,
) -> Result<MigrationCopies, AdapterError> {
    let read = |sql: &str, op: &str| -> Result<Vec<(String, Option<i64>)>, AdapterError> {
        conn.prepare_cached(sql)
            .and_then(|mut stmt| {
                stmt.query_map([session_id], |row| Ok((row.get(0)?, row.get(1)?)))?
                    .collect::<rusqlite::Result<_>>()
            })
            .map_err(|error| db_error(db_path, op, &error))
    };
    let mut ids = HashSet::new();
    for (id, _) in read(
        "SELECT id, NULL FROM message WHERE session_id = ?1",
        "read migrated message ids",
    )? {
        // The notice derives from the last projected row, itself possibly a split.
        let split = synthetic_id(&id);
        ids.insert(synthetic_id(&split));
        ids.insert(split);
        ids.insert(id);
    }
    let through_seq = read(
        "SELECT id, seq FROM session_message WHERE session_id = ?1",
        "read migrated v2 ids",
    )?
    .into_iter()
    .filter(|(id, _)| ids.contains(id))
    .filter_map(|(_, seq)| seq)
    .max();
    Ok(MigrationCopies { ids, through_seq })
}

/// OpenCode's `syntheticID` (`v1-migration.bun.ts`) at salt 0: the source id's
/// first 16 chars plus 14 base62 digits of `sha256("v1-synthetic:" + source)`.
/// The salted retry only fires on a collision with an existing id of the session.
fn synthetic_id(source: &str) -> String {
    use sha2::{Digest, Sha256};
    const ALPHABET: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    let mut value = Sha256::digest(format!("v1-synthetic:{source}")).to_vec();
    let mut suffix = [0u8; 14];
    for slot in suffix.iter_mut().rev() {
        // One step of big-endian long division by 62; the remainder is the digit.
        let mut remainder = 0u32;
        for byte in &mut value {
            let acc = (remainder << 8) | u32::from(*byte);
            *byte = u8::try_from(acc / 62).unwrap_or(u8::MAX);
            remainder = acc % 62;
        }
        *slot = ALPHABET[remainder as usize];
    }
    let prefix: String = source.chars().take(16).collect();
    format!("{prefix}{}", String::from_utf8_lossy(&suffix))
}

/// Whether OpenCode considers a record finished (`isSettled`, `transfer.ts`):
/// an assistant once `time.completed` is set, a shell or compaction once it is
/// no longer `running`. Until then OpenCode rewrites the row in place.
fn is_settled(kind: &str, record: &Value) -> bool {
    match kind {
        "assistant" => record.pointer("/time/completed").is_some(),
        "shell" | "compaction" => record.get("status").and_then(Value::as_str) != Some("running"),
        _ => true,
    }
}

/// Freshness watermark for one DB session, by the tables carrying it. A migrated
/// session's newest record is either its V1 tail or its newest post-migration V2
/// row, so it takes the max of both - unless the V2 side cannot say, which makes
/// the whole session unknown (a re-read that surfaces the fault).
fn db_store_watermark(conn: &Connection, light: &DbLight) -> Result<Option<i64>, AdapterError> {
    let (db_path, session_id) = (light.db_path.as_path(), light.session_id.as_str());
    match light.store {
        DbStore::V1 => db_session_watermark(conn, db_path, session_id),
        DbStore::V2 { .. } => Ok(match v2_session_watermark(conn, session_id, None)? {
            V2Watermark::At(ts) => Some(ts),
            V2Watermark::Empty | V2Watermark::Unknown => None,
        }),
        DbStore::Migrated => {
            let copies = migration_copies(conn, db_path, session_id)?;
            let v1 = db_session_watermark(conn, db_path, session_id)?;
            Ok(
                match v2_session_watermark(conn, session_id, Some(&copies))? {
                    V2Watermark::At(ts) => v1.max(Some(ts)),
                    V2Watermark::Empty => v1,
                    V2Watermark::Unknown => None,
                },
            )
        }
    }
}

enum V2Watermark {
    /// No V2 row this adapter emits (none yet, or only migration copies).
    Empty,
    At(i64),
    /// Completeness cannot be shown from timestamps: re-read.
    Unknown,
}

/// Freshness watermark for the V2 rows of a session (micros). The stored
/// watermark is a max timestamp, which only proves completeness when every row
/// lands with a timestamp above what is already stored. An `assistant` or
/// `compaction` row breaks that: it carries the time its step started, is
/// rewritten in place until it settles (deferred meanwhile by
/// [`read_v2_messages`]), and is inserted only at its first content, after any
/// steering rows - so its settling never raises the watermark. Both are
/// confined to the open turn, the rows from the last `idle` marker on (the
/// `(session_id, type, seq)` index finds it; the whole session before OpenCode
/// wrote idle markers), and the `idle` that closes the turn is newer than all
/// of it. So an open turn holding such a row, or an unreadable one, makes the
/// session unknown until that `idle` lands; so does a background shell still
/// running anywhere, since it outlives its turn. Otherwise the watermark is the
/// max of the timestamps [`build_v2_message_events`] stamps on the open turn's
/// rows and on every finished shell's output carrier; rows before the marker
/// are settled history the stored watermark already covers.
fn v2_session_watermark(
    conn: &Connection,
    session_id: &str,
    copies: Option<&MigrationCopies>,
) -> Result<V2Watermark, AdapterError> {
    let rows = (|| -> rusqlite::Result<(Vec<V2Row>, Vec<String>)> {
        let open_turn = conn
            .prepare_cached(
                "SELECT MAX(seq) FROM session_message WHERE session_id = ?1 AND type = 'idle'",
            )?
            .query_row([session_id], |row| row.get::<_, Option<i64>>(0))?
            .unwrap_or(i64::MIN)
            .max(MigrationCopies::live_from(copies));
        let turn = conn
            .prepare_cached(
                "SELECT id, type, seq, data FROM session_message \
                 WHERE session_id = ?1 AND seq >= ?2 ORDER BY seq",
            )?
            .query_map(rusqlite::params![session_id, open_turn], v2_row)?
            .collect::<rusqlite::Result<_>>()?;
        let shells = conn
            .prepare_cached(
                "SELECT data FROM session_message WHERE session_id = ?1 AND type = 'shell'",
            )?
            .query_map([session_id], |row| row.get(0))?
            .collect::<rusqlite::Result<_>>()?;
        Ok((turn, shells))
    })();
    let Ok((turn, shells)) = rows else {
        return Ok(V2Watermark::Unknown);
    };
    // A shell's output carrier is stamped at its end, which can postdate every
    // later row: those ends join the watermark wherever the shell sits.
    let mut newest: Option<DateTime<Utc>> = None;
    for data in &shells {
        let Ok(record) = serde_json::from_str::<Value>(data) else {
            return Ok(V2Watermark::Unknown);
        };
        if !is_settled("shell", &record) {
            return Ok(V2Watermark::Unknown);
        }
        newest = newest.max(millis_at(&record, &["time", "completed"]));
    }
    for (id, kind, seq, data) in turn {
        if copies.is_some_and(|copies| copies.contains(&id, seq)) {
            continue;
        }
        let Ok(record) = serde_json::from_str::<Value>(&data) else {
            return Ok(V2Watermark::Unknown);
        };
        let Some(created) = millis_at(&record, &["time", "created"]) else {
            return Ok(V2Watermark::Unknown);
        };
        if matches!(kind.as_str(), "assistant" | "compaction") || !is_settled(&kind, &record) {
            return Ok(V2Watermark::Unknown);
        }
        let emitted = v2_tool_items(&record)
            .filter_map(tool_result_time)
            .fold(created, DateTime::max);
        newest = newest.max(Some(emitted));
    }
    Ok(newest.map_or(V2Watermark::Empty, |ts| {
        V2Watermark::At(ts.timestamp_micros())
    }))
}

/// The `session_v2` columns read as JSON text (drizzle `mode: "json"`); every
/// other text column is a plain string.
const V2_JSON_COLUMNS: &[&str] = &[
    "fork_boundary",
    "summary_diffs",
    "metadata",
    "revert",
    "permission",
    "model",
];

/// Fetch one V2 session row by primary key from `table` (`session_v2`, or
/// `session` in a pre-release OpenCode 2 DB). The row is captured whole
/// (`SELECT *`, keyed by column name, null columns omitted) rather than through a
/// fixed column list: OpenCode 2 still adds session columns release to release,
/// and a lossless capture must not depend on pond knowing each one.
fn fetch_v2_session_head(
    conn: &Connection,
    db_path: &Path,
    session_id: &str,
    table: &'static str,
) -> Result<Option<Session>, AdapterError> {
    let mut stmt = conn
        .prepare_cached(&format!("SELECT * FROM {table} WHERE id = ?1"))
        .map_err(|error| db_error(db_path, "prepare v2 session by id", &error))?;
    let row = stmt
        .query_row([session_id], v2_row_value)
        .optional()
        .map_err(|error| db_error(db_path, "query v2 session by id", &error))?;
    row.map(|row| {
        let location = record_location(db_path, session_id, session_id);
        let row = parse_bounded(NAME, compact_json(&row).as_bytes(), || location.clone())?;
        session_from_v2_row(&row, &location, table)
    })
    .transpose()
}

fn v2_row_value(row: &rusqlite::Row) -> rusqlite::Result<Value> {
    let mut map = serde_json::Map::new();
    for (index, name) in row.as_ref().column_names().into_iter().enumerate() {
        let value = match sqlite::value_json(row.get_ref(index)?) {
            Value::Null => continue,
            Value::String(text) if V2_JSON_COLUMNS.contains(&name) => json_or_string(&text),
            value => value,
        };
        map.insert(name.to_owned(), value);
    }
    Ok(Value::Object(map))
}

/// A text column OpenCode's `fromRow` treats as set: non-null and non-empty.
fn set_column<'a>(row: &'a Value, name: &str) -> Option<&'a str> {
    row.get(name)
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())
}

/// Map a captured V2 session row to a canonical [`Session`]. Lineage: a spawned
/// child carries `parent_id`; a fork carries `fork_session_id` and a boundary
/// whose `through` message is its cut-point in the parent. A `before` boundary
/// names the first message NOT copied, so its cut-point is not recorded
/// (spec.md#model-no-synthesis).
fn session_from_v2_row(
    row: &Value,
    location: &str,
    table: &'static str,
) -> Result<Session, AdapterError> {
    let schema =
        |message: &str| AdapterError::schema(NAME, location.to_owned(), message.to_owned());
    let id = row
        .get("id")
        .and_then(Value::as_str)
        .ok_or_else(|| schema("v2 session row missing `id`"))?
        .to_owned();
    let created_at = millis_at(row, &["time_created"])
        .ok_or_else(|| schema("v2 session row missing `time_created`"))?;
    // spec.md#model-project-non-empty: `directory` is a NOT NULL column.
    let project = extract_str(row, "directory")
        .ok_or_else(|| schema("v2 session row missing `directory`"))?;
    let parent = set_column(row, "parent_id");
    let fork = set_column(row, "fork_session_id");
    let parent_message_id = fork
        .and(row.get("fork_boundary"))
        .filter(|boundary| boundary.get("type").and_then(Value::as_str) == Some("through"))
        .and_then(|boundary| boundary.get("messageID"))
        .and_then(Value::as_str)
        .map(ToOwned::to_owned);
    // A spawned child is labeled like a DB-era V1 child (`opencode/<agent>`); a
    // fork is a continuation, not a subagent, and keeps the bare brand.
    let source_agent = match (parent, set_column(row, "agent")) {
        (Some(_), Some(agent)) => format!("{NAME}/{agent}"),
        (Some(_), None) => format!("{NAME}/subagent"),
        (None, _) => NAME.to_owned(),
    };
    let mut options = opencode_raw(row);
    mark_source(&mut options, "store", json!(table));
    Ok(Session {
        id,
        parent_session_id: parent.or(fork).map(ToOwned::to_owned),
        parent_message_id,
        source_agent,
        created_at,
        project,
        options,
    })
}

/// Add a side field next to `options.source.raw_record` (the documented
/// extension point of [`source_options`]). `store` names the table a V2 session
/// head was read from; native restore keys the OpenCode 2 transfer shape off it.
fn mark_source(options: &mut ProviderOptions, key: &str, value: Value) {
    if let Some(Value::Object(source)) = options.get_mut("source") {
        source.insert(key.to_owned(), value);
    }
}

/// One `session_message` row: id, type, seq, `data`.
type V2Row = (String, String, i64, String);

fn v2_row(row: &rusqlite::Row) -> rusqlite::Result<V2Row> {
    Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
}

/// Read one session's `session_message` rows in `seq` order (streamed off the
/// unique `(session_id, seq)` index) and emit each as canonical events. Skipped:
/// with `copies`, the migration's copies of records already read from the V1
/// tables; and a row OpenCode is still rewriting in place - an unsettled row of
/// the open turn (after the last `idle`), or a background shell still running
/// wherever it sits, since it outlives its turn. Stored now, it would freeze
/// half-written under its final id (spec.md#adapter-integrity-additive-sync), so
/// it waits for a later sync (the watermark keeps the session unknown until
/// then). Any other unsettled row sits behind a later `idle` in a turn that
/// closed without settling it, and lands as found. Returns `false` when the
/// consumer dropped the receiver.
fn read_v2_messages(
    conn: &Connection,
    db_path: &Path,
    session_id: &str,
    session_anchor: DateTime<Utc>,
    copies: Option<&MigrationCopies>,
    tx: &mpsc::Sender<Result<AdapterYield, AdapterError>>,
) -> bool {
    let rows = (|| -> rusqlite::Result<Vec<rusqlite::Result<V2Row>>> {
        let mut stmt = conn.prepare_cached(
            "SELECT id, type, seq, data FROM session_message \
             WHERE session_id = ?1 AND seq >= ?2 ORDER BY seq",
        )?;
        let rows = stmt.query_map(
            rusqlite::params![session_id, MigrationCopies::live_from(copies)],
            v2_row,
        )?;
        Ok(rows.collect())
    })();
    let rows = match rows {
        Ok(rows) => rows,
        Err(error) => {
            emit!(tx, Err(db_error(db_path, "read v2 messages", &error)));
            return true;
        }
    };
    let open_turn = rows
        .iter()
        .flatten()
        .filter(|(_, kind, ..)| kind == "idle")
        .map(|(_, _, seq, ..)| *seq)
        .max()
        .unwrap_or(i64::MIN);
    for row in rows {
        let (id, kind, seq, data) = match row {
            Ok(row) => row,
            Err(error) => {
                emit!(tx, Err(db_error(db_path, "read v2 message row", &error)));
                continue;
            }
        };
        if copies.is_some_and(|copies| copies.contains(&id, seq)) {
            continue;
        }
        let record = match reconstruct_record(
            &data,
            [("id", json!(id)), ("type", json!(kind))],
            db_path,
            session_id,
            &id,
        ) {
            Ok(record) => record,
            Err(error) => {
                emit!(tx, Err(error));
                continue;
            }
        };
        if !is_settled(&kind, &record) && (seq > open_turn || kind == "shell") {
            continue;
        }
        for event in build_v2_message_events(session_id, &id, &record, seq, session_anchor) {
            emit!(tx, Ok(AdapterYield::Event(event)));
        }
    }
    true
}

/// The `tool` items of an assistant record's `content`.
fn v2_tool_items(record: &Value) -> impl Iterator<Item = &Value> {
    record
        .get("content")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter(|item| item.get("type").and_then(Value::as_str) == Some("tool"))
}

/// When a settled tool item's result landed: `time.completed`, else `time.ran`,
/// else its own `time.created`. `None` for an unfinished call (no result).
fn tool_result_time(item: &Value) -> Option<DateTime<Utc>> {
    let status = item.pointer("/state/status").and_then(Value::as_str);
    if !matches!(status, Some("completed" | "error")) {
        return None;
    }
    millis_at(item, &["time", "completed"])
        .or_else(|| millis_at(item, &["time", "ran"]))
        .or_else(|| millis_at(item, &["time", "created"]))
}

/// One `session_message` record (`{...data, id, type}`, the `SessionMessage.Info`
/// encoding) as canonical events. Each type takes the conversational slot
/// OpenCode itself sends it in (`to-llm-message.ts`); the whole record rides in
/// the message's `options.source.raw_record`, with its `seq` beside it, so the
/// Parts below are projections and carry no record of their own.
fn build_v2_message_events(
    session_id: &str,
    message_id: &str,
    record: &Value,
    seq: i64,
    session_anchor: DateTime<Utc>,
) -> Vec<IngestEvent> {
    let timestamp = millis_at(record, &["time", "created"]).unwrap_or(session_anchor);
    let mut options = opencode_raw(record);
    mark_source(&mut options, "seq", json!(seq));
    let user = |options| Message::User {
        id: message_id.to_owned(),
        session_id: session_id.to_owned(),
        timestamp,
        options,
    };
    let carrier = |options, content| Message::System {
        id: message_id.to_owned(),
        session_id: session_id.to_owned(),
        timestamp,
        content,
        options,
    };
    let mut parts = V2Parts::new(session_id, message_id);
    let message = match record.get("type").and_then(Value::as_str) {
        Some("user") => {
            for skill in record
                .get("skills")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
            {
                parts.text(Provenance::Injected, skill, "text");
            }
            if record
                .get("text")
                .and_then(Value::as_str)
                .is_some_and(|text| !text.is_empty())
            {
                parts.text(Provenance::Conversational, record, "text");
            }
            for file in record
                .get("files")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
            {
                parts.file(file);
            }
            user(options)
        }
        Some("synthetic" | "skill") => {
            parts.text(Provenance::Injected, record, "text");
            user(options)
        }
        // The user typed the command. A shell finishes in place with no later
        // row to mark it, so - like a tool result - its output rides a synthetic
        // carrier stamped when it ended, which is what lets the freshness
        // watermark see the completion.
        Some("shell") => {
            parts.text(Provenance::Conversational, record, "command");
            let mut events = vec![IngestEvent::Message(user(options))];
            events.extend(parts.parts.into_iter().map(IngestEvent::Part));
            if let Some(ended) = millis_at(record, &["time", "completed"]) {
                events.push(IngestEvent::Message(Message::System {
                    id: format!("{message_id}/output"),
                    session_id: session_id.to_owned(),
                    timestamp: ended.max(timestamp),
                    content: record
                        .get("output")
                        .and_then(|output| extract_str(output, "output")),
                    options: synthetic_options(),
                }));
            }
            return events;
        }
        Some("compaction") if record.get("summary").is_some() => {
            parts.text(Provenance::Injected, record, "summary");
            if record
                .get("recent")
                .and_then(Value::as_str)
                .is_some_and(|recent| !recent.is_empty())
            {
                parts.text(Provenance::Injected, record, "recent");
            }
            user(options)
        }
        Some("system") => carrier(options, extract_str(record, "text")),
        Some("assistant") => {
            let mut results = Vec::new();
            for item in record
                .get("content")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
            {
                match item.get("type").and_then(Value::as_str) {
                    Some("text") => parts.text(Provenance::Conversational, item, "text"),
                    Some("reasoning") => parts.push(
                        Provenance::Conversational,
                        PartKind::Reasoning {
                            text: extract_str(item, "text"),
                        },
                    ),
                    Some("tool") => {
                        if let Some(result) = parts.tool(item, timestamp) {
                            results.push(result);
                        }
                    }
                    // An unknown content kind still lands, verbatim in the
                    // message's raw record; its slot is an injected marker.
                    _ => parts.push(Provenance::Injected, PartKind::Text { text: None }),
                }
            }
            let mut events = vec![IngestEvent::Message(Message::Assistant {
                id: message_id.to_owned(),
                session_id: session_id.to_owned(),
                timestamp,
                options,
            })];
            events.extend(parts.parts.into_iter().map(IngestEvent::Part));
            for ToolSplit { message, result } in results {
                events.push(IngestEvent::Message(message));
                events.push(IngestEvent::Part(result));
            }
            return events;
        }
        // idle, agent/model/location switches, a failed compaction, and any type
        // newer than this adapter: spec placement rule 3, an empty carrier.
        _ => carrier(options, None),
    };
    let mut events = vec![IngestEvent::Message(message)];
    events.extend(parts.parts.into_iter().map(IngestEvent::Part));
    events
}

/// Accumulates the Parts projected out of one V2 record, numbering them in
/// emission order.
struct V2Parts<'a> {
    session_id: &'a str,
    message_id: &'a str,
    parts: Vec<Part>,
}

impl<'a> V2Parts<'a> {
    fn new(session_id: &'a str, message_id: &'a str) -> Self {
        Self {
            session_id,
            message_id,
            parts: Vec::new(),
        }
    }

    fn next_id(&self) -> (String, i32) {
        let ordinal = self.parts.len();
        (part_id(self.message_id, ordinal), part_ordinal(ordinal))
    }

    fn push(&mut self, provenance: Provenance, kind: PartKind) {
        let (id, ordinal) = self.next_id();
        self.parts.push(Part {
            session_id: self.session_id.to_owned(),
            id,
            message_id: self.message_id.to_owned(),
            ordinal,
            provenance,
            options: ProviderOptions::new(),
            kind,
        });
    }

    fn text(&mut self, provenance: Provenance, source: &Value, key: &str) {
        self.push(
            provenance,
            PartKind::Text {
                text: extract_str(source, key),
            },
        );
    }

    /// A prompt attachment: inline base64 `data` when present, else its `uri`.
    fn file(&mut self, file: &Value) {
        let data = match (
            file.get("data").and_then(Value::as_str),
            file.pointer("/source/uri").and_then(Value::as_str),
        ) {
            (Some(data), _) if !data.is_empty() => FileData::String(data.to_owned()),
            (_, Some(uri)) => FileData::Url(uri.to_owned()),
            _ => FileData::String(compact_json(file)),
        };
        self.push(
            Provenance::Conversational,
            PartKind::File {
                media_type: file
                    .get("mime")
                    .and_then(Value::as_str)
                    .map(ToOwned::to_owned),
                file_name: file
                    .get("name")
                    .and_then(Value::as_str)
                    .map(ToOwned::to_owned),
                data,
            },
        );
    }

    /// A `tool` content item: the ToolCall on the assistant message, plus - once
    /// the call settled (`completed`/`error`) - the synthetic `Tool` message and
    /// ToolResult it splits into. An unfinished call (`streaming`/`running`) has
    /// no result yet, and none is invented (spec.md#model-no-synthesis).
    fn tool(&mut self, item: &Value, message_ts: DateTime<Utc>) -> Option<ToolSplit> {
        let (id, _) = self.next_id();
        let call_id = extract_str(item, "id");
        let name = extract_str(item, "name");
        let state = item.get("state");
        let status = state
            .and_then(|state| state.get("status"))
            .and_then(Value::as_str);
        self.push(
            Provenance::Conversational,
            PartKind::ToolCall {
                call_id: call_id.clone(),
                name: name.clone(),
                params: state
                    .and_then(|state| state.get("input"))
                    .cloned()
                    .unwrap_or(Value::Null),
                provider_executed: item.get("executed").and_then(Value::as_bool) == Some(true),
            },
        );
        let result_ts = tool_result_time(item)?.max(message_ts);
        let result = match status {
            Some("error") => state.and_then(|state| state.get("error")),
            _ => state.and_then(|state| state.get("content")),
        };
        let tool_message_id = format!("{id}/result");
        Some(ToolSplit {
            message: Message::Tool {
                id: tool_message_id.clone(),
                session_id: self.session_id.to_owned(),
                timestamp: result_ts,
                options: synthetic_options(),
            },
            result: Part {
                session_id: self.session_id.to_owned(),
                id: part_id(&tool_message_id, 0),
                message_id: tool_message_id,
                ordinal: 0,
                provenance: Provenance::Injected,
                options: synthetic_options(),
                kind: PartKind::ToolResult {
                    call_id,
                    name,
                    is_failure: status == Some("error"),
                    result: result.cloned().unwrap_or(Value::Null),
                },
            },
        })
    }
}

fn record_location(db_path: &Path, session_id: &str, record_id: &str) -> String {
    format!(
        "{}::session={session_id}::record={record_id}",
        db_path.display()
    )
}

/// Read one JSON file, bounding every string leaf at the seam cap
/// (spec.md#adapter-bounded-values) before it leaves this module. The size gate
/// runs on metadata BEFORE the read so the record cap stays a memory bound,
/// never a post-hoc validation of bytes already resident.
fn read_json(path: &Path) -> Result<Value, AdapterError> {
    let io = |source| AdapterError::io(NAME, path.display().to_string(), source);
    let len = std::fs::metadata(path).map_err(io)?.len();
    if len > RECORD_CAP as u64 {
        return Err(AdapterError::schema(
            NAME,
            path.display().to_string(),
            format!("record data exceeds adapter record cap: {len} bytes > {RECORD_CAP}"),
        ));
    }
    let bytes = std::fs::read(path).map_err(io)?;
    parse_bounded(NAME, &bytes, || path.display().to_string())
}

/// List `*.json` files in `dir`, sorted by filename (= creation order, ids are
/// time-sortable). A missing dir is an empty list - a message can legitimately
/// carry no parts.
fn list_json_sorted(dir: &Path) -> Result<Vec<PathBuf>, AdapterError> {
    list_files_sorted(dir, "json", |_| true)
}

fn session_from_value(value: &Value, path: &Path) -> Result<Session, AdapterError> {
    let display = path.display().to_string();
    let id = value
        .get("id")
        .and_then(Value::as_str)
        .ok_or_else(|| AdapterError::schema(NAME, display.clone(), "session missing `id`"))?
        .to_owned();
    let created_at = millis_at(value, &["time", "created"]).ok_or_else(|| {
        AdapterError::schema(NAME, display.clone(), "session missing `time.created`")
    })?;
    // spec.md#model-project-non-empty: opencode always records `directory` (the
    // project cwd); its absence is a malformed session, not a default.
    let project = extract_str(value, "directory")
        .ok_or_else(|| AdapterError::schema(NAME, display, "session missing `directory`"))?;

    let options = opencode_raw(value);

    Ok(Session {
        id,
        // opencode sub-sessions (a Task spawn) carry `parentID`; a soft
        // reference, present only when this session was spawned from another.
        parent_session_id: value
            .get("parentID")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
        parent_message_id: None,
        source_agent: NAME.to_owned(),
        created_at,
        project,
        options,
    })
}

/// Build the ordered event stream for one message: the message, its parts in
/// order, then any synthetic `Tool` messages (one per `tool` part) each
/// followed by its `ToolResult`.
fn build_message_events(
    session_id: &str,
    message_value: &Value,
    part_values: &[Value],
    default_timestamp: DateTime<Utc>,
) -> Result<Vec<IngestEvent>, AdapterError> {
    let message_id = message_value
        .get("id")
        .and_then(Value::as_str)
        .ok_or_else(|| AdapterError::schema(NAME, session_id.to_owned(), "message missing `id`"))?;
    let role = message_value.get("role").and_then(Value::as_str);
    let timestamp = millis_at(message_value, &["time", "created"]).unwrap_or(default_timestamp);

    let options = opencode_raw(message_value);
    let message = match role {
        Some("user") => Message::User {
            id: message_id.to_owned(),
            session_id: session_id.to_owned(),
            timestamp,
            options,
        },
        Some("assistant") => Message::Assistant {
            id: message_id.to_owned(),
            session_id: session_id.to_owned(),
            timestamp,
            options,
        },
        // opencode v2 carries non-conversational message roles (synthetic,
        // shell, compaction); keep them as System carriers rather than drop
        // them (spec.md#adapter-integrity-no-silent-drops). The raw record
        // survives in options; the role label is the content.
        _ => Message::System {
            id: message_id.to_owned(),
            session_id: session_id.to_owned(),
            timestamp,
            content: extract_str(message_value, "role"),
            options,
        },
    };

    let mut events = vec![IngestEvent::Message(message)];
    let mut deferred = Vec::new();
    for (ordinal, part_value) in part_values.iter().enumerate() {
        let mapped = map_part(session_id, message_id, ordinal, part_value, timestamp)?;
        events.push(IngestEvent::Part(mapped.part));
        if let Some(split) = mapped.tool_split {
            deferred.push(split);
        }
    }
    for ToolSplit {
        message: tool_message,
        result,
    } in deferred
    {
        events.push(IngestEvent::Message(tool_message));
        events.push(IngestEvent::Part(result));
    }
    Ok(events)
}

/// One mapped source part: the canonical Part it becomes, plus - for a fused
/// `tool` part - the synthetic `Tool` message and `ToolResult` it splits off.
struct MappedPart {
    part: Part,
    tool_split: Option<ToolSplit>,
}

struct ToolSplit {
    message: Message,
    result: Part,
}

fn map_part(
    session_id: &str,
    message_id: &str,
    ordinal: usize,
    value: &Value,
    message_ts: DateTime<Utc>,
) -> Result<MappedPart, AdapterError> {
    let kind = value.get("type").and_then(Value::as_str);
    let id = value
        .get("id")
        .and_then(Value::as_str)
        .ok_or_else(|| AdapterError::schema(NAME, message_id.to_owned(), "part missing `id`"))?
        .to_owned();

    if kind == Some("tool") {
        return Ok(tool_part(
            session_id, message_id, &id, ordinal, value, message_ts,
        ));
    }

    let (provenance, part_kind) = match kind {
        Some("text") => (text_provenance(value), text_kind(value)),
        Some("reasoning") => (Provenance::Conversational, reasoning_kind(value)),
        Some("file") => (Provenance::Conversational, file_kind(value)),
        // patch / step-start / step-finish (and any other marker) are
        // harness-produced turn machinery, not conversation: keep them as
        // injected Parts whose `raw_record` round-trips the source file.
        _ => (Provenance::Injected, PartKind::Text { text: None }),
    };

    Ok(MappedPart {
        part: Part {
            session_id: session_id.to_owned(),
            id,
            message_id: message_id.to_owned(),
            ordinal: part_ordinal(ordinal),
            provenance,
            options: opencode_raw(value),
            kind: part_kind,
        },
        tool_split: None,
    })
}

/// spec.md#model-part-provenance: opencode marks harness-injected text parts
/// (the `Called the <tool> tool ...` echo, auto-expanded `@file` content) with
/// `synthetic: true`; a genuine prompt or model reply is `synthetic: false`.
fn text_provenance(value: &Value) -> Provenance {
    if value.get("synthetic").and_then(Value::as_bool) == Some(true) {
        Provenance::Injected
    } else {
        Provenance::Conversational
    }
}

fn text_kind(value: &Value) -> PartKind {
    PartKind::Text {
        text: extract_str(value, "text"),
    }
}

fn reasoning_kind(value: &Value) -> PartKind {
    PartKind::Reasoning {
        text: extract_str(value, "text"),
    }
}

fn file_kind(value: &Value) -> PartKind {
    // spec.md#model-no-synthesis: an absent mime hint is faithfully `None`,
    // not a synthesized `application/octet-stream` placeholder.
    let media_type = value
        .get("mime")
        .and_then(Value::as_str)
        .map(ToOwned::to_owned);
    let file_name = value
        .get("filename")
        .and_then(Value::as_str)
        .map(ToOwned::to_owned);
    let data = match value.get("url").and_then(Value::as_str) {
        Some(url) => FileData::Url(url.to_owned()),
        None => FileData::String(compact_json(value)),
    };
    PartKind::File {
        media_type,
        file_name,
        data,
    }
}

/// Split one opencode `tool` part (call + result fused) into a `ToolCall` on the
/// owning assistant message and a synthetic `Tool` message carrying the
/// `ToolResult`. The `ToolCall` keeps the source part's id and stores its full
/// `raw_record`, so native restore reproduces the single source file; the
/// synthetic records carry no `raw_record` and are skipped on restore.
fn tool_part(
    session_id: &str,
    message_id: &str,
    id: &str,
    ordinal: usize,
    value: &Value,
    message_ts: DateTime<Utc>,
) -> MappedPart {
    let call_id = extract_str(value, "callID");
    let name = extract_str(value, "tool");
    let state = value.get("state");
    let status = state.and_then(|s| s.get("status")).and_then(Value::as_str);
    let result_ts = millis_at(value, &["state", "time", "end"]).unwrap_or(message_ts);

    // Take input/output by moving them out of a single owned `state` clone
    // rather than cloning each field separately - a fused tool part fans into
    // three records (call + tool message + result) that all draw on `state`.
    let mut owned_state = state.cloned().unwrap_or(Value::Null);
    let (input, result) = match owned_state.as_object_mut() {
        Some(map) => {
            let input = map.remove("input").unwrap_or(Value::Null);
            let result = map
                .remove("output")
                .or_else(|| map.remove("error"))
                .unwrap_or_else(|| {
                    // No output/error - the rest of `state` IS the payload.
                    std::mem::take(&mut owned_state)
                });
            (input, result)
        }
        None => (Value::Null, Value::Null),
    };

    let tool_call = Part {
        session_id: session_id.to_owned(),
        id: id.to_owned(),
        message_id: message_id.to_owned(),
        ordinal: part_ordinal(ordinal),
        // spec.md#model-part-provenance: the model authored the tool call.
        provenance: Provenance::Conversational,
        options: opencode_raw(value),
        kind: PartKind::ToolCall {
            call_id: call_id.clone(),
            name: name.clone(),
            params: input,
            provider_executed: false,
        },
    };

    let tool_message_id = format!("{id}/result");
    let tool_message = Message::Tool {
        id: tool_message_id.clone(),
        session_id: session_id.to_owned(),
        timestamp: result_ts,
        options: synthetic_options(),
    };
    let result_part = Part {
        session_id: session_id.to_owned(),
        id: part_id(&tool_message_id, 0),
        message_id: tool_message_id,
        ordinal: 0,
        // spec.md#model-part-provenance: tool output is runtime-produced.
        provenance: Provenance::Injected,
        options: synthetic_options(),
        kind: PartKind::ToolResult {
            call_id,
            name,
            is_failure: status == Some("error"),
            result,
        },
    };

    MappedPart {
        part: tool_call,
        tool_split: Some(ToolSplit {
            message: tool_message,
            result: result_part,
        }),
    }
}

#[inline]
fn opencode_raw(value: &Value) -> ProviderOptions {
    source_options(NAME, value)
}

/// Marks a canonical record the adapter synthesized (the `Tool` message and
/// `ToolResult` split off a fused `tool` part). Native restore skips records so
/// marked - they correspond to no source file.
fn synthetic_options() -> ProviderOptions {
    let mut options = ProviderOptions::new();
    options.insert("opencode".to_owned(), json!({ "synthetic": true }));
    options
}

fn millis_at(value: &Value, path: &[&str]) -> Option<DateTime<Utc>> {
    let mut cursor = value;
    for key in path {
        cursor = cursor.get(key)?;
    }
    DateTime::from_timestamp_millis(cursor.as_i64()?)
}

fn is_synthetic(options: &ProviderOptions) -> bool {
    options
        .get("opencode")
        .and_then(|o| o.get("synthetic"))
        .and_then(Value::as_bool)
        == Some(true)
}

fn serialize_native(
    session: &crate::sessions::SessionWithMessages,
) -> Result<Vec<RestoredFile>, AdapterError> {
    // Native replays each stored `raw_record` into the `opencode import`
    // envelope: the session `info`, then each real message's `raw_record` as an
    // `info` with its real parts' `raw_record`s nested under it. The synthetic
    // `Tool` message and `ToolResult` (which carry no `raw_record`) are skipped,
    // re-fusing into the single source `tool` part. Replay echoes a frozen
    // snapshot - safe only while canonical is append-only
    // (spec.md#adapter-integrity-additive-sync). One file per session; a child
    // session is its own `SessionWithMessages`, so the caller iterating every
    // session id emits parent and child files independently
    // (spec.md#adapter-lineage-complete-restore).
    //
    // spec.md#adapter-native-restore-lossless: when the session lacks a stored
    // `raw_record` (older ingest, foreign-sourced session), native is
    // impossible. We downgrade to foreign and stamp `actual_fidelity` so the
    // caller can surface the downgrade instead of getting a silent surprise.
    let Some(session_raw) = raw_record(&session.session.options) else {
        return serialize_foreign(session);
    };
    if session_store(&session.session.options).is_some() {
        return serialize_native_v2(session, &session_raw);
    }

    // Deterministic order: timestamp, then id (peers use the shared comparator).
    let mut ordered = session.messages.clone();
    ordered.sort_by(by_timestamp_then_id);

    let mut messages = Vec::with_capacity(ordered.len());
    for message in &ordered {
        if is_synthetic(message.message.options()) {
            continue;
        }
        // A migrated session that kept going in OpenCode 2 holds V2 records
        // after its V1 ones; no single import shape carries both generations.
        if message_seq(message.message.options()).is_some() {
            return serialize_foreign(session);
        }
        // A non-synthetic message with no stored `raw_record` cannot be replayed
        // natively; downgrade the whole session to foreign (the same fallback the
        // session-level `raw_record` check above applies) rather than silently
        // dropping the message from the envelope.
        let Some(info) = raw_record(message.message.options()) else {
            return serialize_foreign(session);
        };
        let mut parts = Vec::with_capacity(message.parts.len());
        for part in &message.parts {
            // A real part carries its source `raw_record`; the synthetic split
            // `ToolResult` does not, so it is skipped here.
            if let Some(raw) = raw_record(&part.options) {
                parts.push(raw);
            }
        }
        messages.push(json!({ "info": info, "parts": parts }));
    }

    import_file(
        &session.session.id,
        session_raw,
        messages,
        RestoreFidelity::Native,
    )
}

fn session_store(options: &ProviderOptions) -> Option<&str> {
    options.get("source")?.get("store")?.as_str()
}

fn message_seq(options: &ProviderOptions) -> Option<i64> {
    options.get("source")?.get("seq")?.as_i64()
}

/// Native restore of a session read from `session_v2`: the OpenCode 2 transfer
/// shape `opencode session import` reads (`SessionTransfer.Data`,
/// `{ info: Session.Info, messages: SessionMessage.Info[] }`). `info` is
/// OpenCode's own `fromRow` projection of the stored row; `messages` replays
/// each stored record in source `seq` order, skipping the synthetic tool-result
/// carriers the split added.
fn serialize_native_v2(
    session: &crate::sessions::SessionWithMessages,
    row: &Value,
) -> Result<Vec<RestoredFile>, AdapterError> {
    let mut records = Vec::with_capacity(session.messages.len());
    for message in &session.messages {
        if is_synthetic(message.message.options()) {
            continue;
        }
        let (Some(raw), Some(seq)) = (
            raw_record(message.message.options()),
            message_seq(message.message.options()),
        ) else {
            return serialize_foreign(session);
        };
        records.push((seq, raw));
    }
    records.sort_by_key(|(seq, _)| *seq);
    let messages = records.into_iter().map(|(_, raw)| raw).collect();
    import_file(
        &session.session.id,
        v2_session_info(row),
        messages,
        RestoreFidelity::Native,
    )
}

/// OpenCode's `fromRow` (`packages/core/src/session/info.ts`) over a captured
/// `session_v2` row: the `Session.Info` its export writes and its import reads.
fn v2_session_info(row: &Value) -> Value {
    let column = |name: &str| row.get(name).filter(|value| !value.is_null());
    // `fromRow` tests these columns for JS truthiness, so `""` and `0` read as unset.
    let truthy = |name: &str| {
        column(name).filter(|value| {
            !matches!(value, Value::String(text) if text.is_empty()) && value.as_f64() != Some(0.0)
        })
    };
    let mut info = serde_json::Map::new();
    let mut set = |key: &str, value: Option<Value>| {
        if let Some(value) = value {
            info.insert(key.to_owned(), value);
        }
    };
    set("id", column("id").cloned());
    set("projectID", column("project_id").cloned());
    set("title", column("title").cloned());
    set("parentID", truthy("parent_id").cloned());
    if let (Some(session_id), Some(boundary)) = (truthy("fork_session_id"), truthy("fork_boundary"))
    {
        set(
            "fork",
            Some(json!({ "sessionID": session_id, "boundary": boundary })),
        );
    }
    set("agent", truthy("agent").cloned());
    set(
        "model",
        truthy("model").map(|model| {
            let mut model = model.clone();
            if let Value::Object(map) = &mut model {
                // fromRow defaults an unrecorded variant the same way.
                map.entry("variant").or_insert_with(|| json!("default"));
            }
            model
        }),
    );
    set("cost", column("cost").cloned());
    let token = |name: &str| column(name).cloned().unwrap_or(Value::Null);
    set(
        "tokens",
        Some(json!({
            "input": token("tokens_input"),
            "output": token("tokens_output"),
            "reasoning": token("tokens_reasoning"),
            "cache": { "read": token("tokens_cache_read"), "write": token("tokens_cache_write") },
        })),
    );
    let mut location = serde_json::Map::new();
    if let Some(directory) = column("directory") {
        location.insert("directory".to_owned(), directory.clone());
    }
    if let Some(workspace) = column("workspace_id") {
        location.insert("workspaceID".to_owned(), workspace.clone());
    }
    set("location", Some(Value::Object(location)));
    set("subpath", truthy("path").cloned());
    set("metadata", column("metadata").cloned());
    set("permissions", column("permission").cloned());
    set("revert", truthy("revert").map(current_revert));
    set("outcome", column("idle_outcome").cloned());
    let mut time = serde_json::Map::new();
    for (key, name) in [
        ("created", "time_created"),
        ("updated", "time_updated"),
        ("idle", "time_idle"),
        ("viewed", "time_viewed"),
        ("archived", "time_archived"),
    ] {
        let value = if name == "time_archived" {
            truthy(name)
        } else {
            column(name)
        };
        if let Some(value) = value {
            time.insert(key.to_owned(), value.clone());
        }
    }
    set("time", Some(Value::Object(time)));
    Value::Object(info)
}

/// `PersistedRevert` (`session-revert.ts`): revert state stored before
/// `FileDiff` became canonical (`files[].path`, `diff`) decodes to the current
/// shape, which is the only one `Session.Info` accepts.
fn current_revert(revert: &Value) -> Value {
    let files = revert.get("files").and_then(Value::as_array);
    let legacy = revert.get("diff").is_some()
        || files.is_some_and(|files| files.iter().any(|file| file.get("path").is_some()));
    if !legacy {
        return revert.clone();
    }
    let mut current = serde_json::Map::new();
    for key in ["messageID", "partID", "snapshot"] {
        if let Some(value) = revert.get(key).filter(|value| !value.is_null()) {
            current.insert(key.to_owned(), value.clone());
        }
    }
    if let Some(files) = files {
        let files = files
            .iter()
            .map(|file| {
                json!({
                    "file": file.get("path"),
                    "status": file.get("status"),
                    "additions": file.get("additions"),
                    "deletions": file.get("deletions"),
                    "patch": file.get("patch"),
                })
            })
            .collect();
        current.insert("files".to_owned(), Value::Array(files));
    }
    Value::Object(current)
}

fn serialize_foreign(
    session: &crate::sessions::SessionWithMessages,
) -> Result<Vec<RestoredFile>, AdapterError> {
    // Foreign restore: a best-effort, idiomatic `opencode import` envelope. A
    // non-opencode session has no `projectID` hash, so derive a stable key from
    // the project path; tool results (canonical `Tool` messages) and System
    // carriers have no idiomatic home in opencode's message model and are
    // dropped (spec.md#adapter-native-restore-lossless, foreign clause). The
    // minimal `info` shapes omit fields canonical does not carry (a user
    // message's `agent`/`model`) - the same loss foreign restore accepts.
    let created = session.session.created_at.timestamp_millis();
    let info = json!({
        "id": session.session.id,
        "projectID": encode_project(&session.session.project),
        "directory": &*session.session.project,
        "time": { "created": created, "updated": created },
    });

    // Deterministic order: timestamp, then id (peers use the shared comparator).
    let mut ordered = session.messages.clone();
    ordered.sort_by(by_timestamp_then_id);

    let mut messages = Vec::with_capacity(ordered.len());
    for message in &ordered {
        let role = match message.message {
            Message::User { .. } => "user",
            Message::Assistant { .. } => "assistant",
            // No idiomatic opencode home; content stays in canonical.
            Message::Tool { .. } | Message::System { .. } => continue,
        };
        let created = message.message.timestamp().timestamp_millis();
        let msg_info = json!({
            "id": message.message.id(),
            "sessionID": session.session.id,
            "role": role,
            "time": { "created": created },
        });
        let mut parts = Vec::with_capacity(message.parts.len());
        for part in &message.parts {
            if let Some(record) = foreign_part(&session.session.id, part) {
                parts.push(record);
            }
        }
        messages.push(json!({ "info": msg_info, "parts": parts }));
    }

    import_file(
        &session.session.id,
        info,
        messages,
        RestoreFidelity::Foreign,
    )
}

/// Assemble the `opencode import` envelope (`{ info, messages }`) both serializers
/// produce and write it as the single `<session_id>.json` restore file.
fn import_file(
    session_id: &str,
    info: Value,
    messages: Vec<Value>,
    fidelity: RestoreFidelity,
) -> Result<Vec<RestoredFile>, AdapterError> {
    let body = json!({ "info": info, "messages": messages });
    Ok(vec![RestoredFile::new(
        PathBuf::from(format!("{session_id}.json")),
        encode(&body, session_id)?,
        fidelity,
    )])
}

fn foreign_part(session_id: &str, part: &Part) -> Option<Value> {
    let mut record = match &part.kind {
        PartKind::Text { text } => json!({
            "type": "text",
            "text": text.as_deref().map(|t| &**t),
            "synthetic": part.provenance == Provenance::Injected,
        }),
        PartKind::Reasoning { text } => json!({
            "type": "reasoning",
            "text": text.as_deref().map(|t| &**t),
        }),
        PartKind::File {
            media_type,
            file_name,
            data,
        } => json!({
            "type": "file",
            "mime": media_type,
            "filename": file_name,
            "url": match data {
                FileData::Url(url) => Some(url.clone()),
                _ => None,
            },
        }),
        PartKind::ToolCall {
            call_id,
            name,
            params,
            ..
        } => json!({
            "type": "tool",
            "callID": call_id.as_deref().map(|c| &**c),
            "tool": name.as_deref().map(|n| &**n),
            "state": { "status": "completed", "input": params },
        }),
        // ToolResult / approval parts have no standalone opencode shape.
        _ => return None,
    };
    if let Value::Object(map) = &mut record {
        map.insert("id".to_owned(), json!(part.id));
        map.insert("sessionID".to_owned(), json!(session_id));
        map.insert("messageID".to_owned(), json!(part.message_id));
    }
    Some(record)
}

fn encode(value: &Value, location: &str) -> Result<Vec<u8>, AdapterError> {
    serde_json::to_vec(value).map_err(|error| {
        AdapterError::schema(
            NAME,
            location.to_owned(),
            format!("json encode failed: {error}"),
        )
    })
}

/// Lands in a JSON field, never a path segment - so unlike its claude-code and
/// pi namesakes this one needs no Windows treatment.
fn encode_project(project: &str) -> String {
    project
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect()
}

#[cfg(test)]
mod tests {
    //! End-to-end test for the opencode adapter: ingest the committed
    //! split-file fixture corpus and assert pond's canonical shape comes out
    //! the other side, including the fused-tool-part split. The fixture lives
    //! under `tests/fixtures/adapter/opencode/storage/`.
    #![expect(
        clippy::expect_used,
        clippy::unwrap_used,
        reason = "tests fail by panicking"
    )]

    use super::*;
    use crate::{
        adapter::{SyncPlan, extract::LEAF_CAP, test_support::MaxWatermarkOracle},
        handlers::{SyncEvent, SyncStatus, ingest_adapter},
        sessions::Store,
        wire::PartKind,
    };
    use tempfile::TempDir;

    // Manifest-dir anchored: unit tests must not depend on the process cwd
    // (figment::Jail chdirs the whole test process while config tests run).
    // `fixtures()` is the legacy split-file tree (used to exercise the tree path in
    // isolation); `data_dir()` is the opencode data dir holding BOTH the DB and the
    // tree beside it.
    fn fixtures() -> std::path::PathBuf {
        crate::adapter::test_support::manifest_dir().join("tests/fixtures/adapter/opencode/storage")
    }
    fn data_dir() -> std::path::PathBuf {
        crate::adapter::test_support::manifest_dir().join("tests/fixtures/adapter/opencode")
    }
    fn db_fixture() -> std::path::PathBuf {
        crate::adapter::test_support::manifest_dir()
            .join("tests/fixtures/adapter/opencode/opencode.db")
    }
    const FRESH_SESSION_ID: &str = "ses_6405e5a5cffeIG2QHRuTmm4mA7";
    const FRESH_MESSAGE_ID: &str = "msg_zzzzfresh0001";
    const FRESH_PART_ID: &str = "prt_zzzzfresh0001";

    // Facts about the committed DB fixture.
    const DB_SESSION_COUNT: usize = 10;
    const CHILD_SESSION_ID: &str = "ses_09fbc7fc1ffeUaBz77QiNdJbXa";
    const CHILD_PARENT_ID: &str = "ses_09fbc87f2ffeyYCZq51oN2HfGa";
    const DOCTORED_SESSION_ID: &str = "ses_09fbe676bffe9nYsSBi5xhBlaD";
    const DOCTORED_MESSAGE_ID: &str = "msg_f6041991e001BOYvwdP1iI0H0A";
    // The doctored row's `data.time.created` (truth) vs its future `time_created`
    // COLUMN (the migration-stamp quirk).
    const DOCTORED_DATA_CREATED_MS: i64 = 1_784_026_339_614;
    const DOCTORED_COLUMN_CREATED_MS: i64 = 1_794_394_339_614;

    /// Copy the DB fixture into a fresh temp data dir (no `storage/` tree beside
    /// it, so ingest is DB-only). Returns the data dir path.
    fn db_data_dir(temp: &std::path::Path) -> anyhow::Result<PathBuf> {
        let dir = temp.join("data");
        std::fs::create_dir_all(&dir)?;
        std::fs::copy(db_fixture(), dir.join("opencode.db"))?;
        Ok(dir)
    }

    struct FixedOracle {
        session_id: &'static str,
        watermark_micros: i64,
    }

    impl crate::adapter::SkipOracle for FixedOracle {
        fn session_max_ts(&self, session_id: &str) -> Option<i64> {
            (session_id == self.session_id).then_some(self.watermark_micros)
        }
    }

    /// probe_default returns the DATA DIR (not the `storage/` subdir) and only
    /// when it actually holds a DB or a tree.
    #[test]
    fn probe_default_finds_opencode_data_dir() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data_dir = temp.path().join(".local").join("share").join("opencode");
        std::fs::create_dir_all(data_dir.join("storage"))?;
        let env = Env::with_home(temp.path());

        let probe = OpencodeFactory.probe_default(&env);
        let got = probe
            .as_ref()
            .and_then(|value| value.get("path"))
            .and_then(Value::as_str);
        assert_eq!(got, data_dir.to_str(), "probe must return the data dir");

        // An empty data dir (no DB, no tree) is not a source.
        std::fs::remove_dir_all(data_dir.join("storage"))?;
        assert!(
            OpencodeFactory.probe_default(&env).is_none(),
            "an empty data dir must not be offered as a source",
        );
        Ok(())
    }

    /// The `opencode import` envelope a native serialize must produce for one tree
    /// session, derived INDEPENDENTLY from the fixture tree files (session json +
    /// message/ + part/ files) - not from any production serializer internal.
    /// Mirrors the DB conformance test's derive-from-raw approach: message order
    /// matches the serializer's `by_timestamp_then_id` (time.created, then id),
    /// parts stay in id/filename order, and every leaf is bounded via
    /// `extract_raw_record` (identity on the small fixture, faithful in general).
    fn expected_envelope_from_tree(tree_base: &std::path::Path, session_id: &str) -> Value {
        let read = |path: &std::path::Path| -> Value {
            let raw: Value =
                serde_json::from_slice(&std::fs::read(path).expect("read fixture file"))
                    .expect("fixture file is JSON");
            crate::adapter::extract::extract_raw_record(&raw)
        };

        // Locate session/<project>/<id>.json.
        let mut session_json = None;
        for project in std::fs::read_dir(tree_base.join("session")).expect("session dir") {
            let candidate = project
                .expect("session project entry")
                .path()
                .join(format!("{session_id}.json"));
            if candidate.exists() {
                session_json = Some(read(&candidate));
                break;
            }
        }
        let session_json = session_json.expect("session file in fixture tree");

        let mut message_files =
            list_json_sorted(&tree_base.join("message").join(session_id)).expect("message dir");
        message_files.sort_by(|a, b| {
            let (ma, mb) = (read(a), read(b));
            ma["time"]["created"]
                .as_i64()
                .cmp(&mb["time"]["created"].as_i64())
                .then_with(|| ma["id"].as_str().cmp(&mb["id"].as_str()))
        });
        let mut messages = Vec::new();
        for message_path in &message_files {
            let msg = read(message_path);
            let message_id = msg["id"].as_str().expect("message id").to_owned();
            let part_files =
                list_json_sorted(&tree_base.join("part").join(&message_id)).expect("part dir");
            let parts: Vec<Value> = part_files.iter().map(|p| read(p)).collect();
            messages.push(json!({ "info": msg, "parts": parts }));
        }
        json!({ "info": session_json, "messages": messages })
    }

    /// Serialize `session` native and return the single emitted file's parsed
    /// JSON body, asserting the import-shape envelope (`<id>.json`, one file).
    fn serialize_native_body(session: &crate::sessions::SessionWithMessages) -> Value {
        let files = serialize_native(session).expect("native serialize");
        assert_eq!(files.len(), 1, "one file per session");
        let file = &files[0];
        assert_eq!(file.actual_fidelity, RestoreFidelity::Native);
        assert_eq!(
            file.relative_path,
            PathBuf::from(format!("{}.json", session.session.id)),
            "native emits <session_id>.json at the root",
        );
        let body: Value = serde_json::from_slice(&file.bytes).expect("emitted body is JSON");
        assert!(body.get("info").is_some(), "envelope carries session info");
        assert!(
            body.get("messages").and_then(Value::as_array).is_some(),
            "envelope carries a messages array",
        );
        body
    }

    /// A legacy-tree-era session serializes native into the import envelope with
    /// the tree `raw_record`s embedded.
    #[tokio::test(flavor = "multi_thread")]
    async fn native_restore_emits_import_shape_from_tree() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let source = temp.path().join("storage");
        copy_dir(&fixtures(), &source)?;
        let store = Store::open_local(temp.path().join("store")).await?;
        let adapter = OpencodeAdapter::new(&source);
        ingest_adapter(&store, &adapter, &crate::adapter::NoopOracle, |_| {}).await?;

        let session_ids = store.session_ids().await?;
        assert!(!session_ids.is_empty(), "tree fixture ingests sessions");
        for session_id in session_ids {
            let session = store
                .get_session(&session_id)
                .await?
                .expect("session round-trips");
            let body = serialize_native_body(&session);
            assert_eq!(
                body,
                expected_envelope_from_tree(&source, &session_id),
                "tree session {session_id} embeds its raw_records into the envelope",
            );
            // No synthetic split record leaks into the envelope: every emitted
            // message id is a real (non-synthetic) canonical message.
            let real_ids: std::collections::HashSet<&str> = session
                .messages
                .iter()
                .filter(|m| !is_synthetic(m.message.options()))
                .map(|m| m.message.id())
                .collect();
            for message in body["messages"].as_array().unwrap() {
                let id = message["info"]["id"].as_str().expect("message info id");
                assert!(
                    real_ids.contains(id),
                    "emitted message {id} must be a real canonical message",
                );
            }
        }
        Ok(())
    }

    /// Native restore against the DB fixture: for every emitted file, the
    /// envelope `info`/messages/parts value-equal the rows reconstructed straight
    /// from the DB (`session_info_from_row` / `reconstruct_record`), synthetic
    /// split records are absent, and every session - parent AND child - gets its
    /// own file (spec.md#adapter-lineage-complete-restore).
    #[tokio::test(flavor = "multi_thread")]
    async fn native_restore_conformance_against_db_fixture() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        let store = Store::open_local(temp.path().join("store")).await?;
        ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;

        // Independently reconstruct the expected records from the raw DB rows.
        let db = db_fixture();
        let conn = open_db(&db)?;
        let expected_session: HashMap<String, Value> = conn
            .prepare(&format!("SELECT {SESSION_COLUMNS} FROM session"))?
            .query_map([], session_info_from_row)?
            .map(|row| {
                let info = row.expect("session row reconstructs");
                let id = info["id"].as_str().expect("session id").to_owned();
                (id, crate::adapter::extract::extract_raw_record(&info))
            })
            .collect();
        let reconstruct_expected = |data: &str, inject: Vec<(&'static str, Value)>| -> Value {
            reconstruct_record(data, inject, std::path::Path::new(""), "", "").unwrap()
        };

        let mut file_count = 0usize;
        let mut saw_child = false;
        let mut saw_parent = false;
        for session_id in store.session_ids().await? {
            let session = store
                .get_session(&session_id)
                .await?
                .expect("session round-trips");
            let body = serialize_native_body(&session);
            file_count += 1;
            if session_id == CHILD_SESSION_ID {
                saw_child = true;
            }
            if session_id == CHILD_PARENT_ID {
                saw_parent = true;
            }

            // Session info matches the row-reconstructed SessionInfo.
            assert_eq!(
                &body["info"],
                expected_session
                    .get(&session_id)
                    .unwrap_or_else(|| panic!("session {session_id} in DB")),
                "session info equals the row-reconstructed SessionInfo",
            );

            // Message + part bodies match the rows' reconstructed JSON.
            let mut expected_msg_ids: Vec<String> = Vec::new();
            let mut stmt =
                conn.prepare("SELECT id, data FROM message WHERE session_id = ?1 ORDER BY id")?;
            let msg_rows: Vec<(String, String)> = stmt
                .query_map([&session_id], |row| Ok((row.get(0)?, row.get(1)?)))?
                .collect::<rusqlite::Result<_>>()?;
            for (message_id, data) in &msg_rows {
                expected_msg_ids.push(message_id.clone());
                let expected_info = reconstruct_expected(
                    data,
                    vec![("id", json!(message_id)), ("sessionID", json!(session_id))],
                );
                let entry = body["messages"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .find(|m| m["info"]["id"].as_str() == Some(message_id.as_str()))
                    .unwrap_or_else(|| panic!("message {message_id} emitted"));
                assert_eq!(&entry["info"], &expected_info, "message info matches row");

                let mut pstmt =
                    conn.prepare("SELECT id, data FROM part WHERE message_id = ?1 ORDER BY id")?;
                let expected_parts: Vec<Value> = pstmt
                    .query_map([message_id], |row| {
                        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                    })?
                    .map(|r| {
                        let (part_id, data) = r.unwrap();
                        reconstruct_expected(
                            &data,
                            vec![
                                ("id", json!(part_id)),
                                ("sessionID", json!(session_id)),
                                ("messageID", json!(message_id)),
                            ],
                        )
                    })
                    .collect();
                assert_eq!(
                    entry["parts"].as_array().unwrap(),
                    &expected_parts,
                    "parts for message {message_id} match the rows in id order",
                );
            }

            // Synthetic split records are absent: the envelope's message ids are
            // exactly the DB message rows (no `<part>/result` carriers).
            let emitted_ids: Vec<&str> = body["messages"]
                .as_array()
                .unwrap()
                .iter()
                .map(|m| m["info"]["id"].as_str().unwrap())
                .collect();
            assert_eq!(
                emitted_ids.len(),
                expected_msg_ids.len(),
                "no synthetic message carriers leak into the envelope",
            );
        }

        assert_eq!(file_count, DB_SESSION_COUNT, "one file per DB session");
        assert!(
            saw_child,
            "child session {CHILD_SESSION_ID} gets its own file"
        );
        assert!(
            saw_parent,
            "parent session {CHILD_PARENT_ID} gets its own file",
        );
        Ok(())
    }

    /// Shared assertion for `plan_matches_the_events_gate*`: a first sync (empty
    /// oracle) is all-pending, then a max-watermark oracle is re-planned and its
    /// fresh count is asserted to equal the `events_with` gate's fresh count.
    /// Returns `(first_sync, max_plan)` so each caller adds its scenario-specific
    /// count assertions (all-fresh DB vs. one message-less pending in the tree).
    async fn plan_gate_agreement(
        adapter: &OpencodeAdapter,
    ) -> anyhow::Result<(SyncPlan, SyncPlan)> {
        use tokio_stream::StreamExt;

        let first_sync = adapter
            .plan(&crate::adapter::NoopOracle)
            .await?
            .expect("opencode supports plan");
        assert_eq!(
            first_sync.pending, first_sync.sessions,
            "a first sync reads every session"
        );
        assert_eq!(first_sync.fresh, 0);

        let max_plan = adapter
            .plan(&MaxWatermarkOracle)
            .await?
            .expect("opencode supports plan");
        assert_eq!(
            max_plan.sessions, first_sync.sessions,
            "session count is stable across oracles",
        );

        let mut gate_fresh = 0usize;
        let mut stream = adapter.events_with(&MaxWatermarkOracle);
        while let Some(item) = stream.next().await {
            match item? {
                AdapterYield::Skipped {
                    reason: SkipReason::Fresh,
                    ..
                } => gate_fresh += 1,
                AdapterYield::SkippedBatch {
                    reason: SkipReason::Fresh,
                    count,
                } => gate_fresh += count,
                _ => {}
            }
        }
        assert_eq!(gate_fresh, max_plan.fresh, "plan and gate must agree");
        Ok((first_sync, max_plan))
    }

    /// `plan` is the events_with freshness pre-pass run standalone and MUST
    /// agree with it: the sessions plan calls fresh are exactly the sessions
    /// the gate skips. A message-less session stays pending (never Empty) -
    /// reading it still ingests its Session row, so the gate must keep
    /// re-reading it.
    #[tokio::test(flavor = "multi_thread")]
    async fn plan_matches_the_events_gate() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let source = temp.path().join("storage");
        copy_dir(&fixtures(), &source)?;
        let empty_dir = source.join("session").join("proj-empty");
        std::fs::create_dir_all(&empty_dir)?;
        std::fs::write(
            empty_dir.join("ses_zzzzemptysession00000000.json"),
            "{\"id\":\"ses_zzzzemptysession00000000\",\"projectID\":\"proj-empty\",\
             \"directory\":\"/tmp/pond-test\",\"time\":{\"created\":1759859990000}}",
        )?;

        let adapter = OpencodeAdapter::new(&source);
        let (first_sync, max_plan) = plan_gate_agreement(&adapter).await?;
        assert!(first_sync.sessions > 1);
        assert_eq!(
            max_plan.pending, 1,
            "the message-less session must stay pending - its Session row only \
             lands by reading it",
        );
        Ok(())
    }

    /// `append_fresh_opencode_turn` writes its message at this `time.created`
    /// (millis); the freshness gate keys on it in micros.
    const FRESH_TURN_MICROS: i64 = 1_759_859_999_000 * 1_000;

    /// A session whose latest message is newer than the watermark is re-read, and
    /// the appended turn lands.
    #[tokio::test(flavor = "multi_thread")]
    async fn freshness_re_reads_a_session_that_gained_a_newer_message() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let source = temp.path().join("storage");
        copy_dir(&fixtures(), &source)?;

        let store = Store::open_local(temp.path().join("store")).await?;
        let adapter = OpencodeAdapter::new(&source);
        ingest_adapter(&store, &adapter, &crate::adapter::NoopOracle, |_| {}).await?;

        append_fresh_opencode_turn(&source)?;
        // Watermark sits just below the appended message's timestamp.
        let oracle = FixedOracle {
            session_id: FRESH_SESSION_ID,
            watermark_micros: FRESH_TURN_MICROS - 1,
        };
        ingest_adapter(&store, &adapter, &oracle, |_| {}).await?;

        let session = store
            .get_session(FRESH_SESSION_ID)
            .await?
            .expect("fixture session round-trips");
        let fresh = session
            .messages
            .iter()
            .find(|stored| stored.message.id() == FRESH_MESSAGE_ID)
            .expect("message newer than the watermark must land");
        assert!(
            fresh.parts.iter().any(|part| matches!(
                &part.kind,
                PartKind::Text { text } if text.as_deref().map(|value| value.as_str()) == Some("fresh opencode text")
            )),
            "fresh message part must land with the re-read session",
        );
        Ok(())
    }

    /// A session whose latest message is no newer than the watermark is skipped as
    /// `Fresh` - the appended turn is NOT re-read.
    #[tokio::test(flavor = "multi_thread")]
    async fn freshness_skips_a_session_not_newer_than_the_watermark() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let source = temp.path().join("storage");
        copy_dir(&fixtures(), &source)?;

        let store = Store::open_local(temp.path().join("store")).await?;
        let adapter = OpencodeAdapter::new(&source);
        ingest_adapter(&store, &adapter, &crate::adapter::NoopOracle, |_| {}).await?;

        append_fresh_opencode_turn(&source)?;
        // Watermark at/above the appended timestamp: the session is fresh.
        let oracle = FixedOracle {
            session_id: FRESH_SESSION_ID,
            watermark_micros: FRESH_TURN_MICROS,
        };
        let summary = ingest_adapter(&store, &adapter, &oracle, |_| {}).await?;

        assert!(
            summary.skipped_fresh >= 1,
            "the unchanged-vs-watermark session must be skipped, got {summary:?}",
        );
        let session = store
            .get_session(FRESH_SESSION_ID)
            .await?
            .expect("fixture session round-trips");
        assert!(
            !session
                .messages
                .iter()
                .any(|stored| stored.message.id() == FRESH_MESSAGE_ID),
            "a skipped session must not re-read the appended turn",
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn malformed_part_file_drops_only_that_part() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let source = temp.path().join("storage");
        write_minimal_session(&source, "ses_badpart", "msg_badpart")?;
        let part_dir = source.join("part").join("msg_badpart");
        std::fs::write(part_dir.join("prt_000_bad.json"), b"{not json")?;
        write_json_file(
            &part_dir.join("prt_999_good.json"),
            &json!({
                "id": "prt_999_good",
                "sessionID": "ses_badpart",
                "messageID": "msg_badpart",
                "type": "text",
                "text": "valid sibling survives",
                "synthetic": false,
            }),
        )?;

        let store = Store::open_local(temp.path().join("store")).await?;
        let summary = ingest_adapter(
            &store,
            &OpencodeAdapter::new(&source),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;

        assert_eq!(summary.dropped_events, 1);
        let session = store
            .get_session("ses_badpart")
            .await?
            .expect("session with one malformed part still lands");
        let message = session
            .messages
            .iter()
            .find(|stored| stored.message.id() == "msg_badpart")
            .expect("message with valid sibling part still lands");
        assert!(message.parts.iter().any(|part| {
            matches!(
                &part.kind,
                PartKind::Text { text }
                    if text.as_deref().map(String::as_str) == Some("valid sibling survives")
            )
        }));
        Ok(())
    }

    #[test]
    fn missing_message_timestamp_uses_session_anchor() -> anyhow::Result<()> {
        let session_anchor =
            DateTime::parse_from_rfc3339("2026-05-05T12:13:14Z")?.with_timezone(&Utc);
        let events = build_message_events(
            "ses_anchor",
            &json!({"id": "msg_no_time", "role": "user"}),
            &[],
            session_anchor,
        )?;

        let IngestEvent::Message(message) = &events[0] else {
            panic!("first event is the message");
        };
        assert_eq!(message.timestamp(), session_anchor);
        Ok(())
    }

    #[test]
    fn source_part_without_id_is_schema_error() {
        let session_anchor = DateTime::from_timestamp_millis(1_765_000_000_000).unwrap();
        let error = build_message_events(
            "ses_missing_part_id",
            &json!({
                "id": "msg_missing_part_id",
                "role": "assistant",
                "time": { "created": 1_765_000_000_000i64 },
            }),
            &[json!({"type": "text", "text": "cannot restore its filename"})],
            session_anchor,
        )
        .expect_err("part ids are required for native filename replay");

        assert!(error.to_string().contains("part missing `id`"));
    }

    #[test]
    fn read_json_bounds_oversized_string_leaves() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let path = temp.path().join("oversized.json");
        write_json_file(
            &path,
            &json!({
                "id": "oversized",
                "text": "x".repeat(LEAF_CAP + 100),
            }),
        )?;

        let value = read_json(&path)?;
        let text = value
            .get("text")
            .and_then(Value::as_str)
            .expect("text leaf survives as a bounded marker");
        assert!(text.len() <= LEAF_CAP);
        assert!(text.ends_with(&format!("{} bytes>", LEAF_CAP + 100)));
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn opencode_adapter_ingests_fixture_corpus_into_canonical_shape() -> anyhow::Result<()> {
        // `data_dir()` ingests BOTH sources (the DB plus the tree beside it).
        let temp = TempDir::new()?;
        let store = Store::open_local(temp.path()).await?;
        let adapter = OpencodeAdapter::new(data_dir());

        let summary = ingest_adapter(&store, &adapter, &crate::adapter::NoopOracle, |_| {}).await?;
        assert!(summary.accepted() > 0, "ingest must accept rows");
        assert_eq!(summary.dropped_events, 0, "no per-event drops expected");
        assert_eq!(
            summary.dropped_sessions, 0,
            "no session-level rejections expected"
        );

        let (sessions, messages, parts) = store.row_counts().await?;
        assert!(
            sessions >= DB_SESSION_COUNT,
            "the DB sessions plus the tree beside them all ingest",
        );
        assert!(messages > 0, "at least one opencode message");
        assert!(parts > 0, "at least one opencode Part");

        let mut saw_call = false;
        let mut saw_result = false;
        let mut saw_injected_text = false;
        for session_id in store.session_ids().await? {
            let session = store
                .get_session(&session_id)
                .await?
                .expect("session round-trips");
            assert!(
                session.session.source_agent.starts_with(NAME),
                "source_agent is `opencode` or `opencode/<agent>`, got {}",
                session.session.source_agent,
            );
            assert!(
                !(*session.session.project).is_empty(),
                "spec.md#model-project-non-empty",
            );
            for stored in &session.messages {
                for part in &stored.parts {
                    match &part.kind {
                        PartKind::ToolCall { .. } => saw_call = true,
                        PartKind::ToolResult { .. } => saw_result = true,
                        PartKind::Text { .. } if part.provenance == Provenance::Injected => {
                            saw_injected_text = true;
                        }
                        _ => {}
                    }
                }
            }
        }
        assert!(saw_call, "fused tool parts yield ToolCall on the assistant");
        assert!(
            saw_result,
            "fused tool parts split off a ToolResult on a Tool message",
        );
        assert!(
            saw_injected_text,
            "spec.md#model-part-provenance: synthetic text parts are injected",
        );
        Ok(())
    }

    /// The synthetic `Tool` message a `tool` part splits off must carry a
    /// `Tool` role with one `ToolResult`, and must NOT collide with or
    /// overwrite the assistant message that owns the `ToolCall`.
    #[tokio::test(flavor = "multi_thread")]
    async fn fused_tool_part_splits_into_call_and_result() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let store = Store::open_local(temp.path()).await?;
        let adapter = OpencodeAdapter::new(data_dir());
        ingest_adapter(&store, &adapter, &crate::adapter::NoopOracle, |_| {}).await?;

        let mut call_ids = std::collections::HashSet::new();
        let mut result_ids = std::collections::HashSet::new();
        let mut saw_failure = false;
        for session_id in store.session_ids().await? {
            let session = store
                .get_session(&session_id)
                .await?
                .expect("session round-trips");
            for stored in &session.messages {
                for part in &stored.parts {
                    match &part.kind {
                        PartKind::ToolCall { call_id, .. } => {
                            if let Some(id) = call_id.as_deref() {
                                call_ids.insert(id.clone());
                            }
                        }
                        PartKind::ToolResult {
                            call_id,
                            is_failure,
                            result,
                            ..
                        } => {
                            assert!(
                                matches!(stored.message, Message::Tool { .. }),
                                "a ToolResult must live on a Tool-role message",
                            );
                            if *is_failure {
                                saw_failure = true;
                                assert_ne!(
                                    result,
                                    &Value::Null,
                                    "failed tool results must carry the source error/output payload",
                                );
                            }
                            if let Some(id) = call_id.as_deref() {
                                result_ids.insert(id.clone());
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
        assert!(!call_ids.is_empty(), "corpus has tool calls");
        assert_eq!(
            call_ids, result_ids,
            "every tool call's id is matched by its split-off result",
        );
        assert!(
            saw_failure,
            "fixture has at least one failed opencode tool result"
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn db_fixture_ingests_expected_census() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        let store = Store::open_local(temp.path().join("store")).await?;
        let summary = ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;
        assert_eq!(summary.dropped_events, 0, "no per-event drops expected");
        assert_eq!(summary.dropped_sessions, 0, "no session-level rejections");

        let (sessions, messages, parts) = store.row_counts().await?;
        assert_eq!(sessions, DB_SESSION_COUNT, "every DB session ingests");
        assert!(
            messages >= 27,
            "27 message rows plus synthetic tool carriers"
        );
        assert!(parts >= 69, "69 part rows plus split-off tool results");

        // The archived + multi-project sessions all land (census sanity), and the
        // child session's canonical shape is asserted in its own test.
        assert!(
            store.get_session(CHILD_SESSION_ID).await?.is_some(),
            "child session ingests",
        );
        assert!(
            store.get_session(DOCTORED_SESSION_ID).await?.is_some(),
            "migration-stamped session ingests",
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn child_session_labeled_as_subagent() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        let store = Store::open_local(temp.path().join("store")).await?;
        ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;

        let child = store
            .get_session(CHILD_SESSION_ID)
            .await?
            .expect("child session ingests");
        assert_eq!(
            child.session.parent_session_id.as_deref(),
            Some(CHILD_PARENT_ID),
            "child carries its parent pointer",
        );
        assert_eq!(
            child.session.source_agent, "opencode/general",
            "spec.md: a subagent session is labeled opencode/<agent>",
        );
        Ok(())
    }

    /// The doctored row's canonical message timestamp is `data.time.created`, and
    /// the session's freshness watermark ignores the future `time_created` COLUMN.
    #[tokio::test(flavor = "multi_thread")]
    async fn doctored_row_uses_data_time_not_column() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        let store = Store::open_local(temp.path().join("store")).await?;
        ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;

        let session = store
            .get_session(DOCTORED_SESSION_ID)
            .await?
            .expect("doctored session ingests");
        let message = session
            .messages
            .iter()
            .find(|stored| stored.message.id() == DOCTORED_MESSAGE_ID)
            .expect("doctored message ingests");
        assert_eq!(
            message.message.timestamp().timestamp_millis(),
            DOCTORED_DATA_CREATED_MS,
            "canonical timestamp is data.time.created, not the migration column",
        );

        // The freshness watermark also ignores the column: it is derived from the
        // data timestamps (all months before the doctored column value).
        let conn = open_db(&db_fixture())?;
        let watermark = db_session_watermark(&conn, &db_fixture(), DOCTORED_SESSION_ID)?
            .expect("session has a message");
        assert!(
            watermark < DOCTORED_COLUMN_CREATED_MS * 1_000,
            "watermark ({watermark} micros) must ignore the future time_created column",
        );
        Ok(())
    }

    /// Part types absent from the generated corpus (subtask/compaction/agent/
    /// snapshot) land as injected carriers whose `raw_record` round-trips.
    #[tokio::test(flavor = "multi_thread")]
    async fn injected_carrier_part_types_land() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        {
            let conn = Connection::open(data.join("opencode.db"))?;
            // The standalone carrier session references no `project` row; the
            // adapter reads the DB, it does not enforce opencode's FKs, so the
            // fixture writer disables them for this hand-authored session.
            conn.execute_batch("PRAGMA foreign_keys = OFF;")?;
            insert_session(
                &conn,
                "ses_carrier00000000000000000",
                "/tmp/carrier",
                None,
                None,
                1_784_100_000_000,
            )?;
            insert_message(
                &conn,
                "msg_carrier00000000000000000",
                "ses_carrier00000000000000000",
                1_784_100_000_100,
                &json!({ "role": "assistant", "time": { "created": 1_784_100_000_100i64 } }),
            )?;
            for (part_id, body) in [
                (
                    "prt_carrier_a_subtask000000",
                    json!({ "type": "subtask", "prompt": "p", "description": "d", "agent": "general" }),
                ),
                (
                    "prt_carrier_b_compaction00",
                    json!({ "type": "compaction", "auto": true }),
                ),
                (
                    "prt_carrier_c_agent0000000",
                    json!({ "type": "agent", "name": "build" }),
                ),
                (
                    "prt_carrier_d_snapshot0000",
                    json!({ "type": "snapshot", "snapshot": "abcdef" }),
                ),
            ] {
                insert_part(
                    &conn,
                    part_id,
                    "msg_carrier00000000000000000",
                    "ses_carrier00000000000000000",
                    1_784_100_000_100,
                    &body,
                )?;
            }
        }

        let store = Store::open_local(temp.path().join("store")).await?;
        ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;

        let session = store
            .get_session("ses_carrier00000000000000000")
            .await?
            .expect("carrier session ingests");
        let mut seen_types = std::collections::HashSet::new();
        for stored in &session.messages {
            for part in &stored.parts {
                let Some(raw) = raw_record(&part.options) else {
                    continue;
                };
                if let Some(kind) = raw.get("type").and_then(Value::as_str) {
                    seen_types.insert(kind.to_owned());
                    assert_eq!(
                        part.provenance,
                        Provenance::Injected,
                        "carrier part {kind} is injected turn machinery",
                    );
                }
            }
        }
        for expected in ["subtask", "compaction", "agent", "snapshot"] {
            assert!(
                seen_types.contains(expected),
                "carrier type {expected} must land with its raw_record, saw {seen_types:?}",
            );
        }
        Ok(())
    }

    /// A session id present in BOTH the DB and the legacy tree is emitted once
    /// (the DB copy wins) and the deduped tree copy is counted, not silent.
    #[tokio::test(flavor = "multi_thread")]
    async fn dual_source_dedup_prefers_db() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        // A tree that overlaps one DB session id and adds one tree-only session.
        let overlap = "ses_09fb956e1ffeKLKCXceMNLRsS0";
        let tree_only = "ses_treeonly0000000000000000";
        write_tree_session(&data.join("storage"), overlap, "TREE COPY SHOULD LOSE")?;
        write_tree_session(&data.join("storage"), tree_only, "tree-only survives")?;

        let store = Store::open_local(temp.path().join("store")).await?;
        let summary = ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;
        assert!(
            summary.skipped_superseded >= 1,
            "the deduped tree copy must be counted as superseded, got {summary:?}",
        );
        assert_eq!(
            summary.skipped_empty, 0,
            "the dedup must not fold into skipped_empty, got {summary:?}",
        );

        let overlapped = store
            .get_session(overlap)
            .await?
            .expect("overlapping session ingests (DB copy)");
        assert!(
            !overlapped.messages.iter().any(|stored| stored.parts.iter().any(|part| matches!(
                &part.kind,
                PartKind::Text { text } if text.as_deref().map(String::as_str) == Some("TREE COPY SHOULD LOSE")
            ))),
            "the DB copy wins; the tree body must not leak in",
        );
        assert!(
            store.get_session(tree_only).await?.is_some(),
            "the tree-only session still ingests",
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn hostile_db_session_id_is_rejected_at_ingest() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        let conn = Connection::open(data.join("opencode.db"))?;
        conn.pragma_update(None, "foreign_keys", "OFF")?;
        conn.execute(
            "UPDATE session SET id = '../evil' WHERE id = ?1",
            [CHILD_SESSION_ID],
        )?;
        drop(conn);

        let store = Store::open_local(temp.path().join("store")).await?;
        let skip_reasons = std::sync::Mutex::new(Vec::new());
        let summary = ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |event| {
                if let SyncEvent::SessionDone(outcome) = &event
                    && let SyncStatus::Skipped { reason } = &outcome.status
                {
                    skip_reasons.lock().unwrap().push(reason.clone());
                }
            },
        )
        .await?;

        let skip_reasons = skip_reasons.into_inner().unwrap();
        assert!(
            skip_reasons
                .iter()
                .any(|reason| reason.contains("traversal")),
            "the hostile id must surface as a typed skip, got {skip_reasons:?}",
        );
        assert_eq!(summary.skipped_files, 1, "got {summary:?}");
        assert!(store.get_session("../evil").await?.is_none());
        let (sessions, ..) = store.row_counts().await?;
        assert_eq!(
            sessions,
            DB_SESSION_COUNT - 1,
            "every well-formed session still ingests",
        );
        Ok(())
    }

    #[test]
    fn oversized_json_file_is_rejected_by_the_record_cap() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let path = temp.path().join("big.json");
        std::fs::write(&path, vec![b' '; RECORD_CAP + 1])?;
        let error = read_json(&path).unwrap_err();
        assert!(
            error.to_string().contains("record cap"),
            "the pre-read size gate must reject the file, got: {error}",
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn config_path_ending_in_storage_reads_parent_db() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        std::fs::copy(db_fixture(), temp.path().join("opencode.db"))?;
        let store = Store::open_local(temp.path().join("store")).await?;
        // A legacy config points at `<data-dir>/storage`; normalization resolves
        // it to the parent, where the DB lives.
        let adapter = OpencodeAdapter::new(temp.path().join("storage"));
        ingest_adapter(&store, &adapter, &crate::adapter::NoopOracle, |_| {}).await?;

        let (sessions, ..) = store.row_counts().await?;
        assert_eq!(
            sessions, DB_SESSION_COUNT,
            "the normalized parent's DB is read",
        );
        Ok(())
    }

    /// `plan` agrees with the `events_with` gate on the DB source (port of the
    /// tree test): first sync is all-pending, a max watermark makes every session
    /// fresh, and the gate skips exactly those.
    #[tokio::test(flavor = "multi_thread")]
    async fn plan_matches_the_events_gate_db_source() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        let adapter = OpencodeAdapter::new(&data);

        let (first, max_plan) = plan_gate_agreement(&adapter).await?;
        assert_eq!(first.sessions, DB_SESSION_COUNT);
        assert_eq!(
            max_plan.fresh, DB_SESSION_COUNT,
            "every DB session is fresh under a max watermark",
        );
        Ok(())
    }

    const APPEND_SESSION_ID: &str = "ses_09fb956e1ffeKLKCXceMNLRsS0";
    const APPEND_MESSAGE_ID: &str = "msg_zzzzfreshdb0000000000000";
    const APPEND_CREATED_MS: i64 = 1_790_000_000_000;
    const APPEND_MICROS: i64 = APPEND_CREATED_MS * 1_000;

    fn append_db_turn(data: &std::path::Path) -> anyhow::Result<()> {
        let conn = Connection::open(data.join("opencode.db"))?;
        insert_message(
            &conn,
            APPEND_MESSAGE_ID,
            APPEND_SESSION_ID,
            APPEND_CREATED_MS,
            &json!({ "role": "user", "time": { "created": APPEND_CREATED_MS } }),
        )?;
        insert_part(
            &conn,
            "prt_zzzzfreshdb0000000000000",
            APPEND_MESSAGE_ID,
            APPEND_SESSION_ID,
            APPEND_CREATED_MS,
            &json!({ "type": "text", "text": "fresh db text", "synthetic": false }),
        )?;
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn freshness_db_re_reads_a_session_with_a_newer_message() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        let store = Store::open_local(temp.path().join("store")).await?;
        let adapter = OpencodeAdapter::new(&data);
        ingest_adapter(&store, &adapter, &crate::adapter::NoopOracle, |_| {}).await?;

        append_db_turn(&data)?;
        let oracle = FixedOracle {
            session_id: APPEND_SESSION_ID,
            watermark_micros: APPEND_MICROS - 1,
        };
        ingest_adapter(&store, &adapter, &oracle, |_| {}).await?;

        let session = store
            .get_session(APPEND_SESSION_ID)
            .await?
            .expect("session round-trips");
        assert!(
            session
                .messages
                .iter()
                .any(|stored| stored.message.id() == APPEND_MESSAGE_ID),
            "a message newer than the watermark must land",
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn freshness_db_skips_a_session_not_newer_than_the_watermark() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        let store = Store::open_local(temp.path().join("store")).await?;
        let adapter = OpencodeAdapter::new(&data);
        ingest_adapter(&store, &adapter, &crate::adapter::NoopOracle, |_| {}).await?;

        append_db_turn(&data)?;
        let oracle = FixedOracle {
            session_id: APPEND_SESSION_ID,
            watermark_micros: APPEND_MICROS,
        };
        let summary = ingest_adapter(&store, &adapter, &oracle, |_| {}).await?;
        assert!(
            summary.skipped_fresh >= 1,
            "the unchanged-vs-watermark session must be skipped, got {summary:?}",
        );

        let session = store
            .get_session(APPEND_SESSION_ID)
            .await?
            .expect("session round-trips");
        assert!(
            !session
                .messages
                .iter()
                .any(|stored| stored.message.id() == APPEND_MESSAGE_ID),
            "a skipped session must not re-read the appended turn",
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn malformed_db_data_drops_only_that_record() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = db_data_dir(temp.path())?;
        {
            let conn = Connection::open(data.join("opencode.db"))?;
            conn.execute(
                "UPDATE part SET data = '{not json' WHERE id = (SELECT id FROM part ORDER BY id LIMIT 1)",
                [],
            )?;
        }

        let store = Store::open_local(temp.path().join("store")).await?;
        let summary = ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;
        assert_eq!(
            summary.dropped_events, 1,
            "only the malformed part is dropped, got {summary:?}",
        );
        let (sessions, ..) = store.row_counts().await?;
        assert_eq!(sessions, DB_SESSION_COUNT, "all sessions still ingest");
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn legacy_tree_only_root_still_ingests() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let source = temp.path().join("storage");
        copy_dir(&fixtures(), &source)?;
        let store = Store::open_local(temp.path().join("store")).await?;
        ingest_adapter(
            &store,
            &OpencodeAdapter::new(&source),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;

        let (sessions, ..) = store.row_counts().await?;
        assert!(sessions > 0, "the bare legacy tree still ingests");
        assert!(
            store.get_session(FRESH_SESSION_ID).await?.is_some(),
            "a known tree session ingests with no DB present",
        );
        Ok(())
    }

    /// Foreign restore of a non-opencode (pi) session emits one `<id>.json` in
    /// the `opencode import` envelope: `{info, messages:[{info, parts}]}` built
    /// from canonical fields, with a re-fused `tool` part (`state.status =
    /// completed`, `input`). Per spec 6.8 there is no re-parse path for import
    /// JSON, so structural + value assertions suffice (golden-file reviewed).
    #[tokio::test(flavor = "multi_thread")]
    async fn foreign_serialization_emits_import_shape() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let origin_store = Store::open_local(temp.path().join("origin-store")).await?;
        let origin = crate::adapter::PiCodingAgentAdapter::new(
            crate::adapter::test_support::manifest_dir()
                .join("tests/fixtures/adapter/pi-coding-agent/sessions"),
        );
        ingest_adapter(&origin_store, &origin, &crate::adapter::NoopOracle, |_| {}).await?;

        let mut saw_tool = false;
        for session_id in origin_store.session_ids().await? {
            let session = origin_store
                .get_session(&session_id)
                .await?
                .expect("fixture session is readable");

            let mut files = OpencodeFactory.serialize(&session, RestoreFidelity::Foreign)?;
            assert_eq!(files.len(), 1, "foreign emits one file per session");
            let file = files.remove(0);
            assert_eq!(file.actual_fidelity, RestoreFidelity::Foreign);
            assert_eq!(
                file.relative_path,
                PathBuf::from(format!("{session_id}.json")),
                "foreign emits <session_id>.json at the root",
            );
            let body: Value = serde_json::from_slice(&file.bytes)?;
            // Defense-in-depth: the writer accepts the emitted path.
            crate::adapter::write_restored_files(
                &temp.path().join("opencode-restore"),
                vec![file],
            )?;
            assert_eq!(
                body["info"]["id"].as_str(),
                Some(session_id.as_str()),
                "envelope info carries the session id",
            );
            assert!(
                body["info"]["directory"].is_string(),
                "foreign session info carries a directory",
            );
            let messages = body["messages"]
                .as_array()
                .expect("envelope carries a messages array");

            for message in messages {
                let role = message["info"]["role"].as_str().expect("message info role");
                assert!(
                    role == "user" || role == "assistant",
                    "only user/assistant carriers survive foreign restore, got {role}",
                );
                assert_eq!(
                    message["info"]["sessionID"].as_str(),
                    Some(session_id.as_str()),
                );
                for part in message["parts"].as_array().expect("parts array") {
                    if part["type"].as_str() == Some("tool") {
                        saw_tool = true;
                        assert_eq!(
                            part["state"]["status"].as_str(),
                            Some("completed"),
                            "a re-fused tool part is completed",
                        );
                        assert!(
                            part["state"].get("input").is_some(),
                            "a re-fused tool part carries its input",
                        );
                    }
                }
            }
        }
        assert!(
            saw_tool,
            "the pi fixture's tool call re-fuses into a `tool` part",
        );
        Ok(())
    }

    #[test]
    fn path_ids_reject_separators_and_traversal() {
        let where_ = "session/project/session.json";
        assert!(validate_path_id(NAME, "session id", "ses_safe", where_).is_ok());
        assert!(validate_path_id(NAME, "session id", "../ses", where_).is_err());
        assert!(validate_path_id(NAME, "session id", "/tmp/ses", where_).is_err());
        assert!(validate_path_id(NAME, "message id", "msg/a", where_).is_err());
        assert!(validate_path_id(NAME, "message id", "msg\\a", where_).is_err());
    }

    fn append_fresh_opencode_turn(root: &std::path::Path) -> anyhow::Result<()> {
        let message_dir = root.join("message").join(FRESH_SESSION_ID);
        let part_dir = root.join("part").join(FRESH_MESSAGE_ID);
        std::fs::create_dir_all(&message_dir)?;
        std::fs::create_dir_all(&part_dir)?;
        std::fs::write(
            message_dir.join(format!("{FRESH_MESSAGE_ID}.json")),
            serde_json::to_vec(&json!({
                "id": FRESH_MESSAGE_ID,
                "sessionID": FRESH_SESSION_ID,
                "role": "user",
                "time": { "created": 1759859999000i64 }
            }))?,
        )?;
        std::fs::write(
            part_dir.join(format!("{FRESH_PART_ID}.json")),
            serde_json::to_vec(&json!({
                "id": FRESH_PART_ID,
                "sessionID": FRESH_SESSION_ID,
                "messageID": FRESH_MESSAGE_ID,
                "type": "text",
                "text": "fresh opencode text",
                "synthetic": false
            }))?,
        )?;
        Ok(())
    }

    fn write_minimal_session(
        root: &std::path::Path,
        session_id: &str,
        message_id: &str,
    ) -> anyhow::Result<()> {
        write_json_file(
            &root
                .join("session")
                .join("project")
                .join(format!("{session_id}.json")),
            &json!({
                "id": session_id,
                "projectID": "project",
                "directory": "/tmp/project",
                "time": { "created": 1_765_000_000_000i64, "updated": 1_765_000_000_000i64 },
            }),
        )?;
        write_json_file(
            &root
                .join("message")
                .join(session_id)
                .join(format!("{message_id}.json")),
            &json!({
                "id": message_id,
                "sessionID": session_id,
                "role": "assistant",
                "time": { "created": 1_765_000_000_001i64 },
            }),
        )?;
        std::fs::create_dir_all(root.join("part").join(message_id))?;
        Ok(())
    }

    fn write_json_file(path: &std::path::Path, value: &Value) -> anyhow::Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(path, serde_json::to_vec(value)?)?;
        Ok(())
    }

    fn copy_dir(from: &std::path::Path, to: &std::path::Path) -> anyhow::Result<()> {
        std::fs::create_dir_all(to)?;
        for entry in std::fs::read_dir(from)? {
            let entry = entry?;
            let source = entry.path();
            let target = to.join(entry.file_name());
            if entry.file_type()?.is_dir() {
                copy_dir(&source, &target)?;
            } else {
                std::fs::copy(&source, &target)?;
            }
        }
        Ok(())
    }

    fn insert_session(
        conn: &Connection,
        id: &str,
        directory: &str,
        parent: Option<&str>,
        agent: Option<&str>,
        created: i64,
    ) -> anyhow::Result<()> {
        conn.execute(
            "INSERT INTO session (id, project_id, parent_id, slug, directory, title, version, \
             agent, time_created, time_updated) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)",
            rusqlite::params![
                id,
                "proj-test",
                parent,
                "slug",
                directory,
                "title",
                "1.0.0",
                agent,
                created
            ],
        )?;
        Ok(())
    }

    fn insert_message(
        conn: &Connection,
        id: &str,
        session_id: &str,
        created: i64,
        data: &Value,
    ) -> anyhow::Result<()> {
        conn.execute(
            "INSERT INTO message (id, session_id, time_created, time_updated, data) \
             VALUES (?1, ?2, ?3, ?3, ?4)",
            rusqlite::params![id, session_id, created, serde_json::to_string(data)?],
        )?;
        Ok(())
    }

    fn insert_part(
        conn: &Connection,
        id: &str,
        message_id: &str,
        session_id: &str,
        created: i64,
        data: &Value,
    ) -> anyhow::Result<()> {
        conn.execute(
            "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) \
             VALUES (?1, ?2, ?3, ?4, ?4, ?5)",
            rusqlite::params![
                id,
                message_id,
                session_id,
                created,
                serde_json::to_string(data)?
            ],
        )?;
        Ok(())
    }

    /// Write a minimal legacy-tree session (one assistant message, one text part
    /// carrying `marker`) under `tree_base`.
    fn write_tree_session(
        tree_base: &std::path::Path,
        session_id: &str,
        marker: &str,
    ) -> anyhow::Result<()> {
        let message_id = format!("msg_tree_{session_id}");
        let part_id_value = format!("prt_tree_{session_id}");
        write_json_file(
            &tree_base
                .join("session")
                .join("proj-tree")
                .join(format!("{session_id}.json")),
            &json!({
                "id": session_id,
                "projectID": "proj-tree",
                "directory": "/tmp/tree",
                "time": { "created": 1_780_000_000_000i64 },
            }),
        )?;
        write_json_file(
            &tree_base
                .join("message")
                .join(session_id)
                .join(format!("{message_id}.json")),
            &json!({
                "id": message_id,
                "sessionID": session_id,
                "role": "assistant",
                "time": { "created": 1_780_000_000_001i64 },
            }),
        )?;
        write_json_file(
            &tree_base
                .join("part")
                .join(&message_id)
                .join(format!("{part_id_value}.json")),
            &json!({
                "id": part_id_value,
                "sessionID": session_id,
                "messageID": message_id,
                "type": "text",
                "text": marker,
                "synthetic": false,
            }),
        )?;
        Ok(())
    }

    // Facts about the committed OpenCode 2 fixture (`v2/opencode.db`): three
    // OpenCode 1 sessions the V1->V2 migration copied forward, plus nine created
    // by OpenCode 2.0.27.
    const V2_SESSION_COUNT: usize = 12;
    const V2_MIGRATED_CONTINUED: &str = "ses_ece44e9c1ffeJWYCR23BcS31lX";
    const V2_MIGRATED_SPLIT_COPY: &str = "msg_131bb1661001TtVuWkGzyg3n04";
    const V2_POST_MIGRATION_USER: &str = "msg_131c0e706001jV7Smy0gYSlb2L";
    const V2_MIGRATED_WITH_NOTICE: &str = "ses_ece45e791ffekNVGH2hsZMQvl5";
    const V2_LEGACY_TOOL_NOTICE: &str = "msg_131ba23ec001TKOqvkoEn1JeVb";
    const V2_MIGRATED_UNTOUCHED: &str = "ses_ece45fa45ffewtiD8DSPLj3P62";
    const V2_TOOLS_SESSION: &str = "ses_ece44ba32ffevzFy2aZZD3h7TM";
    const V2_CHILD: &str = "ses_ece3f27c0ffeXmTUqsOvLDGlbM";
    const V2_CHILD_PARENT: &str = "ses_ece3f2e9affezCws7GfDhhKVSE";
    const V2_FORK: &str = "ses_ece3c3812ffeMp6n6hGikNUmC3";
    const V2_FORK_THROUGH: &str = "msg_131bb5340001PD3DzEht2R4zp9";
    const V2_OPS_SESSION: &str = "ses_ece3c826dffeLR2B3sqhOHBVYG";

    fn v2_db_fixture() -> PathBuf {
        crate::adapter::test_support::manifest_dir()
            .join("tests/fixtures/adapter/opencode/v2/opencode.db")
    }

    fn v2_data_dir(temp: &std::path::Path) -> anyhow::Result<PathBuf> {
        let dir = temp.join("data");
        std::fs::create_dir_all(&dir)?;
        std::fs::copy(v2_db_fixture(), dir.join("opencode.db"))?;
        Ok(dir)
    }

    async fn ingest_v2(
        temp: &std::path::Path,
    ) -> anyhow::Result<(Store, PathBuf, crate::handlers::IngestSummary)> {
        let data = v2_data_dir(temp)?;
        let store = Store::open_local(temp.join("store")).await?;
        let summary = ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;
        Ok((store, data, summary))
    }

    fn v2_type(message: &crate::sessions::MessageWithParts) -> Option<String> {
        raw_record(message.message.options()).and_then(|raw| {
            raw.get("type")
                .and_then(Value::as_str)
                .map(ToOwned::to_owned)
        })
    }

    fn texts(message: &crate::sessions::MessageWithParts) -> Vec<(Provenance, String)> {
        message
            .parts
            .iter()
            .filter_map(|part| match &part.kind {
                PartKind::Text { text } => Some((
                    part.provenance,
                    text.as_deref()
                        .map(String::as_str)
                        .unwrap_or_default()
                        .to_owned(),
                )),
                _ => None,
            })
            .collect()
    }

    /// Every session of a DB holding both table generations lands once: V1-only
    /// none here, nine V2-only, three migrated. A migrated session keeps its V1
    /// message and part rows, gains the V2 rows written after the migration, and
    /// never re-ingests the migration's own copies (the split-off synthetic row,
    /// the trailing legacy-tool notice).
    #[tokio::test(flavor = "multi_thread")]
    async fn v2_fixture_merges_both_table_generations() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let (store, _, summary) = ingest_v2(temp.path()).await?;
        assert_eq!(summary.dropped_events, 0, "{summary:?}");
        assert_eq!(summary.dropped_sessions, 0, "{summary:?}");
        assert_eq!(store.session_ids().await?.len(), V2_SESSION_COUNT);

        let continued = store
            .get_session(V2_MIGRATED_CONTINUED)
            .await?
            .expect("migrated session ingests");
        let ids: Vec<&str> = continued.messages.iter().map(|m| m.message.id()).collect();
        assert!(
            ids.contains(&V2_POST_MIGRATION_USER),
            "post-migration turn lands"
        );
        assert!(
            !ids.contains(&V2_MIGRATED_SPLIT_COPY),
            "the migration's split-off copy of a V1 record is not re-ingested",
        );
        assert!(
            continued
                .messages
                .iter()
                .flat_map(|m| &m.parts)
                .any(|part| part.id.starts_with("prt_")),
            "migrated history keeps its V1 part rows",
        );
        assert!(
            raw_record(&continued.session.options)
                .is_some_and(|raw| raw.get("projectID").is_some()),
            "a migrated session keeps its V1 head",
        );

        let noticed = store
            .get_session(V2_MIGRATED_WITH_NOTICE)
            .await?
            .expect("migrated session ingests");
        assert!(
            noticed
                .messages
                .iter()
                .all(|m| m.message.id() != V2_LEGACY_TOOL_NOTICE),
            "the migration's appended legacy-tool notice is a copy, not activity",
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn v2_lineage_covers_spawned_children_and_forks() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let (store, _, _) = ingest_v2(temp.path()).await?;

        let child = store.get_session(V2_CHILD).await?.expect("child ingests");
        assert_eq!(
            child.session.parent_session_id.as_deref(),
            Some(V2_CHILD_PARENT)
        );
        assert_eq!(child.session.parent_message_id, None);
        assert_eq!(child.session.source_agent, "opencode/general");

        let fork = store.get_session(V2_FORK).await?.expect("fork ingests");
        assert_eq!(
            fork.session.parent_session_id.as_deref(),
            Some(V2_TOOLS_SESSION)
        );
        assert_eq!(
            fork.session.parent_message_id.as_deref(),
            Some(V2_FORK_THROUGH),
            "a `through` boundary is the fork's cut-point",
        );
        assert_eq!(
            fork.session.source_agent, "opencode",
            "a fork is not a subagent"
        );
        Ok(())
    }

    /// Each V2 message type takes the conversational slot OpenCode sends it in,
    /// with injected content marked; markers are empty system carriers. Every V2
    /// message carries its whole record and `seq`.
    #[tokio::test(flavor = "multi_thread")]
    async fn v2_message_types_land_in_their_model_slots() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let (store, _, _) = ingest_v2(temp.path()).await?;
        let ops = store
            .get_session(V2_OPS_SESSION)
            .await?
            .expect("ops session ingests");
        let by_type = |kind: &str| {
            ops.messages
                .iter()
                .filter(|m| v2_type(m).as_deref() == Some(kind))
                .collect::<Vec<_>>()
        };
        let one = |kind: &str| {
            let found = by_type(kind);
            assert!(!found.is_empty(), "fixture has a {kind} row");
            found[0]
        };
        for message in &ops.messages {
            if !is_synthetic(message.message.options()) {
                assert!(
                    message_seq(message.message.options()).is_some(),
                    "V2 message {} carries its seq",
                    message.message.id(),
                );
            }
        }

        let skill = one("skill");
        assert_eq!(skill.message.role(), crate::wire::Role::User);
        assert!(matches!(
            texts(skill).as_slice(),
            [(Provenance::Injected, _)]
        ));

        let shell = one("shell");
        assert_eq!(shell.message.role(), crate::wire::Role::User);
        assert_eq!(
            texts(shell),
            vec![(Provenance::Conversational, "ls".to_owned())]
        );
        let output = ops
            .messages
            .iter()
            .find(|m| m.message.id() == format!("{}/output", shell.message.id()))
            .expect("a finished shell's output carrier");
        assert!(matches!(
            &output.message,
            Message::System { content: Some(text), .. } if text.as_str() == "README.md\ndot.png\n"
        ));
        assert!(is_synthetic(output.message.options()));

        for synthetic in by_type("synthetic") {
            assert_eq!(synthetic.message.role(), crate::wire::Role::User);
            assert!(
                texts(synthetic)
                    .iter()
                    .all(|(p, _)| *p == Provenance::Injected)
            );
        }

        let compaction = one("compaction");
        assert_eq!(compaction.message.role(), crate::wire::Role::User);
        assert!(
            texts(compaction)
                .iter()
                .all(|(p, _)| *p == Provenance::Injected)
        );

        for kind in ["idle", "agent-switched", "model-switched"] {
            let marker = one(kind);
            assert!(
                matches!(&marker.message, Message::System { content: None, .. }),
                "{kind} is an empty carrier",
            );
            assert!(marker.parts.is_empty());
        }

        let prompt = one("user");
        assert!(matches!(
            texts(prompt).as_slice(),
            [(Provenance::Conversational, text)] if text.contains("Say hi")
        ));
        Ok(())
    }

    /// A V2 tool item becomes a ToolCall plus a split-off result carrier; a failed
    /// call's result is its error and is flagged.
    #[tokio::test(flavor = "multi_thread")]
    async fn v2_tool_items_split_into_call_and_result() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let (store, _, _) = ingest_v2(temp.path()).await?;
        let session = store
            .get_session(V2_TOOLS_SESSION)
            .await?
            .expect("tools session ingests");
        let calls: Vec<String> = session
            .messages
            .iter()
            .flat_map(|m| &m.parts)
            .filter_map(|part| match &part.kind {
                PartKind::ToolCall { call_id, .. } => call_id.as_deref().cloned(),
                _ => None,
            })
            .collect();
        assert_eq!(calls.len(), 2, "two read calls");
        let results: Vec<(String, bool, Value)> = session
            .messages
            .iter()
            .flat_map(|m| &m.parts)
            .filter_map(|part| match &part.kind {
                PartKind::ToolResult {
                    call_id,
                    is_failure,
                    result,
                    ..
                } => Some((call_id.as_deref().cloned()?, *is_failure, result.clone())),
                _ => None,
            })
            .collect();
        assert_eq!(results.len(), 2, "each settled call has a result");
        for (call_id, _, _) in &results {
            assert!(
                calls.contains(call_id),
                "result {call_id} correlates to a call"
            );
        }
        let failed: Vec<_> = results.iter().filter(|(_, failure, _)| *failure).collect();
        assert_eq!(failed.len(), 1);
        assert_eq!(failed[0].2["type"], "tool.execution");
        assert!(
            results
                .iter()
                .any(|(_, failure, result)| !failure && result[0]["text"].is_string()),
            "a completed call's result is its content",
        );
        Ok(())
    }

    /// An unfinished call (`streaming`/`running`) has no result yet, so none is
    /// invented; an unknown content kind and an unknown message type still land.
    #[test]
    fn v2_unfinished_and_unknown_records_land_without_synthesis() {
        let anchor = DateTime::from_timestamp_millis(1).expect("valid");
        let assistant = json!({
            "id": "msg_a", "type": "assistant", "time": { "created": 1000 },
            "content": [
                { "type": "tool", "id": "call_s", "name": "bash",
                  "state": { "status": "streaming", "input": "{\"comm" }, "time": { "created": 1001 } },
                { "type": "tool", "id": "call_r", "name": "bash",
                  "state": { "status": "running", "input": { "command": "ls" }, "metadata": {} },
                  "time": { "created": 1002, "ran": 1003 } },
                { "type": "future-kind", "data": 1 },
            ],
        });
        let events = build_v2_message_events("ses_x", "msg_a", &assistant, 7, anchor);
        let messages = events
            .iter()
            .filter(|event| matches!(event, IngestEvent::Message(_)))
            .count();
        assert_eq!(messages, 1, "no result carrier for an unfinished call");
        let parts: Vec<&Part> = events
            .iter()
            .filter_map(|event| match event {
                IngestEvent::Part(part) => Some(part),
                _ => None,
            })
            .collect();
        assert_eq!(parts.len(), 3);
        assert!(matches!(&parts[0].kind, PartKind::ToolCall { params, .. } if params == "{\"comm"));
        assert!(matches!(&parts[2].kind, PartKind::Text { text: None }));

        let future = json!({ "id": "msg_f", "type": "teleported", "time": { "created": 5 } });
        let events = build_v2_message_events("ses_x", "msg_f", &future, 8, anchor);
        assert!(matches!(
            events.as_slice(),
            [IngestEvent::Message(Message::System { content: None, options, .. })]
                if raw_record(options).is_some_and(|raw| raw["type"] == "teleported")
        ));
    }

    /// Native restore of a V2 session is OpenCode 2's transfer shape: `info` is
    /// `fromRow` of its row and `messages` are its `session_message` records
    /// (`{...data, id, type}`) in `seq` order. A migrated session that continued
    /// in V2 cannot be one import shape and downgrades to foreign; an untouched
    /// migrated one restores natively in the V1 envelope.
    #[tokio::test(flavor = "multi_thread")]
    async fn v2_native_restore_replays_the_transfer_shape() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let (store, data, _) = ingest_v2(temp.path()).await?;
        let conn = open_db(&data.join("opencode.db"))?;
        let v1_ids: HashSet<String> = conn
            .prepare("SELECT id FROM session")?
            .query_map([], |row| row.get(0))?
            .collect::<rusqlite::Result<_>>()?;

        let mut native_v2 = 0usize;
        for session_id in store.session_ids().await? {
            let session = store.get_session(&session_id).await?.expect("round-trips");
            if v1_ids.contains(&session_id) {
                continue;
            }
            let body = serialize_native_body(&session);
            native_v2 += 1;
            let expected: Vec<Value> = conn
                .prepare(
                    "SELECT id, type, data FROM session_message WHERE session_id = ?1 ORDER BY seq",
                )?
                .query_map([&session_id], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, String>(2)?,
                    ))
                })?
                .map(|row| {
                    let (id, kind, data) = row.expect("row");
                    let mut value: Value = serde_json::from_str(&data).expect("json");
                    value["id"] = json!(id);
                    value["type"] = json!(kind);
                    crate::adapter::extract::extract_raw_record(&value)
                })
                .collect();
            assert_eq!(
                body["messages"].as_array().expect("messages"),
                &expected,
                "{session_id}: messages replay the session_message records in seq order",
            );
            let row = conn.query_row(
                "SELECT * FROM session_v2 WHERE id = ?1",
                [&session_id],
                v2_row_value,
            )?;
            assert_eq!(body["info"]["id"], json!(session_id));
            assert_eq!(body["info"]["projectID"], row["project_id"]);
            assert_eq!(body["info"]["location"]["directory"], row["directory"]);
            assert_eq!(body["info"]["time"]["created"], row["time_created"]);
            assert!(
                body["info"]["model"]["variant"].is_string(),
                "fromRow fills variant"
            );
            if session_id == V2_FORK {
                assert_eq!(body["info"]["fork"]["sessionID"], json!(V2_TOOLS_SESSION));
                assert_eq!(body["info"]["fork"]["boundary"]["type"], "through");
            }
        }
        assert_eq!(native_v2, V2_SESSION_COUNT - v1_ids.len());

        let continued = store
            .get_session(V2_MIGRATED_CONTINUED)
            .await?
            .expect("round-trips");
        let files = serialize_native(&continued)?;
        assert_eq!(files[0].actual_fidelity, RestoreFidelity::Foreign);

        let untouched = store
            .get_session(V2_MIGRATED_UNTOUCHED)
            .await?
            .expect("round-trips");
        let body = serialize_native_body(&untouched);
        assert!(
            body["messages"][0]["info"]["role"].is_string(),
            "V1 envelope"
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn plan_matches_the_events_gate_v2_source() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = v2_data_dir(temp.path())?;
        let (first, max_plan) = plan_gate_agreement(&OpencodeAdapter::new(&data)).await?;
        assert_eq!(first.sessions, V2_SESSION_COUNT);
        assert_eq!(max_plan.fresh, V2_SESSION_COUNT);
        Ok(())
    }

    /// The watermark of a migrated session ignores the migration's copies (whose
    /// `time.created` is the migration-stamped V1 column) and rises with the first
    /// post-migration V2 row; a re-read then adds exactly that row.
    #[tokio::test(flavor = "multi_thread")]
    async fn v2_freshness_tracks_post_migration_rows() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let (store, data, _) = ingest_v2(temp.path()).await?;
        let db = data.join("opencode.db");
        let light = |session_id: &str, store| DbLight {
            db_path: db.clone(),
            session_id: session_id.to_owned(),
            store,
        };
        {
            let conn = open_db(&db)?;
            let notice = light(V2_MIGRATED_WITH_NOTICE, DbStore::Migrated);
            assert_eq!(
                db_store_watermark(&conn, &notice)?,
                db_session_watermark(&conn, &db, V2_MIGRATED_WITH_NOTICE)?,
                "a migration copy never raises a migrated session's watermark",
            );
        }

        let appended_ms: i64 = 1_800_000_000_000;
        {
            let conn = Connection::open(&db)?;
            conn.execute(
                "INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data)
                 VALUES ('msg_zzzzv2fresh00000000000000', ?1, 'user', 1000, ?2, ?2, ?3)",
                rusqlite::params![
                    V2_MIGRATED_WITH_NOTICE,
                    appended_ms,
                    json!({ "time": { "created": appended_ms }, "text": "fresh v2 turn" }).to_string(),
                ],
            )?;
            let conn = open_db(&db)?;
            assert_eq!(
                db_store_watermark(&conn, &light(V2_MIGRATED_WITH_NOTICE, DbStore::Migrated))?,
                Some(appended_ms * 1_000),
            );
        }
        let before = store
            .get_session(V2_MIGRATED_WITH_NOTICE)
            .await?
            .expect("ingested")
            .messages
            .len();
        let oracle = FixedOracle {
            session_id: V2_MIGRATED_WITH_NOTICE,
            watermark_micros: appended_ms * 1_000 - 1,
        };
        ingest_adapter(&store, &OpencodeAdapter::new(&data), &oracle, |_| {}).await?;
        let after = store
            .get_session(V2_MIGRATED_WITH_NOTICE)
            .await?
            .expect("ingested");
        assert_eq!(
            after.messages.len(),
            before + 1,
            "only the new V2 row is added"
        );
        Ok(())
    }

    /// A session repeated across DBs (a pre-release `opencode-next.db` its
    /// migration already imported) lands once, from `opencode.db`, and the
    /// repeats are counted as superseded.
    #[tokio::test(flavor = "multi_thread")]
    async fn session_repeated_across_dbs_lands_once() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = v2_data_dir(temp.path())?;
        std::fs::copy(v2_db_fixture(), data.join("opencode-next.db"))?;
        let store = Store::open_local(temp.path().join("store")).await?;
        let summary = ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;
        assert_eq!(store.session_ids().await?.len(), V2_SESSION_COUNT);
        assert_eq!(summary.skipped_superseded, V2_SESSION_COUNT, "{summary:?}");
        Ok(())
    }

    /// A DB with no V1 tables (a fresh OpenCode 2 install) reads every session
    /// from the V2 tables instead of failing enumeration.
    #[tokio::test(flavor = "multi_thread")]
    async fn v2_only_db_without_v1_tables_ingests() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = v2_data_dir(temp.path())?;
        Connection::open(data.join("opencode.db"))?.execute_batch(
            "PRAGMA foreign_keys = OFF; DROP TABLE part; DROP TABLE message; DROP TABLE session;",
        )?;
        let store = Store::open_local(temp.path().join("store")).await?;
        let summary = ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;
        assert_eq!(summary.dropped_events, 0, "{summary:?}");
        assert_eq!(store.session_ids().await?.len(), V2_SESSION_COUNT);
        let migrated = store
            .get_session(V2_MIGRATED_CONTINUED)
            .await?
            .expect("ingests from V2 alone");
        assert!(
            migrated
                .messages
                .iter()
                .any(|m| m.message.id() == V2_MIGRATED_SPLIT_COPY),
            "with no V1 rows to prefer, the V2 copies are the only record",
        );
        Ok(())
    }

    #[test]
    fn synthetic_id_matches_the_migration() {
        assert_eq!(
            synthetic_id("msg_131bb1661001jevwkFX4ZpwQDM"),
            V2_MIGRATED_SPLIT_COPY,
            "the user/synthetic split",
        );
        assert_eq!(
            synthetic_id("msg_131ba23ec001D2OA1U5ijz8c0y"),
            V2_LEGACY_TOOL_NOTICE,
            "the legacy-tool notice after the last projected row",
        );
    }

    fn insert_v2_row(
        conn: &Connection,
        id: &str,
        session_id: &str,
        kind: &str,
        seq: i64,
        created_ms: i64,
        data: &Value,
    ) -> anyhow::Result<()> {
        conn.execute(
            "INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data)
             VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6)",
            rusqlite::params![id, session_id, kind, seq, created_ms, data.to_string()],
        )?;
        Ok(())
    }

    fn message_ids(session: &crate::sessions::SessionWithMessages) -> Vec<&str> {
        session.messages.iter().map(|m| m.message.id()).collect()
    }

    /// A V1 message deleted after the migration (an OpenCode 1.x revert after a
    /// downgrade) leaves its V2 copy inside the migration's `seq` prefix, so it
    /// stays skipped. The live row past the copy prefix is kept, though its id
    /// shares a V1 id's 16-char prefix and its `time_created` predates the
    /// migration: both rejected copy rules (docs/adapters/opencode.md) would drop it.
    #[tokio::test(flavor = "multi_thread")]
    async fn migration_copies_are_exact_and_survive_v1_deletes() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = v2_data_dir(temp.path())?;
        let deleted_v1 = "msg_131ba198c001kCcV4OpDtOChtC";
        let lookalike = "msg_131ba23ec001ZZZZZZZZZZZZZZ";
        {
            let conn = Connection::open(data.join("opencode.db"))?;
            conn.execute_batch("PRAGMA foreign_keys = OFF;")?;
            conn.execute("DELETE FROM part WHERE message_id = ?1", [deleted_v1])?;
            conn.execute("DELETE FROM message WHERE id = ?1", [deleted_v1])?;
            insert_v2_row(
                &conn,
                lookalike,
                V2_MIGRATED_WITH_NOTICE,
                "user",
                500,
                1_700_000_000_000,
                &json!({ "time": { "created": 1_800_000_000_000i64 }, "text": "after the upgrade" }),
            )?;
        }
        let store = Store::open_local(temp.path().join("store")).await?;
        ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;
        let session = store
            .get_session(V2_MIGRATED_WITH_NOTICE)
            .await?
            .expect("ingests");
        let ids = message_ids(&session);
        assert!(
            !ids.contains(&deleted_v1),
            "the deleted V1 message's copy stays skipped"
        );
        assert!(!ids.contains(&V2_LEGACY_TOOL_NOTICE));
        assert!(
            ids.contains(&lookalike),
            "a prefix lookalike is real activity"
        );
        Ok(())
    }

    /// A pre-release OpenCode 2 DB keeps V2 heads in a table still named
    /// `session` (bodies in `session_message`). Its sessions read through the V2
    /// path; one the live DB already holds is superseded, a unique one lands
    /// with its transcript.
    #[tokio::test(flavor = "multi_thread")]
    async fn prerelease_v2_db_reads_heads_from_its_session_table() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = v2_data_dir(temp.path())?;
        let next = data.join("opencode-next.db");
        std::fs::copy(v2_db_fixture(), &next)?;
        let unique = "ses_zzzznextonly000000000000";
        let empty = "ses_zzzznextempty00000000000";
        {
            let conn = Connection::open(&next)?;
            conn.execute_batch(
                "PRAGMA foreign_keys = OFF;
                 DROP TABLE part; DROP TABLE message; DROP TABLE session;
                 ALTER TABLE session_v2 RENAME TO session;",
            )?;
            conn.execute(
                "UPDATE session SET id = ?1 WHERE id = ?2",
                [unique, V2_OPS_SESSION],
            )?;
            conn.execute(
                "UPDATE session_message SET session_id = ?1 WHERE session_id = ?2",
                [unique, V2_OPS_SESSION],
            )?;
            conn.execute(
                "CREATE TEMP TABLE head AS SELECT * FROM session WHERE id = ?1",
                [unique],
            )?;
            conn.execute("UPDATE head SET id = ?1", [empty])?;
            conn.execute_batch("INSERT INTO session SELECT * FROM head;")?;
        }
        let store = Store::open_local(temp.path().join("store")).await?;
        let summary = ingest_adapter(
            &store,
            &OpencodeAdapter::new(&data),
            &crate::adapter::NoopOracle,
            |_| {},
        )
        .await?;
        assert_eq!(summary.dropped_events, 0, "{summary:?}");
        assert_eq!(summary.unreadable_events, 0, "{summary:?}");
        assert_eq!(store.session_ids().await?.len(), V2_SESSION_COUNT + 2);
        assert_eq!(
            summary.skipped_superseded,
            V2_SESSION_COUNT - 1,
            "{summary:?}"
        );
        let session = store
            .get_session(unique)
            .await?
            .expect("unique session lands");
        let ops = store.get_session(V2_OPS_SESSION).await?.expect("ops lands");
        assert_eq!(
            session.messages.len(),
            ops.messages.len(),
            "with its whole transcript"
        );
        assert_eq!(session_store(&session.session.options), Some("session"));
        let empty = store
            .get_session(empty)
            .await?
            .expect("empty session lands");
        assert_eq!(session_store(&empty.session.options), Some("session"));
        assert_eq!(
            serialize_native(&session)?[0].actual_fidelity,
            RestoreFidelity::Native
        );
        Ok(())
    }

    /// OpenCode rewrites a running assistant row in place. A sync mid-turn
    /// defers it (and keeps the session unknown, so it is re-read); once the
    /// turn closes, the finished row lands with its final content.
    #[tokio::test(flavor = "multi_thread")]
    async fn unsettled_rows_wait_for_the_turn_to_close() -> anyhow::Result<()> {
        const SESSION: &str = "ses_ece40409affezvqxNOKCv7GG6X";
        const ASSISTANT: &str = "msg_zzzzv2streaming0000000000";
        let temp = TempDir::new()?;
        let (store, data, _) = ingest_v2(temp.path()).await?;
        let db = data.join("opencode.db");
        let adapter = OpencodeAdapter::new(&data);
        let started: i64 = 1_800_000_000_000;
        let assistant = |text: &str, completed: Option<i64>| {
            let mut time = json!({ "created": started + 1 });
            if let Some(completed) = completed {
                time["completed"] = json!(completed);
            }
            json!({
                "time": time, "agent": "build",
                "model": { "id": "m", "providerID": "p" },
                "content": [{ "type": "text", "text": text }],
            })
        };
        {
            let conn = Connection::open(&db)?;
            insert_v2_row(
                &conn,
                "msg_zzzzv2prompt0000000000000",
                SESSION,
                "user",
                100,
                started,
                &json!({ "time": { "created": started }, "text": "next question" }),
            )?;
            insert_v2_row(
                &conn,
                ASSISTANT,
                SESSION,
                "assistant",
                101,
                started + 1,
                &assistant("par", None),
            )?;
        }
        let light = DbLight {
            db_path: db.clone(),
            session_id: SESSION.to_owned(),
            store: DbStore::V2 { head: "session_v2" },
        };
        assert_eq!(
            db_store_watermark(&open_db(&db)?, &light)?,
            None,
            "open turn: unknown"
        );

        let fresh_everywhere = FixedOracle {
            session_id: SESSION,
            watermark_micros: i64::MAX,
        };
        ingest_adapter(&store, &adapter, &fresh_everywhere, |_| {}).await?;
        let mid = store.get_session(SESSION).await?.expect("ingested");
        assert!(message_ids(&mid).contains(&"msg_zzzzv2prompt0000000000000"));
        assert!(
            !message_ids(&mid).contains(&ASSISTANT),
            "the running row is deferred"
        );

        {
            let conn = Connection::open(&db)?;
            conn.execute(
                "UPDATE session_message SET data = ?1 WHERE id = ?2",
                rusqlite::params![
                    assistant("final answer", Some(started + 5)).to_string(),
                    ASSISTANT
                ],
            )?;
            insert_v2_row(
                &conn,
                "msg_zzzzv2idle000000000000000",
                SESSION,
                "idle",
                102,
                started + 6,
                &json!({ "time": { "created": started + 6 }, "outcome": "succeeded" }),
            )?;
        }
        let oracle = FixedOracle {
            session_id: SESSION,
            watermark_micros: started * 1_000,
        };
        ingest_adapter(&store, &adapter, &oracle, |_| {}).await?;
        let done = store.get_session(SESSION).await?.expect("ingested");
        let finished = done
            .messages
            .iter()
            .find(|m| m.message.id() == ASSISTANT)
            .expect("the settled row lands");
        assert_eq!(
            texts(finished),
            vec![(Provenance::Conversational, "final answer".to_owned())],
        );
        Ok(())
    }

    /// An unreadable newest V2 row makes a migrated session unknown even though
    /// its V1 side alone would read as fresh, so the next sync surfaces it.
    #[test]
    fn unreadable_v2_tail_makes_a_migrated_session_unknown() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = v2_data_dir(temp.path())?;
        let db = data.join("opencode.db");
        Connection::open(&db)?.execute(
            "UPDATE session_message SET data = '{not json' WHERE id = ?1",
            [V2_POST_MIGRATION_USER],
        )?;
        // The marker after it would otherwise close the turn before it.
        Connection::open(&db)?.execute(
            "DELETE FROM session_message WHERE session_id = ?1 AND type = 'idle'",
            [V2_MIGRATED_CONTINUED],
        )?;
        let light = DbLight {
            db_path: db.clone(),
            session_id: V2_MIGRATED_CONTINUED.to_owned(),
            store: DbStore::Migrated,
        };
        assert_eq!(db_store_watermark(&open_db(&db)?, &light)?, None);
        Ok(())
    }

    /// `info` follows OpenCode's `fromRow`: falsy columns read as unset, and a
    /// legacy revert decodes to the current shape.
    #[test]
    fn v2_session_info_follows_from_row() {
        let info = v2_session_info(&json!({
            "id": "ses_a", "project_id": "p", "directory": "/w", "title": "",
            "parent_id": "", "agent": "", "path": "", "time_archived": 0,
            "time_created": 1, "time_updated": 2, "cost": 0.5,
            "tokens_input": 1, "tokens_output": 2, "tokens_reasoning": 0,
            "tokens_cache_read": 0, "tokens_cache_write": 0,
            "revert": { "messageID": "msg_a", "diff": "d",
                        "files": [{ "path": "f", "status": "modified", "additions": 1, "deletions": 0, "patch": "p" }] },
        }));
        assert_eq!(info["title"], "", "title uses `??`, so an empty one stays");
        for key in ["parentID", "agent", "subpath"] {
            assert!(info.get(key).is_none(), "{key} is unset when empty");
        }
        assert!(info["time"].get("archived").is_none());
        assert_eq!(
            info["revert"],
            json!({ "messageID": "msg_a", "files": [{ "file": "f", "status": "modified", "additions": 1, "deletions": 0, "patch": "p" }] }),
        );
    }

    fn v2_light(db: &std::path::Path, session_id: &str) -> DbLight {
        DbLight {
            db_path: db.to_path_buf(),
            session_id: session_id.to_owned(),
            store: DbStore::V2 { head: "session_v2" },
        }
    }

    /// The fixture's ops session, cut right after its seq-21 assistant: that row
    /// was inserted after rows with a later `time.created` (steering while the
    /// step started), so a max-timestamp watermark cannot show it was stored and
    /// the open turn stays unknown until the next `idle` closes it. The same
    /// holds with the assistant inserted in order (seq 13): deferred while it
    /// ran, its settling raises no timestamp above the steering rows after it.
    #[test]
    fn out_of_order_insert_keeps_the_open_turn_unknown() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = v2_data_dir(temp.path())?;
        let db = data.join("opencode.db");
        let conn = Connection::open(&db)?;
        conn.execute(
            "DELETE FROM session_message WHERE session_id = ?1 AND seq > 21",
            [V2_OPS_SESSION],
        )?;
        let light = v2_light(&db, V2_OPS_SESSION);
        assert_eq!(db_store_watermark(&conn, &light)?, None);
        conn.execute(
            "UPDATE session_message SET seq = 13 WHERE session_id = ?1 AND seq = 21",
            [V2_OPS_SESSION],
        )?;
        assert_eq!(db_store_watermark(&conn, &light)?, None, "in order too");
        insert_v2_row(
            &conn,
            "msg_zzzzv2idleaftermath000000",
            V2_OPS_SESSION,
            "idle",
            22,
            1_800_000_000_000,
            &json!({ "time": { "created": 1_800_000_000_000i64 }, "outcome": "succeeded" }),
        )?;
        assert_eq!(
            db_store_watermark(&conn, &light)?,
            Some(1_800_000_000_000 * 1_000),
            "a closed turn reads fresh again",
        );
        Ok(())
    }

    /// A background shell outlives the turn that started it: still running behind
    /// a later `idle`, it is deferred and keeps the session unknown; once it ends
    /// it lands with its output.
    #[tokio::test(flavor = "multi_thread")]
    async fn running_background_shell_waits_even_behind_idle() -> anyhow::Result<()> {
        let temp = TempDir::new()?;
        let data = v2_data_dir(temp.path())?;
        let db = data.join("opencode.db");
        let shell_id: String = Connection::open(&db)?.query_row(
            "SELECT id FROM session_message WHERE session_id = ?1 AND type = 'shell'",
            [V2_OPS_SESSION],
            |row| row.get(0),
        )?;
        let running = json!({
            "metadata": { "background": true }, "time": { "created": 1_791_836_259_452i64 },
            "shellID": "sh_x", "command": "ls", "status": "running",
        });
        Connection::open(&db)?.execute(
            "UPDATE session_message SET data = ?1 WHERE id = ?2",
            rusqlite::params![running.to_string(), shell_id],
        )?;
        assert_eq!(
            db_store_watermark(&open_db(&db)?, &v2_light(&db, V2_OPS_SESSION))?,
            None
        );

        let store = Store::open_local(temp.path().join("store")).await?;
        let adapter = OpencodeAdapter::new(&data);
        ingest_adapter(&store, &adapter, &crate::adapter::NoopOracle, |_| {}).await?;
        let mid = store.get_session(V2_OPS_SESSION).await?.expect("ingests");
        assert!(
            !message_ids(&mid).contains(&shell_id.as_str()),
            "the running shell waits"
        );

        let mut ended = running;
        ended["status"] = json!("exited");
        ended["exit"] = json!(0);
        ended["time"]["completed"] = json!(1_800_000_000_000i64);
        ended["output"] = json!({ "output": "README.md\n" });
        Connection::open(&db)?.execute(
            "UPDATE session_message SET data = ?1 WHERE id = ?2",
            rusqlite::params![ended.to_string(), shell_id],
        )?;
        // The store's own watermarks, as `pond sync` uses them: the shell ended
        // with no later row, and its end alone must trigger the re-read.
        let oracle = crate::sessions::RowmapOracle(store.rowmap_snapshot());
        ingest_adapter(&store, &adapter, &oracle, |_| {}).await?;
        let done = store.get_session(V2_OPS_SESSION).await?.expect("ingests");
        assert!(
            message_ids(&done).contains(&shell_id.as_str()),
            "the ended shell lands"
        );
        let output = done
            .messages
            .iter()
            .find(|m| m.message.id() == format!("{shell_id}/output"))
            .expect("with its output carrier");
        assert!(matches!(
            &output.message,
            Message::System { content: Some(text), .. } if text.as_str() == "README.md\n"
        ));
        let summary = ingest_adapter(
            &store,
            &adapter,
            &crate::sessions::RowmapOracle(store.rowmap_snapshot()),
            |_| {},
        )
        .await?;
        assert_eq!(
            summary.inserted, 0,
            "then the session reads fresh: {summary:?}"
        );
        Ok(())
    }
}