grit-lib 0.5.21

Core library for the grit Git implementation
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
//! Repository maintenance: repack, fsck, and garbage collection orchestration.
//!
//! These APIs wrap existing pack, prune, and fsck primitives for embedders and the
//! `grit` CLI. They never shell out to the system `git` binary.
//!
//! Library guide: [maintenance](https://grit-scm.com/docs/library/maintenance)
//!
//! ```rust
//! use grit_lib::repo::{InitOptions, Repository};
//! # fn main() -> grit_lib::error::Result<()> {
//! let dir = tempfile::tempdir()?;
//! let _repo = Repository::init(dir.path(), &InitOptions::default())?;
//! # Ok(())
//! # }
//! ```

use std::collections::{HashMap, HashSet, VecDeque};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime};

use crate::commit_graph_file::CommitGraphChain;
use crate::commit_graph_write::{
    atomic_replace_commit_graph, build_commit_graph_bytes_from_oid_maps,
    collect_reachable_commit_oids_for_repository, load_commit_graph_commit_info,
    remove_commit_graph_chain_dir, remove_commit_graph_files, BloomWriteStats,
};
use crate::config::ConfigSet;
use crate::diff::bloom::BloomFilterSettings;
use crate::environment::Environment;
use crate::error::{ConfigError, Error, Result};
use crate::fsck as repo_fsck;
use crate::gc::{prune_loose_unreachable_with, LazyReachable, PruneStats};
use crate::git_date::approx::approxidate_careful_at;
use crate::index_pack::{install_pack_bytes, install_pack_path, IngestPackOptions};
use crate::midx::{
    clear_pack_midx_state, midx_version_from_config, midx_write_version,
    write_multi_pack_index_with_options, MidxBitmapWriteOutcome, WriteMultiPackIndexOptions,
    WriteMultiPackIndexResult,
};
use crate::objects::{
    oid_hash_map, parse_commit, parse_tag, parse_tree, ObjectId, ObjectKind, OidHashSet,
};
use crate::odb::Odb;
use crate::odb::UnreachablePackRetention;
use crate::pack_bitmap::{PackBitmapWriteOptions, PackBitmapWriter};
use crate::pack_delta::{pack_delta_search_parallel_options, pack_write_parallel_options};
use crate::pack_object_select::{
    enumerate_pack_objects_naming, NameTrees, PackEnumerateOptions, PackObjectSelection,
};
use crate::pack_objects::{
    build_pack_from_send_list_with_parallel_threads, PackBuildOptions, SerializedDeltaPack,
};
use crate::pack_rev::write_pack_rev_sidecar_for_index_path;
use crate::prune_packed::{prune_packed_objects, PrunePackedOptions};
use crate::reflog::{
    expire_reflog_git, list_reflog_refs, load_gc_reflog_expire_config, ReflogExpireParams,
};
use crate::repack_pack::{write_repack_pack, RepackPackSettings};
use crate::repo::Repository;
use crate::shallow::load_shallow_boundaries;
use time::OffsetDateTime;

/// Options for [`repack_all()`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RepackOptions {
    /// Report actions without writing packs or deleting files.
    pub dry_run: bool,
    /// After repack, write `objects/info/commit-graph` when the ODB is files-backed.
    pub write_commit_graph: bool,
    /// After repack, write a `.bitmap` sidecar for the new pack (files-backed only).
    pub write_bitmap: bool,
    /// When set, prune unreachable loose objects not newer than this instant after repack.
    pub prune_older_than: Option<OffsetDateTime>,
    /// Wall clock passed to maintenance helpers that require an explicit time (e.g. bitmap writes).
    pub now: Option<OffsetDateTime>,
    /// When true (the default), do not delete unreachable loose objects after repack (matches `git repack -ad`).
    pub keep_unreachable: bool,
    /// Worker threads for pack indexing (`None` reads `pack.threads` / CPU count).
    pub threads: Option<usize>,
    /// Override the delta settings of a full repack; `None` uses
    /// [`PackBuildOptions::for_local_copy`] (`pack.window` / `pack.depth` from config).
    ///
    /// A full repack honors `delta`, `window`, `max_depth`, `reuse_deltas`, `reuse_objects`,
    /// `use_ofs_delta` and `use_bitmaps`. Objects already in a pack keep their stored form
    /// when the reuse flags allow it; only the rest go through the `window` search.
    pub pack_build: Option<PackBuildOptions>,
    /// Config/environment for ingest and pack threads (defaults to repo config).
    pub merged_config: Option<ConfigSet>,
    /// Process environment for config discovery and thread counts.
    pub environment: Environment,
    /// Pack only the reachable loose objects into a new pack, keeping existing packs (Git
    /// `repack -d` without `-a`). Unreachable loose objects stay loose for the prune step.
    ///
    /// When [`Self::write_bitmap`] is true and the repository already has pack files, bitmaps are
    /// written via a multi-pack-index sidecar instead of a per-pack `.bitmap` on the new pack alone.
    pub incremental: bool,
    /// When true, [`gc()`] may skip repack on a single pack with no loose objects when every
    /// packed object is still reachable and none would be dropped by the active prune policy.
    /// Explicit [`repack_all`] / [`repack`] leave this false so maintenance still runs.
    pub auto_skip: bool,
    /// When true, recompute every delta instead of keeping the ones stored in packs
    /// (`git repack -f`, `grit repack --force`). Whole objects that stay whole are
    /// still copied verbatim.
    pub force_recompress: bool,
}

impl Default for RepackOptions {
    fn default() -> Self {
        Self {
            dry_run: false,
            write_commit_graph: false,
            write_bitmap: false,
            prune_older_than: None,
            now: None,
            keep_unreachable: true,
            threads: None,
            pack_build: None,
            merged_config: None,
            environment: Environment::empty(),
            incremental: false,
            auto_skip: false,
            force_recompress: false,
        }
    }
}

impl RepackOptions {
    /// Start from [`Default::default`] with [`Self::dry_run`] set.
    #[must_use]
    pub fn with_dry_run(dry_run: bool) -> Self {
        Self {
            dry_run,
            ..Self::default()
        }
    }
}

struct RepackDetail {
    report: RepackReport,
    prune_packed_loose: usize,
    unreachable_loose: PruneStats,
    unreachable_prune_ms: u64,
    unreachable_prune_ran: bool,
}

/// Counters produced by [`repack`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RepackReport {
    /// New pack files installed (0 or 1 for all-into-one repack).
    pub packs_written: usize,
    /// Pack sidecar files removed from `objects/pack/` (excluding `.keep` packs).
    pub packs_removed: usize,
    /// Loose object files removed (`prune-packed` plus unreachable prune).
    pub loose_removed: usize,
    /// Objects written into the new pack.
    pub objects: usize,
}

/// Extended counters and paths produced by [`repack_all`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RepackStats {
    /// Loose object files before repack.
    pub loose_before: usize,
    /// Pack files before repack.
    pub packs_before: usize,
    /// Objects written into the new pack (`None` when [`RepackOptions::dry_run`]).
    pub objects_packed: Option<usize>,
    /// Bytes in the new pack (`None` on dry run).
    pub pack_bytes: Option<u64>,
    /// Path to the installed pack (`None` on dry run or when nothing was packed).
    pub pack_path: Option<PathBuf>,
    /// Sidecar/index files removed from `objects/pack/`.
    pub removed_pack_files: usize,
    /// Loose objects removed because they were redundant with the new pack.
    pub pruned_loose: usize,
    /// Unreachable loose objects removed after repack when pruning is enabled.
    pub unreachable_loose_pruned: usize,
    /// Unreachable loose objects kept (grace window or concurrent safety).
    pub unreachable_loose_kept: usize,
    /// Wall time spent in unreachable loose-object pruning during this repack.
    pub unreachable_prune_ms: u64,
    /// True when unreachable loose-object pruning was executed (even if nothing was removed).
    pub unreachable_prune_ran: bool,
}

/// Options for [`Repository::write_commit_graph`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommitGraphOptions {
    /// When true, emit Bloom filter chunks for changed-path queries.
    pub changed_paths: bool,
    /// Report without writing `objects/info/commit-graph`.
    pub dry_run: bool,
}

impl CommitGraphOptions {
    /// Build options with an explicit changed-paths Bloom setting.
    #[must_use]
    pub fn with_changed_paths(changed_paths: bool) -> Self {
        Self {
            changed_paths,
            ..Self::default()
        }
    }

    /// Build options with [`Self::dry_run`] set.
    #[must_use]
    pub fn with_dry_run(dry_run: bool) -> Self {
        Self {
            dry_run,
            ..Self::default()
        }
    }
}

/// Result of writing `objects/info/commit-graph`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommitGraphWriteReport {
    /// Path to the monolithic commit-graph file.
    pub path: PathBuf,
    /// Commits encoded in the graph (`0` when [`Self::skipped`] is set).
    pub commit_count: usize,
    /// Whether a split `commit-graphs/` chain was removed.
    pub removed_chain: bool,
    /// Bloom generation counters when [`CommitGraphOptions::changed_paths`] was set and a
    /// graph was written.
    pub bloom_stats: Option<BloomWriteStats>,
    /// Why no graph was written, when the repository rewrites parent lists.
    pub skipped: Option<CommitGraphSkipReason>,
}

/// Why [`write_commit_graph`] wrote no graph.
///
/// A commit-graph stores each commit's parents as recorded in the commit object. When the
/// repository overrides those parents, a graph would disagree with what Git sees: Git
/// neither writes nor reads a graph in that state, and `git fsck` rejects one that exists.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CommitGraphSkipReason {
    /// `.git/shallow` lists boundary commits whose parents are cut off.
    Shallow,
    /// `info/grafts` overrides the parents of at least one commit.
    Grafts,
    /// Replace refs (`refs/replace/`) are present and enabled.
    ReplaceRefs,
}

impl CommitGraphSkipReason {
    /// Stable kebab-case identifier: `shallow`, `grafts` or `replace-refs`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Shallow => "shallow",
            Self::Grafts => "grafts",
            Self::ReplaceRefs => "replace-refs",
        }
    }

    /// Check whether the repository at `git_dir` rewrites parent lists.
    ///
    /// `git_dir` may be a linked worktree's git directory; shallow and graft files are read
    /// from the common directory. `has_replace_refs` is only called when neither applies and
    /// reports whether enabled replace refs exist.
    pub(crate) fn detect(
        git_dir: &Path,
        has_replace_refs: impl FnOnce() -> Result<bool>,
    ) -> Result<Option<Self>> {
        let common = crate::repo::common_git_dir_for_config(git_dir);
        if !crate::shallow::load_shallow_boundaries(&common).is_empty() {
            return Ok(Some(Self::Shallow));
        }
        if !crate::rev_parse::load_graft_parents(&common).is_empty() {
            return Ok(Some(Self::Grafts));
        }
        Ok(has_replace_refs()?.then_some(Self::ReplaceRefs))
    }

    /// Like [`Self::detect`] for an open repository, honoring `core.useReplaceRefs`,
    /// `GIT_NO_REPLACE_OBJECTS` and `GIT_REPLACE_REF_BASE`.
    pub(crate) fn detect_for_repository(repo: &Repository) -> Result<Option<Self>> {
        Self::detect(repo.git_dir(), || {
            let Some(base) = repo.replace_ref_base_if_enabled() else {
                return Ok(false);
            };
            Ok(!repo.references().list(&base)?.is_empty())
        })
    }
}

