sley-odb 0.2.0

Native-Rust Git object database for the sley engine: loose objects, packfiles, and multi-pack indexes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
// sley#7: untrusted-input parsing crate — fallible ops propagate errors;
// the only retained `expect`s would be documented compile-time invariants.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]

use flate2::Compression;
use flate2::read::ZlibDecoder;
use flate2::write::ZlibEncoder;
use flate2::{Decompress, FlushDecompress};
use sley_core::{GitError, MissingObjectContext, ObjectFormat, ObjectId, Result};
use sley_formats::{Bundle, BundleReference};
use sley_object::{
    Commit, EncodedObject, ObjectType, Tag, TreeEntries, parse_framed_object,
    tree_entry_object_type,
};
use sley_pack::{
    MultiPackIndex, MultiPackIndexOidLookup, PackBitmapIndex, PackBitmapWriter, PackFile,
    PackIndex, PackIndexByteSource, PackIndexEntry, PackIndexViewData, PackInput, PackWrite,
    PackWriteOptions,
};
use std::collections::{HashMap, HashSet};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::{env, fs};

static TEMPFILE_COUNTER: AtomicU64 = AtomicU64::new(0);

pub trait ObjectReader {
    fn read_object(&self, oid: &ObjectId) -> Result<Arc<EncodedObject>>;

    /// Graft-points seam (shallow clones today, replace refs/grafts later):
    /// `true` when history is cut at `oid`, so every walk must treat the
    /// commit as parentless even though its raw body still names parents.
    ///
    /// [`FileObjectDatabase`] answers from `$GIT_DIR/shallow`; readers that
    /// are not backed by a repository (in-memory stores, pack overlays)
    /// keep the default "no grafts".
    fn is_shallow_graft(&self, _oid: &ObjectId) -> bool {
        false
    }

    /// Whether this reader has any shallow/graft boundaries at all. Walkers can
    /// use this to choose dense graph-only traversal when no boundary can cut
    /// parent edges.
    fn has_shallow_grafts(&self) -> bool {
        false
    }

    /// True when `oid` is covered by a promisor pack. Partial clones are
    /// allowed to omit promised objects until a later on-demand fetch hydrates
    /// them; ordinary readers keep the default "no promised objects".
    fn is_promised_object(&self, _oid: &ObjectId) -> bool {
        false
    }
}

fn implied_empty_tree_object(format: ObjectFormat, oid: &ObjectId) -> Option<Arc<EncodedObject>> {
    (*oid == ObjectId::empty_tree(format))
        .then(|| Arc::new(EncodedObject::new(ObjectType::Tree, Vec::new())))
}

fn with_missing_object_context(
    err: GitError,
    oid: ObjectId,
    context: MissingObjectContext,
) -> GitError {
    let kind = err
        .not_found_kind()
        .and_then(sley_core::NotFoundKind::missing_object_kind);
    match kind {
        Some(kind) => GitError::object_kind_not_found_in(oid, kind, context),
        None => err,
    }
}

/// Parents of a parsed commit with the graft seam applied: empty when the
/// reader cuts history at `oid` (shallow boundary), the raw parsed parents
/// otherwise.
pub fn grafted_parents<R: ObjectReader + ?Sized>(
    reader: &R,
    oid: &ObjectId,
    parents: Vec<ObjectId>,
) -> Vec<ObjectId> {
    if reader.is_shallow_graft(oid) {
        Vec::new()
    } else {
        parents
    }
}

pub trait ObjectWriter {
    /// Write `object`, returning its id. Takes `&self`: every implementation's
    /// write state (in-memory map, loose-object cache) is behind interior
    /// mutability, so a single handle can interleave reads and writes without a
    /// `&mut` borrow. This lets the merge engine read and write through one `db`
    /// instead of opening a second read-only handle that re-warms the caches.
    fn write_object(&self, object: EncodedObject) -> Result<ObjectId>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BundleUnbundleResult {
    pub written_objects: Vec<ObjectId>,
    pub references: Vec<BundleReference>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackUnpackResult {
    pub written_objects: Vec<ObjectId>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackInstallResult {
    pub pack_name: String,
    pub pack_path: PathBuf,
    pub index_path: PathBuf,
    pub promisor_path: Option<PathBuf>,
    pub object_ids: Vec<ObjectId>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawPackInstallResult {
    pub object_ids: Vec<ObjectId>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RawPackInstallOptions {
    pub promisor: bool,
}

pub trait RawPackInstaller {
    fn install_raw_pack(&self, pack_bytes: &[u8]) -> Result<RawPackInstallResult>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ObjectPrefixResolution {
    Missing,
    Unique(ObjectId),
    Ambiguous(Vec<ObjectId>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectStorageInfo {
    pub disk_size: u64,
    pub deltabase: ObjectId,
}

impl RawPackInstaller for FileObjectDatabase {
    fn install_raw_pack(&self, pack_bytes: &[u8]) -> Result<RawPackInstallResult> {
        let result = FileObjectDatabase::install_raw_pack(self, pack_bytes)?;
        Ok(RawPackInstallResult {
            object_ids: result.object_ids,
        })
    }
}

impl RawPackInstaller for ObjectDatabase {
    fn install_raw_pack(&self, pack_bytes: &[u8]) -> Result<RawPackInstallResult> {
        let result = unpack_packfile_objects(pack_bytes, self.format, self)?;
        Ok(RawPackInstallResult {
            object_ids: result.written_objects,
        })
    }
}

pub fn verify_bundle_prerequisites<R: ObjectReader>(bundle: &Bundle, reader: &R) -> Result<()> {
    let mut missing = Vec::new();
    for prerequisite in &bundle.prerequisites {
        match reader.read_object(&prerequisite.oid) {
            Ok(object) => {
                let actual = object.object_id(bundle.format)?;
                if actual != prerequisite.oid {
                    return Err(GitError::InvalidObject(format!(
                        "bundle prerequisite {} hashes to {actual}",
                        prerequisite.oid
                    )));
                }
            }
            Err(GitError::NotFound(_)) => missing.push(prerequisite.oid),
            Err(err) => return Err(err),
        }
    }
    if missing.is_empty() {
        return Ok(());
    }
    Err(GitError::object_not_found_in(
        missing[0],
        MissingObjectContext::PackInstall,
    ))
}

pub fn unbundle_objects<R, W>(
    bundle: &Bundle,
    prerequisite_reader: &R,
    writer: &mut W,
) -> Result<BundleUnbundleResult>
where
    R: ObjectReader,
    W: ObjectWriter,
{
    verify_bundle_prerequisites(bundle, prerequisite_reader)?;
    let pack = PackFile::parse_bundle(bundle)?;
    let written_objects = write_pack_objects(pack, writer, "bundle")?.written_objects;
    Ok(BundleUnbundleResult {
        written_objects,
        references: bundle.references.clone(),
    })
}

pub fn install_bundle_pack<R>(
    bundle: &Bundle,
    prerequisite_reader: &R,
    destination: &impl RawPackInstaller,
) -> Result<BundleUnbundleResult>
where
    R: ObjectReader,
{
    verify_bundle_prerequisites(bundle, prerequisite_reader)?;
    let install = destination.install_raw_pack(&bundle.pack)?;
    Ok(BundleUnbundleResult {
        written_objects: install.object_ids,
        references: bundle.references.clone(),
    })
}

pub fn unpack_packfile_objects<W>(
    pack_bytes: &[u8],
    format: ObjectFormat,
    writer: &W,
) -> Result<PackUnpackResult>
where
    W: ObjectWriter,
{
    let pack = PackFile::parse(pack_bytes, format)?;
    write_pack_objects(pack, writer, "pack")
}

fn write_pack_objects<W>(pack: PackFile, writer: &W, source: &str) -> Result<PackUnpackResult>
where
    W: ObjectWriter,
{
    let mut written_objects = Vec::with_capacity(pack.entries.len());
    for entry in pack.entries {
        let expected = entry.entry.oid;
        let actual = writer.write_object(entry.object)?;
        if actual != expected {
            return Err(GitError::InvalidObject(format!(
                "{source} object id mismatch: expected {expected}, wrote {actual}"
            )));
        }
        written_objects.push(actual);
    }
    Ok(PackUnpackResult { written_objects })
}

pub fn collect_reachable_object_ids<R, I>(
    reader: &R,
    format: ObjectFormat,
    starts: I,
) -> Result<HashSet<ObjectId>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
{
    walk_reachable_objects(reader, format, starts, &HashSet::new(), |_, _| {})
}

/// [`collect_reachable_object_ids`] with a cut set: commits in `cut` are
/// collected, but the walk does not continue to their parents — the view a
/// shallow repository has of its own refs (`$GIT_DIR/shallow` of the *other*
/// side, threaded explicitly because `reader` belongs to this side).
pub fn collect_reachable_object_ids_with_cut<R, I>(
    reader: &R,
    format: ObjectFormat,
    starts: I,
    cut: &HashSet<ObjectId>,
) -> Result<HashSet<ObjectId>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
{
    walk_reachable_objects_with_cut(reader, format, starts, &HashSet::new(), cut, |_, _| {})
}

/// [`collect_reachable_object_ids`] with a stop set: objects in `excluded` are
/// not visited and not expanded, so the walk never sees anything reachable only
/// through them (used to truncate history at a shallow boundary).
pub fn collect_reachable_object_ids_excluding<R, I>(
    reader: &R,
    format: ObjectFormat,
    starts: I,
    excluded: &HashSet<ObjectId>,
) -> Result<HashSet<ObjectId>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
{
    walk_reachable_objects(reader, format, starts, excluded, |_, _| {})
}

pub fn collect_reachable_objects<R, I>(
    reader: &R,
    format: ObjectFormat,
    starts: I,
    excluded: &HashSet<ObjectId>,
) -> Result<Vec<Arc<EncodedObject>>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
{
    let mut objects = Vec::new();
    walk_reachable_objects(reader, format, starts, excluded, |_, object| {
        objects.push(Arc::clone(object));
    })?;
    Ok(objects)
}

#[derive(Debug, Clone)]
struct ReachablePackObject {
    oid: ObjectId,
    object: Arc<EncodedObject>,
}

fn collect_reachable_pack_objects<R, I>(
    reader: &R,
    format: ObjectFormat,
    starts: I,
    excluded: &HashSet<ObjectId>,
) -> Result<Vec<ReachablePackObject>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
{
    let mut objects = Vec::new();
    walk_reachable_objects(reader, format, starts, excluded, |oid, object| {
        objects.push(ReachablePackObject {
            oid: *oid,
            object: Arc::clone(object),
        });
    })?;
    Ok(objects)
}

fn pack_inputs(objects: &[ReachablePackObject]) -> Vec<PackInput<'_>> {
    objects
        .iter()
        .map(|entry| PackInput {
            oid: &entry.oid,
            object: &entry.object,
        })
        .collect()
}

pub fn install_reachable_pack<I>(
    source: &impl ObjectReader,
    destination: &impl RawPackInstaller,
    format: ObjectFormat,
    starts: I,
) -> Result<Option<RawPackInstallResult>>
where
    I: IntoIterator<Item = ObjectId>,
{
    install_reachable_pack_excluding(source, destination, format, starts, &HashSet::new())
}

pub fn install_reachable_pack_excluding<I>(
    source: &impl ObjectReader,
    destination: &impl RawPackInstaller,
    format: ObjectFormat,
    starts: I,
    excluded: &HashSet<ObjectId>,
) -> Result<Option<RawPackInstallResult>>
where
    I: IntoIterator<Item = ObjectId>,
{
    let pack = match build_reachable_pack(source, format, starts, excluded)? {
        Some(pack) => pack,
        None => return Ok(None),
    };
    destination.install_raw_pack(&pack.pack).map(Some)
}

pub fn build_reachable_pack<R, I>(
    reader: &R,
    format: ObjectFormat,
    starts: I,
    excluded: &HashSet<ObjectId>,
) -> Result<Option<PackWrite>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
{
    let objects = collect_reachable_pack_objects(reader, format, starts, excluded)?;
    if objects.is_empty() {
        return Ok(None);
    }
    // Delta-compress reachable packs (used by install/push/fetch) via git-pack's
    // sliding-window selection. Self-contained, ofs-delta by default; round-trips
    // through the existing parser. PackWrite shape is unchanged, so callers are
    // unaffected.
    let inputs = pack_inputs(&objects);
    PackFile::write_packed_with_known_ids(&inputs, format).map(Some)
}

pub fn build_and_install_reachable_pack<R, I>(
    source: &R,
    destination: &FileObjectDatabase,
    format: ObjectFormat,
    starts: I,
    excluded: &HashSet<ObjectId>,
    options: RawPackInstallOptions,
) -> Result<Option<PackInstallResult>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
{
    build_and_install_reachable_pack_filtered(
        source,
        destination,
        format,
        starts,
        excluded,
        options,
        None,
        None,
    )
}

/// A partial-clone object filter applied while building a transfer pack.
///
/// Mirrors the subset of upstream's `list-objects-filter` the in-process local
/// server supports: directly-wanted tips are always packed; the filter only
/// prunes objects reached *through* the traversal (upstream's
/// `filter_blobs_none` runs on traversed blobs, never on wanted tips).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PackObjectFilter {
    /// `blob:none`: omit every blob reached through tree traversal.
    BlobNone,
    /// `blob:limit=<n>`: omit traversed blobs whose body is at least `n` bytes.
    BlobLimit(u64),
    /// `tree:<n>`: keep only trees shallower than `n`, and omit traversed blobs.
    TreeDepth(u32),
    /// `sparse:oid=<blob>`: keep only blobs whose repo path is listed.
    SparsePathSet(Vec<String>),
}

/// [`build_and_install_reachable_pack`] with an optional partial-clone
/// `filter`. With `Some(BlobNone)`, blobs are dropped from the pack unless
/// they are directly wanted (named in `starts`).
#[allow(clippy::too_many_arguments)]
pub fn build_and_install_reachable_pack_filtered<R, I>(
    source: &R,
    destination: &FileObjectDatabase,
    format: ObjectFormat,
    starts: I,
    excluded: &HashSet<ObjectId>,
    options: RawPackInstallOptions,
    filter: Option<PackObjectFilter>,
    unpack_limit: Option<usize>,
) -> Result<Option<PackInstallResult>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
{
    let starts: Vec<ObjectId> = starts.into_iter().collect();
    let wanted: HashSet<ObjectId> = starts.iter().copied().collect();
    let mut objects = collect_reachable_pack_objects(source, format, starts, excluded)?;
    match filter {
        Some(PackObjectFilter::BlobNone) => {
            objects.retain(|entry| {
                entry.object.object_type != ObjectType::Blob || wanted.contains(&entry.oid)
            });
        }
        Some(PackObjectFilter::BlobLimit(limit)) => {
            objects.retain(|entry| {
                entry.object.object_type != ObjectType::Blob
                    || wanted.contains(&entry.oid)
                    || (entry.object.body.len() as u64) < limit
            });
        }
        Some(PackObjectFilter::TreeDepth(depth)) => {
            let tree_depths = collect_tree_filter_depths(source, format, &objects)?;
            objects.retain(|entry| {
                if wanted.contains(&entry.oid) {
                    return true;
                }
                match entry.object.object_type {
                    ObjectType::Blob => false,
                    ObjectType::Tree => tree_depths
                        .get(&entry.oid)
                        .is_some_and(|tree_depth| *tree_depth < depth),
                    _ => true,
                }
            });
        }
        Some(PackObjectFilter::SparsePathSet(paths)) => {
            let allowed_blobs = collect_sparse_filter_blobs(source, format, &objects, &paths)?;
            objects.retain(|entry| {
                entry.object.object_type != ObjectType::Blob
                    || wanted.contains(&entry.oid)
                    || allowed_blobs.contains(&entry.oid)
            });
        }
        None => {}
    }
    if objects.is_empty() {
        return Ok(None);
    }
    // Mirror fetch-pack's unpack-limit: small transfers are exploded into
    // loose objects instead of landing as a pack (upstream `get_pack` picks
    // unpack-objects when the header count is below fetch/transfer.unpackLimit).
    if let Some(limit) = unpack_limit
        && objects.len() < limit
    {
        for entry in &objects {
            destination.loose().write_object((*entry.object).clone())?;
        }
        return Ok(None);
    }
    let inputs = pack_inputs(&objects);
    let pack = PackFile::write_packed_with_known_ids(&inputs, format)?;
    trace_packfile(&pack.pack)?;
    destination
        .install_generated_pack_unchecked(&pack, options)
        .map(Some)
}

fn trace_packfile(pack: &[u8]) -> Result<()> {
    let Some(path) = env::var_os("GIT_TRACE_PACKFILE").filter(|value| !value.is_empty()) else {
        return Ok(());
    };
    fs::write(path, pack)?;
    Ok(())
}

fn collect_tree_filter_depths<R>(
    reader: &R,
    format: ObjectFormat,
    objects: &[ReachablePackObject],
) -> Result<HashMap<ObjectId, u32>>
where
    R: ObjectReader,
{
    let available: HashSet<ObjectId> = objects.iter().map(|entry| entry.oid).collect();
    let mut depths = HashMap::new();
    let mut stack = Vec::new();
    for entry in objects {
        if entry.object.object_type != ObjectType::Commit {
            continue;
        }
        let commit = Commit::parse(format, &entry.object.body)?;
        if available.contains(&commit.tree) {
            stack.push((commit.tree, 0u32));
        }
    }
    while let Some((tree_oid, depth)) = stack.pop() {
        if depths
            .get(&tree_oid)
            .is_some_and(|old_depth| *old_depth <= depth)
        {
            continue;
        }
        depths.insert(tree_oid, depth);
        let tree = reader.read_object(&tree_oid)?;
        if tree.object_type != ObjectType::Tree {
            continue;
        }
        let child_depth = depth.saturating_add(1);
        for entry in TreeEntries::new(format, &tree.body) {
            let entry = entry?;
            if tree_entry_object_type(entry.mode) == ObjectType::Tree
                && available.contains(&entry.oid)
            {
                stack.push((entry.oid, child_depth));
            }
        }
    }
    Ok(depths)
}

fn collect_sparse_filter_blobs<R>(
    reader: &R,
    format: ObjectFormat,
    objects: &[ReachablePackObject],
    paths: &[String],
) -> Result<HashSet<ObjectId>>
where
    R: ObjectReader,
{
    let wanted_paths: HashSet<&str> = paths.iter().map(String::as_str).collect();
    let mut allowed = HashSet::new();
    let mut seen_trees = HashSet::new();
    for entry in objects {
        if entry.object.object_type != ObjectType::Commit {
            continue;
        }
        let commit = Commit::parse(format, &entry.object.body)?;
        collect_sparse_tree_blobs(
            reader,
            format,
            &commit.tree,
            "",
            &wanted_paths,
            &mut seen_trees,
            &mut allowed,
        )?;
    }
    Ok(allowed)
}

fn collect_sparse_tree_blobs<R>(
    reader: &R,
    format: ObjectFormat,
    tree_oid: &ObjectId,
    prefix: &str,
    wanted_paths: &HashSet<&str>,
    seen_trees: &mut HashSet<ObjectId>,
    allowed: &mut HashSet<ObjectId>,
) -> Result<()>
where
    R: ObjectReader,
{
    if !seen_trees.insert(*tree_oid) {
        return Ok(());
    }
    let tree = reader.read_object(tree_oid)?;
    if tree.object_type != ObjectType::Tree {
        return Ok(());
    }
    for entry in TreeEntries::new(format, &tree.body) {
        let entry = entry?;
        let name = String::from_utf8_lossy(entry.name);
        let path = if prefix.is_empty() {
            name.into_owned()
        } else {
            format!("{prefix}/{name}")
        };
        if tree_entry_object_type(entry.mode) == ObjectType::Tree {
            collect_sparse_tree_blobs(
                reader,
                format,
                &entry.oid,
                &path,
                wanted_paths,
                seen_trees,
                allowed,
            )?;
        } else if wanted_paths.contains(path.as_str()) {
            allowed.insert(entry.oid);
        }
    }
    Ok(())
}

/// Assemble a pack stream that reuses an existing pack's object data verbatim
/// (upstream pack-objects' "pack reuse" fast path, full-pack case) and appends
/// `appended` as freshly encoded undeltified entries.
///
/// The reused pack's entry bytes are copied as-is between our own header and
/// trailer: a full-pack copy preserves every relative distance, so internal
/// `OFS_DELTA` bases stay valid. The header object count covers both the
/// reused and appended entries, and the trailing pack checksum is recomputed
/// over the assembled stream.
pub fn assemble_pack_with_verbatim_reuse(
    format: ObjectFormat,
    reused_pack_bytes: &[u8],
    appended: &[PackInput<'_>],
) -> Result<(Vec<u8>, u32)> {
    assemble_pack_with_verbatim_reuses(format, &[reused_pack_bytes], appended)
}

/// Like [`assemble_pack_with_verbatim_reuse`], but concatenates multiple whole
/// packs before appending fresh entries.
pub fn assemble_pack_with_verbatim_reuses(
    format: ObjectFormat,
    reused_packs: &[&[u8]],
    appended: &[PackInput<'_>],
) -> Result<(Vec<u8>, u32)> {
    let hash_len = format.raw_len();
    let mut reused_count = 0u32;
    let mut capacity = 12 + hash_len + 64 * appended.len();
    for reused_pack_bytes in reused_packs {
        if reused_pack_bytes.len() < 12 + hash_len {
            return Err(GitError::InvalidFormat("reused pack too short".into()));
        }
        if &reused_pack_bytes[..4] != b"PACK" {
            return Err(GitError::InvalidFormat(
                "reused pack has no signature".into(),
            ));
        }
        let version = u32::from_be_bytes([
            reused_pack_bytes[4],
            reused_pack_bytes[5],
            reused_pack_bytes[6],
            reused_pack_bytes[7],
        ]);
        if version != 2 {
            return Err(GitError::Unsupported(format!(
                "reused pack version {version}"
            )));
        }
        let count = u32::from_be_bytes([
            reused_pack_bytes[8],
            reused_pack_bytes[9],
            reused_pack_bytes[10],
            reused_pack_bytes[11],
        ]);
        reused_count = reused_count
            .checked_add(count)
            .ok_or_else(|| GitError::InvalidFormat("too many pack objects".into()))?;
        capacity = capacity.saturating_add(reused_pack_bytes.len().saturating_sub(12 + hash_len));
    }
    let total = reused_count
        .checked_add(appended.len() as u32)
        .ok_or_else(|| GitError::InvalidFormat("too many pack objects".into()))?;

    let mut out = Vec::with_capacity(capacity);
    out.extend_from_slice(b"PACK");
    out.extend_from_slice(&2u32.to_be_bytes());
    out.extend_from_slice(&total.to_be_bytes());
    for reused_pack_bytes in reused_packs {
        out.extend_from_slice(&reused_pack_bytes[12..reused_pack_bytes.len() - hash_len]);
    }
    for input in appended {
        write_undeltified_pack_entry(&mut out, input.object)?;
    }
    let checksum = sley_core::digest_bytes(format, &out)?;
    out.extend_from_slice(checksum.as_bytes());
    Ok((out, reused_count))
}

/// Assemble a pack stream by copying already-encoded pack entries verbatim and
/// appending freshly encoded undeltified entries.
pub fn assemble_pack_with_verbatim_entries(
    format: ObjectFormat,
    reused_entries: &[&[u8]],
    appended: &[PackInput<'_>],
) -> Result<(Vec<u8>, u32)> {
    let reused_count = u32::try_from(reused_entries.len())
        .map_err(|_| GitError::InvalidFormat("too many pack objects".into()))?;
    let total = reused_count
        .checked_add(appended.len() as u32)
        .ok_or_else(|| GitError::InvalidFormat("too many pack objects".into()))?;

    let mut capacity = 12 + format.raw_len() + 64 * appended.len();
    for entry in reused_entries {
        capacity = capacity.saturating_add(entry.len());
    }
    let mut out = Vec::with_capacity(capacity);
    out.extend_from_slice(b"PACK");
    out.extend_from_slice(&2u32.to_be_bytes());
    out.extend_from_slice(&total.to_be_bytes());
    for entry in reused_entries {
        out.extend_from_slice(entry);
    }
    for input in appended {
        write_undeltified_pack_entry(&mut out, input.object)?;
    }
    let checksum = sley_core::digest_bytes(format, &out)?;
    out.extend_from_slice(checksum.as_bytes());
    Ok((out, reused_count))
}

/// Append one undeltified pack entry (type/size varint header + zlib body).
fn write_undeltified_pack_entry(out: &mut Vec<u8>, object: &EncodedObject) -> Result<()> {
    let type_bits: u8 = match object.object_type {
        ObjectType::Commit => 1,
        ObjectType::Tree => 2,
        ObjectType::Blob => 3,
        ObjectType::Tag => 4,
    };
    let mut size = object.body.len() as u64;
    let mut byte = (type_bits << 4) | (size & 0x0f) as u8;
    size >>= 4;
    while size > 0 {
        out.push(byte | 0x80);
        byte = (size & 0x7f) as u8;
        size >>= 7;
    }
    out.push(byte);
    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
    encoder.write_all(&object.body)?;
    out.extend_from_slice(&encoder.finish()?);
    Ok(())
}

/// Outcome of consolidating every object in a repository into a single pack.
///
/// This is the engine for `git gc` / `git repack`: [`repack_all_objects`]
/// produces the bytes for one new delta-compressed pack plus its index, and
/// reports which on-disk artifacts the caller could now remove. No deletions
/// are performed by the engine itself; the CLI decides reachability policy and
/// performs any pruning (see [`install_repack_result`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepackResult {
    /// Bytes of the freshly written `.pack` file.
    pub pack: Vec<u8>,
    /// Bytes of the matching `.idx` file for [`RepackResult::pack`].
    pub idx: Vec<u8>,
    /// Number of distinct objects contained in the new pack.
    pub object_count: usize,
    /// Absolute paths of pre-existing `*.pack` files now superseded by the new
    /// pack (every object they hold is present in [`RepackResult::pack`]).
    pub obsolete_packs: Vec<PathBuf>,
    /// Loose object ids that are now also present in the new pack and therefore
    /// redundant on disk.
    pub packed_loose: Vec<ObjectId>,
    /// Pack stems (`pack-<checksum>`) that policy says must survive pruning
    /// even if the new pack contains all of their objects.
    retained_pack_stems: Vec<String>,
    pack_checksum: ObjectId,
    index_entries: Vec<PackIndexEntry>,
}

#[derive(Debug, Clone, Default)]
pub struct RepackOptions {
    /// Do not borrow objects from alternates (`git repack --local`).
    pub local: bool,
    /// Repack objects that are already in `.keep` / `--keep-pack` packs.
    pub pack_kept_objects: bool,
    /// Explicit `--keep-pack=<name>` pack stems (`pack-<checksum>`).
    pub keep_pack_stems: HashSet<String>,
}

/// Gather every object in `git_dir` (loose objects and every existing pack) and
/// write them into a single new delta-compressed pack.
///
/// Returns the new pack/index bytes, the count of packed objects, the list of
/// pre-existing pack files that the new pack supersedes, and the loose object
/// ids that are now packed. Nothing is deleted: the caller (CLI) decides
/// reachability policy and performs any pruning, optionally via
/// [`install_repack_result`].
///
/// Returns `Ok(None)` when the repository contains no objects at all.
/// `git repack -a`'s gathering rule: pack the reachability closure of `roots`
/// (ref tips, `HEAD`, reflog entries, indexed objects) instead of everything
/// on disk. Borrowed objects (alternates) reachable from the roots are packed
/// into the new local pack like upstream `pack-objects --all` without
/// `--local`; previously-packed objects that are no longer reachable are NOT
/// carried forward (that is how `repack -a -d` drops them). Missing objects
/// are tolerated (stale reflog entries may reference pruned history).
///
/// Returns `Ok(None)` when no roots resolve to any object.
pub fn repack_reachable_objects(
    git_dir: &Path,
    format: ObjectFormat,
    roots: &[ObjectId],
) -> Result<Option<RepackResult>> {
    repack_reachable_objects_with_options(git_dir, format, roots, &RepackOptions::default())
}

pub fn repack_reachable_objects_with_options(
    git_dir: &Path,
    format: ObjectFormat,
    roots: &[ObjectId],
    options: &RepackOptions,
) -> Result<Option<RepackResult>> {
    let objects_dir = repository_objects_dir(git_dir);
    let database = if options.local {
        FileObjectDatabase::without_alternates(objects_dir.clone(), format)
    } else {
        FileObjectDatabase::new(objects_dir.clone(), format)
    };
    let retained_pack_stems = repack_retained_pack_stems(
        &objects_dir.join("pack"),
        &options.keep_pack_stems,
        !options.pack_kept_objects,
    )?;
    let excluded_oids = if options.pack_kept_objects {
        HashSet::new()
    } else {
        pack_oids_for_stems(&objects_dir.join("pack"), format, &retained_pack_stems)?
    };

    let mut seen: HashSet<ObjectId> = HashSet::new();
    let mut objects: Vec<ReachablePackObject> = Vec::new();
    let mut pending: Vec<ObjectId> = roots.to_vec();
    while let Some(oid) = pending.pop() {
        if !seen.insert(oid) {
            continue;
        }
        let object = match database.read_object(&oid) {
            Ok(object) => object,
            Err(GitError::NotFound(_)) => continue,
            Err(err) => return Err(err),
        };
        match object.object_type {
            ObjectType::Commit => {
                let commit = Commit::parse_ref(format, &object.body)?;
                pending.extend(grafted_parents(&database, &oid, commit.parents));
                pending.push(commit.tree);
            }
            ObjectType::Tree => {
                for entry in TreeEntries::new(format, &object.body) {
                    let entry = entry?;
                    if !entry.is_gitlink() {
                        pending.push(entry.oid);
                    }
                }
            }
            ObjectType::Tag => {
                let tag = Tag::parse_ref(format, &object.body)?;
                pending.push(tag.object);
            }
            ObjectType::Blob => {}
        }
        if !excluded_oids.contains(&oid) {
            objects.push(ReachablePackObject { oid, object });
        }
    }

    // Non-local repacks borrow packed objects from alternates as complete pack
    // sources, while still leaving loose-only alternate objects alone. This
    // matches `pack-objects --all` without `--local`: packed alternate objects
    // are copied into the local consolidated pack, but a loose object in an
    // alternate ODB is not duplicated just because a local tree points at it.
    if !options.local {
        for (alternate, oid) in alternate_packed_object_ids(&objects_dir, format)? {
            if excluded_oids.contains(&oid) || !seen.insert(oid) {
                continue;
            }
            let alternate_db = FileObjectDatabase::without_alternates(alternate, format);
            match alternate_db.read_object(&oid) {
                Ok(object) => objects.push(ReachablePackObject { oid, object }),
                Err(GitError::NotFound(_)) => {}
                Err(err) => return Err(err),
            }
        }
    }

    if objects.is_empty() {
        return Ok(None);
    }

    let inputs = pack_inputs(&objects);
    let written = PackFile::write_packed_with_known_ids(&inputs, format)?;
    let object_count = written.entries.len();

    // Every pre-existing local pack is superseded under `-a` (their reachable
    // objects are in the new pack; their unreachable ones are being dropped).
    let new_pack_file_name = format!("pack-{}.pack", written.checksum.to_hex());
    let obsolete_packs = existing_pack_files(&objects_dir.join("pack"))?
        .into_iter()
        .filter(|path| path.file_name().and_then(|name| name.to_str()) != Some(&new_pack_file_name))
        .collect();

    let packed_oid_set: HashSet<&ObjectId> = written.entries.iter().map(|e| &e.oid).collect();
    let mut packed_loose: Vec<ObjectId> = loose_object_ids(&objects_dir, format)?
        .into_iter()
        .filter(|oid| packed_oid_set.contains(oid))
        .collect();
    packed_loose.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));

    let pack_checksum = written.checksum;
    let index_entries = written.entries.clone();
    Ok(Some(RepackResult {
        pack: written.pack,
        idx: written.index,
        object_count,
        obsolete_packs,
        packed_loose,
        retained_pack_stems,
        pack_checksum,
        index_entries,
    }))
}

fn repack_retained_pack_stems(
    pack_dir: &Path,
    explicit: &HashSet<String>,
    keep_dot_keep: bool,
) -> Result<Vec<String>> {
    let mut stems = explicit.clone();
    if keep_dot_keep {
        for pack_path in existing_pack_files(pack_dir)? {
            if pack_path.with_extension("keep").exists()
                && let Some(stem) = pack_path.file_stem().and_then(|s| s.to_str())
            {
                stems.insert(stem.to_string());
            }
        }
    }
    let mut stems = stems.into_iter().collect::<Vec<_>>();
    stems.sort();
    Ok(stems)
}

fn pack_oids_for_stems(
    pack_dir: &Path,
    format: ObjectFormat,
    stems: &[String],
) -> Result<HashSet<ObjectId>> {
    let wanted: HashSet<&str> = stems.iter().map(String::as_str).collect();
    if wanted.is_empty() {
        return Ok(HashSet::new());
    }
    let mut oids = HashSet::new();
    for pack_path in existing_pack_files(pack_dir)? {
        let Some(stem) = pack_path.file_stem().and_then(|s| s.to_str()) else {
            continue;
        };
        if !wanted.contains(stem) {
            continue;
        }
        let index_path = pack_path.with_extension("idx");
        if !index_path.exists() {
            continue;
        }
        let index = PackIndex::parse(&fs::read(index_path)?, format)?;
        oids.extend(index.entries.into_iter().map(|entry| entry.oid));
    }
    Ok(oids)
}

fn alternate_packed_object_ids(
    objects_dir: &Path,
    format: ObjectFormat,
) -> Result<Vec<(PathBuf, ObjectId)>> {
    let mut oids = Vec::new();
    for alternate in alternate_object_dirs(objects_dir) {
        let mut alternate_oids = HashSet::new();
        collect_packed_object_ids(&alternate.join("pack"), format, &mut alternate_oids)?;
        oids.extend(
            alternate_oids
                .into_iter()
                .map(|oid| (alternate.clone(), oid)),
        );
    }
    oids.sort_by(|left, right| {
        left.0
            .cmp(&right.0)
            .then(left.1.as_bytes().cmp(right.1.as_bytes()))
    });
    Ok(oids)
}

pub fn repack_all_objects(git_dir: &Path, format: ObjectFormat) -> Result<Option<RepackResult>> {
    let objects_dir = repository_objects_dir(git_dir);
    let database = FileObjectDatabase::new(objects_dir.clone(), format);

    // Enumerate every object id reachable on disk: loose objects, every pack
    // index, and any multi-pack-index. `object_ids_in_objects_dir` already
    // unions all of these and de-duplicates them.
    let all_oids = object_ids_in_objects_dir(&objects_dir, format)?;
    if all_oids.is_empty() {
        return Ok(None);
    }

    // Read each object's canonical encoding so the new pack stores byte-for-byte
    // identical payloads. Loose objects take precedence over packed copies in
    // `FileObjectDatabase::read_object`, but both decode to the same bytes.
    let mut objects = Vec::with_capacity(all_oids.len());
    for oid in &all_oids {
        objects.push(ReachablePackObject {
            oid: *oid,
            object: database.read_object(oid)?,
        });
    }

    let inputs = pack_inputs(&objects);
    let written = PackFile::write_packed_with_known_ids(&inputs, format)?;
    let object_count = written.entries.len();

    // The new pack contains every object on disk, so every pre-existing pack is
    // fully superseded. We still record the exact pack paths (not the index
    // paths) so the caller can delete the right files. The pack we are about to
    // write is excluded by name in case its checksum collides with an existing
    // pack (identical contents).
    let new_pack_file_name = format!("pack-{}.pack", written.checksum.to_hex());
    let obsolete_packs = existing_pack_files(&objects_dir.join("pack"))?
        .into_iter()
        .filter(|path| path.file_name().and_then(|name| name.to_str()) != Some(&new_pack_file_name))
        .collect();

    // Loose object ids that the new pack now also holds (which is all of them,
    // since they were gathered into it).
    let packed_oid_set: HashSet<&ObjectId> = written.entries.iter().map(|e| &e.oid).collect();
    let mut packed_loose: Vec<ObjectId> = loose_object_ids(&objects_dir, format)?
        .into_iter()
        .filter(|oid| packed_oid_set.contains(oid))
        .collect();
    packed_loose.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));

    Ok(Some(RepackResult {
        pack: written.pack,
        idx: written.index,
        object_count,
        obsolete_packs,
        packed_loose,
        retained_pack_stems: Vec::new(),
        pack_checksum: written.checksum,
        index_entries: written.entries,
    }))
}

/// Gather only loose objects in `git_dir` and write them into a new pack.
///
/// This is the engine for plain `git repack -d` (without `-a`): existing packs
/// remain in place, and pruning removes only the loose copies that the new pack
/// now serves.
pub fn repack_loose_objects(git_dir: &Path, format: ObjectFormat) -> Result<Option<RepackResult>> {
    let objects_dir = repository_objects_dir(git_dir);
    let database = FileObjectDatabase::new(objects_dir.clone(), format);
    let loose_oids = loose_object_ids(&objects_dir, format)?;
    if loose_oids.is_empty() {
        return Ok(None);
    }

    let mut objects = Vec::with_capacity(loose_oids.len());
    for oid in &loose_oids {
        objects.push(ReachablePackObject {
            oid: *oid,
            object: database.read_object(oid)?,
        });
    }

    let inputs = pack_inputs(&objects);
    let written = PackFile::write_packed_with_known_ids(&inputs, format)?;
    let object_count = written.entries.len();
    let packed_oid_set: HashSet<&ObjectId> = written.entries.iter().map(|e| &e.oid).collect();
    let mut packed_loose: Vec<ObjectId> = loose_oids
        .into_iter()
        .filter(|oid| packed_oid_set.contains(oid))
        .collect();
    packed_loose.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));

    let pack_checksum = written.checksum;
    let index_entries = written.entries.clone();
    Ok(Some(RepackResult {
        pack: written.pack,
        idx: written.index,
        object_count,
        obsolete_packs: Vec::new(),
        packed_loose,
        retained_pack_stems: Vec::new(),
        pack_checksum,
        index_entries,
    }))
}

/// A local, non-kept, non-cruft pack considered for a geometric rollup,
/// paired with the object count that orders it in the progression.
#[derive(Debug, Clone)]
struct GeometryPack {
    /// Absolute path to the `.pack` file.
    pack_path: PathBuf,
    /// Object ids the pack holds (from its `.idx`).
    oids: Vec<ObjectId>,
    /// `num_objects` weight used to order the progression.
    weight: u64,
    /// True when this pack is a promisor pack (`.promisor` sidecar).
    is_promisor: bool,
}

/// The outcome of a geometric rollup: the new pack (if one was written) plus
/// the rolled-up packs whose objects it now serves.
#[derive(Debug, Clone)]
pub struct GeometricRepackResult {
    /// `Some` when a new pack was written; `None` when nothing needed packing.
    pub result: Option<RepackResult>,
    /// Pack `.pack` paths below the split that may now be removed under `-d`.
    pub rolled_up_packs: Vec<PathBuf>,
}

/// Collect the local non-cruft, non-kept packs eligible for geometric rollup,
/// keyed by promisor-ness, ordered ascending by object count.
fn collect_geometry_packs(
    objects_dir: &Path,
    format: ObjectFormat,
    kept_pack_stems: &HashSet<String>,
) -> Result<Vec<GeometryPack>> {
    let pack_dir = objects_dir.join("pack");
    let mut packs = Vec::new();
    for pack_path in existing_pack_files(&pack_dir)? {
        // Cruft packs (`.mtimes` sidecar) and kept packs are excluded from the
        // progression, matching `pack_geometry_init` in repack-geometry.c.
        if pack_path.with_extension("mtimes").exists() {
            continue;
        }
        if pack_path.with_extension("keep").exists() {
            continue;
        }
        let Some(stem) = pack_path.file_stem().and_then(|s| s.to_str()) else {
            continue;
        };
        if kept_pack_stems.contains(stem) {
            continue;
        }
        let index_path = pack_path.with_extension("idx");
        if !index_path.exists() {
            continue;
        }
        let index = PackIndex::parse(&fs::read(&index_path)?, format)?;
        let oids: Vec<ObjectId> = index.entries.iter().map(|entry| entry.oid).collect();
        let weight = oids.len() as u64;
        packs.push(GeometryPack {
            is_promisor: pack_path.with_extension("promisor").exists(),
            pack_path,
            oids,
            weight,
        });
    }
    // Ascending by weight; pack_path breaks ties deterministically.
    packs.sort_by(|a, b| a.weight.cmp(&b.weight).then(a.pack_path.cmp(&b.pack_path)));
    Ok(packs)
}

/// Port of `compute_pack_geometry_split` (repack-geometry.c): given packs in
/// ascending weight order, return the split index — packs `[0..split)` roll up
/// into one new pack, packs `[split..)` are left alone.
fn compute_geometry_split(packs: &[GeometryPack], split_factor: u64) -> usize {
    let pack_nr = packs.len();
    if pack_nr == 0 {
        return 0;
    }
    // Count packs (descending size) that already form a geometric progression.
    let mut i = pack_nr - 1;
    while i > 0 {
        let ours = packs[i].weight;
        let prev = packs[i - 1].weight;
        if ours < split_factor.saturating_mul(prev) {
            break;
        }
        i -= 1;
    }
    let mut split = i;
    if split != 0 {
        // The top of the last-compared pair can't be in the progression.
        split += 1;
    }

    // Roll up everything below `split`; pulling those into a new pack may break
    // the progression in the heavy half, so absorb heavy-half packs until it
    // holds again.
    let mut total_size: u64 = packs[..split].iter().map(|p| p.weight).sum();
    for pack in &packs[split..] {
        if pack.weight < split_factor.saturating_mul(total_size) {
            split += 1;
            total_size = total_size.saturating_add(pack.weight);
        } else {
            break;
        }
    }
    split
}

/// `git repack --geometric=<factor>`: roll up the smallest packs (plus loose
/// unpacked objects) so the surviving packs form a geometric progression by
/// object count. Objects in the rolled-up packs and loose objects are gathered
/// into one new pack; packs at/above the split are left in place. The new pack
/// excludes objects already served by a left-alone pack.
///
/// Returns the new pack plus the rolled-up pack paths the caller may delete
/// under `-d`. Returns an all-`None`/empty result when nothing needs packing
/// ("Nothing new to pack").
pub fn repack_geometric(
    git_dir: &Path,
    format: ObjectFormat,
    split_factor: u64,
    kept_pack_stems: &HashSet<String>,
) -> Result<GeometricRepackResult> {
    let objects_dir = repository_objects_dir(git_dir);
    let database = FileObjectDatabase::new(objects_dir.clone(), format);

    // Promisor packs follow their own progression; the non-promisor packs are
    // the common case the test-suite exercises. Build the rollup from the
    // non-promisor packs plus loose objects.
    let all_packs = collect_geometry_packs(&objects_dir, format, kept_pack_stems)?;
    let packs: Vec<GeometryPack> = all_packs
        .into_iter()
        .filter(|pack| !pack.is_promisor)
        .collect();

    let split = compute_geometry_split(&packs, split_factor);

    let loose_oids = loose_object_ids(&objects_dir, format)?;

    // The objects that end up in the new pack: every object in a rolled-up pack,
    // plus every loose object — but NOT objects already served by a pack left in
    // place (those above the split). This mirrors the `^pack` exclusion markers
    // that repack.c feeds to `pack-objects --stdin-packs`.
    let mut excluded_oids: HashSet<ObjectId> = HashSet::new();
    for pack in &packs[split..] {
        excluded_oids.extend(pack.oids.iter().copied());
    }

    let mut included: Vec<ObjectId> = Vec::new();
    let mut seen: HashSet<ObjectId> = HashSet::new();
    for pack in &packs[..split] {
        for oid in &pack.oids {
            if excluded_oids.contains(oid) {
                continue;
            }
            if seen.insert(*oid) {
                included.push(*oid);
            }
        }
    }
    for oid in &loose_oids {
        if excluded_oids.contains(oid) {
            continue;
        }
        if seen.insert(*oid) {
            included.push(*oid);
        }
    }

    // "Nothing new to pack": no packs roll up and no loose objects need packing.
    if included.is_empty() {
        return Ok(GeometricRepackResult {
            result: None,
            rolled_up_packs: Vec::new(),
        });
    }

    included.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
    let mut objects = Vec::with_capacity(included.len());
    for oid in &included {
        objects.push(ReachablePackObject {
            oid: *oid,
            object: database.read_object(oid)?,
        });
    }

    let inputs = pack_inputs(&objects);
    let written = PackFile::write_packed_with_known_ids(&inputs, format)?;
    let object_count = written.entries.len();

    let packed_oid_set: HashSet<&ObjectId> = written.entries.iter().map(|e| &e.oid).collect();
    let mut packed_loose: Vec<ObjectId> = loose_oids
        .into_iter()
        .filter(|oid| packed_oid_set.contains(oid))
        .collect();
    packed_loose.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));

