agentstategraph-storage 1.3.2

Pluggable storage backends for AgentStateGraph
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
//! SQLite storage backend — durable, single-file, zero-config.
//!
//! This is the default production backend. All state, commits, and refs
//! are stored in a single SQLite file that survives process restarts.

use std::path::Path;
use std::sync::Mutex;
use std::time::Instant;

use agentstategraph_core::{
    Commit, Epoch, EpochScope, EpochStatus, IntentCategory, Namespace, Node, Object, ObjectId,
    Session, SessionStatus, TAG_GIT_REVISION, TAG_PIN_STATE,
};
use agentstategraph_reminders::{
    Reminder, ReminderError, ReminderFilter, ReminderStore,
    types::{Priority, ReminderStatus},
};
use agentstategraph_taint::{Taint, TaintEffect, TaintKind, TaintMetadata, TaintSeverity};
use chrono::{DateTime, Utc};
use rusqlite::{Connection, OptionalExtension, Row, params};

use crate::traits::{
    CommitStore, CommitTrace, DEFAULT_GC_GRACE, EpochStore, GC_FRESHEN_AFTER, GcReachability,
    GcSweep, HISTORY_NAMESPACE_UNKNOWN, HistoryMilestoneRow, HistoryRollupRow, ObjectStore,
    RefStore, SessionStore, StorageError, StoreShape, StoreTotals, TableBytes, TaintStore,
    VacuumStats,
};

/// SQLite-backed storage. Thread-safe via Mutex around the connection.
///
/// Creates the database file and tables automatically on first use.
pub struct SqliteStorage {
    conn: Mutex<Connection>,
    /// The database file, so a GC sweep can take its write lock on a
    /// connection of its own. `None` for an in-memory store.
    path: Option<std::path::PathBuf>,
    /// The connection holding a GC sweep's write lock, while one is held.
    /// Separate from `conn` so other threads' writes wait for the lock (and
    /// fail loudly on timeout) instead of running inside the sweep's
    /// transaction, where a rollback would discard them after they returned Ok.
    gc_conn: Mutex<Option<Connection>>,
    /// How recently written an unreachable object must be for a GC sweep to
    /// spare it. See [`SqliteStorage::with_gc_grace`].
    gc_grace: std::time::Duration,
}

impl SqliteStorage {
    /// Open or create a SQLite database at the given path.
    ///
    /// Tunes durability for a write-heavy, single-writer graph store. The stock
    /// SQLite defaults (`journal_mode=DELETE`, `synchronous=FULL`) fsync a
    /// rollback journal on *every* commit; a bulk import that does thousands of
    /// commits then lives entirely in the writer. `WAL` + `synchronous=NORMAL`
    /// appends commits to one log and fsyncs only at checkpoints, which on a
    /// full session import measured several times faster. The durability
    /// trade-off is bounded and appropriate: under `NORMAL`+WAL a crash or power
    /// loss can drop only the last few not-yet-checkpointed commits (never
    /// corruption), and this store is rebuildable from its source transcripts.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, StorageError> {
        let path = path.as_ref().to_path_buf();
        let conn = Connection::open(&path)
            .map_err(|e| StorageError::Backend(format!("sqlite open: {}", e)))?;
        // Every statement becomes a database span and a
        // `db.client.operation.duration` measurement.
        oxtel_sql::rusqlite::instrument(&conn);
        // Best-effort: a pragma failure leaves the slower-but-correct default.
        // `journal_mode` returns the new mode as a row, so it needs a query
        // rather than `pragma_update` (which rejects result rows).
        // Enable incremental auto-vacuum BEFORE any table exists so a fresh DB
        // returns freed pages to the freelist as data is deleted, and
        // `PRAGMA incremental_vacuum` can hand them back to the OS without a full
        // rewrite (Plan B t-004). On a pre-existing DB this is a no-op until the
        // next full `VACUUM` converts it. `auto_vacuum` returns a row, so query.
        let _ = conn.query_row("PRAGMA auto_vacuum=INCREMENTAL", [], |r| r.get::<_, i64>(0));
        let _ = conn.query_row("PRAGMA journal_mode=WAL", [], |r| r.get::<_, String>(0));
        let _ = conn.pragma_update(None, "synchronous", "NORMAL");
        let _ = conn.busy_timeout(std::time::Duration::from_secs(5));
        let storage = Self {
            conn: Mutex::new(conn),
            path: Some(path),
            gc_conn: Mutex::new(None),
            gc_grace: DEFAULT_GC_GRACE,
        };
        storage.init_tables()?;
        describe_connection_metrics();
        Ok(storage)
    }

    /// Create an in-memory SQLite database (useful for testing).
    pub fn in_memory() -> Result<Self, StorageError> {
        let conn = Connection::open_in_memory()
            .map_err(|e| StorageError::Backend(format!("sqlite open: {}", e)))?;
        oxtel_sql::rusqlite::instrument(&conn);
        let storage = Self {
            conn: Mutex::new(conn),
            path: None,
            gc_conn: Mutex::new(None),
            gc_grace: DEFAULT_GC_GRACE,
        };
        storage.init_tables()?;
        describe_connection_metrics();
        Ok(storage)
    }

    /// Set how recently written an unreachable object must be for a GC sweep
    /// to spare it (default [`DEFAULT_GC_GRACE`]).
    ///
    /// Every write stores its new objects before it commits them. A sweep
    /// locks writers out while it runs, but a write that stored its objects
    /// before the sweep started would find them gone when it commits; the
    /// grace period spares them. Storing an object again refreshes its write
    /// time once it is over [`GC_FRESHEN_AFTER`] old, so a write that dedups
    /// onto an old unreachable object is covered too. A grace under that
    /// narrows the protection; tests use zero to see garbage go at once. The
    /// reachability report and dry run ignore the grace: they count every
    /// unreachable object.
    pub fn with_gc_grace(mut self, grace: std::time::Duration) -> Self {
        self.gc_grace = grace;
        self
    }

    fn init_tables(&self) -> Result<(), StorageError> {
        let conn = self
            .conn
            .lock()
            .map_err(|e| StorageError::Backend(e.to_string()))?;

        conn.execute_batch(
            "
            -- `written_at` (Unix milliseconds) is when the object was last
            -- stored; a GC sweep spares recent ones. See with_gc_grace.
            CREATE TABLE IF NOT EXISTS objects (
                id         BLOB PRIMARY KEY,
                data       BLOB NOT NULL,
                written_at INTEGER NOT NULL DEFAULT 0
            );

            CREATE TABLE IF NOT EXISTS commits (
                id        BLOB PRIMARY KEY,
                data      BLOB NOT NULL,
                timestamp TEXT NOT NULL
            );

            -- The trace each commit was made in (Plan H t-009): beside the
            -- commit, not in it, so commit ids don't depend on telemetry.
            CREATE TABLE IF NOT EXISTS commit_traces (
                commit_id BLOB PRIMARY KEY,
                trace_id  TEXT NOT NULL,
                span_id   TEXT NOT NULL
            );

            CREATE TABLE IF NOT EXISTS namespaces (
                name       TEXT PRIMARY KEY,
                created_at TEXT NOT NULL
            );

            CREATE TABLE IF NOT EXISTS refs (
                namespace TEXT NOT NULL,
                name      TEXT NOT NULL,
                target    BLOB NOT NULL,
                PRIMARY KEY (namespace, name)
            );

            CREATE TABLE IF NOT EXISTS epochs (
                id              TEXT PRIMARY KEY,
                description     TEXT NOT NULL DEFAULT '',
                status          TEXT NOT NULL DEFAULT 'Active',
                created_at      TEXT NOT NULL,
                sealed_at       TEXT,
                summary         TEXT,
                root_intents    TEXT NOT NULL DEFAULT '[]',
                agents          TEXT NOT NULL DEFAULT '[]',
                tags            TEXT NOT NULL DEFAULT '[]',
                commit_count    INTEGER NOT NULL DEFAULT 0,
                sealed_commits  TEXT NOT NULL DEFAULT '[]',
                seal_hash       BLOB,
                namespace       TEXT,
                scope           TEXT NOT NULL DEFAULT 'all'
            );

            CREATE TABLE IF NOT EXISTS sessions (
                id              TEXT PRIMARY KEY,
                agent_id        TEXT NOT NULL,
                parent_id       TEXT REFERENCES sessions(id),
                scope_path      TEXT,
                scope_branch    TEXT,
                scope_namespace TEXT,
                status          TEXT NOT NULL DEFAULT 'Active',
                created_at      TEXT NOT NULL,
                ended_at        TEXT,
                metadata        TEXT NOT NULL DEFAULT '{}',
                commit_count    INTEGER NOT NULL DEFAULT 0
            );

            CREATE TABLE IF NOT EXISTS taints (
                id              TEXT PRIMARY KEY,
                path            TEXT NOT NULL,
                name            TEXT NOT NULL,
                kind            TEXT NOT NULL,
                effect          TEXT NOT NULL,
                severity        TEXT NOT NULL DEFAULT 'medium',
                reason          TEXT NOT NULL,
                agent_id        TEXT NOT NULL,
                commit_id       TEXT NOT NULL DEFAULT '',
                created_at      TEXT NOT NULL,
                expires_at      TEXT,
                resolved_at     TEXT,
                resolved_by     TEXT,
                resolved_reason TEXT,
                resolved_proof  TEXT,
                propagate       INTEGER NOT NULL DEFAULT 1,
                metadata        TEXT NOT NULL DEFAULT '{}'
            );

            CREATE TABLE IF NOT EXISTS reminders (
                id              TEXT PRIMARY KEY,
                title           TEXT NOT NULL,
                instructions    TEXT NOT NULL,
                commands        TEXT NOT NULL DEFAULT '[]',
                refs            TEXT NOT NULL DEFAULT '[]',
                priority        INTEGER NOT NULL DEFAULT 3,
                due_at          TEXT NOT NULL,
                schedule        TEXT,
                autonomous      INTEGER NOT NULL DEFAULT 1,
                created_by      TEXT NOT NULL,
                created_at      TEXT NOT NULL,
                status          TEXT NOT NULL DEFAULT 'pending',
                snoozed_until   TEXT,
                executions      TEXT NOT NULL DEFAULT '[]',
                tags            TEXT NOT NULL DEFAULT '[]'
            );

            CREATE INDEX IF NOT EXISTS idx_commits_timestamp ON commits(timestamp DESC);

            -- Leaf-value index (plan perf-slow-endpoints t-006). Turns value
            -- search from a full tree walk into a trigram substring probe.
            -- Keyed by (namespace, ref) and maintained IN PLACE as a ref
            -- advances: a one-time backfill on first use, then incremental
            -- add/remove of only the leaves a commit changed.
            --
            -- `leaf_rows` is the base table (real indexes for the ns/ref filter
            -- and for incremental delete-by-path); `leaf_fts` is a trigram FTS5
            -- external-content index over `value`, kept in sync by triggers;
            -- `leaf_index_refs` records which (namespace, ref) sets are built.
            CREATE TABLE IF NOT EXISTS leaf_rows (
                id        INTEGER PRIMARY KEY,
                namespace TEXT NOT NULL,
                ref       TEXT NOT NULL,
                path      TEXT NOT NULL,
                value     TEXT NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_leaf_rows_nsref
                ON leaf_rows(namespace, ref);
            CREATE INDEX IF NOT EXISTS idx_leaf_rows_nsrefpath
                ON leaf_rows(namespace, ref, path);
            CREATE VIRTUAL TABLE IF NOT EXISTS leaf_fts USING fts5(
                value, content='leaf_rows', content_rowid='id', tokenize='trigram'
            );
            CREATE TRIGGER IF NOT EXISTS leaf_rows_ai AFTER INSERT ON leaf_rows BEGIN
                INSERT INTO leaf_fts(rowid, value) VALUES (new.id, new.value);
            END;
            CREATE TRIGGER IF NOT EXISTS leaf_rows_ad AFTER DELETE ON leaf_rows BEGIN
                INSERT INTO leaf_fts(leaf_fts, rowid, value) VALUES ('delete', old.id, old.value);
            END;
            -- `root` is the state root the set reflects (NULL when unknown),
            -- so a diff applies only to the tree it was computed from.
            CREATE TABLE IF NOT EXISTS leaf_index_refs (
                namespace TEXT NOT NULL,
                ref       TEXT NOT NULL,
                root      BLOB,
                PRIMARY KEY (namespace, ref)
            );
            -- Roots of uncommitted work (open speculations) that a GC sweep
            -- must keep, from any process sharing this file. See gc_pin_root.
            CREATE TABLE IF NOT EXISTS gc_pending_roots (
                key        TEXT PRIMARY KEY,
                root       BLOB NOT NULL,
                updated_at INTEGER NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_epochs_status ON epochs(status);
            CREATE INDEX IF NOT EXISTS idx_sessions_agent ON sessions(agent_id);
            CREATE INDEX IF NOT EXISTS idx_taints_path    ON taints(path);
            CREATE INDEX IF NOT EXISTS idx_taints_kind    ON taints(kind);
            CREATE UNIQUE INDEX IF NOT EXISTS idx_taints_unique_active
                ON taints(path, name, kind) WHERE resolved_at IS NULL;
            CREATE INDEX IF NOT EXISTS idx_reminders_status     ON reminders(status);
            CREATE INDEX IF NOT EXISTS idx_reminders_due_at     ON reminders(due_at);
            CREATE INDEX IF NOT EXISTS idx_reminders_priority   ON reminders(priority);
            CREATE INDEX IF NOT EXISTS idx_reminders_created_by ON reminders(created_by);

            -- Plan A t-001: distilled project-history metrics. Populated
            -- incrementally by `history_extract_batch` from the commit chain,
            -- keyed off the monotonic `commits.rowid` cursor stored in
            -- asg_history_meta. Derived, rebuildable — never authoritative.
            CREATE TABLE IF NOT EXISTS asg_history_meta (
                key   TEXT PRIMARY KEY,
                value TEXT NOT NULL
            );
            -- Commit-history rollup: one row per (day, namespace, agent,
            -- intent category). Collapses velocity + authorship + intent-mix
            -- into an indexed table instead of a 512k-row commit scan.
            CREATE TABLE IF NOT EXISTS asg_history_commit_rollup (
                day             TEXT NOT NULL,
                namespace       TEXT NOT NULL,
                agent_id        TEXT NOT NULL,
                intent_category TEXT NOT NULL,
                commit_count    INTEGER NOT NULL DEFAULT 0,
                first_ts        TEXT NOT NULL,
                last_ts         TEXT NOT NULL,
                PRIMARY KEY (day, namespace, agent_id, intent_category)
            );
            CREATE INDEX IF NOT EXISTS idx_asg_history_rollup_day
                ON asg_history_commit_rollup(day);
            -- Milestone timeline: the human-meaningful spine — every
            -- `Checkpoint` commit (epoch/session boundaries land here in a
            -- later task). One row per (commit, kind); insert-or-ignore keeps
            -- re-extraction idempotent. `state_root` (Plan A t-005) is the
            -- retention hook: it names the snapshot a milestone preserves, so
            -- Plan B's GC can keep milestone state reachable while pruning
            -- everything else. It is written only when the intent opts in with
            -- `TAG_PIN_STATE`, because pinning every checkpoint retains one full
            -- state tree per routine re-index and leaves nothing reclaimable.
            -- `git_sha` (from `TAG_GIT_REVISION`) records the revision behind an
            -- unpinned milestone so derived state can be rebuilt from source.
            CREATE TABLE IF NOT EXISTS asg_history_milestone (
                commit_id   BLOB NOT NULL,
                kind        TEXT NOT NULL,
                timestamp   TEXT NOT NULL,
                day         TEXT NOT NULL,
                namespace   TEXT NOT NULL,
                agent_id    TEXT NOT NULL,
                description TEXT NOT NULL,
                state_root  BLOB,
                git_sha     TEXT,
                PRIMARY KEY (commit_id, kind)
            );
            CREATE INDEX IF NOT EXISTS idx_asg_history_milestone_ts
                ON asg_history_milestone(timestamp);
            ",
        )
        .map_err(|e| StorageError::Backend(format!("init tables: {}", e)))?;

        // Plan A t-005: migration-safe add of asg_history_milestone.state_root
        // for DBs that created the milestone table under t-001 (before the
        // column existed). New rows are populated by the extractor; old rows
        // keep NULL until the milestone table is rebuilt.
        let milestone_cols: Vec<String> = {
            let mut stmt = conn
                .prepare("PRAGMA table_info(asg_history_milestone)")
                .map_err(|e| StorageError::Backend(format!("pragma milestone: {}", e)))?;
            let rows = stmt
                .query_map([], |row| row.get::<_, String>(1))
                .map_err(|e| StorageError::Backend(format!("pragma query: {}", e)))?;
            let mut cols = Vec::new();
            for r in rows {
                cols.push(r.map_err(|e| StorageError::Backend(format!("pragma row: {}", e)))?);
            }
            cols
        };
        if !milestone_cols.iter().any(|c| c == "state_root") {
            conn.execute(
                "ALTER TABLE asg_history_milestone ADD COLUMN state_root BLOB",
                [],
            )
            .map_err(|e| StorageError::Backend(format!("add milestone state_root: {}", e)))?;
        }
        // Migration-safe add of asg_history_milestone.git_sha for DBs whose
        // milestone table predates it. Old rows keep NULL — their commits were
        // distilled before the revision was recorded, and re-extraction will not
        // revisit them because the cursor has already passed.
        if !milestone_cols.iter().any(|c| c == "git_sha") {
            conn.execute(
                "ALTER TABLE asg_history_milestone ADD COLUMN git_sha TEXT",
                [],
            )
            .map_err(|e| StorageError::Backend(format!("add milestone git_sha: {}", e)))?;
        }

        // Migration-safe add of objects.written_at. Existing objects read 0,
        // written long ago, so a sweep treats them exactly as before.
        let object_cols: Vec<String> = {
            let mut stmt = conn
                .prepare("PRAGMA table_info(objects)")
                .map_err(|e| StorageError::Backend(format!("pragma objects: {}", e)))?;
            let rows = stmt
                .query_map([], |row| row.get::<_, String>(1))
                .map_err(|e| StorageError::Backend(format!("pragma query: {}", e)))?;
            let mut cols = Vec::new();
            for r in rows {
                cols.push(r.map_err(|e| StorageError::Backend(format!("pragma row: {}", e)))?);
            }
            cols
        };
        if !object_cols.iter().any(|c| c == "written_at") {
            conn.execute(
                "ALTER TABLE objects ADD COLUMN written_at INTEGER NOT NULL DEFAULT 0",
                [],
            )
            .map_err(|e| StorageError::Backend(format!("add objects written_at: {}", e)))?;
        }

        // Migration-safe add of leaf_index_refs.root. Sets built before it
        // read NULL, so the repository rebuilds each one on its next search.
        let leaf_ref_cols: Vec<String> = {
            let mut stmt = conn
                .prepare("PRAGMA table_info(leaf_index_refs)")
                .map_err(|e| StorageError::Backend(format!("pragma leaf_index_refs: {}", e)))?;
            let rows = stmt
                .query_map([], |row| row.get::<_, String>(1))
                .map_err(|e| StorageError::Backend(format!("pragma query: {}", e)))?;
            let mut cols = Vec::new();
            for r in rows {
                cols.push(r.map_err(|e| StorageError::Backend(format!("pragma row: {}", e)))?);
            }
            cols
        };
        if !leaf_ref_cols.iter().any(|c| c == "root") {
            conn.execute("ALTER TABLE leaf_index_refs ADD COLUMN root BLOB", [])
                .map_err(|e| StorageError::Backend(format!("add leaf_index_refs root: {}", e)))?;
        }

        // Migration-safe add of commits.epoch_id / commits.session_id.
        // SQLite's ALTER TABLE ADD COLUMN doesn't support IF NOT EXISTS
        // so we inspect the table first.
        let existing_cols: Vec<String> = {
            let mut stmt = conn
                .prepare("PRAGMA table_info(commits)")
                .map_err(|e| StorageError::Backend(format!("pragma commits: {}", e)))?;
            let rows = stmt
                .query_map([], |row| row.get::<_, String>(1))
                .map_err(|e| StorageError::Backend(format!("pragma query: {}", e)))?;
            let mut cols = Vec::new();
            for r in rows {
                cols.push(r.map_err(|e| StorageError::Backend(format!("pragma row: {}", e)))?);
            }
            cols
        };
        if !existing_cols.iter().any(|c| c == "epoch_id") {
            conn.execute("ALTER TABLE commits ADD COLUMN epoch_id TEXT", [])
                .map_err(|e| StorageError::Backend(format!("add epoch_id col: {}", e)))?;
        }
        if !existing_cols.iter().any(|c| c == "session_id") {
            conn.execute("ALTER TABLE commits ADD COLUMN session_id TEXT", [])
                .map_err(|e| StorageError::Backend(format!("add session_id col: {}", e)))?;
        }
        // Migration-safe add of epochs.sealed_commits for DBs created
        // before 0.6.5-beta.1 shipped (V8 seal-violation enforcement
        // needs this persisted across restarts).
        let epoch_cols: Vec<String> = {
            let mut stmt = conn
                .prepare("PRAGMA table_info(epochs)")
                .map_err(|e| StorageError::Backend(format!("pragma epochs: {}", e)))?;
            let rows = stmt
                .query_map([], |row| row.get::<_, String>(1))
                .map_err(|e| StorageError::Backend(format!("pragma query: {}", e)))?;
            let mut cols = Vec::new();
            for r in rows {
                cols.push(r.map_err(|e| StorageError::Backend(format!("pragma row: {}", e)))?);
            }
            cols
        };
        if !epoch_cols.iter().any(|c| c == "sealed_commits") {
            conn.execute(
                "ALTER TABLE epochs ADD COLUMN sealed_commits TEXT NOT NULL DEFAULT '[]'",
                [],
            )
            .map_err(|e| StorageError::Backend(format!("add sealed_commits: {}", e)))?;
        }
        // Epoch fidelity + scoping. Three columns added together so an upgrade
        // is one pass over the table rather than three:
        //   seal_hash — the tamper-evident digest was modelled on `Epoch` but
        //               had nowhere to live, so it was dropped on every write.
        //   namespace — the table is global, which is why one workspace's
        //               sealed epoch could enforce against every other one.
        //   scope     — what the seal covers; see `EpochScope`.
        // All are nullable or defaulted, so existing rows stay valid and read
        // back as the historical behaviour (global, scope = all).
        for (col, ddl) in [
            ("seal_hash", "ALTER TABLE epochs ADD COLUMN seal_hash BLOB"),
            ("namespace", "ALTER TABLE epochs ADD COLUMN namespace TEXT"),
            (
                "scope",
                "ALTER TABLE epochs ADD COLUMN scope TEXT NOT NULL DEFAULT 'all'",
            ),
        ] {
            if !epoch_cols.iter().any(|c| c == col) {
                conn.execute(ddl, [])
                    .map_err(|e| StorageError::Backend(format!("add epochs.{}: {}", col, e)))?;
            }
        }
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_epochs_namespace ON epochs(namespace)",
            [],
        )
        .map_err(|e| StorageError::Backend(format!("idx_epochs_namespace: {}", e)))?;
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_commits_epoch ON commits(epoch_id)",
            [],
        )
        .map_err(|e| StorageError::Backend(format!("idx epoch: {}", e)))?;
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_commits_session ON commits(session_id)",
            [],
        )
        .map_err(|e| StorageError::Backend(format!("idx session: {}", e)))?;

        // Migration: refs table — add namespace column + composite PK.
        // Check whether refs still has the old flat schema (single-column PK).
        let refs_cols: Vec<String> = {
            let mut stmt = conn
                .prepare("PRAGMA table_info(refs)")
                .map_err(|e| StorageError::Backend(format!("pragma refs: {}", e)))?;
            let rows = stmt
                .query_map([], |row| row.get::<_, String>(1))
                .map_err(|e| StorageError::Backend(format!("pragma query: {}", e)))?;
            let mut cols = Vec::new();
            for r in rows {
                cols.push(r.map_err(|e| StorageError::Backend(format!("pragma row: {}", e)))?);
            }
            cols
        };
        if !refs_cols.iter().any(|c| c == "namespace") {
            // Old schema detected. Recreate with composite PK.
            conn.execute_batch(
                "
                CREATE TABLE refs_new (
                    namespace TEXT NOT NULL,
                    name      TEXT NOT NULL,
                    target    BLOB NOT NULL,
                    PRIMARY KEY (namespace, name)
                );
                INSERT INTO refs_new (namespace, name, target)
                    SELECT 'default', name, target FROM refs;
                DROP TABLE refs;
                ALTER TABLE refs_new RENAME TO refs;
                ",
            )
            .map_err(|e| StorageError::Backend(format!("migrate refs: {}", e)))?;
        }

        // Migration: ensure namespaces table exists and 'default' is seeded.
        conn.execute(
            "INSERT OR IGNORE INTO namespaces (name, created_at) VALUES ('default', ?1)",
            params![chrono::Utc::now().to_rfc3339()],
        )
        .map_err(|e| StorageError::Backend(format!("seed default namespace: {}", e)))?;

        // Migration: sessions — add scope_namespace column if missing.
        let session_cols: Vec<String> = {
            let mut stmt = conn
                .prepare("PRAGMA table_info(sessions)")
                .map_err(|e| StorageError::Backend(format!("pragma sessions: {}", e)))?;
            let rows = stmt
                .query_map([], |row| row.get::<_, String>(1))
                .map_err(|e| StorageError::Backend(format!("pragma query: {}", e)))?;
            let mut cols = Vec::new();
            for r in rows {
                cols.push(r.map_err(|e| StorageError::Backend(format!("pragma row: {}", e)))?);
            }
            cols
        };
        if !session_cols.iter().any(|c| c == "scope_namespace") {
            conn.execute("ALTER TABLE sessions ADD COLUMN scope_namespace TEXT", [])
                .map_err(|e| StorageError::Backend(format!("add scope_namespace: {}", e)))?;
        }

        Ok(())
    }

    /// The store's connection. Waiting for it, and holding it, are recorded
    /// as the conventions' connection pool metrics, as for a pool of one
    /// named `sqlite`.
    fn lock_conn(&self) -> Result<ConnGuard<'_>, StorageError> {
        let waiting = metrics::gauge!(
            "db.client.connection.pending_requests",
            POOL_NAME => SQLITE_POOL
        );
        waiting.increment(1.0);
        let started = Instant::now();
        let conn = self.conn.lock();
        waiting.decrement(1.0);
        metrics::histogram!(
            "db.client.connection.wait_time",
            POOL_NAME => SQLITE_POOL
        )
        .record(started.elapsed().as_secs_f64());
        Ok(ConnGuard {
            conn: conn.map_err(|e| StorageError::Backend(e.to_string()))?,
            since: Instant::now(),
        })
    }
}