/// Options for [`Repository::write_midx`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct MidxOptions {
    /// Write a reachability `.bitmap` sidecar when the MIDX is a root file.
    pub bitmap: bool,
    /// Report without writing `multi-pack-index`.
    pub dry_run: bool,
    /// On-disk MIDX version (`1` or `2`). `None` uses `midx.version` from the repository
    /// config, and v1 when that is unset, so every Git with multi-pack-index support can
    /// read the result.
    pub version: Option<u8>,
}

impl MidxOptions {
    /// Build MIDX write options with an explicit bitmap sidecar flag.
    #[must_use]
    pub fn with_bitmap(bitmap: bool) -> Self {
        Self {
            bitmap,
            ..Self::default()
        }
    }

    /// Build options with [`Self::dry_run`] set.
    #[must_use]
    pub fn with_dry_run(dry_run: bool) -> Self {
        Self {
            dry_run,
            ..Self::default()
        }
    }
}

/// Result of writing `objects/pack/multi-pack-index`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MidxWriteReport {
    /// Path to the tip MIDX file.
    pub path: PathBuf,
    /// Pack indexes covered by the MIDX.
    pub pack_count: usize,
    /// Whether a reachability bitmap was written or skipped.
    pub bitmap: MidxBitmapWriteOutcome,
}

/// Options for [`References::pack`](crate::refs::References::pack).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PackRefsOptions {
    /// When true, pack every packable ref (`git pack-refs --all`); otherwise only tags.
    pub all: bool,
    /// Report without rewriting `packed-refs` or deleting loose refs.
    pub dry_run: bool,
}

impl PackRefsOptions {
    /// Build pack-refs options matching `git pack-refs` / `--all`.
    #[must_use]
    pub fn with_all(all: bool) -> Self {
        Self {
            all,
            ..Self::default()
        }
    }

    /// Build options with [`Self::dry_run`] set.
    #[must_use]
    pub fn with_dry_run(dry_run: bool) -> Self {
        Self {
            dry_run,
            ..Self::default()
        }
    }
}

/// Result of packing refs (files `packed-refs` or reftable compaction).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PackRefsReport {
    /// `packed-refs` path or the `reftable/` directory.
    pub path: PathBuf,
    /// Loose refs merged into the packed store.
    pub refs_packed: usize,
    /// Loose ref files removed (files backend) or tables merged (reftable).
    pub refs_pruned: usize,
}

/// Options for [`gc()`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct GcOptions {
    /// Repack options applied before pruning unreachable objects.
    pub repack: RepackOptions,
    /// Expire reflogs using `gc.reflogExpire*` before repack/prune.
    pub expire_reflog: bool,
    /// Unix seconds for reflog expiry rules.
    pub now_unix: i64,
    /// When true, pack loose refs before other gc steps.
    pub pack_refs: bool,
    /// When true, write `objects/info/commit-graph` after repack/prune.
    ///
    /// Changed-path Bloom filters are kept when the existing graph has them and are not
    /// added otherwise, matching `git gc`.
    pub write_commit_graph: bool,
}

impl Default for GcOptions {
    fn default() -> Self {
        Self {
            repack: RepackOptions {
                auto_skip: true,
                ..RepackOptions::default()
            },
            expire_reflog: true,
            now_unix: 0,
            pack_refs: true,
            write_commit_graph: true,
        }
    }
}

impl GcOptions {
    /// Run gc with repack dry-run control and an explicit wall-clock for reflog expiry.
    #[must_use]
    pub fn with_repack_dry_run(dry_run: bool, now_unix: i64) -> Self {
        Self {
            repack: RepackOptions {
                dry_run,
                auto_skip: true,
                ..RepackOptions::default()
            },
            expire_reflog: true,
            now_unix,
            ..Self::default()
        }
    }

    /// Default repack with explicit reflog expiry policy and wall-clock.
    #[must_use]
    pub fn with_reflog_policy(now_unix: i64, expire_reflog: bool) -> Self {
        Self {
            repack: RepackOptions {
                auto_skip: true,
                ..RepackOptions::default()
            },
            expire_reflog,
            now_unix,
            ..Self::default()
        }
    }

    /// Full maintenance run: pack-refs, reflog expiry, repack, prune, commit-graph.
    #[must_use]
    pub fn full_run(dry_run: bool, now_unix: i64) -> Self {
        Self {
            repack: RepackOptions {
                dry_run,
                auto_skip: true,
                ..RepackOptions::default()
            },
            expire_reflog: true,
            now_unix,
            pack_refs: true,
            write_commit_graph: true,
            ..Self::default()
        }
    }
}

impl PruneOptions {
    /// Prune with an optional explicit cutoff (`None` uses `gc.pruneExpire`).
    #[must_use]
    pub fn with_older_than(older_than: Option<SystemTime>) -> Self {
        Self {
            older_than,
            ..Self::default()
        }
    }
}

/// Object ids that must stay reachable during repack, prune, and fsck walks.
///
/// Includes ref tips, symbolic `HEAD`, every reflog `old`/`new` oid, and every
/// blob/tree oid recorded in the index (including unmerged stages; gitlinks are excluded).
///
/// # Errors
///
/// Propagates ref, reflog, or index load failures.
pub fn collect_maintenance_object_roots(repo: &Repository) -> Result<Vec<ObjectId>> {
    repo_fsck::reachability_roots(repo)
}

pub(crate) fn bloom_settings_for_commit_graph_write(
    config: &ConfigSet,
    changed_paths: bool,
) -> BloomFilterSettings {
    let mut bloom = BloomFilterSettings::default();
    if !changed_paths {
        return bloom;
    }
    if let Some(v) = config
        .get("commitgraph.changedpathsversion")
        .and_then(|s| s.trim().parse::<i32>().ok())
    {
        if v == 2 {
            bloom.hash_version = 2;
        } else if v == 1 {
            bloom.hash_version = 1;
        }
    }
    bloom
}

/// Whether the current commit-graph carries changed-path Bloom filters.
///
/// Maintenance rewrites keep Bloom filters when the graph already has them and otherwise
/// write without them, as Git's gc does: computing filters from scratch diffs every
/// commit's tree and costs far more than the rest of the graph.
fn existing_commit_graph_has_changed_paths(repo: &Repository) -> bool {
    repo.odb()
        .files_objects_dir()
        .and_then(|dir| CommitGraphChain::try_load(dir).ok().flatten())
        .is_some_and(|chain| chain.top_layer_bloom_settings().is_some())
}

pub(crate) fn commit_graph_writes_generation_data(config: &ConfigSet) -> bool {
    config
        .get("commitgraph.generationversion")
        .and_then(|s| s.trim().parse::<i32>().ok())
        .map(|v| v >= 2)
        .unwrap_or(true)
}

/// Write a monolithic reachable commit-graph under `objects/info/commit-graph`.
///
/// Reachable commits are discovered from [`Repository::refs`](crate::repo::Repository::refs)
/// (reftable, packed-refs, and linked-worktree visibility), not by scanning `git_dir/refs` alone.
///
/// In a shallow repository, with `info/grafts`, or with enabled replace refs, nothing is
/// written and [`CommitGraphWriteReport::skipped`] says why (see [`CommitGraphSkipReason`]).
/// Git only skips the write in that state, but `git fsck` still verifies a graph that is
/// already there, so an existing graph and split chain are deleted as well (except in
/// [`CommitGraphOptions::dry_run`]).
///
/// # Errors
///
/// Returns [`Error::UnsupportedObjectStore`] for non-files ODB backends, or errors from graph
/// generation and atomic I/O.
pub fn write_commit_graph(
    repo: &Repository,
    opts: &CommitGraphOptions,
) -> Result<CommitGraphWriteReport> {
    let odb = repo.odb();
    odb.require_files_primary("commit-graph write")?;
    let objects_dir = odb
        .files_objects_dir()
        .ok_or(Error::UnsupportedObjectStore {
            operation: "commit-graph write",
        })?;
    let path = objects_dir.join("info").join("commit-graph");

    if let Some(reason) = CommitGraphSkipReason::detect_for_repository(repo)? {
        let removed_chain = if opts.dry_run {
            false
        } else {
            let removed = remove_commit_graph_files(objects_dir)?;
            repo.caches().invalidate_commit_graph_cache();
            removed
        };
        return Ok(CommitGraphWriteReport {
            path,
            commit_count: 0,
            removed_chain,
            bloom_stats: None,
            skipped: Some(reason),
        });
    }

    let config = repo.config()?;
    let bloom = bloom_settings_for_commit_graph_write(&config, opts.changed_paths);
    let write_generation = commit_graph_writes_generation_data(&config);

    let chain = CommitGraphChain::try_load(objects_dir).ok().flatten();

    let commits = collect_reachable_commit_oids_for_repository(repo)?;
    let mut sorted: Vec<ObjectId> = commits.into_iter().collect();
    sorted.sort();
    let commit_count = sorted.len();

    if opts.dry_run {
        return Ok(CommitGraphWriteReport {
            path,
            commit_count,
            removed_chain: false,
            bloom_stats: opts.changed_paths.then_some(BloomWriteStats::default()),
            skipped: None,
        });
    }

    let mut infos = oid_hash_map();
    for oid in &sorted {
        infos.insert(*oid, load_commit_graph_commit_info(odb, *oid)?);
    }

    let mut existing_filters = oid_hash_map();
    let mut upgraded_filters = oid_hash_map();
    if opts.changed_paths {
        if let Some(ref chain) = chain {
            for oid in &sorted {
                if let Some(bytes) = chain.existing_filter_bytes(oid, &bloom) {
                    existing_filters.insert(*oid, bytes);
                } else if let Some(bytes) = chain.upgradable_filter_bytes(oid, &bloom) {
                    upgraded_filters.insert(*oid, bytes);
                }
            }
        }
    }

    let (bytes, bloom_stats) = build_commit_graph_bytes_from_oid_maps(
        &sorted,
        &infos,
        odb,
        opts.changed_paths,
        &bloom,
        None,
        &[],
        None,
        &existing_filters,
        &upgraded_filters,
        write_generation,
    )?;

    let written_path = atomic_replace_commit_graph(objects_dir, &bytes)?;
    let removed_chain = remove_commit_graph_chain_dir(objects_dir);
    repo.caches().invalidate_commit_graph_cache();

    Ok(CommitGraphWriteReport {
        path: written_path,
        commit_count,
        removed_chain,
        bloom_stats: opts.changed_paths.then_some(bloom_stats),
        skipped: None,
    })
}