    let rolled_up_packs: Vec<PathBuf> = packs[..split]
        .iter()
        .map(|pack| pack.pack_path.clone())
        .collect();

    let pack_checksum = written.checksum;
    let index_entries = written.entries.clone();
    Ok(GeometricRepackResult {
        result: Some(RepackResult {
            pack: written.pack,
            idx: written.index,
            object_count,
            obsolete_packs: rolled_up_packs.clone(),
            packed_loose,
            retained_pack_stems: Vec::new(),
            pack_checksum,
            index_entries,
        }),
        rolled_up_packs,
    })
}

/// Write the consolidated pack from a [`RepackResult`] into
/// `objects/pack/` and, when `prune` is set, remove the now-redundant
/// pre-existing packs and packed loose objects.
///
/// Pruning is opt-in and deliberately conservative: an object or pack is only
/// removed after verifying it is actually present in the freshly written pack
/// on disk. Concretely:
///
/// * a loose object is removed only if its id appears in the new pack;
/// * a pre-existing pack is removed only if it is not the pack we just wrote
///   *and* every object listed in its `.idx` is present in the new pack (its
///   `.idx` and known sidecars are removed alongside it);
/// * a stale `multi-pack-index` is removed only if every pack it references is
///   being removed, so no reader is ever left pointing at a deleted pack.
pub fn install_repack_result(
    git_dir: &Path,
    format: ObjectFormat,
    result: &RepackResult,
    prune: bool,
) -> Result<()> {
    install_repack_result_with_bitmap(git_dir, format, result, prune, None)
}

/// [`install_repack_result`] that additionally writes a `pack-<checksum>.bitmap`
/// reachability bitmap alongside the new pack when `bitmap_tips` is `Some`.
/// `bitmap_tips` carries the repository's ref tips (peeled to commits): they
/// receive selection preference, mirroring upstream's `NEEDS_BITMAP` flagging of
/// ref tips in `git repack -b` / `pack-objects --write-bitmap-index`.
pub fn install_repack_result_with_bitmap(
    git_dir: &Path,
    format: ObjectFormat,
    result: &RepackResult,
    prune: bool,
    bitmap_tips: Option<&HashSet<ObjectId>>,
) -> Result<()> {
    let objects_dir = repository_objects_dir(git_dir);
    let pack_dir = objects_dir.join("pack");
    fs::create_dir_all(&pack_dir)?;

    // Validate the public bytes against the private provenance that
    // `repack_all_objects` captured from `PackFile::write_packed`. This avoids
    // inflating and resolving the freshly-written pack a second time while still
    // catching caller mutations before anything is written or pruned.
    validate_pack_checksum(&result.pack, format, &result.pack_checksum, "repack")?;
    let parsed_index = PackIndex::parse(&result.idx, format)?;
    if parsed_index.pack_checksum != result.pack_checksum {
        return Err(GitError::InvalidFormat(
            "repack index checksum does not match the new pack".into(),
        ));
    }
    if !pack_index_entries_match_writer(&parsed_index.entries, &result.index_entries) {
        return Err(GitError::InvalidFormat(
            "repack index does not match the new pack contents".into(),
        ));
    }
    let pack_name = format!("pack-{}", result.pack_checksum.to_hex());
    let new_pack_path = pack_dir.join(format!("{pack_name}.pack"));
    let new_rev_path = pack_dir.join(format!("{pack_name}.rev"));
    let new_index_path = pack_dir.join(format!("{pack_name}.idx"));
    // git writes a `.rev` alongside every repacked pack (`pack.writeReverseIndex`
    // defaults to true). Write it before the `.idx` so the index never becomes
    // visible ahead of its companions, mirroring upstream's finalize order.
    let reverse_index = sley_pack::PackReverseIndex::write(
        format,
        &sley_pack::pack_order_index_positions(&parsed_index.entries),
        &result.pack_checksum,
    )?;
    write_pack_component(&new_pack_path, &result.pack)?;
    write_pack_component(&new_rev_path, &reverse_index)?;
    write_pack_component(&new_index_path, &result.idx)?;

    if let Some(tips) = bitmap_tips {
        // Build before pruning: the closure walk reads objects through the
        // pre-existing packs/loose store (the new pack holds the same bytes).
        let database = FileObjectDatabase::new(objects_dir.clone(), format);
        if let Some(bitmap) = build_pack_bitmap(
            &database,
            format,
            &result.index_entries,
            &result.pack_checksum,
            tips,
        )? {
            // Unlike the pack/idx/rev (content-addressed by the pack
            // checksum), the bitmap depends on selection inputs (e.g.
            // pack.preferBitmapTips), so an existing file must be replaced —
            // write_pack_component's exists-skip would keep a stale selection.
            let bitmap_path = pack_dir.join(format!("{pack_name}.bitmap"));
            remove_file_if_exists(&bitmap_path)?;
            write_pack_component(&bitmap_path, &bitmap)?;
        }
    }

    if !prune {
        return Ok(());
    }

    // Prune based on the objects the new pack's *index* can resolve (what reads use
    // once the old packs are gone), not just what the pack contains — so a stale
    // pack is never removed for an object the new index cannot serve.
    let present: HashSet<ObjectId> = parsed_index.entries.iter().map(|entry| entry.oid).collect();

    prune_obsolete_pack_paths(
        &objects_dir,
        format,
        &result.obsolete_packs,
        &new_pack_path,
        &result.retained_pack_stems,
    )?;
    prune_loose_objects(&objects_dir, format, result.packed_loose.iter(), &present)?;
    Ok(())
}

/// Install a [`repack_geometric`] result: write the new pack, then under `prune`
/// remove EXACTLY the rolled-up packs (those below the geometric split) plus the
/// loose objects now packed. Unlike [`install_repack_result`], packs left in
/// place above the split are never removed even though some of their objects may
/// also live in the new pack.
pub fn install_geometric_repack_result(
    git_dir: &Path,
    format: ObjectFormat,
    geometric: &GeometricRepackResult,
    prune: bool,
    bitmap_tips: Option<&HashSet<ObjectId>>,
) -> Result<()> {
    let Some(result) = geometric.result.as_ref() else {
        return Ok(());
    };
    let objects_dir = repository_objects_dir(git_dir);
    let pack_dir = objects_dir.join("pack");
    fs::create_dir_all(&pack_dir)?;

    validate_pack_checksum(&result.pack, format, &result.pack_checksum, "repack")?;
    let parsed_index = PackIndex::parse(&result.idx, format)?;
    if parsed_index.pack_checksum != result.pack_checksum {
        return Err(GitError::InvalidFormat(
            "repack index checksum does not match the new pack".into(),
        ));
    }
    if !pack_index_entries_match_writer(&parsed_index.entries, &result.index_entries) {
        return Err(GitError::InvalidFormat(
            "repack index does not match the new pack contents".into(),
        ));
    }
    let pack_name = format!("pack-{}", result.pack_checksum.to_hex());
    let new_pack_path = pack_dir.join(format!("{pack_name}.pack"));
    let new_rev_path = pack_dir.join(format!("{pack_name}.rev"));
    let new_index_path = pack_dir.join(format!("{pack_name}.idx"));
    let reverse_index = sley_pack::PackReverseIndex::write(
        format,
        &sley_pack::pack_order_index_positions(&parsed_index.entries),
        &result.pack_checksum,
    )?;
    write_pack_component(&new_pack_path, &result.pack)?;
    write_pack_component(&new_rev_path, &reverse_index)?;
    write_pack_component(&new_index_path, &result.idx)?;

    if let Some(tips) = bitmap_tips {
        let database = FileObjectDatabase::new(objects_dir.clone(), format);
        if let Some(bitmap) = build_pack_bitmap(
            &database,
            format,
            &result.index_entries,
            &result.pack_checksum,
            tips,
        )? {
            let bitmap_path = pack_dir.join(format!("{pack_name}.bitmap"));
            remove_file_if_exists(&bitmap_path)?;
            write_pack_component(&bitmap_path, &bitmap)?;
        }
    }

    if !prune {
        return Ok(());
    }

    // Remove exactly the rolled-up packs (below the split). Never touch packs
    // left in place above the split.
    for pack_path in &geometric.rolled_up_packs {
        if *pack_path == new_pack_path {
            continue;
        }
        if pack_path.with_extension("keep").exists() {
            continue;
        }
        remove_file_if_exists(pack_path)?;
        remove_file_if_exists(&pack_path.with_extension("idx"))?;
        for ext in ["rev", "mtimes", "bitmap", "promisor"] {
            remove_file_if_exists(&pack_path.with_extension(ext))?;
        }
    }

    // Drop loose copies now served by the new pack.
    let present: HashSet<ObjectId> = parsed_index.entries.iter().map(|entry| entry.oid).collect();
    prune_loose_objects(&objects_dir, format, result.packed_loose.iter(), &present)?;

    // A multi-pack-index that references any removed pack is now stale.
    let removed_stems: HashSet<String> = geometric
        .rolled_up_packs
        .iter()
        .filter_map(|p| p.file_stem().map(|s| s.to_string_lossy().into_owned()))
        .collect();
    prune_stale_multi_pack_index(&pack_dir, format, &removed_stems)?;
    Ok(())
}

fn validate_pack_checksum(
    pack: &[u8],
    format: ObjectFormat,
    expected: &ObjectId,
    context: &str,
) -> Result<()> {
    if expected.format() != format {
        return Err(GitError::InvalidObjectId(format!(
            "{context} checksum format does not match object format"
        )));
    }
    let hash_len = format.raw_len();
    if pack.len() < 12 + hash_len {
        return Err(GitError::InvalidFormat(format!(
            "{context} pack file too short"
        )));
    }
    if &pack[..4] != b"PACK" {
        return Err(GitError::InvalidFormat(format!(
            "{context} pack file missing PACK signature"
        )));
    }
    let trailer_offset = pack.len() - hash_len;
    let actual = sley_core::digest_bytes(format, &pack[..trailer_offset])?;
    let trailer = ObjectId::from_raw(format, &pack[trailer_offset..])?;
    if &actual != expected || trailer != *expected {
        return Err(GitError::InvalidFormat(format!(
            "{context} pack checksum does not match generated pack"
        )));
    }
    Ok(())
}

/// The UNIX-seconds mtime of a path, or `0` when unavailable.
fn path_mtime_secs(path: &Path) -> u32 {
    fs::metadata(path)
        .and_then(|metadata| metadata.modified())
        .ok()
        .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|dur| dur.as_secs() as u32)
        .unwrap_or(0)
}

/// The bytes of one cruft `.mtimes` pack plus its sidecars and checksum, ready
/// to install under `objects/pack/`.
#[derive(Debug, Clone)]
pub struct CruftPack {
    pub pack: Vec<u8>,
    pub idx: Vec<u8>,
    pub rev: Vec<u8>,
    pub mtimes: Vec<u8>,
    pub checksum: ObjectId,
    /// Object ids the cruft pack holds (its surviving unreachable set).
    pub oids: Vec<ObjectId>,
}

/// Outcome of `git repack --cruft`: the reachable pack (if any) plus the cruft
/// `.mtimes` pack of surviving unreachable objects.
#[derive(Debug, Clone)]
pub struct CruftRepackResult {
    /// The all-into-one reachable pack, or `None` when nothing is reachable.
    pub reachable: Option<RepackResult>,
    /// The cruft pack of unreachable objects, or `None` when there are none.
    pub cruft: Option<CruftPack>,
    /// Pre-existing non-cruft, non-kept pack `.pack` paths superseded by the
    /// reachable pack (removed under `-d`).
    pub obsolete_packs: Vec<PathBuf>,
    /// Pre-existing cruft `.pack` paths whose objects are now in the new cruft
    /// pack (removed under `-d`).
    pub obsolete_cruft_packs: Vec<PathBuf>,
    retained_pack_stems: Vec<String>,
}

/// Gather every object id on disk together with the best (max) mtime of any
/// copy: a packed object contributes its pack's mtime (or its own recorded
/// mtime inside a cruft pack), a loose object contributes its file mtime.
pub fn object_mtimes_on_disk_pub(
    objects_dir: &Path,
    format: ObjectFormat,
) -> Result<HashMap<ObjectId, u32>> {
    object_mtimes_on_disk(objects_dir, format)
}

fn object_mtimes_on_disk(
    objects_dir: &Path,
    format: ObjectFormat,
) -> Result<HashMap<ObjectId, u32>> {
    let mut mtimes: HashMap<ObjectId, u32> = HashMap::new();
    let mut record = |oid: ObjectId, mtime: u32| {
        mtimes
            .entry(oid)
            .and_modify(|existing| {
                if mtime > *existing {
                    *existing = mtime;
                }
            })
            .or_insert(mtime);
    };

    let pack_dir = objects_dir.join("pack");
    if let Ok(entries) = fs::read_dir(&pack_dir) {
        let mut idx_paths: Vec<PathBuf> = Vec::new();
        for entry in entries {
            let path = entry?.path();
            if path.extension().and_then(|ext| ext.to_str()) == Some("idx") {
                idx_paths.push(path);
            }
        }
        idx_paths.sort();
        for idx_path in idx_paths {
            let pack_path = idx_path.with_extension("pack");
            if !pack_path.exists() {
                continue;
            }
            let index = PackIndex::parse(&fs::read(&idx_path)?, format)?;
            let mtimes_path = idx_path.with_extension("mtimes");
            let pack_object_mtimes: Option<Vec<u32>> =
                fs::read(&mtimes_path).ok().and_then(|bytes| {
                    sley_pack::PackMtimes::parse(&bytes, format, index.entries.len())
                        .ok()
                        .map(|parsed| parsed.mtimes)
                });
            let pack_mtime = path_mtime_secs(&pack_path);
            for (pos, entry) in index.entries.iter().enumerate() {
                let mtime = pack_object_mtimes
                    .as_ref()
                    .and_then(|table| table.get(pos).copied())
                    .unwrap_or(pack_mtime);
                record(entry.oid, mtime);
            }
        }
    }

    let store = LooseObjectStore::new(objects_dir.to_path_buf(), format);
    for oid in loose_object_ids(objects_dir, format)? {
        let path = store.object_path(&oid)?;
        record(oid, path_mtime_secs(&path));
    }
    Ok(mtimes)
}

/// Public wrapper over [`build_cruft_pack`] for the `--expire-to` limbo pack.
pub fn build_cruft_pack_pub(
    database: &FileObjectDatabase,
    format: ObjectFormat,
    survivors: &HashMap<ObjectId, u32>,
) -> Result<Option<CruftPack>> {
    build_cruft_pack(database, format, survivors)
}

/// Build the cruft `.mtimes` pack from the surviving unreachable objects and
/// their timestamps.
fn build_cruft_pack(
    database: &FileObjectDatabase,
    format: ObjectFormat,
    survivors: &HashMap<ObjectId, u32>,
) -> Result<Option<CruftPack>> {
    if survivors.is_empty() {
        return Ok(None);
    }
    let mut ordered: Vec<(ObjectId, u32)> = survivors.iter().map(|(o, m)| (*o, *m)).collect();
    ordered.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));

    let mut oids: Vec<ObjectId> = Vec::with_capacity(ordered.len());
    let mut objects: Vec<Arc<EncodedObject>> = Vec::with_capacity(ordered.len());
    let mut mtime_by_oid: HashMap<ObjectId, u32> = HashMap::with_capacity(ordered.len());
    for (oid, mtime) in ordered {
        match database.read_object(&oid) {
            Ok(object) => {
                oids.push(oid);
                objects.push(object);
                mtime_by_oid.insert(oid, mtime);
            }
            Err(GitError::NotFound(_)) => {}
            Err(err) => return Err(err),
        }
    }
    if oids.is_empty() {
        return Ok(None);
    }

    let inputs: Vec<PackInput<'_>> = oids
        .iter()
        .zip(&objects)
        .map(|(oid, object)| PackInput {
            oid,
            object: object.as_ref(),
        })
        .collect();
    let written = PackFile::write_packed_with_known_ids(&inputs, format)?;

    // `.mtimes` table is in lexicographic (index/fanout) order.
    let mut sorted_entries: Vec<&sley_pack::PackIndexEntry> = written.entries.iter().collect();
    sorted_entries.sort_by(|a, b| a.oid.as_bytes().cmp(b.oid.as_bytes()));
    let mtimes_table: Vec<u32> = sorted_entries
        .iter()
        .map(|entry| mtime_by_oid.get(&entry.oid).copied().unwrap_or(0))
        .collect();
    let positions = sley_pack::pack_order_index_positions(&written.entries);
    let rev = sley_pack::PackReverseIndex::write(format, &positions, &written.checksum)?;
    let mtimes = sley_pack::PackMtimes::write(format, &mtimes_table, &written.checksum)?;

    let mut cruft_oids: Vec<ObjectId> = sorted_entries.iter().map(|e| e.oid).collect();
    cruft_oids.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
    Ok(Some(CruftPack {
        pack: written.pack,
        idx: written.index,
        rev,
        mtimes,
        checksum: written.checksum,
        oids: cruft_oids,
    }))
}

/// `git repack --cruft [--cruft-expiration=<t>] [-d]`: pack the reachable
/// closure of `roots` into one new pack, then collect every unreachable object
/// into a `.mtimes`-stamped cruft pack (honouring `cruft_expiration`). The
/// caller installs the result and, under `-d`, removes the superseded non-cruft
/// and old cruft packs.
///
/// Mirrors builtin/repack.c's PACK_CRUFT path + repack-cruft.c `write_cruft_pack`
/// without the per-pack stdin protocol: unreachable objects are everything on
/// disk minus the reachable set.
pub fn repack_cruft(
    git_dir: &Path,
    format: ObjectFormat,
    roots: &[ObjectId],
    cruft_expiration: Option<u32>,
) -> Result<CruftRepackResult> {
    repack_cruft_with_options(
        git_dir,
        format,
        roots,
        cruft_expiration,
        &RepackOptions::default(),
    )
}

pub fn repack_cruft_with_options(
    git_dir: &Path,
    format: ObjectFormat,
    roots: &[ObjectId],
    cruft_expiration: Option<u32>,
    options: &RepackOptions,
) -> Result<CruftRepackResult> {
    let objects_dir = repository_objects_dir(git_dir);
    let database = FileObjectDatabase::new(objects_dir.clone(), format);
    let pack_dir = objects_dir.join("pack");
    let retained_pack_stems = repack_retained_pack_stems(
        &pack_dir,
        &options.keep_pack_stems,
        !options.pack_kept_objects,
    )?;
    let excluded_oids = if options.pack_kept_objects {
        HashSet::new()
    } else {
        pack_oids_for_stems(&pack_dir, format, &retained_pack_stems)?
    };

    // Reachable closure → the new "reachable" pack.
    let mut reachable_ids = collect_reachable_object_ids(&database, format, roots.iter().copied())?;
    reachable_ids.retain(|oid| !excluded_oids.contains(oid));
    let reachable_result = if reachable_ids.is_empty() {
        None
    } else {
        let mut ids: Vec<ObjectId> = reachable_ids.iter().copied().collect();
        ids.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
        let mut objects = Vec::with_capacity(ids.len());
        for oid in &ids {
            match database.read_object(oid) {
                Ok(object) => objects.push(ReachablePackObject { oid: *oid, object }),
                Err(GitError::NotFound(_)) => {}
                Err(err) => return Err(err),
            }
        }
        if objects.is_empty() {
            None
        } else {
            let inputs = pack_inputs(&objects);
            let written = PackFile::write_packed_with_known_ids(&inputs, format)?;
            let packed_set: HashSet<&ObjectId> = written.entries.iter().map(|e| &e.oid).collect();
            let mut packed_loose: Vec<ObjectId> = loose_object_ids(&objects_dir, format)?
                .into_iter()
                .filter(|oid| packed_set.contains(oid))
                .collect();
            packed_loose.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
            Some(RepackResult {
                pack: written.pack,
                idx: written.index,
                object_count: written.entries.len(),
                obsolete_packs: Vec::new(),
                packed_loose,
                retained_pack_stems: Vec::new(),
                pack_checksum: written.checksum,
                index_entries: written.entries,
            })
        }
    };

    // Unreachable objects = everything on disk minus the reachable set, stamped
    // with their best mtime.
    let mut survivors: HashMap<ObjectId, u32> = object_mtimes_on_disk(&objects_dir, format)?
        .into_iter()
        .filter(|(oid, _)| !reachable_ids.contains(oid) && !excluded_oids.contains(oid))
        .collect();

    // Expiration: rescue older objects reachable from a recent one, drop the rest.
    if let Some(expiration) = cruft_expiration {
        rescue_and_expire_cruft_objects(&database, format, &mut survivors, expiration)?;
    }

    let cruft = build_cruft_pack(&database, format, &survivors)?;

    // The packs the reachable+cruft packs supersede: every pre-existing
    // non-kept pack. Cruft packs are tracked separately.
    let mut obsolete_packs = Vec::new();
    let mut obsolete_cruft_packs = Vec::new();
    for pack_path in existing_pack_files(&pack_dir)? {
        if let Some(stem) = pack_path.file_stem().and_then(|s| s.to_str())
            && retained_pack_stems.iter().any(|retained| retained == stem)
        {
            continue;
        }
        if pack_path.with_extension("keep").exists() {
            continue;
        }
        if pack_path.with_extension("mtimes").exists() {
            obsolete_cruft_packs.push(pack_path);
        } else {
            obsolete_packs.push(pack_path);
        }
    }

    Ok(CruftRepackResult {
        reachable: reachable_result,
        cruft,
        obsolete_packs,
        obsolete_cruft_packs,
        retained_pack_stems,
    })
}

/// Apply `--cruft-expiration` over the survivor map in place: starting from the
/// recent candidates (mtime strictly newer than `expiration`), walk reachability
/// and rescue every dependency at the cutoff mtime; drop older candidates that
/// no recent object reaches. Mirrors the pack-objects cruft expiry traversal.
fn rescue_and_expire_cruft_objects(
    database: &FileObjectDatabase,
    format: ObjectFormat,
    survivors: &mut HashMap<ObjectId, u32>,
    expiration: u32,
) -> Result<()> {
    let recent: Vec<ObjectId> = survivors
        .iter()
        .filter(|(_, mtime)| **mtime > expiration)
        .map(|(oid, _)| *oid)
        .collect();

    let mut keep: HashSet<ObjectId> = HashSet::new();
    let mut pending: Vec<ObjectId> = recent.clone();
    while let Some(oid) = pending.pop() {
        if !keep.insert(oid) {
            continue;
        }
        let Ok(object) = database.read_object(&oid) else {
            continue;
        };
        match object.object_type {
            ObjectType::Commit => {
                if let Ok(commit) = Commit::parse_ref(format, &object.body) {
                    pending.extend(commit.parents.iter().copied());
                    pending.push(commit.tree);
                }
            }
            ObjectType::Tree => {
                for entry in TreeEntries::new(format, &object.body).flatten() {
                    if !entry.is_gitlink() {
                        pending.push(entry.oid);
                    }
                }
            }
            ObjectType::Tag => {
                if let Ok(tag) = Tag::parse_ref(format, &object.body) {
                    pending.push(tag.object);
                }
            }
            ObjectType::Blob => {}
        }
    }

    // Drop any survivor that is neither recent nor rescued; rescued-but-older
    // objects keep their recorded mtime (already >= 0), recent ones unchanged.
    survivors.retain(|oid, mtime| *mtime > expiration || keep.contains(oid));
    Ok(())
}

/// Install a [`repack_cruft`] result: write the reachable pack and the cruft
/// `.mtimes` pack, then under `prune` remove the superseded non-cruft packs, old
/// cruft packs, and the loose objects now served.
pub fn install_cruft_repack_result(
    git_dir: &Path,
    format: ObjectFormat,
    result: &CruftRepackResult,
    prune: bool,
) -> Result<()> {
    let objects_dir = repository_objects_dir(git_dir);
    let pack_dir = objects_dir.join("pack");
    fs::create_dir_all(&pack_dir)?;

    // Names of packs we are about to remove (so we never delete the new ones).
    let new_reachable_name = result
        .reachable
        .as_ref()
        .map(|r| format!("pack-{}.pack", r.pack_checksum.to_hex()));
    let new_cruft_name = result
        .cruft
        .as_ref()
        .map(|c| format!("pack-{}.pack", c.checksum.to_hex()));

    // Write the reachable pack (idx + rev + pack), content-addressed.
    if let Some(reachable) = result.reachable.as_ref() {
        let parsed_index = PackIndex::parse(&reachable.idx, format)?;
        let pack_name = format!("pack-{}", reachable.pack_checksum.to_hex());
        let reverse_index = sley_pack::PackReverseIndex::write(
            format,
            &sley_pack::pack_order_index_positions(&parsed_index.entries),
            &reachable.pack_checksum,
        )?;
        write_pack_component(&pack_dir.join(format!("{pack_name}.pack")), &reachable.pack)?;
        write_pack_component(&pack_dir.join(format!("{pack_name}.rev")), &reverse_index)?;
        write_pack_component(&pack_dir.join(format!("{pack_name}.idx")), &reachable.idx)?;
    }

    // Write the cruft pack (pack + rev + mtimes + idx).
    if let Some(cruft) = result.cruft.as_ref() {
        let pack_name = format!("pack-{}", cruft.checksum.to_hex());
        write_pack_component(&pack_dir.join(format!("{pack_name}.pack")), &cruft.pack)?;
        write_pack_component(&pack_dir.join(format!("{pack_name}.rev")), &cruft.rev)?;
        write_pack_component(&pack_dir.join(format!("{pack_name}.mtimes")), &cruft.mtimes)?;
        write_pack_component(&pack_dir.join(format!("{pack_name}.idx")), &cruft.idx)?;
    }

    if !prune {
        return Ok(());
    }

    // Objects now served by the new packs.
    let mut present: HashSet<ObjectId> = HashSet::new();
    if let Some(reachable) = result.reachable.as_ref() {
        present.extend(reachable.index_entries.iter().map(|e| e.oid));
    }
    if let Some(cruft) = result.cruft.as_ref() {
        present.extend(cruft.oids.iter().copied());
    }

    // Remove superseded non-cruft + old cruft packs (skip the new ones).
    let mut removed_stems: HashSet<String> = HashSet::new();
    for pack_path in result
        .obsolete_packs
        .iter()
        .chain(result.obsolete_cruft_packs.iter())
    {
        let file_name = pack_path.file_name().and_then(|n| n.to_str());
        if file_name == new_reachable_name.as_deref() || file_name == new_cruft_name.as_deref() {
            continue;
        }
        if let Some(stem) = pack_path.file_stem().and_then(|s| s.to_str())
            && result
                .retained_pack_stems
                .iter()
                .any(|retained| retained == stem)
        {
            continue;
        }
        if pack_path.with_extension("keep").exists() {
            continue;
        }
        if let Some(stem) = pack_path.file_stem().and_then(|s| s.to_str()) {
            removed_stems.insert(stem.to_string());
        }
        remove_file_if_exists(pack_path)?;
        remove_file_if_exists(&pack_path.with_extension("idx"))?;
        for ext in ["rev", "mtimes", "bitmap", "promisor"] {
            remove_file_if_exists(&pack_path.with_extension(ext))?;
        }
    }

    // Drop loose objects now in a new pack.
    let loose_now_packed: Vec<ObjectId> = loose_object_ids(&objects_dir, format)?
        .into_iter()
        .filter(|oid| present.contains(oid))
        .collect();
    prune_loose_objects(&objects_dir, format, loose_now_packed.iter(), &present)?;

    prune_stale_multi_pack_index(&pack_dir, format, &removed_stems)?;
    Ok(())
}

