oakvcs-core 0.114.0

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

use crate::hash::hash_bytes;
use crate::{
    Blob, Branch, BranchStatus, CanonicalChangeSetV1, ChangeScopeV1, ChangeType, ChunkInfo,
    CloseReason, Commit, FileChange, FileMode, Hash, Manifest, ManifestEntry, MetadataKey,
    OakError, Result, Tree, TreeEntry, TreeEntryKind, CHANGE_SET_OBJECT_FORMAT_V1,
};

use crate::traits::{BlobSource, Repository, StatCacheEntry};

/// Decode one stored `branches` row. A column that cannot be decoded yields
/// an [`crate::UnreadableBranch`] naming the branch and column (fb-118);
/// legacy SQLite-default timestamps decode losslessly.
fn decode_branch_row(
    name: String,
    description: Option<String>,
    parent_branch: Option<String>,
    status: BranchStatus,
    close_reason: Option<String>,
    created_at: &str,
) -> std::result::Result<Branch, crate::UnreadableBranch> {
    let unreadable = |name: &str, column| crate::UnreadableBranch {
        name: name.to_string(),
        status,
        column,
    };
    let Some(created_at) = crate::parse_stored_timestamp(created_at) else {
        return Err(unreadable(&name, "created_at"));
    };
    let close_reason = match close_reason.as_deref().map(CloseReason::parse).transpose() {
        Ok(reason) => reason,
        Err(_) => return Err(unreadable(&name, "close_reason")),
    };
    Ok(Branch {
        name,
        description,
        parent_branch,
        status,
        close_reason,
        created_at,
    })
}