const POOL_NAME: &str = "db.client.connection.pool.name";
const SQLITE_POOL: &str = "sqlite";

/// Describe the connection metrics to the current recorder, so they carry
/// their units: without one, Prometheus names them without `_seconds`.
fn describe_connection_metrics() {
    metrics::describe_gauge!(
        "db.client.connection.pending_requests",
        "The number of current pending requests for an open connection."
    );
    metrics::describe_histogram!(
        "db.client.connection.wait_time",
        metrics::Unit::Seconds,
        "The time it took to obtain an open connection from the pool."
    );
    metrics::describe_histogram!(
        "db.client.connection.use_time",
        metrics::Unit::Seconds,
        "The time between borrowing a connection and returning it to the pool."
    );
}

/// The store's connection while it's held; records how long when dropped.
struct ConnGuard<'a> {
    conn: std::sync::MutexGuard<'a, Connection>,
    since: Instant,
}

impl std::ops::Deref for ConnGuard<'_> {
    type Target = Connection;

    fn deref(&self) -> &Connection {
        &self.conn
    }
}

impl std::ops::DerefMut for ConnGuard<'_> {
    fn deref_mut(&mut self) -> &mut Connection {
        &mut self.conn
    }
}

impl Drop for ConnGuard<'_> {
    fn drop(&mut self) {
        metrics::histogram!(
            "db.client.connection.use_time",
            POOL_NAME => SQLITE_POOL
        )
        .record(self.since.elapsed().as_secs_f64());
    }
}

/// Objects, commits and the file's size (page count × page size).
fn totals(conn: &Connection) -> Result<(i64, i64, i64), StorageError> {
    let objects: i64 = conn
        .query_row("SELECT COUNT(*) FROM objects", [], |row| row.get(0))
        .map_err(|e| StorageError::Backend(format!("count objects: {}", e)))?;
    let commits: i64 = conn
        .query_row("SELECT COUNT(*) FROM commits", [], |row| row.get(0))
        .map_err(|e| StorageError::Backend(format!("count commits: {}", e)))?;
    let page_count: i64 = conn
        .query_row("PRAGMA page_count", [], |row| row.get(0))
        .map_err(|e| StorageError::Backend(format!("page_count: {}", e)))?;
    let page_size: i64 = conn
        .query_row("PRAGMA page_size", [], |row| row.get(0))
        .map_err(|e| StorageError::Backend(format!("page_size: {}", e)))?;
    Ok((objects, commits, page_count * page_size))
}

impl ObjectStore for SqliteStorage {
    fn get_object(&self, id: &ObjectId) -> Result<Option<Object>, StorageError> {
        let conn = self.lock_conn()?;
        let result: Option<Vec<u8>> = conn
            .query_row(
                "SELECT data FROM objects WHERE id = ?1",
                params![id.as_bytes().as_slice()],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("get object: {}", e)))?;

        match result {
            Some(data) => {
                let obj: Object = serde_json::from_slice(&data)
                    .map_err(|e| StorageError::Serialization(e.to_string()))?;
                Ok(Some(obj))
            }
            None => Ok(None),
        }
    }

    fn put_object(&self, obj: &Object) -> Result<ObjectId, StorageError> {
        let id = obj.id();
        let data =
            serde_json::to_vec(obj).map_err(|e| StorageError::Serialization(e.to_string()))?;

        let conn = self.lock_conn()?;
        conn.execute(
            PUT_OBJECT,
            params![
                id.as_bytes().as_slice(),
                data,
                now_millis(),
                freshen_after_millis()
            ],
        )
        .map_err(|e| StorageError::Backend(format!("put object: {}", e)))?;

        Ok(id)
    }

    fn leaf_index_is_built(&self, namespace: &str, ref_name: &str) -> Result<bool, StorageError> {
        let conn = self.lock_conn()?;
        conn.query_row(
            "SELECT EXISTS(SELECT 1 FROM leaf_index_refs WHERE namespace = ?1 AND ref = ?2)",
            params![namespace, ref_name],
            |row| row.get(0),
        )
        .map_err(|e| StorageError::Backend(format!("leaf_index_is_built: {}", e)))
    }

    fn leaf_index_build(
        &self,
        namespace: &str,
        ref_name: &str,
        entries: &[(String, String)],
    ) -> Result<(), StorageError> {
        let mut conn = self.lock_conn()?;
        let tx = conn
            .transaction()
            .map_err(|e| StorageError::Backend(format!("leaf_index_build tx: {}", e)))?;
        leaf_set_replace(&tx, namespace, ref_name, None, entries)?;
        tx.commit()
            .map_err(|e| StorageError::Backend(format!("leaf_index_build commit: {}", e)))
    }

    fn leaf_index_apply(
        &self,
        namespace: &str,
        ref_name: &str,
        removed_paths: &[String],
        added: &[(String, String)],
    ) -> Result<(), StorageError> {
        let mut conn = self.lock_conn()?;
        let tx = conn
            .transaction()
            .map_err(|e| StorageError::Backend(format!("leaf_index_apply tx: {}", e)))?;
        // Only maintain a set that has actually been built; otherwise the
        // eventual backfill reads the current state and this diff would be lost.
        // The set no longer reflects a known tree, so its root is cleared.
        let built = tx
            .execute(
                "UPDATE leaf_index_refs SET root = NULL WHERE namespace = ?1 AND ref = ?2",
                params![namespace, ref_name],
            )
            .map_err(|e| StorageError::Backend(format!("leaf_index_apply check: {}", e)))?
            > 0;
        if built {
            leaf_set_apply(&tx, namespace, ref_name, removed_paths, added)?;
        }
        tx.commit()
            .map_err(|e| StorageError::Backend(format!("leaf_index_apply commit: {}", e)))
    }

    fn leaf_index_tracks_roots(&self) -> bool {
        true
    }

    fn leaf_index_root(
        &self,
        namespace: &str,
        ref_name: &str,
    ) -> Result<Option<ObjectId>, StorageError> {
        let conn = self.lock_conn()?;
        let root: Option<Option<Vec<u8>>> = conn
            .query_row(
                "SELECT root FROM leaf_index_refs WHERE namespace = ?1 AND ref = ?2",
                params![namespace, ref_name],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("leaf_index_root: {}", e)))?;
        Ok(root.flatten().as_deref().and_then(object_id_from_bytes))
    }

    fn leaf_index_build_at(
        &self,
        namespace: &str,
        ref_name: &str,
        root: &ObjectId,
        entries: &[(String, String)],
    ) -> Result<(), StorageError> {
        let mut conn = self.lock_conn()?;
        let tx = conn
            .transaction()
            .map_err(|e| StorageError::Backend(format!("leaf_index_build tx: {}", e)))?;
        leaf_set_replace(&tx, namespace, ref_name, Some(root), entries)?;
        tx.commit()
            .map_err(|e| StorageError::Backend(format!("leaf_index_build commit: {}", e)))
    }

    fn leaf_index_advance(
        &self,
        namespace: &str,
        ref_name: &str,
        from: &ObjectId,
        to: &ObjectId,
        removed_paths: &[String],
        added: &[(String, String)],
    ) -> Result<bool, StorageError> {
        let mut conn = self.lock_conn()?;
        let tx = conn
            .transaction()
            .map_err(|e| StorageError::Backend(format!("leaf_index_advance tx: {}", e)))?;
        // Moving the root first takes the write lock, so the check and the
        // rows change together.
        let moved = tx
            .execute(
                "UPDATE leaf_index_refs SET root = ?4 \
                 WHERE namespace = ?1 AND ref = ?2 AND root = ?3",
                params![
                    namespace,
                    ref_name,
                    from.as_bytes().as_slice(),
                    to.as_bytes().as_slice()
                ],
            )
            .map_err(|e| StorageError::Backend(format!("leaf_index_advance root: {}", e)))?
            > 0;
        if !moved {
            return Ok(false);
        }
        leaf_set_apply(&tx, namespace, ref_name, removed_paths, added)?;
        tx.commit()
            .map_err(|e| StorageError::Backend(format!("leaf_index_advance commit: {}", e)))?;
        Ok(true)
    }

    fn leaf_index_search(
        &self,
        namespace: &str,
        ref_name: &str,
        query_lower: &str,
        limit: usize,
    ) -> Result<Option<Vec<(String, String)>>, StorageError> {
        let conn = self.lock_conn()?;
        let built: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM leaf_index_refs WHERE namespace = ?1 AND ref = ?2)",
                params![namespace, ref_name],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("leaf_index_search check: {}", e)))?;
        if !built {
            return Ok(None); // caller falls back to the tree walk
        }
        // Trigram FTS5 gives substring MATCH for needles >= 3 chars. Quote the
        // needle as a phrase and escape embedded quotes so punctuation in the
        // query can't be read as FTS syntax. Shorter needles can't use the
        // trigram index, so fall back to a scan-assisted LIKE on the base rows,
        // with `%`, `_` and `\` escaped so they match themselves, as they do in
        // the trigram path.
        let mut out = Vec::new();
        if query_lower.chars().count() >= 3 {
            let match_expr = format!("\"{}\"", query_lower.replace('"', "\"\""));
            let mut stmt = conn
                .prepare_cached(
                    "SELECT r.path, r.value FROM leaf_rows r \
                     WHERE r.namespace = ?1 AND r.ref = ?2 \
                       AND r.id IN (SELECT rowid FROM leaf_fts WHERE leaf_fts MATCH ?3) \
                     LIMIT ?4",
                )
                .map_err(|e| StorageError::Backend(format!("leaf_index_search prep: {}", e)))?;
            let rows = stmt
                .query_map(
                    params![namespace, ref_name, match_expr, limit as i64],
                    |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
                )
                .map_err(|e| StorageError::Backend(format!("leaf_index_search query: {}", e)))?;
            for r in rows {
                out.push(
                    r.map_err(|e| StorageError::Backend(format!("leaf_index_search row: {}", e)))?,
                );
            }
        } else {
            let mut pattern = String::from("%");
            for ch in query_lower.chars() {
                if matches!(ch, '%' | '_' | '\\') {
                    pattern.push('\\');
                }
                pattern.push(ch);
            }
            pattern.push('%');
            let mut stmt = conn
                .prepare_cached(
                    "SELECT path, value FROM leaf_rows \
                     WHERE namespace = ?1 AND ref = ?2 AND value LIKE ?3 ESCAPE '\\' LIMIT ?4",
                )
                .map_err(|e| StorageError::Backend(format!("leaf_index_search prep2: {}", e)))?;
            let rows = stmt
                .query_map(params![namespace, ref_name, pattern, limit as i64], |row| {
                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                })
                .map_err(|e| StorageError::Backend(format!("leaf_index_search query2: {}", e)))?;
            for r in rows {
                out.push(r.map_err(|e| {
                    StorageError::Backend(format!("leaf_index_search row2: {}", e))
                })?);
            }
        }
        Ok(Some(out))
    }

    fn has_object(&self, id: &ObjectId) -> Result<bool, StorageError> {
        let conn = self.lock_conn()?;
        let exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM objects WHERE id = ?1)",
                params![id.as_bytes().as_slice()],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("has object: {}", e)))?;
        Ok(exists)
    }

    fn batch_put_objects(&self, objs: &[Object]) -> Result<Vec<ObjectId>, StorageError> {
        let conn = self.lock_conn()?;
        let tx = conn
            .unchecked_transaction()
            .map_err(|e| StorageError::Backend(format!("begin tx: {}", e)))?;

        let mut ids = Vec::with_capacity(objs.len());
        {
            let mut stmt = tx
                .prepare_cached(PUT_OBJECT)
                .map_err(|e| StorageError::Backend(format!("prepare: {}", e)))?;

            let now = now_millis();
            for obj in objs {
                let id = obj.id();
                let data = serde_json::to_vec(obj)
                    .map_err(|e| StorageError::Serialization(e.to_string()))?;
                stmt.execute(params![
                    id.as_bytes().as_slice(),
                    data,
                    now,
                    freshen_after_millis()
                ])
                .map_err(|e| StorageError::Backend(format!("batch put: {}", e)))?;
                ids.push(id);
            }
        }

        tx.commit()
            .map_err(|e| StorageError::Backend(format!("commit tx: {}", e)))?;

        Ok(ids)
    }
}

/// Replace the `(namespace, ref)` leaf set with `entries`, marking it built
/// at `root` (unknown when `None`).
fn leaf_set_replace(
    tx: &rusqlite::Transaction<'_>,
    namespace: &str,
    ref_name: &str,
    root: Option<&ObjectId>,
    entries: &[(String, String)],
) -> Result<(), StorageError> {
    tx.execute(
        "INSERT INTO leaf_index_refs (namespace, ref, root) VALUES (?1, ?2, ?3) \
         ON CONFLICT(namespace, ref) DO UPDATE SET root = excluded.root",
        params![namespace, ref_name, root.map(|r| r.as_bytes().to_vec())],
    )
    .map_err(|e| StorageError::Backend(format!("leaf_index_build mark: {}", e)))?;
    tx.execute(
        "DELETE FROM leaf_rows WHERE namespace = ?1 AND ref = ?2",
        params![namespace, ref_name],
    )
    .map_err(|e| StorageError::Backend(format!("leaf_index_build clear: {}", e)))?;
    let mut stmt = tx
        .prepare_cached(
            "INSERT INTO leaf_rows (namespace, ref, path, value) VALUES (?1, ?2, ?3, ?4)",
        )
        .map_err(|e| StorageError::Backend(format!("leaf_index_build prep: {}", e)))?;
    for (path, value) in entries {
        stmt.execute(params![namespace, ref_name, path, value])
            .map_err(|e| StorageError::Backend(format!("leaf_index_build row: {}", e)))?;
    }
    Ok(())
}