fn pack_index_entries_match_writer(
    parsed: &[PackIndexEntry],
    writer_entries: &[PackIndexEntry],
) -> bool {
    if parsed.len() != writer_entries.len() {
        return false;
    }
    let mut writer_entries = writer_entries.iter().collect::<Vec<_>>();
    writer_entries.sort_by(|left, right| left.oid.as_bytes().cmp(right.oid.as_bytes()));
    parsed.iter().zip(writer_entries).all(|(left, right)| {
        left.oid == right.oid && left.crc32 == right.crc32 && left.offset == right.offset
    })
}

/// List loose objects under `git_dir` that are *not* reachable from `roots`,
/// optionally deleting them.
///
/// Reachability is computed with [`collect_reachable_object_ids`] over the
/// repository's object database, so trees, parents, and tag targets are all
/// followed. When `delete` is `false` the returned ids are merely reported;
/// when `true` each unreachable loose object file is removed (packed copies are
/// never touched). Deletion is therefore opt-in.
pub fn prune_unreachable_loose<I>(
    git_dir: &Path,
    format: ObjectFormat,
    roots: I,
    delete: bool,
) -> Result<Vec<ObjectId>>
where
    I: IntoIterator<Item = ObjectId>,
{
    let objects_dir = repository_objects_dir(git_dir);
    let database = FileObjectDatabase::new(objects_dir.clone(), format);
    let reachable = collect_reachable_object_ids(&database, format, roots)?;

    let store = LooseObjectStore::new(objects_dir.clone(), format);
    let mut pruned: Vec<ObjectId> = loose_object_ids(&objects_dir, format)?
        .into_iter()
        .filter(|oid| !reachable.contains(oid))
        .collect();
    pruned.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));

    if delete {
        for oid in &pruned {
            let path = store.object_path(oid)?;
            match fs::remove_file(&path) {
                Ok(()) => {}
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
                Err(err) => return Err(GitError::Io(err.to_string())),
            }
        }
    }
    Ok(pruned)
}

/// Loose object ids under `objects_dir`, sorted by hex, with packed objects
/// excluded.
fn loose_object_ids(objects_dir: &Path, format: ObjectFormat) -> Result<Vec<ObjectId>> {
    let oids = loose_object_id_set(objects_dir, format)?;
    let mut oids = oids.into_iter().collect::<Vec<_>>();
    oids.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));
    Ok(oids)
}

fn loose_object_id_set(objects_dir: &Path, format: ObjectFormat) -> Result<HashSet<ObjectId>> {
    let mut oids = HashSet::new();
    collect_loose_object_ids(objects_dir, format, &mut oids)?;
    Ok(oids)
}

/// Absolute paths of every `*.pack` file directly inside `pack_dir`, sorted for
/// deterministic output.
fn existing_pack_files(pack_dir: &Path) -> Result<Vec<PathBuf>> {
    if !pack_dir.exists() {
        return Ok(Vec::new());
    }
    let mut packs = Vec::new();
    for entry in fs::read_dir(pack_dir)? {
        let path = entry?.path();
        if path.extension().and_then(|ext| ext.to_str()) == Some("pack") && path.is_file() {
            packs.push(path);
        }
    }
    packs.sort();
    Ok(packs)
}

/// Remove pre-existing packs whose every object is contained in `present`,
/// skipping `keep` (the pack just written), `.keep` packs, and `.promisor` packs.
/// A stale multi-pack-index that references any removed pack is removed too.
fn prune_obsolete_pack_paths(
    objects_dir: &Path,
    format: ObjectFormat,
    packs: &[PathBuf],
    keep: &Path,
    retained_pack_stems: &[String],
) -> Result<()> {
    prune_pack_paths_matching(objects_dir, format, packs.iter(), keep, retained_pack_stems, |_| Ok(true))
}

fn prune_pack_paths_matching<'a>(
    objects_dir: &Path,
    format: ObjectFormat,
    packs: impl IntoIterator<Item = &'a PathBuf>,
    keep: &Path,
    retained_pack_stems: &[String],
    mut should_prune: impl FnMut(&Path) -> Result<bool>,
) -> Result<()> {
    let pack_dir = objects_dir.join("pack");
    let keep_stem = keep.file_stem().map(|stem| stem.to_owned());
    let retained_pack_stems: HashSet<&str> =
        retained_pack_stems.iter().map(String::as_str).collect();
    let mut removed_stems: HashSet<String> = HashSet::new();

    for pack_path in packs {
        if pack_path == keep {
            continue;
        }
        let Some(stem) = pack_path.file_stem() else {
            continue;
        };
        if Some(stem) == keep_stem.as_deref() {
            continue;
        }
        if let Some(stem) = stem.to_str()
            && retained_pack_stems.contains(stem)
        {
            continue;
        }
        if pack_path.with_extension("keep").exists()
            || pack_path.with_extension("promisor").exists()
        {
            continue;
        }
        if !should_prune(pack_path)? {
            continue;
        }
        remove_file_if_exists(pack_path)?;
        remove_file_if_exists(&pack_path.with_extension("idx"))?;
        for ext in ["rev", "mtimes", "bitmap"] {
            remove_file_if_exists(&pack_path.with_extension(ext))?;
        }
        removed_stems.insert(stem.to_string_lossy().into_owned());
    }

    prune_stale_multi_pack_index(&pack_dir, format, &removed_stems)?;
    Ok(())
}

/// Remove a `multi-pack-index` if it names *any* pack that was removed.
///
/// A MIDX that still references a deleted pack makes reads fail (the lookup
/// resolves to a pack that is gone) before any fallback. Removing the whole MIDX
/// when even one of its packs is pruned forces readers back to the individual pack
/// indexes, which are correct; `multi-pack-index write` can rebuild it later.
fn prune_stale_multi_pack_index(
    pack_dir: &Path,
    format: ObjectFormat,
    removed_stems: &HashSet<String>,
) -> Result<()> {
    if removed_stems.is_empty() {
        return Ok(());
    }
    let midx_path = pack_dir.join("multi-pack-index");
    if !midx_path.exists() {
        return Ok(());
    }
    let midx = MultiPackIndex::parse(&fs::read(&midx_path)?, format)?;
    let references_removed_pack = midx.pack_names.iter().any(|name| {
        let stem = name.strip_suffix(".idx").unwrap_or(name);
        removed_stems.contains(stem)
    });
    if references_removed_pack {
        remove_file_if_exists(&midx_path)?;
    }
    Ok(())
}

/// Remove each loose object in `candidates` whose id is in `present`, leaving
/// any object not actually packed untouched.
fn prune_loose_objects<'a, I>(
    objects_dir: &Path,
    format: ObjectFormat,
    candidates: I,
    present: &HashSet<ObjectId>,
) -> Result<()>
where
    I: IntoIterator<Item = &'a ObjectId>,
{
    let store = LooseObjectStore::new(objects_dir.to_path_buf(), format);
    for oid in candidates {
        if !present.contains(oid) {
            continue;
        }
        remove_file_if_exists(&store.object_path(oid)?)?;
    }
    Ok(())
}

enum PackDeltaBase {
    Offset(u64),
    Ref(ObjectId),
}

struct PackIndexOffsetInfo {
    end_offset: u64,
    delta_base_oid: Option<ObjectId>,
}

fn scan_pack_index_offsets(
    index: &PackIndex,
    target_offset: u64,
    trailer_offset: u64,
    delta_base_offset: Option<u64>,
) -> Result<PackIndexOffsetInfo> {
    let mut target_count = 0usize;
    let mut next_offset = None;
    let mut delta_base_oid = None;

    for entry in &index.entries {
        if entry.offset == target_offset {
            target_count += 1;
        } else if entry.offset > target_offset {
            match next_offset {
                Some(current) if current <= entry.offset => {}
                _ => next_offset = Some(entry.offset),
            }
        }
        if Some(entry.offset) == delta_base_offset {
            delta_base_oid = Some(entry.oid);
        }
    }

    if target_count == 0 {
        return Err(GitError::InvalidFormat(format!(
            "pack index offset {target_offset} not found"
        )));
    }
    if let Some(offset) = delta_base_offset
        && delta_base_oid.is_none()
    {
        return Err(GitError::InvalidFormat(format!(
            "ofs-delta base offset {offset} not found"
        )));
    }

    Ok(PackIndexOffsetInfo {
        // Preserve the old sorted-vector behavior for malformed indexes with
        // duplicate offsets: the next sorted entry has the same offset.
        end_offset: if target_count > 1 {
            target_offset
        } else {
            next_offset.unwrap_or(trailer_offset)
        },
        delta_base_oid,
    })
}

fn pack_entry_delta_base(
    format: ObjectFormat,
    pack: &[u8],
    entry_offset: u64,
) -> Result<Option<PackDeltaBase>> {
    let mut cursor = usize::try_from(entry_offset)
        .map_err(|_| GitError::InvalidFormat("pack entry offset overflows usize".into()))?;
    let first = pack_next_byte(pack, &mut cursor)?;
    let kind = (first >> 4) & 0x07;
    let mut byte = first;
    while byte & 0x80 != 0 {
        byte = pack_next_byte(pack, &mut cursor)?;
    }
    match kind {
        6 => Ok(Some(PackDeltaBase::Offset(parse_ofs_delta_base_offset(
            pack,
            &mut cursor,
            entry_offset,
        )?))),
        7 => Ok(Some(PackDeltaBase::Ref(parse_ref_delta_base_oid(
            format,
            pack,
            &mut cursor,
        )?))),
        _ => Ok(None),
    }
}

fn parse_ref_delta_base_oid(
    format: ObjectFormat,
    pack: &[u8],
    cursor: &mut usize,
) -> Result<ObjectId> {
    let raw_len = format.raw_len();
    if *cursor + raw_len > pack.len() {
        return Err(GitError::InvalidFormat(
            "truncated ref-delta base object id".into(),
        ));
    }
    let oid = ObjectId::from_raw(format, &pack[*cursor..*cursor + raw_len])?;
    *cursor += raw_len;
    Ok(oid)
}

fn parse_ofs_delta_base_offset(pack: &[u8], cursor: &mut usize, entry_offset: u64) -> Result<u64> {
    let mut byte = pack_next_byte(pack, cursor)?;
    let mut relative = u64::from(byte & 0x7f);
    while byte & 0x80 != 0 {
        byte = pack_next_byte(pack, cursor)?;
        relative = relative
            .checked_add(1)
            .and_then(|value| value.checked_shl(7))
            .and_then(|value| value.checked_add(u64::from(byte & 0x7f)))
            .ok_or_else(|| GitError::InvalidFormat("ofs-delta offset overflow".into()))?;
    }
    entry_offset
        .checked_sub(relative)
        .ok_or_else(|| GitError::InvalidFormat("ofs-delta points before pack start".into()))
}

fn pack_next_byte(pack: &[u8], cursor: &mut usize) -> Result<u8> {
    let Some(byte) = pack.get(*cursor).copied() else {
        return Err(GitError::InvalidFormat("truncated pack entry".into()));
    };
    *cursor += 1;
    Ok(byte)
}

fn zero_oid(format: ObjectFormat) -> Result<ObjectId> {
    Ok(ObjectId::null(format))
}

/// Remove `path` if it exists, treating a missing file as success.
fn remove_file_if_exists(path: &Path) -> Result<()> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(GitError::Io(err.to_string())),
    }
}

fn walk_reachable_objects<R, I, F>(
    reader: &R,
    format: ObjectFormat,
    starts: I,
    excluded: &HashSet<ObjectId>,
    visit: F,
) -> Result<HashSet<ObjectId>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
    F: FnMut(&ObjectId, &Arc<EncodedObject>),
{
    walk_reachable_objects_with_cut(reader, format, starts, excluded, &HashSet::new(), visit)
}

/// [`walk_reachable_objects`] with an additional `cut` set: commits in `cut`
/// are visited (their trees and blobs too) but their parents are not followed,
/// mirroring a shallow client's view of its own history during negotiation.
fn walk_reachable_objects_with_cut<R, I, F>(
    reader: &R,
    format: ObjectFormat,
    starts: I,
    excluded: &HashSet<ObjectId>,
    cut: &HashSet<ObjectId>,
    mut visit: F,
) -> Result<HashSet<ObjectId>>
where
    R: ObjectReader,
    I: IntoIterator<Item = ObjectId>,
    F: FnMut(&ObjectId, &Arc<EncodedObject>),
{
    let mut seen = HashSet::new();
    let mut pending = Vec::new();
    for start in starts {
        pending.push(start);
        while let Some(oid) = pending.pop() {
            if excluded.contains(&oid) {
                continue;
            }
            if !seen.insert(oid) {
                continue;
            }
            let object = reader.read_object(&oid).map_err(|err| {
                with_missing_object_context(err, oid, MissingObjectContext::Traversal)
            })?;
            match object.object_type {
                ObjectType::Commit => {
                    let (tree, parents) = {
                        let commit = Commit::parse_ref(format, &object.body)?;
                        (commit.tree, commit.parents)
                    };
                    visit(&oid, &object);
                    if !cut.contains(&oid) {
                        for parent in grafted_parents(reader, &oid, parents).into_iter().rev() {
                            pending.push(parent);
                        }
                    }
                    pending.push(tree);
                }
                ObjectType::Tree => {
                    let mut child_oids = Vec::new();
                    for entry in TreeEntries::new(format, &object.body) {
                        let entry = entry?;
                        if entry.is_gitlink() {
                            continue;
                        }
                        child_oids.push(entry.oid);
                    }
                    visit(&oid, &object);
                    pending.extend(child_oids.into_iter().rev());
                }
                ObjectType::Tag => {
                    let target = {
                        let tag = Tag::parse_ref(format, &object.body)?;
                        tag.object
                    };
                    visit(&oid, &object);
                    pending.push(target);
                }
                ObjectType::Blob => visit(&oid, &object),
            }
        }
    }
    Ok(seen)
}

// ===== reachability bitmaps (.bitmap write + consult) =====

/// Bit accessors over a `Vec<u64>` bitset using git's bitmap convention:
/// bit `i` lives in word `i / 64` at bit `i % 64` (LSB-first within a word).
fn bitset_get(words: &[u64], position: u32) -> bool {
    let word = (position / 64) as usize;
    word < words.len() && words[word] & (1u64 << (position % 64)) != 0
}

fn bitset_set(words: &mut [u64], position: u32) {
    let word = (position / 64) as usize;
    if word < words.len() {
        words[word] |= 1u64 << (position % 64);
    }
}

fn bitset_or(acc: &mut [u64], other: &[u64]) {
    for (dst, src) in acc.iter_mut().zip(other) {
        *dst |= *src;
    }
}

/// Sorted set-bit positions of a bitset (the inverse of repeated [`bitset_set`]).
fn bitset_positions(words: &[u64]) -> Vec<u32> {
    let mut positions = Vec::new();
    for (word_index, word) in words.iter().enumerate() {
        let mut remaining = *word;
        while remaining != 0 {
            let bit = remaining.trailing_zeros();
            positions.push(word_index as u32 * 64 + bit);
            remaining &= remaining - 1;
        }
    }
    positions
}

/// Committer timestamp (epoch seconds) of a commit identity line
/// (`Name <email> <timestamp> <tz>`); 0 when unparseable, matching git's
/// tolerance for bogus dates during bitmap commit selection.
fn commit_identity_timestamp(identity: &[u8]) -> i64 {
    let mut fields = identity.rsplitn(3, |byte| *byte == b' ');
    let _tz = fields.next();
    fields
        .next()
        .and_then(|raw| std::str::from_utf8(raw).ok())
        .and_then(|raw| raw.parse::<i64>().ok())
        .unwrap_or(0)
}

/// Upstream `next_commit_index` (pack-bitmap-write.c): the spacing schedule for
/// bitmap commit selection over the date-descending commit list.
fn bitmap_next_commit_index(idx: u32) -> u32 {
    const MIN_COMMITS: u32 = 100;
    const MAX_COMMITS: u32 = 5000;
    const MUST_REGION: u32 = 100;
    const MIN_REGION: u32 = 20000;

    if idx <= MUST_REGION {
        return 0;
    }
    if idx <= MIN_REGION {
        let offset = idx - MUST_REGION;
        return offset.min(MIN_COMMITS);
    }
    let offset = idx - MIN_REGION;
    offset.clamp(MIN_COMMITS, MAX_COMMITS)
}

/// Builds a serialised `.bitmap` for the pack described by `index_entries` /
/// `pack_checksum`, mirroring upstream pack-bitmap-write.c:
///
/// * commit selection walks the pack's commits in committer-date-descending
///   order through [`bitmap_next_commit_index`]'s spacing schedule, preferring
///   `preferred_tips` (ref tips — upstream's `NEEDS_BITMAP`) and merge commits
///   inside each window;
/// * each selected commit stores its full reachability closure (commits, trees,
///   blobs) as pack-order bit positions (no XOR compression — `xor_offset` 0 is
///   valid on disk and what readers see after resolution anyway).
///
/// Returns `Ok(None)` — mirroring upstream's warn-and-skip — when the pack
/// lacks full closure (a reachable object is missing from it).
pub fn build_pack_bitmap(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    index_entries: &[PackIndexEntry],
    pack_checksum: &ObjectId,
    preferred_tips: &HashSet<ObjectId>,
) -> Result<Option<Vec<u8>>> {
    // `index_entries` carries no ordering guarantee (writer provenance is in
    // pack-write order); bit numbering follows pack (offset) order.
    let mut by_offset: Vec<usize> = (0..index_entries.len()).collect();
    by_offset.sort_by_key(|&slot| index_entries[slot].offset);
    let bit_order: Vec<ObjectId> = by_offset
        .into_iter()
        .map(|slot| index_entries[slot].oid)
        .collect();
    build_reachability_bitmap(db, format, pack_checksum, &bit_order, preferred_tips)
}

/// [`build_pack_bitmap`]'s multi-pack sibling: builds the serialised
/// `multi-pack-index-<checksum>.bitmap` for `midx_entries`, with bits in
/// pseudo-pack order (preferred pack first, then pack id, then offset — the
/// same order [`MultiPackIndex::write_with_reverse_index`] records in `RIDX`)
/// and the midx checksum in the BITM checksum field.
pub fn build_midx_bitmap(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    midx_entries: &[sley_pack::MultiPackIndexEntry],
    midx_checksum: &ObjectId,
    preferred_pack: u32,
    preferred_tips: &HashSet<ObjectId>,
) -> Result<Option<Vec<u8>>> {
    let mut pseudo: Vec<usize> = (0..midx_entries.len()).collect();
    pseudo.sort_by_key(|&slot| {
        let entry = &midx_entries[slot];
        (
            entry.pack_int_id != preferred_pack,
            entry.pack_int_id,
            entry.offset,
        )
    });
    let bit_order: Vec<ObjectId> = pseudo
        .into_iter()
        .map(|slot| midx_entries[slot].oid)
        .collect();
    build_reachability_bitmap(db, format, midx_checksum, &bit_order, preferred_tips)
}

/// Upstream `bitmap_builder_init`'s `num_maximal` counter (pack-bitmap-write.c):
/// walk the first-parent ancestry of the selected commits, children before
/// parents, propagating per-commit "which selected commits reach me" masks.
/// A commit counts as maximal when it is selected, or when distinct selected
/// lineages converge on it (its mask gains bits its last contributing child
/// did not carry). Only the count is needed (for the trace2 data event), so no
/// reverse-edge bookkeeping is kept.
fn bitmap_num_maximal_commits(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    selected: &[ObjectId],
) -> Result<usize> {
    // First-parent subgraph reachable from the selected commits.
    let mut first_parent: HashMap<ObjectId, Option<ObjectId>> = HashMap::new();
    let mut stack: Vec<ObjectId> = selected.to_vec();
    while let Some(oid) = stack.pop() {
        if first_parent.contains_key(&oid) {
            continue;
        }
        let object = db.read_object(&oid)?;
        let commit = Commit::parse_ref(format, &object.body)?;
        let parent = grafted_parents(db, &oid, commit.parents).first().copied();
        first_parent.insert(oid, parent);
        if let Some(parent) = parent {
            stack.push(parent);
        }
    }
    // Children-before-parents order (Kahn over the single first-parent edge).
    let mut pending_children: HashMap<ObjectId, usize> = HashMap::new();
    for parent in first_parent.values().flatten() {
        *pending_children.entry(*parent).or_default() += 1;
    }
    let word_count = selected.len().div_ceil(64);
    struct MaximalEnt {
        mask: Vec<u64>,
        maximal: bool,
    }
    let mut ents: HashMap<ObjectId, MaximalEnt> = HashMap::new();
    for (bit, oid) in selected.iter().enumerate() {
        let ent = ents.entry(*oid).or_insert_with(|| MaximalEnt {
            mask: vec![0u64; word_count],
            maximal: true,
        });
        ent.mask[bit / 64] |= 1u64 << (bit % 64);
        ent.maximal = true;
    }
    let mut queue: Vec<ObjectId> = first_parent
        .keys()
        .filter(|oid| pending_children.get(*oid).copied().unwrap_or(0) == 0)
        .copied()
        .collect();
    let mut num_maximal = 0usize;
    while let Some(oid) = queue.pop() {
        if let Some(ent) = ents.remove(&oid) {
            if ent.maximal {
                num_maximal += 1;
            }
            if let Some(Some(parent)) = first_parent.get(&oid) {
                match ents.entry(*parent) {
                    std::collections::hash_map::Entry::Vacant(vacant) => {
                        // Fresh parent mask: c_not_p, !p_not_c -> not maximal.
                        vacant.insert(MaximalEnt {
                            mask: ent.mask.clone(),
                            maximal: false,
                        });
                    }
                    std::collections::hash_map::Entry::Occupied(mut occupied) => {
                        let parent_ent = occupied.get_mut();
                        let c_not_p = ent
                            .mask
                            .iter()
                            .zip(&parent_ent.mask)
                            .any(|(child, parent)| child & !parent != 0);
                        if c_not_p {
                            let p_not_c = parent_ent
                                .mask
                                .iter()
                                .zip(&ent.mask)
                                .any(|(parent, child)| parent & !child != 0);
                            for (parent, child) in parent_ent.mask.iter_mut().zip(&ent.mask) {
                                *parent |= child;
                            }
                            parent_ent.maximal = p_not_c;
                        }
                    }
                }
            }
        }
        if let Some(Some(parent)) = first_parent.get(&oid)
            && let Some(remaining) = pending_children.get_mut(parent)
        {
            *remaining -= 1;
            if *remaining == 0 {
                queue.push(*parent);
            }
        }
    }
    Ok(num_maximal)
}

/// Shared write half: `bit_order` lists every covered object's oid in bit
/// order (pack order for a single pack, pseudo-pack order for a midx);
/// `checksum` fills the BITM checksum field (pack checksum / midx checksum).
fn build_reachability_bitmap(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    checksum: &ObjectId,
    bit_order: &[ObjectId],
    preferred_tips: &HashSet<ObjectId>,
) -> Result<Option<Vec<u8>>> {
    if bit_order.is_empty() || bit_order.len() > u32::MAX as usize {
        return Ok(None);
    }
    let object_count = bit_order.len();

    // The on-disk entry position space is the oid-sorted lookup order (.idx /
    // midx OIDL); derive each bit-order slot's rank there.
    let mut oid_sorted: Vec<u32> = (0..object_count as u32).collect();
    oid_sorted.sort_by(|&left, &right| {
        bit_order[left as usize]
            .as_bytes()
            .cmp(bit_order[right as usize].as_bytes())
    });
    let mut index_position = vec![0u32; object_count];
    for (position, &slot) in oid_sorted.iter().enumerate() {
        index_position[slot as usize] = position as u32;
    }
    let mut oid_to_pack = HashMap::with_capacity(object_count);
    for (pack_pos, oid) in bit_order.iter().enumerate() {
        oid_to_pack.insert(*oid, pack_pos as u32);
    }

    // Object types in bit order; commits also collect (date, parent count).
    let mut object_types = Vec::with_capacity(object_count);
    struct IndexedCommit {
        oid: ObjectId,
        pack_pos: u32,
        index_pos: u32,
        date: i64,
        parent_count: usize,
    }
    let mut indexed_commits = Vec::new();
    for (pack_pos, oid) in bit_order.iter().enumerate() {
        // Type via the header fast path: blobs (the bulk of most packs) never
        // need their bodies inflated here.
        let object_type = match db.read_object_header(oid)? {
            Some((object_type, _)) => object_type,
            None => db.read_object(oid)?.object_type,
        };
        object_types.push(object_type);
        if object_type == ObjectType::Commit {
            let object = db.read_object(oid)?;
            let commit = Commit::parse_ref(format, &object.body)?;
            indexed_commits.push(IndexedCommit {
                oid: *oid,
                pack_pos: pack_pos as u32,
                index_pos: index_position[pack_pos],
                date: commit_identity_timestamp(commit.committer),
                parent_count: grafted_parents(db, oid, commit.parents).len(),
            });
        }
    }

    // Selection: date-descending, then the spacing schedule.
    indexed_commits.sort_by_key(|commit| std::cmp::Reverse(commit.date));
    let mut selected: Vec<&IndexedCommit> = Vec::new();
    let commit_count = indexed_commits.len() as u32;
    if commit_count < 100 {
        selected.extend(indexed_commits.iter());
    } else {
        let mut i = 0u32;
        loop {
            let next = bitmap_next_commit_index(i);
            if i + next >= commit_count {
                break;
            }
            let mut chosen = &indexed_commits[(i + next) as usize];
            if next > 0 {
                for j in 0..=next {
                    let candidate = &indexed_commits[(i + j) as usize];
                    if preferred_tips.contains(&candidate.oid) {
                        chosen = candidate;
                        break;
                    }
                    if candidate.parent_count >= 2 {
                        chosen = candidate;
                    }
                }
            }
            selected.push(chosen);
            i += next + 1;
        }
    }

    // Trace2 selection counters (upstream bitmap_builder_init): emitted before
    // the closure walk, like upstream emits them before building the ewah
    // bitmaps. Computing num_maximal_commits needs its own first-parent walk,
    // so it only runs when the trace2 event target is active.
    if std::env::var_os("GIT_TRACE2_EVENT").is_some() {
        let selected_oids: Vec<ObjectId> = selected.iter().map(|commit| commit.oid).collect();
        let num_maximal = bitmap_num_maximal_commits(db, format, &selected_oids)?;
        sley_core::trace2::data("pack-bitmap-write", "num_selected_commits", selected.len());
        sley_core::trace2::data("pack-bitmap-write", "num_maximal_commits", num_maximal);
    }

    // Reachability closures, oldest-first so newer walks stop at memoised
    // older selected commits.
    let word_count = object_count.div_ceil(64);
    let mut memo: HashMap<ObjectId, Arc<Vec<u64>>> = HashMap::new();
    for commit in selected.iter().rev() {
        let mut acc = vec![0u64; word_count];
        let mut pending = vec![commit.oid];
        while let Some(oid) = pending.pop() {
            let Some(&pack_pos) = oid_to_pack.get(&oid) else {
                // Mirrors upstream's "Packfile doesn't have full closure".
                eprintln!(
                    "warning: Failed to write bitmap index. Packfile doesn't have full closure (object {oid} is missing)"
                );
                return Ok(None);
            };
            if bitset_get(&acc, pack_pos) {
                continue;
            }
            if let Some(stored) = memo.get(&oid) {
                bitset_or(&mut acc, stored);
                continue;
            }
            bitset_set(&mut acc, pack_pos);
            let object = db.read_object(&oid)?;
            let tree = {
                let parsed = Commit::parse_ref(format, &object.body)?;
                pending.extend(grafted_parents(db, &oid, parsed.parents));
                parsed.tree
            };
            if !bitmap_mark_tree(db, format, &tree, &oid_to_pack, &mut acc)? {
                return Ok(None);
            }
        }
        memo.insert(commit.oid, Arc::new(acc));
    }

    let mut writer = PackBitmapWriter::new(format, *checksum, &object_types)?;
    for commit in &selected {
        let words = match memo.get(&commit.oid) {
            Some(words) => words,
            None => continue,
        };
        writer.add_commit(commit.pack_pos, commit.index_pos, &bitset_positions(words))?;
    }
    writer.write().map(Some)
}

/// Marks `tree` and everything below it (sub-trees, blobs) in `acc`, skipping
/// already-set bits (their closure is already covered). Returns `false` when an
/// object is missing from the pack (no full closure), after warning.
fn bitmap_mark_tree(
    db: &impl ObjectReader,
    format: ObjectFormat,
    tree: &ObjectId,
    oid_to_pack: &HashMap<ObjectId, u32>,
    acc: &mut [u64],
) -> Result<bool> {
    let Some(&pack_pos) = oid_to_pack.get(tree) else {
        eprintln!(
            "warning: Failed to write bitmap index. Packfile doesn't have full closure (object {tree} is missing)"
        );
        return Ok(false);
    };
    if bitset_get(acc, pack_pos) {
        return Ok(true);
    }
    bitset_set(acc, pack_pos);
    let object = db.read_object(tree)?;
    for entry in TreeEntries::new(format, &object.body) {
        let entry = entry?;
        if entry.is_gitlink() {
            continue;
        }
        if entry.is_tree() {
            if !bitmap_mark_tree(db, format, &entry.oid, oid_to_pack, acc)? {
                return Ok(false);
            }
        } else {
            let Some(&blob_pos) = oid_to_pack.get(&entry.oid) else {
                eprintln!(
                    "warning: Failed to write bitmap index. Packfile doesn't have full closure (object {} is missing)",
                    entry.oid
                );
                return Ok(false);
            };
            bitset_set(acc, blob_pos);
        }
    }
    Ok(true)
}

/// A pack's `.bitmap` loaded for consultation: oid <-> pack-position mappings,
/// resolved (XOR-expanded) per-commit reachability bitsets, and the four object
/// type bitmaps. Bit numbering follows pack order throughout.
pub struct LoadedPackBitmap {
    object_count: u32,
    oid_to_pack: HashMap<ObjectId, u32>,
    pack_to_oid: Vec<ObjectId>,
    commit_words: HashMap<ObjectId, Arc<Vec<u64>>>,
    commits: Vec<u64>,
    trees: Vec<u64>,
    blobs: Vec<u64>,
    tags: Vec<u64>,
}

impl LoadedPackBitmap {
    pub fn object_count(&self) -> u32 {
        self.object_count
    }

    /// Pack-order position of `oid`, when the object is in the bitmapped pack.
    pub fn pack_position(&self, oid: &ObjectId) -> Option<u32> {
        self.oid_to_pack.get(oid).copied()
    }

    pub fn oid_at(&self, position: u32) -> Option<&ObjectId> {
        self.pack_to_oid.get(position as usize)
    }

    /// The resolved reachability bitset stored for `oid`, when it was one of
    /// the writer's selected commits.
    pub fn bitmap_for_commit(&self, oid: &ObjectId) -> Option<&Arc<Vec<u64>>> {
        self.commit_words.get(oid)
    }

    /// Oids of every commit with a stored bitmap entry (unordered).
    pub fn bitmapped_commits(&self) -> impl Iterator<Item = &ObjectId> {
        self.commit_words.keys()
    }

    /// The type bitmap for `object_type` (bit per pack position).
    pub fn type_words(&self, object_type: ObjectType) -> &[u64] {
        match object_type {
            ObjectType::Commit => &self.commits,
            ObjectType::Tree => &self.trees,
            ObjectType::Blob => &self.blobs,
            ObjectType::Tag => &self.tags,
        }
    }

    fn word_count(&self) -> usize {
        (self.object_count as usize).div_ceil(64)
    }
}

/// Loads the single-pack `.bitmap` of `objects_dir/pack`, if a valid one
/// exists. Scans `pack-*.bitmap` files (sorted, first valid wins, like
/// upstream's "first bitmap" behaviour), requires the sibling `.idx`, and
/// verifies the recorded pack checksum. Any unreadable/corrupt bitmap yields
/// `Ok(None)` — consumers fall back to a regular object walk, mirroring
/// upstream's warn-and-ignore on bitmap load failure.
pub fn load_pack_bitmap(
    objects_dir: &Path,
    format: ObjectFormat,
) -> Result<Option<LoadedPackBitmap>> {
    let pack_dir = objects_dir.join("pack");
    if !pack_dir.exists() {
        return Ok(None);
    }
    // A multi-pack bitmap wins over single-pack bitmaps, like upstream's
    // open_bitmap trying the midx first.
    if let Some(bitmap) = load_midx_bitmap(&pack_dir, format)? {
        return Ok(Some(bitmap));
    }
    let mut bitmap_paths = Vec::new();
    for entry in fs::read_dir(&pack_dir)? {
        let path = entry?.path();
        if path.extension().and_then(|ext| ext.to_str()) == Some("bitmap")
            && path
                .file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| name.starts_with("pack-"))
        {
            bitmap_paths.push(path);
        }
    }
    bitmap_paths.sort();
    for bitmap_path in bitmap_paths {
        match load_pack_bitmap_file(&bitmap_path, format) {
            Ok(Some(bitmap)) => return Ok(Some(bitmap)),
            Ok(None) | Err(_) => continue,
        }
    }
    Ok(None)
}