/// Write or refresh `objects/pack/multi-pack-index` for the repository.
///
/// The on-disk version comes from [`MidxOptions::version`], then `midx.version`, then v1.
///
/// # Errors
///
/// Returns [`Error::UnsupportedObjectStore`] for non-files backends, [`Error::Config`] when
/// `midx.version` is not an integer, [`crate::error::MidxError::UnknownWriteVersion`] (as
/// [`Error::Midx`]) when the version is not `1` or `2`, or MIDX write failures.
pub fn write_midx(repo: &Repository, opts: &MidxOptions) -> Result<MidxWriteReport> {
    let odb = repo.odb();
    odb.require_files_primary("midx write")?;
    let requested = match opts.version {
        Some(v) => Some(v),
        None => midx_version_from_config(&*repo.config()?)?,
    };
    let version = Some(midx_write_version(requested)?);
    let objects_dir = odb
        .files_objects_dir()
        .ok_or(Error::UnsupportedObjectStore {
            operation: "midx write",
        })?;
    let pack_dir = objects_dir.join("pack");
    let pack_count = fs::read_dir(&pack_dir)
        .map(|rd| {
            rd.filter_map(|e| e.ok())
                .filter(|e| e.path().extension().is_some_and(|x| x == "idx"))
                .filter(|e| e.path().with_extension("pack").is_file())
                .count()
        })
        .unwrap_or(0);

    let path = pack_dir.join("multi-pack-index");
    if opts.dry_run {
        return Ok(MidxWriteReport {
            path,
            pack_count,
            bitmap: MidxBitmapWriteOutcome::NotRequested,
        });
    }
    let write_opts = WriteMultiPackIndexOptions {
        write_bitmap: opts.bitmap,
        version,
        ..WriteMultiPackIndexOptions::default()
    };
    let WriteMultiPackIndexResult { bitmap } =
        write_multi_pack_index_with_options(&pack_dir, &write_opts)?;
    Ok(MidxWriteReport {
        path,
        pack_count,
        bitmap,
    })
}

/// Options for [`prune_loose_objects`].
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct PruneOptions {
    /// When set, only delete unreachable loose objects strictly older than this time.
    ///
    /// When `None`, uses `gc.pruneExpire` from repository config (default `2.weeks.ago`).
    pub older_than: Option<SystemTime>,
    /// Report without deleting objects.
    pub dry_run: bool,
}

/// Wall-clock milliseconds for each phase of [`gc`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct GcPhaseTimings {
    /// [`pack_refs`] when run as part of gc.
    pub pack_refs_ms: u64,
    /// Reflog expiry before repack.
    pub reflog_ms: u64,
    /// Repack work excluding embedded unreachable prune.
    pub repack_ms: u64,
    /// Unreachable loose-object prune (during repack or standalone).
    pub prune_ms: u64,
    /// Commit-graph write after repack.
    pub commit_graph_ms: u64,
}

/// Result of [`gc`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GcStats {
    /// Loose refs packed during gc (`None` when skipped).
    pub pack_refs: Option<PackRefsReport>,
    /// Counters from the repack phase.
    pub repack: RepackStats,
    /// Counters from loose-object pruning after repack.
    pub prune: PruneStats,
    /// True when full gc ran unreachable loose-object pruning during repack.
    pub prune_ran: bool,
    /// Monolithic commit-graph written after repack/prune (`None` when skipped).
    pub commit_graph: Option<CommitGraphWriteReport>,
    /// Reflog lines removed by expiry during gc.
    pub reflog_entries_pruned: usize,
    /// Per-phase wall times for the gc orchestration.
    pub phase_timings: GcPhaseTimings,
}

/// Repack all reachable objects into a single pack and drop redundant storage.
///
/// Mirrors a minimal `git repack -ad`: one pack for [`reachability_roots`](crate::fsck::reachability_roots), optional `.rev` /
/// `.bitmap` sidecars, delete other packs, [`prune_packed_objects`], and optional unreachable
/// loose-object pruning.
///
/// # Errors
///
/// Propagates pack build/install failures, unsupported custom ODB backends, and I/O errors.
pub fn repack(repo: &Repository, opts: &RepackOptions) -> Result<RepackReport> {
    Ok(repack_detail(repo, opts)?.report)
}

fn repack_detail(repo: &Repository, opts: &RepackOptions) -> Result<RepackDetail> {
    let odb = repo.odb();
    odb.require_files_primary("repack")?;
    let objects_dir = odb
        .files_objects_dir()
        .ok_or(Error::UnsupportedObjectStore {
            operation: "repack",
        })?;
    let pack_dir = objects_dir.join("pack");

    let mut report = RepackReport::default();
    let loose_before = count_loose_objects(odb)?;
    let packs_before = count_pack_files(&pack_dir);

    let roots = collect_maintenance_object_roots(repo)?;
    if roots.is_empty() && loose_before == 0 && packs_before == 0 {
        return Ok(RepackDetail {
            report,
            prune_packed_loose: 0,
            unreachable_loose: PruneStats::default(),
            unreachable_prune_ms: 0,
            unreachable_prune_ran: !opts.keep_unreachable && !opts.dry_run,
        });
    }

    let cfg = opts
        .merged_config
        .clone()
        .or_else(|| repo.config().ok().map(|c| (*c).clone()));
    let mut pack_opts = opts
        .pack_build
        .unwrap_or_else(|| PackBuildOptions::for_local_copy(cfg.as_ref()));
    if opts.force_recompress {
        pack_opts.reuse_deltas = false;
    }

    let run_incremental = opts.incremental;
    let shallow = load_shallow_boundaries(repo.git_dir());
    let reachable = LazyReachable::new(odb, &roots, &shallow);

    let skip_repack = !opts.force_recompress
        && !opts.write_bitmap
        && !opts.write_commit_graph
        && should_auto_skip_repack(
            loose_before,
            packs_before,
            run_incremental,
            opts.auto_skip,
            cfg.as_ref(),
        )
        && !skipping_repack_would_retain_prunable_packed_objects(odb, &pack_dir, &reachable, opts)?;

    if opts.dry_run {
        report.objects = if skip_repack {
            0
        } else if run_incremental {
            reachable_loose_objects(odb, &reachable)?.len()
        } else {
            estimate_repack_object_count(
                odb,
                &roots,
                &shallow,
                opts.keep_unreachable,
                pack_opts.use_bitmaps,
            )?
        };
        return Ok(RepackDetail {
            report,
            prune_packed_loose: 0,
            unreachable_loose: PruneStats::default(),
            unreachable_prune_ms: 0,
            unreachable_prune_ran: false,
        });
    }

    let built_pack = if skip_repack {
        SerializedDeltaPack {
            bytes: Vec::new(),
            index_rows: Vec::new(),
            staging_path: None,
        }
    } else if run_incremental {
        SerializedDeltaPack {
            bytes: pack_loose_objects_incremental(odb, &reachable, &pack_opts, opts.threads)?,
            index_rows: Vec::new(),
            staging_path: None,
        }
    } else {
        build_repack_pack(
            odb,
            &pack_dir,
            &roots,
            &shallow,
            opts.keep_unreachable,
            &pack_opts,
            opts.threads,
            cfg.as_ref(),
        )?
    };
    let pack_bytes_len = built_pack
        .staging_path
        .as_ref()
        .and_then(|p| std::fs::metadata(p).ok())
        .map(|m| m.len() as usize)
        .unwrap_or_else(|| built_pack.bytes.len());
    // An incremental run with only unreachable loose objects writes no pack but must still
    // expire them below.
    if pack_bytes_len == 0 && !run_incremental {
        return Ok(RepackDetail {
            report,
            prune_packed_loose: 0,
            unreachable_loose: PruneStats::default(),
            unreachable_prune_ms: 0,
            unreachable_prune_ran: false,
        });
    }
    let mut prune_packed_loose = 0usize;
    let mut unreachable_loose = PruneStats::default();
    let pack_trailer_len = 12 + odb.hash_algo().len();
    if pack_bytes_len > pack_trailer_len {
        clear_pack_midx_state(&pack_dir)?;

        let trusted_rows = (!built_pack.index_rows.is_empty()).then_some(built_pack.index_rows);
        let ingest_opts = IngestPackOptions {
            fix_thin: false,
            threads: opts.threads,
            merged_config: cfg.clone(),
            environment: opts.environment.clone(),
            // Locally built pack: trailer checked at write time; index rows match the stream.
            skip_post_index_verify: trusted_rows.is_some(),
            trusted_index_rows: trusted_rows,
            ..IngestPackOptions::default()
        };
        let ingested = if let Some(staging) = built_pack.staging_path.as_ref() {
            install_pack_path(staging, odb, &ingest_opts)?
        } else {
            install_pack_bytes(built_pack.bytes, odb, &ingest_opts)?
        };
        report.packs_written = 1;
        report.objects = ingested.object_ids.len();
        let pack_path = ingested.pack_path.ok_or(Error::UnsupportedObjectStore {
            operation: "repack",
        })?;

        let idx_path = pack_path.with_extension("idx");
        if cfg
            .as_ref()
            .is_none_or(|c| c.pack_write_reverse_index_default(&opts.environment))
        {
            write_pack_rev_sidecar_for_index_path(&idx_path)?;
        }

        if opts.write_bitmap {
            if opts.incremental && packs_before > 0 {
                // Per-pack bitmaps require reachability closure within one pack; incremental
                // repack keeps older packs and adds a new layer. Write a multi-pack-index
                // bitmap covering all packs instead of a sidecar on the new pack alone.
                let version = match cfg.as_ref() {
                    Some(c) => midx_version_from_config(c)?,
                    None => None,
                };
                let midx_opts = WriteMultiPackIndexOptions {
                    write_bitmap: true,
                    version,
                    ..WriteMultiPackIndexOptions::default()
                };
                let WriteMultiPackIndexResult { bitmap: _ } =
                    write_multi_pack_index_with_options(&pack_dir, &midx_opts)?;
            } else {
                let bitmap_opts = PackBitmapWriteOptions::default();
                let now = opts
                    .now
                    .map(offset_to_system_time)
                    .unwrap_or(SystemTime::UNIX_EPOCH);
                PackBitmapWriter::write(repo, &idx_path, &bitmap_opts, now)
                    .map_err(|e| Error::CorruptObject(e.to_string()))?;
            }
        }

        let retention = if opts.keep_unreachable {
            UnreachablePackRetention::KeepAll
        } else if let Some(cutoff) = opts.prune_older_than.map(offset_to_system_time) {
            UnreachablePackRetention::KeepGraceProtected(cutoff)
        } else {
            UnreachablePackRetention::DropAll
        };
        // Incremental repack keeps every existing pack, so nothing is superseded.
        if !opts.incremental {
            odb.loosen_unreachable_from_superseded_packs(
                &pack_dir, &pack_path, &reachable, retention,
            )?;
        }

        // Drop cached pack/index mmaps before deleting superseded pack artifacts (Windows).
        odb.invalidate_packs();

        report.packs_removed = if opts.incremental {
            0
        } else {
            remove_superseded_pack_files(&pack_dir, &pack_path)?
        };

        prune_packed_loose =
            prune_packed_objects(objects_dir, PrunePackedOptions::default())?.len();

        if opts.write_commit_graph {
            write_commit_graph(
                repo,
                &CommitGraphOptions::with_changed_paths(existing_commit_graph_has_changed_paths(
                    repo,
                )),
            )?;
        }
    }

    let mut unreachable_prune_ms = 0u64;
    let mut unreachable_prune_ran = false;
    if !opts.keep_unreachable {
        let keep_newer_than = opts.prune_older_than.map(offset_to_system_time);
        let prune_start = Instant::now();
        unreachable_loose = prune_loose_unreachable_with(odb, &reachable, keep_newer_than, false)?;
        unreachable_prune_ms = prune_start.elapsed().as_millis() as u64;
        unreachable_prune_ran = true;
    }

    report.loose_removed = prune_packed_loose + unreachable_loose.pruned;
    Ok(RepackDetail {
        report,
        prune_packed_loose,
        unreachable_loose,
        unreachable_prune_ms,
        unreachable_prune_ran,
    })
}

