meerkat-store 0.8.25

Session persistence for Meerkat
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
//! SQLite-backed session store.

use crate::error::into_session_store_error;
use crate::json_column::JsonColumnBytes;
use crate::{SessionFilter, SessionStore, SessionStoreError, StoreError};
use async_trait::async_trait;
use meerkat_core::session_store::{
    HeadCanonicalAuthorityCrossing, HeadCanonicalStoreActivation, IncrementalSessionStore,
    PreparedHeadCanonicalMutation, PreparedHeadCanonicalParentSplice,
    PreparedHeadCanonicalParentTransition, PreparedHeadCanonicalRewriteMutation,
    SESSION_ROW_LINEAGE_REBASE_INTERVAL, SaveGuardWitness, SessionHead, SessionHeadCas,
    SessionMessageRowPrefixAccumulator, StrandLayout, StrandRewriteLayout, StrandSegment,
    StrandSplice, TranscriptStrandId, VerifiedHeadCanonicalTranscriptHistory,
    head_canonical_plain_save_guard_with_prefix_witness, reconstruct_rewrite_record,
    session_head_cas_token, strand_layout_for_history, validate_save_head_transition,
};
use meerkat_core::time_compat::SystemTime;
use meerkat_core::transcript_messages_digest;
use meerkat_core::types::Message;
use meerkat_core::{
    ComponentEventPrefixAuthority, PreparedComponentEventSuffix, Released0810ImportEvidence,
    SerializedComponentEvent, Session, SessionHeadMetadataCell, SessionHeadMetadataCellIdentity,
    SessionHeadMetadataIdentity, SessionHeadMetadataProjection, SessionHeadMetadataValueDigest,
    SessionId, SessionMeta, StoredComponentEventRow, TranscriptRevisionBody,
    TranscriptRevisionEdge, TranscriptRewriteCommit, TranscriptRewritePrefixAccumulator,
    TranscriptRewriteRecord, ValidatedTranscriptHistory, VerifiedComponentEventSequence,
};
use rusqlite::{Connection, OptionalExtension, Transaction, TransactionBehavior, params};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, UNIX_EPOCH};
use uuid::Uuid;

/// Per-store SQLite contention policy. The default tolerates the long WAL
/// writer holds produced by large durable snapshot commits while keeping the
/// wait bounded. Runtime/session stores may override it per instance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SqliteConnectionOptions {
    /// Maximum time SQLite's busy handler waits and retries a locked write.
    pub busy_timeout: Duration,
}

impl Default for SqliteConnectionOptions {
    fn default() -> Self {
        Self {
            busy_timeout: meerkat_sqlite::SHARED_BUSY_TIMEOUT,
        }
    }
}

const CREATE_SESSIONS_TABLE_SQL: &str = r"
CREATE TABLE IF NOT EXISTS sessions (
    session_id TEXT PRIMARY KEY,
    created_at_ms INTEGER NOT NULL,
    updated_at_ms INTEGER NOT NULL,
    message_count INTEGER NOT NULL,
    total_tokens INTEGER NOT NULL,
    metadata_json TEXT NOT NULL,
    session_json BLOB NOT NULL
)";

const CREATE_SESSIONS_UPDATED_INDEX_SQL: &str = r"
CREATE INDEX IF NOT EXISTS sessions_updated_idx
ON sessions(updated_at_ms DESC, session_id ASC)";

// Incremental session persistence (OB3 ask 11).
//
// Canonical-representation rule (per session): a `session_heads` row exists
// => the head representation is canonical and the blob row (if any) is a
// frozen migration archive, never read or written again; no head row => the
// legacy blob behavior stays byte-for-byte unchanged.
//
// Row-materialization rule (per session): a linked strand owns only its exact
// splice span plus any direct append tail beyond the link's immutable logical
// endpoint. Every other row resolves through the named successor. Current
// prepared rewrites therefore store the child delta over its parent; released
// 0.8.10 strands may retain the inverse parent-to-child supersession shape
// until their one-time verified activation. Both directions obey the same
// mechanical overlay invariant and avoid a fresh full transcript per rewrite
// (measured pre-fix: 98 rewrites of a 371-message transcript => 16,672 rows /
// 24 MB for one session).
const CREATE_SESSION_STRAND_MESSAGES_TABLE_SQL: &str = r"
CREATE TABLE IF NOT EXISTS session_strand_messages (
    session_id TEXT NOT NULL,
    strand TEXT NOT NULL,
    seq INTEGER NOT NULL,
    message_json BLOB NOT NULL,
    created_at_ms INTEGER NOT NULL,
    PRIMARY KEY (session_id, strand, seq)
)";

// Strand overlay edges: `strand` owns exactly `[splice_start, splice_end)` and
// resolves its shared prefix/suffix through `successor`. A strand with no link
// owns every logical row directly.
const CREATE_SESSION_STRAND_LINKS_TABLE_SQL: &str = r"
CREATE TABLE IF NOT EXISTS session_strand_links (
    session_id TEXT NOT NULL,
    strand TEXT NOT NULL,
    successor TEXT NOT NULL,
    strand_len INTEGER NOT NULL,
    splice_start INTEGER NOT NULL,
    splice_end INTEGER NOT NULL,
    successor_end INTEGER NOT NULL,
    created_at_ms INTEGER NOT NULL,
    PRIMARY KEY (session_id, strand)
)";

const CREATE_SESSION_REWRITES_TABLE_SQL: &str = r"
CREATE TABLE IF NOT EXISTS session_rewrites (
    session_id TEXT NOT NULL,
    rewrite_idx INTEGER NOT NULL,
    parent_strand TEXT NOT NULL,
    parent_len INTEGER NOT NULL,
    strand TEXT NOT NULL,
    strand_len INTEGER NOT NULL,
    commit_json BLOB NOT NULL,
    created_at_ms INTEGER NOT NULL,
    PRIMARY KEY (session_id, rewrite_idx)
)";

const CREATE_SESSION_HEADS_TABLE_SQL: &str = r"
CREATE TABLE IF NOT EXISTS session_heads (
    session_id TEXT PRIMARY KEY,
    version INTEGER NOT NULL,
    strand TEXT NOT NULL,
    head_revision TEXT NOT NULL,
    message_count INTEGER NOT NULL,
    rewrite_count INTEGER NOT NULL,
    total_tokens INTEGER NOT NULL,
    created_at_ms INTEGER NOT NULL,
    updated_at_ms INTEGER NOT NULL,
    metadata_json TEXT NOT NULL,
    head_json BLOB NOT NULL,
    cas_token TEXT NOT NULL
)";

const CREATE_SESSION_HEADS_UPDATED_INDEX_SQL: &str = r"
CREATE INDEX IF NOT EXISTS session_heads_updated_idx
ON session_heads(updated_at_ms DESC, session_id ASC)";

const ADD_SESSION_REWRITES_GRAPH_EDGE_COLUMN_SQL: &str =
    "ALTER TABLE session_rewrites ADD COLUMN graph_edge_json BLOB";

const CREATE_SESSION_COMPONENT_EVENTS_TABLE_SQL: &str = r"
CREATE TABLE session_component_events (
    session_id TEXT NOT NULL,
    component TEXT NOT NULL
        CHECK (component = 'realtime'),
    seq INTEGER NOT NULL CHECK (seq >= 0),
    event_json BLOB NOT NULL,
    event_digest TEXT NOT NULL,
    created_at_ms INTEGER NOT NULL,
    PRIMARY KEY (session_id, component, seq)
)";

// First published authenticated HeadCanonical sidecar shape (session schema
// migration v3). Released 0.8.10's v2 schema had neither the rewrite
// graph-edge column nor the component/metadata sidecar tables; no unreleased
// candidate shape is recognized or migrated here.
//
// Cells, states, deltas, and head lineage are immutable. `current` is the
// physical head's materialized key set; `refs` pins the exact physical and
// runtime metadata states. A ref's head token is the immutable token which
// created that state, not every later transcript-only head which reuses the
// same identity; that distinction is what makes an unchanged-metadata
// boundary a literal metadata-table no-write. The runtime validates every
// relationship inside the writing transaction. These tables deliberately
// carry no foreign keys: co-tenant migration and convergence pruning have
// different deletion orders, and neither may turn ordering into authority.
const CREATE_SESSION_HEAD_METADATA_CELLS_TABLE_SQL: &str = r"
CREATE TABLE session_head_metadata_cells (
    session_id TEXT NOT NULL,
    metadata_key TEXT NOT NULL,
    key_route BLOB NOT NULL CHECK (length(key_route) = 32),
    exact_value_digest TEXT NOT NULL,
    metadata_json BLOB NOT NULL,
    created_at_ms INTEGER NOT NULL,
    PRIMARY KEY (session_id, metadata_key, exact_value_digest)
)";

const CREATE_SESSION_HEAD_METADATA_CELLS_ROUTE_KEY_INDEX_SQL: &str = r"
CREATE INDEX session_head_metadata_cells_route_key_idx
ON session_head_metadata_cells(session_id, key_route, metadata_key)";

const CREATE_SESSION_HEAD_METADATA_CURRENT_TABLE_SQL: &str = r"
CREATE TABLE session_head_metadata_current (
    session_id TEXT NOT NULL,
    metadata_key TEXT NOT NULL,
    key_route BLOB NOT NULL CHECK (length(key_route) = 32),
    exact_value_digest TEXT NOT NULL,
    PRIMARY KEY (session_id, metadata_key)
)";

const CREATE_SESSION_HEAD_METADATA_STATES_TABLE_SQL: &str = r"
CREATE TABLE session_head_metadata_states (
    session_id TEXT NOT NULL,
    state_id TEXT NOT NULL,
    predecessor_state_id TEXT,
    identity_json BLOB NOT NULL,
    transition_id TEXT NOT NULL,
    created_at_ms INTEGER NOT NULL,
    PRIMARY KEY (session_id, state_id),
    UNIQUE (session_id, transition_id)
)";

const CREATE_SESSION_HEAD_METADATA_STATES_PREDECESSOR_INDEX_SQL: &str = r"
CREATE INDEX session_head_metadata_states_predecessor_idx
ON session_head_metadata_states(session_id, predecessor_state_id)";

const CREATE_SESSION_HEAD_METADATA_STATE_DELTAS_TABLE_SQL: &str = r"
CREATE TABLE session_head_metadata_state_deltas (
    session_id TEXT NOT NULL,
    state_id TEXT NOT NULL,
    ordinal INTEGER NOT NULL CHECK (ordinal >= 0),
    metadata_key TEXT NOT NULL,
    key_route BLOB NOT NULL CHECK (length(key_route) = 32),
    predecessor_exact_value_digest TEXT,
    successor_exact_value_digest TEXT,
    PRIMARY KEY (session_id, state_id, ordinal),
    UNIQUE (session_id, state_id, metadata_key)
)";

const CREATE_SESSION_HEAD_METADATA_STATE_DELTAS_KEY_INDEX_SQL: &str = r"
CREATE INDEX session_head_metadata_state_deltas_key_idx
ON session_head_metadata_state_deltas(session_id, metadata_key, state_id)";

const CREATE_SESSION_HEAD_METADATA_REFS_TABLE_SQL: &str = r"
CREATE TABLE session_head_metadata_refs (
    session_id TEXT NOT NULL,
    owner TEXT NOT NULL
        CHECK (owner IN ('physical_head', 'runtime_boundary')),
    head_cas_token TEXT NOT NULL,
    state_id TEXT NOT NULL,
    PRIMARY KEY (session_id, owner)
)";

const CREATE_SESSION_HEAD_METADATA_HEAD_LINEAGE_TABLE_SQL: &str = r"
CREATE TABLE session_head_metadata_head_lineage (
    session_id TEXT NOT NULL,
    transition_id TEXT NOT NULL,
    predecessor_head_cas_token TEXT,
    successor_head_cas_token TEXT NOT NULL,
    predecessor_state_id TEXT,
    successor_state_id TEXT NOT NULL,
    created_at_ms INTEGER NOT NULL,
    PRIMARY KEY (session_id, transition_id),
    UNIQUE (session_id, successor_head_cas_token)
)";

const CREATE_SESSION_HEAD_METADATA_HEAD_LINEAGE_PREDECESSOR_INDEX_SQL: &str = r"
CREATE INDEX session_head_metadata_head_lineage_predecessor_idx
ON session_head_metadata_head_lineage(session_id, predecessor_head_cas_token)";

const CREATE_SESSION_HEAD_METADATA_HEAD_LINEAGE_SUCCESSOR_INDEX_SQL: &str = r"
CREATE INDEX session_head_metadata_head_lineage_successor_idx
ON session_head_metadata_head_lineage(session_id, successor_head_cas_token)";

fn system_time_millis(time: SystemTime) -> i64 {
    match time.duration_since(UNIX_EPOCH) {
        Ok(duration) => i64::try_from(duration.as_millis()).unwrap_or(i64::MAX),
        Err(_) => 0,
    }
}

fn millis_to_system_time(value: i64) -> SystemTime {
    let millis = u64::try_from(value).unwrap_or_default();
    UNIX_EPOCH + Duration::from_millis(millis)
}

fn parse_session_id(raw: String) -> Result<SessionId, StoreError> {
    let uuid = Uuid::parse_str(&raw)
        .map_err(|err| StoreError::Internal(format!("invalid session_id '{raw}': {err}")))?;
    Ok(SessionId(uuid))
}

/// Open a session-store connection under the shared Primary profile (WAL,
/// `synchronous=FULL`, the shared busy timeout).
///
/// DDL-free since the storage unification: opening a connection no longer
/// plants the session tables, so co-tenant stores (schedule, runtime) stop
/// materializing empty session tables in their files — they open through
/// their own domain-preflighted openers. Callers apply the
/// [`SESSION_STORE_DOMAIN`] schema domain after opening; the same domain is
/// preflighted at open so an ineligible file is refused before the profile's
/// WAL conversion touches it.
pub fn open_connection(path: &Path) -> Result<Connection, StoreError> {
    open_connection_with_options(path, SqliteConnectionOptions::default())
}

/// [`open_connection`] with a per-store contention policy override.
pub fn open_connection_with_options(
    path: &Path,
    options: SqliteConnectionOptions,
) -> Result<Connection, StoreError> {
    meerkat_sqlite::open_with(
        path,
        meerkat_sqlite::ConnectionProfile::PRIMARY,
        meerkat_sqlite::OpenOptions {
            busy_timeout: Some(options.busy_timeout),
            // Schema-eligibility refusal must fire before the Primary
            // profile's journal-mode conversion mutates the file.
            schema_preflight: &[&SESSION_STORE_DOMAIN],
        },
    )
    .map_err(StoreError::from)
}

fn migration_0001_session_schema(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    tx.execute_batch(CREATE_SESSIONS_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSIONS_UPDATED_INDEX_SQL)?;
    tx.execute_batch(CREATE_SESSION_STRAND_MESSAGES_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_REWRITES_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEADS_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEADS_UPDATED_INDEX_SQL)?;
    Ok(())
}

fn migration_0002_strand_links(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    tx.execute_batch(CREATE_SESSION_STRAND_LINKS_TABLE_SQL)
}

fn migration_0003_authenticated_head_sidecars(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    tx.execute_batch(ADD_SESSION_REWRITES_GRAPH_EDGE_COLUMN_SQL)?;
    tx.execute_batch(CREATE_SESSION_COMPONENT_EVENTS_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_CELLS_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_CELLS_ROUTE_KEY_INDEX_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_CURRENT_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_STATES_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_STATES_PREDECESSOR_INDEX_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_STATE_DELTAS_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_STATE_DELTAS_KEY_INDEX_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_REFS_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_HEAD_LINEAGE_TABLE_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_HEAD_LINEAGE_PREDECESSOR_INDEX_SQL)?;
    tx.execute_batch(CREATE_SESSION_HEAD_METADATA_HEAD_LINEAGE_SUCCESSOR_INDEX_SQL)?;
    migrate_released_blob_envelopes(tx)?;
    migrate_released_head_envelopes(tx)
}

/// Complete the supported HeadCanonical v1-to-v2 crossing.
///
/// Session schema v3 installed the authenticated sidecar tables and converted
/// the exact released 0.8.10 row shape, but deliberately left migrated heads
/// in the inline, pre-component representation for RuntimeStore activation.
/// A v3 database could therefore expose a persisted HeadCanonical head which
/// `PreparedHeadCanonicalMutation` correctly refused, while the only
/// conversion entry point was the co-tenant runtime transaction. Advancing the
/// session domain to v4 makes that representation door explicit and usable by
/// every SQLite session-store composition.
///
/// The existing conversion helper is the authority here. For every supported
/// current-version head it verifies the stored CAS token, resolves and commits
/// the exact serialized row prefix, validates/backfills the compact rewrite
/// graph, then installs the component and metadata authorities before replacing
/// the head. Rows outside the supported current envelope are not candidates for
/// this crossing. All conversion work happens inside this migration transaction,
/// so a failed proof leaves both the source head and schema version unchanged.
fn migration_0004_head_canonical_v2_authority(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    let session_ids = {
        let mut statement = tx.prepare(
            "SELECT session_id
             FROM session_heads
             WHERE version = ?1
             ORDER BY session_id",
        )?;
        statement
            .query_map(params![i64::from(meerkat_core::SESSION_VERSION)], |row| {
                row.get::<_, String>(0)
            })?
            .collect::<Result<Vec<_>, _>>()?
    };

    for raw_id in session_ids {
        let id = parse_session_id(raw_id.clone()).map_err(|error| {
            rusqlite::Error::ToSqlConversionFailure(Box::new(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "head-canonical v1-to-v2 conversion found invalid session identity '{raw_id}': {error}"
                ),
            )))
        })?;
        let crossing = cross_head_canonical_authority_in_txn(tx, &id).map_err(|error| {
            rusqlite::Error::ToSqlConversionFailure(Box::new(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("head-canonical v1-to-v2 conversion failed for session '{id}': {error}"),
            )))
        })?;
        let authority = crossing.authority().ok_or_else(|| {
            rusqlite::Error::ToSqlConversionFailure(Box::new(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "head-canonical v1-to-v2 conversion lost session '{id}' while its head row was present"
                ),
            )))
        })?;
        if authority.head().id != id {
            return Err(rusqlite::Error::ToSqlConversionFailure(Box::new(
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "head-canonical v1-to-v2 conversion did not publish complete authority for session '{id}'"
                    ),
                ),
            )));
        }
    }
    Ok(())
}

fn invalid_released_head_envelope(
    session_id: &str,
    detail: impl std::fmt::Display,
) -> rusqlite::Error {
    rusqlite::Error::ToSqlConversionFailure(Box::new(std::io::Error::new(
        std::io::ErrorKind::InvalidData,
        format!("released 0.8.10 session head '{session_id}' is invalid: {detail}"),
    )))
}

fn released_session_document_from_head(
    session_id: &str,
    head_value: &serde_json::Value,
    serialized_rows: &[Vec<u8>],
    released_history: Option<&[u8]>,
) -> Result<Vec<u8>, rusqlite::Error> {
    let head = head_value
        .as_object()
        .ok_or_else(|| invalid_released_head_envelope(session_id, "head JSON is not an object"))?;
    let required = |key: &'static str| {
        head.get(key).ok_or_else(|| {
            invalid_released_head_envelope(
                session_id,
                format!("head JSON has no required '{key}' field"),
            )
        })
    };
    let version = required("version")?;
    let id = required("id")?;
    let created_at = required("created_at")?;
    let updated_at = required("updated_at")?;
    let metadata = required("metadata")?.as_object().ok_or_else(|| {
        invalid_released_head_envelope(session_id, "head metadata is not an object")
    })?;
    if released_history.is_some()
        && metadata.contains_key(meerkat_core::SESSION_TRANSCRIPT_HISTORY_STATE_KEY)
    {
        return Err(invalid_released_head_envelope(
            session_id,
            "released head unexpectedly carries inline transcript history",
        ));
    }
    let usage = required("usage")?;

    let mut document = Vec::new();
    document.extend_from_slice(br#"{"version":"#);
    serde_json::to_writer(&mut document, version)
        .map_err(|error| invalid_released_head_envelope(session_id, error))?;
    document.extend_from_slice(br#","id":"#);
    serde_json::to_writer(&mut document, id)
        .map_err(|error| invalid_released_head_envelope(session_id, error))?;
    document.extend_from_slice(br#","messages":["#);
    for (index, row) in serialized_rows.iter().enumerate() {
        if index > 0 {
            document.push(b',');
        }
        let mut deserializer = serde_json::Deserializer::from_slice(row);
        serde::de::IgnoredAny::deserialize(&mut deserializer)
            .map_err(|error| invalid_released_head_envelope(session_id, error))?;
        deserializer
            .end()
            .map_err(|error| invalid_released_head_envelope(session_id, error))?;
        document.extend_from_slice(row);
    }
    document.extend_from_slice(br#"],"created_at":"#);
    serde_json::to_writer(&mut document, created_at)
        .map_err(|error| invalid_released_head_envelope(session_id, error))?;
    document.extend_from_slice(br#","updated_at":"#);
    serde_json::to_writer(&mut document, updated_at)
        .map_err(|error| invalid_released_head_envelope(session_id, error))?;
    document.extend_from_slice(br#","metadata":"#);
    document.push(b'{');
    let mut wrote_metadata = false;
    for (key, value) in metadata {
        if wrote_metadata {
            document.push(b',');
        }
        serde_json::to_writer(&mut document, key)
            .map_err(|error| invalid_released_head_envelope(session_id, error))?;
        document.push(b':');
        serde_json::to_writer(&mut document, value)
            .map_err(|error| invalid_released_head_envelope(session_id, error))?;
        wrote_metadata = true;
    }
    if let Some(history) = released_history {
        if wrote_metadata {
            document.push(b',');
        }
        serde_json::to_writer(
            &mut document,
            meerkat_core::SESSION_TRANSCRIPT_HISTORY_STATE_KEY,
        )
        .map_err(|error| invalid_released_head_envelope(session_id, error))?;
        document.push(b':');
        document.extend_from_slice(history);
    }
    document.push(b'}');
    document.extend_from_slice(br#","usage":"#);
    serde_json::to_writer(&mut document, usage)
        .map_err(|error| invalid_released_head_envelope(session_id, error))?;
    document.push(b'}');
    Ok(document)
}

#[derive(Serialize)]
struct Released0810RevisionWire {
    revision: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    parent_revision: Option<String>,
    messages: Vec<Box<serde_json::value::RawValue>>,
    created_at: SystemTime,
}

#[derive(Serialize)]
struct Released0810HistoryWire {
    head: String,
    commits: Vec<serde_json::Value>,
    revisions: Vec<Released0810RevisionWire>,
    digest_format: u32,
}

fn verify_released_0810_rows_digest(
    session_id: &str,
    rows: &[Vec<u8>],
    expected: &str,
    label: &str,
) -> Result<(), rusqlite::Error> {
    let actual = meerkat_core::released_0810_transcript_serialized_rows_digest(rows)
        .map_err(|error| invalid_released_head_envelope(session_id, error))?;
    if actual != expected {
        return Err(invalid_released_head_envelope(
            session_id,
            format!("{label} digest mismatch: expected {expected}, actual {actual}"),
        ));
    }
    Ok(())
}

fn verify_released_0810_rewrite_row_digests(
    session_id: &str,
    row: &RewriteRow,
    parent_rows: &[Vec<u8>],
    child_rows: &[Vec<u8>],
) -> Result<(), rusqlite::Error> {
    if parent_rows.len() != row.commit.messages_before
        || child_rows.len() != row.commit.messages_after
    {
        return Err(invalid_released_head_envelope(
            session_id,
            "released rewrite physical bodies do not match the commit message counts",
        ));
    }
    verify_released_0810_rows_digest(
        session_id,
        parent_rows,
        &row.commit.parent_revision,
        "rewrite parent endpoint",
    )?;
    verify_released_0810_rows_digest(
        session_id,
        child_rows,
        &row.commit.revision,
        "rewrite child endpoint",
    )?;

    let (start, end) = row.commit.selection.bounds();
    let removed = end.checked_sub(start).ok_or_else(|| {
        invalid_released_head_envelope(session_id, "released rewrite selection is inverted")
    })?;
    if end > parent_rows.len() {
        return Err(invalid_released_head_envelope(
            session_id,
            "released rewrite selection exceeds its parent body",
        ));
    }
    let retained = row
        .commit
        .messages_before
        .checked_sub(removed)
        .ok_or_else(|| {
            invalid_released_head_envelope(
                session_id,
                "released rewrite removes more rows than its parent contains",
            )
        })?;
    let replacement_len = row
        .commit
        .messages_after
        .checked_sub(retained)
        .ok_or_else(|| {
            invalid_released_head_envelope(
                session_id,
                "released rewrite replacement length is invalid",
            )
        })?;
    let replacement_end = start.checked_add(replacement_len).ok_or_else(|| {
        invalid_released_head_envelope(session_id, "released rewrite replacement span overflows")
    })?;
    if replacement_end > child_rows.len() {
        return Err(invalid_released_head_envelope(
            session_id,
            "released rewrite replacement span exceeds its child body",
        ));
    }
    verify_released_0810_rows_digest(
        session_id,
        &parent_rows[start..end],
        &row.commit.original_span_digest,
        "rewrite original span",
    )?;
    verify_released_0810_rows_digest(
        session_id,
        &child_rows[start..replacement_end],
        &row.commit.replacement_digest,
        "rewrite replacement span",
    )
}

fn released_history_from_rewrite_rows(
    tx: &Transaction<'_>,
    head: &SessionHead,
    links: &StrandLinks,
) -> Result<Option<Vec<u8>>, rusqlite::Error> {
    if head.rewrite_count == 0 {
        return Ok(None);
    }
    let session_id = head.id.to_string();
    let indexed = indexed_rewrite_rows_range_in_txn(tx, &head.id, 0, head.rewrite_count)
        .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
    if u64::try_from(indexed.len()).ok() != Some(head.rewrite_count) {
        return Err(invalid_released_head_envelope(
            &session_id,
            "released rewrite table does not cover the advertised generation",
        ));
    }

    let mut child_parents = BTreeMap::new();
    for (index, row) in &indexed {
        if row.graph_edge_json.is_some() {
            return Err(invalid_released_head_envelope(
                &session_id,
                "released rewrite row already carries a current graph edge",
            ));
        }
        if child_parents
            .insert(
                row.commit.revision.clone(),
                row.commit.parent_revision.clone(),
            )
            .is_some_and(|existing| existing != row.commit.parent_revision)
        {
            return Err(invalid_released_head_envelope(
                &session_id,
                format!("rewrite occurrence {index} gives one revision two parents"),
            ));
        }
    }

    let mut revisions = Vec::new();
    let mut revision_bodies: BTreeMap<String, Vec<Vec<u8>>> = BTreeMap::new();
    let mut commits = Vec::with_capacity(indexed.len());
    for (expected_index, (index, row)) in indexed.iter().enumerate() {
        if *index
            != u64::try_from(expected_index)
                .map_err(|error| invalid_released_head_envelope(&session_id, error))?
        {
            return Err(invalid_released_head_envelope(
                &session_id,
                "released rewrite occurrences are not contiguous",
            ));
        }
        let parent_rows =
            resolve_strand_bytes_in_txn(tx, &head.id, &row.parent_strand, 0..row.parent_len, links)
                .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let child_rows =
            resolve_strand_bytes_in_txn(tx, &head.id, &row.strand, 0..row.strand_len, links)
                .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        verify_released_0810_rewrite_row_digests(&session_id, row, &parent_rows, &child_rows)?;

        for (revision, rows) in [
            (&row.commit.parent_revision, parent_rows),
            (&row.commit.revision, child_rows),
        ] {
            if let Some(existing) = revision_bodies.get(revision) {
                if existing != &rows {
                    return Err(invalid_released_head_envelope(
                        &session_id,
                        format!("released revision {revision} resolves to contradictory bodies"),
                    ));
                }
                continue;
            }
            let messages = rows
                .iter()
                .map(|row| {
                    serde_json::from_slice::<Box<serde_json::value::RawValue>>(row)
                        .map_err(|error| invalid_released_head_envelope(&session_id, error))
                })
                .collect::<Result<Vec<_>, _>>()?;
            revisions.push(Released0810RevisionWire {
                revision: revision.clone(),
                parent_revision: child_parents.get(revision).cloned(),
                messages,
                created_at: SystemTime::UNIX_EPOCH,
            });
            revision_bodies.insert(revision.clone(), rows);
        }

        let mut commit = serde_json::to_value(&row.commit)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        commit
            .as_object_mut()
            .ok_or_else(|| {
                invalid_released_head_envelope(&session_id, "rewrite commit is not an object")
            })?
            .remove("rewrite_generation");
        commits.push(commit);
    }
    let released_head = indexed
        .last()
        .map(|(_, row)| row.commit.revision.clone())
        .ok_or_else(|| {
            invalid_released_head_envelope(&session_id, "released rewrite history is empty")
        })?;
    serde_json::to_vec(&Released0810HistoryWire {
        head: released_head,
        commits,
        revisions,
        digest_format: 2,
    })
    .map(Some)
    .map_err(|error| invalid_released_head_envelope(&session_id, error))
}

fn validate_released_pending_rewrite_tail(
    tx: &Transaction<'_>,
    head: &SessionHead,
    links: &StrandLinks,
) -> Result<bool, rusqlite::Error> {
    let session_id = head.id.to_string();
    let recorded = rewrite_row_count_in_txn(tx, &head.id)
        .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
    if recorded == head.rewrite_count {
        return Ok(false);
    }
    let pending_end = head.rewrite_count.checked_add(1).ok_or_else(|| {
        invalid_released_head_envelope(&session_id, "released rewrite count overflowed")
    })?;
    if recorded != pending_end {
        return Err(invalid_released_head_envelope(
            &session_id,
            format!(
                "released rewrite table contains {recorded} rows for head generation {}",
                head.rewrite_count
            ),
        ));
    }
    let pending = indexed_rewrite_rows_range_in_txn(tx, &head.id, head.rewrite_count, pending_end)
        .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
    let [(rewrite_idx, row)] = pending.as_slice() else {
        return Err(invalid_released_head_envelope(
            &session_id,
            "released pending rewrite row is missing or duplicated",
        ));
    };
    if *rewrite_idx != head.rewrite_count
        || row.commit.rewrite_generation != 0
        || row.graph_edge_json.is_some()
        || row.commit.parent_revision != head.head_revision
        || row.parent_strand != head.strand
        || row.parent_len
            != u64::try_from(row.commit.messages_before)
                .map_err(|error| invalid_released_head_envelope(&session_id, error))?
        || row.strand != TranscriptStrandId::from_rewrite(&row.commit)
        || row.strand_len
            != u64::try_from(row.commit.messages_after)
                .map_err(|error| invalid_released_head_envelope(&session_id, error))?
    {
        return Err(invalid_released_head_envelope(
            &session_id,
            "released pending rewrite row is not the exact unadopted successor of the head",
        ));
    }
    let parent_rows =
        resolve_strand_bytes_in_txn(tx, &head.id, &row.parent_strand, 0..row.parent_len, links)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
    let child_rows =
        resolve_strand_bytes_in_txn(tx, &head.id, &row.strand, 0..row.strand_len, links)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
    verify_released_0810_rewrite_row_digests(&session_id, row, &parent_rows, &child_rows)?;
    let decode = |rows: &[Vec<u8>]| {
        rows.iter()
            .map(|bytes| {
                serde_json::from_slice::<Message>(bytes)
                    .map_err(|error| invalid_released_head_envelope(&session_id, error))
            })
            .collect::<Result<Vec<_>, _>>()
    };
    let parent = TranscriptRevisionBody {
        revision: row.commit.parent_revision.clone(),
        parent_revision: None,
        messages: decode(&parent_rows)?,
        created_at: SystemTime::UNIX_EPOCH,
    };
    let child = TranscriptRevisionBody {
        revision: row.commit.revision.clone(),
        parent_revision: Some(row.commit.parent_revision.clone()),
        messages: decode(&child_rows)?,
        created_at: SystemTime::UNIX_EPOCH,
    };
    meerkat_core::session::remap_proven_released_0810_rewrite_record(
        row.commit.clone(),
        parent,
        child,
        1,
    )
    .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
    Ok(true)
}

fn migrate_released_blob_envelopes(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    let released_blobs = {
        let mut statement = tx.prepare(
            "SELECT blob.session_id, blob.session_json
             FROM sessions AS blob
             WHERE NOT EXISTS (
                 SELECT 1 FROM session_heads AS head
                 WHERE head.session_id = blob.session_id
             )
             ORDER BY blob.session_id",
        )?;
        statement
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                ))
            })?
            .collect::<Result<Vec<_>, _>>()?
    };

    for (session_id, source_document) in released_blobs {
        let value: serde_json::Value = serde_json::from_slice(&source_document)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let version = value.get("version").and_then(serde_json::Value::as_u64);
        if version != Some(2) {
            return Err(invalid_released_head_envelope(
                &session_id,
                format!(
                    "blob-only row has unsupported envelope version {}",
                    version.map_or_else(
                        || "missing or non-integer".to_string(),
                        |version| version.to_string()
                    )
                ),
            ));
        }
        let source_sha256: [u8; 32] = Sha256::digest(&source_document).into();
        let imported = meerkat_core::import_released_0810_session(&source_document)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let (session, receipt) = imported.into_parts();
        if session.id().to_string() != session_id
            || receipt.session_id() != session.id()
            || receipt.source_document_sha256() != &source_sha256
            || receipt.evidence() != Released0810ImportEvidence::StoreAuthorizationRequired
        {
            return Err(invalid_released_head_envelope(
                &session_id,
                "frozen importer receipt does not bind the exact blob-only source",
            ));
        }
        write_session_snapshot_in_txn(tx, &session)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
    }
    Ok(())
}

fn migrate_released_head_envelopes(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    let released_heads = {
        let mut statement = tx.prepare(
            "SELECT session_id, head_json, cas_token
             FROM session_heads
             WHERE version = ?1
             ORDER BY session_id",
        )?;
        statement
            .query_map(params![2_i64], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                    row.get::<_, String>(2)?,
                ))
            })?
            .collect::<Result<Vec<_>, _>>()?
    };

    for (session_id, head_json, stored_token) in released_heads {
        let head_value: serde_json::Value = serde_json::from_slice(&head_json)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let embedded_version = head_value
            .get("version")
            .and_then(serde_json::Value::as_u64);
        if embedded_version != Some(2) {
            return Err(invalid_released_head_envelope(
                &session_id,
                format!(
                    "row version is 2 but embedded head version is {}",
                    embedded_version.map_or_else(
                        || "missing or non-integer".to_string(),
                        |version| { version.to_string() }
                    )
                ),
            ));
        }
        let head: SessionHead = serde_json::from_value(head_value.clone())
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        if head.id.to_string() != session_id {
            return Err(invalid_released_head_envelope(
                &session_id,
                format!("embedded head identity is '{}'", head.id),
            ));
        }
        let released_token = format!("head-sha256:{:x}", Sha256::digest(&head_json));
        if released_token != stored_token {
            return Err(invalid_released_head_envelope(
                &session_id,
                "stored CAS token does not bind the exact released head",
            ));
        }

        let links = strand_links_in_txn(tx, &head.id)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        validate_strand_links_acyclic(&head.id, &links)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        validate_released_pending_rewrite_tail(tx, &head, &links)?;
        let serialized_rows =
            resolve_strand_bytes_in_txn(tx, &head.id, &head.strand, 0..head.message_count, &links)
                .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let released_message_count = u64::try_from(serialized_rows.len())
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        // This one-time O(document) boundary replays the frozen 0.8.10 digest
        // framing directly from exact physical row bytes. In particular it
        // retains producer spelling inside released RawValue slots, which a
        // current Message decode would irreversibly normalize. Live current
        // persistence never enters this verifier; the same transaction below
        // rebuilds the topology and mints current row/head authority.
        if released_message_count != head.message_count {
            return Err(invalid_released_head_envelope(
                &session_id,
                format!(
                    "resolved transcript does not cover the released head projection \
                     (count {released_message_count}/{})",
                    head.message_count
                ),
            ));
        }
        verify_released_0810_rows_digest(
            &session_id,
            &serialized_rows,
            &head.head_revision,
            "live head",
        )?;
        let released_history = released_history_from_rewrite_rows(tx, &head, &links)?;
        let source_document = released_session_document_from_head(
            &session_id,
            &head_value,
            &serialized_rows,
            released_history.as_deref(),
        )?;
        let source_sha256: [u8; 32] = Sha256::digest(&source_document).into();
        let imported = meerkat_core::import_released_0810_session(&source_document)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let (session, receipt) = imported.into_parts();
        if receipt.session_id() != &head.id
            || receipt.source_document_sha256() != &source_sha256
            || receipt.evidence() != Released0810ImportEvidence::StoreAuthorizationRequired
        {
            return Err(invalid_released_head_envelope(
                &session_id,
                "frozen importer receipt does not bind the exact released source",
            ));
        }

        let released_count = usize::try_from(head.message_count)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let released_messages = serialized_rows
            .iter()
            .map(|row| {
                serde_json::from_slice::<Message>(row)
                    .map_err(|error| invalid_released_head_envelope(&session_id, error))
            })
            .collect::<Result<Vec<_>, _>>()?;
        if session.id() != &head.id
            || session.messages().len() < released_count
            || session.messages()[..released_count] != released_messages
        {
            return Err(invalid_released_head_envelope(
                &session_id,
                "frozen importer changed the released live transcript prefix",
            ));
        }
        for sql in [
            "DELETE FROM session_rewrites WHERE session_id = ?1",
            "DELETE FROM session_strand_links WHERE session_id = ?1",
            "DELETE FROM session_strand_messages WHERE session_id = ?1",
        ] {
            tx.execute(sql, params![head.id.to_string()])?;
        }
        let (layout, current_head) = layout_for_blob_session(&session)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        persist_blob_strand_layout_in_txn(tx, &head.id, &layout)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let current_links = strand_links_in_txn(tx, &head.id)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        validate_strand_links_acyclic(&head.id, &current_links)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let settled = settle_resolved_strand_direct_in_txn(
            tx,
            &head.id,
            &current_head.strand,
            current_head.message_count,
            &current_links,
        )
        .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
        let expected_rows = session
            .messages()
            .iter()
            .map(|message| {
                serde_json::to_vec(message)
                    .map_err(|error| invalid_released_head_envelope(&session_id, error))
            })
            .collect::<Result<Vec<_>, _>>()?;
        if current_head.id != head.id || settled != expected_rows {
            return Err(invalid_released_head_envelope(
                &session_id,
                "canonical rebuild changed the imported session or its current rows",
            ));
        }
        write_head_row_only_in_txn(tx, &current_head)
            .map_err(|error| invalid_released_head_envelope(&session_id, error))?;
    }
    Ok(())
}

fn initialize_current_session_schema(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    migration_0001_session_schema(tx)?;
    migration_0002_strand_links(tx)?;
    migration_0003_authenticated_head_sidecars(tx)?;
    migration_0004_head_canonical_v2_authority(tx)
}

fn build_released_0_8_10_session_schema(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    migration_0001_session_schema(tx)?;
    migration_0002_strand_links(tx)
}

/// Frozen physical DDL of the pre-ledger session store: the plain-CREATE
/// text that released binaries executed before the schema ledger existed.
/// Kept verbatim as the frozen source oracle; never used for new schema.
const RELEASED_PRE_FLOOR_SESSIONS_TABLE_SQL: &str = "CREATE TABLE sessions (
    session_id TEXT PRIMARY KEY,
    created_at_ms INTEGER NOT NULL,
    updated_at_ms INTEGER NOT NULL,
    message_count INTEGER NOT NULL,
    total_tokens INTEGER NOT NULL,
    metadata_json TEXT NOT NULL,
    session_json BLOB NOT NULL
)";

const RELEASED_PRE_FLOOR_SESSIONS_UPDATED_INDEX_SQL: &str = "CREATE INDEX sessions_updated_idx
ON sessions(updated_at_ms DESC, session_id ASC)";

fn build_released_pre_floor_session_schema(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    tx.execute_batch(RELEASED_PRE_FLOOR_SESSIONS_TABLE_SQL)?;
    tx.execute_batch(RELEASED_PRE_FLOOR_SESSIONS_UPDATED_INDEX_SQL)
}

fn build_released_v3_session_schema(tx: &Transaction<'_>) -> Result<(), rusqlite::Error> {
    migration_0001_session_schema(tx)?;
    migration_0002_strand_links(tx)?;
    migration_0003_authenticated_head_sidecars(tx)
}

const RELEASED_0_8_10_SESSION_OBJECTS: &[meerkat_sqlite::SchemaObject] = &[
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "sessions",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_strand_messages",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_strand_links",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_rewrites",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_heads",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "sessions_updated_idx",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "session_heads_updated_idx",
    },
];

const RELEASED_V3_SESSION_OBJECTS: &[meerkat_sqlite::SchemaObject] = &[
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "sessions",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "sessions_updated_idx",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_strand_messages",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_strand_links",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_rewrites",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_heads",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "session_heads_updated_idx",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_component_events",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_head_metadata_cells",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "session_head_metadata_cells_route_key_idx",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_head_metadata_current",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_head_metadata_states",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "session_head_metadata_states_predecessor_idx",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_head_metadata_state_deltas",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "session_head_metadata_state_deltas_key_idx",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_head_metadata_refs",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "session_head_metadata_head_lineage",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "session_head_metadata_head_lineage_predecessor_idx",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "session_head_metadata_head_lineage_successor_idx",
    },
];

const RELEASED_PRE_FLOOR_SESSION_OBJECTS: &[meerkat_sqlite::SchemaObject] = &[
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Table,
        name: "sessions",
    },
    meerkat_sqlite::SchemaObject {
        kind: meerkat_sqlite::SchemaObjectKind::Index,
        name: "sessions_updated_idx",
    },
];

/// Frozen source verifier for schema version 1: the pre-ledger catalog
/// (blob-only `sessions` table plus its update index, nothing else).
///
/// Pre-ledger binaries re-issued this DDL idempotently across releases, so
/// the stored CREATE text is not release-stable evidence. The physical
/// shape is verified exactly instead: column names, declared types,
/// constraints, primary-key positions, and the full index shape.
fn verify_released_pre_floor_session_schema(conn: &Connection) -> Result<(), String> {
    meerkat_sqlite::verify_released_schema_structure(
        conn,
        &SESSION_STORE_DOMAIN,
        RELEASED_PRE_FLOOR_SESSION_OBJECTS,
        build_released_pre_floor_session_schema,
    )
}

/// Maintenance-prepare callback for the explicit pre-0.8.10 session bridge.
///
/// When the transaction's catalog is exactly the released pre-ledger
/// plain-CREATE shape ([`verify_released_pre_floor_session_schema`]), the two
/// legacy objects are rebuilt from the current migration-1 constants (the
/// post-migration convergence fingerprint compares the stored CREATE text)
/// and the remaining migration-1 objects are planted, so migrations
/// 2..=target run over a physical catalog identical to migration 1's output.
/// Every other catalog - a ledgered predecessor, the exact migration-1
/// shape, or the current schema - is left untouched.
pub fn prepare_pre_0_8_10_session_base_schema(
    tx: &Transaction<'_>,
) -> Result<meerkat_sqlite::MaintenancePrepareReport, rusqlite::Error> {
    if verify_released_pre_floor_session_schema(tx).is_err() {
        return Ok(meerkat_sqlite::MaintenancePrepareReport::default());
    }
    tx.execute_batch(
        "DROP INDEX sessions_updated_idx;
         ALTER TABLE sessions RENAME TO pre_floor_sessions_import;",
    )?;
    migration_0001_session_schema(tx)?;
    let changed = tx.execute(
        "INSERT INTO sessions (session_id, created_at_ms, updated_at_ms, message_count,
             total_tokens, metadata_json, session_json)
         SELECT session_id, created_at_ms, updated_at_ms, message_count,
             total_tokens, metadata_json, session_json
         FROM pre_floor_sessions_import",
        [],
    )?;
    tx.execute_batch("DROP TABLE pre_floor_sessions_import")?;
    Ok(meerkat_sqlite::MaintenancePrepareReport::rewrote(changed))
}

fn verify_released_0_8_10_session_schema(conn: &Connection) -> Result<(), String> {
    meerkat_sqlite::verify_released_schema_fingerprint(
        conn,
        &SESSION_STORE_DOMAIN,
        RELEASED_0_8_10_SESSION_OBJECTS,
        build_released_0_8_10_session_schema,
    )
}

fn verify_released_v3_session_schema(conn: &Connection) -> Result<(), String> {
    meerkat_sqlite::verify_released_schema_fingerprint(
        conn,
        &SESSION_STORE_DOMAIN,
        RELEASED_V3_SESSION_OBJECTS,
        build_released_v3_session_schema,
    )
}

/// The session store's schema domain in the per-file migration ledger.
pub const SESSION_STORE_DOMAIN: meerkat_sqlite::SchemaDomain = meerkat_sqlite::SchemaDomain {
    name: "session-store",
    migrations: &[
        meerkat_sqlite::Migration {
            version: 1,
            name: "base-schema",
            apply: migration_0001_session_schema,
        },
        meerkat_sqlite::Migration {
            version: 2,
            name: "strand-supersession-links",
            apply: migration_0002_strand_links,
        },
        meerkat_sqlite::Migration {
            version: 3,
            name: "authenticated-head-sidecars",
            apply: migration_0003_authenticated_head_sidecars,
        },
        meerkat_sqlite::Migration {
            version: 4,
            name: "head-canonical-v2-authority",
            apply: migration_0004_head_canonical_v2_authority,
        },
    ],
    initialize_current: initialize_current_session_schema,
    allowed_existing_versions: &[1, 2, 3, 4],
    bridge_recoverable_versions: &[1],
    released_predecessors: &[
        meerkat_sqlite::SchemaPredecessor {
            version: 1,
            verify: verify_released_pre_floor_session_schema,
        },
        meerkat_sqlite::SchemaPredecessor {
            version: 2,
            verify: verify_released_0_8_10_session_schema,
        },
        meerkat_sqlite::SchemaPredecessor {
            version: 3,
            verify: verify_released_v3_session_schema,
        },
    ],
    owned_objects: &[
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "sessions",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Index,
            name: "sessions_updated_idx",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_strand_messages",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_strand_links",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_rewrites",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_heads",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Index,
            name: "session_heads_updated_idx",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_component_events",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_head_metadata_cells",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Index,
            name: "session_head_metadata_cells_route_key_idx",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_head_metadata_current",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_head_metadata_states",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Index,
            name: "session_head_metadata_states_predecessor_idx",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_head_metadata_state_deltas",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Index,
            name: "session_head_metadata_state_deltas_key_idx",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_head_metadata_refs",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Table,
            name: "session_head_metadata_head_lineage",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Index,
            name: "session_head_metadata_head_lineage_predecessor_idx",
        },
        meerkat_sqlite::SchemaObject {
            kind: meerkat_sqlite::SchemaObjectKind::Index,
            name: "session_head_metadata_head_lineage_successor_idx",
        },
    ],
    retired_objects: &[],
};

#[cfg(test)]
#[allow(clippy::expect_used)]
mod schema_floor_tests {
    use super::*;

    fn pre_exact_head_canonical_v3() -> (Connection, SessionId, Vec<u8>, String) {
        let mut conn = Connection::open_in_memory().expect("open v3 fixture");
        let tx = conn.transaction().expect("v3 schema transaction");
        migration_0001_session_schema(&tx).expect("base schema");
        migration_0002_strand_links(&tx).expect("strand links");
        migration_0003_authenticated_head_sidecars(&tx).expect("v3 sidecars");
        tx.commit().expect("commit v3 schema");
        conn.execute_batch(
            "CREATE TABLE meerkat_schema (
                 domain TEXT PRIMARY KEY,
                 version INTEGER NOT NULL
             );
             INSERT INTO meerkat_schema VALUES ('session-store', 3);",
        )
        .expect("v3 ledger");

        let mut session = Session::new();
        session.push(Message::User(meerkat_core::types::UserMessage::text(
            "v1 physical row".to_string(),
        )));
        let id = session.id().clone();
        let tx = conn.transaction().expect("v1 head transaction");
        let strand = TranscriptStrandId::root();
        insert_strand_rows_in_txn(&tx, &id, &strand, 0, session.messages())
            .expect("insert exact v1 rows");
        let mut head = SessionHead::from_session(&session, strand, 0).expect("project v1 head");
        head.message_row_prefix = None;
        head.row_lineage_anchor = None;
        head.realtime_event_prefix = None;
        let token = write_head_row_only_in_txn(&tx, &head).expect("persist v1 head");
        tx.commit().expect("commit v1 head");
        let bytes = conn
            .query_row(
                "SELECT head_json FROM session_heads WHERE session_id = ?1",
                params![id.to_string()],
                |row| Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes()),
            )
            .expect("read v1 head bytes");
        (conn, id, bytes, token)
    }

    fn insert_head_with_versions(
        conn: &mut Connection,
        row_version: i64,
        embedded_version: u32,
    ) -> (SessionId, serde_json::Value, String) {
        let session = Session::new();
        let mut head = SessionHead::from_session(&session, TranscriptStrandId::root(), 0)
            .expect("project fixture head");
        head.version = embedded_version;
        let head_json = serde_json::to_value(&head).expect("serialize fixture head");
        let token = session_head_cas_token(&head).expect("fixture head token");
        let id = head.id.clone();
        let tx = conn.transaction().expect("head fixture transaction");
        write_head_row_only_in_txn(&tx, &head).expect("insert session head");
        tx.execute(
            "UPDATE session_heads SET version = ?1 WHERE session_id = ?2",
            params![row_version, id.to_string()],
        )
        .expect("set fixture row version");
        tx.commit().expect("commit head fixture");
        (id, head_json, token)
    }

    fn raw_head(conn: &Connection, id: &SessionId) -> (i64, serde_json::Value, String) {
        conn.query_row(
            "SELECT version, head_json, cas_token
             FROM session_heads
             WHERE session_id = ?1",
            params![id.to_string()],
            |row| {
                let head_json = row.get::<_, JsonColumnBytes>(1)?.into_bytes();
                Ok((
                    row.get(0)?,
                    serde_json::from_slice(&head_json).expect("decode head JSON"),
                    row.get(2)?,
                ))
            },
        )
        .expect("read fixture head")
    }

    fn released_v2() -> Connection {
        let mut conn = Connection::open_in_memory().expect("open");
        let tx = conn.transaction().expect("tx");
        build_released_0_8_10_session_schema(&tx).expect("released schema");
        tx.commit().expect("commit");
        conn.execute_batch(
            "CREATE TABLE meerkat_schema (
                 domain TEXT PRIMARY KEY,
                 version INTEGER NOT NULL
             );
             INSERT INTO meerkat_schema VALUES ('session-store', 2);",
        )
        .expect("ledger");
        conn
    }

    #[test]
    fn exact_released_v2_upgrades_to_current() {
        let mut conn = released_v2();
        let report = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
            .expect("upgrade");
        assert_eq!(report.from_version, 2);
        assert_eq!(report.to_version, 4);
    }

    /// The exact catalog of a realm created before the schema ledger: the
    /// two plain-CREATE session objects, nothing else, and no ledger table.
    const PRE_FLOOR_PLAIN_CREATE_FIXTURE_SQL: &str = "CREATE TABLE sessions (
         session_id TEXT PRIMARY KEY,
         created_at_ms INTEGER NOT NULL,
         updated_at_ms INTEGER NOT NULL,
         message_count INTEGER NOT NULL,
         total_tokens INTEGER NOT NULL,
         metadata_json TEXT NOT NULL,
         session_json BLOB NOT NULL
     );
     CREATE INDEX sessions_updated_idx
     ON sessions(updated_at_ms DESC, session_id ASC);";

    fn pre_floor_fixture_conn(fixture_sql: &str) -> Connection {
        let conn = Connection::open_in_memory().expect("open pre-floor fixture");
        conn.execute_batch(fixture_sql).expect("pre-floor ddl");
        conn
    }

    fn released_v2_session_row() -> (String, String, Vec<u8>) {
        let mut session = Session::new();
        session.push(Message::User(meerkat_core::UserMessage::text(
            "pre-floor plain-create fixture",
        )));
        let session_id = session.id().to_string();
        let mut document = serde_json::to_value(&session).expect("session document");
        document["version"] = serde_json::json!(2);
        let source = serde_json::to_vec(&document).expect("serialize session document");
        let _released_session = meerkat_core::import_released_0810_session(&source)
            .expect("fixture must be an exact released-v2 session document");
        let metadata = serde_json::to_string(session.metadata()).expect("metadata");
        (session_id, metadata, source)
    }

    fn bridge_pre_floor(
        conn: &mut Connection,
    ) -> Result<meerkat_sqlite::MaintenanceBridgeReport, meerkat_sqlite::SqliteStoreError> {
        meerkat_core::with_pre_floor_provider_image_metadata_import(|| {
            meerkat_sqlite::bridge_unledgered_domain(
                conn,
                &SESSION_STORE_DOMAIN,
                SESSION_STORE_DOMAIN.supported_version(),
                &[1],
                Some(prepare_pre_0_8_10_session_base_schema),
            )
        })
    }

    #[test]
    fn pre_floor_plain_create_catalog_bridges_to_current() {
        let mut conn = pre_floor_fixture_conn(PRE_FLOOR_PLAIN_CREATE_FIXTURE_SQL);
        let (session_id, metadata, source) = released_v2_session_row();
        conn.execute(
            "INSERT INTO sessions VALUES (?1, 0, 0, 1, 0, ?2, ?3)",
            params![session_id, metadata, source],
        )
        .expect("legacy session row");

        let report = bridge_pre_floor(&mut conn).expect("plain-create pre-floor catalog bridges");
        assert_eq!(report.from_version, 1);
        assert_eq!(report.to_version, SESSION_STORE_DOMAIN.supported_version());
        assert_eq!(report.prepared, 1, "one legacy session row is rebuilt");

        // Usable through the current version chain: ordinary migration
        // application is a fingerprint-verified no-op and the row survived.
        let ledger = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
            .expect("current chain accepts the bridged catalog");
        assert!(!ledger.migrated());
        let stored: String = conn
            .query_row("SELECT session_id FROM sessions", [], |row| row.get(0))
            .expect("bridged session row");
        assert_eq!(stored, session_id);
    }

    #[track_caller]
    fn assert_pre_floor_refused(fixture_sql: &str) {
        let mut conn = pre_floor_fixture_conn(fixture_sql);
        let error = bridge_pre_floor(&mut conn).expect_err("structural deviation must refuse");
        assert!(
            matches!(
                error,
                meerkat_sqlite::SqliteStoreError::UnledgeredSchemaNoMatch { .. }
            ),
            "expected UnledgeredSchemaNoMatch, found {error:?}"
        );
    }

    #[test]
    fn pre_floor_catalog_with_wrong_column_type_stays_refused() {
        assert_pre_floor_refused(
            "CREATE TABLE sessions (
                 session_id TEXT PRIMARY KEY,
                 created_at_ms INTEGER NOT NULL,
                 updated_at_ms INTEGER NOT NULL,
                 message_count INTEGER NOT NULL,
                 total_tokens TEXT NOT NULL,
                 metadata_json TEXT NOT NULL,
                 session_json BLOB NOT NULL
             );
             CREATE INDEX sessions_updated_idx
             ON sessions(updated_at_ms DESC, session_id ASC);",
        );
    }

    #[test]
    fn pre_floor_catalog_missing_index_stays_refused() {
        assert_pre_floor_refused(
            "CREATE TABLE sessions (
                 session_id TEXT PRIMARY KEY,
                 created_at_ms INTEGER NOT NULL,
                 updated_at_ms INTEGER NOT NULL,
                 message_count INTEGER NOT NULL,
                 total_tokens INTEGER NOT NULL,
                 metadata_json TEXT NOT NULL,
                 session_json BLOB NOT NULL
             );",
        );
    }

    #[test]
    fn pre_floor_catalog_with_wrong_index_shape_stays_refused() {
        assert_pre_floor_refused(
            "CREATE TABLE sessions (
                 session_id TEXT PRIMARY KEY,
                 created_at_ms INTEGER NOT NULL,
                 updated_at_ms INTEGER NOT NULL,
                 message_count INTEGER NOT NULL,
                 total_tokens INTEGER NOT NULL,
                 metadata_json TEXT NOT NULL,
                 session_json BLOB NOT NULL
             );
             CREATE INDEX sessions_updated_idx
             ON sessions(updated_at_ms ASC, session_id ASC);",
        );
    }

    #[test]
    fn v3_pre_exact_head_crosses_to_append_ready_v2_authority_atomically() {
        let (mut conn, id, source_head_bytes, source_token) = pre_exact_head_canonical_v3();

        let report = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
            .expect("cross v1 head to v2 authority");

        assert_eq!((report.from_version, report.to_version), (3, 4));
        let tx = conn
            .transaction()
            .expect("verify converted head transaction");
        let (head, stored_token) = head_row_in_txn(&tx, &id)
            .expect("read converted head")
            .expect("converted head exists");
        assert_ne!(
            stored_token, source_token,
            "conversion must rotate authority"
        );
        assert_eq!(
            stored_token,
            session_head_cas_token(&head).expect("converted head token")
        );
        assert!(head.message_row_prefix.is_some());
        assert!(head.row_lineage_anchor.is_some());
        assert!(head.realtime_event_prefix.is_some());
        assert!(head.metadata_identity().is_some());
        let verified = verify_physical_head_canonical_in_txn(&tx, &head)
            .expect("converted head verifies against exact rows and sidecars");
        let mut continued = verified.session().as_ref().clone();
        continued.push(Message::User(meerkat_core::types::UserMessage::text(
            "ordinary append".to_string(),
        )));
        PreparedHeadCanonicalMutation::prepare(&continued, Some(head))
            .expect("converted head admits an ordinary prepared append");
        assert_ne!(
            tx.query_row(
                "SELECT head_json FROM session_heads WHERE session_id = ?1",
                params![id.to_string()],
                |row| Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes()),
            )
            .expect("read converted head bytes"),
            source_head_bytes,
            "the source head must be replaced only after complete authority is ready"
        );
    }

    #[test]
    fn typed_head_crossing_reports_conversion_then_reverified_current_authority() {
        let (mut conn, id, _source_head_bytes, source_token) = pre_exact_head_canonical_v3();

        let tx = conn.transaction().expect("typed conversion transaction");
        let converted = cross_head_canonical_authority_in_txn(&tx, &id)
            .expect("typed crossing converts pre-exact authority");
        assert!(matches!(
            &converted,
            HeadCanonicalAuthorityCrossing::Converted(_)
        ));
        let converted_token = converted
            .authority()
            .expect("converted authority")
            .head_token()
            .to_string();
        assert_ne!(converted_token, source_token);
        tx.commit().expect("commit typed conversion");

        let tx = conn.transaction().expect("typed retry transaction");
        let current = cross_head_canonical_authority_in_txn(&tx, &id)
            .expect("typed crossing reverifies current authority");
        assert!(matches!(
            &current,
            HeadCanonicalAuthorityCrossing::AlreadyCurrent(_)
        ));
        assert_eq!(
            current.authority().expect("current authority").head_token(),
            converted_token.as_str()
        );
        tx.commit().expect("commit typed retry");
    }

    #[test]
    fn store_activation_crosses_sparse_legacy_blob_and_pre_exact_head_atomically()
    -> Result<(), Box<dyn std::error::Error>> {
        let (mut conn, head_id, _source_head_bytes, _source_token) = pre_exact_head_canonical_v3();
        let blob_id = SessionId::parse("ffffffff-ffff-ffff-ffff-ffffffffffff")?;
        assert!(head_id.to_string() < blob_id.to_string());
        let mut blob_session = Session::with_id(blob_id.clone());
        blob_session.push(Message::User(meerkat_core::types::UserMessage::text(
            "legacy blob row".to_string(),
        )));
        let tx = conn.transaction()?;
        write_session_snapshot_in_txn(&tx, &blob_session)?;
        tx.commit()?;

        let tx = conn.transaction()?;
        let activation = activate_head_canonical_store_in_txn(&tx)?;
        let HeadCanonicalStoreActivation::Activated(crossings) = activation else {
            return Err("SQLite HeadCanonical activation must be applicable".into());
        };
        assert_eq!(crossings.len(), 2);
        assert!(
            crossings
                .iter()
                .all(|crossing| matches!(crossing, HeadCanonicalAuthorityCrossing::Converted(_)))
        );
        assert_eq!(
            crossings[0]
                .authority()
                .ok_or("first crossing must carry verified authority")?
                .head()
                .id,
            head_id
        );
        assert_eq!(
            crossings[1]
                .authority()
                .ok_or("second crossing must carry verified authority")?
                .head()
                .id,
            blob_id
        );
        tx.commit()?;

        let tx = conn.transaction()?;
        let (blob_head, blob_token) =
            head_row_in_txn(&tx, &blob_id)?.ok_or("sparse blob must now have a physical head")?;
        assert_eq!(session_head_cas_token(&blob_head)?, blob_token);
        verify_physical_head_canonical_in_txn(&tx, &blob_head)?;
        tx.commit()?;
        Ok(())
    }

    #[test]
    fn store_activation_rolls_back_earlier_crossing_when_later_identity_is_invalid() {
        let (mut conn, head_id, source_head_bytes, source_token) = pre_exact_head_canonical_v3();
        let blob_id = SessionId::parse("ffffffff-ffff-ffff-ffff-ffffffffffff")
            .expect("fixed legacy blob identity");
        let blob_session = Session::with_id(blob_id.clone());
        let tx = conn.transaction().expect("legacy blob transaction");
        write_session_snapshot_in_txn(&tx, &blob_session).expect("insert legacy blob row");
        tx.execute(
            "UPDATE sessions SET session_id = 'zzzz-invalid' WHERE session_id = ?1",
            params![blob_id.to_string()],
        )
        .expect("corrupt later physical identity");
        tx.commit()
            .expect("commit invalid physical identity fixture");

        let tx = conn.transaction().expect("bulk activation transaction");
        activate_head_canonical_store_in_txn(&tx)
            .expect_err("invalid later census identity must abort the full activation");
        drop(tx);

        let (head_bytes, token) = conn
            .query_row(
                "SELECT head_json, cas_token FROM session_heads WHERE session_id = ?1",
                params![head_id.to_string()],
                |row| {
                    Ok((
                        row.get::<_, JsonColumnBytes>(0)?.into_bytes(),
                        row.get::<_, String>(1)?,
                    ))
                },
            )
            .expect("read rolled-back source head");
        assert_eq!(token, source_token);
        assert_eq!(
            head_bytes, source_head_bytes,
            "a later census failure must roll back every earlier crossing"
        );
    }

    #[test]
    fn v3_current_authority_migration_preserves_referenced_head_token_and_bytes() {
        let (mut conn, id, _source_head_bytes, _source_token) = pre_exact_head_canonical_v3();
        let tx = conn
            .transaction()
            .expect("prepare current authority transaction");
        let converted = cross_head_canonical_authority_in_txn(&tx, &id)
            .expect("prepare current authority before schema crossing");
        let referenced_token = converted
            .authority()
            .expect("prepared authority")
            .head_token()
            .to_string();
        tx.commit().expect("commit prepared current authority");
        let referenced_head_bytes = conn
            .query_row(
                "SELECT head_json FROM session_heads WHERE session_id = ?1",
                params![id.to_string()],
                |row| Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes()),
            )
            .expect("read referenced current head bytes");

        let report = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
            .expect("advance schema around current authority");

        assert_eq!((report.from_version, report.to_version), (3, 4));
        let tx = conn
            .transaction()
            .expect("read preserved authority transaction");
        let (head, stored_token) = head_row_in_txn(&tx, &id)
            .expect("read preserved authority")
            .expect("preserved authority exists");
        assert_eq!(stored_token, referenced_token);
        assert_eq!(
            tx.query_row(
                "SELECT head_json FROM session_heads WHERE session_id = ?1",
                params![id.to_string()],
                |row| Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes()),
            )
            .expect("read preserved head bytes"),
            referenced_head_bytes
        );
        verify_physical_head_canonical_in_txn(&tx, &head)
            .expect("preserved authority remains fully verified");
    }

    #[test]
    fn v3_unproved_source_rows_roll_back_head_sidecars_and_schema_floor() {
        let (mut conn, id, source_head_bytes, _source_token) = pre_exact_head_canonical_v3();
        let tampered = serde_json::to_vec(&Message::User(meerkat_core::types::UserMessage::text(
            "tampered physical row".to_string(),
        )))
        .expect("serialize tampered row");
        conn.execute(
            "UPDATE session_strand_messages
             SET message_json = ?1
             WHERE session_id = ?2 AND seq = 0",
            params![tampered, id.to_string()],
        )
        .expect("corrupt exact source row");

        let error = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
            .expect_err("unproved v1 authority must refuse");

        assert!(
            error.to_string().contains("v1-to-v2 conversion failed"),
            "unexpected conversion error: {error}"
        );
        assert_eq!(
            meerkat_sqlite::domain_version(&conn, SESSION_STORE_DOMAIN.name)
                .expect("schema ledger"),
            Some(3),
            "failed conversion must not stamp v4"
        );
        assert_eq!(
            conn.query_row(
                "SELECT head_json FROM session_heads WHERE session_id = ?1",
                params![id.to_string()],
                |row| Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes()),
            )
            .expect("read rolled-back head bytes"),
            source_head_bytes,
            "failed conversion must leave source head bytes intact"
        );
        for table in [
            "session_component_events",
            "session_head_metadata_cells",
            "session_head_metadata_current",
            "session_head_metadata_states",
            "session_head_metadata_state_deltas",
            "session_head_metadata_refs",
            "session_head_metadata_head_lineage",
        ] {
            let count: i64 = conn
                .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
                    row.get(0)
                })
                .expect("count rolled-back sidecar rows");
            assert_eq!(count, 0, "failed conversion must roll back {table}");
        }
    }

    #[test]
    fn exact_released_v2_head_document_imports_atomically_with_schema_floor() {
        let mut conn = released_v2();
        let (id, _, released_token) = insert_head_with_versions(&mut conn, 2, 2);

        let report = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
            .expect("upgrade");

        assert_eq!((report.from_version, report.to_version), (2, 4));
        let (row_version, migrated_json, migrated_token) = raw_head(&conn, &id);
        assert_eq!(
            row_version,
            i64::from(meerkat_core::SESSION_VERSION),
            "the indexed row envelope advances in the migration transaction"
        );
        let migrated: SessionHead =
            serde_json::from_value(migrated_json).expect("deserialize migrated head");
        assert_eq!(migrated.version, meerkat_core::SESSION_VERSION);
        assert_eq!(migrated.id, id);
        assert!(
            migrated.message_row_prefix.is_some() && migrated.row_lineage_anchor.is_some(),
            "the frozen import must publish a fully materializable current head"
        );
        assert_ne!(
            migrated_token, released_token,
            "the CAS token must advance with the imported current authority"
        );
        assert_eq!(
            migrated_token,
            session_head_cas_token(&migrated).expect("current migrated token")
        );
    }

    #[test]
    fn released_v2_migration_leaves_non_v2_head_envelopes_byte_semantically_unchanged() {
        let mut conn = released_v2();
        let (older_id, older_json, older_token) = insert_head_with_versions(&mut conn, 1, 1);
        let (released_id, _, _) = insert_head_with_versions(&mut conn, 2, 2);
        let future_version = meerkat_core::SESSION_VERSION + 1;
        let (future_id, future_json, future_token) =
            insert_head_with_versions(&mut conn, i64::from(future_version), future_version);

        let report = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
            .expect("v2 to current");
        assert_eq!((report.from_version, report.to_version), (2, 4));

        assert_eq!(raw_head(&conn, &older_id), (1, older_json, older_token));
        assert_eq!(
            raw_head(&conn, &future_id),
            (i64::from(future_version), future_json, future_token)
        );
        assert_eq!(
            raw_head(&conn, &released_id).0,
            i64::from(meerkat_core::SESSION_VERSION)
        );
    }

    #[test]
    fn released_v2_schema_rejects_a_nonreleased_head_envelope_without_stamping_current() {
        let mut conn = released_v2();
        let (id, original_json, original_token) =
            insert_head_with_versions(&mut conn, 2, meerkat_core::SESSION_VERSION);

        let error = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
            .expect_err("row/header version disagreement is not released 0.8.10");

        assert!(
            error
                .to_string()
                .contains("row version is 2 but embedded head version is 3"),
            "unexpected migration error: {error}"
        );
        assert_eq!(
            meerkat_sqlite::domain_version(&conn, SESSION_STORE_DOMAIN.name)
                .expect("schema ledger"),
            Some(2),
            "failed conversion must roll back the schema floor"
        );
        assert_eq!(
            raw_head(&conn, &id),
            (2, original_json, original_token),
            "failed conversion must leave the head row untouched"
        );
    }

    #[test]
    fn released_v2_schema_rejects_a_mismatched_head_identity_without_stamping_current() {
        let mut conn = released_v2();
        let (embedded_id, original_json, original_token) =
            insert_head_with_versions(&mut conn, 2, 2);
        let row_id = Session::new().id().clone();
        conn.execute(
            "UPDATE session_heads SET session_id = ?1 WHERE session_id = ?2",
            params![row_id.to_string(), embedded_id.to_string()],
        )
        .expect("install mismatched row identity");

        let error = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
            .expect_err("released row identity must bind the embedded head");

        assert!(
            error
                .to_string()
                .contains(&format!("embedded head identity is '{embedded_id}'")),
            "unexpected migration error: {error}"
        );
        assert_eq!(
            meerkat_sqlite::domain_version(&conn, SESSION_STORE_DOMAIN.name)
                .expect("schema ledger"),
            Some(2),
            "identity mismatch must roll back the schema floor"
        );
        assert_eq!(
            raw_head(&conn, &row_id),
            (2, original_json, original_token),
            "identity mismatch must leave the head row untouched"
        );
    }

    #[test]
    fn released_v2_final_column_table_and_index_collisions_are_refused_unmutated() {
        for collision in [
            "ALTER TABLE session_rewrites ADD COLUMN graph_edge_json BLOB",
            "CREATE TABLE session_component_events (candidate INTEGER)",
            "CREATE INDEX session_head_metadata_states_predecessor_idx
                 ON session_heads(session_id)",
        ] {
            let mut conn = released_v2();
            conn.execute_batch(collision).expect("collision");
            let err = meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)
                .expect_err("refuse collision");
            assert!(matches!(
                err,
                meerkat_sqlite::SqliteStoreError::SchemaFingerprintMismatch { version: 2, .. }
            ));
            assert_eq!(
                meerkat_sqlite::domain_version(&conn, SESSION_STORE_DOMAIN.name).expect("ledger"),
                Some(2)
            );
        }
    }
}

/// Open a connection and bring the session-store schema domain up to date.
fn open_session_connection(
    path: &Path,
    options: SqliteConnectionOptions,
) -> Result<Connection, StoreError> {
    let mut conn = open_connection_with_options(path, options)?;
    meerkat_sqlite::apply_domain_migrations(&mut conn, &SESSION_STORE_DOMAIN)?;
    Ok(conn)
}

pub fn begin_immediate_transaction(conn: &mut Connection) -> Result<Transaction<'_>, StoreError> {
    begin_immediate_transaction_with_options(conn, SqliteConnectionOptions::default())
}

pub fn begin_immediate_transaction_with_options(
    conn: &mut Connection,
    _options: SqliteConnectionOptions,
) -> Result<Transaction<'_>, StoreError> {
    // rusqlite's configured busy handler performs the bounded retry while
    // BEGIN IMMEDIATE waits for the WAL writer. Keeping it on the connection
    // makes the policy apply consistently to begin, statements, and commit.
    conn.transaction_with_behavior(TransactionBehavior::Immediate)
        .map_err(StoreError::from)
}

/// Bring the session-store schema domain up to date on an already-open
/// connection.
///
/// Routes through the shared migration ledger ([`SESSION_STORE_DOMAIN`]):
/// the domain version is checked and stamped in the same transaction as the
/// DDL, and a file stamped by a newer binary is refused typed
/// ([`StoreError::SchemaFromTheFuture`]) before anything runs. There is no
/// unledgered DDL entry point.
pub fn ensure_schema(conn: &mut Connection) -> Result<(), StoreError> {
    meerkat_sqlite::apply_domain_migrations(conn, &SESSION_STORE_DOMAIN)?;
    Ok(())
}

pub fn write_session_snapshot_in_txn(
    tx: &Transaction<'_>,
    session: &Session,
) -> Result<(), StoreError> {
    let session_id = session.id().to_string();
    let metadata_json = serde_json::to_string(session.metadata())?;
    // Encode + midstate admission are one core-owned operation: in-process
    // reads of these exact bytes adopt the warm digest midstates instead of
    // reseeding them with O(document) canonical passes.
    let session_json = session.to_persisted_bytes()?;
    // Derived projection counters must round-trip through the durable i64
    // columns without loss. A count that exceeds i64::MAX is itself an
    // impossible state, so fail closed rather than silently clamping to a
    // fabricated maximum (terminal-truth store-metadata cluster).
    let message_count = i64::try_from(session.messages().len()).map_err(|_| {
        StoreError::Internal(format!(
            "session '{session_id}' message_count {} exceeds durable i64 range",
            session.messages().len()
        ))
    })?;
    let total_tokens = i64::try_from(session.total_tokens()).map_err(|_| {
        StoreError::Internal(format!(
            "session '{session_id}' total_tokens {} exceeds durable i64 range",
            session.total_tokens()
        ))
    })?;
    tx.execute(
        r"
        INSERT INTO sessions (
            session_id,
            created_at_ms,
            updated_at_ms,
            message_count,
            total_tokens,
            metadata_json,
            session_json
        ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
        ON CONFLICT(session_id) DO UPDATE SET
            created_at_ms = excluded.created_at_ms,
            updated_at_ms = excluded.updated_at_ms,
            message_count = excluded.message_count,
            total_tokens = excluded.total_tokens,
            metadata_json = excluded.metadata_json,
            session_json = excluded.session_json
        ",
        params![
            session_id,
            system_time_millis(session.created_at()),
            system_time_millis(session.updated_at()),
            message_count,
            total_tokens,
            metadata_json,
            session_json,
        ],
    )?;
    Ok(())
}

fn load_session_snapshot_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<Option<Session>, StoreError> {
    tx.query_row(
        "SELECT session_json FROM sessions WHERE session_id = ?1",
        params![id.to_string()],
        |row| Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes()),
    )
    .optional()?
    .map(|bytes| Session::from_persisted_bytes(&bytes).map_err(StoreError::Serialization))
    .transpose()
}

// ---------------------------------------------------------------------------
// Incremental (head-canonical) helpers. All run inside an immediate
// transaction on the caller's connection.
// ---------------------------------------------------------------------------

fn now_millis() -> i64 {
    system_time_millis(SystemTime::now())
}

fn head_row_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<Option<(SessionHead, String)>, SessionStoreError> {
    let row = tx
        .query_row(
            "SELECT head_json, cas_token FROM session_heads WHERE session_id = ?1",
            params![id.to_string()],
            |row| {
                Ok((
                    row.get::<_, JsonColumnBytes>(0)?.into_bytes(),
                    row.get::<_, String>(1)?,
                ))
            },
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let Some((head_json, cas_token)) = row else {
        return Ok(None);
    };
    let head: SessionHead =
        serde_json::from_slice(&head_json).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    Ok(Some((head, cas_token)))
}

#[derive(Clone, Copy)]
enum HeadMetadataProjectionOwner {
    PhysicalHead,
    RuntimeBoundary,
}

impl HeadMetadataProjectionOwner {
    fn as_str(self) -> &'static str {
        match self {
            Self::PhysicalHead => "physical_head",
            Self::RuntimeBoundary => "runtime_boundary",
        }
    }
}

#[derive(Debug, Clone)]
struct HeadMetadataOwnerRef {
    /// Immutable head token that created `state_id`.
    ///
    /// Transcript-only successors with the same metadata identity deliberately
    /// do not churn this row.
    head_cas_token: String,
    state_id: String,
}

#[derive(Debug, Clone)]
struct HeadMetadataStateRow {
    predecessor_state_id: Option<String>,
    identity: SessionHeadMetadataIdentity,
    transition_id: String,
}

fn metadata_state_id(head_cas_token: &str) -> String {
    format!("head-metadata-state:{head_cas_token}")
}

fn metadata_owner_ref_in_txn(
    tx: &Connection,
    id: &SessionId,
    owner: HeadMetadataProjectionOwner,
) -> Result<Option<HeadMetadataOwnerRef>, SessionStoreError> {
    tx.query_row(
        r"
        SELECT head_cas_token, state_id
        FROM session_head_metadata_refs
        WHERE session_id = ?1 AND owner = ?2
        ",
        params![id.to_string(), owner.as_str()],
        |row| {
            Ok(HeadMetadataOwnerRef {
                head_cas_token: row.get(0)?,
                state_id: row.get(1)?,
            })
        },
    )
    .optional()
    .map_err(StoreError::from)
    .map_err(into_session_store_error)
}

fn metadata_state_in_txn(
    tx: &Connection,
    id: &SessionId,
    state_id: &str,
) -> Result<Option<HeadMetadataStateRow>, SessionStoreError> {
    let stored = tx
        .query_row(
            r"
            SELECT predecessor_state_id, identity_json, transition_id
            FROM session_head_metadata_states
            WHERE session_id = ?1 AND state_id = ?2
            ",
            params![id.to_string(), state_id],
            |row| {
                Ok((
                    row.get::<_, Option<String>>(0)?,
                    row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                    row.get::<_, String>(2)?,
                ))
            },
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    stored
        .map(|(predecessor_state_id, identity_json, transition_id)| {
            let identity: SessionHeadMetadataIdentity = serde_json::from_slice(&identity_json)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
            if serde_json::to_vec(&identity).map_err(SessionStoreError::from)? != identity_json {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            Ok(HeadMetadataStateRow {
                predecessor_state_id,
                identity,
                transition_id,
            })
        })
        .transpose()
}

fn parse_metadata_cell(
    id: &SessionId,
    key: String,
    key_route: Vec<u8>,
    exact_value_digest: String,
    metadata_json: Vec<u8>,
) -> Result<Arc<SessionHeadMetadataCell>, SessionStoreError> {
    let route: [u8; 32] = key_route
        .try_into()
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let identity = SessionHeadMetadataCellIdentity::new(
        SessionHeadMetadataValueDigest::parse(exact_value_digest)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
    );
    let cell =
        SessionHeadMetadataCell::from_canonical_json(key, identity, Arc::from(metadata_json))
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    if cell.key_route() != &route {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(Arc::new(cell))
}

fn metadata_cell_in_txn(
    tx: &Connection,
    id: &SessionId,
    key: &str,
    exact_value_digest: &str,
) -> Result<Option<Arc<SessionHeadMetadataCell>>, SessionStoreError> {
    let row = tx
        .query_row(
            r"
            SELECT key_route, metadata_json
            FROM session_head_metadata_cells
            WHERE session_id = ?1
              AND metadata_key = ?2
              AND exact_value_digest = ?3
            ",
            params![id.to_string(), key, exact_value_digest],
            |row| {
                Ok((
                    row.get::<_, Vec<u8>>(0)?,
                    row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                ))
            },
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    row.map(|(key_route, metadata_json)| {
        parse_metadata_cell(
            id,
            key.to_string(),
            key_route,
            exact_value_digest.to_string(),
            metadata_json,
        )
    })
    .transpose()
}

fn persist_metadata_cell_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    cell: &SessionHeadMetadataCell,
) -> Result<(), SessionStoreError> {
    // The covering `(session_id, key_route, metadata_key)` index makes both
    // strict key ranges point lookups. Do not use `metadata_key <> ?` here:
    // SQLite can satisfy that only by walking every historical version of the
    // same hot key, turning a collision guard into O(history).
    let lower_collision = tx
        .query_row(
            r"
            SELECT metadata_key
            FROM session_head_metadata_cells
            WHERE session_id = ?1 AND key_route = ?2 AND metadata_key < ?3
            ORDER BY metadata_key DESC
            LIMIT 1
            ",
            params![id.to_string(), cell.key_route().as_slice(), cell.key()],
            |row| row.get::<_, String>(0),
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let upper_collision = tx
        .query_row(
            r"
            SELECT metadata_key
            FROM session_head_metadata_cells
            WHERE session_id = ?1 AND key_route = ?2 AND metadata_key > ?3
            ORDER BY metadata_key ASC
            LIMIT 1
            ",
            params![id.to_string(), cell.key_route().as_slice(), cell.key()],
            |row| row.get::<_, String>(0),
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    if lower_collision.is_some() || upper_collision.is_some() {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let inserted = tx
        .execute(
            r"
            INSERT OR IGNORE INTO session_head_metadata_cells (
                session_id, metadata_key, key_route, exact_value_digest,
                metadata_json, created_at_ms
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6)
            ",
            params![
                id.to_string(),
                cell.key(),
                cell.key_route().as_slice(),
                cell.identity().exact_value_digest().as_str(),
                cell.canonical_json(),
                now_millis(),
            ],
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    if inserted == 0 {
        let stored = metadata_cell_in_txn(
            tx,
            id,
            cell.key(),
            cell.identity().exact_value_digest().as_str(),
        )?
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if stored.key_route() != cell.key_route()
            || stored.identity() != cell.identity()
            || stored.canonical_json() != cell.canonical_json()
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
    }
    Ok(())
}

fn current_metadata_cell_digest_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    key: &str,
) -> Result<Option<(Vec<u8>, String)>, SessionStoreError> {
    tx.query_row(
        r"
        SELECT key_route, exact_value_digest
        FROM session_head_metadata_current
        WHERE session_id = ?1 AND metadata_key = ?2
        ",
        params![id.to_string(), key],
        |row| Ok((row.get(0)?, row.get(1)?)),
    )
    .optional()
    .map_err(StoreError::from)
    .map_err(into_session_store_error)
}

fn move_metadata_owner_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    owner: HeadMetadataProjectionOwner,
    head_cas_token: &str,
    state_id: &str,
) -> Result<(), SessionStoreError> {
    tx.execute(
        r"
        INSERT INTO session_head_metadata_refs (
            session_id, owner, head_cas_token, state_id
        ) VALUES (?1, ?2, ?3, ?4)
        ON CONFLICT(session_id, owner) DO UPDATE SET
            head_cas_token = excluded.head_cas_token,
            state_id = excluded.state_id
        ",
        params![id.to_string(), owner.as_str(), head_cas_token, state_id],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    Ok(())
}

fn insert_metadata_state_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    state_id: &str,
    predecessor_state_id: Option<&str>,
    identity: &SessionHeadMetadataIdentity,
    transition_id: &str,
) -> Result<(), SessionStoreError> {
    let identity_json = serde_json::to_vec(identity).map_err(SessionStoreError::from)?;
    tx.execute(
        r"
        INSERT INTO session_head_metadata_states (
            session_id, state_id, predecessor_state_id, identity_json,
            transition_id, created_at_ms
        ) VALUES (?1, ?2, ?3, ?4, ?5, ?6)
        ",
        params![
            id.to_string(),
            state_id,
            predecessor_state_id,
            identity_json,
            transition_id,
            now_millis(),
        ],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    Ok(())
}

fn insert_metadata_lineage_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    transition_id: &str,
    predecessor_head_cas_token: Option<&str>,
    successor_head_cas_token: &str,
    predecessor_state_id: Option<&str>,
    successor_state_id: &str,
) -> Result<(), SessionStoreError> {
    tx.execute(
        r"
        INSERT INTO session_head_metadata_head_lineage (
            session_id, transition_id, predecessor_head_cas_token,
            successor_head_cas_token, predecessor_state_id,
            successor_state_id, created_at_ms
        ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
        ",
        params![
            id.to_string(),
            transition_id,
            predecessor_head_cas_token,
            successor_head_cas_token,
            predecessor_state_id,
            successor_state_id,
            now_millis(),
        ],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    Ok(())
}

fn persist_metadata_state_delta_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    state_id: &str,
    ordinal: usize,
    mutation: &meerkat_core::session::SessionHeadMetadataCellMutation,
) -> Result<(), SessionStoreError> {
    let ordinal = i64::try_from(ordinal).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    tx.execute(
        r"
        INSERT INTO session_head_metadata_state_deltas (
            session_id, state_id, ordinal, metadata_key, key_route,
            predecessor_exact_value_digest, successor_exact_value_digest
        ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
        ",
        params![
            id.to_string(),
            state_id,
            ordinal,
            mutation.key(),
            mutation.key_route().as_slice(),
            mutation
                .predecessor()
                .map(|identity| identity.exact_value_digest().as_str()),
            mutation
                .successor()
                .map(|cell| cell.identity().exact_value_digest().as_str()),
        ],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    Ok(())
}

fn apply_metadata_mutation_to_current_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    mutation: &meerkat_core::session::SessionHeadMetadataCellMutation,
) -> Result<(), SessionStoreError> {
    let observed = current_metadata_cell_digest_in_txn(tx, id, mutation.key())?;
    let expected = mutation
        .predecessor()
        .map(|identity| identity.exact_value_digest().as_str());
    match (observed.as_ref(), expected) {
        (None, None) => {}
        (Some((route, digest)), Some(expected))
            if route.as_slice() == mutation.key_route() && digest.as_str() == expected => {}
        _ => return Err(SessionStoreError::Corrupted(id.clone())),
    }
    match mutation.successor() {
        Some(cell) => {
            persist_metadata_cell_in_txn(tx, id, cell)?;
            tx.execute(
                r"
                INSERT INTO session_head_metadata_current (
                    session_id, metadata_key, key_route, exact_value_digest
                ) VALUES (?1, ?2, ?3, ?4)
                ON CONFLICT(session_id, metadata_key) DO UPDATE SET
                    key_route = excluded.key_route,
                    exact_value_digest = excluded.exact_value_digest
                ",
                params![
                    id.to_string(),
                    mutation.key(),
                    mutation.key_route().as_slice(),
                    cell.identity().exact_value_digest().as_str(),
                ],
            )
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?;
        }
        None => {
            let deleted = tx
                .execute(
                    r"
                    DELETE FROM session_head_metadata_current
                    WHERE session_id = ?1 AND metadata_key = ?2
                    ",
                    params![id.to_string(), mutation.key()],
                )
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            if deleted != 1 {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
        }
    }
    Ok(())
}

/// Reconcile one authenticated metadata state transition before publishing its
/// compact head row.
///
/// An unchanged identity is a literal metadata-table no-write path: the
/// physical state is point-checked and no cell/state/delta/ref/lineage row is
/// changed. A root or changed identity verifies the prepared sparse-Merkle
/// chain, writes only its changed cells plus compact lineage, and moves the
/// physical owner in this same transaction.
fn reconcile_head_metadata_transition_in_txn(
    tx: &Transaction<'_>,
    predecessor_head: Option<&SessionHead>,
    predecessor_head_token: Option<&str>,
    successor_head: &SessionHead,
    successor_head_token: &str,
) -> Result<(), SessionStoreError> {
    let id = &successor_head.id;
    if session_head_cas_token(successor_head)? != successor_head_token {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let successor_identity = successor_head
        .metadata_identity()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let projection = successor_head
        .metadata_projection()
        .filter(|projection| projection.identity() == successor_identity)
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    if projection
        .mutations()
        .iter()
        .any(|mutation| !mutation.verify())
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }

    let predecessor_identity = predecessor_head.and_then(SessionHead::metadata_identity);
    let physical_ref =
        metadata_owner_ref_in_txn(tx, id, HeadMetadataProjectionOwner::PhysicalHead)?;
    let predecessor_state_id = match predecessor_identity {
        Some(identity) => {
            if projection.predecessor_identity() != Some(identity) {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            let owner = physical_ref
                .as_ref()
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
            let state = metadata_state_in_txn(tx, id, &owner.state_id)?
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
            if &state.identity != identity {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            Some(owner.state_id.clone())
        }
        None => {
            if projection.predecessor_identity().is_some()
                || !projection.is_full_snapshot()
                || physical_ref.is_some()
            {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            let current_count: i64 = tx
                .query_row(
                    "SELECT COUNT(*) FROM session_head_metadata_current WHERE session_id = ?1",
                    params![id.to_string()],
                    |row| row.get(0),
                )
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            if current_count != 0 {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            if projection.mutations().is_empty() {
                if !successor_identity.is_canonical_empty() {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
            } else if projection.mutations().len()
                != usize::try_from(successor_identity.entry_count())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?
                || projection
                    .mutations()
                    .first()
                    .is_none_or(|mutation| !mutation.predecessor_identity().is_canonical_empty())
            {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            None
        }
    };

    if predecessor_identity == Some(successor_identity) {
        if !projection.mutations().is_empty() || predecessor_state_id.is_none() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        // Literal stable path: no metadata table is written and no metadata
        // value row is read. The ref's token remains the state-creating anchor.
        return Ok(());
    }

    if predecessor_identity.is_some() && projection.mutations().is_empty() {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let successor_state_id = metadata_state_id(successor_head_token);
    insert_metadata_state_in_txn(
        tx,
        id,
        &successor_state_id,
        predecessor_state_id.as_deref(),
        successor_identity,
        successor_head_token,
    )?;
    for (ordinal, mutation) in projection.mutations().iter().enumerate() {
        apply_metadata_mutation_to_current_in_txn(tx, id, mutation)?;
        persist_metadata_state_delta_in_txn(tx, id, &successor_state_id, ordinal, mutation)?;
    }
    move_metadata_owner_in_txn(
        tx,
        id,
        HeadMetadataProjectionOwner::PhysicalHead,
        successor_head_token,
        &successor_state_id,
    )?;
    insert_metadata_lineage_in_txn(
        tx,
        id,
        successor_head_token,
        predecessor_head_token,
        successor_head_token,
        predecessor_state_id.as_deref(),
        &successor_state_id,
    )?;
    // Standalone SessionStore users have no RuntimeStore owner-ref move to
    // trigger convergence. Bound them here as soon as the physical state
    // advances. A divergent runtime owner makes this a read-only no-op; its
    // later atomic owner move performs the same prune.
    prune_converged_metadata_history_in_txn(tx, id, None)
}

fn current_metadata_cells_in_txn(
    tx: &Connection,
    id: &SessionId,
) -> Result<BTreeMap<String, Arc<SessionHeadMetadataCell>>, SessionStoreError> {
    let mut statement = tx
        .prepare(
            r"
            SELECT current.metadata_key, current.key_route, cell.key_route,
                   current.exact_value_digest, cell.metadata_json
            FROM session_head_metadata_current AS current
            JOIN session_head_metadata_cells AS cell
              ON cell.session_id = current.session_id
             AND cell.metadata_key = current.metadata_key
             AND cell.exact_value_digest = current.exact_value_digest
            WHERE current.session_id = ?1
            ORDER BY current.metadata_key
            ",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let rows = statement
        .query_map(params![id.to_string()], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, Vec<u8>>(1)?,
                row.get::<_, Vec<u8>>(2)?,
                row.get::<_, String>(3)?,
                row.get::<_, JsonColumnBytes>(4)?.into_bytes(),
            ))
        })
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let mut cells = BTreeMap::new();
    for (key, current_route, cell_route, exact, bytes) in rows {
        if current_route != cell_route {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let cell = parse_metadata_cell(id, key.clone(), current_route, exact, bytes)?;
        if cells.insert(key, cell).is_some() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
    }
    Ok(cells)
}

#[derive(Debug)]
struct StoredMetadataDelta {
    key: String,
    key_route: Vec<u8>,
    predecessor_exact_value_digest: Option<String>,
    successor_exact_value_digest: Option<String>,
}

fn metadata_state_deltas_in_txn(
    tx: &Connection,
    id: &SessionId,
    state_id: &str,
) -> Result<Vec<StoredMetadataDelta>, SessionStoreError> {
    let mut statement = tx
        .prepare(
            r"
            SELECT metadata_key, key_route, predecessor_exact_value_digest,
                   successor_exact_value_digest
            FROM session_head_metadata_state_deltas
            WHERE session_id = ?1 AND state_id = ?2
            ORDER BY ordinal
            ",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    statement
        .query_map(params![id.to_string(), state_id], |row| {
            Ok(StoredMetadataDelta {
                key: row.get(0)?,
                key_route: row.get(1)?,
                predecessor_exact_value_digest: row.get(2)?,
                successor_exact_value_digest: row.get(3)?,
            })
        })
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)
}

fn materialize_standalone_metadata_state_in_txn(
    tx: &Connection,
    id: &SessionId,
    state_id: &str,
) -> Result<BTreeMap<String, Arc<SessionHeadMetadataCell>>, SessionStoreError> {
    let state = metadata_state_in_txn(tx, id, state_id)?
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    if state.predecessor_state_id.is_some() {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let mut cells = BTreeMap::new();
    for delta in metadata_state_deltas_in_txn(tx, id, state_id)? {
        if delta.predecessor_exact_value_digest.is_some() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let exact = delta
            .successor_exact_value_digest
            .as_deref()
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        let cell = metadata_cell_in_txn(tx, id, &delta.key, exact)?
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if cell.key_route().as_slice() != delta.key_route.as_slice()
            || cells.insert(delta.key, cell).is_some()
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
    }
    Ok(cells)
}

fn metadata_state_for_head_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
    head_token: &str,
) -> Result<Option<String>, SessionStoreError> {
    let id = &head.id;
    if let Some(state_id) = tx
        .query_row(
            r"
            SELECT successor_state_id
            FROM session_head_metadata_head_lineage
            WHERE session_id = ?1 AND successor_head_cas_token = ?2
            ",
            params![id.to_string(), head_token],
            |row| row.get::<_, String>(0),
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
    {
        return Ok(Some(state_id));
    }
    if let Some(state_id) = tx
        .query_row(
            r"
            SELECT predecessor_state_id
            FROM session_head_metadata_head_lineage
            WHERE session_id = ?1 AND predecessor_head_cas_token = ?2
            ",
            params![id.to_string(), head_token],
            |row| row.get::<_, Option<String>>(0),
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .flatten()
    {
        return Ok(Some(state_id));
    }
    let expected = head
        .metadata_identity()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    for owner in [
        HeadMetadataProjectionOwner::PhysicalHead,
        HeadMetadataProjectionOwner::RuntimeBoundary,
    ] {
        if let Some(reference) = metadata_owner_ref_in_txn(tx, id, owner)?
            && metadata_state_in_txn(tx, id, &reference.state_id)?
                .is_some_and(|state| &state.identity == expected)
        {
            return Ok(Some(reference.state_id));
        }
    }
    Ok(None)
}

fn attach_head_metadata_projection(
    tx: &Connection,
    head: &mut SessionHead,
    owner: HeadMetadataProjectionOwner,
) -> Result<(), SessionStoreError> {
    let Some(expected_identity) = head.metadata_identity().cloned() else {
        return Ok(());
    };
    let reference = metadata_owner_ref_in_txn(tx, &head.id, owner)?
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    // A transcript-only successor deliberately has no metadata lineage row:
    // the exact owner ref remains pinned to the immutable state-creating
    // token. The compact head's authenticated identity below proves that
    // reusing that state is exact without churning metadata WAL.
    let target_state_id = reference.state_id;
    let target_state = metadata_state_in_txn(tx, &head.id, &target_state_id)?
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    if target_state.identity != expected_identity {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }

    let physical =
        metadata_owner_ref_in_txn(tx, &head.id, HeadMetadataProjectionOwner::PhysicalHead)?
            .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    let mut state_id = physical.state_id;
    let mut cells = current_metadata_cells_in_txn(tx, &head.id)?;
    let mut visited = BTreeSet::new();
    while state_id != target_state_id {
        if !visited.insert(state_id.clone()) {
            return Err(SessionStoreError::Corrupted(head.id.clone()));
        }
        let state = metadata_state_in_txn(tx, &head.id, &state_id)?
            .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
        let Some(predecessor_state_id) = state.predecessor_state_id else {
            cells = materialize_standalone_metadata_state_in_txn(tx, &head.id, &target_state_id)?;
            break;
        };
        for delta in metadata_state_deltas_in_txn(tx, &head.id, &state_id)? {
            match delta.predecessor_exact_value_digest.as_deref() {
                Some(exact) => {
                    let cell = metadata_cell_in_txn(tx, &head.id, &delta.key, exact)?
                        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
                    if cell.key_route().as_slice() != delta.key_route.as_slice() {
                        return Err(SessionStoreError::Corrupted(head.id.clone()));
                    }
                    cells.insert(delta.key, cell);
                }
                None => {
                    cells.remove(&delta.key);
                }
            }
        }
        state_id = predecessor_state_id;
    }
    let projection = Arc::new(
        SessionHeadMetadataProjection::from_snapshot(
            expected_identity,
            cells.into_values().collect(),
        )
        .map_err(|_| SessionStoreError::Corrupted(head.id.clone()))?,
    );
    head.attach_metadata_projection(projection)
}

fn persist_standalone_metadata_snapshot_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
    head_token: &str,
) -> Result<String, SessionStoreError> {
    let id = &head.id;
    let identity = head
        .metadata_identity()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let projection = head
        .metadata_projection()
        .filter(|projection| {
            projection.identity() == identity
                && projection.predecessor_identity().is_none()
                && projection.is_full_snapshot()
        })
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    if projection
        .mutations()
        .iter()
        .any(|mutation| !mutation.verify())
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    if projection.mutations().is_empty() {
        if !identity.is_canonical_empty() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
    } else if projection.mutations().len()
        != usize::try_from(identity.entry_count())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?
        || projection
            .mutations()
            .first()
            .is_none_or(|mutation| !mutation.predecessor_identity().is_canonical_empty())
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let state_id = metadata_state_id(head_token);
    if let Some(stored) = metadata_state_in_txn(tx, id, &state_id)? {
        if stored.identity != *identity
            || stored.predecessor_state_id.is_some()
            || stored.transition_id != head_token
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let stored_deltas = metadata_state_deltas_in_txn(tx, id, &state_id)?;
        if stored_deltas.len() != projection.mutations().len() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        for (delta, mutation) in stored_deltas.iter().zip(projection.mutations()) {
            let cell = mutation
                .successor()
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
            if !mutation.verify()
                || mutation.predecessor().is_some()
                || delta.key != mutation.key()
                || delta.key_route.as_slice() != mutation.key_route()
                || delta.predecessor_exact_value_digest.is_some()
                || delta.successor_exact_value_digest.as_deref()
                    != Some(cell.identity().exact_value_digest().as_str())
            {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            let stored_cell = metadata_cell_in_txn(
                tx,
                id,
                mutation.key(),
                cell.identity().exact_value_digest().as_str(),
            )?
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
            if stored_cell.identity() != cell.identity()
                || stored_cell.key_route() != cell.key_route()
                || stored_cell.canonical_json() != cell.canonical_json()
            {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
        }
        let lineage = tx
            .query_row(
                r"
                SELECT transition_id, predecessor_head_cas_token,
                       predecessor_state_id, successor_state_id
                FROM session_head_metadata_head_lineage
                WHERE session_id = ?1 AND successor_head_cas_token = ?2
                ",
                params![id.to_string(), head_token],
                |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, Option<String>>(1)?,
                        row.get::<_, Option<String>>(2)?,
                        row.get::<_, String>(3)?,
                    ))
                },
            )
            .optional()
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if lineage.0 != head_token
            || lineage.1.is_some()
            || lineage.2.is_some()
            || lineage.3 != state_id
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        return Ok(state_id);
    }
    insert_metadata_state_in_txn(tx, id, &state_id, None, identity, head_token)?;
    for (ordinal, mutation) in projection.mutations().iter().enumerate() {
        if mutation.predecessor().is_some() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let cell = mutation
            .successor()
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        persist_metadata_cell_in_txn(tx, id, cell)?;
        persist_metadata_state_delta_in_txn(tx, id, &state_id, ordinal, mutation)?;
    }
    insert_metadata_lineage_in_txn(tx, id, head_token, None, head_token, None, &state_id)?;
    Ok(state_id)
}

fn delete_unreferenced_metadata_cell_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    key: &str,
    exact_value_digest: &str,
) -> Result<(), SessionStoreError> {
    tx.execute(
        r"
        DELETE FROM session_head_metadata_cells
        WHERE session_id = ?1
          AND metadata_key = ?2
          AND exact_value_digest = ?3
          AND NOT EXISTS (
              SELECT 1 FROM session_head_metadata_current AS current
              WHERE current.session_id = ?1
                AND current.metadata_key = ?2
                AND current.exact_value_digest = ?3
          )
          AND NOT EXISTS (
              SELECT 1 FROM session_head_metadata_state_deltas AS delta
              WHERE delta.session_id = ?1
                AND delta.metadata_key = ?2
                AND (
                    delta.predecessor_exact_value_digest = ?3
                    OR delta.successor_exact_value_digest = ?3
                )
          )
        ",
        params![id.to_string(), key, exact_value_digest],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    Ok(())
}

/// Bound retained metadata history after RuntimeStore and the physical head
/// converge on the same exact state.
///
/// Keep the current state plus its direct predecessor/delta as the latest
/// exact-retry witness. Rebase that predecessor to a root, remove its now-false
/// historical lineage plus every older state/delta/lineage row, then
/// point-delete cell versions no longer named by current state or the retained
/// witness. Work is proportional to the since-boundary metadata chain, never
/// to the accumulated session lifetime.
fn prune_converged_metadata_history_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    retired_runtime_state: Option<&str>,
) -> Result<(), SessionStoreError> {
    let physical = metadata_owner_ref_in_txn(tx, id, HeadMetadataProjectionOwner::PhysicalHead)?
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let runtime = metadata_owner_ref_in_txn(tx, id, HeadMetadataProjectionOwner::RuntimeBoundary)?;
    if runtime
        .as_ref()
        .is_some_and(|runtime| runtime.state_id != physical.state_id)
    {
        return Ok(());
    }

    let physical_state = metadata_state_in_txn(tx, id, &physical.state_id)?
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let retained_predecessor = physical_state.predecessor_state_id;
    let mut delete_states = Vec::new();
    let mut candidates = BTreeSet::new();
    let mut cursor = match retained_predecessor.as_deref() {
        Some(state_id) => {
            metadata_state_in_txn(tx, id, state_id)?
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?
                .predecessor_state_id
        }
        None => None,
    };
    let mut visited = BTreeSet::new();
    while let Some(state_id) = cursor {
        if !visited.insert(state_id.clone()) {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let state = metadata_state_in_txn(tx, id, &state_id)?
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        for delta in metadata_state_deltas_in_txn(tx, id, &state_id)? {
            if let Some(digest) = delta.predecessor_exact_value_digest {
                candidates.insert((delta.key.clone(), digest));
            }
            if let Some(digest) = delta.successor_exact_value_digest {
                candidates.insert((delta.key, digest));
            }
        }
        cursor = state.predecessor_state_id.clone();
        delete_states.push(state_id);
    }
    if let Some(state_id) = retired_runtime_state
        && state_id != physical.state_id
        && retained_predecessor.as_deref() != Some(state_id)
        && !delete_states.iter().any(|existing| existing == state_id)
    {
        let state = metadata_state_in_txn(tx, id, state_id)?
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if state.predecessor_state_id.is_some() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        for delta in metadata_state_deltas_in_txn(tx, id, state_id)? {
            if let Some(digest) = delta.predecessor_exact_value_digest {
                candidates.insert((delta.key.clone(), digest));
            }
            if let Some(digest) = delta.successor_exact_value_digest {
                candidates.insert((delta.key, digest));
            }
        }
        delete_states.push(state_id.to_string());
    }

    if let Some(predecessor_state_id) = retained_predecessor.as_deref() {
        for delta in metadata_state_deltas_in_txn(tx, id, predecessor_state_id)? {
            if let Some(digest) = delta.predecessor_exact_value_digest {
                candidates.insert((delta.key.clone(), digest));
            }
            if let Some(digest) = delta.successor_exact_value_digest {
                candidates.insert((delta.key, digest));
            }
        }
        tx.execute(
            r"
            DELETE FROM session_head_metadata_state_deltas
            WHERE session_id = ?1 AND state_id = ?2
            ",
            params![id.to_string(), predecessor_state_id],
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
        tx.execute(
            r"
            UPDATE session_head_metadata_states
            SET predecessor_state_id = NULL
            WHERE session_id = ?1 AND state_id = ?2
            ",
            params![id.to_string(), predecessor_state_id],
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
        tx.execute(
            r"
            DELETE FROM session_head_metadata_head_lineage
            WHERE session_id = ?1 AND successor_state_id = ?2
            ",
            params![id.to_string(), predecessor_state_id],
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    }
    for state_id in &delete_states {
        tx.execute(
            r"
            DELETE FROM session_head_metadata_state_deltas
            WHERE session_id = ?1 AND state_id = ?2
            ",
            params![id.to_string(), state_id],
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
        tx.execute(
            r"
            DELETE FROM session_head_metadata_head_lineage
            WHERE session_id = ?1 AND successor_state_id = ?2
            ",
            params![id.to_string(), state_id],
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
        tx.execute(
            r"
            DELETE FROM session_head_metadata_states
            WHERE session_id = ?1 AND state_id = ?2
            ",
            params![id.to_string(), state_id],
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    }
    for (key, digest) in candidates {
        delete_unreferenced_metadata_cell_in_txn(tx, id, &key, &digest)?;
    }
    Ok(())
}

/// Move the retained RuntimeStore boundary reference to `head`.
///
/// The runtime authority row and this reference update share one transaction.
/// Ordinary equal-state boundaries are a literal no-write path. Co-tenant
/// stores prune converged physical/runtime metadata history. An externally
/// paired RuntimeStore instead retains only its store-verified runtime snapshot
/// and must not require or invent a local physical-owner reference.
#[doc(hidden)]
pub fn retain_runtime_boundary_head_metadata_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<(), SessionStoreError> {
    let Some(identity) = head.metadata_identity() else {
        return Ok(());
    };
    let head_token = session_head_cas_token(head)?;
    let current =
        metadata_owner_ref_in_txn(tx, &head.id, HeadMetadataProjectionOwner::RuntimeBoundary)?;
    let mut state_id = metadata_state_for_head_in_txn(tx, head, &head_token)?;
    if state_id.is_none() {
        state_id = Some(persist_standalone_metadata_snapshot_in_txn(
            tx,
            head,
            &head_token,
        )?);
    }
    let state_id = state_id.ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    let state = metadata_state_in_txn(tx, &head.id, &state_id)?
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    if &state.identity != identity {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }
    if current
        .as_ref()
        .is_some_and(|current| current.state_id == state_id)
    {
        return Ok(());
    }
    let retired_runtime_state = current.as_ref().map(|current| current.state_id.as_str());
    move_metadata_owner_in_txn(
        tx,
        &head.id,
        HeadMetadataProjectionOwner::RuntimeBoundary,
        &head_token,
        &state_id,
    )?;
    if metadata_owner_ref_in_txn(tx, &head.id, HeadMetadataProjectionOwner::PhysicalHead)?.is_none()
    {
        return Ok(());
    }
    prune_converged_metadata_history_in_txn(tx, &head.id, retired_runtime_state)
}

/// Clear the retained runtime-boundary reference before deleting its
/// co-tenant authority row and prune history no longer needed by any owner.
#[doc(hidden)]
pub fn clear_runtime_boundary_head_metadata_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<(), SessionStoreError> {
    let retired = metadata_owner_ref_in_txn(tx, id, HeadMetadataProjectionOwner::RuntimeBoundary)?;
    tx.execute(
        "DELETE FROM session_head_metadata_refs WHERE session_id = ?1 AND owner = 'runtime_boundary'",
        params![id.to_string()],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    prune_converged_metadata_history_in_txn(
        tx,
        id,
        retired.as_ref().map(|retired| retired.state_id.as_str()),
    )
}

/// Write the head row and restore the row-materialization rule.
///
/// A strand-changing head write point-settles only the strand it just left as
/// a splice delta of the new head. Same-strand appends do no topology work;
/// whole-history reachability and orphan collection are explicit maintenance
/// concerns.
fn write_head_row_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<String, SessionStoreError> {
    if head.metadata_identity().is_some() {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: head.id.clone(),
            reason: "authenticated HeadCanonical metadata may only advance through a sealed \
                     prepared mutation"
                .to_string(),
        });
    }
    let previous_strand = head_row_in_txn(tx, &head.id)?.map(|(stored, _)| stored.strand);
    let cas_token = write_head_row_only_in_txn(tx, head)?;
    settle_strand_topology_in_txn(tx, head, previous_strand.as_ref())?;
    Ok(cas_token)
}

fn write_head_row_only_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<String, SessionStoreError> {
    let cas_token = session_head_cas_token(head)?;
    // `SessionHead` skips the Arc carrier: runtime authority and ordinary CAS
    // rows remain bounded regardless of accumulated user/config metadata.
    let head_json = serde_json::to_vec(head).map_err(SessionStoreError::from)?;
    let metadata_json = serde_json::to_string(&head.metadata).map_err(SessionStoreError::from)?;
    let message_count = i64::try_from(head.message_count).map_err(|_| {
        SessionStoreError::Internal(format!(
            "session '{}' head message_count {} exceeds durable i64 range",
            head.id, head.message_count
        ))
    })?;
    let rewrite_count = i64::try_from(head.rewrite_count).map_err(|_| {
        SessionStoreError::Internal(format!(
            "session '{}' head rewrite_count {} exceeds durable i64 range",
            head.id, head.rewrite_count
        ))
    })?;
    let total_tokens = i64::try_from(head.usage.total_tokens()).map_err(|_| {
        SessionStoreError::Internal(format!(
            "session '{}' head total_tokens {} exceeds durable i64 range",
            head.id,
            head.usage.total_tokens()
        ))
    })?;
    tx.execute(
        r"
        INSERT INTO session_heads (
            session_id, version, strand, head_revision, message_count,
            rewrite_count, total_tokens, created_at_ms, updated_at_ms,
            metadata_json, head_json, cas_token
        ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
        ON CONFLICT(session_id) DO UPDATE SET
            version = excluded.version,
            strand = excluded.strand,
            head_revision = excluded.head_revision,
            message_count = excluded.message_count,
            rewrite_count = excluded.rewrite_count,
            total_tokens = excluded.total_tokens,
            created_at_ms = excluded.created_at_ms,
            updated_at_ms = excluded.updated_at_ms,
            metadata_json = excluded.metadata_json,
            head_json = excluded.head_json,
            cas_token = excluded.cas_token
        ",
        params![
            head.id.to_string(),
            i64::from(head.version),
            head.strand.as_str(),
            head.head_revision,
            message_count,
            rewrite_count,
            total_tokens,
            system_time_millis(head.created_at),
            system_time_millis(head.updated_at),
            metadata_json,
            head_json,
            cas_token,
        ],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    Ok(cas_token)
}

/// Rows a strand physically owns. For a materialized strand this is its
/// logical length; for a superseded one it is only the splice span, so read
/// paths must use [`strand_logical_len_in_txn`] instead.
fn materialized_row_count_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
) -> Result<u64, SessionStoreError> {
    let count: i64 = tx
        .query_row(
            "SELECT COUNT(*) FROM session_strand_messages WHERE session_id = ?1 AND strand = ?2",
            params![id.to_string(), strand.as_str()],
            |row| row.get(0),
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    u64::try_from(count).map_err(|_| SessionStoreError::Corrupted(id.clone()))
}

/// Whether an exact strand key owns any physical row.
///
/// Prepared rewrite occurrence ids must be empty before their immutable link
/// is installed. A LIMIT-1 probe keeps that conflict check independent of the
/// number of stray/corrupt rows at the key.
fn strand_has_physical_rows_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
) -> Result<bool, SessionStoreError> {
    tx.query_row(
        "SELECT 1 FROM session_strand_messages
         WHERE session_id = ?1 AND strand = ?2
         LIMIT 1",
        params![id.to_string(), strand.as_str()],
        |_row| Ok(()),
    )
    .optional()
    .map(|row| row.is_some())
    .map_err(StoreError::from)
    .map_err(into_session_store_error)
}

/// One past the highest physical row sequence on a strand.
///
/// Linked rewrite strands are sparse: they own the replacement span inside
/// the link's base length and may later own an ordinary appended tail beyond
/// that base. `COUNT(*)` cannot describe that logical extent.
fn physical_row_extent_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
) -> Result<u64, SessionStoreError> {
    let max_seq: Option<i64> = tx
        .query_row(
            "SELECT MAX(seq) FROM session_strand_messages WHERE session_id = ?1 AND strand = ?2",
            params![id.to_string(), strand.as_str()],
            |row| row.get(0),
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    match max_seq {
        Some(seq) => u64::try_from(seq)
            .ok()
            .and_then(|seq| seq.checked_add(1))
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone())),
        None => Ok(0),
    }
}

// ---------------------------------------------------------------------------
// Bounded active overlays and periodically settled materialized anchors.
// ---------------------------------------------------------------------------

/// One persisted supersession edge.
#[derive(Debug, Clone)]
struct StrandLinkRow {
    successor: TranscriptStrandId,
    splice: StrandSplice,
}

/// Supersession edges keyed by superseded strand.
///
/// Ordinary materialization populates this map only from bounded point reads
/// reachable from the store-issued anchor/head. Explicit audit and maintenance
/// may still load the complete historical map.
type StrandLinks = std::collections::HashMap<String, StrandLinkRow>;

/// Point-read one immutable strand descriptor.
///
/// Ordinary prepared rewrites name every descriptor they may create or
/// observe. The hot apply/retry path must therefore read those exact keys
/// instead of loading and validating the session's accumulated topology.
/// Full topology validation remains part of explicit activation, rewrite
/// audit, and doctor/maintenance surfaces.
fn strand_link_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
) -> Result<Option<StrandLinkRow>, SessionStoreError> {
    let row = tx
        .query_row(
            "SELECT successor, strand_len, splice_start, splice_end, successor_end
             FROM session_strand_links
             WHERE session_id = ?1 AND strand = ?2",
            params![id.to_string(), strand.as_str()],
            |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, i64>(1)?,
                    row.get::<_, i64>(2)?,
                    row.get::<_, i64>(3)?,
                    row.get::<_, i64>(4)?,
                ))
            },
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let Some((successor, strand_len, splice_start, splice_end, successor_end)) = row else {
        return Ok(None);
    };
    let corrupt = || SessionStoreError::Corrupted(id.clone());
    let splice = StrandSplice {
        strand_len: u64::try_from(strand_len).map_err(|_| corrupt())?,
        splice_start: u64::try_from(splice_start).map_err(|_| corrupt())?,
        splice_end: u64::try_from(splice_end).map_err(|_| corrupt())?,
        successor_end: u64::try_from(successor_end).map_err(|_| corrupt())?,
    };
    if !splice.is_well_formed() {
        return Err(corrupt());
    }
    Ok(Some(StrandLinkRow {
        successor: TranscriptStrandId::from_persisted(successor),
        splice,
    }))
}

/// Load only topology reachable from the named roots, refusing any path whose
/// active depth exceeds the store-issued budget.
///
/// This is the ordinary read primitive. Historical links not reachable from
/// the current anchor/head are deliberately invisible here; whole-graph
/// validation remains an explicit audit/maintenance operation.
fn bounded_strand_links_for_roots_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    roots: &[TranscriptStrandId],
    max_hops_per_root: usize,
) -> Result<StrandLinks, SessionStoreError> {
    let mut links = StrandLinks::new();
    let mut verified_to_terminal = std::collections::HashSet::new();
    for root in roots {
        let mut cursor = root.clone();
        let mut path = std::collections::HashSet::new();
        let mut hops = 0_usize;
        loop {
            if verified_to_terminal.contains(cursor.as_str()) {
                break;
            }
            if !path.insert(cursor.as_str().to_string()) {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            let link = match links.get(cursor.as_str()) {
                Some(link) => Some(link.clone()),
                None => strand_link_in_txn(tx, id, &cursor)?,
            };
            let Some(link) = link else {
                break;
            };
            if hops == max_hops_per_root {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            hops = hops
                .checked_add(1)
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
            let successor = link.successor.clone();
            if let Some(existing) = links.insert(cursor.as_str().to_string(), link)
                && existing.successor != successor
            {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            cursor = successor;
        }
        verified_to_terminal.extend(path);
    }
    Ok(links)
}

fn ordinary_topology_hop_budget(
    head: &SessionHead,
    additional_rewrites: usize,
) -> Result<usize, SessionStoreError> {
    let anchor = head
        .row_lineage_anchor
        .as_ref()
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    let post_anchor = head
        .rewrite_count
        .checked_sub(anchor.rewrite_count())
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    usize::try_from(post_anchor)
        .ok()
        .and_then(|post_anchor| {
            usize::try_from(SESSION_ROW_LINEAGE_REBASE_INTERVAL)
                .ok()
                .and_then(|interval| interval.checked_add(post_anchor))
        })
        .and_then(|budget| budget.checked_add(additional_rewrites))
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))
}

fn reconcile_exact_strand_link_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    successor: &TranscriptStrandId,
    splice: StrandSplice,
) -> Result<(), SessionStoreError> {
    if strand == successor || !splice.is_well_formed() {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    if let Some(existing) = strand_link_in_txn(tx, id, strand)? {
        if existing.successor == *successor && existing.splice == splice {
            return Ok(());
        }
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    if strand_has_physical_rows_in_txn(tx, id, strand)? {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    tx.execute(
        "INSERT INTO session_strand_links
             (session_id, strand, successor, strand_len, splice_start, splice_end,
              successor_end, created_at_ms)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
        params![
            id.to_string(),
            strand.as_str(),
            successor.as_str(),
            i64::try_from(splice.strand_len)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            i64::try_from(splice.splice_start)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            i64::try_from(splice.splice_end)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            i64::try_from(splice.successor_end)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            now_millis(),
        ],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    Ok(())
}

/// Validate the session's functional strand graph once and return every
/// strand named as an edge target.
///
/// Specialized multi-rewrite catch-up carries this result across all pending
/// occurrences. Reloading or re-walking the full retained graph for each
/// occurrence would turn a `k`-rewrite recovery into O(k²) topology work.
fn validate_strand_links_acyclic(
    id: &SessionId,
    links: &StrandLinks,
) -> Result<std::collections::HashSet<String>, SessionStoreError> {
    let linked_successors = links
        .values()
        .map(|link| link.successor.as_str().to_string())
        .collect::<std::collections::HashSet<_>>();
    let mut settled = std::collections::HashSet::with_capacity(links.len());
    for start in links.keys() {
        if settled.contains(start) {
            continue;
        }
        let mut path = std::collections::HashSet::new();
        let mut cursor = start.as_str();
        while let Some(link) = links.get(cursor) {
            if settled.contains(cursor) {
                break;
            }
            if !path.insert(cursor.to_string()) {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            cursor = link.successor.as_str();
        }
        settled.extend(path);
    }
    Ok(linked_successors)
}

fn strand_links_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<StrandLinks, SessionStoreError> {
    let mut stmt = tx
        .prepare(
            "SELECT strand, successor, strand_len, splice_start, splice_end, successor_end
             FROM session_strand_links WHERE session_id = ?1",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let rows = stmt
        .query_map(params![id.to_string()], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, i64>(2)?,
                row.get::<_, i64>(3)?,
                row.get::<_, i64>(4)?,
                row.get::<_, i64>(5)?,
            ))
        })
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let mut links = StrandLinks::with_capacity(rows.len());
    for (strand, successor, strand_len, splice_start, splice_end, successor_end) in rows {
        let corrupt = || SessionStoreError::Corrupted(id.clone());
        let splice = StrandSplice {
            strand_len: u64::try_from(strand_len).map_err(|_| corrupt())?,
            splice_start: u64::try_from(splice_start).map_err(|_| corrupt())?,
            splice_end: u64::try_from(splice_end).map_err(|_| corrupt())?,
            successor_end: u64::try_from(successor_end).map_err(|_| corrupt())?,
        };
        // A malformed durable descriptor could silently serve the wrong
        // rows; refuse it instead (terminal-truth store-metadata cluster).
        if !splice.is_well_formed() {
            return Err(corrupt());
        }
        links.insert(
            strand,
            StrandLinkRow {
                successor: TranscriptStrandId::from_persisted(successor),
                splice,
            },
        );
    }
    Ok(links)
}

/// Logical row count of a strand: the link's recorded length for a
/// superseded strand, the physical count for a materialized one.
fn strand_logical_len_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    links: &StrandLinks,
) -> Result<u64, SessionStoreError> {
    match links.get(strand.as_str()) {
        Some(link) => Ok(link
            .splice
            .strand_len
            .max(physical_row_extent_in_txn(tx, id, strand)?)),
        None => materialized_row_count_in_txn(tx, id, strand),
    }
}

/// Serve a strand's logical rows, following supersession edges for the runs
/// the strand no longer owns.
fn resolve_strand_bytes_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    range: std::ops::Range<u64>,
    links: &StrandLinks,
) -> Result<Vec<Vec<u8>>, SessionStoreError> {
    // A chain cannot legally revisit a strand, so the edge count bounds the
    // hops; exceeding it means the durable edges cycle.
    resolve_strand_bytes_hops(tx, id, strand, range, links, links.len())
}

fn resolve_strand_bytes_hops(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    range: std::ops::Range<u64>,
    links: &StrandLinks,
    hops: usize,
) -> Result<Vec<Vec<u8>>, SessionStoreError> {
    let Some(link) = links.get(strand.as_str()) else {
        return strand_row_bytes_in_txn(tx, id, strand, range);
    };
    let logical_len = link
        .splice
        .strand_len
        .max(physical_row_extent_in_txn(tx, id, strand)?);
    if hops == 0 || range.start > range.end || range.end > logical_len {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let wanted = usize::try_from(range.end - range.start)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let mut rows = Vec::with_capacity(wanted);
    let linked_end = range.end.min(link.splice.strand_len);
    if range.start < linked_end {
        for segment in link.splice.segments(range.start..linked_end) {
            match segment {
                StrandSegment::Retained(span) => {
                    rows.extend(strand_row_bytes_in_txn(tx, id, strand, span)?);
                }
                StrandSegment::Successor(span) => {
                    rows.extend(resolve_strand_bytes_hops(
                        tx,
                        id,
                        &link.successor,
                        span,
                        links,
                        hops - 1,
                    )?);
                }
            }
        }
    }
    let tail_start = range.start.max(link.splice.strand_len);
    if tail_start < range.end {
        rows.extend(strand_row_bytes_in_txn(
            tx,
            id,
            strand,
            tail_start..range.end,
        )?);
    }
    if rows.len() != wanted {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(rows)
}

/// Settle one bounded active overlay into exact direct rows.
///
/// The caller must derive `links` either from a store-issued head/anchor
/// budget or from an explicit one-time migration audit. The full logical bytes
/// are resolved before the edge is retired, missing direct rows are reconciled
/// byte-for-byte, and the resulting strand is then a singular O(document)
/// cold-read authority. Historical inbound links remain valid because the
/// strand id and bytes do not change.
fn settle_resolved_strand_direct_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    logical_len: u64,
    links: &StrandLinks,
) -> Result<Vec<Vec<u8>>, SessionStoreError> {
    let serialized_rows = resolve_strand_bytes_in_txn(tx, id, strand, 0..logical_len, links)?;
    if physical_row_extent_in_txn(tx, id, strand)? > logical_len {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    reconcile_serialized_strand_rows_in_txn(tx, id, strand, 0, &serialized_rows)?;
    if links.contains_key(strand.as_str()) {
        let removed = tx
            .execute(
                "DELETE FROM session_strand_links WHERE session_id = ?1 AND strand = ?2",
                params![id.to_string(), strand.as_str()],
            )
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?;
        if removed != 1 {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
    }
    if materialized_row_count_in_txn(tx, id, strand)? != logical_len
        || physical_row_extent_in_txn(tx, id, strand)? != logical_len
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(serialized_rows)
}

/// Re-encode `strand` as the splice delta of `successor`, deleting the rows
/// the successor reproduces byte-for-byte.
///
/// The splice is derived by comparing the two persisted row vectors, so the
/// edge can never claim sharing that does not exist; a splice that shares
/// nothing (a full-transcript compaction) records the edge and keeps every
/// row. The refusals — already superseded, empty, self, or an edge that
/// would close a cycle — leave the strand materialized: correctness never
/// depends on supersession having run, only durable size does.
fn supersede_strand_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    successor: &TranscriptStrandId,
) -> Result<(), SessionStoreError> {
    if strand == successor {
        return Ok(());
    }
    if strand_link_in_txn(tx, id, strand)?.is_some() {
        return Ok(());
    }
    let hop_budget = usize::try_from(SESSION_ROW_LINEAGE_REBASE_INTERVAL)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let links =
        bounded_strand_links_for_roots_in_txn(tx, id, std::slice::from_ref(successor), hop_budget)?;
    // Refuse an edge whose successor already resolves back through `strand`:
    // a cycle would make both strands unreadable.
    let mut cursor: &str = successor.as_str();
    for _ in 0..=links.len() {
        if cursor == strand.as_str() {
            return Ok(());
        }
        let Some(next) = links.get(cursor) else {
            break;
        };
        cursor = next.successor.as_str();
    }

    let strand_len = materialized_row_count_in_txn(tx, id, strand)?;
    if strand_len == 0 {
        return Ok(());
    }
    let strand_rows = strand_row_bytes_in_txn(tx, id, strand, 0..strand_len)?;
    let successor_len = strand_logical_len_in_txn(tx, id, successor, &links)?;
    let successor_rows = resolve_strand_bytes_in_txn(tx, id, successor, 0..successor_len, &links)?;
    let splice = StrandSplice::between(&strand_rows, &successor_rows);
    // The edge is recorded even when nothing is shared (a full-transcript
    // compaction retains its whole parent by definition): the link is what
    // makes supersession idempotent, so later writes never recompute an
    // O(transcript) comparison that already settled.
    let to_i64 =
        |value: u64| i64::try_from(value).map_err(|_| SessionStoreError::Corrupted(id.clone()));
    let durable_strand_len = to_i64(splice.strand_len)?;
    let durable_splice_start = to_i64(splice.splice_start)?;
    let durable_splice_end = to_i64(splice.splice_end)?;
    let durable_successor_end = to_i64(splice.successor_end)?;
    tx.execute(
        "INSERT OR REPLACE INTO session_strand_links
             (session_id, strand, successor, strand_len, splice_start, splice_end,
              successor_end, created_at_ms)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
        params![
            id.to_string(),
            strand.as_str(),
            successor.as_str(),
            durable_strand_len,
            durable_splice_start,
            durable_splice_end,
            durable_successor_end,
            now_millis(),
        ],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    tx.execute(
        "DELETE FROM session_strand_messages
         WHERE session_id = ?1 AND strand = ?2 AND (seq < ?3 OR seq >= ?4)",
        params![
            id.to_string(),
            strand.as_str(),
            durable_splice_start,
            durable_splice_end,
        ],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    Ok(())
}

/// Settle only the strand transition named by an ordinary head write.
///
/// Whole-history reachability and orphan collection are maintenance concerns;
/// neither belongs on the append/save path.
fn settle_strand_topology_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
    previous_strand: Option<&TranscriptStrandId>,
) -> Result<(), SessionStoreError> {
    let id = &head.id;
    if let Some(previous) = previous_strand
        && previous != &head.strand
    {
        // The head transition names the only newly inactive strand. Point
        // settle that exact edge; historical reachability collection belongs
        // to explicit maintenance and must not tax an ordinary head write.
        if head.rewrite_count == 0 {
            // With no rewrite rows, no historical authority can name the old
            // strand. Delete that exact key instead of retaining a useless
            // overlay edge or scanning an empty-history reachability graph.
            for sql in [
                "DELETE FROM session_strand_messages WHERE session_id = ?1 AND strand = ?2",
                "DELETE FROM session_strand_links WHERE session_id = ?1 AND strand = ?2",
            ] {
                tx.execute(sql, params![id.to_string(), previous.as_str()])
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
            }
        } else {
            supersede_strand_in_txn(tx, id, previous, &head.strand)?;
        }
    }
    Ok(())
}

fn strand_row_bytes_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    range: std::ops::Range<u64>,
) -> Result<Vec<Vec<u8>>, SessionStoreError> {
    if range.start >= range.end {
        return Ok(Vec::new());
    }
    let start = i64::try_from(range.start).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let end = i64::try_from(range.end).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let mut stmt = tx
        .prepare(
            "SELECT message_json FROM session_strand_messages
             WHERE session_id = ?1 AND strand = ?2 AND seq >= ?3 AND seq < ?4
             ORDER BY seq ASC",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let rows = stmt
        .query_map(
            params![id.to_string(), strand.as_str(), start, end],
            |row| Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes()),
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let expected = range.end - range.start;
    if rows.len() as u64 != expected {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(rows)
}

/// A strand's logical messages, following exact overlay edges. Every read path
/// goes through here: a linked strand owns only its splice span and direct
/// append tail.
fn strand_messages_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    range: std::ops::Range<u64>,
) -> Result<Vec<Message>, SessionStoreError> {
    Ok(strand_messages_with_bounded_topology_in_txn(tx, id, strand, range)?.0)
}

fn strand_messages_with_bounded_topology_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    range: std::ops::Range<u64>,
) -> Result<(Vec<Message>, usize), SessionStoreError> {
    let (head, stored_token) =
        head_row_in_txn(tx, id)?.ok_or_else(|| SessionStoreError::NotFound(id.clone()))?;
    if session_head_cas_token(&head)? != stored_token {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let hop_budget = ordinary_topology_hop_budget(&head, 0)?;
    let links =
        bounded_strand_links_for_roots_in_txn(tx, id, std::slice::from_ref(strand), hop_budget)?;
    let loaded_link_rows = links.len();
    let messages = strand_messages_with_links_in_txn(tx, id, strand, range, &links)?;
    Ok((messages, loaded_link_rows))
}

fn strand_messages_with_links_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    range: std::ops::Range<u64>,
    links: &StrandLinks,
) -> Result<Vec<Message>, SessionStoreError> {
    resolve_strand_bytes_in_txn(tx, id, strand, range, links)?
        .into_iter()
        .map(|bytes| {
            serde_json::from_slice::<Message>(&bytes)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))
        })
        .collect()
}

/// Append rows with the trait's contiguity/idempotency contract: base_seq
/// must not exceed the current row count; overlapping rows must be
/// byte-identical; shrink is structurally inexpressible.
fn insert_strand_rows_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    base_seq: u64,
    messages: &[Message],
) -> Result<(), SessionStoreError> {
    let hop_budget = usize::try_from(SESSION_ROW_LINEAGE_REBASE_INTERVAL)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let links =
        bounded_strand_links_for_roots_in_txn(tx, id, std::slice::from_ref(strand), hop_budget)?;
    if let Some(link) = links.get(strand.as_str()) {
        // A superseded strand is history: its rows live as a splice of its
        // successor and are immutable. Re-writing the identical bytes stays
        // idempotent (crash-retry); extending or diverging is exactly the
        // continuity violation the append contract names.
        let serialized: Vec<Vec<u8>> = messages
            .iter()
            .map(|message| serde_json::to_vec(message).map_err(SessionStoreError::from))
            .collect::<Result<_, _>>()?;
        let end = base_seq.saturating_add(serialized.len() as u64);
        let divergence = |detail: String| SessionStoreError::TranscriptContinuityViolation {
            id: id.clone(),
            previous_revision: format!("superseded-strand:{strand}"),
            incoming_revision: format!("append-base-seq:{base_seq}"),
            reason: detail,
        };
        if end > link.splice.strand_len {
            return Err(divergence(format!(
                "append would extend strand {strand}, which was superseded by {} at \
                 {} rows",
                link.successor, link.splice.strand_len
            )));
        }
        let stored = resolve_strand_bytes_in_txn(tx, id, strand, base_seq..end, &links)?;
        if stored != serialized {
            return Err(divergence(format!(
                "append would overwrite superseded strand {strand} with different bytes"
            )));
        }
        return Ok(());
    }
    let existing = materialized_row_count_in_txn(tx, id, strand)?;
    if base_seq > existing {
        return Err(SessionStoreError::TranscriptContinuityViolation {
            id: id.clone(),
            previous_revision: format!("strand-rows:{existing}"),
            incoming_revision: format!("append-base-seq:{base_seq}"),
            reason: format!(
                "append at base_seq {base_seq} would leave a gap in strand {strand} with {existing} rows"
            ),
        });
    }
    let serialized: Vec<Vec<u8>> = messages
        .iter()
        .map(|message| serde_json::to_vec(message).map_err(SessionStoreError::from))
        .collect::<Result<_, _>>()?;
    let overlap_end = existing.min(base_seq + serialized.len() as u64);
    if overlap_end > base_seq {
        let stored = strand_row_bytes_in_txn(tx, id, strand, base_seq..overlap_end)?;
        for (offset, stored_bytes) in stored.iter().enumerate() {
            if stored_bytes != &serialized[offset] {
                return Err(SessionStoreError::TranscriptContinuityViolation {
                    id: id.clone(),
                    previous_revision: format!("strand:{strand} seq:{}", base_seq + offset as u64),
                    incoming_revision: "divergent-bytes".to_string(),
                    reason: format!(
                        "append would overwrite immutable row (strand {strand}, seq {}) with different bytes",
                        base_seq + offset as u64
                    ),
                });
            }
        }
    }
    let created_at_ms = now_millis();
    for (offset, bytes) in serialized.iter().enumerate() {
        let seq = base_seq + offset as u64;
        if seq < existing {
            continue;
        }
        let seq_i64 = i64::try_from(seq).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        tx.execute(
            "INSERT INTO session_strand_messages (session_id, strand, seq, message_json, created_at_ms)
             VALUES (?1, ?2, ?3, ?4, ?5)",
            params![id.to_string(), strand.as_str(), seq_i64, bytes, created_at_ms],
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    }
    Ok(())
}

fn rewrite_row_count_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<u64, SessionStoreError> {
    let count: i64 = tx
        .query_row(
            "SELECT COUNT(*) FROM session_rewrites WHERE session_id = ?1",
            params![id.to_string()],
            |row| row.get(0),
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    u64::try_from(count).map_err(|_| SessionStoreError::Corrupted(id.clone()))
}

struct RewriteRow {
    commit: TranscriptRewriteCommit,
    parent_strand: TranscriptStrandId,
    parent_len: u64,
    strand: TranscriptStrandId,
    strand_len: u64,
    /// Strict current compact-edge wire. Released 0.8.10 rows predate this
    /// column and remain `None` before the head's explicit lineage anchor.
    graph_edge_json: Option<Vec<u8>>,
}

/// Adopted rewrite rows (`rewrite_idx < max_idx_exclusive`), oldest first.
fn rewrite_rows_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    max_idx_exclusive: u64,
) -> Result<Vec<RewriteRow>, SessionStoreError> {
    let limit =
        i64::try_from(max_idx_exclusive).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    rewrite_rows_up_to_in_txn(tx, id, Some(limit))
}

/// Exact persisted rewrite tail `[min_idx_inclusive, max_idx_exclusive)`.
///
/// Activation uses this one-time read to prove that the physical head's
/// rewrite authority is an exact descendant of the frozen runtime boundary.
/// Returning the stored indices prevents a corrupt/gapped table from being
/// mistaken for a contiguous accumulator tail.
fn indexed_rewrite_rows_range_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    min_idx_inclusive: u64,
    max_idx_exclusive: u64,
) -> Result<Vec<(u64, RewriteRow)>, SessionStoreError> {
    let min_idx =
        i64::try_from(min_idx_inclusive).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let max_idx =
        i64::try_from(max_idx_exclusive).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let mut stmt = tx
        .prepare(
            "SELECT rewrite_idx, commit_json, parent_strand, parent_len, strand, strand_len,
                    graph_edge_json
             FROM session_rewrites
             WHERE session_id = ?1 AND rewrite_idx >= ?2 AND rewrite_idx < ?3
             ORDER BY rewrite_idx ASC",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let rows = stmt
        .query_map(params![id.to_string(), min_idx, max_idx], |row| {
            Ok((
                row.get::<_, i64>(0)?,
                row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                row.get::<_, String>(2)?,
                row.get::<_, i64>(3)?,
                row.get::<_, String>(4)?,
                row.get::<_, i64>(5)?,
                row.get::<_, Option<JsonColumnBytes>>(6)?
                    .map(JsonColumnBytes::into_bytes),
            ))
        })
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    rows.into_iter()
        .map(
            |(
                rewrite_idx,
                commit_json,
                parent_strand,
                parent_len,
                strand,
                strand_len,
                graph_edge_json,
            )| {
                let rewrite_idx = u64::try_from(rewrite_idx)
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
                let commit: TranscriptRewriteCommit = serde_json::from_slice(&commit_json)
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
                Ok((
                    rewrite_idx,
                    RewriteRow {
                        commit,
                        parent_strand: TranscriptStrandId::from_persisted(parent_strand),
                        parent_len: u64::try_from(parent_len)
                            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                        strand: TranscriptStrandId::from_persisted(strand),
                        strand_len: u64::try_from(strand_len)
                            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                        graph_edge_json,
                    },
                ))
            },
        )
        .collect()
}

/// Prove that `descendant` extends `ancestor` by the exact persisted rewrite
/// occurrence rows between their generation counters.
#[doc(hidden)]
pub fn verify_head_rewrite_prefix_descent_in_txn(
    tx: &Transaction<'_>,
    ancestor: &SessionHead,
    descendant: &SessionHead,
) -> Result<(), SessionStoreError> {
    if ancestor.id != descendant.id || ancestor.rewrite_count > descendant.rewrite_count {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: descendant.id.clone(),
            reason: "rewrite-prefix descent heads are unrelated or reversed".to_string(),
        });
    }
    let indexed = indexed_rewrite_rows_range_in_txn(
        tx,
        &descendant.id,
        ancestor.rewrite_count,
        descendant.rewrite_count,
    )?;
    let mut prefix = ancestor.rewrite_prefix.clone();
    for (offset, (stored_idx, row)) in indexed.iter().enumerate() {
        let expected_idx = ancestor
            .rewrite_count
            .checked_add(
                u64::try_from(offset)
                    .map_err(|_| SessionStoreError::Corrupted(descendant.id.clone()))?,
            )
            .ok_or_else(|| SessionStoreError::Corrupted(descendant.id.clone()))?;
        if *stored_idx != expected_idx {
            return Err(SessionStoreError::Corrupted(descendant.id.clone()));
        }
        prefix = prefix
            .extend(&row.commit)
            .map_err(SessionStoreError::from)?;
    }
    if prefix != descendant.rewrite_prefix {
        return Err(SessionStoreError::TranscriptContinuityViolation {
            id: descendant.id.clone(),
            previous_revision: ancestor.rewrite_prefix.digest().to_string(),
            incoming_revision: descendant.rewrite_prefix.digest().to_string(),
            reason: "persisted rewrite rows do not bridge runtime and physical prefix authority"
                .to_string(),
        });
    }
    Ok(())
}

fn rewrite_rows_up_to_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    limit: Option<i64>,
) -> Result<Vec<RewriteRow>, SessionStoreError> {
    let mut stmt = tx
        .prepare(
            "SELECT commit_json, parent_strand, parent_len, strand, strand_len,
                    graph_edge_json
             FROM session_rewrites
             WHERE session_id = ?1 AND (?2 IS NULL OR rewrite_idx < ?2)
             ORDER BY rewrite_idx ASC",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let rows = stmt
        .query_map(params![id.to_string(), limit], |row| {
            Ok((
                row.get::<_, JsonColumnBytes>(0)?.into_bytes(),
                row.get::<_, String>(1)?,
                row.get::<_, i64>(2)?,
                row.get::<_, String>(3)?,
                row.get::<_, i64>(4)?,
                row.get::<_, Option<JsonColumnBytes>>(5)?
                    .map(JsonColumnBytes::into_bytes),
            ))
        })
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    rows.into_iter()
        .map(
            |(commit_json, parent_strand, parent_len, strand, strand_len, graph_edge_json)| {
                let commit: TranscriptRewriteCommit = serde_json::from_slice(&commit_json)
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
                Ok(RewriteRow {
                    commit,
                    parent_strand: TranscriptStrandId::from_persisted(parent_strand),
                    parent_len: u64::try_from(parent_len)
                        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                    strand: TranscriptStrandId::from_persisted(strand),
                    strand_len: u64::try_from(strand_len)
                        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                    graph_edge_json,
                })
            },
        )
        .collect()
}

fn insert_rewrite_row_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    rewrite_idx: u64,
    row: &RewriteRow,
) -> Result<(), SessionStoreError> {
    let commit_json = serde_json::to_vec(&row.commit).map_err(SessionStoreError::from)?;
    let idx = i64::try_from(rewrite_idx).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let parent_len =
        i64::try_from(row.parent_len).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let strand_len =
        i64::try_from(row.strand_len).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let graph_edge_json = row
        .graph_edge_json
        .as_deref()
        .ok_or_else(|| legacy_head_canonical_rewrite_error(id))?;
    // Replacing an unadopted row abandons its child strand outright — a full
    // transcript of rows that no verb can reach once the row that named them
    // is gone. Collect them here rather than waiting for a head write.
    let superseded_child: Option<String> = tx
        .query_row(
            "SELECT strand FROM session_rewrites WHERE session_id = ?1 AND rewrite_idx = ?2",
            params![id.to_string(), idx],
            |existing| existing.get::<_, String>(0),
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .filter(|existing| existing != row.strand.as_str());
    tx.execute(
        "INSERT OR REPLACE INTO session_rewrites
             (session_id, rewrite_idx, parent_strand, parent_len, strand, strand_len,
              commit_json, graph_edge_json, created_at_ms)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
        params![
            id.to_string(),
            idx,
            row.parent_strand.as_str(),
            parent_len,
            row.strand.as_str(),
            strand_len,
            commit_json,
            graph_edge_json,
            now_millis(),
        ],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    if let Some(abandoned) = superseded_child {
        let still_referenced: i64 = tx
            .query_row(
                "SELECT (SELECT COUNT(*) FROM session_rewrites
                          WHERE session_id = ?1 AND (parent_strand = ?2 OR strand = ?2))
                      + (SELECT COUNT(*) FROM session_heads
                          WHERE session_id = ?1 AND strand = ?2)
                      + (SELECT COUNT(*) FROM session_strand_links
                          WHERE session_id = ?1 AND successor = ?2)",
                params![id.to_string(), abandoned],
                |row| row.get(0),
            )
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?;
        if still_referenced == 0 {
            for sql in [
                "DELETE FROM session_strand_messages WHERE session_id = ?1 AND strand = ?2",
                "DELETE FROM session_strand_links WHERE session_id = ?1 AND strand = ?2",
            ] {
                tx.execute(sql, params![id.to_string(), abandoned])
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
            }
        }
    }
    Ok(())
}

/// Exact current compact-edge bytes proved by the Session's validated graph.
///
/// Released 0.8.10 WholeBlob ingress validates and normalizes the graph before
/// this store seam runs. The store additionally binds every compact edge to
/// the exact ordered rewrite-prefix authority installed by that importer.
fn validated_graph_edge_bytes_for_session(
    session: &Session,
    expected_rewrite_prefix: &TranscriptRewritePrefixAccumulator,
) -> Result<Vec<Vec<u8>>, SessionStoreError> {
    let history = session
        .validated_transcript_history_state()
        .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
            id: session.id().clone(),
            reason: format!(
                "rewrite-edge migration requires validated compact transcript history: {error}"
            ),
        })?;
    let actual_count = history
        .as_ref()
        .map_or(0, |history| history.state().commit_count());
    if u64::try_from(actual_count).ok() != Some(expected_rewrite_prefix.occurrence_count()) {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: session.id().clone(),
            reason: format!(
                "validated graph carries {actual_count} rewrites but the imported rewrite prefix carries {}",
                expected_rewrite_prefix.occurrence_count()
            ),
        });
    }
    let Some(history) = history else {
        if expected_rewrite_prefix != &TranscriptRewritePrefixAccumulator::empty() {
            return Err(SessionStoreError::Corrupted(session.id().clone()));
        }
        return Ok(Vec::new());
    };
    let mut prefix = TranscriptRewritePrefixAccumulator::empty();
    let mut edges = Vec::with_capacity(actual_count);
    for (index, edge) in history.state().edges().iter().enumerate() {
        let expected_generation = u64::try_from(index)
            .ok()
            .and_then(|index| index.checked_add(1))
            .ok_or_else(|| SessionStoreError::Corrupted(session.id().clone()))?;
        prefix = prefix
            .extend(edge.commit())
            .map_err(SessionStoreError::from)?;
        if edge.rewrite_generation() != expected_generation || edge.rewrite_prefix() != &prefix {
            return Err(SessionStoreError::Corrupted(session.id().clone()));
        }
        let bytes = edge.to_replay_bytes().map_err(SessionStoreError::from)?;
        let decoded =
            TranscriptRevisionEdge::from_replay_bytes(&bytes).map_err(SessionStoreError::from)?;
        if &decoded != edge.as_ref() {
            return Err(SessionStoreError::Corrupted(session.id().clone()));
        }
        edges.push(bytes);
    }
    if &prefix != expected_rewrite_prefix {
        return Err(SessionStoreError::Corrupted(session.id().clone()));
    }
    Ok(edges)
}

/// Fill the per-occurrence compact edge column from a validated
/// Session. This runs only in the explicit 0.8.10/WholeBlob conversion
/// transaction; ordinary current writes require the bytes to exist already.
fn backfill_rewrite_graph_edges_from_validated_session_in_txn(
    tx: &Transaction<'_>,
    session: &Session,
    expected_rewrite_prefix: &TranscriptRewritePrefixAccumulator,
) -> Result<(), SessionStoreError> {
    let id = session.id();
    let expected_rewrite_count = expected_rewrite_prefix.occurrence_count();
    let edges = validated_graph_edge_bytes_for_session(session, expected_rewrite_prefix)?;
    let history = session
        .validated_transcript_history_state()
        .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
            id: id.clone(),
            reason: format!(
                "rewrite-edge migration requires validated compact transcript history: {error}"
            ),
        })?;
    let layout = strand_layout_for_history(session, history.as_ref())?;
    let rows = indexed_rewrite_rows_range_in_txn(tx, id, 0, expected_rewrite_count)?;
    if rows.len() != edges.len() || rows.len() != layout.rewrites.len() {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let mut expected_layout_source = layout.anchor_strand.clone();
    let mut expected_source_len = u64::try_from(layout.serialized_anchor.len())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let mut expected_released_source = TranscriptStrandId::root();
    for (offset, (((rewrite_idx, row), edge_bytes), expected)) in
        rows.iter().zip(&edges).zip(&layout.rewrites).enumerate()
    {
        let expected_idx =
            u64::try_from(offset).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let edge = TranscriptRevisionEdge::from_replay_bytes(edge_bytes)
            .map_err(SessionStoreError::from)?;
        let layout_edge = validate_blob_rewrite_layout(
            id,
            offset,
            &expected_layout_source,
            expected_source_len,
            expected,
        )?;
        let expected_generation = expected_idx
            .checked_add(1)
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if row.commit.rewrite_generation != 0 {
            // Only the released 0.8.10 writer omitted occurrence
            // generations and graph-edge bytes. A current-looking row with
            // a missing edge has no authorized migration provenance.
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let normalized_commit = expected.commit.clone();
        let expected_parent_len = expected
            .parent_base_seq
            .checked_add(
                u64::try_from(expected.serialized_parent_suffix.len())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            )
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        // Released 0.8.10 HeadCanonical rows predate occurrence-scoped
        // strand identities. Exact-append parents reused the preceding
        // revision/root id, non-append parents used rebase:{digest}, and
        // children used the revision digest itself. Validate that released
        // physical vocabulary here; current compact migrations never enter
        // this backfill because their edge bytes are written atomically.
        let expected_released_parent = if edge.parent_advance().exact_splice().is_some() {
            TranscriptStrandId::rebase(&row.commit.parent_revision)
        } else {
            expected_released_source.clone()
        };
        let expected_released_child = TranscriptStrandId::from_rewrite(&row.commit);
        if *rewrite_idx != expected_idx
            || normalized_commit.rewrite_generation != expected_generation
            || normalized_commit != *edge.commit()
            || edge != layout_edge
            || normalized_commit != expected.commit
            || row.parent_strand != expected_released_parent
            || row.parent_len != expected_parent_len
            || row.strand != expected_released_child
            || row.strand_len != expected.link_splice.strand_len
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        if row.commit != normalized_commit {
            let commit_json =
                serde_json::to_vec(&normalized_commit).map_err(SessionStoreError::from)?;
            let changed = tx
                .execute(
                    "UPDATE session_rewrites
                     SET commit_json = ?3
                     WHERE session_id = ?1 AND rewrite_idx = ?2",
                    params![
                        id.to_string(),
                        i64::try_from(*rewrite_idx)
                            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                        commit_json,
                    ],
                )
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            if changed != 1 {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
        }
        match row.graph_edge_json.as_deref() {
            Some(stored) if stored == edge_bytes.as_slice() => {}
            Some(_) => return Err(SessionStoreError::Corrupted(id.clone())),
            None => {
                let changed = tx
                    .execute(
                        "UPDATE session_rewrites
                         SET graph_edge_json = ?3
                         WHERE session_id = ?1 AND rewrite_idx = ?2
                           AND graph_edge_json IS NULL",
                        params![
                            id.to_string(),
                            i64::try_from(*rewrite_idx)
                                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                            edge_bytes,
                        ],
                    )
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
                if changed != 1 {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
            }
        }
        expected_layout_source = expected.strand.clone();
        expected_released_source = expected_released_child;
        expected_source_len = expected.link_splice.strand_len;
    }
    Ok(())
}

fn post_anchor_rewrite_graph_edge_is_missing_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    start_rewrite_count: u64,
    end_rewrite_count: u64,
) -> Result<bool, SessionStoreError> {
    let start_rewrite_count =
        i64::try_from(start_rewrite_count).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let end_rewrite_count =
        i64::try_from(end_rewrite_count).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    tx.query_row(
        "SELECT 1 FROM session_rewrites
         WHERE session_id = ?1 AND rewrite_idx >= ?2 AND rewrite_idx < ?3
           AND graph_edge_json IS NULL
         LIMIT 1",
        params![id.to_string(), start_rewrite_count, end_rewrite_count],
        |_row| Ok(()),
    )
    .optional()
    .map(|row| row.is_some())
    .map_err(StoreError::from)
    .map_err(into_session_store_error)
}

fn validate_blob_parent_splice(
    id: &SessionId,
    parent_splice: &PreparedHeadCanonicalParentSplice,
    expected_source: &TranscriptStrandId,
    expected_bridge: &TranscriptStrandId,
    observed_bridge: &TranscriptStrandId,
    expected_source_len: u64,
) -> Result<(), SessionStoreError> {
    let splice = parent_splice.link_splice();
    let replacement_len = u64::try_from(parent_splice.serialized_replacement().len())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    if parent_splice.source_strand() != expected_source
        || observed_bridge != expected_bridge
        || observed_bridge == expected_source
        || replacement_len == 0
        || !splice.is_well_formed()
        || splice.strand_len != expected_source_len
        || splice.splice_end != splice.successor_end
        || splice.successor_len() != expected_source_len
        || splice.retained_rows() != replacement_len
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(())
}

fn validate_blob_rewrite_layout(
    id: &SessionId,
    rewrite_index: usize,
    expected_source: &TranscriptStrandId,
    expected_source_len: u64,
    rewrite: &StrandRewriteLayout,
) -> Result<TranscriptRevisionEdge, SessionStoreError> {
    let expected_generation = u64::try_from(rewrite_index)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?
        .checked_add(1)
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let edge = TranscriptRevisionEdge::from_replay_bytes(&rewrite.serialized_graph_edge)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let canonical_edge = edge.to_replay_bytes().map_err(SessionStoreError::from)?;
    let parent_suffix =
        serialized_messages_for_lineage_replay(id, edge.parent_advance().appended())?;
    let replacement = serialized_messages_for_lineage_replay(id, edge.rewrite().replacement())?;
    let messages_before_base = u64::try_from(edge.messages_before_base())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let messages_before = u64::try_from(edge.messages_before())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let messages_after = u64::try_from(edge.messages_after())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let (selection_start, selection_end) = rewrite.commit.selection.bounds();
    let selection_start =
        u64::try_from(selection_start).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let selection_end =
        u64::try_from(selection_end).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let replacement_len =
        u64::try_from(replacement.len()).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let expected_splice_end = selection_start
        .checked_add(replacement_len)
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let parent_len = rewrite
        .parent_base_seq
        .checked_add(
            u64::try_from(rewrite.serialized_parent_suffix.len())
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
        )
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let expected_child = TranscriptStrandId::from_rewrite_occurrence(&rewrite.commit);
    if canonical_edge != rewrite.serialized_graph_edge
        || edge.commit() != &rewrite.commit
        || edge.rewrite_generation() != expected_generation
        || rewrite.commit.rewrite_generation != expected_generation
        || messages_before_base != expected_source_len
        || rewrite.parent_base_seq != expected_source_len
        || parent_suffix != rewrite.serialized_parent_suffix
        || replacement != rewrite.serialized_replacement
        || parent_len != messages_before
        || rewrite.strand != expected_child
        || rewrite.strand == rewrite.parent_strand
        || !rewrite.link_splice.is_well_formed()
        || rewrite.link_splice.successor_len() != messages_before
        || rewrite.link_splice.strand_len != messages_after
        || rewrite.link_splice.splice_start != selection_start
        || rewrite.link_splice.splice_end != expected_splice_end
        || rewrite.link_splice.successor_end != selection_end
        || rewrite.link_splice.retained_rows() != replacement_len
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    match (
        &rewrite.parent_transition,
        edge.parent_advance().exact_splice(),
    ) {
        (PreparedHeadCanonicalParentTransition::ExactAppend, None) => {
            if rewrite.parent_strand != *expected_source {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
        }
        (
            PreparedHeadCanonicalParentTransition::ExactSplice(parent_splice),
            Some((at, replacement)),
        ) => {
            let expected_bridge =
                TranscriptStrandId::from_rewrite_parent_occurrence(&rewrite.commit);
            validate_blob_parent_splice(
                id,
                parent_splice,
                expected_source,
                &expected_bridge,
                &rewrite.parent_strand,
                expected_source_len,
            )?;
            let serialized = serialized_messages_for_lineage_replay(id, replacement)?;
            let splice = parent_splice.link_splice();
            let expected_start =
                u64::try_from(at).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
            let expected_end = expected_start
                .checked_add(
                    u64::try_from(replacement.len())
                        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                )
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
            if serialized != parent_splice.serialized_replacement()
                || splice.splice_start != expected_start
                || splice.splice_end != expected_end
            {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
        }
        _ => return Err(SessionStoreError::Corrupted(id.clone())),
    }
    Ok(edge)
}

fn layout_for_blob_session(
    session: &Session,
) -> Result<(StrandLayout, SessionHead), SessionStoreError> {
    let id = session.id();
    let history = session
        .validated_transcript_history_state()
        .map_err(|err| SessionStoreError::InvalidTranscriptRewrite {
            id: id.clone(),
            reason: format!("stored transcript history state is malformed: {err}"),
        })?;
    let layout = strand_layout_for_history(session, history.as_ref())?;
    if layout.anchor_strand != TranscriptStrandId::root()
        || layout.head_len
            != u64::try_from(session.messages().len())
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?
        || history
            .as_ref()
            .map_or(0, |proved| proved.state().commit_count())
            != layout.rewrites.len()
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let mut row_lineage =
        SessionMessageRowPrefixAccumulator::from_serialized_rows(&layout.serialized_anchor)?;
    let mut current_strand = layout.anchor_strand.clone();
    let mut current_count = u64::try_from(layout.serialized_anchor.len())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let mut rewrite_prefix = TranscriptRewritePrefixAccumulator::empty();
    for (index, rewrite) in layout.rewrites.iter().enumerate() {
        let edge =
            validate_blob_rewrite_layout(id, index, &current_strand, current_count, rewrite)?;
        match &rewrite.parent_transition {
            PreparedHeadCanonicalParentTransition::ExactAppend => {}
            PreparedHeadCanonicalParentTransition::ExactSplice(parent_splice) => {
                let splice = parent_splice.link_splice();
                row_lineage = row_lineage.replace_serialized_range(
                    splice.splice_start,
                    splice.splice_end,
                    parent_splice.serialized_replacement(),
                )?;
            }
        }
        row_lineage = row_lineage.extend_serialized_rows(&rewrite.serialized_parent_suffix)?;
        let parent_count = rewrite
            .parent_base_seq
            .checked_add(
                u64::try_from(rewrite.serialized_parent_suffix.len())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            )
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if parent_count != rewrite.link_splice.successor_len()
            || row_lineage != *edge.parent_row_prefix()
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        row_lineage = row_lineage.replace_serialized_range(
            rewrite.link_splice.splice_start,
            rewrite.link_splice.successor_end,
            &rewrite.serialized_replacement,
        )?;
        rewrite_prefix = rewrite_prefix
            .extend(&rewrite.commit)
            .map_err(SessionStoreError::from)?;
        if row_lineage.row_count() != rewrite.link_splice.strand_len
            || row_lineage != *edge.result_witness().row_prefix()
            || rewrite_prefix != *edge.rewrite_prefix()
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        current_strand = rewrite.strand.clone();
        current_count = rewrite.link_splice.strand_len;
    }
    if layout.tail_base_seq != current_count {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    if layout.head_strand != current_strand {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    row_lineage = row_lineage.extend_serialized_rows(&layout.serialized_tail)?;
    if row_lineage.row_count() != layout.head_len {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let proved_rewrite_prefix = session
        .transcript_rewrite_prefix_authority()
        .unwrap_or_else(TranscriptRewritePrefixAccumulator::empty);
    if proved_rewrite_prefix.occurrence_count()
        != u64::try_from(layout.rewrites.len())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?
        || proved_rewrite_prefix != rewrite_prefix
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let head = SessionHead::from_session_with_proved_inline_storage_authority(
        session,
        layout.head_strand.clone(),
        proved_rewrite_prefix,
        row_lineage,
    )?;
    Ok((layout, head))
}

fn persist_blob_strand_layout_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    layout: &StrandLayout,
) -> Result<(), SessionStoreError> {
    reconcile_serialized_strand_rows_in_txn(
        tx,
        id,
        &layout.anchor_strand,
        0,
        &layout.serialized_anchor,
    )?;
    let mut expected_source = layout.anchor_strand.clone();
    let mut expected_source_len = u64::try_from(layout.serialized_anchor.len())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    for (index, rewrite) in layout.rewrites.iter().enumerate() {
        if rewrite.parent_base_seq != expected_source_len {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        match &rewrite.parent_transition {
            PreparedHeadCanonicalParentTransition::ExactAppend => {
                if rewrite.parent_strand != expected_source {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
            }
            PreparedHeadCanonicalParentTransition::ExactSplice(parent_splice) => {
                if parent_splice.source_strand() != &expected_source
                    || rewrite.parent_strand
                        != TranscriptStrandId::from_rewrite_parent_occurrence(&rewrite.commit)
                {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
                reconcile_exact_strand_link_in_txn(
                    tx,
                    id,
                    &rewrite.parent_strand,
                    parent_splice.source_strand(),
                    parent_splice.link_splice(),
                )?;
                reconcile_serialized_strand_rows_in_txn(
                    tx,
                    id,
                    &rewrite.parent_strand,
                    parent_splice.link_splice().splice_start,
                    parent_splice.serialized_replacement(),
                )?;
            }
        }
        reconcile_serialized_strand_rows_in_txn(
            tx,
            id,
            &rewrite.parent_strand,
            rewrite.parent_base_seq,
            &rewrite.serialized_parent_suffix,
        )?;
        let parent_len = rewrite
            .parent_base_seq
            .checked_add(
                u64::try_from(rewrite.serialized_parent_suffix.len())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            )
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if parent_len != rewrite.link_splice.successor_len()
            || rewrite.link_splice.strand_len
                != u64::try_from(rewrite.commit.messages_after)
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?
            || rewrite.link_splice.retained_rows()
                != u64::try_from(rewrite.serialized_replacement.len())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        insert_rewrite_row_in_txn(
            tx,
            id,
            u64::try_from(index).map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            &RewriteRow {
                commit: rewrite.commit.clone(),
                parent_strand: rewrite.parent_strand.clone(),
                parent_len,
                strand: rewrite.strand.clone(),
                strand_len: rewrite.link_splice.strand_len,
                graph_edge_json: Some(rewrite.serialized_graph_edge.clone()),
            },
        )?;
        reconcile_exact_strand_link_in_txn(
            tx,
            id,
            &rewrite.strand,
            &rewrite.parent_strand,
            rewrite.link_splice,
        )?;
        reconcile_serialized_strand_rows_in_txn(
            tx,
            id,
            &rewrite.strand,
            rewrite.link_splice.splice_start,
            &rewrite.serialized_replacement,
        )?;
        expected_source = rewrite.strand.clone();
        expected_source_len = rewrite.link_splice.strand_len;
    }
    if layout.tail_base_seq != expected_source_len {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    if layout.head_strand != expected_source {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    reconcile_serialized_strand_rows_in_txn(
        tx,
        id,
        &layout.head_strand,
        layout.tail_base_seq,
        &layout.serialized_tail,
    )?;
    let final_count = layout
        .tail_base_seq
        .checked_add(
            u64::try_from(layout.serialized_tail.len())
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
        )
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    if final_count != layout.head_len {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(())
}

fn blob_strand_messages(
    session: &Session,
    layout: &StrandLayout,
    strand: &TranscriptStrandId,
) -> Result<Vec<Message>, SessionStoreError> {
    if strand == &layout.head_strand {
        return Ok(session.messages().to_vec());
    }
    let history = session
        .validated_transcript_history_state()
        .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
            id: session.id().clone(),
            reason: format!("stored transcript history state is malformed: {error}"),
        })?;
    let Some(history) = history else {
        return Err(SessionStoreError::Corrupted(session.id().clone()));
    };

    // A physical strand is extended only while it remains the exact parent
    // of the next occurrence. Prefer that maximal parent body over the
    // shorter child endpoint when both names address the same strand.
    if let Some(rewrite) = layout
        .rewrites
        .iter()
        .find(|rewrite| &rewrite.parent_strand == strand)
    {
        return history
            .materialize_rewrite_parent(&rewrite.commit)
            .map(|body| body.messages)
            .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
                id: session.id().clone(),
                reason: format!("failed to materialize blob rewrite parent: {error}"),
            });
    }
    if let Some(rewrite) = layout
        .rewrites
        .iter()
        .find(|rewrite| &rewrite.strand == strand)
    {
        return history
            .materialize_rewrite_child(&rewrite.commit)
            .map(|body| body.messages)
            .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
                id: session.id().clone(),
                reason: format!("failed to materialize blob rewrite child: {error}"),
            });
    }
    if strand == &layout.anchor_strand {
        return Ok(history.state().anchor().messages().to_vec());
    }
    Err(SessionStoreError::Corrupted(session.id().clone()))
}

fn activate_realtime_component_in_txn(
    tx: &Transaction<'_>,
    session: &mut Session,
) -> Result<(), SessionStoreError> {
    // Activation is a representation migration only. The typed component event
    // suffix and its derived root are the authority; the caller binds that root
    // into the upgraded SessionHead in this transaction.
    session
        .activate_realtime_component_sidecar()
        .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
            id: session.id().clone(),
            reason: format!("failed to activate realtime component: {error}"),
        })?;
    if let Some(suffix) = session
        .prepare_realtime_component_event_suffix()
        .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
            id: session.id().clone(),
            reason: format!("failed to seal activated realtime component: {error}"),
        })?
    {
        reconcile_prepared_component_suffix_in_txn(tx, &suffix)?;
    }
    Ok(())
}

/// One-time migration: lay out the legacy blob's strands and head inside the
/// caller's transaction. The blob row is left untouched as a frozen archive
/// and is never read again once the head row exists.
fn migrate_legacy_blob_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<Option<(SessionHead, String)>, SessionStoreError> {
    let Some(session) = load_session_snapshot_in_txn(tx, id).map_err(into_session_store_error)?
    else {
        return Ok(None);
    };
    let (layout, head) = layout_for_blob_session(&session)?;
    persist_blob_strand_layout_in_txn(tx, id, &layout)?;
    // Blob activation is the explicit one-time full-history path. Settle its
    // current store-issued anchor before publishing the canonical head so all
    // subsequent ordinary resumes start from direct rows regardless of how
    // many historical overlay edges the released blob contained.
    let links = strand_links_in_txn(tx, id)?;
    validate_strand_links_acyclic(id, &links)?;
    let settled =
        settle_resolved_strand_direct_in_txn(tx, id, &head.strand, head.message_count, &links)?;
    let expected = session
        .messages()
        .iter()
        .map(|message| serde_json::to_vec(message).map_err(SessionStoreError::from))
        .collect::<Result<Vec<_>, _>>()?;
    if settled != expected {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let token = write_head_row_only_in_txn(tx, &head)?;
    Ok(Some((head, token)))
}

/// Head row if present; otherwise migrate a legacy blob in this transaction
/// (the first incremental WRITE migrates; reads synthesize without writing).
fn ensure_head_canonical_for_write_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<Option<(SessionHead, String)>, SessionStoreError> {
    if let Some((head, stored_token)) = head_row_in_txn(tx, id)? {
        if session_head_cas_token(&head)? != stored_token {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let replay_start = head
            .row_lineage_anchor
            .as_ref()
            .map_or(0, |anchor| anchor.rewrite_count());
        let missing_graph_edge = post_anchor_rewrite_graph_edge_is_missing_in_txn(
            tx,
            id,
            replay_start,
            head.rewrite_count,
        )?;
        if head.message_row_prefix.is_some()
            && head.row_lineage_anchor.is_some()
            && !missing_graph_edge
        {
            return Ok(Some((head, stored_token)));
        }
        if head.realtime_event_prefix.is_some() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        if head.row_lineage_anchor.as_ref().is_some_and(|anchor| {
            anchor.rewrite_count() != head.rewrite_count
                || anchor.strand() != &head.strand
                || anchor.message_count() != head.message_count
        }) {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        // Released 0.8.10 canonical heads carried only the semantic transcript
        // digest, or no current replay anchor/compact edge column. Verify its
        // exact rows and validated compact graph, backfill every adopted edge,
        // and seed the current lineage anchor in this one transaction.
        let links = strand_links_in_txn(tx, id)?;
        validate_strand_links_acyclic(id, &links)?;
        let serialized_rows =
            resolve_strand_bytes_in_txn(tx, id, &head.strand, 0..head.message_count, &links)?;
        let session = head
            .clone()
            .into_session_from_serialized_rows(serialized_rows.clone())?;
        let proved_rewrite_prefix = session
            .transcript_rewrite_prefix_authority()
            .unwrap_or_else(TranscriptRewritePrefixAccumulator::empty);
        if proved_rewrite_prefix.occurrence_count() != head.rewrite_count
            || (head.rewrite_prefix.occurrence_count() == head.rewrite_count
                && head.rewrite_prefix != proved_rewrite_prefix)
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        backfill_rewrite_graph_edges_from_validated_session_in_txn(
            tx,
            &session,
            &proved_rewrite_prefix,
        )?;
        let exact_prefix =
            SessionMessageRowPrefixAccumulator::from_serialized_rows(&serialized_rows)?;
        let upgraded = SessionHead::from_session_with_proved_inline_storage_authority(
            &session,
            head.strand,
            proved_rewrite_prefix,
            exact_prefix,
        )?;
        let settled = settle_resolved_strand_direct_in_txn(
            tx,
            id,
            &upgraded.strand,
            upgraded.message_count,
            &links,
        )?;
        if settled != serialized_rows {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let upgraded_token = write_head_row_only_in_txn(tx, &upgraded)?;
        return Ok(Some((upgraded, upgraded_token)));
    }
    migrate_legacy_blob_in_txn(tx, id)
}

/// Read the exact physical canonical head and stored token in a co-tenant
/// runtime transaction, without materializing message rows.
///
/// The caller owns semantic/runtime-authority comparison. This seam only
/// ensures both facts come from the same transaction snapshot and never
/// synthesizes or migrates a missing head.
#[doc(hidden)]
pub fn load_head_canonical_for_runtime_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<Option<(SessionHead, String)>, SessionStoreError> {
    let current = head_row_in_txn(tx, id)?;
    if let Some((head, stored_token)) = current.as_ref()
        && session_head_cas_token(head)? != *stored_token
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    if let Some((head, _)) = current.as_ref()
        && head.message_row_prefix.is_none()
    {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: id.clone(),
            reason: "canonical head predates exact message-row authority; explicit conversion has not completed"
                .to_string(),
        });
    }
    if let Some((head, _)) = current.as_ref()
        && head.realtime_event_prefix.is_none()
    {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: id.clone(),
            reason:
                "canonical head predates the authenticated realtime component root; explicit activation has not completed"
                    .to_string(),
        });
    }
    Ok(current)
}

/// Attach the authenticated metadata projection to one exact current physical
/// head without materializing transcript rows.
///
/// RuntimeStore uses this bounded co-tenant seam when an idempotent retry must
/// re-prove its body-free catalog projection. The point check keeps a stale or
/// synthetic head from borrowing the physical metadata owner.
#[doc(hidden)]
pub fn materialize_physical_head_metadata_for_runtime_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<SessionHead, SessionStoreError> {
    let (current, stored_token) = head_row_in_txn(tx, &head.id)?
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    if &current != head || session_head_cas_token(head)? != stored_token {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }
    let mut materialized = head.clone();
    attach_head_metadata_projection(
        tx,
        &mut materialized,
        HeadMetadataProjectionOwner::PhysicalHead,
    )?;
    Ok(materialized)
}

/// Materialize one exact retained head inside a co-tenant recovery
/// transaction.
///
/// This exceptional seam may resolve and decode `O(document)` strand rows. It
/// exists only so recovery can re-prove a runtime-authorized predecessor head
/// after a newer physical head replaced it; ordinary commits must use the
/// bounded prepared-mutation helper instead.
#[doc(hidden)]
pub fn materialize_runtime_boundary_head_canonical_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<Session, SessionStoreError> {
    Ok(verify_runtime_boundary_head_canonical_in_txn(tx, head)?
        .session()
        .as_ref()
        .clone())
}

/// Materialize the current physical head for an explicit co-tenant runtime
/// check. The caller must separately bind it to the current head row/token in
/// the same transaction.
#[doc(hidden)]
pub fn materialize_physical_head_canonical_for_runtime_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<Session, SessionStoreError> {
    Ok(verify_physical_head_canonical_in_txn(tx, head)?
        .session()
        .as_ref()
        .clone())
}

/// Verify one retained runtime-boundary head against its exact metadata
/// owner reference plus the raw durable row/component vectors.
#[doc(hidden)]
pub fn verify_runtime_boundary_head_canonical_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<meerkat_core::VerifiedSessionHeadMaterialization, SessionStoreError> {
    verify_head_canonical_with_metadata_owner_in_txn(
        tx,
        head,
        HeadMetadataProjectionOwner::RuntimeBoundary,
    )
}

fn verify_physical_head_canonical_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<meerkat_core::VerifiedSessionHeadMaterialization, SessionStoreError> {
    verify_head_canonical_with_metadata_owner_in_txn(
        tx,
        head,
        HeadMetadataProjectionOwner::PhysicalHead,
    )
}

fn serialized_messages_for_lineage_replay(
    id: &SessionId,
    messages: &[Message],
) -> Result<Vec<Vec<u8>>, SessionStoreError> {
    messages
        .iter()
        .map(|message| {
            serde_json::to_vec(message).map_err(|error| {
                SessionStoreError::InvalidTranscriptRewrite {
                    id: id.clone(),
                    reason: format!(
                        "compact rewrite edge contains an unserializable message: {error}"
                    ),
                }
            })
        })
        .collect()
}

/// Verify that one linked strand owns exactly its replacement span plus the
/// direct append tail after the link's immutable endpoint.
///
/// A replacement-only strand is sparse, so `MAX(seq) + 1` may be far below
/// its logical message count. Once a non-empty tail exists, however, its last
/// row must be the logical tip. Keeping this distinction avoids rejecting a
/// healthy empty-tail rewrite while still detecting stray rows beyond a head.
fn verify_linked_strand_physical_shape_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    link: &StrandLinkRow,
    logical_count: u64,
) -> Result<(), SessionStoreError> {
    if logical_count < link.splice.strand_len {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let tail_len = logical_count
        .checked_sub(link.splice.strand_len)
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let expected_owned_rows = link
        .splice
        .retained_rows()
        .checked_add(tail_len)
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    if materialized_row_count_in_txn(tx, id, strand)? != expected_owned_rows {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let expected_extent = if tail_len > 0 {
        logical_count
    } else if link.splice.retained_rows() > 0 {
        link.splice.splice_end
    } else {
        0
    };
    if physical_row_extent_in_txn(tx, id, strand)? != expected_extent {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(())
}

fn head_has_current_row_lineage_anchor(head: &SessionHead) -> Result<bool, SessionStoreError> {
    let Some(anchor) = head.row_lineage_anchor.as_ref() else {
        return Ok(false);
    };
    let prefix = head
        .message_row_prefix
        .as_ref()
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    Ok(anchor.rewrite_count() == head.rewrite_count
        && anchor.strand() == &head.strand
        && anchor.message_count() == head.message_count
        && anchor.prefix() == prefix)
}

fn verify_direct_current_anchor_rows_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<(), SessionStoreError> {
    if !head_has_current_row_lineage_anchor(head)?
        || strand_link_in_txn(tx, &head.id, &head.strand)?.is_some()
        || materialized_row_count_in_txn(tx, &head.id, &head.strand)? != head.message_count
        || physical_row_extent_in_txn(tx, &head.id, &head.strand)? != head.message_count
    {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }
    let rows = strand_row_bytes_in_txn(tx, &head.id, &head.strand, 0..head.message_count)?;
    let observed = SessionMessageRowPrefixAccumulator::from_serialized_rows(&rows)?;
    let anchor = head
        .row_lineage_anchor
        .as_ref()
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    if observed != *anchor.materialized_prefix() {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }
    Ok(())
}

struct ReplayedHeadCanonicalRows {
    serialized_rows: Vec<Vec<u8>>,
    lineage: meerkat_core::session_store::VerifiedSessionRowLineageReplay,
    history: Option<VerifiedHeadCanonicalTranscriptHistory>,
    anchor_is_current: bool,
    #[cfg(test)]
    decoded_rewrite_count: u64,
    #[cfg(test)]
    loaded_link_row_count: usize,
}

/// Reconstruct the compact domain graph from the out-of-line edge rows owned
/// by HeadCanonical storage.
///
/// Current-head row replay remains bounded by its lineage anchor. History
/// restoration separately decodes each compact edge once and resolves only the
/// original graph anchor document, avoiding both EventStore authority and the
/// former `rewrites × document` body materialization.
fn replay_head_canonical_history_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
) -> Result<Option<VerifiedHeadCanonicalTranscriptHistory>, SessionStoreError> {
    let id = &head.id;
    if head.rewrite_count == 0 {
        if head.rewrite_prefix != TranscriptRewritePrefixAccumulator::empty()
            || head.graph_prefix.is_some()
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        return Ok(None);
    }
    let graph_prefix = head
        .graph_prefix
        .as_ref()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let indexed = indexed_rewrite_rows_range_in_txn(tx, id, 0, head.rewrite_count)?;
    if u64::try_from(indexed.len()).ok() != Some(head.rewrite_count) {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let mut rewrite_prefix = TranscriptRewritePrefixAccumulator::empty();
    let mut edges = Vec::with_capacity(indexed.len());
    for (offset, (rewrite_idx, row)) in indexed.iter().enumerate() {
        let expected_idx =
            u64::try_from(offset).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        if *rewrite_idx != expected_idx {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        rewrite_prefix = rewrite_prefix
            .extend(&row.commit)
            .map_err(SessionStoreError::from)?;
        let edge_bytes = row
            .graph_edge_json
            .as_deref()
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        let edge = TranscriptRevisionEdge::from_replay_bytes(edge_bytes)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let canonical = edge.to_replay_bytes().map_err(SessionStoreError::from)?;
        if canonical.as_slice() != edge_bytes
            || edge.commit() != &row.commit
            || edge.rewrite_generation()
                != expected_idx
                    .checked_add(1)
                    .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?
            || edge.rewrite_prefix() != &rewrite_prefix
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        edges.push(edge);
    }
    if rewrite_prefix != head.rewrite_prefix {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }

    let first_row = &indexed
        .first()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?
        .1;
    let first_edge = edges
        .first()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let mut topology_roots = Vec::with_capacity(
        indexed
            .len()
            .checked_mul(2)
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?,
    );
    for (_, row) in &indexed {
        topology_roots.push(row.parent_strand.clone());
        topology_roots.push(row.strand.clone());
    }
    let links = bounded_strand_links_for_roots_in_txn(
        tx,
        id,
        &topology_roots,
        ordinary_topology_hop_budget(head, 0)?,
    )?;
    let anchor_strand = if first_edge.parent_advance().exact_splice().is_some() {
        links
            .get(first_row.parent_strand.as_str())
            .map(|link| link.successor.clone())
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?
    } else {
        first_row.parent_strand.clone()
    };
    let anchor_count = u64::try_from(first_edge.messages_before_base())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let anchor_rows = resolve_strand_bytes_in_txn(tx, id, &anchor_strand, 0..anchor_count, &links)?;
    let anchor_prefix = SessionMessageRowPrefixAccumulator::from_serialized_rows(&anchor_rows)?;
    let anchor_messages = anchor_rows
        .iter()
        .map(|bytes| {
            serde_json::from_slice::<Message>(bytes)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let history = ValidatedTranscriptHistory::from_store_replayed_compact_graph(
        first_edge.base_revision().to_string(),
        anchor_messages,
        anchor_prefix,
        edges,
        &head.rewrite_prefix,
        graph_prefix,
    )
    .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
        id: id.clone(),
        reason: format!("failed to restore store-owned compact transcript graph: {error}"),
    })?;
    let endpoint_count = history
        .final_endpoint_row_prefix()
        .map(SessionMessageRowPrefixAccumulator::row_count)
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let last_strand = &indexed
        .last()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?
        .1
        .strand;
    if last_strand != &head.strand || endpoint_count > head.message_count {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let live_tail =
        strand_row_bytes_in_txn(tx, id, &head.strand, endpoint_count..head.message_count)?;
    let current = head
        .message_row_prefix
        .as_ref()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    VerifiedHeadCanonicalTranscriptHistory::bind_serialized_live_tail(history, &live_tail, current)
        .map(Some)
}

/// Cold-replay one head's exact operation lineage after its bounded anchor.
///
/// The anchor already binds the exact row and rewrite-prefix accumulators proved
/// before it. Ordinary materialization therefore resolves the anchor document
/// once and decodes only post-anchor rewrite edges; pre-anchor history belongs
/// to explicit audit/migration paths. The final logical document is resolved
/// once and semantic verification remains in core.
fn replay_head_canonical_rows_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
    owner: HeadMetadataProjectionOwner,
) -> Result<ReplayedHeadCanonicalRows, SessionStoreError> {
    let id = &head.id;
    let history = replay_head_canonical_history_in_txn(tx, head)?;
    let anchor = head.row_lineage_anchor.as_ref().ok_or_else(|| {
        SessionStoreError::InvalidTranscriptRewrite {
            id: id.clone(),
            reason: "current canonical head has no bounded row-lineage anchor".to_string(),
        }
    })?;
    let indexed =
        indexed_rewrite_rows_range_in_txn(tx, id, anchor.rewrite_count(), head.rewrite_count)?;
    let post_anchor_rewrite_count = head
        .rewrite_count
        .checked_sub(anchor.rewrite_count())
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    if u64::try_from(indexed.len()).ok() != Some(post_anchor_rewrite_count) {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let mut topology_roots = Vec::with_capacity(
        indexed
            .len()
            .checked_mul(2)
            .and_then(|count| count.checked_add(2))
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?,
    );
    topology_roots.push(anchor.strand().clone());
    topology_roots.push(head.strand.clone());
    for (_, row) in &indexed {
        topology_roots.push(row.parent_strand.clone());
        topology_roots.push(row.strand.clone());
    }
    let hop_budget = ordinary_topology_hop_budget(head, 0)?;
    let links = bounded_strand_links_for_roots_in_txn(tx, id, &topology_roots, hop_budget)?;
    let anchor_rows =
        resolve_strand_bytes_in_txn(tx, id, anchor.strand(), 0..anchor.message_count(), &links)?;
    let observed_anchor = SessionMessageRowPrefixAccumulator::from_serialized_rows(&anchor_rows)?;
    if &observed_anchor != anchor.materialized_prefix() {
        return Err(SessionStoreError::TranscriptContinuityViolation {
            id: id.clone(),
            previous_revision: anchor.materialized_prefix().digest().to_string(),
            incoming_revision: observed_anchor.digest().to_string(),
            reason: "physical anchor rows do not reproduce the sealed lineage origin".to_string(),
        });
    }
    let mut rewrite_prefix = anchor.rewrite_prefix().clone();
    let mut replay = head.begin_row_lineage_replay()?;
    let mut current_strand = anchor.strand().clone();
    let mut current_count = anchor.message_count();
    let mut final_replayed_endpoint = None;
    let mut decoded_rewrite_count = 0_u64;

    for (offset, (rewrite_idx, row)) in indexed.iter().enumerate() {
        let expected_idx = anchor
            .rewrite_count()
            .checked_add(
                u64::try_from(offset).map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            )
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if *rewrite_idx != expected_idx {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        rewrite_prefix = rewrite_prefix
            .extend(&row.commit)
            .map_err(SessionStoreError::from)?;
        let edge_bytes = row
            .graph_edge_json
            .as_deref()
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        let edge = TranscriptRevisionEdge::from_replay_bytes(edge_bytes)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        decoded_rewrite_count = decoded_rewrite_count
            .checked_add(1)
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        let canonical_edge_bytes = edge.to_replay_bytes().map_err(SessionStoreError::from)?;
        if canonical_edge_bytes.as_slice() != edge_bytes
            || edge.commit() != &row.commit
            || edge.rewrite_generation()
                != expected_idx
                    .checked_add(1)
                    .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?
            || edge.rewrite_prefix() != &rewrite_prefix
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let messages_before_base = u64::try_from(edge.messages_before_base())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let messages_before = u64::try_from(edge.messages_before())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let messages_after = u64::try_from(edge.messages_after())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        if messages_before_base < current_count
            || (offset > 0 && messages_before_base != current_count)
            || row.parent_len != messages_before
            || row.strand_len != messages_after
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }

        let appended =
            serialized_messages_for_lineage_replay(id, edge.parent_advance().appended())?;
        let base_bridge = strand_row_bytes_in_txn(
            tx,
            id,
            &row.parent_strand,
            current_count..messages_before_base,
        )?;
        let mut parent_suffix = base_bridge;
        parent_suffix.extend(appended);
        let parent_count = current_count
            .checked_add(
                u64::try_from(parent_suffix.len())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            )
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if parent_count != messages_before {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }

        if let Some((at, replacement_messages)) = edge.parent_advance().exact_splice() {
            let expected_bridge = TranscriptStrandId::from_rewrite_parent_occurrence(&row.commit);
            let bridge_link = links
                .get(row.parent_strand.as_str())
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
            let replacement = serialized_messages_for_lineage_replay(id, replacement_messages)?;
            let splice_start =
                u64::try_from(at).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
            let splice_end = splice_start
                .checked_add(
                    u64::try_from(replacement.len())
                        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                )
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
            if replacement.is_empty()
                || row.parent_strand != expected_bridge
                || bridge_link.successor != current_strand
                || !bridge_link.splice.is_well_formed()
                || bridge_link.splice.strand_len != current_count
                || bridge_link.splice.splice_start != splice_start
                || bridge_link.splice.splice_end != splice_end
                || bridge_link.splice.successor_end != splice_end
                || bridge_link.splice.successor_len() != current_count
                || bridge_link.splice.retained_rows()
                    != u64::try_from(replacement.len())
                        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?
            {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            verify_serialized_strand_rows_in_txn(
                tx,
                id,
                &row.parent_strand,
                splice_start,
                &replacement,
            )?;
            replay.replace_serialized_range(
                row.parent_strand.clone(),
                splice_start,
                splice_end,
                &replacement,
            )?;
        } else if row.parent_strand != current_strand {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        verify_serialized_strand_rows_in_txn(
            tx,
            id,
            &row.parent_strand,
            current_count,
            &parent_suffix,
        )?;
        replay.append_serialized_rows(&row.parent_strand, &parent_suffix)?;
        if let Some(parent_link) = links.get(row.parent_strand.as_str()) {
            verify_linked_strand_physical_shape_in_txn(
                tx,
                id,
                &row.parent_strand,
                parent_link,
                parent_count,
            )?;
        }

        let (selection_start, selection_end) = row.commit.selection.bounds();
        let selection_start =
            u64::try_from(selection_start).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let selection_end =
            u64::try_from(selection_end).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let rewrite_at = u64::try_from(edge.rewrite().at())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let replacement = serialized_messages_for_lineage_replay(id, edge.rewrite().replacement())?;
        let replacement_len = u64::try_from(replacement.len())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let child_link = links
            .get(row.strand.as_str())
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        let expected_child = TranscriptStrandId::from_rewrite_occurrence(&row.commit);
        if row.strand != expected_child
            || row.strand == row.parent_strand
            || rewrite_at != selection_start
            || child_link.successor != row.parent_strand
            || !child_link.splice.is_well_formed()
            || child_link.splice.strand_len != messages_after
            || child_link.splice.successor_len() != messages_before
            || child_link.splice.splice_start != selection_start
            || child_link.splice.successor_end != selection_end
            || child_link.splice.retained_rows() != replacement_len
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        verify_serialized_strand_rows_in_txn(
            tx,
            id,
            &row.strand,
            child_link.splice.splice_start,
            &replacement,
        )?;
        replay.apply_rewrite_edge(row.strand.clone(), &edge)?;
        current_strand = row.strand.clone();
        current_count = messages_after;
        final_replayed_endpoint = Some(messages_after);
    }

    if rewrite_prefix != head.rewrite_prefix
        || current_strand != head.strand
        || current_count > head.message_count
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let tail = strand_row_bytes_in_txn(tx, id, &head.strand, current_count..head.message_count)?;
    replay.append_serialized_rows(&head.strand, &tail)?;
    match links.get(head.strand.as_str()) {
        Some(link) => {
            if final_replayed_endpoint.is_some_and(|endpoint| link.splice.strand_len != endpoint) {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            if matches!(owner, HeadMetadataProjectionOwner::PhysicalHead) {
                verify_linked_strand_physical_shape_in_txn(
                    tx,
                    id,
                    &head.strand,
                    link,
                    head.message_count,
                )?;
            }
        }
        None => {
            if final_replayed_endpoint.is_some()
                || (matches!(owner, HeadMetadataProjectionOwner::PhysicalHead)
                    && (materialized_row_count_in_txn(tx, id, &head.strand)? != head.message_count
                        || physical_row_extent_in_txn(tx, id, &head.strand)? != head.message_count))
            {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
        }
    }
    let lineage = replay.finish(head)?;
    let anchor_is_current = head_has_current_row_lineage_anchor(head)?;
    let serialized_rows = if anchor_is_current {
        anchor_rows
    } else {
        resolve_strand_bytes_in_txn(tx, id, &head.strand, 0..head.message_count, &links)?
    };
    tracing::trace!(
        session_id = %id,
        pre_anchor_rewrite_count = anchor.rewrite_count(),
        decoded_rewrite_count,
        loaded_link_row_count = links.len(),
        "verified HeadCanonical rows from bounded lineage anchor"
    );
    Ok(ReplayedHeadCanonicalRows {
        serialized_rows,
        lineage,
        history,
        anchor_is_current,
        #[cfg(test)]
        decoded_rewrite_count,
        #[cfg(test)]
        loaded_link_row_count: links.len(),
    })
}

fn verify_head_canonical_with_metadata_owner_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
    owner: HeadMetadataProjectionOwner,
) -> Result<meerkat_core::VerifiedSessionHeadMaterialization, SessionStoreError> {
    let mut head = head.clone();
    attach_head_metadata_projection(tx, &mut head, owner)?;
    let ReplayedHeadCanonicalRows {
        serialized_rows,
        lineage,
        history,
        anchor_is_current,
        ..
    } = replay_head_canonical_rows_in_txn(tx, &head, owner)?;
    let verified = match head.realtime_event_prefix.as_ref() {
        Some(realtime) => {
            let realtime = load_verified_component_sequence_in_txn(tx, realtime)?;
            head.verify_serialized_rows_with_component_sequences_and_lineage(
                serialized_rows,
                realtime,
                lineage,
            )
        }
        None if head.rewrite_count == 0 && anchor_is_current => {
            head.verify_serialized_rows(serialized_rows)
        }
        None => head.verify_serialized_rows_with_lineage(serialized_rows, lineage),
    }?;
    verified.with_validated_transcript_history(history)
}

/// Independently replay the retained runtime boundary and physical head.
///
/// A rewrite may replace the middle of the transcript or shrink it, so the
/// boundary is not necessarily a flat prefix of the physical document.
/// Recovery instead proves both exact heads from their own anchors, proves the
/// physical rewrite occurrence prefix descends from the boundary, and then
/// installs the independently verified boundary row token on the physical
/// materialization for the runtime handoff.
#[doc(hidden)]
pub fn verify_physical_head_retains_boundary_prefix_for_runtime_in_txn(
    tx: &Transaction<'_>,
    boundary_head: &SessionHead,
    physical_head: &SessionHead,
) -> Result<meerkat_core::VerifiedSessionHeadMaterialization, SessionStoreError> {
    if boundary_head.id != physical_head.id
        || boundary_head.version != physical_head.version
        || boundary_head.created_at != physical_head.created_at
    {
        return Err(SessionStoreError::Corrupted(physical_head.id.clone()));
    }
    let expected_boundary_prefix = boundary_head.message_row_prefix.as_ref().ok_or_else(|| {
        SessionStoreError::InvalidTranscriptRewrite {
            id: boundary_head.id.clone(),
            reason: "runtime boundary has no exact message-row prefix authority".to_string(),
        }
    })?;
    verify_head_rewrite_prefix_descent_in_txn(tx, boundary_head, physical_head)?;
    let boundary = verify_head_canonical_with_metadata_owner_in_txn(
        tx,
        boundary_head,
        HeadMetadataProjectionOwner::RuntimeBoundary,
    )?;
    if boundary
        .exact_row_prefix_at(boundary_head.message_count)
        .as_ref()
        != Some(expected_boundary_prefix)
    {
        return Err(SessionStoreError::Corrupted(boundary_head.id.clone()));
    }
    let physical = verify_head_canonical_with_metadata_owner_in_txn(
        tx,
        physical_head,
        HeadMetadataProjectionOwner::PhysicalHead,
    )?;
    physical.with_verified_ancestor_row_prefix(expected_boundary_prefix.clone())
}

fn activation_boundary_strand_and_prove_rewrite_descent_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    boundary_rewrite_prefix: &TranscriptRewritePrefixAccumulator,
    physical_head: &SessionHead,
) -> Result<(TranscriptStrandId, u64), SessionStoreError> {
    if physical_head.rewrite_prefix.occurrence_count() != physical_head.rewrite_count {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: id.clone(),
            reason: format!(
                "physical head rewrite-prefix authority covers {} commits but rewrite_count is {}",
                physical_head.rewrite_prefix.occurrence_count(),
                physical_head.rewrite_count
            ),
        });
    }
    let boundary_rewrite_count = boundary_rewrite_prefix.occurrence_count();
    if boundary_rewrite_count > physical_head.rewrite_count {
        return Err(SessionStoreError::TranscriptContinuityViolation {
            id: id.clone(),
            previous_revision: boundary_rewrite_prefix.digest().to_string(),
            incoming_revision: physical_head.rewrite_prefix.digest().to_string(),
            reason: format!(
                "physical head rewrite generation {} precedes frozen runtime boundary generation {boundary_rewrite_count}",
                physical_head.rewrite_count
            ),
        });
    }

    let tail = indexed_rewrite_rows_range_in_txn(
        tx,
        id,
        boundary_rewrite_count,
        physical_head.rewrite_count,
    )?;
    let expected_tail_len = physical_head
        .rewrite_count
        .checked_sub(boundary_rewrite_count)
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    if u64::try_from(tail.len()).ok() != Some(expected_tail_len) {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }

    let mut observed_physical_prefix = boundary_rewrite_prefix.clone();
    for (offset, (rewrite_idx, row)) in tail.iter().enumerate() {
        let expected_idx = boundary_rewrite_count
            .checked_add(
                u64::try_from(offset).map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            )
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if *rewrite_idx != expected_idx {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        observed_physical_prefix = observed_physical_prefix
            .extend(&row.commit)
            .map_err(SessionStoreError::from)?;
    }
    if observed_physical_prefix != physical_head.rewrite_prefix {
        return Err(SessionStoreError::TranscriptContinuityViolation {
            id: id.clone(),
            previous_revision: boundary_rewrite_prefix.digest().to_string(),
            incoming_revision: physical_head.rewrite_prefix.digest().to_string(),
            reason:
                "physical head rewrite-prefix authority is not an exact descendant of the frozen runtime boundary"
                    .to_string(),
        });
    }

    // With no intervening rewrite, A is an ordinary message prefix of H's
    // live strand. With a rewrite tail, the first persisted edge owns the
    // exact pre-rewrite parent strand; that retained strand, not H's possibly
    // compacted live strand, is the row authority for A.
    Ok(match tail.first() {
        Some((_idx, first)) => (first.parent_strand.clone(), first.parent_len),
        None => (physical_head.strand.clone(), physical_head.message_count),
    })
}

/// Derive a retained runtime-boundary head from a verified frozen Session and
/// the exact retained rows proved by the current physical head's lineage.
///
/// Explicit WholeBlob-to-HeadCanonical activation uses this after canonical
/// session conversion, before ordinary service is admitted. The returned head
/// is not installed as the physical head: it is the small A authority retained
/// by RuntimeStore while H may already be a newer intra-turn append or rewrite.
#[doc(hidden)]
pub fn derive_runtime_boundary_head_for_activation_in_txn(
    tx: &Transaction<'_>,
    session: &Session,
    boundary_rewrite_prefix: &TranscriptRewritePrefixAccumulator,
    physical_head: &SessionHead,
) -> Result<SessionHead, SessionStoreError> {
    if session.id() != &physical_head.id
        || session.version() != physical_head.version
        || session.created_at() != physical_head.created_at
    {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: session.id().clone(),
            reason: "frozen runtime boundary does not share the physical head's immutable envelope"
                .to_string(),
        });
    }
    let boundary_count = session.messages().len() as u64;
    let (boundary_strand, retained_boundary_range) =
        activation_boundary_strand_and_prove_rewrite_descent_in_txn(
            tx,
            session.id(),
            boundary_rewrite_prefix,
            physical_head,
        )?;
    if boundary_count > retained_boundary_range {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: session.id().clone(),
            reason: format!(
                "frozen runtime boundary contains {boundary_count} messages but its retained physical strand covers only {retained_boundary_range}"
            ),
        });
    }
    let links = strand_links_in_txn(tx, session.id())?;
    validate_strand_links_acyclic(session.id(), &links)?;
    let serialized_prefix = resolve_strand_bytes_in_txn(
        tx,
        session.id(),
        &boundary_strand,
        0..boundary_count,
        &links,
    )?;
    let decoded_prefix = serialized_prefix
        .iter()
        .map(|bytes| {
            serde_json::from_slice::<Message>(bytes)
                .map_err(|_| SessionStoreError::Corrupted(session.id().clone()))
        })
        .collect::<Result<Vec<_>, _>>()?;
    if decoded_prefix.as_slice() != session.messages() {
        return Err(SessionStoreError::TranscriptContinuityViolation {
            id: session.id().clone(),
            previous_revision: session
                .transcript_content_digest()
                .map_err(SessionStoreError::from)?,
            incoming_revision: transcript_messages_digest(&decoded_prefix)
                .map_err(SessionStoreError::from)?,
            reason:
                "physical canonical rows do not retain the frozen runtime boundary's exact typed prefix"
                    .to_string(),
        });
    }
    let exact_prefix =
        SessionMessageRowPrefixAccumulator::from_serialized_rows(&serialized_prefix)?;
    SessionHead::from_session_with_proved_storage_authority(
        session,
        boundary_strand,
        boundary_rewrite_prefix.clone(),
        exact_prefix,
    )
}

/// One-time blob-to-head conversion seam for the co-tenant runtime store.
///
/// This is intentionally hidden from generated documentation: ordinary
/// head-canonical boundaries must call
/// [`apply_prepared_head_canonical_mutation_in_txn`] and remain bounded.
/// The runtime may call this only from its explicit activation transaction,
/// and the session store may call it from its ledgered authority crossing,
/// after fencing the exact current authority and proving the released 0.8.10
/// source head. It borrows the caller's transaction and neither opens nor
/// commits one.
#[doc(hidden)]
pub fn ensure_head_canonical_for_runtime_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<Option<(SessionHead, String)>, SessionStoreError> {
    let Some((head, token)) = ensure_head_canonical_for_write_in_txn(tx, id)? else {
        return Ok(None);
    };
    if head.realtime_event_prefix.is_some() {
        return Ok(Some((head, token)));
    }
    let mut session = verify_physical_head_canonical_in_txn(tx, &head)?
        .session()
        .as_ref()
        .clone();
    activate_realtime_component_in_txn(tx, &mut session)?;
    let message_row_prefix = head
        .message_row_prefix
        .clone()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let upgraded = SessionHead::from_session_with_proved_storage_authority(
        &session,
        head.strand.clone(),
        head.rewrite_prefix.clone(),
        message_row_prefix,
    )?;
    let upgraded_token = session_head_cas_token(&upgraded)?;
    reconcile_head_metadata_transition_in_txn(
        tx,
        Some(&head),
        Some(&token),
        &upgraded,
        &upgraded_token,
    )?;
    let upgraded_token = write_head_row_only_in_txn(tx, &upgraded)?;
    Ok(Some((upgraded, upgraded_token)))
}

/// Cross one persisted SQLite HeadCanonical representation and return the
/// trusted-backend authority assertion proved in this same transaction.
///
/// Classification observes both the compact head and the out-of-line rewrite
/// edges before conversion. The returned variant is constructed only after a
/// full replay of every row and sidecar named by the successor head. The caller
/// owns commit, so any verification or construction failure rolls the entire
/// crossing back.
fn cross_head_canonical_authority_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<HeadCanonicalAuthorityCrossing, SessionStoreError> {
    let source_was_current = match head_row_in_txn(tx, id)? {
        Some((source_head, source_token)) => {
            if source_head.id != *id || session_head_cas_token(&source_head)? != source_token {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            let replay_start = source_head
                .row_lineage_anchor
                .as_ref()
                .map_or(0, |anchor| anchor.rewrite_count());
            let missing_graph_edge = post_anchor_rewrite_graph_edge_is_missing_in_txn(
                tx,
                id,
                replay_start,
                source_head.rewrite_count,
            )?;
            source_head.message_row_prefix.is_some()
                && source_head.row_lineage_anchor.is_some()
                && source_head.realtime_event_prefix.is_some()
                && source_head.metadata_identity().is_some()
                && !missing_graph_edge
        }
        // A structurally current database may still contain a sparse legacy
        // blob row because v2 DDL did not backfill physical heads. Enter the
        // existing exact blob-to-head conversion seam before classifying the
        // identity as absent/not-applicable.
        None => false,
    };

    let Some((head, stored_token)) = ensure_head_canonical_for_runtime_in_txn(tx, id)? else {
        return Ok(HeadCanonicalAuthorityCrossing::NotApplicable);
    };
    let (published_head, published_token) =
        head_row_in_txn(tx, id)?.ok_or_else(|| SessionStoreError::NotFound(id.clone()))?;
    if head.id != *id
        || published_head.id != *id
        || published_token != stored_token
        || session_head_cas_token(&head)? != published_token
        || session_head_cas_token(&published_head)? != published_token
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let verified = verify_physical_head_canonical_in_txn(tx, &published_head)?;
    if source_was_current {
        HeadCanonicalAuthorityCrossing::already_current(verified, published_token)
    } else {
        HeadCanonicalAuthorityCrossing::converted(verified, published_token)
    }
}

fn activate_head_canonical_store_in_txn(
    tx: &Transaction<'_>,
) -> Result<HeadCanonicalStoreActivation, SessionStoreError> {
    let raw_ids = {
        let mut statement = tx
            .prepare(
                r"
                SELECT session_id FROM session_heads
                UNION
                SELECT session_id FROM sessions
                ORDER BY session_id ASC
                ",
            )
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?;
        let rows = statement
            .query_map([], |row| row.get::<_, String>(0))
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?;
        rows.collect::<Result<Vec<_>, _>>()
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?
    };
    let mut crossings = Vec::with_capacity(raw_ids.len());
    for raw_id in raw_ids {
        let id = parse_session_id(raw_id).map_err(into_session_store_error)?;
        let crossing = cross_head_canonical_authority_in_txn(tx, &id)?;
        if matches!(crossing, HeadCanonicalAuthorityCrossing::NotApplicable) {
            return Err(SessionStoreError::InvalidTranscriptRewrite {
                id,
                reason: "physical session cannot cross into HeadCanonical authority".to_string(),
            });
        }
        crossings.push(crossing);
    }
    Ok(HeadCanonicalStoreActivation::Activated(crossings))
}

/// Result of applying one sealed ordinary head-canonical mutation.
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeadCanonicalMutationApplyOutcome {
    /// The exact predecessor was current and the mutation was installed.
    Applied,
    /// The exact successor was already current; no rows were written.
    AlreadyApplied,
}

fn prepared_head_conflict(
    mutation: &PreparedHeadCanonicalMutation,
    actual: impl Into<String>,
) -> SessionStoreError {
    let expected = match mutation.predecessor_head_token() {
        Some(token) => token.to_string(),
        None => "absent canonical head".to_string(),
    };
    SessionStoreError::TranscriptRevisionConflict {
        id: mutation.session_id().clone(),
        expected,
        actual: actual.into(),
    }
}

fn point_check_materialized_append_boundary_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalMutation,
) -> Result<(), SessionStoreError> {
    let id = mutation.session_id();
    let strand = mutation.strand();
    let base_seq = mutation.base_seq();
    let predecessor_lineage = match mutation.predecessor_head() {
        Some(predecessor) => {
            let canonical_token = session_head_cas_token(predecessor)?;
            if &predecessor.id != id
                || &predecessor.strand != strand
                || predecessor.message_count != base_seq
                || mutation.predecessor_head_token() != Some(canonical_token.as_str())
            {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            predecessor
                .message_row_prefix
                .as_ref()
                .filter(|lineage| lineage.row_count() == base_seq)
                .cloned()
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?
        }
        None if matches!(mutation.expected_cas(), SessionHeadCas::Create)
            && strand == &TranscriptStrandId::root()
            && base_seq == 0 =>
        {
            SessionMessageRowPrefixAccumulator::empty()
        }
        None => return Err(SessionStoreError::Corrupted(id.clone())),
    };
    let successor_lineage = predecessor_lineage
        .extend_serialized_rows(mutation.serialized_suffix())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    if mutation.successor_head().message_row_prefix.as_ref() != Some(&successor_lineage) {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }

    let physical_extent = physical_row_extent_in_txn(tx, id, strand)?;
    let link = strand_link_in_txn(tx, id, strand)?;
    if mutation.predecessor_head().is_none() && link.is_some() {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let logical_len = match link {
        Some(link) => link.splice.strand_len.max(physical_extent),
        None => physical_extent,
    };
    if logical_len != base_seq {
        return Err(SessionStoreError::TranscriptContinuityViolation {
            id: id.clone(),
            previous_revision: format!("strand:{strand} logical-rows:{logical_len}"),
            incoming_revision: format!("append-base-seq:{base_seq}"),
            reason: "ordinary append base does not equal the exact logical strand tip".to_string(),
        });
    }
    let successor_count = i64::try_from(mutation.successor_head().message_count)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let trailing_row = tx
        .query_row(
            "SELECT seq FROM session_strand_messages
             WHERE session_id = ?1 AND strand = ?2 AND seq >= ?3
             ORDER BY seq ASC
             LIMIT 1",
            params![id.to_string(), strand.as_str(), successor_count],
            |row| row.get::<_, i64>(0),
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    if let Some(existing_seq) = trailing_row {
        return Err(SessionStoreError::TranscriptContinuityViolation {
            id: id.clone(),
            previous_revision: format!("strand:{strand} trailing-seq:{existing_seq}"),
            incoming_revision: format!(
                "prepared-successor-count:{}",
                mutation.successor_head().message_count
            ),
            reason: "ordinary append cannot retract unadopted rows beyond its exact successor"
                .to_string(),
        });
    }
    Ok(())
}

fn reconcile_prepared_suffix_rows_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalMutation,
) -> Result<(), SessionStoreError> {
    let id = mutation.session_id();
    let strand = mutation.strand();
    let start =
        i64::try_from(mutation.base_seq()).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let end = i64::try_from(mutation.successor_head().message_count)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let mut statement = tx
        .prepare(
            "SELECT seq, message_json FROM session_strand_messages
             WHERE session_id = ?1 AND strand = ?2 AND seq >= ?3 AND seq < ?4
             ORDER BY seq ASC",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let existing_rows = statement
        .query_map(
            params![id.to_string(), strand.as_str(), start, end],
            |row| {
                Ok((
                    row.get::<_, i64>(0)?,
                    row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                ))
            },
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    drop(statement);

    let created_at_ms = now_millis();
    let mut existing = existing_rows.into_iter().peekable();
    for (offset, expected_bytes) in mutation.serialized_suffix().iter().enumerate() {
        let offset = u64::try_from(offset).map_err(|_| {
            SessionStoreError::Internal(format!(
                "session {id} ordinary suffix exceeds the durable u64 row range"
            ))
        })?;
        let expected_seq = mutation.base_seq().checked_add(offset).ok_or_else(|| {
            SessionStoreError::Internal(format!("session {id} ordinary suffix sequence overflow"))
        })?;
        let expected_seq_i64 =
            i64::try_from(expected_seq).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        match existing.peek() {
            Some((stored_seq, stored_bytes)) if *stored_seq == expected_seq_i64 => {
                if stored_bytes.as_slice() != expected_bytes.as_slice() {
                    return Err(SessionStoreError::TranscriptContinuityViolation {
                        id: id.clone(),
                        previous_revision: format!("strand:{strand} seq:{expected_seq}"),
                        incoming_revision: "divergent-bytes".to_string(),
                        reason:
                            "ordinary append encountered different bytes in an immutable suffix row"
                                .to_string(),
                    });
                }
                existing.next();
            }
            Some((stored_seq, _)) if *stored_seq < expected_seq_i64 => {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            _ => {
                tx.execute(
                    "INSERT INTO session_strand_messages
                         (session_id, strand, seq, message_json, created_at_ms)
                     VALUES (?1, ?2, ?3, ?4, ?5)",
                    params![
                        id.to_string(),
                        strand.as_str(),
                        expected_seq_i64,
                        expected_bytes,
                        created_at_ms
                    ],
                )
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            }
        }
    }
    if existing.next().is_some() {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(())
}

fn reconcile_serialized_strand_rows_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    base_seq: u64,
    serialized_rows: &[Vec<u8>],
) -> Result<(), SessionStoreError> {
    let end = base_seq
        .checked_add(u64::try_from(serialized_rows.len()).map_err(|_| {
            SessionStoreError::Internal(format!(
                "session {id} serialized row delta exceeds the durable u64 range"
            ))
        })?)
        .ok_or_else(|| {
            SessionStoreError::Internal(format!(
                "session {id} serialized row delta sequence overflow"
            ))
        })?;
    let start_i64 =
        i64::try_from(base_seq).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let end_i64 = i64::try_from(end).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let mut statement = tx
        .prepare(
            "SELECT seq, message_json FROM session_strand_messages
             WHERE session_id = ?1 AND strand = ?2 AND seq >= ?3 AND seq < ?4
             ORDER BY seq ASC",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let existing = statement
        .query_map(
            params![id.to_string(), strand.as_str(), start_i64, end_i64],
            |row| {
                Ok((
                    row.get::<_, i64>(0)?,
                    row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                ))
            },
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    drop(statement);

    let mut existing = existing.into_iter().peekable();
    let created_at_ms = now_millis();
    for (offset, expected_bytes) in serialized_rows.iter().enumerate() {
        let expected_seq = base_seq
            .checked_add(u64::try_from(offset).map_err(|_| {
                SessionStoreError::Internal(format!(
                    "session {id} serialized row offset exceeds u64"
                ))
            })?)
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        let expected_seq_i64 =
            i64::try_from(expected_seq).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        match existing.peek() {
            Some((stored_seq, stored_bytes)) if *stored_seq == expected_seq_i64 => {
                if stored_bytes.as_slice() != expected_bytes.as_slice() {
                    return Err(SessionStoreError::TranscriptContinuityViolation {
                        id: id.clone(),
                        previous_revision: format!("strand:{strand} seq:{expected_seq}"),
                        incoming_revision: "divergent-bytes".to_string(),
                        reason: "prepared rewrite encountered different immutable row bytes"
                            .to_string(),
                    });
                }
                existing.next();
            }
            Some((stored_seq, _)) if *stored_seq < expected_seq_i64 => {
                return Err(SessionStoreError::Corrupted(id.clone()));
            }
            _ => {
                tx.execute(
                    "INSERT INTO session_strand_messages
                         (session_id, strand, seq, message_json, created_at_ms)
                     VALUES (?1, ?2, ?3, ?4, ?5)",
                    params![
                        id.to_string(),
                        strand.as_str(),
                        expected_seq_i64,
                        expected_bytes,
                        created_at_ms
                    ],
                )
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            }
        }
    }
    if existing.next().is_some() {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(())
}

fn verify_serialized_strand_rows_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    base_seq: u64,
    serialized_rows: &[Vec<u8>],
) -> Result<(), SessionStoreError> {
    let end = base_seq
        .checked_add(u64::try_from(serialized_rows.len()).map_err(|_| {
            SessionStoreError::Internal(format!(
                "session {id} serialized row delta exceeds the durable u64 range"
            ))
        })?)
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let stored = strand_row_bytes_in_txn(tx, id, strand, base_seq..end)?;
    if stored.as_slice() != serialized_rows {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(())
}

fn verify_prepared_suffix_rows_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalMutation,
    require_current_tip: bool,
) -> Result<(), SessionStoreError> {
    let id = mutation.session_id();
    let strand = mutation.strand();
    let start =
        i64::try_from(mutation.base_seq()).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let end = i64::try_from(mutation.successor_head().message_count)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let mut statement = tx
        .prepare(
            "SELECT seq, message_json FROM session_strand_messages
             WHERE session_id = ?1 AND strand = ?2 AND seq >= ?3 AND seq < ?4
             ORDER BY seq ASC",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let mut rows = statement
        .query(params![id.to_string(), strand.as_str(), start, end])
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    for (offset, expected_bytes) in mutation.serialized_suffix().iter().enumerate() {
        let Some(row) = rows
            .next()
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?
        else {
            return Err(SessionStoreError::Corrupted(id.clone()));
        };
        let stored_seq = row
            .get::<_, i64>(0)
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?;
        let stored_bytes = row
            .get::<_, JsonColumnBytes>(1)
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?
            .into_bytes();
        let offset = u64::try_from(offset).map_err(|_| {
            SessionStoreError::Internal(format!(
                "session {id} ordinary suffix exceeds the durable u64 row range"
            ))
        })?;
        let expected_seq = mutation
            .base_seq()
            .checked_add(offset)
            .and_then(|seq| i64::try_from(seq).ok())
            .ok_or_else(|| {
                SessionStoreError::Internal(format!(
                    "session {id} ordinary suffix sequence overflow"
                ))
            })?;
        if stored_seq != expected_seq || stored_bytes.as_slice() != expected_bytes.as_slice() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
    }
    if rows
        .next()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .is_some()
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    drop(rows);
    drop(statement);

    let trailing_row_exists = tx
        .query_row(
            "SELECT 1 FROM session_strand_messages
             WHERE session_id = ?1 AND strand = ?2 AND seq >= ?3
             ORDER BY seq ASC
             LIMIT 1",
            params![id.to_string(), strand.as_str(), end],
            |_row| Ok(()),
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .is_some();
    if require_current_tip && trailing_row_exists {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(())
}

fn component_rows_corrupted(id: &SessionId) -> SessionStoreError {
    SessionStoreError::Corrupted(id.clone())
}

fn load_verified_component_sequence_in_txn(
    tx: &Transaction<'_>,
    expected: &ComponentEventPrefixAuthority,
) -> Result<VerifiedComponentEventSequence, SessionStoreError> {
    let id = expected.session_id();
    let expected_count =
        i64::try_from(expected.event_count()).map_err(|_| component_rows_corrupted(id))?;
    let mut statement = tx
        .prepare(
            "SELECT seq, event_json, event_digest
             FROM session_component_events
             WHERE session_id = ?1 AND component = ?2 AND seq < ?3
             ORDER BY seq ASC",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let rows = statement
        .query_map(
            params![
                id.to_string(),
                expected.component().as_str(),
                expected_count
            ],
            |row| {
                Ok((
                    row.get::<_, i64>(0)?,
                    row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                    row.get::<_, String>(2)?,
                ))
            },
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let mut stored = Vec::with_capacity(rows.len());
    for (seq, bytes, stored_digest) in rows {
        let seq = u64::try_from(seq).map_err(|_| component_rows_corrupted(id))?;
        let event = SerializedComponentEvent::from_canonical_bytes(bytes.clone())
            .map_err(|_| component_rows_corrupted(id))?;
        if event.digest().as_str() != stored_digest.as_str() {
            return Err(component_rows_corrupted(id));
        }
        stored.push(StoredComponentEventRow::new(seq, bytes));
    }
    VerifiedComponentEventSequence::verify_full(expected.clone(), stored)
        .map_err(|_| component_rows_corrupted(id))
}

fn point_check_component_predecessor_in_txn(
    tx: &Transaction<'_>,
    suffix: &PreparedComponentEventSuffix,
) -> Result<(), SessionStoreError> {
    let id = suffix.session_id();
    let component = suffix.component().as_str();
    if suffix.base_seq() > 0 {
        let predecessor_seq =
            i64::try_from(suffix.base_seq() - 1).map_err(|_| component_rows_corrupted(id))?;
        let predecessor_exists = tx
            .query_row(
                "SELECT 1 FROM session_component_events
                 WHERE session_id = ?1 AND component = ?2 AND seq = ?3",
                params![id.to_string(), component, predecessor_seq],
                |_row| Ok(()),
            )
            .optional()
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?
            .is_some();
        if !predecessor_exists {
            return Err(SessionStoreError::TranscriptContinuityViolation {
                id: id.clone(),
                previous_revision: suffix.predecessor().root_digest().to_string(),
                incoming_revision: suffix.successor().root_digest().to_string(),
                reason: format!(
                    "{} component predecessor row {} is missing",
                    suffix.component(),
                    suffix.base_seq() - 1
                ),
            });
        }
    }
    Ok(())
}

fn point_check_component_append_boundary_in_txn(
    tx: &Transaction<'_>,
    suffix: &PreparedComponentEventSuffix,
) -> Result<(), SessionStoreError> {
    point_check_component_predecessor_in_txn(tx, suffix)?;
    let id = suffix.session_id();
    let component = suffix.component().as_str();
    let successor_count = i64::try_from(suffix.successor().event_count())
        .map_err(|_| component_rows_corrupted(id))?;
    let trailing = tx
        .query_row(
            "SELECT seq FROM session_component_events
             WHERE session_id = ?1 AND component = ?2 AND seq >= ?3
             ORDER BY seq ASC LIMIT 1",
            params![id.to_string(), component, successor_count],
            |row| row.get::<_, i64>(0),
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    if let Some(seq) = trailing {
        return Err(SessionStoreError::TranscriptContinuityViolation {
            id: id.clone(),
            previous_revision: format!("{}-component-trailing-seq:{seq}", suffix.component()),
            incoming_revision: suffix.successor().root_digest().to_string(),
            reason: "component append cannot retract rows beyond its exact successor".to_string(),
        });
    }
    Ok(())
}

fn reconcile_prepared_component_suffix_in_txn(
    tx: &Transaction<'_>,
    suffix: &PreparedComponentEventSuffix,
) -> Result<(), SessionStoreError> {
    point_check_component_append_boundary_in_txn(tx, suffix)?;
    let id = suffix.session_id();
    let component = suffix.component().as_str();
    let start = i64::try_from(suffix.base_seq()).map_err(|_| component_rows_corrupted(id))?;
    let end = i64::try_from(suffix.successor().event_count())
        .map_err(|_| component_rows_corrupted(id))?;
    let mut statement = tx
        .prepare(
            "SELECT seq, event_json, event_digest
             FROM session_component_events
             WHERE session_id = ?1 AND component = ?2 AND seq >= ?3 AND seq < ?4
             ORDER BY seq ASC",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let existing = statement
        .query_map(params![id.to_string(), component, start, end], |row| {
            Ok((
                row.get::<_, i64>(0)?,
                row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                row.get::<_, String>(2)?,
            ))
        })
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    drop(statement);

    let mut existing = existing.into_iter().peekable();
    let created_at_ms = now_millis();
    for (offset, event) in suffix.events().iter().enumerate() {
        let offset = u64::try_from(offset).map_err(|_| component_rows_corrupted(id))?;
        let expected_seq = suffix
            .base_seq()
            .checked_add(offset)
            .ok_or_else(|| component_rows_corrupted(id))?;
        let expected_seq_i64 =
            i64::try_from(expected_seq).map_err(|_| component_rows_corrupted(id))?;
        match existing.peek() {
            Some((stored_seq, stored_bytes, stored_digest)) if *stored_seq == expected_seq_i64 => {
                if stored_bytes.as_slice() != event.bytes()
                    || stored_digest.as_str() != event.digest().as_str()
                {
                    return Err(SessionStoreError::TranscriptContinuityViolation {
                        id: id.clone(),
                        previous_revision: format!(
                            "{}-component-seq:{expected_seq}",
                            suffix.component()
                        ),
                        incoming_revision: event.digest().to_string(),
                        reason: "component append encountered different immutable event bytes"
                            .to_string(),
                    });
                }
                existing.next();
            }
            Some((stored_seq, _, _)) if *stored_seq < expected_seq_i64 => {
                return Err(component_rows_corrupted(id));
            }
            _ => {
                tx.execute(
                    "INSERT INTO session_component_events
                         (session_id, component, seq, event_json, event_digest, created_at_ms)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    params![
                        id.to_string(),
                        component,
                        expected_seq_i64,
                        event.bytes(),
                        event.digest().as_str(),
                        created_at_ms,
                    ],
                )
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            }
        }
    }
    if existing.next().is_some() {
        return Err(component_rows_corrupted(id));
    }
    Ok(())
}

fn verify_prepared_component_suffix_rows_in_txn(
    tx: &Transaction<'_>,
    suffix: &PreparedComponentEventSuffix,
    require_current_tip: bool,
) -> Result<(), SessionStoreError> {
    if require_current_tip {
        point_check_component_append_boundary_in_txn(tx, suffix)?;
    } else {
        point_check_component_predecessor_in_txn(tx, suffix)?;
    }
    let id = suffix.session_id();
    let component = suffix.component().as_str();
    let start = i64::try_from(suffix.base_seq()).map_err(|_| component_rows_corrupted(id))?;
    let end = i64::try_from(suffix.successor().event_count())
        .map_err(|_| component_rows_corrupted(id))?;
    let mut statement = tx
        .prepare(
            "SELECT seq, event_json, event_digest
             FROM session_component_events
             WHERE session_id = ?1 AND component = ?2 AND seq >= ?3 AND seq < ?4
             ORDER BY seq ASC",
        )
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    let mut rows = statement
        .query(params![id.to_string(), component, start, end])
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?;
    for (offset, event) in suffix.events().iter().enumerate() {
        let Some(row) = rows
            .next()
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?
        else {
            return Err(component_rows_corrupted(id));
        };
        let offset = u64::try_from(offset).map_err(|_| component_rows_corrupted(id))?;
        let expected_seq = suffix
            .base_seq()
            .checked_add(offset)
            .and_then(|seq| i64::try_from(seq).ok())
            .ok_or_else(|| component_rows_corrupted(id))?;
        let stored_seq = row
            .get::<_, i64>(0)
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?;
        let stored_bytes = row
            .get::<_, JsonColumnBytes>(1)
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?
            .into_bytes();
        let stored_digest = row
            .get::<_, String>(2)
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?;
        if stored_seq != expected_seq
            || stored_bytes.as_slice() != event.bytes()
            || stored_digest.as_str() != event.digest().as_str()
        {
            return Err(component_rows_corrupted(id));
        }
    }
    if rows
        .next()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .is_some()
    {
        return Err(component_rows_corrupted(id));
    }
    Ok(())
}

fn verify_prepared_component_suffix_in_txn(
    tx: &Transaction<'_>,
    suffix: &PreparedComponentEventSuffix,
) -> Result<(), SessionStoreError> {
    verify_prepared_component_suffix_rows_in_txn(tx, suffix, true)
}

fn verify_prepared_head_metadata_projection_for_owner_in_txn(
    tx: &Transaction<'_>,
    head: &SessionHead,
    owner: HeadMetadataProjectionOwner,
    expected_predecessor_head_token: Option<&str>,
) -> Result<(), SessionStoreError> {
    let Some(identity) = head.metadata_identity() else {
        return Ok(());
    };
    let projection = head
        .metadata_projection()
        .filter(|projection| projection.identity() == identity)
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    if projection
        .mutations()
        .iter()
        .any(|mutation| !mutation.verify())
    {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }
    let head_token = session_head_cas_token(head)?;
    let reference = metadata_owner_ref_in_txn(tx, &head.id, owner)?
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    let state_id = reference.state_id.as_str();
    let state = metadata_state_in_txn(tx, &head.id, state_id)?
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    if &state.identity != identity {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }
    if projection.mutations().is_empty() {
        match projection.predecessor_identity() {
            Some(predecessor) if predecessor == identity => return Ok(()),
            None if identity.is_canonical_empty() && projection.is_full_snapshot() => {}
            _ => return Err(SessionStoreError::Corrupted(head.id.clone())),
        }
    }
    if state.transition_id != head_token || reference.head_cas_token != head_token {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }
    let lineage = tx
        .query_row(
            r"
            SELECT transition_id, predecessor_head_cas_token,
                   predecessor_state_id, successor_state_id
            FROM session_head_metadata_head_lineage
            WHERE session_id = ?1 AND successor_head_cas_token = ?2
            ",
            params![head.id.to_string(), head_token],
            |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, Option<String>>(1)?,
                    row.get::<_, Option<String>>(2)?,
                    row.get::<_, String>(3)?,
                ))
            },
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
    if lineage.0 != head_token
        || lineage.1.as_deref() != expected_predecessor_head_token
        || lineage.2.as_deref() != state.predecessor_state_id.as_deref()
        || lineage.3 != state_id
    {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }
    match projection.predecessor_identity() {
        Some(expected_predecessor) => {
            let predecessor_state_id = state
                .predecessor_state_id
                .as_deref()
                .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
            let predecessor_state = metadata_state_in_txn(tx, &head.id, predecessor_state_id)?
                .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
            if &predecessor_state.identity != expected_predecessor {
                return Err(SessionStoreError::Corrupted(head.id.clone()));
            }
        }
        None => {
            if state.predecessor_state_id.is_some()
                || !projection.is_full_snapshot()
                || (projection.mutations().is_empty() && !identity.is_canonical_empty())
            {
                return Err(SessionStoreError::Corrupted(head.id.clone()));
            }
        }
    }
    let stored_deltas = metadata_state_deltas_in_txn(tx, &head.id, state_id)?;
    if stored_deltas.len() != projection.mutations().len() {
        return Err(SessionStoreError::Corrupted(head.id.clone()));
    }
    for (stored, mutation) in stored_deltas.iter().zip(projection.mutations()) {
        if stored.key != mutation.key()
            || stored.key_route.as_slice() != mutation.key_route()
            || stored.predecessor_exact_value_digest.as_deref()
                != mutation
                    .predecessor()
                    .map(|identity| identity.exact_value_digest().as_str())
            || stored.successor_exact_value_digest.as_deref()
                != mutation
                    .successor()
                    .map(|cell| cell.identity().exact_value_digest().as_str())
        {
            return Err(SessionStoreError::Corrupted(head.id.clone()));
        }
        if let Some(predecessor) = mutation.predecessor() {
            let stored_predecessor = metadata_cell_in_txn(
                tx,
                &head.id,
                mutation.key(),
                predecessor.exact_value_digest().as_str(),
            )?
            .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
            if stored_predecessor.identity() != predecessor
                || stored_predecessor.key_route() != &mutation.key_route()
            {
                return Err(SessionStoreError::Corrupted(head.id.clone()));
            }
        }
        if let Some(cell) = mutation.successor() {
            let stored_cell = metadata_cell_in_txn(
                tx,
                &head.id,
                mutation.key(),
                cell.identity().exact_value_digest().as_str(),
            )?
            .ok_or_else(|| SessionStoreError::Corrupted(head.id.clone()))?;
            if stored_cell.identity() != cell.identity()
                || stored_cell.key_route() != cell.key_route()
                || stored_cell.canonical_json() != cell.canonical_json()
            {
                return Err(SessionStoreError::Corrupted(head.id.clone()));
            }
        }
        if matches!(owner, HeadMetadataProjectionOwner::PhysicalHead) {
            let current = current_metadata_cell_digest_in_txn(tx, &head.id, mutation.key())?;
            match (mutation.successor(), current) {
                (Some(cell), Some((route, digest)))
                    if route.as_slice() == mutation.key_route()
                        && digest == cell.identity().exact_value_digest().as_str() => {}
                (None, None) => {}
                _ => return Err(SessionStoreError::Corrupted(head.id.clone())),
            }
        }
    }
    Ok(())
}

/// Re-prove every SessionStore-owned row named by an exact prepared-mutation
/// retry without requiring the physical head to remain at that successor.
///
/// RuntimeStore's durable ordinary witness may stay authoritative after a
/// later physical append or rewrite. Message/component rows are immutable and
/// the successor metadata state remains reachable through the runtime-boundary
/// owner ref, so this helper validates those exact effects directly.
#[doc(hidden)]
pub fn verify_prepared_head_canonical_rows_for_exact_retry_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalMutation,
) -> Result<(), SessionStoreError> {
    verify_prepared_suffix_rows_in_txn(tx, mutation, false)?;
    if let Some(suffix) = mutation.realtime_suffix() {
        verify_prepared_component_suffix_rows_in_txn(tx, suffix, false)?;
    }

    verify_prepared_head_metadata_projection_for_owner_in_txn(
        tx,
        mutation.successor_head(),
        HeadMetadataProjectionOwner::RuntimeBoundary,
        mutation.predecessor_head_token(),
    )
}

/// Apply a prepared ordinary create/append inside the caller's transaction.
///
/// The sealed carrier binds the exact predecessor and successor. This helper
/// revalidates that predecessor against the durable head, accepts the exact
/// successor as an idempotent retry, checks only indexed live-strand boundary
/// facts, inserts the pre-serialized suffix, and writes the successor head
/// without topology settlement. It never opens or commits a transaction and
/// never scans rewrite or strand-link history.
pub fn apply_prepared_head_canonical_mutation_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalMutation,
) -> Result<HeadCanonicalMutationApplyOutcome, SessionStoreError> {
    let current = head_row_in_txn(tx, mutation.session_id())?;
    if let Some((current_head, stored_token)) = current.as_ref() {
        let canonical_token = session_head_cas_token(current_head)?;
        if canonical_token != *stored_token {
            return Err(SessionStoreError::Corrupted(mutation.session_id().clone()));
        }
        if stored_token == mutation.successor_head_token() {
            verify_prepared_suffix_rows_in_txn(tx, mutation, true)?;
            if let Some(suffix) = mutation.realtime_suffix() {
                verify_prepared_component_suffix_in_txn(tx, suffix)?;
            }
            verify_prepared_head_metadata_projection_for_owner_in_txn(
                tx,
                mutation.successor_head(),
                HeadMetadataProjectionOwner::PhysicalHead,
                mutation.predecessor_head_token(),
            )?;
            return Ok(HeadCanonicalMutationApplyOutcome::AlreadyApplied);
        }
    }

    match (mutation.expected_cas(), current.as_ref()) {
        (SessionHeadCas::Create, None) => {
            let legacy_blob_exists = tx
                .query_row(
                    "SELECT 1 FROM sessions WHERE session_id = ?1 LIMIT 1",
                    params![mutation.session_id().to_string()],
                    |_row| Ok(()),
                )
                .optional()
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?
                .is_some();
            if legacy_blob_exists {
                return Err(prepared_head_conflict(
                    mutation,
                    "legacy whole-blob session exists without a canonical head",
                ));
            }
        }
        (SessionHeadCas::IfToken(expected), Some((current_head, actual)))
            if expected == actual
                && mutation
                    .predecessor_head()
                    .is_some_and(|head| head == current_head) => {}
        (_, Some((_head, token))) => {
            return Err(prepared_head_conflict(mutation, token.clone()));
        }
        (_, None) => {
            return Err(prepared_head_conflict(mutation, "absent canonical head"));
        }
    }

    point_check_materialized_append_boundary_in_txn(tx, mutation)?;
    reconcile_prepared_suffix_rows_in_txn(tx, mutation)?;
    if let Some(suffix) = mutation.realtime_suffix() {
        reconcile_prepared_component_suffix_in_txn(tx, suffix)?;
    }
    reconcile_head_metadata_transition_in_txn(
        tx,
        mutation.predecessor_head(),
        mutation.predecessor_head_token(),
        mutation.successor_head(),
        mutation.successor_head_token(),
    )?;
    let written_token = write_head_row_only_in_txn(tx, mutation.successor_head())?;
    if written_token != mutation.successor_head_token() {
        return Err(SessionStoreError::Internal(format!(
            "session {} prepared successor token changed during head write",
            mutation.session_id()
        )));
    }
    Ok(HeadCanonicalMutationApplyOutcome::Applied)
}

fn prepared_rewrite_conflict(
    mutation: &PreparedHeadCanonicalRewriteMutation,
    actual: impl Into<String>,
) -> SessionStoreError {
    SessionStoreError::TranscriptRevisionConflict {
        id: mutation.session_id().clone(),
        expected: mutation.predecessor_head_token().to_string(),
        actual: actual.into(),
    }
}

fn reconcile_prepared_rewrite_row_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalRewriteMutation,
    rewrite_idx: u64,
    step: &meerkat_core::session_store::PreparedHeadCanonicalRewriteStep,
) -> Result<(), SessionStoreError> {
    let id = mutation.session_id();
    let existing = indexed_rewrite_rows_range_in_txn(
        tx,
        id,
        rewrite_idx,
        rewrite_idx
            .checked_add(1)
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?,
    )?;
    let expected = RewriteRow {
        commit: step.commit().clone(),
        parent_strand: step.parent_strand().clone(),
        parent_len: u64::try_from(step.commit().messages_before)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
        strand: step.strand().clone(),
        strand_len: u64::try_from(step.commit().messages_after)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
        graph_edge_json: Some(step.serialized_graph_edge().to_vec()),
    };
    match existing.as_slice() {
        [] => insert_rewrite_row_in_txn(tx, id, rewrite_idx, &expected),
        [(stored_idx, stored)]
            if *stored_idx == rewrite_idx
                && stored.commit == expected.commit
                && stored.parent_strand == expected.parent_strand
                && stored.parent_len == expected.parent_len
                && stored.strand == expected.strand
                && stored.strand_len == expected.strand_len
                && stored.graph_edge_json == expected.graph_edge_json =>
        {
            Ok(())
        }
        _ => Err(SessionStoreError::Corrupted(id.clone())),
    }
}

fn reconcile_prepared_rewrite_parent_transition_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalRewriteMutation,
    step: &meerkat_core::session_store::PreparedHeadCanonicalRewriteStep,
    expected_source: &TranscriptStrandId,
    expected_source_len: u64,
) -> Result<(), SessionStoreError> {
    let id = mutation.session_id();
    match step.parent_transition() {
        PreparedHeadCanonicalParentTransition::ExactAppend => {
            if step.parent_strand() != expected_source {
                return Err(SessionStoreError::InvalidTranscriptRewrite {
                    id: id.clone(),
                    reason:
                        "prepared exact-append rewrite parent is not the preceding occurrence strand"
                            .to_string(),
                });
            }
            Ok(())
        }
        PreparedHeadCanonicalParentTransition::ExactSplice(parent_splice) => {
            let expected_bridge = TranscriptStrandId::from_rewrite_parent_occurrence(step.commit());
            if parent_splice.source_strand() != expected_source
                || step.parent_strand() != &expected_bridge
                || step.parent_strand() == parent_splice.source_strand()
            {
                return Err(SessionStoreError::InvalidTranscriptRewrite {
                    id: id.clone(),
                    reason: "prepared exact-splice parent bridge has inconsistent strand identity"
                        .to_string(),
                });
            }
            let splice = parent_splice.link_splice();
            let replacement_rows = u64::try_from(parent_splice.serialized_replacement().len())
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
            if !splice.is_well_formed()
                || splice.strand_len != step.parent_base_seq()
                || replacement_rows == 0
                || splice.splice_end != splice.successor_end
                || splice.retained_rows() != replacement_rows
            {
                return Err(SessionStoreError::InvalidTranscriptRewrite {
                    id: id.clone(),
                    reason:
                        "prepared exact-splice parent bridge does not describe an exact same-cardinality replacement"
                            .to_string(),
                });
            }
            if expected_source_len != splice.successor_len() {
                return Err(SessionStoreError::TranscriptContinuityViolation {
                    id: id.clone(),
                    previous_revision: format!(
                        "strand:{} logical-rows:{expected_source_len}",
                        parent_splice.source_strand()
                    ),
                    incoming_revision: format!(
                        "rewrite-parent-source-rows:{}",
                        splice.successor_len()
                    ),
                    reason:
                        "prepared exact-splice parent bridge does not target the exact preceding strand"
                            .to_string(),
                });
            }
            if let Some(existing) = strand_link_in_txn(tx, id, step.parent_strand())? {
                if existing.successor != *parent_splice.source_strand() || existing.splice != splice
                {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
            } else {
                if strand_has_physical_rows_in_txn(tx, id, step.parent_strand())? {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
                // The bridge id is occurrence-derived and the sealed carrier
                // proves it is not the preceding source. An absent row at
                // this exact key is therefore the only admissible fresh
                // state. Cold topology verification owns detection of
                // unrelated pre-existing graph corruption.
                tx.execute(
                    "INSERT INTO session_strand_links
                         (session_id, strand, successor, strand_len, splice_start, splice_end,
                          successor_end, created_at_ms)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                    params![
                        id.to_string(),
                        step.parent_strand().as_str(),
                        parent_splice.source_strand().as_str(),
                        i64::try_from(splice.strand_len)
                            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                        i64::try_from(splice.splice_start)
                            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                        i64::try_from(splice.splice_end)
                            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                        i64::try_from(splice.successor_end)
                            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                        now_millis(),
                    ],
                )
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            }
            reconcile_serialized_strand_rows_in_txn(
                tx,
                id,
                step.parent_strand(),
                splice.splice_start,
                parent_splice.serialized_replacement(),
            )
        }
    }
}

fn reconcile_prepared_rewrite_link_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalRewriteMutation,
    step: &meerkat_core::session_store::PreparedHeadCanonicalRewriteStep,
) -> Result<(), SessionStoreError> {
    let id = mutation.session_id();
    if step.strand() == step.parent_strand() {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: id.clone(),
            reason: "prepared rewrite link points a strand at itself".to_string(),
        });
    }
    if let Some(existing) = strand_link_in_txn(tx, id, step.strand())? {
        if existing.successor == *step.parent_strand() && existing.splice == step.link_splice() {
            return Ok(());
        }
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    if strand_has_physical_rows_in_txn(tx, id, step.strand())? {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let splice = step.link_splice();
    let messages_before = u64::try_from(step.commit().messages_before)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let messages_after = u64::try_from(step.commit().messages_after)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    let replacement_rows = u64::try_from(step.serialized_replacement().len())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    if !splice.is_well_formed()
        || splice.successor_len() != messages_before
        || splice.strand_len != messages_after
        || splice.retained_rows() != replacement_rows
    {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: id.clone(),
            reason: "prepared rewrite link does not match its sealed occurrence delta".to_string(),
        });
    }
    tx.execute(
        "INSERT INTO session_strand_links
             (session_id, strand, successor, strand_len, splice_start, splice_end,
              successor_end, created_at_ms)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
        params![
            id.to_string(),
            step.strand().as_str(),
            step.parent_strand().as_str(),
            i64::try_from(splice.strand_len)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            i64::try_from(splice.splice_start)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            i64::try_from(splice.splice_end)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            i64::try_from(splice.successor_end)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            now_millis(),
        ],
    )
    .map_err(StoreError::from)
    .map_err(into_session_store_error)?;
    Ok(())
}

fn verify_named_strand_link_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    strand: &TranscriptStrandId,
    successor: &TranscriptStrandId,
    splice: StrandSplice,
) -> Result<(), SessionStoreError> {
    let stored = strand_link_in_txn(tx, id, strand)?
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    if stored.successor != *successor || stored.splice != splice {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(())
}

/// Derive the exact successor row lineage from the predecessor head and the
/// sealed mutation deltas.
///
/// The commitment is deliberately history/occurrence aware: a rewrite back
/// to byte-identical visible content remains a distinct successor. Every
/// transition hashes only its appended/replaced rows.
fn verify_prepared_rewrite_row_lineage(
    mutation: &PreparedHeadCanonicalRewriteMutation,
) -> Result<(), SessionStoreError> {
    let id = mutation.session_id();
    let predecessor_head = mutation.predecessor_head();
    let successor_head = mutation.successor_head();
    if &predecessor_head.id != id
        || &successor_head.id != id
        || session_head_cas_token(predecessor_head)? != mutation.predecessor_head_token()
        || session_head_cas_token(successor_head)? != mutation.successor_head_token()
        || !matches!(
            mutation.expected_cas(),
            SessionHeadCas::IfToken(token) if token == mutation.predecessor_head_token()
        )
        || predecessor_head.rewrite_prefix.occurrence_count() != predecessor_head.rewrite_count
        || successor_head.rewrite_prefix.occurrence_count() != successor_head.rewrite_count
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let mut row_lineage = predecessor_head
        .message_row_prefix
        .as_ref()
        .filter(|prefix| prefix.row_count() == predecessor_head.message_count)
        .cloned()
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let successor_row_lineage = successor_head
        .message_row_prefix
        .as_ref()
        .filter(|prefix| prefix.row_count() == successor_head.message_count)
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    let mut rewrite_prefix = predecessor_head.rewrite_prefix.clone();
    let mut rewrite_count = predecessor_head.rewrite_count;
    let mut expected_source = predecessor_head.strand.clone();
    let mut expected_source_len = predecessor_head.message_count;
    for step in mutation.steps() {
        let messages_before = u64::try_from(step.commit().messages_before)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let messages_after = u64::try_from(step.commit().messages_after)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        if step.parent_base_seq() != expected_source_len {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let advanced = match step.parent_transition() {
            PreparedHeadCanonicalParentTransition::ExactAppend => {
                if step.parent_strand() != &expected_source {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
                row_lineage
            }
            PreparedHeadCanonicalParentTransition::ExactSplice(parent_splice) => {
                let expected_bridge =
                    TranscriptStrandId::from_rewrite_parent_occurrence(step.commit());
                let splice = parent_splice.link_splice();
                let replacement_rows = u64::try_from(parent_splice.serialized_replacement().len())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
                if parent_splice.source_strand() != &expected_source
                    || step.parent_strand() != &expected_bridge
                    || replacement_rows == 0
                    || !splice.is_well_formed()
                    || splice.strand_len != step.parent_base_seq()
                    || splice.splice_end != splice.successor_end
                    || splice.successor_len() != expected_source_len
                    || splice.retained_rows() != replacement_rows
                {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
                row_lineage
                    .replace_serialized_range(
                        splice.splice_start,
                        splice.splice_end,
                        parent_splice.serialized_replacement(),
                    )
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?
            }
        };
        let parent_row_lineage = advanced
            .extend_serialized_rows(step.serialized_parent_suffix())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        if parent_row_lineage.row_count() != messages_before {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let splice = step.link_splice();
        let replacement_rows = u64::try_from(step.serialized_replacement().len())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        if !splice.is_well_formed()
            || splice.successor_len() != messages_before
            || splice.strand_len != messages_after
            || splice.retained_rows() != replacement_rows
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let result_row_lineage = parent_row_lineage
            .replace_serialized_range(
                splice.splice_start,
                splice.successor_end,
                step.serialized_replacement(),
            )
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        if result_row_lineage.row_count() != messages_after {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        rewrite_prefix = rewrite_prefix
            .extend(step.commit())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        rewrite_count = rewrite_count
            .checked_add(1)
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        expected_source = step.strand().clone();
        expected_source_len = messages_after;
        row_lineage = result_row_lineage;
    }
    if rewrite_count != successor_head.rewrite_count
        || rewrite_prefix != successor_head.rewrite_prefix
        || expected_source != successor_head.strand
        || expected_source_len != mutation.tail_base_seq()
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let final_row_lineage = row_lineage
        .extend_serialized_rows(mutation.serialized_tail())
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    if &final_row_lineage != successor_row_lineage
        || final_row_lineage.row_count() != successor_head.message_count
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(())
}

/// Point-check every immutable physical fact named by one sealed rewrite.
///
/// This deliberately does not reload unchanged predecessor rows or the
/// accumulated strand graph. Exact byte-lineage is derived from the
/// predecessor head and the same prepared deltas below; cold materialization
/// re-proves only the bounded active topology and live document. Full-history
/// reproof belongs to explicit audit surfaces.
fn verify_prepared_head_canonical_rewrite_rows_named_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalRewriteMutation,
    metadata_owner: HeadMetadataProjectionOwner,
) -> Result<(), SessionStoreError> {
    let id = mutation.session_id();
    let successor_head = mutation.successor_head();
    let successor_anchor_rotated = head_has_current_row_lineage_anchor(successor_head)?
        && successor_head.row_lineage_anchor != mutation.predecessor_head().row_lineage_anchor;
    verify_prepared_rewrite_row_lineage(mutation)?;

    let mut rewrite_idx = mutation.predecessor_head().rewrite_count;
    let mut expected_source = mutation.predecessor_head().strand.clone();
    let mut expected_source_len = mutation.predecessor_head().message_count;
    for step in mutation.steps() {
        let messages_before = u64::try_from(step.commit().messages_before)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let messages_after = u64::try_from(step.commit().messages_after)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        if step.parent_base_seq() != expected_source_len {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        match step.parent_transition() {
            PreparedHeadCanonicalParentTransition::ExactAppend => {
                if step.parent_strand() != &expected_source {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
            }
            PreparedHeadCanonicalParentTransition::ExactSplice(parent_splice) => {
                let expected_bridge =
                    TranscriptStrandId::from_rewrite_parent_occurrence(step.commit());
                let splice = parent_splice.link_splice();
                let replacement_rows = u64::try_from(parent_splice.serialized_replacement().len())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
                if parent_splice.source_strand() != &expected_source
                    || step.parent_strand() != &expected_bridge
                    || replacement_rows == 0
                    || !splice.is_well_formed()
                    || splice.strand_len != step.parent_base_seq()
                    || splice.splice_end != splice.successor_end
                    || splice.retained_rows() != replacement_rows
                    || splice.successor_len() != expected_source_len
                {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
                verify_named_strand_link_in_txn(
                    tx,
                    id,
                    step.parent_strand(),
                    parent_splice.source_strand(),
                    splice,
                )?;
                verify_serialized_strand_rows_in_txn(
                    tx,
                    id,
                    step.parent_strand(),
                    splice.splice_start,
                    parent_splice.serialized_replacement(),
                )?;
            }
        }
        let parent_len = step
            .parent_base_seq()
            .checked_add(
                u64::try_from(step.serialized_parent_suffix().len())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            )
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if parent_len != messages_before {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        verify_serialized_strand_rows_in_txn(
            tx,
            id,
            step.parent_strand(),
            step.parent_base_seq(),
            step.serialized_parent_suffix(),
        )?;
        if matches!(metadata_owner, HeadMetadataProjectionOwner::PhysicalHead)
            && let Some(parent_link) = strand_link_in_txn(tx, id, step.parent_strand())?
        {
            verify_linked_strand_physical_shape_in_txn(
                tx,
                id,
                step.parent_strand(),
                &parent_link,
                parent_len,
            )?;
        }
        let stored = indexed_rewrite_rows_range_in_txn(
            tx,
            id,
            rewrite_idx,
            rewrite_idx
                .checked_add(1)
                .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?,
        )?;
        match stored.as_slice() {
            [(stored_idx, row)]
                if *stored_idx == rewrite_idx
                    && row.commit == *step.commit()
                    && row.parent_strand == *step.parent_strand()
                    && row.parent_len == messages_before
                    && row.strand == *step.strand()
                    && row.strand_len == messages_after
                    && row.graph_edge_json.as_deref() == Some(step.serialized_graph_edge()) => {}
            _ => return Err(SessionStoreError::Corrupted(id.clone())),
        }
        let splice = step.link_splice();
        let replacement_rows = u64::try_from(step.serialized_replacement().len())
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        if !splice.is_well_formed()
            || splice.successor_len() != messages_before
            || splice.strand_len != messages_after
            || splice.retained_rows() != replacement_rows
        {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        let is_settled_successor =
            successor_anchor_rotated && step.strand() == &successor_head.strand;
        if !is_settled_successor || strand_link_in_txn(tx, id, step.strand())?.is_some() {
            verify_named_strand_link_in_txn(tx, id, step.strand(), step.parent_strand(), splice)?;
        }
        verify_serialized_strand_rows_in_txn(
            tx,
            id,
            step.strand(),
            step.link_splice().splice_start,
            step.serialized_replacement(),
        )?;
        rewrite_idx = rewrite_idx
            .checked_add(1)
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        expected_source = step.strand().clone();
        expected_source_len = messages_after;
    }
    if rewrite_idx != successor_head.rewrite_count
        || expected_source != successor_head.strand
        || expected_source_len != mutation.tail_base_seq()
    {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    verify_serialized_strand_rows_in_txn(
        tx,
        id,
        &successor_head.strand,
        mutation.tail_base_seq(),
        mutation.serialized_tail(),
    )?;
    let final_message_count = mutation
        .tail_base_seq()
        .checked_add(
            u64::try_from(mutation.serialized_tail().len())
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
        )
        .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
    if final_message_count != successor_head.message_count {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let final_link = strand_link_in_txn(tx, id, &successor_head.strand)?;
    match final_link.as_ref() {
        None if successor_anchor_rotated => {
            verify_direct_current_anchor_rows_in_txn(tx, successor_head)?;
        }
        None => return Err(SessionStoreError::Corrupted(id.clone())),
        Some(_) => {}
    }
    if matches!(metadata_owner, HeadMetadataProjectionOwner::PhysicalHead)
        && let Some(final_link) = final_link
    {
        if final_link.splice.strand_len != mutation.tail_base_seq() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        verify_linked_strand_physical_shape_in_txn(
            tx,
            id,
            &successor_head.strand,
            &final_link,
            successor_head.message_count,
        )?;
    }
    if let Some(suffix) = mutation.realtime_suffix() {
        verify_prepared_component_suffix_rows_in_txn(tx, suffix, false)?;
    }
    verify_prepared_head_metadata_projection_for_owner_in_txn(
        tx,
        successor_head,
        metadata_owner,
        Some(mutation.predecessor_head_token()),
    )
}

/// Re-prove every immutable SessionStore effect named by a specialized
/// rewrite after RuntimeStore has already adopted its successor.
#[doc(hidden)]
pub fn verify_prepared_head_canonical_rewrite_rows_for_exact_retry_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalRewriteMutation,
) -> Result<(), SessionStoreError> {
    verify_prepared_head_canonical_rewrite_rows_named_in_txn(
        tx,
        mutation,
        HeadMetadataProjectionOwner::RuntimeBoundary,
    )
}

/// Apply one sealed HeadCanonical rewrite using only bridge/replacement/tail
/// rows. Shared prefix/suffix rows are linked to earlier strands; no full
/// successor strand is ever staged.
pub fn apply_prepared_head_canonical_rewrite_mutation_in_txn(
    tx: &Transaction<'_>,
    mutation: &PreparedHeadCanonicalRewriteMutation,
) -> Result<HeadCanonicalMutationApplyOutcome, SessionStoreError> {
    let current = head_row_in_txn(tx, mutation.session_id())?;
    if let Some((current_head, stored_token)) = current.as_ref() {
        let canonical_token = session_head_cas_token(current_head)?;
        if canonical_token != *stored_token {
            return Err(SessionStoreError::Corrupted(mutation.session_id().clone()));
        }
        if stored_token == mutation.successor_head_token()
            && current_head == mutation.successor_head()
        {
            verify_prepared_head_canonical_rewrite_rows_named_in_txn(
                tx,
                mutation,
                HeadMetadataProjectionOwner::PhysicalHead,
            )?;
            return Ok(HeadCanonicalMutationApplyOutcome::AlreadyApplied);
        }
    }
    match current.as_ref() {
        Some((head, token))
            if token == mutation.predecessor_head_token()
                && head == mutation.predecessor_head() => {}
        Some((_head, token)) => {
            return Err(prepared_rewrite_conflict(mutation, token.clone()));
        }
        None => {
            return Err(prepared_rewrite_conflict(mutation, "absent canonical head"));
        }
    }

    verify_prepared_rewrite_row_lineage(mutation)?;

    let id = mutation.session_id();
    let mut rewrite_idx = mutation.predecessor_head().rewrite_count;
    let mut expected_source = mutation.predecessor_head().strand.clone();
    let mut expected_source_len = mutation.predecessor_head().message_count;
    for step in mutation.steps() {
        if step.parent_base_seq() != expected_source_len {
            return Err(SessionStoreError::TranscriptContinuityViolation {
                id: id.clone(),
                previous_revision: format!(
                    "strand:{expected_source} logical-rows:{expected_source_len}"
                ),
                incoming_revision: format!("rewrite-parent-base:{}", step.parent_base_seq()),
                reason: "prepared rewrite parent bridge does not begin at the sealed strand tip"
                    .to_string(),
            });
        }
        reconcile_prepared_rewrite_parent_transition_in_txn(
            tx,
            mutation,
            step,
            &expected_source,
            expected_source_len,
        )?;
        reconcile_serialized_strand_rows_in_txn(
            tx,
            id,
            step.parent_strand(),
            step.parent_base_seq(),
            step.serialized_parent_suffix(),
        )?;
        let messages_before = u64::try_from(step.commit().messages_before)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
        let bridged_len = step
            .parent_base_seq()
            .checked_add(
                u64::try_from(step.serialized_parent_suffix().len())
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
            )
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if bridged_len != messages_before {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
        reconcile_prepared_rewrite_row_in_txn(tx, mutation, rewrite_idx, step)?;
        reconcile_prepared_rewrite_link_in_txn(tx, mutation, step)?;
        reconcile_serialized_strand_rows_in_txn(
            tx,
            id,
            step.strand(),
            step.link_splice().splice_start,
            step.serialized_replacement(),
        )?;
        rewrite_idx = rewrite_idx
            .checked_add(1)
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        expected_source = step.strand().clone();
        expected_source_len = u64::try_from(step.commit().messages_after)
            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    }
    if rewrite_idx != mutation.successor_head().rewrite_count {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    let final_strand = &mutation.successor_head().strand;
    if &expected_source != final_strand || expected_source_len != mutation.tail_base_seq() {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    reconcile_serialized_strand_rows_in_txn(
        tx,
        id,
        final_strand,
        mutation.tail_base_seq(),
        mutation.serialized_tail(),
    )?;
    let successor_anchor_rotated = head_has_current_row_lineage_anchor(mutation.successor_head())?
        && mutation.successor_head().row_lineage_anchor
            != mutation.predecessor_head().row_lineage_anchor;
    if successor_anchor_rotated {
        let additional_hops = mutation
            .steps()
            .len()
            .checked_mul(2)
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        let hop_budget =
            ordinary_topology_hop_budget(mutation.predecessor_head(), additional_hops)?;
        let links = bounded_strand_links_for_roots_in_txn(
            tx,
            id,
            std::slice::from_ref(final_strand),
            hop_budget,
        )?;
        let settled = settle_resolved_strand_direct_in_txn(
            tx,
            id,
            final_strand,
            mutation.successor_head().message_count,
            &links,
        )?;
        let observed = SessionMessageRowPrefixAccumulator::from_serialized_rows(&settled)?;
        let anchor = mutation
            .successor_head()
            .row_lineage_anchor
            .as_ref()
            .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
        if observed != *anchor.materialized_prefix() {
            return Err(SessionStoreError::Corrupted(id.clone()));
        }
    }
    if let Some(suffix) = mutation.realtime_suffix() {
        reconcile_prepared_component_suffix_in_txn(tx, suffix)?;
    }
    reconcile_head_metadata_transition_in_txn(
        tx,
        Some(mutation.predecessor_head()),
        Some(mutation.predecessor_head_token()),
        mutation.successor_head(),
        mutation.successor_head_token(),
    )?;
    let written_token = write_head_row_only_in_txn(tx, mutation.successor_head())?;
    if written_token != mutation.successor_head_token() {
        return Err(SessionStoreError::Internal(format!(
            "session {} prepared rewrite successor token changed during head write",
            mutation.session_id()
        )));
    }
    Ok(HeadCanonicalMutationApplyOutcome::Applied)
}

fn materialize_slim_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
    head: &SessionHead,
    stored_token: &str,
) -> Result<Session, SessionStoreError> {
    if &head.id != id || session_head_cas_token(head)? != stored_token {
        return Err(SessionStoreError::Corrupted(id.clone()));
    }
    Ok(verify_physical_head_canonical_in_txn(tx, head)?
        .session()
        .as_ref()
        .clone())
}

/// Head-canonical compat write: delta-append when the incoming transcript
/// extends the persisted head strand, otherwise a `rebase:` strand switch.
///
/// The rebase branch writes a whole transcript of rows, but the head write
/// point-settles (or, for rewrite-free state, deletes) only the exact strand
/// it left. It never scans the accumulated rewrite/link graph.
fn write_head_canonical_session_in_txn(
    tx: &Transaction<'_>,
    session: &Session,
    head: &SessionHead,
) -> Result<(), SessionStoreError> {
    let id = session.id();
    let live = session.messages();
    let prev_count = usize::try_from(head.message_count)
        .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
    // A superseded head strand no longer owns its rows, so it cannot be
    // appended to; such a head rebases onto a fresh materialized strand.
    let head_is_materialized = strand_link_in_txn(tx, id, &head.strand)?.is_none();
    let plain_append = head_is_materialized
        && live.len() >= prev_count
        && transcript_messages_digest(&live[..prev_count]).map_err(SessionStoreError::from)?
            == head.head_revision;
    let strand = if plain_append {
        if live.len() > prev_count {
            insert_strand_rows_in_txn(
                tx,
                id,
                &head.strand,
                head.message_count,
                &live[prev_count..],
            )?;
        }
        head.strand.clone()
    } else {
        let live_digest = transcript_messages_digest(live).map_err(SessionStoreError::from)?;
        let rebased = TranscriptStrandId::rebase(&live_digest);
        insert_strand_rows_in_txn(tx, id, &rebased, 0, live)?;
        rebased
    };
    let new_head = SessionHead::from_session(session, strand, head.rewrite_count)?;
    write_head_row_in_txn(tx, &new_head)?;
    Ok(())
}

/// SQLite-backed session store with one connection per operation.
pub struct SqliteSessionStore {
    path: PathBuf,
    options: SqliteConnectionOptions,
}

impl SqliteSessionStore {
    pub fn open(path: impl Into<PathBuf>) -> Result<Self, StoreError> {
        Self::open_with_options(path, SqliteConnectionOptions::default())
    }

    pub fn open_with_options(
        path: impl Into<PathBuf>,
        options: SqliteConnectionOptions,
    ) -> Result<Self, StoreError> {
        let path = path.into();
        let _guard = meerkat_sqlite::OperationGuard::for_database(&path)?;
        let conn = open_session_connection(&path, options)?;
        drop(conn);
        Ok(Self { path, options })
    }

    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl SqliteSessionStore {
    async fn in_write_txn<T, F>(&self, op: F) -> Result<T, SessionStoreError>
    where
        T: Send + 'static,
        F: FnOnce(&Transaction<'_>) -> Result<T, SessionStoreError> + Send + 'static,
    {
        let path = self.path.clone();
        let options = self.options;
        tokio::task::spawn_blocking(move || -> Result<T, SessionStoreError> {
            let _guard = meerkat_sqlite::OperationGuard::for_database(&path)
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            let mut conn =
                open_session_connection(&path, options).map_err(into_session_store_error)?;
            let tx = begin_immediate_transaction_with_options(&mut conn, options)
                .map_err(into_session_store_error)?;
            let value = op(&tx)?;
            tx.commit()
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            Ok(value)
        })
        .await
        .map_err(StoreError::Join)
        .map_err(into_session_store_error)?
    }

    /// Consistent multi-row read snapshot without taking the write lock.
    async fn in_read_txn<T, F>(&self, op: F) -> Result<T, SessionStoreError>
    where
        T: Send + 'static,
        F: FnOnce(&Transaction<'_>) -> Result<T, SessionStoreError> + Send + 'static,
    {
        let path = self.path.clone();
        let options = self.options;
        tokio::task::spawn_blocking(move || -> Result<T, SessionStoreError> {
            let _guard = meerkat_sqlite::OperationGuard::for_database(&path)
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            let mut conn =
                open_session_connection(&path, options).map_err(into_session_store_error)?;
            let tx = conn
                .transaction()
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            let value = op(&tx)?;
            tx.commit()
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            Ok(value)
        })
        .await
        .map_err(StoreError::Join)
        .map_err(into_session_store_error)?
    }
}

#[async_trait]
impl SessionStore for SqliteSessionStore {
    async fn save(&self, session: &Session) -> Result<(), SessionStoreError> {
        // F1 closure (wave-c C-H1): reject shrink-attempts at the trait
        // boundary before the row is overwritten on disk.
        let session = session.clone();
        self.in_write_txn(move |tx| {
            if let Some((head, stored_token)) = head_row_in_txn(tx, session.id())? {
                // Head-canonical: retained history lives out-of-line; the
                // plain save writes ONLY the delta rows + the small head.
                let previous = materialize_slim_in_txn(tx, session.id(), &head, &stored_token)?;
                head_canonical_plain_save_guard_with_prefix_witness(
                    &session,
                    &previous,
                    head.rewrite_count,
                    &head.rewrite_prefix,
                    SaveGuardWitness::none().with_previous_revision(&head.head_revision),
                )?;
                write_head_canonical_session_in_txn(tx, &session, &head)?;
                return Ok(());
            }
            let previous =
                load_session_snapshot_in_txn(tx, session.id()).map_err(into_session_store_error)?;
            meerkat_core::session_store::append_only_save_guard(&session, previous.as_ref())?;
            write_session_snapshot_in_txn(tx, &session).map_err(into_session_store_error)?;
            Ok(())
        })
        .await
    }

    async fn save_transcript_rewrite(
        &self,
        session: &Session,
        commit: &meerkat_core::TranscriptRewriteCommit,
    ) -> Result<(), SessionStoreError> {
        let session = session.clone();
        let commit = commit.clone();
        self.in_write_txn(move |tx| {
            if head_row_in_txn(tx, session.id())?.is_some() {
                // A TranscriptRewriteRecord does not bind the occurrence
                // generation, parent advance, graph prefix, or row-lineage
                // witnesses needed by cold replay. Never manufacture or
                // adopt a NULL edge for a current HeadCanonical session.
                return Err(legacy_head_canonical_rewrite_error(session.id()));
            }
            let previous =
                load_session_snapshot_in_txn(tx, session.id()).map_err(into_session_store_error)?;
            meerkat_core::session_store::transcript_rewrite_save_guard(
                &session,
                previous.as_ref(),
                &commit,
            )?;
            write_session_snapshot_in_txn(tx, &session).map_err(into_session_store_error)?;
            Ok(())
        })
        .await
    }

    async fn save_authoritative_projection(
        &self,
        session: &Session,
    ) -> Result<(), SessionStoreError> {
        let session = session.clone();
        self.in_write_txn(move |tx| {
            if let Some((head, stored_token)) = head_row_in_txn(tx, session.id())? {
                if session_head_cas_token(&head)? != stored_token {
                    return Err(SessionStoreError::Corrupted(session.id().clone()));
                }
                write_head_canonical_session_in_txn(tx, &session, &head)?;
                return Ok(());
            }
            write_session_snapshot_in_txn(tx, &session).map_err(into_session_store_error)?;
            Ok(())
        })
        .await
    }

    async fn save_authoritative_projection_if_current_revision(
        &self,
        session: &Session,
        expected_current_revision: Option<String>,
    ) -> Result<(), SessionStoreError> {
        let session = session.clone();
        self.in_write_txn(move |tx| {
            if let Some((head, stored_token)) = head_row_in_txn(tx, session.id())? {
                // The caller's token was computed over the slim
                // materialization it loaded; the same deterministic
                // materialization is compared here.
                let previous = materialize_slim_in_txn(tx, session.id(), &head, &stored_token)?;
                meerkat_core::session_store::authoritative_projection_current_revision_guard(
                    &session,
                    Some(&previous),
                    expected_current_revision.as_deref(),
                )?;
                write_head_canonical_session_in_txn(tx, &session, &head)?;
                return Ok(());
            }
            let previous =
                load_session_snapshot_in_txn(tx, session.id()).map_err(into_session_store_error)?;
            meerkat_core::session_store::authoritative_projection_current_revision_guard(
                &session,
                previous.as_ref(),
                expected_current_revision.as_deref(),
            )?;
            write_session_snapshot_in_txn(tx, &session).map_err(into_session_store_error)?;
            Ok(())
        })
        .await
    }

    async fn load(&self, id: &SessionId) -> Result<Option<Session>, SessionStoreError> {
        let id = id.clone();
        self.in_read_txn(move |tx| {
            if let Some((head, stored_token)) = head_row_in_txn(tx, &id)? {
                // Slim, no history metadata — the O(live) cold-resume contract.
                return Ok(Some(materialize_slim_in_txn(
                    tx,
                    &id,
                    &head,
                    &stored_token,
                )?));
            }
            load_session_snapshot_in_txn(tx, &id).map_err(into_session_store_error)
        })
        .await
    }

    async fn list(&self, filter: SessionFilter) -> Result<Vec<SessionMeta>, SessionStoreError> {
        let path = self.path.clone();
        let options = self.options;
        tokio::task::spawn_blocking(move || -> Result<Vec<SessionMeta>, SessionStoreError> {
            enum ListedSession {
                Head {
                    raw_id: String,
                    head_json: Vec<u8>,
                    stored_token: String,
                },
                Legacy(SessionMeta),
            }

            let _guard = meerkat_sqlite::OperationGuard::for_database(&path)
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            let conn = open_session_connection(&path, options).map_err(into_session_store_error)?;
            let created_after = filter.created_after.map(system_time_millis);
            let updated_after = filter.updated_after.map(system_time_millis);
            let offset = i64::try_from(filter.offset.unwrap_or(0)).map_err(|_| {
                SessionStoreError::Internal("session list offset exceeds SQLite range".to_string())
            })?;
            // SQLite's documented LIMIT -1 form means "no limit" while still
            // admitting an OFFSET. This keeps pagination in the query for both
            // bounded and unbounded callers.
            let limit = match filter.limit {
                Some(limit) => i64::try_from(limit).map_err(|_| {
                    SessionStoreError::Internal(
                        "session list limit exceeds SQLite range".to_string(),
                    )
                })?,
                None => -1,
            };

            // Page the compact head/legacy projections first. In particular,
            // do not resolve every digest-addressed metadata payload only to
            // discard most of them during in-memory pagination.
            let mut statement = conn
                .prepare(
                    r"
                    SELECT session_id, created_at_ms, updated_at_ms, message_count,
                           total_tokens, projection_json, cas_token, is_head
                    FROM (
                        SELECT session_id, created_at_ms, updated_at_ms, message_count,
                               total_tokens, head_json AS projection_json,
                               cas_token, 1 AS is_head
                        FROM session_heads
                        WHERE (?1 IS NULL OR created_at_ms >= ?1)
                          AND (?2 IS NULL OR updated_at_ms >= ?2)

                        UNION ALL

                        SELECT session_id, created_at_ms, updated_at_ms, message_count,
                               total_tokens, metadata_json AS projection_json,
                               NULL AS cas_token, 0 AS is_head
                        FROM sessions AS legacy
                        WHERE (?1 IS NULL OR created_at_ms >= ?1)
                          AND (?2 IS NULL OR updated_at_ms >= ?2)
                          AND NOT EXISTS (
                              SELECT 1
                              FROM session_heads AS canonical
                              WHERE canonical.session_id = legacy.session_id
                          )
                    )
                    ORDER BY updated_at_ms DESC, session_id ASC
                    LIMIT ?3 OFFSET ?4
                    ",
                )
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            let selected = statement
                .query_map(
                    params![created_after, updated_after, limit, offset],
                    |row| {
                        if row.get::<_, i64>(7)? == 1 {
                            Ok(ListedSession::Head {
                                raw_id: row.get(0)?,
                                head_json: row.get::<_, JsonColumnBytes>(5)?.into_bytes(),
                                stored_token: row.get(6)?,
                            })
                        } else {
                            Ok(ListedSession::Legacy(session_meta_from_row(row)?))
                        }
                    },
                )
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?
                .collect::<Result<Vec<_>, _>>()
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            drop(statement);

            let mut metas = Vec::with_capacity(selected.len());
            for selected in selected {
                match selected {
                    ListedSession::Head {
                        raw_id,
                        head_json,
                        stored_token,
                    } => {
                        let id = parse_session_id(raw_id).map_err(into_session_store_error)?;
                        let mut head: SessionHead = serde_json::from_slice(&head_json)
                            .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
                        if head.id != id || session_head_cas_token(&head)? != stored_token {
                            return Err(SessionStoreError::Corrupted(id));
                        }
                        attach_head_metadata_projection(
                            &conn,
                            &mut head,
                            HeadMetadataProjectionOwner::PhysicalHead,
                        )?;
                        metas.push(session_meta_from_head(&head)?);
                    }
                    ListedSession::Legacy(meta) => metas.push(meta),
                }
            }
            Ok(metas)
        })
        .await
        .map_err(StoreError::Join)
        .map_err(into_session_store_error)?
    }

    /// Metadata-only partial read over the durable head projection and its
    /// authenticated metadata cells — head row wins, the legacy session row
    /// is the fallback. Never touches `session_json` or strand rows.
    async fn load_meta(&self, id: &SessionId) -> Result<Option<SessionMeta>, SessionStoreError> {
        let path = self.path.clone();
        let options = self.options;
        let id = id.clone();
        tokio::task::spawn_blocking(move || -> Result<Option<SessionMeta>, SessionStoreError> {
            let _guard = meerkat_sqlite::OperationGuard::for_database(&path)
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            let conn = open_session_connection(&path, options).map_err(into_session_store_error)?;
            let head_row = conn
                .query_row(
                    r"
                    SELECT head_json, cas_token
                    FROM session_heads
                    WHERE session_id = ?1
                    ",
                    params![id.to_string()],
                    |row| {
                        Ok((
                            row.get::<_, JsonColumnBytes>(0)?.into_bytes(),
                            row.get::<_, String>(1)?,
                        ))
                    },
                )
                .optional()
                .map_err(StoreError::from)
                .map_err(into_session_store_error)?;
            if let Some((head_json, stored_token)) = head_row {
                let mut head: SessionHead = serde_json::from_slice(&head_json)
                    .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
                if head.id != id || session_head_cas_token(&head)? != stored_token {
                    return Err(SessionStoreError::Corrupted(id));
                }
                attach_head_metadata_projection(
                    &conn,
                    &mut head,
                    HeadMetadataProjectionOwner::PhysicalHead,
                )?;
                return Ok(Some(session_meta_from_head(&head)?));
            }
            conn.query_row(
                r"
                SELECT session_id, created_at_ms, updated_at_ms, message_count,
                       total_tokens, metadata_json
                FROM sessions
                WHERE session_id = ?1
                ",
                params![id.to_string()],
                session_meta_from_row,
            )
            .optional()
            .map_err(StoreError::from)
            .map_err(into_session_store_error)
        })
        .await
        .map_err(StoreError::Join)
        .map_err(into_session_store_error)?
    }

    async fn delete(&self, id: &SessionId) -> Result<(), SessionStoreError> {
        let id = id.clone();
        self.in_write_txn(move |tx| {
            delete_all_session_rows_in_txn(tx, &id)?;
            Ok(())
        })
        .await
    }

    async fn delete_if_current_revision(
        &self,
        id: &SessionId,
        expected_current_revision: &str,
    ) -> Result<bool, SessionStoreError> {
        let session_id = id.clone();
        let expected_current_revision = expected_current_revision.to_string();
        self.in_write_txn(move |tx| {
            let previous = if let Some((head, stored_token)) = head_row_in_txn(tx, &session_id)? {
                Some(materialize_slim_in_txn(
                    tx,
                    &session_id,
                    &head,
                    &stored_token,
                )?)
            } else {
                load_session_snapshot_in_txn(tx, &session_id).map_err(into_session_store_error)?
            };
            let Some(previous) = previous else {
                return Ok(false);
            };
            let previous_token =
                meerkat_core::session_store::session_projection_cas_token(&previous)?;
            if previous_token != expected_current_revision {
                return Ok(false);
            }
            delete_all_session_rows_in_txn(tx, &session_id)?;
            Ok(true)
        })
        .await
    }

    fn as_incremental(self: Arc<Self>) -> Option<Arc<dyn IncrementalSessionStore>> {
        Some(self)
    }
}

fn session_meta_from_head(head: &SessionHead) -> Result<SessionMeta, SessionStoreError> {
    let message_count = usize::try_from(head.message_count)
        .map_err(|_| SessionStoreError::Corrupted(head.id.clone()))?;
    Ok(SessionMeta {
        id: head.id.clone(),
        created_at: head.created_at,
        updated_at: head.updated_at,
        message_count,
        total_tokens: head.usage.total_tokens(),
        metadata: head.materialized_metadata()?,
    })
}

fn session_meta_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<SessionMeta> {
    let metadata_json = row.get::<_, JsonColumnBytes>(5)?.into_bytes();
    let metadata = serde_json::from_slice(&metadata_json).map_err(|err| {
        rusqlite::Error::FromSqlConversionFailure(5, rusqlite::types::Type::Text, Box::new(err))
    })?;
    let id = parse_session_id(row.get(0)?).map_err(|err| {
        rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(err))
    })?;
    // Derived projection counters are stored as i64; negative or
    // out-of-range values are impossible durable states and fail closed
    // (terminal-truth store-metadata cluster).
    let message_count = usize::try_from(row.get::<_, i64>(3)?).map_err(|_| {
        rusqlite::Error::FromSqlConversionFailure(
            3,
            rusqlite::types::Type::Integer,
            Box::new(StoreError::Corrupted(id.clone())),
        )
    })?;
    let total_tokens = u64::try_from(row.get::<_, i64>(4)?).map_err(|_| {
        rusqlite::Error::FromSqlConversionFailure(
            4,
            rusqlite::types::Type::Integer,
            Box::new(StoreError::Corrupted(id.clone())),
        )
    })?;
    Ok(SessionMeta {
        id,
        created_at: millis_to_system_time(row.get(1)?),
        updated_at: millis_to_system_time(row.get(2)?),
        message_count,
        total_tokens,
        metadata,
    })
}

fn delete_all_session_rows_in_txn(
    tx: &Transaction<'_>,
    id: &SessionId,
) -> Result<(), SessionStoreError> {
    let retained_runtime_boundary = tx
        .query_row(
            r"
            SELECT 1
            FROM session_head_metadata_refs
            WHERE session_id = ?1 AND owner = 'runtime_boundary'
            LIMIT 1
            ",
            params![id.to_string()],
            |_row| Ok(()),
        )
        .optional()
        .map_err(StoreError::from)
        .map_err(into_session_store_error)?
        .is_some();
    if retained_runtime_boundary {
        return Err(SessionStoreError::InvalidTranscriptRewrite {
            id: id.clone(),
            reason:
                "session deletion requires its retained runtime-boundary authority to be deleted first"
                    .to_string(),
        });
    }
    for sql in [
        "DELETE FROM sessions WHERE session_id = ?1",
        "DELETE FROM session_strand_messages WHERE session_id = ?1",
        "DELETE FROM session_strand_links WHERE session_id = ?1",
        "DELETE FROM session_rewrites WHERE session_id = ?1",
        "DELETE FROM session_component_events WHERE session_id = ?1",
        "DELETE FROM session_head_metadata_refs WHERE session_id = ?1",
        "DELETE FROM session_head_metadata_head_lineage WHERE session_id = ?1",
        "DELETE FROM session_head_metadata_state_deltas WHERE session_id = ?1",
        "DELETE FROM session_head_metadata_states WHERE session_id = ?1",
        "DELETE FROM session_head_metadata_current WHERE session_id = ?1",
        "DELETE FROM session_head_metadata_cells WHERE session_id = ?1",
        "DELETE FROM session_heads WHERE session_id = ?1",
    ] {
        tx.execute(sql, params![id.to_string()])
            .map_err(StoreError::from)
            .map_err(into_session_store_error)?;
    }
    Ok(())
}

fn legacy_head_canonical_rewrite_error(id: &SessionId) -> SessionStoreError {
    SessionStoreError::InvalidTranscriptRewrite {
        id: id.clone(),
        reason: "HeadCanonical rewrites require PreparedHeadCanonicalRewriteMutation; the legacy TranscriptRewriteRecord path cannot prove an exact compact replay edge"
            .to_string(),
    }
}

#[async_trait]
impl IncrementalSessionStore for SqliteSessionStore {
    async fn activate_head_canonical_store(
        &self,
    ) -> Result<HeadCanonicalStoreActivation, SessionStoreError> {
        self.in_write_txn(activate_head_canonical_store_in_txn)
            .await
    }

    async fn cross_head_canonical_authority(
        &self,
        id: &SessionId,
    ) -> Result<HeadCanonicalAuthorityCrossing, SessionStoreError> {
        let id = id.clone();
        self.in_write_txn(move |tx| cross_head_canonical_authority_in_txn(tx, &id))
            .await
    }

    async fn append_messages(
        &self,
        id: &SessionId,
        strand: &TranscriptStrandId,
        base_seq: u64,
        messages: &[Message],
    ) -> Result<(), SessionStoreError> {
        let id = id.clone();
        let strand = strand.clone();
        let messages = messages.to_vec();
        self.in_write_txn(move |tx| {
            // First incremental write on a blob-only session migrates it.
            let _ = ensure_head_canonical_for_write_in_txn(tx, &id)?;
            insert_strand_rows_in_txn(tx, &id, &strand, base_seq, &messages)
        })
        .await
    }

    async fn commit_rewrite(
        &self,
        id: &SessionId,
        _record: &TranscriptRewriteRecord,
        _expected: SessionHeadCas,
    ) -> Result<SessionHead, SessionStoreError> {
        Err(legacy_head_canonical_rewrite_error(id))
    }

    async fn save_head(
        &self,
        head: &SessionHead,
        expected: SessionHeadCas,
    ) -> Result<(), SessionStoreError> {
        let head = head.clone();
        self.in_write_txn(move |tx| {
            let stored = ensure_head_canonical_for_write_in_txn(tx, &head.id)?;
            let replay_start = head
                .row_lineage_anchor
                .as_ref()
                .map_or(0, |anchor| anchor.rewrite_count());
            if post_anchor_rewrite_graph_edge_is_missing_in_txn(
                tx,
                &head.id,
                replay_start,
                head.rewrite_count,
            )? {
                return Err(legacy_head_canonical_rewrite_error(&head.id));
            }
            let hop_budget = ordinary_topology_hop_budget(&head, 0)?;
            let links = bounded_strand_links_for_roots_in_txn(
                tx,
                &head.id,
                std::slice::from_ref(&head.strand),
                hop_budget,
            )?;
            let strand_len = strand_logical_len_in_txn(tx, &head.id, &head.strand, &links)?;
            let recorded = rewrite_row_count_in_txn(tx, &head.id)?;
            validate_save_head_transition(
                &head,
                stored.as_ref().map(|(h, t)| (h, t.as_str())),
                &expected,
                strand_len,
                recorded,
            )?;
            write_head_row_in_txn(tx, &head)?;
            Ok(())
        })
        .await
    }

    async fn load_head(&self, id: &SessionId) -> Result<Option<SessionHead>, SessionStoreError> {
        let id = id.clone();
        self.in_read_txn(move |tx| {
            if let Some((head, _token)) = head_row_in_txn(tx, &id)? {
                return Ok(Some(head));
            }
            // Blob-only session: synthesize read-only (no write). The layout
            // is deterministic, so the token a caller derives here matches
            // the one the first migrating write persists.
            let Some(session) =
                load_session_snapshot_in_txn(tx, &id).map_err(into_session_store_error)?
            else {
                return Ok(None);
            };
            let (_layout, head) = layout_for_blob_session(&session)?;
            Ok(Some(head))
        })
        .await
    }

    async fn apply_prepared_head_canonical_mutation(
        &self,
        mutation: &PreparedHeadCanonicalMutation,
    ) -> Result<String, SessionStoreError> {
        let mutation = mutation.clone();
        self.in_write_txn(move |tx| {
            let _ = apply_prepared_head_canonical_mutation_in_txn(tx, &mutation)?;
            Ok(mutation.successor_head_token().to_string())
        })
        .await
    }

    async fn apply_prepared_head_canonical_rewrite_mutation(
        &self,
        mutation: &PreparedHeadCanonicalRewriteMutation,
    ) -> Result<String, SessionStoreError> {
        let mutation = mutation.clone();
        self.in_write_txn(move |tx| {
            let _ = apply_prepared_head_canonical_rewrite_mutation_in_txn(tx, &mutation)?;
            Ok(mutation.successor_head_token().to_string())
        })
        .await
    }

    async fn materialize_head(
        &self,
        expected: &SessionHead,
    ) -> Result<meerkat_core::VerifiedSessionHeadMaterialization, SessionStoreError> {
        let expected = expected.clone();
        self.in_read_txn(move |tx| {
            let (current, stored_token) = head_row_in_txn(tx, &expected.id)?
                .ok_or_else(|| SessionStoreError::NotFound(expected.id.clone()))?;
            let current_token = session_head_cas_token(&current)?;
            if current_token != stored_token {
                return Err(SessionStoreError::Corrupted(expected.id));
            }
            let expected_token = session_head_cas_token(&expected)?;
            if expected_token != current_token {
                return Err(SessionStoreError::TranscriptRevisionConflict {
                    id: expected.id,
                    expected: expected_token,
                    actual: current_token,
                });
            }
            verify_physical_head_canonical_in_txn(tx, &current)
        })
        .await
    }

    async fn load_messages(
        &self,
        id: &SessionId,
        strand: &TranscriptStrandId,
        range: std::ops::Range<u64>,
    ) -> Result<Vec<Message>, SessionStoreError> {
        let id = id.clone();
        let strand = strand.clone();
        self.in_read_txn(move |tx| {
            if head_row_in_txn(tx, &id)?.is_some() {
                return strand_messages_in_txn(tx, &id, &strand, range);
            }
            let Some(session) =
                load_session_snapshot_in_txn(tx, &id).map_err(into_session_store_error)?
            else {
                return Err(SessionStoreError::NotFound(id));
            };
            let (layout, _head) = layout_for_blob_session(&session)?;
            let rows = blob_strand_messages(&session, &layout, &strand)?;
            let start = usize::try_from(range.start)
                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
            let end =
                usize::try_from(range.end).map_err(|_| SessionStoreError::Corrupted(id.clone()))?;
            if start > end || end > rows.len() {
                return Err(SessionStoreError::Corrupted(id));
            }
            Ok(rows[start..end].to_vec())
        })
        .await
    }

    async fn load_rewrites(
        &self,
        id: &SessionId,
    ) -> Result<Vec<TranscriptRewriteRecord>, SessionStoreError> {
        let id = id.clone();
        self.in_read_txn(move |tx| {
            if let Some((head, _token)) = head_row_in_txn(tx, &id)? {
                let rows = rewrite_rows_in_txn(tx, &id, head.rewrite_count)?;
                // One link map for the whole reconstruction: each retained
                // body resolves through its exact overlay chain.
                let links = strand_links_in_txn(tx, &id)?;
                return rows
                    .into_iter()
                    .map(|row| {
                        let parent_messages = strand_messages_with_links_in_txn(
                            tx,
                            &id,
                            &row.parent_strand,
                            0..row.parent_len,
                            &links,
                        )?;
                        let revision_messages = strand_messages_with_links_in_txn(
                            tx,
                            &id,
                            &row.strand,
                            0..row.strand_len,
                            &links,
                        )?;
                        reconstruct_rewrite_record(
                            &id,
                            row.commit,
                            parent_messages,
                            revision_messages,
                        )
                    })
                    .collect();
            }
            let Some(session) =
                load_session_snapshot_in_txn(tx, &id).map_err(into_session_store_error)?
            else {
                return Ok(Vec::new());
            };
            let history = session
                .validated_transcript_history_state()
                .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
                    id: id.clone(),
                    reason: format!("stored transcript history state is malformed: {error}"),
                })?;
            let (layout, _head) = layout_for_blob_session(&session)?;
            let Some(history) = history else {
                if layout.rewrites.is_empty() {
                    return Ok(Vec::new());
                }
                return Err(SessionStoreError::Corrupted(id));
            };
            layout
                .rewrites
                .into_iter()
                .map(|rewrite| {
                    let parent_messages = history
                        .materialize_rewrite_parent(&rewrite.commit)
                        .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
                            id: id.clone(),
                            reason: format!("failed to materialize blob rewrite parent: {error}"),
                        })?
                        .messages;
                    let revision_messages = history
                        .materialize_rewrite_child(&rewrite.commit)
                        .map_err(|error| SessionStoreError::InvalidTranscriptRewrite {
                            id: id.clone(),
                            reason: format!("failed to materialize blob rewrite child: {error}"),
                        })?
                        .messages;
                    reconstruct_rewrite_record(
                        &id,
                        rewrite.commit,
                        parent_messages,
                        revision_messages,
                    )
                })
                .collect()
        })
        .await
    }

    async fn load_canonical_head(
        &self,
        id: &SessionId,
    ) -> Result<Option<SessionHead>, SessionStoreError> {
        let id = id.clone();
        // Head row ONLY: unlike `load_head`, a blob-only session gets `None`
        // rather than an O(document) synthesized head (no blob read at all).
        self.in_read_txn(move |tx| Ok(head_row_in_txn(tx, &id)?.map(|(head, _token)| head)))
            .await
    }

    async fn load_rewrite_commits(
        &self,
        id: &SessionId,
    ) -> Result<Vec<TranscriptRewriteCommit>, SessionStoreError> {
        let id = id.clone();
        self.in_read_txn(move |tx| {
            if let Some((head, _token)) = head_row_in_txn(tx, &id)? {
                // The commit half of the rewrite rows only (bounded by the
                // adopted count); no strand-body reads.
                return Ok(rewrite_rows_in_txn(tx, &id, head.rewrite_count)?
                    .into_iter()
                    .map(|row| row.commit)
                    .collect());
            }
            // Blob-only session: derive the commits from the frozen blob's
            // layout so the answer always equals `load_rewrites`' commits.
            // (Blob-only sessions are never served by the fast read path —
            // `load_canonical_head` is `None` — so this arm is contract
            // parity, not a hot path.)
            let Some(session) =
                load_session_snapshot_in_txn(tx, &id).map_err(into_session_store_error)?
            else {
                return Ok(Vec::new());
            };
            let (layout, _head) = layout_for_blob_session(&session)?;
            Ok(layout
                .rewrites
                .into_iter()
                .map(|rewrite| rewrite.commit)
                .collect())
        })
        .await
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;
    use meerkat_core::types::{
        AssistantBlock, BlockAssistantMessage, Message, SystemMessage, UserMessage,
    };
    use meerkat_core::{StopReason, TranscriptRewriteReason, TranscriptRewriteSelection};
    use tempfile::TempDir;

    fn temp_store() -> (TempDir, SqliteSessionStore) {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("sessions.sqlite3");
        let store = SqliteSessionStore::open(&path).unwrap();
        (dir, store)
    }

    /// The durable-writer invariant for the session store, asserted through
    /// the constructor every surface calls. Read back over a connection the
    /// store did not configure, because journal mode belongs to the file: a
    /// rollback-journal session database would take a database-wide
    /// EXCLUSIVE lock for every write.
    #[test]
    fn production_session_store_open_leaves_the_database_in_wal() {
        let (_dir, store) = temp_store();
        let conn = meerkat_sqlite::open(store.path(), meerkat_sqlite::ConnectionProfile::ReadOnly)
            .expect("read-only reopen");
        let mode: String = conn
            .pragma_query_value(None, "journal_mode", |row| row.get(0))
            .expect("journal_mode");
        assert_eq!(mode, "wal");
    }

    #[test]
    fn busy_writer_is_retried_with_per_store_policy() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("busy.sqlite3");
        let options = SqliteConnectionOptions {
            busy_timeout: Duration::from_millis(250),
        };
        let (locked_tx, locked_rx) = std::sync::mpsc::channel();
        let holder_path = path.clone();
        let holder = std::thread::spawn(move || {
            let mut connection = open_connection_with_options(&holder_path, options).unwrap();
            let transaction =
                begin_immediate_transaction_with_options(&mut connection, options).unwrap();
            locked_tx.send(()).unwrap();
            std::thread::sleep(Duration::from_millis(120));
            transaction.commit().unwrap();
        });
        locked_rx.recv().unwrap();

        let mut contender = open_connection_with_options(&path, options).unwrap();
        let transaction = begin_immediate_transaction_with_options(&mut contender, options)
            .expect("bounded busy retry should survive the concurrent writer");
        transaction.commit().unwrap();
        holder.join().unwrap();
    }

    #[test]
    fn ensure_schema_stamps_the_session_domain_ledger() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("schema.sqlite3");
        let mut conn = open_connection(&path).unwrap();
        ensure_schema(&mut conn).unwrap();
        assert_eq!(
            meerkat_sqlite::domain_version(&conn, SESSION_STORE_DOMAIN.name).unwrap(),
            Some(SESSION_STORE_DOMAIN.supported_version())
        );
        // The DDL actually ran under the ledger.
        conn.query_row("SELECT COUNT(*) FROM session_heads", [], |row| {
            row.get::<_, i64>(0)
        })
        .unwrap();
        conn.query_row("SELECT COUNT(*) FROM session_component_events", [], |row| {
            row.get::<_, i64>(0)
        })
        .unwrap();
        for table in [
            "session_head_metadata_cells",
            "session_head_metadata_current",
            "session_head_metadata_states",
            "session_head_metadata_state_deltas",
            "session_head_metadata_refs",
            "session_head_metadata_head_lineage",
        ] {
            conn.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
                row.get::<_, i64>(0)
            })
            .unwrap();
        }
        let route_index: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM sqlite_master \
                 WHERE type = 'index' AND name = 'session_head_metadata_cells_route_key_idx'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            route_index, 1,
            "changed-cell collision checks require the covering route/key index"
        );
        let metadata_cell_columns = conn
            .prepare("PRAGMA table_info(session_head_metadata_cells)")
            .unwrap()
            .query_map([], |row| row.get::<_, String>(1))
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        assert_eq!(
            metadata_cell_columns,
            [
                "session_id",
                "metadata_key",
                "key_route",
                "exact_value_digest",
                "metadata_json",
                "created_at_ms",
            ],
            "metadata cells have one exact byte-derived identity column"
        );
    }

    #[tokio::test]
    async fn exact_released_0810_corpus_imports_and_fully_loads_current_session() {
        let workspace_root = std::env::var_os("MEERKAT_WORKSPACE_ROOT")
            .map(PathBuf::from)
            .or_else(|| {
                std::env::current_dir()
                    .ok()
                    .filter(|root| root.join("Cargo.toml").is_file())
            })
            .unwrap_or_else(|| {
                Path::new(env!("CARGO_MANIFEST_DIR"))
                    .parent()
                    .expect("meerkat-store manifest has a workspace parent")
                    .to_path_buf()
            });
        let source = workspace_root.join(
            "meerkat-runtime/tests/fixtures/v0_8_10_released_realm/corpus/realm/sessions.sqlite3",
        );
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("sessions.sqlite3");
        std::fs::copy(&source, &path).expect("copy exact released 0.8.10 corpus database");

        let raw = open_connection(&path).unwrap();
        let raw_id = raw
            .query_row(
                "SELECT session_id FROM session_heads ORDER BY session_id LIMIT 1",
                [],
                |row| row.get::<_, String>(0),
            )
            .expect("released corpus head identity");
        drop(raw);
        let id = SessionId::parse(&raw_id).expect("released corpus session identity");

        let store = SqliteSessionStore::open(&path)
            .expect("current store migrates the exact released 0.8.10 corpus");
        let session = store
            .load(&id)
            .await
            .expect("fully materialize migrated released session")
            .expect("released corpus session remains present");
        assert_eq!(session.version(), meerkat_core::SESSION_VERSION);
        assert_eq!(session.messages().len(), 5);
        assert!(
            !session
                .metadata()
                .contains_key("session_checkpoint_stamp_v1"),
            "the frozen importer must retire released checkpoint metadata"
        );
        assert!(
            !session
                .metadata()
                .contains_key("session_system_context_state"),
            "the frozen importer must adopt and retire released System context"
        );
        session
            .validated_transcript_history_state()
            .expect("imported transcript history must use the current validated wire");

        let head = IncrementalSessionStore::load_head(&store, &id)
            .await
            .expect("load migrated released head")
            .expect("released corpus head remains present");
        assert_eq!(head.version, meerkat_core::SESSION_VERSION);

        let migrated = open_connection(&path).unwrap();
        let (row_version, embedded_version, stored_token): (i64, u32, String) = migrated
            .query_row(
                "SELECT version, head_json, cas_token
                 FROM session_heads
                 WHERE session_id = ?1",
                params![id.to_string()],
                |row| {
                    let head_json = row.get::<_, JsonColumnBytes>(1)?.into_bytes();
                    let head: SessionHead =
                        serde_json::from_slice(&head_json).expect("decode migrated corpus head");
                    Ok((row.get(0)?, head.version, row.get(2)?))
                },
            )
            .expect("read migrated corpus head envelope");
        assert_eq!(row_version, i64::from(meerkat_core::SESSION_VERSION));
        assert_eq!(embedded_version, meerkat_core::SESSION_VERSION);
        assert_eq!(
            stored_token,
            session_head_cas_token(&head).expect("migrated corpus head token")
        );
    }

    #[test]
    fn ensure_schema_refuses_a_future_domain_version() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("future.sqlite3");
        let mut conn = open_connection(&path).unwrap();
        conn.execute_batch(
            "CREATE TABLE meerkat_schema (domain TEXT PRIMARY KEY, version INTEGER NOT NULL)",
        )
        .unwrap();
        conn.execute(
            "INSERT INTO meerkat_schema (domain, version) VALUES (?1, ?2)",
            params![
                SESSION_STORE_DOMAIN.name,
                SESSION_STORE_DOMAIN.supported_version() + 1
            ],
        )
        .unwrap();
        let err = ensure_schema(&mut conn).expect_err("future schema must be refused");
        assert!(
            matches!(err, StoreError::SchemaFromTheFuture { .. }),
            "unexpected error: {err:?}"
        );
    }

    #[tokio::test]
    async fn save_load_roundtrip() {
        let (_dir, store) = temp_store();
        let mut session = Session::new();
        session.push(Message::User(UserMessage::text("hello".to_string())));

        store.save(&session).await.unwrap();
        let loaded = store.load(session.id()).await.unwrap().unwrap();
        assert_eq!(loaded.id(), session.id());
        assert_eq!(loaded.messages().len(), 1);
    }

    #[tokio::test]
    async fn load_surfaces_corrupt_session_blob_as_serialization_error() {
        let (_dir, store) = temp_store();
        let session = Session::new();
        store.save(&session).await.unwrap();

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE sessions SET session_json = ?1 WHERE session_id = ?2",
            params![
                b"{ not a serialized Session".as_slice(),
                session.id().to_string()
            ],
        )
        .unwrap();

        let error = store
            .load(session.id())
            .await
            .expect_err("corrupt persisted Session bytes must fail load");
        assert!(
            matches!(error, SessionStoreError::Serialization(_)),
            "corrupt persisted Session bytes must remain a typed serialization error, got {error:?}"
        );
    }

    #[tokio::test]
    async fn list_is_ordered_by_updated_desc() {
        let (_dir, store) = temp_store();
        let first = Session::new();
        store.save(&first).await.unwrap();
        std::thread::sleep(Duration::from_millis(10));

        let second = Session::new();
        store.save(&second).await.unwrap();

        let sessions = store.list(SessionFilter::default()).await.unwrap();
        assert_eq!(sessions.len(), 2);
        assert_eq!(sessions[0].id, *second.id());
        assert_eq!(sessions[1].id, *first.id());
    }

    #[tokio::test]
    async fn delete_removes_session() {
        let (_dir, store) = temp_store();
        let session = Session::new();
        store.save(&session).await.unwrap();
        store.delete(session.id()).await.unwrap();
        assert!(store.load(session.id()).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn reopen_reads_existing_data() {
        let (dir, store) = temp_store();
        let session = Session::new();
        store.save(&session).await.unwrap();

        let reopened = SqliteSessionStore::open(dir.path().join("sessions.sqlite3")).unwrap();
        assert!(reopened.load(session.id()).await.unwrap().is_some());
    }

    #[tokio::test]
    async fn two_handles_share_same_file() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("sessions.sqlite3");
        let first = SqliteSessionStore::open(&path).unwrap();
        let second = SqliteSessionStore::open(&path).unwrap();

        let session = Session::new();
        first.save(&session).await.unwrap();
        let loaded = second.load(session.id()).await.unwrap();
        assert!(loaded.is_some());
    }

    #[tokio::test]
    async fn save_transcript_rewrite_rejects_stale_parent_after_intervening_save() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("sessions.sqlite3");
        let first = SqliteSessionStore::open(&path).unwrap();
        let second = SqliteSessionStore::open(&path).unwrap();

        let mut session = Session::new();
        session.push(Message::User(UserMessage::text("hello".to_string())));
        session.push(Message::BlockAssistant(BlockAssistantMessage::new(
            vec![AssistantBlock::Text {
                text: "original".to_string(),
                meta: None,
            }],
            StopReason::EndTurn,
        )));
        first.save(&session).await.unwrap();

        // A raw WholeBlob reload intentionally has no current exact
        // row-lineage authority. Keep two writers from the exact constructed
        // state so the rewrite itself is valid and this probe reaches the
        // store's stale-parent guard.
        let mut stale = session.clone();
        let mut newer = session.clone();
        newer.push(Message::User(UserMessage::text("intervening".to_string())));
        second.save(&newer).await.unwrap();

        let commit = stale
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 1, end: 2 },
                vec![Message::BlockAssistant(BlockAssistantMessage::new(
                    vec![AssistantBlock::Text {
                        text: "replacement".to_string(),
                        meta: None,
                    }],
                    StopReason::EndTurn,
                ))],
                TranscriptRewriteReason::new("compaction"),
                Some("test".to_string()),
                None,
            )
            .unwrap();

        let err = first
            .save_transcript_rewrite(&stale, &commit)
            .await
            .expect_err("stale rewrite must not overwrite newer session state");
        assert!(
            matches!(err, SessionStoreError::TranscriptRevisionConflict { .. }),
            "unexpected error: {err}"
        );

        let saved = first.load(session.id()).await.unwrap().unwrap();
        assert_eq!(saved.messages().len(), newer.messages().len());
    }

    #[tokio::test]
    async fn authoritative_projection_expected_revision_rejects_stale_writer() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("sessions.sqlite3");
        let first = SqliteSessionStore::open(&path).unwrap();
        let second = SqliteSessionStore::open(&path).unwrap();

        let mut session = Session::new();
        session.push(Message::User(UserMessage::text("base".to_string())));
        first.save(&session).await.unwrap();
        let expected_revision = session.transcript_revision().unwrap();

        let mut newer = second.load(session.id()).await.unwrap().unwrap();
        newer.push(Message::User(UserMessage::text("newer".to_string())));
        second.save(&newer).await.unwrap();

        let mut stale_projection = session.clone();
        stale_projection.push(Message::User(UserMessage::text("stale".to_string())));
        let err = first
            .save_authoritative_projection_if_current_revision(
                &stale_projection,
                Some(expected_revision),
            )
            .await
            .expect_err("stale authoritative projection should be rejected");
        assert!(
            matches!(err, SessionStoreError::TranscriptContinuityViolation { .. }),
            "unexpected error: {err}"
        );

        let saved = first.load(session.id()).await.unwrap().unwrap();
        assert_eq!(saved.messages().len(), newer.messages().len());
        assert_eq!(
            saved.transcript_revision().unwrap(),
            newer.transcript_revision().unwrap()
        );
    }

    #[tokio::test]
    async fn delete_if_current_revision_only_deletes_matching_projection() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("sessions.sqlite3");
        let first = SqliteSessionStore::open(&path).unwrap();
        let second = SqliteSessionStore::open(&path).unwrap();

        let mut session = Session::new();
        session.push(Message::User(UserMessage::text("base".to_string())));
        first.save(&session).await.unwrap();
        let stale_token =
            meerkat_core::session_store::session_projection_cas_token(&session).unwrap();

        let mut newer = second.load(session.id()).await.unwrap().unwrap();
        newer.push(Message::User(UserMessage::text("newer".to_string())));
        second.save(&newer).await.unwrap();

        assert!(
            !first
                .delete_if_current_revision(session.id(), &stale_token)
                .await
                .unwrap()
        );
        assert!(first.load(session.id()).await.unwrap().is_some());

        let current_token =
            meerkat_core::session_store::session_projection_cas_token(&newer).unwrap();
        assert!(
            first
                .delete_if_current_revision(session.id(), &current_token)
                .await
                .unwrap()
        );
        assert!(first.load(session.id()).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn list_fails_closed_on_negative_durable_counter() {
        // Gate (row #238): a durable row carrying a negative message_count is
        // an impossible-state projection. list() must surface a typed error
        // rather than laundering it to usize::MAX. OLD behavior:
        // `usize::try_from(...).unwrap_or(usize::MAX)` returned a fabricated
        // count and list() succeeded.
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("sessions.sqlite3");
        let store = SqliteSessionStore::open(&path).unwrap();

        let session = Session::new();
        store.save(&session).await.unwrap();

        // Corrupt the derived counter column directly on disk.
        let conn = open_connection(&path).unwrap();
        conn.execute(
            "UPDATE sessions SET message_count = -1 WHERE session_id = ?1",
            params![session.id().to_string()],
        )
        .unwrap();
        drop(conn);

        let err = store
            .list(SessionFilter::default())
            .await
            .expect_err("list must fail closed on a negative durable counter");
        // Negative counters surface through the typed StoreError boundary,
        // not as usize::MAX.
        assert!(
            matches!(err, SessionStoreError::Internal(_)),
            "unexpected error: {err}"
        );

        // Canonical truth still recoverable from session_json via load().
        let loaded = store.load(session.id()).await.unwrap().unwrap();
        assert_eq!(loaded.id(), session.id());
    }

    // -----------------------------------------------------------------------
    // Incremental session persistence (OB3 ask 11)
    // -----------------------------------------------------------------------

    fn user(text: &str) -> Message {
        Message::User(UserMessage::text(text.to_string()))
    }

    fn incremental(store: &SqliteSessionStore) -> Arc<dyn IncrementalSessionStore> {
        let store = SqliteSessionStore::open(store.path()).unwrap();
        Arc::new(store)
            .as_incremental()
            .expect("sqlite store must expose the incremental capability")
    }

    fn prepared_root_with_metadata(
        key: &str,
        value: serde_json::Value,
    ) -> (Session, PreparedHeadCanonicalMutation) {
        let mut session = Session::new();
        session.set_metadata(key, value);
        session.push(user("root"));
        let mutation = PreparedHeadCanonicalMutation::prepare_root(&session)
            .expect("prepare rooted HeadCanonical mutation");
        (session, mutation)
    }

    #[tokio::test]
    async fn head_canonical_roundtrip_preserves_ordered_system_rows_exactly() {
        let (_dir, store) = temp_store();
        let incremental = incremental(&store);
        let mut session = Session::new();
        session.push(Message::System(SystemMessage::new("")));
        session.push(user("between"));
        session.push(Message::System(SystemMessage::new(" \t\n")));
        session.push(Message::System(SystemMessage::new("duplicate")));
        session.push(Message::System(SystemMessage::new("duplicate")));
        let expected = session.messages().to_vec();

        let root =
            PreparedHeadCanonicalMutation::prepare_root(&session).expect("prepare exact rows");
        incremental
            .apply_prepared_head_canonical_mutation(&root)
            .await
            .expect("persist exact rows");

        let loaded = store
            .load(session.id())
            .await
            .expect("load exact rows")
            .expect("session exists");
        assert_eq!(loaded.messages(), expected);
        let connection = open_connection(store.path()).expect("open store");
        let component_rows: i64 = connection
            .query_row(
                "SELECT COUNT(*) FROM session_component_events WHERE session_id = ?1",
                params![session.id().to_string()],
                |row| row.get(0),
            )
            .expect("count component rows");
        assert_eq!(
            component_rows, 0,
            "ordinary System rows must not mint out-of-band component events"
        );
    }

    #[tokio::test]
    async fn incremental_trait_applies_prepared_mutation_atomically_and_returns_exact_token() {
        let (_dir, store) = temp_store();
        let (_session, root) =
            prepared_root_with_metadata("application", serde_json::json!({"value": 1}));
        let incremental = incremental(&store);
        assert_eq!(
            incremental
                .apply_prepared_head_canonical_mutation(&root)
                .await
                .unwrap(),
            root.successor_head_token()
        );
        assert_eq!(
            incremental
                .apply_prepared_head_canonical_mutation(&root)
                .await
                .expect("exact reply-loss retry"),
            root.successor_head_token()
        );
    }

    #[tokio::test]
    async fn canonical_empty_root_is_the_only_zero_mutation_initial_metadata_state() {
        let (_dir, store) = temp_store();
        let mut session = Session::new();
        session.push(user("empty metadata root"));
        let root = PreparedHeadCanonicalMutation::prepare_root(&session)
            .expect("prepare canonical empty root");
        let identity = root
            .successor_head()
            .metadata_identity()
            .expect("authenticated metadata identity");
        assert!(identity.is_canonical_empty());
        assert!(root.metadata_projection().mutations().is_empty());
        let persisted = root.clone();
        let _ = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &persisted))
            .await
            .unwrap();
        let exact_retry = root.clone();
        let _ = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &exact_retry))
            .await
            .expect("canonical empty root must be exactly retryable");
    }

    #[tokio::test]
    async fn authenticated_per_key_metadata_is_compact_hot_and_complete_cold() {
        let (_dir, store) = temp_store();
        let (mut session, root) =
            prepared_root_with_metadata("application", serde_json::json!({"value": 1}));
        let persisted = root.clone();
        let _ = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &persisted))
            .await
            .unwrap();
        root.acknowledge_session(&mut session, root.successor_head_token())
            .unwrap();

        let compact = incremental(&store)
            .load_head(session.id())
            .await
            .unwrap()
            .unwrap();
        assert!(compact.metadata_identity().is_some());
        assert!(
            compact.metadata_projection().is_none(),
            "ordinary load_head must not parse/hash metadata cells"
        );
        let materialized = incremental(&store)
            .materialize_head(&compact)
            .await
            .expect("explicit current-head materialization");
        assert_eq!(
            materialized.session().metadata().get("application"),
            Some(&serde_json::json!({"value": 1}))
        );
        assert!(materialized.head().realtime_event_prefix.is_some());
        session.push(user("ordinary delta"));
        let successor =
            PreparedHeadCanonicalMutation::prepare(&session, Some(compact.clone())).unwrap();
        assert_eq!(
            successor
                .predecessor_head()
                .and_then(SessionHead::metadata_identity),
            successor.successor_head().metadata_identity(),
            "ordinary transcript deltas must retain metadata identity"
        );
        let persisted = successor.clone();
        let _ = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &persisted))
            .await
            .unwrap();
        assert!(matches!(
            incremental(&store).materialize_head(&compact).await,
            Err(SessionStoreError::TranscriptRevisionConflict { .. })
        ));
        let stable_successor = successor.successor_head().clone();
        store
            .in_write_txn(move |tx| {
                let current = head_row_in_txn(tx, &stable_successor.id)?
                    .ok_or_else(|| SessionStoreError::NotFound(stable_successor.id.clone()))?;
                let before = tx
                    .query_row("SELECT total_changes()", [], |row| row.get::<_, i64>(0))
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
                let stable_token = session_head_cas_token(&stable_successor)?;
                reconcile_head_metadata_transition_in_txn(
                    tx,
                    Some(&current.0),
                    Some(&current.1),
                    &stable_successor,
                    &stable_token,
                )?;
                let after = tx
                    .query_row("SELECT total_changes()", [], |row| row.get::<_, i64>(0))
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
                assert_eq!(
                    after, before,
                    "same physical owner/digest must be a literal no-write path"
                );
                Ok(())
            })
            .await
            .unwrap();

        let loaded = store.load(session.id()).await.unwrap().unwrap();
        assert_eq!(
            loaded.metadata().get("application"),
            Some(&serde_json::json!({"value": 1}))
        );
        let meta = store.load_meta(session.id()).await.unwrap().unwrap();
        assert_eq!(
            meta.metadata.get("application"),
            Some(&serde_json::json!({"value": 1}))
        );
        let listed = store.list(SessionFilter::default()).await.unwrap();
        assert_eq!(
            listed[0].metadata.get("application"),
            Some(&serde_json::json!({"value": 1}))
        );

        let conn = open_connection(store.path()).unwrap();
        let inventory: (i64, i64, i64, i64, i64, i64, i64) = conn
            .query_row(
                r"
                SELECT
                    (SELECT COUNT(*) FROM session_head_metadata_cells
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_current
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_states
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_state_deltas
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_refs
                     WHERE session_id = ?1 AND owner = 'physical_head'),
                    (SELECT COUNT(*) FROM session_head_metadata_refs
                     WHERE session_id = ?1 AND owner = 'runtime_boundary'),
                    (SELECT COUNT(*) FROM session_head_metadata_head_lineage
                     WHERE session_id = ?1)
                ",
                params![session.id().to_string()],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                        row.get(5)?,
                        row.get(6)?,
                    ))
                },
            )
            .unwrap();
        assert_eq!(
            inventory,
            (1, 1, 1, 1, 1, 0, 1),
            "an unchanged metadata root must reuse its one cell/state/delta/lineage"
        );
    }

    #[tokio::test]
    async fn metadata_reachability_bounds_owner_states_and_direct_retry_witness() {
        let (_dir, store) = temp_store();
        let (mut session, root) =
            prepared_root_with_metadata("application", serde_json::json!({"value": 1}));
        let persisted = root.clone();
        let _ = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &persisted))
            .await
            .unwrap();
        root.acknowledge_session(&mut session, root.successor_head_token())
            .unwrap();
        let runtime_boundary = root.successor_head().clone();
        let unretained = runtime_boundary.clone();
        assert!(matches!(
            store
                .in_read_txn(move |tx| {
                    verify_runtime_boundary_head_canonical_in_txn(tx, &unretained)
                })
                .await,
            Err(SessionStoreError::Corrupted(_))
        ));
        store
            .in_write_txn(move |tx| {
                retain_runtime_boundary_head_metadata_in_txn(tx, &runtime_boundary)
            })
            .await
            .unwrap();
        let stable_runtime_boundary = root.successor_head().clone();
        store
            .in_write_txn(move |tx| {
                let before = tx
                    .query_row("SELECT total_changes()", [], |row| row.get::<_, i64>(0))
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
                retain_runtime_boundary_head_metadata_in_txn(tx, &stable_runtime_boundary)?;
                let after = tx
                    .query_row("SELECT total_changes()", [], |row| row.get::<_, i64>(0))
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
                assert_eq!(
                    after, before,
                    "same runtime owner/digest must be a literal no-write path"
                );
                Ok(())
            })
            .await
            .unwrap();

        session.set_metadata("application", serde_json::json!({"value": 2}));
        let observed = incremental(&store)
            .load_head(session.id())
            .await
            .unwrap()
            .unwrap();
        let successor = PreparedHeadCanonicalMutation::prepare(&session, Some(observed)).unwrap();
        let persisted = successor.clone();
        let _ = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &persisted))
            .await
            .unwrap();

        let conn = open_connection(store.path()).unwrap();
        let divergent: (i64, i64, i64, i64, i64, i64, i64) = conn
            .query_row(
                r"
                SELECT
                    (SELECT COUNT(*) FROM session_head_metadata_cells
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_current
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_states
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_state_deltas
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_refs
                     WHERE session_id = ?1 AND owner = 'physical_head'),
                    (SELECT COUNT(*) FROM session_head_metadata_refs
                     WHERE session_id = ?1 AND owner = 'runtime_boundary'),
                    (SELECT COUNT(*) FROM session_head_metadata_head_lineage
                     WHERE session_id = ?1)
                ",
                params![session.id().to_string()],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                        row.get(5)?,
                        row.get(6)?,
                    ))
                },
            )
            .unwrap();
        assert_eq!(
            divergent,
            (2, 1, 2, 2, 1, 1, 2),
            "divergent physical/runtime owners must retain both authenticated transitions"
        );
        drop(conn);
        let exact_retry = root.clone();
        store
            .in_read_txn(move |tx| {
                verify_prepared_head_canonical_rows_for_exact_retry_in_txn(tx, &exact_retry)
            })
            .await
            .expect("runtime-retained predecessor rows must remain exactly retryable");

        let new_runtime_boundary = successor.successor_head().clone();
        store
            .in_write_txn(move |tx| {
                retain_runtime_boundary_head_metadata_in_txn(tx, &new_runtime_boundary)
            })
            .await
            .unwrap();
        let conn = open_connection(store.path()).unwrap();
        let converged: (i64, i64, i64, i64, i64, i64, i64) = conn
            .query_row(
                r"
                SELECT
                    (SELECT COUNT(*) FROM session_head_metadata_cells
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_current
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_states
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_state_deltas
                     WHERE session_id = ?1),
                    (SELECT COUNT(*) FROM session_head_metadata_refs
                     WHERE session_id = ?1 AND owner = 'physical_head'),
                    (SELECT COUNT(*) FROM session_head_metadata_refs
                     WHERE session_id = ?1 AND owner = 'runtime_boundary'),
                    (SELECT COUNT(*) FROM session_head_metadata_head_lineage
                     WHERE session_id = ?1)
                ",
                params![session.id().to_string()],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                        row.get(5)?,
                        row.get(6)?,
                    ))
                },
            )
            .unwrap();
        assert_eq!(
            converged,
            (2, 1, 2, 1, 1, 1, 1),
            "convergence must retain only the current state and its direct retry witness"
        );
        drop(conn);
        assert!(
            store.delete(session.id()).await.is_err(),
            "session deletion must not strand a retained runtime boundary"
        );
        let session_id = session.id().clone();
        store
            .in_write_txn(move |tx| clear_runtime_boundary_head_metadata_in_txn(tx, &session_id))
            .await
            .unwrap();
        store.delete(session.id()).await.unwrap();
        let conn = open_connection(store.path()).unwrap();
        for table in [
            "session_head_metadata_cells",
            "session_head_metadata_current",
            "session_head_metadata_states",
            "session_head_metadata_state_deltas",
            "session_head_metadata_refs",
            "session_head_metadata_head_lineage",
        ] {
            let retained: i64 = conn
                .query_row(
                    &format!("SELECT COUNT(*) FROM {table} WHERE session_id = ?1"),
                    params![session.id().to_string()],
                    |row| row.get(0),
                )
                .unwrap();
            assert_eq!(retained, 0, "table {table} must be cleared by delete");
        }
    }

    #[tokio::test]
    async fn standalone_one_hot_metadata_mutations_keep_two_cells_and_one_retry_delta() {
        let (_dir, store) = temp_store();
        let mut session = Session::new();
        session.set_metadata("hot", serde_json::json!({"value": 0}));
        session.set_metadata(
            "large-cold",
            serde_json::json!({"payload": "x".repeat(16_384)}),
        );
        session.push(user("root"));
        let root = PreparedHeadCanonicalMutation::prepare_root(&session)
            .expect("prepare rooted HeadCanonical mutation");
        let persisted_root = root.clone();
        let root_outcome = store
            .in_write_txn(move |tx| {
                apply_prepared_head_canonical_mutation_in_txn(tx, &persisted_root)
            })
            .await
            .unwrap();
        assert_eq!(
            root_outcome,
            HeadCanonicalMutationApplyOutcome::Applied,
            "the initial rooted mutation must be installed"
        );
        root.acknowledge_session(&mut session, root.successor_head_token())
            .unwrap();

        for value in 1..=16 {
            session.set_metadata("hot", serde_json::json!({"value": value}));
            let observed = incremental(&store)
                .load_head(session.id())
                .await
                .unwrap()
                .unwrap();
            let successor =
                PreparedHeadCanonicalMutation::prepare(&session, Some(observed)).unwrap();
            assert_eq!(
                successor.metadata_projection().mutations().len(),
                1,
                "one hot-key update must carry exactly one authenticated mutation"
            );
            let persisted = successor.clone();
            let successor_outcome = store
                .in_write_txn(move |tx| {
                    apply_prepared_head_canonical_mutation_in_txn(tx, &persisted)
                })
                .await
                .unwrap();
            assert_eq!(
                successor_outcome,
                HeadCanonicalMutationApplyOutcome::Applied,
                "each new hot-key mutation must advance the canonical head"
            );
            successor
                .acknowledge_session(&mut session, successor.successor_head_token())
                .unwrap();

            let exact_retry = successor.clone();
            let retry_outcome = store
                .in_write_txn(move |tx| {
                    apply_prepared_head_canonical_mutation_in_txn(tx, &exact_retry)
                })
                .await
                .expect("the latest changed-cell bytes, proof, state, and lineage must re-prove");
            assert_eq!(
                retry_outcome,
                HeadCanonicalMutationApplyOutcome::AlreadyApplied,
                "an exact retry must re-prove the existing successor without rewriting it"
            );

            let conn = open_connection(store.path()).unwrap();
            let bounded: (i64, i64, i64, i64, i64, i64, i64) = conn
                .query_row(
                    r"
                    SELECT
                        (SELECT COUNT(*) FROM session_head_metadata_cells
                         WHERE session_id = ?1),
                        (SELECT COUNT(*) FROM session_head_metadata_current
                         WHERE session_id = ?1),
                        (SELECT COUNT(*) FROM session_head_metadata_states
                         WHERE session_id = ?1),
                        (SELECT COUNT(*) FROM session_head_metadata_state_deltas
                         WHERE session_id = ?1),
                        (SELECT COUNT(*) FROM session_head_metadata_refs
                         WHERE session_id = ?1 AND owner = 'physical_head'),
                        (SELECT COUNT(*) FROM session_head_metadata_refs
                         WHERE session_id = ?1 AND owner = 'runtime_boundary'),
                        (SELECT COUNT(*) FROM session_head_metadata_head_lineage
                         WHERE session_id = ?1)
                    ",
                    params![session.id().to_string()],
                    |row| {
                        Ok((
                            row.get(0)?,
                            row.get(1)?,
                            row.get(2)?,
                            row.get(3)?,
                            row.get(4)?,
                            row.get(5)?,
                            row.get(6)?,
                        ))
                    },
                )
                .unwrap();
            assert_eq!(
                bounded,
                (3, 2, 2, 1, 1, 0, 1),
                "a standalone store must keep one cold cell plus current+retry hot versions"
            );
        }

        session.push(user("metadata-stable transcript delta"));
        let observed = incremental(&store)
            .load_head(session.id())
            .await
            .unwrap()
            .unwrap();
        let stable = PreparedHeadCanonicalMutation::prepare(&session, Some(observed)).unwrap();
        assert!(stable.metadata_projection().mutations().is_empty());
        let stable = stable.clone();
        store
            .in_write_txn(move |tx| {
                let before = tx
                    .query_row("SELECT total_changes()", [], |row| row.get::<_, i64>(0))
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
                reconcile_head_metadata_transition_in_txn(
                    tx,
                    stable.predecessor_head(),
                    stable.predecessor_head_token(),
                    stable.successor_head(),
                    stable.successor_head_token(),
                )?;
                let after = tx
                    .query_row("SELECT total_changes()", [], |row| row.get::<_, i64>(0))
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
                assert_eq!(
                    after, before,
                    "zero-dirty metadata must produce no SQLite metadata change and therefore no metadata WAL record"
                );
                Ok(())
            })
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn retained_runtime_boundary_verifies_exact_prefix_after_same_strand_append() {
        let (_dir, store) = temp_store();
        let (mut session, root) =
            prepared_root_with_metadata("application", serde_json::json!({"value": 1}));
        let persisted_root = root.clone();
        let _ = store
            .in_write_txn(move |tx| {
                apply_prepared_head_canonical_mutation_in_txn(tx, &persisted_root)
            })
            .await
            .expect("persist root");
        let runtime_boundary = root.successor_head().clone();
        let retained_boundary = runtime_boundary.clone();
        store
            .in_write_txn(move |tx| {
                retain_runtime_boundary_head_metadata_in_txn(tx, &retained_boundary)
            })
            .await
            .expect("retain runtime boundary metadata");
        root.acknowledge_session(&mut session, root.successor_head_token())
            .expect("acknowledge root");

        session.push(user("later physical append"));
        let observed = incremental(&store)
            .load_head(session.id())
            .await
            .expect("load root head")
            .expect("root head exists");
        let append = PreparedHeadCanonicalMutation::prepare(&session, Some(observed))
            .expect("prepare append");
        incremental(&store)
            .apply_prepared_head_canonical_mutation(&append)
            .await
            .expect("persist append");

        let boundary_for_read = runtime_boundary.clone();
        let verified = store
            .in_read_txn(move |tx| {
                verify_runtime_boundary_head_canonical_in_txn(tx, &boundary_for_read)
            })
            .await
            .expect("retained boundary prefix must remain independently verifiable");
        assert_eq!(verified.session().messages(), &session.messages()[..1]);

        let connection = open_connection(store.path()).expect("open store");
        let corrupted_row =
            serde_json::to_vec(&user("corrupted retained prefix")).expect("serialize corruption");
        connection
            .execute(
                r"
                UPDATE session_strand_messages
                SET message_json = ?3
                WHERE session_id = ?1 AND strand = ?2 AND seq = 0
                ",
                params![
                    session.id().to_string(),
                    runtime_boundary.strand.as_str(),
                    corrupted_row,
                ],
            )
            .expect("corrupt retained prefix row");
        drop(connection);
        let boundary_for_corruption_check = runtime_boundary.clone();
        let error = store
            .in_read_txn(move |tx| {
                verify_runtime_boundary_head_canonical_in_txn(tx, &boundary_for_corruption_check)
            })
            .await
            .expect_err("corrupt retained prefix must fail closed");
        assert!(
            matches!(
                error,
                SessionStoreError::Corrupted(ref id)
                    | SessionStoreError::TranscriptContinuityViolation { ref id, .. }
                    if id == session.id()
            ),
            "unexpected retained-prefix corruption error: {error:?}"
        );
    }

    #[tokio::test]
    async fn corrupted_metadata_cell_fails_cold_reads_as_corruption() {
        let (_dir, store) = temp_store();
        let (session, root) =
            prepared_root_with_metadata("application", serde_json::json!({"value": 1}));
        let initial = root.clone();
        let initial_outcome = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &initial))
            .await
            .unwrap();
        assert_eq!(
            initial_outcome,
            HeadCanonicalMutationApplyOutcome::Applied,
            "the fixture root must be installed before its metadata cell is corrupted"
        );
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            r"
            UPDATE session_head_metadata_cells
            SET metadata_json = X'7B7D'
            WHERE session_id = ?1
            ",
            params![session.id().to_string()],
        )
        .unwrap();
        drop(conn);

        let error = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &root))
            .await
            .expect_err("exact retry must byte-compare its physical metadata cell");
        assert!(matches!(error, SessionStoreError::Corrupted(id) if id == *session.id()));
        assert!(matches!(
            store.load(session.id()).await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        assert!(matches!(
            store.load_meta(session.id()).await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
    }

    #[tokio::test]
    async fn exact_retry_recomputes_the_retained_predecessor_cell_bytes() {
        let (_dir, store) = temp_store();
        let (mut session, root) =
            prepared_root_with_metadata("application", serde_json::json!({"value": 1}));
        let persisted_root = root.clone();
        let root_outcome = store
            .in_write_txn(move |tx| {
                apply_prepared_head_canonical_mutation_in_txn(tx, &persisted_root)
            })
            .await
            .unwrap();
        assert_eq!(
            root_outcome,
            HeadCanonicalMutationApplyOutcome::Applied,
            "the predecessor fixture must be installed"
        );
        let runtime_root = root.successor_head().clone();
        store
            .in_write_txn(move |tx| retain_runtime_boundary_head_metadata_in_txn(tx, &runtime_root))
            .await
            .unwrap();
        root.acknowledge_session(&mut session, root.successor_head_token())
            .unwrap();

        session.set_metadata("application", serde_json::json!({"value": 2}));
        let observed = incremental(&store)
            .load_head(session.id())
            .await
            .unwrap()
            .unwrap();
        let successor = PreparedHeadCanonicalMutation::prepare(&session, Some(observed)).unwrap();
        let persisted = successor.clone();
        let successor_outcome = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &persisted))
            .await
            .unwrap();
        assert_eq!(
            successor_outcome,
            HeadCanonicalMutationApplyOutcome::Applied,
            "the changed metadata cell must advance the canonical head"
        );
        let runtime_successor = successor.successor_head().clone();
        store
            .in_write_txn(move |tx| {
                retain_runtime_boundary_head_metadata_in_txn(tx, &runtime_successor)
            })
            .await
            .unwrap();

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            r"
            UPDATE session_head_metadata_cells
            SET metadata_json = X'7B7D'
            WHERE session_id = ?1
              AND metadata_key = 'application'
              AND exact_value_digest <> (
                  SELECT exact_value_digest
                  FROM session_head_metadata_current
                  WHERE session_id = ?1 AND metadata_key = 'application'
              )
            ",
            params![session.id().to_string()],
        )
        .unwrap();
        drop(conn);

        let exact_retry = successor.clone();
        let error = store
            .in_read_txn(move |tx| {
                verify_prepared_head_canonical_rows_for_exact_retry_in_txn(tx, &exact_retry)
            })
            .await
            .expect_err("retry must recompute and reject corrupt retained predecessor bytes");
        assert!(matches!(error, SessionStoreError::Corrupted(id) if id == *session.id()));
    }

    #[tokio::test]
    async fn list_pages_compact_heads_before_metadata_hydration() {
        let (_dir, store) = temp_store();
        let (newer, newer_root) =
            prepared_root_with_metadata("application", serde_json::json!({"value": "newer"}));
        let (older, older_root) =
            prepared_root_with_metadata("application", serde_json::json!({"value": "older"}));
        store
            .in_write_txn(move |tx| {
                assert_eq!(
                    apply_prepared_head_canonical_mutation_in_txn(tx, &newer_root)?,
                    HeadCanonicalMutationApplyOutcome::Applied,
                    "the newer list fixture must be installed"
                );
                assert_eq!(
                    apply_prepared_head_canonical_mutation_in_txn(tx, &older_root)?,
                    HeadCanonicalMutationApplyOutcome::Applied,
                    "the older list fixture must be installed"
                );
                Ok(())
            })
            .await
            .unwrap();

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_heads SET updated_at_ms = 2000 WHERE session_id = ?1",
            params![newer.id().to_string()],
        )
        .unwrap();
        conn.execute(
            "UPDATE session_heads SET updated_at_ms = 1000 WHERE session_id = ?1",
            params![older.id().to_string()],
        )
        .unwrap();
        conn.execute(
            "UPDATE session_head_metadata_cells SET metadata_json = X'7B7D' \
             WHERE session_id = ?1",
            params![older.id().to_string()],
        )
        .unwrap();
        drop(conn);

        let first_page = store
            .list(SessionFilter {
                limit: Some(1),
                ..SessionFilter::default()
            })
            .await
            .expect("unselected corrupt metadata payload must not be hydrated");
        assert_eq!(first_page.len(), 1);
        assert_eq!(first_page[0].id, *newer.id());

        assert!(matches!(
            store
                .list(SessionFilter {
                    limit: Some(1),
                    offset: Some(1),
                    ..SessionFilter::default()
                })
                .await,
            Err(SessionStoreError::Corrupted(id)) if id == *older.id()
        ));
    }

    #[tokio::test]
    async fn prepared_retry_refuses_a_missing_metadata_cell() {
        let (_dir, store) = temp_store();
        let (session, root) =
            prepared_root_with_metadata("application", serde_json::json!({"value": 1}));
        let initial = root.clone();
        let initial_outcome = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &initial))
            .await
            .unwrap();
        assert_eq!(
            initial_outcome,
            HeadCanonicalMutationApplyOutcome::Applied,
            "the fixture root must be installed before its metadata cell is removed"
        );
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "DELETE FROM session_head_metadata_cells WHERE session_id = ?1",
            params![session.id().to_string()],
        )
        .unwrap();
        drop(conn);

        let error = store
            .in_write_txn(move |tx| apply_prepared_head_canonical_mutation_in_txn(tx, &root))
            .await
            .expect_err("exact retry must point-check its immutable metadata cell");
        assert!(matches!(error, SessionStoreError::Corrupted(id) if id == *session.id()));
    }

    /// Seed a head-canonical session through the incremental contract:
    /// root strand rows + a Create head.
    async fn seed_incremental(
        inc: &Arc<dyn IncrementalSessionStore>,
        session: &Session,
    ) -> SessionHead {
        let root = TranscriptStrandId::root();
        inc.append_messages(session.id(), &root, 0, session.messages())
            .await
            .unwrap();
        let head = SessionHead::from_session(session, root, 0).unwrap();
        inc.save_head(&head, SessionHeadCas::Create).await.unwrap();
        head
    }

    fn strand_row_count(path: &Path, id: &SessionId, strand: &TranscriptStrandId) -> i64 {
        let conn = open_connection(path).unwrap();
        conn.query_row(
            "SELECT COUNT(*) FROM session_strand_messages WHERE session_id = ?1 AND strand = ?2",
            params![id.to_string(), strand.as_str()],
            |row| row.get(0),
        )
        .unwrap()
    }

    /// Every strand row the session persists, across all strands.
    fn total_strand_rows(path: &Path, id: &SessionId) -> i64 {
        let conn = open_connection(path).unwrap();
        conn.query_row(
            "SELECT COUNT(*) FROM session_strand_messages WHERE session_id = ?1",
            params![id.to_string()],
            |row| row.get(0),
        )
        .unwrap()
    }

    fn strand_link_count(path: &Path, id: &SessionId) -> i64 {
        let conn = open_connection(path).unwrap();
        conn.query_row(
            "SELECT COUNT(*) FROM session_strand_links WHERE session_id = ?1",
            params![id.to_string()],
            |row| row.get(0),
        )
        .unwrap()
    }

    fn blob_row_bytes(path: &Path, id: &SessionId) -> Option<Vec<u8>> {
        let conn = open_connection(path).unwrap();
        conn.query_row(
            "SELECT session_json FROM sessions WHERE session_id = ?1",
            params![id.to_string()],
            |row| Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes()),
        )
        .optional()
        .unwrap()
    }

    #[tokio::test]
    async fn prepared_rewrite_persists_only_delta_rows_and_supports_linked_tail_append() {
        let (_dir, store) = temp_store();
        let incremental = incremental(&store);
        let mut session = Session::new();
        session.set_metadata("application", serde_json::json!({"value": 1}));
        for turn in 0..64 {
            session.push(user(&format!("turn {turn}")));
        }
        let root = PreparedHeadCanonicalMutation::prepare_root(&session).expect("prepare root");
        incremental
            .apply_prepared_head_canonical_mutation(&root)
            .await
            .expect("persist root");
        root.acknowledge_session(&mut session, root.successor_head_token())
            .expect("acknowledge root");
        let runtime_head = root.successor_head().clone();

        session
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 10, end: 11 },
                vec![user("replacement")],
                TranscriptRewriteReason::new("delta topology test"),
                Some("unit-test".to_string()),
                None,
            )
            .expect("commit rewrite");
        let rewrite = PreparedHeadCanonicalRewriteMutation::prepare_intra_turn(
            &session,
            &runtime_head,
            runtime_head.clone(),
        )
        .expect("prepare rewrite");
        assert_eq!(rewrite.steps().len(), 1);
        assert!(rewrite.steps()[0].serialized_parent_suffix().is_empty());
        assert_eq!(rewrite.steps()[0].serialized_replacement().len(), 1);
        let rewrite_strand = rewrite.steps()[0].strand().clone();
        assert_eq!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await
                .expect("persist rewrite"),
            rewrite.successor_head_token()
        );
        assert_eq!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await
                .expect("exact rewrite retry"),
            rewrite.successor_head_token()
        );
        let replacement_only = store
            .load(session.id())
            .await
            .expect("replacement-only sparse head must cold replay")
            .expect("session present");
        assert_eq!(
            replacement_only.messages(),
            session.messages(),
            "an empty direct tail may end physically at the replacement span, below the logical head count"
        );
        assert_eq!(
            strand_row_count(store.path(), session.id(), &rewrite_strand),
            1
        );
        assert_eq!(strand_link_count(store.path(), session.id()), 1);
        assert_eq!(
            total_strand_rows(store.path(), session.id()),
            65,
            "one one-row rewrite must add one physical row, not another 64-row document"
        );

        rewrite
            .acknowledge_physical_projection(&mut session, rewrite.successor_head_token())
            .expect("acknowledge rewrite projection");
        session.push(user("linked tail"));
        let tail = PreparedHeadCanonicalMutation::prepare_intra_turn(
            &session,
            &runtime_head,
            rewrite.successor_head().clone(),
        )
        .expect("prepare linked tail");
        assert_eq!(tail.serialized_suffix().len(), 1);
        incremental
            .apply_prepared_head_canonical_mutation(&tail)
            .await
            .expect("append linked tail");
        tail.acknowledge_physical_projection(&mut session, tail.successor_head_token())
            .expect("acknowledge linked tail");

        assert_eq!(
            strand_row_count(store.path(), session.id(), &rewrite_strand),
            2
        );
        assert_eq!(
            total_strand_rows(store.path(), session.id()),
            66,
            "ordinary append on a linked head must add only its one tail row"
        );
        let replay_head = tail.successor_head().clone();
        let (decoded, loaded_links) = store
            .in_read_txn(move |tx| {
                let replayed = replay_head_canonical_rows_in_txn(
                    tx,
                    &replay_head,
                    HeadMetadataProjectionOwner::PhysicalHead,
                )?;
                Ok((
                    replayed.decoded_rewrite_count,
                    replayed.loaded_link_row_count,
                ))
            })
            .await
            .expect("bounded post-anchor replay");
        assert_eq!(
            decoded, 1,
            "ordinary materialization must decode only the one post-anchor rewrite"
        );
        assert_eq!(
            loaded_links, 1,
            "ordinary materialization must point-read only the active child link"
        );
        let loaded = store
            .load(session.id())
            .await
            .expect("load linked head")
            .expect("session present");
        assert_eq!(loaded.messages(), session.messages());
    }

    #[tokio::test]
    async fn ordinary_cold_load_skips_long_pre_anchor_rewrite_history() {
        let (_dir, store) = temp_store();
        let mut session = Session::new();
        for turn in 0..32 {
            session.push(user(&format!("turn {turn}")));
        }
        for generation in 0..24 {
            session
                .commit_transcript_rewrite(
                    TranscriptRewriteSelection::MessageRange { start: 0, end: 1 },
                    vec![user(&format!("summary {generation}"))],
                    TranscriptRewriteReason::new("bounded cold-load fixture"),
                    Some("unit-test".to_string()),
                    None,
                )
                .expect("commit fixture rewrite");
        }
        let expected_messages = session.messages().to_vec();
        let id = session.id().clone();
        let (layout, head) = layout_for_blob_session(&session).expect("prepare canonical layout");
        assert_eq!(
            head.row_lineage_anchor
                .as_ref()
                .expect("current bounded anchor")
                .rewrite_count(),
            head.rewrite_count
        );
        assert!(head.rewrite_count >= 24);
        let head_for_write = head.clone();
        let layout_for_write = layout.clone();
        store
            .in_write_txn(move |tx| {
                persist_blob_strand_layout_in_txn(tx, &id, &layout_for_write)?;
                let links = strand_links_in_txn(tx, &id)?;
                let settled = settle_resolved_strand_direct_in_txn(
                    tx,
                    &id,
                    &head_for_write.strand,
                    head_for_write.message_count,
                    &links,
                )?;
                let observed = SessionMessageRowPrefixAccumulator::from_serialized_rows(&settled)?;
                let anchor = head_for_write
                    .row_lineage_anchor
                    .as_ref()
                    .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
                if observed != *anchor.materialized_prefix() {
                    return Err(SessionStoreError::Corrupted(id.clone()));
                }
                write_head_row_only_in_txn(tx, &head_for_write)?;
                Ok(())
            })
            .await
            .expect("persist current canonical fixture");

        let head_for_cost = head.clone();
        let (decoded, loaded_links) = store
            .in_read_txn(move |tx| {
                let replayed = replay_head_canonical_rows_in_txn(
                    tx,
                    &head_for_cost,
                    HeadMetadataProjectionOwner::PhysicalHead,
                )?;
                assert_eq!(replayed.serialized_rows.len(), expected_messages.len());
                Ok((
                    replayed.decoded_rewrite_count,
                    replayed.loaded_link_row_count,
                ))
            })
            .await
            .expect("bounded replay");
        assert_eq!(
            decoded, 0,
            "a current anchor must make all preceding rewrite rows invisible to ordinary load"
        );
        assert_eq!(
            loaded_links, 0,
            "a settled current anchor must not load any historical topology"
        );
        assert!(
            strand_link_count(store.path(), session.id()) > 0,
            "the cost probe must retain historical links so zero loaded links cannot be an empty-history artifact"
        );

        // The current lineage anchor is the store-issued authority for an
        // ordinary load. Pre-anchor rewrite edges and links are intentionally
        // outside this bounded read; explicit history/audit operations own
        // their validation. Legal representation-only changes such as trailing
        // JSON whitespace are likewise not a second semantic authority.
        // Structural row continuity remains mandatory.
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "DELETE FROM session_strand_messages
             WHERE session_id = ?1 AND strand = ?2 AND seq = 0",
            params![session.id().to_string(), head.strand.as_str()],
        )
        .unwrap();
        drop(conn);
        assert!(matches!(
            store.load(session.id()).await,
            Err(SessionStoreError::Corrupted(corrupted)) if corrupted == *session.id()
        ));
    }

    #[tokio::test]
    async fn prepared_rewrites_rotate_and_settle_the_active_topology_budget() {
        let (_dir, store) = temp_store();
        let incremental = incremental(&store);
        let mut session = Session::new();
        session.set_metadata("application", serde_json::json!({"value": 1}));
        for turn in 0..16 {
            session.push(user(&format!("turn {turn}")));
        }
        let root = PreparedHeadCanonicalMutation::prepare_root(&session).expect("prepare root");
        incremental
            .apply_prepared_head_canonical_mutation(&root)
            .await
            .expect("persist root");
        root.acknowledge_session(&mut session, root.successor_head_token())
            .expect("acknowledge root");
        let mut observed_head = root.successor_head().clone();

        let rewrite_total = SESSION_ROW_LINEAGE_REBASE_INTERVAL + 8;
        for generation in 0..rewrite_total {
            session
                .commit_transcript_rewrite(
                    TranscriptRewriteSelection::MessageRange { start: 0, end: 1 },
                    vec![user(&format!("summary {generation}"))],
                    TranscriptRewriteReason::new("active topology budget probe"),
                    Some("unit-test".to_string()),
                    None,
                )
                .expect("commit rewrite");
            let runtime_boundary_head = observed_head.clone();
            let rewrite = PreparedHeadCanonicalRewriteMutation::prepare_intra_turn(
                &session,
                &runtime_boundary_head,
                observed_head,
            )
            .expect("prepare bounded rewrite");
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await
                .expect("persist bounded rewrite");
            if generation + 1 == SESSION_ROW_LINEAGE_REBASE_INTERVAL {
                incremental
                    .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                    .await
                    .expect("settled anchor rewrite retries exactly");
            }
            rewrite
                .acknowledge_physical_projection(&mut session, rewrite.successor_head_token())
                .expect("acknowledge rewrite");
            observed_head = rewrite.successor_head().clone();
        }

        let anchor = observed_head
            .row_lineage_anchor
            .as_ref()
            .expect("bounded row-lineage anchor");
        assert_eq!(
            anchor.rewrite_count(),
            SESSION_ROW_LINEAGE_REBASE_INTERVAL,
            "the interval rewrite must rotate the store-issued replay origin"
        );
        let replay_head = observed_head.clone();
        let (decoded, loaded_links) = store
            .in_read_txn(move |tx| {
                let replayed = replay_head_canonical_rows_in_txn(
                    tx,
                    &replay_head,
                    HeadMetadataProjectionOwner::PhysicalHead,
                )?;
                Ok((
                    replayed.decoded_rewrite_count,
                    replayed.loaded_link_row_count,
                ))
            })
            .await
            .expect("bounded active-topology replay");
        assert_eq!(decoded, 8);
        assert_eq!(
            loaded_links, 8,
            "ordinary replay must see only post-anchor active links"
        );
        assert!(
            usize::try_from(strand_link_count(store.path(), session.id())).unwrap() > loaded_links,
            "historical links must exist without being loaded by ordinary resume"
        );
        let named_id = session.id().clone();
        let named_strand = observed_head.strand.clone();
        let named_count = observed_head.message_count;
        let (named_messages, named_link_rows) = store
            .in_read_txn(move |tx| {
                strand_messages_with_bounded_topology_in_txn(
                    tx,
                    &named_id,
                    &named_strand,
                    0..named_count,
                )
            })
            .await
            .expect("bounded named-strand read");
        assert_eq!(named_messages, session.messages());
        assert_eq!(
            named_link_rows, 8,
            "load_messages must point-read only post-anchor active link rows"
        );
        let loaded = store
            .load(session.id())
            .await
            .expect("load bounded topology")
            .expect("session present");
        assert_eq!(loaded.messages(), session.messages());
    }

    #[tokio::test]
    async fn prepared_rewrite_exact_retry_point_checks_every_named_row_and_link() {
        let (_dir, store) = temp_store();
        let incremental = incremental(&store);
        let mut session = Session::new();
        for turn in 0..8 {
            session.push(user(&format!("turn {turn}")));
        }
        let root = PreparedHeadCanonicalMutation::prepare_root(&session).expect("prepare root");
        incremental
            .apply_prepared_head_canonical_mutation(&root)
            .await
            .expect("persist root");
        let runtime_head = root.successor_head().clone();
        root.acknowledge_session(&mut session, root.successor_head_token())
            .expect("acknowledge root");

        session.push(user("parent append"));
        session
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 2, end: 3 },
                vec![user("replacement")],
                TranscriptRewriteReason::new("named retry effects"),
                Some("unit-test".to_string()),
                None,
            )
            .expect("commit rewrite");
        session.push(user("successor tail"));
        let rewrite = PreparedHeadCanonicalRewriteMutation::prepare_intra_turn(
            &session,
            &runtime_head,
            runtime_head.clone(),
        )
        .expect("prepare rewrite with parent and successor suffixes");
        assert_eq!(rewrite.steps().len(), 1);
        let step = &rewrite.steps()[0];
        assert_eq!(step.serialized_parent_suffix().len(), 1);
        assert_eq!(step.serialized_replacement().len(), 1);
        assert_eq!(rewrite.serialized_tail().len(), 1);
        incremental
            .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
            .await
            .expect("persist prepared rewrite");

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_strand_messages SET message_json = X'7B7D'
             WHERE session_id = ?1 AND strand = ?2 AND seq = ?3",
            params![
                session.id().to_string(),
                step.parent_strand().as_str(),
                i64::try_from(step.parent_base_seq()).unwrap()
            ],
        )
        .unwrap();
        drop(conn);
        assert!(matches!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        assert!(matches!(
            store.load(session.id()).await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_strand_messages SET message_json = ?4
             WHERE session_id = ?1 AND strand = ?2 AND seq = ?3",
            params![
                session.id().to_string(),
                step.parent_strand().as_str(),
                i64::try_from(step.parent_base_seq()).unwrap(),
                &step.serialized_parent_suffix()[0]
            ],
        )
        .unwrap();
        drop(conn);

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_strand_messages SET message_json = X'7B7D'
             WHERE session_id = ?1 AND strand = ?2 AND seq = ?3",
            params![
                session.id().to_string(),
                step.strand().as_str(),
                i64::try_from(step.link_splice().splice_start).unwrap()
            ],
        )
        .unwrap();
        drop(conn);
        assert!(matches!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_strand_messages SET message_json = ?4
             WHERE session_id = ?1 AND strand = ?2 AND seq = ?3",
            params![
                session.id().to_string(),
                step.strand().as_str(),
                i64::try_from(step.link_splice().splice_start).unwrap(),
                &step.serialized_replacement()[0]
            ],
        )
        .unwrap();
        drop(conn);

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_strand_messages SET message_json = X'7B7D'
             WHERE session_id = ?1 AND strand = ?2 AND seq = ?3",
            params![
                session.id().to_string(),
                rewrite.successor_head().strand.as_str(),
                i64::try_from(rewrite.tail_base_seq()).unwrap()
            ],
        )
        .unwrap();
        drop(conn);
        assert!(matches!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_strand_messages SET message_json = ?4
             WHERE session_id = ?1 AND strand = ?2 AND seq = ?3",
            params![
                session.id().to_string(),
                rewrite.successor_head().strand.as_str(),
                i64::try_from(rewrite.tail_base_seq()).unwrap(),
                &rewrite.serialized_tail()[0]
            ],
        )
        .unwrap();
        drop(conn);

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_strand_links SET successor = 'corrupt'
             WHERE session_id = ?1 AND strand = ?2",
            params![session.id().to_string(), step.strand().as_str()],
        )
        .unwrap();
        drop(conn);
        assert!(matches!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_strand_links SET successor = ?3
             WHERE session_id = ?1 AND strand = ?2",
            params![
                session.id().to_string(),
                step.strand().as_str(),
                step.parent_strand().as_str()
            ],
        )
        .unwrap();
        drop(conn);

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_rewrites SET commit_json = X'7B7D'
             WHERE session_id = ?1 AND rewrite_idx = ?2",
            params![
                session.id().to_string(),
                i64::try_from(runtime_head.rewrite_count).unwrap()
            ],
        )
        .unwrap();
        drop(conn);
        assert!(matches!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_rewrites SET commit_json = ?3
             WHERE session_id = ?1 AND rewrite_idx = ?2",
            params![
                session.id().to_string(),
                i64::try_from(runtime_head.rewrite_count).unwrap(),
                serde_json::to_vec(step.commit()).unwrap()
            ],
        )
        .unwrap();
        drop(conn);

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_rewrites SET graph_edge_json = X'7B7D'
             WHERE session_id = ?1 AND rewrite_idx = ?2",
            params![
                session.id().to_string(),
                i64::try_from(runtime_head.rewrite_count).unwrap()
            ],
        )
        .unwrap();
        drop(conn);
        assert!(matches!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        assert!(matches!(
            store.load(session.id()).await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_rewrites SET graph_edge_json = ?3
             WHERE session_id = ?1 AND rewrite_idx = ?2",
            params![
                session.id().to_string(),
                i64::try_from(runtime_head.rewrite_count).unwrap(),
                step.serialized_graph_edge()
            ],
        )
        .unwrap();
        drop(conn);

        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_heads SET head_json = X'7B7D' WHERE session_id = ?1",
            params![session.id().to_string()],
        )
        .unwrap();
        drop(conn);
        assert!(matches!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await,
            Err(SessionStoreError::Corrupted(id)) if id == *session.id()
        ));
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "UPDATE session_heads SET head_json = ?2 WHERE session_id = ?1",
            params![
                session.id().to_string(),
                serde_json::to_vec(rewrite.successor_head()).unwrap()
            ],
        )
        .unwrap();
        drop(conn);

        assert_eq!(
            incremental
                .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
                .await
                .expect("all restored named effects retry exactly"),
            rewrite.successor_head_token()
        );
    }

    #[tokio::test]
    async fn canonical_head_is_row_only_and_never_synthesizes_for_blob_only() {
        let (_dir, store) = temp_store();

        // WholeBlob session: plain save writes the document row; no canonical head
        // row exists.
        let mut blob_session = Session::new();
        blob_session.push(user("blob one"));
        store.save(&blob_session).await.unwrap();
        assert!(blob_row_bytes(store.path(), blob_session.id()).is_some());

        let inc = incremental(&store);
        // `load_head` still synthesizes (compat contract, unchanged)...
        assert!(inc.load_head(blob_session.id()).await.unwrap().is_some());
        // ...but the canonical probe must answer None without synthesizing.
        assert!(
            inc.load_canonical_head(blob_session.id())
                .await
                .unwrap()
                .is_none(),
            "a blob-only session has no canonical head row"
        );
        {
            let conn = open_connection(store.path()).unwrap();
            let heads: i64 = conn
                .query_row("SELECT COUNT(*) FROM session_heads", [], |row| row.get(0))
                .unwrap();
            assert_eq!(heads, 0, "the canonical probe must not write");
        }

        // Absent session: None, not an error.
        assert!(
            inc.load_canonical_head(&SessionId::new())
                .await
                .unwrap()
                .is_none()
        );

        // Head-canonical session: the canonical probe serves exactly the
        // persisted head row (== load_head for a head-canonical session).
        let mut head_session = Session::new();
        head_session.push(user("head one"));
        head_session.push(user("head two"));
        let saved_head = seed_incremental(&inc, &head_session).await;
        let canonical = inc
            .load_canonical_head(head_session.id())
            .await
            .unwrap()
            .expect("head-canonical session must advertise its head row");
        assert_eq!(canonical, saved_head);
        assert_eq!(
            Some(canonical),
            inc.load_head(head_session.id()).await.unwrap(),
            "for a head-canonical session the canonical probe equals load_head"
        );
    }

    #[tokio::test]
    async fn rewrite_commits_serve_adopted_commit_rows_without_bodies() {
        let (_dir, store) = temp_store();
        let inc = incremental(&store);
        let mut session = Session::new();
        session.push(user("one"));
        session.push(user("two"));
        let root = PreparedHeadCanonicalMutation::prepare_root(&session)
            .expect("prepare exact component-rooted session");
        inc.apply_prepared_head_canonical_mutation(&root)
            .await
            .expect("persist exact component-rooted session");
        root.acknowledge_session(&mut session, root.successor_head_token())
            .expect("acknowledge exact component roots");
        let head = root.successor_head().clone();
        assert!(
            inc.load_rewrite_commits(session.id())
                .await
                .unwrap()
                .is_empty()
        );

        let commit = session
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 0, end: 2 },
                vec![user("[compacted] summary")],
                TranscriptRewriteReason::new("compaction"),
                Some("test".to_string()),
                None,
            )
            .unwrap();
        let rewrite =
            PreparedHeadCanonicalRewriteMutation::prepare_intra_turn(&session, &head, head.clone())
                .expect("prepare exact compact rewrite");

        // Preparing a carrier is side-effect free. The commit view changes
        // only when the singular prepared mutation atomically installs the
        // exact replay edge and successor head.
        assert!(
            inc.load_rewrite_commits(session.id())
                .await
                .unwrap()
                .is_empty(),
            "an uncommitted prepared rewrite must not be served"
        );
        inc.apply_prepared_head_canonical_rewrite_mutation(&rewrite)
            .await
            .expect("atomically persist exact rewrite carrier");
        let commits = inc.load_rewrite_commits(session.id()).await.unwrap();
        assert_eq!(commits, vec![commit]);
        assert_eq!(
            commits,
            inc.load_rewrites(session.id())
                .await
                .unwrap()
                .into_iter()
                .map(|record| record.commit)
                .collect::<Vec<_>>(),
            "the commit view must equal load_rewrites' commits"
        );
    }

    #[tokio::test]
    async fn incremental_append_and_load_round_trip() {
        let (_dir, store) = temp_store();
        let inc = incremental(&store);
        let mut session = Session::new();
        session.push(user("one"));
        session.push(user("two"));
        seed_incremental(&inc, &session).await;

        let root = TranscriptStrandId::root();
        let loaded = inc.load_messages(session.id(), &root, 0..2).await.unwrap();
        assert_eq!(loaded.len(), 2);

        // Identical re-append is idempotent Ok.
        inc.append_messages(session.id(), &root, 0, session.messages())
            .await
            .expect("identical re-append must be idempotent");
        assert_eq!(strand_row_count(store.path(), session.id(), &root), 2);

        // base_seq gap fails closed.
        let err = inc
            .append_messages(session.id(), &root, 5, &[user("gap")])
            .await
            .expect_err("gap append must be rejected");
        assert!(
            matches!(err, SessionStoreError::TranscriptContinuityViolation { .. }),
            "unexpected error: {err}"
        );

        // Divergent bytes at an existing (strand, seq) fail closed.
        let err = inc
            .append_messages(session.id(), &root, 0, &[user("DIVERGENT")])
            .await
            .expect_err("divergent overwrite must be rejected");
        assert!(
            matches!(err, SessionStoreError::TranscriptContinuityViolation { .. }),
            "unexpected error: {err}"
        );
    }

    #[tokio::test]
    async fn incremental_save_head_guards() {
        let (_dir, store) = temp_store();
        let inc = incremental(&store);
        let mut session = Session::new();
        session.push(user("one"));
        session.push(user("two"));
        let head = seed_incremental(&inc, &session).await;

        // Create on an existing row conflicts.
        let err = inc
            .save_head(&head, SessionHeadCas::Create)
            .await
            .expect_err("Create over an existing head must conflict");
        assert!(matches!(
            err,
            SessionStoreError::TranscriptRevisionConflict { .. }
        ));

        // Stale IfToken conflicts.
        let err = inc
            .save_head(
                &head,
                SessionHeadCas::IfToken("head-sha256:stale".to_string()),
            )
            .await
            .expect_err("stale token must conflict");
        assert!(matches!(
            err,
            SessionStoreError::TranscriptRevisionConflict { .. }
        ));

        let token = session_head_cas_token(&head).unwrap();

        // Same-strand shrink is a MonotonicityViolation.
        let mut shrunk_session = Session::with_id(session.id().clone());
        shrunk_session.push(user("one"));
        let shrunk =
            SessionHead::from_session(&shrunk_session, TranscriptStrandId::root(), 0).unwrap();
        let err = inc
            .save_head(&shrunk, SessionHeadCas::IfToken(token.clone()))
            .await
            .expect_err("same-strand shrink must be rejected");
        assert!(matches!(
            err,
            SessionStoreError::MonotonicityViolation { .. }
        ));

        // Head pointing past persisted rows is rejected.
        let mut extended_session = session.clone();
        extended_session.push(user("three"));
        let past =
            SessionHead::from_session(&extended_session, TranscriptStrandId::root(), 0).unwrap();
        let err = inc
            .save_head(&past, SessionHeadCas::IfToken(token.clone()))
            .await
            .expect_err("head past persisted rows must be rejected");
        assert!(matches!(
            err,
            SessionStoreError::InvalidTranscriptRewrite { .. }
        ));

        // Strand-switch to a fully covered strand is Ok.
        let rebased = TranscriptStrandId::rebase("switch-target");
        inc.append_messages(session.id(), &rebased, 0, session.messages())
            .await
            .unwrap();
        let switched = SessionHead::from_session(&session, rebased, 0).unwrap();
        inc.save_head(&switched, SessionHeadCas::IfToken(token))
            .await
            .expect("strand switch to a covered strand must be accepted");
    }

    fn compacted_fixture() -> (Session, Session, meerkat_core::TranscriptRewriteCommit) {
        let mut parent = Session::new();
        parent.push(user("turn one"));
        parent.push(user("turn two"));
        parent.push(user("turn three"));
        parent.push(user("turn four"));
        let mut compacted = parent.clone();
        let commit = compacted
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 0, end: 4 },
                vec![
                    user("[Context compacted] summary"),
                    user("turn four retained"),
                ],
                TranscriptRewriteReason::new("compaction"),
                Some("test".to_string()),
                None,
            )
            .unwrap();
        (parent, compacted, commit)
    }

    fn record_for(
        session: &Session,
        commit: &meerkat_core::TranscriptRewriteCommit,
    ) -> TranscriptRewriteRecord {
        let parent = session
            .transcript_revision_body(&commit.parent_revision)
            .unwrap()
            .expect("parent body");
        let child = session
            .transcript_revision_body(&commit.revision)
            .unwrap()
            .expect("child body");
        TranscriptRewriteRecord::new(commit.clone(), parent, child).unwrap()
    }

    fn released_exact_splice_document() -> Vec<u8> {
        fn revision(messages: &[Message]) -> String {
            transcript_messages_digest(messages).expect("digest released revision")
        }

        fn released_commit(
            parent: &[Message],
            child: &[Message],
            start: usize,
            end: usize,
            reason: &str,
        ) -> serde_json::Value {
            let commit = TranscriptRewriteCommit {
                rewrite_generation: 0,
                parent_revision: revision(parent),
                revision: revision(child),
                selection: TranscriptRewriteSelection::MessageRange { start, end },
                original_span_digest: transcript_messages_digest(&parent[start..end])
                    .expect("digest released original span"),
                replacement_digest: transcript_messages_digest(
                    &child[start..start + child.len() - (parent.len() - (end - start))],
                )
                .expect("digest released replacement"),
                messages_before: parent.len(),
                messages_after: child.len(),
                reason: TranscriptRewriteReason::new(reason),
                actor: Some("released-fixture".to_string()),
                committed_at: SystemTime::UNIX_EPOCH,
            };
            let mut value = serde_json::to_value(commit).expect("serialize released commit");
            value
                .as_object_mut()
                .expect("released commit object")
                .remove("rewrite_generation");
            value
        }

        let anchor = vec![
            user("retained prefix"),
            user("base row"),
            user("retained suffix"),
        ];
        let mut first = anchor.clone();
        first[1] = user("first rewrite");
        let mut second_parent = first.clone();
        second_parent[1] = user("imported arbitrary-role splice");
        second_parent.push(user("appended parent row"));
        let mut second = second_parent.clone();
        second[2] = user("second rewrite");
        let anchor_revision = revision(&anchor);
        let first_revision = revision(&first);
        let second_parent_revision = revision(&second_parent);
        let second_revision = revision(&second);
        let created_at = serde_json::to_value(SystemTime::UNIX_EPOCH).expect("serialize time");
        let revisions = [
            (&anchor, None),
            (&first, Some(anchor_revision)),
            (&second_parent, Some(first_revision)),
            (&second, Some(second_parent_revision)),
        ]
        .into_iter()
        .map(|(messages, parent_revision)| {
            serde_json::json!({
                "revision": revision(messages),
                "parent_revision": parent_revision,
                "messages": messages,
                "created_at": created_at.clone(),
            })
        })
        .collect::<Vec<_>>();
        let history = serde_json::json!({
            "head": second_revision,
            "commits": [
                released_commit(&anchor, &first, 1, 2, "released edit one"),
                released_commit(&second_parent, &second, 2, 3, "released edit two"),
            ],
            "revisions": revisions,
            "digest_format": 2,
        });
        let mut envelope = serde_json::to_value(Session::new()).expect("serialize envelope");
        envelope["version"] = serde_json::json!(2);
        envelope["messages"] = serde_json::to_value(&second).expect("serialize live messages");
        envelope["metadata"] = serde_json::json!({
            (meerkat_core::SESSION_TRANSCRIPT_HISTORY_STATE_KEY): history,
        });
        serde_json::to_vec(&envelope).expect("serialize released fixture")
    }

    fn imported_released_exact_splice_session() -> Session {
        meerkat_core::import_released_0810_session(&released_exact_splice_document())
            .expect("released importer accepts exact store-authorized splice fixture")
            .into_parts()
            .0
    }

    fn released_v2_file(path: &Path) -> Connection {
        let mut connection = Connection::open(path).expect("open released fixture database");
        let transaction = connection
            .transaction()
            .expect("released schema transaction");
        build_released_0_8_10_session_schema(&transaction).expect("install released schema");
        transaction.commit().expect("commit released schema");
        connection
            .execute_batch(
                "CREATE TABLE meerkat_schema (
                     domain TEXT PRIMARY KEY,
                     version INTEGER NOT NULL
                 );
                 INSERT INTO meerkat_schema VALUES ('session-store', 2);",
            )
            .expect("stamp released schema ledger");
        connection
    }

    fn insert_released_blob_row(connection: &Connection, source_document: &[u8]) -> Session {
        let imported = meerkat_core::import_released_0810_session(source_document)
            .expect("released blob source imports")
            .into_parts()
            .0;
        let source: serde_json::Value =
            serde_json::from_slice(source_document).expect("decode released blob source");
        let metadata = source
            .get("metadata")
            .and_then(serde_json::Value::as_object)
            .expect("released blob metadata");
        connection
            .execute(
                "INSERT INTO sessions (
                     session_id, created_at_ms, updated_at_ms, message_count,
                     total_tokens, metadata_json, session_json
                 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                params![
                    imported.id().to_string(),
                    system_time_millis(imported.created_at()),
                    system_time_millis(imported.updated_at()),
                    i64::try_from(
                        source
                            .get("messages")
                            .and_then(serde_json::Value::as_array)
                            .expect("released blob messages")
                            .len()
                    )
                    .expect("released message count"),
                    i64::try_from(imported.total_tokens()).expect("released token count"),
                    serde_json::to_string(metadata).expect("released metadata JSON"),
                    source_document,
                ],
            )
            .expect("insert released blob row");
        imported
    }

    fn insert_released_rewrite_head(connection: &mut Connection, session: &Session) -> SessionHead {
        let history = session
            .validated_transcript_history_state()
            .expect("released fixture current history validates")
            .expect("released fixture carries rewrite history");
        let layout =
            strand_layout_for_history(session, Some(&history)).expect("lay out released history");
        assert_eq!(layout.rewrites.len(), 2);

        let transaction = connection.transaction().expect("released head transaction");
        let mut released_source = TranscriptStrandId::root();
        let mut released_head_strand = released_source.clone();
        for (index, expected) in layout.rewrites.iter().enumerate() {
            let parent = history
                .materialize_rewrite_parent(&expected.commit)
                .expect("materialize released parent")
                .messages;
            let child = history
                .materialize_rewrite_child(&expected.commit)
                .expect("materialize released child")
                .messages;
            let released_parent = match &expected.parent_transition {
                PreparedHeadCanonicalParentTransition::ExactAppend => released_source.clone(),
                PreparedHeadCanonicalParentTransition::ExactSplice(_) => {
                    TranscriptStrandId::rebase(&expected.commit.parent_revision)
                }
            };
            let mut released_commit = expected.commit.clone();
            released_commit.rewrite_generation = 0;
            let released_child = TranscriptStrandId::from_rewrite(&released_commit);
            insert_strand_rows_in_txn(&transaction, session.id(), &released_parent, 0, &parent)
                .expect("insert released parent body");
            insert_strand_rows_in_txn(&transaction, session.id(), &released_child, 0, &child)
                .expect("insert released child body");
            let mut commit_json =
                serde_json::to_value(&released_commit).expect("serialize released commit");
            commit_json
                .as_object_mut()
                .expect("released commit object")
                .remove("rewrite_generation");
            transaction
                .execute(
                    "INSERT INTO session_rewrites (
                         session_id, rewrite_idx, parent_strand, parent_len,
                         strand, strand_len, commit_json, created_at_ms
                     ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                    params![
                        session.id().to_string(),
                        i64::try_from(index).expect("released rewrite index"),
                        released_parent.as_str(),
                        i64::try_from(parent.len()).expect("released parent length"),
                        released_child.as_str(),
                        i64::try_from(child.len()).expect("released child length"),
                        serde_json::to_vec(&commit_json).expect("released commit bytes"),
                        now_millis(),
                    ],
                )
                .expect("insert released rewrite row");
            supersede_strand_in_txn(
                &transaction,
                session.id(),
                &released_parent,
                &released_child,
            )
            .expect("install released supersession link");
            released_source = released_child.clone();
            released_head_strand = released_child;
        }

        let projected =
            SessionHead::from_session(session, released_head_strand, layout.rewrites.len() as u64)
                .expect("project released head");
        let mut released_head_json =
            serde_json::to_value(&projected).expect("serialize projected head");
        let released_head = released_head_json
            .as_object_mut()
            .expect("released head object");
        released_head.insert("version".to_string(), serde_json::json!(2));
        for current_only in [
            "message_row_prefix",
            "row_lineage_anchor",
            "rewrite_prefix",
            "graph_prefix",
            "realtime_event_prefix",
            "metadata_identity",
        ] {
            released_head.remove(current_only);
        }
        let released_head: SessionHead =
            serde_json::from_value(released_head_json).expect("decode exact released head shape");
        let released_head_bytes =
            serde_json::to_vec(&released_head).expect("serialize exact released head bytes");
        let released_token = format!("head-sha256:{:x}", Sha256::digest(&released_head_bytes));
        transaction
            .execute(
                "INSERT INTO session_heads (
                     session_id, version, strand, head_revision, message_count,
                     rewrite_count, total_tokens, created_at_ms, updated_at_ms,
                     metadata_json, head_json, cas_token
                 ) VALUES (?1, 2, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
                params![
                    released_head.id.to_string(),
                    released_head.strand.as_str(),
                    released_head.head_revision,
                    i64::try_from(released_head.message_count).expect("released head count"),
                    i64::try_from(released_head.rewrite_count).expect("released rewrite count"),
                    i64::try_from(released_head.usage.total_tokens())
                        .expect("released head token count"),
                    system_time_millis(released_head.created_at),
                    system_time_millis(released_head.updated_at),
                    serde_json::to_string(&released_head.metadata).expect("released head metadata"),
                    released_head_bytes,
                    released_token,
                ],
            )
            .expect("write exact released head");
        transaction
            .commit()
            .expect("commit released rewrite fixture");
        released_head
    }

    fn released_prompt_row(generation: usize) -> Vec<u8> {
        serde_json::to_vec(&serde_json::json!({
            "role": "system",
            "content": format!("HomeCore prompt generation {generation}"),
            "mutation_kind": "explicit_build",
            "created_at": "2026-07-30T13:43:00Z",
        }))
        .expect("serialize exact released prompt row")
    }

    fn released_rows_digest(rows: &[Vec<u8>]) -> String {
        meerkat_core::released_0810_transcript_serialized_rows_digest(rows)
            .expect("digest exact released rows")
    }

    fn insert_released_prompt_rewrite_chain(
        connection: &mut Connection,
        rewrite_count: usize,
    ) -> (SessionId, SessionHead) {
        assert!(rewrite_count > 0, "released prompt chain must be non-empty");
        let id = SessionId::new();
        let transaction = connection
            .transaction()
            .expect("released prompt-chain transaction");
        let mut parent_row = released_prompt_row(0);
        let mut parent_revision = released_rows_digest(std::slice::from_ref(&parent_row));
        let mut parent_strand = TranscriptStrandId::root();

        transaction
            .execute(
                "INSERT INTO session_strand_messages (
                     session_id, strand, seq, message_json, created_at_ms
                 ) VALUES (?1, ?2, 0, ?3, ?4)",
                params![
                    id.to_string(),
                    parent_strand.as_str(),
                    &parent_row,
                    now_millis(),
                ],
            )
            .expect("insert released prompt anchor");

        for index in 0..rewrite_count {
            let child_row = released_prompt_row(index + 1);
            let child_revision = released_rows_digest(std::slice::from_ref(&child_row));
            let commit = TranscriptRewriteCommit {
                rewrite_generation: 0,
                parent_revision: parent_revision.clone(),
                revision: child_revision.clone(),
                selection: TranscriptRewriteSelection::MessageRange { start: 0, end: 1 },
                original_span_digest: parent_revision.clone(),
                replacement_digest: child_revision.clone(),
                messages_before: 1,
                messages_after: 1,
                reason: TranscriptRewriteReason::new(format!(
                    "released prompt refresh {}",
                    index + 1
                )),
                actor: Some("released-homecore-fixture".to_string()),
                committed_at: SystemTime::UNIX_EPOCH,
            };
            let child_strand = TranscriptStrandId::from_rewrite(&commit);
            transaction
                .execute(
                    "INSERT INTO session_strand_messages (
                         session_id, strand, seq, message_json, created_at_ms
                     ) VALUES (?1, ?2, 0, ?3, ?4)",
                    params![
                        id.to_string(),
                        child_strand.as_str(),
                        &child_row,
                        now_millis(),
                    ],
                )
                .expect("insert released prompt child");
            let mut commit_json =
                serde_json::to_value(&commit).expect("serialize released prompt commit");
            commit_json
                .as_object_mut()
                .expect("released prompt commit object")
                .remove("rewrite_generation");
            transaction
                .execute(
                    "INSERT INTO session_rewrites (
                         session_id, rewrite_idx, parent_strand, parent_len,
                         strand, strand_len, commit_json, created_at_ms
                     ) VALUES (?1, ?2, ?3, 1, ?4, 1, ?5, ?6)",
                    params![
                        id.to_string(),
                        i64::try_from(index).expect("released prompt rewrite index"),
                        parent_strand.as_str(),
                        child_strand.as_str(),
                        serde_json::to_vec(&commit_json)
                            .expect("serialize released prompt commit bytes"),
                        now_millis(),
                    ],
                )
                .expect("insert released prompt rewrite");
            supersede_strand_in_txn(&transaction, &id, &parent_strand, &child_strand)
                .expect("install released prompt supersession");
            parent_row = child_row;
            parent_revision = child_revision;
            parent_strand = child_strand;
        }

        let final_message: Message =
            serde_json::from_slice(&parent_row).expect("decode released prompt endpoint");
        let mut final_session = Session::with_id(id.clone());
        final_session.push(final_message);
        let mut released_head =
            SessionHead::from_session(&final_session, TranscriptStrandId::root(), 0)
                .expect("project released prompt envelope");
        released_head.version = 2;
        released_head.strand = parent_strand;
        released_head.head_revision = parent_revision;
        released_head.rewrite_count =
            u64::try_from(rewrite_count).expect("released prompt rewrite count");
        released_head.message_row_prefix = None;
        released_head.row_lineage_anchor = None;
        released_head.rewrite_prefix = TranscriptRewritePrefixAccumulator::empty();
        released_head.graph_prefix = None;
        released_head.realtime_event_prefix = None;
        released_head.metadata_identity = None;
        let released_head_bytes =
            serde_json::to_vec(&released_head).expect("serialize released prompt head");
        let released_token = format!("head-sha256:{:x}", Sha256::digest(&released_head_bytes));
        transaction
            .execute(
                "INSERT INTO session_heads (
                     session_id, version, strand, head_revision, message_count,
                     rewrite_count, total_tokens, created_at_ms, updated_at_ms,
                     metadata_json, head_json, cas_token
                 ) VALUES (?1, 2, ?2, ?3, 1, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
                params![
                    id.to_string(),
                    released_head.strand.as_str(),
                    released_head.head_revision,
                    i64::try_from(rewrite_count).expect("released prompt rewrite count"),
                    i64::try_from(released_head.usage.total_tokens())
                        .expect("released prompt token count"),
                    system_time_millis(released_head.created_at),
                    system_time_millis(released_head.updated_at),
                    serde_json::to_string(&released_head.metadata)
                        .expect("released prompt metadata"),
                    released_head_bytes,
                    released_token,
                ],
            )
            .expect("write released prompt head");
        transaction
            .commit()
            .expect("commit released prompt-chain fixture");
        (id, released_head)
    }

    fn replace_all_bytes(haystack: &mut Vec<u8>, needle: &[u8], replacement: &[u8]) -> usize {
        let mut replaced = 0;
        let mut cursor = 0;
        while let Some(offset) = haystack[cursor..]
            .windows(needle.len())
            .position(|candidate| candidate == needle)
        {
            let start = cursor + offset;
            haystack.splice(start..start + needle.len(), replacement.iter().copied());
            cursor = start + replacement.len();
            replaced += 1;
        }
        replaced
    }

    fn released_tool_message(name: &str, raw: &str) -> Message {
        Message::BlockAssistant(BlockAssistantMessage::new(
            vec![AssistantBlock::ToolUse {
                id: "tool-1".to_string(),
                name: name.to_string(),
                args: serde_json::value::RawValue::from_string(raw.to_string())
                    .expect("valid released tool arguments"),
                meta: None,
            }],
            StopReason::ToolUse,
        ))
    }

    fn released_tool_row(message: &Message, canonical_raw: &str, released_raw: &str) -> Vec<u8> {
        let mut row = serde_json::to_vec(message).expect("serialize released tool row");
        let replacements =
            replace_all_bytes(&mut row, canonical_raw.as_bytes(), released_raw.as_bytes());
        assert_eq!(replacements, 1, "fixture must replace one raw payload");
        row
    }

    fn released_tool_digest(message: &Message, canonical_raw: &str, released_raw: &str) -> String {
        let mut canonical = message.clone();
        assert!(matches!(canonical, Message::BlockAssistant(_)));
        if let Message::BlockAssistant(assistant) = &mut canonical {
            assistant.identity = Default::default();
            assistant.created_at = chrono::DateTime::UNIX_EPOCH;
        }
        let mut bytes =
            serde_json::to_vec(&[canonical]).expect("serialize released tool digest form");
        let replacements = replace_all_bytes(
            &mut bytes,
            canonical_raw.as_bytes(),
            released_raw.as_bytes(),
        );
        assert_eq!(
            replacements, 1,
            "fixture must replace one digest raw payload"
        );
        format!("sha256:{:x}", Sha256::digest(bytes))
    }

    fn insert_exact_released_strand_row(
        transaction: &Transaction<'_>,
        id: &SessionId,
        strand: &TranscriptStrandId,
        row: &[u8],
    ) {
        transaction
            .execute(
                "INSERT INTO session_strand_messages (
                     session_id, strand, seq, message_json, created_at_ms
                 ) VALUES (?1, ?2, 0, ?3, ?4)",
                params![id.to_string(), strand.as_str(), row, now_millis()],
            )
            .expect("insert exact released strand row");
    }

    fn insert_released_raw_collapse_head(
        connection: &mut Connection,
        retain_semantic_tail: bool,
    ) -> (SessionId, String) {
        let canonical_raw = r#"{"a":2,"z":1}"#;
        let released_raw = r#"{"z":1,"a":2}"#;
        let parent = released_tool_message("opaque", released_raw);
        let collapsed = released_tool_message("opaque", canonical_raw);
        let final_message = if retain_semantic_tail {
            released_tool_message("opaque-revised", released_raw)
        } else {
            collapsed.clone()
        };
        let parent_revision = released_tool_digest(&parent, canonical_raw, released_raw);
        let collapsed_revision = released_tool_digest(&collapsed, canonical_raw, canonical_raw);
        let final_revision = if retain_semantic_tail {
            released_tool_digest(&final_message, canonical_raw, released_raw)
        } else {
            collapsed_revision.clone()
        };
        assert_ne!(parent_revision, collapsed_revision);
        assert_eq!(
            transcript_messages_digest(std::slice::from_ref(&parent))
                .expect("current parent digest"),
            transcript_messages_digest(std::slice::from_ref(&collapsed))
                .expect("current collapsed digest"),
            "the first released occurrence differs only by RawValue spelling"
        );

        let commit = |parent_revision: String,
                      revision: String,
                      original_span_digest: String,
                      replacement_digest: String,
                      reason: &str| TranscriptRewriteCommit {
            rewrite_generation: 0,
            parent_revision,
            revision,
            selection: TranscriptRewriteSelection::MessageRange { start: 0, end: 1 },
            original_span_digest,
            replacement_digest,
            messages_before: 1,
            messages_after: 1,
            reason: TranscriptRewriteReason::new(reason),
            actor: Some("released-fixture".to_string()),
            committed_at: SystemTime::UNIX_EPOCH,
        };
        let collapsed_commit = commit(
            parent_revision.clone(),
            collapsed_revision.clone(),
            parent_revision,
            collapsed_revision.clone(),
            "released spelling-only rewrite",
        );
        let mut commits = vec![collapsed_commit];
        if retain_semantic_tail {
            commits.push(commit(
                collapsed_revision.clone(),
                final_revision.clone(),
                collapsed_revision,
                final_revision.clone(),
                "released semantic rewrite",
            ));
        }

        let mut session = Session::new();
        session.push(final_message.clone());
        let id = session.id().clone();
        let transaction = connection
            .transaction()
            .expect("released collapse transaction");
        let root = TranscriptStrandId::root();
        insert_exact_released_strand_row(
            &transaction,
            &id,
            &root,
            &released_tool_row(&parent, canonical_raw, released_raw),
        );
        let mut parent_strand = root;
        let mut head_strand = parent_strand.clone();
        for (index, rewrite) in commits.iter().enumerate() {
            let child = TranscriptStrandId::from_rewrite(rewrite);
            let (message, physical_raw) = if index == 0 {
                (&collapsed, canonical_raw)
            } else {
                (&final_message, released_raw)
            };
            insert_exact_released_strand_row(
                &transaction,
                &id,
                &child,
                &released_tool_row(message, canonical_raw, physical_raw),
            );
            let mut commit_json =
                serde_json::to_value(rewrite).expect("serialize released collapse commit");
            commit_json
                .as_object_mut()
                .expect("released collapse commit object")
                .remove("rewrite_generation");
            transaction
                .execute(
                    "INSERT INTO session_rewrites (
                         session_id, rewrite_idx, parent_strand, parent_len,
                         strand, strand_len, commit_json, created_at_ms
                     ) VALUES (?1, ?2, ?3, 1, ?4, 1, ?5, ?6)",
                    params![
                        id.to_string(),
                        i64::try_from(index).expect("released collapse rewrite index"),
                        parent_strand.as_str(),
                        child.as_str(),
                        serde_json::to_vec(&commit_json)
                            .expect("serialize released collapse commit bytes"),
                        now_millis(),
                    ],
                )
                .expect("insert released collapse rewrite row");
            supersede_strand_in_txn(&transaction, &id, &parent_strand, &child)
                .expect("install released collapse supersession");
            parent_strand = child.clone();
            head_strand = child;
        }

        let head = SessionHead::from_session(&session, head_strand, 0)
            .expect("project released collapse head envelope");
        let mut head_json = serde_json::to_value(&head).expect("serialize released collapse head");
        let head_object = head_json
            .as_object_mut()
            .expect("released collapse head object");
        head_object.insert("version".to_string(), serde_json::json!(2));
        head_object.insert(
            "head_revision".to_string(),
            serde_json::Value::String(final_revision.clone()),
        );
        head_object.insert(
            "rewrite_count".to_string(),
            serde_json::json!(commits.len()),
        );
        for current_only in [
            "message_row_prefix",
            "row_lineage_anchor",
            "rewrite_prefix",
            "graph_prefix",
            "realtime_event_prefix",
            "metadata_identity",
        ] {
            head_object.remove(current_only);
        }
        let released_head: SessionHead =
            serde_json::from_value(head_json).expect("decode exact released collapse head");
        let released_head_bytes =
            serde_json::to_vec(&released_head).expect("serialize exact released collapse head");
        let released_token = format!("head-sha256:{:x}", Sha256::digest(&released_head_bytes));
        transaction
            .execute(
                "INSERT INTO session_heads (
                     session_id, version, strand, head_revision, message_count,
                     rewrite_count, total_tokens, created_at_ms, updated_at_ms,
                     metadata_json, head_json, cas_token
                 ) VALUES (?1, 2, ?2, ?3, 1, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
                params![
                    id.to_string(),
                    released_head.strand.as_str(),
                    released_head.head_revision,
                    i64::try_from(released_head.rewrite_count)
                        .expect("released collapse rewrite count"),
                    i64::try_from(released_head.usage.total_tokens())
                        .expect("released collapse token count"),
                    system_time_millis(released_head.created_at),
                    system_time_millis(released_head.updated_at),
                    serde_json::to_string(&released_head.metadata)
                        .expect("released collapse metadata"),
                    released_head_bytes,
                    released_token,
                ],
            )
            .expect("write exact released collapse head");
        transaction
            .commit()
            .expect("commit released collapse fixture");
        (id, final_revision)
    }

    fn insert_released_pending_rewrite_tail(
        connection: &mut Connection,
        head: &SessionHead,
        session: &Session,
    ) -> TranscriptRewriteCommit {
        let mut child_messages = session.messages().to_vec();
        let start = child_messages
            .len()
            .checked_sub(1)
            .expect("released pending fixture has a parent row");
        child_messages[start] = user("unadopted pending replacement");
        let child_revision =
            transcript_messages_digest(&child_messages).expect("released pending child digest");
        let commit = TranscriptRewriteCommit {
            rewrite_generation: 0,
            parent_revision: head.head_revision.clone(),
            revision: child_revision,
            selection: TranscriptRewriteSelection::MessageRange {
                start,
                end: start + 1,
            },
            original_span_digest: transcript_messages_digest(&session.messages()[start..=start])
                .expect("released pending original span"),
            replacement_digest: transcript_messages_digest(&child_messages[start..=start])
                .expect("released pending replacement span"),
            messages_before: session.messages().len(),
            messages_after: child_messages.len(),
            reason: TranscriptRewriteReason::new("unadopted pending rewrite"),
            actor: Some("released-fixture".to_string()),
            committed_at: SystemTime::UNIX_EPOCH,
        };
        let child_strand = TranscriptStrandId::from_rewrite(&commit);
        let transaction = connection
            .transaction()
            .expect("released pending transaction");
        insert_strand_rows_in_txn(
            &transaction,
            session.id(),
            &child_strand,
            0,
            &child_messages,
        )
        .expect("insert released pending child body");
        let mut commit_json =
            serde_json::to_value(&commit).expect("serialize released pending commit");
        commit_json
            .as_object_mut()
            .expect("released pending commit object")
            .remove("rewrite_generation");
        transaction
            .execute(
                "INSERT INTO session_rewrites (
                     session_id, rewrite_idx, parent_strand, parent_len,
                     strand, strand_len, commit_json, created_at_ms
                 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                params![
                    session.id().to_string(),
                    i64::try_from(head.rewrite_count).expect("released pending rewrite index"),
                    head.strand.as_str(),
                    i64::try_from(session.messages().len())
                        .expect("released pending parent length"),
                    child_strand.as_str(),
                    i64::try_from(child_messages.len()).expect("released pending child length"),
                    serde_json::to_vec(&commit_json)
                        .expect("serialize released pending commit bytes"),
                    now_millis(),
                ],
            )
            .expect("insert released pending rewrite row");
        transaction
            .commit()
            .expect("commit released pending rewrite fixture");
        commit
    }

    #[tokio::test]
    async fn released_rewrite_head_import_preserves_audit_and_supports_new_work() {
        let directory = TempDir::new().expect("released rewrite fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let released_session = imported_released_exact_splice_session();
        let released_head = insert_released_rewrite_head(&mut connection, &released_session);
        assert_eq!(released_head.rewrite_count, 2);
        drop(connection);

        let store =
            SqliteSessionStore::open(&path).expect("migrate exact released rewrite-bearing store");
        let imported = store
            .load(released_session.id())
            .await
            .expect("load migrated rewrite-bearing session")
            .expect("migrated rewrite-bearing session exists");
        assert_eq!(imported.messages(), released_session.messages());
        let incremental = incremental(&store);
        let imported_records = incremental
            .load_rewrites(released_session.id())
            .await
            .expect("load imported rewrite audit");
        assert_eq!(imported_records.len(), 2);
        let released_history = released_session
            .validated_transcript_history_state()
            .expect("released expected history validates")
            .expect("released expected history exists");
        let released_suffix = released_history
            .prove_commit_suffix_after(&TranscriptRewritePrefixAccumulator::empty())
            .expect("released expected rewrite suffix");
        let first_released_commit = released_suffix
            .commits()
            .next()
            .expect("released expected first rewrite");
        let first_released_parent = released_history
            .materialize_rewrite_parent(first_released_commit)
            .expect("materialize released expected first parent");
        assert_eq!(
            imported_records[0].parent_body.messages,
            first_released_parent.messages
        );
        assert_eq!(
            imported_records[1].revision_body.messages,
            released_session.messages()
        );
        let imported_head = incremental
            .load_head(released_session.id())
            .await
            .expect("load imported head")
            .expect("imported head exists");
        assert_eq!(imported_head.rewrite_count, 2);
        assert_eq!(imported_head.version, meerkat_core::SESSION_VERSION);

        let store_for_activation =
            SqliteSessionStore::open(&path).expect("open activation store handle");
        let id = released_session.id().clone();
        let (runtime_head, _) = store_for_activation
            .in_write_txn(move |transaction| {
                ensure_head_canonical_for_runtime_in_txn(transaction, &id)?
                    .ok_or(SessionStoreError::NotFound(id))
            })
            .await
            .expect("activate imported rewrite-bearing head");
        let materialized = incremental
            .materialize_head(&runtime_head)
            .await
            .expect("materialize imported rewrite audit");
        let mut continued = materialized.session().as_ref().clone();
        continued.push(user("post-import append"));
        let append = PreparedHeadCanonicalMutation::prepare(&continued, Some(runtime_head.clone()))
            .expect("prepare post-import append");
        incremental
            .apply_prepared_head_canonical_mutation(&append)
            .await
            .expect("apply post-import append");
        append
            .acknowledge_physical_projection(&mut continued, append.successor_head_token())
            .expect("acknowledge post-import append");

        continued
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 1, end: 2 },
                vec![user("post-import replacement")],
                TranscriptRewriteReason::new("post-import rewrite"),
                Some("migration-test".to_string()),
                None,
            )
            .expect("commit post-import rewrite");
        let rewrite = PreparedHeadCanonicalRewriteMutation::prepare_intra_turn(
            &continued,
            &runtime_head,
            append.successor_head().clone(),
        )
        .expect("prepare post-import rewrite");
        incremental
            .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
            .await
            .expect("apply post-import rewrite");

        let final_records = incremental
            .load_rewrites(released_session.id())
            .await
            .expect("load extended rewrite audit");
        assert_eq!(final_records.len(), 3);
        assert_eq!(
            final_records[..2]
                .iter()
                .map(|record| record.commit.reason.clone())
                .collect::<Vec<_>>(),
            [
                TranscriptRewriteReason::new("released edit one"),
                TranscriptRewriteReason::new("released edit two"),
            ]
        );
        let final_session = store
            .load(released_session.id())
            .await
            .expect("load post-import rewritten session")
            .expect("post-import rewritten session exists");
        assert_eq!(final_session.messages(), continued.messages());
    }

    #[tokio::test]
    async fn released_twenty_six_prompt_rewrites_import_as_exact_prefix_and_continue() {
        const RELEASED_REWRITE_COUNT: usize = 26;

        let directory = TempDir::new().expect("released prompt-chain fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let (id, released_head) =
            insert_released_prompt_rewrite_chain(&mut connection, RELEASED_REWRITE_COUNT);
        assert_eq!(
            released_head.rewrite_count,
            u64::try_from(RELEASED_REWRITE_COUNT).expect("released rewrite count")
        );
        drop(connection);

        let store =
            SqliteSessionStore::open(&path).expect("migrate released 26-prompt-rewrite store");
        let incremental = incremental(&store);
        let imported = store
            .load(&id)
            .await
            .expect("load migrated prompt chain")
            .expect("migrated prompt chain exists");
        let imported_history = imported
            .validated_transcript_history_state()
            .expect("imported prompt graph validates")
            .expect("imported prompt graph exists");
        assert_eq!(imported_history.commit_count(), RELEASED_REWRITE_COUNT);
        let imported_edges = imported_history.edges().to_vec();
        let imported_records = incremental
            .load_rewrites(&id)
            .await
            .expect("load all imported prompt rewrites");
        assert_eq!(imported_records.len(), RELEASED_REWRITE_COUNT);
        assert_eq!(
            imported_records
                .iter()
                .map(|record| record.commit.rewrite_generation)
                .collect::<Vec<_>>(),
            (1..=u64::try_from(RELEASED_REWRITE_COUNT).expect("released rewrite count"))
                .collect::<Vec<_>>()
        );

        let activation_store =
            SqliteSessionStore::open(&path).expect("open prompt-chain activation store");
        let activation_id = id.clone();
        let (runtime_head, _) = activation_store
            .in_write_txn(move |transaction| {
                ensure_head_canonical_for_runtime_in_txn(transaction, &activation_id)?
                    .ok_or(SessionStoreError::NotFound(activation_id))
            })
            .await
            .expect("activate imported prompt chain");
        assert_eq!(
            incremental
                .load_rewrites(&id)
                .await
                .expect("bare resume leaves prompt history untouched")
                .len(),
            RELEASED_REWRITE_COUNT,
            "0.8.11 activation must not mint a resume-time prompt replacement"
        );

        let materialized = incremental
            .materialize_head(&runtime_head)
            .await
            .expect("materialize imported prompt chain");
        let mut continued = materialized.session().as_ref().clone();
        continued.push(Message::System(SystemMessage::new(
            "post-upgrade ordered instruction",
        )));
        let append = PreparedHeadCanonicalMutation::prepare(&continued, Some(runtime_head.clone()))
            .expect("prepare post-upgrade System append");
        incremental
            .apply_prepared_head_canonical_mutation(&append)
            .await
            .expect("persist post-upgrade System append");
        append
            .acknowledge_physical_projection(&mut continued, append.successor_head_token())
            .expect("acknowledge post-upgrade System append");
        assert_eq!(
            incremental
                .load_rewrites(&id)
                .await
                .expect("System append leaves rewrite history untouched")
                .len(),
            RELEASED_REWRITE_COUNT
        );

        continued
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 0, end: 1 },
                vec![Message::System(SystemMessage::new(
                    "first current prompt rewrite",
                ))],
                TranscriptRewriteReason::new("post-upgrade explicit rewrite"),
                Some("migration-test".to_string()),
                None,
            )
            .expect("commit first current prompt rewrite");
        let rewrite = PreparedHeadCanonicalRewriteMutation::prepare_intra_turn(
            &continued,
            &runtime_head,
            append.successor_head().clone(),
        )
        .expect("prepare first current prompt rewrite");
        incremental
            .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
            .await
            .expect("persist first current prompt rewrite");

        let final_records = incremental
            .load_rewrites(&id)
            .await
            .expect("load extended prompt rewrite audit");
        assert_eq!(final_records.len(), RELEASED_REWRITE_COUNT + 1);
        assert_eq!(
            final_records[..RELEASED_REWRITE_COUNT]
                .iter()
                .map(|record| &record.commit)
                .collect::<Vec<_>>(),
            imported_records
                .iter()
                .map(|record| &record.commit)
                .collect::<Vec<_>>(),
            "all released prompt rewrites must remain the exact ordered prefix"
        );
        assert_eq!(
            final_records
                .last()
                .expect("current rewrite exists")
                .commit
                .rewrite_generation,
            u64::try_from(RELEASED_REWRITE_COUNT + 1).expect("current rewrite generation")
        );

        let final_session = store
            .load(&id)
            .await
            .expect("load continued prompt chain")
            .expect("continued prompt chain exists");
        let final_history = final_session
            .validated_transcript_history_state()
            .expect("continued prompt graph validates")
            .expect("continued prompt graph exists");
        assert_eq!(final_history.commit_count(), RELEASED_REWRITE_COUNT + 1);
        assert_eq!(
            &final_history.edges()[..RELEASED_REWRITE_COUNT],
            imported_edges.as_slice(),
            "current work must extend, never replace, the imported compact graph"
        );
    }

    #[tokio::test]
    async fn released_raw_spelling_collapse_rebuilds_only_semantic_rewrite_tail() {
        let directory = TempDir::new().expect("released collapse fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let (id, released_head_revision) = insert_released_raw_collapse_head(&mut connection, true);
        let exact_rows = connection
            .prepare(
                "SELECT message_json FROM session_strand_messages
                 WHERE session_id = ?1 ORDER BY strand, seq",
            )
            .expect("query released collapse rows")
            .query_map(params![id.to_string()], |row| {
                Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes())
            })
            .expect("read released collapse rows")
            .collect::<Result<Vec<_>, _>>()
            .expect("collect released collapse rows");
        assert!(
            exact_rows.iter().any(|row| row
                .windows(br#"{"z":1,"a":2}"#.len())
                .any(|candidate| candidate == br#"{"z":1,"a":2}"#)),
            "fixture must retain the exact noncanonical released RawValue spelling"
        );
        drop(connection);

        let store =
            SqliteSessionStore::open(&path).expect("migrate released raw-spelling collapse");
        let incremental = incremental(&store);
        let head = incremental
            .load_head(&id)
            .await
            .expect("load rebuilt collapse head")
            .expect("rebuilt collapse head exists");
        assert_eq!(head.version, meerkat_core::SESSION_VERSION);
        assert_eq!(head.rewrite_count, 1);
        assert_ne!(head.head_revision, released_head_revision);
        let records = incremental
            .load_rewrites(&id)
            .await
            .expect("load rebuilt semantic rewrite tail");
        assert_eq!(records.len(), 1);
        assert_eq!(
            records[0].commit.reason,
            TranscriptRewriteReason::new("released semantic rewrite")
        );

        let store_for_activation =
            SqliteSessionStore::open(&path).expect("open collapse activation store");
        let activation_id = id.clone();
        let (runtime_head, _) = store_for_activation
            .in_write_txn(move |transaction| {
                ensure_head_canonical_for_runtime_in_txn(transaction, &activation_id)?
                    .ok_or(SessionStoreError::NotFound(activation_id))
            })
            .await
            .expect("activate rebuilt collapse head");
        let materialized = incremental
            .materialize_head(&runtime_head)
            .await
            .expect("materialize rebuilt collapse head");
        let mut continued = materialized.session().as_ref().clone();
        continued
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 0, end: 1 },
                vec![user("post-collapse replacement")],
                TranscriptRewriteReason::new("post-collapse rewrite"),
                Some("migration-test".to_string()),
                None,
            )
            .expect("commit post-collapse rewrite");
        let rewrite = PreparedHeadCanonicalRewriteMutation::prepare_intra_turn(
            &continued,
            &runtime_head,
            runtime_head.clone(),
        )
        .expect("prepare post-collapse rewrite");
        incremental
            .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
            .await
            .expect("persist post-collapse rewrite");
        assert_eq!(
            incremental
                .load_rewrites(&id)
                .await
                .expect("load extended collapse history")
                .len(),
            2
        );
    }

    #[tokio::test]
    async fn released_all_collapsed_raw_spelling_history_disappears_cleanly() {
        let directory = TempDir::new().expect("released all-collapsed fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let (id, released_head_revision) =
            insert_released_raw_collapse_head(&mut connection, false);
        drop(connection);

        let store =
            SqliteSessionStore::open(&path).expect("migrate all-collapsed released history");
        let incremental = incremental(&store);
        let head = incremental
            .load_head(&id)
            .await
            .expect("load all-collapsed rebuilt head")
            .expect("all-collapsed rebuilt head exists");
        assert_eq!(head.rewrite_count, 0);
        assert_eq!(head.head_revision, released_head_revision);
        assert!(
            incremental
                .load_rewrites(&id)
                .await
                .expect("load all-collapsed rewrite audit")
                .is_empty()
        );

        let store_for_activation =
            SqliteSessionStore::open(&path).expect("open all-collapsed activation store");
        let activation_id = id.clone();
        let (runtime_head, _) = store_for_activation
            .in_write_txn(move |transaction| {
                ensure_head_canonical_for_runtime_in_txn(transaction, &activation_id)?
                    .ok_or(SessionStoreError::NotFound(activation_id))
            })
            .await
            .expect("activate all-collapsed rebuilt head");
        let materialized = incremental
            .materialize_head(&runtime_head)
            .await
            .expect("materialize all-collapsed rebuilt head");
        let mut continued = materialized.session().as_ref().clone();
        continued
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 0, end: 1 },
                vec![user("first current rewrite")],
                TranscriptRewriteReason::new("current rewrite"),
                Some("migration-test".to_string()),
                None,
            )
            .expect("commit first current rewrite");
        let rewrite = PreparedHeadCanonicalRewriteMutation::prepare_intra_turn(
            &continued,
            &runtime_head,
            runtime_head.clone(),
        )
        .expect("prepare first current rewrite");
        incremental
            .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
            .await
            .expect("persist first current rewrite");
        assert_eq!(
            incremental
                .load_rewrites(&id)
                .await
                .expect("load first current rewrite")
                .len(),
            1
        );
    }

    #[tokio::test]
    async fn released_unadopted_pending_rewrite_is_discarded_before_current_work() {
        let directory = TempDir::new().expect("released pending fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let released_session = imported_released_exact_splice_session();
        let released_head = insert_released_rewrite_head(&mut connection, &released_session);
        let pending = insert_released_pending_rewrite_tail(
            &mut connection,
            &released_head,
            &released_session,
        );
        assert_eq!(pending.rewrite_generation, 0);
        assert_eq!(
            rewrite_row_count_in_txn(
                &connection.transaction().expect("pending count transaction"),
                released_session.id()
            )
            .expect("count released pending rows"),
            released_head.rewrite_count + 1
        );
        drop(connection);

        let store =
            SqliteSessionStore::open(&path).expect("migrate released head with pending rewrite");
        let incremental = incremental(&store);
        let imported_head = incremental
            .load_head(released_session.id())
            .await
            .expect("load pending-cleaned head")
            .expect("pending-cleaned head exists");
        assert_eq!(imported_head.rewrite_count, 2);
        let imported_records = incremental
            .load_rewrites(released_session.id())
            .await
            .expect("load pending-cleaned audit");
        assert_eq!(imported_records.len(), 2);
        assert!(
            imported_records
                .iter()
                .all(|record| record.commit.reason != pending.reason),
            "the separately durable runtime candidate owns recovery; public session migration \
             must not adopt its unadopted rewrite row"
        );

        let store_for_activation =
            SqliteSessionStore::open(&path).expect("open pending activation store");
        let activation_id = released_session.id().clone();
        let (runtime_head, _) = store_for_activation
            .in_write_txn(move |transaction| {
                ensure_head_canonical_for_runtime_in_txn(transaction, &activation_id)?
                    .ok_or(SessionStoreError::NotFound(activation_id))
            })
            .await
            .expect("activate pending-cleaned head");
        let materialized = incremental
            .materialize_head(&runtime_head)
            .await
            .expect("materialize pending-cleaned head");
        let mut continued = materialized.session().as_ref().clone();
        continued
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 0, end: 1 },
                vec![user("first post-pending rewrite")],
                TranscriptRewriteReason::new("post-pending rewrite"),
                Some("migration-test".to_string()),
                None,
            )
            .expect("commit first post-pending rewrite");
        let rewrite = PreparedHeadCanonicalRewriteMutation::prepare_intra_turn(
            &continued,
            &runtime_head,
            runtime_head.clone(),
        )
        .expect("prepare first post-pending rewrite");
        incremental
            .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
            .await
            .expect("persist first post-pending rewrite");
        incremental
            .apply_prepared_head_canonical_rewrite_mutation(&rewrite)
            .await
            .expect("retry first post-pending rewrite idempotently");
        let records = incremental
            .load_rewrites(released_session.id())
            .await
            .expect("load post-pending audit");
        assert_eq!(records.len(), 3);
        assert_eq!(records[2].commit.rewrite_generation, 3);
        assert_eq!(
            records[2].commit.reason,
            TranscriptRewriteReason::new("post-pending rewrite")
        );
    }

    #[test]
    fn corrupt_released_pending_rewrite_rolls_back_entire_migration() {
        let directory = TempDir::new().expect("corrupt pending fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let released_session = imported_released_exact_splice_session();
        let released_head = insert_released_rewrite_head(&mut connection, &released_session);
        let mut pending = insert_released_pending_rewrite_tail(
            &mut connection,
            &released_head,
            &released_session,
        );
        pending.parent_revision = format!("sha256:{}", "0".repeat(64));
        let mut pending_json =
            serde_json::to_value(&pending).expect("serialize corrupt pending commit");
        pending_json
            .as_object_mut()
            .expect("corrupt pending commit object")
            .remove("rewrite_generation");
        connection
            .execute(
                "UPDATE session_rewrites
                 SET commit_json = ?1
                 WHERE session_id = ?2 AND rewrite_idx = ?3",
                params![
                    serde_json::to_vec(&pending_json)
                        .expect("serialize corrupt pending commit bytes"),
                    released_session.id().to_string(),
                    i64::try_from(released_head.rewrite_count)
                        .expect("corrupt pending rewrite index"),
                ],
            )
            .expect("corrupt pending rewrite row");
        let source_head: (Vec<u8>, String) = connection
            .query_row(
                "SELECT head_json, cas_token FROM session_heads WHERE session_id = ?1",
                params![released_session.id().to_string()],
                |row| Ok((row.get::<_, JsonColumnBytes>(0)?.into_bytes(), row.get(1)?)),
            )
            .expect("capture released head before failed migration");
        drop(connection);

        let error = SqliteSessionStore::open(&path)
            .err()
            .expect("corrupt released pending rewrite must fail migration");
        assert!(
            error.to_string().contains("unadopted successor"),
            "unexpected migration failure: {error}"
        );
        let connection = open_connection(&path).expect("reopen rolled-back pending fixture");
        assert_eq!(
            meerkat_sqlite::domain_version(&connection, SESSION_STORE_DOMAIN.name)
                .expect("read rolled-back schema version"),
            Some(2)
        );
        assert_eq!(
            connection
                .query_row(
                    "SELECT COUNT(*) FROM session_rewrites WHERE session_id = ?1",
                    params![released_session.id().to_string()],
                    |row| row.get::<_, i64>(0),
                )
                .expect("count rows after rollback"),
            3
        );
        let rolled_back_head: (Vec<u8>, String) = connection
            .query_row(
                "SELECT head_json, cas_token FROM session_heads WHERE session_id = ?1",
                params![released_session.id().to_string()],
                |row| Ok((row.get::<_, JsonColumnBytes>(0)?.into_bytes(), row.get(1)?)),
            )
            .expect("read released head after failed migration");
        assert_eq!(rolled_back_head, source_head);
    }

    #[derive(Debug, PartialEq, Eq)]
    struct ReleasedPhysicalSnapshot {
        schema_version: Option<i64>,
        head: (i64, Vec<u8>, String),
        strand_rows: Vec<(String, i64, Vec<u8>)>,
        rewrite_rows: Vec<(i64, String, i64, String, i64, Vec<u8>)>,
        links: Vec<(String, String, i64, i64, i64, i64)>,
    }

    fn released_physical_snapshot(
        connection: &Connection,
        id: &SessionId,
    ) -> ReleasedPhysicalSnapshot {
        let head = connection
            .query_row(
                "SELECT version, head_json, cas_token
                 FROM session_heads WHERE session_id = ?1",
                params![id.to_string()],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get::<_, JsonColumnBytes>(1)?.into_bytes(),
                        row.get(2)?,
                    ))
                },
            )
            .expect("snapshot released head");
        let strand_rows = connection
            .prepare(
                "SELECT strand, seq, message_json
                 FROM session_strand_messages
                 WHERE session_id = ?1
                 ORDER BY strand, seq",
            )
            .expect("prepare released strand snapshot")
            .query_map(params![id.to_string()], |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get::<_, JsonColumnBytes>(2)?.into_bytes(),
                ))
            })
            .expect("read released strand snapshot")
            .collect::<Result<Vec<_>, _>>()
            .expect("collect released strand snapshot");
        let rewrite_rows = connection
            .prepare(
                "SELECT rewrite_idx, parent_strand, parent_len, strand, strand_len, commit_json
                 FROM session_rewrites
                 WHERE session_id = ?1
                 ORDER BY rewrite_idx",
            )
            .expect("prepare released rewrite snapshot")
            .query_map(params![id.to_string()], |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                    row.get::<_, JsonColumnBytes>(5)?.into_bytes(),
                ))
            })
            .expect("read released rewrite snapshot")
            .collect::<Result<Vec<_>, _>>()
            .expect("collect released rewrite snapshot");
        let links = connection
            .prepare(
                "SELECT strand, successor, strand_len, splice_start, splice_end, successor_end
                 FROM session_strand_links
                 WHERE session_id = ?1
                 ORDER BY strand",
            )
            .expect("prepare released link snapshot")
            .query_map(params![id.to_string()], |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                    row.get(5)?,
                ))
            })
            .expect("read released link snapshot")
            .collect::<Result<Vec<_>, _>>()
            .expect("collect released link snapshot");
        ReleasedPhysicalSnapshot {
            schema_version: meerkat_sqlite::domain_version(connection, SESSION_STORE_DOMAIN.name)
                .expect("snapshot released schema version"),
            head,
            strand_rows,
            rewrite_rows,
            links,
        }
    }

    fn assert_released_digest_migration_rolls_back(
        connection: &mut Connection,
        id: &SessionId,
        expected_error: &str,
    ) {
        let source = released_physical_snapshot(connection, id);
        let error = meerkat_sqlite::apply_domain_migrations(connection, &SESSION_STORE_DOMAIN)
            .expect_err("tampered released digest evidence must fail migration");
        assert!(
            error.to_string().contains(expected_error),
            "unexpected migration error: {error}"
        );
        assert_eq!(
            released_physical_snapshot(connection, id),
            source,
            "digest refusal must roll back schema, head, rows, rewrites, and links"
        );
    }

    fn replace_released_row_bytes(
        connection: &Connection,
        id: &SessionId,
        strand: &str,
        seq: i64,
        needle: &[u8],
        replacement: &[u8],
    ) {
        let mut row = connection
            .query_row(
                "SELECT message_json
                 FROM session_strand_messages
                 WHERE session_id = ?1 AND strand = ?2 AND seq = ?3",
                params![id.to_string(), strand, seq],
                |row| Ok(row.get::<_, JsonColumnBytes>(0)?.into_bytes()),
            )
            .expect("read released row to tamper");
        assert_eq!(
            replace_all_bytes(&mut row, needle, replacement),
            1,
            "tamper fixture must replace exactly one byte span"
        );
        connection
            .execute(
                "UPDATE session_strand_messages
                 SET message_json = ?1
                 WHERE session_id = ?2 AND strand = ?3 AND seq = ?4",
                params![row, id.to_string(), strand, seq],
            )
            .expect("write tampered released row");
    }

    #[test]
    fn released_raw_semantic_live_row_tamper_rolls_back_every_physical_owner() {
        let directory = TempDir::new().expect("raw tamper fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let (id, _) = insert_released_raw_collapse_head(&mut connection, true);
        let head_strand: String = connection
            .query_row(
                "SELECT strand FROM session_heads WHERE session_id = ?1",
                params![id.to_string()],
                |row| row.get(0),
            )
            .expect("released live strand");
        replace_released_row_bytes(&connection, &id, &head_strand, 0, br#""z":1"#, br#""z":9"#);

        assert_released_digest_migration_rolls_back(
            &mut connection,
            &id,
            "live head digest mismatch",
        );
    }

    #[test]
    fn released_endpoint_label_body_mismatch_rolls_back_every_physical_owner() {
        let directory = TempDir::new().expect("endpoint tamper fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let released = imported_released_exact_splice_session();
        insert_released_rewrite_head(&mut connection, &released);
        let mut commit: serde_json::Value = connection
            .query_row(
                "SELECT commit_json
                 FROM session_rewrites
                 WHERE session_id = ?1 AND rewrite_idx = 0",
                params![released.id().to_string()],
                |row| {
                    let bytes = row.get::<_, JsonColumnBytes>(0)?.into_bytes();
                    Ok(serde_json::from_slice(&bytes).expect("decode released commit"))
                },
            )
            .expect("released first commit");
        commit["parent_revision"] = serde_json::json!(format!("sha256:{}", "0".repeat(64)));
        connection
            .execute(
                "UPDATE session_rewrites
                 SET commit_json = ?1
                 WHERE session_id = ?2 AND rewrite_idx = 0",
                params![
                    serde_json::to_vec(&commit).expect("serialize tampered endpoint label"),
                    released.id().to_string(),
                ],
            )
            .expect("tamper released endpoint label");

        assert_released_digest_migration_rolls_back(
            &mut connection,
            released.id(),
            "rewrite parent endpoint digest mismatch",
        );
    }

    #[test]
    fn released_non_raw_live_row_tamper_rolls_back_every_physical_owner() {
        let directory = TempDir::new().expect("ordinary tamper fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let (id, _) = insert_released_raw_collapse_head(&mut connection, true);
        let head_strand: String = connection
            .query_row(
                "SELECT strand FROM session_heads WHERE session_id = ?1",
                params![id.to_string()],
                |row| row.get(0),
            )
            .expect("released live strand");
        replace_released_row_bytes(
            &connection,
            &id,
            &head_strand,
            0,
            b"opaque-revised",
            b"opaque-tampered",
        );

        assert_released_digest_migration_rolls_back(
            &mut connection,
            &id,
            "live head digest mismatch",
        );
    }

    #[test]
    fn released_selected_span_label_tamper_rolls_back_every_physical_owner() {
        let directory = TempDir::new().expect("span tamper fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let mut connection = released_v2_file(&path);
        let released = imported_released_exact_splice_session();
        insert_released_rewrite_head(&mut connection, &released);
        let mut commit: serde_json::Value = connection
            .query_row(
                "SELECT commit_json
                 FROM session_rewrites
                 WHERE session_id = ?1 AND rewrite_idx = 0",
                params![released.id().to_string()],
                |row| {
                    let bytes = row.get::<_, JsonColumnBytes>(0)?.into_bytes();
                    Ok(serde_json::from_slice(&bytes).expect("decode released commit"))
                },
            )
            .expect("released first commit");
        commit["original_span_digest"] = serde_json::json!(format!("sha256:{}", "0".repeat(64)));
        connection
            .execute(
                "UPDATE session_rewrites
                 SET commit_json = ?1
                 WHERE session_id = ?2 AND rewrite_idx = 0",
                params![
                    serde_json::to_vec(&commit).expect("serialize tampered span label"),
                    released.id().to_string(),
                ],
            )
            .expect("tamper released span label");

        assert_released_digest_migration_rolls_back(
            &mut connection,
            released.id(),
            "rewrite original span digest mismatch",
        );
    }

    #[tokio::test]
    async fn released_blob_only_import_preserves_plain_save_and_head_conversion() {
        let directory = TempDir::new().expect("released blob fixture directory");
        let path = directory.path().join("sessions.sqlite3");
        let connection = released_v2_file(&path);
        let source = released_exact_splice_document();
        let released_session = insert_released_blob_row(&connection, &source);
        drop(connection);

        let store = SqliteSessionStore::open(&path).expect("migrate exact released blob-only row");
        let loaded = store
            .load(released_session.id())
            .await
            .expect("load migrated blob-only session")
            .expect("migrated blob-only session exists");
        assert_eq!(loaded.messages(), released_session.messages());
        assert_eq!(
            loaded
                .validated_transcript_history_state()
                .expect("migrated blob history validates")
                .expect("migrated blob retains history")
                .state()
                .commit_count(),
            2
        );
        let listed = store
            .list(SessionFilter::default())
            .await
            .expect("list migrated blob-only session");
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].id, *released_session.id());
        let metadata = store
            .load_meta(released_session.id())
            .await
            .expect("load migrated blob metadata")
            .expect("migrated blob metadata exists");
        assert_eq!(metadata.id, *released_session.id());

        let mut plain_saved = loaded.clone();
        plain_saved.push(user("plain-save tail"));
        store
            .save(&plain_saved)
            .await
            .expect("plain-save migrated blob");
        let incremental = incremental(&store);
        assert!(
            incremental
                .load_canonical_head(released_session.id())
                .await
                .expect("probe blob-only canonical head")
                .is_none(),
            "plain save must keep the imported WholeBlob representation"
        );
        let synthesized = incremental
            .load_head(released_session.id())
            .await
            .expect("synthesize imported blob head")
            .expect("synthesized imported blob head exists");
        assert_eq!(synthesized.rewrite_count, 2);
        let synthesized_token =
            session_head_cas_token(&synthesized).expect("synthesized imported blob CAS");
        assert_eq!(
            session_head_cas_token(
                &incremental
                    .load_head(released_session.id())
                    .await
                    .expect("repeat synthesized head")
                    .expect("repeat synthesized head exists")
            )
            .expect("repeat synthesized CAS"),
            synthesized_token
        );

        let store_for_activation =
            SqliteSessionStore::open(&path).expect("open activation store handle");
        let id = released_session.id().clone();
        let (converted, converted_token) = store_for_activation
            .in_write_txn(move |transaction| {
                ensure_head_canonical_for_runtime_in_txn(transaction, &id)?
                    .ok_or(SessionStoreError::NotFound(id))
            })
            .await
            .expect("convert imported blob to current HeadCanonical");
        assert_eq!(
            session_head_cas_token(&converted).expect("converted canonical CAS"),
            converted_token
        );
        let materialized = incremental
            .materialize_head(&converted)
            .await
            .expect("materialize converted imported blob");
        assert_eq!(materialized.session().messages(), plain_saved.messages());
        assert_eq!(
            incremental
                .load_rewrites(released_session.id())
                .await
                .expect("load converted imported blob audit")
                .len(),
            2
        );
    }

    #[tokio::test]
    async fn released_v0_8_10_rewrite_rows_backfill_exact_edges_without_relabeling_rows() {
        let (_dir, store) = temp_store();
        let session = imported_released_exact_splice_session();

        let history = session
            .validated_transcript_history_state()
            .unwrap()
            .expect("fixture carries validated compact history");
        let layout =
            strand_layout_for_history(&session, Some(&history)).expect("current compact layout");
        assert_eq!(layout.rewrites.len(), 2);
        assert!(matches!(
            &layout.rewrites[0].parent_transition,
            PreparedHeadCanonicalParentTransition::ExactAppend
        ));
        assert!(matches!(
            &layout.rewrites[1].parent_transition,
            PreparedHeadCanonicalParentTransition::ExactSplice(_)
        ));

        let mut released_source = TranscriptStrandId::root();
        let released_rows = layout
            .rewrites
            .iter()
            .map(|rewrite| {
                let parent_strand = match &rewrite.parent_transition {
                    PreparedHeadCanonicalParentTransition::ExactAppend => released_source.clone(),
                    PreparedHeadCanonicalParentTransition::ExactSplice(_) => {
                        TranscriptStrandId::rebase(&rewrite.commit.parent_revision)
                    }
                };
                let strand = TranscriptStrandId::from_rewrite(&rewrite.commit);
                released_source = strand.clone();
                let mut released_commit = rewrite.commit.clone();
                released_commit.rewrite_generation = 0;
                (
                    released_commit,
                    parent_strand,
                    u64::try_from(rewrite.commit.messages_before).unwrap(),
                    strand,
                    u64::try_from(rewrite.commit.messages_after).unwrap(),
                )
            })
            .collect::<Vec<_>>();
        let expected_count = u64::try_from(released_rows.len()).unwrap();
        let id = session.id().clone();
        store
            .in_write_txn(move |tx| {
                for (index, (commit, parent, parent_len, strand, strand_len)) in
                    released_rows.iter().enumerate()
                {
                    tx.execute(
                        "INSERT INTO session_rewrites
                             (session_id, rewrite_idx, parent_strand, parent_len, strand,
                              strand_len, commit_json, graph_edge_json, created_at_ms)
                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, ?8)",
                        params![
                            id.to_string(),
                            i64::try_from(index)
                                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                            parent.as_str(),
                            i64::try_from(*parent_len)
                                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                            strand.as_str(),
                            i64::try_from(*strand_len)
                                .map_err(|_| SessionStoreError::Corrupted(id.clone()))?,
                            serde_json::to_vec(commit).map_err(SessionStoreError::from)?,
                            now_millis(),
                        ],
                    )
                    .map_err(StoreError::from)
                    .map_err(into_session_store_error)?;
                }

                let expected_prefix = session
                    .transcript_rewrite_prefix_authority()
                    .ok_or_else(|| SessionStoreError::Corrupted(id.clone()))?;
                if expected_prefix.occurrence_count() != expected_count {
                    return Err(SessionStoreError::Corrupted(id));
                }
                backfill_rewrite_graph_edges_from_validated_session_in_txn(
                    tx,
                    &session,
                    &expected_prefix,
                )?;
                let stored = indexed_rewrite_rows_range_in_txn(tx, &id, 0, expected_count)?;
                assert_eq!(stored.len(), layout.rewrites.len());
                for ((_, row), (released, expected)) in stored
                    .iter()
                    .zip(released_rows.iter().zip(&layout.rewrites))
                {
                    assert_eq!(row.commit, expected.commit);
                    assert_eq!(row.parent_strand, released.1);
                    assert_eq!(row.strand, released.3);
                    assert_eq!(
                        row.graph_edge_json.as_deref(),
                        Some(expected.serialized_graph_edge.as_slice())
                    );
                    assert_ne!(
                        row.strand, expected.strand,
                        "released physical ids must not be confused with current occurrence ids"
                    );
                    if matches!(
                        &expected.parent_transition,
                        PreparedHeadCanonicalParentTransition::ExactSplice(_)
                    ) {
                        assert_ne!(
                            row.parent_strand, expected.parent_strand,
                            "released non-append parents use rebase ids, not current occurrence bridges"
                        );
                    }
                }
                Ok(())
            })
            .await
            .expect("released rows backfill without physical relabeling");
    }

    #[tokio::test]
    async fn legacy_head_canonical_rewrite_paths_fail_closed_without_replay_edges() {
        let (_dir, store) = temp_store();
        let inc = incremental(&store);
        let (parent, compacted, commit) = compacted_fixture();
        let head = seed_incremental(&inc, &parent).await;
        let token = session_head_cas_token(&head).unwrap();
        let record = record_for(&compacted, &commit);

        let error = inc
            .commit_rewrite(parent.id(), &record, SessionHeadCas::IfToken(token.clone()))
            .await
            .expect_err("record-only incremental rewrites cannot prove a replay edge");
        assert!(matches!(
            error,
            SessionStoreError::InvalidTranscriptRewrite { .. }
        ));
        let error = store
            .save_transcript_rewrite(&compacted, &commit)
            .await
            .expect_err("record-only compatibility save cannot prove a replay edge");
        assert!(matches!(
            error,
            SessionStoreError::InvalidTranscriptRewrite { .. }
        ));
        assert!(
            inc.load_rewrite_commits(parent.id())
                .await
                .unwrap()
                .is_empty()
        );

        // A released/preexisting record-only pending row cannot be smuggled
        // into current authority by calling save_head directly.
        let child = TranscriptStrandId::from_rewrite(&commit);
        let conn = open_connection(store.path()).unwrap();
        conn.execute(
            "INSERT INTO session_rewrites
                 (session_id, rewrite_idx, parent_strand, parent_len, strand,
                  strand_len, commit_json, graph_edge_json, created_at_ms)
             VALUES (?1, 0, ?2, ?3, ?4, ?5, ?6, NULL, ?7)",
            params![
                parent.id().to_string(),
                TranscriptStrandId::root().as_str(),
                i64::try_from(commit.messages_before).unwrap(),
                child.as_str(),
                i64::try_from(commit.messages_after).unwrap(),
                serde_json::to_vec(&commit).unwrap(),
                now_millis(),
            ],
        )
        .unwrap();
        drop(conn);
        let unproved_head = SessionHead::from_session(&compacted, child, 1).unwrap();
        let error = inc
            .save_head(&unproved_head, SessionHeadCas::IfToken(token))
            .await
            .expect_err("save_head must not adopt a rewrite without an exact replay edge");
        assert!(matches!(
            error,
            SessionStoreError::InvalidTranscriptRewrite { .. }
        ));
        assert!(
            inc.load_rewrite_commits(parent.id())
                .await
                .unwrap()
                .is_empty()
        );
        assert_eq!(total_strand_rows(store.path(), parent.id()), 4);
    }

    #[tokio::test]
    async fn whole_blob_snapshot_read_view_is_side_effect_free_without_runtime_receipt() {
        let (_dir, store) = temp_store();

        // Supported whole-blob snapshot with two audited rewrites and a live
        // append tail. Activation must preserve both authorities: the graph
        // stays at the latest audited occurrence while the physical head
        // names the complete live transcript.
        let mut session = Session::new();
        session.push(user("turn one"));
        session.push(user("turn two"));
        store.save(&session).await.unwrap();
        let _first_commit = session
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 0, end: 2 },
                vec![user("[compacted] summary one")],
                TranscriptRewriteReason::new("compaction"),
                Some("test".to_string()),
                None,
            )
            .unwrap();
        session.push(user("turn three"));
        let second_commit = session
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 0, end: 2 },
                vec![user("[compacted] summary two")],
                TranscriptRewriteReason::new("compaction"),
                Some("test".to_string()),
                None,
            )
            .unwrap();
        let audited_graph = session
            .validated_transcript_history_state()
            .unwrap()
            .expect("second rewrite installs audited graph");
        let audited_rewrite_prefix = audited_graph.rewrite_prefix().clone();
        let audited_graph_prefix = audited_graph.graph_prefix().clone();
        session.push(user("turn four"));
        for turn in 0..16 {
            session.push(user(&format!("ordinary turn {turn}")));
        }
        let state = session
            .validated_transcript_history_state()
            .unwrap()
            .expect("ordinary appends retain typed compact history");
        assert_eq!(
            state.rewrite_prefix(),
            &audited_rewrite_prefix,
            "ordinary whole-blob appends must leave rewrite-prefix authority untouched"
        );
        assert_eq!(
            state.graph_prefix(),
            &audited_graph_prefix,
            "ordinary whole-blob appends must leave compact graph authority untouched"
        );
        assert_eq!(state.head(), second_commit.revision);
        assert_eq!(
            state.commits().last(),
            Some(&second_commit),
            "audited graph must end at the exact latest rewrite occurrence"
        );
        assert_ne!(
            state.head(),
            session.transcript_content_digest().unwrap(),
            "live tail authority must remain separate from the audited graph head"
        );

        // Seed the supported WholeBlob side of the activation boundary.
        store.save_authoritative_projection(&session).await.unwrap();
        assert!(blob_row_bytes(store.path(), session.id()).is_some());

        let inc = incremental(&store);
        // Blob-only exceptional reads may explicitly materialize occurrence
        // bodies, but they must not force migration or revive a k-fold strand
        // vector in the layout carrier.
        let blob_records = inc.load_rewrites(session.id()).await.unwrap();
        assert_eq!(blob_records.len(), 2);
        let first_parent = &blob_records[0].parent_body.messages;
        let blob_root = inc
            .load_messages(
                session.id(),
                &TranscriptStrandId::root(),
                0..u64::try_from(first_parent.len()).unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(&blob_root, first_parent);

        // load_head synthesizes deterministically without writing.
        let synthesized = inc.load_head(session.id()).await.unwrap().unwrap();
        assert_eq!(synthesized.rewrite_count, 2);
        assert_eq!(synthesized.message_count, session.messages().len() as u64);
        let synthesized_token = session_head_cas_token(&synthesized).unwrap();
        let synthesized_again = inc.load_head(session.id()).await.unwrap().unwrap();
        assert_eq!(
            synthesized_again, synthesized,
            "the same stored WholeBlob must synthesize the same typed read view"
        );
        assert_eq!(
            session_head_cas_token(&synthesized_again).unwrap(),
            synthesized_token,
            "the synthesized view must deterministically bind its own CAS authority"
        );
        {
            let conn = open_connection(store.path()).unwrap();
            let heads: i64 = conn
                .query_row("SELECT COUNT(*) FROM session_heads", [], |row| row.get(0))
                .unwrap();
            assert_eq!(heads, 0, "load_head must not write");
        }
    }

    #[tokio::test]
    async fn head_canonical_save_paths() {
        let (_dir, store) = temp_store();
        let inc = incremental(&store);
        let mut session = Session::new();
        session.push(user("one"));
        session.push(user("two"));
        seed_incremental(&inc, &session).await;
        let root = TranscriptStrandId::root();

        // Plain save append writes ONLY delta rows.
        let mut appended = store.load(session.id()).await.unwrap().unwrap();
        appended.push(user("three"));
        store.save(&appended).await.unwrap();
        assert_eq!(strand_row_count(store.path(), session.id(), &root), 3);

        // Plain save shrink is rejected.
        let mut shrunk = Session::with_id(session.id().clone());
        shrunk.push(user("one"));
        let err = store
            .save(&shrunk)
            .await
            .expect_err("head-canonical shrink must be rejected");
        assert!(matches!(
            err,
            SessionStoreError::MonotonicityViolation { .. }
        ));

        // Record-only rewrite saves are deliberately unsupported after
        // activation: only the prepared carrier proves exact replay edges.
        let mut compacted = store.load(session.id()).await.unwrap().unwrap();
        let parent_revision = compacted.transcript_revision().unwrap();
        let commit = compacted
            .commit_transcript_rewrite(
                TranscriptRewriteSelection::MessageRange { start: 0, end: 3 },
                vec![user("[compacted] summary")],
                TranscriptRewriteReason::new("compaction"),
                Some("test".to_string()),
                Some(parent_revision),
            )
            .unwrap();
        let error = store
            .save_transcript_rewrite(&compacted, &commit)
            .await
            .expect_err("HeadCanonical compatibility rewrite must fail closed");
        assert!(matches!(
            error,
            SessionStoreError::InvalidTranscriptRewrite { .. }
        ));
        let head = inc.load_head(session.id()).await.unwrap().unwrap();
        assert_eq!(head.rewrite_count, 0);
        assert_eq!(head.message_count, 3);
        let slim = store.load(session.id()).await.unwrap().unwrap();
        assert_eq!(slim.messages().len(), 3);

        // save_authoritative_projection_if_current_revision with the
        // materialized token succeeds; a stale token is rejected.
        let current = store.load(session.id()).await.unwrap().unwrap();
        let token = meerkat_core::session_store::session_projection_cas_token(&current).unwrap();
        let mut next = current.clone();
        next.push(user("post-compaction turn"));
        store
            .save_authoritative_projection_if_current_revision(&next, Some(token.clone()))
            .await
            .expect("materialized token must match");
        let err = store
            .save_authoritative_projection_if_current_revision(&next, Some(token))
            .await
            .expect_err("stale token must be rejected");
        assert!(matches!(
            err,
            SessionStoreError::TranscriptContinuityViolation { .. }
        ));
    }

    /// A rebase strand switch (authoritative projection that does not extend
    /// the head strand) must supersede the strand it left instead of leaving
    /// a second full copy behind.
    #[tokio::test]
    async fn rebase_strand_switch_does_not_leave_a_second_transcript_copy() {
        let (_dir, store) = temp_store();
        let inc = incremental(&store);
        let mut seeded = Session::new();
        for turn in 0..5 {
            seeded.push(user(&format!("turn {turn}")));
        }
        seed_incremental(&inc, &seeded).await;
        assert_eq!(total_strand_rows(store.path(), seeded.id()), 5);

        // A projection that replaces message 0 does not extend the head
        // strand, so the write rebases onto a fresh strand.
        let mut projection = Session::with_id(seeded.id().clone());
        projection.push(user("refreshed turn 0"));
        for turn in 1..5 {
            projection.push(user(&format!("turn {turn}")));
        }
        store
            .save_authoritative_projection(&projection)
            .await
            .unwrap();

        let head = inc.load_head(seeded.id()).await.unwrap().unwrap();
        assert_ne!(head.strand, TranscriptStrandId::root());
        assert_eq!(
            total_strand_rows(store.path(), seeded.id()),
            5,
            "a rebase must not leave the abandoned strand's rows behind"
        );
        assert_eq!(
            strand_link_count(store.path(), seeded.id()),
            0,
            "an abandoned strand no rewrite names must be collected outright"
        );
        let slim = store.load(seeded.id()).await.unwrap().unwrap();
        assert_eq!(slim.messages(), projection.messages());
    }
}