/// Loads `multi-pack-index-<checksum>.bitmap` when the pack directory has a
/// multi-pack-index with a `RIDX` chunk (the bit-order permutation) and a
/// matching bitmap file. Returns `Ok(None)` — never an error — on any missing
/// or unusable piece, so callers fall through to single-pack bitmaps.
fn load_midx_bitmap(pack_dir: &Path, format: ObjectFormat) -> Result<Option<LoadedPackBitmap>> {
    let midx_path = pack_dir.join("multi-pack-index");
    if !midx_path.exists() {
        return Ok(None);
    }
    let Ok(midx_bytes) = fs::read(&midx_path) else {
        return Ok(None);
    };
    if midx_has_bad_ridx_chunk(&midx_bytes, format) {
        eprintln!("error: multi-pack-index reverse-index chunk is the wrong size");
        eprintln!("warning: multi-pack bitmap is missing required reverse index");
        return Ok(None);
    }
    let midx = match MultiPackIndex::parse(&midx_bytes, format) {
        Ok(midx) => midx,
        Err(GitError::InvalidFormat(message))
            if message == "multi-pack-index reverse-index chunk is the wrong size" =>
        {
            eprintln!("error: {message}");
            eprintln!("warning: multi-pack bitmap is missing required reverse index");
            return Ok(None);
        }
        Err(_) => return Ok(None),
    };
    let bitmap_path = pack_dir.join(format!(
        "multi-pack-index-{}.bitmap",
        midx.checksum.to_hex()
    ));
    if !bitmap_path.exists() {
        return Ok(None);
    }
    let object_count = midx.objects.len();
    // Upstream `load_midx_revindex`: prefer the midx's own RIDX chunk unless
    // GIT_TEST_MIDX_READ_RIDX=0 disables it, else fall back to the separate
    // `multi-pack-index-<checksum>.rev` file; a trace2 data event records
    // which source supplied the permutation.
    let read_ridx_chunk = env::var("GIT_TEST_MIDX_READ_RIDX")
        .map(|value| value != "0" && !value.eq_ignore_ascii_case("false"))
        .unwrap_or(true);
    let reverse_index: Vec<u32> = match (&midx.reverse_index, read_ridx_chunk) {
        (Some(chunk), true) => {
            sley_core::trace2::data("load_midx_revindex", "source", "midx");
            chunk.clone()
        }
        _ => {
            let rev_path =
                pack_dir.join(format!("multi-pack-index-{}.rev", midx.checksum.to_hex()));
            let Ok(rev_bytes) = fs::read(&rev_path) else {
                // Without the RIDX permutation the bit numbering is unknown.
                return Ok(None);
            };
            let Ok(parsed_rev) =
                sley_pack::PackReverseIndex::parse(&rev_bytes, format, object_count)
            else {
                return Ok(None);
            };
            sley_core::trace2::data("load_midx_revindex", "source", "rev");
            parsed_rev.positions
        }
    };
    let Ok(bitmap_bytes) = fs::read(&bitmap_path) else {
        return Ok(None);
    };
    let parsed = match PackBitmapIndex::parse(&bitmap_bytes, format, object_count) {
        Ok(parsed) => parsed,
        Err(_) => return Ok(None),
    };
    if parsed.pack_checksum != midx.checksum {
        return Ok(None);
    }

    // midx.objects is in lookup (oid-sorted) order; RIDX maps bit positions
    // to lookup positions.
    let mut pack_to_oid = Vec::with_capacity(object_count);
    for &midx_pos in &reverse_index {
        let Some(entry) = midx.objects.get(midx_pos as usize) else {
            return Ok(None);
        };
        pack_to_oid.push(entry.oid);
    }
    let mut oid_to_pack = HashMap::with_capacity(object_count);
    for (pack_pos, oid) in pack_to_oid.iter().enumerate() {
        oid_to_pack.insert(*oid, pack_pos as u32);
    }
    match assemble_loaded_bitmap(parsed, object_count, pack_to_oid, oid_to_pack, |position| {
        midx.objects.get(position).map(|entry| entry.oid)
    }) {
        Ok(loaded) => Ok(Some(loaded)),
        Err(_) => Ok(None),
    }
}

fn midx_has_bad_ridx_chunk(bytes: &[u8], format: ObjectFormat) -> bool {
    let hash_len = format.raw_len();
    if bytes.len() < 12 + 12 + hash_len || &bytes[..4] != b"MIDX" {
        return false;
    }
    let chunk_count = bytes[6] as usize;
    let table_len = match (chunk_count + 1).checked_mul(12) {
        Some(table_len) => table_len,
        None => return false,
    };
    let table_end = match 12usize.checked_add(table_len) {
        Some(table_end) if table_end <= bytes.len().saturating_sub(hash_len) => table_end,
        _ => return false,
    };
    let mut entries = Vec::with_capacity(chunk_count + 1);
    let mut cursor = 12usize;
    while cursor < table_end {
        let id = [
            bytes[cursor],
            bytes[cursor + 1],
            bytes[cursor + 2],
            bytes[cursor + 3],
        ];
        let mut raw_offset = [0u8; 8];
        raw_offset.copy_from_slice(&bytes[cursor + 4..cursor + 12]);
        entries.push((id, u64::from_be_bytes(raw_offset) as usize));
        cursor += 12;
    }
    let mut oidf = None;
    let mut ridx = None;
    for pair in entries.windows(2) {
        let start = pair[0].1;
        let end = pair[1].1;
        if end < start || end > bytes.len().saturating_sub(hash_len) {
            return false;
        }
        match &pair[0].0 {
            b"OIDF" => oidf = Some((start, end)),
            b"RIDX" => ridx = Some((start, end)),
            _ => {}
        }
    }
    let Some((oidf_start, oidf_end)) = oidf else {
        return false;
    };
    let Some((ridx_start, ridx_end)) = ridx else {
        return false;
    };
    if oidf_end.saturating_sub(oidf_start) != 256 * 4 {
        return false;
    }
    let object_count_start = oidf_end - 4;
    let object_count = u32::from_be_bytes([
        bytes[object_count_start],
        bytes[object_count_start + 1],
        bytes[object_count_start + 2],
        bytes[object_count_start + 3],
    ]) as usize;
    ridx_end.saturating_sub(ridx_start) != object_count.saturating_mul(4)
}

fn load_pack_bitmap_file(
    bitmap_path: &Path,
    format: ObjectFormat,
) -> Result<Option<LoadedPackBitmap>> {
    let index_path = bitmap_path.with_extension("idx");
    if !index_path.exists() {
        return Ok(None);
    }
    let index = PackIndex::parse(&fs::read(&index_path)?, format)?;
    let object_count = index.entries.len();
    let parsed = PackBitmapIndex::parse(&fs::read(bitmap_path)?, format, object_count)?;
    if parsed.pack_checksum != index.pack_checksum {
        return Ok(None);
    }

    let mut pack_order: Vec<u32> = (0..object_count as u32).collect();
    pack_order.sort_by_key(|index_pos| index.entries[*index_pos as usize].offset);
    let mut pack_to_oid = Vec::with_capacity(object_count);
    for index_pos in &pack_order {
        pack_to_oid.push(index.entries[*index_pos as usize].oid);
    }
    let mut oid_to_pack = HashMap::with_capacity(object_count);
    for (pack_pos, oid) in pack_to_oid.iter().enumerate() {
        oid_to_pack.insert(*oid, pack_pos as u32);
    }

    assemble_loaded_bitmap(parsed, object_count, pack_to_oid, oid_to_pack, |position| {
        index.entries.get(position).map(|entry| entry.oid)
    })
    .map(Some)
}

/// Shared tail of the bitmap loaders: expands the type bitmaps, resolves the
/// per-commit entries (XOR offsets reference earlier entries in file order),
/// and maps each entry's lookup-order position back to a commit oid via
/// `lookup_oid`.
fn assemble_loaded_bitmap(
    parsed: PackBitmapIndex,
    object_count: usize,
    pack_to_oid: Vec<ObjectId>,
    oid_to_pack: HashMap<ObjectId, u32>,
    lookup_oid: impl Fn(usize) -> Option<ObjectId>,
) -> Result<LoadedPackBitmap> {
    let word_count = object_count.div_ceil(64);
    let expand = |bitmap: &sley_pack::EwahBitmap| -> Result<Vec<u64>> {
        let mut words = bitmap.to_words()?;
        words.resize(word_count, 0);
        Ok(words)
    };

    let mut resolved: Vec<Arc<Vec<u64>>> = Vec::with_capacity(parsed.entries.len());
    let mut commit_words = HashMap::with_capacity(parsed.entries.len());
    for (entry_index, entry) in parsed.entries.iter().enumerate() {
        let mut words = expand(&entry.bitmap)?;
        if entry.xor_offset > 0 {
            let base_index = entry_index - entry.xor_offset as usize;
            let base = &resolved[base_index];
            for (dst, src) in words.iter_mut().zip(base.iter()) {
                *dst ^= *src;
            }
        }
        let words = Arc::new(words);
        resolved.push(Arc::clone(&words));
        let commit_oid = lookup_oid(entry.object_position as usize)
            .ok_or_else(|| GitError::InvalidFormat("bitmap entry position out of range".into()))?;
        commit_words.insert(commit_oid, words);
    }

    Ok(LoadedPackBitmap {
        object_count: object_count as u32,
        oid_to_pack,
        pack_to_oid,
        commit_words,
        commits: expand(&parsed.type_bitmaps.commits)?,
        trees: expand(&parsed.type_bitmaps.trees)?,
        blobs: expand(&parsed.type_bitmaps.blobs)?,
        tags: expand(&parsed.type_bitmaps.tags)?,
    })
}

/// Result of a bitmap-assisted reachability walk: pack-position bits for
/// in-pack objects plus the "extended" objects encountered outside the
/// bitmapped pack (in first-seen order, like upstream's extended index).
pub struct BitmapWalkResult {
    pub words: Vec<u64>,
    pub extended: Vec<(ObjectId, ObjectType)>,
}

impl BitmapWalkResult {
    /// Removes everything reachable in `haves` from this result.
    pub fn subtract(&mut self, haves: &BitmapWalkResult) {
        for (dst, src) in self.words.iter_mut().zip(haves.words.iter()) {
            *dst &= !*src;
        }
        let have_ext: HashSet<ObjectId> = haves.extended.iter().map(|(oid, _)| *oid).collect();
        self.extended.retain(|(oid, _)| !have_ext.contains(oid));
    }
}

/// Computes the set of objects reachable from `roots` using stored bitmaps
/// where available and a fill-in object walk where not — the consult half of
/// the bitmap engine (upstream `find_objects` + `fill_in_bitmap`).
///
/// Roots may be any object type; tag chains are peeled with every tag object
/// itself included, like the pending-object handling in
/// `prepare_bitmap_walk`. When `include_objects` is false only commits are
/// walked (tree contents of fill-in commits are not marked) — callers that
/// only count/enumerate commits mask with the commit type bitmap, so the
/// extra non-commit bits OR-ed in from stored (closed) bitmaps are harmless.
pub fn bitmap_reachable(
    bitmap: &LoadedPackBitmap,
    db: &impl ObjectReader,
    format: ObjectFormat,
    roots: &[ObjectId],
    include_objects: bool,
) -> Result<BitmapWalkResult> {
    let mut walk = BitmapFillWalk {
        bitmap,
        words: vec![0u64; bitmap.word_count()],
        extended: Vec::new(),
        extended_seen: HashSet::new(),
    };
    let mut commit_stack: Vec<ObjectId> = Vec::new();

    for root in roots {
        let mut oid = *root;
        // Peel tag chains, marking each tag object on the way.
        loop {
            let object = db.read_object(&oid)?;
            match object.object_type {
                ObjectType::Tag => {
                    walk.mark(&oid, ObjectType::Tag);
                    let tag = Tag::parse_ref(format, &object.body)?;
                    oid = tag.object;
                }
                ObjectType::Commit => {
                    commit_stack.push(oid);
                    break;
                }
                ObjectType::Tree => {
                    walk.mark_tree_closure(db, format, &oid)?;
                    break;
                }
                ObjectType::Blob => {
                    walk.mark(&oid, ObjectType::Blob);
                    break;
                }
            }
        }
    }

    while let Some(oid) = commit_stack.pop() {
        if let Some(position) = bitmap.pack_position(&oid) {
            if bitset_get(&walk.words, position) {
                continue;
            }
            if let Some(stored) = bitmap.bitmap_for_commit(&oid) {
                bitset_or(&mut walk.words, stored);
                continue;
            }
            bitset_set(&mut walk.words, position);
        } else {
            if walk.extended_seen.contains(&oid) {
                continue;
            }
            walk.extended_seen.insert(oid);
            walk.extended.push((oid, ObjectType::Commit));
        }
        let object = db.read_object(&oid)?;
        let commit = Commit::parse_ref(format, &object.body)?;
        commit_stack.extend(grafted_parents(db, &oid, commit.parents));
        if include_objects {
            walk.mark_tree_closure(db, format, &commit.tree)?;
        }
    }

    Ok(BitmapWalkResult {
        words: walk.words,
        extended: walk.extended,
    })
}

struct BitmapFillWalk<'a> {
    bitmap: &'a LoadedPackBitmap,
    words: Vec<u64>,
    extended: Vec<(ObjectId, ObjectType)>,
    extended_seen: HashSet<ObjectId>,
}