/// Like [`repack`], with legacy [`RepackStats`] fields for the CLI.
pub fn repack_all(repo: &Repository, opts: &RepackOptions) -> Result<RepackStats> {
    let odb = repo.odb();
    let objects_dir = odb
        .files_objects_dir()
        .ok_or(Error::UnsupportedObjectStore {
            operation: "repack",
        })?;
    let pack_dir = objects_dir.join("pack");
    let mut stats = RepackStats {
        loose_before: count_loose_objects(odb)?,
        packs_before: count_pack_files(&pack_dir),
        ..RepackStats::default()
    };
    if opts.dry_run {
        let count = repack_detail(repo, opts)?.report.objects;
        stats.objects_packed = (count > 0).then_some(count);
        return Ok(stats);
    }
    let detail = repack_detail(repo, opts)?;
    let report = detail.report;
    stats.objects_packed = (report.packs_written > 0).then_some(report.objects);
    stats.removed_pack_files = report.packs_removed;
    stats.pruned_loose = detail.prune_packed_loose;
    stats.unreachable_loose_pruned = detail.unreachable_loose.pruned;
    stats.unreachable_loose_kept = detail.unreachable_loose.kept;
    stats.unreachable_prune_ms = detail.unreachable_prune_ms;
    stats.unreachable_prune_ran = detail.unreachable_prune_ran;
    if report.packs_written > 0 {
        let packs: Vec<_> = fs::read_dir(&pack_dir)
            .ok()
            .into_iter()
            .flatten()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|x| x == "pack"))
            .map(|e| e.path())
            .collect();
        if packs.len() == 1 {
            stats.pack_path = Some(packs[0].clone());
            stats.pack_bytes = packs[0].metadata().ok().map(|m| m.len());
        }
    }
    Ok(stats)
}

fn offset_to_system_time(odt: OffsetDateTime) -> SystemTime {
    SystemTime::UNIX_EPOCH
        + std::time::Duration::new(odt.unix_timestamp().max(0) as u64, odt.nanosecond())
}

fn apply_gc_prune_policy_to_repack(repack: &mut RepackOptions, policy: &GcLoosePrunePolicy) {
    match policy {
        GcLoosePrunePolicy::Disabled => {
            repack.keep_unreachable = true;
        }
        GcLoosePrunePolicy::Enabled { keep_newer_than } => {
            repack.keep_unreachable = false;
            repack.prune_older_than = keep_newer_than.map(|t| {
                let dur = t.duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default();
                OffsetDateTime::from_unix_timestamp(dur.as_secs() as i64)
                    .unwrap_or(OffsetDateTime::UNIX_EPOCH)
            });
        }
    }
}

fn gc_repack_writes_bitmap(repo: &Repository, config: &ConfigSet) -> bool {
    if let Some(Ok(v)) = config.get_bool("repack.writeBitmaps") {
        return v;
    }
    repo.work_tree().is_none()
}

/// Loose objects reachable from the maintenance roots: what Git's incremental `repack -d`
/// packs. Unreachable loose objects stay loose so `gc.pruneExpire` can expire them.
fn reachable_loose_objects(odb: &Odb, reachable: &LazyReachable<'_>) -> Result<Vec<ObjectId>> {
    let loose = odb.enumerate_local_loose_objects()?;
    if loose.is_empty() {
        return Ok(Vec::new());
    }
    let reachable = reachable.get()?;
    Ok(loose
        .into_iter()
        .map(|(oid, _)| oid)
        .filter(|oid| reachable.contains(oid))
        .collect())
}

fn pack_loose_objects_incremental(
    odb: &Odb,
    reachable: &LazyReachable<'_>,
    pack_opts: &PackBuildOptions,
    threads: Option<usize>,
) -> Result<Vec<u8>> {
    let loose = reachable_loose_objects(odb, reachable)?;
    if loose.is_empty() {
        return Ok(Vec::new());
    }
    let mut incremental_opts = *pack_opts;
    incremental_opts.delta = false;
    incremental_opts.reuse_deltas = false;
    incremental_opts.use_bitmaps = false;
    build_pack_from_send_list_with_parallel_threads(
        odb,
        &loose,
        &HashSet::new(),
        &incremental_opts,
        &HashMap::new(),
        None,
        threads,
    )
}

/// Whether maintenance should skip rebuilding packs when [`RepackOptions::auto_skip`] is set.
///
/// Used by [`gc`]: skip when a single pack already holds all objects and nothing is loose.
/// Multiple packs never skip (consolidation required), even when `gc.autoPackLimit` is zero.
fn should_auto_skip_repack(
    loose_objects: usize,
    pack_count: usize,
    incremental: bool,
    auto_skip: bool,
    _config: Option<&ConfigSet>,
) -> bool {
    if !auto_skip || incremental {
        return false;
    }
    if pack_count > 1 {
        return false;
    }
    if pack_count == 1 {
        return loose_objects == 0;
    }
    loose_objects == 0
}

/// True when skipping repack would leave unreachable objects in pack storage that repack would
/// remove under `opts` (for example expired unreachable commits when `gc.pruneExpire=now`).
///
/// The reachability walk only runs once some pack is old enough to have objects dropped.
fn skipping_repack_would_retain_prunable_packed_objects(
    odb: &Odb,
    pack_dir: &Path,
    reachable: &LazyReachable<'_>,
    opts: &RepackOptions,
) -> Result<bool> {
    if opts.keep_unreachable {
        return Ok(false);
    }
    let retention = if let Some(cutoff) = opts.prune_older_than.map(offset_to_system_time) {
        UnreachablePackRetention::KeepGraceProtected(cutoff)
    } else {
        UnreachablePackRetention::DropAll
    };
    let indexes = crate::pack::read_local_pack_indexes_cached(odb.objects_dir())?;
    for idx in indexes {
        if pack_has_keep_marker(pack_dir, &idx.pack_path) {
            continue;
        }
        let pack_mtime = fs::metadata(&idx.pack_path)
            .and_then(|m| m.modified())
            .unwrap_or(SystemTime::UNIX_EPOCH);
        let drop_unreachable_from_pack = match retention {
            UnreachablePackRetention::KeepAll => false,
            UnreachablePackRetention::DropAll => true,
            UnreachablePackRetention::KeepGraceProtected(cutoff) => pack_mtime < cutoff,
        };
        if !drop_unreachable_from_pack {
            continue;
        }
        let reachable = reachable.get()?;
        for entry in idx.iter() {
            let Ok(oid) = ObjectId::from_bytes(entry.oid()) else {
                continue;
            };
            if !reachable.contains(&oid) {
                return Ok(true);
            }
        }
    }
    Ok(false)
}

/// Delete unreachable loose objects using `gc.pruneExpire` or an explicit cutoff.
///
/// # Errors
///
/// Propagates config parse failures, unsupported ODB backends, and I/O errors.
pub fn prune_loose_objects(repo: &Repository, opts: &PruneOptions) -> Result<PruneStats> {
    let odb = repo.odb();
    odb.require_files_primary("prune")?;
    let cfg = repo.config()?;
    let now = gc_now_unix(0);
    let keep_newer_than = match opts.older_than {
        Some(t) => Some(t),
        None => match gc_loose_prune_policy(&cfg, now)? {
            GcLoosePrunePolicy::Disabled => return Ok(PruneStats::default()),
            GcLoosePrunePolicy::Enabled { keep_newer_than } => keep_newer_than,
        },
    };
    let roots = collect_maintenance_object_roots(repo)?;
    let shallow = load_shallow_boundaries(repo.git_dir());
    prune_loose_unreachable_with(
        odb,
        &LazyReachable::new(odb, &roots, &shallow),
        keep_newer_than,
        opts.dry_run,
    )
}

fn duration_ms(d: std::time::Duration) -> u64 {
    d.as_millis() as u64
}

/// Run pack-refs, reflog expiry, repack, prune, and commit-graph maintenance.
///
/// Unless [`RepackOptions::dry_run`] is set, holds the repository's `gc.pid` lock for the
/// whole run, so it never overlaps another grit or Git gc (see [`GcLock`]).
///
/// # Errors
///
/// [`Error::MaintenanceRunning`] when another process holds the `gc.pid` lock, plus failures
/// from each maintenance step.
pub fn gc(repo: &Repository, opts: &GcOptions) -> Result<GcStats> {
    repo.odb().require_files_primary("gc")?;
    let now = gc_now_unix(opts.now_unix);
    let _lock = if opts.repack.dry_run {
        None
    } else {
        match GcLock::try_acquire(repo, now)? {
            GcLockAttempt::Acquired(lock) => Some(lock),
            GcLockAttempt::Held(holder) => return Err(Error::MaintenanceRunning { holder }),
        }
    };
    gc_locked(repo, opts, now)
}

/// Why automatic maintenance is due, as decided by [`auto_gc_needed`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutoGcReason {
    /// The loose-object estimate is above `gc.auto`. [`gc_auto`] packs the reachable loose
    /// objects into one new pack and leaves existing packs alone.
    TooManyLoose {
        /// Loose objects in the sampled fan-out directory (`objects/17`) times 256.
        estimate: usize,
        /// Effective `gc.auto` threshold.
        limit: usize,
    },
    /// There are more non-`.keep` packs than `gc.autoPackLimit`. [`gc_auto`] consolidates
    /// every pack into one.
    TooManyPacks {
        /// Local packs without a `.keep` marker.
        count: usize,
        /// Effective `gc.autoPackLimit`.
        limit: usize,
    },
}

/// Fan-out directory sampled to estimate the loose-object count, as Git documents for `gc.auto`.
const AUTO_GC_SAMPLE_FANOUT: &str = "17";