/// Delete the rows at `removed_paths` and insert `added`.
fn leaf_set_apply(
    tx: &rusqlite::Transaction<'_>,
    namespace: &str,
    ref_name: &str,
    removed_paths: &[String],
    added: &[(String, String)],
) -> Result<(), StorageError> {
    let mut del = tx
        .prepare_cached("DELETE FROM leaf_rows WHERE namespace = ?1 AND ref = ?2 AND path = ?3")
        .map_err(|e| StorageError::Backend(format!("leaf_index_apply del prep: {}", e)))?;
    for path in removed_paths {
        del.execute(params![namespace, ref_name, path])
            .map_err(|e| StorageError::Backend(format!("leaf_index_apply del: {}", e)))?;
    }
    let mut ins = tx
        .prepare_cached(
            "INSERT INTO leaf_rows (namespace, ref, path, value) VALUES (?1, ?2, ?3, ?4)",
        )
        .map_err(|e| StorageError::Backend(format!("leaf_index_apply ins prep: {}", e)))?;
    for (path, value) in added {
        ins.execute(params![namespace, ref_name, path, value])
            .map_err(|e| StorageError::Backend(format!("leaf_index_apply ins: {}", e)))?;
    }
    Ok(())
}

impl CommitStore for SqliteStorage {
    fn put_commit_traced(
        &self,
        commit: &Commit,
        trace: Option<&CommitTrace>,
    ) -> Result<(), StorageError> {
        let Some(trace) = trace else {
            return self.put_commit(commit);
        };
        let data =
            serde_json::to_vec(commit).map_err(|e| StorageError::Serialization(e.to_string()))?;
        let timestamp = commit.timestamp.to_rfc3339();
        let mut conn = self.lock_conn()?;
        let tx = conn
            .transaction()
            .map_err(|e| StorageError::Backend(format!("begin put commit: {}", e)))?;
        tx.execute(
            "INSERT OR IGNORE INTO commits (id, data, timestamp) VALUES (?1, ?2, ?3)",
            params![commit.id.as_bytes().as_slice(), data, timestamp],
        )
        .map_err(|e| StorageError::Backend(format!("put commit: {}", e)))?;
        tx.execute(
            "INSERT OR IGNORE INTO commit_traces (commit_id, trace_id, span_id)
             VALUES (?1, ?2, ?3)",
            params![
                commit.id.as_bytes().as_slice(),
                trace.trace_id,
                trace.span_id
            ],
        )
        .map_err(|e| StorageError::Backend(format!("set commit trace: {}", e)))?;
        tx.commit()
            .map_err(|e| StorageError::Backend(format!("commit put commit: {}", e)))
    }

    fn set_commit_trace(
        &self,
        commit_id: &ObjectId,
        trace: &CommitTrace,
    ) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        conn.execute(
            "INSERT OR IGNORE INTO commit_traces (commit_id, trace_id, span_id)
             VALUES (?1, ?2, ?3)",
            params![
                commit_id.as_bytes().as_slice(),
                trace.trace_id,
                trace.span_id
            ],
        )
        .map_err(|e| StorageError::Backend(format!("set commit trace: {}", e)))?;
        Ok(())
    }

    fn get_commit_trace(&self, commit_id: &ObjectId) -> Result<Option<CommitTrace>, StorageError> {
        let conn = self.lock_conn()?;
        conn.query_row(
            "SELECT trace_id, span_id FROM commit_traces WHERE commit_id = ?1",
            params![commit_id.as_bytes().as_slice()],
            |row| {
                Ok(CommitTrace {
                    trace_id: row.get(0)?,
                    span_id: row.get(1)?,
                })
            },
        )
        .optional()
        .map_err(|e| StorageError::Backend(format!("get commit trace: {}", e)))
    }

    fn all_commit_ids(&self) -> Result<Vec<ObjectId>, StorageError> {
        let conn = self.lock_conn()?;
        let mut stmt = conn
            .prepare("SELECT id FROM commits")
            .map_err(|e| StorageError::Backend(format!("all commit ids: {}", e)))?;
        let rows = stmt
            .query_map([], |row| row.get::<_, Vec<u8>>(0))
            .map_err(|e| StorageError::Backend(format!("all commit ids: {}", e)))?;
        let mut ids = Vec::new();
        for row in rows {
            let bytes = row.map_err(|e| StorageError::Backend(format!("all commit ids: {}", e)))?;
            if bytes.len() == 32 {
                let mut arr = [0u8; 32];
                arr.copy_from_slice(&bytes);
                ids.push(ObjectId::from_bytes(arr));
            }
        }
        Ok(ids)
    }

    fn history_extract_batch(&self, batch_size: usize) -> Result<usize, StorageError> {
        let batch_size = batch_size.max(1) as i64;
        let conn = self.lock_conn()?;
        let tx = conn
            .unchecked_transaction()
            .map_err(|e| StorageError::Backend(format!("history tx: {}", e)))?;

        let cursor: i64 = tx
            .query_row(
                "SELECT value FROM asg_history_meta WHERE key = 'commit_cursor'",
                [],
                |row| row.get::<_, String>(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("history cursor read: {}", e)))?
            .and_then(|s| s.parse::<i64>().ok())
            .unwrap_or(0);

        // Pull the next batch in rowid order. LEFT JOIN sessions to attribute a
        // namespace when the commit was made inside a scoped session.
        //
        // A commit with no session is attributed to `HISTORY_NAMESPACE_UNKNOWN`
        // rather than to "default". The old fallback asserted a namespace it had
        // not established: on a store where nothing writes sessions, EVERY commit
        // was filed under "default" — measured on the AgentStateDeveloper store,
        // all 39,446 of them, though ~35,000 belong to a different namespace
        // entirely. Callers filtering by namespace silently got everything or
        // nothing, and "default" is a real namespace name, so there was no way to
        // tell a genuine attribution from a fallback.
        //
        // This does not make attribution correct, only honest. A commit carries
        // no namespace — namespace lives on refs, so deriving it properly means a
        // reachability walk or a new column on `commits`. Until then an
        // unattributable commit says so.
        let batch: Vec<(i64, Vec<u8>, String)> = {
            let mut stmt = tx
                .prepare(
                    "SELECT c.rowid, c.data, COALESCE(s.scope_namespace, ?3) \
                     FROM commits c \
                     LEFT JOIN sessions s ON c.session_id = s.id \
                     WHERE c.rowid > ?1 ORDER BY c.rowid LIMIT ?2",
                )
                .map_err(|e| StorageError::Backend(format!("history select: {}", e)))?;
            let rows = stmt
                .query_map(
                    params![cursor, batch_size, HISTORY_NAMESPACE_UNKNOWN],
                    |row| {
                        Ok((
                            row.get::<_, i64>(0)?,
                            row.get::<_, Vec<u8>>(1)?,
                            row.get::<_, String>(2)?,
                        ))
                    },
                )
                .map_err(|e| StorageError::Backend(format!("history query: {}", e)))?;
            let mut out = Vec::new();
            for r in rows {
                out.push(r.map_err(|e| StorageError::Backend(format!("history row: {}", e)))?);
            }
            out
        };

        if batch.is_empty() {
            return Ok(0);
        }

        let mut max_rowid = cursor;
        let mut processed = 0usize;
        for (rowid, data, namespace) in &batch {
            max_rowid = (*rowid).max(max_rowid);
            let commit: Commit = serde_json::from_slice(data)
                .map_err(|e| StorageError::Serialization(e.to_string()))?;
            let day = commit.timestamp.format("%Y-%m-%d").to_string();
            let ts = commit.timestamp.to_rfc3339();
            let agent = &commit.agent_id;
            let category = format!("{:?}", commit.intent.category);

            tx.execute(
                "INSERT INTO asg_history_commit_rollup \
                   (day, namespace, agent_id, intent_category, commit_count, first_ts, last_ts) \
                 VALUES (?1, ?2, ?3, ?4, 1, ?5, ?5) \
                 ON CONFLICT(day, namespace, agent_id, intent_category) DO UPDATE SET \
                   commit_count = commit_count + 1, \
                   first_ts = MIN(first_ts, excluded.first_ts), \
                   last_ts  = MAX(last_ts,  excluded.last_ts)",
                params![day, namespace, agent, category, ts],
            )
            .map_err(|e| StorageError::Backend(format!("history rollup upsert: {}", e)))?;

            if commit.intent.category == IntentCategory::Checkpoint {
                // Pinning is opt-in. A checkpoint keeps its snapshot reachable
                // through a sweep only when it asks to; otherwise the milestone
                // records the moment but names no state, and GC may reclaim the
                // objects behind it. Pinning unconditionally retains a full
                // state tree per checkpoint, and a routine re-index emits one
                // every run — which is how a store reaches millions of objects
                // with almost nothing reclaimable.
                let pinned_root = commit
                    .intent
                    .tags
                    .iter()
                    .any(|t| t == TAG_PIN_STATE)
                    .then(|| commit.state_root.as_bytes().to_vec());
                // The revision this state was derived from, so an unpinned
                // milestone still says how to rebuild it.
                let git_sha = commit
                    .intent
                    .tags
                    .iter()
                    .find_map(|t| t.strip_prefix(TAG_GIT_REVISION))
                    .filter(|sha| !sha.is_empty());
                tx.execute(
                    "INSERT OR IGNORE INTO asg_history_milestone \
                       (commit_id, kind, timestamp, day, namespace, agent_id, description, state_root, git_sha) \
                     VALUES (?1, 'checkpoint', ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                    params![
                        commit.id.as_bytes().as_slice(),
                        ts,
                        day,
                        namespace,
                        agent,
                        commit.intent.description,
                        pinned_root,
                        git_sha,
                    ],
                )
                .map_err(|e| StorageError::Backend(format!("history milestone: {}", e)))?;
            }
            processed += 1;
        }

        // Advance the cursor in the SAME transaction as the writes: a crash
        // rolls the whole batch back, so the next run re-folds it rather than
        // double-counting.
        tx.execute(
            "INSERT INTO asg_history_meta (key, value) VALUES ('commit_cursor', ?1) \
             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            params![max_rowid.to_string()],
        )
        .map_err(|e| StorageError::Backend(format!("history cursor write: {}", e)))?;

        tx.commit()
            .map_err(|e| StorageError::Backend(format!("history commit: {}", e)))?;
        Ok(processed)
    }

    fn history_cursor(&self) -> Result<i64, StorageError> {
        let conn = self.lock_conn()?;
        let cursor: i64 = conn
            .query_row(
                "SELECT value FROM asg_history_meta WHERE key = 'commit_cursor'",
                [],
                |row| row.get::<_, String>(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("history cursor: {}", e)))?
            .and_then(|s| s.parse::<i64>().ok())
            .unwrap_or(0);
        Ok(cursor)
    }

    fn history_undistilled_commit_count(&self) -> Result<i64, StorageError> {
        let conn = self.lock_conn()?;
        let cursor: i64 = conn
            .query_row(
                "SELECT value FROM asg_history_meta WHERE key = 'commit_cursor'",
                [],
                |row| row.get::<_, String>(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("undistilled cursor: {}", e)))?
            .and_then(|s| s.parse::<i64>().ok())
            .unwrap_or(0);
        let n: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM commits WHERE rowid > ?1",
                params![cursor],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("undistilled count: {}", e)))?;
        Ok(n)
    }

    fn history_rollup(&self) -> Result<Vec<HistoryRollupRow>, StorageError> {
        let conn = self.lock_conn()?;
        let mut stmt = conn
            .prepare(
                "SELECT day, namespace, agent_id, intent_category, commit_count, first_ts, last_ts \
                 FROM asg_history_commit_rollup \
                 ORDER BY day, namespace, agent_id, intent_category",
            )
            .map_err(|e| StorageError::Backend(format!("history rollup read: {}", e)))?;
        let rows = stmt
            .query_map([], |row| {
                Ok(HistoryRollupRow {
                    day: row.get(0)?,
                    namespace: row.get(1)?,
                    agent_id: row.get(2)?,
                    intent_category: row.get(3)?,
                    commit_count: row.get(4)?,
                    first_ts: row.get(5)?,
                    last_ts: row.get(6)?,
                })
            })
            .map_err(|e| StorageError::Backend(format!("history rollup query: {}", e)))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(r.map_err(|e| StorageError::Backend(format!("history rollup row: {}", e)))?);
        }
        Ok(out)
    }

    fn history_milestones(&self, limit: usize) -> Result<Vec<HistoryMilestoneRow>, StorageError> {
        let conn = self.lock_conn()?;
        let mut stmt = conn
            .prepare(
                "SELECT commit_id, kind, timestamp, day, namespace, agent_id, description, state_root, git_sha \
                 FROM asg_history_milestone ORDER BY timestamp DESC LIMIT ?1",
            )
            .map_err(|e| StorageError::Backend(format!("history milestones read: {}", e)))?;
        let rows = stmt
            .query_map(params![limit as i64], |row| {
                Ok((
                    row.get::<_, Vec<u8>>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                    row.get::<_, String>(4)?,
                    row.get::<_, String>(5)?,
                    row.get::<_, String>(6)?,
                    row.get::<_, Option<Vec<u8>>>(7)?,
                    row.get::<_, Option<String>>(8)?,
                ))
            })
            .map_err(|e| StorageError::Backend(format!("history milestones query: {}", e)))?;
        let mut out = Vec::new();
        for r in rows {
            let (
                id_bytes,
                kind,
                timestamp,
                day,
                namespace,
                agent_id,
                description,
                root_bytes,
                git_sha,
            ) = r.map_err(|e| StorageError::Backend(format!("history milestone row: {}", e)))?;
            let Some(commit_id) = object_id_from_bytes(&id_bytes) else {
                continue;
            };
            out.push(HistoryMilestoneRow {
                commit_id,
                kind,
                timestamp,
                day,
                namespace,
                agent_id,
                description,
                state_root: root_bytes.as_deref().and_then(object_id_from_bytes),
                git_sha,
            });
        }
        Ok(out)
    }

    fn history_is_commit_distilled(&self, id: &ObjectId) -> Result<bool, StorageError> {
        let conn = self.lock_conn()?;
        let cursor: i64 = conn
            .query_row(
                "SELECT value FROM asg_history_meta WHERE key = 'commit_cursor'",
                [],
                |row| row.get::<_, String>(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("distilled cursor: {}", e)))?
            .and_then(|s| s.parse::<i64>().ok())
            .unwrap_or(0);
        let rowid: Option<i64> = conn
            .query_row(
                "SELECT rowid FROM commits WHERE id = ?1",
                params![id.as_bytes().as_slice()],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("distilled rowid: {}", e)))?;
        // Distilled iff the commit exists and its rowid is at/behind the cursor.
        Ok(matches!(rowid, Some(r) if r <= cursor))
    }

    fn history_retained_state_roots(&self) -> Result<Vec<ObjectId>, StorageError> {
        let conn = self.lock_conn()?;
        let mut stmt = conn
            .prepare(
                "SELECT DISTINCT state_root FROM asg_history_milestone WHERE state_root IS NOT NULL",
            )
            .map_err(|e| StorageError::Backend(format!("retained roots read: {}", e)))?;
        let rows = stmt
            .query_map([], |row| row.get::<_, Vec<u8>>(0))
            .map_err(|e| StorageError::Backend(format!("retained roots query: {}", e)))?;
        let mut out = Vec::new();
        for r in rows {
            let bytes = r.map_err(|e| StorageError::Backend(format!("retained root: {}", e)))?;
            if let Some(id) = object_id_from_bytes(&bytes) {
                out.push(id);
            }
        }
        Ok(out)
    }

    fn history_gc_reachability(
        &self,
        roots: &[ObjectId],
        batch: usize,
    ) -> Result<GcReachability, StorageError> {
        let batch = batch.max(1) as i64;
        let conn = self.lock_conn()?;
        gc_build_mark(&conn, roots, batch)?;

        let live: i64 = conn
            .query_row("SELECT COUNT(*) FROM gc_mark", [], |row| row.get(0))
            .map_err(|e| StorageError::Backend(format!("gc live count: {}", e)))?;
        let total: i64 = conn
            .query_row("SELECT COUNT(*) FROM objects", [], |row| row.get(0))
            .map_err(|e| StorageError::Backend(format!("gc total count: {}", e)))?;
        conn.execute("DELETE FROM gc_mark", [])
            .map_err(|e| StorageError::Backend(format!("gc cleanup: {}", e)))?;

        Ok(GcReachability {
            total_objects: total,
            live_objects: live,
            reclaimable_objects: (total - live).max(0),
            roots_walked: roots.len(),
        })
    }

    fn history_gc_sweep(&self, roots: &[ObjectId], batch: usize) -> Result<GcSweep, StorageError> {
        let batch = batch.max(1) as i64;
        // Under `history_gc_lock_writers` the sweep runs on the connection that
        // holds the lock.
        {
            let gc = self
                .gc_conn
                .lock()
                .map_err(|e| StorageError::Backend(e.to_string()))?;
            if let Some(gc_conn) = gc.as_ref() {
                return gc_sweep_locked(gc_conn, roots, batch, self.gc_grace);
            }
        }
        let conn = self.lock_conn()?;
        // Exclude every other writer from the mark to the last delete. Without
        // it a commit from another connection can land mid-sweep and lose its
        // objects: reachable only from a ref tip the mark never saw, or
        // re-referenced (content addressing) after being queued as dead.
        // Readers are unaffected under WAL. A caller already holding the lock —
        // `Repository::gc_sweep` takes it before computing its keep-set — is
        // joined rather than locked twice.
        let own_lock = conn.is_autocommit();
        if own_lock {
            conn.execute_batch("BEGIN IMMEDIATE")
                .map_err(|e| StorageError::Backend(format!("gc sweep lock: {}", e)))?;
        }
        let result = gc_sweep_locked(&conn, roots, batch, self.gc_grace);
        if own_lock {
            match &result {
                Ok(_) => conn
                    .execute_batch("COMMIT")
                    .map_err(|e| StorageError::Backend(format!("gc sweep commit: {}", e)))?,
                // Keep the original error; a failed rollback here changes nothing
                // the caller can act on.
                Err(_) => {
                    let _ = conn.execute_batch("ROLLBACK");
                }
            }
        }
        result
    }

    fn gc_pin_root(&self, key: &str, root: &ObjectId) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        conn.execute(
            "INSERT OR REPLACE INTO gc_pending_roots (key, root, updated_at) VALUES (?1, ?2, ?3)",
            params![
                key,
                root.as_bytes().as_slice(),
                chrono::Utc::now().timestamp()
            ],
        )
        .map_err(|e| StorageError::Backend(format!("gc pin root: {}", e)))?;
        Ok(())
    }

    fn gc_unpin_root(&self, key: &str) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        conn.execute("DELETE FROM gc_pending_roots WHERE key = ?1", params![key])
            .map_err(|e| StorageError::Backend(format!("gc unpin root: {}", e)))?;
        Ok(())
    }

    fn gc_pinned_roots(&self, max_age: std::time::Duration) -> Result<Vec<ObjectId>, StorageError> {
        let conn = self.lock_conn()?;
        gc_pending_roots(&conn, max_age)
    }

    fn history_gc_lock_writers(&self) -> Result<(), StorageError> {
        let Some(path) = self.path.as_ref() else {
            // In-memory: there is no second connection to take. Only the
            // owning process can reach the store, and sweeping one that other
            // threads are writing is not supported.
            let conn = self.lock_conn()?;
            return conn
                .execute_batch("BEGIN IMMEDIATE")
                .map_err(|e| StorageError::Backend(format!("gc lock writers: {}", e)));
        };
        let mut gc = self
            .gc_conn
            .lock()
            .map_err(|e| StorageError::Backend(e.to_string()))?;
        if gc.is_some() {
            return Err(StorageError::Backend(
                "gc lock writers: a sweep already holds the lock".into(),
            ));
        }
        let conn = Connection::open(path)
            .map_err(|e| StorageError::Backend(format!("gc lock connection: {}", e)))?;
        oxtel_sql::rusqlite::instrument(&conn);
        // Wait out an in-flight writer rather than failing the sweep at once.
        let _ = conn.busy_timeout(std::time::Duration::from_secs(30));
        conn.execute_batch("BEGIN IMMEDIATE")
            .map_err(|e| StorageError::Backend(format!("gc lock writers: {}", e)))?;
        *gc = Some(conn);
        Ok(())
    }

    fn history_gc_unlock_writers(&self, commit: bool) -> Result<(), StorageError> {
        let held = self
            .gc_conn
            .lock()
            .map_err(|e| StorageError::Backend(e.to_string()))?
            .take();
        if let Some(conn) = held {
            // Dropping the connection rolls back anything uncommitted, so a
            // failed COMMIT cannot leave the lock (or a transaction) behind.
            if commit {
                conn.execute_batch("COMMIT").map_err(|e| {
                    StorageError::Backend(format!("gc unlock writers (COMMIT): {}", e))
                })?;
            }
            return Ok(());
        }
        let conn = self.lock_conn()?;
        if conn.is_autocommit() {
            // Nothing held — already released, or never taken.
            return Ok(());
        }
        let end = if commit { "COMMIT" } else { "ROLLBACK" };
        conn.execute_batch(end)
            .map_err(|e| StorageError::Backend(format!("gc unlock writers ({end}): {}", e)))
    }

    fn history_unpin_legacy_milestones(&self) -> Result<usize, StorageError> {
        let conn = self.lock_conn()?;
        let unrequested: Vec<Vec<u8>> = {
            let mut stmt = conn
                .prepare(
                    "SELECT m.commit_id, c.data FROM asg_history_milestone m \
                     JOIN commits c ON c.id = m.commit_id \
                     WHERE m.state_root IS NOT NULL",
                )
                .map_err(|e| StorageError::Backend(format!("unpin read: {}", e)))?;
            let rows = stmt
                .query_map([], |row| {
                    Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, Vec<u8>>(1)?))
                })
                .map_err(|e| StorageError::Backend(format!("unpin query: {}", e)))?;
            let mut out = Vec::new();
            for r in rows {
                let (id, data) =
                    r.map_err(|e| StorageError::Backend(format!("unpin row: {}", e)))?;
                let commit: Commit = serde_json::from_slice(&data)
                    .map_err(|e| StorageError::Serialization(e.to_string()))?;
                if !commit.intent.tags.iter().any(|t| t == TAG_PIN_STATE) {
                    out.push(id);
                }
            }
            out
        };
        gc_in_tx(&conn, "unpin milestones", |c| {
            let mut updated = 0usize;
            for id in &unrequested {
                updated += c
                    .execute(
                        "UPDATE asg_history_milestone SET state_root = NULL WHERE commit_id = ?1",
                        params![id.as_slice()],
                    )
                    .map_err(|e| StorageError::Backend(format!("unpin update: {}", e)))?;
            }
            Ok(updated)
        })
    }

    fn history_vacuum(&self) -> Result<VacuumStats, StorageError> {
        let conn = self.lock_conn()?;
        let db_bytes = |conn: &Connection| -> Result<i64, StorageError> {
            let pc: i64 = conn
                .query_row("PRAGMA page_count", [], |r| r.get(0))
                .map_err(|e| StorageError::Backend(format!("page_count: {}", e)))?;
            let ps: i64 = conn
                .query_row("PRAGMA page_size", [], |r| r.get(0))
                .map_err(|e| StorageError::Backend(format!("page_size: {}", e)))?;
            Ok(pc * ps)
        };
        let bytes_before = db_bytes(&conn)?;
        // Full VACUUM: rewrites the DB compactly, returning freed pages to the
        // OS. Also adopts the current `auto_vacuum` mode (INCREMENTAL, set at
        // open), so subsequent sweeps can reclaim incrementally.
        conn.execute_batch("VACUUM")
            .map_err(|e| StorageError::Backend(format!("vacuum: {}", e)))?;
        let bytes_after = db_bytes(&conn)?;
        Ok(VacuumStats {
            bytes_before,
            bytes_after,
            bytes_reclaimed: (bytes_before - bytes_after).max(0),
        })
    }

    fn commit_state_roots_recent_first(&self) -> Result<Vec<ObjectId>, StorageError> {
        let conn = self.lock_conn()?;
        let mut stmt = conn
            .prepare("SELECT data FROM commits ORDER BY rowid DESC")
            .map_err(|e| StorageError::Backend(format!("commit roots read: {}", e)))?;
        let rows = stmt
            .query_map([], |row| row.get::<_, Vec<u8>>(0))
            .map_err(|e| StorageError::Backend(format!("commit roots query: {}", e)))?;
        let mut out = Vec::new();
        for r in rows {
            let data = r.map_err(|e| StorageError::Backend(format!("commit roots row: {}", e)))?;
            let commit: Commit = serde_json::from_slice(&data)
                .map_err(|e| StorageError::Serialization(e.to_string()))?;
            out.push(commit.state_root);
        }
        Ok(out)
    }

    fn store_totals(&self) -> Result<Option<StoreTotals>, StorageError> {
        let conn = self.lock_conn()?;
        let (objects, commits, bytes) = totals(&conn)?;
        Ok(Some(StoreTotals {
            objects,
            commits,
            bytes: self.path.is_some().then_some(bytes),
        }))
    }

    fn history_store_shape(&self) -> Result<StoreShape, StorageError> {
        let conn = self.lock_conn()?;
        let (objects, commits, total_bytes) = totals(&conn)?;

        // Per-table bytes need the dbstat virtual table, which is only present
        // when SQLite was built with SQLITE_ENABLE_DBSTAT_VTAB. Probe it and
        // degrade gracefully to a totals-only report if it's missing.
        let (tables, dbstat_available) = match conn.prepare(
            "SELECT name, SUM(pgsize) AS bytes FROM dbstat GROUP BY name ORDER BY bytes DESC",
        ) {
            Ok(mut stmt) => {
                let rows = stmt.query_map([], |row| {
                    Ok(TableBytes {
                        name: row.get::<_, String>(0)?,
                        bytes: row.get::<_, i64>(1)?,
                    })
                });
                match rows {
                    Ok(iter) => {
                        let mut v = Vec::new();
                        let mut ok = true;
                        for r in iter {
                            match r {
                                Ok(tb) => v.push(tb),
                                Err(_) => {
                                    ok = false;
                                    break;
                                }
                            }
                        }
                        if ok { (v, true) } else { (Vec::new(), false) }
                    }
                    Err(_) => (Vec::new(), false),
                }
            }
            Err(_) => (Vec::new(), false),
        };

        Ok(StoreShape {
            objects,
            commits,
            total_bytes,
            tables,
            dbstat_available,
        })
    }

    fn get_commit(&self, id: &ObjectId) -> Result<Option<Commit>, StorageError> {
        let conn = self.lock_conn()?;
        let result: Option<Vec<u8>> = conn
            .query_row(
                "SELECT data FROM commits WHERE id = ?1",
                params![id.as_bytes().as_slice()],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("get commit: {}", e)))?;

        match result {
            Some(data) => {
                let commit: Commit = serde_json::from_slice(&data)
                    .map_err(|e| StorageError::Serialization(e.to_string()))?;
                Ok(Some(commit))
            }
            None => Ok(None),
        }
    }

    fn put_commit(&self, commit: &Commit) -> Result<(), StorageError> {
        let data =
            serde_json::to_vec(commit).map_err(|e| StorageError::Serialization(e.to_string()))?;
        let timestamp = commit.timestamp.to_rfc3339();

        let conn = self.lock_conn()?;
        conn.execute(
            "INSERT OR IGNORE INTO commits (id, data, timestamp) VALUES (?1, ?2, ?3)",
            params![commit.id.as_bytes().as_slice(), data, timestamp],
        )
        .map_err(|e| StorageError::Backend(format!("put commit: {}", e)))?;

        Ok(())
    }

    fn has_commit(&self, id: &ObjectId) -> Result<bool, StorageError> {
        let conn = self.lock_conn()?;
        let exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM commits WHERE id = ?1)",
                params![id.as_bytes().as_slice()],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("has commit: {}", e)))?;
        Ok(exists)
    }

    fn list_commits(&self, from: &ObjectId, limit: usize) -> Result<Vec<Commit>, StorageError> {
        // Walk the parent chain from the given commit
        let conn = self.lock_conn()?;
        let mut result = Vec::new();
        let mut current = Some(*from);

        while let Some(id) = current {
            if result.len() >= limit {
                break;
            }

            let data: Option<Vec<u8>> = conn
                .query_row(
                    "SELECT data FROM commits WHERE id = ?1",
                    params![id.as_bytes().as_slice()],
                    |row| row.get(0),
                )
                .optional()
                .map_err(|e| StorageError::Backend(format!("list commits: {}", e)))?;

            match data {
                Some(data) => {
                    let commit: Commit = serde_json::from_slice(&data)
                        .map_err(|e| StorageError::Serialization(e.to_string()))?;
                    current = commit.parents.first().copied();
                    result.push(commit);
                }
                None => break,
            }
        }

        Ok(result)
    }
}