impl BitmapFillWalk<'_> {
    /// Marks one object; returns false when it was already marked.
    fn mark(&mut self, oid: &ObjectId, object_type: ObjectType) -> bool {
        if let Some(position) = self.bitmap.pack_position(oid) {
            if bitset_get(&self.words, position) {
                return false;
            }
            bitset_set(&mut self.words, position);
            true
        } else {
            if !self.extended_seen.insert(*oid) {
                return false;
            }
            self.extended.push((*oid, object_type));
            true
        }
    }

    /// Marks `tree` and everything below it, skipping subtrees already marked
    /// (a set in-pack bit means its closure is covered: either it came from a
    /// stored — closed — bitmap, or this walk already expanded it).
    fn mark_tree_closure(
        &mut self,
        db: &impl ObjectReader,
        format: ObjectFormat,
        tree: &ObjectId,
    ) -> Result<()> {
        if !self.mark(tree, ObjectType::Tree) {
            return Ok(());
        }
        let object = db.read_object(tree)?;
        for entry in TreeEntries::new(format, &object.body) {
            let entry = entry?;
            if entry.is_gitlink() {
                continue;
            }
            if entry.is_tree() {
                self.mark_tree_closure(db, format, &entry.oid)?;
            } else {
                self.mark(&entry.oid, ObjectType::Blob);
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
pub struct ObjectDatabase {
    format: ObjectFormat,
    // Behind a `Mutex` so `write_object` can take `&self` (matching the
    // `ObjectWriter` trait) and a single handle can interleave reads and writes
    // without a `&mut` borrow — the same shared-by-`&` shape the file-backed
    // database uses for its caches. Removes the need for callers to wrap this in
    // a `RefCell`/`&mut` just to write (see sley-fetch's former `RefCell` dance).
    objects: Mutex<HashMap<ObjectId, Arc<EncodedObject>>>,
    promisor: bool,
}

impl ObjectDatabase {
    pub fn new(format: ObjectFormat) -> Self {
        Self {
            format,
            objects: Mutex::new(HashMap::new()),
            promisor: false,
        }
    }

    pub fn with_promisor(mut self, promisor: bool) -> Self {
        self.promisor = promisor;
        self
    }

    pub fn contains(&self, oid: &ObjectId) -> bool {
        self.objects
            .lock()
            .map(|objects| objects.contains_key(oid))
            .unwrap_or(false)
    }

    pub fn validate(&self, oid: &ObjectId) -> Result<()> {
        let object = self.read_object(oid)?;
        let actual = object.object_id(self.format)?;
        if &actual == oid {
            Ok(())
        } else {
            Err(GitError::InvalidObject(format!(
                "object id mismatch: expected {oid}, got {actual}"
            )))
        }
    }
}

impl ObjectReader for ObjectDatabase {
    fn read_object(&self, oid: &ObjectId) -> Result<Arc<EncodedObject>> {
        self.objects
            .lock()
            .map_err(|_| GitError::object_not_found_in(*oid, MissingObjectContext::Read))?
            .get(oid)
            .map(Arc::clone)
            .or_else(|| implied_empty_tree_object(self.format, oid))
            .ok_or_else(|| GitError::object_not_found_in(*oid, MissingObjectContext::Read))
    }
}

impl ObjectWriter for ObjectDatabase {
    fn write_object(&self, object: EncodedObject) -> Result<ObjectId> {
        let oid = object.object_id(self.format)?;
        self.objects
            .lock()
            .map_err(|_| GitError::Io("object cache lock poisoned".into()))?
            .entry(oid)
            .or_insert_with(|| Arc::new(object));
        Ok(oid)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Alternate {
    pub path: std::path::PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PartialClonePolicy {
    pub promisor_remote: Option<String>,
    pub allow_missing_promised_objects: bool,
}

/// Raw pack-file bytes keyed by pack path, shared across cloned handles. Loaded
/// once so individual objects can be decoded at their offsets (see
/// [`sley_pack::read_object_at`]) without re-reading the whole file per read.
type PackBytesCache = Arc<Mutex<HashMap<PathBuf, Arc<PackData>>>>;

/// Backing bytes of a pack file: either memory-mapped (under the `mmap` feature)
/// or read into the heap. Both deref to `&[u8]`, so the decode path is identical.
#[derive(Debug)]
enum PackData {
    #[cfg(feature = "mmap")]
    Mapped(sley_mmap::MappedFile),
    Heap(Vec<u8>),
}

impl std::ops::Deref for PackData {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        match self {
            #[cfg(feature = "mmap")]
            Self::Mapped(mapped) => mapped,
            Self::Heap(bytes) => bytes,
        }
    }
}

/// Load a pack file's bytes: memory-mapped when the `mmap` feature is on (falling
/// back to a heap read if the map fails), otherwise read into the heap.
#[cfg(feature = "mmap")]
fn load_pack_data(pack_path: &Path) -> Result<PackData> {
    match sley_mmap::MappedFile::open_pack(pack_path) {
        Ok(mapped) => Ok(PackData::Mapped(mapped)),
        Err(_) => Ok(PackData::Heap(fs::read(pack_path)?)),
    }
}

#[cfg(not(feature = "mmap"))]
fn load_pack_data(pack_path: &Path) -> Result<PackData> {
    Ok(PackData::Heap(fs::read(pack_path)?))
}

#[cfg(feature = "mmap")]
fn load_pack_index_data(index_path: &Path) -> Result<Arc<dyn PackIndexByteSource>> {
    match sley_mmap::MappedFile::open_pack(index_path) {
        Ok(mapped) => Ok(Arc::new(mapped)),
        Err(_) => Ok(Arc::new(fs::read(index_path)?)),
    }
}

#[cfg(not(feature = "mmap"))]
fn load_pack_index_data(index_path: &Path) -> Result<Arc<dyn PackIndexByteSource>> {
    Ok(Arc::new(fs::read(index_path)?))
}

#[cfg(feature = "mmap")]
fn load_multi_pack_index_lookup_data(midx_path: &Path) -> Result<Arc<dyn PackIndexByteSource>> {
    match sley_mmap::MappedFile::open_multi_pack_index(midx_path) {
        Ok(mapped) => Ok(Arc::new(mapped)),
        Err(_) => Ok(Arc::new(fs::read(midx_path)?)),
    }
}

#[cfg(not(feature = "mmap"))]
fn load_multi_pack_index_lookup_data(midx_path: &Path) -> Result<Arc<dyn PackIndexByteSource>> {
    Ok(Arc::new(fs::read(midx_path)?))
}

/// Memory-capped LRU of recently decoded objects, shared across cloned handles,
/// so hot delta bases and repeated reads during a walk aren't re-decoded. The
/// cache is bounded by an approximate byte budget (not a fixed object count) so
/// it neither thrashes on bulk reads of small objects nor blows up on a few
/// large ones.
type DecodedObjectCache = Arc<Mutex<LruObjectCache>>;

/// Per-pack caches of objects decoded from a pack, keyed by pack path and then by
/// the in-pack byte offset of each object's entry. Shared across cloned handles.
/// This is the delta-base cache: resolving a delta chain by offset reuses already
/// decoded bases instead of re-inflating the whole chain on every read.
type PackDeltaCaches = Arc<Mutex<HashMap<PathBuf, Arc<Mutex<LruOffsetCache>>>>>;

/// Per-pack memo of `in-pack offset -> end-of-chain object type` for the
/// `cat-file --batch-check` header fast path. Resolving a packed delta's *type*
/// walks the delta chain to its base; without this memo every header read
/// re-walks (and re-inflates) the whole chain, so reading every object in a
/// deeply-deltified pack is super-linear (sley#26). The type only depends on the
/// chain base, so memoizing `offset -> type` lets each chain be walked at most
/// once across a batch. Keyed by pack path so an offset key is never applied to
/// the wrong pack's bytes; shared across cloned handles.
/// One pack's offset-keyed header memo (see [`PackHeaderTypeCaches`]).
type PackHeaderTypeCache = Arc<Mutex<HashMap<u64, (ObjectType, u64)>>>;

type PackHeaderTypeCaches = Arc<Mutex<HashMap<PathBuf, PackHeaderTypeCache>>>;

/// Default approximate byte budget for the decoded-object LRU. Sized to comfortably
/// hold the working set of a history walk (commits/trees/blobs and their delta
/// bases) without growing without bound on large repositories. Overridable via the
/// `SLEY_OBJECT_CACHE_BYTES` environment variable; there is currently no git-config
/// hook threaded into the object database, so this constant is the default.
const DEFAULT_OBJECT_CACHE_BYTES: usize = 96 * 1024 * 1024;

/// Default approximate byte budget for each per-pack delta-base cache. Holds the
/// decoded bases of the delta chains being walked so neighboring reads stay warm.
/// Overridable via `SLEY_DELTA_BASE_CACHE_BYTES`.
const DEFAULT_DELTA_BASE_CACHE_BYTES: usize = 96 * 1024 * 1024;

/// Approximate heap cost of caching one [`EncodedObject`]: its body plus a fixed
/// allowance for the key, enum/`Vec` headers, and per-entry map overhead. Used
/// only to drive eviction, so an estimate is fine.
fn cached_object_cost(object: &EncodedObject) -> usize {
    object.body.len().saturating_add(64)
}

/// Read an approximate byte budget from `var`, falling back to `default` when the
/// variable is unset or unparseable. A value of `0` disables the cache.
fn cache_budget_from_env(var: &str, default: usize) -> usize {
    match env::var(var) {
        Ok(value) => value.trim().parse::<usize>().unwrap_or(default),
        Err(_) => default,
    }
}

/// Approximate byte budget for the decoded-object LRU (see
/// [`DEFAULT_OBJECT_CACHE_BYTES`], `SLEY_OBJECT_CACHE_BYTES`).
///
/// Resolved once per process: the environment does not change under us, and a new
/// `FileObjectDatabase` is built often enough (e.g. once per revision resolved)
/// that re-reading the variable each time showed up as per-object overhead.
fn object_cache_budget() -> usize {
    static BUDGET: OnceLock<usize> = OnceLock::new();
    *BUDGET.get_or_init(|| {
        cache_budget_from_env("SLEY_OBJECT_CACHE_BYTES", DEFAULT_OBJECT_CACHE_BYTES)
    })
}

/// Approximate byte budget for each per-pack delta-base cache (see
/// [`DEFAULT_DELTA_BASE_CACHE_BYTES`], `SLEY_DELTA_BASE_CACHE_BYTES`). Resolved
/// once per process for the same reason as [`object_cache_budget`].
fn delta_base_cache_budget() -> usize {
    static BUDGET: OnceLock<usize> = OnceLock::new();
    *BUDGET.get_or_init(|| {
        cache_budget_from_env(
            "SLEY_DELTA_BASE_CACHE_BYTES",
            DEFAULT_DELTA_BASE_CACHE_BYTES,
        )
    })
}

/// Whether to re-hash every object on read and compare it to the requested id.
///
/// Off by default, matching git: reads trust the pack index → offset mapping and
/// the loose object's on-disk name, and object ids are verified where git verifies
/// them — when a pack is received (the index build re-hashes every object) and on
/// demand via [`FileObjectDatabase`]'s `validate`/fsck. Re-hashing on *every* read
/// dominated bulk-read cost (a scalar pure-Rust SHA-1 over each object's full
/// body), so it is opt-in via `SLEY_VERIFY_READS` (any value other than unset, ``,
/// or `0`) for callers that want the paranoid check back. Read once and cached, so
/// the default path pays only a single relaxed atomic load per read.
fn verify_reads_enabled() -> bool {
    static VERIFY: OnceLock<bool> = OnceLock::new();
    *VERIFY.get_or_init(|| match env::var("SLEY_VERIFY_READS") {
        Ok(value) => !matches!(value.trim(), "" | "0"),
        Err(_) => false,
    })
}

/// A memory-capped LRU map from a key `K` to a decoded [`EncodedObject`].
///
/// Eviction is by approximate byte budget (gix-style), not object count, so the
/// cache adapts to object size. On access an entry is moved to most-recently-used;
/// on insert, least-recently-used entries are dropped until the budget holds. A
/// budget of `0` makes the cache inert. Generic over the key so it backs both the
/// oid-keyed decoded-object cache and the offset-keyed delta-base cache.
#[derive(Debug)]
struct LruCache<K: std::hash::Hash + Eq + Clone> {
    budget: usize,
    used: usize,
    map: HashMap<K, LruEntry<K>>,
    head: Option<K>,
    tail: Option<K>,
}

#[derive(Debug)]
struct LruEntry<K> {
    object: Arc<EncodedObject>,
    prev: Option<K>,
    next: Option<K>,
}

impl<K: std::hash::Hash + Eq + Clone> LruCache<K> {
    fn new(budget: usize) -> Self {
        Self {
            budget,
            used: 0,
            map: HashMap::new(),
            head: None,
            tail: None,
        }
    }

    fn get(&mut self, key: &K) -> Option<Arc<EncodedObject>> {
        let object = Arc::clone(&self.map.get(key)?.object);
        self.touch(key);
        Some(object)
    }

    /// Move `key` to the most-recently-used end in O(1).
    fn touch(&mut self, key: &K) {
        if self.tail.as_ref() == Some(key) {
            return;
        }
        if self.map.contains_key(key) {
            self.detach(key);
            self.attach_back(key.clone());
        }
    }

    /// Drop `key` from both the map and the recency queue, releasing its budget.
    fn remove(&mut self, key: &K) {
        if let Some(entry) = self.map.get(key) {
            self.used = self.used.saturating_sub(cached_object_cost(&entry.object));
        }
        self.detach(key);
        self.map.remove(key);
    }

    fn detach(&mut self, key: &K) {
        let Some((prev, next)) = self.map.get_mut(key).map(|entry| {
            let prev = entry.prev.take();
            let next = entry.next.take();
            (prev, next)
        }) else {
            return;
        };

        match &prev {
            Some(prev_key) => {
                if let Some(prev_entry) = self.map.get_mut(prev_key) {
                    prev_entry.next = next.clone();
                }
            }
            None => self.head = next.clone(),
        }
        match &next {
            Some(next_key) => {
                if let Some(next_entry) = self.map.get_mut(next_key) {
                    next_entry.prev = prev.clone();
                }
            }
            None => self.tail = prev.clone(),
        }
    }

    fn attach_back(&mut self, key: K) {
        let previous_tail = self.tail.replace(key.clone());
        match previous_tail {
            Some(tail_key) => {
                if let Some(tail_entry) = self.map.get_mut(&tail_key) {
                    tail_entry.next = Some(key.clone());
                }
                if let Some(entry) = self.map.get_mut(&key) {
                    entry.prev = Some(tail_key);
                    entry.next = None;
                }
            }
            None => {
                self.head = Some(key.clone());
                if let Some(entry) = self.map.get_mut(&key) {
                    entry.prev = None;
                    entry.next = None;
                }
            }
        }
    }

    fn clear(&mut self) {
        self.map.clear();
        self.head = None;
        self.tail = None;
        self.used = 0;
    }

    fn put(&mut self, key: K, object: Arc<EncodedObject>) {
        if self.budget == 0 {
            return;
        }
        let cost = cached_object_cost(&object);
        // A single object larger than the whole budget is not worth caching; it
        // would immediately evict everything including itself. Drop any stale
        // smaller entry stored under the same key so accounting stays exact.
        if cost > self.budget {
            self.remove(&key);
            return;
        }
        if let Some(entry) = self.map.get_mut(&key) {
            let previous = std::mem::replace(&mut entry.object, object);
            // Replacing an existing entry: adjust accounting and refresh recency.
            self.used = self
                .used
                .saturating_sub(cached_object_cost(&previous))
                .saturating_add(cost);
            self.touch(&key);
        } else {
            self.used = self.used.saturating_add(cost);
            self.map.insert(
                key.clone(),
                LruEntry {
                    object,
                    prev: None,
                    next: None,
                },
            );
            self.attach_back(key);
        }
        while self.used > self.budget {
            let Some(evicted) = self.head.clone() else {
                break;
            };
            self.remove(&evicted);
        }
    }
}

/// Decoded-object cache keyed by object id (loose + packed reads share it).
type LruObjectCache = LruCache<ObjectId>;
/// Delta-base cache keyed by in-pack byte offset, scoped to one pack.
type LruOffsetCache = LruCache<u64>;

/// Bridges the offset-keyed [`LruOffsetCache`] to [`sley_pack::PackDeltaCache`]
/// so the pack decoder can reuse decoded delta bases. Holds the shared cache
/// behind its mutex; a poisoned lock simply behaves as a cache miss/no-op, so a
/// decode still completes correctly (just without reuse).
struct PackDeltaCacheAdapter<'a>(&'a Arc<Mutex<LruOffsetCache>>);

impl sley_pack::PackDeltaCache for PackDeltaCacheAdapter<'_> {
    fn get(&self, offset: u64) -> Option<Arc<EncodedObject>> {
        self.0.lock().ok()?.get(&offset)
    }

    fn insert(&self, offset: u64, object: Arc<EncodedObject>) {
        if let Ok(mut cache) = self.0.lock() {
            cache.put(offset, object);
        }
    }
}

/// Bridges a per-pack `offset -> ObjectType` memo into the header fast path so
/// the ofs-delta chain walk is performed at most once per chain across a batch
/// of `read_object_header` calls (sley#26).
struct PackHeaderTypeCacheAdapter<'a>(&'a PackHeaderTypeCache);

impl sley_pack::HeaderTypeCache for PackHeaderTypeCacheAdapter<'_> {
    fn get(&self, pack_offset: u64) -> Option<(ObjectType, u64)> {
        self.0.lock().ok()?.get(&pack_offset).copied()
    }

    fn put(&mut self, pack_offset: u64, header: (ObjectType, u64)) {
        if let Ok(mut cache) = self.0.lock() {
            cache.insert(pack_offset, header);
        }
    }
}

/// Parsed pack indexes keyed by `.idx` path, shared across cloned handles. This
/// remains for MIDX and path-only fallback lookups; normal pack-directory scans
/// use [`PackRegistrySnapshot`] so the lookup hot path can walk already-parsed
/// pack records directly.
type PackIndexCache = Arc<Mutex<HashMap<PathBuf, Arc<PackIndex>>>>;

/// Parsed multi-pack-index files keyed by path, shared across cloned handles.
/// Caches the MIDX parse so object lookups in repositories with a MIDX avoid
/// reparsing the same fanout/object tables for every read.
type MultiPackIndexCache = Arc<Mutex<HashMap<PathBuf, Arc<MultiPackIndex>>>>;

/// Raw multi-pack-index OID lookup tables keyed by path, shared across cloned
/// handles. These avoid hashing and materializing every MIDX object when a
/// command only needs point lookups.
type MultiPackIndexOidLookupCache = Arc<Mutex<HashMap<PathBuf, Arc<MultiPackIndexOidLookup>>>>;

/// One registered `.idx`/`.pack` pair from a pack directory. The index is parsed
/// when the registry snapshot is built; pack bytes and per-pack decode/header
/// caches hang directly off this record so repeated object lookups do not bounce
/// through path-keyed maps.
#[derive(Debug)]
struct RegisteredPack {
    idx: PathBuf,
    pack: PathBuf,
    index: Mutex<Option<Arc<PackIndexViewData>>>,
    data: Mutex<Option<Arc<PackData>>>,
    delta_cache: Arc<Mutex<LruOffsetCache>>,
    header_type_cache: PackHeaderTypeCache,
}

impl RegisteredPack {
    fn new(idx: PathBuf, pack: PathBuf) -> Self {
        Self {
            idx,
            pack,
            index: Mutex::new(None),
            data: Mutex::new(None),
            delta_cache: Arc::new(Mutex::new(LruOffsetCache::new(delta_base_cache_budget()))),
            header_type_cache: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    fn index(&self, format: ObjectFormat) -> Result<Arc<PackIndexViewData>> {
        if let Ok(cache) = self.index.lock()
            && let Some(index) = cache.as_ref()
        {
            return Ok(Arc::clone(index));
        }
        let index_bytes = load_pack_index_data(&self.idx)?;
        let index = Arc::new(PackIndexViewData::parse_trusted_source_without_checksum(
            index_bytes,
            format,
        )?);
        if let Ok(mut cache) = self.index.lock() {
            *cache = Some(Arc::clone(&index));
        }
        Ok(index)
    }

    fn bytes(&self, pack_bytes: &PackBytesCache) -> Result<Arc<PackData>> {
        if let Ok(cache) = self.data.lock()
            && let Some(bytes) = cache.as_ref()
        {
            return Ok(Arc::clone(bytes));
        }
        if let Ok(cache) = pack_bytes.lock()
            && let Some(bytes) = cache.get(&self.pack)
        {
            let bytes = Arc::clone(bytes);
            if let Ok(mut local_cache) = self.data.lock() {
                *local_cache = Some(Arc::clone(&bytes));
            }
            return Ok(bytes);
        }
        let bytes = Arc::new(load_pack_data(&self.pack)?);
        if let Ok(mut local_cache) = self.data.lock() {
            *local_cache = Some(Arc::clone(&bytes));
        }
        if let Ok(mut cache) = pack_bytes.lock() {
            cache.insert(self.pack.clone(), Arc::clone(&bytes));
        }
        Ok(bytes)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PackDirFingerprint {
    modified: Option<std::time::SystemTime>,
    idx_count: usize,
    pack_count: usize,
}

/// Snapshot of a pack directory's lookup state, shared across cloned handles.
/// New packs are still found: a lookup that misses every cached pack re-scans the
/// directory once before concluding the object is absent (see
/// [`FileObjectDatabase::find_pack_containing`]).
#[derive(Debug)]
struct PackRegistrySnapshot {
    fingerprint: PackDirFingerprint,
    packs: Vec<Arc<RegisteredPack>>,
    recent_pack: Mutex<Option<usize>>,
}

impl PackRegistrySnapshot {
    fn new(fingerprint: PackDirFingerprint, packs: Vec<Arc<RegisteredPack>>) -> Self {
        Self {
            fingerprint,
            packs,
            recent_pack: Mutex::new(None),
        }
    }

    fn cached_hint(&self) -> Option<usize> {
        self.recent_pack
            .lock()
            .ok()
            .and_then(|hint| *hint)
            .filter(|pack_index| *pack_index < self.packs.len())
    }

    fn remember_hint(&self, pack_index: usize) {
        if let Ok(mut hint) = self.recent_pack.lock() {
            *hint = Some(pack_index);
        }
    }
}

/// Cached pack-registry snapshot for this object directory, shared across cloned
/// handles. A `FileObjectDatabase` owns exactly one object directory, so this is
/// an `Option` instead of another path-keyed map.
type PackRegistryCache = Arc<Mutex<Option<Arc<PackRegistrySnapshot>>>>;

#[derive(Debug, Clone)]
struct PackLookup {
    pack: PathBuf,
    registered: Option<Arc<RegisteredPack>>,
    offset: u64,
}

impl PackLookup {
    fn from_registered(pack: Arc<RegisteredPack>, offset: u64) -> Self {
        Self {
            pack: pack.pack.clone(),
            registered: Some(pack),
            offset,
        }
    }

    fn from_path(pack: PathBuf, offset: u64) -> Self {
        Self {
            pack,
            registered: None,
            offset,
        }
    }

    fn pack_path(&self) -> &Path {
        &self.pack
    }

    fn pack_bytes(&self, database: &FileObjectDatabase) -> Result<Arc<PackData>> {
        match &self.registered {
            Some(pack) => pack.bytes(&database.pack_bytes),
            None => database.cached_pack_bytes(&self.pack),
        }
    }

    fn pack_index(&self, database: &FileObjectDatabase) -> Result<Arc<PackIndex>> {
        match &self.registered {
            Some(pack) => database.cached_pack_index(&pack.idx),
            None => database.cached_pack_index(&self.pack.with_extension("idx")),
        }
    }

    fn delta_cache(&self, database: &FileObjectDatabase) -> Option<Arc<Mutex<LruOffsetCache>>> {
        match &self.registered {
            Some(pack) => Some(Arc::clone(&pack.delta_cache)),
            None => database.pack_delta_cache(&self.pack),
        }
    }

    fn header_type_cache(&self, database: &FileObjectDatabase) -> Option<PackHeaderTypeCache> {
        match &self.registered {
            Some(pack) => Some(Arc::clone(&pack.header_type_cache)),
            None => database.pack_header_type_cache(&self.pack),
        }
    }
}

#[derive(Debug, Clone)]
pub struct FileObjectDatabase {
    loose: LooseObjectStore,
    objects_dir: PathBuf,
    alternates: Vec<PathBuf>,
    format: ObjectFormat,
    pack_bytes: PackBytesCache,
    pack_indexes: PackIndexCache,
    multi_pack_indexes: MultiPackIndexCache,
    multi_pack_oid_lookups: MultiPackIndexOidLookupCache,
    pack_registry: PackRegistryCache,
    decoded: DecodedObjectCache,
    pack_deltas: PackDeltaCaches,
    pack_header_types: PackHeaderTypeCaches,
    promisor_objects: Arc<OnceLock<HashSet<ObjectId>>>,
    /// Graft points (`$GIT_DIR/shallow`), loaded lazily on the first
    /// [`ObjectReader::is_shallow_graft`] query. `$GIT_DIR` is taken to be
    /// the parent of `objects_dir`, matching the standard layout.
    shallow_grafts: Arc<std::sync::OnceLock<HashSet<ObjectId>>>,
}

#[derive(Debug)]
pub struct ObjectPresenceChecker {
    db: FileObjectDatabase,
    pack_dir: PathBuf,
    midx: Option<Arc<MultiPackIndexOidLookup>>,
    registry: Option<Arc<PackRegistrySnapshot>>,
    registry_indexes: Vec<Option<Arc<PackIndexViewData>>>,
    recent_pack: Option<usize>,
    prepared_packs: bool,
    prepared_registry: bool,
}

impl ObjectPresenceChecker {
    fn new(db: FileObjectDatabase) -> Self {
        let pack_dir = db.objects_dir.join("pack");
        Self {
            db,
            pack_dir,
            midx: None,
            registry: None,
            registry_indexes: Vec::new(),
            recent_pack: None,
            prepared_packs: false,
            prepared_registry: false,
        }
    }

    pub fn contains(&mut self, oid: &ObjectId) -> Result<bool> {
        if oid.format() != self.db.format {
            return Err(GitError::InvalidObjectId(format!(
                "object {oid} uses {}, store uses {}",
                oid.format().name(),
                self.db.format.name()
            )));
        }
        if self.db.loose.exists(oid)? {
            return Ok(true);
        }
        if self.find_packed(oid, false)? {
            return Ok(true);
        }
        if self.find_packed(oid, true)? {
            return Ok(true);
        }
        for alternate in &self.db.alternates {
            if FileObjectDatabase::without_alternates(alternate, self.db.format).contains(oid)? {
                return Ok(true);
            }
        }
        // Preserve the regular contains() reprepare-on-miss behavior for loose
        // objects that appeared after the fanout cache was populated.
        self.db.loose.invalidate_cache();
        self.db.loose.exists(oid)
    }

    fn find_packed(&mut self, oid: &ObjectId, force_rescan: bool) -> Result<bool> {
        self.prepare_packs(force_rescan)?;
        if let Some(midx) = &self.midx
            && midx.contains(oid)
        {
            return Ok(true);
        }
        self.prepare_registry(force_rescan)?;
        self.find_in_registry(oid)
    }

    fn prepare_packs(&mut self, force_rescan: bool) -> Result<()> {
        if self.prepared_packs && !force_rescan {
            return Ok(());
        }
        let midx_path = self.pack_dir.join("multi-pack-index");
        self.midx = self.db.cached_multi_pack_index_oid_lookup(&midx_path)?;
        self.prepared_packs = true;
        Ok(())
    }

    fn prepare_registry(&mut self, force_rescan: bool) -> Result<()> {
        if self.prepared_registry && !force_rescan {
            return Ok(());
        }
        let registry = self.db.cached_pack_registry(&self.pack_dir, force_rescan)?;
        let registry_changed = match self.registry.as_ref() {
            Some(cached) => !Arc::ptr_eq(cached, &registry),
            None => true,
        };
        if registry_changed {
            self.registry_indexes = vec![None; registry.packs.len()];
            self.recent_pack = None;
            self.registry = Some(registry);
        }
        self.prepared_registry = true;
        Ok(())
    }

    fn find_in_registry(&mut self, oid: &ObjectId) -> Result<bool> {
        let Some(registry) = self.registry.as_ref().map(Arc::clone) else {
            return Ok(false);
        };
        if let Some(pack_index) = self
            .recent_pack
            .filter(|pack_index| *pack_index < registry.packs.len())
        {
            let index = self.registry_index(&registry, pack_index)?;
            if index.find(oid).is_some() {
                return Ok(true);
            }
        }
        for pack_index in 0..registry.packs.len() {
            if Some(pack_index) == self.recent_pack {
                continue;
            }
            let index = self.registry_index(&registry, pack_index)?;
            if index.find(oid).is_some() {
                self.recent_pack = Some(pack_index);
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn registry_index(
        &mut self,
        registry: &PackRegistrySnapshot,
        pack_index: usize,
    ) -> Result<Arc<PackIndexViewData>> {
        if self.registry_indexes.len() != registry.packs.len() {
            self.registry_indexes = vec![None; registry.packs.len()];
            self.recent_pack = None;
        }
        if let Some(index) = self
            .registry_indexes
            .get(pack_index)
            .and_then(|index| index.as_ref())
        {
            return Ok(Arc::clone(index));
        }
        let index = registry.packs[pack_index].index(self.db.format)?;
        if let Some(slot) = self.registry_indexes.get_mut(pack_index) {
            *slot = Some(Arc::clone(&index));
        }
        Ok(index)
    }
}

/// Parse `$GIT_DIR/shallow`: one hex object id per line. A missing file is an
/// empty set (the repository is not shallow); unparsable lines are ignored so
/// a torn write never poisons walks.
fn read_shallow_grafts(shallow_file: &Path, format: ObjectFormat) -> HashSet<ObjectId> {
    let Ok(contents) = std::fs::read_to_string(shallow_file) else {
        return HashSet::new();
    };
    contents
        .lines()
        .filter_map(|line| ObjectId::from_hex(format, line.trim()).ok())
        .collect()
}

pub fn repository_objects_dir(git_dir: impl AsRef<Path>) -> PathBuf {
    env::var_os("GIT_OBJECT_DIRECTORY")
        .map(PathBuf::from)
        .unwrap_or_else(|| repository_common_dir(git_dir).join("objects"))
}

pub fn repository_common_dir(git_dir: impl AsRef<Path>) -> PathBuf {
    if let Some(common_dir) = env::var_os("GIT_COMMON_DIR") {
        return PathBuf::from(common_dir);
    }
    let git_dir = git_dir.as_ref();
    let commondir = git_dir.join("commondir");
    if let Ok(value) = fs::read_to_string(&commondir) {
        let path = PathBuf::from(value.trim());
        let common = if path.is_absolute() {
            path
        } else {
            git_dir.join(path)
        };
        return fs::canonicalize(&common).unwrap_or(common);
    }
    git_dir.to_path_buf()
}

pub fn repository_object_ids(
    git_dir: impl AsRef<Path>,
    format: ObjectFormat,
) -> Result<Vec<ObjectId>> {
    object_ids_in_objects_dir(repository_objects_dir(git_dir), format)
}

pub fn object_ids_in_objects_dir(
    objects_dir: impl AsRef<Path>,
    format: ObjectFormat,
) -> Result<Vec<ObjectId>> {
    let objects_dir = objects_dir.as_ref();
    let mut oids = HashSet::new();
    collect_loose_object_ids(objects_dir, format, &mut oids)?;
    collect_packed_object_ids(&objects_dir.join("pack"), format, &mut oids)?;
    let mut oids = oids.into_iter().collect::<Vec<_>>();
    oids.sort_by_key(ObjectId::to_hex);
    Ok(oids)
}

fn collect_loose_object_ids(
    objects_dir: &Path,
    format: ObjectFormat,
    oids: &mut HashSet<ObjectId>,
) -> Result<()> {
    if !objects_dir.exists() {
        return Ok(());
    }
    let hex_len = format.hex_len();
    for entry in fs::read_dir(objects_dir)? {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let name = entry.file_name();
        let Some(fanout) = name.to_str() else {
            continue;
        };
        if fanout.len() != 2 || !fanout.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            continue;
        }
        for object_entry in fs::read_dir(entry.path())? {
            let object_entry = object_entry?;
            if !object_entry.file_type()?.is_file() {
                continue;
            }
            let name = object_entry.file_name();
            let Some(suffix) = name.to_str() else {
                continue;
            };
            if suffix.len() != hex_len - 2 || !suffix.bytes().all(|byte| byte.is_ascii_hexdigit()) {
                continue;
            }
            oids.insert(ObjectId::from_hex(format, &format!("{fanout}{suffix}"))?);
        }
    }
    Ok(())
}

fn collect_loose_fanout_object_ids(
    objects_dir: &Path,
    format: ObjectFormat,
    fanout: u8,
    oids: &mut HashSet<ObjectId>,
) -> Result<()> {
    let fanout_hex = format!("{fanout:02x}");
    let fanout_dir = objects_dir.join(&fanout_hex);
    let entries = match fs::read_dir(&fanout_dir) {
        Ok(entries) => entries,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(err) => return Err(GitError::Io(err.to_string())),
    };
    let hex_len = format.hex_len();
    for object_entry in entries {
        let object_entry = object_entry?;
        let name = object_entry.file_name();
        let Some(suffix) = name.to_str() else {
            continue;
        };
        if suffix.len() != hex_len - 2 || !suffix.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            continue;
        }
        oids.insert(ObjectId::from_hex(
            format,
            &format!("{fanout_hex}{suffix}"),
        )?);
    }
    Ok(())
}

#[derive(Debug, Default)]
struct LoosePresenceCache {
    loaded_fanouts: HashSet<u8>,
    objects: HashSet<ObjectId>,
}

/// Every object id resolvable through a pack (any `.idx` or the
/// multi-pack-index) under `objects_dir/pack`. Used by `--unpacked`
/// filtering: an object is "unpacked" when absent from this set, regardless
/// of a loose copy also existing.
pub fn packed_object_ids(
    objects_dir: impl AsRef<Path>,
    format: ObjectFormat,
) -> Result<HashSet<ObjectId>> {
    let mut oids = HashSet::new();
    collect_packed_object_ids(&objects_dir.as_ref().join("pack"), format, &mut oids)?;
    Ok(oids)
}

fn collect_packed_object_ids(
    pack_dir: &Path,
    format: ObjectFormat,
    oids: &mut HashSet<ObjectId>,
) -> Result<()> {
    if !pack_dir.exists() {
        return Ok(());
    }
    let mut midx_pack_names = HashSet::new();
    let midx_path = pack_dir.join("multi-pack-index");
    if midx_path.exists() {
        let midx = MultiPackIndex::parse_without_checksum(&fs::read(&midx_path)?, format)?;
        midx_pack_names.extend(midx.pack_names.iter().cloned());
        oids.extend(midx.objects.into_iter().map(|entry| entry.oid));
    }
    for entry in fs::read_dir(pack_dir)? {
        let path = entry?.path();
        if path.extension().and_then(|ext| ext.to_str()) != Some("idx") {
            continue;
        }
        if !path.with_extension("pack").exists() {
            continue;
        }
        let index = match PackIndex::parse(&fs::read(&path)?, format) {
            Ok(index) => index,
            Err(_err)
                if path
                    .file_name()
                    .and_then(|name| name.to_str())
                    .is_some_and(|name| midx_pack_names.contains(name)) =>
            {
                eprintln!(
                    "error: packfile {} index unavailable",
                    path.with_extension("pack").display()
                );
                continue;
            }
            Err(err) => return Err(err),
        };
        oids.extend(index.entries.into_iter().map(|entry| entry.oid));
    }
    Ok(())
}

impl FileObjectDatabase {
    /// The object-id format (hash algorithm) this database was opened with.
    pub fn object_format(&self) -> ObjectFormat {
        self.format
    }

    /// The repository object directory this database reads from.
    pub fn objects_dir(&self) -> &Path {
        &self.objects_dir
    }

    pub fn new(objects_dir: impl Into<PathBuf>, format: ObjectFormat) -> Self {
        let objects_dir = objects_dir.into();
        Self {
            loose: LooseObjectStore::new(objects_dir.clone(), format),
            alternates: alternate_object_dirs(&objects_dir),
            objects_dir,
            format,
            pack_bytes: Arc::new(Mutex::new(HashMap::new())),
            pack_indexes: Arc::new(Mutex::new(HashMap::new())),
            multi_pack_indexes: Arc::new(Mutex::new(HashMap::new())),
            multi_pack_oid_lookups: Arc::new(Mutex::new(HashMap::new())),
            pack_registry: Arc::new(Mutex::new(None)),
            decoded: Arc::new(Mutex::new(LruObjectCache::new(object_cache_budget()))),
            pack_deltas: Arc::new(Mutex::new(HashMap::new())),
            pack_header_types: Arc::new(Mutex::new(HashMap::new())),
            promisor_objects: Arc::new(OnceLock::new()),
            shallow_grafts: Arc::new(std::sync::OnceLock::new()),
        }
    }

    fn without_alternates(objects_dir: impl Into<PathBuf>, format: ObjectFormat) -> Self {
        let objects_dir = objects_dir.into();
        Self {
            loose: LooseObjectStore::new(objects_dir.clone(), format),
            alternates: Vec::new(),
            objects_dir,
            format,
            pack_bytes: Arc::new(Mutex::new(HashMap::new())),
            pack_indexes: Arc::new(Mutex::new(HashMap::new())),
            multi_pack_indexes: Arc::new(Mutex::new(HashMap::new())),
            multi_pack_oid_lookups: Arc::new(Mutex::new(HashMap::new())),
            pack_registry: Arc::new(Mutex::new(None)),
            decoded: Arc::new(Mutex::new(LruObjectCache::new(object_cache_budget()))),
            pack_deltas: Arc::new(Mutex::new(HashMap::new())),
            pack_header_types: Arc::new(Mutex::new(HashMap::new())),
            promisor_objects: Arc::new(OnceLock::new()),
            shallow_grafts: Arc::new(std::sync::OnceLock::new()),
        }
    }

    pub fn from_git_dir(git_dir: impl AsRef<Path>, format: ObjectFormat) -> Self {
        Self::new(repository_objects_dir(git_dir), format)
    }

    /// Drop cached pack registries, indexes, and decoded objects so the next read
    /// sees packs/objects installed after this handle was created (e.g. after
    /// `fetch` or `install_pack`). Long-lived [`Repository`] sessions call this
    /// via the owning repository's `refresh_objects` hook.
    pub fn refresh_read_cache(&self) {
        if let Ok(mut cache) = self.pack_registry.lock() {
            *cache = None;
        }
        if let Ok(mut cache) = self.pack_indexes.lock() {
            cache.clear();
        }
        if let Ok(mut cache) = self.multi_pack_indexes.lock() {
            cache.clear();
        }
        if let Ok(mut cache) = self.multi_pack_oid_lookups.lock() {
            cache.clear();
        }
        if let Ok(mut cache) = self.pack_bytes.lock() {
            cache.clear();
        }
        if let Ok(mut cache) = self.pack_deltas.lock() {
            cache.clear();
        }
        if let Ok(mut cache) = self.pack_header_types.lock() {
            cache.clear();
        }
        if let Ok(mut cache) = self.decoded.lock() {
            cache.clear();
        }
        self.loose.invalidate_cache();
    }

    pub fn loose(&self) -> &LooseObjectStore {
        &self.loose
    }

    pub fn presence_checker(&self) -> ObjectPresenceChecker {
        ObjectPresenceChecker::new(self.clone())
    }

    pub fn install_pack(&self, pack: &PackWrite) -> Result<PackInstallResult> {
        self.install_pack_with_options(pack, RawPackInstallOptions::default())
    }

    pub fn write_blob_as_pack(
        &self,
        oid: ObjectId,
        object: &EncodedObject,
        compression_level: u32,
    ) -> Result<ObjectId> {
        if object.object_type != ObjectType::Blob {
            return Err(GitError::InvalidObject(
                "write_blob_as_pack requires a blob object".into(),
            ));
        }
        if oid.format() != self.format {
            return Err(GitError::InvalidObjectId(format!(
                "object {oid} uses {}, store uses {}",
                oid.format().name(),
                self.format.name()
            )));
        }
        if self.contains(&oid)? {
            return Ok(oid);
        }
        let input = [PackInput {
            oid: &oid,
            object,
        }];
        let options = PackWriteOptions::new()
            .with_window(0)
            .with_depth(0)
            .with_reorder(false)
            .with_compression_level(compression_level);
        let pack = PackFile::write_packed_with_known_ids_and_options(&input, self.format, &options)?;
        self.install_pack(&pack)?;
        Ok(oid)
    }

    pub fn write_blobs_as_pack(
        &self,
        objects: &[(ObjectId, EncodedObject)],
        compression_level: u32,
    ) -> Result<()> {
        let mut seen = HashSet::with_capacity(objects.len());
        let mut inputs = Vec::new();
        for (oid, object) in objects {
            if object.object_type != ObjectType::Blob {
                return Err(GitError::InvalidObject(
                    "write_blobs_as_pack requires blob objects".into(),
                ));
            }
            if oid.format() != self.format {
                return Err(GitError::InvalidObjectId(format!(
                    "object {oid} uses {}, store uses {}",
                    oid.format().name(),
                    self.format.name()
                )));
            }
            if seen.insert(*oid) && !self.contains(oid)? {
                inputs.push(PackInput { oid, object });
            }
        }
        if inputs.is_empty() {
            return Ok(());
        }
        let options = PackWriteOptions::new()
            .with_window(0)
            .with_depth(0)
            .with_reorder(false)
            .with_compression_level(compression_level);
        let pack = PackFile::write_packed_with_known_ids_and_options(&inputs, self.format, &options)?;
        self.install_pack(&pack)?;
        Ok(())
    }

    pub fn install_pack_with_options(
        &self,
        pack: &PackWrite,
        options: RawPackInstallOptions,
    ) -> Result<PackInstallResult> {
        if pack.checksum.format() != self.format {
            return Err(GitError::InvalidObjectId(format!(
                "pack checksum uses {}, store uses {}",
                pack.checksum.format().name(),
                self.format.name()
            )));
        }
        for entry in &pack.entries {
            if entry.oid.format() != self.format {
                return Err(GitError::InvalidObjectId(format!(
                    "pack entry {} uses {}, store uses {}",
                    entry.oid,
                    entry.oid.format().name(),
                    self.format.name()
                )));
            }
        }
        let canonical_index = PackIndex::write_v2_for_pack(&pack.pack, self.format)?;
        let parsed_index = PackIndex::parse(&pack.index, self.format)?;
        if canonical_index.pack_checksum != pack.checksum
            || parsed_index.pack_checksum != pack.checksum
        {
            return Err(GitError::InvalidFormat(
                "pack and index checksums do not match pack write".into(),
            ));
        }
        if pack.index != canonical_index.index {
            return Err(GitError::InvalidFormat(
                "pack index does not match pack contents".into(),
            ));
        }

        let pack_dir = self.objects_dir.join("pack");
        fs::create_dir_all(&pack_dir)?;
        let pack_name = format!("pack-{}", pack.checksum.to_hex());
        let pack_path = pack_dir.join(format!("{pack_name}.pack"));
        let index_path = pack_dir.join(format!("{pack_name}.idx"));
        if !pack_path.exists() || !index_path.exists() {
            write_pack_component(&pack_path, &pack.pack)?;
            write_pack_component(&index_path, &pack.index)?;
        }
        let promisor_path = write_promisor_pack_sidecar(&pack_dir, &pack_name, options.promisor)?;
        Ok(PackInstallResult {
            pack_name,
            pack_path,
            index_path,
            promisor_path,
            object_ids: canonical_index
                .entries
                .iter()
                .map(|entry| entry.oid)
                .collect(),
        })
    }

    /// Install a pack that was produced in this process by [`PackFile::write_packed`].
    ///
    /// Unlike [`Self::install_raw_pack_with_options`], this does not re-inflate
    /// every pack entry to rebuild the index. It validates the generated pack
    /// trailer and generated index against the writer's object ids, CRCs, and
    /// offsets, then writes those bytes directly. Use the raw installer for
    /// arbitrary pack bytes received from an untrusted transport.
    pub fn install_written_pack(&self, pack: &PackWrite) -> Result<PackInstallResult> {
        self.install_written_pack_with_options(pack, RawPackInstallOptions::default())
    }

    pub fn install_written_pack_with_options(
        &self,
        pack: &PackWrite,
        options: RawPackInstallOptions,
    ) -> Result<PackInstallResult> {
        validate_pack_checksum(&pack.pack, self.format, &pack.checksum, "pack write")?;
        let parsed_index = PackIndex::parse(&pack.index, self.format)?;
        if parsed_index.pack_checksum != pack.checksum {
            return Err(GitError::InvalidFormat(
                "pack write index checksum does not match pack".into(),
            ));
        }
        if !pack_index_entries_match_writer(&parsed_index.entries, &pack.entries) {
            return Err(GitError::InvalidFormat(
                "pack write index does not match generated entries".into(),
            ));
        }
        self.install_generated_pack_unchecked(pack, options)
    }

    fn install_generated_pack_unchecked(
        &self,
        pack: &PackWrite,
        options: RawPackInstallOptions,
    ) -> Result<PackInstallResult> {
        let pack_dir = self.objects_dir.join("pack");
        fs::create_dir_all(&pack_dir)?;
        let pack_name = format!("pack-{}", pack.checksum.to_hex());
        let pack_path = pack_dir.join(format!("{pack_name}.pack"));
        let index_path = pack_dir.join(format!("{pack_name}.idx"));
        if !pack_path.exists() || !index_path.exists() {
            write_pack_component(&pack_path, &pack.pack)?;
            write_pack_component(&index_path, &pack.index)?;
        }
        let promisor_path = write_promisor_pack_sidecar(&pack_dir, &pack_name, options.promisor)?;
        Ok(PackInstallResult {
            pack_name,
            pack_path,
            index_path,
            promisor_path,
            object_ids: pack.entries.iter().map(|entry| entry.oid).collect(),
        })
    }

    pub fn install_raw_pack(&self, pack_bytes: &[u8]) -> Result<PackInstallResult> {
        self.install_raw_pack_with_options(pack_bytes, RawPackInstallOptions::default())
    }

    pub fn install_raw_pack_with_options(
        &self,
        pack_bytes: &[u8],
        options: RawPackInstallOptions,
    ) -> Result<PackInstallResult> {
        let built = PackIndex::write_v2_for_pack(pack_bytes, self.format)?;
        let pack_dir = self.objects_dir.join("pack");
        fs::create_dir_all(&pack_dir)?;
        let pack_name = format!("pack-{}", built.pack_checksum.to_hex());
        let pack_path = pack_dir.join(format!("{pack_name}.pack"));
        let index_path = pack_dir.join(format!("{pack_name}.idx"));
        if !pack_path.exists() || !index_path.exists() {
            write_pack_component(&pack_path, pack_bytes)?;
            write_pack_component(&index_path, &built.index)?;
        }
        let promisor_path = write_promisor_pack_sidecar(&pack_dir, &pack_name, options.promisor)?;
        Ok(PackInstallResult {
            pack_name,
            pack_path,
            index_path,
            promisor_path,
            object_ids: built.entries.iter().map(|entry| entry.oid).collect(),
        })
    }

    pub fn contains(&self, oid: &ObjectId) -> Result<bool> {
        if self.loose.exists(oid)? {
            return Ok(true);
        }
        if self.find_pack_containing(oid)?.is_some() {
            return Ok(true);
        }
        for alternate in &self.alternates {
            if Self::without_alternates(alternate, self.format).contains(oid)? {
                return Ok(true);
            }
        }
        // Reprepare-on-miss: a cached negative loose verdict may predate a
        // sibling write. Drop it and exact-probe once before reporting absence.
        self.loose.invalidate_cache();
        self.loose.exists(oid)
    }

    pub fn object_ids(&self) -> Result<Vec<ObjectId>> {
        let mut oids = object_ids_in_objects_dir(&self.objects_dir, self.format)?
            .into_iter()
            .collect::<HashSet<_>>();
        for alternate in &self.alternates {
            oids.extend(Self::without_alternates(alternate, self.format).object_ids()?);
        }
        let mut oids = oids.into_iter().collect::<Vec<_>>();
        oids.sort_by_key(ObjectId::to_hex);
        Ok(oids)
    }

    pub fn object_storage_info(&self, oid: &ObjectId) -> Result<Option<ObjectStorageInfo>> {
        if let Some(disk_size) = self.loose.disk_size(oid)? {
            return Ok(Some(ObjectStorageInfo {
                disk_size,
                deltabase: zero_oid(self.format)?,
            }));
        }
        if let Some(info) = self.packed_object_storage_info(oid)? {
            return Ok(Some(info));
        }
        for alternate in &self.alternates {
            if let Some(info) =
                Self::without_alternates(alternate, self.format).object_storage_info(oid)?
            {
                return Ok(Some(info));
            }
        }
        // Reprepare-on-miss: drop any stale negative loose cache and exact-probe
        // once before reporting absence (see `read_object`).
        self.loose.invalidate_cache();
        if let Some(disk_size) = self.loose.disk_size(oid)? {
            return Ok(Some(ObjectStorageInfo {
                disk_size,
                deltabase: zero_oid(self.format)?,
            }));
        }
        Ok(None)
    }

    pub fn resolve_prefix(&self, prefix: &str) -> Result<ObjectPrefixResolution> {
        let mut matches = self.object_ids_with_prefix(prefix)?;
        Ok(match matches.len() {
            0 => ObjectPrefixResolution::Missing,
            1 => ObjectPrefixResolution::Unique(matches.remove(0)),
            _ => ObjectPrefixResolution::Ambiguous(matches),
        })
    }

    pub fn object_ids_with_prefix(&self, prefix: &str) -> Result<Vec<ObjectId>> {
        validate_object_id_prefix(self.format, prefix)?;
        let mut matches = Vec::new();
        for oid in self.object_ids()? {
            if object_id_matches_prefix(&oid, prefix) {
                matches.push(oid);
            }
        }
        Ok(matches)
    }

    /// The object type and content size of `oid` without decoding its full body —
    /// git's `cat-file --batch-check` fast path. Tries the decoded-object cache,
    /// then loose storage (inflating only the framing header), then packs (reading
    /// the entry header and, for deltas, only the delta's leading varints), then
    /// alternates. Returns `Ok(None)` if the object is not present.
    ///
    /// Unlike [`ObjectReader::read_object`], this never materializes the body, so it
    /// stays cheap on huge blobs and deep delta chains. It does not populate the
    /// decoded-object cache (nothing is decoded).
    pub fn read_object_header(&self, oid: &ObjectId) -> Result<Option<(ObjectType, u64)>> {
        if implied_empty_tree_object(self.format, oid).is_some() {
            return Ok(Some((ObjectType::Tree, 0)));
        }
        if let Ok(mut cache) = self.decoded.lock()
            && let Some(object) = cache.get(oid)
        {
            return Ok(Some((object.object_type, object.body.len() as u64)));
        }
        if let Some(header) = self.loose.read_header(oid)? {
            return Ok(Some(header));
        }
        if let Some(pack_lookup) = self.find_pack_containing(oid)? {
            let bytes = pack_lookup.pack_bytes(self)?;
            // Per-pack offset->type memo so the ofs-delta chain walk that resolves
            // a packed object's type runs at most once per chain across the batch,
            // instead of re-walking (and re-inflating each link's leading varints)
            // on every header read — the sley#26 super-linear cat-file --batch-check.
            let type_cache = pack_lookup.header_type_cache(self);
            let resolve_ref_base = |base: &ObjectId| {
                self.read_object_header(base)
                    .map(|header| header.map(|(t, _)| t))
            };
            let header = match &type_cache {
                Some(cache) => {
                    let mut adapter = PackHeaderTypeCacheAdapter(cache);
                    sley_pack::read_object_header_at_with_cache(
                        &bytes,
                        pack_lookup.offset,
                        self.format,
                        resolve_ref_base,
                        &mut adapter,
                    )?
                }
                None => sley_pack::read_object_header_at(
                    &bytes,
                    pack_lookup.offset,
                    self.format,
                    resolve_ref_base,
                )?,
            };
            return Ok(Some(header));
        }
        for alternate in &self.alternates {
            if let Some(header) =
                Self::without_alternates(alternate, self.format).read_object_header(oid)?
            {
                return Ok(Some(header));
            }
        }
        // Reprepare-on-miss: discard any stale negative loose cache and retry an
        // exact path probe once before reporting absence (see `read_object`).
        self.loose.invalidate_cache();
        if let Some(header) = self.loose.read_header(oid)? {
            return Ok(Some(header));
        }
        Ok(None)
    }

    fn read_packed_object(&self, oid: &ObjectId) -> Result<Option<Arc<EncodedObject>>> {
        // Memory-capped decoded-object cache first (delta-base reuse for ref-delta
        // bases that resolve back through the store + repeated whole-object reads).
        if let Ok(mut cache) = self.decoded.lock()
            && let Some(object) = cache.get(oid)
        {
            return Ok(Some(object));
        }
        let Some(pack_lookup) = self.find_pack_containing(oid)? else {
            return Ok(None);
        };
        self.read_packed_object_at_lookup(oid, &pack_lookup)
            .map(Some)
    }

    fn read_packed_object_at_lookup(
        &self,
        oid: &ObjectId,
        pack_lookup: &PackLookup,
    ) -> Result<Arc<EncodedObject>> {
        if let Ok(mut cache) = self.decoded.lock()
            && let Some(object) = cache.get(oid)
        {
            return Ok(object);
        }
        let bytes = pack_lookup.pack_bytes(self)?;
        // Per-pack delta-base cache (keyed by in-pack offset). Resolving an
        // ofs-delta chain reuses already-decoded bases instead of re-inflating the
        // whole chain on every read. Scoped to this pack's path so an offset key is
        // never applied to the wrong pack's bytes.
        let delta_cache = pack_lookup.delta_cache(self);
        let delta_adapter = delta_cache.as_ref().map(PackDeltaCacheAdapter);
        // Decode only this object at its offset (plus its delta-base chain). A
        // ref-delta base resolves through the full store (loose / other packs) and
        // reuses the decoded-object cache. No cache lock is held across the decode,
        // so the recursive resolver re-entry (which may re-enter read_object) is
        // safe.
        let resolve_ref_base = |base: &ObjectId| self.read_object(base).map(Some);
        let object = match &delta_adapter {
            Some(adapter) => sley_pack::read_object_at_with_cache_arc(
                &bytes,
                pack_lookup.offset,
                self.format,
                resolve_ref_base,
                adapter,
            )?,
            None => sley_pack::read_object_at_arc(
                &bytes,
                pack_lookup.offset,
                self.format,
                resolve_ref_base,
            )?,
        };
        // Trust the index → offset mapping rather than re-hashing every decoded
        // object on read (see `verify_reads_enabled`); this re-hash dominated
        // bulk-read cost. Opt back in with `SLEY_VERIFY_READS` for a paranoid check.
        if verify_reads_enabled() {
            let actual = object.object_id(self.format)?;
            if actual != *oid {
                return Err(GitError::InvalidObject(format!(
                    "pack object id mismatch: index says {oid}, decoded {actual}"
                )));
            }
        }
        if let Ok(mut cache) = self.decoded.lock() {
            cache.put(*oid, Arc::clone(&object));
        }
        Ok(object)
    }

    /// The per-pack delta-base cache for `pack_path`, creating it on first use.
    /// Returns `None` only if the shared map's lock is poisoned, in which case the
    /// caller falls back to an uncached decode (correctness preserved).
    fn pack_delta_cache(&self, pack_path: &Path) -> Option<Arc<Mutex<LruOffsetCache>>> {
        let mut caches = self.pack_deltas.lock().ok()?;
        let cache = caches.entry(pack_path.to_path_buf()).or_insert_with(|| {
            Arc::new(Mutex::new(LruOffsetCache::new(delta_base_cache_budget())))
        });
        Some(Arc::clone(cache))
    }

    /// The per-pack header-type memo for `pack_path`, creating it on first use.
    /// Returns `None` only if the shared map's lock is poisoned, in which case the
    /// caller falls back to an unmemoized header walk (correctness preserved).
    fn pack_header_type_cache(&self, pack_path: &Path) -> Option<PackHeaderTypeCache> {
        let mut caches = self.pack_header_types.lock().ok()?;
        let cache = caches
            .entry(pack_path.to_path_buf())
            .or_insert_with(|| Arc::new(Mutex::new(HashMap::new())));
        Some(Arc::clone(cache))
    }

    /// Backing bytes of the pack at `pack_path`, loaded at most once per database
    /// handle (cached, shared across clones). Memory-mapped under the `mmap` feature,
    /// otherwise read into the heap. On a poisoned lock it falls back to loading
    /// without caching, preserving correctness.
    fn cached_pack_bytes(&self, pack_path: &Path) -> Result<Arc<PackData>> {
        if let Ok(cache) = self.pack_bytes.lock()
            && let Some(bytes) = cache.get(pack_path)
        {
            return Ok(Arc::clone(bytes));
        }
        let bytes = Arc::new(load_pack_data(pack_path)?);
        if let Ok(mut cache) = self.pack_bytes.lock() {
            cache.insert(pack_path.to_path_buf(), Arc::clone(&bytes));
        }
        Ok(bytes)
    }

    /// Parsed index for the `.idx` at `index_path`, parsed at most once per
    /// database handle. On a poisoned lock it falls back to parsing without
    /// caching, preserving correctness.
    fn cached_pack_index(&self, index_path: &Path) -> Result<Arc<PackIndex>> {
        if let Ok(cache) = self.pack_indexes.lock()
            && let Some(index) = cache.get(index_path)
        {
            return Ok(Arc::clone(index));
        }
        let index = Arc::new(PackIndex::parse(&fs::read(index_path)?, self.format)?);
        if let Ok(mut cache) = self.pack_indexes.lock() {
            cache.insert(index_path.to_path_buf(), Arc::clone(&index));
        }
        Ok(index)
    }

    fn cached_multi_pack_index_oid_lookup(
        &self,
        midx_path: &Path,
    ) -> Result<Option<Arc<MultiPackIndexOidLookup>>> {
        if !midx_path.exists() {
            return Ok(None);
        }
        if let Ok(cache) = self.multi_pack_oid_lookups.lock()
            && let Some(midx) = cache.get(midx_path)
        {
            return Ok(Some(Arc::clone(midx)));
        }
        let bytes = load_multi_pack_index_lookup_data(midx_path)?;
        let midx = match MultiPackIndexOidLookup::parse(bytes, self.format) {
            Ok(midx) => Arc::new(midx),
            Err(GitError::InvalidFormat(message))
                if message.starts_with("multi-pack-index hash id ") =>
            {
                let actual = message
                    .strip_prefix("multi-pack-index hash id ")
                    .and_then(|rest| rest.split_whitespace().next())
                    .unwrap_or("0");
                let expected = match self.format {
                    ObjectFormat::Sha1 => 1,
                    ObjectFormat::Sha256 => 2,
                };
                eprintln!(
                    "error: multi-pack-index hash version {actual} does not match version {expected}"
                );
                return Ok(None);
            }
            Err(err) => return Err(err),
        };
        if let Ok(mut cache) = self.multi_pack_oid_lookups.lock() {
            cache.insert(midx_path.to_path_buf(), Arc::clone(&midx));
        }
        Ok(Some(midx))
    }

    /// Registry snapshot for this database's pack directory. With `force_rescan`,
    /// the directory is re-read; when the fingerprint and pack set match the
    /// cached snapshot, the same `Arc` is returned so miss handling can tell that
    /// no new packs appeared.
    fn cached_pack_registry(
        &self,
        pack_dir: &Path,
        force_rescan: bool,
    ) -> Result<Arc<PackRegistrySnapshot>> {
        if !force_rescan && let Some(registry) = self.cached_loaded_pack_registry(pack_dir)? {
            return Ok(registry);
        }
        let scanned = Arc::new(scan_pack_registry(pack_dir, self.format)?);
        if let Ok(mut cache) = self.pack_registry.lock() {
            match cache.as_ref() {
                Some(existing)
                    if existing.fingerprint == scanned.fingerprint
                        && same_registered_pack_set(&existing.packs, &scanned.packs) =>
                {
                    return Ok(Arc::clone(existing));
                }
                _ => {
                    *cache = Some(Arc::clone(&scanned));
                }
            }
        }
        Ok(scanned)
    }

    fn find_in_pack_registry(
        &self,
        registry: Arc<PackRegistrySnapshot>,
        oid: &ObjectId,
    ) -> Result<Option<PackLookup>> {
        let hinted_pack_index = registry.cached_hint();
        if let Some(pack_index) = hinted_pack_index {
            let pack = &registry.packs[pack_index];
            match pack.index(self.format) {
                Ok(index) => {
                    if let Some(entry) = index.find(oid) {
                        return Ok(Some(PackLookup::from_registered(
                            Arc::clone(pack),
                            entry.offset,
                        )));
                    }
                }
                Err(_) => {
                    eprintln!("error: packfile {} index unavailable", pack.pack.display());
                }
            }
        }
        for (pack_index, pack) in registry.packs.iter().enumerate() {
            if Some(pack_index) == hinted_pack_index {
                continue;
            }
            let index = match pack.index(self.format) {
                Ok(index) => index,
                Err(_) => {
                    eprintln!("error: packfile {} index unavailable", pack.pack.display());
                    continue;
                }
            };
            if let Some(entry) = index.find(oid) {
                registry.remember_hint(pack_index);
                return Ok(Some(PackLookup::from_registered(
                    Arc::clone(pack),
                    entry.offset,
                )));
            }
        }
        Ok(None)
    }

    /// Read `oid` from any pack *other than* the one named by `exclude`, used as
    /// a corruption fallback: a redundant packed copy survives one pack's
    /// damage. Scans the on-disk `.idx` files directly (bypassing the registry
    /// cache, whose first hit is the excluded pack) and decodes from the first
    /// other pack that both indexes the object and parses cleanly.
    fn read_packed_object_from_other_packs(
        &self,
        oid: &ObjectId,
        exclude: &PackLookup,
    ) -> Result<Option<Arc<EncodedObject>>> {
        let pack_dir = self.objects_dir.join("pack");
        let Ok(entries) = fs::read_dir(&pack_dir) else {
            return Ok(None);
        };
        let excluded_pack = exclude.pack_path().to_path_buf();
        for entry in entries {
            let idx_path = entry?.path();
            if idx_path.extension().and_then(|ext| ext.to_str()) != Some("idx") {
                continue;
            }
            let pack_path = idx_path.with_extension("pack");
            if pack_path == excluded_pack {
                continue;
            }
            let Ok(idx_bytes) = fs::read(&idx_path) else {
                continue;
            };
            let Ok(index) = PackIndex::parse(&idx_bytes, self.format) else {
                continue;
            };
            let Some(entry) = index.find(oid) else {
                continue;
            };
            let candidate = PackLookup::from_path(pack_path, entry.offset);
            if let Ok(object) = self.read_packed_object_at_lookup(oid, &candidate) {
                return Ok(Some(object));
            }
        }
        Ok(None)
    }

    fn find_pack_containing(&self, oid: &ObjectId) -> Result<Option<PackLookup>> {
        if oid.format() != self.format {
            return Err(GitError::InvalidObjectId(format!(
                "object {oid} uses {}, store uses {}",
                oid.format().name(),
                self.format.name()
            )));
        }
        let pack_dir = self.objects_dir.join("pack");
        // Hot path: a previously cached pack registry or multi-pack-index already
        // names every pack, and locating `oid` in them is pure in-memory index
        // work. Try that first so a warm handle does not parse indexes or hash
        // pack paths on every lookup.
        if let Some(midx) = self.cached_loaded_multi_pack_index_oid_lookup()
            && let Some(pack_paths) = self.midx_oid_lookup_pack_paths(&pack_dir, &midx, oid)?
        {
            return Ok(Some(pack_paths));
        }
        if let Some(registry) = self.cached_loaded_pack_registry(&pack_dir)?
            && let Some(pack_paths) = self.find_in_pack_registry(registry, oid)?
        {
            return Ok(Some(pack_paths));
        }

        if !pack_dir.exists() {
            return Ok(None);
        }
        if let Some(pack_paths) = self.find_midx_pack_containing(&pack_dir, oid)? {
            return Ok(Some(pack_paths));
        }
        // Search the cached registry first. On a complete miss, re-scan the
        // directory once (picking up any pack added since the registry was
        // cached) and search again, so newly written packs are still found.
        let registry = self.cached_pack_registry(&pack_dir, false)?;
        if let Some(pack_paths) = self.find_in_pack_registry(Arc::clone(&registry), oid)? {
            return Ok(Some(pack_paths));
        }
        let refreshed = self.cached_pack_registry(&pack_dir, true)?;
        if Arc::ptr_eq(&registry, &refreshed) {
            // The re-scan produced the same registry, so nothing new appeared.
            return Ok(None);
        }
        self.find_in_pack_registry(refreshed, oid)
    }

    fn packed_object_storage_info(&self, oid: &ObjectId) -> Result<Option<ObjectStorageInfo>> {
        let Some(pack_lookup) = self.find_pack_containing(oid)? else {
            return Ok(None);
        };
        let pack_len = fs::metadata(pack_lookup.pack_path())?.len();
        let trailer_offset = pack_len
            .checked_sub(self.format.raw_len() as u64)
            .ok_or_else(|| GitError::InvalidFormat("pack file shorter than checksum".into()))?;
        let index = pack_lookup.pack_index(self)?;
        let pack = pack_lookup.pack_bytes(self)?;
        let delta_base = pack_entry_delta_base(self.format, &pack, pack_lookup.offset)?;
        let delta_base_offset = match &delta_base {
            Some(PackDeltaBase::Offset(offset)) => Some(*offset),
            Some(PackDeltaBase::Ref(_)) | None => None,
        };
        let offset_info = scan_pack_index_offsets(
            &index,
            pack_lookup.offset,
            trailer_offset,
            delta_base_offset,
        )?;
        let disk_size = offset_info
            .end_offset
            .checked_sub(pack_lookup.offset)
            .ok_or_else(|| GitError::InvalidFormat("pack index offsets are not sorted".into()))?;
        let deltabase = match delta_base {
            Some(PackDeltaBase::Offset(_)) => offset_info.delta_base_oid.ok_or_else(|| {
                // scan_pack_index_offsets returns Err when delta_base_offset is
                // Some but no matching entry is found, so this is unreachable for
                // valid packs; propagate as an error rather than panic to keep a
                // malformed pack from taking down the process if that invariant
                // ever drifts.
                GitError::InvalidFormat("ofs-delta base oid missing from pack index".into())
            })?,
            Some(PackDeltaBase::Ref(oid)) => oid,
            None => zero_oid(self.format)?,
        };
        Ok(Some(ObjectStorageInfo {
            disk_size,
            deltabase,
        }))
    }

    fn find_midx_pack_containing(
        &self,
        pack_dir: &Path,
        oid: &ObjectId,
    ) -> Result<Option<PackLookup>> {
        let midx_path = pack_dir.join("multi-pack-index");
        let Some(midx) = self.cached_multi_pack_index_oid_lookup(&midx_path)? else {
            return Ok(None);
        };
        self.midx_oid_lookup_pack_paths(pack_dir, &midx, oid)
    }

    fn midx_oid_lookup_pack_paths(
        &self,
        pack_dir: &Path,
        midx: &MultiPackIndexOidLookup,
        oid: &ObjectId,
    ) -> Result<Option<PackLookup>> {
        let Some(entry) = midx.find(oid)? else {
            return Ok(None);
        };
        let Some(pack_name) = midx.pack_name(entry.pack_int_id) else {
            return Err(GitError::InvalidFormat(
                "multi-pack-index object points past pack table".into(),
            ));
        };
        let pack_file_name = pack_name
            .strip_suffix(".idx")
            .map(|stem| format!("{stem}.pack"))
            .unwrap_or_else(|| pack_name.to_string());
        let pack = pack_dir.join(pack_file_name);
        Ok(Some(PackLookup::from_path(pack, entry.offset)))
    }

    fn cached_loaded_multi_pack_index_oid_lookup(&self) -> Option<Arc<MultiPackIndexOidLookup>> {
        let midx_path = self.objects_dir.join("pack").join("multi-pack-index");
        let cache = self.multi_pack_oid_lookups.lock().ok()?;
        cache.get(&midx_path).map(Arc::clone)
    }

    /// The pack registry for `pack_dir` *only if already scanned and cached* —
    /// never touches the filesystem. Used by the lookup hot path to skip
    /// per-object pack-dir metadata checks once a handle is warm. A cold cache
    /// returns `None`, so the caller falls back to the scanning path. A complete
    /// miss still forces one rescan, preserving the new-pack discovery semantics.
    fn cached_loaded_pack_registry(
        &self,
        _pack_dir: &Path,
    ) -> Result<Option<Arc<PackRegistrySnapshot>>> {
        let cache = match self.pack_registry.lock() {
            Ok(cache) => cache,
            Err(_) => return Ok(None),
        };
        Ok(cache.as_ref().map(Arc::clone))
    }
}

fn validate_object_id_prefix(format: ObjectFormat, prefix: &str) -> Result<()> {
    if prefix.len() < 4 || prefix.len() > format.hex_len() {
        return Err(GitError::InvalidObjectId(format!(
            "expected 4 to {} hex digits for {}, got {}",
            format.hex_len(),
            format.name(),
            prefix.len()
        )));
    }
    if !prefix.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(GitError::InvalidObjectId(format!(
            "non-hex object id prefix {prefix}"
        )));
    }
    Ok(())
}

fn object_id_matches_prefix(oid: &ObjectId, prefix: &str) -> bool {
    oid.to_hex()
        .as_bytes()
        .iter()
        .zip(prefix.as_bytes())
        .all(|(actual, expected)| actual.eq_ignore_ascii_case(expected))
}

fn pack_dir_modified(pack_dir: &Path) -> Result<Option<std::time::SystemTime>> {
    match fs::metadata(pack_dir) {
        Ok(metadata) => Ok(metadata.modified().ok()),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(err) => Err(GitError::Io(err.to_string())),
    }
}

/// Scan `pack_dir` for `.idx` files that have a matching `.pack` sibling and
/// parse each index into a registered pack. An `.idx` without its `.pack` is
/// skipped (an orphan index cannot serve objects), matching the prior per-read
/// behavior.
fn scan_pack_registry(pack_dir: &Path, _format: ObjectFormat) -> Result<PackRegistrySnapshot> {
    let modified = pack_dir_modified(pack_dir)?;
    let entries = match fs::read_dir(pack_dir) {
        Ok(entries) => entries,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            return Ok(PackRegistrySnapshot::new(
                PackDirFingerprint {
                    modified,
                    idx_count: 0,
                    pack_count: 0,
                },
                Vec::new(),
            ));
        }
        Err(err) => return Err(GitError::Io(err.to_string())),
    };

    let mut idx_paths = Vec::new();
    let mut idx_count = 0;
    let mut pack_count = 0;
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        match path.extension().and_then(|ext| ext.to_str()) {
            Some("idx") => {
                idx_count += 1;
                idx_paths.push(path);
            }
            Some("pack") => {
                pack_count += 1;
            }
            _ => {}
        }
    }

    let mut packs = Vec::new();
    for idx in idx_paths {
        let pack = idx.with_extension("pack");
        let Ok(metadata) = fs::metadata(&pack) else {
            continue;
        };
        let modified = pack_sort_modified(&metadata);
        packs.push((
            modified,
            metadata.len(),
            Arc::new(RegisteredPack::new(idx, pack)),
        ));
    }
    // Git keeps a most-recently-used pack order; seed ours with newer/larger
    // packs before falling back to the path. In repositories with many packs,
    // this avoids parsing a long run of unrelated `.idx` files before the first
    // lookup establishes the recent-pack hint.
    packs.sort_by(|left, right| {
        right
            .0
            .cmp(&left.0)
            .then_with(|| right.1.cmp(&left.1))
            .then_with(|| left.2.idx.cmp(&right.2.idx))
    });
    let packs = packs.into_iter().map(|(_, _, pack)| pack).collect();
    Ok(PackRegistrySnapshot::new(
        PackDirFingerprint {
            modified,
            idx_count,
            pack_count,
        },
        packs,
    ))
}

fn pack_sort_modified(metadata: &fs::Metadata) -> (u64, u32) {
    metadata
        .modified()
        .ok()
        .and_then(|modified| {
            modified
                .duration_since(std::time::UNIX_EPOCH)
                .ok()
                .map(|duration| (duration.as_secs(), duration.subsec_nanos()))
        })
        .unwrap_or((0, 0))
}

/// Whether two pack registries reference the same pack/index paths (order is
/// already normalized by [`scan_pack_registry`]).
fn same_registered_pack_set(left: &[Arc<RegisteredPack>], right: &[Arc<RegisteredPack>]) -> bool {
    left.len() == right.len()
        && left
            .iter()
            .zip(right.iter())
            .all(|(a, b)| a.idx == b.idx && a.pack == b.pack)
}

fn alternate_object_dirs(objects_dir: &Path) -> Vec<PathBuf> {
    let mut alternates = Vec::new();
    if let Some(value) = env::var_os("GIT_ALTERNATE_OBJECT_DIRECTORIES") {
        for raw in value.to_string_lossy().split(':') {
            if !raw.is_empty() {
                alternates.push(PathBuf::from(raw));
            }
        }
    }
    let alternates_path = objects_dir.join("info").join("alternates");
    if let Ok(contents) = fs::read(&alternates_path) {
        for raw in contents.split(|byte| *byte == b'\n') {
            let line = raw.strip_suffix(b"\r").unwrap_or(raw);
            if line.is_empty() || line.starts_with(b"#") {
                continue;
            }
            let Ok(value) = std::str::from_utf8(line) else {
                continue;
            };
            let path = Path::new(value);
            let absolute = if path.is_absolute() {
                path.to_path_buf()
            } else {
                objects_dir.join(path)
            };
            alternates.push(absolute);
        }
    }
    alternates
}

impl ObjectReader for FileObjectDatabase {
    fn is_promised_object(&self, oid: &ObjectId) -> bool {
        self.promisor_objects().contains(oid)
    }

    fn has_shallow_grafts(&self) -> bool {
        !self
            .shallow_grafts
            .get_or_init(|| {
                let shallow_file = self
                    .objects_dir
                    .parent()
                    .map(|git_dir| git_dir.join("shallow"));
                match shallow_file {
                    Some(path) => read_shallow_grafts(&path, self.format),
                    None => HashSet::new(),
                }
            })
            .is_empty()
    }

    fn is_shallow_graft(&self, oid: &ObjectId) -> bool {
        self.shallow_grafts
            .get_or_init(|| {
                let shallow_file = self
                    .objects_dir
                    .parent()
                    .map(|git_dir| git_dir.join("shallow"));
                match shallow_file {
                    Some(path) => read_shallow_grafts(&path, self.format),
                    None => HashSet::new(),
                }
            })
            .contains(oid)
    }

    fn read_object(&self, oid: &ObjectId) -> Result<Arc<EncodedObject>> {
        if let Some(object) = implied_empty_tree_object(self.format, oid) {
            return Ok(object);
        }
        // A corrupt loose copy must not shadow a good packed copy: git's
        // `oid_object_info_extended` consults every source, so a repacked object
        // whose loose file was later corrupted still reads fine from the pack. If
        // a packed copy exists, prefer it WITHOUT touching the corrupt loose file
        // (which would otherwise emit a spurious `inflate:` diagnostic on each
        // probe). Only when no pack copy exists do we read (and, if corrupt,
        // surface the error from) the loose file.
        if let Some(pack_lookup) = self.find_pack_containing(oid)? {
            match self.read_packed_object_at_lookup(oid, &pack_lookup) {
                Ok(object) => return Ok(object),
                Err(GitError::NotFound(_)) => {}
                // A corrupt packed copy must not be fatal when another good copy
                // exists: git's `oid_object_info_extended` keeps consulting the
                // remaining sources (loose, other packs, alternates) when a pack
                // read fails. Fall through to the loose/other-pack probes and
                // only surface the packed error if every source comes up empty.
                Err(packed_err) => {
                    if let Ok(object) = self.loose.read_object(oid) {
                        return Ok(object);
                    }
                    // Try any *other* pack that also holds the object (a
                    // redundant copy survives one pack's corruption).
                    if let Some(object) =
                        self.read_packed_object_from_other_packs(oid, &pack_lookup)?
                    {
                        return Ok(object);
                    }
                    for alternate in &self.alternates {
                        if let Ok(object) =
                            Self::without_alternates(alternate, self.format).read_object(oid)
                        {
                            return Ok(object);
                        }
                    }
                    return Err(packed_err);
                }
            }
        }
        let loose_err = match self.loose.read_object(oid) {
            Ok(object) => return Ok(object),
            Err(GitError::NotFound(_)) => None,
            Err(err) => Some(err),
        };
        if let Some(object) = self.read_packed_object(oid)? {
            return Ok(object);
        }
        for alternate in &self.alternates {
            match Self::without_alternates(alternate, self.format).read_object(oid) {
                Ok(object) => return Ok(object),
                Err(GitError::NotFound(_)) => {}
                Err(err) => return Err(err),
            }
        }
        // Hard miss against every store. If an earlier enumeration built a loose
        // cache, an object written loose afterward by a sibling handle could have
        // been skipped above. Mirror git's `oid_object_info_extended`
        // reprepare-on-miss: drop stale cache state and retry an exact loose path
        // probe once before declaring the object missing.
        self.loose.invalidate_cache();
        match self.loose.read_object(oid) {
            Ok(object) => return Ok(object),
            Err(GitError::NotFound(_)) => {}
            Err(err) => return Err(err),
        }
        // No good copy in any store. If the local loose copy was corrupt (not
        // merely absent), surface that error — it is more specific than a plain
        // "not found".
        if let Some(err) = loose_err {
            return Err(err);
        }
        Err(GitError::object_not_found_in(
            *oid,
            MissingObjectContext::Read,
        ))
    }
}

impl FileObjectDatabase {
    fn promisor_objects(&self) -> &HashSet<ObjectId> {
        self.promisor_objects.get_or_init(|| {
            let mut promised =
                promisor_pack_object_ids(&self.objects_dir, self.format).unwrap_or_default();
            let mut pending = promised.iter().copied().collect::<Vec<_>>();
            while let Some(oid) = pending.pop() {
                let Ok(object) = self.read_object(&oid) else {
                    continue;
                };
                for link in promisor_object_links(self.format, &object) {
                    if promised.insert(link) {
                        pending.push(link);
                    }
                }
            }
            promised
        })
    }
}

fn promisor_pack_object_ids(objects_dir: &Path, format: ObjectFormat) -> Result<HashSet<ObjectId>> {
    let pack_dir = objects_dir.join("pack");
    let mut oids = HashSet::new();
    if !pack_dir.exists() {
        return Ok(oids);
    }
    for entry in fs::read_dir(pack_dir)? {
        let path = entry?.path();
        if path.extension().and_then(|ext| ext.to_str()) != Some("idx") {
            continue;
        }
        if !path.with_extension("pack").exists() || !path.with_extension("promisor").exists() {
            continue;
        }
        let index = PackIndex::parse(&fs::read(path)?, format)?;
        oids.extend(index.entries.into_iter().map(|entry| entry.oid));
    }
    Ok(oids)
}

fn promisor_object_links(format: ObjectFormat, object: &EncodedObject) -> Vec<ObjectId> {
    match object.object_type {
        ObjectType::Commit => Commit::parse_ref(format, &object.body)
            .map(|commit| {
                let mut links = Vec::with_capacity(commit.parents.len() + 1);
                links.push(commit.tree);
                links.extend(commit.parents);
                links
            })
            .unwrap_or_default(),
        ObjectType::Tree => TreeEntries::new(format, &object.body)
            .filter_map(|entry| entry.ok().map(|entry| entry.oid))
            .collect(),
        ObjectType::Tag => Tag::parse_ref(format, &object.body)
            .map(|tag| vec![tag.object])
            .unwrap_or_default(),
        ObjectType::Blob => Vec::new(),
    }
}

impl ObjectWriter for FileObjectDatabase {
    fn write_object(&self, object: EncodedObject) -> Result<ObjectId> {
        // Mirror git's freshen semantics (`write_object_file`:
        // `freshen_packed_object || freshen_loose_object`): an object already
        // present anywhere in the database — loose, packed, or through an
        // alternate — is not written again, so e.g. `git add` after
        // `git repack -ad` does not resurrect a loose copy of a packed object.
        let oid = object.object_id(self.format)?;
        if self.contains(&oid)? {
            return Ok(oid);
        }
        self.loose.write_object(object)
    }
}

fn write_pack_component(path: &Path, bytes: &[u8]) -> Result<()> {
    if path.exists() {
        return Ok(());
    }
    let parent = path
        .parent()
        .ok_or_else(|| GitError::InvalidPath("pack component path has no parent".into()))?;
    fs::create_dir_all(parent)?;
    let temp_path = unique_temp_path(parent);
    let write_result = (|| -> Result<()> {
        {
            let mut file = fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&temp_path)?;
            file.write_all(bytes)?;
            file.sync_all()?;
        }
        match fs::rename(&temp_path, path) {
            Ok(()) => Ok(()),
            Err(_) if path.exists() => {
                let _ = fs::remove_file(&temp_path);
                Ok(())
            }
            Err(err) => Err(GitError::Io(err.to_string())),
        }
    })();
    if write_result.is_err() {
        let _ = fs::remove_file(&temp_path);
    }
    write_result
}

fn write_promisor_pack_sidecar(
    pack_dir: &Path,
    pack_name: &str,
    promisor: bool,
) -> Result<Option<PathBuf>> {
    if !promisor {
        return Ok(None);
    }
    let path = pack_dir.join(format!("{pack_name}.promisor"));
    write_pack_component(&path, b"")?;
    Ok(Some(path))
}

/// Maximum number of bytes git will inflate when reading a loose object's
/// `"<type> <size>\0"` header (git's `MAX_HEADER_LEN` in object-file.c). The NUL
/// terminator must land within this window, so a header of 32 or more non-NUL
/// bytes is rejected as too long.
const MAX_LOOSE_HEADER_LEN: usize = 32;

/// git's exact `error:`-level diagnostic for a loose object whose header overflows
/// `MAX_LOOSE_HEADER_LEN` (object-file.c: `error(_("header for %s too long, exceeds
/// %d bytes"), ...)`). Shared by the header-only and full-read paths so both surface
/// byte-identical text.
fn loose_header_too_long(oid: &ObjectId) -> GitError {
    GitError::InvalidObject(format!(
        "header for {oid} too long, exceeds {MAX_LOOSE_HEADER_LEN} bytes"
    ))
}

/// git's `error:`-level diagnostic when the loose framing header cannot be inflated at
/// all (object-file.c `loose_object_info`, the `ULHR_BAD` arm: `error(_("unable to
/// unpack %s header"), ...)`).
fn loose_unpack_header_failed(oid: &ObjectId) -> GitError {
    GitError::InvalidObject(format!("unable to unpack {oid} header"))
}

/// git-zlib.c's `error("inflate: %s (%s)", ...)` text for an inflate failure whose
/// cause is identifiable from the zlib stream header. The checks mirror zlib's own
/// `inflate()` HEAD-state validation, in order: the FCHECK checksum over CMF+FLG,
/// the compression method, the window size, and the FDICT preset-dictionary bit
/// (zlib reports `Z_NEED_DICT` with a NULL `msg`, which git renders as
/// "(no message)"). Failures past the stream header return `None`: flate2 does not
/// surface zlib's per-case `msg` strings, so no diagnostic is fabricated for them.
fn inflate_header_diagnostic(input: &[u8]) -> Option<&'static str> {
    let [cmf, flg, ..] = *input else { return None };
    if ((u16::from(cmf) << 8) | u16::from(flg)) % 31 != 0 {
        return Some("inflate: data stream error (incorrect header check)");
    }
    if cmf & 0x0f != 8 {
        return Some("inflate: data stream error (unknown compression method)");
    }
    if cmf >> 4 > 7 {
        return Some("inflate: data stream error (invalid window size)");
    }
    if flg & 0x20 != 0 {
        return Some("inflate: needs dictionary (no message)");
    }
    None
}

/// Print the `error: inflate: ...` line git's zlib wrapper emits the moment
/// `inflate()` fails, when the failure is classifiable from the stream header.
fn emit_inflate_diagnostic(input: &[u8]) {
    if let Some(diagnostic) = inflate_header_diagnostic(input) {
        eprintln!("error: {diagnostic}");
    }
}

/// Integrity verdict for a single loose object file, as classified by
/// [`LooseObjectStore::verify_object`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LooseObjectIntegrity {
    /// Inflated, parsed, and re-hashed to its path-derived oid.
    Ok,
    /// Readable and well-formed, but its content hashes to a different oid
    /// (a loose file stored under the wrong path).
    HashMismatch { actual: ObjectId },
    /// Unreadable: corrupt zlib stream, truncated content, or unparseable header.
    /// The `error:`-level diagnostics were already printed to stderr.
    Corrupt,
}