/// Decide whether automatic maintenance is due, using Git's `gc --auto` heuristics.
///
/// Pack consolidation wins when the number of local packs without a `.keep` marker is above
/// [`ConfigSet::gc_auto_pack_limit`]. Otherwise the loose-object count is estimated from a
/// single fan-out directory (`objects/17`) and compared with [`ConfigSet::gc_auto_threshold`],
/// so the check costs two directory reads however large the repository is. `gc.auto <= 0`
/// turns both checks off. Repositories without a files object store never need it.
///
/// This does not look at `maintenance.auto`; callers that start maintenance after a command
/// check [`ConfigSet::maintenance_auto`] themselves.
///
/// # Errors
///
/// Config load failures and I/O errors other than a missing directory.
pub fn auto_gc_needed(repo: &Repository) -> Result<Option<AutoGcReason>> {
    let cfg = repo.config()?;
    let Some(threshold) = cfg.gc_auto_threshold() else {
        return Ok(None);
    };
    let Some(objects_dir) = repo.odb().files_objects_dir() else {
        return Ok(None);
    };
    if let Some(limit) = cfg.gc_auto_pack_limit() {
        let count = count_pack_files(&objects_dir.join("pack"));
        if count > limit {
            return Ok(Some(AutoGcReason::TooManyPacks { count, limit }));
        }
    }
    let name_len = repo.odb().hash_algo().hex_len() - 2;
    let sampled = count_loose_in_fanout(&objects_dir.join(AUTO_GC_SAMPLE_FANOUT), name_len)?;
    if sampled > threshold.div_ceil(256) {
        return Ok(Some(AutoGcReason::TooManyLoose {
            estimate: sampled.saturating_mul(256),
            limit: threshold,
        }));
    }
    Ok(None)
}

/// Count entries of one loose-object fan-out directory that look like object files.
fn count_loose_in_fanout(dir: &Path, name_len: usize) -> Result<usize> {
    let entries = match fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(0),
        Err(e) => return Err(Error::Io(e)),
    };
    Ok(entries
        .filter_map(|e| e.ok())
        .filter(|e| {
            let name = e.file_name();
            let name = name.as_encoded_bytes();
            name.len() == name_len && name.iter().all(u8::is_ascii_hexdigit)
        })
        .count())
}

/// Result of [`gc_auto`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AutoGcOutcome {
    /// Neither threshold is exceeded (or `gc.auto` is off); nothing ran.
    NotNeeded,
    /// Another process holds the `gc.pid` lock; nothing ran.
    AlreadyRunning(GcLockHolder),
    /// The `pre-auto-gc` hook exited non-zero; nothing ran.
    DeclinedByHook {
        /// Exit status of the hook.
        status: i32,
        /// What the hook wrote, when hook output is captured ([`Repository::hook_stdio`]).
        output: crate::hooks::HookOutput,
    },
    /// Maintenance ran.
    Ran {
        /// Which threshold triggered the run.
        reason: AutoGcReason,
        /// What each step did.
        stats: Box<GcStats>,
    },
}

/// Run maintenance only when Git's `gc --auto` heuristics say it is due ([`auto_gc_needed`]).
///
/// When too many loose objects triggered the run, the reachable ones are packed into one new
/// pack without rewriting existing packs and without a bitmap, so the cost scales with the
/// loose objects rather than the repository. Unreachable loose objects stay loose until
/// `gc.pruneExpire` lets the prune step delete them, as in Git. Too many packs runs a full consolidating [`gc`]. Either way the
/// other `opts` steps (pack-refs, reflog expiry, unreachable prune under `gc.pruneExpire`,
/// commit-graph) run as in [`gc`].
///
/// Before doing any work this takes the `gc.pid` lock ([`GcLock`]) and runs the `pre-auto-gc`
/// hook; a held lock or a failing hook ends the call without changes. With
/// [`RepackOptions::dry_run`] neither happens and the returned stats describe the planned work.
///
/// The library never forks: callers that honor [`ConfigSet::gc_auto_detach`] start a separate
/// process that calls this function.
///
/// # Errors
///
/// Config, hook spawn, lock and I/O failures, and any error from the maintenance steps.
pub fn gc_auto(repo: &Repository, opts: &GcOptions) -> Result<AutoGcOutcome> {
    let Some(reason) = auto_gc_needed(repo)? else {
        return Ok(AutoGcOutcome::NotNeeded);
    };
    let now = gc_now_unix(opts.now_unix);
    let dry_run = opts.repack.dry_run;
    let _lock = if dry_run {
        None
    } else {
        match GcLock::try_acquire(repo, now)? {
            GcLockAttempt::Acquired(lock) => Some(lock),
            GcLockAttempt::Held(holder) => return Ok(AutoGcOutcome::AlreadyRunning(holder)),
        }
    };
    if !dry_run {
        if let crate::hooks::HookResult::Failed { status, output } =
            crate::hooks::run_hook(repo, "pre-auto-gc", &[], None)?
        {
            return Ok(AutoGcOutcome::DeclinedByHook { status, output });
        }
    }
    let mut run_opts = opts.clone();
    if matches!(reason, AutoGcReason::TooManyLoose { .. }) {
        run_opts.repack.incremental = true;
        run_opts.repack.write_bitmap = false;
    }
    let stats = gc_locked(repo, &run_opts, now)?;
    Ok(AutoGcOutcome::Ran {
        reason,
        stats: Box::new(stats),
    })
}

/// Process recorded in `gc.pid` by a maintenance run that is still in progress.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GcLockHolder {
    /// Process id from `gc.pid`, when it could be read.
    pub pid: Option<u64>,
    /// Host name from `gc.pid`, when it could be read.
    pub host: Option<String>,
}

/// Outcome of [`GcLock::try_acquire`].
#[derive(Debug)]
#[must_use]
pub enum GcLockAttempt {
    /// This process now owns `gc.pid`.
    Acquired(GcLock),
    /// Another live maintenance run owns it.
    Held(GcLockHolder),
}

/// How long a `gc.pid` written by another run is honored before it is treated as stale.
const GC_PID_STALE_AFTER: time::Duration = time::Duration::hours(12);

/// Repository-wide maintenance lock, compatible with Git's `gc.pid`.
///
/// The lock file holds `"<pid> <hostname>"` and is removed when this value is dropped. An
/// existing `gc.pid` counts as held while it is younger than 12 hours and either names another
/// host or a process on this host that is still running; older or dead entries are taken over.
#[derive(Debug)]
pub struct GcLock {
    path: PathBuf,
}

impl GcLock {
    /// Try to take the `gc.pid` lock in the repository's common directory without waiting.
    ///
    /// `now_unix` is the wall clock used to decide whether an existing `gc.pid` is stale.
    ///
    /// # Errors
    ///
    /// I/O failures while creating, writing or renaming the lock file.
    pub fn try_acquire(repo: &Repository, now_unix: i64) -> Result<GcLockAttempt> {
        let path = repo.common_git_dir().join("gc.pid");
        let mut lock = match crate::lockfile::LockFile::acquire(
            &path.with_extension("pid.lock"),
            crate::lockfile::LockWait::Immediately,
        ) {
            Ok(lock) => lock,
            Err(crate::lockfile::LockError::Held { .. }) => {
                return Ok(GcLockAttempt::Held(read_gc_pid(&path).unwrap_or(
                    GcLockHolder {
                        pid: None,
                        host: None,
                    },
                )));
            }
            Err(crate::lockfile::LockError::Io { source, .. }) => return Err(Error::Io(source)),
        };
        let host = local_host_name();
        if let Some(holder) = live_gc_pid_holder(&path, &host, now_unix) {
            lock.rollback();
            return Ok(GcLockAttempt::Held(holder));
        }
        use std::io::Write as _;
        write!(lock, "{} {host}", std::process::id())?;
        lock.commit_to(&path).map_err(|e| match e {
            crate::lockfile::LockError::Io { source, .. } => Error::Io(source),
            held @ crate::lockfile::LockError::Held { .. } => Error::Io(io::Error::other(held)),
        })?;
        Ok(GcLockAttempt::Acquired(GcLock { path }))
    }

    /// The maintenance run currently holding `gc.pid`, without taking the lock.
    ///
    /// Uses the same staleness rules as [`Self::try_acquire`], so `None` means an attempt would
    /// most likely succeed. Lets a caller avoid starting a process that would only find the
    /// lock held.
    #[must_use]
    pub fn current_holder(repo: &Repository, now_unix: i64) -> Option<GcLockHolder> {
        let path = repo.common_git_dir().join("gc.pid");
        live_gc_pid_holder(&path, &local_host_name(), now_unix)
    }
}