impl RefStore for SqliteStorage {
    fn create_namespace(&self, namespace: &Namespace) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        let rows = conn
            .execute(
                "INSERT OR IGNORE INTO namespaces (name, created_at) VALUES (?1, ?2)",
                params![namespace.as_str(), chrono::Utc::now().to_rfc3339()],
            )
            .map_err(|e| StorageError::Backend(format!("create namespace: {}", e)))?;
        if rows == 0 {
            return Err(StorageError::NamespaceAlreadyExists(
                namespace.as_str().to_string(),
            ));
        }
        Ok(())
    }

    fn list_namespaces(&self) -> Result<Vec<Namespace>, StorageError> {
        let conn = self.lock_conn()?;
        let mut stmt = conn
            .prepare("SELECT name FROM namespaces ORDER BY name")
            .map_err(|e| StorageError::Backend(format!("list namespaces: {}", e)))?;
        let rows = stmt
            .query_map([], |row| row.get::<_, String>(0))
            .map_err(|e| StorageError::Backend(format!("list namespaces query: {}", e)))?;
        let mut result = Vec::new();
        for row in rows {
            let name =
                row.map_err(|e| StorageError::Backend(format!("list namespaces row: {}", e)))?;
            let ns = Namespace::new(name)
                .map_err(|e| StorageError::Backend(format!("invalid namespace in db: {}", e)))?;
            result.push(ns);
        }
        Ok(result)
    }

    fn get_ref(&self, namespace: &Namespace, name: &str) -> Result<Option<ObjectId>, StorageError> {
        let conn = self.lock_conn()?;
        let ns_exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM namespaces WHERE name = ?1)",
                params![namespace.as_str()],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("check namespace: {}", e)))?;
        if !ns_exists {
            return Err(StorageError::NamespaceNotFound(
                namespace.as_str().to_string(),
            ));
        }

        let result: Option<Vec<u8>> = conn
            .query_row(
                "SELECT target FROM refs WHERE namespace = ?1 AND name = ?2",
                params![namespace.as_str(), name],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("get ref: {}", e)))?;

        match result {
            Some(bytes) => {
                let mut arr = [0u8; 32];
                arr.copy_from_slice(&bytes);
                Ok(Some(ObjectId::from_bytes(arr)))
            }
            None => Ok(None),
        }
    }

    fn set_ref(
        &self,
        namespace: &Namespace,
        name: &str,
        target: ObjectId,
    ) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        let ns_exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM namespaces WHERE name = ?1)",
                params![namespace.as_str()],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("check namespace: {}", e)))?;
        if !ns_exists {
            return Err(StorageError::NamespaceNotFound(
                namespace.as_str().to_string(),
            ));
        }

        conn.execute(
            "INSERT OR REPLACE INTO refs (namespace, name, target) VALUES (?1, ?2, ?3)",
            params![namespace.as_str(), name, target.as_bytes().as_slice()],
        )
        .map_err(|e| StorageError::Backend(format!("set ref: {}", e)))?;
        Ok(())
    }

    fn cas_ref(
        &self,
        namespace: &Namespace,
        name: &str,
        expected: ObjectId,
        new: ObjectId,
    ) -> Result<bool, StorageError> {
        let conn = self.lock_conn()?;
        let ns_exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM namespaces WHERE name = ?1)",
                params![namespace.as_str()],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("check namespace: {}", e)))?;
        if !ns_exists {
            return Err(StorageError::NamespaceNotFound(
                namespace.as_str().to_string(),
            ));
        }

        let rows = conn
            .execute(
                "UPDATE refs SET target = ?1 \
                 WHERE namespace = ?2 AND name = ?3 AND target = ?4",
                params![
                    new.as_bytes().as_slice(),
                    namespace.as_str(),
                    name,
                    expected.as_bytes().as_slice()
                ],
            )
            .map_err(|e| StorageError::Backend(format!("cas ref: {}", e)))?;
        Ok(rows > 0)
    }

    fn create_ref(
        &self,
        namespace: &Namespace,
        name: &str,
        target: ObjectId,
    ) -> Result<bool, StorageError> {
        let conn = self.lock_conn()?;
        require_namespace(&conn, namespace)?;
        let rows = conn
            .execute(
                "INSERT OR IGNORE INTO refs (namespace, name, target) VALUES (?1, ?2, ?3)",
                params![namespace.as_str(), name, target.as_bytes().as_slice()],
            )
            .map_err(|e| StorageError::Backend(format!("create ref: {}", e)))?;
        Ok(rows > 0)
    }

    fn cas_delete_ref(
        &self,
        namespace: &Namespace,
        name: &str,
        expected: ObjectId,
    ) -> Result<bool, StorageError> {
        let conn = self.lock_conn()?;
        require_namespace(&conn, namespace)?;
        let rows = conn
            .execute(
                "DELETE FROM refs WHERE namespace = ?1 AND name = ?2 AND target = ?3",
                params![namespace.as_str(), name, expected.as_bytes().as_slice()],
            )
            .map_err(|e| StorageError::Backend(format!("cas delete ref: {}", e)))?;
        Ok(rows > 0)
    }

    fn list_refs(
        &self,
        namespace: &Namespace,
        prefix: &str,
    ) -> Result<Vec<(String, ObjectId)>, StorageError> {
        let conn = self.lock_conn()?;
        let ns_exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM namespaces WHERE name = ?1)",
                params![namespace.as_str()],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("check namespace: {}", e)))?;
        if !ns_exists {
            return Err(StorageError::NamespaceNotFound(
                namespace.as_str().to_string(),
            ));
        }

        let mut stmt = conn
            .prepare(
                "SELECT name, target FROM refs \
                 WHERE namespace = ?1 AND name LIKE ?2 ORDER BY name",
            )
            .map_err(|e| StorageError::Backend(format!("list refs: {}", e)))?;

        let pattern = format!("{}%", prefix);
        let rows = stmt
            .query_map(params![namespace.as_str(), pattern], |row| {
                let name: String = row.get(0)?;
                let bytes: Vec<u8> = row.get(1)?;
                Ok((name, bytes))
            })
            .map_err(|e| StorageError::Backend(format!("list refs query: {}", e)))?;

        let mut result = Vec::new();
        for row in rows {
            let (name, bytes) =
                row.map_err(|e| StorageError::Backend(format!("list refs row: {}", e)))?;
            let mut arr = [0u8; 32];
            arr.copy_from_slice(&bytes);
            result.push((name, ObjectId::from_bytes(arr)));
        }
        Ok(result)
    }

    fn delete_ref(&self, namespace: &Namespace, name: &str) -> Result<bool, StorageError> {
        let conn = self.lock_conn()?;
        let ns_exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM namespaces WHERE name = ?1)",
                params![namespace.as_str()],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("check namespace: {}", e)))?;
        if !ns_exists {
            return Err(StorageError::NamespaceNotFound(
                namespace.as_str().to_string(),
            ));
        }

        let rows = conn
            .execute(
                "DELETE FROM refs WHERE namespace = ?1 AND name = ?2",
                params![namespace.as_str(), name],
            )
            .map_err(|e| StorageError::Backend(format!("delete ref: {}", e)))?;
        Ok(rows > 0)
    }

    fn delete_namespace(&self, namespace: &Namespace) -> Result<bool, StorageError> {
        if namespace.as_str() == Namespace::DEFAULT {
            return Err(StorageError::InvalidOperation(
                "cannot delete the 'default' namespace".to_string(),
            ));
        }
        let conn = self.lock_conn()?;
        conn.execute(
            "DELETE FROM refs WHERE namespace = ?1",
            [namespace.as_str()],
        )
        .map_err(|e| StorageError::Backend(e.to_string()))?;
        let rows = conn
            .execute(
                "DELETE FROM namespaces WHERE name = ?1",
                [namespace.as_str()],
            )
            .map_err(|e| StorageError::Backend(e.to_string()))?;
        Ok(rows > 0)
    }
}

/// Store an object (`?1` id, `?2` data, `?3` now and `?4`
/// [`GC_FRESHEN_AFTER`], in milliseconds). An
/// object already stored keeps its row, but its write time is refreshed once
/// it is older than [`GC_FRESHEN_AFTER`], so a GC sweep's grace period covers
/// a write that dedups onto it.
const PUT_OBJECT: &str = "INSERT INTO objects (id, data, written_at) VALUES (?1, ?2, ?3) \
     ON CONFLICT(id) DO UPDATE SET written_at = excluded.written_at \
     WHERE objects.written_at < excluded.written_at - ?4";

fn freshen_after_millis() -> i64 {
    GC_FRESHEN_AFTER.as_millis() as i64
}

fn now_millis() -> i64 {
    chrono::Utc::now().timestamp_millis()
}

/// Max bound parameters per statement — well under SQLite's default
/// `SQLITE_MAX_VARIABLE_NUMBER` (999) so the GC bulk statements never overflow.
const GC_SQL_CHUNK: usize = 400;

/// Populate the disk-backed `gc_mark` temp table with every object reachable
/// from `roots` (Plan B t-001/t-003 marker), in bounded memory. Shared by the
/// reachability report and the sweep. On return, `gc_mark` holds exactly the
/// live closure (a subset of `objects`).
fn require_namespace(conn: &Connection, namespace: &Namespace) -> Result<(), StorageError> {
    let exists: bool = conn
        .query_row(
            "SELECT EXISTS(SELECT 1 FROM namespaces WHERE name = ?1)",
            params![namespace.as_str()],
            |row| row.get(0),
        )
        .map_err(|e| StorageError::Backend(format!("check namespace: {}", e)))?;
    if exists {
        Ok(())
    } else {
        Err(StorageError::NamespaceNotFound(
            namespace.as_str().to_string(),
        ))
    }
}

fn gc_build_mark(conn: &Connection, roots: &[ObjectId], batch: i64) -> Result<(), StorageError> {
    // The mark set lives on disk, not in RAM. `expanded` tracks the BFS
    // frontier: 0 = marked but children not yet followed.
    conn.execute_batch(
        "CREATE TEMP TABLE IF NOT EXISTS gc_mark (id BLOB PRIMARY KEY, expanded INTEGER NOT NULL DEFAULT 0); \
         CREATE INDEX IF NOT EXISTS gc_mark_expanded ON gc_mark(expanded); \
         DELETE FROM gc_mark;",
    )
    .map_err(|e| StorageError::Backend(format!("gc_mark init: {}", e)))?;

    // Seed roots — only those that exist as objects, so `gc_mark ⊆ objects`.
    for r in roots {
        conn.execute(
            "INSERT OR IGNORE INTO gc_mark (id, expanded) \
             SELECT id, 0 FROM objects WHERE id = ?1",
            params![r.as_bytes().as_slice()],
        )
        .map_err(|e| StorageError::Backend(format!("gc seed: {}", e)))?;
    }

    // Drain the frontier a batch at a time with set-based statements (JOIN
    // fetch, chunked multi-row insert of children, chunked IN-clause expand).
    loop {
        let frontier: Vec<(Vec<u8>, Option<Vec<u8>>)> = {
            let mut stmt = conn
                .prepare_cached(
                    "SELECT m.id, o.data FROM gc_mark m \
                     LEFT JOIN objects o ON o.id = m.id \
                     WHERE m.expanded = 0 LIMIT ?1",
                )
                .map_err(|e| StorageError::Backend(format!("gc frontier: {}", e)))?;
            let rows = stmt
                .query_map(params![batch], |row| {
                    Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, Option<Vec<u8>>>(1)?))
                })
                .map_err(|e| StorageError::Backend(format!("gc frontier q: {}", e)))?;
            let mut v = Vec::new();
            for r in rows {
                v.push(r.map_err(|e| StorageError::Backend(format!("gc frontier row: {}", e)))?);
            }
            v
        };
        if frontier.is_empty() {
            break;
        }
        let mut children: Vec<Vec<u8>> = Vec::new();
        let mut expand_ids: Vec<Vec<u8>> = Vec::with_capacity(frontier.len());
        for (id_bytes, data) in frontier {
            if let Some(data) = &data {
                let obj: Object = serde_json::from_slice(data)
                    .map_err(|e| StorageError::Serialization(e.to_string()))?;
                for child in child_ids(&obj) {
                    children.push(child.as_bytes().to_vec());
                }
            }
            expand_ids.push(id_bytes);
        }
        gc_in_tx(conn, "gc mark", |c| {
            bulk_insert_marks(c, &children)?;
            bulk_mark_expanded(c, &expand_ids)
        })?;
    }
    Ok(())
}