#[derive(Debug, Clone)]
pub struct LooseObjectStore {
    objects_dir: PathBuf,
    format: ObjectFormat,
    /// Lazily-populated set of loose object ids present on disk, mirroring git's
    /// `loose_objects_cache` (object-file.c). A lookup scans the queried
    /// `objects/XX/` fanout once; afterward misses in that fanout are in-memory
    /// checks instead of failed exact-path opens. Shared across
    /// `FileObjectDatabase` clones via `Arc` so a write through one handle is
    /// visible to reads through another; cleared by `refresh_read_cache` so
    /// objects installed out-of-band (fetch, repack) become visible. Writes
    /// extend the set in place rather than invalidating it.
    loose_cache: Arc<Mutex<LoosePresenceCache>>,
}

impl LooseObjectStore {
    pub fn new(objects_dir: impl Into<PathBuf>, format: ObjectFormat) -> Self {
        Self {
            objects_dir: objects_dir.into(),
            format,
            loose_cache: Arc::new(Mutex::new(LoosePresenceCache::default())),
        }
    }

    /// Whether `oid` is present according to the loose-object cache, populating
    /// the cache on first use. Returns `None` when the lock cannot be trusted or
    /// the scan fails; callers should fall back to an exact filesystem probe in
    /// that case so a cache-building problem cannot change read semantics.
    fn cached_loose_presence(&self, oid: &ObjectId) -> Option<bool> {
        let mut guard = self.loose_cache.lock().ok()?;
        let fanout = oid.as_bytes()[0];
        if !guard.loaded_fanouts.contains(&fanout) {
            collect_loose_fanout_object_ids(
                &self.objects_dir,
                self.format,
                fanout,
                &mut guard.objects,
            )
            .ok()?;
            guard.loaded_fanouts.insert(fanout);
        }
        Some(guard.objects.contains(oid))
    }

    /// Populate the loose-object cache and return the sorted ids. This mirrors
    /// git's `odb_loose_cache` lazy fill and is reserved for operations that
    /// really need loose-object enumeration.
    fn loose_object_ids_cached(&self) -> Result<Vec<ObjectId>> {
        if let Ok(mut guard) = self.loose_cache.lock() {
            guard.objects = loose_object_id_set(&self.objects_dir, self.format)?;
            guard.loaded_fanouts = (0..=u8::MAX).collect();
            let mut ids = guard.objects.iter().copied().collect::<Vec<_>>();
            ids.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));
            return Ok(ids);
        }
        loose_object_ids(&self.objects_dir, self.format)
    }

    /// Record `oid` as present in loose storage so subsequent reads find it
    /// without a rescan. A no-op when the cache has not been populated yet (the
    /// eventual lazy scan will pick the object up) or the lock is poisoned.
    fn note_loose_write(&self, oid: ObjectId) {
        if let Ok(mut guard) = self.loose_cache.lock() {
            guard.objects.insert(oid);
        }
    }

    /// Drop the in-memory loose set so the next access rescans the fanout. Called
    /// by `FileObjectDatabase::refresh_read_cache` after out-of-band installs.
    pub(crate) fn invalidate_cache(&self) {
        if let Ok(mut guard) = self.loose_cache.lock() {
            *guard = LoosePresenceCache::default();
        }
    }

    pub fn from_git_dir(git_dir: impl AsRef<Path>, format: ObjectFormat) -> Self {
        Self::new(repository_objects_dir(git_dir), format)
    }

    fn validate_oid_format(&self, oid: &ObjectId) -> Result<()> {
        if oid.format() != self.format {
            return Err(GitError::InvalidObjectId(format!(
                "object {oid} uses {}, store uses {}",
                oid.format().name(),
                self.format.name()
            )));
        }
        Ok(())
    }

    pub fn object_path(&self, oid: &ObjectId) -> Result<PathBuf> {
        self.validate_oid_format(oid)?;
        let hex = oid.to_hex();
        Ok(self.objects_dir.join(&hex[..2]).join(&hex[2..]))
    }

    pub fn exists(&self, oid: &ObjectId) -> Result<bool> {
        self.validate_oid_format(oid)?;
        if self.cached_loose_presence(oid) == Some(false) {
            return Ok(false);
        }
        let path = self.object_path(oid)?;
        Ok(path.exists())
    }

    pub fn disk_size(&self, oid: &ObjectId) -> Result<Option<u64>> {
        self.validate_oid_format(oid)?;
        if self.cached_loose_presence(oid) == Some(false) {
            return Ok(None);
        }
        let path = self.object_path(oid)?;
        match fs::metadata(path) {
            Ok(metadata) => Ok(Some(metadata.len())),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(err) => Err(GitError::Io(err.to_string())),
        }
    }

    /// The object type and content size of `oid` from loose storage, inflating only
    /// the framing header (`"<type> <size>\0"`) and not the body. Output-limited
    /// reads keep miniz from inflating past the header even for large objects.
    /// Returns `Ok(None)` when the loose object is absent.
    pub fn read_header(&self, oid: &ObjectId) -> Result<Option<(ObjectType, u64)>> {
        self.validate_oid_format(oid)?;
        if self.cached_loose_presence(oid) == Some(false) {
            return Ok(None);
        }
        let path = self.object_path(oid)?;
        let compressed = match fs::read(&path) {
            Ok(compressed) => compressed,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(err) => return Err(GitError::Io(err.to_string())),
        };
        match inflate_loose_header(&compressed)? {
            LooseHeader::Ok(header) => {
                let header = std::str::from_utf8(&header)
                    .map_err(|err| GitError::InvalidObject(err.to_string()))?;
                let (kind, size) = header
                    .split_once(' ')
                    .ok_or_else(|| GitError::InvalidObject("missing object size".into()))?;
                let object_type = kind.parse::<ObjectType>()?;
                let size = size
                    .parse::<u64>()
                    .map_err(|_| GitError::InvalidObject("invalid object size".into()))?;
                Ok(Some((object_type, size)))
            }
            LooseHeader::Bad => {
                // git's ULHR_BAD: the zlib wrapper's `error: inflate: ...` line, then
                // "unable to unpack <oid> header".
                emit_inflate_diagnostic(compressed.get(..2).unwrap_or(&compressed));
                Err(loose_unpack_header_failed(oid))
            }
            LooseHeader::TooLong => {
                // git inflates only the first `MAX_LOOSE_HEADER_LEN` bytes
                // (object-file.c `unpack_loose_header`) and reports ULHR_TOO_LONG when
                // no NUL terminator lands within them — whether the stream simply ends
                // early or overflows the window. Both collapse to the same diagnostic.
                Err(loose_header_too_long(oid))
            }
        }
    }

    /// Loose object ids in this store, sorted by hex.
    pub fn object_ids(&self) -> Result<Vec<ObjectId>> {
        self.loose_object_ids_cached()
    }

    /// fsck's loose-object integrity probe, mirroring C git's `read_loose_object`
    /// (object-file.c) as called from `fsck_loose` (builtin/fsck.c): inflate and
    /// parse the file at `oid`'s loose path, then re-hash its content against the
    /// path-derived oid. `display_path` appears verbatim in the `error:`-level
    /// diagnostics — the path-form messages of `read_loose_object` ("unable to
    /// unpack header of <path>"), unlike the oid-form messages of the normal read
    /// path. Returns `Ok(None)` when no loose file exists for `oid`.
    pub fn verify_object(
        &self,
        oid: &ObjectId,
        display_path: &str,
    ) -> Result<Option<LooseObjectIntegrity>> {
        let path = self.object_path(oid)?;
        let compressed = match fs::read(&path) {
            Ok(compressed) => compressed,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(err) => return Err(GitError::Io(err.to_string())),
        };
        let mut decoder = ZlibDecoder::new(compressed.as_slice());
        let mut framed = Vec::new();
        if decoder.read_to_end(&mut framed).is_err() {
            emit_inflate_diagnostic(&compressed);
            // git inflates the header first (`unpack_loose_header`), then the body
            // (`unpack_loose_rest`). If the header inflated (its NUL is visible in
            // the partial output) but the body broke, that is a *content*
            // corruption: git's `unpack_loose_rest` prints `corrupt loose object
            // '<oid>'` (status != Z_STREAM_END), then `read_loose_object` adds
            // `unable to unpack contents of <path>`. If inflation died before the
            // header materialized, only the header message fires.
            if framed_loose_header_terminated(&framed) {
                eprintln!("error: corrupt loose object '{oid}'");
                eprintln!("error: unable to unpack contents of {display_path}");
            } else {
                eprintln!("error: unable to unpack header of {display_path}");
            }
            return Ok(Some(LooseObjectIntegrity::Corrupt));
        }
        if !framed_loose_header_terminated(&framed) {
            // ULHR_TOO_LONG collapses into the same path-form message here: C's
            // `read_loose_object` treats every non-OK `unpack_loose_header` alike.
            eprintln!("error: unable to unpack header of {display_path}");
            return Ok(Some(LooseObjectIntegrity::Corrupt));
        }
        // git's `unpack_loose_rest`/`check_stream_oid` reject trailing bytes after
        // the zlib stream: a fully-inflated object whose compressed input was not
        // entirely consumed is `garbage at end of loose object '<oid>'`, then
        // `object corrupt or missing: <path>` from `fsck_loose`. (read_to_end
        // stops at Z_STREAM_END and silently ignores the trailing bytes, so we
        // compare consumed input against the file size ourselves.)
        if (decoder.total_in() as usize) < compressed.len() {
            // git's `unpack_loose_rest` prints `garbage at end of loose object`
            // then returns NULL, so `read_loose_object` also prints `unable to
            // unpack contents of <path>`.
            eprintln!("error: garbage at end of loose object '{oid}'");
            eprintln!("error: unable to unpack contents of {display_path}");
            return Ok(Some(LooseObjectIntegrity::Corrupt));
        }
        // A truncated object can inflate to a clean stream end yet yield fewer
        // body bytes than the header's declared size. git's `unpack_loose_rest`
        // inflates exactly `size` bytes and, finding the stream ends short,
        // prints `corrupt loose object '<oid>'`; `read_loose_object` then adds
        // `unable to unpack contents of <path>`. Detect the short body here so it
        // is not misreported as a header-parse failure.
        if let Some(declared) = loose_header_declared_size(&framed) {
            let nul = framed.iter().position(|&b| b == 0).unwrap_or(framed.len());
            let body_len = framed.len() - (nul + 1).min(framed.len());
            if body_len < declared {
                eprintln!("error: corrupt loose object '{oid}'");
                eprintln!("error: unable to unpack contents of {display_path}");
                return Ok(Some(LooseObjectIntegrity::Corrupt));
            }
        }
        let Ok(object) = parse_framed_object(&framed) else {
            // Distinguish git's two header-parse failures: a structurally valid
            // `"<word> <size>\0"` header whose *type word* is not a known object
            // type yields `unable to parse type from header '<header>'`, while a
            // genuinely malformed header yields `unable to parse header`.
            if let Some(header) = loose_header_with_unknown_type(&framed) {
                eprintln!("error: unable to parse type from header '{header}' of {display_path}");
            } else {
                eprintln!("error: unable to parse header of {display_path}");
            }
            return Ok(Some(LooseObjectIntegrity::Corrupt));
        };
        let actual = object.object_id(self.format)?;
        if &actual != oid {
            return Ok(Some(LooseObjectIntegrity::HashMismatch { actual }));
        }
        Ok(Some(LooseObjectIntegrity::Ok))
    }
}