impl Drop for GcLock {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

fn read_gc_pid(path: &Path) -> Option<GcLockHolder> {
    let raw = fs::read_to_string(path).ok()?;
    let mut fields = raw.split_whitespace();
    let pid = fields.next().and_then(|p| p.parse::<u64>().ok());
    let host = fields.next().map(str::to_owned);
    Some(GcLockHolder { pid, host })
}

/// The holder recorded in `gc.pid` when it still blocks a new run on `host`.
fn live_gc_pid_holder(path: &Path, host: &str, now_unix: i64) -> Option<GcLockHolder> {
    let mtime = fs::metadata(path).and_then(|m| m.modified()).ok()?;
    let mtime = OffsetDateTime::from(mtime);
    let now = OffsetDateTime::from_unix_timestamp(now_unix).ok()?;
    if now - mtime > GC_PID_STALE_AFTER {
        return None;
    }
    let holder = read_gc_pid(path)?;
    let pid = holder.pid?;
    let same_host = holder.host.as_deref() == Some(host);
    if same_host && !crate::index::is_process_running(pid) {
        return None;
    }
    Some(holder)
}

/// Host name as Git records it in `gc.pid` (`gethostname`), so either tool can tell whether
/// the other's lock belongs to this machine.
fn local_host_name() -> String {
    #[cfg(unix)]
    {
        if let Ok(uts) = nix::sys::utsname::uname() {
            if let Some(name) = uts.nodename().to_str() {
                return name.to_owned();
            }
        }
    }
    #[cfg(windows)]
    {
        if let Some(name) = windows_dns_host_name() {
            return name;
        }
    }
    "localhost".to_owned()
}

/// The DNS host name, which is what Winsock `gethostname` (used by Git for Windows) returns.
#[cfg(windows)]
fn windows_dns_host_name() -> Option<String> {
    use windows_sys::Win32::System::SystemInformation::{
        ComputerNameDnsHostname, GetComputerNameExW,
    };
    let mut len: u32 = 0;
    // SAFETY: a null buffer with zero length only asks for the required size in `len`.
    unsafe { GetComputerNameExW(ComputerNameDnsHostname, std::ptr::null_mut(), &mut len) };
    if len == 0 {
        return None;
    }
    let mut buf = vec![0u16; len as usize];
    // SAFETY: `buf` has room for the `len` UTF-16 units the previous call asked for.
    let ok = unsafe { GetComputerNameExW(ComputerNameDnsHostname, buf.as_mut_ptr(), &mut len) };
    (ok != 0).then(|| String::from_utf16_lossy(&buf[..len as usize]))
}

fn gc_locked(repo: &Repository, opts: &GcOptions, now: i64) -> Result<GcStats> {
    let mut stats = GcStats::default();
    let cfg = repo.config()?;
    let prune_policy = gc_loose_prune_policy(&cfg, now)?;
    let dry_run = opts.repack.dry_run;

    if opts.pack_refs && !dry_run {
        let start = Instant::now();
        stats.pack_refs = Some(pack_refs(repo, &PackRefsOptions::with_all(true))?);
        stats.phase_timings.pack_refs_ms = duration_ms(start.elapsed());
    }

    if opts.expire_reflog {
        let start = Instant::now();
        stats.reflog_entries_pruned = expire_reflogs_for_gc(repo, dry_run, now)?;
        stats.phase_timings.reflog_ms = duration_ms(start.elapsed());
    }

    let mut repack_opts = opts.repack.clone();
    apply_gc_prune_policy_to_repack(&mut repack_opts, &prune_policy);
    if repack_opts.now.is_none() {
        repack_opts.now =
            Some(OffsetDateTime::from_unix_timestamp(now).unwrap_or(OffsetDateTime::UNIX_EPOCH));
    }
    // Incremental runs skip bitmaps, as Git's `gc --auto` does: a bitmap covers the whole
    // object graph and costs far more than packing the loose objects.
    if !repack_opts.write_bitmap && !repack_opts.incremental {
        repack_opts.write_bitmap = gc_repack_writes_bitmap(repo, &cfg);
    }
    let repack_start = Instant::now();
    stats.repack = repack_all(repo, &repack_opts)?;
    let repack_total_ms = duration_ms(repack_start.elapsed());
    stats.phase_timings.prune_ms = stats.repack.unreachable_prune_ms;
    stats.phase_timings.repack_ms = repack_total_ms.saturating_sub(stats.phase_timings.prune_ms);

    if dry_run {
        return Ok(stats);
    }

    // Repack prunes unreachable loose objects itself (sharing its reachability walk), so gc
    // only reports the outcome.
    stats.prune_ran = stats.repack.unreachable_prune_ran;
    stats.prune = PruneStats {
        pruned: stats.repack.unreachable_loose_pruned,
        kept: stats.repack.unreachable_loose_kept,
    };

    if opts.write_commit_graph {
        let start = Instant::now();
        stats.commit_graph = Some(write_commit_graph(
            repo,
            &CommitGraphOptions::with_changed_paths(existing_commit_graph_has_changed_paths(repo)),
        )?);
        stats.phase_timings.commit_graph_ms = duration_ms(start.elapsed());
    }
    Ok(stats)
}

/// How [`gc`] applies loose-object pruning for `gc.pruneExpire`.
enum GcLoosePrunePolicy {
    /// `gc.pruneExpire=never` — do not delete unreachable loose objects.
    Disabled,
    /// Prune unreachable loose objects not protected by the grace cutoff.
    Enabled {
        /// When `Some(t)`, only delete loose objects strictly older than `t` (Git grace window).
        keep_newer_than: Option<SystemTime>,
    },
}

fn gc_loose_prune_policy(config: &ConfigSet, now_unix: i64) -> Result<GcLoosePrunePolicy> {
    let spec = config
        .get("gc.pruneExpire")
        .map(|s| s.trim().to_owned())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "2.weeks.ago".to_owned());
    if spec.eq_ignore_ascii_case("never") || spec.eq_ignore_ascii_case("false") {
        return Ok(GcLoosePrunePolicy::Disabled);
    }
    // Git expires everything for `now` and `all`, including objects written this second.
    if spec.eq_ignore_ascii_case("now") || spec.eq_ignore_ascii_case("all") {
        return Ok(GcLoosePrunePolicy::Enabled {
            keep_newer_than: None,
        });
    }
    let mut err = 0;
    let cutoff_sec = approxidate_careful_at(&spec, now_unix, Some(&mut err)) as i64;
    if err != 0 {
        return Err(Error::Config(ConfigError::Other(format!(
            "bad config value '{spec}' for 'gc.pruneExpire'"
        ))));
    }
    let keep_newer_than = SystemTime::UNIX_EPOCH
        .checked_add(std::time::Duration::from_secs(cutoff_sec.max(0) as u64));
    Ok(GcLoosePrunePolicy::Enabled { keep_newer_than })
}

fn gc_now_unix(now_unix: i64) -> i64 {
    if now_unix != 0 {
        return now_unix;
    }
    time::OffsetDateTime::now_utc().unix_timestamp()
}

fn expire_reflogs_for_gc(repo: &Repository, dry_run: bool, now: i64) -> Result<usize> {
    let cfg = repo.config()?;
    let gc_cfg = load_gc_reflog_expire_config(&cfg, now);
    let git_dir = repo.git_dir();
    let params = ReflogExpireParams {
        stale_fix: false,
        dry_run,
        verbose: false,
    };
    let mut total = 0usize;
    for refname in list_reflog_refs(git_dir)? {
        let result = expire_reflog_git(
            repo,
            git_dir,
            &refname,
            &params,
            None,
            None,
            &gc_cfg.patterns,
            gc_cfg.global_total,
            gc_cfg.global_unreachable,
            now,
        )?;
        total += result.pruned;
    }
    Ok(total)
}

fn count_loose_objects(odb: &Odb) -> Result<usize> {
    Ok(odb.enumerate_local_loose_objects()?.len())
}

/// Build the all-into-one repack pack for `roots`, stopping history at the `shallow`
/// boundary commits.
#[allow(clippy::too_many_arguments)]
fn build_repack_pack(
    odb: &Odb,
    pack_dir: &Path,
    roots: &[ObjectId],
    shallow: &HashSet<ObjectId>,
    keep_unreachable: bool,
    opts: &PackBuildOptions,
    threads: Option<usize>,
    cfg: Option<&ConfigSet>,
) -> Result<SerializedDeltaPack> {
    let selection = repack_object_list(odb, roots, shallow, keep_unreachable, opts.use_bitmaps)?;
    odb.clear_delta_base_cache();
    let max_depth = if opts.delta { opts.max_depth } else { 0 };
    let settings = RepackPackSettings {
        window: opts.window,
        max_depth,
        reuse_deltas: opts.reuse_deltas,
        reuse_objects: opts.reuse_objects,
        use_ofs_delta: opts.use_ofs_delta,
        window_memory: cfg.map_or(0, ConfigSet::pack_window_memory_bytes),
        search_threads: pack_delta_search_parallel_options(odb, threads)?
            .threads
            .get(),
        write_threads: pack_write_parallel_options(odb, threads)?.threads.get(),
    };
    fs::create_dir_all(pack_dir).map_err(Error::Io)?;
    let staging = pack_dir.join(format!("tmp_repack_{}", std::process::id()));
    let written = write_repack_pack(
        odb,
        &selection.send,
        &selection.name_hashes,
        &settings,
        &staging,
    );
    match written {
        Ok(index_rows) => Ok(SerializedDeltaPack {
            bytes: Vec::new(),
            index_rows,
            staging_path: Some(staging),
        }),
        Err(err) => {
            let _ = fs::remove_file(&staging);
            Err(err)
        }
    }
}

/// Objects a full repack writes: everything reachable from `roots` down to the
/// `shallow` boundary commits, plus every other packed and loose object when
/// `keep_unreachable` is set.
fn repack_object_list(
    odb: &Odb,
    roots: &[ObjectId],
    shallow: &HashSet<ObjectId>,
    keep_unreachable: bool,
    use_bitmaps: bool,
) -> Result<PackObjectSelection> {
    // Roots arrive in hash-set order; sorting them makes the pack (and its name)
    // the same on every run.
    let mut roots = roots.to_vec();
    roots.sort_unstable();
    let mut selection = enumerate_pack_objects_naming(
        odb,
        &roots,
        &[],
        &PackEnumerateOptions {
            filter: None,
            shallow_grafts: shallow,
            have_shallow_grafts: Some(shallow),
            use_bitmaps,
            exclude_objects: None,
            peer_odb: None,
        },
        NameTrees::Yes,
    )?;
    if keep_unreachable {
        append_repack_unreachable_retention(odb, &mut selection.send)?;
    }
    Ok(selection)
}

/// Append packed and loose objects not already selected for the repack send list.
fn append_repack_unreachable_retention(odb: &Odb, send: &mut Vec<ObjectId>) -> Result<()> {
    let mut in_send: OidHashSet = send.iter().copied().collect();
    odb.primary()?
        .packed_objects()
        .for_each_removable_pack_object(&mut |oid| {
            if in_send.insert(*oid) {
                send.push(*oid);
            }
            std::ops::ControlFlow::Continue(())
        })?;
    for (oid, _) in odb.enumerate_local_loose_objects()? {
        if in_send.insert(oid) {
            send.push(oid);
        }
    }
    Ok(())
}

fn estimate_repack_object_count(
    odb: &Odb,
    roots: &[ObjectId],
    shallow: &HashSet<ObjectId>,
    keep_unreachable: bool,
    use_bitmaps: bool,
) -> Result<usize> {
    if !keep_unreachable {
        return estimate_reachable_count(odb, roots, shallow);
    }
    Ok(repack_object_list(odb, roots, shallow, true, use_bitmaps)?
        .send
        .len())
}

/// Packs in `pack_dir` without a `.keep` marker, from a single directory read.
fn count_pack_files(pack_dir: &Path) -> usize {
    let Ok(entries) = fs::read_dir(pack_dir) else {
        return 0;
    };
    let mut packs = HashSet::new();
    let mut kept = HashSet::new();
    for entry in entries.filter_map(|e| e.ok()) {
        let path = PathBuf::from(entry.file_name());
        let (Some(stem), Some(ext)) = (path.file_stem(), path.extension()) else {
            continue;
        };
        if ext == "pack" {
            packs.insert(stem.to_owned());
        } else if ext == "keep" {
            kept.insert(stem.to_owned());
        }
    }
    packs.difference(&kept).count()
}

fn estimate_reachable_count(
    odb: &Odb,
    roots: &[ObjectId],
    shallow: &HashSet<ObjectId>,
) -> Result<usize> {
    let mut seen: HashSet<ObjectId> = HashSet::new();
    let mut queue: VecDeque<ObjectId> = VecDeque::new();
    for &root in roots {
        if seen.insert(root) {
            queue.push_back(root);
        }
    }
    while let Some(oid) = queue.pop_front() {
        let obj = match odb.read(&oid) {
            Ok(o) => o,
            Err(_) => continue,
        };
        match obj.kind {
            ObjectKind::Commit => {
                let commit = parse_commit(&obj.data)?;
                if !shallow.contains(&oid) {
                    for parent in commit.parents {
                        if seen.insert(parent) {
                            queue.push_back(parent);
                        }
                    }
                }
                if seen.insert(commit.tree) {
                    queue.push_back(commit.tree);
                }
            }
            ObjectKind::Tree => {
                for entry in parse_tree(&obj.data)? {
                    if entry.mode == 0o160000 {
                        continue;
                    }
                    if seen.insert(entry.oid) {
                        queue.push_back(entry.oid);
                    }
                }
            }
            ObjectKind::Tag => {
                let tag = parse_tag(&obj.data)?;
                if seen.insert(tag.object) {
                    queue.push_back(tag.object);
                }
            }
            ObjectKind::Blob => {}
        }
    }
    Ok(seen.len())
}