/// Run `f` as its own transaction, or inline when the connection is already
/// inside one.
///
/// A mutating sweep holds the write lock (`BEGIN IMMEDIATE`) from its keep-set
/// through its final delete. The batched helpers it shares with the read-only
/// reachability walk must join that transaction — SQLite rejects a nested
/// `BEGIN` — while the walk, which runs in autocommit mode, still gets a
/// transaction per batch as before.
fn gc_in_tx<T>(
    conn: &Connection,
    what: &str,
    f: impl FnOnce(&Connection) -> Result<T, StorageError>,
) -> Result<T, StorageError> {
    if !conn.is_autocommit() {
        return f(conn);
    }
    let tx = conn
        .unchecked_transaction()
        .map_err(|e| StorageError::Backend(format!("{what} tx: {e}")))?;
    let out = f(&tx)?;
    tx.commit()
        .map_err(|e| StorageError::Backend(format!("{what} commit: {e}")))?;
    Ok(out)
}

/// The state root of every ref tip, across every namespace, read on `conn` as
/// of now.
///
/// A sweep adds these to whatever keep-set its caller computed, under the write
/// lock. The caller's roots can predate a commit made on another connection;
/// these cannot. Live state is therefore never swept, whatever the caller did.
fn gc_live_tip_roots(conn: &Connection) -> Result<Vec<ObjectId>, StorageError> {
    let mut stmt = conn
        .prepare("SELECT c.data FROM refs r JOIN commits c ON c.id = r.target")
        .map_err(|e| StorageError::Backend(format!("gc tips read: {}", e)))?;
    let rows = stmt
        .query_map([], |row| row.get::<_, Vec<u8>>(0))
        .map_err(|e| StorageError::Backend(format!("gc tips query: {}", e)))?;
    let mut out = Vec::new();
    for r in rows {
        let data = r.map_err(|e| StorageError::Backend(format!("gc tip row: {}", e)))?;
        let commit: Commit = serde_json::from_slice(&data)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;
        out.push(commit.state_root);
    }
    Ok(out)
}

/// How long an open speculation's pin protects its objects without being
/// refreshed. Longer than any real speculation; a pin this old belongs to a
/// process that exited without committing or discarding.
const GC_PIN_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);

fn gc_pending_roots(
    conn: &Connection,
    max_age: std::time::Duration,
) -> Result<Vec<ObjectId>, StorageError> {
    let cutoff = chrono::Utc::now().timestamp() - max_age.as_secs() as i64;
    let mut stmt = conn
        .prepare("SELECT root FROM gc_pending_roots WHERE updated_at >= ?1")
        .map_err(|e| StorageError::Backend(format!("gc pinned roots: {}", e)))?;
    let rows = stmt
        .query_map(params![cutoff], |row| row.get::<_, Vec<u8>>(0))
        .map_err(|e| StorageError::Backend(format!("gc pinned roots: {}", e)))?;
    let mut out = Vec::new();
    for bytes in rows {
        let bytes = bytes.map_err(|e| StorageError::Backend(format!("gc pinned roots: {}", e)))?;
        out.extend(object_id_from_bytes(&bytes));
    }
    Ok(out)
}

/// The body of a sweep. The caller holds the write lock, so nothing can commit
/// between the mark and the last delete. Objects written within `grace` of
/// now are spared: a write that stored its tree before the lock was taken
/// commits it after the lock is released.
fn gc_sweep_locked(
    conn: &Connection,
    roots: &[ObjectId],
    batch: i64,
    grace: std::time::Duration,
) -> Result<GcSweep, StorageError> {
    let cutoff = now_millis().saturating_sub(i64::try_from(grace.as_millis()).unwrap_or(i64::MAX));
    let total_before: i64 = conn
        .query_row("SELECT COUNT(*) FROM objects", [], |row| row.get(0))
        .map_err(|e| StorageError::Backend(format!("gc sweep count: {}", e)))?;

    let mut roots = roots.to_vec();
    roots.extend(gc_live_tip_roots(conn)?);
    // Re-read under the lock, like the live tips: an open speculation in any
    // process pins the objects it has written but not yet committed.
    roots.extend(gc_pending_roots(conn, GC_PIN_MAX_AGE)?);

    // Mark the live closure, then materialize the dead set (objects not
    // reachable from the keep-set) into its own temp table — one anti-join
    // pass — so the batched DELETE never re-scans the live objects.
    gc_build_mark(conn, &roots, batch)?;
    conn.execute_batch(
        "CREATE TEMP TABLE IF NOT EXISTS gc_dead (id BLOB PRIMARY KEY); \
         DELETE FROM gc_dead;",
    )
    .map_err(|e| StorageError::Backend(format!("gc dead set: {}", e)))?;
    conn.execute(
        "INSERT INTO gc_dead (id) \
           SELECT o.id FROM objects o LEFT JOIN gc_mark m ON o.id = m.id \
           WHERE m.id IS NULL AND o.written_at < ?1",
        params![cutoff],
    )
    .map_err(|e| StorageError::Backend(format!("gc dead set: {}", e)))?;

    let deleted_target: i64 = conn
        .query_row("SELECT COUNT(*) FROM gc_dead", [], |row| row.get(0))
        .map_err(|e| StorageError::Backend(format!("gc dead count: {}", e)))?;

    // Delete in bounded chunks so no single statement grows with the store.
    // They all belong to the caller's transaction: a crash rolls the whole
    // sweep back rather than leaving it half done.
    let mut deleted = 0i64;
    loop {
        let dead: Vec<Vec<u8>> = {
            let mut stmt = conn
                .prepare_cached("SELECT id FROM gc_dead LIMIT ?1")
                .map_err(|e| StorageError::Backend(format!("gc dead sel: {}", e)))?;
            let rows = stmt
                .query_map(params![batch], |row| row.get::<_, Vec<u8>>(0))
                .map_err(|e| StorageError::Backend(format!("gc dead q: {}", e)))?;
            let mut v = Vec::new();
            for r in rows {
                v.push(r.map_err(|e| StorageError::Backend(format!("gc dead row: {}", e)))?);
            }
            v
        };
        if dead.is_empty() {
            break;
        }
        gc_bulk_delete(conn, "objects", &dead)?;
        gc_bulk_delete(conn, "gc_dead", &dead)?;
        deleted += dead.len() as i64;
    }

    conn.execute("DELETE FROM gc_mark", [])
        .map_err(|e| StorageError::Backend(format!("gc mark cleanup: {}", e)))?;

    let total_after: i64 = conn
        .query_row("SELECT COUNT(*) FROM objects", [], |row| row.get(0))
        .map_err(|e| StorageError::Backend(format!("gc after count: {}", e)))?;

    Ok(GcSweep {
        objects_before: total_before,
        objects_deleted: deleted,
        objects_after: total_after,
        deleted_target,
    })
}

/// Bulk `DELETE FROM <table> WHERE id IN (...)` in [`GC_SQL_CHUNK`] chunks.
/// `table` is a fixed internal identifier (never user input).
fn gc_bulk_delete(tx: &Connection, table: &str, ids: &[Vec<u8>]) -> Result<(), StorageError> {
    for chunk in ids.chunks(GC_SQL_CHUNK) {
        let mut sql = format!("DELETE FROM {} WHERE id IN (", table);
        for i in 0..chunk.len() {
            if i > 0 {
                sql.push(',');
            }
            sql.push('?');
        }
        sql.push(')');
        tx.execute(
            &sql,
            rusqlite::params_from_iter(chunk.iter().map(|b| b.as_slice())),
        )
        .map_err(|e| StorageError::Backend(format!("gc bulk delete {}: {}", table, e)))?;
    }
    Ok(())
}

/// Bulk `INSERT OR IGNORE` the given ids into `gc_mark` (expanded=0), in chunks
/// of [`GC_SQL_CHUNK`] via multi-row VALUES — one statement per chunk instead of
/// one per id.
fn bulk_insert_marks(tx: &Connection, ids: &[Vec<u8>]) -> Result<(), StorageError> {
    for chunk in ids.chunks(GC_SQL_CHUNK) {
        let mut sql = String::from("INSERT OR IGNORE INTO gc_mark (id, expanded) VALUES ");
        for i in 0..chunk.len() {
            if i > 0 {
                sql.push(',');
            }
            sql.push_str("(?, 0)");
        }
        tx.execute(
            &sql,
            rusqlite::params_from_iter(chunk.iter().map(|b| b.as_slice())),
        )
        .map_err(|e| StorageError::Backend(format!("gc bulk insert: {}", e)))?;
    }
    Ok(())
}

/// Bulk `UPDATE gc_mark SET expanded = 1` for the given ids, in chunks of
/// [`GC_SQL_CHUNK`] via an `IN (...)` clause.
fn bulk_mark_expanded(tx: &Connection, ids: &[Vec<u8>]) -> Result<(), StorageError> {
    for chunk in ids.chunks(GC_SQL_CHUNK) {
        let mut sql = String::from("UPDATE gc_mark SET expanded = 1 WHERE id IN (");
        for i in 0..chunk.len() {
            if i > 0 {
                sql.push(',');
            }
            sql.push('?');
        }
        sql.push(')');
        tx.execute(
            &sql,
            rusqlite::params_from_iter(chunk.iter().map(|b| b.as_slice())),
        )
        .map_err(|e| StorageError::Backend(format!("gc bulk expand: {}", e)))?;
    }
    Ok(())
}

/// The child object ids a node references (empty for atoms). The DAG edges the
/// GC reachability mark follows.
fn child_ids(obj: &Object) -> Vec<ObjectId> {
    match obj {
        Object::Node(Node::Map(entries)) => entries.values().copied().collect(),
        Object::Node(Node::List(items)) | Object::Node(Node::Set(items)) => items.clone(),
        Object::Atom(_) => Vec::new(),
    }
}

/// Decode a 32-byte blob into an `ObjectId`, or `None` if the length is wrong
/// (e.g. a NULL/short `state_root` on a pre-t-005 milestone row).
fn object_id_from_bytes(bytes: &[u8]) -> Option<ObjectId> {
    if bytes.len() != 32 {
        return None;
    }
    let mut arr = [0u8; 32];
    arr.copy_from_slice(bytes);
    Some(ObjectId::from_bytes(arr))
}

fn epoch_status_str(s: &EpochStatus) -> &'static str {
    match s {
        EpochStatus::Active => "Active",
        EpochStatus::Sealed => "Sealed",
        EpochStatus::Archived => "Archived",
    }
}

fn parse_epoch_status(s: &str) -> EpochStatus {
    match s {
        "Sealed" => EpochStatus::Sealed,
        "Archived" => EpochStatus::Archived,
        _ => EpochStatus::Active,
    }
}

fn parse_rfc3339(s: &str) -> Result<DateTime<Utc>, StorageError> {
    DateTime::parse_from_rfc3339(s)
        .map(|dt| dt.with_timezone(&Utc))
        .map_err(|e| StorageError::Serialization(format!("timestamp parse: {}", e)))
}

#[allow(clippy::too_many_arguments)]
fn row_to_epoch(
    id: String,
    description: String,
    status: String,
    created_at: String,
    sealed_at: Option<String>,
    summary: Option<String>,
    root_intents: String,
    agents: String,
    tags: String,
    sealed_commits: String,
    seal_hash: Option<Vec<u8>>,
    namespace: Option<String>,
    scope: Option<String>,
) -> Result<Epoch, StorageError> {
    let root_intents: Vec<String> = serde_json::from_str(&root_intents)
        .map_err(|e| StorageError::Serialization(format!("root_intents: {}", e)))?;
    let agents: Vec<String> = serde_json::from_str(&agents)
        .map_err(|e| StorageError::Serialization(format!("agents: {}", e)))?;
    let tags: Vec<String> = serde_json::from_str(&tags)
        .map_err(|e| StorageError::Serialization(format!("tags: {}", e)))?;
    let sealed_commits: Vec<ObjectId> = serde_json::from_str(&sealed_commits)
        .map_err(|e| StorageError::Serialization(format!("sealed_commits: {}", e)))?;

    Ok(Epoch {
        id,
        description,
        root_intents,
        status: parse_epoch_status(&status),
        created_at: parse_rfc3339(&created_at)?,
        sealed_at: sealed_at.as_deref().map(parse_rfc3339).transpose()?,
        seal_summary: summary,
        // A 32-byte BLOB or nothing; a short/corrupt value is treated as absent
        // rather than failing the whole read.
        seal_hash: seal_hash.and_then(|b| {
            <[u8; 32]>::try_from(b.as_slice())
                .ok()
                .map(ObjectId::from_bytes)
        }),
        commits: Vec::new(),
        agents,
        branches: Vec::new(),
        scope: scope
            .as_deref()
            .map(EpochScope::from_storage_str)
            .unwrap_or_default(),
        namespace,
        tags,
        sealed_commits,
    })
}

impl EpochStore for SqliteStorage {
    fn create_epoch(&self, epoch: &Epoch) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        let root_intents = serde_json::to_string(&epoch.root_intents)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;
        let agents = serde_json::to_string(&epoch.agents)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;
        let tags = serde_json::to_string(&epoch.tags)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;
        let sealed_commits = serde_json::to_string(&epoch.sealed_commits)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;
        conn.execute(
            "INSERT INTO epochs
             (id, description, status, created_at, sealed_at, summary,
              root_intents, agents, tags, commit_count, sealed_commits,
              namespace, scope)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
            params![
                epoch.id,
                epoch.description,
                epoch_status_str(&epoch.status),
                epoch.created_at.to_rfc3339(),
                epoch.sealed_at.map(|t| t.to_rfc3339()),
                epoch.seal_summary,
                root_intents,
                agents,
                tags,
                epoch.commits.len() as i64,
                sealed_commits,
                epoch.namespace,
                epoch.scope.as_storage_str(),
            ],
        )
        .map_err(|e| StorageError::Backend(format!("create epoch: {}", e)))?;
        Ok(())
    }

    fn seal_epoch(
        &self,
        id: &str,
        summary: &str,
        sealed_at: DateTime<Utc>,
        sealed_commits: &[ObjectId],
        seal_hash: &ObjectId,
    ) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        let sc_json = serde_json::to_string(sealed_commits)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;
        // One conditional UPDATE. A status check followed by a separate write
        // let every process racing to seal one epoch "win", each overwriting
        // the last one's sealed commits and digest.
        let sealed = conn
            .execute(
                // commit_count is set here too: it was written once at create
                // time from the then-empty commit list and never updated, so a
                // sealed epoch reported 0 for work it demonstrably covered.
                "UPDATE epochs
                 SET status = 'Sealed', sealed_at = ?1, summary = ?2, sealed_commits = ?3,
                     seal_hash = ?4, commit_count = ?5
                 WHERE id = ?6 AND status NOT IN ('Sealed', 'Archived')",
                params![
                    sealed_at.to_rfc3339(),
                    summary,
                    sc_json,
                    seal_hash.as_bytes().to_vec(),
                    sealed_commits.len() as i64,
                    id
                ],
            )
            .map_err(|e| StorageError::Backend(format!("seal epoch: {}", e)))?;
        if sealed > 0 {
            return Ok(());
        }
        let exists: Option<i64> = conn
            .query_row("SELECT 1 FROM epochs WHERE id = ?1", params![id], |row| {
                row.get(0)
            })
            .optional()
            .map_err(|e| StorageError::Backend(format!("seal lookup: {}", e)))?;
        match exists {
            Some(_) => Err(StorageError::EpochAlreadySealed { id: id.to_string() }),
            None => Err(StorageError::Backend(format!("epoch not found: {}", id))),
        }
    }

    fn assign_epoch_namespace(&self, id: &str, namespace: &str) -> Result<bool, StorageError> {
        let conn = self.lock_conn()?;
        // `namespace IS NULL` in the predicate is what makes this assign-only:
        // an epoch that already has an owner is left untouched and reports
        // false, so this can never move an epoch between workspaces.
        let changed = conn
            .execute(
                "UPDATE epochs SET namespace = ?1 WHERE id = ?2 AND namespace IS NULL",
                params![namespace, id],
            )
            .map_err(|e| StorageError::Backend(format!("assign epoch namespace: {}", e)))?;
        if changed > 0 {
            return Ok(true);
        }
        // Distinguish "already assigned" from "no such epoch" — a caller
        // backfilling a known id wants to hear about a typo, not a silent false.
        let exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM epochs WHERE id = ?1)",
                params![id],
                |row| row.get(0),
            )
            .map_err(|e| StorageError::Backend(format!("assign epoch lookup: {}", e)))?;
        if exists {
            Ok(false)
        } else {
            Err(StorageError::Backend(format!("epoch not found: {}", id)))
        }
    }

    fn list_epochs(&self) -> Result<Vec<Epoch>, StorageError> {
        let conn = self.lock_conn()?;
        let mut stmt = conn
            .prepare(
                "SELECT id, description, status, created_at, sealed_at, summary,
                        root_intents, agents, tags, sealed_commits,
                        seal_hash, namespace, scope
                 FROM epochs ORDER BY created_at DESC",
            )
            .map_err(|e| StorageError::Backend(format!("list epochs prep: {}", e)))?;
        let rows = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                    row.get::<_, Option<String>>(4)?,
                    row.get::<_, Option<String>>(5)?,
                    row.get::<_, String>(6)?,
                    row.get::<_, String>(7)?,
                    row.get::<_, String>(8)?,
                    row.get::<_, String>(9)?,
                    row.get::<_, Option<Vec<u8>>>(10)?,
                    row.get::<_, Option<String>>(11)?,
                    row.get::<_, Option<String>>(12)?,
                ))
            })
            .map_err(|e| StorageError::Backend(format!("list epochs query: {}", e)))?;
        let mut out = Vec::new();
        for r in rows {
            let (id, desc, status, created_at, sealed_at, summary, ri, ag, tg, sc, sh, ns, scp) =
                r.map_err(|e| StorageError::Backend(format!("list epochs row: {}", e)))?;
            out.push(row_to_epoch(
                id, desc, status, created_at, sealed_at, summary, ri, ag, tg, sc, sh, ns, scp,
            )?);
        }
        Ok(out)
    }

    fn get_epoch(&self, id: &str) -> Result<Option<Epoch>, StorageError> {
        let conn = self.lock_conn()?;
        type EpochRow = (
            String,
            String,
            String,
            String,
            Option<String>,
            Option<String>,
            String,
            String,
            String,
            String,
            Option<Vec<u8>>,
            Option<String>,
            Option<String>,
        );
        let row: Option<EpochRow> = conn
            .query_row(
                "SELECT id, description, status, created_at, sealed_at, summary,
                        root_intents, agents, tags, sealed_commits,
                        seal_hash, namespace, scope
                 FROM epochs WHERE id = ?1",
                params![id],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                        row.get(5)?,
                        row.get(6)?,
                        row.get(7)?,
                        row.get(8)?,
                        row.get(9)?,
                        row.get(10)?,
                        row.get(11)?,
                        row.get(12)?,
                    ))
                },
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("get epoch: {}", e)))?;
        match row {
            None => Ok(None),
            Some((
                id,
                desc,
                status,
                created_at,
                sealed_at,
                summary,
                ri,
                ag,
                tg,
                sc,
                sh,
                ns,
                scp,
            )) => {
                let mut epoch = row_to_epoch(
                    id, desc, status, created_at, sealed_at, summary, ri, ag, tg, sc, sh, ns, scp,
                )?;
                // Rehydrate commits list from the commits table.
                let mut stmt = conn
                    .prepare("SELECT id FROM commits WHERE epoch_id = ?1 ORDER BY rowid")
                    .map_err(|e| StorageError::Backend(format!("prepare epoch commits: {}", e)))?;
                let commit_ids: Vec<ObjectId> = stmt
                    .query_map(params![epoch.id], |row| {
                        let bytes: Vec<u8> = row.get(0)?;
                        Ok(bytes)
                    })
                    .map_err(|e| StorageError::Backend(format!("query epoch commits: {}", e)))?
                    .filter_map(|r| r.ok())
                    .filter_map(|b| {
                        if b.len() == 32 {
                            let mut arr = [0u8; 32];
                            arr.copy_from_slice(&b);
                            Some(ObjectId::from_bytes(arr))
                        } else {
                            None
                        }
                    })
                    .collect();
                epoch.commits = commit_ids;
                Ok(Some(epoch))
            }
        }
    }

    fn archive_epoch(&self, id: &str) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        let rows = conn
            .execute(
                "UPDATE epochs SET status = 'Archived' WHERE id = ?1 AND status = 'Sealed'",
                params![id],
            )
            .map_err(|e| StorageError::Backend(format!("archive epoch: {}", e)))?;
        if rows == 0 {
            return Err(StorageError::Backend(format!(
                "epoch '{}' not found or not sealed",
                id
            )));
        }
        Ok(())
    }

    fn set_commit_epoch(&self, commit_id: &ObjectId, epoch_id: &str) -> Result<(), StorageError> {
        let mut conn = self.lock_conn()?;
        // One write transaction, so a seal from another process can't land
        // between the status check and the association.
        let conn = conn
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(|e| StorageError::Backend(format!("begin assoc: {}", e)))?;
        let status: Option<String> = conn
            .query_row(
                "SELECT status FROM epochs WHERE id = ?1",
                params![epoch_id],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("assoc lookup: {}", e)))?;
        match status.as_deref() {
            None => {
                return Err(StorageError::Backend(format!(
                    "epoch not found: {}",
                    epoch_id
                )));
            }
            Some("Sealed") | Some("Archived") => {
                return Err(StorageError::EpochAlreadySealed {
                    id: epoch_id.to_string(),
                });
            }
            _ => {}
        }
        let joined = conn
            .execute(
                "UPDATE commits SET epoch_id = ?1
                 WHERE id = ?2 AND epoch_id IS NOT ?1",
                params![epoch_id, commit_id.as_bytes().as_slice()],
            )
            .map_err(|e| StorageError::Backend(format!("set commit epoch: {}", e)))?;
        // A running count, bumped only when the commit actually joins; the old
        // COUNT(*) per commit grew with the epoch. Sealing writes the exact count.
        if joined > 0 {
            conn.execute(
                "UPDATE epochs SET commit_count = commit_count + 1 WHERE id = ?1",
                params![epoch_id],
            )
            .map_err(|e| StorageError::Backend(format!("update commit_count: {}", e)))?;
        }
        conn.commit()
            .map_err(|e| StorageError::Backend(format!("commit assoc: {}", e)))?;
        Ok(())
    }
}