/// Whether the inflated framing bytes contain the header's NUL terminator within
/// git's `MAX_HEADER_LEN` window (object-file.c `unpack_loose_header`'s success
/// condition).
fn framed_loose_header_terminated(framed: &[u8]) -> bool {
    framed
        .iter()
        .take(MAX_LOOSE_HEADER_LEN)
        .any(|byte| *byte == 0)
}

/// If the framing has a structurally valid `"<word> <size>\0"` header whose body
/// length matches `<size>` but whose `<word>` is not a known object type, return
/// the header string (the bytes before the NUL). Mirrors git's
/// `parse_loose_header` reporting `unable to parse type from header '<header>'`.
fn loose_header_with_unknown_type(framed: &[u8]) -> Option<String> {
    let nul = framed.iter().position(|&b| b == 0)?;
    let header = std::str::from_utf8(&framed[..nul]).ok()?;
    let (kind, size) = header.split_once(' ')?;
    let size: usize = size.parse().ok()?;
    // Body length must match the declared size (otherwise it is a different
    // corruption, handled by the generic path).
    if framed.len() - (nul + 1) != size {
        return None;
    }
    // A known type word would have parsed successfully upstream; only return
    // when the word is genuinely unknown.
    if kind.parse::<ObjectType>().is_ok() {
        return None;
    }
    Some(header.to_string())
}

/// The size declared in a loose object's `"<type> <size>\0"` header, if the
/// header is structurally a `<word> <decimal-size>` pair. Used to detect a body
/// inflated short of its declared length (a truncated object).
fn loose_header_declared_size(framed: &[u8]) -> Option<usize> {
    let nul = framed.iter().position(|&b| b == 0)?;
    let header = std::str::from_utf8(&framed[..nul]).ok()?;
    let (_kind, size) = header.split_once(' ')?;
    size.parse::<usize>().ok()
}

/// Read up to `prefix.len()` bytes from the start of `file`, returning how many
/// were available (short only when the file itself is shorter).
/// Outcome of inflating a loose object's header, mirroring git's
/// `unpack_loose_header` result codes (object-file.c `enum
/// unpack_loose_header_result`).
enum LooseHeader {
    /// ULHR_OK: a NUL-terminated header was found within the window. Carries the
    /// header bytes up to (not including) the NUL.
    Ok(Vec<u8>),
    /// ULHR_BAD: the zlib stream would not inflate (status != Z_OK/Z_STREAM_END).
    Bad,
    /// ULHR_TOO_LONG: the inflated output filled the header window with no NUL.
    TooLong,
}

/// Inflate a loose object's *header* exactly as git's `unpack_loose_header` does
/// (object-file.c): a single bounded inflate into a `MAX_LOOSE_HEADER_LEN`-byte
/// output buffer, then look for the header-terminating NUL in what came out.
///
/// The byte budget is load-bearing for corruption parity: git inflates only up to
/// `MAX_HEADER_LEN` (32) bytes of *output* before stopping, so a `cat-file -s`/`-t`
/// header read detects a zlib data error only when it lands within those first 32
/// inflated bytes (the header plus the start of the body for a small object) — and
/// silently returns the header for corruption buried deeper in the body, which the
/// full-object read path catches instead. A byte-by-byte loop that stopped at the
/// NUL would never inflate into the corrupt region and miss the bit-error case
/// (t1060 "getting type of a corrupt blob fails"); feeding too much output budget
/// would over-detect relative to git. So this matches git's exact window.
fn inflate_loose_header(compressed: &[u8]) -> Result<LooseHeader> {
    let mut out = [0u8; MAX_LOOSE_HEADER_LEN];
    let mut decompress = Decompress::new(true);
    // git feeds the whole mapped file as `avail_in` and inflates once into a
    // 32-byte `avail_out`; zlib stops at the output limit (Z_OK with avail_out==0)
    // or at the stream's end, propagating Z_DATA_ERROR for a corrupt stream.
    let status = decompress.decompress(compressed, &mut out, FlushDecompress::None);
    let produced = decompress.total_out() as usize;
    match status {
        Ok(_) => {
            let window = &out[..produced.min(MAX_LOOSE_HEADER_LEN)];
            match window.iter().position(|&byte| byte == 0) {
                Some(nul) => Ok(LooseHeader::Ok(window[..nul].to_vec())),
                // No NUL within the window: either the stream ended early or the
                // header overflows `MAX_LOOSE_HEADER_LEN`. git collapses both into
                // ULHR_TOO_LONG (object-file.c `unpack_loose_header`).
                None => Ok(LooseHeader::TooLong),
            }
        }
        // Any zlib error before a NUL materializes is git's ULHR_BAD.
        Err(_) => Ok(LooseHeader::Bad),
    }
}

impl ObjectReader for LooseObjectStore {
    fn read_object(&self, oid: &ObjectId) -> Result<Arc<EncodedObject>> {
        self.validate_oid_format(oid)?;
        // Skip the `open()` (and its ENOENT) when an already-built loose cache
        // knows the id is absent. Without a cache, use an exact path probe; a
        // full fanout scan is far more expensive for one-shot packed-object reads.
        if self.cached_loose_presence(oid) == Some(false) {
            return Err(GitError::object_not_found_in(
                *oid,
                MissingObjectContext::Read,
            ));
        }
        let path = self.object_path(oid)?;
        let compressed = match fs::read(&path) {
            Ok(compressed) => compressed,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                return Err(GitError::object_not_found_in(
                    *oid,
                    MissingObjectContext::Read,
                ));
            }
            Err(err) => return Err(GitError::Io(err.to_string())),
        };
        let mut decoder = ZlibDecoder::new(compressed.as_slice());
        let mut framed = Vec::new();
        if decoder.read_to_end(&mut framed).is_err() {
            emit_inflate_diagnostic(&compressed);
            // A stream that dies before the framing header materializes is git's
            // ULHR_BAD ("unable to unpack <oid> header"); with the header intact,
            // the body is what broke (`unpack_loose_rest`'s "corrupt loose
            // object").
            if !framed_loose_header_terminated(&framed) {
                return Err(loose_unpack_header_failed(oid));
            }
            return Err(GitError::InvalidObject(format!(
                "corrupt loose object '{oid}'"
            )));
        }
        // git only inflates the first `MAX_LOOSE_HEADER_LEN` bytes looking for the
        // header's NUL terminator before parsing the type; an over-long header is
        // rejected here (with git's diagnostic) rather than failing later as an
        // "unknown object type". Mirror that so `cat-file -p` matches upstream.
        if framed
            .iter()
            .take(MAX_LOOSE_HEADER_LEN)
            .all(|byte| *byte != 0)
        {
            return Err(loose_header_too_long(oid));
        }
        let object = parse_framed_object(&framed)?;
        // Trust the loose object's on-disk name rather than re-hashing its full body
        // on every read (see `verify_reads_enabled`); use `validate`/fsck or
        // `SLEY_VERIFY_READS` for an explicit integrity check.
        if verify_reads_enabled() {
            let actual = object.object_id(self.format)?;
            if &actual != oid {
                return Err(GitError::InvalidObject(format!(
                    "loose object {} hashes to {actual}",
                    path.display()
                )));
            }
        }
        Ok(Arc::new(object))
    }
}

impl ObjectWriter for LooseObjectStore {
    fn write_object(&self, object: EncodedObject) -> Result<ObjectId> {
        let oid = object.object_id(self.format)?;
        let path = self.object_path(&oid)?;
        if path.exists() {
            self.note_loose_write(oid);
            return Ok(oid);
        }
        let parent = path
            .parent()
            .ok_or_else(|| GitError::InvalidPath("loose object path has no parent".into()))?;
        fs::create_dir_all(parent)?;
        let temp_path = unique_temp_path(parent);
        let write_result = (|| -> Result<()> {
            let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
            encoder.write_all(&object.framed_bytes())?;
            let compressed = encoder.finish()?;
            {
                let mut file = fs::OpenOptions::new()
                    .write(true)
                    .create_new(true)
                    .open(&temp_path)?;
                file.write_all(&compressed)?;
                // No fsync: git's default `core.fsync=none` fsyncs nothing on the
                // loose-object write path (object-file.c writes the temp file and
                // renames it without syncing unless `core.fsync` names
                // `loose-object`/`objects`/`all`, which it does not by default).
                // A per-object sync_all() here made `git add` of N files cost N
                // fsyncs — the dominant term in sley#27's 10x `add -u` slowdown —
                // for durability git itself does not provide by default. The
                // create_new temp + atomic rename below still guarantees the
                // object never appears half-written under its final name.
            }
            match fs::rename(&temp_path, &path) {
                Ok(()) => Ok(()),
                Err(_) if path.exists() => {
                    let _ = fs::remove_file(&temp_path);
                    Ok(())
                }
                Err(err) => Err(GitError::Io(err.to_string())),
            }
        })();
        if write_result.is_err() {
            let _ = fs::remove_file(&temp_path);
        }
        write_result?;
        self.note_loose_write(oid);
        Ok(oid)
    }
}

fn unique_temp_path(parent: &Path) -> PathBuf {
    let id = TEMPFILE_COUNTER.fetch_add(1, Ordering::Relaxed);
    parent.join(format!("tmp_obj_{}_{}", std::process::id(), id))
}

#[cfg(test)]
mod tests {
    use super::*;
    use sley_core::BString;
    use sley_object::{Commit, EncodedObject, ObjectType, Tag, Tree, TreeEntry};
    use sley_pack::{PackFile, PackWriteOptions};

    fn blob_of(byte: u8, len: usize) -> EncodedObject {
        EncodedObject::new(ObjectType::Blob, vec![byte; len])
    }

    fn cached_blob_of(byte: u8, len: usize) -> Arc<EncodedObject> {
        Arc::new(blob_of(byte, len))
    }

    fn read_object_for_assert(reader: &impl ObjectReader, oid: &ObjectId) -> EncodedObject {
        reader
            .read_object(oid)
            .expect("test operation should succeed")
            .as_ref()
            .clone()
    }

    #[test]
    fn lru_cache_evicts_by_byte_budget_least_recently_used_first() {
        // Budget holds two ~1 KiB objects but not three.
        let one = cached_object_cost(&blob_of(0, 1000));
        let mut cache = LruCache::<u32>::new(one * 2 + 8);
        cache.put(1, cached_blob_of(b'a', 1000));
        cache.put(2, cached_blob_of(b'b', 1000));
        // Touch key 1 so key 2 becomes least-recently-used.
        assert!(cache.get(&1).is_some());
        cache.put(3, cached_blob_of(b'c', 1000));
        // Key 2 (LRU) is evicted; 1 and 3 remain.
        assert!(cache.get(&1).is_some());
        assert!(cache.get(&2).is_none());
        assert!(cache.get(&3).is_some());
    }

    #[test]
    fn lru_cache_zero_budget_is_inert() {
        let mut cache = LruCache::<u32>::new(0);
        cache.put(1, cached_blob_of(b'a', 16));
        assert!(cache.get(&1).is_none());
    }

    #[test]
    fn lru_cache_skips_object_larger_than_budget_and_clears_stale_entry() {
        let mut cache = LruCache::<u32>::new(cached_object_cost(&blob_of(0, 100)));
        cache.put(1, cached_blob_of(b'a', 50));
        assert!(cache.get(&1).is_some());
        // An object that cannot fit is not cached, and it evicts the prior entry
        // stored under the same key (so we never serve a stale value for it).
        cache.put(1, cached_blob_of(b'b', 10_000));
        assert!(cache.get(&1).is_none());
        // A subsequent fitting insert under another key still works and accounting
        // is not corrupted by the oversized insert.
        cache.put(2, cached_blob_of(b'c', 50));
        assert!(cache.get(&2).is_some());
    }

    #[test]
    fn lru_cache_replacing_entry_updates_byte_accounting() {
        // Budget holds two 500-byte objects (plus headroom) but not a 500 + a
        // ~1900-byte object.
        let small = cached_object_cost(&blob_of(0, 500));
        let mut cache = LruCache::<u32>::new(small * 2 + 200);
        cache.put(1, cached_blob_of(b'a', 500));
        cache.put(2, cached_blob_of(b'b', 500));
        assert!(cache.get(&1).is_some());
        assert!(cache.get(&2).is_some());
        // Replace key 2 (now MRU after the gets above re-ordered 1 then 2) with a
        // bigger value that still fits the budget alone but makes the running total
        // exceed it; the LRU (key 1) is evicted while the replaced key 2 stays.
        // This exercises the replace-path accounting.
        cache.put(2, cached_blob_of(b'b', 1000));
        assert!(cache.get(&2).is_some());
        assert!(cache.get(&1).is_none());
    }

    #[test]
    fn write_and_validate_blob() {
        let db = ObjectDatabase::new(ObjectFormat::Sha1);
        let oid = db
            .write_object(EncodedObject::new(ObjectType::Blob, b"hello\n".to_vec()))
            .expect("test operation should succeed");
        assert_eq!(oid.to_hex(), "ce013625030ba8dba906f756967f9e9ca394464a");
        db.validate(&oid).expect("test operation should succeed");
    }