/// Remove pack artifacts in `pack_dir` except those belonging to `keep_pack`.
pub fn remove_superseded_pack_files(pack_dir: &Path, keep_pack: &Path) -> Result<usize> {
    let keep_stem = keep_pack
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or_else(|| Error::Io(io::Error::new(io::ErrorKind::InvalidInput, "bad pack path")))?;
    if !pack_dir.is_dir() {
        return Ok(0);
    }
    let mut removed = 0usize;
    for entry in fs::read_dir(pack_dir).map_err(Error::Io)? {
        let entry = entry.map_err(Error::Io)?;
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        if name_str == keep_stem || name_str.starts_with(&format!("{keep_stem}.")) {
            continue;
        }
        if !(name_str.starts_with("pack-") || name_str.starts_with(".pack-")) {
            continue;
        }
        let path = entry.path();
        if path.is_file() {
            if pack_has_keep_marker(pack_dir, &path) {
                continue;
            }
            fs::remove_file(&path).map_err(Error::Io)?;
            removed += 1;
        }
    }
    Ok(removed)
}

fn pack_has_keep_marker(pack_dir: &Path, path: &Path) -> bool {
    let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
        return false;
    };
    pack_dir.join(format!("{stem}.keep")).is_file()
}

/// Pack loose refs into `packed-refs` (files backend) or compact reftable stacks.
///
/// # Errors
///
/// Propagates ref-store, locking, and I/O failures.
pub fn pack_refs(repo: &Repository, opts: &PackRefsOptions) -> Result<PackRefsReport> {
    let (path, refs_packed, refs_pruned) =
        crate::refs::pack_refs_for_repository(repo, opts.all, opts.dry_run)?;
    Ok(PackRefsReport {
        path,
        refs_packed,
        refs_pruned,
    })
}

impl Repository {
    /// Write a reachable commit-graph file for this repository.
    ///
    /// # Errors
    ///
    /// See [`write_commit_graph`].
    pub fn write_commit_graph(&self, opts: &CommitGraphOptions) -> Result<CommitGraphWriteReport> {
        write_commit_graph(self, opts)
    }

    /// Write or refresh the multi-pack index for this repository's pack directory.
    ///
    /// # Errors
    ///
    /// See [`write_midx`].
    pub fn write_midx(&self, opts: &MidxOptions) -> Result<MidxWriteReport> {
        write_midx(self, opts)
    }
}

/// Standalone object fsck helpers.
pub mod fsck {
    pub use crate::fsck_standalone::*;
}

/// Repository-wide fsck (object store, connectivity, refs).
pub mod repository_fsck {
    pub use crate::fsck::*;
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;
    use crate::config::{ConfigFile, ConfigScope, ConfigSet};
    use crate::porcelain::add::stage_for_commit;
    use crate::porcelain::commit::{create_commit, CommitRequest, HookPolicy};
    use crate::progress::{NeverCancel, NullProgress};
    use crate::repo::InitOptions;
    use tempfile::TempDir;

    #[test]
    fn gc_auto_skip_single_pack_without_loose() {
        let dir = TempDir::new().unwrap();
        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
        std::fs::write(repo.work_tree().unwrap().join("a"), b"x").unwrap();
        stage_for_commit(&repo, &mut NullProgress).expect("stage");
        let ident = "Test <t@example.com> 1 +0000".to_string();
        create_commit(
            &repo,
            &CommitRequest {
                message: "init".into(),
                author: Some(ident.parse().expect("signature")),
                committer: Some(ident.parse().expect("signature")),
                allow_empty: false,
                sign_override: None,
                amend: false,
                assume_worktree_synced: false,
                skip_pre_commit_tree_match: false,
                staged_change_count: None,
                ..Default::default()
            },
            &mut NullProgress,
        )
        .expect("commit");
        git_cmd(dir.path(), &["repack", "-a", "-d"]);
        assert!(should_auto_skip_repack(0, 1, false, true, None));
        assert!(!should_auto_skip_repack(3, 1, false, true, None));
        assert!(!should_auto_skip_repack(0, 2, false, true, None));
        assert!(!should_auto_skip_repack(0, 2, false, false, None));
    }

    #[test]
    fn count_pack_files_ignores_keep_markers() {
        let dir = TempDir::new().unwrap();
        let pack_dir = dir.path().join("pack");
        fs::create_dir_all(&pack_dir).unwrap();
        fs::write(pack_dir.join("pack-aaa.pack"), b"PACK").unwrap();
        fs::write(pack_dir.join("pack-bbb.pack"), b"PACK").unwrap();
        fs::write(pack_dir.join("pack-bbb.keep"), b"").unwrap();
        assert_eq!(count_pack_files(&pack_dir), 1);
    }

    fn repo_with_config(snippet: &str) -> (TempDir, Repository) {
        let dir = TempDir::new().unwrap();
        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
        let config_path = repo.git_dir().join("config");
        let mut config = fs::read_to_string(&config_path).unwrap();
        config.push_str(snippet);
        fs::write(&config_path, config).unwrap();
        repo.reload_config().expect("reload config");
        (dir, repo)
    }

    fn fake_loose(repo: &Repository, fanout: &str, names: &[&str]) {
        let dir = repo.git_dir().join("objects").join(fanout);
        fs::create_dir_all(&dir).unwrap();
        for name in names {
            fs::write(dir.join(name), b"").unwrap();
        }
    }

    const NAME_A: &str = "00000000000000000000000000000000000001";
    const NAME_B: &str = "00000000000000000000000000000000000002";
    const NAME_C: &str = "00000000000000000000000000000000000003";

    #[test]
    fn auto_gc_needed_samples_one_fanout_directory() {
        // gc.auto = 300 allows ceil(300 / 256) = 2 sampled objects.
        let (_dir, repo) = repo_with_config("[gc]\n\tauto = 300\n");
        assert_eq!(auto_gc_needed(&repo).unwrap(), None);
        fake_loose(&repo, "17", &[NAME_A, NAME_B]);
        fake_loose(&repo, "18", &[NAME_C]);
        fake_loose(
            &repo,
            "17",
            &["tmp_obj_123", "0000000000000000000000000000000000000z"],
        );
        assert_eq!(auto_gc_needed(&repo).unwrap(), None);
        fake_loose(&repo, "17", &[NAME_C]);
        assert_eq!(
            auto_gc_needed(&repo).unwrap(),
            Some(AutoGcReason::TooManyLoose {
                estimate: 3 * 256,
                limit: 300
            })
        );
    }

    #[test]
    fn auto_gc_needed_is_off_when_gc_auto_is_zero() {
        let (_dir, repo) = repo_with_config("[gc]\n\tauto = 0\n\tautoPackLimit = 1\n");
        fake_loose(&repo, "17", &[NAME_A, NAME_B, NAME_C]);
        let pack_dir = repo.git_dir().join("objects/pack");
        fs::write(pack_dir.join("pack-aaa.pack"), b"PACK").unwrap();
        fs::write(pack_dir.join("pack-bbb.pack"), b"PACK").unwrap();
        assert_eq!(auto_gc_needed(&repo).unwrap(), None);
        assert_eq!(
            gc_auto(&repo, &GcOptions::default()).unwrap(),
            AutoGcOutcome::NotNeeded
        );
    }

    #[test]
    fn auto_gc_needed_counts_packs_without_keep_markers() {
        let (_dir, repo) = repo_with_config("[gc]\n\tautoPackLimit = 2\n");
        let pack_dir = repo.git_dir().join("objects/pack");
        for stem in ["pack-aaa", "pack-bbb", "pack-ccc"] {
            fs::write(pack_dir.join(format!("{stem}.pack")), b"PACK").unwrap();
        }
        assert_eq!(
            auto_gc_needed(&repo).unwrap(),
            Some(AutoGcReason::TooManyPacks { count: 3, limit: 2 })
        );
        fs::write(pack_dir.join("pack-ccc.keep"), b"").unwrap();
        assert_eq!(auto_gc_needed(&repo).unwrap(), None);
    }

    fn config_snippet(text: &str) -> ConfigSet {
        let file = ConfigFile::parse(Path::new(".git/config"), text, ConfigScope::Local).unwrap();
        let mut set = ConfigSet::new();
        set.merge(&file);
        set
    }

    #[test]
    fn prune_expire_now_and_all_have_no_grace_window() {
        let now = 1_700_000_000;
        for spec in ["now", "all", "NOW"] {
            let cfg = config_snippet(&format!("[gc]\n\tpruneExpire = {spec}\n"));
            assert!(matches!(
                gc_loose_prune_policy(&cfg, now).unwrap(),
                GcLoosePrunePolicy::Enabled {
                    keep_newer_than: None
                }
            ));
        }
        for spec in ["never", "false"] {
            let cfg = config_snippet(&format!("[gc]\n\tpruneExpire = {spec}\n"));
            assert!(matches!(
                gc_loose_prune_policy(&cfg, now).unwrap(),
                GcLoosePrunePolicy::Disabled
            ));
        }
        let cfg = ConfigSet::new();
        assert!(matches!(
            gc_loose_prune_policy(&cfg, now).unwrap(),
            GcLoosePrunePolicy::Enabled {
                keep_newer_than: Some(_)
            }
        ));
    }

    #[test]
    fn gc_lock_is_exclusive_and_released_on_drop() {
        let (_dir, repo) = repo_with_config("");
        let now = OffsetDateTime::now_utc().unix_timestamp();
        let pid_path = repo.git_dir().join("gc.pid");
        let GcLockAttempt::Acquired(lock) = GcLock::try_acquire(&repo, now).unwrap() else {
            panic!("first acquire must succeed");
        };
        let recorded = read_gc_pid(&pid_path).expect("gc.pid written");
        assert_eq!(recorded.pid, Some(u64::from(std::process::id())));
        assert_eq!(recorded.host.as_deref(), Some(local_host_name().as_str()));
        match GcLock::try_acquire(&repo, now).unwrap() {
            GcLockAttempt::Held(holder) => assert_eq!(holder, recorded),
            GcLockAttempt::Acquired(_) => panic!("second acquire must see the live holder"),
        }
        assert_eq!(GcLock::current_holder(&repo, now), Some(recorded));
        assert!(matches!(
            gc(&repo, &GcOptions::default()),
            Err(Error::MaintenanceRunning { .. })
        ));
        assert!(!repo.git_dir().join("gc.pid.lock").exists());
        drop(lock);
        assert!(!pid_path.exists());
        assert_eq!(GcLock::current_holder(&repo, now), None);
        assert!(matches!(
            GcLock::try_acquire(&repo, now).unwrap(),
            GcLockAttempt::Acquired(_)
        ));
    }