#[allow(clippy::too_many_arguments)]
fn row_to_session(
    id: String,
    agent_id: String,
    parent_id: Option<String>,
    scope_path: Option<String>,
    scope_branch: Option<String>,
    scope_namespace: Option<String>,
    status: String,
    created_at: String,
    ended_at: Option<String>,
    metadata: String,
) -> Result<Session, StorageError> {
    // The `metadata` JSON blob carries fields the Session struct has
    // but the schema doesn't surface as dedicated columns
    // (working_branch's full path, head object id, delegated_intent,
    // report_to). Parse it back; default missing pieces defensively.
    #[derive(serde::Deserialize, Default)]
    struct Meta {
        #[serde(default)]
        head: Option<ObjectId>,
        #[serde(default)]
        delegated_intent: Option<String>,
        #[serde(default)]
        report_to: Option<String>,
        #[serde(default)]
        working_branch: Option<String>,
        #[serde(default)]
        scope_tenant: Option<String>,
    }
    let meta: Meta = serde_json::from_str(&metadata).unwrap_or_default();
    let head = meta.head.unwrap_or_else(|| ObjectId::hash(b""));
    let working_branch = meta
        .working_branch
        .unwrap_or_else(|| scope_branch.clone().unwrap_or_default());
    Ok(Session {
        id,
        agent_id,
        working_branch,
        head,
        parent_session: parent_id,
        delegated_intent: meta.delegated_intent,
        report_to: meta.report_to,
        path_scope: scope_path,
        scope_tenant: meta.scope_tenant,
        scope_namespace: scope_namespace
            .as_deref()
            .and_then(|s| Namespace::new(s).ok()),
        status: SessionStatus::from_wire(&status),
        created_at: parse_rfc3339(&created_at)?,
        ended_at: ended_at.as_deref().map(parse_rfc3339).transpose()?,
    })
}

impl SessionStore for SqliteStorage {
    fn create_session(&self, session: &Session) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        let metadata = serde_json::json!({
            "head": session.head,
            "delegated_intent": session.delegated_intent,
            "report_to": session.report_to,
            "working_branch": session.working_branch,
            "scope_tenant": session.scope_tenant,
        })
        .to_string();
        conn.execute(
            "INSERT OR REPLACE INTO sessions
             (id, agent_id, parent_id, scope_path, scope_branch, scope_namespace,
              status, created_at, ended_at, metadata, commit_count)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10,
                     COALESCE((SELECT commit_count FROM sessions WHERE id = ?1), 0))",
            params![
                session.id,
                session.agent_id,
                session.parent_session,
                session.path_scope,
                session.working_branch,
                session.scope_namespace.as_ref().map(|n| n.as_str()),
                session.status.as_str(),
                session.created_at.to_rfc3339(),
                session.ended_at.map(|t| t.to_rfc3339()),
                metadata,
            ],
        )
        .map_err(|e| StorageError::Backend(format!("create session: {}", e)))?;
        Ok(())
    }

    fn end_session(
        &self,
        id: &str,
        status: SessionStatus,
        ended_at: DateTime<Utc>,
    ) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        // One conditional UPDATE: a status check followed by a separate write
        // let several processes all "end" the same session.
        let ended = conn
            .execute(
                "UPDATE sessions SET status = ?1, ended_at = ?2
                 WHERE id = ?3 AND status = 'Active'",
                params![status.as_str(), ended_at.to_rfc3339(), id],
            )
            .map_err(|e| StorageError::Backend(format!("end session: {}", e)))?;
        if ended > 0 {
            return Ok(());
        }
        let exists: Option<i64> = conn
            .query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |row| {
                row.get(0)
            })
            .optional()
            .map_err(|e| StorageError::Backend(format!("end session lookup: {}", e)))?;
        match exists {
            Some(_) => Err(StorageError::SessionEnded { id: id.to_string() }),
            None => Err(StorageError::Backend(format!("session not found: {}", id))),
        }
    }

    fn list_sessions(&self, agent_filter: Option<&str>) -> Result<Vec<Session>, StorageError> {
        let conn = self.lock_conn()?;
        let mut stmt = conn
            .prepare(
                "SELECT id, agent_id, parent_id, scope_path, scope_branch, scope_namespace,
                        status, created_at, ended_at, metadata
                 FROM sessions
                 WHERE (?1 IS NULL OR agent_id = ?1)
                 ORDER BY created_at DESC",
            )
            .map_err(|e| StorageError::Backend(format!("list sessions prep: {}", e)))?;
        let rows = stmt
            .query_map(params![agent_filter], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, Option<String>>(2)?,
                    row.get::<_, Option<String>>(3)?,
                    row.get::<_, Option<String>>(4)?,
                    row.get::<_, Option<String>>(5)?,
                    row.get::<_, String>(6)?,
                    row.get::<_, String>(7)?,
                    row.get::<_, Option<String>>(8)?,
                    row.get::<_, String>(9)?,
                ))
            })
            .map_err(|e| StorageError::Backend(format!("list sessions query: {}", e)))?;
        let mut out = Vec::new();
        for r in rows {
            let (id, agent, parent, sp, sb, sns, st, ca, ea, md) =
                r.map_err(|e| StorageError::Backend(format!("list sessions row: {}", e)))?;
            out.push(row_to_session(
                id, agent, parent, sp, sb, sns, st, ca, ea, md,
            )?);
        }
        Ok(out)
    }

    fn get_session(&self, id: &str) -> Result<Option<Session>, StorageError> {
        let conn = self.lock_conn()?;
        type SessionRow = (
            String,
            String,
            Option<String>,
            Option<String>,
            Option<String>,
            Option<String>,
            String,
            String,
            Option<String>,
            String,
        );
        let row: Option<SessionRow> = conn
            .query_row(
                "SELECT id, agent_id, parent_id, scope_path, scope_branch, scope_namespace,
                        status, created_at, ended_at, metadata
                 FROM sessions WHERE id = ?1",
                params![id],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                        row.get(5)?,
                        row.get(6)?,
                        row.get(7)?,
                        row.get(8)?,
                        row.get(9)?,
                    ))
                },
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("get session: {}", e)))?;
        match row {
            None => Ok(None),
            Some((id, agent, parent, sp, sb, sns, st, ca, ea, md)) => Ok(Some(row_to_session(
                id, agent, parent, sp, sb, sns, st, ca, ea, md,
            )?)),
        }
    }

    fn set_commit_session(
        &self,
        commit_id: &ObjectId,
        session_id: &str,
    ) -> Result<(), StorageError> {
        let mut conn = self.lock_conn()?;
        // As set_commit_epoch: one write transaction, so ending the session
        // from another process can't land between the check and the write.
        let conn = conn
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(|e| StorageError::Backend(format!("begin assoc: {}", e)))?;
        let status: Option<String> = conn
            .query_row(
                "SELECT status FROM sessions WHERE id = ?1",
                params![session_id],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("assoc lookup: {}", e)))?;
        match status.as_deref() {
            None => {
                return Err(StorageError::Backend(format!(
                    "session not found: {}",
                    session_id
                )));
            }
            Some(s) if s != "Active" => {
                return Err(StorageError::SessionEnded {
                    id: session_id.to_string(),
                });
            }
            _ => {}
        }
        let joined = conn
            .execute(
                "UPDATE commits SET session_id = ?1
                 WHERE id = ?2 AND session_id IS NOT ?1",
                params![session_id, commit_id.as_bytes().as_slice()],
            )
            .map_err(|e| StorageError::Backend(format!("set commit session: {}", e)))?;
        if joined > 0 {
            conn.execute(
                "UPDATE sessions SET commit_count = commit_count + 1 WHERE id = ?1",
                params![session_id],
            )
            .map_err(|e| StorageError::Backend(format!("update session commit_count: {}", e)))?;
        }
        conn.commit()
            .map_err(|e| StorageError::Backend(format!("commit assoc: {}", e)))?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// TaintStore (0.7.75 §3)
// ---------------------------------------------------------------------------

fn kind_to_str(k: TaintKind) -> &'static str {
    match k {
        TaintKind::Taint => "taint",
        TaintKind::Quarantine => "quarantine",
        TaintKind::Watch => "watch",
    }
}

fn kind_from_str(s: &str) -> Result<TaintKind, StorageError> {
    match s {
        "taint" => Ok(TaintKind::Taint),
        "quarantine" => Ok(TaintKind::Quarantine),
        "watch" => Ok(TaintKind::Watch),
        other => Err(StorageError::Backend(format!(
            "unknown taint kind: {other}"
        ))),
    }
}

fn effect_to_str(e: TaintEffect) -> &'static str {
    match e {
        TaintEffect::Warn => "warn",
        TaintEffect::Block => "block",
        TaintEffect::Review => "review",
        TaintEffect::Isolate => "isolate",
        TaintEffect::Advisory => "advisory",
    }
}

fn effect_from_str(s: &str) -> Result<TaintEffect, StorageError> {
    match s {
        "warn" => Ok(TaintEffect::Warn),
        "block" => Ok(TaintEffect::Block),
        "review" => Ok(TaintEffect::Review),
        "isolate" => Ok(TaintEffect::Isolate),
        "advisory" => Ok(TaintEffect::Advisory),
        other => Err(StorageError::Backend(format!(
            "unknown taint effect: {other}"
        ))),
    }
}

fn severity_to_str(s: TaintSeverity) -> &'static str {
    match s {
        TaintSeverity::Low => "low",
        TaintSeverity::Medium => "medium",
        TaintSeverity::High => "high",
        TaintSeverity::Critical => "critical",
    }
}

fn severity_from_str(s: &str) -> Result<TaintSeverity, StorageError> {
    match s {
        "low" => Ok(TaintSeverity::Low),
        "medium" => Ok(TaintSeverity::Medium),
        "high" => Ok(TaintSeverity::High),
        "critical" => Ok(TaintSeverity::Critical),
        other => Err(StorageError::Backend(format!(
            "unknown taint severity: {other}"
        ))),
    }
}

/// Row extraction returns `rusqlite::Error` so the closure fits
/// `query_map` / `query_row` signatures. Decode-side parsing errors
/// (serde, chrono) are remapped to
/// `rusqlite::Error::FromSqlConversionFailure` so callers see them
/// as backend errors; all cases are converted to `StorageError` in
/// the calling impls via `map_err`.
fn row_to_taint(row: &Row<'_>) -> rusqlite::Result<Taint> {
    use rusqlite::types::{FromSqlError, Type};

    fn decode_err<E: std::fmt::Display>(col: usize, ty: Type, e: E) -> rusqlite::Error {
        rusqlite::Error::FromSqlConversionFailure(
            col,
            ty,
            Box::new(FromSqlError::Other(format!("{e}").into())),
        )
    }

    let kind: String = row.get("kind")?;
    let effect: String = row.get("effect")?;
    let severity: String = row.get("severity")?;
    let metadata_raw: String = row.get("metadata")?;
    let created_at_s: String = row.get("created_at")?;
    let expires_at_s: Option<String> = row.get("expires_at")?;
    let resolved_at_s: Option<String> = row.get("resolved_at")?;

    let metadata: TaintMetadata = serde_json::from_str(&metadata_raw)
        .map_err(|e| decode_err(0, Type::Text, format!("taint metadata: {e}")))?;
    let created_at = DateTime::parse_from_rfc3339(&created_at_s)
        .map_err(|e| decode_err(0, Type::Text, format!("created_at: {e}")))?
        .with_timezone(&Utc);
    let expires_at = match expires_at_s {
        Some(s) => Some(
            DateTime::parse_from_rfc3339(&s)
                .map_err(|e| decode_err(0, Type::Text, format!("expires_at: {e}")))?
                .with_timezone(&Utc),
        ),
        None => None,
    };
    let resolved_at = match resolved_at_s {
        Some(s) => Some(
            DateTime::parse_from_rfc3339(&s)
                .map_err(|e| decode_err(0, Type::Text, format!("resolved_at: {e}")))?
                .with_timezone(&Utc),
        ),
        None => None,
    };
    let kind = kind_from_str(&kind).map_err(|e| decode_err(0, Type::Text, e.to_string()))?;
    let effect = effect_from_str(&effect).map_err(|e| decode_err(0, Type::Text, e.to_string()))?;
    let severity =
        severity_from_str(&severity).map_err(|e| decode_err(0, Type::Text, e.to_string()))?;

    Ok(Taint {
        id: row.get("id")?,
        path: row.get("path")?,
        name: row.get("name")?,
        kind,
        effect,
        severity,
        reason: row.get("reason")?,
        agent_id: row.get("agent_id")?,
        commit_id: row.get("commit_id")?,
        created_at,
        expires_at,
        resolved_at,
        resolved_by: row.get("resolved_by")?,
        resolved_reason: row.get("resolved_reason")?,
        resolved_proof: row.get("resolved_proof")?,
        propagate: row.get::<_, i64>("propagate")? != 0,
        metadata,
    })
}

impl TaintStore for SqliteStorage {
    fn create_taint(&self, taint: &Taint) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        let metadata_json = serde_json::to_string(&taint.metadata)
            .map_err(|e| StorageError::Serialization(format!("taint metadata: {e}")))?;
        conn.execute(
            "INSERT INTO taints (
                id, path, name, kind, effect, severity, reason, agent_id,
                commit_id, created_at, expires_at, resolved_at, resolved_by,
                resolved_reason, resolved_proof, propagate, metadata
            ) VALUES (
                ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8,
                ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17
            )",
            params![
                taint.id,
                taint.path,
                taint.name,
                kind_to_str(taint.kind),
                effect_to_str(taint.effect),
                severity_to_str(taint.severity),
                taint.reason,
                taint.agent_id,
                taint.commit_id,
                taint.created_at.to_rfc3339(),
                taint.expires_at.map(|t| t.to_rfc3339()),
                taint.resolved_at.map(|t| t.to_rfc3339()),
                taint.resolved_by,
                taint.resolved_reason,
                taint.resolved_proof,
                if taint.propagate { 1_i64 } else { 0_i64 },
                metadata_json,
            ],
        )
        .map_err(|e| StorageError::Backend(format!("insert taint: {e}")))?;
        Ok(())
    }

    fn resolve_taint(
        &self,
        id: &str,
        resolved_by: &str,
        reason: &str,
        proof: Option<&str>,
        resolved_at: DateTime<Utc>,
    ) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        // Guard: fail on already-resolved.
        let already: Option<String> = conn
            .query_row(
                "SELECT resolved_at FROM taints WHERE id = ?1",
                params![id],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| StorageError::Backend(format!("resolve check: {e}")))?
            .ok_or_else(|| StorageError::Backend(format!("taint {id} not found")))?;
        if already.is_some() {
            return Err(StorageError::Backend(format!(
                "taint {id} is already resolved"
            )));
        }
        conn.execute(
            "UPDATE taints SET resolved_at = ?1, resolved_by = ?2,
                resolved_reason = ?3, resolved_proof = ?4
             WHERE id = ?5",
            params![resolved_at.to_rfc3339(), resolved_by, reason, proof, id],
        )
        .map_err(|e| StorageError::Backend(format!("resolve taint: {e}")))?;
        Ok(())
    }

    fn list_taints(
        &self,
        path_prefix: Option<&str>,
        kind: Option<TaintKind>,
        include_resolved: bool,
    ) -> Result<Vec<Taint>, StorageError> {
        let conn = self.lock_conn()?;
        let mut sql = String::from("SELECT * FROM taints WHERE 1=1");
        if !include_resolved {
            sql.push_str(" AND resolved_at IS NULL");
        }
        if let Some(_p) = path_prefix {
            sql.push_str(" AND (path = :p OR path LIKE :plike)");
        }
        if kind.is_some() {
            sql.push_str(" AND kind = :k");
        }
        sql.push_str(" ORDER BY created_at DESC");
        let mut stmt = conn
            .prepare(&sql)
            .map_err(|e| StorageError::Backend(format!("list taints prep: {e}")))?;
        let mut params_named: Vec<(&str, Box<dyn rusqlite::ToSql>)> = Vec::new();
        let plike;
        if let Some(p) = path_prefix {
            let p = p.trim_end_matches('/');
            plike = format!("{}/%", p);
            params_named.push((":p", Box::new(p.to_string())));
            params_named.push((":plike", Box::new(plike.clone())));
        }
        if let Some(k) = kind {
            params_named.push((":k", Box::new(kind_to_str(k).to_string())));
        }
        let refs: Vec<(&str, &dyn rusqlite::ToSql)> =
            params_named.iter().map(|(n, v)| (*n, v.as_ref())).collect();
        let rows = stmt
            .query_map(refs.as_slice(), row_to_taint)
            .map_err(|e| StorageError::Backend(format!("list taints query: {e}")))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(r.map_err(|e| StorageError::Backend(format!("list taints row: {e}")))?);
        }
        Ok(out)
    }

    fn check_taint(&self, request_path: &str) -> Result<Vec<Taint>, StorageError> {
        let conn = self.lock_conn()?;
        let now = Utc::now().to_rfc3339();
        // Ancestor match: exact OR (propagate=1 AND request_path LIKE
        // path || '/%'). SQLite LIKE is case-sensitive by default
        // which matches our path semantics.
        let mut stmt = conn
            .prepare(
                "SELECT * FROM taints
                 WHERE resolved_at IS NULL
                   AND (expires_at IS NULL OR expires_at > :now)
                   AND (path = :path
                        OR (propagate = 1 AND :path LIKE path || '/%'))
                 ORDER BY created_at DESC",
            )
            .map_err(|e| StorageError::Backend(format!("check_taint prep: {e}")))?;
        let rows = stmt
            .query_map(
                &[
                    (":now", &now as &dyn rusqlite::ToSql),
                    (":path", &request_path),
                ],
                row_to_taint,
            )
            .map_err(|e| StorageError::Backend(format!("check_taint query: {e}")))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(r.map_err(|e| StorageError::Backend(format!("check_taint row: {e}")))?);
        }
        Ok(out)
    }

    fn get_taint(&self, id: &str) -> Result<Option<Taint>, StorageError> {
        let conn = self.lock_conn()?;
        let mut stmt = conn
            .prepare("SELECT * FROM taints WHERE id = ?1")
            .map_err(|e| StorageError::Backend(format!("get_taint prep: {e}")))?;
        let t = stmt
            .query_row(params![id], row_to_taint)
            .optional()
            .map_err(|e| StorageError::Backend(format!("get_taint: {e}")))?;
        Ok(t)
    }

    fn set_taint_commit_id(&self, id: &str, commit_id: &str) -> Result<(), StorageError> {
        let conn = self.lock_conn()?;
        conn.execute(
            "UPDATE taints SET commit_id = ?1 WHERE id = ?2 AND resolved_at IS NULL",
            params![commit_id, id],
        )
        .map_err(|e| StorageError::Backend(format!("set_taint_commit_id: {e}")))?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// ReminderStore — durable SQLite reminder storage
// ---------------------------------------------------------------------------

fn reminder_status_to_str(s: ReminderStatus) -> &'static str {
    match s {
        ReminderStatus::Pending => "pending",
        ReminderStatus::Due => "due",
        ReminderStatus::AwaitingPermission => "awaiting_permission",
        ReminderStatus::InProgress => "in_progress",
        ReminderStatus::Completed => "completed",
        ReminderStatus::Snoozed => "snoozed",
        ReminderStatus::Cancelled => "cancelled",
    }
}