    #[test]
    fn loose_store_writes_and_reads_object() {
        let root = std::env::temp_dir().join(format!(
            "sley-loose-store-{}-{}",
            std::process::id(),
            TEMPFILE_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let store = LooseObjectStore::new(root.join("objects"), ObjectFormat::Sha1);
        let object = EncodedObject::new(ObjectType::Blob, b"hello\n".to_vec());
        let oid = store
            .write_object(object.clone())
            .expect("test operation should succeed");
        assert_eq!(read_object_for_assert(&store, &oid), object);
        assert!(
            store
                .object_path(&oid)
                .expect("test operation should succeed")
                .exists()
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn read_header_detects_corruption_within_gits_header_window() {
        // git's `unpack_loose_header` inflates only the first MAX_HEADER_LEN (32)
        // bytes of output; a zlib data error inside that window makes `cat-file
        // -s`/`-t` fail (ULHR_BAD → "unable to unpack header"). A byte-by-byte
        // header read that stopped at the NUL would never inflate into the corrupt
        // region and would silently return a bogus size — the t1060 "getting type
        // of a corrupt blob fails" bug. Corrupt a byte inside the inflate stream of
        // a tiny object so the damage lands within the first 32 inflated bytes.
        let root = temp_root("sley-loose-header-corrupt");
        let store = LooseObjectStore::new(root.join("objects"), ObjectFormat::Sha1);
        let object = EncodedObject::new(ObjectType::Blob, b"content\n".to_vec());
        let oid = store
            .write_object(object)
            .expect("test operation should succeed");
        let path = store
            .object_path(&oid)
            .expect("test operation should succeed");
        let mut bytes = fs::read(&path).expect("test operation should succeed");
        // Offset 10 is inside the deflate stream (past the 2-byte zlib header) and,
        // for an 8-byte blob, decodes into the first 32 output bytes. Zero it to
        // break inflation, mirroring t1060's `corrupt_byte HEAD:content.t 10`.
        bytes[10] = 0;
        fs::write(&path, &bytes).expect("test operation should succeed");
        store.invalidate_cache();
        let err = store
            .read_header(&oid)
            .expect_err("corrupt loose header must fail like git's ULHR_BAD");
        let msg = err.to_string();
        assert!(
            msg.contains("unable to unpack") && msg.contains(&oid.to_hex()),
            "expected git's ULHR_BAD message, got: {msg}"
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn read_header_ignores_corruption_past_gits_header_window() {
        // Mirror git: corruption deeper than the 32-byte header window is NOT
        // detected by a header-only read (`cat-file -s` still returns the size);
        // the full-object read path catches it instead. Over-detecting here would
        // diverge from upstream on large objects with a clean header.
        let root = temp_root("sley-loose-header-deep-corrupt");
        let store = LooseObjectStore::new(root.join("objects"), ObjectFormat::Sha1);
        // Incompressible body so the deflate stream is long and a deep byte is well
        // past the 32 inflated header-window bytes.
        let body: Vec<u8> = (0..4096u32)
            .map(|i| (i.wrapping_mul(2654435761)) as u8)
            .collect();
        let object = EncodedObject::new(ObjectType::Blob, body.clone());
        let oid = store
            .write_object(object)
            .expect("test operation should succeed");
        let path = store
            .object_path(&oid)
            .expect("test operation should succeed");
        let mut bytes = fs::read(&path).expect("test operation should succeed");
        let deep = bytes.len() / 2;
        bytes[deep] ^= 0xff;
        fs::write(&path, &bytes).expect("test operation should succeed");
        store.invalidate_cache();
        let header = store
            .read_header(&oid)
            .expect("header-only read must still succeed for deep body corruption");
        assert_eq!(header, Some((ObjectType::Blob, body.len() as u64)));
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_reads_object_from_pack_index() {
        let root = temp_root("sley-file-odb-pack");
        let git_dir = root.join(".git");
        let pack_dir = git_dir.join("objects").join("pack");
        fs::create_dir_all(&pack_dir).expect("test operation should succeed");
        let object = EncodedObject::new(ObjectType::Blob, b"packed\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let written = PackFile::write_undeltified_sha1(std::slice::from_ref(&object))
            .expect("test operation should succeed");
        let pack_name = written.checksum.to_hex();
        fs::write(
            pack_dir.join(format!("pack-{pack_name}.pack")),
            written.pack,
        )
        .expect("test operation should succeed");
        fs::write(
            pack_dir.join(format!("pack-{pack_name}.idx")),
            written.index,
        )
        .expect("test operation should succeed");

        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);
        assert!(db.contains(&oid).expect("test operation should succeed"));
        assert_eq!(read_object_for_assert(&db, &oid), object);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_loose_cache_observes_same_process_write_after_miss() {
        let root = temp_root("sley-file-odb-loose-cache-write");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);

        let object = EncodedObject::new(ObjectType::Blob, b"written after miss\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");

        assert!(matches!(db.read_object(&oid), Err(GitError::NotFound(_))));
        db.loose()
            .write_object(object.clone())
            .expect("test operation should succeed");

        assert_eq!(read_object_for_assert(&db, &oid), object);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn object_presence_checker_observes_same_process_loose_write_after_miss() {
        let root = temp_root("sley-presence-checker-loose-cache-write");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);
        let mut checker = db.presence_checker();

        let object = EncodedObject::new(ObjectType::Blob, b"checker loose after miss\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");

        assert!(
            !checker
                .contains(&oid)
                .expect("test operation should succeed")
        );
        db.loose()
            .write_object(object)
            .expect("test operation should succeed");

        assert!(
            checker
                .contains(&oid)
                .expect("test operation should succeed")
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn read_object_header_matches_full_read_for_loose_and_packed_and_delta() {
        let root = temp_root("sley-read-object-header");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let db = FileObjectDatabase::from_git_dir(&git_dir, format);

        // Loose object: the header read inflates only the framing, not the body.
        let loose = EncodedObject::new(ObjectType::Blob, b"loose header object\n".to_vec());
        let loose_oid = db
            .write_object(loose.clone())
            .expect("test operation should succeed");

        // Packed objects, including an ofs-delta whose *result* size lives in the
        // delta stream (not the pack entry header) and whose type is inherited from
        // its base at the end of the chain.
        let base = EncodedObject::new(ObjectType::Blob, vec![b'a'; 4096]);
        let mut child_body = vec![b'a'; 4096];
        child_body.extend_from_slice(b" plus a deltified tail\n");
        let child = EncodedObject::new(ObjectType::Blob, child_body);
        let commitish =
            EncodedObject::new(ObjectType::Commit, b"header-only type probe\n".to_vec());
        let base_oid = base
            .object_id(format)
            .expect("test operation should succeed");
        let child_oid = child
            .object_id(format)
            .expect("test operation should succeed");
        let commit_oid = commitish
            .object_id(format)
            .expect("test operation should succeed");
        let options = PackWriteOptions::new()
            .with_prefer_ofs_delta(true)
            .with_reorder(false);
        let pack = PackFile::write_packed_with_options(
            &[base.clone(), child.clone(), commitish.clone()],
            format,
            &options,
        )
        .expect("test operation should succeed");
        db.install_pack(&pack)
            .expect("test operation should succeed");

        // The header read agrees with a full decode for every object and storage
        // class, without ever materializing the body.
        for (oid, want_type, want_len) in [
            (&loose_oid, ObjectType::Blob, loose.body.len()),
            (&base_oid, ObjectType::Blob, base.body.len()),
            (&child_oid, ObjectType::Blob, child.body.len()),
            (&commit_oid, ObjectType::Commit, commitish.body.len()),
        ] {
            assert_eq!(
                db.read_object_header(oid)
                    .expect("test operation should succeed"),
                Some((want_type, want_len as u64)),
                "header for {oid}"
            );
            let full = db.read_object(oid).expect("test operation should succeed");
            assert_eq!(
                db.read_object_header(oid)
                    .expect("test operation should succeed"),
                Some((full.object_type, full.body.len() as u64))
            );
        }

        let missing = ObjectId::from_hex(format, "0000000000000000000000000000000000000001")
            .expect("test operation should succeed");
        assert_eq!(
            db.read_object_header(&missing)
                .expect("test operation should succeed"),
            None
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn object_storage_info_reports_loose_packed_and_delta_metadata() {
        let root = temp_root("sley-object-storage-info");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let db = FileObjectDatabase::from_git_dir(&git_dir, format);

        let loose = EncodedObject::new(ObjectType::Blob, b"loose storage object\n".to_vec());
        let loose_oid = db
            .write_object(loose)
            .expect("test operation should succeed");
        let loose_size = fs::metadata(
            db.loose()
                .object_path(&loose_oid)
                .expect("test operation should succeed"),
        )
        .expect("test operation should succeed")
        .len();
        let loose_info = db
            .object_storage_info(&loose_oid)
            .expect("test operation should succeed")
            .expect("test operation should succeed");
        assert_eq!(loose_info.disk_size, loose_size);
        assert_eq!(
            loose_info.deltabase,
            zero_oid(format).expect("test operation should succeed")
        );

        let base = EncodedObject::new(ObjectType::Blob, vec![b'a'; 4096]);
        let mut child_body = vec![b'a'; 4096];
        child_body.extend_from_slice(b" changed tail\n");
        let child = EncodedObject::new(ObjectType::Blob, child_body);
        let base_oid = base
            .object_id(format)
            .expect("test operation should succeed");
        let child_oid = child
            .object_id(format)
            .expect("test operation should succeed");
        let options = PackWriteOptions::new()
            .with_prefer_ofs_delta(true)
            .with_reorder(false);
        let pack = PackFile::write_packed_with_options(&[base, child], format, &options)
            .expect("test operation should succeed");
        db.install_pack(&pack)
            .expect("test operation should succeed");

        let base_info = db
            .object_storage_info(&base_oid)
            .expect("test operation should succeed")
            .expect("test operation should succeed");
        assert!(base_info.disk_size > 0);
        assert_eq!(
            base_info.deltabase,
            zero_oid(format).expect("test operation should succeed")
        );

        let child_info = db
            .object_storage_info(&child_oid)
            .expect("test operation should succeed")
            .expect("test operation should succeed");
        assert!(child_info.disk_size > 0);
        assert_eq!(child_info.deltabase, base_oid);

        let missing = ObjectId::from_hex(format, "0000000000000000000000000000000000000001")
            .expect("test operation should succeed");
        assert_eq!(
            db.object_storage_info(&missing)
                .expect("test operation should succeed"),
            None
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_resolves_unique_loose_object_prefix() {
        let root = temp_root("sley-file-odb-prefix-loose");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);
        let object = EncodedObject::new(ObjectType::Blob, b"prefix loose\n".to_vec());
        let oid = db
            .write_object(object)
            .expect("test operation should succeed");
        let prefix = &oid.to_hex()[..8];

        assert_eq!(
            db.resolve_prefix(prefix)
                .expect("test operation should succeed"),
            ObjectPrefixResolution::Unique(oid)
        );
        assert!(
            db.object_ids()
                .expect("test operation should succeed")
                .contains(&oid)
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_resolves_unique_packed_object_prefix() {
        let root = temp_root("sley-file-odb-prefix-packed");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);
        let object = EncodedObject::new(ObjectType::Blob, b"prefix packed\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&object))
            .expect("test operation should succeed");
        db.install_pack(&pack)
            .expect("test operation should succeed");
        let prefix = &oid.to_hex()[..8];

        assert_eq!(
            db.resolve_prefix(prefix)
                .expect("test operation should succeed"),
            ObjectPrefixResolution::Unique(oid)
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_reports_ambiguous_object_prefix() {
        let root = temp_root("sley-file-odb-prefix-ambiguous");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);
        let mut seen = HashMap::new();
        let (prefix, first, second) = (0..10_000)
            .find_map(|idx| {
                let object =
                    EncodedObject::new(ObjectType::Blob, format!("ambiguous {idx}\n").into_bytes());
                let oid = db
                    .write_object(object)
                    .expect("test operation should succeed");
                let prefix = oid.to_hex()[..4].to_string();
                seen.insert(prefix.clone(), oid)
                    .map(|first| (prefix, first, oid))
            })
            .expect("test should find a 4-hex collision");

        let ObjectPrefixResolution::Ambiguous(mut matches) = db
            .resolve_prefix(&prefix)
            .expect("test operation should succeed")
        else {
            panic!("expected ambiguous prefix {prefix}");
        };
        matches.sort_by_key(ObjectId::to_hex);
        let mut expected = vec![first, second];
        expected.sort_by_key(ObjectId::to_hex);
        assert_eq!(matches, expected);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_rejects_too_short_object_prefix() {
        let root = temp_root("sley-file-odb-prefix-short");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);

        assert!(matches!(
            db.resolve_prefix("abc"),
            Err(GitError::InvalidObjectId(_))
        ));
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_reads_sha256_object_from_pack_index() {
        let root = temp_root("sley-file-odb-pack-sha256");
        let git_dir = root.join(".git");
        let pack_dir = git_dir.join("objects").join("pack");
        fs::create_dir_all(&pack_dir).expect("test operation should succeed");
        let object = EncodedObject::new(ObjectType::Blob, b"packed sha256\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha256)
            .expect("test operation should succeed");
        let written =
            PackFile::write_undeltified(std::slice::from_ref(&object), ObjectFormat::Sha256)
                .expect("test operation should succeed");
        let pack_name = written.checksum.to_hex();
        fs::write(
            pack_dir.join(format!("pack-{pack_name}.pack")),
            written.pack,
        )
        .expect("test operation should succeed");
        fs::write(
            pack_dir.join(format!("pack-{pack_name}.idx")),
            written.index,
        )
        .expect("test operation should succeed");

        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha256);
        assert!(db.contains(&oid).expect("test operation should succeed"));
        assert_eq!(read_object_for_assert(&db, &oid), object);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_installs_sha256_pack_without_loose_objects() {
        let root = temp_root("sley-file-odb-install-pack");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let object = EncodedObject::new(ObjectType::Blob, b"installed sha256 pack\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha256)
            .expect("test operation should succeed");
        let pack = PackFile::write_undeltified(std::slice::from_ref(&object), ObjectFormat::Sha256)
            .expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha256);

        let result = db
            .install_pack(&pack)
            .expect("test operation should succeed");

        assert_eq!(result.pack_name, format!("pack-{}", pack.checksum.to_hex()));
        assert_eq!(result.object_ids, vec![oid]);
        assert!(result.pack_path.exists());
        assert!(result.index_path.exists());
        assert_eq!(result.promisor_path, None);
        assert!(
            !db.loose()
                .object_path(&oid)
                .expect("test operation should succeed")
                .exists()
        );
        assert!(db.contains(&oid).expect("test operation should succeed"));
        assert_eq!(read_object_for_assert(&db, &oid), object);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_installs_raw_sha256_pack_without_loose_objects() {
        let root = temp_root("sley-file-odb-install-raw-pack");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let object = EncodedObject::new(ObjectType::Blob, b"installed raw sha256 pack\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha256)
            .expect("test operation should succeed");
        let pack = PackFile::write_undeltified(std::slice::from_ref(&object), ObjectFormat::Sha256)
            .expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha256);

        let result = db
            .install_raw_pack(&pack.pack)
            .expect("test operation should succeed");

        assert_eq!(result.pack_name, format!("pack-{}", pack.checksum.to_hex()));
        assert_eq!(result.object_ids, vec![oid]);
        assert!(result.pack_path.exists());
        assert!(result.index_path.exists());
        assert_eq!(result.promisor_path, None);
        assert!(
            !db.loose()
                .object_path(&oid)
                .expect("test operation should succeed")
                .exists()
        );
        assert!(db.contains(&oid).expect("test operation should succeed"));
        assert_eq!(read_object_for_assert(&db, &oid), object);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_rejects_noncanonical_pack_index() {
        let root = temp_root("sley-file-odb-install-bad-index");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let object = EncodedObject::new(ObjectType::Blob, b"bad index crc\n".to_vec());
        let pack = PackFile::write_undeltified(std::slice::from_ref(&object), ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let mut entries = pack.entries.clone();
        entries[0].crc32 ^= 1;
        let mut bad_pack = pack.clone();
        bad_pack.index = PackIndex::write_v2(ObjectFormat::Sha1, &entries, &pack.checksum)
            .expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);

        assert!(db.install_pack(&bad_pack).is_err());

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_installs_raw_promisor_pack_with_sidecar() {
        let root = temp_root("sley-file-odb-install-raw-promisor-pack");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let object = EncodedObject::new(ObjectType::Blob, b"installed promisor pack\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let pack = PackFile::write_undeltified(std::slice::from_ref(&object), ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);

        let result = db
            .install_raw_pack_with_options(&pack.pack, RawPackInstallOptions { promisor: true })
            .expect("test operation should succeed");

        let promisor_path = result.promisor_path.expect("promisor sidecar");
        assert_eq!(promisor_path.file_stem(), result.pack_path.file_stem());
        assert_eq!(
            promisor_path.extension().and_then(|ext| ext.to_str()),
            Some("promisor")
        );
        assert!(promisor_path.exists());
        assert_eq!(
            fs::read(&promisor_path).expect("test operation should succeed"),
            b""
        );
        assert!(result.pack_path.exists());
        assert!(result.index_path.exists());
        assert!(
            !db.loose()
                .object_path(&oid)
                .expect("test operation should succeed")
                .exists()
        );
        assert_eq!(read_object_for_assert(&db, &oid), object);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn repository_objects_dir_uses_linked_worktree_common_dir() {
        let root = temp_root("sley-odb-common-dir");
        let common = root.join(".git");
        let admin = common.join("worktrees").join("linked");
        fs::create_dir_all(&admin).expect("test operation should succeed");
        fs::write(admin.join("commondir"), "../..\n").expect("test operation should succeed");

        let common = fs::canonicalize(common).expect("test operation should succeed");
        assert_eq!(repository_common_dir(&admin), common);
        assert_eq!(repository_objects_dir(&admin), common.join("objects"));

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn reachable_object_helpers_walk_graph_and_install_pack() {
        let root = temp_root("sley-reachable-pack");
        let source_git_dir = root.join("source.git");
        let destination_git_dir = root.join("destination.git");
        fs::create_dir_all(source_git_dir.join("objects")).expect("test operation should succeed");
        fs::create_dir_all(destination_git_dir.join("objects"))
            .expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let source = FileObjectDatabase::from_git_dir(&source_git_dir, format);
        let destination = FileObjectDatabase::from_git_dir(&destination_git_dir, format);

        let blob = EncodedObject::new(ObjectType::Blob, b"reachable payload\n".to_vec());
        let blob_oid = source
            .write_object(blob.clone())
            .expect("test operation should succeed");
        let tree = EncodedObject::new(
            ObjectType::Tree,
            Tree {
                entries: vec![TreeEntry {
                    mode: 0o100644,
                    name: BString::from(b"payload.txt"),
                    oid: blob_oid,
                }],
            }
            .write(),
        );
        let tree_oid = source
            .write_object(tree.clone())
            .expect("test operation should succeed");
        let identity = b"Example <example@example.invalid> 0 +0000".to_vec();
        let commit = EncodedObject::new(
            ObjectType::Commit,
            Commit {
                tree: tree_oid,
                parents: Vec::new(),
                author: identity.clone(),
                committer: identity,
                encoding: None,
                message: b"initial\n".to_vec(),
            }
            .write(),
        );
        let commit_oid = source
            .write_object(commit.clone())
            .expect("test operation should succeed");

        let reachable = collect_reachable_object_ids(&source, format, std::iter::once(commit_oid))
            .expect("test operation should succeed");
        assert!(reachable.contains(&commit_oid));
        assert!(reachable.contains(&tree_oid));
        assert!(reachable.contains(&blob_oid));

        let install =
            install_reachable_pack(&source, &destination, format, std::iter::once(commit_oid))
                .expect("test operation should succeed")
                .expect("reachable pack should be written");
        assert_eq!(install.object_ids.len(), 3);
        for (oid, object) in [
            (&commit_oid, &commit),
            (&tree_oid, &tree),
            (&blob_oid, &blob),
        ] {
            assert!(
                !destination
                    .loose()
                    .object_path(oid)
                    .expect("test operation should succeed")
                    .exists()
            );
            assert!(
                destination
                    .contains(oid)
                    .expect("test operation should succeed")
            );
            assert_eq!(read_object_for_assert(&destination, oid), *object);
        }
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn reachable_object_helpers_respect_exclusions_and_duplicate_starts() {
        let root = temp_root("sley-reachable-exclusions");
        let git_dir = root.join("repo.git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let db = FileObjectDatabase::from_git_dir(&git_dir, format);

        let blob = EncodedObject::new(ObjectType::Blob, b"excluded payload\n".to_vec());
        let blob_oid = db
            .write_object(blob)
            .expect("test operation should succeed");
        let tree = EncodedObject::new(
            ObjectType::Tree,
            Tree {
                entries: vec![TreeEntry {
                    mode: 0o100644,
                    name: BString::from(b"payload.txt"),
                    oid: blob_oid,
                }],
            }
            .write(),
        );
        let tree_oid = db
            .write_object(tree)
            .expect("test operation should succeed");
        let identity = b"Example <example@example.invalid> 0 +0000".to_vec();
        let commit = EncodedObject::new(
            ObjectType::Commit,
            Commit {
                tree: tree_oid,
                parents: Vec::new(),
                author: identity.clone(),
                committer: identity,
                encoding: None,
                message: b"initial\n".to_vec(),
            }
            .write(),
        );
        let commit_oid = db
            .write_object(commit)
            .expect("test operation should succeed");
        let excluded = HashSet::from([tree_oid]);

        let objects = collect_reachable_objects(&db, format, [commit_oid, commit_oid], &excluded)
            .expect("test operation should succeed");

        assert_eq!(objects.len(), 1);
        assert_eq!(
            objects[0]
                .object_id(format)
                .expect("test operation should succeed"),
            commit_oid
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn build_reachable_pack_returns_raw_pack_and_respects_empty_exclusions() {
        let root = temp_root("sley-build-reachable-pack");
        let git_dir = root.join("repo.git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let db = FileObjectDatabase::from_git_dir(&git_dir, format);

        let object = EncodedObject::new(ObjectType::Blob, b"raw reachable pack\n".to_vec());
        let oid = db
            .write_object(object.clone())
            .expect("test operation should succeed");
        let pack = build_reachable_pack(&db, format, std::iter::once(oid), &HashSet::new())
            .expect("test operation should succeed")
            .expect("reachable pack should be built");
        assert!(pack.pack.starts_with(b"PACK"));
        assert_eq!(pack.entries.len(), 1);
        assert_eq!(pack.entries[0].oid, oid);

        let excluded = HashSet::from([oid]);
        assert!(
            build_reachable_pack(
                &db,
                format,
                pack.entries.into_iter().map(|entry| entry.oid),
                &excluded
            )
            .expect("test operation should succeed")
            .is_none()
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn reachable_object_helpers_follow_tags_and_report_missing_objects() {
        let root = temp_root("sley-reachable-tags");
        let git_dir = root.join("repo.git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let db = FileObjectDatabase::from_git_dir(&git_dir, format);

        let blob = EncodedObject::new(ObjectType::Blob, b"tagged payload\n".to_vec());
        let blob_oid = db
            .write_object(blob)
            .expect("test operation should succeed");
        let tag = EncodedObject::new(
            ObjectType::Tag,
            Tag {
                object: blob_oid,
                object_type: ObjectType::Blob,
                name: b"v1".to_vec(),
                tagger: Some(b"Example <example@example.invalid> 0 +0000".to_vec()),
                message: b"tag message\n".to_vec(),
                raw_body: None,
            }
            .write(),
        );
        let tag_oid = db.write_object(tag).expect("test operation should succeed");

        let reachable = collect_reachable_object_ids(&db, format, std::iter::once(tag_oid))
            .expect("test operation should succeed");
        assert!(reachable.contains(&tag_oid));
        assert!(reachable.contains(&blob_oid));

        let missing = ObjectId::from_hex(format, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
            .expect("test operation should succeed");
        let err = collect_reachable_object_ids(&db, format, std::iter::once(missing))
            .expect_err("missing traversal root should error");
        let kind = err.not_found_kind().expect("typed not found");
        assert_eq!(kind.object_id(), Some(missing));
        assert_eq!(
            kind.missing_object_context(),
            Some(MissingObjectContext::Traversal)
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn install_reachable_pack_empty_starts_create_no_pack() {
        let root = temp_root("sley-reachable-empty");
        let source_git_dir = root.join("source.git");
        let destination_git_dir = root.join("destination.git");
        fs::create_dir_all(source_git_dir.join("objects")).expect("test operation should succeed");
        fs::create_dir_all(destination_git_dir.join("objects"))
            .expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let source = FileObjectDatabase::from_git_dir(&source_git_dir, format);
        let destination = FileObjectDatabase::from_git_dir(&destination_git_dir, format);

        let result = install_reachable_pack(&source, &destination, format, Vec::<ObjectId>::new())
            .expect("test operation should succeed");

        assert!(result.is_none());
        assert!(!destination_git_dir.join("objects").join("pack").exists());
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn install_reachable_pack_excluding_skips_fully_excluded_starts() {
        let root = temp_root("sley-reachable-install-excluding");
        let source_git_dir = root.join("source.git");
        let destination_git_dir = root.join("destination.git");
        fs::create_dir_all(source_git_dir.join("objects")).expect("test operation should succeed");
        fs::create_dir_all(destination_git_dir.join("objects"))
            .expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let source = FileObjectDatabase::from_git_dir(&source_git_dir, format);
        let destination = FileObjectDatabase::from_git_dir(&destination_git_dir, format);
        let object = EncodedObject::new(ObjectType::Blob, b"excluded install\n".to_vec());
        let oid = source
            .write_object(object)
            .expect("test operation should succeed");
        let excluded = HashSet::from([oid]);

        let result = install_reachable_pack_excluding(
            &source,
            &destination,
            format,
            std::iter::once(oid),
            &excluded,
        )
        .expect("test operation should succeed");

        assert!(result.is_none());
        assert!(!destination_git_dir.join("objects").join("pack").exists());
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn install_reachable_pack_supports_sha256() {
        let root = temp_root("sley-reachable-pack-sha256");
        let source_git_dir = root.join("source.git");
        let destination_git_dir = root.join("destination.git");
        fs::create_dir_all(source_git_dir.join("objects")).expect("test operation should succeed");
        fs::create_dir_all(destination_git_dir.join("objects"))
            .expect("test operation should succeed");
        let format = ObjectFormat::Sha256;
        let source = FileObjectDatabase::from_git_dir(&source_git_dir, format);
        let destination = FileObjectDatabase::from_git_dir(&destination_git_dir, format);
        let object = EncodedObject::new(ObjectType::Blob, b"sha256 reachable pack\n".to_vec());
        let oid = source
            .write_object(object.clone())
            .expect("test operation should succeed");

        let pack = build_reachable_pack(&source, format, std::iter::once(oid), &HashSet::new())
            .expect("test operation should succeed")
            .expect("sha256 reachable pack should be built");
        assert!(pack.pack.starts_with(b"PACK"));
        assert_eq!(pack.entries[0].oid, oid);

        let result = install_reachable_pack(&source, &destination, format, std::iter::once(oid))
            .expect("test operation should succeed")
            .expect("sha256 reachable pack should be written");

        assert_eq!(result.object_ids, vec![oid]);
        assert!(
            !destination
                .loose()
                .object_path(&oid)
                .expect("test operation should succeed")
                .exists()
        );
        assert_eq!(read_object_for_assert(&destination, &oid), object);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn install_helpers_accept_custom_raw_pack_installer() {
        #[derive(Default)]
        struct RecordingInstaller {
            packs: std::cell::RefCell<Vec<Vec<u8>>>,
            installed: std::cell::RefCell<Vec<ObjectId>>,
        }

        impl RawPackInstaller for RecordingInstaller {
            fn install_raw_pack(&self, pack_bytes: &[u8]) -> Result<RawPackInstallResult> {
                self.packs.borrow_mut().push(pack_bytes.to_vec());
                let object_ids = self.installed.borrow().clone();
                Ok(RawPackInstallResult { object_ids })
            }
        }

        let format = ObjectFormat::Sha1;
        let source = ObjectDatabase::new(format);
        let object = EncodedObject::new(ObjectType::Blob, b"custom raw installer\n".to_vec());
        let oid = source
            .write_object(object)
            .expect("test operation should succeed");
        let installer = RecordingInstaller::default();
        installer.installed.borrow_mut().push(oid);

        let result = install_reachable_pack(&source, &installer, format, std::iter::once(oid))
            .expect("test operation should succeed")
            .expect("custom installer should receive pack");

        assert_eq!(result.object_ids, installer.installed.into_inner());
        let packs = installer.packs.into_inner();
        assert_eq!(packs.len(), 1);
        assert!(packs[0].starts_with(b"PACK"));
    }

    #[test]
    fn file_database_reads_object_from_multi_pack_index() {
        let root = temp_root("sley-file-odb-midx");
        let git_dir = root.join(".git");
        let pack_dir = git_dir.join("objects").join("pack");
        fs::create_dir_all(&pack_dir).expect("test operation should succeed");
        let first = EncodedObject::new(ObjectType::Blob, b"first packed\n".to_vec());
        let second = EncodedObject::new(ObjectType::Blob, b"second packed\n".to_vec());
        let first_oid = first
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let second_oid = second
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let first_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&first))
            .expect("test operation should succeed");
        let second_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&second))
            .expect("test operation should succeed");
        let first_pack_name = format!("pack-{}.idx", first_pack.checksum.to_hex());
        let second_pack_name = format!("pack-{}.idx", second_pack.checksum.to_hex());
        fs::write(
            pack_dir.join(first_pack_name.replace(".idx", ".pack")),
            first_pack.pack,
        )
        .expect("test operation should succeed");
        fs::write(
            pack_dir.join(second_pack_name.replace(".idx", ".pack")),
            second_pack.pack,
        )
        .expect("test operation should succeed");
        let midx = MultiPackIndex::write(
            ObjectFormat::Sha1,
            2,
            &[first_pack_name, second_pack_name],
            &[
                sley_pack::MultiPackIndexEntry {
                    oid: first_oid,
                    pack_int_id: 0,
                    offset: first_pack.entries[0].offset,
                    force_large_offset: false,
                },
                sley_pack::MultiPackIndexEntry {
                    oid: second_oid,
                    pack_int_id: 1,
                    offset: second_pack.entries[0].offset,
                    force_large_offset: false,
                },
            ],
        )
        .expect("test operation should succeed");
        fs::write(pack_dir.join("multi-pack-index"), midx).expect("test operation should succeed");

        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);
        assert!(
            db.contains(&second_oid)
                .expect("test operation should succeed")
        );
        assert_eq!(
            db.resolve_prefix(&second_oid.to_hex()[..8])
                .expect("test operation should succeed"),
            ObjectPrefixResolution::Unique(second_oid)
        );
        assert_eq!(read_object_for_assert(&db, &second_oid), second);
        assert_eq!(read_object_for_assert(&db, &first_oid), first);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_finds_pack_added_after_registry_was_cached() {
        // Regression guard for the cached pack-directory registry: a pack written
        // after the registry was first cached (via a prior read) must still be
        // discovered by the same handle, because a miss triggers a re-scan.
        let root = temp_root("sley-file-odb-pack-added-late");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);

        // First pack + object; reading it populates the registry cache.
        let first = EncodedObject::new(ObjectType::Blob, b"first late\n".to_vec());
        let first_oid = first
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let first_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&first))
            .expect("test operation should succeed");
        db.install_pack(&first_pack)
            .expect("test operation should succeed");
        assert_eq!(read_object_for_assert(&db, &first_oid), first);

        // A second object that the cached registry does not yet know about.
        let second = EncodedObject::new(ObjectType::Blob, b"second late\n".to_vec());
        let second_oid = second
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        // It is genuinely absent right now.
        assert!(matches!(
            db.read_object(&second_oid),
            Err(GitError::NotFound(_))
        ));

        // Install its pack through the same handle; the next read must find it via
        // a re-scan, not be masked by the stale registry.
        let second_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&second))
            .expect("test operation should succeed");
        db.install_pack(&second_pack)
            .expect("test operation should succeed");
        assert!(
            db.contains(&second_oid)
                .expect("test operation should succeed")
        );
        assert_eq!(read_object_for_assert(&db, &second_oid), second);
        // The original object still resolves too.
        assert_eq!(read_object_for_assert(&db, &first_oid), first);

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn object_presence_checker_finds_pack_added_after_registry_was_cached() {
        let root = temp_root("sley-presence-checker-pack-added-late");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);

        let first = EncodedObject::new(ObjectType::Blob, b"checker first late\n".to_vec());
        let first_oid = first
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let first_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&first))
            .expect("test operation should succeed");
        db.install_pack(&first_pack)
            .expect("test operation should succeed");

        let second = EncodedObject::new(ObjectType::Blob, b"checker second late\n".to_vec());
        let second_oid = second
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let mut checker = db.presence_checker();
        assert!(
            checker
                .contains(&first_oid)
                .expect("test operation should succeed")
        );
        assert!(
            !checker
                .contains(&second_oid)
                .expect("test operation should succeed")
        );

        let second_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&second))
            .expect("test operation should succeed");
        db.install_pack(&second_pack)
            .expect("test operation should succeed");

        assert!(
            checker
                .contains(&second_oid)
                .expect("test operation should succeed")
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_pack_registry_loads_indexes_lazily_and_refreshes_after_count_change() {
        let root = temp_root("sley-file-odb-pack-registry-refresh");
        let git_dir = root.join(".git");
        let pack_dir = git_dir.join("objects").join("pack");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);

        let first = EncodedObject::new(ObjectType::Blob, b"registry first\n".to_vec());
        let first_oid = first
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let first_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&first))
            .expect("test operation should succeed");
        db.install_pack(&first_pack)
            .expect("test operation should succeed");

        let first_registry = db
            .cached_pack_registry(&pack_dir, false)
            .expect("test operation should succeed");
        assert_eq!(first_registry.fingerprint.idx_count, 1);
        assert_eq!(first_registry.fingerprint.pack_count, 1);
        assert_eq!(first_registry.packs.len(), 1);
        assert!(
            first_registry.packs[0]
                .index
                .lock()
                .expect("test operation should succeed")
                .is_none()
        );
        assert!(
            first_registry.packs[0]
                .data
                .lock()
                .expect("test operation should succeed")
                .is_none()
        );

        // Existence checks use the parsed index directly and do not load pack
        // bytes; a full read fills the registry-owned pack data handle.
        assert!(
            db.contains(&first_oid)
                .expect("test operation should succeed")
        );
        assert!(
            first_registry.packs[0]
                .index
                .lock()
                .expect("test operation should succeed")
                .is_some()
        );
        assert!(
            first_registry.packs[0]
                .data
                .lock()
                .expect("test operation should succeed")
                .is_none()
        );
        assert_eq!(read_object_for_assert(&db, &first_oid), first);
        assert!(
            first_registry.packs[0]
                .data
                .lock()
                .expect("test operation should succeed")
                .is_some()
        );

        let second = EncodedObject::new(ObjectType::Blob, b"registry second\n".to_vec());
        let second_oid = second
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let second_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&second))
            .expect("test operation should succeed");
        db.install_pack(&second_pack)
            .expect("test operation should succeed");

        let refreshed = db
            .cached_pack_registry(&pack_dir, true)
            .expect("test operation should succeed");
        assert!(!Arc::ptr_eq(&first_registry, &refreshed));
        assert_eq!(refreshed.fingerprint.idx_count, 2);
        assert_eq!(refreshed.fingerprint.pack_count, 2);
        assert_eq!(refreshed.packs.len(), 2);
        assert_eq!(read_object_for_assert(&db, &second_oid), second);

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_pack_search_hint_rebuilds_after_pack_added() {
        // Regression guard for the recent-pack search hint: it is tied to the
        // cached pack registry, so a miss followed by a changed registry must not
        // hide newly-added packs.
        let root = temp_root("sley-file-odb-pack-lookup-added-late");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);

        let first = EncodedObject::new(ObjectType::Blob, b"first lookup\n".to_vec());
        let second = EncodedObject::new(ObjectType::Blob, b"second lookup\n".to_vec());
        let third = EncodedObject::new(ObjectType::Blob, b"third lookup\n".to_vec());
        let first_oid = first
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let second_oid = second
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let third_oid = third
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");

        let first_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&first))
            .expect("test operation should succeed");
        let second_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&second))
            .expect("test operation should succeed");
        db.install_pack(&first_pack)
            .expect("test operation should succeed");
        db.install_pack(&second_pack)
            .expect("test operation should succeed");

        // With two packs, these reads establish a cached registry and pack hint.
        assert_eq!(read_object_for_assert(&db, &first_oid), first);
        assert_eq!(read_object_for_assert(&db, &second_oid), second);
        assert!(matches!(
            db.read_object(&third_oid),
            Err(GitError::NotFound(_))
        ));

        let third_pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&third))
            .expect("test operation should succeed");
        db.install_pack(&third_pack)
            .expect("test operation should succeed");

        assert_eq!(read_object_for_assert(&db, &third_oid), third);
        assert_eq!(read_object_for_assert(&db, &first_oid), first);

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn file_database_prefers_loose_object_over_packed_object() {
        let root = temp_root("sley-file-odb-prefer-loose");
        let git_dir = root.join(".git");
        let pack_dir = git_dir.join("objects").join("pack");
        fs::create_dir_all(&pack_dir).expect("test operation should succeed");
        let object = EncodedObject::new(ObjectType::Blob, b"same\n".to_vec());
        let written = PackFile::write_undeltified_sha1(std::slice::from_ref(&object))
            .expect("test operation should succeed");
        let pack_name = written.checksum.to_hex();
        fs::write(
            pack_dir.join(format!("pack-{pack_name}.pack")),
            written.pack,
        )
        .expect("test operation should succeed");
        fs::write(
            pack_dir.join(format!("pack-{pack_name}.idx")),
            written.index,
        )
        .expect("test operation should succeed");

        let db = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);
        let oid = db
            .write_object(object.clone())
            .expect("test operation should succeed");
        assert_eq!(read_object_for_assert(&db, &oid), object);
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn bundle_prerequisite_verification_reads_existing_objects() {
        let db = ObjectDatabase::new(ObjectFormat::Sha1);
        let oid = db
            .write_object(EncodedObject::new(ObjectType::Blob, b"base\n".to_vec()))
            .expect("test operation should succeed");
        let bundle_bytes = format!("# v2 git bundle\n-{oid} base\n\n").into_bytes();
        let bundle = Bundle::parse(&bundle_bytes, ObjectFormat::Sha1)
            .expect("test operation should succeed");

        verify_bundle_prerequisites(&bundle, &db).expect("test operation should succeed");
    }

    #[test]
    fn bundle_prerequisite_verification_reports_missing_objects() {
        let db = ObjectDatabase::new(ObjectFormat::Sha1);
        let missing = sley_core::object_id_for_bytes(ObjectFormat::Sha1, "blob", b"missing\n")
            .expect("test operation should succeed");
        let bundle_bytes = format!("# v2 git bundle\n-{missing} missing\n\n").into_bytes();
        let bundle = Bundle::parse(&bundle_bytes, ObjectFormat::Sha1)
            .expect("test operation should succeed");

        assert!(verify_bundle_prerequisites(&bundle, &db).is_err());
    }

    #[test]
    fn unbundle_objects_writes_pack_entries_and_returns_refs() {
        let prerequisite_reader = ObjectDatabase::new(ObjectFormat::Sha1);
        let mut writer = ObjectDatabase::new(ObjectFormat::Sha1);
        let object = EncodedObject::new(ObjectType::Blob, b"bundle object\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&object))
            .expect("test operation should succeed");
        let bundle_bytes = format!("# v2 git bundle\n{oid} refs/heads/main\n\n")
            .into_bytes()
            .into_iter()
            .chain(pack.pack)
            .collect::<Vec<_>>();
        let bundle = Bundle::parse(&bundle_bytes, ObjectFormat::Sha1)
            .expect("test operation should succeed");

        let result = unbundle_objects(&bundle, &prerequisite_reader, &mut writer)
            .expect("test operation should succeed");
        assert_eq!(result.written_objects, vec![oid]);
        assert_eq!(result.references, bundle.references);
        assert_eq!(read_object_for_assert(&writer, &oid), object);
    }

    #[test]
    fn install_bundle_pack_writes_pack_and_returns_refs() {
        let root = temp_root("sley-install-bundle-pack");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let prerequisite_reader = ObjectDatabase::new(ObjectFormat::Sha1);
        let database = FileObjectDatabase::from_git_dir(&git_dir, ObjectFormat::Sha1);
        let object = EncodedObject::new(ObjectType::Blob, b"bundle pack object\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&object))
            .expect("test operation should succeed");
        let bundle_bytes = format!("# v2 git bundle\n{oid} refs/heads/main\n\n")
            .into_bytes()
            .into_iter()
            .chain(pack.pack)
            .collect::<Vec<_>>();
        let bundle = Bundle::parse(&bundle_bytes, ObjectFormat::Sha1)
            .expect("test operation should succeed");

        let result = install_bundle_pack(&bundle, &prerequisite_reader, &database)
            .expect("test operation should succeed");

        assert_eq!(result.written_objects, vec![oid]);
        assert_eq!(result.references, bundle.references);
        assert!(
            database
                .contains(&oid)
                .expect("test operation should succeed")
        );
        assert_eq!(read_object_for_assert(&database, &oid), object);
        assert!(
            !database
                .loose()
                .object_path(&oid)
                .expect("test operation should succeed")
                .exists()
        );
        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn unpack_packfile_objects_writes_sha256_pack_entries() {
        let writer = ObjectDatabase::new(ObjectFormat::Sha256);
        let object = EncodedObject::new(ObjectType::Blob, b"transport pack object\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha256)
            .expect("test operation should succeed");
        let pack = PackFile::write_undeltified(std::slice::from_ref(&object), ObjectFormat::Sha256)
            .expect("test operation should succeed");

        let result = unpack_packfile_objects(&pack.pack, ObjectFormat::Sha256, &writer)
            .expect("test operation should succeed");

        assert_eq!(result.written_objects, vec![oid]);
        assert_eq!(read_object_for_assert(&writer, &oid), object);
    }

    #[test]
    fn unbundle_objects_rejects_missing_prerequisites_before_writing() {
        let prerequisite_reader = ObjectDatabase::new(ObjectFormat::Sha1);
        let mut writer = ObjectDatabase::new(ObjectFormat::Sha1);
        let missing = sley_core::object_id_for_bytes(ObjectFormat::Sha1, "blob", b"missing\n")
            .expect("test operation should succeed");
        let object = EncodedObject::new(ObjectType::Blob, b"bundle object\n".to_vec());
        let oid = object
            .object_id(ObjectFormat::Sha1)
            .expect("test operation should succeed");
        let pack = PackFile::write_undeltified_sha1(std::slice::from_ref(&object))
            .expect("test operation should succeed");
        let bundle_bytes =
            format!("# v2 git bundle\n-{missing} missing\n{oid} refs/heads/main\n\n")
                .into_bytes()
                .into_iter()
                .chain(pack.pack)
                .collect::<Vec<_>>();
        let bundle = Bundle::parse(&bundle_bytes, ObjectFormat::Sha1)
            .expect("test operation should succeed");

        assert!(unbundle_objects(&bundle, &prerequisite_reader, &mut writer).is_err());
        assert!(!writer.contains(&oid));
    }

    /// Build a commit -> tree -> blob graph in `db`, returning the three object
    /// ids and their canonical encodings as `(oid, object)` pairs.
    fn write_commit_graph(
        db: &mut FileObjectDatabase,
        payload: &[u8],
    ) -> Vec<(ObjectId, EncodedObject)> {
        let blob = EncodedObject::new(ObjectType::Blob, payload.to_vec());
        let blob_oid = db
            .write_object(blob.clone())
            .expect("test operation should succeed");
        let tree = EncodedObject::new(
            ObjectType::Tree,
            Tree {
                entries: vec![TreeEntry {
                    mode: 0o100644,
                    name: BString::from(b"payload.txt"),
                    oid: blob_oid,
                }],
            }
            .write(),
        );
        let tree_oid = db
            .write_object(tree.clone())
            .expect("test operation should succeed");
        let identity = b"Example <example@example.invalid> 0 +0000".to_vec();
        let commit = EncodedObject::new(
            ObjectType::Commit,
            Commit {
                tree: tree_oid,
                parents: Vec::new(),
                author: identity.clone(),
                committer: identity,
                encoding: None,
                message: b"initial\n".to_vec(),
            }
            .write(),
        );
        let commit_oid = db
            .write_object(commit.clone())
            .expect("test operation should succeed");
        vec![(commit_oid, commit), (tree_oid, tree), (blob_oid, blob)]
    }

    fn repack_all_objects_consolidates_loose_and_pack(format: ObjectFormat) {
        let root = temp_root("sley-repack-all");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let mut db = FileObjectDatabase::from_git_dir(&git_dir, format);

        // A pre-existing pack holds one blob; the rest of the graph is loose.
        let packed_blob = EncodedObject::new(ObjectType::Blob, b"already packed\n".to_vec());
        let packed_oid = packed_blob
            .object_id(format)
            .expect("test operation should succeed");
        let existing_pack = PackFile::write_undeltified(std::slice::from_ref(&packed_blob), format)
            .expect("test operation should succeed");
        let existing = db
            .install_pack(&existing_pack)
            .expect("test operation should succeed");

        let graph = write_commit_graph(&mut db, b"repack payload\n");

        let mut expected: HashMap<ObjectId, EncodedObject> = graph.iter().cloned().collect();
        expected.insert(packed_oid, packed_blob.clone());

        let result = repack_all_objects(&git_dir, format)
            .expect("test operation should succeed")
            .expect("repository has objects");

        // The new pack round-trips and contains every original object byte-for-byte.
        assert_eq!(result.object_count, expected.len());
        let parsed = PackFile::parse(&result.pack, format).expect("test operation should succeed");
        assert_eq!(parsed.entries.len(), expected.len());
        for entry in &parsed.entries {
            let want = expected
                .get(&entry.entry.oid)
                .expect("packed object was in the repository");
            assert_eq!(&entry.object, want);
            assert_eq!(
                entry
                    .object
                    .object_id(format)
                    .expect("test operation should succeed"),
                entry.entry.oid
            );
        }
        // The generated index parses and agrees with the pack checksum.
        let idx = PackIndex::parse(&result.idx, format).expect("test operation should succeed");
        assert_eq!(idx.pack_checksum, parsed.checksum);
        assert_eq!(idx.entries.len(), expected.len());

        // The pre-existing pack is reported obsolete (by its .pack path).
        assert_eq!(result.obsolete_packs, vec![existing.pack_path.clone()]);
        // Every loose object id is reported as now packed.
        let mut want_loose: Vec<ObjectId> = graph.iter().map(|(oid, _)| *oid).collect();
        want_loose.sort_by_key(ObjectId::to_hex);
        assert_eq!(result.packed_loose, want_loose);
        assert!(!result.packed_loose.contains(&packed_oid));

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn repack_all_objects_consolidates_loose_and_pack_sha1() {
        repack_all_objects_consolidates_loose_and_pack(ObjectFormat::Sha1);
    }

    #[test]
    fn repack_all_objects_consolidates_loose_and_pack_sha256() {
        repack_all_objects_consolidates_loose_and_pack(ObjectFormat::Sha256);
    }

    #[test]
    fn repack_all_objects_returns_none_for_empty_repository() {
        let root = temp_root("sley-repack-empty");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");

        assert!(
            repack_all_objects(&git_dir, ObjectFormat::Sha1)
                .expect("test operation should succeed")
                .is_none()
        );

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn install_repack_result_writes_pack_without_pruning_by_default() {
        let root = temp_root("sley-repack-install-nodelete");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let mut db = FileObjectDatabase::from_git_dir(&git_dir, format);
        let graph = write_commit_graph(&mut db, b"install no prune\n");

        let result = repack_all_objects(&git_dir, format)
            .expect("test operation should succeed")
            .expect("test operation should succeed");
        install_repack_result(&git_dir, format, &result, false)
            .expect("test operation should succeed");

        // New pack is on disk and readable.
        let parsed = PackFile::parse(&result.pack, format).expect("test operation should succeed");
        let pack_dir = git_dir.join("objects").join("pack");
        let pack_path = pack_dir.join(format!("pack-{}.pack", parsed.checksum.to_hex()));
        let idx_path = pack_dir.join(format!("pack-{}.idx", parsed.checksum.to_hex()));
        assert!(pack_path.exists());
        assert!(idx_path.exists());
        // Loose objects survive because prune was not requested.
        for (oid, object) in &graph {
            assert!(
                db.loose()
                    .object_path(oid)
                    .expect("test operation should succeed")
                    .exists()
            );
            assert_eq!(read_object_for_assert(&db, oid), *object);
        }

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn install_repack_result_prunes_obsolete_packs_and_loose_objects() {
        let root = temp_root("sley-repack-install-prune");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let mut db = FileObjectDatabase::from_git_dir(&git_dir, format);

        let packed_blob = EncodedObject::new(ObjectType::Blob, b"prune packed\n".to_vec());
        let existing_pack = PackFile::write_undeltified(std::slice::from_ref(&packed_blob), format)
            .expect("test operation should succeed");
        let existing = db
            .install_pack(&existing_pack)
            .expect("test operation should succeed");
        let graph = write_commit_graph(&mut db, b"prune payload\n");

        let result = repack_all_objects(&git_dir, format)
            .expect("test operation should succeed")
            .expect("test operation should succeed");
        let new_pack_checksum = PackFile::parse(&result.pack, format)
            .expect("test operation should succeed")
            .checksum;
        install_repack_result(&git_dir, format, &result, true)
            .expect("test operation should succeed");

        // Obsolete pack and its index are gone.
        assert!(!existing.pack_path.exists());
        assert!(!existing.index_path.exists());
        // Packed loose objects are gone from disk.
        for (oid, _) in &graph {
            assert!(
                !db.loose()
                    .object_path(oid)
                    .expect("test operation should succeed")
                    .exists()
            );
        }
        // The new consolidated pack remains and still serves every object.
        let pack_dir = git_dir.join("objects").join("pack");
        assert!(
            pack_dir
                .join(format!("pack-{}.pack", new_pack_checksum.to_hex()))
                .exists()
        );
        let reopened = FileObjectDatabase::from_git_dir(&git_dir, format);
        for (oid, object) in &graph {
            assert!(
                reopened
                    .contains(oid)
                    .expect("test operation should succeed")
            );
            assert_eq!(read_object_for_assert(&reopened, oid), *object);
        }
        let packed_oid = packed_blob
            .object_id(format)
            .expect("test operation should succeed");
        assert_eq!(read_object_for_assert(&reopened, &packed_oid), packed_blob);

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn install_repack_result_preserves_keep_and_promisor_packs() {
        let root = temp_root("sley-repack-install-keep-promisor");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let mut db = FileObjectDatabase::from_git_dir(&git_dir, format);

        let keep_blob = EncodedObject::new(ObjectType::Blob, b"keep protected\n".to_vec());
        let keep_pack = PackFile::write_undeltified(std::slice::from_ref(&keep_blob), format)
            .expect("test operation should succeed");
        let keep_install = db
            .install_pack(&keep_pack)
            .expect("test operation should succeed");
        let keep_sidecar = keep_install.pack_path.with_extension("keep");
        fs::write(&keep_sidecar, b"").expect("test operation should succeed");

        let promisor_blob = EncodedObject::new(ObjectType::Blob, b"promisor protected\n".to_vec());
        let promisor_pack =
            PackFile::write_undeltified(std::slice::from_ref(&promisor_blob), format)
                .expect("test operation should succeed");
        let promisor_install = db
            .install_pack_with_options(&promisor_pack, RawPackInstallOptions { promisor: true })
            .expect("test operation should succeed");
        let promisor_sidecar = promisor_install
            .promisor_path
            .clone()
            .expect("promisor sidecar");

        let graph = write_commit_graph(&mut db, b"new consolidated payload\n");
        let result = repack_all_objects(&git_dir, format)
            .expect("test operation should succeed")
            .expect("test operation should succeed");
        assert!(result.obsolete_packs.contains(&keep_install.pack_path));
        assert!(result.obsolete_packs.contains(&promisor_install.pack_path));

        install_repack_result(&git_dir, format, &result, true)
            .expect("test operation should succeed");

        for path in [
            &keep_install.pack_path,
            &keep_install.index_path,
            &keep_sidecar,
            &promisor_install.pack_path,
            &promisor_install.index_path,
            &promisor_sidecar,
        ] {
            assert!(path.exists(), "{} should be preserved", path.display());
        }
        for (oid, _) in &graph {
            assert!(
                !db.loose()
                    .object_path(oid)
                    .expect("test operation should succeed")
                    .exists()
            );
        }

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn install_repack_result_keeps_loose_object_absent_from_new_pack() {
        // Safety: a loose object whose id is not in the new pack must survive
        // pruning even if the caller lists it in `packed_loose`.
        let root = temp_root("sley-repack-install-safety");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let mut db = FileObjectDatabase::from_git_dir(&git_dir, format);
        let graph = write_commit_graph(&mut db, b"safety packed\n");

        let mut result = repack_all_objects(&git_dir, format)
            .expect("test operation should succeed")
            .expect("test operation should succeed");

        // A loose object that is NOT in the new pack, but mislabeled as packed.
        let stray = EncodedObject::new(ObjectType::Blob, b"never packed\n".to_vec());
        let stray_oid = db
            .write_object(stray.clone())
            .expect("test operation should succeed");
        assert!(!result.packed_loose.contains(&stray_oid));
        result.packed_loose.push(stray_oid);

        install_repack_result(&git_dir, format, &result, true)
            .expect("test operation should succeed");

        // The stray loose object is untouched because it is not in the new pack.
        assert!(
            db.loose()
                .object_path(&stray_oid)
                .expect("test operation should succeed")
                .exists()
        );
        assert_eq!(read_object_for_assert(&db, &stray_oid), stray);
        // Genuinely packed loose objects were still removed.
        for (oid, _) in &graph {
            assert!(
                !db.loose()
                    .object_path(oid)
                    .expect("test operation should succeed")
                    .exists()
            );
        }

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn prune_unreachable_loose_reports_and_deletes_only_unreachable() {
        let root = temp_root("sley-prune-unreachable");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let mut db = FileObjectDatabase::from_git_dir(&git_dir, format);
        let graph = write_commit_graph(&mut db, b"reachable payload\n");
        let commit_oid = graph[0].0.clone();

        // A dangling loose blob not referenced by the commit graph.
        let dangling = EncodedObject::new(ObjectType::Blob, b"dangling\n".to_vec());
        let dangling_oid = db
            .write_object(dangling)
            .expect("test operation should succeed");

        // Report-only pass leaves everything on disk.
        let reported = prune_unreachable_loose(&git_dir, format, [commit_oid], false)
            .expect("test operation should succeed");
        assert_eq!(reported, vec![dangling_oid]);
        assert!(
            db.loose()
                .object_path(&dangling_oid)
                .expect("test operation should succeed")
                .exists()
        );

        // Deleting pass removes only the unreachable object.
        let deleted = prune_unreachable_loose(&git_dir, format, [commit_oid], true)
            .expect("test operation should succeed");
        assert_eq!(deleted, vec![dangling_oid]);
        assert!(
            !db.loose()
                .object_path(&dangling_oid)
                .expect("test operation should succeed")
                .exists()
        );
        for (oid, object) in &graph {
            assert!(
                db.loose()
                    .object_path(oid)
                    .expect("test operation should succeed")
                    .exists()
            );
            assert_eq!(read_object_for_assert(&db, oid), *object);
        }

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    #[test]
    fn prune_unreachable_loose_ignores_gitlink_targets() {
        let root = temp_root("sley-prune-gitlink");
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).expect("test operation should succeed");
        let format = ObjectFormat::Sha1;
        let db = FileObjectDatabase::from_git_dir(&git_dir, format);

        let submodule_oid = ObjectId::from_hex(format, "1111111111111111111111111111111111111111")
            .expect("test operation should succeed");
        let tree = EncodedObject::new(
            ObjectType::Tree,
            Tree {
                entries: vec![TreeEntry {
                    mode: 0o160000,
                    name: BString::from(b"submodule"),
                    oid: submodule_oid,
                }],
            }
            .write(),
        );
        let tree_oid = db
            .write_object(tree)
            .expect("test operation should succeed");
        let identity = b"Example <example@example.invalid> 0 +0000".to_vec();
        let commit = EncodedObject::new(
            ObjectType::Commit,
            Commit {
                tree: tree_oid,
                parents: Vec::new(),
                author: identity.clone(),
                committer: identity,
                encoding: None,
                message: b"gitlink\n".to_vec(),
            }
            .write(),
        );
        let commit_oid = db
            .write_object(commit)
            .expect("test operation should succeed");
        let dangling = EncodedObject::new(ObjectType::Blob, b"dangling with gitlink\n".to_vec());
        let dangling_oid = db
            .write_object(dangling)
            .expect("test operation should succeed");

        let deleted = prune_unreachable_loose(&git_dir, format, [commit_oid], true)
            .expect("test operation should succeed");

        assert_eq!(deleted, vec![dangling_oid]);
        assert!(
            !db.loose()
                .object_path(&dangling_oid)
                .expect("test operation should succeed")
                .exists()
        );

        fs::remove_dir_all(root).expect("test operation should succeed");
    }

    fn temp_root(prefix: &str) -> PathBuf {
        std::env::temp_dir().join(format!(
            "{prefix}-{}-{}",
            std::process::id(),
            TEMPFILE_COUNTER.fetch_add(1, Ordering::Relaxed)
        ))
    }
}