    #[test]
    fn gc_lock_takes_over_stale_entries() {
        let (_dir, repo) = repo_with_config("");
        let now = OffsetDateTime::now_utc().unix_timestamp();
        let pid_path = repo.git_dir().join("gc.pid");
        let host = local_host_name();

        // A process on this host that is no longer running.
        fs::write(&pid_path, format!("{} {host}", i32::MAX)).unwrap();
        assert!(matches!(
            GcLock::try_acquire(&repo, now).unwrap(),
            GcLockAttempt::Acquired(_)
        ));

        // Another host cannot be checked, so a recent entry blocks.
        fs::write(&pid_path, "4242 some-other-host").unwrap();
        assert!(matches!(
            GcLock::try_acquire(&repo, now).unwrap(),
            GcLockAttempt::Held(GcLockHolder {
                pid: Some(4242),
                ..
            })
        ));

        // The same entry is ignored once it is older than 12 hours.
        let later = now + time::Duration::hours(13).whole_seconds();
        assert!(matches!(
            GcLock::try_acquire(&repo, later).unwrap(),
            GcLockAttempt::Acquired(_)
        ));
    }

    #[test]
    fn gc_auto_reports_held_lock_without_running() {
        let (_dir, repo) = repo_with_config("[gc]\n\tauto = 1\n");
        fake_loose(&repo, "17", &[NAME_A, NAME_B]);
        fs::write(repo.git_dir().join("gc.pid"), "4242 some-other-host").unwrap();
        let outcome = gc_auto(&repo, &GcOptions::default()).unwrap();
        assert!(
            matches!(&outcome, AutoGcOutcome::AlreadyRunning(holder) if holder.pid == Some(4242)),
            "{outcome:?}"
        );
        assert!(repo.git_dir().join("objects/17").join(NAME_A).exists());
    }

    #[cfg(unix)]
    #[test]
    fn gc_auto_honors_failing_pre_auto_gc_hook() {
        use std::os::unix::fs::PermissionsExt as _;
        let (_dir, repo) = repo_with_config("[gc]\n\tauto = 1\n");
        fake_loose(&repo, "17", &[NAME_A, NAME_B]);
        let hook = repo.git_dir().join("hooks/pre-auto-gc");
        fs::create_dir_all(hook.parent().unwrap()).unwrap();
        fs::write(&hook, "#!/bin/sh\nexit 3\n").unwrap();
        fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap();
        let outcome = gc_auto(&repo, &GcOptions::default()).unwrap();
        assert!(
            matches!(outcome, AutoGcOutcome::DeclinedByHook { status: 3, .. }),
            "{outcome:?}"
        );
        assert!(!repo.git_dir().join("gc.pid").exists());
    }

    fn git_cmd(dir: &Path, args: &[&str]) {
        let status = std::process::Command::new("git")
            .current_dir(dir)
            .args(args)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .status()
            .expect("git");
        assert!(status.success(), "git {args:?}");
    }

    fn assert_fsck_clean(repo: &Repository) {
        let opts = repo_fsck::FsckOptions::full_repository(true).with_check_dangling(false);
        let report = repo_fsck::fsck(repo, &opts, &mut NullProgress, &NeverCancel).expect("fsck");
        assert!(
            report.ok(&repo.config().expect("config"), &opts),
            "{:?}",
            report.issues
        );
    }

    #[test]
    fn fsck_clean_repo_ok() {
        let dir = TempDir::new().unwrap();
        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
        std::fs::write(repo.work_tree().unwrap().join("a"), b"x").unwrap();
        stage_for_commit(&repo, &mut NullProgress).expect("stage");
        let ident = "Test <t@example.com> 1 +0000".to_string();
        create_commit(
            &repo,
            &CommitRequest {
                message: "init".into(),
                author: Some(ident.parse().expect("signature")),
                committer: Some(ident.parse().expect("signature")),
                allow_empty: false,
                sign_override: None,
                amend: false,
                assume_worktree_synced: false,
                skip_pre_commit_tree_match: false,
                staged_change_count: None,
                ..Default::default()
            },
            &mut NullProgress,
        )
        .expect("commit");
        assert_fsck_clean(&repo);
    }

    #[test]
    fn incremental_repack_with_bitmap_keeps_base_pack_and_writes_midx_bitmap() {
        let dir = TempDir::new().unwrap();
        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
        let wt = repo.work_tree().unwrap();
        std::fs::write(wt.join("base"), b"v1").unwrap();
        stage_for_commit(&repo, &mut NullProgress).expect("stage");
        let ident = "Test <t@example.com> 1 +0000".to_string();
        create_commit(
            &repo,
            &CommitRequest {
                message: "base".into(),
                author: Some(ident.parse().expect("signature")),
                committer: Some(ident.parse().expect("signature")),
                allow_empty: false,
                sign_override: None,
                amend: false,
                assume_worktree_synced: false,
                skip_pre_commit_tree_match: false,
                staged_change_count: None,
                ..Default::default()
            },
            &mut NullProgress,
        )
        .expect("commit");
        repack_all(
            &repo,
            &RepackOptions {
                keep_unreachable: false,
                ..RepackOptions::default()
            },
        )
        .expect("repack base");
        let pack_dir = repo.git_dir().join("objects/pack");
        assert_eq!(count_pack_files(&pack_dir), 1);

        std::fs::write(wt.join("child"), b"v2").unwrap();
        stage_for_commit(&repo, &mut NullProgress).expect("stage child");
        create_commit(
            &repo,
            &CommitRequest {
                message: "child".into(),
                author: Some(ident.parse().expect("signature")),
                committer: Some(ident.parse().expect("signature")),
                allow_empty: false,
                sign_override: None,
                amend: false,
                assume_worktree_synced: false,
                skip_pre_commit_tree_match: false,
                staged_change_count: None,
                ..Default::default()
            },
            &mut NullProgress,
        )
        .expect("child commit");
        assert!(count_loose_objects(repo.odb()).expect("loose") >= 2);

        let packs_before = count_pack_files(&pack_dir);
        repack_all(
            &repo,
            &RepackOptions {
                incremental: true,
                write_bitmap: true,
                ..RepackOptions::default()
            },
        )
        .expect("incremental repack with bitmap must not fail after installing a pack");

        assert!(
            count_pack_files(&pack_dir) > packs_before,
            "incremental repack should add a pack"
        );
        let midx = pack_dir.join("multi-pack-index");
        assert!(
            midx.is_file(),
            "expected multi-pack-index after bitmap repack"
        );
        let midx_bytes = fs::read(&midx).expect("read midx");
        assert_eq!(
            midx_bytes.get(4),
            Some(&1),
            "MIDX on-disk version must be v1 for system git compatibility"
        );
        let bitmaps: Vec<_> = fs::read_dir(&pack_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|x| x == "bitmap"))
            .collect();
        assert!(
            !bitmaps.is_empty(),
            "expected a MIDX or pack bitmap sidecar after incremental repack with write_bitmap"
        );

        assert_fsck_clean(&repo);
    }

    #[test]
    fn incremental_repack_adds_pack_without_removing_base() {
        let dir = TempDir::new().unwrap();
        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
        let wt = repo.work_tree().unwrap();
        std::fs::write(wt.join("base"), b"v1").unwrap();
        stage_for_commit(&repo, &mut NullProgress).expect("stage");
        let ident = "Test <t@example.com> 1 +0000".to_string();
        create_commit(
            &repo,
            &CommitRequest {
                message: "base".into(),
                author: Some(ident.parse().expect("signature")),
                committer: Some(ident.parse().expect("signature")),
                allow_empty: false,
                sign_override: None,
                amend: false,
                assume_worktree_synced: false,
                skip_pre_commit_tree_match: false,
                staged_change_count: None,
                ..Default::default()
            },
            &mut NullProgress,
        )
        .expect("commit");
        repack_all(
            &repo,
            &RepackOptions {
                keep_unreachable: false,
                ..RepackOptions::default()
            },
        )
        .expect("repack");
        let pack_dir = repo.git_dir().join("objects/pack");
        let packs_before = count_pack_files(&pack_dir);
        assert_eq!(packs_before, 1);
        for i in 0..5 {
            create_commit(
                &repo,
                &CommitRequest {
                    message: format!("empty-{i}"),
                    author: Some(ident.parse().expect("signature")),
                    committer: Some(ident.parse().expect("signature")),
                    allow_empty: true,
                    sign_override: None,
                    amend: false,
                    assume_worktree_synced: false,
                    skip_pre_commit_tree_match: false,
                    staged_change_count: None,
                    ..Default::default()
                },
                &mut NullProgress,
            )
            .expect("empty");
        }
        assert!(count_loose_objects(repo.odb()).expect("loose") >= 2);
        repack_all(
            &repo,
            &RepackOptions {
                incremental: true,
                write_bitmap: false,
                ..RepackOptions::default()
            },
        )
        .expect("incremental repack");
        assert!(
            count_pack_files(&pack_dir) >= 2,
            "incremental repack should add a pack, not replace the base"
        );
    }

    #[test]
    fn gc_full_run_records_per_phase_timings() {
        let dir = TempDir::new().unwrap();
        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
        let wt = repo.work_tree().unwrap();
        for i in 0..5 {
            std::fs::write(wt.join(format!("f{i}.txt")), format!("{i}\n")).unwrap();
            stage_for_commit(&repo, &mut NullProgress).expect("stage");
            let ident = "Test <t@example.com> 1 +0000".to_string();
            create_commit(
                &repo,
                &CommitRequest {
                    message: format!("c{i}"),
                    author: Some(ident.parse().expect("signature")),
                    committer: Some(ident.parse().expect("signature")),
                    allow_empty: false,
                    sign_override: None,
                    amend: false,
                    assume_worktree_synced: false,
                    skip_pre_commit_tree_match: false,
                    staged_change_count: None,
                    ..Default::default()
                },
                &mut NullProgress,
            )
            .expect("commit");
        }
        let stats = gc(
            &repo,
            &GcOptions::full_run(false, OffsetDateTime::now_utc().unix_timestamp()),
        )
        .expect("gc");
        let t = stats.phase_timings;
        assert!(stats.repack.objects_packed.is_some_and(|n| n > 0));
        assert!(
            t.repack_ms > 0,
            "repack phase must be timed separately from full gc"
        );
        assert!(stats.pack_refs.is_some());
        assert!(stats.commit_graph.is_some());
        assert_eq!(
            t.prune_ms, stats.repack.unreachable_prune_ms,
            "prune_ms must track unreachable loose prune inside repack, not repack_ms"
        );
        // Cached ref/config paths can finish pack-refs or commit-graph in under 1 ms (0 in
        // millisecond buckets). Require repack timing plus evidence the other phases ran.
        assert!(
            t.repack_ms > 0 && stats.pack_refs.is_some() && stats.commit_graph.is_some(),
            "full gc must time repack and run pack-refs + commit-graph, got {t:?}"
        );
        assert!(stats.prune_ran, "full gc should run unreachable prune");
    }
}