fn reminder_status_from_str(s: &str) -> Result<ReminderStatus, ReminderError> {
    match s {
        "pending" => Ok(ReminderStatus::Pending),
        "due" => Ok(ReminderStatus::Due),
        "awaiting_permission" => Ok(ReminderStatus::AwaitingPermission),
        "in_progress" => Ok(ReminderStatus::InProgress),
        "completed" => Ok(ReminderStatus::Completed),
        "snoozed" => Ok(ReminderStatus::Snoozed),
        "cancelled" => Ok(ReminderStatus::Cancelled),
        other => Err(ReminderError::Store(format!(
            "unknown reminder status: {other}"
        ))),
    }
}

fn priority_to_i64(p: Priority) -> i64 {
    p.as_u8() as i64
}

fn priority_from_i64(n: i64) -> Result<Priority, ReminderError> {
    match n {
        1 => Ok(Priority::Critical),
        2 => Ok(Priority::High),
        3 => Ok(Priority::Medium),
        4 => Ok(Priority::Low),
        5 => Ok(Priority::Minimal),
        other => Err(ReminderError::Store(format!(
            "unknown priority value: {other}"
        ))),
    }
}

fn row_to_reminder(row: &Row<'_>) -> rusqlite::Result<Reminder> {
    use rusqlite::types::{FromSqlError, Type};

    fn decode_err<E: std::fmt::Display>(e: E) -> rusqlite::Error {
        rusqlite::Error::FromSqlConversionFailure(
            0,
            Type::Text,
            Box::new(FromSqlError::Other(format!("{e}").into())),
        )
    }

    let status_s: String = row.get("status")?;
    let priority_n: i64 = row.get("priority")?;
    let due_at_s: String = row.get("due_at")?;
    let created_at_s: String = row.get("created_at")?;
    let snoozed_until_s: Option<String> = row.get("snoozed_until")?;
    let commands_s: String = row.get("commands")?;
    let refs_s: String = row.get("refs")?;
    let schedule_s: Option<String> = row.get("schedule")?;
    let executions_s: String = row.get("executions")?;
    let tags_s: String = row.get("tags")?;
    let autonomous: i64 = row.get("autonomous")?;

    let status = reminder_status_from_str(&status_s).map_err(|e| decode_err(e))?;
    let priority = priority_from_i64(priority_n).map_err(|e| decode_err(e))?;
    let due_at = DateTime::parse_from_rfc3339(&due_at_s)
        .map_err(|e| decode_err(format!("due_at: {e}")))?
        .with_timezone(&Utc);
    let created_at = DateTime::parse_from_rfc3339(&created_at_s)
        .map_err(|e| decode_err(format!("created_at: {e}")))?
        .with_timezone(&Utc);
    let snoozed_until = match snoozed_until_s {
        Some(s) => Some(
            DateTime::parse_from_rfc3339(&s)
                .map_err(|e| decode_err(format!("snoozed_until: {e}")))?
                .with_timezone(&Utc),
        ),
        None => None,
    };
    let commands: Vec<String> =
        serde_json::from_str(&commands_s).map_err(|e| decode_err(format!("commands: {e}")))?;
    let refs = serde_json::from_str(&refs_s).map_err(|e| decode_err(format!("refs: {e}")))?;
    let schedule = match schedule_s {
        Some(s) => {
            Some(serde_json::from_str(&s).map_err(|e| decode_err(format!("schedule: {e}")))?)
        }
        None => None,
    };
    let executions: Vec<agentstategraph_reminders::types::ExecutionRecord> =
        serde_json::from_str(&executions_s).map_err(|e| decode_err(format!("executions: {e}")))?;
    let tags: Vec<String> =
        serde_json::from_str(&tags_s).map_err(|e| decode_err(format!("tags: {e}")))?;

    Ok(Reminder {
        id: row.get("id")?,
        title: row.get("title")?,
        instructions: row.get("instructions")?,
        commands,
        refs,
        priority,
        due_at,
        schedule,
        autonomous: autonomous != 0,
        created_by: row.get("created_by")?,
        created_at,
        status,
        snoozed_until,
        executions,
        tags,
    })
}

impl ReminderStore for SqliteStorage {
    fn save(&self, reminder: &Reminder) -> Result<(), ReminderError> {
        let conn = self
            .lock_conn()
            .map_err(|e| ReminderError::Store(e.to_string()))?;
        let commands_json = serde_json::to_string(&reminder.commands)
            .map_err(|e| ReminderError::Store(format!("commands: {e}")))?;
        let refs_json = serde_json::to_string(&reminder.refs)
            .map_err(|e| ReminderError::Store(format!("refs: {e}")))?;
        let schedule_json = reminder
            .schedule
            .as_ref()
            .map(|s| serde_json::to_string(s))
            .transpose()
            .map_err(|e| ReminderError::Store(format!("schedule: {e}")))?;
        let executions_json = serde_json::to_string(&reminder.executions)
            .map_err(|e| ReminderError::Store(format!("executions: {e}")))?;
        let tags_json = serde_json::to_string(&reminder.tags)
            .map_err(|e| ReminderError::Store(format!("tags: {e}")))?;
        conn.execute(
            "INSERT INTO reminders (
                id, title, instructions, commands, refs, priority, due_at,
                schedule, autonomous, created_by, created_at, status,
                snoozed_until, executions, tags
            ) VALUES (
                ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15
            )",
            params![
                reminder.id,
                reminder.title,
                reminder.instructions,
                commands_json,
                refs_json,
                priority_to_i64(reminder.priority),
                reminder.due_at.to_rfc3339(),
                schedule_json,
                if reminder.autonomous { 1_i64 } else { 0_i64 },
                reminder.created_by,
                reminder.created_at.to_rfc3339(),
                reminder_status_to_str(reminder.status),
                reminder.snoozed_until.map(|t| t.to_rfc3339()),
                executions_json,
                tags_json,
            ],
        )
        .map_err(|e| ReminderError::Store(format!("insert reminder: {e}")))?;
        Ok(())
    }

    fn get(&self, id: &str) -> Result<Option<Reminder>, ReminderError> {
        let conn = self
            .lock_conn()
            .map_err(|e| ReminderError::Store(e.to_string()))?;
        let mut stmt = conn
            .prepare("SELECT * FROM reminders WHERE id = ?1")
            .map_err(|e| ReminderError::Store(format!("get reminder prep: {e}")))?;
        let result = stmt
            .query_row(params![id], row_to_reminder)
            .optional()
            .map_err(|e| ReminderError::Store(format!("get reminder: {e}")))?;
        Ok(result)
    }

    fn update(&self, reminder: &Reminder) -> Result<(), ReminderError> {
        let conn = self
            .lock_conn()
            .map_err(|e| ReminderError::Store(e.to_string()))?;
        update_reminder_on(&conn, reminder)
    }

    fn update_if_unchanged(
        &self,
        expected: &Reminder,
        new: &Reminder,
    ) -> Result<bool, ReminderError> {
        let mut conn = self
            .lock_conn()
            .map_err(|e| ReminderError::Store(e.to_string()))?;
        // Compare and write under one write transaction, so another
        // connection (process) cannot change the row in between.
        let tx = conn
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(|e| ReminderError::Store(format!("begin reminder update: {e}")))?;
        let current = tx
            .query_row(
                "SELECT * FROM reminders WHERE id = ?1",
                params![expected.id],
                row_to_reminder,
            )
            .optional()
            .map_err(|e| ReminderError::Store(format!("get reminder: {e}")))?;
        match current {
            None => Err(ReminderError::NotFound(expected.id.clone())),
            Some(current) if !agentstategraph_reminders::same_reminder(&current, expected) => {
                Ok(false) // dropped transaction rolls back; nothing written
            }
            Some(_) => {
                update_reminder_on(&tx, new)?;
                tx.commit()
                    .map_err(|e| ReminderError::Store(format!("commit reminder update: {e}")))?;
                Ok(true)
            }
        }
    }

    fn delete(&self, id: &str) -> Result<bool, ReminderError> {
        let conn = self
            .lock_conn()
            .map_err(|e| ReminderError::Store(e.to_string()))?;
        let n = conn
            .execute("DELETE FROM reminders WHERE id = ?1", params![id])
            .map_err(|e| ReminderError::Store(format!("delete reminder: {e}")))?;
        Ok(n > 0)
    }

    fn list(&self, filter: &ReminderFilter) -> Result<Vec<Reminder>, ReminderError> {
        let conn = self
            .lock_conn()
            .map_err(|e| ReminderError::Store(e.to_string()))?;

        // Build SQL for the parts expressible at the DB layer.
        let mut sql = String::from("SELECT * FROM reminders WHERE 1=1");
        if filter.status.is_some() {
            sql.push_str(" AND status = :status");
        }
        if filter.priority_at_most.is_some() {
            sql.push_str(" AND priority <= :priority");
        }
        if filter.created_by.is_some() {
            sql.push_str(" AND created_by = :created_by");
        }
        if filter.due_before.is_some() {
            sql.push_str(" AND due_at <= :due_before");
        }
        sql.push_str(" ORDER BY priority ASC, due_at ASC");

        let mut stmt = conn
            .prepare(&sql)
            .map_err(|e| ReminderError::Store(format!("list reminders prep: {e}")))?;

        let mut named: Vec<(&str, Box<dyn rusqlite::ToSql>)> = Vec::new();
        if let Some(s) = filter.status {
            named.push((":status", Box::new(reminder_status_to_str(s).to_string())));
        }
        if let Some(p) = filter.priority_at_most {
            named.push((":priority", Box::new(priority_to_i64(p))));
        }
        if let Some(ref cb) = filter.created_by {
            named.push((":created_by", Box::new(cb.clone())));
        }
        if let Some(due) = filter.due_before {
            named.push((":due_before", Box::new(due.to_rfc3339())));
        }

        let refs_kv: Vec<(&str, &dyn rusqlite::ToSql)> =
            named.iter().map(|(n, v)| (*n, v.as_ref())).collect();

        let rows = stmt
            .query_map(refs_kv.as_slice(), row_to_reminder)
            .map_err(|e| ReminderError::Store(format!("list reminders query: {e}")))?;

        let mut out = Vec::new();
        for r in rows {
            let reminder =
                r.map_err(|e| ReminderError::Store(format!("list reminders row: {e}")))?;
            // Post-filter for ref_id and tags (JSON columns).
            if let Some(ref rid) = filter.ref_id {
                if !reminder.refs.iter().any(|rf| &rf.id == rid) {
                    continue;
                }
            }
            if filter.tags.iter().any(|tag| !reminder.tags.contains(tag)) {
                continue;
            }
            out.push(reminder);
        }
        Ok(out)
    }
}