fn advance_description_generation(conn: &Connection) -> Result<i64> {
    conn.query_row(
        "UPDATE branch_description_clock SET generation = generation + 1
         WHERE singleton = 1 AND generation < 9223372036854775807 RETURNING generation",
        [],
        |row| row.get(0),
    )
    .map_err(|error| {
        OakError::Database(format!(
            "could not advance branch description generation: {error}"
        ))
    })
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangeCaptureProvenance {
    pub owner: String,
    pub name: String,
    pub origin: Option<String>,
    pub source_branch: String,
    pub base_commit: Option<Hash>,
    pub captured_at: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoredChangeCapture {
    pub capture_id: String,
    pub change_set: CanonicalChangeSetV1,
    pub provenance: ChangeCaptureProvenance,
}

struct ChangeCaptureRow {
    change_id: String,
    format_version: i64,
    owner: String,
    name: String,
    origin: Option<String>,
    source_branch: String,
    base_commit: Option<String>,
    captured_at: String,
}

struct ChangeSetRow {
    schema_version: i64,
    object_format: String,
    base_tree: String,
    result_tree: String,
    scope_kind: String,
    scope_paths_json: String,
    descriptor_json: String,
    created_at: String,
}

const MIGRATION_BASELINE: &str = include_str!("migrations/sqlite/0000_baseline.sql");
const MIGRATION_0001_RELAX_BRANCH_FKS_AND_MESSAGE: &str =
    include_str!("migrations/sqlite/0001_relax_branch_fks_and_message.sql");
const MIGRATION_0002_RELAX_COMMITS_PARENT_HASH_FK: &str =
    include_str!("migrations/sqlite/0002_relax_commits_parent_hash_fk.sql");
const MIGRATION_0003_STAT_CACHE: &str = include_str!("migrations/sqlite/0003_stat_cache.sql");
const MIGRATION_0004_STAT_CACHE_CTIME: &str =
    include_str!("migrations/sqlite/0004_stat_cache_ctime.sql");
const MIGRATION_0005_MERGE_PARENT_INDEX: &str =
    include_str!("migrations/sqlite/0005_merge_parent_index.sql");
const MIGRATION_0006_DROP_REDUNDANT_TREE_ENTRIES_INDEX: &str =
    include_str!("migrations/sqlite/0006_drop_redundant_tree_entries_index.sql");
const MIGRATION_0007_BLOBS_CODEC: &str = include_str!("migrations/sqlite/0007_blobs_codec.sql");
const MIGRATION_0008_TREES_CONTENT: &str = include_str!("migrations/sqlite/0008_trees_content.sql");
const MIGRATION_0009_RELAX_BLOB_CHUNKS_FK: &str =
    include_str!("migrations/sqlite/0009_relax_blob_chunks_fk.sql");
const MIGRATION_0010_BRANCH_CLOSE_REASON: &str =
    include_str!("migrations/sqlite/0010_branch_close_reason.sql");
const MIGRATION_0011_SERVE_MAPPING_PROOFS: &str =
    include_str!("migrations/sqlite/0011_serve_mapping_proofs.sql");

/// SQLite-backed repository for local storage
pub struct SqliteRepository {
    conn: Mutex<Connection>,
    /// Whole-tree flattens served through this handle
    /// ([`Repository::walk_tree`], and [`Repository::get_manifest`], which
    /// goes through it). Each one reads every directory of a tree, so
    /// commands with a "loads HEAD once" budget assert on it in tests.
    tree_flattens: AtomicU64,
    /// Individual tree objects read through this handle
    /// ([`Repository::get_tree`]) — what any flatten, however it is spelled,
    /// is made of.
    tree_reads: AtomicU64,
}

/// One row per migration. Mirrors the structure on the postgres side. New
/// migrations append to `MIGRATIONS` below; existing entries are immutable
/// once shipped.
struct Migration {
    version: &'static str,
    sql: &'static str,
    required: bool,
}

/// Canonical ordering of migrations. Migrations 001..011 were squashed into
/// `0000_baseline` on 2026-05-05; the `migration_already_applied` heuristic
/// recognises previously-migrated repositories and marks the baseline as
/// applied without re-running its DDL.
const MIGRATIONS: &[Migration] = &[
    Migration {
        version: "0000_baseline",
        sql: MIGRATION_BASELINE,
        required: true,
    },
    Migration {
        version: "0001_relax_branch_fks_and_message",
        sql: MIGRATION_0001_RELAX_BRANCH_FKS_AND_MESSAGE,
        required: true,
    },
    Migration {
        version: "0002_relax_commits_parent_hash_fk",
        sql: MIGRATION_0002_RELAX_COMMITS_PARENT_HASH_FK,
        required: true,
    },
    Migration {
        version: "0003_stat_cache",
        sql: MIGRATION_0003_STAT_CACHE,
        required: true,
    },
    Migration {
        version: "0004_stat_cache_ctime",
        sql: MIGRATION_0004_STAT_CACHE_CTIME,
        required: true,
    },
    Migration {
        version: "0005_merge_parent_index",
        sql: MIGRATION_0005_MERGE_PARENT_INDEX,
        required: true,
    },
    Migration {
        version: "0006_drop_redundant_tree_entries_index",
        sql: MIGRATION_0006_DROP_REDUNDANT_TREE_ENTRIES_INDEX,
        required: true,
    },
    Migration {
        version: "0007_blobs_codec",
        sql: MIGRATION_0007_BLOBS_CODEC,
        required: true,
    },
    Migration {
        version: "0008_trees_content",
        sql: MIGRATION_0008_TREES_CONTENT,
        required: true,
    },
    Migration {
        version: "0009_relax_blob_chunks_fk",
        sql: MIGRATION_0009_RELAX_BLOB_CHUNKS_FK,
        required: true,
    },
    Migration {
        version: "0010_branch_close_reason",
        sql: MIGRATION_0010_BRANCH_CLOSE_REASON,
        required: true,
    },
    Migration {
        version: "0011_serve_mapping_proofs",
        sql: MIGRATION_0011_SERVE_MAPPING_PROOFS,
        required: true,
    },
    Migration {
        version: "0012_pending_branch_description",
        sql: include_str!("migrations/sqlite/0012_pending_branch_description.sql"),
        required: true,
    },
    Migration {
        version: "0013_branch_description_generation",
        sql: include_str!("migrations/sqlite/0013_branch_description_generation.sql"),
        required: true,
    },
    Migration {
        version: "0014_change_captures",
        sql: include_str!("migrations/sqlite/0014_change_captures.sql"),
        required: true,
    },
    Migration {
        version: "0015_serve_published_objects",
        sql: include_str!("migrations/sqlite/0015_serve_published_objects.sql"),
        required: true,
    },
    Migration {
        version: "0016_serve_stage_objects",
        sql: include_str!("migrations/sqlite/0016_serve_stage_objects.sql"),
        required: true,
    },
    Migration {
        version: "0017_tag_releases",
        sql: include_str!("migrations/sqlite/0017_tag_releases.sql"),
        required: true,
    },
    Migration {
        version: "0018_drop_tags_commit_fk",
        sql: include_str!("migrations/sqlite/0018_drop_tags_commit_fk.sql"),
        required: true,
    },
];

/// zstd level for at-rest compression. 3 is the default — fast, and tree
/// content / source blobs are highly compressible, so a higher level buys
/// little for the per-write cost during bulk import.
const ZSTD_LEVEL: i32 = 3;

/// `blobs.codec` markers.
const CODEC_RAW: i64 = 0;
const CODEC_ZSTD: i64 = 1;

fn zstd_compress(data: &[u8]) -> Result<Vec<u8>> {
    zstd::encode_all(data, ZSTD_LEVEL)
        .map_err(|e| OakError::Database(format!("zstd compress: {e}")))
}

fn zstd_decompress(data: &[u8]) -> Result<Vec<u8>> {
    zstd::decode_all(data).map_err(|e| OakError::Database(format!("zstd decompress: {e}")))
}

/// Decompress a stored tree row. A manifest walk reads one row per directory,
/// and [`zstd_decompress`] builds a fresh decompression context per call,
/// which costs several times the decode itself on rows this small. Reuse one
/// context and output buffer per thread. Tree frames don't record their
/// decoded size, so the buffer grows on demand; rows past `MAX_REUSED` (or
/// corrupt ones) go through the streaming decoder, which reports the error.
fn zstd_decompress_tree(data: &[u8]) -> Result<Vec<u8>> {
    use std::cell::RefCell;
    const INITIAL: usize = 64 * 1024;
    const KEEP: usize = 1024 * 1024;
    const MAX_REUSED: usize = 16 * 1024 * 1024;
    thread_local! {
        static TREE_DECODER: RefCell<Option<(zstd::bulk::Decompressor<'static>, Vec<u8>)>> =
            const { RefCell::new(None) };
    }
    // An empty row is an incomplete frame to the streaming decoder but
    // decodes to nothing in bulk; keep the streaming decoder's error.
    if data.is_empty() {
        return zstd_decompress(data);
    }
    TREE_DECODER.with(|cell| {
        let mut slot = cell.borrow_mut();
        if slot.is_none() {
            let decoder = zstd::bulk::Decompressor::new()
                .map_err(|e| OakError::Database(format!("zstd decompress: {e}")))?;
            *slot = Some((decoder, Vec::with_capacity(INITIAL)));
        }
        let (decoder, buf) = slot.as_mut().expect("decoder initialized above");
        loop {
            buf.clear();
            match decoder.decompress_to_buffer(data, buf) {
                Ok(_) => {
                    let raw = buf.as_slice().to_vec();
                    if buf.capacity() > KEEP {
                        *buf = Vec::with_capacity(INITIAL);
                    }
                    return Ok(raw);
                }
                Err(_) if buf.capacity() < MAX_REUSED => buf.reserve(buf.capacity() * 4),
                Err(_) => return zstd_decompress(data),
            }
        }
    })
}

/// Encode blob content for storage: zstd when it actually shrinks, else raw.
/// Returns the bytes to store and the codec marker. Hashing is always over the
/// plaintext, so this choice never affects a blob's content-addressed identity.
fn encode_blob(content: &[u8]) -> Result<(std::borrow::Cow<'_, [u8]>, i64)> {
    let compressed = zstd_compress(content)?;
    if compressed.len() < content.len() {
        Ok((std::borrow::Cow::Owned(compressed), CODEC_ZSTD))
    } else {
        Ok((std::borrow::Cow::Borrowed(content), CODEC_RAW))
    }
}

/// Decode stored blob content given its codec marker.
fn decode_blob(content: Vec<u8>, codec: i64) -> Result<Vec<u8>> {
    if codec == CODEC_ZSTD {
        zstd_decompress(&content)
    } else {
        Ok(content)
    }
}

/// Insert a tree in the new on-disk format (migration 0008): its canonical hash
/// preimage, zstd-compressed, as a single `trees.content` row — no per-entry
/// `tree_entries` rows. `conn` may be a plain connection, a transaction, or a
/// savepoint (all deref to `Connection`).
fn insert_tree_row(conn: &Connection, tree: &Tree) -> Result<()> {
    let canonical = Tree::new(tree.entries.clone())?;
    if canonical.hash != tree.hash {
        return Err(OakError::InvalidHash(format!(
            "tree {} does not match content hash {}",
            tree.hash, canonical.hash
        )));
    }
    let content = zstd_compress(&canonical.canonical_bytes())?;
    conn.execute(
        "INSERT OR IGNORE INTO trees (hash, content) VALUES (?1, ?2)",
        params![canonical.hash.as_str(), content],
    )
    .map_err(|e| OakError::Database(e.to_string()))?;
    Ok(())
}

/// Read a legacy tree (one stored as `tree_entries` rows, i.e. `trees.content`
/// is NULL). Used as the fallback path in `get_tree` for repos written before
/// migration 0008 / not yet compacted.
fn read_tree_entries(conn: &Connection, hash: &Hash) -> Result<Tree> {
    let mut stmt = conn
        .prepare("SELECT name, kind, hash, mode FROM tree_entries WHERE tree_hash = ?1")
        .map_err(|e| OakError::Database(e.to_string()))?;

    let mut entries: Vec<TreeEntry> = stmt
        .query_map(params![hash.as_str()], |row| {
            let name: String = row.get(0)?;
            let kind_str: String = row.get(1)?;
            let entry_hash: String = row.get(2)?;
            let mode_str: String = row.get(3)?;

            let kind = match kind_str.as_str() {
                "tree" => TreeEntryKind::Tree,
                _ => TreeEntryKind::Blob,
            };
            let mode = match mode_str.as_str() {
                "executable" => FileMode::Executable,
                "symlink" => FileMode::Symlink,
                _ => FileMode::Regular,
            };
            Ok(TreeEntry {
                name,
                kind,
                hash: Hash(entry_hash),
                mode,
            })
        })
        .map_err(|e| OakError::Database(e.to_string()))?
        .collect::<std::result::Result<Vec<_>, _>>()
        .map_err(|e| OakError::Database(e.to_string()))?;

    // Re-sort to match Tree::new canonical ordering (PK guarantees uniqueness,
    // not row order).
    entries.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(Tree {
        hash: hash.clone(),
        entries,
    })
}

fn table_exists(conn: &Connection, name: &str) -> rusqlite::Result<bool> {
    conn.query_row(
        "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1)",
        params![name],
        |row| row.get(0),
    )
}

fn column_exists(conn: &Connection, table: &str, column: &str) -> Result<bool> {
    let mut stmt = conn
        .prepare(&format!("PRAGMA table_info({table})"))
        .map_err(|e| OakError::Database(e.to_string()))?;
    let mut rows = stmt
        .query([])
        .map_err(|e| OakError::Database(e.to_string()))?;
    while let Some(row) = rows.next().map_err(|e| OakError::Database(e.to_string()))? {
        let name: String = row.get(1).map_err(|e| OakError::Database(e.to_string()))?;
        if name == column {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Heuristic: has this migration already been applied? A positive result
/// lets the runner record the version without re-executing its DDL — used
/// when an existing repository (created under the pre-squash chain) is
/// opened by a build that only knows about the baseline.
fn migration_already_applied(version: &str, conn: &Connection) -> Result<bool> {
    match version {
        // Baseline is "applied" iff the schema already has the canonical
        // `commits` table — created by the original 001_initial and never
        // dropped, so its presence implies the squashed baseline's effects
        // are already in place.
        "0000_baseline" => {
            table_exists(conn, "commits").map_err(|e| OakError::Database(e.to_string()))
        }
        // 0001 rebuilds `commits`, `branches`, `branch_heads` to drop the
        // strict FKs on branch_name/parent_branch and to make
        // `commits.message` nullable. A freshly-created DB (built from the
        // current `0000_baseline`) already has the relaxed schema, so the
        // migration is a no-op there. Detect that case by checking whether
        // the stored CREATE TABLE for `commits` still has `message TEXT
        // NOT NULL` — the marker of the pre-relax schema.
        "0001_relax_branch_fks_and_message" => {
            let sql: Option<String> = conn
                .query_row(
                    "SELECT sql FROM sqlite_master WHERE type='table' AND name='commits'",
                    [],
                    |row| row.get(0),
                )
                .optional()
                .map_err(|e| OakError::Database(e.to_string()))?;
            // No `commits` table at all means the baseline hasn't run yet;
            // leave to the baseline migration to set up. If `commits` is
            // present and `message` is already nullable, the relax-pass is
            // implicit and we mark this version applied without re-running.
            Ok(sql
                .map(|s| !s.contains("message TEXT NOT NULL"))
                .unwrap_or(false))
        }
        // 0002 rebuilds `commits` to drop the FK on `parent_hash`. The
        // current baseline still has that FK, so a freshly-applied
        // baseline always needs this migration to run; only DBs that have
        // already been migrated (the stored `commits` CREATE TABLE no
        // longer mentions a FOREIGN KEY clause for parent_hash) should
        // mark this version applied without re-running.
        "0002_relax_commits_parent_hash_fk" => {
            let sql: Option<String> = conn
                .query_row(
                    "SELECT sql FROM sqlite_master WHERE type='table' AND name='commits'",
                    [],
                    |row| row.get(0),
                )
                .optional()
                .map_err(|e| OakError::Database(e.to_string()))?;
            Ok(sql
                .map(|s| !s.contains("FOREIGN KEY (parent_hash)"))
                .unwrap_or(false))
        }
        // These migrations are single ADD COLUMN statements. If a repository
        // was already upgraded but missed the corresponding tracker row, the
        // column is the authoritative marker; re-running the ALTER would fail
        // with "duplicate column name" and block opening the repo.
        "0007_blobs_codec" => column_exists(conn, "blobs", "codec"),
        "0008_trees_content" => column_exists(conn, "trees", "content"),
        "0010_branch_close_reason" => column_exists(conn, "branches", "close_reason"),
        "0012_pending_branch_description" => column_exists(conn, "branches", "description_pending"),
        _ => Ok(false),
    }
}

fn run_migrations(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS schema_migrations (
            version TEXT PRIMARY KEY,
            applied_at TEXT NOT NULL DEFAULT (datetime('now')),
            succeeded INTEGER NOT NULL DEFAULT 1
        )",
    )
    .map_err(|e| OakError::Database(e.to_string()))?;

    for m in MIGRATIONS {
        let already: Option<i64> = conn
            .query_row(
                "SELECT succeeded FROM schema_migrations WHERE version = ?1",
                params![m.version],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| OakError::Database(e.to_string()))?;
        if already == Some(1) {
            continue;
        }

        // Tracker doesn't know about this migration. If the schema already
        // reflects it (squashed baseline running against a database that
        // was migrated under the old per-step chain), mark applied without
        // re-running the DDL.
        if migration_already_applied(m.version, conn)? {
            conn.execute(
                "INSERT INTO schema_migrations (version, succeeded) VALUES (?1, 1)
                 ON CONFLICT(version) DO UPDATE SET succeeded = 1",
                params![m.version],
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
            continue;
        }

        match conn.execute_batch(m.sql) {
            Ok(_) => {
                conn.execute(
                    "INSERT INTO schema_migrations (version, succeeded) VALUES (?1, 1)
                     ON CONFLICT(version) DO UPDATE SET succeeded = 1",
                    params![m.version],
                )
                .map_err(|e| OakError::Database(e.to_string()))?;
            }
            Err(e) if m.required => {
                return Err(OakError::Database(format!(
                    "migration {} failed: {}",
                    m.version, e
                )));
            }
            Err(_) => {
                // Best-effort migration — record as attempted so we don't
                // retry every connect, but don't fail.
                conn.execute(
                    "INSERT INTO schema_migrations (version, succeeded) VALUES (?1, 0)
                     ON CONFLICT(version) DO NOTHING",
                    params![m.version],
                )
                .map_err(|e| OakError::Database(e.to_string()))?;
            }
        }
    }
    Ok(())
}

/// Restrict a freshly-created repo database to owner-only access (`0600`).
///
/// The repo `oak.db` can hold the user's API token (persisted on `oak clone`
/// / `oak create`), so it must not land at the umask default (typically
/// `0644`, world-readable) inside the working tree — mirroring the `0600`
/// handling of `~/.oak/credentials`. No-op on non-Unix; best-effort (a chmod
/// failure must not break opening the repo).
fn harden_db_file_permissions(db_path: &Path) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(db_path, std::fs::Permissions::from_mode(0o600));
    }
    #[cfg(not(unix))]
    {
        let _ = db_path;
    }
}

fn capture_integrity(capture_id: &str, detail: &str) -> OakError {
    OakError::ChangeCaptureIntegrity {
        capture_id: capture_id.to_string(),
        detail: detail.to_string(),
    }
}

fn validate_capture_id(capture_id: &str) -> Result<()> {
    let suffix = capture_id
        .strip_prefix("capture-")
        .ok_or_else(|| capture_integrity(capture_id, "invalid capture occurrence identifier"))?;
    if suffix.len() != 32
        || !suffix
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    {
        return Err(capture_integrity(
            capture_id,
            "invalid capture occurrence identifier",
        ));
    }
    Ok(())
}

fn parse_native_hash(capture_id: &str, value: &str, label: &str) -> Result<Hash> {
    if value.len() != 64
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    {
        return Err(capture_integrity(
            capture_id,
            &format!("invalid {label} identity"),
        ));
    }
    Hash::from_hex(value)
        .map_err(|_| capture_integrity(capture_id, &format!("invalid {label} identity")))
}

fn validate_capture_segment(capture_id: &str, value: &str, label: &str) -> Result<()> {
    if value.is_empty()
        || value.len() > 255
        || value.trim() != value
        || value == "."
        || value == ".."
        || value
            .chars()
            .any(|c| c.is_whitespace() || c.is_control() || c == '/' || c == '\\')
    {
        return Err(capture_integrity(
            capture_id,
            &format!("invalid stored {label}"),
        ));
    }
    Ok(())
}

fn validate_capture_branch(capture_id: &str, branch: &str) -> Result<()> {
    if branch.is_empty()
        || branch.trim() != branch
        || branch
            .chars()
            .any(|c| c.is_whitespace() || c.is_control() || c == '/' || c == '\\')
    {
        return Err(capture_integrity(
            capture_id,
            "invalid stored source branch",
        ));
    }
    Ok(())
}

fn validate_capture_origin(capture_id: &str, origin: &str) -> Result<()> {
    if origin.len() > 2_048
        || origin.chars().any(|c| c.is_whitespace() || c.is_control())
        || origin.contains(['?', '#'])
    {
        return Err(capture_integrity(
            capture_id,
            "invalid stored repository origin",
        ));
    }
    let authority_and_path = origin
        .strip_prefix("https://")
        .or_else(|| origin.strip_prefix("http://"))
        .ok_or_else(|| capture_integrity(capture_id, "invalid stored repository origin"))?;
    let authority = authority_and_path.split('/').next().unwrap_or_default();
    if authority.is_empty() || authority.contains('@') {
        return Err(capture_integrity(
            capture_id,
            "invalid stored repository origin",
        ));
    }
    Ok(())
}

fn validate_capture_provenance(
    capture_id: &str,
    owner: &str,
    name: &str,
    origin: Option<&str>,
    source_branch: &str,
    base_commit: Option<&Hash>,
) -> Result<()> {
    validate_capture_segment(capture_id, owner, "repository owner")?;
    validate_capture_segment(capture_id, name, "repository name")?;
    validate_capture_branch(capture_id, source_branch)?;
    if let Some(origin) = origin {
        validate_capture_origin(capture_id, origin)?;
    }
    if let Some(base_commit) = base_commit {
        parse_native_hash(capture_id, base_commit.as_str(), "base commit")?;
    }
    Ok(())
}

fn effective_head_in_connection(conn: &Connection, branch: &str) -> Result<Option<Hash>> {
    let mut seen = HashSet::new();
    let mut current = branch.to_string();
    loop {
        if !seen.insert(current.clone()) {
            return Ok(None);
        }
        let head: Option<String> = conn
            .query_row(
                "SELECT head_hash FROM branch_heads WHERE branch_name = ?1",
                [current.as_str()],
                |row| row.get(0),
            )
            .optional()
            .map_err(|error| OakError::Database(error.to_string()))?;
        if let Some(head) = head {
            return Ok(Some(Hash(head)));
        }
        let parent: Option<Option<String>> = conn
            .query_row(
                "SELECT parent_branch FROM branches WHERE name = ?1",
                [current.as_str()],
                |row| row.get(0),
            )
            .optional()
            .map_err(|error| OakError::Database(error.to_string()))?;
        match parent.flatten() {
            Some(parent) => current = parent,
            None => return Ok(None),
        }
    }
}

fn validate_capture_base_in_connection(
    conn: &Connection,
    capture_id: &str,
    base_commit: Option<&Hash>,
    base_tree: &Hash,
) -> Result<()> {
    let Some(base_commit) = base_commit else {
        if base_tree != &Tree::empty_hash() {
            return Err(capture_integrity(
                capture_id,
                "a headless capture must use the canonical empty base tree",
            ));
        }
        return Ok(());
    };
    let manifest_hash: Option<String> = conn
        .query_row(
            "SELECT manifest_hash FROM commits WHERE hash = ?1",
            [base_commit.as_str()],
            |row| row.get(0),
        )
        .optional()
        .map_err(|error| OakError::Database(error.to_string()))?;
    let Some(manifest_hash) = manifest_hash else {
        return Err(capture_integrity(
            capture_id,
            "the recorded base commit is unavailable",
        ));
    };
    let manifest_hash = parse_native_hash(capture_id, &manifest_hash, "base commit tree")?;
    if &manifest_hash != base_tree {
        return Err(capture_integrity(
            capture_id,
            "the descriptor base tree does not match the recorded base commit",
        ));
    }
    Ok(())
}

/// SQLite can report CANTOPEN when a full filesystem prevents WAL/SHM
/// creation. Consult free space only after that specific failure; permissions
/// and malformed database errors must retain their original diagnosis.
fn sqlite_open_error(path: &Path, error: rusqlite::Error) -> OakError {
    if matches!(&error, rusqlite::Error::SqliteFailure(code, _) if code.code == rusqlite::ErrorCode::DiskFull)
    {
        return OakError::DiskFull {
            path: path.display().to_string(),
        };
    }
    diagnose_open_storage_error(path, OakError::Database(error.to_string()))
}

fn diagnose_open_storage_error(path: &Path, error: OakError) -> OakError {
    let OakError::Database(message) = &error else {
        return error;
    };
    let sqlite_full = message == "database or disk is full";
    let may_be_full = message.starts_with("unable to open database file")
        || message.starts_with("disk I/O error");
    if sqlite_full || (may_be_full && filesystem_is_full(path)) {
        OakError::DiskFull {
            path: path.display().to_string(),
        }
    } else {
        error
    }
}

#[cfg(unix)]
fn filesystem_is_full(path: &Path) -> bool {
    use std::os::unix::ffi::OsStrExt;
    let Some(existing) = path.ancestors().find(|p| p.exists()) else {
        return false;
    };
    let Ok(path) = std::ffi::CString::new(existing.as_os_str().as_bytes()) else {
        return false;
    };
    let mut stats = std::mem::MaybeUninit::<libc::statvfs>::uninit();
    // SAFETY: path is NUL terminated and stats points to writable storage.
    if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 {
        return false;
    }
    // SAFETY: statvfs initialized stats on success.
    let stats = unsafe { stats.assume_init() };
    stats.f_bavail == 0
}

#[cfg(not(unix))]
fn filesystem_is_full(_path: &Path) -> bool {
    false
}

/// Buffer between SQLite incremental blob I/O and the decoder.
const STORED_BLOB_READ_BYTES: usize = 1024 * 1024;

/// One open incremental-I/O handle on a `blobs.content` row, together with
/// the read-only connection it belongs to.
///
/// The handle must stay open for the whole stream: SQLite finds an offset in
/// a large row by walking its overflow-page chain, and only an open handle
/// remembers that chain, so re-opening per read makes a sequential read
/// quadratic. A handle borrows its connection, and the repository's own
/// connection sits behind a mutex that must not stay locked between reads,
/// so the stream owns a private read-only connection instead.
struct StoredBlobRows {
    // Field order is drop order: the handle is closed before its connection.
    blob: rusqlite::blob::Blob<'static>,
    _conn: Box<Connection>,
}

// SAFETY: `blob` borrows only `_conn`, which this struct owns exclusively and
// which is never shared, so the pair is used by one thread at a time and may
// move between threads together (`Connection` itself is `Send`).
unsafe impl Send for StoredBlobRows {}

impl StoredBlobRows {
    fn open(db_path: &Path, rowid: i64) -> Result<Self> {
        let conn = Box::new(
            Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
                .map_err(|e| OakError::Database(e.to_string()))?,
        );
        let blob = conn
            .blob_open(rusqlite::MAIN_DB, "blobs", "content", rowid, true)
            .map_err(|e| OakError::Database(e.to_string()))?;
        // SAFETY: the handle borrows the boxed connection, whose heap address
        // is stable for as long as `_conn` lives; the struct never hands out
        // the connection and drops `blob` first (field order above), so the
        // extended lifetime never outlives the connection it refers to.
        let blob = unsafe {
            std::mem::transmute::<rusqlite::blob::Blob<'_>, rusqlite::blob::Blob<'static>>(blob)
        };
        Ok(Self { blob, _conn: conn })
    }
}

impl std::io::Read for StoredBlobRows {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        std::io::Read::read(&mut self.blob, buf)
    }
}

enum StoredBlobReaderInner {
    Raw(std::io::BufReader<StoredBlobRows>),
    Zstd(Box<zstd::stream::read::Decoder<'static, std::io::BufReader<StoredBlobRows>>>),
}

/// Reader returned by [`SqliteRepository::stored_blob_reader`].
pub struct StoredBlobReader {
    inner: StoredBlobReaderInner,
}

impl std::io::Read for StoredBlobReader {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match &mut self.inner {
            StoredBlobReaderInner::Raw(rows) => rows.read(buf),
            StoredBlobReaderInner::Zstd(decoder) => decoder.read(buf),
        }
    }
}

impl SqliteRepository {
    /// Run `f` inside one read transaction when the connection isn't already
    /// in one. In WAL mode every autocommit statement takes and releases the
    /// shared-memory read lock itself, which dominates a loop of point lookups.
    fn with_read_txn<T>(conn: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        if !conn.is_autocommit() {
            return f(conn);
        }
        conn.execute_batch("BEGIN DEFERRED")
            .map_err(|e| OakError::Database(e.to_string()))?;
        let result = f(conn);
        let end = conn
            .execute_batch("COMMIT")
            .map_err(|e| OakError::Database(e.to_string()));
        let value = result?;
        end?;
        Ok(value)
    }

    /// `(size, chunk reference count)` of each stored blob, in order, without
    /// reading blob bytes; `None` for a blob not stored locally. One read
    /// transaction and two cached statements for the whole batch.
    pub fn blob_descriptors(&self, hashes: &[&Hash]) -> Result<Vec<Option<(u64, usize)>>> {
        let conn = self.conn.lock().unwrap();
        Self::with_read_txn(&conn, |conn| {
            let db = |e: rusqlite::Error| OakError::Database(e.to_string());
            let mut size_stmt = conn
                .prepare_cached("SELECT size FROM blobs WHERE hash = ?1")
                .map_err(db)?;
            let mut chunks_stmt = conn
                .prepare_cached("SELECT COUNT(*) FROM blob_chunks WHERE blob_hash = ?1")
                .map_err(db)?;
            hashes
                .iter()
                .map(|hash| {
                    let Some(size) = size_stmt
                        .query_row(params![hash.as_str()], |row| row.get::<_, i64>(0))
                        .optional()
                        .map_err(db)?
                    else {
                        return Ok(None);
                    };
                    let chunk_refs: i64 = chunks_stmt
                        .query_row(params![hash.as_str()], |row| row.get(0))
                        .map_err(db)?;
                    Ok(Some((size as u64, chunk_refs as usize)))
                })
                .collect()
        })
    }

    /// Inspect an existing repository in one SQLite read transaction. Does not
    /// create a database, migrate schema, chmod, or change journal mode. Normal
    /// SQLite locking remains enabled (WAL coordination sidecars may be used).
    /// Mutating Repository methods fail on this connection.
    pub fn open_read_only(db_path: &Path) -> Result<Self> {
        let conn = Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
            .map_err(|e| OakError::Database(e.to_string()))?;
        conn.busy_timeout(std::time::Duration::from_millis(100))
            .map_err(|e| OakError::Database(e.to_string()))?;
        conn.execute_batch("BEGIN DEFERRED")
            .map_err(|e| OakError::Database(e.to_string()))?;
        // Pin the read snapshot now. Refuse an unknown/partial schema rather
        // than migrating it or interpreting missing columns as empty state.
        {
            let mut stmt = conn
                .prepare("SELECT version, succeeded FROM schema_migrations LIMIT 1000")
                .map_err(|e| OakError::Database(e.to_string()))?;
            let rows = stmt
                .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?)))
                .map_err(|e| OakError::Database(e.to_string()))?;
            let versions = rows
                .collect::<std::result::Result<Vec<_>, _>>()
                .map_err(|e| OakError::Database(e.to_string()))?;
            if !versions
                .iter()
                .any(|(version, ok)| *ok && version == "0000_baseline")
                || versions
                    .iter()
                    .any(|(version, ok)| !ok || !MIGRATIONS.iter().any(|m| m.version == version))
            {
                return Err(OakError::Database(
                    "unsupported schema for read-only inspection".into(),
                ));
            }
        }
        Ok(Self {
            conn: Mutex::new(conn),
            tree_flattens: AtomicU64::new(0),
            tree_reads: AtomicU64::new(0),
        })
    }

    /// Open or create a SQLite repository at the given path
    pub fn open(db_path: &Path) -> Result<Self> {
        (|| -> Result<Self> {
            let conn = Connection::open(db_path).map_err(|e| sqlite_open_error(db_path, e))?;
            conn.busy_timeout(std::time::Duration::from_secs(5))
                .map_err(|e| sqlite_open_error(db_path, e))?;
            harden_db_file_permissions(db_path);

            // Enable WAL mode for concurrent multi-process access
            conn.execute_batch("PRAGMA journal_mode=WAL;")
                .map_err(|e| sqlite_open_error(db_path, e))?;

            run_migrations(&conn)?;

            Ok(SqliteRepository {
                conn: Mutex::new(conn),
                tree_flattens: AtomicU64::new(0),
                tree_reads: AtomicU64::new(0),
            })
        })()
        .map_err(|error| diagnose_open_storage_error(db_path, error))
    }

    /// Open or create a SQLite repository at the given path with foreign-key
    /// enforcement disabled.
    ///
    /// Used by `oak mount` for its lazy blob cache: the mount stores a
    /// manifest whose entries reference blobs that haven't been fetched
    /// yet. The default schema declares `manifest_entries.blob_hash` as a
    /// foreign key to `blobs(hash)`; rusqlite enables enforcement by
    /// default, so inserts would fail. The mount cache is a private,
    /// per-mount store — relaxing FK enforcement is safe there because
    /// nothing else points at it.
    pub fn open_relaxed(db_path: &Path) -> Result<Self> {
        (|| -> Result<Self> {
            let conn = Connection::open(db_path).map_err(|e| sqlite_open_error(db_path, e))?;
            conn.busy_timeout(std::time::Duration::from_secs(5))
                .map_err(|e| sqlite_open_error(db_path, e))?;
            harden_db_file_permissions(db_path);
            conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=OFF;")
                .map_err(|e| sqlite_open_error(db_path, e))?;
            run_migrations(&conn)?;
            Ok(SqliteRepository {
                conn: Mutex::new(conn),
                tree_flattens: AtomicU64::new(0),
                tree_reads: AtomicU64::new(0),
            })
        })()
        .map_err(|error| diagnose_open_storage_error(db_path, error))
    }

    /// A sequential reader over a stored blob's plaintext that never holds
    /// the whole blob: the stored row is read through SQLite incremental
    /// blob I/O on a private read-only connection (the repository's own
    /// connection is not locked while the stream is open) and zstd rows are
    /// decoded as a stream. It reads committed state. Returns the blob's
    /// declared size with the reader, or `None` when the blob has no
    /// content row. The caller verifies the bytes against the hash.
    pub fn stored_blob_reader(&self, hash: &Hash) -> Result<Option<(u64, StoredBlobReader)>> {
        let row: Option<(i64, i64, i64)> = {
            let conn = self.conn.lock().unwrap();
            conn.query_row(
                "SELECT rowid, size, codec FROM blobs WHERE hash = ?1",
                params![hash.as_str()],
                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
            )
            .optional()
            .map_err(|e| OakError::Database(e.to_string()))?
        };
        let Some((rowid, size, codec)) = row else {
            return Ok(None);
        };
        let rows = std::io::BufReader::with_capacity(
            STORED_BLOB_READ_BYTES,
            StoredBlobRows::open(&self.database_path()?, rowid)?,
        );
        let inner = if codec == CODEC_ZSTD {
            StoredBlobReaderInner::Zstd(Box::new(
                zstd::stream::read::Decoder::with_buffer(rows)
                    .map_err(|e| OakError::Database(format!("zstd decompress: {e}")))?,
            ))
        } else {
            StoredBlobReaderInner::Raw(rows)
        };
        Ok(Some((size as u64, StoredBlobReader { inner })))
    }

    pub fn database_path(&self) -> Result<PathBuf> {
        let conn = self.conn.lock().unwrap();
        conn.path()
            .map(PathBuf::from)
            .ok_or_else(|| OakError::Database("repository is not file-backed".to_string()))
    }

    /// Atomically publish a complete canonical descriptor and one immutable
    /// local capture occurrence after rechecking the branch snapshot inside
    /// the write transaction. Identical portable changes share one descriptor;
    /// provenance rows are never replaced or deduplicated.
    #[allow(clippy::too_many_arguments)]
    pub fn store_change_capture(
        &self,
        capture_id: &str,
        change_set: &CanonicalChangeSetV1,
        owner: &str,
        name: &str,
        origin: Option<&str>,
        source_branch: &str,
        base_commit: Option<&Hash>,
    ) -> Result<()> {
        validate_capture_id(capture_id)?;
        validate_capture_provenance(capture_id, owner, name, origin, source_branch, base_commit)?;
        let (scope_kind, scope_paths_json, descriptor_json) =
            self.validate_change_set_objects(capture_id, change_set)?;
        let now = chrono::Utc::now().to_rfc3339();

        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(|error| OakError::Database(error.to_string()))?;

        let current_branch: Option<String> = tx
            .query_row(
                "SELECT value FROM metadata WHERE key = ?1",
                [MetadataKey::CurrentBranch.as_str()],
                |row| row.get(0),
            )
            .optional()
            .map_err(|error| OakError::Database(error.to_string()))?;
        let current_head = effective_head_in_connection(&tx, source_branch)?;
        if current_branch.as_deref() != Some(source_branch) || current_head.as_ref() != base_commit
        {
            return Err(OakError::WorktreeCaptureRaced {
                detail: "the current branch or effective HEAD changed before durable capture publication"
                    .to_string(),
            });
        }
        validate_capture_base_in_connection(&tx, capture_id, base_commit, change_set.base_tree())?;

        tx.execute(
            "INSERT OR IGNORE INTO change_sets
             (change_id, schema_version, object_format, base_tree_hash, result_tree_hash,
              scope_kind, scope_paths_json, descriptor_json, created_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
            params![
                change_set.id().as_str(),
                i64::from(change_set.schema_version()),
                change_set.object_format(),
                change_set.base_tree().as_str(),
                change_set.result_tree().as_str(),
                scope_kind,
                scope_paths_json,
                descriptor_json,
                now,
            ],
        )
        .map_err(|error| OakError::Database(error.to_string()))?;

        let stored: (i64, String, String, String, String, String, String) = tx
            .query_row(
                "SELECT schema_version, object_format, base_tree_hash, result_tree_hash,
                        scope_kind, scope_paths_json, descriptor_json
                 FROM change_sets WHERE change_id = ?1",
                [change_set.id().as_str()],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                        row.get(5)?,
                        row.get(6)?,
                    ))
                },
            )
            .map_err(|_| capture_integrity(capture_id, "stored descriptor row is unreadable"))?;
        if stored
            != (
                i64::from(change_set.schema_version()),
                change_set.object_format().to_string(),
                change_set.base_tree().to_string(),
                change_set.result_tree().to_string(),
                scope_kind.to_string(),
                scope_paths_json.clone(),
                descriptor_json.clone(),
            )
        {
            return Err(capture_integrity(
                capture_id,
                "change ID already names a different or corrupt descriptor",
            ));
        }

        tx.execute(
            "INSERT INTO change_captures
             (capture_id, change_id, format_version, repo_owner, repo_name, origin,
              source_branch, base_commit_hash, captured_at)
             VALUES (?1, ?2, 1, ?3, ?4, ?5, ?6, ?7, ?8)",
            params![
                capture_id,
                change_set.id().as_str(),
                owner,
                name,
                origin,
                source_branch,
                base_commit.map(Hash::as_str),
                now,
            ],
        )
        .map_err(|_| {
            capture_integrity(
                capture_id,
                "capture occurrence ID already exists or provenance could not be stored",
            )
        })?;
        tx.commit()
            .map_err(|error| OakError::Database(error.to_string()))?;
        Ok(())
    }

    /// Resolve one durable capture occurrence and rederive its complete
    /// canonical descriptor from the immutable base/result tree objects.
    /// Working-tree bytes are never rescanned and inherited blobs are not
    /// hydrated by this lookup.
    pub fn get_change_capture(&self, capture_id: &str) -> Result<StoredChangeCapture> {
        if validate_capture_id(capture_id).is_err() {
            return Err(OakError::ChangeCaptureNotFound {
                capture_id: capture_id.to_string(),
            });
        }
        let conn = self.conn.lock().unwrap();
        let occurrence: Option<ChangeCaptureRow> = conn
            .query_row(
                "SELECT change_id, format_version, repo_owner, repo_name, origin,
                        source_branch, base_commit_hash, captured_at
                 FROM change_captures WHERE capture_id = ?1",
                [capture_id],
                |row| {
                    Ok(ChangeCaptureRow {
                        change_id: row.get(0)?,
                        format_version: row.get(1)?,
                        owner: row.get(2)?,
                        name: row.get(3)?,
                        origin: row.get(4)?,
                        source_branch: row.get(5)?,
                        base_commit: row.get(6)?,
                        captured_at: row.get(7)?,
                    })
                },
            )
            .optional()
            .map_err(|_| capture_integrity(capture_id, "capture occurrence row is unreadable"))?;
        let Some(ChangeCaptureRow {
            change_id,
            format_version,
            owner,
            name,
            origin,
            source_branch,
            base_commit,
            captured_at,
        }) = occurrence
        else {
            return Err(OakError::ChangeCaptureNotFound {
                capture_id: capture_id.to_string(),
            });
        };
        if format_version != 1 {
            return Err(capture_integrity(
                capture_id,
                "unsupported capture occurrence format",
            ));
        }
        let base_commit = base_commit
            .as_deref()
            .map(|value| parse_native_hash(capture_id, value, "base commit"))
            .transpose()?;
        validate_capture_provenance(
            capture_id,
            &owner,
            &name,
            origin.as_deref(),
            &source_branch,
            base_commit.as_ref(),
        )?;
        let captured_at = chrono::DateTime::parse_from_rfc3339(&captured_at)
            .map_err(|_| capture_integrity(capture_id, "invalid capture timestamp"))?
            .with_timezone(&chrono::Utc);

        let descriptor: Option<ChangeSetRow> = conn
            .query_row(
                "SELECT schema_version, object_format, base_tree_hash, result_tree_hash,
                        scope_kind, scope_paths_json, descriptor_json, created_at
                 FROM change_sets WHERE change_id = ?1",
                [change_id.as_str()],
                |row| {
                    Ok(ChangeSetRow {
                        schema_version: row.get(0)?,
                        object_format: row.get(1)?,
                        base_tree: row.get(2)?,
                        result_tree: row.get(3)?,
                        scope_kind: row.get(4)?,
                        scope_paths_json: row.get(5)?,
                        descriptor_json: row.get(6)?,
                        created_at: row.get(7)?,
                    })
                },
            )
            .optional()
            .map_err(|_| capture_integrity(capture_id, "stored descriptor row is unreadable"))?;
        drop(conn);
        let Some(ChangeSetRow {
            schema_version,
            object_format,
            base_tree,
            result_tree,
            scope_kind,
            scope_paths_json,
            descriptor_json,
            created_at: descriptor_created_at,
        }) = descriptor
        else {
            return Err(capture_integrity(
                capture_id,
                "capture occurrence references a missing descriptor",
            ));
        };
        if schema_version != 1 || object_format != CHANGE_SET_OBJECT_FORMAT_V1 {
            return Err(capture_integrity(
                capture_id,
                "unsupported or corrupt change descriptor format",
            ));
        }
        chrono::DateTime::parse_from_rfc3339(&descriptor_created_at)
            .map_err(|_| capture_integrity(capture_id, "invalid descriptor timestamp"))?;
        let base_tree = parse_native_hash(capture_id, &base_tree, "base tree")?;
        let result_tree = parse_native_hash(capture_id, &result_tree, "result tree")?;
        let stored_change_id = parse_native_hash(capture_id, &change_id, "change ID")?;
        let paths: Vec<String> = serde_json::from_str(&scope_paths_json)
            .map_err(|_| capture_integrity(capture_id, "invalid descriptor scope"))?;
        let scope = match scope_kind.as_str() {
            "full" if scope_paths_json == "[]" => ChangeScopeV1::Full,
            "paths" => ChangeScopeV1::Paths { paths },
            _ => return Err(capture_integrity(capture_id, "invalid descriptor scope")),
        };
        let base_manifest = self
            .get_manifest(&base_tree)
            .map_err(|_| capture_integrity(capture_id, "base tree could not be validated"))?
            .ok_or_else(|| capture_integrity(capture_id, "base tree is missing"))?;
        let result_manifest = self
            .get_manifest(&result_tree)
            .map_err(|_| capture_integrity(capture_id, "result tree could not be validated"))?
            .ok_or_else(|| capture_integrity(capture_id, "result tree is missing"))?;
        let change_set =
            CanonicalChangeSetV1::from_manifests(&base_manifest, &result_manifest, scope)
                .map_err(|_| capture_integrity(capture_id, "descriptor could not be rederived"))?;
        let canonical_json = serde_json::to_string(&change_set)
            .map_err(|_| capture_integrity(capture_id, "descriptor could not be encoded"))?;
        let canonical_scope_json = match change_set.scope() {
            ChangeScopeV1::Full => "[]".to_string(),
            ChangeScopeV1::Paths { paths } => serde_json::to_string(paths).map_err(|_| {
                capture_integrity(capture_id, "descriptor scope could not be encoded")
            })?,
        };
        let expected_scope_kind = match change_set.scope() {
            ChangeScopeV1::Full => "full",
            ChangeScopeV1::Paths { .. } => "paths",
        };
        if change_set.id() != &stored_change_id
            || change_set.base_tree() != &base_tree
            || change_set.result_tree() != &result_tree
            || scope_kind != expected_scope_kind
            || scope_paths_json != canonical_scope_json
            || descriptor_json != canonical_json
        {
            return Err(capture_integrity(
                capture_id,
                "stored descriptor does not match its canonical tree-derived identity",
            ));
        }
        match base_commit.as_ref() {
            Some(base_commit) => {
                let commit = self
                    .get_commit(base_commit)
                    .map_err(|_| {
                        capture_integrity(capture_id, "the recorded base commit is unavailable")
                    })?
                    .ok_or_else(|| {
                        capture_integrity(capture_id, "the recorded base commit is unavailable")
                    })?;
                if commit.manifest_hash != base_tree {
                    return Err(capture_integrity(
                        capture_id,
                        "the descriptor base tree does not match the recorded base commit",
                    ));
                }
            }
            None if base_tree != Tree::empty_hash() => {
                return Err(capture_integrity(
                    capture_id,
                    "a headless capture must use the canonical empty base tree",
                ));
            }
            None => {}
        }
        Ok(StoredChangeCapture {
            capture_id: capture_id.to_string(),
            change_set,
            provenance: ChangeCaptureProvenance {
                owner,
                name,
                origin,
                source_branch,
                base_commit,
                captured_at,
            },
        })
    }

    fn validate_change_set_objects(
        &self,
        capture_id: &str,
        change_set: &CanonicalChangeSetV1,
    ) -> Result<(&'static str, String, String)> {
        let base = self
            .get_manifest(change_set.base_tree())
            .map_err(|_| capture_integrity(capture_id, "base tree could not be validated"))?
            .ok_or_else(|| capture_integrity(capture_id, "base tree is missing"))?;
        let result = self
            .get_manifest(change_set.result_tree())
            .map_err(|_| capture_integrity(capture_id, "result tree could not be validated"))?
            .ok_or_else(|| capture_integrity(capture_id, "result tree is missing"))?;
        let rederived =
            CanonicalChangeSetV1::from_manifests(&base, &result, change_set.scope().clone())
                .map_err(|_| capture_integrity(capture_id, "descriptor could not be rederived"))?;
        if &rederived != change_set {
            return Err(capture_integrity(
                capture_id,
                "descriptor does not match its canonical tree-derived identity",
            ));
        }
        let (scope_kind, scope_paths_json) = match change_set.scope() {
            ChangeScopeV1::Full => ("full", "[]".to_string()),
            ChangeScopeV1::Paths { paths } => (
                "paths",
                serde_json::to_string(paths).map_err(|_| {
                    capture_integrity(capture_id, "descriptor scope could not be encoded")
                })?,
            ),
        };
        let descriptor_json = serde_json::to_string(change_set)
            .map_err(|_| capture_integrity(capture_id, "descriptor could not be encoded"))?;
        Ok((scope_kind, scope_paths_json, descriptor_json))
    }

    ///
    /// The server's PostgreSQL schema is more permissive than the client's
    /// SQLite schema: `parent_branch` and `parent_hash` are unenforced on the
    /// server but FK-checked here. Bulk imports (e.g. `oak clone`) need to relax
    /// enforcement so that legitimate server data — branches whose parent has
    /// been deleted, or commits whose timestamp ordering doesn't match
    /// topology — can be ingested. Always re-enable after the bulk load so
    /// subsequent normal operations stay validated.
    pub fn set_foreign_keys(&self, enabled: bool) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let pragma = if enabled {
            "PRAGMA foreign_keys=ON;"
        } else {
            "PRAGMA foreign_keys=OFF;"
        };
        conn.execute_batch(pragma)
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    /// Reconcile cached metadata with a remote row, retaining pending local descriptions.
    ///
    /// `store_branch` is insert-only because local callers often create a
    /// placeholder branch row before later local edits. Remote refresh paths
    /// refresh lifecycle fields, but a locally edited description remains owned
    /// by the user until observed/published remotely with that exact value.
    /// Returns false when a newer local generation fenced out this response's
    /// description. Lifecycle reconciliation still follows the caller policy.
    pub fn upsert_branch_metadata_at_generation(
        &self,
        branch: &Branch,
        observed_generation: i64,
    ) -> Result<bool> {
        self.reconcile_branch_metadata(branch, true, observed_generation)
    }

    /// Pull preserves existing local lifecycle decisions (e.g. an unsynced
    /// close) while refreshing descriptions that have no pending local edit.
    /// The parent branch is the exception: the server owns it (it restacks a
    /// branch when its parent lands), so a non-null remote parent always wins.
    /// Returns false if the response predates this branch's local generation.
    pub fn reconcile_pulled_branch_metadata(
        &self,
        branch: &Branch,
        observed_generation: i64,
    ) -> Result<bool> {
        self.reconcile_branch_metadata(branch, false, observed_generation)
    }

    /// Capture before issuing a remote metadata request; never reconstruct this
    /// token from local state after the response arrives.
    pub fn description_generation(&self) -> Result<i64> {
        self.conn
            .lock()
            .unwrap()
            .query_row(
                "SELECT generation FROM branch_description_clock WHERE singleton = 1",
                [],
                |row| row.get(0),
            )
            .map_err(|error| OakError::Database(error.to_string()))
    }

    fn reconcile_branch_metadata(
        &self,
        branch: &Branch,
        refresh_lifecycle: bool,
        observed_generation: i64,
    ) -> Result<bool> {
        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .savepoint()
            .map_err(|error| OakError::Database(error.to_string()))?;
        let generation = advance_description_generation(&tx)?;
        let fresh = tx
            .query_row(
                "SELECT description_generation <= ?2 FROM branches WHERE name = ?1",
                params![branch.name, observed_generation],
                |row| row.get::<_, bool>(0),
            )
            .optional()
            .map_err(|error| OakError::Database(error.to_string()))?
            .unwrap_or(true);
        tx.execute(
            "INSERT INTO branches (name, description, parent_branch, status, close_reason, created_at, description_generation) \
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?9) \
             ON CONFLICT(name) DO UPDATE SET \
               description = CASE WHEN branches.description_generation <= ?8 AND branches.description_pending = 0 THEN excluded.description ELSE branches.description END, \
               description_pending = CASE WHEN branches.description_generation <= ?8 AND branches.description IS excluded.description THEN 0 ELSE branches.description_pending END, \
               description_generation = CASE WHEN branches.description_generation <= ?8 AND (branches.description_pending = 0 OR branches.description IS excluded.description) THEN ?9 ELSE branches.description_generation END, \
               parent_branch = CASE WHEN ?7 OR excluded.parent_branch IS NOT NULL THEN excluded.parent_branch ELSE branches.parent_branch END, \
               status = CASE WHEN ?7 THEN excluded.status ELSE branches.status END, \
               close_reason = CASE WHEN ?7 THEN excluded.close_reason ELSE branches.close_reason END, \
               created_at = CASE WHEN ?7 THEN excluded.created_at ELSE branches.created_at END",
            params![
                branch.name,
                branch.description,
                branch.parent_branch,
                branch.status.as_str(),
                branch.close_reason.as_ref().map(|r| r.as_str()),
                branch.created_at.to_rfc3339(),
                refresh_lifecycle,
                observed_generation,
                generation,
            ],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        tx.commit()
            .map_err(|error| OakError::Database(error.to_string()))?;
        Ok(fresh)
    }

    /// A description edited locally (or predating synchronization tracking)
    /// must not be replaced by a differing remote value.
    pub fn branch_description_pending(&self, name: &str) -> Result<bool> {
        let conn = self.conn.lock().unwrap();
        conn.query_row(
            "SELECT description_pending != 0 FROM branches WHERE name = ?1",
            [name],
            |row| row.get(0),
        )
        .optional()
        .map(|value| value.unwrap_or(false))
        .map_err(|error| OakError::Database(error.to_string()))
    }

    /// Begin a relaxed-durability transaction for a bulk ingest (clone / pull).
    ///
    /// Lowers `synchronous` to `NORMAL` and opens a transaction, so the many
    /// per-object INSERTs that follow commit as a batch instead of fsync-ing
    /// once per statement. The default `synchronous=FULL` in WAL mode fsyncs
    /// on every auto-commit, and the clone ingest writes each chunk, blob,
    /// `blob_chunks` row, tree, and commit as its own statement — so that
    /// per-statement fsync dominates clone time on repos with many files.
    /// Subsequent `store_*` calls join this open transaction (SQLite leaves
    /// auto-commit mode while a manual `BEGIN` is active).
    ///
    /// Pair with [`Self::bulk_flush`] (called periodically to bound WAL
    /// growth on a large import) and exactly one of [`Self::bulk_commit`] /
    /// [`Self::bulk_rollback`]. Single-writer only: the caller must not issue
    /// writes through another handle to the same database while the batch is
    /// open, or that write will silently join — and ride the fate of — this
    /// transaction.
    pub fn bulk_begin(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute_batch("PRAGMA synchronous=NORMAL; BEGIN;")
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    /// Commit the current bulk batch and immediately open the next, so a long
    /// import doesn't accumulate its entire dataset in the WAL before a single
    /// final commit. Cheap under `synchronous=NORMAL` — no fsync until the
    /// next checkpoint.
    pub fn bulk_flush(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute_batch("COMMIT; BEGIN;")
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    /// Commit the bulk transaction and restore full durability.
    pub fn bulk_commit(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute_batch("COMMIT; PRAGMA synchronous=FULL;")
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    /// Roll back an in-flight bulk transaction and restore full durability.
    /// Best-effort, for the error path so a failed import doesn't leave a
    /// dangling transaction or a half-applied batch behind.
    pub fn bulk_rollback(&self) {
        if let Ok(conn) = self.conn.lock() {
            let _ = conn.execute_batch("ROLLBACK; PRAGMA synchronous=FULL;");
        }
    }

    /// Begin a normal durable write transaction.
    ///
    /// Unlike [`Self::bulk_begin`], this deliberately leaves SQLite's
    /// durability pragmas alone. Use it for small publication steps where the
    /// caller needs many repository setters to become observable as one unit.
    pub fn write_txn_begin(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute_batch("BEGIN IMMEDIATE;")
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    /// Commit a transaction opened with [`Self::write_txn_begin`].
    pub fn write_txn_commit(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute_batch("COMMIT;")
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    /// Roll back a transaction opened with [`Self::write_txn_begin`].
    pub fn write_txn_rollback(&self) {
        if let Ok(conn) = self.conn.lock() {
            let _ = conn.execute_batch("ROLLBACK;");
        }
    }

    /// Remove a metadata row entirely (rather than storing an empty value).
    pub fn delete_metadata(&self, key: MetadataKey) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute("DELETE FROM metadata WHERE key = ?1", params![key.as_str()])
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    /// Create an in-memory repository (for testing)
    #[cfg(test)]
    pub fn in_memory() -> Result<Self> {
        let conn = Connection::open_in_memory().map_err(|e| OakError::Database(e.to_string()))?;
        run_migrations(&conn)?;
        Ok(SqliteRepository {
            conn: Mutex::new(conn),
            tree_flattens: AtomicU64::new(0),
            tree_reads: AtomicU64::new(0),
        })
    }

    /// Open a [`BulkImporter`] against the same database file.
    ///
    /// The importer holds its own connection (so it can manage long-lived
    /// transactions independently of the regular repo's mutex), batches writes
    /// across `batch_size` commits, and caches inserted-tree hashes in memory
    /// to skip per-subtree EXISTS lookups during deeply repetitive imports
    /// (e.g. `oak clone <git-url>` or `oak init` over an existing `.git`).
    ///
    /// The caller must not concurrently issue writes via the underlying
    /// `SqliteRepository` until the importer is dropped or finished —
    /// SQLite only allows one writer at a time, and a clash will block.
    pub fn bulk_importer(&self, batch_size: usize) -> Result<BulkImporter> {
        let conn = self.conn.lock().unwrap();
        let path = conn
            .path()
            .ok_or_else(|| {
                OakError::Database("bulk importer requires a file-backed connection".to_string())
            })?
            .to_string();
        drop(conn);
        BulkImporter::open(Path::new(&path), batch_size)
    }

    /// One-shot storage compaction. Converts the database to the compact
    /// on-disk format and reclaims the freed space:
    ///   1. Backfills `trees.content` for every legacy tree (one still stored as
    ///      `tree_entries` rows), verifying each reconstructed tree re-hashes to
    ///      its key before writing.
    ///   2. Drops the now-unused `tree_entries` table (only if every tree has
    ///      `content`, so the fallback path is never needed again).
    ///   3. Re-compresses legacy raw blobs (`codec = 0`) that actually shrink.
    ///   4. `VACUUM`s to shrink the file on disk.
    ///
    /// Idempotent: a second run finds nothing to backfill/recompress and just
    /// VACUUMs. `VACUUM` needs transient free disk roughly equal to the final
    /// database size.
    pub fn compact_storage(&self) -> Result<CompactStats> {
        let mut conn = self.conn.lock().unwrap();

        // 1. Backfill legacy trees (content IS NULL) from tree_entries.
        let legacy_trees: Vec<String> = {
            let table = table_exists(&conn, "tree_entries")
                .map_err(|e| OakError::Database(e.to_string()))?;
            if !table {
                Vec::new() // already compacted away
            } else {
                let mut stmt = conn
                    .prepare("SELECT hash FROM trees WHERE content IS NULL")
                    .map_err(|e| OakError::Database(e.to_string()))?;
                let rows = stmt
                    .query_map([], |r| r.get::<_, String>(0))
                    .map_err(|e| OakError::Database(e.to_string()))?;
                rows.collect::<std::result::Result<Vec<_>, _>>()
                    .map_err(|e| OakError::Database(e.to_string()))?
            }
        };

        let mut trees_backfilled = 0u64;
        if !legacy_trees.is_empty() {
            let tx = conn
                .transaction()
                .map_err(|e| OakError::Database(e.to_string()))?;
            for h in &legacy_trees {
                let hash = Hash(h.clone());
                let tree = read_tree_entries(&tx, &hash)?;
                // Integrity: the reconstructed tree must re-hash to its key.
                if hash_bytes(&tree.canonical_bytes()) != hash {
                    return Err(OakError::Database(format!(
                        "tree {h} failed integrity check during compaction"
                    )));
                }
                let content = zstd_compress(&tree.canonical_bytes())?;
                tx.execute(
                    "UPDATE trees SET content = ?2 WHERE hash = ?1",
                    params![h, content],
                )
                .map_err(|e| OakError::Database(e.to_string()))?;
                trees_backfilled += 1;
            }
            tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        }

        // 2. Drop tree_entries once every tree has content.
        let remaining_null: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM trees WHERE content IS NULL",
                [],
                |r| r.get(0),
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        let tree_entries_dropped = if remaining_null == 0
            && table_exists(&conn, "tree_entries").map_err(|e| OakError::Database(e.to_string()))?
        {
            conn.execute_batch("DROP TABLE IF EXISTS tree_entries;")
                .map_err(|e| OakError::Database(e.to_string()))?;
            true
        } else {
            false
        };

        // 3. Re-compress legacy raw blobs that shrink.
        let raw_blobs: Vec<String> = {
            let mut stmt = conn
                .prepare("SELECT hash FROM blobs WHERE codec = 0")
                .map_err(|e| OakError::Database(e.to_string()))?;
            let rows = stmt
                .query_map([], |r| r.get::<_, String>(0))
                .map_err(|e| OakError::Database(e.to_string()))?;
            rows.collect::<std::result::Result<Vec<_>, _>>()
                .map_err(|e| OakError::Database(e.to_string()))?
        };

        let mut blobs_recompressed = 0u64;
        if !raw_blobs.is_empty() {
            let tx = conn
                .transaction()
                .map_err(|e| OakError::Database(e.to_string()))?;
            for h in &raw_blobs {
                let content: Vec<u8> = tx
                    .query_row(
                        "SELECT content FROM blobs WHERE hash = ?1",
                        params![h],
                        |r| r.get(0),
                    )
                    .map_err(|e| OakError::Database(e.to_string()))?;
                let compressed = zstd_compress(&content)?;
                if compressed.len() < content.len() {
                    tx.execute(
                        "UPDATE blobs SET content = ?2, codec = 1 WHERE hash = ?1",
                        params![h, compressed],
                    )
                    .map_err(|e| OakError::Database(e.to_string()))?;
                    blobs_recompressed += 1;
                }
            }
            tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        }

        // 4. VACUUM (must run outside any transaction) to reclaim freed pages.
        conn.execute_batch("VACUUM;")
            .map_err(|e| OakError::Database(e.to_string()))?;

        Ok(CompactStats {
            trees_backfilled,
            tree_entries_dropped,
            blobs_recompressed,
        })
    }

    /// Replace a blob's chunk mapping wholesale. `store_blob_chunks` is
    /// `INSERT OR IGNORE` (append-only), which is right for ingest but can't
    /// correct an existing mapping — needed when a blob arrives mis-chunked
    /// from a skewed server and the client re-chunks the repaired plaintext.
    pub fn replace_blob_chunks(&self, blob_hash: &Hash, chunks: &[ChunkInfo]) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        // Savepoint, not `transaction()`: pull ingest calls this inside an
        // already-open `BulkTxn` (same rationale as `store_tree`).
        let tx = conn
            .savepoint()
            .map_err(|e| OakError::Database(e.to_string()))?;
        tx.execute(
            "DELETE FROM blob_chunks WHERE blob_hash = ?1",
            params![blob_hash.as_str()],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        for (index, chunk) in chunks.iter().enumerate() {
            tx.execute(
                "INSERT INTO blob_chunks (blob_hash, chunk_hash, chunk_index, offset, size) VALUES (?1, ?2, ?3, ?4, ?5)",
                params![
                    blob_hash.as_str(),
                    chunk.hash.as_str(),
                    index as i64,
                    chunk.offset as i64,
                    chunk.length as i64,
                ],
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        }
        tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    /// Remove a cached chunk by content hash.
    ///
    /// Lazy hydration uses this to discard a previously-persisted corrupt row
    /// before retrying the download. Blob-to-chunk mappings are intentionally
    /// left intact: migration 0009 made those references metadata hints, so a
    /// later hydration can still use them to fetch the missing bytes.
    pub fn delete_chunk(&self, hash: &Hash) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute("DELETE FROM chunks WHERE hash = ?1", params![hash.as_str()])
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    /// Store `trees` (skipping ones already present), insert `commit` with
    /// its file rows, and point the commit's branch and the legacy head at
    /// it — all in one transaction. With `require_root`, refuses a commit
    /// whose root tree is neither in `trees` nor already stored.
    fn publish_commit(&self, commit: &Commit, trees: &[Tree], require_root: bool) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .transaction()
            .map_err(|e| OakError::Database(e.to_string()))?;

        for tree in trees {
            let already_present: bool = tx
                .query_row(
                    "SELECT EXISTS(SELECT 1 FROM trees WHERE hash = ?1)",
                    params![tree.hash.as_str()],
                    |row| row.get(0),
                )
                .map_err(|e| OakError::Database(e.to_string()))?;
            if already_present {
                continue;
            }
            insert_tree_row(&tx, tree)?;
        }

        if require_root {
            let root = &commit.manifest_hash;
            let root_present: bool = *root == Tree::empty_hash()
                || tx
                    .query_row(
                        "SELECT EXISTS(SELECT 1 FROM trees WHERE hash = ?1)",
                        params![root.as_str()],
                        |row| row.get(0),
                    )
                    .map_err(|e| OakError::Database(e.to_string()))?;
            if !root_present {
                return Err(OakError::ManifestNotFound(root.to_string()));
            }
        }

        let inserted = tx
            .execute(
            "INSERT OR IGNORE INTO commits (hash, branch_name, parent_hash, merge_parent_hash, manifest_hash, author, message, timestamp) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
            params![
                commit.hash.as_str(),
                commit.branch_name.as_str(),
                commit.parent_hash.as_ref().map(|h| h.as_str()),
                commit.merge_parent_hash.as_ref().map(|h| h.as_str()),
                commit.manifest_hash.as_str(),
                commit.author.as_str(),
                commit.message.as_deref(),
                commit.timestamp.to_rfc3339(),
            ],
        )
            .map_err(|e| OakError::Database(e.to_string()))?;

        if inserted != 0 {
            for file in &commit.files {
                let change_type_str = match file.change_type {
                    ChangeType::Added => "added",
                    ChangeType::Modified => "modified",
                    ChangeType::Deleted => "deleted",
                    ChangeType::Renamed => "renamed",
                };
                tx.execute(
                    "INSERT INTO commit_files (commit_hash, path, change_type, old_blob_hash, new_blob_hash, old_path) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    params![
                        commit.hash.as_str(),
                        file.path.as_str(),
                        change_type_str,
                        file.old_blob_hash.as_ref().map(|h| h.as_str()),
                        file.new_blob_hash.as_ref().map(|h| h.as_str()),
                        file.old_path.as_deref(),
                    ],
                )
                .map_err(|e| OakError::Database(e.to_string()))?;
            }
        }

        tx.execute(
            "INSERT OR REPLACE INTO branch_heads (branch_name, head_hash) VALUES (?1, ?2)",
            params![commit.branch_name.as_str(), commit.hash.as_str()],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;

        tx.execute(
            "INSERT OR REPLACE INTO metadata (key, value) VALUES (?1, ?2)",
            params![MetadataKey::Head.as_str(), commit.hash.as_str()],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;

        tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }
}

/// Outcome of [`SqliteRepository::compact_storage`].
#[derive(Debug, Clone, Default)]
pub struct CompactStats {
    /// Legacy trees converted from `tree_entries` rows to `trees.content`.
    pub trees_backfilled: u64,
    /// Whether the `tree_entries` table was dropped (all trees now compact).
    pub tree_entries_dropped: bool,
    /// Legacy raw blobs re-compressed with zstd.
    pub blobs_recompressed: u64,
}

/// Bulk-write helper for git import (and similar one-shot replays).
///
/// Wraps a private connection to the repo's SQLite database that:
///   - Runs with relaxed durability pragmas (`synchronous=NORMAL`, larger cache,
///     `temp_store=MEMORY`) — appropriate for a re-runnable bulk import.
///   - Holds an outer transaction across `batch_size` commits, flushed
///     automatically when the threshold is reached. This collapses thousands
///     of per-commit `tx.commit()` fsyncs into a handful.
///   - Caches inserted tree hashes in a `HashSet` so unchanged subtrees skip
///     the SQL `SELECT EXISTS` lookup on every commit.
///
/// `finish()` flushes the final batch and must be called for the import to
/// be durable. If the importer is dropped without finishing, the open
/// transaction is rolled back.
pub struct BulkImporter {
    conn: Connection,
    tree_cache: HashSet<Hash>,
    uncommitted: usize,
    batch_size: usize,
    in_tx: bool,
}

impl BulkImporter {
    fn open(db_path: &Path, batch_size: usize) -> Result<Self> {
        let conn = Connection::open(db_path).map_err(|e| OakError::Database(e.to_string()))?;
        conn.execute_batch(
            "PRAGMA journal_mode=WAL;
             PRAGMA synchronous=NORMAL;
             PRAGMA temp_store=MEMORY;
             PRAGMA cache_size=-262144;
             BEGIN;",
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(BulkImporter {
            conn,
            tree_cache: HashSet::new(),
            uncommitted: 0,
            batch_size: batch_size.max(1),
            in_tx: true,
        })
    }

    /// Hash and insert a blob's content into the open batch.
    pub fn put_blob(&mut self, content: Vec<u8>) -> Result<Hash> {
        let blob = Blob::new(content);
        let (stored, codec) = encode_blob(&blob.content)?;
        self.conn
            .execute(
                "INSERT OR IGNORE INTO blobs (hash, content, size, codec) VALUES (?1, ?2, ?3, ?4)",
                params![blob.hash.as_str(), stored.as_ref(), blob.size as i64, codec],
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(blob.hash)
    }

    /// Build a tree from manifest entries and insert all subtrees into the
    /// open batch. Subtrees already inserted in this importer session are
    /// skipped without a roundtrip; subtrees already present on disk from
    /// prior work fall through to `INSERT OR IGNORE` and silently no-op.
    pub fn put_tree(&mut self, entries: Vec<ManifestEntry>) -> Result<Hash> {
        let built = crate::build_tree(&entries)?;
        for tree in &built.trees {
            if !self.tree_cache.insert(tree.hash.clone()) {
                continue;
            }
            insert_tree_row(&self.conn, tree)?;
        }
        Ok(built.root_hash)
    }

    /// Insert a single, already-built tree node into the open batch, skipping
    /// the write if this importer session already stored a tree with the same
    /// hash (same dedup as [`put_tree`], one node at a time).
    ///
    /// Lets a caller that builds trees bottom-up — the git converter memoizing
    /// on git tree oids — store each node as it's produced instead of handing
    /// over a flat manifest and rebuilding the whole hierarchy per commit.
    pub fn put_tree_node(&mut self, tree: &Tree) -> Result<()> {
        if self.tree_cache.insert(tree.hash.clone()) {
            insert_tree_row(&self.conn, tree)?;
        }
        Ok(())
    }

    /// Insert a commit (plus its `commit_files`, if any) and tick the batch
    /// counter. Flushes the current transaction when the threshold is hit.
    pub fn store_commit(&mut self, commit: &Commit) -> Result<()> {
        let inserted = self
            .conn
            .execute(
                "INSERT OR IGNORE INTO commits (hash, branch_name, parent_hash, merge_parent_hash, manifest_hash, author, message, timestamp) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                params![
                    commit.hash.as_str(),
                    commit.branch_name,
                    commit.parent_hash.as_ref().map(|h| h.as_str()),
                    commit.merge_parent_hash.as_ref().map(|h| h.as_str()),
                    commit.manifest_hash.as_str(),
                    commit.author,
                    commit.message,
                    commit.timestamp.to_rfc3339(),
                ],
            )
            .map_err(|e| OakError::Database(e.to_string()))?;

        if inserted == 0 {
            return Ok(());
        }

        for file in &commit.files {
            let change_type_str = match file.change_type {
                ChangeType::Added => "added",
                ChangeType::Modified => "modified",
                ChangeType::Deleted => "deleted",
                ChangeType::Renamed => "renamed",
            };
            self.conn
                .execute(
                    "INSERT INTO commit_files (commit_hash, path, change_type, old_blob_hash, new_blob_hash, old_path) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    params![
                        commit.hash.as_str(),
                        file.path,
                        change_type_str,
                        file.old_blob_hash.as_ref().map(|h| h.as_str()),
                        file.new_blob_hash.as_ref().map(|h| h.as_str()),
                        file.old_path,
                    ],
                )
                .map_err(|e| OakError::Database(e.to_string()))?;
        }

        self.uncommitted += 1;
        if self.uncommitted >= self.batch_size {
            self.flush_batch()?;
        }
        Ok(())
    }

    fn flush_batch(&mut self) -> Result<()> {
        if !self.in_tx {
            return Ok(());
        }
        self.conn
            .execute_batch("COMMIT; BEGIN;")
            .map_err(|e| OakError::Database(e.to_string()))?;
        self.uncommitted = 0;
        Ok(())
    }

    /// Commit the final batch. After this the importer is durable on disk.
    pub fn finish(mut self) -> Result<()> {
        if self.in_tx {
            self.conn
                .execute_batch("COMMIT;")
                .map_err(|e| OakError::Database(e.to_string()))?;
            self.in_tx = false;
        }
        Ok(())
    }
}

impl Drop for BulkImporter {
    fn drop(&mut self) {
        if self.in_tx {
            // Best-effort rollback so a panicked / errored import doesn't leave
            // a half-applied batch behind. `finish()` clears `in_tx` first, so
            // a clean finish path skips this.
            let _ = self.conn.execute_batch("ROLLBACK;");
        }
    }
}

/// How much blob content a [`Repository::put_blob_sources`] pipeline may hold
/// in memory at once (in-flight reads plus rows queued for insert).
const BLOB_BATCH_BUDGET_BYTES: i64 = 64 * 1024 * 1024;

/// Below this much total hinted content, `put_blob_sources` skips the
/// streaming pipeline and stores the batch as one fused parallel pass plus a
/// single transaction. The pipeline's spawned thread + channel + budget
/// bookkeeping only pays for itself when there's enough content for reads and
/// hashes to genuinely overlap the inserts (multi-megabyte batches); on a
/// few-KB commit it's pure fixed cost per call — measurable as lost snapshot
/// throughput when many tiny commits contend for the same repository.
const BLOB_STREAMING_THRESHOLD_BYTES: i64 = 8 * 1024 * 1024;

const BLOB_INSERT_SQL: &str =
    "INSERT OR IGNORE INTO blobs (hash, content, size, codec) VALUES (?1, ?2, ?3, ?4)";

/// What a source counts against the byte budget: its hinted size clamped to
/// the whole budget (so an oversized file is admitted alone rather than
/// never); an unknown size is treated as "could be huge".
fn source_charge(source: &BlobSource) -> i64 {
    source.size_hint.map_or(BLOB_BATCH_BUDGET_BYTES, |s| {
        (s.min(i64::MAX as u64) as i64).min(BLOB_BATCH_BUDGET_BYTES)
    })
}

/// Byte-budget gate bounding a `put_blob_sources` pipeline's in-flight
/// content. Workers [`ByteBudget::acquire`] a source's size before reading it
/// and the insert thread [`ByteBudget::release`]s after the row lands, so the
/// total stays under the cap without imposing pre-partitioned batches (whose
/// boundaries serialize — the tail batch overlaps nothing). [`ByteBudget::close`]
/// unparks every waiter for teardown when the releaser is gone, so an aborted
/// batch can't deadlock.
struct ByteBudget {
    remaining: std::sync::Mutex<i64>,
    available: std::sync::Condvar,
}

impl ByteBudget {
    fn new(cap: i64) -> Self {
        Self {
            remaining: std::sync::Mutex::new(cap),
            available: std::sync::Condvar::new(),
        }
    }

    /// Block until `n` bytes fit, then take them. Callers must clamp `n` to
    /// the cap (a charge larger than the cap would wait forever).
    fn acquire(&self, n: i64) {
        let mut remaining = self.remaining.lock().unwrap();
        while *remaining < n {
            remaining = self.available.wait(remaining).unwrap();
        }
        *remaining -= n;
    }

    fn release(&self, n: i64) {
        *self.remaining.lock().unwrap() += n;
        self.available.notify_all();
    }

    /// Open the gate unconditionally so every parked `acquire` returns.
    fn close(&self) {
        *self.remaining.lock().unwrap() = i64::MAX;
        self.available.notify_all();
    }
}

impl Repository for SqliteRepository {
    fn store_blob(&self, blob: &Blob) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let (stored, codec) = encode_blob(&blob.content)?;
        conn.execute(
            "INSERT OR IGNORE INTO blobs (hash, content, size, codec) VALUES (?1, ?2, ?3, ?4)",
            params![blob.hash.as_str(), stored.as_ref(), blob.size as i64, codec],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn put_blob_sources(&self, sources: Vec<BlobSource>) -> Result<Vec<Hash>> {
        if sources.is_empty() {
            return Ok(Vec::new());
        }
        if sources.len() == 1 {
            // A one-blob batch gains nothing from an explicit transaction;
            // keep it a single autocommit insert like `put_blob`.
            let content = (sources.into_iter().next().unwrap().read)()?;
            return Ok(vec![self.put_blob(content)?]);
        }

        use rayon::prelude::*;

        // Small batch (by hinted bytes): read + hash + encode fused per blob
        // in one parallel pass, then insert everything in one transaction — a
        // `put_blob` loop would pay an autocommit (WAL append + sync) per
        // blob. The all-hashed-before-any-insert barrier is harmless at this
        // size, and skipping the streaming pipeline below keeps a tiny
        // commit's latency free of its thread/channel setup cost.
        let total_hinted = sources
            .iter()
            .map(source_charge)
            .fold(0i64, |acc, charge| acc.saturating_add(charge));
        if total_hinted <= BLOB_STREAMING_THRESHOLD_BYTES {
            let rows: Vec<(Hash, Vec<u8>, i64, i64)> = sources
                .into_par_iter()
                .map(|source| -> Result<(Hash, Vec<u8>, i64, i64)> {
                    let blob = Blob::new((source.read)()?);
                    let size = blob.size as i64;
                    let (encoded, codec) = encode_blob(&blob.content)?;
                    let stored = match encoded {
                        std::borrow::Cow::Owned(v) => v,
                        std::borrow::Cow::Borrowed(_) => blob.content,
                    };
                    Ok((blob.hash, stored, size, codec))
                })
                .collect::<Result<Vec<_>>>()?;

            let mut conn = self.conn.lock().unwrap();
            let tx = conn
                .transaction()
                .map_err(|e| OakError::Database(e.to_string()))?;
            {
                let mut stmt = tx
                    .prepare(BLOB_INSERT_SQL)
                    .map_err(|e| OakError::Database(e.to_string()))?;
                for (hash, stored, size, codec) in &rows {
                    stmt.execute(params![hash.as_str(), stored, size, codec])
                        .map_err(|e| OakError::Database(e.to_string()))?;
                }
            }
            tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
            return Ok(rows.into_iter().map(|(hash, _, _, _)| hash).collect());
        }

        // Big batch: pipeline, not phases. Rayon workers read + hash + encode
        // each source fused per blob (so one file's read overlaps another's
        // BLAKE3/zstd) and stream finished rows over a channel to this
        // thread, which inserts them all inside ONE transaction. There is no
        // all-read or all-hash barrier anywhere: with a few large files the
        // insert of the first overlaps the hash of the last, and with
        // thousands of files the inserts run continuously behind the hashing
        // instead of after it.
        //
        // Memory is bounded by `BLOB_BATCH_BUDGET_BYTES`: a worker admits a
        // source's charge (see `source_charge`) before reading it, and the
        // charge is released only after the row has been inserted and dropped.
        let n = sources.len();
        let budget = ByteBudget::new(BLOB_BATCH_BUDGET_BYTES);
        type Row = (usize, Hash, Vec<u8>, i64, i64, i64);
        let (sender, receiver) = std::sync::mpsc::channel::<Row>();

        let mut hashes: Vec<Option<Hash>> = Vec::with_capacity(n);
        hashes.resize_with(n, || None);

        let (producer_result, consumer_result) = std::thread::scope(|scope| {
            let budget_ref = &budget;
            let producer = scope.spawn(move || -> Result<()> {
                sources
                    .into_par_iter()
                    .enumerate()
                    .try_for_each(|(idx, source)| -> Result<()> {
                        let charge = source_charge(&source);
                        budget_ref.acquire(charge);
                        let blob = Blob::new((source.read)()?);
                        let size = blob.size as i64;
                        let (encoded, codec) = encode_blob(&blob.content)?;
                        let stored = match encoded {
                            std::borrow::Cow::Owned(v) => v,
                            std::borrow::Cow::Borrowed(_) => blob.content,
                        };
                        sender
                            .send((idx, blob.hash, stored, size, codec, charge))
                            .map_err(|_| {
                                OakError::Database("blob batch insert aborted".to_string())
                            })
                    })
            });

            let consumer_result = (|| -> Result<()> {
                let mut conn = self.conn.lock().unwrap();
                let tx = conn
                    .transaction()
                    .map_err(|e| OakError::Database(e.to_string()))?;
                {
                    let mut stmt = tx
                        .prepare(BLOB_INSERT_SQL)
                        .map_err(|e| OakError::Database(e.to_string()))?;
                    for (idx, hash, stored, size, codec, charge) in &receiver {
                        let inserted = stmt
                            .execute(params![hash.as_str(), stored, size, codec])
                            .map_err(|e| OakError::Database(e.to_string()));
                        drop(stored);
                        budget_ref.release(charge);
                        inserted?;
                        hashes[idx] = Some(hash);
                    }
                }
                tx.commit().map_err(|e| OakError::Database(e.to_string()))
            })();

            // Teardown for the error path: this thread is the only budget
            // releaser, so a worker could be parked in `acquire` forever once
            // the insert loop has bailed. Closing the channel fails the sends
            // and opening the budget unparks the waiters, so the producer
            // drains with errors instead of deadlocking. Both are no-ops when
            // everything succeeded (the producer already finished — that's
            // what ended the insert loop).
            drop(receiver);
            budget.close();
            let producer_result = match producer.join() {
                Ok(result) => result,
                Err(_) => Err(OakError::Database(
                    "blob batch producer panicked".to_string(),
                )),
            };
            (producer_result, consumer_result)
        });
        consumer_result?;
        producer_result?;
        Ok(hashes
            .into_iter()
            .map(|h| h.expect("every source yields exactly one inserted row"))
            .collect())
    }

    fn get_blob(&self, hash: &Hash) -> Result<Option<Blob>> {
        let conn = self.conn.lock().unwrap();
        let result: Option<(Vec<u8>, i64, i64)> = conn
            .prepare_cached("SELECT content, size, codec FROM blobs WHERE hash = ?1")
            .and_then(|mut stmt| {
                stmt.query_row(params![hash.as_str()], |row| {
                    Ok((row.get(0)?, row.get(1)?, row.get(2)?))
                })
                .optional()
            })
            .map_err(|e| OakError::Database(e.to_string()))?;

        match result {
            None => Ok(None),
            Some((content, size, codec)) => Ok(Some(Blob {
                hash: hash.clone(),
                content: decode_blob(content, codec)?,
                size: size as u64,
            })),
        }
    }

    fn has_blob(&self, hash: &Hash) -> Result<bool> {
        let conn = self.conn.lock().unwrap();
        let exists: bool = conn
            .prepare_cached("SELECT EXISTS(SELECT 1 FROM blobs WHERE hash = ?1)")
            .and_then(|mut stmt| stmt.query_row(params![hash.as_str()], |row| row.get(0)))
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(exists)
    }

    fn has_blobs(&self, hashes: &[&Hash]) -> Result<Vec<bool>> {
        let conn = self.conn.lock().unwrap();
        Self::with_read_txn(&conn, |conn| {
            let mut stmt = conn
                .prepare_cached("SELECT EXISTS(SELECT 1 FROM blobs WHERE hash = ?1)")
                .map_err(|e| OakError::Database(e.to_string()))?;
            hashes
                .iter()
                .map(|hash| {
                    stmt.query_row(params![hash.as_str()], |row| row.get(0))
                        .map_err(|e| OakError::Database(e.to_string()))
                })
                .collect()
        })
    }

    fn get_blob_size(&self, hash: &Hash) -> Result<Option<u64>> {
        let conn = self.conn.lock().unwrap();
        conn.query_row(
            "SELECT size FROM blobs WHERE hash = ?1",
            params![hash.as_str()],
            |row| row.get::<_, i64>(0),
        )
        .optional()
        .map(|size| size.map(|size| size as u64))
        .map_err(|error| OakError::Database(error.to_string()))
    }

    /// Write a manifest as a tree. The hash of `manifest` is already the tree
    /// root hash (computed by `Manifest::new` via `build_tree`), so this is
    /// just a tree-store of the corresponding nested structure.
    fn store_manifest(&self, manifest: &Manifest) -> Result<()> {
        self.put_tree(manifest.entries.clone()).map(|_| ())
    }

    /// Read a manifest by hash. Reads from the tree tables.
    fn get_manifest(&self, hash: &Hash) -> Result<Option<Manifest>> {
        if self.has_tree(hash)? {
            let entries = self.walk_tree(hash)?;
            return Ok(Some(Manifest {
                hash: hash.clone(),
                entries,
            }));
        }
        Ok(None)
    }

    // --- Tree operations ---

    fn store_tree(&self, tree: &Tree) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        // Use a savepoint, not `transaction()`: clone/pull ingest calls this
        // inside an already-open bulk transaction (`BulkTxn`), and SQLite
        // rejects a nested `BEGIN` ("cannot start a transaction within a
        // transaction"). A savepoint nests cleanly inside the bulk txn and, when
        // there's no outer transaction (a standalone call), still commits on its
        // own — so these writes stay atomic in both cases.
        let tx = conn
            .savepoint()
            .map_err(|e| OakError::Database(e.to_string()))?;

        insert_tree_row(&tx, tree)?;

        tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn walk_tree(&self, root: &Hash) -> Result<Vec<ManifestEntry>> {
        self.tree_flattens.fetch_add(1, Ordering::Relaxed);
        let mut fetch = |h: &Hash| -> Result<Tree> {
            self.get_tree(h)?
                .ok_or_else(|| OakError::ManifestNotFound(h.to_string()))
        };
        crate::flatten_tree(root, &mut fetch)
    }

    fn get_tree(&self, hash: &Hash) -> Result<Option<Tree>> {
        self.tree_reads.fetch_add(1, Ordering::Relaxed);
        if hash == &Tree::empty_hash() {
            return Ok(Some(Tree::empty()));
        }
        let conn = self.conn.lock().unwrap();

        // New format (migration 0008): a single compressed-content row.
        // `content` is NULL for legacy trees still stored as tree_entries rows.
        let row: Option<Option<Vec<u8>>> = conn
            .prepare_cached("SELECT content FROM trees WHERE hash = ?1")
            .and_then(|mut stmt| {
                stmt.query_row(params![hash.as_str()], |r| r.get::<_, Option<Vec<u8>>>(0))
                    .optional()
            })
            .map_err(|e| OakError::Database(e.to_string()))?;

        match row {
            None => Ok(None), // no such tree
            Some(Some(content)) => {
                let raw = zstd_decompress_tree(&content)?;
                let actual = hash_bytes(&raw);
                if &actual != hash {
                    return Err(OakError::InvalidHash(format!(
                        "tree {} does not match stored content hash {}",
                        hash, actual
                    )));
                }
                Ok(Some(Tree::from_canonical_bytes(hash.clone(), &raw)?))
            }
            Some(None) => Ok(Some(read_tree_entries(&conn, hash)?)), // legacy fallback
        }
    }

    fn has_tree(&self, hash: &Hash) -> Result<bool> {
        if hash == &Tree::empty_hash() {
            return Ok(true);
        }
        let conn = self.conn.lock().unwrap();
        let exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM trees WHERE hash = ?1)",
                params![hash.as_str()],
                |row| row.get(0),
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(exists)
    }

    /// Optimized `put_tree`: builds the nested tree, then inserts all tree
    /// objects in a single transaction, skipping subtrees whose hash already
    /// exists. This is the key write-path optimization for tree storage.
    fn put_tree(&self, entries: Vec<ManifestEntry>) -> Result<Hash> {
        let built = crate::build_tree(&entries)?;
        let mut conn = self.conn.lock().unwrap();
        // Savepoint, not `transaction()`: clone/pull ingest can call this
        // while a bulk transaction is already open, and standalone tree writes
        // still need this block to be all-or-nothing.
        let tx = conn
            .savepoint()
            .map_err(|e| OakError::Database(e.to_string()))?;

        for tree in &built.trees {
            let already_present: bool = tx
                .query_row(
                    "SELECT EXISTS(SELECT 1 FROM trees WHERE hash = ?1)",
                    params![tree.hash.as_str()],
                    |row| row.get(0),
                )
                .map_err(|e| OakError::Database(e.to_string()))?;
            if already_present {
                continue;
            }

            insert_tree_row(&tx, tree)?;
        }

        tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        Ok(built.root_hash)
    }

    // --- Branch operations ---

    fn close_branch(&self, name: &str, close_reason: Option<crate::CloseReason>) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "UPDATE branches SET status = ?1, close_reason = ?2 WHERE name = ?3",
            params![
                BranchStatus::Closed.as_str(),
                close_reason.as_ref().map(|r| r.as_str()),
                name,
            ],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn update_branch_close_reason(
        &self,
        name: &str,
        close_reason: crate::CloseReason,
    ) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "UPDATE branches SET close_reason = ?1 WHERE name = ?2",
            params![close_reason.as_str(), name],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn store_branch(&self, branch: &Branch) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .savepoint()
            .map_err(|error| OakError::Database(error.to_string()))?;
        let generation = advance_description_generation(&tx)?;
        tx.execute(
            "INSERT OR IGNORE INTO branches (name, description, parent_branch, status, close_reason, created_at, description_generation) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
            params![
                branch.name,
                branch.description,
                branch.parent_branch,
                branch.status.as_str(),
                branch.close_reason.as_ref().map(|r| r.as_str()),
                branch.created_at.to_rfc3339(),
                generation,
            ],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        tx.commit()
            .map_err(|error| OakError::Database(error.to_string()))
    }

    fn get_branch(&self, name: &str) -> Result<Option<Branch>> {
        // (description, parent_branch, status, close_reason, created_at)
        type BranchRow = (
            Option<String>,
            Option<String>,
            String,
            Option<String>,
            String,
        );
        let conn = self.conn.lock().unwrap();
        let result: Option<BranchRow> = conn
            .query_row(
                "SELECT description, parent_branch, status, close_reason, created_at FROM branches WHERE name = ?1",
                params![name],
                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)),
            )
            .optional()
            .map_err(|e| OakError::Database(e.to_string()))?;

        match result {
            Some((description, parent_branch, status_str, close_reason_str, created_at_str)) => {
                let status = BranchStatus::from_db_str(&status_str);
                decode_branch_row(
                    name.to_string(),
                    description,
                    parent_branch,
                    status,
                    close_reason_str,
                    &created_at_str,
                )
                .map(Some)
                .map_err(|unreadable| unreadable.to_error())
            }
            None => Ok(None),
        }
    }

    fn list_branches(&self) -> Result<Vec<Branch>> {
        self.list_branches_isolated()?
            .into_iter()
            .map(|row| row.map_err(|unreadable| unreadable.to_error()))
            .collect()
    }

    fn list_branches_isolated(
        &self,
    ) -> Result<Vec<std::result::Result<Branch, crate::UnreadableBranch>>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn
            .prepare("SELECT name, description, parent_branch, status, close_reason, created_at FROM branches ORDER BY created_at ASC")
            .map_err(|e| OakError::Database(e.to_string()))?;

        let branches = stmt
            .query_map([], |row| {
                let name: String = row.get(0)?;
                let description: Option<String> = row.get(1)?;
                let parent_branch: Option<String> = row.get(2)?;
                let status_str: String = row.get(3)?;
                let close_reason_str: Option<String> = row.get(4)?;
                let created_at_str: String = row.get(5)?;
                Ok((
                    name,
                    description,
                    parent_branch,
                    status_str,
                    close_reason_str,
                    created_at_str,
                ))
            })
            .map_err(|e| OakError::Database(e.to_string()))?
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|e| OakError::Database(e.to_string()))?;

        branches
            .into_iter()
            .map(
                |(
                    name,
                    description,
                    parent_branch,
                    status_str,
                    close_reason_str,
                    created_at_str,
                )| {
                    decode_branch_row(
                        name,
                        description,
                        parent_branch,
                        BranchStatus::from_db_str(&status_str),
                        close_reason_str,
                        &created_at_str,
                    )
                },
            )
            .map(Ok)
            .collect()
    }

    fn update_branch_status(&self, name: &str, status: BranchStatus) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "UPDATE branches SET status = ?1 WHERE name = ?2",
            params![status.as_str(), name],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn set_branch_parent(&self, name: &str, parent: Option<&str>) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "UPDATE branches SET parent_branch = ?1 WHERE name = ?2",
            params![parent, name],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn update_branch_description(&self, name: &str, description: &str) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .savepoint()
            .map_err(|error| OakError::Database(error.to_string()))?;
        let generation = advance_description_generation(&tx)?;
        tx.execute(
            "UPDATE branches SET description = ?1, description_generation = ?3 WHERE name = ?2",
            params![description, name, generation],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        tx.commit()
            .map_err(|error| OakError::Database(error.to_string()))
    }

    fn edit_branch_description(&self, name: &str, description: &str) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .savepoint()
            .map_err(|error| OakError::Database(error.to_string()))?;
        let generation = advance_description_generation(&tx)?;
        tx.execute(
            "UPDATE branches SET description = ?1, description_pending = 1, description_generation = ?3 WHERE name = ?2",
            params![description, name, generation],
        )
        .map_err(|error| OakError::Database(error.to_string()))?;
        tx.commit()
            .map_err(|error| OakError::Database(error.to_string()))
    }

    fn description_publication_generation(&self) -> Result<Option<i64>> {
        self.description_generation().map(Some)
    }

    fn acknowledge_branch_description(
        &self,
        name: &str,
        description: Option<&str>,
        generation: Option<i64>,
    ) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .savepoint()
            .map_err(|error| OakError::Database(error.to_string()))?;
        // Publication changes which remote responses are safe to reconcile,
        // even when the text itself did not change. Fence fetches that began
        // before this acknowledgment, including while the POST was in flight.
        let acknowledged_generation = advance_description_generation(&tx)?;
        tx.execute(
            "UPDATE branches SET description_pending = 0, description_generation = ?4 WHERE name = ?1 AND description IS ?2 AND description_generation <= ?3",
            params![name, description, generation, acknowledged_generation],
        )
        .map_err(|error| OakError::Database(error.to_string()))?;
        tx.commit()
            .map_err(|error| OakError::Database(error.to_string()))
    }

    fn rename_branch(&self, old_name: &str, new_name: &str) -> Result<()> {
        if old_name == new_name {
            return Ok(());
        }
        if new_name.is_empty() {
            return Err(OakError::Database("new branch name cannot be empty".into()));
        }

        let mut conn = self.conn.lock().unwrap();
        // Savepoint, not `transaction()`: pull publishes branch renames inside
        // an already-open write transaction, while standalone branch rename
        // still needs this block to be all-or-nothing.
        let tx = conn
            .savepoint()
            .map_err(|e| OakError::Database(e.to_string()))?;

        let exists: bool = tx
            .query_row(
                "SELECT 1 FROM branches WHERE name = ?1",
                params![old_name],
                |_| Ok(true),
            )
            .optional()
            .map_err(|e| OakError::Database(e.to_string()))?
            .unwrap_or(false);
        if !exists {
            return Err(OakError::BranchNotFound(old_name.to_string()));
        }

        let conflict: bool = tx
            .query_row(
                "SELECT 1 FROM branches WHERE name = ?1
                 UNION
                 SELECT 1 FROM branch_heads WHERE branch_name = ?1",
                params![new_name],
                |_| Ok(true),
            )
            .optional()
            .map_err(|e| OakError::Database(e.to_string()))?
            .unwrap_or(false);
        if conflict {
            return Err(OakError::BranchAlreadyExists(new_name.to_string()));
        }

        // Insert renamed row, repoint all references, then delete the old row.
        // Insert-before-update keeps FK semantics correct if foreign_keys are
        // ever turned on; the order below is safe with FKs OFF too.
        let generation = advance_description_generation(&tx)?;
        tx.execute(
            "INSERT INTO branches (name, description, parent_branch, status, close_reason, created_at, description_pending, description_generation) \
             SELECT ?1, description, parent_branch, status, close_reason, created_at, description_pending, ?3 FROM branches WHERE name = ?2",
            params![new_name, old_name, generation],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;

        tx.execute(
            "UPDATE branches SET parent_branch = ?1 WHERE parent_branch = ?2",
            params![new_name, old_name],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;

        tx.execute(
            "UPDATE commits SET branch_name = ?1 WHERE branch_name = ?2",
            params![new_name, old_name],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;

        tx.execute(
            "UPDATE branch_heads SET branch_name = ?1 WHERE branch_name = ?2",
            params![new_name, old_name],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;

        tx.execute(
            "UPDATE metadata SET value = ?1 WHERE key = ?2 AND value = ?3",
            params![new_name, MetadataKey::CurrentBranch.as_str(), old_name],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;

        tx.execute("DELETE FROM branches WHERE name = ?1", params![old_name])
            .map_err(|e| OakError::Database(e.to_string()))?;

        tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn delete_branch(&self, name: &str) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .transaction()
            .map_err(|e| OakError::Database(e.to_string()))?;
        tx.execute(
            "DELETE FROM branch_heads WHERE branch_name = ?1",
            params![name],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        tx.execute("DELETE FROM branches WHERE name = ?1", params![name])
            .map_err(|e| OakError::Database(e.to_string()))?;
        tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn get_branch_head(&self, name: &str) -> Result<Option<Hash>> {
        let conn = self.conn.lock().unwrap();
        let result: Option<String> = conn
            .query_row(
                "SELECT head_hash FROM branch_heads WHERE branch_name = ?1",
                params![name],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(result.map(Hash))
    }

    fn set_branch_head(&self, name: &str, hash: &Hash) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "INSERT OR REPLACE INTO branch_heads (branch_name, head_hash) VALUES (?1, ?2)",
            params![name, hash.as_str()],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn reconcile_remote_merge_branch_state(
        &self,
        closed_branch: &str,
        new_branch: &Branch,
        seed_head: &Hash,
    ) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .transaction()
            .map_err(|e| OakError::Database(e.to_string()))?;
        let generation = advance_description_generation(&tx)?;

        tx.execute(
            "UPDATE branches SET status = ?1 WHERE name = ?2",
            params![BranchStatus::Closed.as_str(), closed_branch],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        tx.execute(
            "INSERT OR IGNORE INTO branches (name, description, parent_branch, status, close_reason, created_at, description_generation) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
            params![
                new_branch.name,
                new_branch.description,
                new_branch.parent_branch,
                new_branch.status.as_str(),
                new_branch.close_reason.as_ref().map(|r| r.as_str()),
                new_branch.created_at.to_rfc3339(),
                generation,
            ],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        tx.execute(
            "INSERT OR REPLACE INTO branch_heads (branch_name, head_hash) VALUES (?1, ?2)",
            params![new_branch.name, seed_head.as_str()],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        tx.execute(
            "INSERT OR REPLACE INTO metadata (key, value) VALUES (?1, ?2)",
            params![MetadataKey::Head.as_str(), seed_head.as_str()],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        tx.execute(
            "INSERT OR REPLACE INTO metadata (key, value) VALUES (?1, ?2)",
            params![MetadataKey::CurrentBranch.as_str(), new_branch.name],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;

        tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    // --- Commit operations ---

    fn store_commit(&self, commit: &Commit) -> Result<()> {
        let mut conn = self.conn.lock().unwrap();
        // Savepoint rather than `transaction()` for the same reason as
        // `store_tree`: clone/pull's `store_pull_response` calls this inside an
        // open `BulkTxn`, where a nested `BEGIN` would error. A savepoint nests
        // there and still commits standalone.
        let tx = conn
            .savepoint()
            .map_err(|e| OakError::Database(e.to_string()))?;

        let inserted = tx
            .execute(
            "INSERT OR IGNORE INTO commits (hash, branch_name, parent_hash, merge_parent_hash, manifest_hash, author, message, timestamp) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
            params![
                commit.hash.as_str(),
                commit.branch_name,
                commit.parent_hash.as_ref().map(|h| h.as_str()),
                commit.merge_parent_hash.as_ref().map(|h| h.as_str()),
                commit.manifest_hash.as_str(),
                commit.author,
                commit.message,
                commit.timestamp.to_rfc3339(),
            ],
        )
            .map_err(|e| OakError::Database(e.to_string()))?;

        if inserted != 0 {
            for file in &commit.files {
                let change_type_str = match file.change_type {
                    ChangeType::Added => "added",
                    ChangeType::Modified => "modified",
                    ChangeType::Deleted => "deleted",
                    ChangeType::Renamed => "renamed",
                };

                tx.execute(
                    "INSERT INTO commit_files (commit_hash, path, change_type, old_blob_hash, new_blob_hash, old_path) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    params![
                        commit.hash.as_str(),
                        file.path,
                        change_type_str,
                        file.old_blob_hash.as_ref().map(|h| h.as_str()),
                        file.new_blob_hash.as_ref().map(|h| h.as_str()),
                        file.old_path,
                    ],
                )
                .map_err(|e| OakError::Database(e.to_string()))?;
            }
        }

        tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn get_commit(&self, hash: &Hash) -> Result<Option<Commit>> {
        let conn = self.conn.lock().unwrap();

        #[allow(clippy::type_complexity)]
        let result: Option<(String, Option<String>, Option<String>, String, String, Option<String>, String)> = conn
            .query_row(
                "SELECT branch_name, parent_hash, merge_parent_hash, manifest_hash, author, message, timestamp FROM commits WHERE hash = ?1",
                params![hash.as_str()],
                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?, row.get(5)?, row.get(6)?)),
            )
            .optional()
            .map_err(|e| OakError::Database(e.to_string()))?;

        let (
            branch_name,
            parent_hash,
            merge_parent_hash,
            manifest_hash,
            author,
            message,
            timestamp_str,
        ) = match result {
            Some(r) => r,
            None => return Ok(None),
        };

        let mut stmt = conn
            .prepare("SELECT path, change_type, old_blob_hash, new_blob_hash, old_path FROM commit_files WHERE commit_hash = ?1")
            .map_err(|e| OakError::Database(e.to_string()))?;

        let files: Vec<FileChange> = stmt
            .query_map(params![hash.as_str()], |row| {
                let path: String = row.get(0)?;
                let change_type_str: String = row.get(1)?;
                let old_blob_hash: Option<String> = row.get(2)?;
                let new_blob_hash: Option<String> = row.get(3)?;
                let old_path: Option<String> = row.get(4)?;

                let change_type = match change_type_str.as_str() {
                    "added" => ChangeType::Added,
                    "deleted" => ChangeType::Deleted,
                    "renamed" => ChangeType::Renamed,
                    _ => ChangeType::Modified,
                };

                Ok(FileChange {
                    path,
                    change_type,
                    old_blob_hash: old_blob_hash.map(Hash),
                    new_blob_hash: new_blob_hash.map(Hash),
                    old_path,
                    old_mode: None,
                    new_mode: None,
                })
            })
            .map_err(|e| OakError::Database(e.to_string()))?
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|e| OakError::Database(e.to_string()))?;

        let timestamp = chrono::DateTime::parse_from_rfc3339(&timestamp_str)
            .map_err(|e| OakError::Database(e.to_string()))?
            .with_timezone(&chrono::Utc);

        Ok(Some(Commit {
            hash: hash.clone(),
            branch_name,
            parent_hash: parent_hash.map(Hash),
            merge_parent_hash: merge_parent_hash.map(Hash),
            manifest_hash: Hash(manifest_hash),
            author,
            message,
            timestamp,
            files,
        }))
    }

    fn repair_commit_fields(&self, verified: &Commit) -> Result<bool> {
        verified.verify_fields()?;
        let Some(stored) = self.get_commit(&verified.hash)? else {
            return Ok(false);
        };
        if stored.verify_fields().is_ok() {
            return Ok(false);
        }
        if stored.parent_hash != verified.parent_hash
            || stored.merge_parent_hash != verified.merge_parent_hash
            || stored.manifest_hash != verified.manifest_hash
        {
            return Err(OakError::InvalidHash(format!(
                "refusing to repair commit {}: the verified fields name different parents or a different manifest than the stored row",
                verified.hash.short()
            )));
        }
        let conn = self.conn.lock().unwrap();
        let changed = conn
            .execute(
                "UPDATE commits SET branch_name = ?2, author = ?3, message = ?4, timestamp = ?5 WHERE hash = ?1",
                params![
                    verified.hash.as_str(),
                    verified.branch_name,
                    verified.author,
                    verified.message,
                    verified.timestamp.to_rfc3339(),
                ],
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(changed != 0)
    }

    fn has_commit(&self, hash: &Hash) -> Result<bool> {
        let conn = self.conn.lock().unwrap();
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM commits WHERE hash = ?1",
                params![hash.as_str()],
                |row| row.get(0),
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(count > 0)
    }

    fn get_commits_for_branch(&self, branch_name: &str) -> Result<Vec<Commit>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn
            .prepare("SELECT hash FROM commits WHERE branch_name = ?1 ORDER BY timestamp ASC")
            .map_err(|e| OakError::Database(e.to_string()))?;

        let hashes: Vec<String> = stmt
            .query_map(params![branch_name], |row| row.get(0))
            .map_err(|e| OakError::Database(e.to_string()))?
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|e| OakError::Database(e.to_string()))?;

        drop(stmt);
        drop(conn);

        let mut commits = Vec::new();
        for hash in hashes {
            if let Some(edit) = self.get_commit(&Hash(hash))? {
                commits.push(edit);
            }
        }
        Ok(commits)
    }

    fn count_commits_for_branch(&self, branch_name: &str) -> Result<usize> {
        let conn = self.conn.lock().unwrap();
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM commits WHERE branch_name = ?1",
                params![branch_name],
                |row| row.get(0),
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(count as usize)
    }

    fn merge_child_exists(&self, branch_head: &Hash) -> Result<bool> {
        let conn = self.conn.lock().unwrap();
        let exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM commits WHERE merge_parent_hash = ?1)",
                params![branch_head.as_str()],
                |row| row.get(0),
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(exists)
    }

    fn get_commits_since(&self, branch_name: &str, since: Option<&Hash>) -> Result<Vec<Commit>> {
        let all = self.get_commits_for_branch(branch_name)?;

        match since {
            None => Ok(all),
            Some(since_hash) => {
                let mut found = false;
                let mut result = Vec::new();
                for commit in &all {
                    if &commit.hash == since_hash {
                        found = true;
                    } else if found {
                        result.push(commit.clone());
                    }
                }
                // If since_hash wasn't found in this branch's commits (e.g.
                // it belongs to a different branch), return all commits —
                // they are all new from the caller's perspective.
                if !found {
                    return Ok(all);
                }
                Ok(result)
            }
        }
    }

    fn get_all_commits(&self) -> Result<Vec<Commit>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn
            .prepare("SELECT hash FROM commits ORDER BY timestamp ASC")
            .map_err(|e| OakError::Database(e.to_string()))?;

        let hashes: Vec<String> = stmt
            .query_map([], |row| row.get(0))
            .map_err(|e| OakError::Database(e.to_string()))?
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|e| OakError::Database(e.to_string()))?;

        drop(stmt);
        drop(conn);

        let mut commits = Vec::new();
        for hash in hashes {
            if let Some(edit) = self.get_commit(&Hash(hash))? {
                commits.push(edit);
            }
        }
        Ok(commits)
    }

    // --- Metadata ---

    fn get_metadata(&self, key: MetadataKey) -> Result<Option<String>> {
        let conn = self.conn.lock().unwrap();
        let result: Option<String> = conn
            .query_row(
                "SELECT value FROM metadata WHERE key = ?1",
                params![key.as_str()],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(result)
    }

    fn set_metadata(&self, key: MetadataKey, value: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "INSERT OR REPLACE INTO metadata (key, value) VALUES (?1, ?2)",
            params![key.as_str(), value],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn insert_metadata_if_absent(&self, key: MetadataKey, value: &str) -> Result<bool> {
        let conn = self.conn.lock().unwrap();
        let inserted = conn
            .execute(
                "INSERT OR IGNORE INTO metadata (key, value) VALUES (?1, ?2)",
                params![key.as_str(), value],
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(inserted > 0)
    }

    // --- Working-tree stat cache ---

    fn load_stat_cache(&self) -> Result<HashMap<String, StatCacheEntry>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn
            .prepare("SELECT path, mtime_ns, ctime_ns, size, blob_hash FROM stat_cache")
            .map_err(|e| OakError::Database(e.to_string()))?;
        let rows = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    StatCacheEntry {
                        mtime_ns: row.get(1)?,
                        ctime_ns: row.get(2)?,
                        size: row.get(3)?,
                        blob_hash: Hash(row.get::<_, String>(4)?),
                    },
                ))
            })
            .map_err(|e| OakError::Database(e.to_string()))?;
        let mut map = HashMap::new();
        for row in rows {
            let (path, entry) = row.map_err(|e| OakError::Database(e.to_string()))?;
            map.insert(path, entry);
        }
        Ok(map)
    }

    fn update_stat_cache(
        &self,
        upserts: &[(String, StatCacheEntry)],
        removed: &[String],
    ) -> Result<()> {
        if upserts.is_empty() && removed.is_empty() {
            return Ok(());
        }
        let mut conn = self.conn.lock().unwrap();
        let tx = conn
            .transaction()
            .map_err(|e| OakError::Database(e.to_string()))?;
        {
            let mut upsert = tx
                .prepare(
                    "INSERT INTO stat_cache (path, mtime_ns, ctime_ns, size, blob_hash) VALUES (?1, ?2, ?3, ?4, ?5)
                     ON CONFLICT(path) DO UPDATE SET
                         mtime_ns = excluded.mtime_ns,
                         ctime_ns = excluded.ctime_ns,
                         size = excluded.size,
                         blob_hash = excluded.blob_hash",
                )
                .map_err(|e| OakError::Database(e.to_string()))?;
            for (path, entry) in upserts {
                upsert
                    .execute(params![
                        path,
                        entry.mtime_ns,
                        entry.ctime_ns,
                        entry.size,
                        entry.blob_hash.as_str()
                    ])
                    .map_err(|e| OakError::Database(e.to_string()))?;
            }
            let mut delete = tx
                .prepare("DELETE FROM stat_cache WHERE path = ?1")
                .map_err(|e| OakError::Database(e.to_string()))?;
            for path in removed {
                delete
                    .execute(params![path])
                    .map_err(|e| OakError::Database(e.to_string()))?;
            }
        }
        tx.commit().map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    // --- Chunk operations ---

    fn store_chunk(&self, hash: &Hash, content: &[u8]) -> Result<()> {
        let actual = hash_bytes(content);
        if &actual != hash {
            return Err(OakError::InvalidHash(format!(
                "chunk {} does not match content hash {}",
                hash, actual
            )));
        }
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "INSERT OR IGNORE INTO chunks (hash, content, size) VALUES (?1, ?2, ?3)",
            params![hash.as_str(), content, content.len() as i64],
        )
        .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(())
    }

    fn get_chunk(&self, hash: &Hash) -> Result<Option<Vec<u8>>> {
        let conn = self.conn.lock().unwrap();
        let result: Option<Vec<u8>> = conn
            .query_row(
                "SELECT content FROM chunks WHERE hash = ?1",
                params![hash.as_str()],
                |row| row.get(0),
            )
            .optional()
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(result)
    }

    fn has_chunk(&self, hash: &Hash) -> Result<bool> {
        let conn = self.conn.lock().unwrap();
        let exists: bool = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM chunks WHERE hash = ?1)",
                params![hash.as_str()],
                |row| row.get(0),
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        Ok(exists)
    }

    fn store_blob_chunks(&self, blob_hash: &Hash, chunks: &[ChunkInfo]) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        for (index, chunk) in chunks.iter().enumerate() {
            conn.execute(
                "INSERT OR IGNORE INTO blob_chunks (blob_hash, chunk_hash, chunk_index, offset, size) VALUES (?1, ?2, ?3, ?4, ?5)",
                params![
                    blob_hash.as_str(),
                    chunk.hash.as_str(),
                    index as i64,
                    chunk.offset as i64,
                    chunk.length as i64,
                ],
            )
            .map_err(|e| OakError::Database(e.to_string()))?;
        }
        Ok(())
    }

    fn get_blob_chunks(&self, blob_hash: &Hash) -> Result<Option<Vec<ChunkInfo>>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn
            .prepare(
                "SELECT chunk_hash, offset, size FROM blob_chunks WHERE blob_hash = ?1 ORDER BY chunk_index",
            )
            .map_err(|e| OakError::Database(e.to_string()))?;

        let rows: Vec<ChunkInfo> = stmt
            .query_map(params![blob_hash.as_str()], |row| {
                let hash_str: String = row.get(0)?;
                let offset: i64 = row.get(1)?;
                let size: i64 = row.get(2)?;
                Ok(ChunkInfo {
                    hash: Hash(hash_str),
                    offset: offset as u64,
                    length: size as u32,
                })
            })
            .map_err(|e| OakError::Database(e.to_string()))?
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|e| OakError::Database(e.to_string()))?;

        if rows.is_empty() {
            Ok(None)
        } else {
            Ok(Some(rows))
        }
    }

    fn put_commit_and_advance_refs(
        &self,
        branch_name: String,
        parent_hash: Option<Hash>,
        merge_parent_hash: Option<Hash>,
        entries: Vec<ManifestEntry>,
        author: String,
        message: Option<String>,
        timestamp: chrono::DateTime<chrono::Utc>,
        files: Vec<FileChange>,
    ) -> Result<Hash> {
        // Build tree structure and hash the commit before opening the
        // transaction so the SQLite write lock is held only for publication.
        let built = crate::build_tree(&entries)?;
        let manifest_hash = built.root_hash.clone();
        let commit = Commit::with_timestamp(
            branch_name,
            parent_hash,
            merge_parent_hash,
            manifest_hash,
            author,
            message,
            files,
            timestamp,
        )?;
        let commit_hash = commit.hash.clone();

        self.publish_commit(&commit, &built.trees, false)?;
        Ok(commit_hash)
    }

    fn put_tree_commit_and_advance_refs(
        &self,
        branch_name: String,
        parent_hash: Option<Hash>,
        merge_parent_hash: Option<Hash>,
        root: Hash,
        trees: &[Tree],
        author: String,
        message: Option<String>,
        timestamp: chrono::DateTime<chrono::Utc>,
        files: Vec<FileChange>,
    ) -> Result<Hash> {
        let commit = Commit::with_timestamp(
            branch_name,
            parent_hash,
            merge_parent_hash,
            root,
            author,
            message,
            files,
            timestamp,
        )?;
        let commit_hash = commit.hash.clone();
        self.publish_commit(&commit, trees, true)?;
        Ok(commit_hash)
    }
}

// --- Test instrumentation ---

impl SqliteRepository {
    /// How many whole trees have been flattened through this handle by
    /// [`Repository::walk_tree`] or [`Repository::get_manifest`]. Test
    /// instrumentation for load budgets (e.g. `oak status --json` flattens
    /// HEAD exactly once).
    #[doc(hidden)]
    pub fn tree_flatten_count(&self) -> u64 {
        self.tree_flattens.load(Ordering::Relaxed)
    }

    /// How many tree objects [`Repository::get_tree`] has been asked for
    /// through this handle. A flatten that bypasses `walk_tree` (a caller
    /// driving `flatten_tree` with its own fetch closure) still shows up
    /// here, one read per directory.
    #[doc(hidden)]
    pub fn tree_read_count(&self) -> u64 {
        self.tree_reads.load(Ordering::Relaxed)
    }
}

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

    #[test]
    fn tree_decoder_reuses_context_and_grows_for_large_rows() {
        let small = b"blob\ta.txt\tabc\tregular".to_vec();
        // Larger than the initial 64 KiB buffer and poorly compressible.
        let large: Vec<u8> = (0..300_000u32)
            .map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8)
            .collect();
        for raw in [&small, &large, &small] {
            let stored = zstd_compress(raw).unwrap();
            assert_eq!(&zstd_decompress_tree(&stored).unwrap(), raw);
        }
        let frame = zstd_compress(&small).unwrap();
        for bad in [
            b"not a zstd frame".to_vec(),
            Vec::new(),
            [frame.as_slice(), b"trailing"].concat(),
            frame[..frame.len() - 1].to_vec(),
        ] {
            assert_eq!(
                zstd_decompress_tree(&bad).is_err(),
                zstd_decompress(&bad).is_err(),
                "{bad:?}"
            );
        }
        let two = [frame.as_slice(), frame.as_slice()].concat();
        assert_eq!(
            zstd_decompress_tree(&two).unwrap(),
            zstd_decompress(&two).unwrap()
        );
        assert!(zstd_decompress_tree(b"not a zstd frame").is_err());
        // A failed row leaves the per-thread decoder usable.
        assert_eq!(
            zstd_decompress_tree(&zstd_compress(&small).unwrap()).unwrap(),
            small
        );
    }

    fn delete_migration_row(db_path: &Path, version: &str) {
        let conn = Connection::open(db_path).unwrap();
        conn.execute(
            "DELETE FROM schema_migrations WHERE version = ?1",
            params![version],
        )
        .unwrap();
    }

    fn migration_succeeded(db_path: &Path, version: &str) -> bool {
        let conn = Connection::open(db_path).unwrap();
        conn.query_row(
            "SELECT succeeded FROM schema_migrations WHERE version = ?1",
            params![version],
            |row| row.get::<_, i64>(0),
        )
        .optional()
        .unwrap()
            == Some(1)
    }

    #[test]
    fn missing_0007_row_with_existing_blob_codec_is_marked_applied() {
        let temp = tempfile::TempDir::new().unwrap();
        let db_path = temp.path().join("oak.db");
        drop(SqliteRepository::open(&db_path).unwrap());
        delete_migration_row(&db_path, "0007_blobs_codec");

        SqliteRepository::open(&db_path).unwrap();

        assert!(migration_succeeded(&db_path, "0007_blobs_codec"));
    }

    #[test]
    fn missing_0008_row_with_existing_tree_content_is_marked_applied() {
        let temp = tempfile::TempDir::new().unwrap();
        let db_path = temp.path().join("oak.db");
        drop(SqliteRepository::open(&db_path).unwrap());
        delete_migration_row(&db_path, "0008_trees_content");

        SqliteRepository::open(&db_path).unwrap();

        assert!(migration_succeeded(&db_path, "0008_trees_content"));
    }

    #[test]
    fn test_blob_roundtrip() {
        let repo = SqliteRepository::in_memory().unwrap();
        let blob = Blob::from_str("hello world");

        repo.store_blob(&blob).unwrap();
        let retrieved = repo.get_blob(&blob.hash).unwrap().unwrap();

        assert_eq!(retrieved.hash, blob.hash);
        assert_eq!(retrieved.content, blob.content);
    }

    #[test]
    fn test_tree_put_walk_roundtrip() {
        let repo = SqliteRepository::in_memory().unwrap();
        // Store the blobs first (FK enforcement at sqlite level requires they exist).
        for content in ["a", "b", "c"] {
            repo.store_blob(&Blob::from_str(content)).unwrap();
        }

        let entries = vec![
            ManifestEntry {
                path: "src/lib.rs".to_string(),
                blob_hash: Blob::from_str("a").hash,
                mode: FileMode::Regular,
            },
            ManifestEntry {
                path: "src/bin/main.rs".to_string(),
                blob_hash: Blob::from_str("b").hash,
                mode: FileMode::Regular,
            },
            ManifestEntry {
                path: "README.md".to_string(),
                blob_hash: Blob::from_str("c").hash,
                mode: FileMode::Regular,
            },
        ];

        let root = repo.put_tree(entries.clone()).unwrap();
        assert!(repo.has_tree(&root).unwrap());

        let walked = repo.walk_tree(&root).unwrap();
        assert_eq!(walked.len(), 3);

        let manifest = Manifest::new(entries);
        let walked_manifest = Manifest::new(walked);
        assert_eq!(manifest.hash, walked_manifest.hash);
    }

    #[test]
    fn put_tree_commit_stores_new_trees_and_advances_refs() {
        let repo = SqliteRepository::in_memory().unwrap();
        let entry = |path: &str, content: &str| ManifestEntry {
            path: path.to_string(),
            blob_hash: crate::hash_string(content),
            mode: FileMode::Regular,
        };
        let base = crate::build_tree(&[entry("src/a.rs", "a"), entry("docs/x.md", "x")]).unwrap();
        for tree in &base.trees {
            repo.store_tree(tree).unwrap();
        }
        // An edit that reuses the stored `docs/` subtree by hash.
        let mut fetch = |h: &Hash| {
            repo.get_tree(h)?
                .ok_or_else(|| OakError::ManifestNotFound(h.to_string()))
        };
        let edited =
            crate::edit_tree(&base.root_hash, &[entry("src/a.rs", "a2")], &[], &mut fetch).unwrap();
        assert_eq!(edited.trees.len(), 2, "new root and src/ only");

        let commit = repo
            .put_tree_commit_and_advance_refs(
                "feature".to_string(),
                None,
                None,
                edited.root_hash.clone(),
                &edited.trees,
                "tester".to_string(),
                None,
                chrono::Utc::now(),
                vec![],
            )
            .unwrap();
        assert_eq!(
            repo.get_branch_head("feature").unwrap(),
            Some(commit.clone())
        );
        assert_eq!(repo.get_head().unwrap(), Some(commit.clone()));
        assert_eq!(
            repo.get_commit(&commit).unwrap().unwrap().manifest_hash,
            edited.root_hash
        );
        let manifest = repo.get_manifest(&edited.root_hash).unwrap().unwrap();
        assert_eq!(
            manifest.hash,
            Manifest::new(vec![entry("src/a.rs", "a2"), entry("docs/x.md", "x")]).hash
        );

        // A root that is neither passed nor stored is refused, and no ref moves.
        let dangling = crate::build_tree(&[entry("lost.txt", "lost")]).unwrap();
        let err = repo
            .put_tree_commit_and_advance_refs(
                "feature".to_string(),
                Some(commit.clone()),
                None,
                dangling.root_hash,
                &[],
                "tester".to_string(),
                None,
                chrono::Utc::now(),
                vec![],
            )
            .unwrap_err();
        assert!(matches!(err, OakError::ManifestNotFound(_)), "got {err:?}");
        assert_eq!(repo.get_branch_head("feature").unwrap(), Some(commit));
    }

    #[test]
    fn store_tree_rejects_mismatched_storage_hash() {
        let repo = SqliteRepository::in_memory().unwrap();
        let tree = Tree::new(vec![TreeEntry {
            name: "a.txt".to_string(),
            kind: TreeEntryKind::Blob,
            hash: Hash::from_hex(&"a".repeat(64)).unwrap(),
            mode: FileMode::Regular,
        }])
        .unwrap();
        let mut tampered = tree.clone();
        tampered.hash = Hash::from_hex(&"b".repeat(64)).unwrap();

        let err = repo.store_tree(&tampered).unwrap_err();
        assert!(
            matches!(err, OakError::InvalidHash(_)),
            "expected invalid hash error, got {err:?}"
        );
        assert!(!repo.has_tree(&tampered.hash).unwrap());
        assert!(repo.get_tree(&tampered.hash).unwrap().is_none());
    }

    #[test]
    fn get_tree_rejects_compressed_row_under_mismatched_hash() {
        let repo = SqliteRepository::in_memory().unwrap();
        let tree = Tree::new(vec![TreeEntry {
            name: "a.txt".to_string(),
            kind: TreeEntryKind::Blob,
            hash: Hash::from_hex(&"a".repeat(64)).unwrap(),
            mode: FileMode::Regular,
        }])
        .unwrap();
        let claimed = Hash::from_hex(&"c".repeat(64)).unwrap();
        let content = zstd_compress(&tree.canonical_bytes()).unwrap();
        {
            let conn = repo.conn.lock().unwrap();
            conn.execute(
                "INSERT INTO trees (hash, content) VALUES (?1, ?2)",
                rusqlite::params![claimed.as_str(), content],
            )
            .unwrap();
        }

        let err = repo.get_tree(&claimed).unwrap_err();
        assert!(
            matches!(err, OakError::InvalidHash(_)),
            "expected invalid hash error, got {err:?}"
        );
    }

    #[test]
    fn legacy_tree_entries_fallback() {
        // A tree written in the pre-0008 format (trees.content NULL + per-entry
        // tree_entries rows) must still read back correctly via get_tree's
        // fallback, identically to the new compressed-content format.
        let repo = SqliteRepository::in_memory().unwrap();
        let entries = vec![
            TreeEntry {
                name: "a.txt".to_string(),
                kind: TreeEntryKind::Blob,
                hash: Hash::from_hex(&"a".repeat(64)).unwrap(),
                mode: FileMode::Executable,
            },
            TreeEntry {
                name: "sub".to_string(),
                kind: TreeEntryKind::Tree,
                hash: Hash::from_hex(&"b".repeat(64)).unwrap(),
                mode: FileMode::Regular,
            },
        ];
        let tree = Tree::new(entries).unwrap();
        {
            let conn = repo.conn.lock().unwrap();
            conn.execute(
                "INSERT INTO trees (hash) VALUES (?1)",
                rusqlite::params![tree.hash.as_str()],
            )
            .unwrap();
            for e in &tree.entries {
                let mode_str = match (e.kind, e.mode) {
                    (TreeEntryKind::Tree, _) => "tree",
                    (TreeEntryKind::Blob, FileMode::Regular) => "regular",
                    (TreeEntryKind::Blob, FileMode::Executable) => "executable",
                    (TreeEntryKind::Blob, FileMode::Symlink) => "symlink",
                };
                conn.execute(
                    "INSERT INTO tree_entries (tree_hash, name, kind, hash, mode) VALUES (?1, ?2, ?3, ?4, ?5)",
                    rusqlite::params![tree.hash.as_str(), e.name, e.kind.as_str(), e.hash.as_str(), mode_str],
                )
                .unwrap();
            }
        }
        let got = repo.get_tree(&tree.hash).unwrap().unwrap();
        assert_eq!(got.hash, tree.hash);
        assert_eq!(got.canonical_bytes(), tree.canonical_bytes());
    }

    #[test]
    fn compact_storage_backfills_drops_and_recompresses() {
        let repo = SqliteRepository::in_memory().unwrap();

        // A new-format tree via the normal write path (gets trees.content).
        repo.store_blob(&Blob::from_str("x")).unwrap();
        let new_root = repo
            .put_tree(vec![ManifestEntry {
                path: "dir/x.txt".to_string(),
                blob_hash: Blob::from_str("x").hash,
                mode: FileMode::Regular,
            }])
            .unwrap();

        // A legacy tree: content NULL + tree_entries rows.
        let legacy = Tree::new(vec![TreeEntry {
            name: "old.txt".to_string(),
            kind: TreeEntryKind::Blob,
            hash: Hash::from_hex(&"c".repeat(64)).unwrap(),
            mode: FileMode::Regular,
        }])
        .unwrap();
        // A legacy raw blob: codec 0, compressible.
        let legacy_blob = Blob::from_str(&"zzzz ".repeat(80));
        {
            let conn = repo.conn.lock().unwrap();
            conn.execute(
                "INSERT INTO trees (hash) VALUES (?1)",
                rusqlite::params![legacy.hash.as_str()],
            )
            .unwrap();
            for e in &legacy.entries {
                conn.execute(
                    "INSERT INTO tree_entries (tree_hash, name, kind, hash, mode) VALUES (?1, ?2, ?3, ?4, 'regular')",
                    rusqlite::params![legacy.hash.as_str(), e.name, e.kind.as_str(), e.hash.as_str()],
                )
                .unwrap();
            }
            conn.execute(
                "INSERT INTO blobs (hash, content, size, codec) VALUES (?1, ?2, ?3, 0)",
                rusqlite::params![
                    legacy_blob.hash.as_str(),
                    legacy_blob.content,
                    legacy_blob.size as i64
                ],
            )
            .unwrap();
        }

        let stats = repo.compact_storage().unwrap();
        assert_eq!(stats.trees_backfilled, 1);
        assert!(stats.tree_entries_dropped);
        assert!(stats.blobs_recompressed >= 1);

        // tree_entries table is gone.
        {
            let conn = repo.conn.lock().unwrap();
            assert!(!table_exists(&conn, "tree_entries").unwrap());
        }

        // Both trees and both blobs still read correctly.
        assert!(repo.get_tree(&new_root).unwrap().is_some());
        let got_legacy = repo.get_tree(&legacy.hash).unwrap().unwrap();
        assert_eq!(got_legacy.canonical_bytes(), legacy.canonical_bytes());
        assert_eq!(
            repo.get_blob(&legacy_blob.hash).unwrap().unwrap().content,
            legacy_blob.content
        );

        // Idempotent: a second run is a no-op (plus a VACUUM).
        let stats2 = repo.compact_storage().unwrap();
        assert_eq!(stats2.trees_backfilled, 0);
        assert_eq!(stats2.blobs_recompressed, 0);
    }

    #[test]
    fn legacy_raw_blob_fallback() {
        // A pre-0007 blob row (raw content, codec 0) must read back as plaintext
        // even though new writes would have zstd-compressed it.
        let repo = SqliteRepository::in_memory().unwrap();
        let blob = Blob::from_str(&"hello world ".repeat(50)); // very compressible
        {
            let conn = repo.conn.lock().unwrap();
            conn.execute(
                "INSERT INTO blobs (hash, content, size, codec) VALUES (?1, ?2, ?3, 0)",
                rusqlite::params![blob.hash.as_str(), blob.content, blob.size as i64],
            )
            .unwrap();
        }
        let got = repo.get_blob(&blob.hash).unwrap().unwrap();
        assert_eq!(got.content, blob.content);
    }

    #[test]
    fn new_blob_compresses_and_roundtrips() {
        // A compressible blob stored through the normal path is zstd-encoded
        // (codec 1) yet returns identical plaintext.
        let repo = SqliteRepository::in_memory().unwrap();
        let blob = Blob::from_str(&"abcabcabc ".repeat(100));
        repo.store_blob(&blob).unwrap();
        let codec: i64 = {
            let conn = repo.conn.lock().unwrap();
            conn.query_row(
                "SELECT codec FROM blobs WHERE hash = ?1",
                rusqlite::params![blob.hash.as_str()],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert_eq!(codec, 1, "compressible blob should store as zstd");
        let got = repo.get_blob(&blob.hash).unwrap().unwrap();
        assert_eq!(got.content, blob.content);
    }

    #[test]
    fn test_tree_subtree_dedup() {
        let repo = SqliteRepository::in_memory().unwrap();
        for content in ["x", "y"] {
            repo.store_blob(&Blob::from_str(content)).unwrap();
        }

        // Two roots that share the "shared/" subtree exactly.
        let entries_a = vec![
            ManifestEntry {
                path: "shared/x.txt".to_string(),
                blob_hash: Blob::from_str("x").hash,
                mode: FileMode::Regular,
            },
            ManifestEntry {
                path: "shared/y.txt".to_string(),
                blob_hash: Blob::from_str("y").hash,
                mode: FileMode::Regular,
            },
        ];
        let entries_b = vec![
            ManifestEntry {
                path: "shared/x.txt".to_string(),
                blob_hash: Blob::from_str("x").hash,
                mode: FileMode::Regular,
            },
            ManifestEntry {
                path: "shared/y.txt".to_string(),
                blob_hash: Blob::from_str("y").hash,
                mode: FileMode::Regular,
            },
            ManifestEntry {
                path: "extra.txt".to_string(),
                blob_hash: Blob::from_str("x").hash,
                mode: FileMode::Regular,
            },
        ];

        let root_a = repo.put_tree(entries_a).unwrap();
        let root_b = repo.put_tree(entries_b).unwrap();
        assert_ne!(root_a, root_b);

        // The "shared" subtree should be the same object for both roots.
        let shared_a = repo.subtree_at_path(&root_a, "shared").unwrap().unwrap();
        let shared_b = repo.subtree_at_path(&root_b, "shared").unwrap().unwrap();
        assert_eq!(shared_a, shared_b);
    }

    #[test]
    fn test_tree_resolve_path() {
        let repo = SqliteRepository::in_memory().unwrap();
        repo.store_blob(&Blob::from_str("file")).unwrap();
        let entries = vec![ManifestEntry {
            path: "a/b/c.txt".to_string(),
            blob_hash: Blob::from_str("file").hash,
            mode: FileMode::Regular,
        }];
        let root = repo.put_tree(entries).unwrap();

        let blob = repo.resolve_path_in_tree(&root, "a/b/c.txt").unwrap();
        assert!(blob.is_some());
        assert_eq!(blob.unwrap().kind, TreeEntryKind::Blob);

        let dir = repo.resolve_path_in_tree(&root, "a/b").unwrap();
        assert_eq!(dir.unwrap().kind, TreeEntryKind::Tree);

        let missing = repo.resolve_path_in_tree(&root, "a/zzz.txt").unwrap();
        assert!(missing.is_none());
    }

    #[test]
    fn test_tree_put_idempotent() {
        let repo = SqliteRepository::in_memory().unwrap();
        repo.store_blob(&Blob::from_str("c")).unwrap();
        let entries = vec![ManifestEntry {
            path: "x.txt".to_string(),
            blob_hash: Blob::from_str("c").hash,
            mode: FileMode::Regular,
        }];
        let r1 = repo.put_tree(entries.clone()).unwrap();
        let r2 = repo.put_tree(entries).unwrap();
        assert_eq!(r1, r2);
    }

    #[test]
    fn test_put_commit_and_advance_refs_stores_commit_and_moves_heads() {
        let repo = SqliteRepository::in_memory().unwrap();
        let blob = Blob::from_str("content");
        repo.store_blob(&blob).unwrap();
        let entries = vec![ManifestEntry {
            path: "file.txt".to_string(),
            blob_hash: blob.hash.clone(),
            mode: FileMode::Regular,
        }];
        let files = vec![FileChange {
            path: "file.txt".to_string(),
            change_type: ChangeType::Added,
            old_blob_hash: None,
            new_blob_hash: Some(blob.hash),
            old_path: None,
            old_mode: None,
            new_mode: None,
        }];
        let timestamp = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();

        let commit_hash = repo
            .put_commit_and_advance_refs(
                "main".to_string(),
                None,
                None,
                entries,
                "tester <t@example.com>".to_string(),
                None,
                timestamp,
                files,
            )
            .unwrap();

        assert_eq!(
            repo.get_branch_head("main").unwrap(),
            Some(commit_hash.clone())
        );
        assert_eq!(repo.get_head().unwrap(), Some(commit_hash.clone()));
        let commit = repo.get_commit(&commit_hash).unwrap().unwrap();
        assert_eq!(commit.timestamp, timestamp);
        assert_eq!(commit.files.len(), 1);
        let manifest = repo.get_manifest(&commit.manifest_hash).unwrap().unwrap();
        assert_eq!(manifest.entries.len(), 1);
        assert_eq!(manifest.entries[0].path, "file.txt");
    }

    #[test]
    fn test_manifest_roundtrip() {
        let repo = SqliteRepository::in_memory().unwrap();

        let blob = Blob::from_str("content");
        repo.store_blob(&blob).unwrap();

        let manifest = Manifest::new(vec![ManifestEntry {
            path: "test.txt".to_string(),
            blob_hash: blob.hash.clone(),
            mode: FileMode::Regular,
        }]);

        repo.store_manifest(&manifest).unwrap();
        let retrieved = repo.get_manifest(&manifest.hash).unwrap().unwrap();

        assert_eq!(retrieved.hash, manifest.hash);
        assert_eq!(retrieved.entries.len(), 1);
        assert_eq!(retrieved.entries[0].path, "test.txt");
    }

    #[test]
    fn test_branch_roundtrip() {
        let repo = SqliteRepository::in_memory().unwrap();

        let br = Branch::new("feature-x".to_string(), Some("A feature".to_string()), None);
        repo.store_branch(&br).unwrap();

        let retrieved = repo.get_branch("feature-x").unwrap().unwrap();
        assert_eq!(retrieved.name, "feature-x");
        assert_eq!(retrieved.description, Some("A feature".to_string()));
        assert_eq!(retrieved.status, BranchStatus::Open);
    }

    #[test]
    fn test_commit_roundtrip() {
        let repo = SqliteRepository::in_memory().unwrap();

        let blob = Blob::from_str("content");
        repo.store_blob(&blob).unwrap();

        let manifest = Manifest::new(vec![ManifestEntry {
            path: "test.txt".to_string(),
            blob_hash: blob.hash.clone(),
            mode: FileMode::Regular,
        }]);
        repo.store_manifest(&manifest).unwrap();

        let br = Branch::new("main".to_string(), None, None);
        repo.store_branch(&br).unwrap();

        let commit = Commit::new(
            "main".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "Test Author".to_string(),
            Some("Initial commit".to_string()),
            vec![FileChange {
                path: "test.txt".to_string(),
                change_type: ChangeType::Added,
                old_blob_hash: None,
                new_blob_hash: Some(blob.hash.clone()),
                old_path: None,
                old_mode: None,
                new_mode: None,
            }],
        )
        .unwrap();

        repo.store_commit(&commit).unwrap();
        let retrieved = repo.get_commit(&commit.hash).unwrap().unwrap();

        assert_eq!(retrieved.hash, commit.hash);
        assert_eq!(retrieved.branch_name, "main");
        assert_eq!(retrieved.message, Some("Initial commit".to_string()));
        assert_eq!(retrieved.files.len(), 1);
    }

    #[test]
    fn store_commit_is_idempotent_for_file_changes() {
        let repo = SqliteRepository::in_memory().unwrap();

        let blob = Blob::from_str("content");
        repo.store_blob(&blob).unwrap();
        let manifest = Manifest::new(vec![ManifestEntry {
            path: "test.txt".to_string(),
            blob_hash: blob.hash.clone(),
            mode: FileMode::Regular,
        }]);
        repo.store_manifest(&manifest).unwrap();

        let commit = Commit::new(
            "main".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "Test Author".to_string(),
            Some("Initial commit".to_string()),
            vec![FileChange {
                path: "test.txt".to_string(),
                change_type: ChangeType::Added,
                old_blob_hash: None,
                new_blob_hash: Some(blob.hash.clone()),
                old_path: None,
                old_mode: None,
                new_mode: None,
            }],
        )
        .unwrap();

        repo.store_commit(&commit).unwrap();
        repo.store_commit(&commit).unwrap();

        let conn = repo.conn.lock().unwrap();
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM commit_files WHERE commit_hash = ?1",
                rusqlite::params![commit.hash.as_str()],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count, 1);
    }

    /// The server's squash commit, and the row older `oak merge` binaries
    /// stored for it: the server's hash over a placeholder author and the
    /// client's clock (zach/nas-monitoring 0b40b5ee).
    fn squash_commit_and_placeholder_row() -> (Commit, Commit) {
        let server = Commit::with_timestamp(
            "main".to_string(),
            None,
            Some(Hash("e5".repeat(32))),
            Tree::empty_hash(),
            "zach".to_string(),
            Some("Land the feature".to_string()),
            Vec::new(),
            chrono::DateTime::parse_from_rfc3339("2026-10-22T02:14:31.185316+00:00")
                .unwrap()
                .with_timezone(&chrono::Utc),
        )
        .unwrap();
        let placeholder = Commit {
            author: "<remote>".to_string(),
            timestamp: server.timestamp + chrono::Duration::microseconds(153_983),
            ..server.clone()
        };
        (server, placeholder)
    }

    #[test]
    fn repair_commit_fields_rewrites_a_placeholder_row_to_the_verified_preimage() {
        let repo = SqliteRepository::in_memory().unwrap();
        let (server, placeholder) = squash_commit_and_placeholder_row();
        repo.store_commit(&placeholder).unwrap();
        // `store_commit` keeps the first row, so storing the verified commit
        // alone can't fix it.
        repo.store_commit(&server).unwrap();
        let err = repo
            .get_commit(&server.hash)
            .unwrap()
            .unwrap()
            .verify_fields()
            .unwrap_err();
        assert!(err.to_string().contains("author=\"<remote>\""), "{err}");

        assert!(repo.repair_commit_fields(&server).unwrap());
        let repaired = repo.get_commit(&server.hash).unwrap().unwrap();
        repaired.verify_fields().unwrap();
        assert_eq!(repaired.author, "zach");
        assert_eq!(repaired.timestamp, server.timestamp);

        // A row that already verifies is left alone.
        assert!(!repo.repair_commit_fields(&server).unwrap());
    }

    #[test]
    fn repair_commit_fields_refuses_unverified_input_and_edge_changes() {
        let repo = SqliteRepository::in_memory().unwrap();
        let (server, placeholder) = squash_commit_and_placeholder_row();
        repo.store_commit(&placeholder).unwrap();

        // The "repair" must itself reproduce the hash.
        assert!(repo.repair_commit_fields(&placeholder).is_err());

        // A verified commit with the same hash but different graph edges
        // cannot exist without a BLAKE3 collision, so fake one by
        // rewriting the stored row's parent instead.
        repo.conn
            .lock()
            .unwrap()
            .execute(
                "UPDATE commits SET merge_parent_hash = ?2 WHERE hash = ?1",
                rusqlite::params![server.hash.as_str(), "ab".repeat(32)],
            )
            .unwrap();
        let err = repo.repair_commit_fields(&server).unwrap_err();
        assert!(err.to_string().contains("refusing to repair"), "{err}");
        assert_eq!(
            repo.get_commit(&server.hash).unwrap().unwrap().author,
            "<remote>"
        );

        // Nothing stored under the hash: nothing to repair.
        let empty = SqliteRepository::in_memory().unwrap();
        assert!(!empty.repair_commit_fields(&server).unwrap());
    }

    #[test]
    fn test_branch_head() {
        let repo = SqliteRepository::in_memory().unwrap();

        let br = Branch::new("main".to_string(), None, None);
        repo.store_branch(&br).unwrap();

        assert!(repo.get_branch_head("main").unwrap().is_none());

        let blob = Blob::new(b"test".to_vec());
        repo.store_blob(&blob).unwrap();
        let manifest = Manifest::new(vec![ManifestEntry {
            path: "test.txt".to_string(),
            blob_hash: blob.hash.clone(),
            mode: FileMode::Regular,
        }]);
        repo.store_manifest(&manifest).unwrap();

        let commit = Commit::new(
            "main".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "test".to_string(),
            Some("test commit".to_string()),
            vec![],
        )
        .unwrap();
        repo.store_commit(&commit).unwrap();

        repo.set_branch_head("main", &commit.hash).unwrap();

        let retrieved = repo.get_branch_head("main").unwrap().unwrap();
        assert_eq!(retrieved, commit.hash);
    }

    #[test]
    fn test_list_branches() {
        let repo = SqliteRepository::in_memory().unwrap();

        let br1 = Branch::new("main".to_string(), None, None);
        let br2 = Branch::new(
            "feature".to_string(),
            Some("feature branch".to_string()),
            Some("main".to_string()),
        );
        repo.store_branch(&br1).unwrap();
        repo.store_branch(&br2).unwrap();

        let all = repo.list_branches().unwrap();
        assert_eq!(all.len(), 2);
    }

    #[test]
    fn legacy_sqlite_default_created_at_decodes_losslessly() {
        // fb-118: rows written through the column default `datetime('now')`
        // (space-separated UTC, no offset) used to abort every listing with
        // "premature end of input".
        let repo = SqliteRepository::in_memory().unwrap();
        repo.store_branch(&Branch::new("main".into(), None, None))
            .unwrap();
        repo.store_branch(&Branch::new("legacy".into(), None, Some("main".into())))
            .unwrap();
        repo.conn
            .lock()
            .unwrap()
            .execute(
                "UPDATE branches SET created_at = '2026-03-04 05:06:07' WHERE name = 'legacy'",
                [],
            )
            .unwrap();

        let legacy = repo.get_branch("legacy").unwrap().unwrap();
        assert_eq!(legacy.created_at.to_rfc3339(), "2026-03-04T05:06:07+00:00");
        assert_eq!(repo.list_branches().unwrap().len(), 2);
    }

    #[test]
    fn corrupt_created_at_is_isolated_to_its_row() {
        let repo = SqliteRepository::in_memory().unwrap();
        repo.store_branch(&Branch::new("main".into(), None, None))
            .unwrap();
        repo.store_branch(&Branch::new("broken".into(), None, Some("main".into())))
            .unwrap();
        repo.store_branch(&Branch::new("healthy".into(), None, Some("main".into())))
            .unwrap();
        repo.conn
            .lock()
            .unwrap()
            .execute(
                "UPDATE branches SET created_at = 'not-a-time' WHERE name = 'broken'",
                [],
            )
            .unwrap();

        let rows = repo.list_branches_isolated().unwrap();
        assert_eq!(rows.len(), 3);
        let unreadable: Vec<_> = rows.iter().filter_map(|row| row.as_ref().err()).collect();
        assert_eq!(unreadable.len(), 1);
        assert_eq!(unreadable[0].name, "broken");
        assert_eq!(unreadable[0].column, "created_at");
        assert_eq!(unreadable[0].status, BranchStatus::Open);
        assert_eq!(unreadable[0].code(), crate::BRANCH_METADATA_UNREADABLE);

        // Point reads of other rows are unaffected; the bad row's own read
        // fails with a typed error naming the branch, not a parser dump.
        assert!(repo.get_branch("healthy").unwrap().is_some());
        let error = repo.get_branch("broken").unwrap_err().to_string();
        assert!(error.contains("branch_metadata_unreadable"), "{error}");
        assert!(error.contains("'broken'") && error.contains("created_at"));
        assert!(!error.contains("not-a-time") && !error.contains("premature"));
    }

    #[test]
    fn parse_stored_timestamp_accepts_rfc3339_and_sqlite_forms_only() {
        use crate::parse_stored_timestamp as parse;
        assert!(parse("2026-03-04T05:06:07.123456+00:00").is_some());
        assert!(parse("2026-03-04T05:06:07Z").is_some());
        assert_eq!(
            parse("2026-03-04 05:06:07.250").unwrap().to_rfc3339(),
            "2026-03-04T05:06:07.250+00:00"
        );
        assert!(parse("2026-03-04").is_none());
        assert!(parse("").is_none());
        assert!(parse("yesterday").is_none());
    }

    #[test]
    fn test_commits_for_branch() {
        let repo = SqliteRepository::in_memory().unwrap();

        let br = Branch::new("main".to_string(), None, None);
        repo.store_branch(&br).unwrap();

        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();

        let commit1 = Commit::new(
            "main".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "author".to_string(),
            Some("commit 1".to_string()),
            vec![],
        )
        .unwrap();
        repo.store_commit(&commit1).unwrap();

        let commit2 = Commit::new(
            "main".to_string(),
            Some(commit1.hash.clone()),
            None,
            manifest.hash.clone(),
            "author".to_string(),
            Some("commit 2".to_string()),
            vec![],
        )
        .unwrap();
        repo.store_commit(&commit2).unwrap();

        let commits = repo.get_commits_for_branch("main").unwrap();
        assert_eq!(commits.len(), 2);
    }

    #[test]
    fn test_count_commits_for_branch() {
        let repo = SqliteRepository::in_memory().unwrap();

        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();

        // A branch with no commits of its own (freshly seeded onto a parent)
        // counts zero — the unmerged-work baseline.
        assert_eq!(repo.count_commits_for_branch("feature").unwrap(), 0);

        // One commit on `main`, two authored on `feature`. The count is keyed
        // strictly off the `branch_name` column, so `feature` reports 2
        // regardless of `main`'s history — exactly the "commits not yet merged
        // into the parent" signal.
        let base = Commit::new(
            "main".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "author".to_string(),
            None,
            vec![],
        )
        .unwrap();
        repo.store_commit(&base).unwrap();

        let feat1 = Commit::new(
            "feature".to_string(),
            Some(base.hash.clone()),
            None,
            manifest.hash.clone(),
            "author".to_string(),
            None,
            vec![],
        )
        .unwrap();
        repo.store_commit(&feat1).unwrap();

        let feat2 = Commit::new(
            "feature".to_string(),
            Some(feat1.hash.clone()),
            None,
            manifest.hash.clone(),
            "author".to_string(),
            None,
            vec![],
        )
        .unwrap();
        repo.store_commit(&feat2).unwrap();

        assert_eq!(repo.count_commits_for_branch("feature").unwrap(), 2);
        assert_eq!(repo.count_commits_for_branch("main").unwrap(), 1);
        // Matches the materializing path it optimizes.
        assert_eq!(
            repo.count_commits_for_branch("feature").unwrap(),
            repo.get_commits_for_branch("feature").unwrap().len()
        );
    }

    #[test]
    fn test_merge_child_exists() {
        let repo = SqliteRepository::in_memory().unwrap();

        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();

        let feature = Commit::new(
            "feature".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "author".to_string(),
            None,
            vec![],
        )
        .unwrap();
        repo.store_commit(&feature).unwrap();

        assert!(!repo.merge_child_exists(&feature.hash).unwrap());

        let main_merge = Commit::new(
            "main".to_string(),
            None,
            Some(feature.hash.clone()),
            manifest.hash.clone(),
            "author".to_string(),
            Some("merged feature".to_string()),
            vec![],
        )
        .unwrap();
        repo.store_commit(&main_merge).unwrap();

        assert!(repo.merge_child_exists(&feature.hash).unwrap());
    }

    #[test]
    fn test_metadata() {
        let repo = SqliteRepository::in_memory().unwrap();

        assert!(repo.get_head().unwrap().is_none());

        let hash = Hash("a".repeat(64));
        repo.set_head(&hash).unwrap();

        let retrieved = repo.get_head().unwrap().unwrap();
        assert_eq!(retrieved, hash);
    }

    #[test]
    fn test_current_branch() {
        let repo = SqliteRepository::in_memory().unwrap();

        assert!(repo.get_current_branch_name().unwrap().is_none());

        repo.set_current_branch("main").unwrap();
        let name = repo.get_current_branch_name().unwrap().unwrap();
        assert_eq!(name, "main");
    }

    /// A repo created before the foreign key was dropped keeps its tags, with
    /// every column intact, and leaves enforcement as the connection set it.
    #[test]
    fn tag_foreign_key_migration_preserves_existing_tags() {
        let temp = tempfile::TempDir::new().unwrap();
        let path = temp.path().join("oak.db");
        drop(SqliteRepository::open(&path).unwrap());

        // Put the database back to the schema before the migration.
        let conn = Connection::open(&path).unwrap();
        let commit = "cd".repeat(32);
        conn.execute_batch(&format!(
            "PRAGMA foreign_keys=OFF;
             DROP TABLE tags;
             CREATE TABLE tags (
                 name TEXT PRIMARY KEY,
                 commit_hash TEXT NOT NULL,
                 created_at TEXT NOT NULL DEFAULT (datetime('now')),
                 title TEXT,
                 notes TEXT,
                 is_prerelease INTEGER NOT NULL DEFAULT 0,
                 finalized INTEGER NOT NULL DEFAULT 0,
                 published_at TEXT,
                 created_by TEXT NOT NULL DEFAULT '',
                 revision INTEGER NOT NULL DEFAULT 0,
                 synced INTEGER NOT NULL DEFAULT 0,
                 FOREIGN KEY (commit_hash) REFERENCES commits(hash)
             );
             INSERT INTO tags VALUES ('v1.0', '{commit}', '2026-11-01T00:00:00+00:00',
                 'Title', 'Notes', 1, 1, '2026-11-02T00:00:00+00:00', 'bot', 7, 1);
             DELETE FROM schema_migrations WHERE version = '0018_drop_tags_commit_fk';"
        ))
        .unwrap();
        drop(conn);

        let repo = SqliteRepository::open(&path).unwrap();
        let conn = repo.conn.lock().unwrap();
        let row: (String, String, String, i64, i64, String, i64, i64) = conn
            .query_row(
                "SELECT commit_hash, title, notes, is_prerelease, finalized, created_by, \
                        revision, synced FROM tags WHERE name = 'v1.0'",
                [],
                |r| {
                    Ok((
                        r.get(0)?,
                        r.get(1)?,
                        r.get(2)?,
                        r.get(3)?,
                        r.get(4)?,
                        r.get(5)?,
                        r.get(6)?,
                        r.get(7)?,
                    ))
                },
            )
            .unwrap();
        assert_eq!(
            row,
            (
                commit,
                "Title".into(),
                "Notes".into(),
                1,
                1,
                "bot".into(),
                7,
                1
            )
        );

        let fks: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM pragma_foreign_key_list('tags')",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(fks, 0);
        let enforced: i64 = conn
            .query_row("PRAGMA foreign_keys", [], |r| r.get(0))
            .unwrap();
        assert_eq!(enforced, 1, "the migration must not change enforcement");
    }

    #[test]
    fn test_branch_description_update() {
        let repo = SqliteRepository::in_memory().unwrap();

        let br = Branch::new("main".to_string(), Some("old desc".to_string()), None);
        repo.store_branch(&br).unwrap();

        repo.update_branch_description("main", "new desc").unwrap();

        let updated = repo.get_branch("main").unwrap().unwrap();
        assert_eq!(updated.description, Some("new desc".to_string()));
    }

    #[test]
    fn legacy_description_requires_matching_baseline_before_remote_refresh() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("oak.db");
        {
            let repo = SqliteRepository::open(&path).unwrap();
            repo.store_branch(&Branch::new(
                "feature".into(),
                Some("legacy local".into()),
                None,
            ))
            .unwrap();
            // Fixture of the previous schema: no local/remote synchronization evidence.
            repo.conn
                .lock()
                .unwrap()
                .execute_batch(
                    "ALTER TABLE branches DROP COLUMN description_pending;
                 DELETE FROM schema_migrations WHERE version = '0012_pending_branch_description';",
                )
                .unwrap();
        }
        let repo = SqliteRepository::open(&path).unwrap();
        assert!(repo.branch_description_pending("feature").unwrap());
        let mut remote = Branch::new("feature".into(), Some("remote changed".into()), None);
        repo.upsert_branch_metadata_at_generation(&remote, repo.description_generation().unwrap())
            .unwrap();
        assert_eq!(
            repo.get_branch("feature")
                .unwrap()
                .unwrap()
                .description
                .as_deref(),
            Some("legacy local")
        );
        remote.description = Some("legacy local".into());
        repo.upsert_branch_metadata_at_generation(&remote, repo.description_generation().unwrap())
            .unwrap();
        assert!(!repo.branch_description_pending("feature").unwrap());
        remote.description = None;
        repo.upsert_branch_metadata_at_generation(&remote, repo.description_generation().unwrap())
            .unwrap();
        assert_eq!(
            repo.get_branch("feature").unwrap().unwrap().description,
            None
        );
    }

    #[test]
    fn pending_description_survives_rename_and_stale_publish_ack() {
        let repo = SqliteRepository::in_memory().unwrap();
        repo.store_branch(&Branch::new("feature".into(), None, None))
            .unwrap();
        repo.edit_branch_description("feature", "pending").unwrap();
        repo.rename_branch("feature", "renamed").unwrap();
        assert!(repo.branch_description_pending("renamed").unwrap());
        repo.edit_branch_description("renamed", "newer").unwrap();
        repo.acknowledge_branch_description(
            "renamed",
            Some("pending"),
            repo.description_publication_generation().unwrap(),
        )
        .unwrap();
        assert!(repo.branch_description_pending("renamed").unwrap());
        repo.acknowledge_branch_description(
            "renamed",
            Some("newer"),
            repo.description_publication_generation().unwrap(),
        )
        .unwrap();
        assert!(!repo.branch_description_pending("renamed").unwrap());
    }

    #[test]
    fn description_fetch_fence_covers_aba_new_rows_and_overlapping_refreshes() {
        let repo = SqliteRepository::in_memory().unwrap();
        let mut remote = Branch::new("feature".into(), Some("A".into()), None);
        repo.store_branch(&remote).unwrap();
        let before = repo.description_generation().unwrap();
        repo.edit_branch_description("feature", "B").unwrap();
        repo.edit_branch_description("feature", "A").unwrap();
        // Matching text from an older fetch cannot acknowledge an ABA edit.
        assert!(!repo
            .reconcile_pulled_branch_metadata(&remote, before)
            .unwrap());
        assert!(repo.branch_description_pending("feature").unwrap());
        repo.acknowledge_branch_description("feature", Some("A"), Some(before))
            .unwrap();
        assert!(
            repo.branch_description_pending("feature").unwrap(),
            "old successful POST cannot acknowledge an ABA edit"
        );
        repo.acknowledge_branch_description(
            "feature",
            Some("A"),
            repo.description_publication_generation().unwrap(),
        )
        .unwrap();
        remote.description = Some("stale remote".into());
        assert!(!repo
            .reconcile_pulled_branch_metadata(&remote, before)
            .unwrap());
        assert_eq!(
            repo.get_branch("feature")
                .unwrap()
                .unwrap()
                .description
                .as_deref(),
            Some("A")
        );
        let fresh = repo.description_generation().unwrap();
        assert!(repo
            .reconcile_pulled_branch_metadata(&remote, fresh)
            .unwrap());
        remote.description = Some("overlapping old response".into());
        assert!(!repo
            .upsert_branch_metadata_at_generation(&remote, fresh)
            .unwrap());
        assert_eq!(
            repo.get_branch("feature")
                .unwrap()
                .unwrap()
                .description
                .as_deref(),
            Some("stale remote")
        );

        let before_creation = repo.description_generation().unwrap();
        let mut new_branch = Branch::new("new".into(), Some("locally created".into()), None);
        repo.store_branch(&new_branch).unwrap();
        new_branch.description = Some("older remote response".into());
        assert!(!repo
            .upsert_branch_metadata_at_generation(&new_branch, before_creation)
            .unwrap());
        assert_eq!(
            repo.get_branch("new")
                .unwrap()
                .unwrap()
                .description
                .as_deref(),
            Some("locally created")
        );

        // A sibling edit does not unnecessarily block this branch's refresh.
        let before_sibling = repo.description_generation().unwrap();
        repo.edit_branch_description("new", "sibling update")
            .unwrap();
        assert!(repo
            .reconcile_pulled_branch_metadata(&remote, before_sibling)
            .unwrap());
    }

    #[test]
    fn test_get_commits_since_edge_cases() {
        let repo = SqliteRepository::in_memory().unwrap();

        let br = Branch::new("main".to_string(), None, None);
        repo.store_branch(&br).unwrap();

        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();

        // No commits - get_commits_since should return empty
        let commits = repo.get_commits_since("main", None).unwrap();
        assert!(commits.is_empty());

        // With a non-existent since hash and no commits — returns empty (no commits on branch)
        let commits = repo
            .get_commits_since("main", Some(&Hash("nonexistent".to_string())))
            .unwrap();
        assert!(commits.is_empty());
    }

    #[test]
    fn test_get_commits_since_cross_branch_hash_returns_all() {
        // When since_hash belongs to a different branch (not found in this
        // branch's commits), get_commits_since should return ALL commits
        // for this branch, since they are all new from the caller's view.
        let repo = SqliteRepository::in_memory().unwrap();
        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();
        repo.store_branch(&Branch::new("default".to_string(), None, None))
            .unwrap();
        repo.store_branch(&Branch::new(
            "update".to_string(),
            None,
            Some("default".to_string()),
        ))
        .unwrap();

        // Commit on "default"
        let c_default = Commit::new(
            "default".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "a".to_string(),
            Some("default commit".to_string()),
            vec![],
        )
        .unwrap();
        repo.store_commit(&c_default).unwrap();

        // Commits on "update"
        let c_update1 = Commit::new(
            "update".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "a".to_string(),
            Some("update commit 1".to_string()),
            vec![],
        )
        .unwrap();
        let c_update2 = Commit::new(
            "update".to_string(),
            Some(c_update1.hash.clone()),
            None,
            manifest.hash.clone(),
            "a".to_string(),
            Some("update commit 2".to_string()),
            vec![],
        )
        .unwrap();
        repo.store_commit(&c_update1).unwrap();
        repo.store_commit(&c_update2).unwrap();

        // get_commits_since("update", default_branch_head) should return
        // ALL "update" commits since the hash doesn't belong to "update"
        let since = repo
            .get_commits_since("update", Some(&c_default.hash))
            .unwrap();
        assert_eq!(
            since.len(),
            2,
            "should return all update commits when since_hash is from another branch"
        );
        assert_eq!(since[0].message, Some("update commit 1".to_string()));
        assert_eq!(since[1].message, Some("update commit 2".to_string()));
    }

    // ============================================================
    // Blob edge cases
    // ============================================================

    #[test]
    fn test_has_blob() {
        let repo = SqliteRepository::in_memory().unwrap();
        let blob = Blob::from_str("test content");

        assert!(!repo.has_blob(&blob.hash).unwrap());
        repo.store_blob(&blob).unwrap();
        assert!(repo.has_blob(&blob.hash).unwrap());
    }

    #[test]
    fn test_get_nonexistent_blob() {
        let repo = SqliteRepository::in_memory().unwrap();
        let result = repo.get_blob(&Hash("nonexistent".to_string())).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_store_blob_idempotent() {
        let repo = SqliteRepository::in_memory().unwrap();
        let blob = Blob::from_str("same content");

        repo.store_blob(&blob).unwrap();
        repo.store_blob(&blob).unwrap(); // Should not error (INSERT OR IGNORE)

        let retrieved = repo.get_blob(&blob.hash).unwrap().unwrap();
        assert_eq!(retrieved.content, blob.content);
    }

    #[test]
    fn test_blob_empty_content() {
        let repo = SqliteRepository::in_memory().unwrap();
        let blob = Blob::new(Vec::new());

        repo.store_blob(&blob).unwrap();
        let retrieved = repo.get_blob(&blob.hash).unwrap().unwrap();
        assert!(retrieved.content.is_empty());
        assert_eq!(retrieved.size, 0);
    }

    #[test]
    fn test_put_blob_sources_matches_put_blob() {
        let repo = SqliteRepository::in_memory().unwrap();
        let contents: Vec<Vec<u8>> = vec![
            b"alpha".to_vec(),
            Vec::new(),
            b"alpha".to_vec(), // duplicate within one batch
            vec![0u8; 64 * 1024],
        ];

        let hashes = repo
            .put_blob_sources(
                contents
                    .iter()
                    .cloned()
                    .map(BlobSource::from_content)
                    .collect(),
            )
            .unwrap();
        assert_eq!(hashes.len(), contents.len());
        for (content, hash) in contents.iter().zip(&hashes) {
            // Same canonical hash as the one-at-a-time path...
            assert_eq!(hash, &repo.put_blob(content.clone()).unwrap());
            // ...and the content round-trips.
            let retrieved = repo.get_blob(hash).unwrap().unwrap();
            assert_eq!(&retrieved.content, content);
        }
        assert_eq!(hashes[0], hashes[2]);

        assert!(repo.put_blob_sources(Vec::new()).unwrap().is_empty());

        // The deferred-source entry point yields the same canonical hashes,
        // in input order, with or without size hints.
        let sources: Vec<BlobSource> = contents
            .iter()
            .cloned()
            .enumerate()
            .map(|(i, c)| {
                let hint = if i % 2 == 0 {
                    Some(c.len() as u64)
                } else {
                    None
                };
                BlobSource::new(hint, move || Ok(c))
            })
            .collect();
        assert_eq!(repo.put_blob_sources(sources).unwrap(), hashes);
        assert!(repo.put_blob_sources(Vec::new()).unwrap().is_empty());
        // Single-source fast path (autocommit, no transaction) agrees too.
        let single = vec![BlobSource::new(None, || Ok(b"alpha".to_vec()))];
        assert_eq!(
            repo.put_blob_sources(single).unwrap(),
            vec![hashes[0].clone()]
        );
    }

    #[test]
    fn test_blob_binary_content() {
        let repo = SqliteRepository::in_memory().unwrap();
        let binary_data: Vec<u8> = (0..=255).collect();
        let blob = Blob::new(binary_data.clone());

        repo.store_blob(&blob).unwrap();
        let retrieved = repo.get_blob(&blob.hash).unwrap().unwrap();
        assert_eq!(retrieved.content, binary_data);
    }

    // ============================================================
    // Manifest edge cases
    // ============================================================

    #[test]
    fn test_get_nonexistent_manifest() {
        let repo = SqliteRepository::in_memory().unwrap();
        let result = repo.get_manifest(&Hash("nonexistent".to_string())).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_manifest_with_multiple_entries() {
        let repo = SqliteRepository::in_memory().unwrap();

        let blob1 = Blob::from_str("content1");
        let blob2 = Blob::from_str("content2");
        repo.store_blob(&blob1).unwrap();
        repo.store_blob(&blob2).unwrap();

        let manifest = Manifest::new(vec![
            ManifestEntry {
                path: "src/main.rs".to_string(),
                blob_hash: blob1.hash.clone(),
                mode: FileMode::Regular,
            },
            ManifestEntry {
                path: "scripts/build.sh".to_string(),
                blob_hash: blob2.hash.clone(),
                mode: FileMode::Executable,
            },
        ]);

        repo.store_manifest(&manifest).unwrap();
        let retrieved = repo.get_manifest(&manifest.hash).unwrap().unwrap();

        assert_eq!(retrieved.entries.len(), 2);
        let paths: Vec<&str> = retrieved.entries.iter().map(|e| e.path.as_str()).collect();
        assert!(paths.contains(&"src/main.rs"));
        assert!(paths.contains(&"scripts/build.sh"));

        // Check modes are preserved
        let exec_entry = retrieved
            .entries
            .iter()
            .find(|e| e.path == "scripts/build.sh")
            .unwrap();
        assert_eq!(exec_entry.mode, FileMode::Executable);
    }

    #[test]
    fn test_store_manifest_idempotent() {
        let repo = SqliteRepository::in_memory().unwrap();
        let manifest = Manifest::empty();

        repo.store_manifest(&manifest).unwrap();
        repo.store_manifest(&manifest).unwrap(); // Should not error
    }

    // ============================================================
    // Branch edge cases
    // ============================================================

    #[test]
    fn test_get_nonexistent_branch() {
        let repo = SqliteRepository::in_memory().unwrap();
        let result = repo.get_branch("nonexistent").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_branch_status_update() {
        let repo = SqliteRepository::in_memory().unwrap();
        let br = Branch::new("feature".to_string(), None, None);
        repo.store_branch(&br).unwrap();

        assert_eq!(
            repo.get_branch("feature").unwrap().unwrap().status,
            BranchStatus::Open
        );

        repo.update_branch_status("feature", BranchStatus::Closed)
            .unwrap();
        assert_eq!(
            repo.get_branch("feature").unwrap().unwrap().status,
            BranchStatus::Closed
        );

        repo.update_branch_status("feature", BranchStatus::Open)
            .unwrap();
        assert_eq!(
            repo.get_branch("feature").unwrap().unwrap().status,
            BranchStatus::Open
        );
    }

    #[test]
    fn test_branch_with_parent() {
        let repo = SqliteRepository::in_memory().unwrap();

        let main = Branch::new("main".to_string(), None, None);
        let feature = Branch::new(
            "feature".to_string(),
            Some("my feature".to_string()),
            Some("main".to_string()),
        );
        repo.store_branch(&main).unwrap();
        repo.store_branch(&feature).unwrap();

        let retrieved = repo.get_branch("feature").unwrap().unwrap();
        assert_eq!(retrieved.parent_branch, Some("main".to_string()));
        assert_eq!(retrieved.description, Some("my feature".to_string()));
    }

    #[test]
    fn test_get_branch_head_nonexistent() {
        let repo = SqliteRepository::in_memory().unwrap();
        let result = repo.get_branch_head("nonexistent").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_rename_branch_rejects_orphan_target_head() {
        let repo = SqliteRepository::in_memory().unwrap();
        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();

        repo.store_branch(&Branch::new("old".to_string(), None, None))
            .unwrap();

        let old_commit = Commit::new(
            "old".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "author".to_string(),
            Some("old".to_string()),
            vec![],
        )
        .unwrap();
        let target_commit = Commit::new(
            "target".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "author".to_string(),
            Some("target".to_string()),
            vec![],
        )
        .unwrap();
        repo.store_commit(&old_commit).unwrap();
        repo.store_commit(&target_commit).unwrap();
        repo.set_branch_head("old", &old_commit.hash).unwrap();
        repo.set_branch_head("target", &target_commit.hash).unwrap();

        let err = repo.rename_branch("old", "target").unwrap_err();
        assert!(
            matches!(err, OakError::BranchAlreadyExists(ref name) if name == "target"),
            "expected BranchAlreadyExists, got {err:?}"
        );
        assert_eq!(
            repo.get_branch_head("old").unwrap(),
            Some(old_commit.hash.clone())
        );
        assert_eq!(
            repo.get_branch_head("target").unwrap(),
            Some(target_commit.hash.clone())
        );
    }

    // ============================================================
    // Commit edge cases
    // ============================================================

    #[test]
    fn test_has_commit() {
        let repo = SqliteRepository::in_memory().unwrap();
        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();
        let br = Branch::new("main".to_string(), None, None);
        repo.store_branch(&br).unwrap();

        let commit = Commit::new(
            "main".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "author".to_string(),
            Some("test".to_string()),
            vec![],
        )
        .unwrap();

        assert!(!repo.has_commit(&commit.hash).unwrap());
        repo.store_commit(&commit).unwrap();
        assert!(repo.has_commit(&commit.hash).unwrap());
    }

    #[test]
    fn test_get_nonexistent_commit() {
        let repo = SqliteRepository::in_memory().unwrap();
        let result = repo.get_commit(&Hash("nonexistent".to_string())).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_get_commits_since_with_valid_hash() {
        let repo = SqliteRepository::in_memory().unwrap();
        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();
        let br = Branch::new("main".to_string(), None, None);
        repo.store_branch(&br).unwrap();

        let c1 = Commit::new(
            "main".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "a".to_string(),
            Some("c1".to_string()),
            vec![],
        )
        .unwrap();
        let c2 = Commit::new(
            "main".to_string(),
            Some(c1.hash.clone()),
            None,
            manifest.hash.clone(),
            "a".to_string(),
            Some("c2".to_string()),
            vec![],
        )
        .unwrap();
        let c3 = Commit::new(
            "main".to_string(),
            Some(c2.hash.clone()),
            None,
            manifest.hash.clone(),
            "a".to_string(),
            Some("c3".to_string()),
            vec![],
        )
        .unwrap();
        repo.store_commit(&c1).unwrap();
        repo.store_commit(&c2).unwrap();
        repo.store_commit(&c3).unwrap();

        // Get commits since c1 should return c2 and c3
        let since = repo.get_commits_since("main", Some(&c1.hash)).unwrap();
        assert_eq!(since.len(), 2);
        assert_eq!(since[0].message, Some("c2".to_string()));
        assert_eq!(since[1].message, Some("c3".to_string()));

        // Get commits since c2 should return only c3
        let since = repo.get_commits_since("main", Some(&c2.hash)).unwrap();
        assert_eq!(since.len(), 1);
        assert_eq!(since[0].message, Some("c3".to_string()));

        // Get commits since c3 should return empty
        let since = repo.get_commits_since("main", Some(&c3.hash)).unwrap();
        assert!(since.is_empty());
    }

    #[test]
    fn test_get_all_commits() {
        let repo = SqliteRepository::in_memory().unwrap();
        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();
        repo.store_branch(&Branch::new("main".to_string(), None, None))
            .unwrap();
        repo.store_branch(&Branch::new(
            "feature".to_string(),
            None,
            Some("main".to_string()),
        ))
        .unwrap();

        let c1 = Commit::new(
            "main".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "a".to_string(),
            Some("main commit".to_string()),
            vec![],
        )
        .unwrap();
        let c2 = Commit::new(
            "feature".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "a".to_string(),
            Some("feature commit".to_string()),
            vec![],
        )
        .unwrap();
        repo.store_commit(&c1).unwrap();
        repo.store_commit(&c2).unwrap();

        let all = repo.get_all_commits().unwrap();
        assert_eq!(all.len(), 2);
    }

    #[test]
    fn test_commit_with_file_changes() {
        let repo = SqliteRepository::in_memory().unwrap();
        let manifest = Manifest::empty();
        repo.store_manifest(&manifest).unwrap();
        let br = Branch::new("main".to_string(), None, None);
        repo.store_branch(&br).unwrap();

        let blob_hash = Hash("abc123".repeat(11)[..64].to_string());
        let commit = Commit::new(
            "main".to_string(),
            None,
            None,
            manifest.hash.clone(),
            "author".to_string(),
            Some("with changes".to_string()),
            vec![
                FileChange {
                    path: "added.txt".to_string(),
                    change_type: ChangeType::Added,
                    old_blob_hash: None,
                    new_blob_hash: Some(blob_hash.clone()),
                    old_path: None,
                    old_mode: None,
                    new_mode: None,
                },
                FileChange {
                    path: "modified.txt".to_string(),
                    change_type: ChangeType::Modified,
                    old_blob_hash: Some(blob_hash.clone()),
                    new_blob_hash: Some(blob_hash.clone()),
                    old_path: None,
                    old_mode: None,
                    new_mode: None,
                },
                FileChange {
                    path: "deleted.txt".to_string(),
                    change_type: ChangeType::Deleted,
                    old_blob_hash: Some(blob_hash.clone()),
                    new_blob_hash: None,
                    old_path: None,
                    old_mode: None,
                    new_mode: None,
                },
            ],
        )
        .unwrap();

        repo.store_commit(&commit).unwrap();
        let retrieved = repo.get_commit(&commit.hash).unwrap().unwrap();

        assert_eq!(retrieved.files.len(), 3);
        assert!(retrieved
            .files
            .iter()
            .any(|f| f.path == "added.txt" && f.change_type == ChangeType::Added));
        assert!(retrieved
            .files
            .iter()
            .any(|f| f.path == "modified.txt" && f.change_type == ChangeType::Modified));
        assert!(retrieved
            .files
            .iter()
            .any(|f| f.path == "deleted.txt" && f.change_type == ChangeType::Deleted));
    }

    // ============================================================
    // Chunk operations
    // ============================================================

    #[test]
    fn test_chunk_roundtrip() {
        let repo = SqliteRepository::in_memory().unwrap();
        let data = b"chunk content here";
        let hash = hash_bytes(data);

        assert!(!repo.has_chunk(&hash).unwrap());
        repo.store_chunk(&hash, data).unwrap();
        assert!(repo.has_chunk(&hash).unwrap());

        let retrieved = repo.get_chunk(&hash).unwrap().unwrap();
        assert_eq!(retrieved, data);
    }

    #[test]
    fn stored_blob_reader_streams_raw_and_compressed_rows() {
        use std::io::Read;
        let dir = tempfile::tempdir().unwrap();
        let repo = SqliteRepository::open(&dir.path().join("oak.db")).unwrap();
        let mut state = 0x9E37_79B9u32;
        let incompressible: Vec<u8> = (0..3 * 1024 * 1024 + 17)
            .map(|_| {
                state ^= state << 13;
                state ^= state >> 17;
                state ^= state << 5;
                (state & 0xFF) as u8
            })
            .collect();
        let compressible = b"oak stored blob reader\n".repeat(200_000);
        for content in [incompressible, compressible, Vec::new()] {
            let hash = repo.put_blob(content.clone()).unwrap();
            let (size, mut reader) = repo.stored_blob_reader(&hash).unwrap().unwrap();
            assert_eq!(size, content.len() as u64);
            let mut read = Vec::new();
            reader.read_to_end(&mut read).unwrap();
            assert!(read == content, "streamed bytes differ for {hash}");
            // Other repository calls interleave with an open reader.
            let (_, mut interleaved) = repo.stored_blob_reader(&hash).unwrap().unwrap();
            let mut first = [0u8; 7];
            let got = interleaved.read(&mut first).unwrap();
            assert_eq!(repo.get_blob_size(&hash).unwrap(), Some(size));
            assert_eq!(&first[..got], &content[..got]);
        }
        assert!(repo
            .stored_blob_reader(&crate::hash_bytes(b"absent"))
            .unwrap()
            .is_none());
    }

    #[test]
    fn test_store_chunk_rejects_hash_mismatch() {
        let repo = SqliteRepository::in_memory().unwrap();
        let claimed = hash_bytes(b"expected");

        let err = repo.store_chunk(&claimed, b"different").unwrap_err();
        assert!(
            matches!(err, OakError::InvalidHash(_)),
            "expected invalid hash error, got {err:?}"
        );
        assert!(!repo.has_chunk(&claimed).unwrap());
    }

    #[test]
    fn test_get_nonexistent_chunk() {
        let repo = SqliteRepository::in_memory().unwrap();
        let result = repo.get_chunk(&Hash("nonexistent".to_string())).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_blob_chunks_mapping() {
        let repo = SqliteRepository::in_memory().unwrap();
        let blob_hash = Hash("blobhash".repeat(8)[..64].to_string());
        let chunk1_data = b"chunk1data";
        let chunk2_data = b"chunk2data";
        let chunk1_hash = hash_bytes(chunk1_data);
        let chunk2_hash = hash_bytes(chunk2_data);

        // Store the actual chunks first (FK constraint)
        repo.store_chunk(&chunk1_hash, chunk1_data).unwrap();
        repo.store_chunk(&chunk2_hash, chunk2_data).unwrap();

        let chunks = vec![
            ChunkInfo {
                hash: chunk1_hash,
                offset: 0,
                length: 1024,
            },
            ChunkInfo {
                hash: chunk2_hash,
                offset: 1024,
                length: 512,
            },
        ];

        // No mapping initially
        assert!(repo.get_blob_chunks(&blob_hash).unwrap().is_none());

        repo.store_blob_chunks(&blob_hash, &chunks).unwrap();

        let retrieved = repo.get_blob_chunks(&blob_hash).unwrap().unwrap();
        assert_eq!(retrieved.len(), 2);
        assert_eq!(retrieved[0].offset, 0);
        assert_eq!(retrieved[0].length, 1024);
        assert_eq!(retrieved[1].offset, 1024);
        assert_eq!(retrieved[1].length, 512);
    }

    // ============================================================
    // Metadata edge cases
    // ============================================================

    #[test]
    fn test_metadata_overwrite() {
        let repo = SqliteRepository::in_memory().unwrap();

        repo.set_metadata(MetadataKey::RemoteUrl, "http://old.example.com")
            .unwrap();
        repo.set_metadata(MetadataKey::RemoteUrl, "http://new.example.com")
            .unwrap();

        let val = repo.get_metadata(MetadataKey::RemoteUrl).unwrap().unwrap();
        assert_eq!(val, "http://new.example.com");
    }

    #[test]
    fn test_metadata_nonexistent_key() {
        let repo = SqliteRepository::in_memory().unwrap();
        let result = repo.get_metadata(MetadataKey::ApiKey).unwrap();
        assert!(result.is_none());
    }

    // ============================================================
    // BulkImporter
    // ============================================================

    #[test]
    fn test_bulk_importer_roundtrip() {
        // Importer needs a file-backed connection — in-memory rejects.
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("oak.db");
        let repo = SqliteRepository::open(&db_path).unwrap();
        let branch = Branch::new("main".to_string(), None, None);
        repo.store_branch(&branch).unwrap();

        let mut importer = repo.bulk_importer(2).unwrap();
        // Two commits, each with the same single-file manifest. Forces the
        // tree cache to short-circuit the second commit's subtree inserts.
        let blob_hash = importer.put_blob(b"hello".to_vec()).unwrap();
        let entries = vec![ManifestEntry {
            path: "a.txt".to_string(),
            blob_hash: blob_hash.clone(),
            mode: FileMode::Regular,
        }];
        let manifest_hash = importer.put_tree(entries.clone()).unwrap();

        let ts = chrono::DateTime::from_timestamp(1_000_000, 0).unwrap();
        let c1 = Commit::with_timestamp(
            "main".to_string(),
            None,
            None,
            manifest_hash.clone(),
            "tester <t@example.com>".to_string(),
            None,
            vec![FileChange {
                path: "a.txt".to_string(),
                change_type: ChangeType::Added,
                old_blob_hash: None,
                new_blob_hash: Some(blob_hash.clone()),
                old_path: None,
                old_mode: None,
                new_mode: None,
            }],
            ts,
        )
        .unwrap();
        importer.store_commit(&c1).unwrap();
        importer.store_commit(&c1).unwrap();
        // Re-using the same entries on commit 2 exercises the in-memory
        // tree cache: build_tree returns the same subtree hashes, which the
        // importer should recognize without re-inserting.
        let manifest_hash2 = importer.put_tree(entries).unwrap();
        assert_eq!(manifest_hash, manifest_hash2);
        let c2 = Commit::with_timestamp(
            "main".to_string(),
            Some(c1.hash.clone()),
            None,
            manifest_hash2,
            "tester <t@example.com>".to_string(),
            None,
            Vec::new(),
            ts,
        )
        .unwrap();
        importer.store_commit(&c2).unwrap();
        importer.finish().unwrap();

        // Both commits durable, blob readable through the normal repo.
        assert!(repo.has_commit(&c1.hash).unwrap());
        assert!(repo.has_commit(&c2.hash).unwrap());
        assert!(repo.has_blob(&blob_hash).unwrap());
        let manifest = repo.get_manifest(&manifest_hash).unwrap().unwrap();
        assert_eq!(manifest.entries.len(), 1);
        assert_eq!(manifest.entries[0].path, "a.txt");
        let commit_file_count: i64 = repo
            .conn
            .lock()
            .unwrap()
            .query_row(
                "SELECT COUNT(*) FROM commit_files WHERE commit_hash = ?1",
                rusqlite::params![c1.hash.as_str()],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(commit_file_count, 1);
    }

    #[test]
    fn test_bulk_importer_drop_rolls_back() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("oak.db");
        let repo = SqliteRepository::open(&db_path).unwrap();

        let commit_hash = {
            let mut importer = repo.bulk_importer(100).unwrap();
            let blob_hash = importer.put_blob(b"ephemeral".to_vec()).unwrap();
            let entries = vec![ManifestEntry {
                path: "x.txt".to_string(),
                blob_hash,
                mode: FileMode::Regular,
            }];
            let manifest_hash = importer.put_tree(entries).unwrap();
            let c = Commit::with_timestamp(
                "main".to_string(),
                None,
                None,
                manifest_hash,
                "tester <t@example.com>".to_string(),
                None,
                Vec::new(),
                chrono::DateTime::from_timestamp(0, 0).unwrap(),
            )
            .unwrap();
            importer.store_commit(&c).unwrap();
            c.hash
            // importer dropped here without finish() → outer tx rolled back.
        };

        // The unflushed commit must not be visible.
        assert!(!repo.has_commit(&commit_hash).unwrap());
    }

    #[test]
    fn test_bulk_txn_commit_persists() {
        // Writes issued inside a bulk transaction are durable after commit —
        // this is the clone/pull ingest path (store_chunk et al. join the
        // open BEGIN rather than auto-committing per statement).
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("oak.db");
        let repo = SqliteRepository::open(&db_path).unwrap();

        let a = hash_bytes(b"aaaa");
        let b = hash_bytes(b"bbbb");
        repo.bulk_begin().unwrap();
        repo.store_chunk(&a, b"aaaa").unwrap();
        repo.store_chunk(&b, b"bbbb").unwrap();
        repo.bulk_commit().unwrap();

        assert!(repo.has_chunk(&a).unwrap());
        assert!(repo.has_chunk(&b).unwrap());
    }

    #[test]
    fn test_bulk_txn_rollback_discards() {
        // bulk_rollback (the BulkTxn guard's drop path) must discard every
        // write made since bulk_begin, so a failed import leaves nothing
        // half-applied.
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("oak.db");
        let repo = SqliteRepository::open(&db_path).unwrap();

        let a = hash_bytes(b"aaaa");
        repo.bulk_begin().unwrap();
        repo.store_chunk(&a, b"aaaa").unwrap();
        repo.bulk_rollback();

        assert!(!repo.has_chunk(&a).unwrap());
        // Connection is usable again afterwards (rollback restored a clean
        // auto-commit state, not a dangling transaction).
        repo.store_chunk(&a, b"aaaa").unwrap();
        assert!(repo.has_chunk(&a).unwrap());
    }

    #[test]
    fn test_bulk_txn_flush_checkpoints_then_rollback() {
        // bulk_flush commits the batch so far and opens the next one. A write
        // before the flush survives; a write after it (with no further
        // commit) is rolled back. This is what bounds WAL growth mid-import
        // without losing already-flushed objects.
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("oak.db");
        let repo = SqliteRepository::open(&db_path).unwrap();

        let before = hash_bytes(b"keep");
        let after = hash_bytes(b"drop");
        repo.bulk_begin().unwrap();
        repo.store_chunk(&before, b"keep").unwrap();
        repo.bulk_flush().unwrap();
        repo.store_chunk(&after, b"drop").unwrap();
        repo.bulk_rollback();

        assert!(repo.has_chunk(&before).unwrap());
        assert!(!repo.has_chunk(&after).unwrap());
    }

    #[test]
    fn test_write_txn_commit_persists() {
        let repo = SqliteRepository::in_memory().unwrap();

        repo.write_txn_begin().unwrap();
        repo.set_metadata(MetadataKey::RemoteUrl, "https://example.com")
            .unwrap();
        repo.write_txn_commit().unwrap();

        assert_eq!(
            repo.get_metadata(MetadataKey::RemoteUrl)
                .unwrap()
                .as_deref(),
            Some("https://example.com")
        );
    }

    #[test]
    fn test_write_txn_rollback_discards() {
        let repo = SqliteRepository::in_memory().unwrap();

        repo.write_txn_begin().unwrap();
        repo.set_metadata(MetadataKey::RemoteUrl, "https://example.com")
            .unwrap();
        repo.write_txn_rollback();

        assert_eq!(repo.get_metadata(MetadataKey::RemoteUrl).unwrap(), None);
        repo.set_metadata(MetadataKey::RemoteUrl, "https://example.com")
            .unwrap();
        assert_eq!(
            repo.get_metadata(MetadataKey::RemoteUrl)
                .unwrap()
                .as_deref(),
            Some("https://example.com")
        );
    }
}

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

    #[test]
    fn sqlite_full_becomes_typed_path_diagnostic() {
        let sqlite = rusqlite::Error::SqliteFailure(
            rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_FULL),
            None,
        );
        let error = sqlite_open_error(Path::new("repo/.oak/oak.db"), sqlite);
        assert!(matches!(error, OakError::DiskFull { path } if path == "repo/.oak/oak.db"));
    }

    #[test]
    fn missing_database_parent_is_not_misreported_as_full() {
        let temp = tempfile::TempDir::new().unwrap();
        let path = temp.path().join("missing/oak.db");
        let error = SqliteRepository::open(&path).err().unwrap();
        assert!(matches!(error, OakError::Database(_)), "{error}");
        assert!(!path.exists());
    }
}