/// The full-record `UPDATE` shared by `update` and `update_if_unchanged`.
fn update_reminder_on(conn: &Connection, reminder: &Reminder) -> Result<(), ReminderError> {
    let commands_json = serde_json::to_string(&reminder.commands)
        .map_err(|e| ReminderError::Store(format!("commands: {e}")))?;
    let refs_json = serde_json::to_string(&reminder.refs)
        .map_err(|e| ReminderError::Store(format!("refs: {e}")))?;
    let schedule_json = reminder
        .schedule
        .as_ref()
        .map(serde_json::to_string)
        .transpose()
        .map_err(|e| ReminderError::Store(format!("schedule: {e}")))?;
    let executions_json = serde_json::to_string(&reminder.executions)
        .map_err(|e| ReminderError::Store(format!("executions: {e}")))?;
    let tags_json = serde_json::to_string(&reminder.tags)
        .map_err(|e| ReminderError::Store(format!("tags: {e}")))?;
    let n = conn
        .execute(
            "UPDATE reminders SET
                    title = ?2, instructions = ?3, commands = ?4, refs = ?5,
                    priority = ?6, due_at = ?7, schedule = ?8, autonomous = ?9,
                    created_by = ?10, created_at = ?11, status = ?12,
                    snoozed_until = ?13, executions = ?14, tags = ?15
                 WHERE id = ?1",
            params![
                reminder.id,
                reminder.title,
                reminder.instructions,
                commands_json,
                refs_json,
                priority_to_i64(reminder.priority),
                reminder.due_at.to_rfc3339(),
                schedule_json,
                if reminder.autonomous { 1_i64 } else { 0_i64 },
                reminder.created_by,
                reminder.created_at.to_rfc3339(),
                reminder_status_to_str(reminder.status),
                reminder.snoozed_until.map(|t| t.to_rfc3339()),
                executions_json,
                tags_json,
            ],
        )
        .map_err(|e| ReminderError::Store(format!("update reminder: {e}")))?;
    if n == 0 {
        return Err(ReminderError::NotFound(reminder.id.clone()));
    }
    Ok(())
}

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

    fn test_store() -> SqliteStorage {
        SqliteStorage::in_memory().unwrap()
    }

    // --- full-DAG commit walk (plan asg-commit-dag-walk t-001) -------------
    //
    // `list_commits` follows parents[0] only. These pin the difference, not
    // just the new behaviour: a later refactor that collapsed the two would
    // otherwise pass silently.

    fn commit_with(store: &SqliteStorage, label: &str, parents: Vec<ObjectId>) -> Commit {
        let c = CommitBuilder::new(
            ObjectId::hash(label.as_bytes()),
            "agent/test",
            Authority::simple("test"),
            Intent::new(IntentCategory::Checkpoint, label),
        )
        .parents(parents)
        .build();
        store.put_commit(&c).unwrap();
        c
    }

    /// A merge: base <- left, base <- right, merge(left, right).
    /// The first-parent walk sees the left side only.
    #[test]
    fn dag_walk_reaches_the_second_parent_and_log_does_not() {
        let store = test_store();
        let base = commit_with(&store, "base", vec![]);
        let left = commit_with(&store, "left", vec![base.id]);
        let right = commit_with(&store, "right", vec![base.id]);
        let merge = commit_with(&store, "merge", vec![left.id, right.id]);

        let linear: Vec<ObjectId> = store
            .list_commits(&merge.id, 100)
            .unwrap()
            .into_iter()
            .map(|c| c.id)
            .collect();
        assert!(
            !linear.contains(&right.id),
            "first-parent walk must NOT reach the second parent — if it does, \
             the bug this walk exists for is gone and this test is misleading"
        );

        let walk = store.list_commits_dag(&merge.id, 100).unwrap();
        let ids: Vec<ObjectId> = walk.commits.iter().map(|c| c.id).collect();
        for (name, id) in [
            ("merge", merge.id),
            ("left", left.id),
            ("right", right.id),
            ("base", base.id),
        ] {
            assert!(ids.contains(&id), "DAG walk missed {name}");
        }
        assert!(!walk.truncated, "walk fit inside the limit");
    }

    /// `base` is reachable down both sides of the merge; it must appear once.
    #[test]
    fn dag_walk_dedups_a_commit_reachable_from_both_sides() {
        let store = test_store();
        let base = commit_with(&store, "base", vec![]);
        let left = commit_with(&store, "left", vec![base.id]);
        let right = commit_with(&store, "right", vec![base.id]);
        let merge = commit_with(&store, "merge", vec![left.id, right.id]);

        let walk = store.list_commits_dag(&merge.id, 100).unwrap();
        let n = walk.commits.iter().filter(|c| c.id == base.id).count();
        assert_eq!(n, 1, "base reachable from both sides must appear once");
        assert_eq!(walk.commits.len(), 4, "four distinct commits");
    }

    /// Truncation has to be distinguishable from completion, or a caller
    /// cannot tell a small complete history from a large truncated one.
    #[test]
    fn dag_walk_reports_truncation_only_when_more_remained() {
        let store = test_store();
        let base = commit_with(&store, "base", vec![]);
        let mid = commit_with(&store, "mid", vec![base.id]);
        let tip = commit_with(&store, "tip", vec![mid.id]);

        let capped = store.list_commits_dag(&tip.id, 2).unwrap();
        assert_eq!(capped.commits.len(), 2);
        assert!(capped.truncated, "stopped with a parent still unexplored");

        let exact = store.list_commits_dag(&tip.id, 3).unwrap();
        assert_eq!(exact.commits.len(), 3);
        assert!(
            !exact.truncated,
            "a walk that consumed the whole DAG must NOT claim truncation, \
             even when it used the limit exactly"
        );
    }

    /// A pruned parent ends that edge; the rest of the DAG still walks.
    /// This is the swept-store case, and it must not error.
    #[test]
    fn dag_walk_survives_a_pruned_parent() {
        let store = test_store();
        let missing = ObjectId::hash(b"swept-away");
        let real = commit_with(&store, "real", vec![]);
        // Merge whose first parent was garbage-collected.
        let tip = commit_with(&store, "tip", vec![missing, real.id]);

        let walk = store.list_commits_dag(&tip.id, 100).unwrap();
        let ids: Vec<ObjectId> = walk.commits.iter().map(|c| c.id).collect();
        assert!(ids.contains(&tip.id));
        assert!(
            ids.contains(&real.id),
            "the surviving edge must still be walked past a pruned parent"
        );
        assert!(
            !ids.contains(&missing),
            "a pruned commit cannot be returned"
        );
    }

    #[test]
    fn dag_walk_on_a_single_commit_is_complete() {
        let store = test_store();
        let only = commit_with(&store, "only", vec![]);
        let walk = store.list_commits_dag(&only.id, 100).unwrap();
        assert_eq!(walk.commits.len(), 1);
        assert!(!walk.truncated);
    }

    #[test]
    fn dag_walk_from_a_missing_commit_is_empty_not_an_error() {
        let store = test_store();
        let walk = store
            .list_commits_dag(&ObjectId::hash(b"never-existed"), 100)
            .unwrap();
        assert!(walk.commits.is_empty());
        assert!(!walk.truncated);
    }

    // --- history namespace attribution (plan asg-commit-dag-walk t-010) ----

    /// A commit with no session must NOT be filed under "default", which is a
    /// real namespace name and so indistinguishable from a real attribution.
    ///
    /// This is the case that matters: on the AgentStateDeveloper store nothing
    /// writes sessions, so the old fallback filed all 39,446 commits under
    /// "default" while ~35,000 of them belonged elsewhere.
    #[test]
    fn unattributable_commits_are_not_filed_under_default() {
        let store = test_store();
        let c = CommitBuilder::new(
            ObjectId::hash(b"state"),
            "agent/test",
            Authority::simple("test"),
            Intent::new(IntentCategory::Checkpoint, "no session"),
        )
        .build();
        store.put_commit(&c).unwrap();

        assert!(store.history_extract_batch(100).unwrap() > 0);
        let rows = store.history_rollup().unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(
            rows[0].namespace, HISTORY_NAMESPACE_UNKNOWN,
            "a commit with no session must say so, not claim 'default'"
        );
        assert_ne!(
            rows[0].namespace, "default",
            "the old fallback asserted a namespace it had not established"
        );
    }

    #[test]
    fn test_object_roundtrip() {
        let store = test_store();
        let obj = Object::string("hello sqlite");
        let id = store.put_object(&obj).unwrap();
        let retrieved = store.get_object(&id).unwrap();
        assert_eq!(retrieved, Some(obj));
    }

    #[test]
    fn test_object_dedup() {
        let store = test_store();
        let obj = Object::string("dedup");
        let id1 = store.put_object(&obj).unwrap();
        let id2 = store.put_object(&obj).unwrap();
        assert_eq!(id1, id2);
    }

    #[test]
    fn test_commit_roundtrip() {
        let store = test_store();
        let commit = CommitBuilder::new(
            ObjectId::hash(b"state"),
            "agent/test",
            Authority::simple("test"),
            Intent::new(IntentCategory::Checkpoint, "test commit"),
        )
        .reasoning("testing sqlite backend")
        .confidence(0.9)
        .build();

        store.put_commit(&commit).unwrap();
        let retrieved = store.get_commit(&commit.id).unwrap().unwrap();
        assert_eq!(retrieved.agent_id, "agent/test");
        assert_eq!(
            retrieved.reasoning,
            Some("testing sqlite backend".to_string())
        );
        assert_eq!(retrieved.confidence, Some(0.9));
    }

    #[test]
    fn test_ref_operations() {
        let store = test_store();
        let target = ObjectId::hash(b"commit-1");
        let new_target = ObjectId::hash(b"commit-2");

        let ns = Namespace::default_ns();
        store.set_ref(&ns, "main", target).unwrap();
        assert_eq!(store.get_ref(&ns, "main").unwrap(), Some(target));

        // CAS success
        assert!(store.cas_ref(&ns, "main", target, new_target).unwrap());
        assert_eq!(store.get_ref(&ns, "main").unwrap(), Some(new_target));

        // CAS failure
        let stale = ObjectId::hash(b"stale");
        assert!(!store.cas_ref(&ns, "main", stale, target).unwrap());
    }

    #[test]
    fn test_list_refs() {
        let store = test_store();
        let ns = Namespace::default_ns();
        store
            .set_ref(&ns, "agents/a", ObjectId::hash(b"a"))
            .unwrap();
        store
            .set_ref(&ns, "agents/b", ObjectId::hash(b"b"))
            .unwrap();
        store.set_ref(&ns, "main", ObjectId::hash(b"m")).unwrap();

        let agents = store.list_refs(&ns, "agents/").unwrap();
        assert_eq!(agents.len(), 2);

        let all = store.list_refs(&ns, "").unwrap();
        assert_eq!(all.len(), 3);
    }

    #[test]
    fn test_batch_put_objects() {
        let store = test_store();
        let objs = vec![
            Object::string("one"),
            Object::string("two"),
            Object::string("three"),
        ];
        let ids = store.batch_put_objects(&objs).unwrap();
        assert_eq!(ids.len(), 3);

        for id in ids.iter() {
            assert!(store.has_object(id).unwrap());
        }
    }

    #[test]
    fn test_commit_chain() {
        let store = test_store();

        let commit1 = CommitBuilder::new(
            ObjectId::hash(b"state-1"),
            "agent/test",
            Authority::simple("test"),
            Intent::new(IntentCategory::Checkpoint, "first"),
        )
        .build();
        store.put_commit(&commit1).unwrap();

        let commit2 = CommitBuilder::new(
            ObjectId::hash(b"state-2"),
            "agent/test",
            Authority::simple("test"),
            Intent::new(IntentCategory::Refine, "second"),
        )
        .parent(commit1.id)
        .build();
        store.put_commit(&commit2).unwrap();

        let commit3 = CommitBuilder::new(
            ObjectId::hash(b"state-3"),
            "agent/test",
            Authority::simple("test"),
            Intent::new(IntentCategory::Refine, "third"),
        )
        .parent(commit2.id)
        .build();
        store.put_commit(&commit3).unwrap();

        let log = store.list_commits(&commit3.id, 10).unwrap();
        assert_eq!(log.len(), 3);
        assert_eq!(log[0].intent.description, "third");
        assert_eq!(log[1].intent.description, "second");
        assert_eq!(log[2].intent.description, "first");
    }

    #[test]
    fn test_full_workflow_sqlite_storage_traits() {
        // Test that SqliteStorage works correctly through the trait interface
        let store = test_store();

        // Store objects
        let obj1 = Object::string("cluster-name");
        let id1 = store.put_object(&obj1).unwrap();

        // Store a commit referencing the object
        let commit = CommitBuilder::new(
            id1,
            "agent/test",
            Authority::simple("test"),
            Intent::new(IntentCategory::Checkpoint, "full workflow test"),
        )
        .build();
        store.put_commit(&commit).unwrap();

        // Set a ref
        let ns = Namespace::default_ns();
        store.set_ref(&ns, "main", commit.id).unwrap();

        // Read it all back
        let ref_target = store.get_ref(&ns, "main").unwrap().unwrap();
        assert_eq!(ref_target, commit.id);

        let retrieved_commit = store.get_commit(&ref_target).unwrap().unwrap();
        assert_eq!(retrieved_commit.state_root, id1);

        let retrieved_obj = store.get_object(&id1).unwrap().unwrap();
        assert_eq!(retrieved_obj, obj1);
    }

    // -----------------------------------------------------------------------
    // ReminderStore tests
    // -----------------------------------------------------------------------

    use agentstategraph_reminders::{
        Reminder, ReminderFilter, ReminderStore,
        types::{CreateReminder, Priority, ReminderRef, ReminderStatus, Schedule},
    };
    use chrono::Duration;

    fn future(secs: i64) -> chrono::DateTime<chrono::Utc> {
        chrono::Utc::now() + Duration::seconds(secs)
    }

    fn past_ts(secs: i64) -> chrono::DateTime<chrono::Utc> {
        chrono::Utc::now() - Duration::seconds(secs)
    }

    fn make_reminder(title: &str, secs_from_now: i64) -> Reminder {
        CreateReminder::new(title, "do something", future(secs_from_now), "agent/test")
            .into_reminder()
    }

    #[test]
    fn reminder_save_and_get_roundtrip() {
        let store = test_store();
        let r = make_reminder("check server", 600);
        store.save(&r).unwrap();
        let got = store.get(&r.id).unwrap().unwrap();
        assert_eq!(got.id, r.id);
        assert_eq!(got.title, "check server");
        assert_eq!(got.status, ReminderStatus::Pending);
        assert!(got.autonomous);
    }

    #[test]
    fn reminder_get_missing_returns_none() {
        let store = test_store();
        let result = store.get("nonexistent").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn reminder_save_duplicate_id_fails() {
        let store = test_store();
        let r = make_reminder("dup", 60);
        store.save(&r).unwrap();
        let err = store.save(&r).unwrap_err();
        assert!(err.to_string().contains("insert reminder"));
    }

    #[test]
    fn reminder_update_roundtrip() {
        let store = test_store();
        let mut r = make_reminder("update me", 300);
        store.save(&r).unwrap();
        r.status = ReminderStatus::Due;
        r.title = "updated title".to_string();
        store.update(&r).unwrap();
        let got = store.get(&r.id).unwrap().unwrap();
        assert_eq!(got.status, ReminderStatus::Due);
        assert_eq!(got.title, "updated title");
    }

    #[test]
    fn reminder_update_missing_returns_not_found() {
        let store = test_store();
        let r = make_reminder("ghost", 60);
        let err = store.update(&r).unwrap_err();
        assert!(matches!(
            err,
            agentstategraph_reminders::ReminderError::NotFound(_)
        ));
    }

    #[test]
    fn reminder_delete_existing_returns_true() {
        let store = test_store();
        let r = make_reminder("delete me", 60);
        store.save(&r).unwrap();
        assert!(store.delete(&r.id).unwrap());
        assert!(store.get(&r.id).unwrap().is_none());
    }

    #[test]
    fn reminder_delete_missing_returns_false() {
        let store = test_store();
        assert!(!store.delete("ghost").unwrap());
    }

    #[test]
    fn reminder_list_empty_filter_returns_all() {
        let store = test_store();
        let r1 = make_reminder("a", 100);
        let r2 = make_reminder("b", 200);
        store.save(&r1).unwrap();
        store.save(&r2).unwrap();
        let all = store.list(&ReminderFilter::default()).unwrap();
        assert_eq!(all.len(), 2);
    }

    #[test]
    fn reminder_list_filter_by_status() {
        let store = test_store();
        let r1 = make_reminder("pending", 100);
        let mut r2 = make_reminder("due", 50);
        r2.status = ReminderStatus::Due;
        store.save(&r1).unwrap();
        store.save(&r2).unwrap();

        let filter = ReminderFilter {
            status: Some(ReminderStatus::Due),
            ..Default::default()
        };
        let results = store.list(&filter).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "due");
    }

    #[test]
    fn reminder_list_filter_by_priority_at_most() {
        let store = test_store();
        let critical = CreateReminder::new("c", "i", future(100), "a")
            .with_priority(Priority::Critical)
            .into_reminder();
        let low = CreateReminder::new("l", "i", future(200), "a")
            .with_priority(Priority::Low)
            .into_reminder();
        store.save(&critical).unwrap();
        store.save(&low).unwrap();

        let filter = ReminderFilter {
            priority_at_most: Some(Priority::High),
            ..Default::default()
        };
        let results = store.list(&filter).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "c");
    }

    #[test]
    fn reminder_list_filter_by_created_by() {
        let store = test_store();
        let r1 = CreateReminder::new("r1", "i", future(60), "agent/alice").into_reminder();
        let r2 = CreateReminder::new("r2", "i", future(60), "agent/bob").into_reminder();
        store.save(&r1).unwrap();
        store.save(&r2).unwrap();

        let filter = ReminderFilter {
            created_by: Some("agent/alice".into()),
            ..Default::default()
        };
        let results = store.list(&filter).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "r1");
    }

    #[test]
    fn reminder_list_filter_by_due_before() {
        let store = test_store();
        let soon = CreateReminder::new("soon", "i", future(60), "a").into_reminder();
        let later = CreateReminder::new("later", "i", future(7200), "a").into_reminder();
        store.save(&soon).unwrap();
        store.save(&later).unwrap();

        let filter = ReminderFilter {
            due_before: Some(future(600)),
            ..Default::default()
        };
        let results = store.list(&filter).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "soon");
    }

    #[test]
    fn reminder_list_filter_by_ref_id() {
        let store = test_store();
        let mut with_ref = make_reminder("with-ref", 60);
        with_ref.refs = vec![ReminderRef::branch("main", "main branch")];
        let without = make_reminder("without-ref", 60);
        store.save(&with_ref).unwrap();
        store.save(&without).unwrap();

        let filter = ReminderFilter {
            ref_id: Some("main".into()),
            ..Default::default()
        };
        let results = store.list(&filter).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "with-ref");
    }

    #[test]
    fn reminder_list_filter_by_tags() {
        let store = test_store();
        let mut tagged = make_reminder("tagged", 60);
        tagged.tags = vec!["cleanup".into(), "server".into()];
        let untagged = make_reminder("untagged", 60);
        store.save(&tagged).unwrap();
        store.save(&untagged).unwrap();

        let filter = ReminderFilter {
            tags: vec!["cleanup".into()],
            ..Default::default()
        };
        let results = store.list(&filter).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "tagged");
    }

    #[test]
    fn reminder_list_ordered_by_priority_then_due() {
        let store = test_store();
        let medium_late = CreateReminder::new("medium-late", "i", future(200), "a")
            .with_priority(Priority::Medium)
            .into_reminder();
        let high_early = CreateReminder::new("high-early", "i", future(100), "a")
            .with_priority(Priority::High)
            .into_reminder();
        let high_later = CreateReminder::new("high-later", "i", future(300), "a")
            .with_priority(Priority::High)
            .into_reminder();
        store.save(&medium_late).unwrap();
        store.save(&high_early).unwrap();
        store.save(&high_later).unwrap();

        let all = store.list(&ReminderFilter::default()).unwrap();
        assert_eq!(all[0].title, "high-early");
        assert_eq!(all[1].title, "high-later");
        assert_eq!(all[2].title, "medium-late");
    }

    #[test]
    fn reminder_persists_schedule_and_refs() {
        let store = test_store();
        let mut r = CreateReminder::new("scheduled", "i", future(60), "a")
            .with_schedule(Schedule::Interval {
                every_seconds: 3600,
            })
            .with_refs(vec![ReminderRef::plan("plan-123", "My plan")])
            .into_reminder();
        r.autonomous = false;
        store.save(&r).unwrap();

        let got = store.get(&r.id).unwrap().unwrap();
        assert!(!got.autonomous);
        assert!(matches!(
            got.schedule,
            Some(Schedule::Interval {
                every_seconds: 3600
            })
        ));
        assert_eq!(got.refs.len(), 1);
        assert_eq!(got.refs[0].id, "plan-123");
        assert_eq!(got.refs[0].label.as_deref(), Some("My plan"));
    }

    #[test]
    fn reminder_persists_snoozed_until() {
        let store = test_store();
        let mut r = make_reminder("snooze me", 60);
        let snooze_time = future(3600);
        r.status = ReminderStatus::Snoozed;
        r.snoozed_until = Some(snooze_time);
        store.save(&r).unwrap();

        let got = store.get(&r.id).unwrap().unwrap();
        assert_eq!(got.status, ReminderStatus::Snoozed);
        assert!(got.snoozed_until.is_some());
        let diff = (got.snoozed_until.unwrap() - snooze_time)
            .num_seconds()
            .abs();
        assert!(diff < 2, "snoozed_until timestamp drifted by {diff}s");
    }

    #[test]
    fn reminder_all_statuses_roundtrip() {
        let store = test_store();
        let statuses = [
            ReminderStatus::Pending,
            ReminderStatus::Due,
            ReminderStatus::AwaitingPermission,
            ReminderStatus::InProgress,
            ReminderStatus::Completed,
            ReminderStatus::Snoozed,
            ReminderStatus::Cancelled,
        ];
        for status in statuses {
            let mut r = make_reminder(&format!("{status:?}"), 60);
            r.status = status;
            store.save(&r).unwrap();
            let got = store.get(&r.id).unwrap().unwrap();
            assert_eq!(got.status, status, "status roundtrip failed for {status:?}");
        }
    }

    #[test]
    fn reminder_all_priorities_roundtrip() {
        let store = test_store();
        let priorities = [
            Priority::Critical,
            Priority::High,
            Priority::Medium,
            Priority::Low,
            Priority::Minimal,
        ];
        for p in priorities {
            let r = CreateReminder::new(&format!("{p:?}"), "i", future(60), "a")
                .with_priority(p)
                .into_reminder();
            store.save(&r).unwrap();
            let got = store.get(&r.id).unwrap().unwrap();
            assert_eq!(got.priority, p, "priority roundtrip failed for {p:?}");
        }
    }

    // --- GC write lock and legacy unpin -------------------------------------

    /// A unique on-disk path; the lock test needs a second, independent
    /// connection, which an in-memory database cannot give it.
    fn temp_db_path(tag: &str) -> std::path::PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("asg-{tag}-{}-{nanos}.db", std::process::id()))
    }

    fn remove_db(path: &std::path::Path) {
        for suffix in ["", "-wal", "-shm"] {
            let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));
        }
    }

    /// While a sweep holds the GC write lock no other connection can begin a
    /// write — that exclusion is the whole fix — yet readers still work, and
    /// the lock is gone once released.
    #[test]
    fn gc_write_lock_excludes_other_writers_but_not_readers() {
        let path = temp_db_path("gc-lock");
        let store = SqliteStorage::open(&path).unwrap();
        store.put_object(&Object::string("seed")).unwrap();

        let other = rusqlite::Connection::open(&path).unwrap();
        other.busy_timeout(std::time::Duration::ZERO).unwrap();

        store.history_gc_lock_writers().unwrap();
        match other.execute_batch("BEGIN IMMEDIATE") {
            Err(rusqlite::Error::SqliteFailure(e, _)) => {
                assert_eq!(e.code, rusqlite::ErrorCode::DatabaseBusy)
            }
            other => panic!("a second writer got in while the GC lock was held: {other:?}"),
        }
        let objects: i64 = other
            .query_row("SELECT COUNT(*) FROM objects", [], |r| r.get(0))
            .unwrap();
        assert_eq!(objects, 1, "readers are not blocked");

        store.history_gc_unlock_writers(true).unwrap();
        other
            .execute_batch("BEGIN IMMEDIATE; COMMIT;")
            .expect("released lock admits writers again");
        // Releasing when nothing is held is a no-op, not an error.
        store.history_gc_unlock_writers(true).unwrap();

        drop(other);
        drop(store);
        remove_db(&path);
    }

    /// Rows distilled before opt-in pinning pinned every checkpoint. The unpin
    /// op must clear exactly those — checkpoints that never asked to be pinned —
    /// leave a deliberately pinned one alone, and keep both on the timeline.
    #[test]
    fn unpin_legacy_milestones_clears_only_unrequested_pins() {
        let store = test_store();
        let routine = CommitBuilder::new(
            ObjectId::hash(b"routine-state"),
            "asd",
            Authority::simple("asd"),
            Intent::new(IntentCategory::Checkpoint, "asd index: 9 symbols"),
        )
        .build();
        let release = CommitBuilder::new(
            ObjectId::hash(b"release-state"),
            "alice",
            Authority::simple("alice"),
            Intent::new(IntentCategory::Checkpoint, "v1.0 release")
                .with_tags(vec![TAG_PIN_STATE.to_string()]),
        )
        .build();
        store.put_commit(&routine).unwrap();
        store.put_commit(&release).unwrap();
        store.history_extract_batch(100).unwrap();

        // What a pre-1.2.2 extractor wrote for the routine checkpoint.
        {
            let conn = store.lock_conn().unwrap();
            conn.execute(
                "UPDATE asg_history_milestone SET state_root = ?1 WHERE commit_id = ?2",
                params![
                    routine.state_root.as_bytes().as_slice(),
                    routine.id.as_bytes().as_slice()
                ],
            )
            .unwrap();
        }
        let before = store.history_retained_state_roots().unwrap();
        assert!(before.contains(&routine.state_root));
        assert!(before.contains(&release.state_root));

        assert_eq!(store.history_unpin_legacy_milestones().unwrap(), 1);
        assert_eq!(
            store.history_retained_state_roots().unwrap(),
            vec![release.state_root],
            "only the requested pin survives"
        );
        assert_eq!(
            store.history_unpin_legacy_milestones().unwrap(),
            0,
            "one-time: nothing left to unpin"
        );
        assert_eq!(
            store.history_milestones(10).unwrap().len(),
            2,
            "unpinning drops the snapshot hook, not the milestone"
        );
    }
}